<commit_before>/*!
  \author Chase Hutchens

  \brief
    This will attempt to locate 2 prime factors of a larger number.
    The discrepancy with this method is the prime factors must be in the range
    of the 2 <= factor <= ceil(goldenRatio * sqrt(largePrime)). The reason I chose
    to scale by the goldenRatio is because I feel the golden ratio and
    prime numbers go hand in hand.

    Example Values :
        FAST CALCULATION
          25450261 = 5087 * 5003

        LONGER CALCULATION
          3574406403731 = 2750159 * 1299709
*/

#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include "PrimeFactorization.h"

static const double goldenRatio = (1.0 + sqrt(5)) / 2.0;

// PRIVATE

/*!
  \param thePrime
    This is our 'F' number that we are trying to prime factor
*/
void EncryptionSequence::PrimeFactor::DeterminePrimes(const ull thePrime)
{
  // initial p'
  ull prime = static_cast<ull>(ceil(goldenRatio * sqrt(thePrime)));

  while (prime > 1)
  {
    // p'
    ull checkPrime = prime;

    // p''
    ull startPrime = static_cast<ull>(ceil(goldenRatio * sqrt(checkPrime)));
    // make sure the startPrime isn't the same as the base prime we're checking against
    startPrime = startPrime == prime ? startPrime - 1 : startPrime;
    bool validPrime = false;

    // determine what is prime
    while (checkPrime % startPrime != 0)
    {
      --startPrime;
      // make sure the startPrime isn't the same as the checkPrime we're comparing
      // the startPrime might initially be greater than the checkPrime
      // (kind of messy)
      startPrime = startPrime == checkPrime ? startPrime - 1 : startPrime;

      if (startPrime == 1)
      {
        validPrime = true;
        break;
      }
    }

    if (validPrime || startPrime == 1)
    {
      this->primes.push_back(checkPrime);
    }

    --prime;

    // a prime is never even, but a prime is 2
    while (prime % 2 == 0 && prime != 2)
      --prime;
  }

  std::cout << "\nFound : " << this->primes.size() << " Primes That May Make Up " << thePrime << "\n";
}

// END PRIVATE

// PUBLIC

void EncryptionSequence::PrimeFactor::FactorPrime(const ull toFactorPrime, const int charLen)
{
  std::stringstream greatestDigit;
  greatestDigit << toFactorPrime;

  DeterminePrimes(toFactorPrime);

  time_t startTime;
  time(&startTime);

  unsigned foundPrimes = this->primes.size();

  for (unsigned i = 0; i < foundPrimes; ++i)
  {
    ull prime = this->primes[i];
    bool broke = false;
    for (unsigned j = i; j < foundPrimes; ++j)
    {
      ull primeVal = prime * this->primes[j];

      // This causes noticeable slowdown instead of just elapsing
      /*if (charLen != 0)
      {
        std::stringstream ss;
        ss << primeVal;

        // not going to be any other larger primes beyond this one
        // multiplied with this one
        if (ss.str().size() != charLen)
        {
          break;
          broke = true;
        }
      }*/

      // we've eliminated what we don't want

      //std::cout << primeVal << " | " << prime << " * " << primes[j] << std::endl;

      // 5087 * 5003 (etc..)
      if (primeVal == toFactorPrime)
      {
        time_t endTime;
        time(&endTime);
        double timeTaken = difftime(endTime, startTime);

        std::cout << "\nFound Prime Factors : [p] = " << prime << " | [q] = " << this->primes[j] << std::endl;
        std::cout << "Time Taken To Factor Prime : " << timeTaken << " seconds" << std::endl;

        return;
      }
    }
  }

  std::cout << "\nFound : No Two Primes That Make Up : " << toFactorPrime << std::endl;
}

// END PUBLIC

void EncryptionSequence::DoPrimeFactor()
{
  std::string inputNumber, foundNumber;
  std::cout << "What Number Do You Want To Factor?\n:";
  std::getline(std::cin, inputNumber);

  // parse the inputted number for only numbers
  unsigned stringSize = inputNumber.size();
  for (unsigned i = 0; i <= stringSize; ++i)
  {
    if ((inputNumber[i] >= '0' && inputNumber[i] <= '9'))
    {
      foundNumber += inputNumber[i];
    }
  }

  EncryptionSequence::PrimeFactor pFactor;
  pFactor.FactorPrime(std::stoull(foundNumber), stringSize);

  std::cout << "\nPress Enter To Continue";
  getchar();
}<commit_msg>[ PrimeFactorization.cpp Changes ]<commit_after>/*!
  \author Chase Hutchens

  \brief
    This will attempt to locate 2 prime factors of a larger number.
    The discrepancy with this method is the prime factors must be in the range
    of the 2 <= factor <= ceil(goldenRatio * sqrt(largePrime)). The reason I chose
    to scale by the goldenRatio is because I feel the golden ratio and
    prime numbers go hand in hand.

    Example Values :
        FAST CALCULATION
          25450261 = 5087 * 5003

        LONGER CALCULATION
          3574406403731 = 2750159 * 1299709
*/

#include <iostream>
#include <sstream>
#include <string>
#include <ctime>
#include "PrimeFactorization.h"

static const double goldenRatio = (1.0 + sqrt(5)) / 2.0;

// PRIVATE

/*!
  \param thePrime
    This is our 'F' number that we are trying to prime factor
*/
void EncryptionSequence::PrimeFactor::DeterminePrimes(const ull thePrime)
{
  // initial p'
  ull prime = static_cast<ull>(ceil(goldenRatio * sqrt(thePrime)));

  while (prime > 1)
  {
    // p'
    ull checkPrime = prime;

    // p''
    ull comparison = static_cast<ull>(ceil(goldenRatio * sqrt(checkPrime)));
    // make sure the startPrime isn't the same as the base prime we're checking against
    comparison = comparison == prime ? comparison - 1 : comparison;
    bool validPrime = false;

    // determine what is prime
    while (checkPrime % comparison != 0)
    {
      --comparison;
      // make sure the startPrime isn't the same as the checkPrime we're comparing
      // the startPrime might initially be greater than the checkPrime
      // (kind of messy)
      comparison = comparison == checkPrime ? comparison - 1 : comparison;

      if (comparison == 1)
      {
        validPrime = true;
        break;
      }
    }

    if (validPrime || comparison == 1)
    {
      this->primes.push_back(checkPrime);
    }

    --prime;

    // a prime is never even, but a prime is 2
    while (prime % 2 == 0 && prime != 2)
      --prime;
  }

  std::cout << "\nFound : " << this->primes.size() << " Primes That May Make Up " << thePrime << "\n";
}

// END PRIVATE

// PUBLIC

void EncryptionSequence::PrimeFactor::FactorPrime(const ull toFactorPrime, const int charLen)
{
  std::stringstream greatestDigit;
  greatestDigit << toFactorPrime;

  DeterminePrimes(toFactorPrime);

  time_t startTime;
  time(&startTime);

  unsigned foundPrimes = this->primes.size();

  for (unsigned i = 0; i < foundPrimes; ++i)
  {
    ull prime = this->primes[i];
    bool broke = false;
    for (unsigned j = i; j < foundPrimes; ++j)
    {
      ull primeVal = prime * this->primes[j];

      // This causes noticeable slowdown instead of just elapsing
      /*if (charLen != 0)
      {
        std::stringstream ss;
        ss << primeVal;

        // not going to be any other larger primes beyond this one
        // multiplied with this one
        if (ss.str().size() != charLen)
        {
          break;
          broke = true;
        }
      }*/

      // we've eliminated what we don't want

      //std::cout << primeVal << " | " << prime << " * " << primes[j] << std::endl;

      // 5087 * 5003 (etc..)
      if (primeVal == toFactorPrime)
      {
        time_t endTime;
        time(&endTime);
        double timeTaken = difftime(endTime, startTime);

        std::cout << "\nFound Prime Factors : [p] = " << prime << " | [q] = " << this->primes[j] << std::endl;
        std::cout << "Time Taken To Factor Prime : " << timeTaken << " seconds" << std::endl;

        return;
      }
    }
  }

  std::cout << "\nFound : No Two Primes That Make Up : " << toFactorPrime << std::endl;
}

// END PUBLIC

void EncryptionSequence::DoPrimeFactor()
{
  std::string inputNumber, foundNumber;
  std::cout << "What Number Do You Want To Factor?\n:";
  std::getline(std::cin, inputNumber);

  // parse the inputted number for only numbers
  unsigned stringSize = inputNumber.size();
  for (unsigned i = 0; i <= stringSize; ++i)
  {
    if ((inputNumber[i] >= '0' && inputNumber[i] <= '9'))
    {
      foundNumber += inputNumber[i];
    }
  }

  EncryptionSequence::PrimeFactor pFactor;
  pFactor.FactorPrime(std::stoull(foundNumber), stringSize);

  std::cout << "\nPress Enter To Continue";
  getchar();
}<|endoftext|>


<commit_before>/***************************************************************************
 *  io/iostats.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de>
 *  Copyright (C) 2008 Andreas Beckmann <beckmann@mpi-inf.mpg.de>
 *
 *  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)
 **************************************************************************/

#include <string>
#include <sstream>
#include <iomanip>
#include <stxxl/bits/io/iostats.h>

__STXXL_BEGIN_NAMESPACE

stats::stats() :
    reads(0),
    writes(0),
    volume_read(0),
    volume_written(0),
    t_reads(0.0),
    t_writes(0.0),
    p_reads(0.0),
    p_writes(0.0),
    p_begin_read(0.0),
    p_begin_write(0.0),
    p_ios(0.0),
    p_begin_io(0.0),
    t_waits(0.0),
    p_waits(0.0),
    p_begin_wait(0.0),
    acc_reads(0), acc_writes(0),
    acc_ios(0),
    acc_waits(0),
    last_reset(timestamp())
{ }

#ifndef STXXL_IO_STATS_RESET_FORBIDDEN
void stats::reset()
{
    {
        scoped_mutex_lock ReadLock(read_mutex);

        //assert(acc_reads == 0);
        if (acc_reads)
            STXXL_ERRMSG("Warning: " << acc_reads <<
                         " read(s) not yet finished");

        reads = 0;

        volume_read = 0;
        t_reads = 0;
        p_reads = 0.0;
    }
    {
        scoped_mutex_lock WriteLock(write_mutex);

        //assert(acc_writes == 0);
        if (acc_writes)
            STXXL_ERRMSG("Warning: " << acc_writes <<
                         " write(s) not yet finished");

        writes = 0;

        volume_written = 0;
        t_writes = 0.0;
        p_writes = 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        //assert(acc_ios == 0);
        if (acc_ios)
            STXXL_ERRMSG("Warning: " << acc_ios <<
                         " io(s) not yet finished");

        p_ios = 0.0;
    }
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        //assert(acc_waits == 0);
        if (acc_waits)
            STXXL_ERRMSG("Warning: " << acc_waits <<
                         " wait(s) not yet finished");

        t_waits = 0.0;
        p_waits = 0.0;
    }

    last_reset = timestamp();
}
#endif

