text:
//
// Copyright (c) 2019-2020 INRIA
//

#include <pinocchio/math/rpy.hpp>
#include <pinocchio/math/quaternion.hpp>
#include <pinocchio/spatial/skew.hpp>

#include <boost/variant.hpp> // to avoid C99 warnings

#include <boost/test/unit_test.hpp>
#include <boost/utility/binary.hpp>

BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)

BOOST_AUTO_TEST_CASE(test_rpyToMatrix)
{
  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);
  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;

  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(r, p, y);

  Eigen::Matrix3d Raa = (Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ())
                            * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())
                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX())
                            ).toRotationMatrix();

  BOOST_CHECK(R.isApprox(Raa));

  Eigen::Vector3d v;
  v << r, p, y;

  Eigen::Matrix3d Rv = pinocchio::rpy::rpyToMatrix(v);

  BOOST_CHECK(Rv.isApprox(Raa));
  BOOST_CHECK(Rv.isApprox(R));
}

BOOST_AUTO_TEST_CASE(test_matrixToRpy)
{
  #ifdef NDEBUG
    const int n = 1e5;
  #else
    const int n = 1e2;
  #endif
  for(int k = 0; k < n ; ++k)
  {
    Eigen::Quaterniond quat;
    pinocchio::quaternion::uniformRandom(quat);
    const Eigen::Matrix3d R = quat.toRotationMatrix();

    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);
    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);

    BOOST_CHECK(Rprime.isApprox(R));
    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);
    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);
    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);
  }

#ifdef NDEBUG
  const int n2 = 1e3;
#else
  const int n2 = 1e2;
#endif

  // Test singular case theta = pi/2
  for(int k = 0; k < n2 ; ++k)
  {
    double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
    double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
    Eigen::Matrix3d Rp;
    Rp <<  0.0, 0.0, 1.0,
           0.0, 1.0, 0.0,
          -1.0, 0.0, 0.0;
    const Eigen::Matrix3d R = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix()
                            * Rp
                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix();

    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);
    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);

    BOOST_CHECK(Rprime.isApprox(R));
    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);
    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);
    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);
  }

  // Test singular case theta = -pi/2
  for(int k = 0; k < n2 ; ++k)
  {
    double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
    double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
    Eigen::Matrix3d Rp;
    Rp << 0.0, 0.0, -1.0,
          0.0, 1.0,  0.0,
          1.0, 0.0,  0.0;
    const Eigen::Matrix3d R = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix()
                            * Rp
                            * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix();

    const Eigen::Vector3d v = pinocchio::rpy::matrixToRpy(R);
    Eigen::Matrix3d Rprime = pinocchio::rpy::rpyToMatrix(v);

    BOOST_CHECK(Rprime.isApprox(R));
    BOOST_CHECK(-M_PI <= v[0] && v[0] <= M_PI);
    BOOST_CHECK(-M_PI/2 <= v[1] && v[1] <= M_PI/2);
    BOOST_CHECK(-M_PI <= v[2] && v[2] <= M_PI);
  }
}

BOOST_AUTO_TEST_CASE(test_computeRpyJacobian)
{
  // Check identity at zero
  Eigen::Vector3d rpy(Eigen::Vector3d::Zero());
  Eigen::Matrix3d j0 = pinocchio::rpy::computeRpyJacobian(rpy);
  BOOST_CHECK(j0.isIdentity());
  Eigen::Matrix3d jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);
  BOOST_CHECK(jL.isIdentity());
  Eigen::Matrix3d jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);
  BOOST_CHECK(jW.isIdentity());
  Eigen::Matrix3d jA = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL_WORLD_ALIGNED);
  BOOST_CHECK(jA.isIdentity());

  // Check correct identities between different versions
  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);
  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
  rpy = Eigen::Vector3d(r, p, y);
  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(rpy);
  j0 = pinocchio::rpy::computeRpyJacobian(rpy);
  jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);
  jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);
  jA = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL_WORLD_ALIGNED);
  BOOST_CHECK(j0 == jL);
  BOOST_CHECK(jW == jA);
  BOOST_CHECK(jW.isApprox(R*jL));

  // Check against analytical formulas
  Eigen::Vector3d jL0Expected = Eigen::Vector3d::UnitX();
  Eigen::Vector3d jL1Expected = Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX()).toRotationMatrix().transpose().col(1);
  Eigen::Vector3d jL2Expected = (Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())
                               * Eigen::AngleAxisd(r, Eigen::Vector3d::UnitX())
                                ).toRotationMatrix().transpose().col(2);
  BOOST_CHECK(jL.col(0).isApprox(jL0Expected));
  BOOST_CHECK(jL.col(1).isApprox(jL1Expected));
  BOOST_CHECK(jL.col(2).isApprox(jL2Expected));

  Eigen::Vector3d jW0Expected = (Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ())
                               * Eigen::AngleAxisd(p, Eigen::Vector3d::UnitY())
                                ).toRotationMatrix().col(0);
  Eigen::Vector3d jW1Expected = Eigen::AngleAxisd(y, Eigen::Vector3d::UnitZ()).toRotationMatrix().col(1);
  Eigen::Vector3d jW2Expected = Eigen::Vector3d::UnitZ();
  BOOST_CHECK(jW.col(0).isApprox(jW0Expected));
  BOOST_CHECK(jW.col(1).isApprox(jW1Expected));
  BOOST_CHECK(jW.col(2).isApprox(jW2Expected));

  // Check against finite differences
  Eigen::Vector3d rpydot = Eigen::Vector3d::Random();
  double const eps = 1e-7;
  double const tol = 1e-5;

  Eigen::Matrix3d dRdr = (pinocchio::rpy::rpyToMatrix(r + eps, p, y) - R) / eps;
  Eigen::Matrix3d dRdp = (pinocchio::rpy::rpyToMatrix(r, p + eps, y) - R) / eps;
  Eigen::Matrix3d dRdy = (pinocchio::rpy::rpyToMatrix(r, p, y + eps) - R) / eps;
  Eigen::Matrix3d Rdot = dRdr * rpydot[0] + dRdp * rpydot[1] + dRdy * rpydot[2];

  Eigen::Vector3d omegaL = jL * rpydot;
  BOOST_CHECK(Rdot.isApprox(R * pinocchio::skew(omegaL), tol));

  Eigen::Vector3d omegaW = jW * rpydot;
  BOOST_CHECK(Rdot.isApprox(pinocchio::skew(omegaW) * R, tol));
}

BOOST_AUTO_TEST_CASE(test_computeRpyJacobianInverse)
{
  // Check correct identities between different versions
  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);
  p *= 0.999; // ensure we are not too close to a singularity
  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
  Eigen::Vector3d rpy(r, p, y);

  Eigen::Matrix3d j0 = pinocchio::rpy::computeRpyJacobian(rpy);
  Eigen::Matrix3d j0inv = pinocchio::rpy::computeRpyJacobianInverse(rpy);
  BOOST_CHECK(j0inv.isApprox(j0.inverse()));

  Eigen::Matrix3d jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);
  Eigen::Matrix3d jLinv = pinocchio::rpy::computeRpyJacobianInverse(rpy, pinocchio::LOCAL);
  BOOST_CHECK(jLinv.isApprox(jL.inverse()));

  Eigen::Matrix3d jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);
  Eigen::Matrix3d jWinv = pinocchio::rpy::computeRpyJacobianInverse(rpy, pinocchio::WORLD);
  BOOST_CHECK(jWinv.isApprox(jW.inverse()));

  Eigen::Matrix3d jA = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL_WORLD_ALIGNED);
  Eigen::Matrix3d jAinv = pinocchio::rpy::computeRpyJacobianInverse(rpy, pinocchio::LOCAL_WORLD_ALIGNED);
  BOOST_CHECK(jAinv.isApprox(jA.inverse()));
}

BOOST_AUTO_TEST_CASE(test_computeRpyJacobianTimeDerivative)
{
  // Check zero at zero velocity
  double r = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
  double p = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/M_PI)) - (M_PI/2);
  double y = static_cast <double> (rand()) / (static_cast <double> (RAND_MAX/(2*M_PI))) - M_PI;
  Eigen::Vector3d rpy(r, p, y);
  Eigen::Vector3d rpydot(Eigen::Vector3d::Zero());
  Eigen::Matrix3d dj0 = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot);
  BOOST_CHECK(dj0.isZero());
  Eigen::Matrix3d djL = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL);
  BOOST_CHECK(djL.isZero());
  Eigen::Matrix3d djW = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::WORLD);
  BOOST_CHECK(djW.isZero());
  Eigen::Matrix3d djA = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL_WORLD_ALIGNED);
  BOOST_CHECK(djA.isZero());

  // Check correct identities between different versions
  rpydot = Eigen::Vector3d::Random();
  dj0 = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot);
  djL = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL);
  djW = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::WORLD);
  djA = pinocchio::rpy::computeRpyJacobianTimeDerivative(rpy, rpydot, pinocchio::LOCAL_WORLD_ALIGNED);
  BOOST_CHECK(dj0 == djL);
  BOOST_CHECK(djW == djA);

  Eigen::Matrix3d R = pinocchio::rpy::rpyToMatrix(rpy);
  Eigen::Matrix3d jL = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::LOCAL);
  Eigen::Matrix3d jW = pinocchio::rpy::computeRpyJacobian(rpy, pinocchio::WORLD);
  Eigen::Vector3d omegaL = jL * rpydot;
  Eigen::Vector3d omegaW = jW * rpydot;
  BOOST_CHECK(omegaW.isApprox(R*omegaL));
  BOOST_CHECK(djW.isApprox(pinocchio::skew(omegaW)*R*jL + R*djL));
  BOOST_CHECK(djW.isApprox(R*pinocchio::skew(omegaL)*jL + R*djL));

  // Check against finite differences
  double const eps = 1e-7;
  double const tol = 1e-5;
  Eigen::Vector3d rpyEps = rpy;

  rpyEps[0] += eps;
  Eigen::Matrix3d djLdr = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::LOCAL) - jL) / eps;
  rpyEps[0] = rpy[0];
  rpyEps[1] += eps;
  Eigen::Matrix3d djLdp = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::LOCAL) - jL) / eps;
  rpyEps[1] = rpy[1];
  rpyEps[2] += eps;
  Eigen::Matrix3d djLdy = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::LOCAL) - jL) / eps;
  rpyEps[2] = rpy[2];
  Eigen::Matrix3d djLf = djLdr * rpydot[0] + djLdp * rpydot[1] + djLdy * rpydot[2];
  BOOST_CHECK(djL.isApprox(djLf, tol));

  rpyEps[0] += eps;
  Eigen::Matrix3d djWdr = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::WORLD) - jW) / eps;
  rpyEps[0] = rpy[0];
  rpyEps[1] += eps;
  Eigen::Matrix3d djWdp = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::WORLD) - jW) / eps;
  rpyEps[1] = rpy[1];
  rpyEps[2] += eps;
  Eigen::Matrix3d djWdy = (pinocchio::rpy::computeRpyJacobian(rpyEps, pinocchio::WORLD) - jW) / eps;
  rpyEps[2] = rpy[2];
  Eigen::Matrix3d djWf = djWdr * rpydot[0] + djWdp * rpydot[1] + djWdy * rpydot[2];
  BOOST_CHECK(djW.isApprox(djWf, tol));
}

