text:
///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2013 - 2014.
// Copyright John Maddock 2013.
// 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)
//
// This work is based on an earlier work:
// "Algorithm 910: A Portable C++ Multiple-Precision System for Special-Function Calculations",
// in ACM TOMS, {VOL 37, ISSUE 4, (February 2011)} (C) ACM, 2011. http://doi.acm.org/10.1145/1916461.1916469
//

#include <algorithm>
#include <cstdint>
#include <deque>
#include <functional>
#include <iostream>
#include <limits>
#include <numeric>
#include <vector>
#include <boost/math/constants/constants.hpp>
#include <boost/noncopyable.hpp>

//#define USE_CPP_BIN_FLOAT
#define USE_CPP_DEC_FLOAT
//#define USE_MPFR

#if !defined(DIGIT_COUNT)
#define DIGIT_COUNT 100
#endif

#if !defined(BOOST_NO_CXX11_HDR_CHRONO)
  #include <chrono>
  #define STD_CHRONO std::chrono
#else
  #include <boost/chrono.hpp>
  #define STD_CHRONO boost::chrono
#endif

#if defined(USE_CPP_BIN_FLOAT)
  #include <boost/multiprecision/cpp_bin_float.hpp>
  typedef boost::multiprecision::number<boost::multiprecision::cpp_bin_float<DIGIT_COUNT + 10> > mp_type;
#elif defined(USE_CPP_DEC_FLOAT)
  #include <boost/multiprecision/cpp_dec_float.hpp>
  typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<DIGIT_COUNT + 10> > mp_type;
#elif defined(USE_MPFR)
  #include <boost/multiprecision/mpfr.hpp>
  typedef boost::multiprecision::number<boost::multiprecision::mpfr_float_backend<DIGIT_COUNT + 10> > mp_type;
#else
  #error no multiprecision floating type is defined
#endif

template <class clock_type>
struct stopwatch
{
public:
  typedef typename clock_type::duration duration_type;

  stopwatch() : m_start(clock_type::now()) { }

  stopwatch(const stopwatch& other) : m_start(other.m_start) { }

  stopwatch& operator=(const stopwatch& other)
  {
    m_start = other.m_start;
    return *this;
  }

  ~stopwatch() { }

  duration_type elapsed() const
  {
    return (clock_type::now() - m_start);
  }

  void reset()
  {
    m_start = clock_type::now();
  }

private:
  typename clock_type::time_point m_start;
};

namespace my_math
{
  template<class T> T chebyshev_t(const std::int32_t n, const T& x);

  template<class T> T chebyshev_t(const std::uint32_t n, const T& x, std::vector<T>* vp);

  template<class T> bool isneg(const T& x) { return (x < T(0)); }

  template<class T> const T& zero() { static const T value_zero(0); return value_zero; }
  template<class T> const T& one () { static const T value_one (1); return value_one; }
  template<class T> const T& two () { static const T value_two (2); return value_two; }
}

namespace orthogonal_polynomial_series
{
  template<typename T> static inline T orthogonal_polynomial_template(const T& x, const std::uint32_t n, std::vector<T>* const vp = static_cast<std::vector<T>*>(0u))
  {
    // Compute the value of an orthogonal chebyshev polinomial.
    // Use stable upward recursion.

    if(vp != nullptr)
    {
      vp->clear();
      vp->reserve(static_cast<std::size_t>(n + 1u));
    }

    T y0 = my_math::one<T>();

    if(vp != nullptr) { vp->push_back(y0); }

    if(n == static_cast<std::uint32_t>(0u))
    {
      return y0;
    }

    T y1 = x;

    if(vp != nullptr) { vp->push_back(y1); }

    if(n == static_cast<std::uint32_t>(1u))
    {
      return y1;
    }

    T a = my_math::two <T>();
    T b = my_math::zero<T>();
    T c = my_math::one <T>();

    T yk;

    // Calculate higher orders using the recurrence relation.
    // The direction of stability is upward recursion.
    for(std::int32_t k = static_cast<std::int32_t>(2); k <= static_cast<std::int32_t>(n); ++k)
    {
      yk = (((a * x) + b) * y1) - (c * y0);

      y0 = y1;
      y1 = yk;

      if(vp != nullptr) { vp->push_back(yk); }
    }

    return yk;
  }
}

template<class T> T my_math::chebyshev_t(const std::int32_t n, const T& x)
{
  if(my_math::isneg(x))
  {
    const bool b_negate = ((n % static_cast<std::int32_t>(2)) != static_cast<std::int32_t>(0));

    const T y = chebyshev_t(n, -x);

    return (!b_negate ? y : -y);
  }

  if(n < static_cast<std::int32_t>(0))
  {
    const std::int32_t nn = static_cast<std::int32_t>(-n);

    return chebyshev_t(nn, x);
  }
  else
  {
    return orthogonal_polynomial_series::orthogonal_polynomial_template(x, static_cast<std::uint32_t>(n));
  }
}

template<class T> T my_math::chebyshev_t(const std::uint32_t n, const T& x, std::vector<T>* const vp) { return orthogonal_polynomial_series::orthogonal_polynomial_template(x, static_cast<std::int32_t>(n),  vp); }

namespace util
{
  template <class T> float digit_scale()
  {
    const int d = ((std::max)(std::numeric_limits<T>::digits10, 15));
    return static_cast<float>(d) / 300.0F;
  }
}

namespace examples
{
  namespace nr_006
  {
    template<typename T> class hypergeometric_pfq_base : private boost::noncopyable
    {
    public:
      virtual ~hypergeometric_pfq_base() { }

      virtual void ccoef() const = 0;

      virtual T series() const
      {
        using my_math::chebyshev_t;

        // Compute the Chebyshev coefficients.
        // Get the values of the shifted Chebyshev polynomials.
        std::vector<T> chebyshev_t_shifted_values;
        const T z_shifted = ((Z / W) * static_cast<std::int32_t>(2)) - static_cast<std::int32_t>(1);

        chebyshev_t(static_cast<std::uint32_t>(C.size()),
                    z_shifted,
                    &chebyshev_t_shifted_values);

        // Luke: C     ---------- COMPUTE SCALE FACTOR                       ----------
        // Luke: C
        // Luke: C     ---------- SCALE THE COEFFICIENTS                     ----------
        // Luke: C

        // The coefficient scaling is preformed after the Chebyshev summation,
        // and it is carried out with a single division operation.
        bool b_neg = false;

        const T scale = std::accumulate(C.begin(),
                                        C.end(),
                                        T(0),
                                        [&b_neg](T scale_sum, const T& ck) -> T
                                        {
                                          ((!b_neg) ? (scale_sum += ck) : (scale_sum -= ck));
                                          b_neg = (!b_neg);
                                          return scale_sum;
                                        });

        // Compute the result of the series expansion using unscaled coefficients.
        const T sum = std::inner_product(C.begin(),
                                         C.end(),
                                         chebyshev_t_shifted_values.begin(),
                                         T(0));

        // Return the properly scaled result.
        return sum / scale;
      }

    protected:
      const   T             Z;
      const   T             W;
      mutable std::deque<T> C;

      hypergeometric_pfq_base(const T& z,
                              const T& w) : Z(z),
                                            W(w),
                                            C(0u) { }

      virtual std::int32_t N() const { return static_cast<std::int32_t>(util::digit_scale<T>() * 500.0F); }
    };

    template<typename T> class ccoef4_hypergeometric_0f1 : public hypergeometric_pfq_base<T>
    {
    public:
      ccoef4_hypergeometric_0f1(const T& c,
                                const T& z,
                                const T& w) : hypergeometric_pfq_base<T>(z, w),
                                              CP(c) { }

      virtual ~ccoef4_hypergeometric_0f1() { }

      virtual void ccoef() const
      {
        // See Luke 1977 page 80.
        const std::int32_t N1 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(1));
        const std::int32_t N2 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(2));

        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------
        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------
        // Luke: C
        T A3(0);
        T A2(0);
        T A1(boost::math::tools::root_epsilon<T>());

        hypergeometric_pfq_base<T>::C.resize(1u, A1);

        std::int32_t X1 = N2;