#if STXXL_IO_STATS
void stats::write_started(unsigned size_)
{
    double now = timestamp();
    {
        scoped_mutex_lock WriteLock(write_mutex);

        ++writes;
        volume_written += size_;
        double diff = now - p_begin_write;
        t_writes += double(acc_writes) * diff;
        p_begin_write = now;
        p_writes += (acc_writes++) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios++) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::write_finished()
{
    double now = timestamp();
    {
        scoped_mutex_lock WriteLock(write_mutex);

        double diff = now - p_begin_write;
        t_writes += double(acc_writes) * diff;
        p_begin_write = now;
        p_writes += (acc_writes--) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios--) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::write_cached(unsigned size_)
{
    scoped_mutex_lock WriteLock(write_mutex);

    ++c_writes;
    c_volume_written += size_;
}

void stats::read_started(unsigned size_)
{
    double now = timestamp();
    {
        scoped_mutex_lock ReadLock(read_mutex);

        ++reads;
        volume_read += size_;
        double diff = now - p_begin_read;
        t_reads += double(acc_reads) * diff;
        p_begin_read = now;
        p_reads += (acc_reads++) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios++) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::read_finished()
{
    double now = timestamp();
    {
        scoped_mutex_lock ReadLock(read_mutex);

        double diff = now - p_begin_read;
        t_reads += double(acc_reads) * diff;
        p_begin_read = now;
        p_reads += (acc_reads--) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios--) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::read_cached(unsigned size_)
{
    scoped_mutex_lock WriteLock(read_mutex);

    ++c_reads;
    c_volume_read += size_;
}
#endif

#ifdef COUNT_WAIT_TIME
void stats::wait_started()
{
    double now = timestamp();
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        double diff = now - p_begin_wait;
        t_waits += double(acc_waits) * diff;
        p_begin_wait = now;
        p_waits += (acc_waits++) ? diff : 0.0;
    }
}

void stats::wait_finished()
{
    double now = timestamp();
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        double diff = now - p_begin_wait;
        t_waits += double(acc_waits) * diff;
        p_begin_wait = now;
        p_waits += (acc_waits--) ? diff : 0.0;
    }
}
#endif

void stats::_reset_io_wait_time()
{
#ifdef COUNT_WAIT_TIME
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        //assert(acc_waits == 0);
        if (acc_waits)
            STXXL_ERRMSG("Warning: " << acc_waits <<
                         " wait(s) not yet finished");

        t_waits = 0.0;
        p_waits = 0.0;
    }
#endif
}

std::string hr(uint64 number, const char * unit = "")
{
    // may not overflow, std::numeric_limits<uint64>::max() == 16 EB
    static const char * endings[] = { " ", "K", "M", "G", "T", "P", "E" };
    std::ostringstream out;
    out << number << ' ';
    int scale = 0;
    double number_d = number;
    while (number_d >= 1024.0)
    {
        number_d /= 1024.0;
        ++scale;
    }
    if (scale > 0)
        out << '(' << std::fixed << std::setprecision(3) << number_d << ' ' << endings[scale] << unit << ") ";
    return out.str();
}

std::ostream & operator << (std::ostream & o, const stats_data & s)
{
    o << "STXXL I/O statistics" << std::endl;
#if STXXL_IO_STATS
    o << " total number of reads                      : " << hr(s.get_reads()) << std::endl;
    o << " average block size (read)                  : "
      << hr(s.get_reads() ? s.get_read_volume() / s.get_reads() : 0, "B") << std::endl;
    o << " number of bytes read from disks            : " << hr(s.get_read_volume(), "B") << std::endl;
    o << " time spent in serving all read requests    : " << s.get_read_time() << " sec."
      << " @ " << (s.get_read_volume() / 1048576.0 / s.get_read_time()) << " MB/sec."
      << std::endl;
    o << " time spent in reading (parallel read time) : " << s.get_pread_time() << " sec."
      << " @ " << (s.get_read_volume() / 1048576.0 / s.get_pread_time()) << " MB/sec."
      << std::endl;
   if (s.get_cached_reads()) {
    o << " total number of cached reads               : " << hr(s.get_cached_reads()) << std::endl;
    o << " number of bytes read from cache            : " << hr(s.get_cached_read_volume(), "B") << std::endl;
   }
   if (s.get_cached_writes()) {
    o << " total number of cached writes              : " << hr(s.get_cached_writes()) << std::endl;
    o << " number of bytes written to cache           : " << hr(s.get_cached_written_volume(), "B") << std::endl;
   }
    o << " total number of writes                     : " << hr(s.get_writes()) << std::endl;
    o << " average block size (write)                 : "
      << hr(s.get_writes() ? s.get_written_volume() / s.get_writes() : 0, "B") << std::endl;
    o << " number of bytes written to disks           : " << hr(s.get_written_volume(), "B") << std::endl;
    o << " time spent in serving all write requests   : " << s.get_write_time() << " sec."
      << " @ " << (s.get_written_volume() / 1048576.0 / s.get_write_time()) << " MB/sec."
      << std::endl;
    o << " time spent in writing (parallel write time): " << s.get_pwrite_time() << " sec."
      << " @ " << (s.get_written_volume() / 1048576.0 / s.get_pwrite_time()) << " MB/sec."
      << std::endl;
    o << " time spent in I/O (parallel I/O time)      : " << s.get_pio_time() << " sec."
      << " @ " << ((s.get_read_volume() + s.get_written_volume()) / 1048576.0 / s.get_pio_time()) << " MB/sec."
      << std::endl;
#else
    o << " n/a" << std::endl;
#endif
#ifdef COUNT_WAIT_TIME
    o << " I/O wait time                              : " << s.get_io_wait_time() << " sec." << std::endl;
#endif
    o << " Time since the last reset                  : " << s.get_elapsed_time() << " sec." << std::endl;
    return o;
}

__STXXL_END_NAMESPACE
<commit_msg>add average cached block sizes<commit_after>/***************************************************************************
 *  io/iostats.cpp
 *
 *  Part of the STXXL. See http://stxxl.sourceforge.net
 *
 *  Copyright (C) 2002-2004 Roman Dementiev <dementiev@mpi-sb.mpg.de>
 *  Copyright (C) 2008 Andreas Beckmann <beckmann@mpi-inf.mpg.de>
 *
 *  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)
 **************************************************************************/

#include <string>
#include <sstream>
#include <iomanip>
#include <stxxl/bits/io/iostats.h>

__STXXL_BEGIN_NAMESPACE

stats::stats() :
    reads(0),
    writes(0),
    volume_read(0),
    volume_written(0),
    t_reads(0.0),
    t_writes(0.0),
    p_reads(0.0),
    p_writes(0.0),
    p_begin_read(0.0),
    p_begin_write(0.0),
    p_ios(0.0),
    p_begin_io(0.0),
    t_waits(0.0),
    p_waits(0.0),
    p_begin_wait(0.0),
    acc_reads(0), acc_writes(0),
    acc_ios(0),
    acc_waits(0),
    last_reset(timestamp())
{ }

#ifndef STXXL_IO_STATS_RESET_FORBIDDEN
void stats::reset()
{
    {
        scoped_mutex_lock ReadLock(read_mutex);

        //assert(acc_reads == 0);
        if (acc_reads)
            STXXL_ERRMSG("Warning: " << acc_reads <<
                         " read(s) not yet finished");

        reads = 0;

        volume_read = 0;
        t_reads = 0;
        p_reads = 0.0;
    }
    {
        scoped_mutex_lock WriteLock(write_mutex);

        //assert(acc_writes == 0);
        if (acc_writes)
            STXXL_ERRMSG("Warning: " << acc_writes <<
                         " write(s) not yet finished");

        writes = 0;

        volume_written = 0;
        t_writes = 0.0;
        p_writes = 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        //assert(acc_ios == 0);
        if (acc_ios)
            STXXL_ERRMSG("Warning: " << acc_ios <<
                         " io(s) not yet finished");

        p_ios = 0.0;
    }
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        //assert(acc_waits == 0);
        if (acc_waits)
            STXXL_ERRMSG("Warning: " << acc_waits <<
                         " wait(s) not yet finished");

        t_waits = 0.0;
        p_waits = 0.0;
    }

    last_reset = timestamp();
}
#endif