BOOST_AUTO_TEST_SUITE_END()


text:
/*=============================================================================
    Copyright (c) 2001-2009 Joel de Guzman
    Copyright (c) 2005-2006 Dan Marsden
    Copyright (c) 2010 Christopher Schmidt

    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)
==============================================================================*/

#ifndef BOOST_FUSION_ADAPTED_ADT_DETAIL_ADAPT_BASE_HPP
#define BOOST_FUSION_ADAPTED_ADT_DETAIL_ADAPT_BASE_HPP

#include <boost/fusion/adapted/struct/detail/adapt_auto.hpp>
#include <boost/fusion/adapted/struct/detail/adapt_is_tpl.hpp>
#include <boost/fusion/support/config.hpp>

#include <boost/mpl/if.hpp>
#include <boost/preprocessor/control/expr_if.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/seq/elem.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_reference.hpp>

#include <boost/typeof/typeof.hpp>

#define BOOST_FUSION_ADAPT_ADT_GET_IDENTITY_TEMPLATE_IMPL(TEMPLATE_PARAMS_SEQ) \
  typename detail::get_identity<lvalue, BOOST_PP_SEQ_ELEM(                     \
                                            1, TEMPLATE_PARAMS_SEQ)>::type

#define BOOST_FUSION_ADAPT_ADT_GET_IDENTITY_NON_TEMPLATE_IMPL(                 \
    TEMPLATE_PARAMS_SEQ)                                                       \
                                                                               \
  boost::remove_const<boost::remove_reference<lvalue>::type>::type

#define BOOST_FUSION_ADAPT_ADT_ATTRIBUTE_GETEXPR(                              \
    ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, DEDUCE_TYPE)                              \
  BOOST_PP_TUPLE_ELEM(ATTRIBUTE_TUPLE_SIZE, BOOST_PP_IF(DEDUCE_TYPE, 0, 2),    \
                      ATTRIBUTE)

#define BOOST_FUSION_ADAPT_ADT_ATTRIBUTE_SETEXPR(                              \
    ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, DEDUCE_TYPE)                              \
  BOOST_PP_TUPLE_ELEM(ATTRIBUTE_TUPLE_SIZE, BOOST_PP_IF(DEDUCE_TYPE, 1, 3),    \
                      ATTRIBUTE)

#ifdef BOOST_MSVC
#define BOOST_FUSION_DEDUCED_ATTR_TYPE(                                        \
    NAME_SEQ, ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, PREFIX, TEMPLATE_PARAMS_SEQ)    \
                                                                               \
  BOOST_FUSION_ADAPT_STRUCT_MSVC_REDEFINE_TEMPLATE_PARAMS(TEMPLATE_PARAMS_SEQ) \
                                                                               \
  struct deduced_attr_type {                                                   \
    static const BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) & obj;        \
    typedef BOOST_PP_EXPR_IF(BOOST_FUSION_ADAPT_IS_TPL(TEMPLATE_PARAMS_SEQ),   \
                             typename)                                         \
        BOOST_TYPEOF(PREFIX() BOOST_FUSION_ADAPT_ADT_ATTRIBUTE_GETEXPR(        \
            ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, 1)) type;                         \
  };

#else
#define BOOST_FUSION_DEDUCED_ATTR_TYPE(                                        \
    NAME_SEQ, ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, PREFIX, TEMPLATE_PARAMS_SEQ)    \
  struct deduced_attr_type {                                                   \
    static const BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) & obj;        \
    typedef BOOST_TYPEOF(PREFIX() BOOST_FUSION_ADAPT_ADT_ATTRIBUTE_GETEXPR(    \
        ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, 1)) type;                             \
  };

#endif

#define BOOST_FUSION_ADT_ATTRIBUTE_TYPEOF(                                     \
    NAME_SEQ, ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, PREFIX, TEMPLATE_PARAMS_SEQ)    \
                                                                               \
  BOOST_FUSION_DEDUCED_ATTR_TYPE(NAME_SEQ, ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE,    \
                                 PREFIX, TEMPLATE_PARAMS_SEQ)                  \
                                                                               \
  typedef BOOST_PP_EXPR_IF(BOOST_FUSION_ADAPT_IS_TPL(TEMPLATE_PARAMS_SEQ),     \
                           typename) deduced_attr_type::type type;             \
  typedef type const_type;

#define BOOST_FUSION_ADT_ATTRIBUTE_GIVENTYPE(                                  \
    NAME_SEQ, ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, PREFIX, TEMPLATE_PARAMS_SEQ)    \
                                                                               \
  typedef BOOST_PP_TUPLE_ELEM(ATTRIBUTE_TUPLE_SIZE, 0, ATTRIBUTE) type;        \
  typedef BOOST_PP_TUPLE_ELEM(ATTRIBUTE_TUPLE_SIZE, 1, ATTRIBUTE) const_type;

#define BOOST_FUSION_ADAPT_ADT_C_BASE(TEMPLATE_PARAMS_SEQ, NAME_SEQ, I,        \
                                      PREFIX, ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, \
                                      DEDUCE_TYPE)                             \
                                                                               \
  template <BOOST_FUSION_ADAPT_STRUCT_UNPACK_TEMPLATE_PARAMS(                  \
      TEMPLATE_PARAMS_SEQ)>                                                    \
  struct access::adt_attribute_access<                                         \
      BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ), I> {                    \
                                                                               \
    BOOST_PP_IF(DEDUCE_TYPE, BOOST_FUSION_ADT_ATTRIBUTE_TYPEOF,                \
                BOOST_FUSION_ADT_ATTRIBUTE_GIVENTYPE)                          \
    (NAME_SEQ, ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, PREFIX, TEMPLATE_PARAMS_SEQ)   \
                                                                               \
        template <class Val>                                                   \
        BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED                         \
        static void boost_fusion_adapt_adt_impl_set(                           \
            BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) & obj,             \
            Val const &val) {                                                  \
      PREFIX()                                                                 \
      BOOST_FUSION_ADAPT_ADT_ATTRIBUTE_SETEXPR(                                \
          ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, DEDUCE_TYPE);                       \
    }                                                                          \
                                                                               \
    BOOST_FUSION_GPU_ENABLED                                                   \
    static type boost_fusion_adapt_adt_impl_get(                               \
        BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) & obj) {               \
      return PREFIX() BOOST_FUSION_ADAPT_ADT_ATTRIBUTE_GETEXPR(                \
          ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, DEDUCE_TYPE);                       \
    }                                                                          \
                                                                               \
    BOOST_FUSION_GPU_ENABLED                                                   \
    static const_type boost_fusion_adapt_adt_impl_get(                         \
        BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) const &obj) {          \
      return PREFIX() BOOST_FUSION_ADAPT_ADT_ATTRIBUTE_GETEXPR(                \
          ATTRIBUTE, ATTRIBUTE_TUPLE_SIZE, DEDUCE_TYPE);                       \
    }                                                                          \
  };                                                                           \
                                                                               \
  template <BOOST_FUSION_ADAPT_STRUCT_UNPACK_TEMPLATE_PARAMS(                  \
      TEMPLATE_PARAMS_SEQ)>                                                    \
  struct adt_attribute_proxy<BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ),  \
                             I, true> {                                        \
    typedef BOOST_PP_EXPR_IF(BOOST_PP_SEQ_HEAD(TEMPLATE_PARAMS_SEQ), typename) \
        access::adt_attribute_access<                                          \
            BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ), I>::const_type    \
        type;                                                                  \
                                                                               \
    BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit adt_attribute_proxy(     \
        BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) const &o)              \
        : obj(&o) {}                                                           \
                                                                               \
    BOOST_FUSION_GPU_ENABLED                                                   \
    type get() const {                                                         \
      return access::adt_attribute_access<                                     \
          BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ),                     \
          I>::boost_fusion_adapt_adt_impl_get(*obj);                           \
    }                                                                          \
                                                                               \
    BOOST_FUSION_GPU_ENABLED                                                   \
    operator type() const { return get(); }                                    \
                                                                               \
    BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) const *obj;                \
  };                                                                           \
                                                                               \
  template <BOOST_FUSION_ADAPT_STRUCT_UNPACK_TEMPLATE_PARAMS(                  \
      TEMPLATE_PARAMS_SEQ)>                                                    \
  struct adt_attribute_proxy<BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ),  \
                             I, false> {                                       \
    typedef BOOST_PP_EXPR_IF(BOOST_PP_SEQ_HEAD(TEMPLATE_PARAMS_SEQ), typename) \
        access::adt_attribute_access<                                          \
            BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ), I>::type type;    \
                                                                               \
    BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED explicit adt_attribute_proxy(     \
        BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) & o)                   \
        : obj(&o) {}                                                           \
                                                                               \
    template <class Val>                                                       \
    BOOST_CXX14_CONSTEXPR BOOST_FUSION_GPU_ENABLED adt_attribute_proxy &       \
    operator=(Val const &val) {                                                \
      access::adt_attribute_access<BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(      \
                                       NAME_SEQ),                              \
                                   I>::boost_fusion_adapt_adt_impl_set(*obj,   \
                                                                       val);   \
      return *this;                                                            \
    }                                                                          \
                                                                               \
    BOOST_FUSION_GPU_ENABLED                                                   \
    type get() const {                                                         \
      return access::adt_attribute_access<                                     \
          BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ),                     \
          I>::boost_fusion_adapt_adt_impl_get(*obj);                           \
    }                                                                          \
                                                                               \
    BOOST_FUSION_GPU_ENABLED                                                   \
    operator type() const { return get(); }                                    \
                                                                               \
    BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ) * obj;                     \
  };                                                                           \
                                                                               \
  template <BOOST_FUSION_ADAPT_STRUCT_UNPACK_TEMPLATE_PARAMS(                  \
      TEMPLATE_PARAMS_SEQ)>                                                    \
  struct access::struct_member<                                                \
      BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ), I> {                    \
    typedef BOOST_PP_EXPR_IF(BOOST_PP_SEQ_HEAD(TEMPLATE_PARAMS_SEQ), typename) \
        adt_attribute_proxy<BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ),   \
                            I, false>::type lvalue;                            \
                                                                               \
    BOOST_FUSION_ADAPT_STRUCT_MSVC_REDEFINE_TEMPLATE_PARAMS(                   \
        TEMPLATE_PARAMS_SEQ)                                                   \
                                                                               \
    typedef BOOST_PP_IF(                                                       \
        BOOST_PP_SEQ_HEAD(TEMPLATE_PARAMS_SEQ),                                \
        BOOST_FUSION_ADAPT_ADT_GET_IDENTITY_TEMPLATE_IMPL,                     \
        BOOST_FUSION_ADAPT_ADT_GET_IDENTITY_NON_TEMPLATE_IMPL)(                \
        TEMPLATE_PARAMS_SEQ) type;                                             \
                                                                               \
    template <typename Seq> struct apply {                                     \
      typedef adt_attribute_proxy<BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(       \
                                      NAME_SEQ),                               \
                                  I, is_const<Seq>::value>                     \
          type;                                                                \
                                                                               \
      BOOST_CONSTEXPR BOOST_FUSION_GPU_ENABLED static type call(Seq &obj) {    \
        return type(obj);                                                      \
      }                                                                        \
    };                                                                         \
  };