        T C1 = T(1) - CP;

        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;

        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)
        {
          const T DIVFAC = T(1) / X1;

          --X1;

          // The terms have been slightly re-arranged resulting in lower complexity.
          // Parentheses have been added to avoid reliance on operator precedence.
          const T term =   (A2 - ((A3 * DIVFAC) * X1))
                         + ((A2 * X1) * ((1 + (C1 + X1)) * Z1))
                         + ((A1 * X1) * ((DIVFAC - (C1 * Z1)) + (X1 * Z1)));

          hypergeometric_pfq_base<T>::C.push_front(term);

          A3 = A2;
          A2 = A1;
          A1 = hypergeometric_pfq_base<T>::C.front();
        }

        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);
      }

    private:
      const T CP;
    };

    template<typename T> class ccoef1_hypergeometric_1f0 : public hypergeometric_pfq_base<T>
    {
    public:
      ccoef1_hypergeometric_1f0(const T& a,
                                const T& z,
                                const T& w) : hypergeometric_pfq_base<T>(z, w),
                                              AP(a) { }

      virtual ~ccoef1_hypergeometric_1f0() { }

      virtual void ccoef() const
      {
        // See Luke 1977 page 67.
        const std::int32_t N1 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(1));
        const std::int32_t N2 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(2));

        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------
        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------
        // Luke: C
        T A2(0);
        T A1(boost::math::tools::root_epsilon<T>());

        hypergeometric_pfq_base<T>::C.resize(1u, A1);

        std::int32_t X1 = N2;

        T V1 = T(1) - AP;

        // Here, we have corrected what appears to be an error in Luke's code.

        // Luke's original code listing has:
        //  AFAC = 2 + FOUR/W
        // But it appears as though the correct form is:
        //  AFAC = 2 - FOUR/W.

        const T AFAC = 2 - (T(4) / hypergeometric_pfq_base<T>::W);

        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)
        {
          --X1;

          // The terms have been slightly re-arranged resulting in lower complexity.
          // Parentheses have been added to avoid reliance on operator precedence.
          const T term = -(((X1 * AFAC) * A1) + ((X1 + V1) * A2)) / (X1 - V1);

          hypergeometric_pfq_base<T>::C.push_front(term);

          A2 = A1;
          A1 = hypergeometric_pfq_base<T>::C.front();
        }

        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);
      }

    private:
      const T AP;

      virtual std::int32_t N() const { return static_cast<std::int32_t>(util::digit_scale<T>() * 1600.0F); }
    };

    template<typename T> class ccoef3_hypergeometric_1f1 : public hypergeometric_pfq_base<T>
    {
    public:
      ccoef3_hypergeometric_1f1(const T& a,
                                const T& c,
                                const T& z,
                                const T& w) : hypergeometric_pfq_base<T>(z, w),
                                              AP(a),
                                              CP(c) { }

      virtual ~ccoef3_hypergeometric_1f1() { }

      virtual void ccoef() const
      {
        // See Luke 1977 page 74.
        const std::int32_t N1 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(1));
        const std::int32_t N2 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(2));

        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------
        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------
        // Luke: C
        T A3(0);
        T A2(0);
        T A1(boost::math::tools::root_epsilon<T>());

        hypergeometric_pfq_base<T>::C.resize(1u, A1);

        std::int32_t X  = N1;
        std::int32_t X1 = N2;

        T XA  =  X + AP;
        T X3A = (X + 3) - AP;

        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;

        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)
        {
          --X;
          --X1;
          --XA;
          --X3A;

          const T X3A_over_X2 = X3A / static_cast<std::int32_t>(X + 2);

          // The terms have been slightly re-arranged resulting in lower complexity.
          // Parentheses have been added to avoid reliance on operator precedence.
          const T PART1 =  A1 * (((X + CP) * Z1) - X3A_over_X2);
          const T PART2 =  A2 * (Z1 * ((X + 3) - CP) + (XA / X1));
          const T PART3 =  A3 * X3A_over_X2;

          const T term = (((PART1 + PART2) + PART3) * X1) / XA;

          hypergeometric_pfq_base<T>::C.push_front(term);

          A3 = A2;
          A2 = A1;
          A1 = hypergeometric_pfq_base<T>::C.front();
        }

        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);
      }

    private:
      const T AP;
      const T CP;
    };

    template<typename T> class ccoef6_hypergeometric_1f2 : public hypergeometric_pfq_base<T>
    {
    public:
      ccoef6_hypergeometric_1f2(const T& a,
                                const T& b,
                                const T& c,
                                const T& z,
                                const T& w) : hypergeometric_pfq_base<T>(z, w),
                                              AP(a),
                                              BP(b),
                                              CP(c) { }

      virtual ~ccoef6_hypergeometric_1f2() { }

      virtual void ccoef() const
      {
        // See Luke 1977 page 85.
        const std::int32_t N1 = static_cast<std::int32_t>(this->N() + static_cast<std::int32_t>(1));

        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------
        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------
        // Luke: C
        T A4(0);
        T A3(0);
        T A2(0);
        T A1(boost::math::tools::root_epsilon<T>());

        hypergeometric_pfq_base<T>::C.resize(1u, A1);

        std::int32_t X  = N1;
        T            PP = X + AP;

        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;

        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)
        {
          --X;
          --PP;

          const std::int32_t TWO_X    = static_cast<std::int32_t>(X * 2);
          const std::int32_t X_PLUS_1 = static_cast<std::int32_t>(X + 1);
          const std::int32_t X_PLUS_3 = static_cast<std::int32_t>(X + 3);
          const std::int32_t X_PLUS_4 = static_cast<std::int32_t>(X + 4);

          const T QQ = T(TWO_X + 3) / static_cast<std::int32_t>(TWO_X + static_cast<std::int32_t>(5));
          const T SS = (X + BP) * (X + CP);

          // The terms have been slightly re-arranged resulting in lower complexity.
          // Parentheses have been added to avoid reliance on operator precedence.
          const T PART1 =   A1 * (((PP - (QQ * (PP + 1))) * 2) + (SS * Z1));
          const T PART2 =  (A2 * (X + 2)) * ((((TWO_X + 1) * PP) / X_PLUS_1) - ((QQ * 4) * (PP + 1)) + (((TWO_X + 3) * (PP + 2)) / X_PLUS_3) + ((Z1 * 2) * (SS - (QQ * (X_PLUS_1 + BP)) * (X_PLUS_1 + CP))));
          const T PART3 =   A3 * ((((X_PLUS_3 - AP) - (QQ * (X_PLUS_4 - AP))) * 2) + (((QQ * Z1) * (X_PLUS_4 - BP)) * (X_PLUS_4 - CP)));
          const T PART4 = ((A4 * QQ) * (X_PLUS_4 - AP)) / X_PLUS_3;

          const T term = (((PART1 - PART2) + (PART3 - PART4)) * X_PLUS_1) / PP;

          hypergeometric_pfq_base<T>::C.push_front(term);

          A4 = A3;
          A3 = A2;
          A2 = A1;
          A1 = hypergeometric_pfq_base<T>::C.front();
        }

        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);
      }

    private:
      const T AP;
      const T BP;
      const T CP;
    };

    template<typename T> class ccoef2_hypergeometric_2f1 : public hypergeometric_pfq_base<T>
    {
    public:
      ccoef2_hypergeometric_2f1(const T& a,
                                const T& b,
                                const T& c,
                                const T& z,
                                const T& w) : hypergeometric_pfq_base<T>(z, w),
                                              AP(a),
                                              BP(b),
                                              CP(c) { }

      virtual ~ccoef2_hypergeometric_2f1() { }

      virtual void ccoef() const
      {
        // See Luke 1977 page 59.
        const std::int32_t N1 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(1));
        const std::int32_t N2 = static_cast<std::int32_t>(N() + static_cast<std::int32_t>(2));

        // Luke: C     ---------- START COMPUTING COEFFICIENTS USING         ----------
        // Luke: C     ---------- BACKWARD RECURRENCE SCHEME                 ----------
        // Luke: C
        T A3(0);
        T A2(0);
        T A1(boost::math::tools::root_epsilon<T>());

        hypergeometric_pfq_base<T>::C.resize(1u, A1);

        std::int32_t X  = N1;
        std::int32_t X1 = N2;
        std::int32_t X3 = static_cast<std::int32_t>((X * 2) + 3);

        T X3A = (X + 3) - AP;
        T X3B = (X + 3) - BP;

        const T Z1 = T(4) / hypergeometric_pfq_base<T>::W;

        for(std::int32_t k = static_cast<std::int32_t>(0); k < N1; ++k)
        {
          --X;
          --X1;
          --X3A;
          --X3B;
          X3 -= 2;

          const std::int32_t X_PLUS_2 = static_cast<std::int32_t>(X + 2);

          const T XAB = T(1) / ((X + AP) * (X + BP));

          // The terms have been slightly re-arranged resulting in lower complexity.
          // Parentheses have been added to avoid reliance on operator precedence.
          const T PART1 = (A1 * X1) * (2 - (((AP + X1) * (BP + X1)) * ((T(X3) / X_PLUS_2) * XAB)) + ((CP + X) * (XAB * Z1)));
          const T PART2 = (A2 * XAB) * ((X3A * X3B) - (X3 * ((X3A + X3B) - 1)) + (((3 - CP) + X) * (X1 * Z1)));
          const T PART3 = (A3 * X1) * (X3A / X_PLUS_2) * (X3B * XAB);

          const T term = (PART1 + PART2) - PART3;

          hypergeometric_pfq_base<T>::C.push_front(term);

          A3 = A2;
          A2 = A1;
          A1 = hypergeometric_pfq_base<T>::C.front();
        }

        hypergeometric_pfq_base<T>::C.front() /= static_cast<std::int32_t>(2);
      }

    private:
      const T AP;
      const T BP;
      const T CP;

      virtual std::int32_t N() const { return static_cast<std::int32_t>(util::digit_scale<T>() * 1600.0F); }
    };

    template<class T> T luke_ccoef4_hypergeometric_0f1(const T& a, const T& x);
    template<class T> T luke_ccoef1_hypergeometric_1f0(const T& a, const T& x);
    template<class T> T luke_ccoef3_hypergeometric_1f1(const T& a, const T& b, const T& x);
    template<class T> T luke_ccoef6_hypergeometric_1f2(const T& a, const T& b, const T& c, const T& x);
    template<class T> T luke_ccoef2_hypergeometric_2f1(const T& a, const T& b, const T& c, const T& x);
  }
}

template<class T>
T examples::nr_006::luke_ccoef4_hypergeometric_0f1(const T& a, const T& x)
{
  const ccoef4_hypergeometric_0f1<T> hypergeometric_0f1_object(a, x, T(-20));

  hypergeometric_0f1_object.ccoef();

  return hypergeometric_0f1_object.series();
}

template<class T>
T examples::nr_006::luke_ccoef1_hypergeometric_1f0(const T& a, const T& x)
{
  const ccoef1_hypergeometric_1f0<T> hypergeometric_1f0_object(a, x, T(-20));

  hypergeometric_1f0_object.ccoef();

  return hypergeometric_1f0_object.series();
}

template<class T>
T examples::nr_006::luke_ccoef3_hypergeometric_1f1(const T& a, const T& b, const T& x)
{
  const ccoef3_hypergeometric_1f1<T> hypergeometric_1f1_object(a, b, x, T(-20));

  hypergeometric_1f1_object.ccoef();

  return hypergeometric_1f1_object.series();
}

template<class T>
T examples::nr_006::luke_ccoef6_hypergeometric_1f2(const T& a, const T& b, const T& c, const T& x)
{
  const ccoef6_hypergeometric_1f2<T> hypergeometric_1f2_object(a, b, c, x, T(-20));

  hypergeometric_1f2_object.ccoef();

  return hypergeometric_1f2_object.series();
}

template<class T>
T examples::nr_006::luke_ccoef2_hypergeometric_2f1(const T& a, const T& b, const T& c, const T& x)
{
  const ccoef2_hypergeometric_2f1<T> hypergeometric_2f1_object(a, b, c, x, T(-20));

  hypergeometric_2f1_object.ccoef();

  return hypergeometric_2f1_object.series();
}

int main()
{
  stopwatch<STD_CHRONO::high_resolution_clock> my_stopwatch;
  float total_time = 0.0F;

  std::vector<mp_type> hypergeometric_0f1_results(20U);
  std::vector<mp_type> hypergeometric_1f0_results(20U);
  std::vector<mp_type> hypergeometric_1f1_results(20U);
  std::vector<mp_type> hypergeometric_2f1_results(20U);
  std::vector<mp_type> hypergeometric_1f2_results(20U);

  const mp_type a(mp_type(3) / 7);
  const mp_type b(mp_type(2) / 3);
  const mp_type c(mp_type(1) / 4);

  std::int_least16_t i;

  std::cout << "test hypergeometric_0f1." << std::endl;
  i = 1U;
  my_stopwatch.reset();

  // Generate a table of values of Hypergeometric0F1.
  // Compare with the Mathematica command:
  // Table[N[HypergeometricPFQ[{}, {3/7}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]
  std::for_each(hypergeometric_0f1_results.begin(),
                hypergeometric_0f1_results.end(),
                [&i, &a](mp_type& new_value)
                {
                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));

                  new_value = examples::nr_006::luke_ccoef4_hypergeometric_0f1(a, x);

                  ++i;
                });

  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();

  // Print the values of Hypergeometric0F1.
  std::for_each(hypergeometric_0f1_results.begin(),
                hypergeometric_0f1_results.end(),
                [](const mp_type& h)
                {
                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;
                });

  std::cout << "test hypergeometric_1f0." << std::endl;
  i = 1U;
  my_stopwatch.reset();

  // Generate a table of values of Hypergeometric1F0.
  // Compare with the Mathematica command:
  // Table[N[HypergeometricPFQ[{3/7}, {}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]
  std::for_each(hypergeometric_1f0_results.begin(),
                hypergeometric_1f0_results.end(),
                [&i, &a](mp_type& new_value)
                {
                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));

                  new_value = examples::nr_006::luke_ccoef1_hypergeometric_1f0(a, x);

                  ++i;
                });

  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();

  // Print the values of Hypergeometric1F0.
  std::for_each(hypergeometric_1f0_results.begin(),
                hypergeometric_1f0_results.end(),
                [](const mp_type& h)
                {
                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;
                });

  std::cout << "test hypergeometric_1f1." << std::endl;
  i = 1U;
  my_stopwatch.reset();

  // Generate a table of values of Hypergeometric1F1.
  // Compare with the Mathematica command:
  // Table[N[HypergeometricPFQ[{3/7}, {2/3}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]
  std::for_each(hypergeometric_1f1_results.begin(),
                hypergeometric_1f1_results.end(),
                [&i, &a, &b](mp_type& new_value)
                {
                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));

                  new_value = examples::nr_006::luke_ccoef3_hypergeometric_1f1(a, b, x);

                  ++i;
                });

  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();

  // Print the values of Hypergeometric1F1.
  std::for_each(hypergeometric_1f1_results.begin(),
                hypergeometric_1f1_results.end(),
                [](const mp_type& h)
                {
                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;
                });

  std::cout << "test hypergeometric_1f2." << std::endl;
  i = 1U;
  my_stopwatch.reset();

  // Generate a table of values of Hypergeometric1F2.
  // Compare with the Mathematica command:
  // Table[N[HypergeometricPFQ[{3/7}, {2/3, 1/4}, -(i*EulerGamma)], 100], {i, 1, 20, 1}]
  std::for_each(hypergeometric_1f2_results.begin(),
                hypergeometric_1f2_results.end(),
                [&i, &a, &b, &c](mp_type& new_value)
                {
                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));

                  new_value = examples::nr_006::luke_ccoef6_hypergeometric_1f2(a, b, c, x);

                  ++i;
                });

  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();

  // Print the values of Hypergeometric1F2.
  std::for_each(hypergeometric_1f2_results.begin(),
                hypergeometric_1f2_results.end(),
                [](const mp_type& h)
                {
                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;
                });

  std::cout << "test hypergeometric_2f1." << std::endl;
  i = 1U;
  my_stopwatch.reset();

  // Generate a table of values of Hypergeometric2F1.
  // Compare with the Mathematica command:
  // Table[N[HypergeometricPFQ[{3/7, 2/3}, {1/4}, -(i * EulerGamma)], 100], {i, 1, 20, 1}]
  std::for_each(hypergeometric_2f1_results.begin(),
                hypergeometric_2f1_results.end(),
                [&i, &a, &b, &c](mp_type& new_value)
                {
                  const mp_type x(-(boost::math::constants::euler<mp_type>() * i));

                  new_value = examples::nr_006::luke_ccoef2_hypergeometric_2f1(a, b, c, x);

                  ++i;
                });

  total_time += STD_CHRONO::duration_cast<STD_CHRONO::duration<float> >(my_stopwatch.elapsed()).count();

  // Print the values of Hypergeometric2F1.
  std::for_each(hypergeometric_2f1_results.begin(),
                hypergeometric_2f1_results.end(),
                [](const mp_type& h)
                {
                  std::cout << std::setprecision(DIGIT_COUNT) << h << std::endl;
                });

  std::cout << "Total execution time = " << std::setprecision(3) << total_time << "s" << std::endl;
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
//
// Expansion Hunter
// Copyright 2016-2019 Illumina, Inc.
// All rights reserved.
//
// Author: Egor Dolzhenko <edolzhenko@illumina.com>
//
// 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.
//
//