#if STXXL_IO_STATS
void stats::write_started(unsigned size_)
{
    double now = timestamp();
    {
        scoped_mutex_lock WriteLock(write_mutex);

        ++writes;
        volume_written += size_;
        double diff = now - p_begin_write;
        t_writes += double(acc_writes) * diff;
        p_begin_write = now;
        p_writes += (acc_writes++) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios++) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::write_finished()
{
    double now = timestamp();
    {
        scoped_mutex_lock WriteLock(write_mutex);

        double diff = now - p_begin_write;
        t_writes += double(acc_writes) * diff;
        p_begin_write = now;
        p_writes += (acc_writes--) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios--) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::write_cached(unsigned size_)
{
    scoped_mutex_lock WriteLock(write_mutex);

    ++c_writes;
    c_volume_written += size_;
}

void stats::read_started(unsigned size_)
{
    double now = timestamp();
    {
        scoped_mutex_lock ReadLock(read_mutex);

        ++reads;
        volume_read += size_;
        double diff = now - p_begin_read;
        t_reads += double(acc_reads) * diff;
        p_begin_read = now;
        p_reads += (acc_reads++) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios++) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::read_finished()
{
    double now = timestamp();
    {
        scoped_mutex_lock ReadLock(read_mutex);

        double diff = now - p_begin_read;
        t_reads += double(acc_reads) * diff;
        p_begin_read = now;
        p_reads += (acc_reads--) ? diff : 0.0;
    }
    {
        scoped_mutex_lock IOLock(io_mutex);

        double diff = now - p_begin_io;
        p_ios += (acc_ios--) ? diff : 0.0;
        p_begin_io = now;
    }
}

void stats::read_cached(unsigned size_)
{
    scoped_mutex_lock WriteLock(read_mutex);

    ++c_reads;
    c_volume_read += size_;
}
#endif

#ifdef COUNT_WAIT_TIME
void stats::wait_started()
{
    double now = timestamp();
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        double diff = now - p_begin_wait;
        t_waits += double(acc_waits) * diff;
        p_begin_wait = now;
        p_waits += (acc_waits++) ? diff : 0.0;
    }
}

void stats::wait_finished()
{
    double now = timestamp();
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        double diff = now - p_begin_wait;
        t_waits += double(acc_waits) * diff;
        p_begin_wait = now;
        p_waits += (acc_waits--) ? diff : 0.0;
    }
}
#endif

void stats::_reset_io_wait_time()
{
#ifdef COUNT_WAIT_TIME
    {
        scoped_mutex_lock WaitLock(wait_mutex);

        //assert(acc_waits == 0);
        if (acc_waits)
            STXXL_ERRMSG("Warning: " << acc_waits <<
                         " wait(s) not yet finished");

        t_waits = 0.0;
        p_waits = 0.0;
    }
#endif
}

std::string hr(uint64 number, const char * unit = "")
{
    // may not overflow, std::numeric_limits<uint64>::max() == 16 EB
    static const char * endings[] = { " ", "K", "M", "G", "T", "P", "E" };
    std::ostringstream out;
    out << number << ' ';
    int scale = 0;
    double number_d = number;
    while (number_d >= 1024.0)
    {
        number_d /= 1024.0;
        ++scale;
    }
    if (scale > 0)
        out << '(' << std::fixed << std::setprecision(3) << number_d << ' ' << endings[scale] << unit << ") ";
    return out.str();
}

std::ostream & operator << (std::ostream & o, const stats_data & s)
{
    o << "STXXL I/O statistics" << std::endl;
#if STXXL_IO_STATS
    o << " total number of reads                      : " << hr(s.get_reads()) << std::endl;
    o << " average block size (read)                  : "
      << hr(s.get_reads() ? s.get_read_volume() / s.get_reads() : 0, "B") << std::endl;
    o << " number of bytes read from disks            : " << hr(s.get_read_volume(), "B") << std::endl;
    o << " time spent in serving all read requests    : " << s.get_read_time() << " sec."
      << " @ " << (s.get_read_volume() / 1048576.0 / s.get_read_time()) << " MB/sec."
      << std::endl;
    o << " time spent in reading (parallel read time) : " << s.get_pread_time() << " sec."
      << " @ " << (s.get_read_volume() / 1048576.0 / s.get_pread_time()) << " MB/sec."
      << std::endl;
   if (s.get_cached_reads()) {
    o << " total number of cached reads               : " << hr(s.get_cached_reads()) << std::endl;
    o << " average block size (cached read)           : " << hr(s.get_cached_read_volume() / s.get_cached_reads(), "B") << std::endl;
    o << " number of bytes read from cache            : " << hr(s.get_cached_read_volume(), "B") << std::endl;
   }
   if (s.get_cached_writes()) {
    o << " total number of cached writes              : " << hr(s.get_cached_writes()) << std::endl;
    o << " average block size (cached write)          : " << hr(s.get_cached_written_volume() / s.get_cached_writes(), "B") << std::endl;
    o << " number of bytes written to cache           : " << hr(s.get_cached_written_volume(), "B") << std::endl;
   }
    o << " total number of writes                     : " << hr(s.get_writes()) << std::endl;
    o << " average block size (write)                 : "
      << hr(s.get_writes() ? s.get_written_volume() / s.get_writes() : 0, "B") << std::endl;
    o << " number of bytes written to disks           : " << hr(s.get_written_volume(), "B") << std::endl;
    o << " time spent in serving all write requests   : " << s.get_write_time() << " sec."
      << " @ " << (s.get_written_volume() / 1048576.0 / s.get_write_time()) << " MB/sec."
      << std::endl;
    o << " time spent in writing (parallel write time): " << s.get_pwrite_time() << " sec."
      << " @ " << (s.get_written_volume() / 1048576.0 / s.get_pwrite_time()) << " MB/sec."
      << std::endl;
    o << " time spent in I/O (parallel I/O time)      : " << s.get_pio_time() << " sec."
      << " @ " << ((s.get_read_volume() + s.get_written_volume()) / 1048576.0 / s.get_pio_time()) << " MB/sec."
      << std::endl;
#else
    o << " n/a" << std::endl;
#endif
#ifdef COUNT_WAIT_TIME
    o << " I/O wait time                              : " << s.get_io_wait_time() << " sec." << std::endl;
#endif
    o << " Time since the last reset                  : " << s.get_elapsed_time() << " sec." << std::endl;
    return o;
}

__STXXL_END_NAMESPACE
<|endoftext|>


<commit_before>
#include "DuktapeScriptBackend.h"

#include <iostream>

#include <cppassist/logging/logging.h>

#include <cppexpose/reflection/Object.h>
#include <cppexpose/variant/Variant.h>
#include <cppexpose/scripting/ScriptContext.h>

#include "DuktapeScriptFunction.h"
#include "DuktapeObjectWrapper.h"

using namespace cppassist;

namespace cppexpose
{

const char * s_duktapeScriptBackendKey   = "duktapeScriptBackend";
const char * s_duktapeNextStashIndexKey  = "duktapeNextStashFunctionIndex";
const char * s_duktapeFunctionPointerKey = "duktapeFunctionPointer";
const char * s_duktapeObjectPointerKey   = "duktapeObjectPointer";
const char * s_duktapePropertyNameKey    = "duktapePropertyName";

DuktapeScriptBackend::DuktapeScriptBackend()
: m_context(nullptr)
, m_globalObjWrapper(nullptr)
{
    // Create duktape script context
    m_context = duk_create_heap_default();
}

DuktapeScriptBackend::~DuktapeScriptBackend()
{
    // Destroy duktape script context
    duk_destroy_heap(m_context);
}

void DuktapeScriptBackend::initialize(ScriptContext * scriptContext)
{
    // Store script context
    m_scriptContext = scriptContext;

    // Get stash
    duk_push_global_stash(m_context);

    // Save pointer to script backend in global stash
    void * context_ptr = static_cast<void *>(this);
    duk_push_pointer(m_context, context_ptr);
    duk_put_prop_string(m_context, -2, s_duktapeScriptBackendKey);

    // Initialize next index for storing functions and objects in the stash
    duk_push_int(m_context, 0);
    duk_put_prop_string(m_context, -2, s_duktapeNextStashIndexKey);

    // Release stash
    duk_pop(m_context);
}

void DuktapeScriptBackend::setGlobalObject(Object * obj)
{
    // Destroy former global object wrapper
    if (m_globalObjWrapper)
    {
        // Remove property in the global object
        duk_push_global_object(m_context);
        duk_del_prop_string(m_context, duk_get_top_index(m_context), obj->name().c_str());
        duk_pop(m_context);
    }

    // Create object wrapper
    m_globalObjWrapper = cppassist::make_unique<DuktapeObjectWrapper>(this);

    // Wrap object in javascript object and put it into the global object
    duk_push_global_object(m_context);
    m_globalObjWrapper->wrapObject(duk_get_top_index(m_context), obj);
    duk_pop(m_context);
}

Variant DuktapeScriptBackend::evaluate(const std::string & code)
{
    // Check code for errors
    duk_int_t error = duk_peval_string(m_context, code.c_str());

    if (error)
    {
        // Raise exception
        m_scriptContext->scriptException(std::string(duk_safe_to_string(m_context, -1)));

        // Abort and return undefined value
        duk_pop(m_context);
        return Variant();
    }

    // Convert return value to variant
    Variant value = fromDukStack();
    duk_pop(m_context);
    return value;
}

DuktapeScriptBackend * DuktapeScriptBackend::getScriptBackend(duk_context * context)
{
    // Get stash object
    duk_push_global_stash(context);

    // Get pointer to duktape scripting backend
    duk_get_prop_string(context, -1, s_duktapeScriptBackendKey);
    void * ptr = duk_get_pointer(context, -1);
    duk_pop_2(context);

    // Return duktape scripting backend
    return static_cast<DuktapeScriptBackend *>(ptr);
}

Variant DuktapeScriptBackend::fromDukStack(duk_idx_t index)
{
    // Wrapped object function
    if (duk_is_c_function(m_context, index))
    {
        // Get pointer to wrapped function
        duk_get_prop_string(m_context, index, s_duktapeFunctionPointerKey);
        Function * func = reinterpret_cast<Function *>( duk_get_pointer(m_context, -1) );
        duk_pop(m_context);

        // Return wrapped function
        return Variant::fromValue<Function>(*func);
    }

    // Javascript function - will be stored in global stash for access from C++ later
    else if (duk_is_ecmascript_function(m_context, index))
    {
        // Get stash object
        duk_push_global_stash(m_context);

        // Get next free index in global stash
        int funcIndex = getNextStashIndex();
        duk_push_int(m_context, funcIndex);

        // Copy function object to the top and put it as property into global stash
        duk_dup(m_context, -3);
        duk_put_prop(m_context, -3);

        // Close stash
        duk_pop(m_context);

        // Return callable function
        Function function(cppassist::make_unique<DuktapeScriptFunction>(this, funcIndex));
        return Variant::fromValue<Function>(function);
    }

    // Number
    else if (duk_is_number(m_context, index))
    {
        double value = duk_get_number(m_context, index);
        return Variant(value);
    }

    // Boolean
    else if (duk_is_boolean(m_context, index))
    {
        bool value = duk_get_boolean(m_context, index) > 0;
        return Variant(value);
    }

    // String
    else if (duk_is_string(m_context, index))
    {
        const char *str = duk_get_string(m_context, index);
        return Variant(str);
    }

    // Array
    else if (duk_is_array(m_context, index))
    {
        VariantArray array;

        for (unsigned int i = 0; i < duk_get_length(m_context, index); ++i)
        {
            duk_get_prop_index(m_context, index, i);
            array.push_back(fromDukStack());
            duk_pop(m_context);
        }

        return array;
    }

    // Object
    else if (duk_is_object(m_context, index))
    {
        VariantMap map;

        duk_enum(m_context, index, 0);
        while (duk_next(m_context, -1, 1))
        {
            // Prevent the pointer to the C++ object that is stored in the Ecmascript object from being serialized
            if (!(duk_is_pointer(m_context, -1) && fromDukStack(-2).value<std::string>() == s_duktapeObjectPointerKey))
            {
                map.insert({ fromDukStack(-2).value<std::string>(), fromDukStack(-1) });
            }

            duk_pop_2(m_context);
        }

        duk_pop(m_context);

        return Variant(map);
    }

    // Pointer
    else if (duk_is_pointer(m_context, index))
    {
        return Variant::fromValue<void *>(duk_get_pointer(m_context, index));
    }

    // Undefined
    else if (duk_is_undefined(m_context, index))
    {
        return Variant();
    }

    // Unknown type
    warning() << "Unknown type found: " << duk_get_type(m_context, index) << std::endl;
    warning() << "Duktape stack dump:" << std::endl;
    duk_dump_context_stderr(m_context);
    return Variant();
}

void DuktapeScriptBackend::pushToDukStack(const Variant & value)
{
    if (value.isBool()) {
        duk_push_boolean(m_context, value.toBool());
    }

    else if (value.isUnsignedIntegral()) {
        duk_push_number(m_context, value.toULongLong());
    }

    else if (value.isSignedIntegral() || value.isIntegral()) {
        duk_push_number(m_context, value.toLongLong());
    }

    else if (value.isFloatingPoint()) {
        duk_push_number(m_context, value.toDouble());
    }

    else if (value.isString()) {
        duk_push_string(m_context, value.toString().c_str());
    }

    else if (value.hasType<char*>()) {
        duk_push_string(m_context, value.value<char*>());
    }

    else if (value.isVariantArray())
    {
        VariantArray variantArray = value.value<VariantArray>();
        duk_idx_t arr_idx = duk_push_array(m_context);

        for (unsigned int i=0; i<variantArray.size(); i++) {
            pushToDukStack(variantArray.at(i));
            duk_put_prop_index(m_context, arr_idx, i);
        }
    }

    else if (value.isVariantMap())
    {
        VariantMap variantMap = value.value<VariantMap>();
        duk_push_object(m_context);

        for (const std::pair<std::string, Variant> & pair : variantMap)
        {
            pushToDukStack(pair.second);
            duk_put_prop_string(m_context, -2, pair.first.c_str());
        }
    }
}

int DuktapeScriptBackend::getNextStashIndex()
{
    // Get stash object
    duk_push_global_stash(m_context);

    // Get next free index for functions or objects in global stash
    duk_get_prop_string(m_context, -1, s_duktapeNextStashIndexKey);
    int index = duk_get_int(m_context, -1);

    // Increment next free index
    duk_push_int(m_context, index + 1);
    duk_put_prop_string(m_context, -3, s_duktapeNextStashIndexKey);

    // Clean up stack
    duk_pop(m_context);
    duk_pop(m_context);

    // Return index
    return index;
}

} // namespace cppexpose
<commit_msg>Fix crash in duktape backend when property value cannot be converted<commit_after>
#include "DuktapeScriptBackend.h"

#include <iostream>

#include <cppassist/logging/logging.h>

#include <cppexpose/reflection/Object.h>
#include <cppexpose/variant/Variant.h>
#include <cppexpose/scripting/ScriptContext.h>

#include "DuktapeScriptFunction.h"
#include "DuktapeObjectWrapper.h"

using namespace cppassist;

namespace cppexpose
{

const char * s_duktapeScriptBackendKey   = "duktapeScriptBackend";
const char * s_duktapeNextStashIndexKey  = "duktapeNextStashFunctionIndex";
const char * s_duktapeFunctionPointerKey = "duktapeFunctionPointer";
const char * s_duktapeObjectPointerKey   = "duktapeObjectPointer";
const char * s_duktapePropertyNameKey    = "duktapePropertyName";

DuktapeScriptBackend::DuktapeScriptBackend()
: m_context(nullptr)
, m_globalObjWrapper(nullptr)
{
    // Create duktape script context
    m_context = duk_create_heap_default();
}

DuktapeScriptBackend::~DuktapeScriptBackend()
{
    // Destroy duktape script context
    duk_destroy_heap(m_context);
}

void DuktapeScriptBackend::initialize(ScriptContext * scriptContext)
{
    // Store script context
    m_scriptContext = scriptContext;

    // Get stash
    duk_push_global_stash(m_context);

    // Save pointer to script backend in global stash
    void * context_ptr = static_cast<void *>(this);
    duk_push_pointer(m_context, context_ptr);
    duk_put_prop_string(m_context, -2, s_duktapeScriptBackendKey);

    // Initialize next index for storing functions and objects in the stash
    duk_push_int(m_context, 0);
    duk_put_prop_string(m_context, -2, s_duktapeNextStashIndexKey);

    // Release stash
    duk_pop(m_context);
}

void DuktapeScriptBackend::setGlobalObject(Object * obj)
{
    // Destroy former global object wrapper
    if (m_globalObjWrapper)
    {
        // Remove property in the global object
        duk_push_global_object(m_context);
        duk_del_prop_string(m_context, duk_get_top_index(m_context), obj->name().c_str());
        duk_pop(m_context);
    }

    // Create object wrapper
    m_globalObjWrapper = cppassist::make_unique<DuktapeObjectWrapper>(this);

    // Wrap object in javascript object and put it into the global object
    duk_push_global_object(m_context);
    m_globalObjWrapper->wrapObject(duk_get_top_index(m_context), obj);
    duk_pop(m_context);
}

Variant DuktapeScriptBackend::evaluate(const std::string & code)
{
    // Check code for errors
    duk_int_t error = duk_peval_string(m_context, code.c_str());

    if (error)
    {
        // Raise exception
        m_scriptContext->scriptException(std::string(duk_safe_to_string(m_context, -1)));

        // Abort and return undefined value
        duk_pop(m_context);
        return Variant();
    }

    // Convert return value to variant
    Variant value = fromDukStack();
    duk_pop(m_context);
    return value;
}

DuktapeScriptBackend * DuktapeScriptBackend::getScriptBackend(duk_context * context)
{
    // Get stash object
    duk_push_global_stash(context);

    // Get pointer to duktape scripting backend
    duk_get_prop_string(context, -1, s_duktapeScriptBackendKey);
    void * ptr = duk_get_pointer(context, -1);
    duk_pop_2(context);

    // Return duktape scripting backend
    return static_cast<DuktapeScriptBackend *>(ptr);
}

Variant DuktapeScriptBackend::fromDukStack(duk_idx_t index)
{
    // Wrapped object function
    if (duk_is_c_function(m_context, index))
    {
        // Get pointer to wrapped function
        duk_get_prop_string(m_context, index, s_duktapeFunctionPointerKey);
        Function * func = reinterpret_cast<Function *>( duk_get_pointer(m_context, -1) );
        duk_pop(m_context);

        // Return wrapped function
        return Variant::fromValue<Function>(*func);
    }

    // Javascript function - will be stored in global stash for access from C++ later
    else if (duk_is_ecmascript_function(m_context, index))
    {
        // Get stash object
        duk_push_global_stash(m_context);

        // Get next free index in global stash
        int funcIndex = getNextStashIndex();
        duk_push_int(m_context, funcIndex);

        // Copy function object to the top and put it as property into global stash
        duk_dup(m_context, -3);
        duk_put_prop(m_context, -3);

        // Close stash
        duk_pop(m_context);

        // Return callable function
        Function function(cppassist::make_unique<DuktapeScriptFunction>(this, funcIndex));
        return Variant::fromValue<Function>(function);
    }

    // Number
    else if (duk_is_number(m_context, index))
    {
        double value = duk_get_number(m_context, index);
        return Variant(value);
    }

    // Boolean
    else if (duk_is_boolean(m_context, index))
    {
        bool value = duk_get_boolean(m_context, index) > 0;
        return Variant(value);
    }

    // String
    else if (duk_is_string(m_context, index))
    {
        const char *str = duk_get_string(m_context, index);
        return Variant(str);
    }

    // Array
    else if (duk_is_array(m_context, index))
    {
        VariantArray array;

        for (unsigned int i = 0; i < duk_get_length(m_context, index); ++i)
        {
            duk_get_prop_index(m_context, index, i);
            array.push_back(fromDukStack());
            duk_pop(m_context);
        }

        return array;
    }

    // Object
    else if (duk_is_object(m_context, index))
    {
        VariantMap map;

        duk_enum(m_context, index, 0);
        while (duk_next(m_context, -1, 1))
        {
            // Prevent the pointer to the C++ object that is stored in the Ecmascript object from being serialized
            if (!(duk_is_pointer(m_context, -1) && fromDukStack(-2).value<std::string>() == s_duktapeObjectPointerKey))
            {
                map.insert({ fromDukStack(-2).value<std::string>(), fromDukStack(-1) });
            }

            duk_pop_2(m_context);
        }

        duk_pop(m_context);

        return Variant(map);
    }

    // Pointer
    else if (duk_is_pointer(m_context, index))
    {
        return Variant::fromValue<void *>(duk_get_pointer(m_context, index));
    }

    // Undefined
    else if (duk_is_undefined(m_context, index))
    {
        return Variant();
    }

    // Unknown type
    warning() << "Unknown type found: " << duk_get_type(m_context, index) << std::endl;
    warning() << "Duktape stack dump:" << std::endl;
    duk_dump_context_stderr(m_context);
    return Variant();
}

void DuktapeScriptBackend::pushToDukStack(const Variant & value)
{
    if (value.isBool()) {
        duk_push_boolean(m_context, value.toBool());
    }

    else if (value.isUnsignedIntegral()) {
        duk_push_number(m_context, value.toULongLong());
    }

    else if (value.isSignedIntegral() || value.isIntegral()) {
        duk_push_number(m_context, value.toLongLong());
    }

    else if (value.isFloatingPoint()) {
        duk_push_number(m_context, value.toDouble());
    }

    else if (value.isString()) {
        duk_push_string(m_context, value.toString().c_str());
    }

    else if (value.hasType<char*>()) {
        duk_push_string(m_context, value.value<char*>());
    }

    else if (value.isVariantArray())
    {
        VariantArray variantArray = value.value<VariantArray>();
        duk_idx_t arr_idx = duk_push_array(m_context);

        for (unsigned int i=0; i<variantArray.size(); i++) {
            pushToDukStack(variantArray.at(i));
            duk_put_prop_index(m_context, arr_idx, i);
        }
    }

    else if (value.isVariantMap())
    {
        VariantMap variantMap = value.value<VariantMap>();
        duk_push_object(m_context);

        for (const std::pair<std::string, Variant> & pair : variantMap)
        {
            pushToDukStack(pair.second);
            duk_put_prop_string(m_context, -2, pair.first.c_str());
        }
    }

    else
    {
        warning() << "Unknown variant type found: " << value.type().name();
        duk_push_undefined(m_context);
    }
}

int DuktapeScriptBackend::getNextStashIndex()
{
    // Get stash object
    duk_push_global_stash(m_context);

    // Get next free index for functions or objects in global stash
    duk_get_prop_string(m_context, -1, s_duktapeNextStashIndexKey);
    int index = duk_get_int(m_context, -1);

    // Increment next free index
    duk_push_int(m_context, index + 1);
    duk_put_prop_string(m_context, -3, s_duktapeNextStashIndexKey);

    // Clean up stack
    duk_pop(m_context);
    duk_pop(m_context);

    // Return index
    return index;
}

} // namespace cppexpose
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#include    "../../Characters/Format.h"
#include    "../../Characters/String_Constant.h"
#include    "../../Characters/String2Float.h"
#include    "../../Characters/String2Int.h"
#include    "../../Streams/TextInputStreamBinaryAdapter.h"
#include    "../BadFormatException.h"

#include    "Reader.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::DataExchange;

using   Characters::String_Constant;

/*
 ********************************************************************************
 ************************** DataExchange::INI::Reader ***************************
 ********************************************************************************
 */
class   DataExchange::INI::Reader::Rep_ : public DataExchange::Reader::_IRep {
public:
    DECLARE_USE_BLOCK_ALLOCATION (Rep_);
public:
    virtual _SharedPtrIRep  Clone () const override
    {
        return _SharedPtrIRep (new Rep_ ());    // no instance data
    }
    virtual String          GetDefaultFileSuffix () const override
    {
        return String_Constant (L".ini");
    }
    virtual VariantValue    Read (const Streams::BinaryInputStream& in) override
    {
        return Read (Streams::TextInputStreamBinaryAdapter (in));
    }
    virtual VariantValue    Read (const Streams::TextInputStream& in) override
    {
        Profile  p;
        Optional<String>    readingSection;
        Section             currentSection;
        for (String line : in.ReadLines ()) {
            line = line.Trim ();
            if (line.StartsWith (L"[") and line.EndsWith (L"]")) {
                if (readingSection.IsPresent ()) {
                    p.fNamedSections.Add (*readingSection, currentSection);
                    currentSection.fProperties.clear ();
                }
                readingSection = line.CircularSubString (1, -1);
            }
            else if (line.StartsWith (L";")) {
                // drop comments on the floor
            }
            else if (line.Contains (L"=")) {
                size_t  i   =   line.Find ('=');
                Assert (i != String::npos);
                String key = line.SubString (0, i).Trim ();
                String value = line.SubString (i + 1).Trim ();
                if (value.StartsWith (L"\"") and value.EndsWith (L"\"")) {
                    value = value.CircularSubString (1, -1);
                }
                if (readingSection.IsPresent ()) {
                    currentSection.fProperties.Add (key, value);
                }
                else {
                    p.fUnnamedSection.fProperties.Add (key, value);
                }
            }
            else {
                // @todo not sure what todo with other sorts of lines??
            }
        }
        return Convert (p);
    }
};
DataExchange::INI::Reader::Reader ()
    : inherited (shared_ptr<_IRep> (new Rep_ ()))
{
}
<commit_msg>fixed serious bug with DataExchange/INI/Reader - not including last named section<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2014.  All rights reserved
 */
#include    "../../StroikaPreComp.h"

#include    "../../Characters/Format.h"
#include    "../../Characters/String_Constant.h"
#include    "../../Characters/String2Float.h"
#include    "../../Characters/String2Int.h"
#include    "../../Streams/TextInputStreamBinaryAdapter.h"
#include    "../BadFormatException.h"

#include    "Reader.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::DataExchange;

using   Characters::String_Constant;

/*
 ********************************************************************************
 ************************** DataExchange::INI::Reader ***************************
 ********************************************************************************
 */
class   DataExchange::INI::Reader::Rep_ : public DataExchange::Reader::_IRep {
public:
    DECLARE_USE_BLOCK_ALLOCATION (Rep_);
public:
    virtual _SharedPtrIRep  Clone () const override
    {
        return _SharedPtrIRep (new Rep_ ());    // no instance data
    }
    virtual String          GetDefaultFileSuffix () const override
    {
        return String_Constant (L".ini");
    }
    virtual VariantValue    Read (const Streams::BinaryInputStream& in) override
    {
        return Read (Streams::TextInputStreamBinaryAdapter (in));
    }
    virtual VariantValue    Read (const Streams::TextInputStream& in) override
    {
        Profile  p;
        Optional<String>    readingSection;
        Section             currentSection;
        for (String line : in.ReadLines ()) {
            line = line.Trim ();
            if (line.StartsWith (L"[") and line.EndsWith (L"]")) {
                if (readingSection.IsPresent ()) {
                    p.fNamedSections.Add (*readingSection, currentSection);
                    currentSection.fProperties.clear ();
                }
                readingSection = line.CircularSubString (1, -1);
            }
            else if (line.StartsWith (L";")) {
                // drop comments on the floor
            }
            else if (line.Contains (L"=")) {
                size_t  i   =   line.Find ('=');
                Assert (i != String::npos);
                String key = line.SubString (0, i).Trim ();
                String value = line.SubString (i + 1).Trim ();
                if (value.StartsWith (L"\"") and value.EndsWith (L"\"")) {
                    value = value.CircularSubString (1, -1);
                }
                if (readingSection.IsPresent ()) {
                    currentSection.fProperties.Add (key, value);
                }
                else {
                    p.fUnnamedSection.fProperties.Add (key, value);
                }
            }
            else {
                // @todo not sure what todo with other sorts of lines??
            }
        }
        if (readingSection.IsPresent ()) {
            p.fNamedSections.Add (*readingSection, currentSection);
        }
        return Convert (p);
    }
};
DataExchange::INI::Reader::Reader ()
    : inherited (shared_ptr<_IRep> (new Rep_ ()))
{
}
<|endoftext|>


<commit_before>///
/// \file AliFemtoModelCorrFctnTrueQ3D.cxx
///

#include "AliFemtoModelCorrFctnTrueQ3D.h"
#include "AliFemtoPair.h"
#include "AliFemtoModelManager.h"
#include "AliFemtoModelHiddenInfo.h"

#include <TH3F.h>
#include <TList.h>
#include <TString.h>
#include <TRandom.h>

#include <tuple>
#include <iostream>

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D():
  AliFemtoModelCorrFctnTrueQ3D("CF_TrueQ3D_")
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix):
  AliFemtoModelCorrFctnTrueQ3D(prefix, 56, 0.14)
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix,
                                                           UInt_t nbins,
                                                           Double_t qmax):
  AliFemtoModelCorrFctnTrueQ3D(prefix, nbins, -qmax, qmax)
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const TString &prefix,
                                                           UInt_t nbins,
                                                           Double_t qmin,
                                                           Double_t qmax):
  AliFemtoCorrFctn()
  , fManager(nullptr)
  , fNumeratorGenerated(nullptr)
  , fNumeratorReconstructed(nullptr)
  , fNumeratorGenUnweighted(nullptr)
  , fNumeratorRecUnweighted(nullptr)
  , fDenominatorGenerated(nullptr)
  , fDenominatorReconstructed(nullptr)
  , fDenominatorGenWeighted(nullptr)
  , fDenominatorRecWeighted(nullptr)
  , fRng(new TRandom())
{
  fNumeratorGenerated = new TH3F(prefix + "NumGen",
                                 "Numerator (MC-Generated Momentum)",
                                 nbins, qmin, qmax,
                                 nbins, qmin, qmax,
                                 nbins, qmin, qmax);
  fNumeratorReconstructed = new TH3F(prefix + "NumRec",
                                     "Numerator (Reconstructed Momentum)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fNumeratorRecUnweighted = new TH3F(prefix + "NumRecUnweighted",
                                     "Numerator (Reconstructed Momentum - No femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fNumeratorGenUnweighted = new TH3F(prefix + "NumGenUnweighted",
                                     "Numerator (Generated Momentum - No femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fDenominatorGenerated = new TH3F(prefix + "DenGen",
                                   "Denominator (MC-Generated Momentum)",
                                   nbins, qmin, qmax,
                                   nbins, qmin, qmax,
                                   nbins, qmin, qmax);
  fDenominatorReconstructed = new TH3F(prefix + "DenRec",
                                       "Denominator (Reconstructed Momentum)",
                                       nbins, qmin, qmax,
                                       nbins, qmin, qmax,
                                       nbins, qmin, qmax);
  fDenominatorGenWeighted = new TH3F(prefix + "DenGenWeight",
                                     "Denominator (Generated Momentum - with femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fDenominatorRecWeighted = new TH3F(prefix + "DenRecWeight",
                                     "Numerator (Reconstructed Momentum - with femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fNumeratorGenerated->Sumw2();
  fNumeratorReconstructed->Sumw2();
  fDenominatorGenWeighted->Sumw2();
  fDenominatorRecWeighted->Sumw2();
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmax):
  AliFemtoModelCorrFctnTrueQ3D(nbins, -abs(qmax), abs(qmax))
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmin, Double_t qmax):
  AliFemtoModelCorrFctnTrueQ3D("", nbins, qmin, qmax)
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D::Parameters &params):
  AliFemtoModelCorrFctnTrueQ3D(params.prefix.Data(), params.bin_count, params.qmin, params.qmax)
{
  SetManager(params.mc_manager);
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D& orig):
  AliFemtoCorrFctn(orig)
  , fManager(orig.fManager)
  , fNumeratorGenerated(nullptr)
  , fNumeratorReconstructed(nullptr)
  , fNumeratorGenUnweighted(nullptr)
  , fNumeratorRecUnweighted(nullptr)
  , fDenominatorGenerated(nullptr)
  , fDenominatorReconstructed(nullptr)
  , fDenominatorGenWeighted(nullptr)
  , fDenominatorRecWeighted(nullptr)
  , fRng(new TRandom())
{
  fNumeratorGenerated = new TH3F(*orig.fNumeratorGenerated);
  fNumeratorReconstructed = new TH3F(*orig.fNumeratorReconstructed);
  fDenominatorGenerated = new TH3F(*orig.fDenominatorGenerated);
  fDenominatorReconstructed = new TH3F(*orig.fDenominatorReconstructed);

  fNumeratorGenUnweighted = new TH3F(*orig.fNumeratorGenUnweighted);
  fNumeratorRecUnweighted = new TH3F(*orig.fNumeratorRecUnweighted);
  fDenominatorGenWeighted = new TH3F(*orig.fDenominatorGenWeighted);
  fDenominatorRecWeighted = new TH3F(*orig.fDenominatorRecWeighted);
}