#endif

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
#include <boost/test/unit_test.hpp>

#include "fixtures.h"
#include <stdexcept>

using std::string;

using lua::Retval;
using lua::Context;
using lua::Valset;
using lua::Value;
using lua::Table;
using lua::mkcf;
using lua::Nil;
using lua::nil;
using lua::CFunction;

struct Udata{int x;};
LUAPP_USERDATA(Udata, "Test.Userdata")

BOOST_AUTO_TEST_SUITE(ContextReturn)

static Retval ret0(Context& context) { return context.ret(); }
static Retval ret1(Context& context) { return context.ret(1); }
static Retval ret3(Context& context) { return context.ret(1, 2, 3); }

BOOST_FIXTURE_TEST_CASE(returnAmount, fxSignal)
{
	gs.runString("function Test(fn) local rv = {fn()}; if #rv == 0 then fnSignal() end end");
	context.global["Test"](mkcf<ret0>, 0);
	BOOST_CHECK(isSignaled());

	gs.runString("function Test(fn) local rv = {fn()}; if #rv == 1 and rv[1] == 1 then fnSignal() end end");
	context.global["Test"](mkcf<ret1>, 1);
	BOOST_CHECK(isSignaled());

	gs.runString("function Test(fn) local rv = {fn()}; if #rv == 3 and rv[1] == 1 and rv[2] == 2 and rv[3] == 3 then fnSignal() end end");
	context.global["Test"](mkcf<ret3>, 3);
	BOOST_CHECK(isSignaled());
}

static Retval doReturn(Context& c)
{
	c.global["val"] = 3.14;
	Valset vs(c);
	vs.push_back(42);
	vs.push_back(43);
	Value v(6.4, c);
	Table t = Table::array(c, 2.718);
	return c.ret(
		nil,
		true,
		1,
		2u,
		3.0f,
		4.0,
		"a string",
		string("another string"),
		mkcf<doReturn>,
		Udata{108},
		vs,
		vs[0],
		v,
		t,
		c.global["val"],
		-64ll,
		65ull
	);
}

BOOST_FIXTURE_TEST_CASE(ReturnedTypes, fxContext)
{
	context.mt<Udata>() = Table::records(context);
	Valset rv = context.closure(mkcf<doReturn>)();
	BOOST_CHECK_EQUAL(rv.size(), 18);
	BOOST_CHECK(rv[0].is<Nil>());
	BOOST_CHECK(rv[1].is<bool>());
	BOOST_CHECK(rv[1].cast<bool>());
	BOOST_CHECK(rv[2].is<int>());
	BOOST_CHECK_EQUAL(rv[2].cast<int>(), 1);
	BOOST_CHECK(rv[3].is<unsigned int>());
	BOOST_CHECK_EQUAL(rv[3].cast<unsigned int>(), 2u);
	BOOST_CHECK(rv[4].is<float>());
	BOOST_CHECK_EQUAL(rv[4].cast<float>(), 3.0f);
	BOOST_CHECK(rv[5].is<double>());
	BOOST_CHECK_EQUAL(rv[5].cast<double>(), 4.0);
	BOOST_CHECK(rv[6].is<string>());
	BOOST_CHECK_EQUAL(rv[6].cast<string>(), "a string");
	BOOST_CHECK(rv[7].is<string>());
	BOOST_CHECK_EQUAL(rv[7].cast<string>(), "another string");
	BOOST_CHECK(rv[8].is<CFunction>());
	BOOST_CHECK(rv[8].cast<CFunction>() == &mkcf<doReturn>);
	BOOST_CHECK(rv[9].is<Udata>());
	BOOST_CHECK_EQUAL(rv[9].cast<Udata>().x, 108);
	BOOST_CHECK(rv[10].is<int>());
	BOOST_CHECK_EQUAL(rv[10].cast<int>(), 42);
	BOOST_CHECK(rv[11].is<int>());
	BOOST_CHECK_EQUAL(rv[11].cast<int>(), 43);
	BOOST_CHECK(rv[12].is<int>());
	BOOST_CHECK_EQUAL(rv[12].cast<int>(), 42);
	BOOST_CHECK(rv[13].is<double>());
	BOOST_CHECK_EQUAL(rv[13].cast<double>(), 6.4);
	BOOST_CHECK(rv[14].is<Table>());
	BOOST_CHECK(rv[15].is<double>());
	BOOST_CHECK_EQUAL(rv[15].cast<double>(), 3.14);
	BOOST_CHECK(rv[16].is<long long>());
	BOOST_CHECK_EQUAL(rv[16].cast<long long>(), -64ll);
	BOOST_CHECK(rv[17].is<unsigned long long>());
	BOOST_CHECK_EQUAL(rv[17].cast<unsigned long long>(), 65ull);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp


text:
/*
 * File:   Sf1TopologyTest.cpp
 * Author: Paolo D'Apice
 *
 * Created on February 22, 2012, 10:06 AM
 */

#define BOOST_TEST_MODULE Sf1TopologyTest
#include <boost/test/unit_test.hpp>

#include "../common.h"
#include "net/sf1r/distributed/Sf1Topology.hpp"
#include <boost/foreach.hpp>
#include <iostream>

using namespace NS_IZENELIB_SF1R;
using std::string;
using std::set;
using std::vector;
using std::cout;
using std::endl;

BOOST_AUTO_TEST_SUITE(Sf1TopologyTest)

/* enable/disable dump to stdout */
//#define DUMP

void
dumpNodes(NodeContainer& nodes) {
#ifdef DUMP
    cout << "=== dump nodes ===" << endl;
    BOOST_FOREACH(Sf1Node node, nodes) {
        cout << node << endl;
    }
    cout << "=== end ===" << endl;
#endif
}

void
dumpCollections(const set<string>& index, NodeCollectionsContainer& colls) {
#ifdef DUMP
    cout << "--- dump collections ---" << endl;
    BOOST_FOREACH(string col, index) {
        NodeCollectionsRange range = colls.equal_range(col);
        cout << col << " =>";
        for (NodeCollectionsContainer::iterator it = range.first; it != range.second; ++it) {
            cout << " " << it->second->getPath();
        }
        cout << endl;
    }
    cout << "--- end ---" << endl;
#endif
}

/** Operations example. */
BOOST_AUTO_TEST_CASE(operations_test) {
    Sf1Topology topology;
    BOOST_CHECK_EQUAL(0, topology.getCollectionIndex().size());

    // add

    topology.addNode("/test/test", "collection#coll1$dataport#18121$baport#18181$masterport#18131$host#host");
    BOOST_CHECK_EQUAL(1, topology.count());
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().size());
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().count("coll1"));
    BOOST_CHECK(not topology.isPresent("/test/node"));
#ifdef ENABLE_ZK_TEST
    dumpCollections(topology.getCollectionIndex(), topology._colls());
#endif
    BOOST_CHECK_EQUAL(1, topology.count("coll1"));
    BOOST_CHECK_EQUAL(0, topology.count("coll2"));
#ifdef ENABLE_ZK_TEST
    dumpNodes(topology._nodes());
#endif

    topology.addNode("/test/node", "collection#coll1,coll2$dataport#18121$baport#18181$masterport#18131$host#host");
    BOOST_CHECK_EQUAL(2, topology.count());
    BOOST_CHECK_EQUAL(2, topology.getCollectionIndex().size());
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().count("coll1"));
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().count("coll2"));
    BOOST_CHECK(topology.isPresent("/test/node"));
#ifdef ENABLE_ZK_TEST
    dumpCollections(topology.getCollectionIndex(), topology._colls());
#endif
    BOOST_CHECK_EQUAL(2, topology.count("coll1"));
    BOOST_CHECK_EQUAL(1, topology.count("coll2"));
#ifdef ENABLE_ZK_TEST
    dumpNodes(topology._nodes());
#endif

    // update

    topology.updateNode("/test/node", "collection#coll2$dataport#18121$baport#18181$masterport#18131$host#host");
    BOOST_CHECK_EQUAL(2, topology.count());
    BOOST_CHECK_EQUAL(2, topology.getCollectionIndex().size());
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().count("coll1"));
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().count("coll2"));
    BOOST_CHECK(topology.isPresent("/test/node"));
#ifdef ENABLE_ZK_TEST
    dumpCollections(topology.getCollectionIndex(), topology._colls());
#endif
     BOOST_CHECK_EQUAL(1, topology.count("coll1"));
     BOOST_CHECK_EQUAL(1, topology.count("coll2"));
#ifdef ENABLE_ZK_TEST
    dumpNodes(topology._nodes());
#endif

    // remove

    topology.removeNode("/test/node");
    BOOST_CHECK_EQUAL(1, topology.count());
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().size());
    BOOST_CHECK_EQUAL(1, topology.getCollectionIndex().count("coll1"));
    BOOST_CHECK_EQUAL(0, topology.getCollectionIndex().count("coll2"));
    BOOST_CHECK(not topology.isPresent("/test/node"));
#ifdef ENABLE_ZK_TEST
    dumpCollections(topology.getCollectionIndex(), topology._colls());
#endif
    BOOST_CHECK_EQUAL(1, topology.count("coll1"));
    BOOST_CHECK_EQUAL(0, topology.count("coll2"));
#ifdef ENABLE_ZK_TEST
    dumpNodes(topology._nodes());
#endif
}

/** Test fixture. */
struct Nodes {
    Nodes() {
        topology.addNode("/test/node1", "collection#coll1$dataport#18121$baport#18181$masterport#18131$host#host1");
        topology.addNode("/test/node2", "collection#coll2$dataport#18121$baport#18181$masterport#18131$host#host2");
        topology.addNode("/test/node3", "collection#coll1,coll2$dataport#18121$baport#18181$masterport#18131$host#host3");
        topology.addNode("/test/node4", "collection#coll1,coll3$dataport#18121$baport#18181$masterport#18131$host#host4");
#ifdef ENABLE_ZK_TEST
        dumpCollections(topology.getCollectionIndex(), topology._colls());
        dumpNodes(topology._nodes());
#endif
    }

    Sf1Topology topology;
};