#pragma once

#include <cstdint>
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include <boost/optional.hpp>

#include "reads/Read.hh"

namespace ehunter
{
using ReadIdToReadReference = std::unordered_map<std::string, std::reference_wrapper<Read>>;

struct ReadPair
{
    int numMatesSet() const
    {
        return static_cast<int>(firstMate != boost::none) + static_cast<int>(secondMate != boost::none);
    }

    boost::optional<MappedRead> firstMate;
    boost::optional<MappedRead> secondMate;
};

bool operator==(const ReadPair& readPair_a, const ReadPair& readPair_b);

/**
 * Read pair container class
 */
class ReadPairs
{
public:
    typedef std::unordered_map<std::string, ReadPair>::const_iterator const_iterator;
    typedef std::unordered_map<std::string, ReadPair>::iterator iterator;
    const_iterator begin() const { return readPairs_.begin(); }
    const_iterator end() const { return readPairs_.end(); }
    iterator begin() { return readPairs_.begin(); }
    iterator end() { return readPairs_.end(); }

    ReadPairs() = default;
    void Clear();
    void Add(MappedRead read);
    void AddMateToExistingRead(MappedRead mate);

    const ReadPair& operator[](const std::string& fragmentId) const;

    int32_t NumReads() const { return numReads_; }
    int32_t NumCompletePairs() const;

    bool operator==(const ReadPairs& other) const
    {
        return (readPairs_ == other.readPairs_ && numReads_ == other.numReads_);
    }

private:
    std::unordered_map<std::string, ReadPair> readPairs_;
    int32_t numReads_ = 0;
};

}

ext: hh

max_stars_repo_name: AlesMaver/ExpansionHunter

max_issues_repo_name: AlesMaver/ExpansionHunter

max_forks_repo_name: AlesMaver/ExpansionHunter


text:
// Include =====================================================================
#include <boost/python/module.hpp>

// Exports =====================================================================
void Export_pyste_src_implicitly_convertible();
void Export_pyste_src_AxUtil();
void Export_pyste_src_AxTypes();
void Export_pyste_src_AxTaggedValue();
void Export_pyste_src_AxSmartPointer();
void Export_pyste_src_AxPropertyValue();
void Export_pyste_src_AxProperty();
void Export_pyste_src_AxParameter();
void Export_pyste_src_AxObject();
void Export_pyste_src_AxMobSlot();
void Export_pyste_src_AxMob();
void Export_pyste_src_AxMetaDef();
void Export_pyste_src_AxKLVData();
void Export_pyste_src_AxIterator();
void Export_pyste_src_AxInit();
void Export_pyste_src_AxHeader();
void Export_pyste_src_AxFIle();
void Export_pyste_src_AxEssence();
void Export_pyste_src_AxDictionary();
void Export_pyste_src_AxDefObject();
void Export_pyste_src_AxContentStorage();
void Export_pyste_src_AxComponent();
void Export_pyste_src_AxBaseObjIter();
void Export_pyste_src_AxBaseObj();
void Export_pyste_src_AAFTypes();
void Export_pyste_src_AAFTypeDefUIDs();
void Export_pyste_src_AAFPropertyDefs();
void Export_pyste_src_AAFParameterDefs();
void Export_pyste_src_AAFOperationDefs();
void Export_pyste_src_AAFOPDefs();
void Export_pyste_src_AAFInterpolatorDefs();
void Export_pyste_src_AAFFileKinds();
void Export_pyste_src_AAFEssenceFormats();
void Export_pyste_src_AAFDataDefs();
void Export_pyste_src_AAFContainerDefs();
void Export_pyste_src_AAFCompressionDefs();
void Export_pyste_src_AAFCodecDefs();
void Export_pyste_src_AAFClassDefUIDs();

// Module ======================================================================
BOOST_PYTHON_MODULE(core)
{
    Export_pyste_src_implicitly_convertible();
    Export_pyste_src_AxUtil();
    Export_pyste_src_AxTypes();
    Export_pyste_src_AxTaggedValue();
    Export_pyste_src_AxSmartPointer();
    Export_pyste_src_AxPropertyValue();
    Export_pyste_src_AxProperty();
    Export_pyste_src_AxParameter();
    Export_pyste_src_AxObject();
    Export_pyste_src_AxMobSlot();
    Export_pyste_src_AxMob();
    Export_pyste_src_AxMetaDef();
    Export_pyste_src_AxKLVData();
    Export_pyste_src_AxIterator();
    Export_pyste_src_AxInit();
    Export_pyste_src_AxHeader();
    Export_pyste_src_AxFIle();
    Export_pyste_src_AxEssence();
    Export_pyste_src_AxDictionary();
    Export_pyste_src_AxDefObject();
    Export_pyste_src_AxContentStorage();
    Export_pyste_src_AxComponent();
    Export_pyste_src_AxBaseObjIter();
    Export_pyste_src_AxBaseObj();
    Export_pyste_src_AAFTypes();
    Export_pyste_src_AAFTypeDefUIDs();
    Export_pyste_src_AAFPropertyDefs();
    Export_pyste_src_AAFParameterDefs();
    Export_pyste_src_AAFOperationDefs();
    Export_pyste_src_AAFOPDefs();
    Export_pyste_src_AAFInterpolatorDefs();
    Export_pyste_src_AAFFileKinds();
    Export_pyste_src_AAFEssenceFormats();
    Export_pyste_src_AAFDataDefs();
    Export_pyste_src_AAFContainerDefs();
    Export_pyste_src_AAFCompressionDefs();
    Export_pyste_src_AAFCodecDefs();
    Export_pyste_src_AAFClassDefUIDs();
}

ext: cpp

max_stars_repo_name: DIT-Tools/pyaaf

max_issues_repo_name: DIT-Tools/pyaaf

max_forks_repo_name: DIT-Tools/pyaaf


text:
#include "request/DescribeCoverage.h"
#include "QueryBase.h"
#include "WcsConst.h"
#include "WcsConvenience.h"
#include "WcsException.h"
#include "xml/XmlUtils.h"
#include <boost/algorithm/string.hpp>
#include <ctpp2/CDT.hpp>
#include <macgyver/StringConversion.h>
#include <macgyver/TypeName.h>