AliFemtoModelCorrFctnTrueQ3D&
AliFemtoModelCorrFctnTrueQ3D::operator=(const AliFemtoModelCorrFctnTrueQ3D&)
{
  return *this;
}

AliFemtoModelCorrFctnTrueQ3D::~AliFemtoModelCorrFctnTrueQ3D()
{
  delete fNumeratorGenerated;
  delete fNumeratorReconstructed;
  delete fDenominatorGenerated;
  delete fDenominatorReconstructed;
  delete fNumeratorGenUnweighted;
  delete fNumeratorRecUnweighted;
  delete fDenominatorGenWeighted;
  delete fDenominatorRecWeighted;
  delete fRng;
}

TList*
AliFemtoModelCorrFctnTrueQ3D::GetOutputList()
{
  TList *result = new TList();
  AppendOutputList(*result);
  return result;
}

TList*
AliFemtoModelCorrFctnTrueQ3D::AppendOutputList(TList &list)
{
  AddOutputObjectsTo(list);
  return &list;
}

void
AliFemtoModelCorrFctnTrueQ3D::AddOutputObjectsTo(TCollection &list)
{
  list.Add(fNumeratorGenerated);
  list.Add(fNumeratorReconstructed);
  list.Add(fDenominatorGenerated);
  list.Add(fDenominatorReconstructed);
  list.Add(fNumeratorGenUnweighted);
  list.Add(fNumeratorRecUnweighted);
  list.Add(fDenominatorGenWeighted);
  list.Add(fDenominatorRecWeighted);
}