/** Use node-collections relationship. */
BOOST_FIXTURE_TEST_CASE(nodes_collections_test, Nodes) {
    NodeCollectionsRange range;

    BOOST_CHECK_EQUAL(3, topology.count("coll1"));
    range = topology.getNodesFor("coll1");
    BOOST_CHECK(range.first != range.second);
    for (NodeCollectionsIterator it = range.first; it != range.second; ++it) {
        Sf1Node n = it->second;
        BOOST_CHECK((n.getPath() == "/test/node1") xor (n.getPath() == "/test/node3") xor (n.getPath() == "/test/node4"));
    }

    // use a list instead of a range, for random access
    NodeCollectionsList list(range.first, range.second);
    BOOST_CHECK_EQUAL(3, list.size());
    BOOST_CHECK(list[0].second.getPath() == "/test/node1");
    BOOST_CHECK(list[1].second.getPath() == "/test/node3");
    BOOST_CHECK(list[2].second.getPath() == "/test/node4");

    BOOST_CHECK_EQUAL(2, topology.count("coll2"));
    range = topology.getNodesFor("coll2");
    BOOST_CHECK(range.first != range.second);
    for (NodeCollectionsIterator& it = range.first; it != range.second; ++it) {
        Sf1Node n = it->second;
        BOOST_CHECK((n.getPath() == "/test/node2") xor (n.getPath() == "/test/node3"));
    }

    BOOST_CHECK_EQUAL(1, topology.count("coll3"));
    range = topology.getNodesFor("coll3");
    BOOST_CHECK(range.first != range.second);
    for (NodeCollectionsIterator& it = range.first; it != range.second; ++it) {
        Sf1Node n = it->second;
        BOOST_CHECK(n.getPath() == "/test/node4");
    }

    BOOST_CHECK_EQUAL(0, topology.count("coll5"));
    range = topology.getNodesFor("coll5");
    BOOST_CHECK(range.first == range.second);
}

/** Use nodes. */
BOOST_FIXTURE_TEST_CASE(all_nodes_test, Nodes) {
    NodeListRange range = topology.getNodes();
    BOOST_CHECK_EQUAL(4, range.second - range.first);
}

/** Access a node by path/position. */
BOOST_FIXTURE_TEST_CASE(node_path_test, Nodes) {
    const Sf1Node& node = topology.getNodeAt("/test/node1");
    BOOST_CHECK_EQUAL("/test/node1", node.getPath());
    BOOST_CHECK_EQUAL("host1", node.getHost());

    const Sf1Node& same = topology.getNodeAt(0);
    BOOST_CHECK_EQUAL(node, same);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text: #include <boost/iostreams/filter/regex.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 * Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */
#include <boost/python.hpp>

#include "logdevice/admin/settings/AdminServerSettings.h"
#include "logdevice/clients/python/util/util.h"
#include "logdevice/common/plugin/CommonBuiltinPlugins.h"
#include "logdevice/common/plugin/PluginRegistry.h"
#include "logdevice/common/plugin/StaticPluginLoader.h"
#include "logdevice/common/settings/GossipSettings.h"
#include "logdevice/common/settings/RebuildingSettings.h"
#include "logdevice/common/settings/Settings.h"
#include "logdevice/common/settings/SettingsUpdater.h"
#include "logdevice/common/settings/UpdateableSettings.h"
#include "logdevice/lib/ClientPluginHelper.h"
#include "logdevice/server/ServerSettings.h"
#include "logdevice/server/locallogstore/LocalLogStoreSettings.h"
#include "logdevice/server/locallogstore/RocksDBSettings.h"

using namespace boost::python;
using namespace facebook::logdevice;

std::unordered_map<std::string, std::string>
dict_to_map(boost::python::dict input) {
  std::unordered_map<std::string, std::string> input_settings;
  stl_input_iterator<object> begin(input.keys()), end;
  std::for_each(begin, end, [&](object key) {
    auto key_str = extract_string(key, "settings key");
    auto value =
        extract_string(input.get(key),
                       ("settings value for key\"" + key_str + "\"").c_str(),
                       true /* coerce */);
    input_settings.insert(std::make_pair(key_str, value));
  });

  return input_settings;
}

void validate_server_settings(boost::python::dict input) {
  if (input.is_none()) {
    return;
  }

  UpdateableSettings<ServerSettings> server_settings;
  UpdateableSettings<RebuildingSettings> rebuilding_settings;
  UpdateableSettings<LocalLogStoreSettings> locallogstore_settings;
  UpdateableSettings<GossipSettings> gossip_settings;
  UpdateableSettings<Settings> settings;
  UpdateableSettings<RocksDBSettings> rocksdb_settings;
  UpdateableSettings<AdminServerSettings> admin_server_settings;

  auto settings_updater = std::make_shared<SettingsUpdater>();
  settings_updater->registerSettings(server_settings);
  settings_updater->registerSettings(rebuilding_settings);
  settings_updater->registerSettings(locallogstore_settings);
  settings_updater->registerSettings(gossip_settings);
  settings_updater->registerSettings(settings);
  settings_updater->registerSettings(rocksdb_settings);
  settings_updater->registerSettings(admin_server_settings);

  std::shared_ptr<PluginRegistry> plugin_registry =
      std::make_shared<PluginRegistry>(
          createPluginVector<StaticPluginLoader, BuiltinPluginProvider>());
  plugin_registry->addOptions(settings_updater.get());

  auto input_settings = dict_to_map(input);
  try {
    settings_updater->validateFromConfig(input_settings, SettingFlag::SERVER);
  } catch (const boost::program_options::error& ex) {
    throw_python_exception(PyExc_ValueError, str(ex.what()));
  }
}

void validate_client_settings(boost::python::dict input) {
  if (input.is_none()) {
    return;
  }

  UpdateableSettings<RebuildingSettings> rebuilding_settings;
  UpdateableSettings<GossipSettings> gossip_settings;
  UpdateableSettings<Settings> settings;

  auto settings_updater = std::make_shared<SettingsUpdater>();
  settings_updater->registerSettings(rebuilding_settings);
  settings_updater->registerSettings(gossip_settings);
  settings_updater->registerSettings(settings);

  std::shared_ptr<PluginRegistry> plugin_registry =
      std::make_shared<PluginRegistry>(getClientPluginProviders());
  plugin_registry->addOptions(settings_updater.get());

  auto input_settings = dict_to_map(input);
  try {
    settings_updater->validateFromConfig(input_settings, SettingFlag::CLIENT);
  } catch (const boost::program_options::error& ex) {
    throw_python_exception(PyExc_ValueError, str(ex.what()));
  }
}

BOOST_PYTHON_MODULE(settings) {
  def("validate_server_settings", &validate_server_settings);
  def("validate_client_settings", &validate_client_settings);
}

max_stars_repo_name: ahmad-diaa/LogDevice

max_issues_repo_name: ahmad-diaa/LogDevice

max_forks_repo_name: ahmad-diaa/LogDevice


text:
/*
 * This file is part of MXE. See LICENSE.md for licensing information.
 */

#include <iostream>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/tss.hpp>

boost::thread_specific_ptr<int> ptr;

#if 0
// https://www.boost.org/doc/libs/1_60_0/libs/context/doc/html/context/context.html
#include <boost/context/all.hpp>
boost::context::fcontext_t fcm,fc1,fc2;
#endif

void test_thread()
{
    if (ptr.get() == 0) {
        ptr.reset(new int(0));
    }
    std::cout << "Hello, World! from thread" << std::endl;
}

#if 0
void f1(intptr_t)
{
    std::cout<<"f1: entered"<<std::endl;
    std::cout<<"f1: call jump_fcontext( & fc1, fc2, 0)"<< std::endl;
    boost::context::jump_fcontext(&fc1,fc2,0);
    std::cout<<"f1: return"<<std::endl;
    boost::context::jump_fcontext(&fc1,fcm,0);
}

void f2(intptr_t)
{
    std::cout<<"f2: entered"<<std::endl;
    std::cout<<"f2: call jump_fcontext( & fc2, fc1, 0)"<<std::endl;
    boost::context::jump_fcontext(&fc2,fc1,0);
    BOOST_ASSERT(false&&!"f2: never returns");
}

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

    boost::archive::xml_oarchive oa(std::cout);
    std::string s = "\n\n    Hello, World!\n\n";
    oa << BOOST_SERIALIZATION_NVP(s);

    boost::thread thrd(test_thread);
    thrd.join();

    std::size_t size(8192);
    void* sp1(std::malloc(size));
    void* sp2(std::malloc(size));

    fc1=boost::context::make_fcontext(sp1,size,f1);
    fc2=boost::context::make_fcontext(sp2,size,f2);

    std::cout<<"main: call jump_fcontext( & fcm, fc1, 0)"<<std::endl;
    boost::context::jump_fcontext(&fcm,fc1,0);

    return 0;
}
#else
int main(int argc, char *argv[])
{
    (void)argc;
    (void)argv;

    boost::thread thrd(test_thread);
    thrd.join();

    return 0;
}
#endif

max_stars_repo_name: revilo/mxe

max_issues_repo_name: revilo/mxe

max_forks_repo_name: revilo/mxe


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

#include "orb2fchk.h"

// Third party includes
#include <boost/algorithm/string.hpp>

// Local VOTCA includes
#include "votca/xtp/gaussianwriter.h"
#include "votca/xtp/orbitals.h"
#include <votca/tools/constants.h>

namespace votca {
namespace xtp {

void Orb2Fchk::ParseOptions(const tools::Property& options) {

  basename_ = job_name_;
  orbfile_ = job_name_ + ".orb";
  state_ = options.get(".qmstate").as<QMState>();
  diff2gs_ = options.get(".diff2gs").as<bool>();
}

bool Orb2Fchk::Run() {
  log_.setReportLevel(Log::current_level);
  log_.setMultithreading(true);
  log_.setCommonPreface("\n... ...");

  Orbitals orbitals;
  XTP_LOG(Log::error, log_) << "Loading data from " << orbfile_ << std::flush;
  XTP_LOG(Log::error, log_)
      << "Using density of state:  " << state_.ToString() << std::flush;
  orbitals.ReadFromCpt(orbfile_);

  GaussianWriter writer(log_);
  writer.WriteFile(basename_, orbitals, state_, diff2gs_);

  return true;
}

}  // namespace xtp
}  // namespace votca

ext: cc

max_stars_repo_name: rubengerritsen/xtp

max_issues_repo_name: rubengerritsen/xtp

max_forks_repo_name: rubengerritsen/xtp


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

#include "normalize_data_transformer.h"

#include "neural_network_exception.h"

#include <opencv2/core/core.hpp>
#include <boost/format.hpp>
#include <boost/uuid/uuid_io.hpp>

namespace nnforge
{
	// {9BABFBB9-3502-4C58-AA38-A550C1AA843D}
	const boost::uuids::uuid normalize_data_transformer::normalizer_guid =
	{ 0x9b, 0xab, 0xfb, 0xb9
	, 0x35, 0x02
	, 0x4c, 0x58
	, 0xaa, 0x38
	, 0xa5, 0x50, 0xc1, 0xaa, 0x84, 0x3d };

	normalize_data_transformer::normalize_data_transformer()
	{
	}