namespace SmartMet
{
namespace Plugin
{
namespace WCS
{
namespace ba = boost::algorithm;
namespace pt = boost::posix_time;
namespace Request
{
DescribeCoverage::DescribeCoverage(const PluginData& pluginData)
    : RequestBase(),
      mPluginData(pluginData),
      mSupportedFormats({"application/gml+xml; version=3.2",
                         "text/xml; subtype=gml/3.2",
                         "text/xml; version=3.2",
                         "application/gml+xml; subtype=gml/3.2"})
{
}

void DescribeCoverage::setCoverageIds(const std::vector<std::string>& ids)
{
  mIds = ids;
  std::sort(mIds.begin(), mIds.end());
}

DescribeCoverage::~DescribeCoverage() {}
RequestType DescribeCoverage::getType() const
{
  return DESCRIBE_COVERAGE;
}
void DescribeCoverage::execute(std::ostream& output) const
{
  int debugLevel = mPluginData.getConfig().getDebugLevel();

  CTPP::CDT hash;
  const auto& capabilities = mPluginData.getCapabilities();
  const auto& dataSetMap = capabilities.getSupportedDatasets();

  auto fmiApikey = getFmiApikey();
  hash["fmi_apikey"] = fmiApikey ? *fmiApikey : "";
  hash["fmi_apikey_prefix"] = QueryBase::FMI_APIKEY_PREFIX_SUBST;
  auto hostname = getHostname();
  hash["hostname"] = hostname ? *hostname : mPluginData.getConfig().getFallbackHostname();

  int cnt = 0;
  std::set<std::string> validIds;
  std::vector<std::string> invalidIds;
  for (const auto& id : mIds)
  {
    std::string idLower = Fmi::ascii_tolower_copy(id);
    WcsCapabilities::DatasetMap::const_iterator it = dataSetMap.find(idLower);
    if (it == dataSetMap.end())
      invalidIds.push_back(id);
    else
      validIds.insert(idLower);
  }

  if (not invalidIds.empty())
  {
    WcsException wcsException(WcsException::NO_SUCH_COVERAGE,
                              "One of the identifiers passed does not match with any of the "
                              "coverages offered by this server.");
    for (const auto& id : invalidIds)
      wcsException.addText(id);

    throw wcsException;
  }

  const auto querydataEngine = mPluginData.getQuerydataEngine();
  auto& crs_registry = mPluginData.getCrsRegistry();

  for (const auto& id : validIds)
  {
    WcsCapabilities::DatasetMap::const_iterator it = dataSetMap.find(id);
    if (it == dataSetMap.end())
    {
      if (debugLevel > 2)
        std::cout << "Id '" << id << "' skipped\n";
      continue;
    }

    Engine::Querydata::MetaQueryOptions opt;
    opt.setProducer(it->second.getProducer());
    opt.addParameter(it->second.getParameterName());
    std::list<Engine::Querydata::MetaData> metaList = querydataEngine->getEngineMetadata(opt);
    if (metaList.empty())
    {
      std::ostringstream msg;
      msg << "ERROR: Server internal error - "
          << "Meta data not found with the values: producer='" << it->second.getProducer()
          << "' and parameterName='" << it->second.getParameterName() << "'";
      std::cerr << msg.str();
      continue;
    }

    // Skipping the missing Area or Grid cases.
    auto q = querydataEngine->get(it->second.getProducer());
    if (not q->isArea() and q->isGrid())
    {
      if (debugLevel > 2)
        std::cout << "Id '" << id << "' has missing Area or Grid\n";
      continue;
    }
    CTPP::CDT& cov = hash["coverageList"][cnt++];

    bool showHeight = false;
    int crsCode = 0;
    std::string projUri;
    std::string projEpochUri;
    std::string projPressEpochUri;
    std::string projLabels;
    bool swapCoord = false;

    // Get target CRS information from GisEngine.
    const CompoundCRS& compoundcrs = it->second.getDataSetDef()->getCompoundcrs();
    std::string crsName = compoundcrs.getIdentifier();
    crs_registry.get_attribute(crsName, "epsg", &crsCode);
    crs_registry.get_attribute(crsName, "showHeight", &showHeight);
    crs_registry.get_attribute(crsName, "projUri", &projUri);
    crs_registry.get_attribute(crsName, "projEpochUri", &projEpochUri);
    crs_registry.get_attribute(crsName, "projPressEpochUri", &projPressEpochUri);
    crs_registry.get_attribute(crsName, "swapCoord", &swapCoord);

    // EPSG crs code is either 2D or 3D. Compound height is not allowed in the case of 3D.
    unsigned srsDimension = (showHeight ? 3 : 2);
    std::string axisLabels = (swapCoord ? "y x" : "x y");

    if (showHeight)
      axisLabels.append(" z");

    auto abbreviations = compoundcrs.getAbbreviations();
    for (const auto& label : abbreviations->getAbbreviationVector())
    {
      if (not projLabels.empty())
        projLabels.append(" ");
      projLabels.append(label);
    }

    const bool showCompoundcrsHeight = (compoundcrs.getVerticalCRS() ? true : false);
    const bool showCompoundcrsTime = (compoundcrs.getTemporalCRS() ? true : false);

    // Compound height is not allowed in the case of 3D.
    if (showHeight and showCompoundcrsHeight)
    {
      std::ostringstream msg;
      msg << "3D Coordinate Reference System and VerticalCRS of "
          << "compound CRS is not possible to use at the same time."
          << "Check coverageid '" << id << "'configuration. Vertical CRS is '"
          << compoundcrs.getVerticalCRS()->getIdentifier() << "'.";
      WcsException wcsException(WcsException::NO_APPLICABLE_CODE, msg.str());
      throw wcsException;
    }

    unsigned compoundAxisId = 1;
    // Constructing compound CRS URI.
    std::string compoundcrsUri = mPluginData.getConfig().getCompoundcrsUri() + "?";
    compoundcrsUri.append(Fmi::to_string(compoundAxisId++)).append("=").append(crsName);
    if (showCompoundcrsHeight)
    {
      auto& verticalCRS = compoundcrs.getVerticalCRS();
      compoundcrsUri.append("&")
          .append(Fmi::to_string(compoundAxisId++))
          .append("=")
          .append(verticalCRS->getIdentifier());
      axisLabels.append(" z");
      srsDimension++;
    }
    if (showCompoundcrsTime)
    {
      auto& temporalCRS = compoundcrs.getTemporalCRS();
      compoundcrsUri.append("&").append(Fmi::to_string(compoundAxisId++)).append("=");
      compoundcrsUri.append(temporalCRS->getIdentifier());
      axisLabels.append(" t");
      srsDimension++;
    }

    cov["id"] = id;
    cov["subtype"] = it->second.getDataSetDef()->getSubtype();
    cov["fieldName"] = it->second.getParameterName();
    cov["srsName"] = projUri;
    cov["srsNameEpoch"] = projEpochUri;
    cov["srsNamePressEpoch"] = compoundcrsUri;
    cov["srsLabels"] = projLabels;
    cov["axisLabels"] = axisLabels;
    // cov["uomLabels"] = "deg deg";
    cov["srsDimension"] = srsDimension;

    const NFmiArea& area = q->area();

    auto transformation = crs_registry.create_transformation(DATA_CRS_NAME, crsName);
    if (!transformation)
      throw std::runtime_error(
          "Failed to create the needed coordinate transformation for generating positions");

    q->resetLevel();
    q->nextLevel();

    // Define the grid geometry. Coordinate order in the area object
    // is always east-north, so the values are swapped to get correct
    // input order for the tranformation. Output axis order is defined
    // in a crs configuration.
    const NFmiPoint topLeft = transformation->transform(swap(area.TopLeftLatLon(), true));
    const NFmiPoint topRight = transformation->transform(swap(area.TopRightLatLon(), true));
    const NFmiPoint bottomLeft = transformation->transform(swap(area.BottomLeftLatLon(), true));
    const NFmiPoint bottomRight = transformation->transform(swap(area.BottomRightLatLon(), true));

    cov["bottom_left"][0] = bottomLeft.X();
    cov["bottom_left"][1] = bottomLeft.Y();
    cov["top_right"][0] = topRight.X();
    cov["top_right"][1] = topRight.Y();

    const NFmiGrid& grid = q->grid();
    cov["grid_size"][0] = (swapCoord ? grid.YNumber() - 1 : grid.XNumber() - 1);
    cov["grid_size"][1] = (swapCoord ? grid.XNumber() - 1 : grid.YNumber() - 1);

    // If the value is not set the template does not use the dimension.
    if (showHeight or showCompoundcrsHeight)
    {
      cov["grid_size"][2] = 0;
      cov["grid_offset_z"] = 0;
    }
    if (showCompoundcrsTime)
    {
      cov["grid_size"][3] = (metaList.front().nTimeSteps - 1);
      cov["grid_offset_t"] = 60 * metaList.front().timeStep;
    }

    unsigned long maxXInd = grid.XNumber() - 1;
    unsigned long maxYInd = grid.YNumber() - 1;
    unsigned long maxInd = grid.XNumber() * grid.YNumber() - 1;
    cov["max_x_ind"] = maxXInd;
    cov["max_y_ind"] = maxYInd;
    cov["max_ind"] = maxInd;

    double blTlX = (topLeft.X() - bottomLeft.X()) / maxYInd;
    double blTlY = (topLeft.Y() - bottomLeft.Y()) / maxYInd;
    double blBrX = (bottomRight.X() - bottomLeft.X()) / maxXInd;
    double blBrY = (bottomRight.Y() - bottomLeft.Y()) / maxXInd;

    cov["grid_offset_x"][0] = (swapCoord ? blTlX : blBrX);
    cov["grid_offset_x"][1] = (swapCoord ? blTlY : blBrY);
    cov["grid_offset_y"][0] = (swapCoord ? blBrX : blTlX);
    cov["grid_offset_y"][1] = (swapCoord ? blBrY : blTlY);

    cov["bbox_bl"][0] = bottomLeft.X();
    cov["bbox_bl"][1] = bottomLeft.Y();
    cov["bbox_tr"][0] = topRight.X();
    cov["bbox_tr"][1] = topRight.Y();

    int gmCnt = 0;
    q->resetTime();
    q->nextTime();
    cov["bbox_time"][0] = epochToString(q->validTime().PosixTime(), "iso-8901");
    cov["epoch_time"][0] = epochToString(q->validTime().PosixTime());
    q->lastTime();
    cov["bbox_time"][1] = epochToString(q->validTime().PosixTime(), "iso-8901");
    cov["epoch_time"][1] = epochToString(q->validTime().PosixTime());

    double levelValue = static_cast<double>(q->level().LevelValue());
    double levelValueMin = levelValue;
    double levelValueMax = levelValue;
    do
    {
      CTPP::CDT& gmhash = cov["gm"][gmCnt++];
      levelValue = q->level().LevelValue();
      gmhash["level"] = levelValue;
      if (levelValueMin > levelValue)
        levelValueMin = levelValue;
      if (levelValueMax < levelValue)
        levelValueMax = levelValue;
    } while (q->nextLevel());
    cov["elevation"][0] = levelValueMin;
    cov["elevation"][1] = levelValueMax;
  }

  hash["language"] =
      (mAcceptLanguages.size() ? mAcceptLanguages.at(0) : mPluginData.getLanguages().at(0));

  std::string logMessages;
  try
  {
    auto formatter = mPluginData.getDescribeCoverageFormatter();
    assert(formatter != 0);
    std::string response;
    formatter->process(hash, response, logMessages);
    substituteAll(response, output);
  }
  catch (const std::exception&)
  {
    std::ostringstream msg;
    msg << METHOD_NAME << ": template formatter exception '" << Fmi::current_exception_type()
        << "' catched: " << logMessages;
    throw WcsException(WcsException::OPERATION_PROCESSING_FAILED, msg.str());
  }
}

boost::shared_ptr<DescribeCoverage> DescribeCoverage::createFromKvp(
    const Spine::HTTP::Request& httpRequest, const PluginData& pluginData)
{
  auto ids = httpRequest.getParameterList("coverageid");
  for (auto& id : ids)
  {
    ba::trim(id);
  }

  boost::shared_ptr<DescribeCoverage> request;
  request.reset(new DescribeCoverage(pluginData));
  request->setCoverageIds(ids);
  request->checkKvpAttributes(httpRequest);
  request->checkCoverageIds();
  request->checkKvpAcceptLanguages(httpRequest);

  return request;
}

boost::shared_ptr<DescribeCoverage> DescribeCoverage::createFromXml(
    const xercesc::DOMDocument& document, const PluginData& pluginData)
{
  const xercesc::DOMElement* root = RequestBase::getXmlRoot(document);
  std::vector<std::string> ids;
  std::vector<xercesc::DOMElement*> elems =
      Xml::get_child_elements(*root, WCS_NAMESPACE_URI, "CoverageId");

  for (const xercesc::DOMElement* elem : elems)
  {
    const std::string value = ba::trim_copy(Xml::extract_text(*elem));
    if (not value.empty())
    {
      ids.push_back(value);
    }
  }

  boost::shared_ptr<DescribeCoverage> request;
  request.reset(new DescribeCoverage(pluginData));
  request->setCoverageIds(ids);
  request->checkXmlAttributes(document);
  request->checkCoverageIds();
  request->checkXmlAcceptLanguages(document);

  return request;
}

void DescribeCoverage::checkKvpAttributes(const Spine::HTTP::Request& httpRequest)
{
  checkRequestName(httpRequest, "DescribeCoverage");
  checkServiceName(httpRequest, "WCS");
  checkWcsVersion(httpRequest, mPluginData.getCapabilities().getSupportedVersions());
}
void DescribeCoverage::checkKvpAcceptLanguages(const Spine::HTTP::Request& httpRequest)
{
  std::vector<std::string> languages;
  auto languagesStr = httpRequest.getParameter("AcceptLanguages");
  if (languagesStr)
  {
    ba::split(languages, *languagesStr, ba::is_any_of(","));
  }
  checkLanguages(mPluginData.getLanguages(), languages);
}

void DescribeCoverage::checkXmlAttributes(const xercesc::DOMDocument& document)
{
  checkRequestName(document, "DescribeCoverage");
  checkServiceName(document, "WCS");
  checkWcsVersion(document, mPluginData.getCapabilities().getSupportedVersions());
}

void DescribeCoverage::checkXmlAcceptLanguages(const xercesc::DOMDocument& document)
{
  std::vector<std::string> languages;
  const xercesc::DOMElement* root = RequestBase::getXmlRoot(document);
  std::vector<xercesc::DOMElement*> extensionElems =
      Xml::get_child_elements(*root, WCS_NAMESPACE_URI, "Extension");
  if (not extensionElems.empty())
  {
    std::vector<xercesc::DOMElement*> acceptlanguagesElems =
        Xml::get_child_elements(*extensionElems.at(0), OWS_NAMESPACE_URI, "AcceptLanguages");
    if (not acceptlanguagesElems.empty())
    {
      std::vector<xercesc::DOMElement*> elems =
          Xml::get_child_elements(*acceptlanguagesElems.at(0), OWS_NAMESPACE_URI, "Language");

      for (const xercesc::DOMElement* elem : elems)
      {
        languages.push_back(Xml::extract_text(*elem));
      }
    }
  }
  checkLanguages(mPluginData.getLanguages(), languages);
}

void DescribeCoverage::checkCoverageIds()
{
  if (mIds.empty())
  {
    WcsException err(WcsException::EMPTY_COVERAGE_ID_LIST, "Mandatory parameter value not found.");
    err.setLocation("CoverageId");
    throw err;
  }
}

void DescribeCoverage::checkLanguages(const std::vector<std::string>& languagesAccepted,
                                      const std::vector<std::string>& languages)
{
  if (languages.empty())
  {
    mAcceptLanguages = languagesAccepted;
    return;
  }

  const std::string langAnyStr = "any";
  bool languageAnyOk = false;
  for (auto& lang : languages)
  {
    ba::trim_copy(lang);
    if (lang == langAnyStr)
      languageAnyOk = true;

    if (std::find(languagesAccepted.begin(), languagesAccepted.end(), lang) !=
            languagesAccepted.end() or
        languageAnyOk)
    {
      if (mAcceptLanguages.empty() and languageAnyOk)
      {
        mAcceptLanguages = languagesAccepted;
        break;
      }
      if (languageAnyOk)
        break;
      else
        mAcceptLanguages.push_back(lang);
    }
  }
  if (not languageAnyOk)
  {
    std::ostringstream msg;
    msg << "Mandatory parameter value '" << langAnyStr << "' not found.";
    WcsException err(WcsException::MISSING_PARAMETER_VALUE, msg.str());
    err.setLocation("AcceptLanguages");
    throw err;
  }
}

int DescribeCoverage::getResponseExpiresSeconds() const
{
  return mPluginData.getConfig().getDefaultExpiresSeconds();
}

NFmiPoint DescribeCoverage::transform(
    const std::unique_ptr<OGRCoordinateTransformation>& transformation, const NFmiPoint&& p) const
{
  double x = p.X();
  double y = p.Y();
  if (not transformation->Transform(1, &x, &y))
  {
    std::ostringstream msg;
    msg << "Transformation failed from '" << transformation->GetSourceCS()->GetEPSGGeogCS()
        << "' to '" << transformation->GetTargetCS()->GetEPSGGeogCS() << "'.";
    WcsException err(WcsException::OPERATION_PROCESSING_FAILED, msg.str());
    throw err;
  }

  return NFmiPoint(x, y);
}

std::string DescribeCoverage::epochToString(const pt::ptime&& epoch,
                                            const std::string&& encodingStyle) const
{
  if (encodingStyle == "iso-8901")
    return Fmi::to_iso_extended_string(epoch) + "Z";
  else
  {
    static const long refJd = boost::gregorian::date(1970, 1, 1).julian_day();
    long long jd = epoch.date().julian_day();
    long seconds = epoch.time_of_day().total_seconds();
    INT_64 sEpoch = 86400LL * (jd - refJd) + seconds;
    return Fmi::to_string(sEpoch);
  }
}
}  // namespace Request
}  // namespace WCS
}  // namespace Plugin
}  // namespace SmartMet