/// Return q{Out-Side-Long} tuple, calculated from momentum vectors p1 & p2
static
std::tuple<Double_t, Double_t, Double_t>
Qcms(const AliFemtoLorentzVector &p1, const AliFemtoLorentzVector &p2)
{
  const AliFemtoLorentzVector p = p1 + p2,
                              d = p1 - p2;

  Double_t k1 = p.Perp(),
           k2 = d.x()*p.x() + d.y()*p.y();

  // relative momentum out component in lab frame
  Double_t qout = (k1 == 0) ? 0.0 : k2/k1;

  // relative momentum side component in lab frame
  Double_t qside = (k1 == 0) ? 0.0 : 2.0 * (p2.x()*p1.y() - p1.x()*p2.y())/k1;

  // relative momentum component in lab frame

  Double_t beta = p.z()/p.t(),
          gamma = 1.0 / TMath::Sqrt((1.0-beta)*(1.0+beta));

  Double_t qlong = gamma * (d.z() - beta*d.t());

  // double qlong = (p.t()*d.z() - p.z()*d.t()) / TMath::Sqrt(p.t()*p.t() - p.z()*p.z());

  return std::make_tuple(qout, qside, qlong);
}

static void
AddPair(const AliFemtoParticle &particle1,
        const AliFemtoParticle &particle2,
        TH3F &gen_hist,
        TH3F &rec_hist,
        TH3F &gen_hist_unw,
        TH3F &rec_hist_unw,
        Double_t weight)
{
  Double_t q_out, q_side, q_long;

  // Fill reconstructed histogram with "standard" particle momentum
  std::tie(q_out, q_side, q_long) = Qcms(particle1.FourMomentum(), particle2.FourMomentum());
  Int_t rec_bin = gen_hist.GetBin(q_out, q_long, q_side);
  if (!(gen_hist.IsBinOverflow(rec_bin) or gen_hist.IsBinUnderflow(rec_bin))) {
    rec_hist.Fill(q_out, q_side, q_long, weight);
    rec_hist_unw.Fill(q_out, q_side, q_long, 1.0);
  }

  // Get generated momentum from hidden info
  const AliFemtoModelHiddenInfo
    *info1 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle1.HiddenInfo()),
    *info2 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle2.HiddenInfo());

  if (info1 == nullptr || info2 == nullptr) {
    return;
  }

  const Float_t mass1 = info1->GetMass(),
                mass2 = info2->GetMass();

  // block all zero-mass particles from the correlation function
  if (mass1 == 0.0 || mass2 == 0.0) {
    return;
  }

  const AliFemtoThreeVector *true_momentum1 = info1->GetTrueMomentum(),
                            *true_momentum2 = info2->GetTrueMomentum();

  const Double_t e1 = sqrt(mass1 * mass1 + true_momentum1->Mag2()),
                 e2 = sqrt(mass2 * mass2 + true_momentum2->Mag2());

  const AliFemtoLorentzVector p1 = AliFemtoLorentzVector(e1, *true_momentum1),
                              p2 = AliFemtoLorentzVector(e2, *true_momentum2);

  // Fill generated-momentum histogram with "true" particle momentum
  std::tie(q_out, q_side, q_long) = Qcms(p1, p2);
  Int_t gen_bin = gen_hist.GetBin(q_out, q_long, q_side);
  if (!(gen_hist.IsBinOverflow(gen_bin) or gen_hist.IsBinUnderflow(gen_bin))) {
    gen_hist.Fill(q_out, q_side, q_long, weight);
    gen_hist_unw.Fill(q_out, q_side, q_long, weight);
  }
}