	normalize_data_transformer::normalize_data_transformer(const std::vector<feature_map_data_stat>& feature_map_data_stat_list)
	{
		for (std::vector<feature_map_data_stat>::const_iterator it = feature_map_data_stat_list.begin(); it != feature_map_data_stat_list.end(); ++it)
		{
			const feature_map_data_stat& current_stat = *it;
			float mult;
			float add;
			float t1 = std::max(current_stat.max - current_stat.average, current_stat.average - current_stat.min);
			if (t1 > 0.0F)
			{
				mult = 1.0F / t1;
				add = -current_stat.average * mult;
			}
			else
			{
				if (current_stat.average == 0.0F)
				{
					mult = 1.0F;
					add = 1.0F;
				}
				else
				{
					mult = 1.0F / current_stat.average;
					add = 0.0F;
				}
			}

			mul_add_list.push_back(std::make_pair(mult, add));
		}
	}

	normalize_data_transformer::~normalize_data_transformer()
	{
	}

	nnforge_shared_ptr<normalize_data_transformer> normalize_data_transformer::get_inverted_transformer() const
	{
		nnforge_shared_ptr<normalize_data_transformer> res(new normalize_data_transformer());

		for(std::vector<std::pair<float, float> >::const_iterator mul_add_it = mul_add_list.begin(); mul_add_it != mul_add_list.end(); ++mul_add_it)
		{
			float new_mult = 1.0F / mul_add_it->first;
			float new_add = -new_mult * mul_add_it->second;

			res->mul_add_list.push_back(std::make_pair(new_mult, new_add));
		}

		return res;
	}

	void normalize_data_transformer::transform(
		const void * data,
		void * data_transformed,
		neuron_data_type::input_type type,
		const layer_configuration_specific& original_config,
		unsigned int sample_id)
	{
		if (type != neuron_data_type::type_float)
			throw neural_network_exception("normalize_data_transformer is implemented for data stored as floats only");

		float * dt = static_cast<float *>(data_transformed);
		unsigned int elem_count_per_feature_map = original_config.get_neuron_count_per_feature_map();

		for(std::vector<std::pair<float, float> >::const_iterator mul_add_it = mul_add_list.begin(); mul_add_it != mul_add_list.end(); ++mul_add_it, dt += elem_count_per_feature_map)
			std::transform(dt, dt + elem_count_per_feature_map, dt, normalize_helper_struct(mul_add_it->first, mul_add_it->second));
	}

	void normalize_data_transformer::write(std::ostream& binary_stream_to_write_to) const
	{
		binary_stream_to_write_to.exceptions(std::ostream::eofbit | std::ostream::failbit | std::ostream::badbit);

		binary_stream_to_write_to.write(reinterpret_cast<const char*>(normalizer_guid.data), sizeof(normalizer_guid.data));

		unsigned int feature_map_count = static_cast<unsigned int>(mul_add_list.size());
		binary_stream_to_write_to.write(reinterpret_cast<const char*>(&feature_map_count), sizeof(feature_map_count));

		for(std::vector<std::pair<float, float> >::const_iterator it =  mul_add_list.begin(); it != mul_add_list.end(); ++it)
		{
			binary_stream_to_write_to.write(reinterpret_cast<const char*>(&(it->first)), sizeof(float));
			binary_stream_to_write_to.write(reinterpret_cast<const char*>(&(it->second)), sizeof(float));
		}

		binary_stream_to_write_to.flush();
	}

	void normalize_data_transformer::read(std::istream& binary_stream_to_read_from)
	{
 		mul_add_list.clear();

		binary_stream_to_read_from.exceptions(std::ostream::eofbit | std::ostream::failbit | std::ostream::badbit);

		boost::uuids::uuid normalizer_guid_read;
		binary_stream_to_read_from.read(reinterpret_cast<char*>(normalizer_guid_read.data), sizeof(normalizer_guid_read.data));
		if (normalizer_guid_read != normalizer_guid)
			throw neural_network_exception((boost::format("Unknown normalizer GUID encountered in input stream: %1%") % normalizer_guid_read).str());

		unsigned int feature_map_count_read;
		binary_stream_to_read_from.read(reinterpret_cast<char*>(&feature_map_count_read), sizeof(feature_map_count_read));

		for(unsigned int i = 0; i < feature_map_count_read; ++i)
		{
			float mult;
			binary_stream_to_read_from.read(reinterpret_cast<char*>(&mult), sizeof(float));
			float add;
			binary_stream_to_read_from.read(reinterpret_cast<char*>(&add), sizeof(float));

			mul_add_list.push_back(std::make_pair(mult, add));
		}
	}

 	bool normalize_data_transformer::is_deterministic() const
	{
		return true;
	}
}

max_stars_repo_name: yanshanjing/nnForge

max_issues_repo_name: yanshanjing/nnForge

max_forks_repo_name: yanshanjing/nnForge


text: #include <boost/numeric/odeint/stepper/generation/generation_runge_kutta_fehlberg78.hpp>


text:
/**
 ******************************************************************************
 * @file    socket_hal.c
 * @author  Matthew McGowan
 * @version V1.0.0
 * @date    25-Sept-2014
 * @brief
 ******************************************************************************
  Copyright (c) 2013-2015 Particle Industries, Inc.  All rights reserved.

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

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

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************
 */
#include "socket_hal.h"
#include "inet_hal.h"
#include "core_msg.h"

#pragma GCC diagnostic ignored "-Wunused-variable"
#pragma GCC diagnostic ignored "-Wmissing-braces"
#include <boost/array.hpp>

// conflict of types
#define socklen_t boost_socklen_t
#include <boost/asio.hpp>
#undef socklen_t

namespace ip = boost::asio::ip;

const sock_handle_t SOCKET_MAX = (sock_handle_t)8;
const sock_handle_t SOCKET_INVALID = (sock_handle_t)-1;

boost::asio::io_service io_service;
boost::system::error_code ec;

boost::array<ip::tcp::socket, 8> handles = {
    ip::tcp::socket(io_service),
    ip::tcp::socket(io_service),
    ip::tcp::socket(io_service),
    ip::tcp::socket(io_service),
    ip::tcp::socket(io_service),
    ip::tcp::socket(io_service),
    ip::tcp::socket(io_service),
    ip::tcp::socket(io_service)
};

ip::tcp::socket invalid_(io_service);

ip::tcp::socket& invalid() {
    return invalid_;
}

ip::tcp::socket& from(sock_handle_t sd)
{
    if (sd>=SOCKET_MAX)
        return invalid();
    return handles[sd];
}

sock_handle_t next_unused()
{
    for (sock_handle_t i=0; i<SOCKET_MAX; i++) {
        if (!from(i).is_open())
            return i;
    }
    return -1;
}

bool is_valid(ip::tcp::socket& handle) {
    return &handle!=&invalid();
}

int inet_gethostbyname(char* hostname, uint16_t hostnameLen, HAL_IPAddress* out_ip_addr)
{
    out_ip_addr->ipv4 = 0;
    ip::tcp::resolver resolver(io_service);
    ip::tcp::resolver::query query(hostname, "");
    for(ip::tcp::resolver::iterator i = resolver.resolve(query);
                            i != ip::tcp::resolver::iterator();
                            ++i)
    {
        ip::tcp::endpoint end = *i;
        ip::address addr = end.address();
        if (addr.is_v4()) {
            ip::address_v4 addr_v4 = addr.to_v4();
            out_ip_addr->ipv4 = addr_v4.to_ulong();
        }
    }
    return 0;
}

int32_t socket_connect(sock_handle_t sd, const sockaddr_t *addr, long addrlen)
{
    auto& handle = from(sd);
    if (!is_valid(handle))
        return -1;

    unsigned port = addr->sa_data[0] << 8 | addr->sa_data[1];
    // 2-5 are IP address in network byte order
    const uint8_t* dest = addr->sa_data+2;

    ip::address_v4::bytes_type address = {{ dest[0], dest[1], dest[2], dest[3] }};
    ip::tcp::endpoint endpoint(boost::asio::ip::address_v4(address),port);

    handle.connect(endpoint, ec);
    bool open = handle.is_open();
    return ec.value();
}

sock_result_t socket_reset_blocking_call()
{
    return 0;
}

sock_result_t socket_receive(sock_handle_t sd, void* buffer, socklen_t len, system_tick_t _timeout)
{
    auto& handle = from(sd);
    if (!is_valid(handle))
        return -1;
    boost::asio::socket_base::bytes_readable command(true);
    handle.io_control(command);
    std::size_t available = command.get();
    sock_result_t result = 0;
    if (available) {
        available = handle.read_some(boost::asio::buffer(buffer, len), ec);
        result = ec.value() ? -1 : available;
    }
    return result;
}

sock_result_t socket_send(sock_handle_t sd, const void* buffer, socklen_t len)
{
    auto& socket = from(sd);
    if (!is_valid(socket))
        return -1;
    sock_result_t result = socket.send(boost::asio::buffer(buffer, len));
    return result;
}

sock_result_t socket_create_nonblocking_server(sock_handle_t sock, uint16_t port)
{
    NOT_IMPLEMENTED("create nonblocking server");
    return 0;
}

sock_result_t socket_receivefrom(sock_handle_t sock, void* buffer, socklen_t bufLen, uint32_t flags, sockaddr_t* addr, socklen_t* addrsize)
{
    NOT_IMPLEMENTED("socket_receivefrom");
    return 0;
}

sock_result_t socket_bind(sock_handle_t sock, uint16_t port)
{
    NOT_IMPLEMENTED("socket_bind");
    return 0;
}

sock_result_t socket_accept(sock_handle_t sock)
{
    NOT_IMPLEMENTED("socket_accept");
    return 0;
}

uint8_t socket_active_status(sock_handle_t socket)
{
    bool open = from(socket).is_open();
    return open ? SOCKET_STATUS_ACTIVE : SOCKET_STATUS_INACTIVE;
}

sock_result_t socket_close(sock_handle_t sock)
{
    auto& handle = from(sock);
    handle.close();
    return 0;
}

sock_handle_t socket_create(uint8_t family, uint8_t type, uint8_t protocol, uint16_t port, network_interface_t nif)
{
    sock_handle_t handle = next_unused();
    if (handle==SOCKET_INVALID)
        return -1;

    auto& socket = from(handle);
    socket.open(::ip::tcp::v4(), ec);
    sock_handle_t result = ec.value();
    return result ? result : handle;
}

sock_result_t socket_sendto(sock_handle_t sd, const void* buffer, socklen_t len, uint32_t flags, sockaddr_t* addr, socklen_t addr_size)
{
    //NOT_IMPLEMENTED("socket_sendto");
    return 0;
}

uint8_t socket_handle_valid(sock_handle_t handle) {
    return is_valid(from(handle));
}

sock_handle_t socket_handle_invalid()
{
    return SOCKET_INVALID;
}

sock_result_t socket_join_multicast(const HAL_IPAddress* addr, network_interface_t nif, void* reserved)
{
    return -1;
}

sock_result_t socket_leave_multicast(const HAL_IPAddress* addr, network_interface_t nif, void* reserved)
{
	return -1;
}

sock_result_t socket_peer(sock_handle_t sd, sock_peer_t* peer, void* reserved)
{
    return -1;
}


text:
//*****************************************************************
// Copyright 2015 MIT Lincoln Laboratory
// Project:            SPAR
// Authors:            OMD
// Description:        Unit tests for KnotNodeDeque, its iterator, etc.
//
// Modifications:
// Date          Name           Modification
// ----          ----           ------------
// 31 Jul 2012   omd            Original Version
//*****************************************************************