max_stars_repo_name: fmidev/smartmet-plugin-wcs

max_issues_repo_name: fmidev/smartmet-plugin-wcs

max_forks_repo_name: fmidev/smartmet-plugin-wcs


text:
/*
	This file is part of solidity.

	solidity is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	solidity is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with solidity.  If not, see <http://www.gnu.org/licenses/>.
*/
/**
 * @author Christian <c@ethdev.com>
 * @date 2015
 * Tests for high level features like import.
 */

#include <test/libsolidity/ErrorCheck.h>

#include <libsolidity/interface/Exceptions.h>
#include <libsolidity/interface/CompilerStack.h>

#include <boost/test/unit_test.hpp>

#include <string>

using namespace std;

namespace dev
{
namespace solidity
{
namespace test
{

BOOST_AUTO_TEST_SUITE(SolidityImports)

BOOST_AUTO_TEST_CASE(smoke_test)
{
	CompilerStack c;
	c.addSource("a", "contract C {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(regular_import)
{
	CompilerStack c;
	c.addSource("a", "contract C {} pragma solidity >=0.0;");
	c.addSource("b", "import \"a\"; contract D is C {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(import_does_not_clutter_importee)
{
	CompilerStack c;
	c.addSource("a", "contract C { D d; } pragma solidity >=0.0;");
	c.addSource("b", "import \"a\"; contract D is C {} pragma solidity >=0.0;");
	BOOST_CHECK(!c.compile());
}

BOOST_AUTO_TEST_CASE(import_is_transitive)
{
	CompilerStack c;
	c.addSource("a", "contract C { } pragma solidity >=0.0;");
	c.addSource("b", "import \"a\"; pragma solidity >=0.0;");
	c.addSource("c", "import \"b\"; contract D is C {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(circular_import)
{
	CompilerStack c;
	c.addSource("a", "import \"b\"; contract C { D d; } pragma solidity >=0.0;");
	c.addSource("b", "import \"a\"; contract D { C c; } pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(relative_import)
{
	CompilerStack c;
	c.addSource("a", "import \"./dir/b\"; contract A is B {} pragma solidity >=0.0;");
	c.addSource("dir/b", "contract B {} pragma solidity >=0.0;");
	c.addSource("dir/c", "import \"../a\"; contract C is A {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(relative_import_multiplex)
{
	CompilerStack c;
	c.addSource("a", "contract A {} pragma solidity >=0.0;");
	c.addSource("dir/a/b/c", "import \"../../.././a\"; contract B is A {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(simple_alias)
{
	CompilerStack c;
	c.addSource("a", "contract A {} pragma solidity >=0.0;");
	c.addSource("dir/a/b/c", "import \"../../.././a\" as x; contract B is x.A { function() { x.A r = x.A(20); } } pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(library_name_clash)
{
	CompilerStack c;
	c.addSource("a", "library A {} pragma solidity >=0.0;");
	c.addSource("b", "library A {} pragma solidity >=0.0;");
	c.addSource("c", "import {A} from \"./a\"; import {A} from \"./b\";");
	BOOST_CHECK(!c.compile());
}

BOOST_AUTO_TEST_CASE(library_name_clash_with_contract)
{
	CompilerStack c;
	c.addSource("a", "contract A {} pragma solidity >=0.0;");
	c.addSource("b", "library A {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(complex_import)
{
	CompilerStack c;
	c.addSource("a", "contract A {} contract B {} contract C { struct S { uint a; } } pragma solidity >=0.0;");
	c.addSource("b", "import \"a\" as x; import {B as b, C as c, C} from \"a\"; "
				"contract D is b { function f(c.S var1, x.C.S var2, C.S var3) internal {} } pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(name_clash_in_import)
{
	CompilerStack c;
	c.addSource("a", "contract A {} pragma solidity >=0.0;");
	c.addSource("b", "import \"a\"; contract A {} pragma solidity >=0.0;");
	BOOST_CHECK(!c.compile());
	c.addSource("b", "import \"a\" as A; contract A {} pragma solidity >=0.0;");
	BOOST_CHECK(!c.compile());
	c.addSource("b", "import {A as b} from \"a\"; contract b {} pragma solidity >=0.0;");
	BOOST_CHECK(!c.compile());
	c.addSource("b", "import {A} from \"a\"; contract A {} pragma solidity >=0.0;");
	BOOST_CHECK(!c.compile());
	c.addSource("b", "import {A} from \"a\"; contract B {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(remappings)
{
	CompilerStack c;
	c.setRemappings(vector<string>{"s=s_1.4.6", "t=Tee"});
	c.addSource("a", "import \"s/s.sol\"; contract A is S {} pragma solidity >=0.0;");
	c.addSource("b", "import \"t/tee.sol\"; contract A is Tee {} pragma solidity >=0.0;");
	c.addSource("s_1.4.6/s.sol", "contract S {} pragma solidity >=0.0;");
	c.addSource("Tee/tee.sol", "contract Tee {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(context_dependent_remappings)
{
	CompilerStack c;
	c.setRemappings(vector<string>{"a:s=s_1.4.6", "b:s=s_1.4.7"});
	c.addSource("a/a.sol", "import \"s/s.sol\"; contract A is SSix {} pragma solidity >=0.0;");
	c.addSource("b/b.sol", "import \"s/s.sol\"; contract B is SSeven {} pragma solidity >=0.0;");
	c.addSource("s_1.4.6/s.sol", "contract SSix {} pragma solidity >=0.0;");
	c.addSource("s_1.4.7/s.sol", "contract SSeven {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(filename_with_period)
{
	CompilerStack c;
	c.addSource("a/a.sol", "import \".b.sol\"; contract A is B {} pragma solidity >=0.0;");
	c.addSource("a/.b.sol", "contract B {} pragma solidity >=0.0;");
	BOOST_CHECK(!c.compile());
}

BOOST_AUTO_TEST_CASE(context_dependent_remappings_ensure_default_and_module_preserved)
{
	CompilerStack c;
	c.setRemappings(vector<string>{"foo=vendor/foo_2.0.0", "vendor/bar:foo=vendor/foo_1.0.0", "bar=vendor/bar"});
	c.addSource("main.sol", "import \"foo/foo.sol\"; import {Bar} from \"bar/bar.sol\"; contract Main is Foo2, Bar {} pragma solidity >=0.0;");
	c.addSource("vendor/bar/bar.sol", "import \"foo/foo.sol\"; contract Bar {Foo1 foo;} pragma solidity >=0.0;");
	c.addSource("vendor/foo_1.0.0/foo.sol", "contract Foo1 {} pragma solidity >=0.0;");
	c.addSource("vendor/foo_2.0.0/foo.sol", "contract Foo2 {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
}

BOOST_AUTO_TEST_CASE(context_dependent_remappings_order_independent)
{
	CompilerStack c;
	c.setRemappings(vector<string>{"a:x/y/z=d", "a/b:x=e"});
	c.addSource("a/main.sol", "import \"x/y/z/z.sol\"; contract Main is D {} pragma solidity >=0.0;");
	c.addSource("a/b/main.sol", "import \"x/y/z/z.sol\"; contract Main is E {} pragma solidity >=0.0;");
	c.addSource("d/z.sol", "contract D {} pragma solidity >=0.0;");
	c.addSource("e/y/z/z.sol", "contract E {} pragma solidity >=0.0;");
	BOOST_CHECK(c.compile());
	CompilerStack d;
	d.setRemappings(vector<string>{"a/b:x=e", "a:x/y/z=d"});
	d.addSource("a/main.sol", "import \"x/y/z/z.sol\"; contract Main is D {} pragma solidity >=0.0;");
	d.addSource("a/b/main.sol", "import \"x/y/z/z.sol\"; contract Main is E {} pragma solidity >=0.0;");
	d.addSource("d/z.sol", "contract D {} pragma solidity >=0.0;");
	d.addSource("e/y/z/z.sol", "contract E {} pragma solidity >=0.0;");
	BOOST_CHECK(d.compile());
}

BOOST_AUTO_TEST_CASE(shadowing_via_import)
{
	CompilerStack c;
	c.addSource("a", "library A {} pragma solidity >=0.0;");
	c.addSource("b", "library A {} pragma solidity >=0.0;");
	c.addSource("c", "import {A} from \"./a\"; import {A} from \"./b\";");
	BOOST_CHECK(!c.compile());
}

BOOST_AUTO_TEST_CASE(shadowing_builtins_with_imports)
{
	CompilerStack c;
	c.addSource("B.sol", "contract X {} pragma solidity >=0.0;");
	c.addSource("b", R"(
		pragma solidity >=0.0;
		import * as msg from "B.sol";
		contract C {
		}
	)");
	BOOST_CHECK(c.compile());
	size_t errorCount = 0;
	for (auto const& e: c.errors())
	{
		string const* msg = e->comment();
		BOOST_REQUIRE(msg);
		if (msg->find("pre-release") != string::npos)
			continue;
		BOOST_CHECK(
			msg->find("shadows a builtin symbol") != string::npos
		);
		errorCount++;
	}
	BOOST_CHECK_EQUAL(errorCount, 1);
}

BOOST_AUTO_TEST_CASE(shadowing_builtins_with_multiple_imports)
{
	CompilerStack c;
	c.addSource("B.sol", "contract msg {} contract block{} pragma solidity >=0.0;");
	c.addSource("b", R"(
		pragma solidity >=0.0;
		import {msg, block} from "B.sol";
		contract C {
		}
	)");
	BOOST_CHECK(c.compile());
	auto numErrors = c.errors().size();
	// Sometimes we get the prerelease warning, sometimes not.
	BOOST_CHECK(4 <= numErrors && numErrors <= 5);
	for (auto const& e: c.errors())
	{
		string const* msg = e->comment();
		BOOST_REQUIRE(msg);
		BOOST_CHECK(
			msg->find("pre-release") != string::npos ||
			msg->find("shadows a builtin symbol") != string::npos
		);
	}
}

BOOST_AUTO_TEST_SUITE_END()

}
}
} // end namespaces

max_stars_repo_name: jansenbarabona/NFT-Game-Development

max_issues_repo_name: jansenbarabona/NFT-Game-Development

max_forks_repo_name: jansenbarabona/NFT-Game-Development


text:
#include <rtw/socket/udp_socket.h>

#include <chrono>
#include <iostream>

#include <boost/bind.hpp>

namespace rtw {

udp_socket::udp_socket()
: io_service_{  }
, thread_{  }
, local_ip_address_{ "0.0.0.0" }
, local_port_number_{ 0 }
, remote_ip_address_{ "127.0.0.1" }
, remote_port_number_{ 0 }
, socket_{ io_service_ }
, receive_buff_{  }
, receive_callback_{  }
, is_started_{ false }
{

}

void udp_socket::start_io_service()
{
    thread_ = std::thread([this]() -> void {
        io_service_.reset();
        io_service_.run();
    });
}

void udp_socket::stop_io_service()
{
    io_service_.stop();
    if (thread_.joinable()) {
        thread_.join();
    }
}

void udp_socket::open()
{
    // open socket
    boost::asio::ip::udp protocol = boost::asio::ip::udp::v4();
    boost::system::error_code error_code;
    socket_.open(protocol, error_code);
    if (error_code.value() != 0) {
        std::cout << "failed to open a socket. error code = " << error_code.value() << ", message: " << error_code.message() << std::endl;
    }

    // set sock opt
    socket_.set_option(boost::asio::socket_base::reuse_address(true), error_code);
    if (error_code.value() != 0) {
        std::cout << "failed to set a socket option. error code = " << error_code.value() << ", message: " << error_code.message() << std::endl;
    }

    // create a local endpoint
    boost::asio::ip::address address = boost::asio::ip::address::from_string(local_ip_address_, error_code);
    if (error_code.value() != 0) {
        std::cout << "failed to parse the ip address. error code = " << error_code.value() << ", message: " << error_code.message() << std::endl;
    }
    boost::asio::ip::udp::endpoint endpoint{ address, local_port_number_ };

    // bind a socket to a local endpoint
    socket_.bind(endpoint, error_code);
    if (error_code.value() != 0) {
        std::cout << "failed to bind a socket. error code = " << error_code.value() << ", message: " << error_code.message() << std::endl;
    }
}

void udp_socket::receive()
{
    // create a remote endpoint
    boost::system::error_code error_code;
    boost::asio::ip::address address = boost::asio::ip::address::from_string(remote_ip_address_, error_code);
    if (error_code.value() != 0) {
        std::cout << "failed to parse the ip address. error code = " << error_code.value() << ", message: " << error_code.message() << std::endl;
    }
    // async read from
    boost::asio::ip::udp::endpoint endpoint{ address, remote_port_number_ };
    socket_.async_receive_from(receive_buff_.prepare(65536), endpoint, boost::bind(&udp_socket::on_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}

void udp_socket::on_receive(const boost::system::error_code& error, std::size_t bytes_transferred)
{
    if (error) {
        std::cout << "receive failed: " << error.message() << std::endl;
        close();
        open();
        receive();
    }
    else {
        if (receive_callback_) {
            receive_callback_(boost::asio::buffer_cast<const unsigned char*>(receive_buff_.data()), bytes_transferred);
        }
        receive_buff_.consume(receive_buff_.size());
        receive();
    }
}

void udp_socket::on_send(const boost::system::error_code& error, std::size_t bytes_transferred, std::shared_ptr<std::vector<unsigned char>>)
{
    if (error.value() != 0) {
        std::cout << "failed to send. error code = " << error.value() << ", message: " << error.message() << std::endl;
    }
}

void udp_socket::close()
{
    // close
    boost::system::error_code error;
    socket_.close(error);
    if (error) {
        std::cout << "close failed: " << error.message() << std::endl;
    }

    // clear buffer
    receive_buff_.consume(receive_buff_.size());
}

bool udp_socket::start(std::function<void(const unsigned char*, std::size_t)> receive_callback, const std::string& remote_ip_address, unsigned short remote_port_number, const std::string& local_ip_address, unsigned short local_port_number)
{
    if (is_started_) {
        return false;
    }
    is_started_ = true;
    receive_callback_ = receive_callback;
    remote_ip_address_ = remote_ip_address;
    remote_port_number_ = remote_port_number;
    local_ip_address_ = local_ip_address;
    local_port_number_ = local_port_number;
    open();
    receive();
    start_io_service();
    return true;
}

bool udp_socket::send(const std::vector<unsigned char>& data)
{
    if (!is_started_) {
        return false;
    }
    // create a remote endpoint
    boost::system::error_code error_code;
    boost::asio::ip::address address = boost::asio::ip::address::from_string(remote_ip_address_, error_code);
    if (error_code.value() != 0) {
        std::cout << "failed to parse the ip address. error code = " << error_code.value() << ", message: " << error_code.message() << std::endl;
        return false;
    }
    boost::asio::ip::udp::endpoint endpoint{ address, remote_port_number_ };
    // async send to
    std::shared_ptr<std::vector<unsigned char>> buffer = std::make_shared<std::vector<unsigned char>>(data);
    socket_.async_send_to(boost::asio::buffer(*buffer), endpoint, boost::bind(&udp_socket::on_send, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, buffer));
    return true;
}

bool udp_socket::send(const unsigned char* data, std::size_t size)
{
    if (!is_started_) {
        return false;
    }
    // create a remote endpoint
    boost::system::error_code error_code;
    boost::asio::ip::address address = boost::asio::ip::address::from_string(remote_ip_address_, error_code);
    if (error_code.value() != 0) {
        std::cout << "failed to parse the ip address. error code = " << error_code.value() << ", message: " << error_code.message() << std::endl;
        return false;
    }
    boost::asio::ip::udp::endpoint endpoint{ address, remote_port_number_ };
    // async send to
    std::shared_ptr<std::vector<unsigned char>> buffer = std::make_shared<std::vector<unsigned char>>(data, data + size);
    socket_.async_send_to(boost::asio::buffer(*buffer), endpoint, boost::bind(&udp_socket::on_send, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, buffer));
    return true;
}

bool udp_socket::stop()
{
    if (!is_started_) {
        return false;
    }
    is_started_ = false;
    stop_io_service();
    close();
    return true;
}

bool udp_socket::is_started() const
{
    return is_started_;
}

} // namespace rtw

max_stars_repo_name: masahisa/rtw

max_issues_repo_name: masahisa/rtw

max_forks_repo_name: masahisa/rtw


text:
// Copyright (c) 2019 The Bitcoin SV developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "config.h"
#include "key.h"
#include "pubkey.h"
#include "test/test_bitcoin.h"
#include "txmempool.h"
#include "txn_validator.h"

#include <boost/test/unit_test.hpp>

namespace {
    std::vector<TxSource> vTxSources {
        TxSource::wallet,
        TxSource::rpc,
        TxSource::file,
        TxSource::p2p,
        TxSource::reorg,
        TxSource::unknown,
        TxSource::finalised
    };
    // An exception thrown by GetValueOut .
    bool GetValueOutException(const std::runtime_error &e) {
        static std::string expectedException("GetValueOut: value out of range");
        return expectedException == e.what();
    }
    // Support for P2P node.
    CService ip(uint32_t i) {
        struct in_addr s;
        s.s_addr = i;
        return CService(CNetAddr(s), Params().GetDefaultPort());
    }
    // Create scriptPubKey from a given key
    CScript GetScriptPubKey(CKey& key) {
        CScript scriptPubKey = CScript() << ToByteVector(key.GetPubKey())
                                         << OP_CHECKSIG;
        return scriptPubKey;
    }
    // Create a double spend txn
    CMutableTransaction CreateDoubleSpendTxn(CTransaction& fundTxn,
                                       CKey& key,
                                       CScript& scriptPubKey) {
        static uint32_t dummyLockTime = 0;
        CMutableTransaction spend_txn;
        spend_txn.nVersion = 1;
        spend_txn.nLockTime = ++dummyLockTime;
        spend_txn.vin.resize(1);
        spend_txn.vin[0].prevout = COutPoint(fundTxn.GetId(), 0);
        spend_txn.vout.resize(1);
        spend_txn.vout[0].nValue = 11 * CENT;
        spend_txn.vout[0].scriptPubKey = scriptPubKey;
        // Sign:
        std::vector<uint8_t> vchSig {};
        uint256 hash = SignatureHash(scriptPubKey, CTransaction(spend_txn), 0,
                                     SigHashType().withForkId(),
                                     fundTxn.vout[0].nValue);
        BOOST_CHECK(key.Sign(hash, vchSig));
        vchSig.push_back(uint8_t(SIGHASH_ALL | SIGHASH_FORKID));
        spend_txn.vin[0].scriptSig << vchSig;
        return spend_txn;
    }
    // Make N unique large (but rubbish) transactions
    std::vector<CMutableTransaction> MakeNLargeTxns(size_t nNumTxns,
                                                    CTransaction& fundTxn,
                                                    CScript& scriptPubKey) {
        std::vector<CMutableTransaction> res {};
        for (size_t i=0; i<nNumTxns; i++) {
            CMutableTransaction txn;
            txn.nVersion = 1;
            txn.vin.resize(1);
            txn.vin[0].prevout = COutPoint(fundTxn.GetId(), i);
            txn.vout.resize(1000);
            for(size_t j=0; j<1000; ++j) {
                txn.vout[j].nValue = 11 * CENT;
                txn.vout[j].scriptPubKey = scriptPubKey;
            }
            res.emplace_back(txn);
        }
        return res;
    }
    // Create N double spend txns from the given fund txn
    std::vector<CMutableTransaction> CreateNDoubleSpendTxns(size_t nSpendTxns,
                                                      CTransaction& fundTxn,
                                                      CKey& key,
                                                      CScript& scriptPubKey) {
        // Create txns spending the same coinbase txn.
        std::vector<CMutableTransaction> spends {};
        for (size_t i=0; i<nSpendTxns; i++) {
            spends.emplace_back(CreateDoubleSpendTxn(fundTxn, key, scriptPubKey));
        };
        return spends;
    }
    // Create txn input data for a given txn and source
    TxInputDataSPtr TxInputData(TxSource source,
                                CMutableTransaction& spend,
                                std::shared_ptr<CNode> pNode = nullptr) {
        // Return txn's input data
        return std::make_shared<CTxInputData>(
                   g_connman->GetTxIdTracker(), // a pointer to the TxIdTracker
                   MakeTransactionRef(spend),// a pointer to the tx
                   source,   // tx source
                   TxValidationPriority::normal, // tx validation priority
                   GetTime(),// nAcceptTime
                   false,    // mfLimitFree
                   Amount(0), // nAbsurdFee
                   pNode);   // pNode
    }
    // Create a vector with input data for a given txn and source
    std::vector<TxInputDataSPtr> TxInputDataVec(TxSource source,
                                                std::vector<CMutableTransaction>& spends,
                                                std::shared_ptr<CNode> pNode = nullptr) {
        std::vector<TxInputDataSPtr> vTxInputData {};
        // Get a pointer to the TxIdTracker.
        const TxIdTrackerSPtr& pTxIdTracker = g_connman->GetTxIdTracker();
        for (auto& elem : spends) {
            vTxInputData.
                emplace_back(
                    std::make_shared<CTxInputData>(
                        pTxIdTracker, // a pointer to the TxIdTracker
                        MakeTransactionRef(elem),  // a pointer to the tx
                        source,   // tx source
                        TxValidationPriority::normal, // tx validation priority
                        GetTime(),// nAcceptTime
                        false,    // mfLimitFree
                        Amount(0), // nAbsurdFee
                        pNode));   // pNode
        }
        return vTxInputData;
    }
    // Validate txn using asynchronous validation interface
    void ProcessTxnsAsynchApi(std::vector<CMutableTransaction>& spends,
                              TxSource source,
                              std::shared_ptr<CNode> pNode = nullptr) {
        // Create txn validator
        std::shared_ptr<CTxnValidator> txnValidator {
            std::make_shared<CTxnValidator>(
                    GlobalConfig::GetConfig(),
                    mempool,
                    std::make_shared<CTxnDoubleSpendDetector>(),
                    g_connman->GetTxIdTracker())
        };
        // Clear mempool before validation
        mempool.Clear();
        // Schedule txns for processing.
        txnValidator->newTransaction(TxInputDataVec(source, spends, pNode));
        // Wait for the Validator to process all queued txns.
        txnValidator->waitForEmptyQueue();
    }
    // Validate a single txn using synchronous validation interface
    CValidationState ProcessTxnSynchApi(CMutableTransaction& spend,
                                        TxSource source,
                                        std::shared_ptr<CNode> pNode = nullptr) {
        // Create txn validator
        std::shared_ptr<CTxnValidator> txnValidator {
            std::make_shared<CTxnValidator>(
                    GlobalConfig::GetConfig(),
                    mempool,
                    std::make_shared<CTxnDoubleSpendDetector>(),
                    g_connman->GetTxIdTracker())
        };
        // Clear mempool before validation
        mempool.Clear();
        // Mempool Journal ChangeSet
        mining::CJournalChangeSetPtr changeSet {nullptr};
        return txnValidator->processValidation(TxInputData(source, spend, pNode), changeSet);
    }
    // Validate txn using synchronous validation interface
    void ProcessTxnsSynchApi(std::vector<CMutableTransaction>& spends,
                             TxSource source,
                             std::shared_ptr<CNode> pNode = nullptr) {
        // Create txn validator
        std::shared_ptr<CTxnValidator> txnValidator {
            std::make_shared<CTxnValidator>(
                    GlobalConfig::GetConfig(),
                    mempool,
                    std::make_shared<CTxnDoubleSpendDetector>(),
                    g_connman->GetTxIdTracker())
        };
        // Clear mempool before validation
        mempool.Clear();
        // Mempool Journal ChangeSet
        mining::CJournalChangeSetPtr changeSet {nullptr};
        // Validate the first txn
        CValidationState result {
            txnValidator->processValidation(TxInputData(source, spends[0], pNode), changeSet)
        };
        BOOST_CHECK(result.IsValid());
        // Validate the second txn
        // spends1 should be rejected if spend0 is in the mempool
        result = txnValidator->processValidation(TxInputData(source, spends[1], pNode), changeSet);
        BOOST_CHECK(!result.IsValid());
    }
    // Validate txns using synchronous batch validation interface
    CTxnValidator::RejectedTxns ProcessTxnsSynchBatchApi(std::vector<CMutableTransaction>& spends,
                                  TxSource source,
                                  std::shared_ptr<CNode> pNode = nullptr) {
        // Create txn validator
        std::shared_ptr<CTxnValidator> txnValidator {
            std::make_shared<CTxnValidator>(
                    GlobalConfig::GetConfig(),
                    mempool,
                    std::make_shared<CTxnDoubleSpendDetector>(),
                    g_connman->GetTxIdTracker())
        };
        // Clear mempool before validation
        mempool.Clear();
        // Mempool Journal ChangeSet
        mining::CJournalChangeSetPtr changeSet {nullptr};
        // Validate the first txn
        return txnValidator->processValidation(TxInputDataVec(source, spends, pNode), changeSet);
    }
    struct TestChain100Setup2 : TestChain100Setup {
        CScript scriptPubKey {
            GetScriptPubKey(coinbaseKey)
        };
        // twoDoubleSpend2Txns contains two txns spending the same coinbase txn
        std::vector<CMutableTransaction> doubleSpend2Txns {
            CreateDoubleSpendTxn(coinbaseTxns[0], coinbaseKey, scriptPubKey),
            CreateDoubleSpendTxn(coinbaseTxns[0], coinbaseKey, scriptPubKey)
        };
        // doubleSpend10Txns contains 10 double spend txns spending the same coinbase txn
        std::vector<CMutableTransaction> doubleSpend10Txns {
            CreateNDoubleSpendTxns(10, coinbaseTxns[0], coinbaseKey, scriptPubKey)
        };
    };
}

BOOST_FIXTURE_TEST_SUITE(test_txnvalidator, TestChain100Setup2)

BOOST_AUTO_TEST_CASE(txn_validator_creation) {
    // Create txn validator
    std::shared_ptr<CTxnValidator> txnValidator {
        std::make_shared<CTxnValidator>(
                GlobalConfig::GetConfig(),
                mempool,
                std::make_shared<CTxnDoubleSpendDetector>(),
                g_connman->GetTxIdTracker())
    };
    // Check if the Validator was created
    BOOST_REQUIRE(txnValidator);
    // Check if orphan txns buffer was created
    BOOST_REQUIRE(txnValidator->getOrphanTxnsPtr());
    // Check if txn recent rejects buffer was created
    BOOST_REQUIRE(txnValidator->getTxnRecentRejectsPtr());
}

BOOST_AUTO_TEST_CASE(txn_validator_set_get_frequency) {
    // Create txn validator
    std::shared_ptr<CTxnValidator> txnValidator {
        std::make_shared<CTxnValidator>(
                GlobalConfig::GetConfig(),
                mempool,
                std::make_shared<CTxnDoubleSpendDetector>(),
                g_connman->GetTxIdTracker())
    };
    auto defaultfreq = std::chrono::milliseconds(CTxnValidator::DEFAULT_ASYNCH_RUN_FREQUENCY_MILLIS);
    BOOST_CHECK(defaultfreq == txnValidator->getRunFrequency());
    txnValidator->setRunFrequency(++defaultfreq);
    BOOST_CHECK(defaultfreq == txnValidator->getRunFrequency());
}

BOOST_AUTO_TEST_CASE(txn_validator_istxnknown) {
    // Create txn validator
    std::shared_ptr<CTxnValidator> txnValidator {
        std::make_shared<CTxnValidator>(
                GlobalConfig::GetConfig(),
                mempool,
                std::make_shared<CTxnDoubleSpendDetector>(),
                g_connman->GetTxIdTracker())
    };
    // Schedule txns for processing.
    txnValidator->newTransaction(TxInputDataVec(TxSource::p2p, doubleSpend10Txns));
    BOOST_CHECK(txnValidator->isTxnKnown(doubleSpend10Txns[0].GetId()));
    // Wait for the Validator to process all queued txns.
    txnValidator->waitForEmptyQueue();
    BOOST_CHECK(!txnValidator->isTxnKnown(doubleSpend10Txns[0].GetId()));
}

/**
 * TxnValidator: Test synch interface.
 */
BOOST_AUTO_TEST_CASE(txnvalidator_doublespend_synch_api) {
    // Test all sources.
    for (const auto& txsource: vTxSources) {
        ProcessTxnsSynchApi(doubleSpend2Txns, txsource);
        BOOST_CHECK_EQUAL(mempool.Size(), 1);
    }
    // Test: Txns from p2p with a pointer to a dummy node.
    {
        // Create a dummy address
        CAddress dummy_addr(ip(0xa0b0c001), NODE_NONE);
        CConnman::CAsyncTaskPool asyncTaskPool{GlobalConfig::GetConfig()};
        CNodePtr pDummyNode =
            CNode::Make(
                0,
                NODE_NETWORK,
                0,
                INVALID_SOCKET,
                dummy_addr,
                0u,
                0u,
                asyncTaskPool,
                "",
                true);
        ProcessTxnsSynchApi(doubleSpend2Txns, TxSource::p2p, pDummyNode);
        BOOST_CHECK_EQUAL(mempool.Size(), 1);
    }
}

BOOST_AUTO_TEST_CASE(txnvalidator_doublespend_synch_batch_api) {
    CTxnValidator::RejectedTxns mRejectedTxns {};
    // Test all sources.
    for (const auto& txsource: vTxSources) {
        mRejectedTxns = ProcessTxnsSynchBatchApi(doubleSpend10Txns, txsource);
        BOOST_CHECK_EQUAL(mempool.Size(), 1);
        // There should be no insufficient fee txns returned.
        BOOST_REQUIRE(!mRejectedTxns.second.size());
        // Check an expected number of invalid txns returned.
        const CTxnValidator::InvalidTxnStateUMap& mInvalidTxns = mRejectedTxns.first;
        BOOST_REQUIRE(mInvalidTxns.size() == doubleSpend10Txns.size()-1);
        for (const auto& elem : mInvalidTxns) {
            BOOST_REQUIRE(!elem.second.IsValid());
            // Due to runtime-conditions it might be detected as:
            // - a mempool conflict
            // - a double spend
            BOOST_REQUIRE(elem.second.IsMempoolConflictDetected() ||
                elem.second.IsDoubleSpendDetected());
        }
    }
    // Test: Txns from p2p with a pointer to a dummy node.
    {
        // Create a dummy address
        CAddress dummy_addr(ip(0xa0b0c001), NODE_NONE);
        CConnman::CAsyncTaskPool asyncTaskPool{GlobalConfig::GetConfig()};
        CNodePtr pDummyNode =
            CNode::Make(
                0,
                NODE_NETWORK,
                0,
                INVALID_SOCKET,
                dummy_addr,
                0u,
                0u,
                asyncTaskPool,
                "",
                true);
        mRejectedTxns = ProcessTxnsSynchBatchApi(doubleSpend10Txns, TxSource::p2p, pDummyNode);
        BOOST_CHECK_EQUAL(mempool.Size(), 1);
        // There should be no insufficient fee txns returned.
        BOOST_REQUIRE(!mRejectedTxns.second.size());
        // Check an expected number of invalid txns returned.
        const CTxnValidator::InvalidTxnStateUMap& mInvalidTxns = mRejectedTxns.first;
        BOOST_REQUIRE(mInvalidTxns.size() == doubleSpend10Txns.size()-1);
        for (const auto& elem : mInvalidTxns) {
            BOOST_REQUIRE(!elem.second.IsValid());
            // Due to runtime-conditions it might be detected as:
            // - a mempool conflict
            // - a double spend
            BOOST_REQUIRE(elem.second.IsMempoolConflictDetected() ||
                elem.second.IsDoubleSpendDetected());
        }
    }
}

/**
 * TxnValidator: Test asynch interface.
 */
BOOST_AUTO_TEST_CASE(txnvalidator_wallet_doublespend_via_asynch_api) {
    // Test: Txns from wallet.
    ProcessTxnsAsynchApi(doubleSpend10Txns, TxSource::wallet);
    BOOST_CHECK_EQUAL(mempool.Size(), 1);
}

BOOST_AUTO_TEST_CASE(txnvalidator_rpc_doublespend_via_asynch_api) {
    // Test: Txns from rpc.
    ProcessTxnsAsynchApi(doubleSpend10Txns, TxSource::rpc);
    BOOST_CHECK_EQUAL(mempool.Size(), 1);
}

BOOST_AUTO_TEST_CASE(txnvalidator_file_doublespend_via_asynch_api) {
    // Test: Txns from file.
    ProcessTxnsAsynchApi(doubleSpend10Txns, TxSource::file);
    BOOST_CHECK_EQUAL(mempool.Size(), 1);
}

BOOST_AUTO_TEST_CASE(txnvalidator_p2p_doublespend_via_asynch_api) {
    // Test: Txns from p2p.
    {
        // Create a dummy address
        CAddress dummy_addr(ip(0xa0b0c001), NODE_NONE);
        CConnman::CAsyncTaskPool asyncTaskPool{GlobalConfig::GetConfig()};
        CNodePtr pDummyNode =
            CNode::Make(
                0,
                NODE_NETWORK,
                0,
                INVALID_SOCKET,
                dummy_addr,
                0u,
                0u,
                asyncTaskPool,
                "",
                true);
        ProcessTxnsAsynchApi(doubleSpend10Txns, TxSource::p2p, pDummyNode);
        BOOST_CHECK_EQUAL(mempool.Size(), 1);
    }
    // Process txn if it is valid.
    ProcessTxnsAsynchApi(doubleSpend10Txns, TxSource::p2p);
    BOOST_CHECK_EQUAL(mempool.Size(), 1);
}

BOOST_AUTO_TEST_CASE(txnvalidator_reorg_doublespend_via_asynch_api) {
    // Test: Txns from reorg.
    ProcessTxnsAsynchApi(doubleSpend10Txns, TxSource::reorg);
    BOOST_CHECK_EQUAL(mempool.Size(), 1);
}

BOOST_AUTO_TEST_CASE(txnvalidator_dummy_doublespend_via_asynch_api) {
    // Process txn if it is valid.
    ProcessTxnsAsynchApi(doubleSpend10Txns, TxSource::unknown);
    BOOST_CHECK_EQUAL(mempool.Size(), 1);
}

BOOST_AUTO_TEST_CASE(txnvalidator_limit_memory_usage)
{
    // Make sure validation thread won't run during this test
    gArgs.ForceSetArg("-txnvalidationasynchrunfreq", "10000");
    gArgs.ForceSetArg("-txnvalidationqueuesmaxmemory", "1");

    // Create a larger number of txns than will fit in a 1Mb queue
    std::vector<CMutableTransaction> txns { MakeNLargeTxns(25, coinbaseTxns[0], scriptPubKey) };
    auto txnsInputs { TxInputDataVec(TxSource::p2p, txns) };

    // Create txn validator
    std::shared_ptr<CTxnValidator> txnValidator {
        std::make_shared<CTxnValidator>(
                GlobalConfig::GetConfig(),
                mempool,
                std::make_shared<CTxnDoubleSpendDetector>(),
                g_connman->GetTxIdTracker())
    };

    // Attempt to enqueue all txns and verify that we stopped when we hit the max size limit
    txnValidator->newTransaction(txnsInputs);
    BOOST_CHECK(txnValidator->GetTransactionsInQueueCount() < txns.size());
    BOOST_CHECK(txnValidator->GetStdQueueMemUsage() <= 1*ONE_MEBIBYTE);
    BOOST_CHECK_EQUAL(txnValidator->GetNonStdQueueMemUsage(), 0);
}

BOOST_AUTO_TEST_CASE(txnvalidator_nvalueoutofrange_sync_api) {
    // spendtx_nValue_OutOfRange (a copy of doubleSpend2Txns[0]) with unsupported nValue amount.
    // Set nValue = MAX_MONEY + 1 for the txn to trigger exception when GetValueOut is called.
    auto spendtx_nValue_OutOfRange = doubleSpend2Txns[0];
    spendtx_nValue_OutOfRange.vout[0].nValue = MAX_MONEY + Amount(1);
    BOOST_CHECK_EXCEPTION(
        !MoneyRange(CTransaction(spendtx_nValue_OutOfRange).GetValueOut()),
        std::runtime_error,
        GetValueOutException);
    CValidationState result {};
    // Test all sources.
    for (const auto& txsource: vTxSources) {
        result = ProcessTxnSynchApi(spendtx_nValue_OutOfRange, txsource);
        BOOST_CHECK(!result.IsValid());
        BOOST_CHECK_EQUAL(mempool.Size(), 0);
    }
}

BOOST_AUTO_TEST_CASE(txnvalidator_nvalueoutofrange_async_api) {
    // Create txn validator
    std::shared_ptr<CTxnValidator> txnValidator {
        std::make_shared<CTxnValidator>(
                GlobalConfig::GetConfig(),
                mempool,
                std::make_shared<CTxnDoubleSpendDetector>(),
                g_connman->GetTxIdTracker())
    };
    // Case1:
    // doubleSpends10Txns_nValue_OutOfRange (a copy of doubleSpend10Txns) with unsupported nValue amount.
    {
        // Set nValue = MAX_MONEY + 1 for each txn to trigger exception when GetValueOut is called.
        auto doubleSpends10Txns_nValue_OutOfRange = doubleSpend10Txns;
        for (auto& spend: doubleSpends10Txns_nValue_OutOfRange) {
            spend.vout[0].nValue = MAX_MONEY + Amount(1);
            BOOST_CHECK_EXCEPTION(!MoneyRange(CTransaction(spend).GetValueOut()), std::runtime_error, GetValueOutException);
        }
        // Schedule txns for processing.
        txnValidator->newTransaction(TxInputDataVec(TxSource::p2p, doubleSpends10Txns_nValue_OutOfRange));
        // Wait for the Validator to process all queued txns.
        txnValidator->waitForEmptyQueue();
        // Non transaction should be accepted due to nValue (value out of range).
        BOOST_CHECK_EQUAL(mempool.Size(), 0);
    }
    // Case2:
    // Send the same txns again (with valid nValue).
    // Check if only one txn (from doubleSpend10Txns) is accepted by the mempool.
    {
        txnValidator->newTransaction(TxInputDataVec(TxSource::p2p, doubleSpend10Txns));
        txnValidator->waitForEmptyQueue();
        BOOST_CHECK_EQUAL(mempool.Size(), 1);
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: adampaigge/bitcoin-supernova

max_issues_repo_name: adampaigge/bitcoin-supernova

max_forks_repo_name: adampaigge/bitcoin-supernova


text:
// This file is part of RegSeg
//
// Copyright 2014-2017, Oscar Esteban <code@oscaresteban.es>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#include "SparseToDenseFieldResampleFilter.h"
#include "IDWMultivariateInterpolator.h"

#include <stdio.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <ctime>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>

#include <itkImage.h>
#include <itkVectorImage.h>
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkMesh.h>
#include <itkMeshFileReader.h>
#include "DisplacementFieldFileWriter.h"

namespace bpo = boost::program_options;

typedef float       PixelType;
const unsigned int Dimension = 3;
typedef itk::Vector< PixelType, 3 >                 PointType;
typedef itk::Image< PointType, Dimension >         DenseVectorFieldType;
typedef itk::PointSet< PointType, Dimension >      SparseVectorFieldType;
typedef rstk::SparseToDenseFieldResampleFilter<SparseVectorFieldType, DenseVectorFieldType>  ResamplerType;
//typedef itk::ImageFileWriter< DenseVectorFieldType > Writer;
typedef rstk::DisplacementFieldFileWriter<DenseVectorFieldType> Writer;

int main(int argc, char *argv[]) {
	// Create PointSet
	SparseVectorFieldType::Pointer svf = SparseVectorFieldType::New();
	svf->SetRequestedRegion( 3 );

	// Set some vectors
	PointType p1;
	PointType v1;
	v1.Fill( 5.0 );
	p1[0] = 10;
	p1[1] = 10;
	p1[2] = 10;
	svf->SetPoint( 0, p1 );
	svf->SetPointData( 0, v1 );

	PointType p2;
	p2[0] = 90;
	p2[1] = 90;
	p2[2] = 90;
	PointType v2;
	v2[0] = -5.0;
	v2[1] = -15.0;
	v2[2] = 10.0;

	svf->SetPoint( 1, p2 );
	svf->SetPointData( 1, v2 );

	PointType p3;
	p3[0] = 10;
	p3[1] = 90;
	p3[2] = 70;
	PointType v3;
	v3[0] = 2.0;
	v3[1] = -1.0;
	v3[2] = -5.0;

	svf->SetPoint( 2, p3 );
	svf->SetPointData( 2, v3 );

	// Resample
	ResamplerType::OutputImageSizeType size;
	size.Fill( 50 );
	ResamplerType::Pointer res = ResamplerType::New();
	res->SetInput( svf );
	res->AddControlPoints( svf );
	res->SetFieldSize( size );
	res->SetFieldSpacing( 2.0 );
	res->Update();
	DenseVectorFieldType::Pointer df = res->GetOutput();

	// Write result
	Writer::Pointer p = Writer::New();
	p->SetFileName( "IDWMultivariateInterpolatorTest.nii.gz" );
	p->SetInput( df );
	p->Update();

	return EXIT_SUCCESS;
}

ext: cxx

max_stars_repo_name: xiaochengcike/RegSeg

max_issues_repo_name: xiaochengcike/RegSeg

max_forks_repo_name: oesteban/RegSeg


text:
/*
 * Copyright (C) 2009-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef UCONTEXT_IMPL_HH
# define UCONTEXT_IMPL_HH

#include <set>

#include <boost/function.hpp>
#include <libport/system-warning-push.hh>
#include <boost/thread.hpp>
#include <libport/system-warning-pop.hh>

#include <libport/asio.hh>

#include <urbi/fwd.hh>
#include <urbi/uprop.hh>

namespace urbi
{
  /** The interfaces UContextImpl, UVarImpl, UObjectImpl and
   * UGenericCallbackImpl are what must be implemented to make an UObject
   * backend.
   */
  namespace impl
  {
    class URBI_SDK_API UContextImpl
    {
    public:
      virtual ~UContextImpl() = 0;
      /// Inject all loaded uobjects in the system by calling newUObjectClass.
      void init();
      /// Inject a specific uobject
      bool bind(const std::string& name, std::string rename = std::string());
      /// Called to instanciate the first Object of class.
      virtual void newUObjectClass(::urbi::baseURBIStarter* s) = 0;
      virtual void newUObjectHubClass(::urbi::baseURBIStarterHub* s) = 0;
      /// Retrieve a UObjectHub based on its name or return 0 if not found.
      ATTRIBUTE_PURE
      virtual UObjectHub* getUObjectHub(const std::string& n);
      /// Retrieve a UObject based on its name or return 0 if not found.
      ATTRIBUTE_PURE
      virtual UObject* getUObject(const std::string& n);
      /// Send Urbi code (ghost connection in plugin mode, default
      /// connection in remote mode).
      virtual void uobject_unarmorAndSend(const char* str) = 0;

      /// Send the string to the connection hosting the UObject.
      virtual void send(const char* str) = 0;

      /// Send buf to the connection hosting the UObject.
      virtual void send(const void* buf, size_t size) = 0;

      /// Bouncing overload.
      void send(const std::string& s);

      virtual void call(const std::string& object,
                        const std::string& method,
                        UAutoValue v1 = UAutoValue(),
                        UAutoValue v2 = UAutoValue(),
                        UAutoValue v3 = UAutoValue(),
                        UAutoValue v4 = UAutoValue(),
                        UAutoValue v5 = UAutoValue(),
                        UAutoValue v6 = UAutoValue()) = 0;

      virtual void declare_event(const UEvent* owner) = 0;

      virtual void emit(const std::string& object,
                        UAutoValue& v1,
                        UAutoValue& v2,
                        UAutoValue& v3,
                        UAutoValue& v4,
                        UAutoValue& v5,
                        UAutoValue& v6,
                        UAutoValue& v7) = 0;

      /// The mode in which the code is running.
      virtual UObjectMode getRunningMode() const = 0;
      /// The kernel major,minor version
      virtual std::pair<int, int> kernelVersion() const = 0;

      /// Yield execution until next cycle.
      /// Process pending messages in remote mode.
      virtual void yield() const = 0;

      /// Yield execution until \b deadline is met (see libport::utime()).
      virtual void yield_until(libport::utime_t deadline) const = 0;

      /// Yield execution for \b delay.
      /// Bounces to yield_until.
      virtual void yield_for(libport::utime_t delay) const;

      /** If \b s is true, mark the current task as having no side effect.
       * This call has no effect in remote mode.
       */
      virtual void side_effect_free_set(bool s) = 0;
      /// Get the current side_effect_free state.
      virtual bool side_effect_free_get() const = 0;
      virtual UVarImpl* getVarImpl() = 0;
      virtual UObjectImpl* getObjectImpl() = 0;
      virtual UGenericCallbackImpl* getGenericCallbackImpl() = 0;
      /// Default implementations appends to 'objects'.
      virtual void registerObject(UObject*o);
      virtual TimerHandle setTimer(UTimerCallback* cb) = 0;
      virtual void registerHub(UObjectHub*);
      virtual void removeHub(UObjectHub*) = 0;
      virtual void setHubUpdate(UObjectHub*, ufloat) = 0;
      /// Called by the urbiStarter after each UObject instanciation.
      virtual void instanciated(UObject*) = 0;
      typedef boost::unordered_map<std::string, UObject*>  objects_type;
      objects_type objects;
      typedef boost::unordered_map<std::string, UObjectHub*> hubs_type;
      hubs_type hubs;
      std::set<void*> initialized;

      /** Cleanup Stack RAII. Useful to delete temporaries created by
       * UValue casters.
       * The UObject API instanciates one for each call to a bound function or
       * notify.
       */
      class URBI_SDK_API CleanupStack
      {
      public:
        CleanupStack(UContextImpl& owner);
        ~CleanupStack();
      private:
        UContextImpl& owner_;
      };

      /// Add \b ptr to the list of objects to delete whean cleanup() is called.
      template<typename T>
      void addCleanup(T* ptr);

      /// Add an arbitrary operation to perform at cleanup() time.
      void addCleanup(boost::function0<void> op);

      /// Push a new cleanup stack.
      void pushCleanupStack();
     /// Delete all pointers passed to addCleanup in current stack and pop.
      void popCleanupStack();

      /** Request a context lock from another thread to perform multiple
       * operations.
       */
      virtual void lock() = 0;
      /// Release lock acquired with lock()
      virtual void unlock() = 0;
      /// The io_service used by this context.
      virtual boost::asio::io_service& getIoService() = 0;

      virtual Barrier* barrier() = 0;
      /// RTP hooks for performance
      typedef void(*RTPSend)(UObject* rtp, const UValue& v);
      typedef void(*RTPSendGrouped)(UObject* rtp, const std::string&,
                                    const UValue&,
                                   libport::utime_t);
      RTPSend rtpSend;
      RTPSendGrouped rtpSendGrouped;
    private:
      typedef std::vector<std::vector<boost::function0<void> > > CleanupList;
      boost::thread_specific_ptr<CleanupList> cleanup_list_;
    };

    class URBI_SDK_API UObjectImpl
    {
    public:
      virtual ~UObjectImpl() = 0;
      // Called by uobject constructor
      virtual void initialize(UObject* owner) = 0;
      virtual void clean() = 0;
      virtual void setUpdate(ufloat period) = 0;
      virtual bool removeTimer(TimerHandle h) = 0;
    };

    class URBI_SDK_API UVarImpl
    {
    public:
      virtual ~UVarImpl() = 0;
      virtual void initialize(UVar* owner) = 0;
      virtual void clean() = 0;
      virtual void setOwned() = 0;
      virtual void sync() = 0;
      virtual void request() = 0;
      virtual void keepSynchronized() = 0;
      // Set the UVar value from v. Must deep-copy unless bypass mode is enabled
      virtual void set(const UValue& v) = 0;
      virtual const UValue& get() const = 0;
      virtual UDataType type() const = 0;
      virtual UValue getProp(UProperty prop) = 0;
      virtual void setProp(UProperty prop, const UValue& v) = 0;
      virtual bool setBypass(bool enable) = 0;
      virtual time_t timestamp() const = 0;
      virtual void unnotify() = 0;
      virtual void useRTP(bool enable) = 0;
      virtual void setInputPort(bool enable) = 0;
    };
  }
}

# include <urbi/ucontext-impl.hxx>

#endif

max_stars_repo_name: jcbaillie/urbi

max_issues_repo_name: jcbaillie/urbi

max_forks_repo_name: jcbaillie/urbi