void
AliFemtoModelCorrFctnTrueQ3D::AddRealPair(AliFemtoPair *pair)
{
  const AliFemtoParticle *p1 = pair->Track1(),
                         *p2 = pair->Track2();

  // randomize to avoid ordering biases
  if (fRng->Uniform() >= 0.5) {
    std::swap(p1, p2);
  }
  AddPair(*p1, *p2,
          *fNumeratorGenUnweighted,
          *fNumeratorRecUnweighted,
          *fNumeratorGenerated,
          *fNumeratorReconstructed,
          fManager->GetWeight(pair));
}

void
AliFemtoModelCorrFctnTrueQ3D::AddMixedPair(AliFemtoPair *pair)
{
  const AliFemtoParticle *p1 = pair->Track1(),
                         *p2 = pair->Track2();

  // randomize to avoid ordering biases
  if (fRng->Uniform() >= 0.5) {
    std::swap(p1, p2);
  }

  AddPair(*p1, *p2,
          *fDenominatorGenWeighted,
          *fDenominatorRecWeighted,
          *fDenominatorGenerated,
          *fDenominatorReconstructed,
          fManager->GetWeight(pair));
}

AliFemtoString
AliFemtoModelCorrFctnTrueQ3D::Report()
{
  AliFemtoString report;
  return report;
}

void
AliFemtoModelCorrFctnTrueQ3D::Finish()
{
#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 10, 8)
  // remove {under,over}flow to shrink file sizes
  fNumeratorGenerated->ClearUnderflowAndOverflow();
  fNumeratorReconstructed->ClearUnderflowAndOverflow();
  fDenominatorGenerated->ClearUnderflowAndOverflow();
  fDenominatorReconstructed->ClearUnderflowAndOverflow();

  fNumeratorGenUnweighted->ClearUnderflowAndOverflow();
  fNumeratorRecUnweighted->ClearUnderflowAndOverflow();
  fDenominatorGenWeighted->ClearUnderflowAndOverflow();
  fDenominatorRecWeighted->ClearUnderflowAndOverflow();
#endif
}
<commit_msg>AliFemtoModelCorrFctnTrueQ3D - Replace GetBin with FindBin<commit_after>///
/// \file AliFemtoModelCorrFctnTrueQ3D.cxx
///

#include "AliFemtoModelCorrFctnTrueQ3D.h"
#include "AliFemtoPair.h"
#include "AliFemtoModelManager.h"
#include "AliFemtoModelHiddenInfo.h"

#include <TH3F.h>
#include <TList.h>
#include <TString.h>
#include <TRandom.h>

#include <tuple>
#include <iostream>

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D():
  AliFemtoModelCorrFctnTrueQ3D("CF_TrueQ3D_")
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix):
  AliFemtoModelCorrFctnTrueQ3D(prefix, 56, 0.14)
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const char *prefix,
                                                           UInt_t nbins,
                                                           Double_t qmax):
  AliFemtoModelCorrFctnTrueQ3D(prefix, nbins, -qmax, qmax)
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const TString &prefix,
                                                           UInt_t nbins,
                                                           Double_t qmin,
                                                           Double_t qmax):
  AliFemtoCorrFctn()
  , fManager(nullptr)
  , fNumeratorGenerated(nullptr)
  , fNumeratorReconstructed(nullptr)
  , fNumeratorGenUnweighted(nullptr)
  , fNumeratorRecUnweighted(nullptr)
  , fDenominatorGenerated(nullptr)
  , fDenominatorReconstructed(nullptr)
  , fDenominatorGenWeighted(nullptr)
  , fDenominatorRecWeighted(nullptr)
  , fRng(new TRandom())
{
  fNumeratorGenerated = new TH3F(prefix + "NumGen",
                                 "Numerator (MC-Generated Momentum)",
                                 nbins, qmin, qmax,
                                 nbins, qmin, qmax,
                                 nbins, qmin, qmax);
  fNumeratorReconstructed = new TH3F(prefix + "NumRec",
                                     "Numerator (Reconstructed Momentum)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fNumeratorRecUnweighted = new TH3F(prefix + "NumRecUnweighted",
                                     "Numerator (Reconstructed Momentum - No femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fNumeratorGenUnweighted = new TH3F(prefix + "NumGenUnweighted",
                                     "Numerator (Generated Momentum - No femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fDenominatorGenerated = new TH3F(prefix + "DenGen",
                                   "Denominator (MC-Generated Momentum)",
                                   nbins, qmin, qmax,
                                   nbins, qmin, qmax,
                                   nbins, qmin, qmax);
  fDenominatorReconstructed = new TH3F(prefix + "DenRec",
                                       "Denominator (Reconstructed Momentum)",
                                       nbins, qmin, qmax,
                                       nbins, qmin, qmax,
                                       nbins, qmin, qmax);
  fDenominatorGenWeighted = new TH3F(prefix + "DenGenWeight",
                                     "Denominator (Generated Momentum - with femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fDenominatorRecWeighted = new TH3F(prefix + "DenRecWeight",
                                     "Numerator (Reconstructed Momentum - with femto weight)",
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax,
                                     nbins, qmin, qmax);
  fNumeratorGenerated->Sumw2();
  fNumeratorReconstructed->Sumw2();
  fDenominatorGenWeighted->Sumw2();
  fDenominatorRecWeighted->Sumw2();
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmax):
  AliFemtoModelCorrFctnTrueQ3D(nbins, -abs(qmax), abs(qmax))
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(UInt_t nbins, Double_t qmin, Double_t qmax):
  AliFemtoModelCorrFctnTrueQ3D("", nbins, qmin, qmax)
{
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D::Parameters &params):
  AliFemtoModelCorrFctnTrueQ3D(params.prefix.Data(), params.bin_count, params.qmin, params.qmax)
{
  SetManager(params.mc_manager);
}

AliFemtoModelCorrFctnTrueQ3D::AliFemtoModelCorrFctnTrueQ3D(const AliFemtoModelCorrFctnTrueQ3D& orig):
  AliFemtoCorrFctn(orig)
  , fManager(orig.fManager)
  , fNumeratorGenerated(nullptr)
  , fNumeratorReconstructed(nullptr)
  , fNumeratorGenUnweighted(nullptr)
  , fNumeratorRecUnweighted(nullptr)
  , fDenominatorGenerated(nullptr)
  , fDenominatorReconstructed(nullptr)
  , fDenominatorGenWeighted(nullptr)
  , fDenominatorRecWeighted(nullptr)
  , fRng(new TRandom())
{
  fNumeratorGenerated = new TH3F(*orig.fNumeratorGenerated);
  fNumeratorReconstructed = new TH3F(*orig.fNumeratorReconstructed);
  fDenominatorGenerated = new TH3F(*orig.fDenominatorGenerated);
  fDenominatorReconstructed = new TH3F(*orig.fDenominatorReconstructed);

  fNumeratorGenUnweighted = new TH3F(*orig.fNumeratorGenUnweighted);
  fNumeratorRecUnweighted = new TH3F(*orig.fNumeratorRecUnweighted);
  fDenominatorGenWeighted = new TH3F(*orig.fDenominatorGenWeighted);
  fDenominatorRecWeighted = new TH3F(*orig.fDenominatorRecWeighted);
}

AliFemtoModelCorrFctnTrueQ3D&
AliFemtoModelCorrFctnTrueQ3D::operator=(const AliFemtoModelCorrFctnTrueQ3D&)
{
  return *this;
}

AliFemtoModelCorrFctnTrueQ3D::~AliFemtoModelCorrFctnTrueQ3D()
{
  delete fNumeratorGenerated;
  delete fNumeratorReconstructed;
  delete fDenominatorGenerated;
  delete fDenominatorReconstructed;
  delete fNumeratorGenUnweighted;
  delete fNumeratorRecUnweighted;
  delete fDenominatorGenWeighted;
  delete fDenominatorRecWeighted;
  delete fRng;
}

TList*
AliFemtoModelCorrFctnTrueQ3D::GetOutputList()
{
  TList *result = new TList();
  AppendOutputList(*result);
  return result;
}

TList*
AliFemtoModelCorrFctnTrueQ3D::AppendOutputList(TList &list)
{
  AddOutputObjectsTo(list);
  return &list;
}