#include "knot-node-deque.h"

#include <boost/assign/list_of.hpp>
#include <cstring>
#include <sstream>
#include <vector>

#include "knot-node.h"
#include "strand.h"
#include "common/string-algo.h"

#define BOOST_TEST_MODULE KnotNodeDequeTest

#include "common/test-init.h"

using namespace std;
using boost::assign::list_of;

// Check that I can create a left sub-deque (e.g. it's all the characters
// starting at the left, up to some point) from a deque. Also check that after
// free the full deque the sub-deque is still defined.
BOOST_AUTO_TEST_CASE(LeftSubDequeWorks) {
  auto_ptr<KnotNodeDeque> full(new KnotNodeDeque);

  vector<const char*> parts;
  parts.push_back("This is ");
  parts.push_back("a series ");
  parts.push_back("of strings ");
  parts.push_back("that make one long deque ");
  for (vector<const char*>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand* s = new CharPtrStrand(StrDup(*i), strlen(*i));
    full->Append(s);
  }

  auto_ptr<KnotNodeDeque> sub(full->GetSubDeque(0, 2, NULL, NULL));

  BOOST_REQUIRE_EQUAL(full->GetNumStrands(), 4);
  for (int i = 0; i < 4; ++i) {
    BOOST_CHECK_EQUAL(full->GetStrand(i)->ToString(), parts[i]);
  }

  BOOST_REQUIRE_EQUAL(sub->GetNumStrands(), 2);
  for (int i = 0; i < 2; ++i) {
    BOOST_CHECK_EQUAL(sub->GetStrand(i)->ToString(), parts[i]);
  }

  full.reset();

  // The sub-deque should still be valid.
  BOOST_REQUIRE_EQUAL(sub->GetNumStrands(), 2);
  for (int i = 0; i < 2; ++i) {
    BOOST_CHECK_EQUAL(sub->GetStrand(i)->ToString(), parts[i]);
  }
}

// Check that we can delete the sub-knot before the full knot and that works.
// Note that the destructor has extra check in debug builds to ensure that
// everything was, in fact, freed.
BOOST_AUTO_TEST_CASE(DeleteLeftSubSubBeforeFull) {
  auto_ptr<KnotNodeDeque> full(new KnotNodeDeque);

  vector<const char*> parts;
  parts.push_back("This is ");
  parts.push_back("a series ");
  parts.push_back("of strings ");
  parts.push_back("that make one long deque ");
  for (vector<const char*>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand* s = new CharPtrStrand(StrDup(*i), strlen(*i));
    full->Append(s);
  }

  auto_ptr<KnotNodeDeque> sub(full->GetSubDeque(0, 2, NULL, NULL));
  BOOST_REQUIRE_EQUAL(sub->GetNumStrands(), 2);
  for (int i = 0; i < 2; ++i) {
    BOOST_CHECK_EQUAL(sub->GetStrand(i)->ToString(), parts[i]);
  }
  sub.reset();

  // The full deque should still be valid.
  BOOST_REQUIRE_EQUAL(full->GetNumStrands(), 4);
  for (int i = 0; i < 4; ++i) {
    BOOST_CHECK_EQUAL(full->GetStrand(i)->ToString(), parts[i]);
  }
}

// Test that a sub-knot with a replacement node on the right works.
BOOST_AUTO_TEST_CASE(LeftSubWithReplaceWorks) {
  auto_ptr<KnotNodeDeque> full(new KnotNodeDeque);

  vector<const char*> parts;
  parts.push_back("s1 ");
  parts.push_back("s2 ");
  parts.push_back("s3 ");
  parts.push_back("longer string here ");
  parts.push_back("s5 ");
  parts.push_back("s6 ");
  parts.push_back("s7 ");
  for (vector<const char*>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand* s = new CharPtrStrand(StrDup(*i), strlen(*i));
    full->Append(s);
  }

  auto_ptr<KnotNodeDeque> sub(
      full->GetSubDeque(0, 4, NULL, full->GetStrand(3)->GetSubstrand(0, 4)));

  BOOST_CHECK_EQUAL(sub->GetStrand(0)->ToString(), "s1 ");
  BOOST_CHECK_EQUAL(sub->GetStrand(1)->ToString(), "s2 ");
  BOOST_CHECK_EQUAL(sub->GetStrand(2)->ToString(), "s3 ");
  BOOST_CHECK_EQUAL(sub->GetStrand(3)->ToString(), "long");
}

// Create a subknot that holds the characters from some point in the middle up
// to and including the end.
BOOST_AUTO_TEST_CASE(RightSubDequeWorks) {
  auto_ptr<KnotNodeDeque> full(new KnotNodeDeque);

  vector<string> parts = list_of("Part 1")("Part 2")("Part 3")("Part 4")
      ("Part 5");

  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand *s = new CharPtrStrand(StrDup(i->c_str()), i->size());
    full->Append(s);
  }

  auto_ptr<KnotNodeDeque> sub(full->GetSubDeque(2, 3, NULL, NULL));

  BOOST_REQUIRE_EQUAL(sub->GetNumStrands(), 3);
  BOOST_CHECK_EQUAL(sub->GetStrand(0)->ToString(), parts[2]);
  BOOST_CHECK_EQUAL(sub->GetStrand(1)->ToString(), parts[3]);
  BOOST_CHECK_EQUAL(sub->GetStrand(2)->ToString(), parts[4]);

  // The full deque should still be valid.
  BOOST_REQUIRE_EQUAL(full->GetNumStrands(), parts.size());
  for (int i = 0; i < 4; ++i) {
    BOOST_CHECK_EQUAL(full->GetStrand(i)->ToString(), parts[i]);
  }
}

// Check that I can create a sub-deque, free it, and the full deque is still
// valid.
BOOST_AUTO_TEST_CASE(DeleteRightSubBeforeFullWorks) {
  auto_ptr<KnotNodeDeque> full(new KnotNodeDeque);

  vector<string> parts = list_of("Part 1")("Part 2")("Part 3")("Part 4")
      ("Part 5");

  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand *s = new CharPtrStrand(StrDup(i->c_str()), i->size());
    full->Append(s);
  }

  auto_ptr<KnotNodeDeque> sub(full->GetSubDeque(2, 2, NULL, NULL));

  BOOST_REQUIRE_EQUAL(sub->GetNumStrands(), 2);
  BOOST_CHECK_EQUAL(sub->GetStrand(0)->ToString(), parts[2]);
  BOOST_CHECK_EQUAL(sub->GetStrand(1)->ToString(), parts[3]);

  // Free the sub-deque
  sub.reset();

  // The full deque should still be valid.
  BOOST_REQUIRE_EQUAL(full->GetNumStrands(), parts.size());
  for (int i = 0; i < 4; ++i) {
    BOOST_CHECK_EQUAL(full->GetStrand(i)->ToString(), parts[i]);
  }

}

// Make sure a right-subknot with a left ghost strand works.
BOOST_AUTO_TEST_CASE(RightSubDequeWithGhostWorks) {
  auto_ptr<KnotNodeDeque> full(new KnotNodeDeque);

  vector<string> parts = list_of("Part 1")("Part 2")("Part 3")("Part 4")
      ("Part 5");

  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand *s = new CharPtrStrand(StrDup(i->c_str()), i->size());
    full->Append(s);
  }

  auto_ptr<KnotNodeDeque> sub(full->GetSubDeque(
          2, 2, full->GetStrand(2)->GetSubstrand(3, 3), NULL));

  BOOST_REQUIRE_EQUAL(sub->GetNumStrands(), 2);
  // The first node should be a sub-strand.
  BOOST_CHECK_EQUAL(sub->GetStrand(0)->ToString(), "t 3");
  BOOST_CHECK_EQUAL(sub->GetStrand(1)->ToString(), parts[3]);

  // The full deque should still be valid.
  BOOST_REQUIRE_EQUAL(full->GetNumStrands(), parts.size());
  for (int i = 0; i < 4; ++i) {
    BOOST_CHECK_EQUAL(full->GetStrand(i)->ToString(), parts[i]);
  }
}

// Make sure StrandWithChar works on a regular, full deque.
BOOST_AUTO_TEST_CASE(StrandWithCharWorks) {
  KnotNodeDeque full_d;

  vector<string> parts = list_of("Part 1")("Part 2")("Part 3")("Part 4")
      ("Part 5");

  string complete_string;

  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand *s = new CharPtrStrand(StrDup(i->c_str()), i->size());
    full_d.Append(s);
    complete_string += *i;
  }

  for (size_t i = 0; i < complete_string.size(); ++i) {
    int strand_idx, offset;
    strand_idx = full_d.StrandWithChar(i, &offset);
    BOOST_CHECK_EQUAL(full_d.GetStrand(strand_idx)->CharAt(offset),
                      complete_string[i]);
  }
}

// First test to check that StrandWithChar works properly with a subknot that's
// the right sub-knot. This checks that it works when the right sub-knot
// includes the 1st node in the deque.
BOOST_AUTO_TEST_CASE(StrandWithCharRightSubFirstNode) {
  KnotNodeDeque full_d;

  vector<string> parts = list_of("This is")(" a goo")("d unit")(" test");

  string complete_string;
  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand *s = new CharPtrStrand(StrDup(i->c_str()), i->size());
    full_d.Append(s);
    complete_string += *i;
  }

  auto_ptr<KnotNodeDeque> sub(full_d.GetSubDeque(
          0, 4, full_d.GetStrand(0)->GetSubstrand(3, Strand::npos), NULL));
  string substr(complete_string.begin() + 3, complete_string.end());

  for (size_t i = 0; i < substr.size(); ++i) {
    int strand_idx, offset;
    strand_idx = sub->StrandWithChar(i, &offset);
    BOOST_CHECK_EQUAL(sub->GetStrand(strand_idx)->CharAt(offset), substr[i]);
  }
}

// Similar to the above but the subknot starts in the 2nd node and there are no
// ghost nodes at all.
BOOST_AUTO_TEST_CASE(StrandWithCharRightSubSecondNodeNoGhost) {
  KnotNodeDeque full_d;

  vector<string> parts = list_of("This is")(" a goo")("d unit")(" test");

  string complete_string;
  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand *s = new CharPtrStrand(StrDup(i->c_str()), i->size());
    full_d.Append(s);
    complete_string += *i;
  }

  auto_ptr<KnotNodeDeque> sub(full_d.GetSubDeque(
          1, 3, NULL, NULL));
  string substr(complete_string.begin() + parts[0].size(),
                complete_string.end());

  for (size_t i = 0; i < substr.size(); ++i) {
    int strand_idx, offset;
    strand_idx = sub->StrandWithChar(i, &offset);
    BOOST_CHECK_EQUAL(sub->GetStrand(strand_idx)->CharAt(offset), substr[i]);
  }
}

// Like the above but also uses a left ghost node.
BOOST_AUTO_TEST_CASE(StrandWithCharRightSubSecondNodeWithGhost) {
  KnotNodeDeque full_d;

  vector<string> parts = list_of("This is")(" a goo")("d unit")(" test");

  string complete_string;
  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    Strand *s = new CharPtrStrand(StrDup(i->c_str()), i->size());
    full_d.Append(s);
    complete_string += *i;
  }

  auto_ptr<KnotNodeDeque> sub(full_d.GetSubDeque(
          1, 3, full_d.GetStrand(1)->GetSubstrand(1, Strand::npos), NULL));
  string substr(complete_string.begin() + parts[0].size() + 1,
                complete_string.end());

  for (size_t i = 0; i < substr.size(); ++i) {
    int strand_idx, offset;
    strand_idx = sub->StrandWithChar(i, &offset);
    BOOST_CHECK_EQUAL(sub->GetStrand(strand_idx)->CharAt(offset), substr[i]);
  }
}

// Create a sub-deque that contains the middle of a deque. Then delete the full
// deque and make sure the sub-deque is still valid and that character access
// works as expected.
BOOST_AUTO_TEST_CASE(MiddleSubAfterDeleteFullWorks) {
  auto_ptr<KnotNodeDeque> full(new KnotNodeDeque);
  string full_string;

  vector<string> parts = list_of("part 1 ")("part 2 ")("longer part 3")
      (" also part 4.")(" There's a part 5 for fun.")(" and one to grow on!");

  for (vector<string>::iterator i = parts.begin(); i != parts.end(); ++i) {
    full->Append(new StringStrand(new string(*i)));
    full_string += *i;
  }

  // Now create a sub-deque. This will contain part of the 2nd strand, all of
  // strands 3 and 4, and part of strand 5 (all 1-indexed here).
  auto_ptr<KnotNodeDeque> sub(full->GetSubDeque(
          1, 4, full->GetStrand(1)->GetSubstrand(4, 3),
          full->GetStrand(4)->GetSubstrand(0, 6)));
  // sub should now contain the data " 2 longer part 3 also part 4. There". Make
  // sure this is true on a character-by-character basis.
  string sub_str = full_string.substr(11, 35);

  for (size_t i = 0; i < sub_str.size(); ++i) {
    int strand_idx, offset;
    strand_idx = sub->StrandWithChar(i, &offset);
    BOOST_CHECK_EQUAL(sub->GetStrand(strand_idx)->CharAt(offset), sub_str[i]);
  }

  // Now free the base deque and make sure the sub-deque is still valid.
  full.reset();
  for (size_t i = 0; i < sub_str.size(); ++i) {
    int strand_idx, offset;
    strand_idx = sub->StrandWithChar(i, &offset);
    BOOST_CHECK_EQUAL(sub->GetStrand(strand_idx)->CharAt(offset), sub_str[i]);
  }
}

max_stars_repo_name: nathanawmk/SPARTA

max_issues_repo_name: nathanawmk/SPARTA

max_forks_repo_name: nathanawmk/SPARTA


text:
// Copyright (c) 2021, The Talleo developers
// Copyright (c) 2021 - 2022, The parsec developers
//
// This file is part of parsec.
//
// parsec is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// parsec is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with parsec. If not, see <http://www.gnu.org/licenses/>.

#ifdef WIN32
#define NOMINMAX
#include <windows.h>
#endif

#include <boost/program_options.hpp>
#include <chrono>
#include <fstream>
#include <mutex>
#include <random>

#include "Common/int-util.h"
#include "Common/Base58.h"
#include "Common/ColouredMsg.h"
#include "Common/CommandLine.h"
#include "Common/ConsoleTools.h"
#include "Common/StringTools.h"
#include "Common/Varint.h"
#include "crypto/hash.h"
#include "crypto/crypto.h"
extern "C"
{
#include "crypto/keccak.h"
}
#include "CryptoNoteCore/Account.h"
#include "CryptoNoteCore/Currency.h"
#include "CryptoNoteCore/CryptoNoteBasicImpl.h"
#include "Logging/LoggerGroup.h"
#include "Logging/ConsoleLogger.h"
#include "Logging/LoggerRef.h"
#include "Logging/LoggerManager.h"
#include "Mnemonics/electrum-words.h"
#include "System/Dispatcher.h"
#include "System/RemoteContext.h"
#include "CryptoNoteConfig.h"
#include "CryptoTypes.h"
#include "version.h"

using namespace CryptoNote;
using namespace Logging;

namespace po = boost::program_options;

std::mutex outputMutex;

namespace command_line
{
  const command_line::arg_descriptor<std::string> arg_prefix = {"prefix", "Specify the address prefix"};
  const command_line::arg_descriptor<int> arg_count = {"count", "Specify the number of addresses to find", 1};
  const command_line::arg_descriptor<int> arg_threads = {"threads", "Specify the number of threads to use", 1};
  const command_line::arg_descriptor<std::string> arg_file = {"file", "Specify the file name to save generated keys to file, "
    "by default found keys are just shown in console. If the file exists, new keys are appended"};
}

void seedFormater(std::string& seed) {
    const unsigned int word_width = 12;
    const unsigned int seed_col = 5;
    std::string word_buff;
    std::vector<std::string> seed_array;
    unsigned int word_n = 0;
    for (unsigned int n = 0; n <= seed.length(); n++) {
        if (seed[n] != 0x20 && seed[n] != 0x0A && seed[n] != 0x00) {
            word_buff.push_back(seed[n]);
        }
        else {
            if (!word_buff.empty()) {
                seed_array.push_back(word_buff);
                word_buff.clear();
            }
        }
    }
    seed.clear();
    for (std::string word : seed_array) {
        seed.append(word);
        for (unsigned int k = 2; k <= word_width - word.length() && word.length() <= word_width; k++) seed.append(" ");
        seed.append(" ");
        word_n++;
        if (word_n >= seed_col) {
            word_n = 0;
            seed.append("\n           ");
        }
    }
    seed.erase(seed.size() - 11); // remove last line of spacers
}