void
AliFemtoModelCorrFctnTrueQ3D::AddOutputObjectsTo(TCollection &list)
{
  list.Add(fNumeratorGenerated);
  list.Add(fNumeratorReconstructed);
  list.Add(fDenominatorGenerated);
  list.Add(fDenominatorReconstructed);
  list.Add(fNumeratorGenUnweighted);
  list.Add(fNumeratorRecUnweighted);
  list.Add(fDenominatorGenWeighted);
  list.Add(fDenominatorRecWeighted);
}

/// Return q{Out-Side-Long} tuple, calculated from momentum vectors p1 & p2
static
std::tuple<Double_t, Double_t, Double_t>
Qcms(const AliFemtoLorentzVector &p1, const AliFemtoLorentzVector &p2)
{
  const AliFemtoLorentzVector p = p1 + p2,
                              d = p1 - p2;

  Double_t k1 = p.Perp(),
           k2 = d.x()*p.x() + d.y()*p.y();

  // relative momentum out component in lab frame
  Double_t qout = (k1 == 0) ? 0.0 : k2/k1;

  // relative momentum side component in lab frame
  Double_t qside = (k1 == 0) ? 0.0 : 2.0 * (p2.x()*p1.y() - p1.x()*p2.y())/k1;

  // relative momentum component in lab frame

  Double_t beta = p.z()/p.t(),
          gamma = 1.0 / TMath::Sqrt((1.0-beta)*(1.0+beta));

  Double_t qlong = gamma * (d.z() - beta*d.t());

  // double qlong = (p.t()*d.z() - p.z()*d.t()) / TMath::Sqrt(p.t()*p.t() - p.z()*p.z());

  return std::make_tuple(qout, qside, qlong);
}

static void
AddPair(const AliFemtoParticle &particle1,
        const AliFemtoParticle &particle2,
        TH3F &gen_hist,
        TH3F &rec_hist,
        TH3F &gen_hist_unw,
        TH3F &rec_hist_unw,
        Double_t weight)
{
  Double_t q_out, q_side, q_long;

  // Fill reconstructed histogram with "standard" particle momentum
  std::tie(q_out, q_side, q_long) = Qcms(particle1.FourMomentum(), particle2.FourMomentum());
  Int_t rec_bin = gen_hist.FindBin(q_out, q_long, q_side);
  if (!(gen_hist.IsBinOverflow(rec_bin) or gen_hist.IsBinUnderflow(rec_bin))) {
    rec_hist.Fill(q_out, q_side, q_long, weight);
    rec_hist_unw.Fill(q_out, q_side, q_long, 1.0);
  }

  // Get generated momentum from hidden info
  const AliFemtoModelHiddenInfo
    *info1 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle1.HiddenInfo()),
    *info2 = dynamic_cast<const AliFemtoModelHiddenInfo*>(particle2.HiddenInfo());

  if (info1 == nullptr || info2 == nullptr) {
    return;
  }

  const Float_t mass1 = info1->GetMass(),
                mass2 = info2->GetMass();

  // block all zero-mass particles from the correlation function
  if (mass1 == 0.0 || mass2 == 0.0) {
    return;
  }

  const AliFemtoThreeVector *true_momentum1 = info1->GetTrueMomentum(),
                            *true_momentum2 = info2->GetTrueMomentum();

  const Double_t e1 = sqrt(mass1 * mass1 + true_momentum1->Mag2()),
                 e2 = sqrt(mass2 * mass2 + true_momentum2->Mag2());

  const AliFemtoLorentzVector p1 = AliFemtoLorentzVector(e1, *true_momentum1),
                              p2 = AliFemtoLorentzVector(e2, *true_momentum2);

  // Fill generated-momentum histogram with "true" particle momentum
  std::tie(q_out, q_side, q_long) = Qcms(p1, p2);
  Int_t gen_bin = gen_hist.FindBin(q_out, q_long, q_side);
  if (!(gen_hist.IsBinOverflow(gen_bin) or gen_hist.IsBinUnderflow(gen_bin))) {
    gen_hist.Fill(q_out, q_side, q_long, weight);
    gen_hist_unw.Fill(q_out, q_side, q_long, weight);
  }
}

void
AliFemtoModelCorrFctnTrueQ3D::AddRealPair(AliFemtoPair *pair)
{
  const AliFemtoParticle *p1 = pair->Track1(),
                         *p2 = pair->Track2();

  // randomize to avoid ordering biases
  if (fRng->Uniform() >= 0.5) {
    std::swap(p1, p2);
  }
  AddPair(*p1, *p2,
          *fNumeratorGenUnweighted,
          *fNumeratorRecUnweighted,
          *fNumeratorGenerated,
          *fNumeratorReconstructed,
          fManager->GetWeight(pair));
}

void
AliFemtoModelCorrFctnTrueQ3D::AddMixedPair(AliFemtoPair *pair)
{
  const AliFemtoParticle *p1 = pair->Track1(),
                         *p2 = pair->Track2();

  // randomize to avoid ordering biases
  if (fRng->Uniform() >= 0.5) {
    std::swap(p1, p2);
  }

  AddPair(*p1, *p2,
          *fDenominatorGenWeighted,
          *fDenominatorRecWeighted,
          *fDenominatorGenerated,
          *fDenominatorReconstructed,
          fManager->GetWeight(pair));
}

AliFemtoString
AliFemtoModelCorrFctnTrueQ3D::Report()
{
  AliFemtoString report;
  return report;
}

void
AliFemtoModelCorrFctnTrueQ3D::Finish()
{
#if ROOT_VERSION_CODE >= ROOT_VERSION(6, 10, 8)
  // remove {under,over}flow to shrink file sizes
  fNumeratorGenerated->ClearUnderflowAndOverflow();
  fNumeratorReconstructed->ClearUnderflowAndOverflow();
  fDenominatorGenerated->ClearUnderflowAndOverflow();
  fDenominatorReconstructed->ClearUnderflowAndOverflow();

  fNumeratorGenUnweighted->ClearUnderflowAndOverflow();
  fNumeratorRecUnweighted->ClearUnderflowAndOverflow();
  fDenominatorGenWeighted->ClearUnderflowAndOverflow();
  fDenominatorRecWeighted->ClearUnderflowAndOverflow();
#endif
}
<|endoftext|>


<commit_before>#pragma once

#include "boost_defs.hpp"

#include "dispatcher.hpp"
#include "iokit_utility.hpp"
#include "logger.hpp"
#include "services.hpp"
#include <boost/signals2.hpp>

namespace krbn {
namespace monitor {
namespace service_monitor {
class service_monitor final : pqrs::dispatcher::extra::dispatcher_client {
public:
  // Signals (invoked from the shared dispatcher thread)

  boost::signals2::signal<void(std::shared_ptr<services>)> service_detected;
  boost::signals2::signal<void(std::shared_ptr<services>)> service_removed;

  // Methods

  service_monitor(const service_monitor&) = delete;

  service_monitor(CFDictionaryRef _Nonnull matching_dictionary) : matching_dictionary_(matching_dictionary),
                                                                  notification_port_(nullptr),
                                                                  matched_notification_(IO_OBJECT_NULL),
                                                                  terminated_notification_(IO_OBJECT_NULL) {
    if (matching_dictionary_) {
      CFRetain(matching_dictionary_);
    }
  }

  virtual ~service_monitor(void) {
    detach_from_dispatcher([this] {
      stop();
    });

    if (matching_dictionary_) {
      CFRelease(matching_dictionary_);
    }
  }

  void async_start(void) {
    enqueue_to_dispatcher([this] {
      start();
    });
  }

  void async_stop(void) {
    enqueue_to_dispatcher([this] {
      stop();
    });
  }

  void async_invoke_service_detected(void) {
    enqueue_to_dispatcher([this] {
      if (matching_dictionary_) {
        CFRetain(matching_dictionary_);
        io_iterator_t it;
        auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matching_dictionary_, &it);
        if (kr != KERN_SUCCESS) {
          logger::get_logger().error("IOServiceGetMatchingServices is failed: {0}",
                                     iokit_utility::get_error_name(kr));
        } else {
          matched_callback(it);
          IOObjectRelease(it);
        }
      }
    });
  }

private:
  // This method is executed in the dispatcher thread.
  void start(void) {
    if (!notification_port_) {
      notification_port_ = IONotificationPortCreate(kIOMasterPortDefault);
      if (!notification_port_) {
        logger::get_logger().error("IONotificationPortCreate is failed.");
        return;
      }

      if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {
        CFRunLoopAddSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);
      } else {
        logger::get_logger().error("IONotificationPortGetRunLoopSource is failed.");
      }
    }

    // kIOMatchedNotification

    if (!matched_notification_) {
      if (matching_dictionary_) {
        CFRetain(matching_dictionary_);
        auto kr = IOServiceAddMatchingNotification(notification_port_,
                                                   kIOFirstMatchNotification,
                                                   matching_dictionary_,
                                                   &(service_monitor::static_matched_callback),
                                                   static_cast<void*>(this),
                                                   &matched_notification_);
        if (kr != kIOReturnSuccess) {
          logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}",
                                     iokit_utility::get_error_name(kr));
          CFRelease(matching_dictionary_);
        } else {
          matched_callback(matched_notification_);
        }
      }
    }

    // kIOTerminatedNotification

    if (!terminated_notification_) {
      if (matching_dictionary_) {
        CFRetain(matching_dictionary_);
        auto kr = IOServiceAddMatchingNotification(notification_port_,
                                                   kIOTerminatedNotification,
                                                   matching_dictionary_,
                                                   &(service_monitor::static_terminated_callback),
                                                   static_cast<void*>(this),
                                                   &terminated_notification_);
        if (kr != kIOReturnSuccess) {
          logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}",
                                     iokit_utility::get_error_name(kr));
          CFRelease(matching_dictionary_);
        } else {
          terminated_callback(terminated_notification_);
        }
      }
    }
  }

  // This method is executed in the dispatcher thread.
  void stop(void) {
    if (matched_notification_) {
      IOObjectRelease(matched_notification_);
      matched_notification_ = IO_OBJECT_NULL;
    }

    if (terminated_notification_) {
      IOObjectRelease(terminated_notification_);
      terminated_notification_ = IO_OBJECT_NULL;
    }

    if (notification_port_) {
      if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {
        CFRunLoopRemoveSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);
      }

      IONotificationPortDestroy(notification_port_);
      notification_port_ = nullptr;
    }
  }

  static void static_matched_callback(void* _Nonnull refcon, io_iterator_t iterator) {
    auto self = static_cast<service_monitor*>(refcon);
    if (!self) {
      return;
    }

    self->matched_callback(iterator);
  }

  void matched_callback(io_iterator_t iterator) {
    auto s = std::make_shared<services>(iterator);
    enqueue_to_dispatcher([this, s] {
      service_detected(s);
    });
  }

  static void static_terminated_callback(void* _Nonnull refcon, io_iterator_t iterator) {
    auto self = static_cast<service_monitor*>(refcon);
    if (!self) {
      return;
    }

    self->terminated_callback(iterator);
  }

  void terminated_callback(io_iterator_t iterator) {
    auto s = std::make_shared<services>(iterator);
    enqueue_to_dispatcher([this, s] {
      service_removed(s);
    });
  }

  CFDictionaryRef _Nonnull matching_dictionary_;

  IONotificationPortRef _Nullable notification_port_;
  io_iterator_t matched_notification_;
  io_iterator_t terminated_notification_;
};
} // namespace service_monitor
} // namespace monitor
} // namespace krbn
<commit_msg>use cf_ptr<commit_after>#pragma once