bool is_valid_prefix(const std::string& prefix, Currency& currency) {
    if (prefix.length() <= 2 || prefix.length() >= 95)
        return false;

    const char alphabet[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    for (const char& c : prefix) {
        if (std::string(alphabet).find(c) == std::string::npos)
            return false;
    }

    std::string zerohex = "0000000000000000000000000000000000000000000000000000000000000000";
    std::string ffhex = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";

    AccountPublicAddress lowest_acc;
    AccountPublicAddress highest_acc;

    Common::podFromHex(zerohex, lowest_acc.spendPublicKey);
    Common::podFromHex(zerohex, lowest_acc.viewPublicKey);
    Common::podFromHex(ffhex, highest_acc.spendPublicKey);
    Common::podFromHex(ffhex, highest_acc.viewPublicKey);

    std::string lowest_address = currency.accountAddressAsString(lowest_acc);
    std::string highest_address = currency.accountAddressAsString(highest_acc);

    std::string lowest = lowest_address.substr(0, prefix.length());
    std::string highest = highest_address.substr(0, prefix.length());

    if (prefix < lowest)
        return false;
    if (prefix > highest)
        return false;

    return true;
}

bool check_address_prefix(const std::string& prefix, Currency& currency, const po::variables_map& vm, AccountKeys& _keys) {
    CryptoNote::AccountPublicAddress publicKeys;
    if (secret_key_to_public_key(_keys.spendSecretKey, publicKeys.spendPublicKey)) {
        AccountBase::generateViewFromSpend(_keys.spendSecretKey, _keys.viewSecretKey, publicKeys.viewPublicKey);
        std::string address = currency.accountAddressAsString(publicKeys);
        if ((address.substr(0, prefix.length()) == prefix)) {
            std::lock_guard<std::mutex> guard(outputMutex);

            std::string found = "\n";

            found += "Address:   " + address + "\n";
            found += "Spend key: " + Common::podToHex(_keys.spendSecretKey) + "\n";
            found += "View key:  " + Common::podToHex(_keys.viewSecretKey) + "\n";

            std::string electrum_words;
            std::string lang = "English";
            Crypto::ElectrumWords::bytes_to_words(_keys.spendSecretKey, electrum_words, lang);
            Crypto::SecretKey second;
            keccak((uint8_t*)&_keys.spendSecretKey, sizeof(Crypto::SecretKey), (uint8_t*)&second, sizeof(Crypto::SecretKey));
            sc_reduce32((uint8_t*)&second);
            bool success = memcmp(second.data, _keys.viewSecretKey.data, sizeof(Crypto::SecretKey)) == 0;
            if (success)
            {
                seedFormater(electrum_words);
                found += "Mnemonic:  ";
                found += electrum_words + "\n";
            }

            std::cout << SuccessMsg(found) << ENDL;

            if (!command_line::get_arg(vm, command_line::arg_file).empty()) {
                std::string filename = command_line::get_arg(vm, command_line::arg_file);
                std::ofstream ofs;
                ofs.open(filename + ".txt", std::ofstream::out | std::ofstream::app);
                ofs << found;
                ofs.close();
            }

            return true;
        }
    }

    return false;
}

void prefix_worker(const std::string& prefix, Currency& currency, const po::variables_map& vm, int threads, int threadId, volatile int& found, int count) {
    bool found_needed = false;
    while (!found_needed) {
        AccountKeys keys;
        Crypto::SecretKey second;
        Crypto::generate_keys(keys.address.spendPublicKey, keys.spendSecretKey);
        keccak((uint8_t*)&keys.spendSecretKey, sizeof(Crypto::SecretKey), (uint8_t*)&second, sizeof(Crypto::SecretKey));
        Crypto::generate_deterministic_keys(keys.address.viewPublicKey, keys.viewSecretKey, second);

        if (check_address_prefix(prefix, currency, vm, keys)) {
            found++;
        }

        if (found >= count) {
            found_needed = true;
        }
    }

    return;
}

bool find_prefix(const po::variables_map& vm, Currency& currency, System::Dispatcher& dispatcher) {
    std::string prefix = command_line::get_arg(vm, command_line::arg_prefix);
    int count = command_line::get_arg(vm, command_line::arg_count);
    int threads = std::max(1, command_line::get_arg(vm, command_line::arg_threads));
    int found = 0;

    if ((prefix.substr(0, 1) != "K") || prefix.length() > 95 || prefix.length() < 2) {
        std::cerr << WarningMsg("Invalid address prefix!") << std::endl;
        return false;
    }

    if (!is_valid_prefix(prefix, currency)) {
        std::cerr << WarningMsg("Invalid character in prefix!") << std::endl;
        return false;
    }

    std::cout << InformationMsg("Trying to find address for prefix \"") << prefix << InformationMsg("\"...") << std::endl << std::endl;

    std::vector<std::unique_ptr<System::RemoteContext<void>>> m_workers;

    for (int i = 0; i < threads; i++) {
        m_workers.emplace_back(
               new System::RemoteContext<void>(dispatcher, [&, i]() {
                   prefix_worker(prefix, currency, vm, threads, i, found, count);
               })
        );
    }

    m_workers.clear();
    return found != 0;
}

int main(int argc, char** argv) {
    LoggerManager logManager;
    LoggerRef logger(logManager, "vanitygen");

    CurrencyBuilder builder(logManager);
    Currency currency = builder.currency();

    System::Dispatcher dispatcher;

#ifdef _WIN32
    std::string consoletitle = std::string(CryptoNote::CRYPTONOTE_NAME) + " address generator v. " + std::string(PROJECT_VERSION_LONG);
    SetConsoleTitleA(consoletitle.c_str());
#endif

    std::string coinName(CryptoNote::CRYPTONOTE_NAME);
    std::cout << InformationMsg(coinName + " address generator v. " + std::string(PROJECT_VERSION)) << std::endl;

    try {
        po::options_description desc_cmd_only("Available command line options");

        command_line::add_arg(desc_cmd_only, command_line::arg_prefix);
        command_line::add_arg(desc_cmd_only, command_line::arg_count);
        command_line::add_arg(desc_cmd_only, command_line::arg_threads);
        command_line::add_arg(desc_cmd_only, command_line::arg_file);

        command_line::add_arg(desc_cmd_only, command_line::arg_help);

        bool r = command_line::handle_error_helper(desc_cmd_only, [&]()
        {
            po::variables_map vm;
            po::store(po::parse_command_line(argc, argv, desc_cmd_only), vm);

            if (!command_line::get_arg(vm, command_line::arg_prefix).empty()) {
                return find_prefix(vm, currency, dispatcher);
            }

            if (command_line::get_arg(vm, command_line::arg_help)) {
                std::cout << desc_cmd_only << std::endl;
                return true;
            }

            std::cout << desc_cmd_only << std::endl;

            return true;
        });

        if (!r)
            return 1;
    } catch (const std::exception& e) {
        logger(ERROR, BRIGHT_RED) << "Exception: " << e.what();
        return 1;
    }
    return 0;
}

max_stars_repo_name: parsecnode/parsec

max_issues_repo_name: parsecnode/parsec

max_forks_repo_name: parsecnode/parsec


text:
#ifndef mesh_reader
#define mesh_reader

#include <fstream>
#include <sstream>
#include <iostream>
#include <string>
#include <math.h>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>

using namespace boost::numeric::ublas;

namespace mesh {

    matrix<double> read_vertices() {
        /* index # is vertix id, contains x and y
        coordinate respectively of vertix, and
        a flag, 1 if boundary point 0 if not */
        std::ifstream infile("../triangle/circle.1.node");
        std::string line;
        double a, b, c, d, line_nb = 0;
        std::getline(infile, line);
        std::istringstream iss(line);
        iss >> a >> b >> c;
        int nb_nodes = a;
        matrix<double> vertices(nb_nodes, 3);

        while (std::getline(infile, line)) {
            std::istringstream iss(line);
            if (iss >> a >> b >> c >> d) {
                vertices(line_nb, 0) = b;
                vertices(line_nb, 1) = c;
                vertices(line_nb, 2) = d;
            }
            else {
                // std::cout << "ERROR: in .1.node file" << std::endl;
                break;
            }
            line_nb += 1;
        }

        return vertices;
    }

    matrix<double> read_triangles(matrix<double> &vertices) {
        /* index # is triangle id, contains
        the 3 vertix id's of the corner nodes  and
        the area of the triangle, calculated using
        the vertices matrix */
        std::ifstream infile("../triangle/circle.1.ele");
        std::string line;
        int a, b, c, d, line_nb = 0;
        std::getline(infile, line);
        std::istringstream iss(line);
        iss >> a >> b >> c;
        int nb_triangles = a;
        matrix<double> triangles(nb_triangles, 4);

        while (std::getline(infile, line)) {
            std::istringstream iss(line);
            if (iss >> a >> b >> c >> d) {
                triangles(line_nb, 0) = b-1;
                triangles(line_nb, 1) = c-1;
                triangles(line_nb, 2) = d-1;
                triangles(line_nb, 3) = 0.5*fabs(vertices(b-1, 0)*(vertices(c-1, 1) - vertices(d-1, 1)) +
                    vertices(c-1, 0)*(vertices(d-1, 1) - vertices(b-1, 1)) +
                    vertices(d-1, 0)*(vertices(b-1, 1) - vertices(c-1, 1)));
            }
            else {
                // std::cout << "ERROR: in .1.ele file" << std::endl;
                break;
            }
            line_nb += 1;
        }

        return triangles;
    }

    matrix<int> read_boundaries(matrix<double> &vertices) {
        /* index # is triangle id, contains
        the 3 vertix id's of the corner nodes  and
        the area of the triangle, calculated using
        the vertices matrix */
        std::ifstream infile("../triangle/circle.1.poly");
        std::string line;
        int a, b, c, d, count = 0;
        std::getline(infile, line);
        std::getline(infile, line);
        std::istringstream iss(line);
        iss >> a >> b;
        int nb_boundaries = a;
        matrix<int> boundaries(nb_boundaries, 2);

        while (std::getline(infile, line)) {
            std::istringstream iss(line);
            if (iss >> a >> b >> c >> d) {
                if (vertices(b-1, 0) != 0 || vertices(c-1, 0) != 0) {
                  boundaries(count, 0) = b-1;
                  boundaries(count, 1) = c-1;
                  count += 1;
                }
            }
            else {
                // std::cout << "ERROR: in .1.poly file" << std::endl;
                break;
            }
        }

        matrix<int> boundaries_red(count, 2);
        boundaries_red = project(boundaries, range(0, count), range(0, 2));
        return boundaries_red;
    }

}

#endif

max_stars_repo_name: PieterAppeltans/ProjectWIT

max_issues_repo_name: PieterAppeltans/ProjectWIT

max_forks_repo_name: PieterAppeltans/ProjectWIT


text:
/*
 *  Copyright (c) 2015 David Yuste Romero
 *
 *  THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
 *  OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
 *
 *  Permission is hereby granted to use or copy this program
 *  for any purpose,  provided the above notices are retained on all copies.
 *  Permission to modify the code and to distribute modified code is granted,
 *  provided the above notices are retained, and a notice that the code was
 *  modified is included with the above copyright notice.
 */
#include "Connection.h"
#include <vector>
#include <boost/bind.hpp>
#include "RequestHandler.h"
#include "Log.h"

namespace yucode {
namespace server {

Connection::Connection(boost::asio::io_service& io_service,
		RequestHandler& handler)
	: strand_(io_service),
		socket_(io_service),
		RequestHandler_(handler)
{
}

boost::asio::ip::tcp::socket& Connection::socket()
{
	return socket_;
}

void Connection::start()
{
	static int req_sec_number = 0;
	Request_.seq_number = ++req_sec_number;
	Request_.remote_endpoint = socket_.remote_endpoint().address().to_string();

	socket_.async_read_some(boost::asio::buffer(buffer_),
			strand_.wrap(
				boost::bind(&Connection::handle_read, shared_from_this(),
					boost::asio::placeholders::error,
					boost::asio::placeholders::bytes_transferred)));
}

void Connection::handle_read(const boost::system::error_code& e,
		std::size_t bytes_transferred)
{
	if (!e)
	{
		boost::tribool result;
		boost::tie(result, boost::tuples::ignore) = RequestParser_.parse(
				Request_, buffer_.data(), buffer_.data() + bytes_transferred);

		if (result)
		{
			RequestHandler_.handleRequest(Request_, Reply_);
			boost::asio::async_write(socket_, Reply_.to_buffers(),
					strand_.wrap(
						boost::bind(&Connection::handle_write, shared_from_this(),
							boost::asio::placeholders::error)));
		}
		else if (!result)
		{
			Reply_ = Reply::stock_Reply(Reply::bad_Request);
			boost::asio::async_write(socket_, Reply_.to_buffers(),
					strand_.wrap(
						boost::bind(&Connection::handle_write, shared_from_this(),
							boost::asio::placeholders::error)));
		}
		else
		{
			boost::asio::ip::tcp::socket::non_blocking_io non_blocking_io(true);
			socket_.io_control(non_blocking_io);
			socket_.async_read_some(boost::asio::buffer(buffer_),
					strand_.wrap(
						boost::bind(&Connection::handle_read, shared_from_this(),
							boost::asio::placeholders::error,
							boost::asio::placeholders::bytes_transferred)));
		}
	}

	// If an error occurs then no new asynchronous operations are started. This
	// means that all shared_ptr references to the Connection object will
	// disappear and the object will be destroyed automatically after this
	// handler returns. The Connection class's destructor closes the socket.
}

void Connection::handle_write(const boost::system::error_code& e)
{
	if (!e)
	{
		// Initiate graceful Connection closure.
		boost::system::error_code ignored_ec;
		socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
	}

	// No new asynchronous operations are started. This means that all shared_ptr
	// references to the Connection object will disappear and the object will be
	// destroyed automatically after this handler returns. The Connection class's
	// destructor closes the socket.
}

} // namespace server
} // namespace yucode

max_stars_repo_name: dyuste/greedy-cats-lake-server

max_issues_repo_name: dyuste/greedy-cats-lake-server

max_forks_repo_name: dyuste/greedy-cats-lake-server


text:
//
// Copyright Copyright 2009-2022, AMT – The Association For Manufacturing Technology (“AMT”)
// All rights reserved.
//
//    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 <boost/beast/core/error.hpp>

#include <memory>

#include "entity/entity.hpp"
#include "url_parser.hpp"

namespace mtconnect::source::adapter {
  struct Handler;
}
namespace mtconnect::pipeline {
  struct ResponseDocument;
}

namespace mtconnect::source::adapter::agent_adapter {
  struct AgentHandler;
  class Session : public std::enable_shared_from_this<Session>
  {
  public:
    using Next = std::function<bool()>;
    using Failure = std::function<void(std::error_code &ec)>;
    using UpdateAssets = std::function<void()>;

    struct Request
    {
      Request(const std::optional<std::string> &device, const std::string &suffix,
              const UrlQuery &query, bool stream, Next next)
        : m_sourceDevice(device), m_suffix(suffix), m_query(query), m_stream(stream), m_next(next)
      {}

      Request(const Request &request) = default;

      std::optional<std::string> m_sourceDevice;
      std::string m_suffix;
      UrlQuery m_query;
      bool m_stream;
      Next m_next;

      auto getTarget(const Url &url) { return url.getTarget(m_sourceDevice, m_suffix, m_query); }
    };

    virtual ~Session() {}
    virtual bool isOpen() const = 0;
    virtual void stop() = 0;
    virtual void failed(std::error_code ec, const char *what) = 0;

    virtual bool makeRequest(const Request &request) = 0;

    Handler *m_handler = nullptr;
    std::string m_identity;
    Failure m_failed;
    UpdateAssets m_updateAssets;
    bool m_closeConnectionAfterResponse = false;
    std::chrono::milliseconds m_timeout = std::chrono::milliseconds(30000);
  };

}  // namespace mtconnect::source::adapter::agent_adapter

max_stars_repo_name: bburns/cppagent

max_issues_repo_name: bburns/cppagent

max_forks_repo_name: bburns/cppagent