#include "boost_defs.hpp"

#include "cf_utility.hpp"
#include "dispatcher.hpp"
#include "iokit_utility.hpp"
#include "logger.hpp"
#include "services.hpp"
#include <boost/signals2.hpp>

namespace krbn {
namespace monitor {
namespace service_monitor {
class service_monitor final : pqrs::dispatcher::extra::dispatcher_client {
public:
  // Signals (invoked from the shared dispatcher thread)

  boost::signals2::signal<void(std::shared_ptr<services>)> service_detected;
  boost::signals2::signal<void(std::shared_ptr<services>)> service_removed;

  // Methods

  service_monitor(const service_monitor&) = delete;

  service_monitor(CFDictionaryRef _Nonnull matching_dictionary) : matching_dictionary_(matching_dictionary),
                                                                  notification_port_(nullptr),
                                                                  matched_notification_(IO_OBJECT_NULL),
                                                                  terminated_notification_(IO_OBJECT_NULL) {
  }

  virtual ~service_monitor(void) {
    detach_from_dispatcher([this] {
      stop();
    });
  }

  void async_start(void) {
    enqueue_to_dispatcher([this] {
      start();
    });
  }

  void async_stop(void) {
    enqueue_to_dispatcher([this] {
      stop();
    });
  }

  void async_invoke_service_detected(void) {
    enqueue_to_dispatcher([this] {
      if (*matching_dictionary_) {
        CFRetain(*matching_dictionary_);
        io_iterator_t it;
        auto kr = IOServiceGetMatchingServices(kIOMasterPortDefault, *matching_dictionary_, &it);
        if (kr != KERN_SUCCESS) {
          logger::get_logger().error("IOServiceGetMatchingServices is failed: {0}",
                                     iokit_utility::get_error_name(kr));
        } else {
          matched_callback(it);
          IOObjectRelease(it);
        }
      }
    });
  }

private:
  // This method is executed in the dispatcher thread.
  void start(void) {
    if (!notification_port_) {
      notification_port_ = IONotificationPortCreate(kIOMasterPortDefault);
      if (!notification_port_) {
        logger::get_logger().error("IONotificationPortCreate is failed.");
        return;
      }

      if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {
        CFRunLoopAddSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);
      } else {
        logger::get_logger().error("IONotificationPortGetRunLoopSource is failed.");
      }
    }

    // kIOMatchedNotification

    if (!matched_notification_) {
      if (*matching_dictionary_) {
        CFRetain(*matching_dictionary_);
        auto kr = IOServiceAddMatchingNotification(notification_port_,
                                                   kIOFirstMatchNotification,
                                                   *matching_dictionary_,
                                                   &(service_monitor::static_matched_callback),
                                                   static_cast<void*>(this),
                                                   &matched_notification_);
        if (kr != kIOReturnSuccess) {
          logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}",
                                     iokit_utility::get_error_name(kr));
          CFRelease(*matching_dictionary_);
        } else {
          matched_callback(matched_notification_);
        }
      }
    }

    // kIOTerminatedNotification

    if (!terminated_notification_) {
      if (*matching_dictionary_) {
        CFRetain(*matching_dictionary_);
        auto kr = IOServiceAddMatchingNotification(notification_port_,
                                                   kIOTerminatedNotification,
                                                   *matching_dictionary_,
                                                   &(service_monitor::static_terminated_callback),
                                                   static_cast<void*>(this),
                                                   &terminated_notification_);
        if (kr != kIOReturnSuccess) {
          logger::get_logger().error("IOServiceAddMatchingNotification is failed: {0}",
                                     iokit_utility::get_error_name(kr));
          CFRelease(*matching_dictionary_);
        } else {
          terminated_callback(terminated_notification_);
        }
      }
    }
  }

  // This method is executed in the dispatcher thread.
  void stop(void) {
    if (matched_notification_) {
      IOObjectRelease(matched_notification_);
      matched_notification_ = IO_OBJECT_NULL;
    }

    if (terminated_notification_) {
      IOObjectRelease(terminated_notification_);
      terminated_notification_ = IO_OBJECT_NULL;
    }

    if (notification_port_) {
      if (auto loop_source = IONotificationPortGetRunLoopSource(notification_port_)) {
        CFRunLoopRemoveSource(CFRunLoopGetMain(), loop_source, kCFRunLoopCommonModes);
      }

      IONotificationPortDestroy(notification_port_);
      notification_port_ = nullptr;
    }
  }

  static void static_matched_callback(void* _Nonnull refcon, io_iterator_t iterator) {
    auto self = static_cast<service_monitor*>(refcon);
    if (!self) {
      return;
    }

    self->matched_callback(iterator);
  }

  void matched_callback(io_iterator_t iterator) {
    auto s = std::make_shared<services>(iterator);
    enqueue_to_dispatcher([this, s] {
      service_detected(s);
    });
  }

  static void static_terminated_callback(void* _Nonnull refcon, io_iterator_t iterator) {
    auto self = static_cast<service_monitor*>(refcon);
    if (!self) {
      return;
    }

    self->terminated_callback(iterator);
  }

  void terminated_callback(io_iterator_t iterator) {
    auto s = std::make_shared<services>(iterator);
    enqueue_to_dispatcher([this, s] {
      service_removed(s);
    });
  }

  cf_utility::cf_ptr<CFDictionaryRef> matching_dictionary_;

  IONotificationPortRef _Nullable notification_port_;
  io_iterator_t matched_notification_;
  io_iterator_t terminated_notification_;
};
} // namespace service_monitor
} // namespace monitor
} // namespace krbn
<|endoftext|>


<commit_before>#pragma once

#if ENABLE_S3

#include "ref.hh"

#include <optional>

namespace Aws { namespace Client { class ClientConfiguration; } }
namespace Aws { namespace S3 { class S3Client; } }

namespace nix {

struct S3Helper
{
    ref<Aws::Client::ClientConfiguration> config;
    ref<Aws::S3::S3Client> client;

    S3Helper(const std::string & profile, const std::string & region, const std::string & scheme, const std::string & endpoint);

    ref<Aws::Client::ClientConfiguration> makeConfig(const std::string & region, const std::string & scheme, const std::string & endpoint);

    struct FileTransferResult
    {
        std::optional<std::string> data;
        unsigned int durationMs;
    };

    FileTransferResult getObject(
        const std::string & bucketName, const std::string & key);
};

}

#endif
<commit_msg>Fix libcxx build<commit_after>#pragma once

#if ENABLE_S3

#include "ref.hh"

#include <optional>
#include <string>

namespace Aws { namespace Client { class ClientConfiguration; } }
namespace Aws { namespace S3 { class S3Client; } }

namespace nix {

struct S3Helper
{
    ref<Aws::Client::ClientConfiguration> config;
    ref<Aws::S3::S3Client> client;

    S3Helper(const std::string & profile, const std::string & region, const std::string & scheme, const std::string & endpoint);

    ref<Aws::Client::ClientConfiguration> makeConfig(const std::string & region, const std::string & scheme, const std::string & endpoint);

    struct FileTransferResult
    {
        std::optional<std::string> data;
        unsigned int durationMs;
    };

    FileTransferResult getObject(
        const std::string & bucketName, const std::string & key);
};

}

#endif
<|endoftext|>


<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__

#include <stan/prob/distributions/univariate/continuous/beta.hpp>
#include <stan/prob/distributions/univariate/continuous/cauchy.hpp>
#include <stan/prob/distributions/univariate/continuous/chi_square.hpp>
#include <stan/prob/distributions/univariate/continuous/double_exponential.hpp>
#include <stan/prob/distributions/univariate/continuous/exponential.hpp>
#include <stan/prob/distributions/univariate/continuous/exp_mod_normal.hpp>
#include <stan/prob/distributions/univariate/continuous/gamma.hpp>
#include <stan/prob/distributions/univariate/continuous/gumbel.hpp>
#include <stan/prob/distributions/univariate/continuous/inv_chi_square.hpp>
#include <stan/prob/distributions/univariate/continuous/inv_gamma.hpp>
#include <stan/prob/distributions/univariate/continuous/logistic.hpp>
#include <stan/prob/distributions/univariate/continuous/lognormal.hpp>
#include <stan/prob/distributions/univariate/continuous/normal.hpp>
#include <stan/prob/distributions/univariate/continuous/pareto.hpp>
#include <stan/prob/distributions/univariate/continuous/rayleigh.hpp>
#include <stan/prob/distributions/univariate/continuous/scaled_inv_chi_square.hpp>
#include <stan/prob/distributions/univariate/continuous/skew_normal.hpp>
#include <stan/prob/distributions/univariate/continuous/student_t.hpp>
#include <stan/prob/distributions/univariate/continuous/uniform.hpp>
#include <stan/prob/distributions/univariate/continuous/von_mises.hpp>
#include <stan/prob/distributions/univariate/continuous/weibull.hpp>

#endif
<commit_msg>add wiener to continuous.hpp<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS_HPP__

#include <stan/prob/distributions/univariate/continuous/beta.hpp>
#include <stan/prob/distributions/univariate/continuous/cauchy.hpp>
#include <stan/prob/distributions/univariate/continuous/chi_square.hpp>
#include <stan/prob/distributions/univariate/continuous/double_exponential.hpp>
#include <stan/prob/distributions/univariate/continuous/exponential.hpp>
#include <stan/prob/distributions/univariate/continuous/exp_mod_normal.hpp>
#include <stan/prob/distributions/univariate/continuous/gamma.hpp>
#include <stan/prob/distributions/univariate/continuous/gumbel.hpp>
#include <stan/prob/distributions/univariate/continuous/inv_chi_square.hpp>
#include <stan/prob/distributions/univariate/continuous/inv_gamma.hpp>
#include <stan/prob/distributions/univariate/continuous/logistic.hpp>
#include <stan/prob/distributions/univariate/continuous/lognormal.hpp>
#include <stan/prob/distributions/univariate/continuous/normal.hpp>
#include <stan/prob/distributions/univariate/continuous/pareto.hpp>
#include <stan/prob/distributions/univariate/continuous/rayleigh.hpp>
#include <stan/prob/distributions/univariate/continuous/scaled_inv_chi_square.hpp>
#include <stan/prob/distributions/univariate/continuous/skew_normal.hpp>
#include <stan/prob/distributions/univariate/continuous/student_t.hpp>
#include <stan/prob/distributions/univariate/continuous/uniform.hpp>
#include <stan/prob/distributions/univariate/continuous/von_mises.hpp>
#include <stan/prob/distributions/univariate/continuous/weibull.hpp>
#include <stan/prob/distributions/univariate/continuous/wiener.hpp>

#endif
<|endoftext|>