text:
//  (C) Copyright John Maddock 2006.
//  (C) Copyright Jeremy William Murphy 2015.

//  Use, modification and distribution are subject to 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_MATH_TOOLS_POLYNOMIAL_HPP
#define BOOST_MATH_TOOLS_POLYNOMIAL_HPP

#ifdef _MSC_VER
#pragma once
#endif

#include <boost/assert.hpp>
#include <boost/config.hpp>
#ifdef BOOST_NO_CXX11_LAMBDAS
#include <boost/lambda/lambda.hpp>
#endif
#include <boost/math/tools/rational.hpp>
#include <boost/math/tools/real_cast.hpp>
#include <boost/math/policies/error_handling.hpp>
#include <boost/math/special_functions/binomial.hpp>
#include <boost/core/enable_if.hpp>

#include <vector>
#include <ostream>
#include <algorithm>
#ifndef BOOST_NO_CXX11_HDR_INITIALIZER_LIST
#include <initializer_list>
#endif

namespace boost{ namespace math{ namespace tools{

template <class T>
T chebyshev_coefficient(unsigned n, unsigned m)
{
   BOOST_MATH_STD_USING
   if(m > n)
      return 0;
   if((n & 1) != (m & 1))
      return 0;
   if(n == 0)
      return 1;
   T result = T(n) / 2;
   unsigned r = n - m;
   r /= 2;

   BOOST_ASSERT(n - 2 * r == m);

   if(r & 1)
      result = -result;
   result /= n - r;
   result *= boost::math::binomial_coefficient<T>(n - r, r);
   result *= ldexp(1.0f, m);
   return result;
}

template <class Seq>
Seq polynomial_to_chebyshev(const Seq& s)
{
   // Converts a Polynomial into Chebyshev form:
   typedef typename Seq::value_type value_type;
   typedef typename Seq::difference_type difference_type;
   Seq result(s);
   difference_type order = s.size() - 1;
   difference_type even_order = order & 1 ? order - 1 : order;
   difference_type odd_order = order & 1 ? order : order - 1;

   for(difference_type i = even_order; i >= 0; i -= 2)
   {
      value_type val = s[i];
      for(difference_type k = even_order; k > i; k -= 2)
      {
         val -= result[k] * chebyshev_coefficient<value_type>(static_cast<unsigned>(k), static_cast<unsigned>(i));
      }
      val /= chebyshev_coefficient<value_type>(static_cast<unsigned>(i), static_cast<unsigned>(i));
      result[i] = val;
   }
   result[0] *= 2;

   for(difference_type i = odd_order; i >= 0; i -= 2)
   {
      value_type val = s[i];
      for(difference_type k = odd_order; k > i; k -= 2)
      {
         val -= result[k] * chebyshev_coefficient<value_type>(static_cast<unsigned>(k), static_cast<unsigned>(i));
      }
      val /= chebyshev_coefficient<value_type>(static_cast<unsigned>(i), static_cast<unsigned>(i));
      result[i] = val;
   }
   return result;
}

template <class Seq, class T>
T evaluate_chebyshev(const Seq& a, const T& x)
{
   // Clenshaw's formula:
   typedef typename Seq::difference_type difference_type;
   T yk2 = 0;
   T yk1 = 0;
   T yk = 0;
   for(difference_type i = a.size() - 1; i >= 1; --i)
   {
      yk2 = yk1;
      yk1 = yk;
      yk = 2 * x * yk1 - yk2 + a[i];
   }
   return a[0] / 2 + yk * x - yk1;
}

template <typename T>
class polynomial;

namespace detail {

/**
* Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998
* Chapter 4.6.1, Algorithm D: Division of polynomials over a field.
*
* @tparam  T   Coefficient type, must be not be an integer.
*
* Template-parameter T actually must be a field but we don't currently have that
* subtlety of distinction.
*/
template <typename T, typename N>
BOOST_DEDUCED_TYPENAME disable_if_c<std::numeric_limits<T>::is_integer, void >::type
division_impl(polynomial<T> &q, polynomial<T> &u, const polynomial<T>& v, N n, N k)
{
    q[k] = u[n + k] / v[n];
    for (N j = n + k; j > k;)
    {
        j--;
        u[j] -= q[k] * v[j - k];
    }
}

template <class T, class N>
T integer_power(T t, N n)
{
   switch(n)
   {
   case 0:
      return static_cast<T>(1u);
   case 1:
      return t;
   case 2:
      return t * t;
   case 3:
      return t * t * t;
   }
   T result = integer_power(t, n / 2);
   result *= result;
   if(n & 1)
      result *= t;
   return result;
}

/**
* Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998
* Chapter 4.6.1, Algorithm R: Pseudo-division of polynomials.
*
* @tparam  T   Coefficient type, must be an integer.
*
* Template-parameter T actually must be a unique factorization domain but we
* don't currently have that subtlety of distinction.
*/
template <typename T, typename N>
BOOST_DEDUCED_TYPENAME enable_if_c<std::numeric_limits<T>::is_integer, void >::type
division_impl(polynomial<T> &q, polynomial<T> &u, const polynomial<T>& v, N n, N k)
{
    q[k] = u[n + k] * integer_power(v[n], k);
    for (N j = n + k; j > 0;)
    {
        j--;
        u[j] = v[n] * u[j] - (j < k ? T(0) : u[n + k] * v[j - k]);
    }
}

/**
 * Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998
 * Chapter 4.6.1, Algorithm D and R: Main loop.
 *
 * @param   u   Dividend.
 * @param   v   Divisor.
 */
template <typename T>
std::pair< polynomial<T>, polynomial<T> >
division(polynomial<T> u, const polynomial<T>& v)
{
    BOOST_ASSERT(v.size() <= u.size());
    BOOST_ASSERT(v);
    BOOST_ASSERT(u);

    typedef typename polynomial<T>::size_type N;

    N const m = u.size() - 1, n = v.size() - 1;
    N k = m - n;
    polynomial<T> q;
    q.data().resize(m - n + 1);

    do
    {
        division_impl(q, u, v, n, k);
    }
    while (k-- != 0);
    u.data().resize(n);
    u.normalize(); // Occasionally, the remainder is zeroes.
    return std::make_pair(q, u);
}

//
// These structures are the same as the void specializations of the functors of the same name
// in the std lib from C++14 onwards:
//
struct negate
{
   template <class T>
   T operator()(T const &x) const
   {
      return -x;
   }
};

struct plus
{
   template <class T, class U>
   T operator()(T const &x, U const& y) const
   {
      return x + y;
   }
};

struct minus
{
   template <class T, class U>
   T operator()(T const &x, U const& y) const
   {
      return x - y;
   }
};

} // namespace detail

/**
 * Returns the zero element for multiplication of polynomials.
 */
template <class T>
polynomial<T> zero_element(std::multiplies< polynomial<T> >)
{
    return polynomial<T>();
}

template <class T>
polynomial<T> identity_element(std::multiplies< polynomial<T> >)
{
    return polynomial<T>(T(1));
}

/* Calculates a / b and a % b, returning the pair (quotient, remainder) together
 * because the same amount of computation yields both.
 * This function is not defined for division by zero: user beware.
 */
template <typename T>
std::pair< polynomial<T>, polynomial<T> >
quotient_remainder(const polynomial<T>& dividend, const polynomial<T>& divisor)
{
    BOOST_ASSERT(divisor);
    if (dividend.size() < divisor.size())
        return std::make_pair(polynomial<T>(), dividend);
    return detail::division(dividend, divisor);
}

template <class T>
class polynomial
{
public:
   // typedefs:
   typedef typename std::vector<T>::value_type value_type;
   typedef typename std::vector<T>::size_type size_type;

   // construct:
   polynomial(){}

   template <class U>
   polynomial(const U* data, unsigned order)
      : m_data(data, data + order + 1)
   {
       normalize();
   }

   template <class I>
   polynomial(I first, I last)
   : m_data(first, last)
   {
       normalize();
   }

   template <class U>
   explicit polynomial(const U& point)
   {
       if (point != U(0))
          m_data.push_back(point);
   }

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   // move:
   polynomial(polynomial&& p) BOOST_NOEXCEPT
      : m_data(std::move(p.m_data)) { }
#endif

   // copy:
   polynomial(const polynomial& p)
      : m_data(p.m_data) { }

   template <class U>
   polynomial(const polynomial<U>& p)
   {
      for(unsigned i = 0; i < p.size(); ++i)
      {
         m_data.push_back(boost::math::tools::real_cast<T>(p[i]));
      }
   }

#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST) && !BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)
    polynomial(std::initializer_list<T> l) : polynomial(std::begin(l), std::end(l))
    {
    }

    polynomial&
    operator=(std::initializer_list<T> l)
    {
        m_data.assign(std::begin(l), std::end(l));
        normalize();
        return *this;
    }
#endif

   // access:
   size_type size() const { return m_data.size(); }
   size_type degree() const
   {
       if (size() == 0)
           throw std::logic_error("degree() is undefined for the zero polynomial.");
       return m_data.size() - 1;
   }
   value_type& operator[](size_type i)
   {
      return m_data[i];
   }
   const value_type& operator[](size_type i) const
   {
      return m_data[i];
   }
   T evaluate(T z) const
   {
      return m_data.size() > 0 ? boost::math::tools::evaluate_polynomial(&m_data[0], z, m_data.size()) : 0;
   }
   std::vector<T> chebyshev() const
   {
      return polynomial_to_chebyshev(m_data);
   }

   std::vector<T> const& data() const
   {
       return m_data;
   }

   std::vector<T> & data()
   {
       return m_data;
   }

   // operators:
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
   polynomial& operator =(polynomial&& p) BOOST_NOEXCEPT
   {
       m_data = std::move(p.m_data);
       return *this;
   }
#endif
   polynomial& operator =(const polynomial& p)
   {
       m_data = p.m_data;
       return *this;
   }

   template <class U>
   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator +=(const U& value)
   {
       addition(value);
       normalize();
       return *this;
   }

   template <class U>
   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator -=(const U& value)
   {
       subtraction(value);
       normalize();
       return *this;
   }

   template <class U>
   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator *=(const U& value)
   {
      multiplication(value);
      normalize();
      return *this;
   }

   template <class U>
   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator /=(const U& value)
   {
       division(value);
       normalize();
       return *this;
   }

   template <class U>
   typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial&>::type operator %=(const U& /*value*/)
   {
       // We can always divide by a scalar, so there is no remainder:
       this->set_zero();
       return *this;
   }

   template <class U>
   polynomial& operator +=(const polynomial<U>& value)
   {
      addition(value);
      normalize();
      return *this;
   }

   template <class U>
   polynomial& operator -=(const polynomial<U>& value)
   {
       subtraction(value);
       normalize();
       return *this;
   }

   template <typename U, typename V>
   void multiply(const polynomial<U>& a, const polynomial<V>& b) {
       if (!a || !b)
       {
           this->set_zero();
           return;
       }
       std::vector<T> prod(a.size() + b.size() - 1, T(0));
       for (unsigned i = 0; i < a.size(); ++i)
           for (unsigned j = 0; j < b.size(); ++j)
               prod[i+j] += a.m_data[i] * b.m_data[j];
       m_data.swap(prod);
   }

   template <class U>
   polynomial& operator *=(const polynomial<U>& value)
   {
      this->multiply(*this, value);
      return *this;
   }

   template <typename U>
   polynomial& operator /=(const polynomial<U>& value)
   {
       *this = quotient_remainder(*this, value).first;
       return *this;
   }

   template <typename U>
   polynomial& operator %=(const polynomial<U>& value)
   {
       *this = quotient_remainder(*this, value).second;
       return *this;
   }

   template <typename U>
   polynomial& operator >>=(U const &n)
   {
       BOOST_ASSERT(n <= m_data.size());
       m_data.erase(m_data.begin(), m_data.begin() + n);
       return *this;
   }

   template <typename U>
   polynomial& operator <<=(U const &n)
   {
       m_data.insert(m_data.begin(), n, static_cast<T>(0));
       normalize();
       return *this;
   }

   // Convenient and efficient query for zero.
   bool is_zero() const
   {
       return m_data.empty();
   }

   // Conversion to bool.
#ifdef BOOST_NO_CXX11_EXPLICIT_CONVERSION_OPERATORS
   typedef bool (polynomial::*unmentionable_type)() const;

   BOOST_FORCEINLINE operator unmentionable_type() const
   {
       return is_zero() ? false : &polynomial::is_zero;
   }
#else
   BOOST_FORCEINLINE explicit operator bool() const
   {
       return !m_data.empty();
   }
#endif

   // Fast way to set a polynomial to zero.
   void set_zero()
   {
       m_data.clear();
   }

    /** Remove zero coefficients 'from the top', that is for which there are no
    *        non-zero coefficients of higher degree. */
   void normalize()
   {
#ifndef BOOST_NO_CXX11_LAMBDAS
      m_data.erase(std::find_if(m_data.rbegin(), m_data.rend(), [](const T& x)->bool { return x != 0; }).base(), m_data.end());
#else
       using namespace boost::lambda;
       m_data.erase(std::find_if(m_data.rbegin(), m_data.rend(), _1 != T(0)).base(), m_data.end());
#endif
   }

private:
    template <class U, class R>
    polynomial& addition(const U& value, R op)
    {
        if(m_data.size() == 0)
            m_data.resize(1, 0);
        m_data[0] = op(m_data[0], value);
        return *this;
    }

    template <class U>
    polynomial& addition(const U& value)
    {
        return addition(value, detail::plus());
    }

    template <class U>
    polynomial& subtraction(const U& value)
    {
        return addition(value, detail::minus());
    }

    template <class U, class R>
    polynomial& addition(const polynomial<U>& value, R op)
    {
        if (m_data.size() < value.size())
            m_data.resize(value.size(), 0);
        for(size_type i = 0; i < value.size(); ++i)
            m_data[i] = op(m_data[i], value[i]);
        return *this;
    }

    template <class U>
    polynomial& addition(const polynomial<U>& value)
    {
        return addition(value, detail::plus());
    }

    template <class U>
    polynomial& subtraction(const polynomial<U>& value)
    {
        return addition(value, detail::minus());
    }

    template <class U>
    polynomial& multiplication(const U& value)
    {
#ifndef BOOST_NO_CXX11_LAMBDAS
       std::transform(m_data.begin(), m_data.end(), m_data.begin(), [&](const T& x)->T { return x * value; });
#else
        using namespace boost::lambda;
        std::transform(m_data.begin(), m_data.end(), m_data.begin(), ret<T>(_1 * value));
#endif
        return *this;
    }

    template <class U>
    polynomial& division(const U& value)
    {
#ifndef BOOST_NO_CXX11_LAMBDAS
       std::transform(m_data.begin(), m_data.end(), m_data.begin(), [&](const T& x)->T { return x / value; });
#else
        using namespace boost::lambda;
        std::transform(m_data.begin(), m_data.end(), m_data.begin(), ret<T>(_1 / value));
#endif
        return *this;
    }

    std::vector<T> m_data;
};

template <class T>
inline polynomial<T> operator + (const polynomial<T>& a, const polynomial<T>& b)
{
   polynomial<T> result(a);
   result += b;
   return result;
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class T>
inline polynomial<T> operator + (polynomial<T>&& a, const polynomial<T>& b)
{
   a += b;
   return a;
}
template <class T>
inline polynomial<T> operator + (const polynomial<T>& a, polynomial<T>&& b)
{
   b += a;
   return b;
}
template <class T>
inline polynomial<T> operator + (polynomial<T>&& a, polynomial<T>&& b)
{
   a += b;
   return a;
}
#endif

template <class T>
inline polynomial<T> operator - (const polynomial<T>& a, const polynomial<T>& b)
{
   polynomial<T> result(a);
   result -= b;
   return result;
}
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
template <class T>
inline polynomial<T> operator - (polynomial<T>&& a, const polynomial<T>& b)
{
   a -= b;
   return a;
}
template <class T>
inline polynomial<T> operator - (const polynomial<T>& a, polynomial<T>&& b)
{
   b -= a;
   return -b;
}
template <class T>
inline polynomial<T> operator - (polynomial<T>&& a, polynomial<T>&& b)
{
   a -= b;
   return a;
}
#endif

template <class T>
inline polynomial<T> operator * (const polynomial<T>& a, const polynomial<T>& b)
{
   polynomial<T> result;
   result.multiply(a, b);
   return result;
}

template <class T>
inline polynomial<T> operator / (const polynomial<T>& a, const polynomial<T>& b)
{
   return quotient_remainder(a, b).first;
}

template <class T>
inline polynomial<T> operator % (const polynomial<T>& a, const polynomial<T>& b)
{
   return quotient_remainder(a, b).second;
}

template <class T, class U>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator + (polynomial<T> a, const U& b)
{
   a += b;
   return a;
}

template <class T, class U>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator - (polynomial<T> a, const U& b)
{
   a -= b;
   return a;
}

template <class T, class U>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator * (polynomial<T> a, const U& b)
{
   a *= b;
   return a;
}

template <class T, class U>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator / (polynomial<T> a, const U& b)
{
   a /= b;
   return a;
}

template <class T, class U>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator % (const polynomial<T>&, const U&)
{
   // Since we can always divide by a scalar, result is always an empty polynomial:
   return polynomial<T>();
}

template <class U, class T>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator + (const U& a, polynomial<T> b)
{
   b += a;
   return b;
}

template <class U, class T>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator - (const U& a, polynomial<T> b)
{
   b -= a;
   return -b;
}

template <class U, class T>
inline typename boost::enable_if_c<boost::is_constructible<T, U>::value, polynomial<T> >::type operator * (const U& a, polynomial<T> b)
{
   b *= a;
   return b;
}

template <class T>
bool operator == (const polynomial<T> &a, const polynomial<T> &b)
{
    return a.data() == b.data();
}

template <class T>
bool operator != (const polynomial<T> &a, const polynomial<T> &b)
{
    return a.data() != b.data();
}

template <typename T, typename U>
polynomial<T> operator >> (polynomial<T> a, const U& b)
{
    a >>= b;
    return a;
}

template <typename T, typename U>
polynomial<T> operator << (polynomial<T> a, const U& b)
{
    a <<= b;
    return a;
}

// Unary minus (negate).
template <class T>
polynomial<T> operator - (polynomial<T> a)
{
    std::transform(a.data().begin(), a.data().end(), a.data().begin(), detail::negate());
    return a;
}

template <class T>
bool odd(polynomial<T> const &a)
{
    return a.size() > 0 && a[0] != static_cast<T>(0);
}

template <class T>
bool even(polynomial<T> const &a)
{
    return !odd(a);
}

template <class T>
polynomial<T> pow(polynomial<T> base, int exp)
{
    if (exp < 0)
        return policies::raise_domain_error(
                "boost::math::tools::pow<%1%>",
                "Negative powers are not supported for polynomials.",
                base, policies::policy<>());
        // if the policy is ignore_error or errno_on_error, raise_domain_error
        // will return std::numeric_limits<polynomial<T>>::quiet_NaN(), which
        // defaults to polynomial<T>(), which is the zero polynomial
    polynomial<T> result(T(1));
    if (exp & 1)
        result = base;
    /* "Exponentiation by squaring" */
    while (exp >>= 1)
    {
        base *= base;
        if (exp & 1)
            result *= base;
    }
    return result;
}

template <class charT, class traits, class T>
inline std::basic_ostream<charT, traits>& operator << (std::basic_ostream<charT, traits>& os, const polynomial<T>& poly)
{
   os << "{ ";
   for(unsigned i = 0; i < poly.size(); ++i)
   {
      if(i) os << ", ";
      os << poly[i];
   }
   os << " }";
   return os;
}

} // namespace tools
} // namespace math
} // namespace boost

//
// Polynomial specific overload of gcd algorithm:
//
#include <boost/math/tools/polynomial_gcd.hpp>

#endif // BOOST_MATH_TOOLS_POLYNOMIAL_HPP

max_stars_repo_name: alexhenrie/poedit

max_issues_repo_name: alexhenrie/poedit

max_forks_repo_name: alexhenrie/poedit


text:
#include <boost/hof.hpp>
#include <functional>

template<typename T>
T sum(T a, T b) {
    return a + b;
}

int main() {
    std::function<int(int)> addFiveInt = boost::hof::partial(
            BOOST_HOF_LIFT(sum)
        )(5);

    addFiveInt(10);
    // returns 15
}

ext: cc

max_stars_repo_name: JohnMurray/cpp-vs

max_issues_repo_name: JohnMurray/cpp-vs

max_forks_repo_name: JohnMurray/cpp-vs


text:
#ifndef BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED
#define BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED

// Copyright Aleksey Gurtovoy 2003-2004
// Copyright Eric Friedman 2003
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.

// $Source: /cvsroot/boost/boost/boost/mpl/iter_fold_if.hpp,v $
// $Date: 2004/09/02 15:40:41 $
// $Revision: 1.7 $

#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/logical.hpp>
#include <boost/mpl/always.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/pair.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/aux_/iter_fold_if_impl.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
#include <boost/mpl/aux_/lambda_support.hpp>
#include <boost/mpl/aux_/config/forwarding.hpp>
#include <boost/mpl/aux_/config/workaround.hpp>

#include <boost/type_traits/is_same.hpp>

namespace boost { namespace mpl {

namespace aux {

template< typename Predicate, typename LastIterator >
struct iter_fold_if_pred
{
    template< typename State, typename Iterator > struct apply
#if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING)
        : and_<
              not_< is_same<Iterator,LastIterator> >
            , apply1<Predicate,Iterator>
            >
    {
#else
    {
        typedef and_<
              not_< is_same<Iterator,LastIterator> >
            , apply1<Predicate,Iterator>
            > type;
#endif
    };
};

} // namespace aux

template<
      typename BOOST_MPL_AUX_NA_PARAM(Sequence)
    , typename BOOST_MPL_AUX_NA_PARAM(State)
    , typename BOOST_MPL_AUX_NA_PARAM(ForwardOp)
    , typename BOOST_MPL_AUX_NA_PARAM(ForwardPredicate)
    , typename BOOST_MPL_AUX_NA_PARAM(BackwardOp)
    , typename BOOST_MPL_AUX_NA_PARAM(BackwardPredicate)
    >
struct iter_fold_if
{

    typedef typename begin<Sequence>::type first_;
    typedef typename end<Sequence>::type last_;

    typedef typename eval_if<
          is_na<BackwardPredicate>
        , if_< is_na<BackwardOp>, always<false_>, always<true_> >
        , identity<BackwardPredicate>
        >::type backward_pred_;

// cwpro8 doesn't like 'cut-off' type here (use typedef instead)
#if !BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) && !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600))
    struct result_ :
#else
    typedef
#endif
        aux::iter_fold_if_impl<
          first_
        , State
        , ForwardOp
        , protect< aux::iter_fold_if_pred< ForwardPredicate,last_ > >
        , BackwardOp
        , backward_pred_
        >
#if !BOOST_WORKAROUND(__MWERKS__, BOOST_TESTED_AT(0x3003)) && !BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(600))
    { };
#else
    result_;
#endif

public:

    typedef pair<
          typename result_::state
        , typename result_::iterator
        > type;

    BOOST_MPL_AUX_LAMBDA_SUPPORT(
          6
        , iter_fold_if
        , (Sequence,State,ForwardOp,ForwardPredicate,BackwardOp,BackwardPredicate)
        )
};

BOOST_MPL_AUX_NA_SPEC(6, iter_fold_if)

}}

#endif // BOOST_MPL_ITER_FOLD_IF_HPP_INCLUDED

ext: hpp

max_stars_repo_name: dstrigl/mcotf

max_issues_repo_name: dstrigl/mcotf

max_forks_repo_name: dstrigl/mcotf


text:
#pragma once

#include <vector>
#include <cassert>

#include <iostream>
#include <iomanip>

#include <Eigen/Dense>

//! \file rkintegrator.hpp Solution for Problem 1, implementing RkIntegrator class

//! \brief Implements a Runge-Kutta explicit solver for a given Butcher tableau for autonomous ODEs
//! \tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd.
template <class State>
class RKIntegrator {
public:
    //! \brief Constructor for the RK method.
    //! Performs size checks and copies A and b into internal storage
    //! \param[in] A matrix containing coefficents of Butcher tableau, must be (strictly) lower triangular (no check)
    //! \param[in] b vector containing coefficients of lower part of Butcher tableau
    RKIntegrator(const Eigen::MatrixXd & A, const Eigen::VectorXd & b)
        : A(A), b(b), s(b.size()) {
        assert( A.cols() == A.rows() && "Matrix must be square.");
        assert( A.cols() == b.size() && "Incompatible matrix/vector size.");
    }

    //! \brief Perform the solution of the ODE
    //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a RK scheme given in the Butcher tableau provided in the
    //! constructor. Performs N equidistant steps upto time T with initial data y0
    //! \tparam Function type for function implementing the rhs function. Must have State operator()(State x)
    //! \param[in] f function handle for rhs in y' = f(y), e.g. implemented using lambda funciton
    //! \param[in] T final time T
    //! \param[in] y0 initial data y(0) = y0 for y' = f(y)
    //! \param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.
    //! \return vector containing all steps y^n (for each n) including initial and final value
    template <class Function>
    std::vector<State> solve(const Function &f, double T, const State & y0, unsigned int N) const {
        // Iniz step size
        double h = T / N;

        // Will contain all steps, reserve memory for efficiency
        std::vector<State> res;
        res.reserve(N+1);

        // Store initial data
        res.push_back(y0);

        // Initialize some memory to store temporary values
        State ytemp1 = y0;
        State ytemp2 = y0;
        // Pointers to swap previous value
        State * yold = &ytemp1;
        State * ynew = &ytemp2;

        // Loop over all fixed steps
        for(unsigned int k = 0; k < N; ++k) {
            // Compute, save and swap next step
            step(f, h, *yold, *ynew);
            res.push_back(*ynew);
            std::swap(yold, ynew);
        }

        return res;
    }

private:

    //! \brief Perform a single step of the RK method for the solution of the autonomous ODE
    //! Compute a single explicit RK step y^{n+1} = y_n + \sum ... starting from value y0 and storing next value in y1
    //! \tparam Function type for function implementing the rhs. Must have State operator()(State x)
    //! \param[in] f function handle for ths f, s.t. y' = f(y)
    //! \param[in] h step size
    //! \param[in] y0 initial state
    //! \param[out] y1 next step y^{n+1} = y^n + ...
    template <class Function>
    void step(const Function &f, double h, const State & y0, State & y1) const {
        // create vector holding next value
        y1 = y0;

        // Reserve space for increments
        std::vector<State> k;
        k.reserve(s);

        // Loop over the size of RK
        for(unsigned int i = 0; i < s; ++i) {
            // Compute increments and save them to k
            State incr = y0;
            for(unsigned int j = 0; j < i; ++j) {
                incr += h*A(i,j)*k.at(j);
            }
            k.push_back( f( incr ) );
            y1 += h * b(i) * k.back();
        }
    }

    //! Matrix A in Butcher scheme
    const Eigen::MatrixXd A;
    //! Vector b in Butcher scheme
    const Eigen::VectorXd b;
    //! Size of Butcher matrix and vector A and b
    unsigned int s;
};

max_stars_repo_path: Nummerical Methods for CSE/PS13/solutions_ps13/rkintegrator.hpp

max_stars_repo_name: valentinjacot/backupETHZ

max_issues_repo_name: valentinjacot/backupETHZ

max_forks_repo_name: valentinjacot/backupETHZ


text:
#define BOOST_TEST_IGNORE_NON_ZERO_CHILD_CODE
#define BOOST_TEST_MODULE libeverestTests
#include <boost/test/unit_test.hpp>

ext: cpp

max_stars_repo_name: Vestiacom/libeverest

max_issues_repo_name: Vestiacom/libeverest

max_forks_repo_name: Vestiacom/libeverest


text:
/*
 * Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
 *
 * Distributed under 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 <cetty/handler/timeout/WriteTimeoutHandler.h>

#include <boost/bind.hpp>
#include <boost/thread/thread_time.hpp>

#include <cetty/channel/Timeout.h>
#include <cetty/channel/Channel.h>
#include <cetty/channel/ChannelPipeline.h>
#include <cetty/channel/ChannelHandlerContext.h>

namespace cetty {
namespace handler {
namespace timeout {

const WriteTimeoutException WriteTimeoutHandler::EXCEPTION("WriteTimeout");

WriteTimeoutHandler::WriteTimeoutHandler(int timeoutSeconds)
    : timeoutMillis_(timeoutSeconds * 1000) {
    if (timeoutSeconds <= 0) {
        timeoutMillis_ = 0;
    }
}

WriteTimeoutHandler::WriteTimeoutHandler(const Duration& timeout)
    : timeoutMillis_(timeout.total_milliseconds()) {
    if (timeoutMillis_ <= 0) {
        timeoutMillis_ = 0;
    }
}

void WriteTimeoutHandler::flush(ChannelHandlerContext& ctx,
                                const ChannelFuturePtr& future) {
    if (timeoutMillis_ > 0) {
        // Schedule a timeout.
        ctx.eventLoop()->runAfter(timeoutMillis_, boost::bind(
                                      &WriteTimeoutHandler::handleWriteTimeout,
                                      this,
                                      boost::ref(ctx),
                                      boost::cref(future)));

        // Cancel the scheduled timeout if the flush future is complete.
        future->addListener(boost::bind(
                                &WriteTimeoutHandler::cancelTimeout,
                                this,
                                _1));
    }

    ctx.flush(future);
}

void WriteTimeoutHandler::handleWriteTimeout(ChannelHandlerContext& ctx,
        const ChannelFuturePtr& future) {

    // Mark the future as failure
    if (future->setFailure(EXCEPTION)) {
        // If succeeded to mark as failure, notify the pipeline, too.
        try {
            onWriteTimedOut(ctx);
        }
        catch (const std::exception& t) {
            // TODO
            // here may have problems:
            // if the timer is in the different thread (not the default AsioDeadlineTimer)
            // with this pipeline, and user override the
            // {@link writeTimedOut(ChannelHandlerContext&) writeTimedOut},
            // and also unfortunately, the writeTimedOut throw an exception,
            // then the pipeline will concurrently work in different threads.
            //
            // So at present, make sure handleWriteTimeout will be invoked in the
            // same thread with the channel's pipeline.
            ctx.fireExceptionCaught(ChannelException(t.what()));
        }
        catch (...) {
            ctx.fireExceptionCaught(ChannelException("Unknown exception"));
        }
    }
}

void WriteTimeoutHandler::cancelTimeout(ChannelFuture& future) {
    if (timeout_) {
        timeout_->cancel();
    }
}

void WriteTimeoutHandler::onWriteTimedOut(ChannelHandlerContext& ctx) {
    if (!closed_) {
        ctx.fireExceptionCaught(EXCEPTION);
        ctx.close();
        closed_ = true;
    }
}

}
}
}


text:
#include "alconnclient.hpp"
#include "contact.hpp"
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

// TODO: move to config file
std::string SERVER_WS_LINK = "wss://signal.altexo.com";

AlConnClient::AlConnClient(AlWsCb *alWsCb) : m_debug(true) {
  std::cout << "constructor" << std::endl;
  m_alWsCb = alWsCb;
  m_token = "";
}

AlConnClient::~AlConnClient() { std::cout << "destructor" << std::endl; }

void AlConnClient::initWsConnection() {
  m_wssLink = SERVER_WS_LINK + "/al_chat";

  if (m_debug) {
    std::cout << m_wssLink << std::endl;
  }

  m_wsCl.init(m_wssLink, m_alWsCb);
  m_wsCl.run();
}

max_stars_repo_name: xorsnn/altexo

max_issues_repo_name: xorsnn/altexo

max_forks_repo_name: xorsnn/altexo


text:
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.

// All rights reserved.

// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/

#ifndef STAPL_VIEWS_TYPE_TRAITS_IS_DOMAIN_SPARSE_HPP
#define STAPL_VIEWS_TYPE_TRAITS_IS_DOMAIN_SPARSE_HPP

#include <boost/mpl/bool.hpp>

namespace stapl {

//////////////////////////////////////////////////////////////////////
/// @brief Type checker to determine if a domain is a sparse domain.
//////////////////////////////////////////////////////////////////////
template <typename Dom>
struct is_domain_sparse
  : boost::mpl::false_
{ };

} // stapl namespace

#endif /* STAPL_VIEWS_TYPE_TRAITS_IS_DOMAIN_SPARSE_HPP */


text:
#include "util/dynamic_graph.hpp"
#include "util/typedefs.hpp"

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

#include <vector>

BOOST_AUTO_TEST_SUITE(dynamic_graph)

using namespace osrm;
using namespace osrm::util;

struct TestData
{
    EdgeID id;
};

typedef DynamicGraph<TestData> TestDynamicGraph;
typedef TestDynamicGraph::InputEdge TestInputEdge;

BOOST_AUTO_TEST_CASE(find_test)
{
    /*
     *  (0) -1-> (1)
     *  ^ ^
     *  2 5
     *  | |
     *  (3) -3-> (4)
     *      <-4-
     */
    std::vector<TestInputEdge> input_edges = {TestInputEdge{0, 1, TestData{1}},
                                              TestInputEdge{3, 0, TestData{2}},
                                              TestInputEdge{3, 0, TestData{5}},
                                              TestInputEdge{3, 4, TestData{3}},
                                              TestInputEdge{4, 3, TestData{4}}};
    TestDynamicGraph simple_graph(5, input_edges);

    auto eit = simple_graph.FindEdge(0, 1);
    BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 1);

    eit = simple_graph.FindEdge(1, 0);
    BOOST_CHECK_EQUAL(eit, SPECIAL_EDGEID);

    eit = simple_graph.FindEdgeInEitherDirection(1, 0);
    BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 1);

    bool reverse = false;
    eit = simple_graph.FindEdgeIndicateIfReverse(1, 0, reverse);
    BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 1);
    BOOST_CHECK(reverse);

    eit = simple_graph.FindEdge(3, 1);
    BOOST_CHECK_EQUAL(eit, SPECIAL_EDGEID);
    eit = simple_graph.FindEdge(0, 4);
    BOOST_CHECK_EQUAL(eit, SPECIAL_EDGEID);

    eit = simple_graph.FindEdge(3, 4);
    BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 3);
    eit = simple_graph.FindEdgeInEitherDirection(3, 4);
    BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 3);

    eit = simple_graph.FindEdge(3, 0);
    BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 2);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: jhermsmeier/osrm-backend

max_issues_repo_name: jhermsmeier/osrm-backend

max_forks_repo_name: jhermsmeier/osrm-backend


text:
// smooth: Lie Theory for Robotics
// https://github.com/pettni/smooth
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2021 Petter Nilsson
//
// 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.

#ifndef SMOOTH__DIFF_HPP_
#define SMOOTH__DIFF_HPP_

/**
 * @file
 * @brief Differentiation on Manifolds.
 */

#include <Eigen/Core>
#include <type_traits>

#include "internal/utils.hpp"
#include "manifold.hpp"
#include "wrt.hpp"

namespace smooth {

// differentiation module
namespace diff {
namespace detail {

/**
 * @brief Numerical first-order differentiation in tangent space.
 *
 * @param f function to differentiate
 * @param x reference tuple of function arguments
 * @return \p std::pair containing value and right derivative: \f$(f(x), \mathrm{d}^r f_x)\f$
 *
 * @note All arguments in x as well as the return type \f$f(x)\f$ must satisfy
 * the Manifold concept.
 */
template<std::size_t K = 1>
  requires(K >= 1 && K <= 2)
auto dr_numerical(auto && f, auto && x)
{
  using Wrt    = decltype(x);
  using Result = decltype(std::apply(f, x));
  using Scalar = ::smooth::Scalar<Result>;

  static constexpr auto NumArgs = std::tuple_size_v<std::decay_t<Wrt>>;

  static_assert(Manifold<Result>, "f(x) is not a Manifold");

  const Scalar eps = std::sqrt(Eigen::NumTraits<Scalar>::epsilon());

  // arguments are modified below, so we create a copy of those that come in as const
  auto x_nc = wrt_copy_if_const(std::forward<Wrt>(x));
  Result F  = std::apply(f, x_nc);

  // static sizes
  static constexpr Eigen::Index Nx = wrt_Dof<Wrt>();
  static constexpr Eigen::Index Ny = Dof<Result>;

  // dynamic sizes
  Eigen::Index nx = std::apply([](auto &&... args) { return (dof(args) + ...); }, x_nc);
  Eigen::Index ny = dof<Result>(F);

  // output variable
  Eigen::Matrix<Scalar, Ny, Nx> J(ny, nx);

  if constexpr (K == 1) {
    Eigen::Index I0 = 0;
    utils::static_for<NumArgs>([&](auto i) {
      auto & w = std::get<i>(x_nc);
      using W  = std::decay_t<decltype(w)>;

      static constexpr Eigen::Index Nx_j = Dof<W>;
      const int nx_j                     = dof<W>(w);

      for (auto j = 0; j != nx_j; ++j) {
        Scalar eps_j = eps;
        if constexpr (std::is_base_of_v<Eigen::MatrixBase<W>, W>) {
          // scale step size if we are in Rn
          eps_j *= abs(w[j]);
          if (eps_j == 0.) { eps_j = eps; }
        }
        w             = rplus<W>(w, (eps_j * Eigen::Vector<Scalar, Nx_j>::Unit(nx_j, j)).eval());
        J.col(I0 + j) = rminus<Result>(std::apply(f, x_nc), F) / eps_j;
        w             = rplus<W>(w, (-eps_j * Eigen::Vector<Scalar, Nx_j>::Unit(nx_j, j)).eval());
      }
      I0 += nx_j;
    });

    return std::make_pair(std::move(F), std::move(J));
  }

  if constexpr (K == 2) {
    static_assert(Ny == 1, "2nd derivative only implemented for scalar functions");

    const auto sqrteps = std::sqrt(eps);

    Eigen::Matrix<Scalar, Nx, Nx> H(nx, nx);

    Eigen::Index I0 = 0;
    utils::static_for<NumArgs>([&](auto i0) {
      auto & w0                           = std::get<i0>(x_nc);
      using W0                            = std::decay_t<decltype(w0)>;
      static constexpr Eigen::Index Nx_i0 = Dof<W0>;
      const int nx_i0                     = dof<W0>(w0);

      Eigen::Index I1 = 0;
      utils::static_for<NumArgs>([&](auto i1) {
        if (i1 > i0) { return; }

        auto & w1                           = std::get<i1>(x_nc);
        using W1                            = std::decay_t<decltype(w1)>;
        static constexpr Eigen::Index Nx_i1 = Dof<W1>;
        const int nx_i1                     = dof<W1>(w1);

        for (auto k0 = 0; k0 != nx_i0; ++k0) {
          Scalar eps0 = sqrteps;
          if constexpr (std::is_base_of_v<Eigen::MatrixBase<W0>, W0>) {
            eps0 *= abs(w0[k0]);
            if (eps0 == 0.) { eps0 = sqrteps; }
          }

          w0               = rplus<W0>(w0, eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));
          const Result F10 = std::apply(f, x_nc);
          w0               = rplus<W0>(w0, -eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));

          J(0, I0 + k0) = (F10 - F) / eps0;

          for (auto k1 = 0; k1 < (i0 == i1 ? k0 + 1 : nx_i1); ++k1) {
            Scalar eps1 = sqrteps;
            if constexpr (std::is_base_of_v<Eigen::MatrixBase<W1>, W1>) {
              eps1 *= abs(w1[k1]);
              if (eps1 == 0.) { eps1 = sqrteps; }
            }

            // do this in order to ensure we return to same point on spaces with non-zero brackets
            w1               = rplus<W1>(w1, eps1 * Eigen::Vector<Scalar, Nx_i1>::Unit(nx_i1, k1));
            const Result F01 = std::apply(f, x_nc);
            w0               = rplus<W0>(w0, eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));
            const Result F11 = std::apply(f, x_nc);
            w0               = rplus<W0>(w0, -eps0 * Eigen::Vector<Scalar, Nx_i0>::Unit(nx_i0, k0));
            w1               = rplus<W1>(w1, -eps1 * Eigen::Vector<Scalar, Nx_i1>::Unit(nx_i1, k1));

            // hessian is symmetric
            H(I0 + k0, I1 + k1) = H(I1 + k1, I0 + k0) = (F11 - F01 - F10 + F) / eps0 / eps1;
          }
        }
        I1 += nx_i1;
      });
      I0 += nx_i0;
    });

    return std::make_tuple(std::move(F), std::move(J), std::move(H));
  }
}

}  // namespace detail

/**
 * @brief Available differentiation methods
 */
enum class Type {
  Numerical,  ///< Numerical (forward) derivatives
  Autodiff,   ///< Uses the autodiff (https://autodiff.github.io) library; requires  \p
              ///< compat/autodiff.hpp
  Ceres,      ///< Uses the Ceres (http://ceres-solver.org) built-in autodiff; requires \p
              ///< compat/ceres.hpp
  Analytic,   ///< Hand-coded derivative, requires that function returns \p std::pair \f$(f(x),
              ///< \mathrm{d}^r f_x) \f$
  Default     ///< Automatically select type based on availability
};

static constexpr Type DefaultType =
#ifdef SMOOTH_DIFF_AUTODIFF
  Type::Autodiff;
#elif defined SMOOTH_DIFF_CERES
  Type::Ceres;
#else
  Type::Numerical;
#endif

/**
 * @brief Differentiation in tangent space
 *
 * @tparam K differentiation order (1 or 2)
 * @tparam D differentiation method to use
 *
 * @param f function to differentiate
 * @param x reference tuple of function arguments
 * @return {f(x), dr f(x)} for K = 1, {f(x), dr f(x), d2r f(x)} for K = 2
 *
 * @note Only scalar functions suppored for K = 2
 *
 * @note All arguments in x as well as the return type \f$f(x)\f$ must satisfy
 * the Manifold concept.
 */
template<std::size_t K, Type D>
auto dr(auto && f, auto && x)
{
  using F   = decltype(f);
  using Wrt = decltype(x);

  if constexpr (D == Type::Numerical) {
    return detail::dr_numerical<K>(std::forward<F>(f), std::forward<Wrt>(x));
  } else if constexpr (D == Type::Autodiff) {
#ifdef SMOOTH_DIFF_AUTODIFF
    return dr_autodiff<K>(std::forward<F>(f), std::forward<Wrt>(x));
#else
    static_assert(D != Type::Autodiff, "compat/autodiff.hpp header not included");
#endif
  } else if constexpr (D == Type::Ceres) {
    static_assert(K == 1, "Only K = 1 supported with Ceres");
#ifdef SMOOTH_DIFF_CERES
    return dr_ceres(std::forward<F>(f), std::forward<Wrt>(x));
#else
    static_assert(D != Type::Ceres, "compat/ceres.hpp header not included");
#endif
  } else if constexpr (D == Type::Analytic) {
    auto F  = std::apply(f, x);
    auto dF = std::apply(std::bind_front(std::mem_fn(&std::decay_t<decltype(f)>::jacobian), f), x);
    if constexpr (K == 1) {
      return std::make_tuple(std::move(F), std::move(dF));
    } else if constexpr (K == 2) {
      auto d2F =
        std::apply(std::bind_front(std::mem_fn(&std::decay_t<decltype(f)>::hessian), f), x);
      return std::make_tuple(F, dF, d2F);
    }
  } else if constexpr (D == Type::Default) {
    return dr<K, DefaultType>(std::forward<F>(f), std::forward<Wrt>(x));
  }
}

/**
 * @brief Differentiation in tangent space using default method
 *
 * @tparam K differentiation order
 *
 * @param f function to differentiate
 * @param x reference tuple of function arguments
 * @return \p std::pair containing value and right derivative: \f$(f(x), \mathrm{d}^r f_x)\f$
 *
 * @note All arguments in x as well as the return type \f$f(x)\f$ must satisfy
 * the Manifold concept.
 */
template<std::size_t K = 1>
auto dr(auto && f, auto && x)
{
  return dr<K, Type::Default>(std::forward<decltype(f)>(f), std::forward<decltype(x)>(x));
}

}  // namespace diff
}  // namespace smooth

#endif  // SMOOTH__DIFF_HPP_

max_stars_repo_name: pettni/smooth

max_issues_repo_name: pettni/lie

max_forks_repo_name: pettni/lie


text:
// Copyright (c) 2017 Pieter Wuille
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <blech32.h>
#include <random.h>
#include <util/strencodings.h>
#include <test/util/setup_common.h>
#include <test/util/str.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(blech32_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(blech32_testvectors_valid)
{
    static const std::string CASES[] = {
        "A133NZFWEYK7UT",
        "a133nzfweyk7ut",
        "an83characterlonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio195jhgldwsn5j",
        "abcdef1qpzry9x8gf2tvdw0s3jn54khce6mua7lgmcn7l7t7xve",
        "11qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3xldwlutcw2l",
        "split1checkupstagehandshakeupstreamerranterredcaperredegneyqml9esp",
        "?19dv34t3p4s35",
    };
    for (const std::string& str : CASES) {
        const auto dec = blech32::Decode(str);
        BOOST_CHECK(dec.encoding == blech32::Encoding::BLECH32);
        std::string recode = blech32::Encode(blech32::Encoding::BLECH32, dec.hrp, dec.data);
        BOOST_CHECK(!recode.empty());
        BOOST_CHECK(CaseInsensitiveEqual(str, recode));
    }
}

BOOST_AUTO_TEST_CASE(blech32m_testvectors_valid)
{
    static const std::string CASES[] = {
        "A1EYL4VXQ3HRPT",
        "a1eyl4vxq3hrpt",
        "an83characterlonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11yatn6l85muud",
        "abcdef1l7aum6echk45nj3s0wdvt2fg8x9yrzpqg8m5pqg67zq3",
        "11llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll09wxh8ajdvxv",
        "split1checkupstagehandshakeupstreamerranterredcaperred3alwpgz2yydp",
        "?1dcqxsrg55dv5"
    };
    for (const std::string& str : CASES) {
        const auto dec = blech32::Decode(str);
        BOOST_CHECK(dec.encoding == blech32::Encoding::BLECH32M);
        std::string recode = blech32::Encode(blech32::Encoding::BLECH32M, dec.hrp, dec.data);
        BOOST_CHECK(!recode.empty());
        BOOST_CHECK(CaseInsensitiveEqual(str, recode));
    }
}

BOOST_AUTO_TEST_CASE(blech32m_testvectors_invalid)
{
    static const std::string CASES[] = {
        " 1xj0phk",
        "\x7f""1g6xzxy",
        "\x80""1vctc34",
        "an84characterslonghumanreadablepartthatcontainsthetheexcludedcharactersbioandnumber11d6pts4",
        "qyrz8wqd2c9m",
        "1qyrz8wqd2c9m",
        "y1b0jsk6g",
        "lt1igcx5c0",
        "in1muywd",
        "mm1crxm3i",
        "au1s5cgom",
        "M1VUXWEZ",
        "16plkw9",
        "1p2gdwpf"
    };
    for (const std::string& str : CASES) {
        const auto dec = blech32::Decode(str);
        BOOST_CHECK(dec.encoding == blech32::Encoding::INVALID);
    }
}

BOOST_AUTO_TEST_CASE(blech32_testvectors_invalid)
{
    static const std::string CASES[] = {
        " 1nwldj5",
        "\x7f""1axkwrx",
        "\x80""1eym55h",
        "an84characterslonghumanreadablepartthatcontainsthenumber1andtheexcludedcharactersbio1569pvx",
        "pzry9x0s0muk",
        "1pzry9x0s0muk",
        "x1b4n0q5v",
        "li1dgmt3",
        "de1lg7wt\xff",
        "A1G7SGD8",
        "10a06t8",
        "1qzzfhee",
        "a12UEL5L",
        "A12uEL5L",
    };
    for (const std::string& str : CASES) {
        const auto dec = blech32::Decode(str);
        BOOST_CHECK(dec.encoding == blech32::Encoding::INVALID);
    }
}

BOOST_AUTO_TEST_CASE(blech32_polymod_sanity)
{
    std::vector<unsigned char> data(40);
    // GetRandBytes only allows 32 bytes at a time
    GetRandBytes(data.data(), 32);
    GetRandBytes(data.data() + 32, data.size() - 32);

    std::vector<unsigned char> base32;
    ConvertBits<8, 5, true>([&](unsigned char c) { base32.push_back(c); }, data.begin(), data.end());
    uint64_t plm1 = blech32::PolyMod(base32);

    // Now add 1023 zeros.
    for (auto i = 0; i < 1023; i++) {
        base32.push_back(0);
    }
    uint64_t plm2 = blech32::PolyMod(base32);

    BOOST_CHECK_EQUAL(plm1, plm2);
}

BOOST_AUTO_TEST_CASE(blech32_checksum)
{
    std::vector<unsigned char> vector{7,2,3,4,5,6,7,8,9,234,123,213,16};
    std::vector<unsigned char> b32;
    ConvertBits<8, 5, true>([&](unsigned char c) { b32.push_back(c); }, vector.begin(), vector.end());
    std::vector<unsigned char> cs = blech32::CreateChecksum(blech32::Encoding::BLECH32, "lq", b32);

    std::vector<unsigned char> expected_cs{22,13,13,5,4,4,23,7,28,21,30,12};
    for (size_t i = 0; i < expected_cs.size(); i++) {
        BOOST_CHECK_EQUAL(expected_cs[i], cs[i]);
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: psgreco/elements

max_issues_repo_name: psgreco/elements

max_forks_repo_name: psgreco/elements


text:
/*
 * test_matelem.cpp
 *
 *  Created on: 28 mai 2016
 *      Author: boubad
 */
#include <boost/test/unit_test.hpp>
/////////////////////////
#include <matelem.h>
/////////////////////////////
#include <mytestfixture.h>
////////////////////////////////////
#include <global_defs.h>
////////////////////
using namespace info;
using namespace std;
///////////////////////////////////
using MyFixture = MyTestFixture<IDTYPE, INTTYPE, STRINGTYPE, WEIGHTYPE>;
/////////////////////////////////////
using IndivType = typename MyFixture::IndivType;
using DataMap = typename MyFixture::DataMap;
using IndivTypePtr = typename MyFixture::IndivTypePtr;
using SourceType = typename MyFixture::SourceType;
////////////////////////////////
using MatElemType = MatElem<IDTYPE,DISTANCETYPE,STRINGTYPE>;
using DistanceMapType = typename MatElemType::DistanceMapType;
using ints_vector = typename MatElemType::ints_vector;
using sizets_vector = typename MatElemType::sizets_vector;
using MatElemResultType = typename MatElemType::MatElemResultType;
using MatElemResultPtr = typename MatElemType::MatElemResultPtr;
/////////////////////////////////////
BOOST_FIXTURE_TEST_SUITE(MatElemTestSuite,MyFixture)
BOOST_AUTO_TEST_CASE(testMortalMatElem) {
	SourceType *pProvider = this->mortal_source();
	BOOST_CHECK(pProvider != nullptr);
	//
	MatElemType::DistanceMapType oDist(pProvider);
	MatElemType::ints_vector oIds;
	oDist.indexes(oIds);
	//BOOST_TEST_MESSAGE("\nTEST MATELEM MORTAL");
	MatElemType oMat(&oDist, &oIds);
	//BOOST_TEST_MESSAGE("Start criteria: " << oMat.criteria());
	oMat.process();
	//BOOST_TEST_MESSAGE("End criteria: " << oMat.criteria());
	MatElemType::ints_vector ids;
	oMat.ids(ids);
	for (auto aIndex : ids) {
		MatElemType::IndivTypePtr oInd = pProvider->find(aIndex);
		MatElemType::IndivType *pInd = oInd.get();
		BOOST_CHECK(pInd != nullptr);
		STRINGTYPE s = pInd->sigle();
		//BOOST_TEST_MESSAGE(s);
	}
} //testMortalMatElem
#ifdef MYTOTO
BOOST_AUTO_TEST_CASE(testMortalMatElemSignal) {
	SourceType *pProvider = this->mortal_source();
	BOOST_CHECK(pProvider != nullptr);
	//
	MatElemType::DistanceMapType oDist(pProvider);
	MatElemType::ints_vector oIds;
	oDist.indexes(oIds);
	//BOOST_TEST_MESSAGE("\nTEST MATELEM MORTAL");
	MatElemType oMat(&oDist, &oIds);
	//
	size_t nIter = 0;
	DISTANCETYPE oldCrit = 0;
	auto fReceiver =
			[&](MatElemType::MatElemResultPtr oCrit) {
				if (oCrit.get() != nullptr) {
					++nIter;
					DISTANCETYPE crit = oCrit->first;
					if (oldCrit == 0) {
						BOOST_TEST_MESSAGE("Iteration: " << nIter << ",\t" << crit);
						oldCrit = crit;
					} else {
						DISTANCETYPE delta = oldCrit - crit;
						double f = 10000.0 * (delta/(double)oldCrit);
						BOOST_TEST_MESSAGE("Iteration: " << nIter << ",\t" << crit << ",\t" << delta << ",\t" << f);
						oldCrit = crit;
					}

				} //ptr
			};
	auto con = oMat.connect(fReceiver);
	//BOOST_TEST_MESSAGE("Start criteria: " << oMat.criteria());
	oMat.process_signal();
	//BOOST_TEST_MESSAGE("End criteria: " << oMat.criteria());
	MatElemType::ints_vector ids;
	oMat.ids(ids);
	for (auto aIndex : ids) {
		MatElemType::IndivTypePtr oInd = pProvider->find(aIndex);
		MatElemType::IndivType *pInd = oInd.get();
		BOOST_CHECK(pInd != nullptr);
		STRINGTYPE s = pInd->sigle();
		//BOOST_TEST_MESSAGE(s);
	}
} //testMortalMatElemSignal
#endif // MYTOTO
BOOST_AUTO_TEST_CASE(testConsoMatElem) {
	SourceType *pProvider = this->conso_source();
	BOOST_CHECK(pProvider != nullptr);
	//
	MatElemType::DistanceMapType oDist(pProvider);
	MatElemType::ints_vector oIds;
	oDist.indexes(oIds);
	//BOOST_TEST_MESSAGE("\nTEST MATELEM CONSO");
	MatElemType oMat(&oDist, &oIds);
	//BOOST_TEST_MESSAGE("Start criteria: " << oMat.criteria());
	oMat.process();
	//BOOST_TEST_MESSAGE("End criteria: " << oMat.criteria());
	MatElemType::ints_vector ids;
	oMat.ids(ids);
	for (auto aIndex : ids) {
		MatElemType::IndivTypePtr oInd = pProvider->find(aIndex);
		MatElemType::IndivType *pInd = oInd.get();
		BOOST_CHECK(pInd != nullptr);
		STRINGTYPE s = pInd->sigle();
		//BOOST_TEST_MESSAGE(s);
	}
} //testConsoMatElem
#ifdef MYTOTO
BOOST_AUTO_TEST_CASE(testTestMatElem) {
	SourceType *pProvider = this->test_source();
	BOOST_CHECK(pProvider != nullptr);
	//
	MatElemType::DistanceMapType oDist(pProvider);
	MatElemType::ints_vector oIds;
	oDist.indexes(oIds);
	BOOST_TEST_MESSAGE("\nTEST MATELEM TEST");
	MatElemType oMat(&oDist, &oIds);
	BOOST_TEST_MESSAGE("Start criteria: " << oMat.criteria());
	size_t nIter = 0;
	DISTANCETYPE oldCrit = 0;
	oMat.process_interm(
			[&](const MatElemResultPtr &oCrit) {
				if (oCrit.get() != nullptr) {
					++nIter;
					DISTANCETYPE crit = oCrit->first;
					if (oldCrit == 0) {
						BOOST_TEST_MESSAGE("Iteration: " << nIter << ",\t" << crit);
						oldCrit = crit;
					} else {
						DISTANCETYPE delta = oldCrit - crit;
						double f = 10000.0 * (delta/(double)oldCrit);
						BOOST_TEST_MESSAGE("Iteration: " << nIter << ",\t" << crit << ",\t" << delta << ",\t" << f);
						oldCrit = crit;
					}

				} //ptr
			});
	BOOST_TEST_MESSAGE("End criteria: " << oMat.criteria());
	MatElemType::ints_vector ids;
	oMat.ids(ids);
	for (auto aIndex : ids) {
		MatElemType::IndivTypePtr oInd = pProvider->find(aIndex);
		MatElemType::IndivType *pInd = oInd.get();
		BOOST_CHECK(pInd != nullptr);
		STRINGTYPE s = pInd->sigle();
		BOOST_TEST_MESSAGE(s);
	}
} //testTestMatElem
#endif
BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: boubad/CygProjects

max_issues_repo_name: boubad/CygProjects

max_forks_repo_name: boubad/CygProjects


text:
// Software License Agreement (BSD License)
// Copyright (c) 2008, Rosen Diankov
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright
//     notice, this list of conditions and the following disclaimer in the
//     documentation and/or other materials provided with the distribution.
//   * The name of the author may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// author: Rosen Diankov
#include <cstdio>
#include <vector>
#include <ros/ros.h>

#include <boost/thread/mutex.hpp>

#include "opencv/cv.hpp"
#include "opencv/highgui.h"
#include "cv_bridge/cv_bridge.h"
#include "sensor_msgs/image_encodings.h"
#include "sensor_msgs/Image.h"
#include "math.h"

#include <sys/timeb.h>    // ftime(), struct timeb
#include <sys/time.h>

using namespace std;
using namespace ros;

template <typename T>
T SQR(T t) { return t*t; }

class CheckerboardCalibration
{
public:
    ros::NodeHandle _nh;
    ros::Subscriber _sub, _sub2;
    struct CHECKERBOARD
    {
        CvSize griddims; ///< number of squares
        vector<RaveVector<float> > grid3d;
        vector<CvPoint2D32f> corners;
    };

    cv_bridge::CvImagePtr _cvbridge;

    int display;
    CHECKERBOARD _checkerboard; // grid points for every checkerboard
    IplImage* frame;
    vector<CvPoint2D32f> _vAllPoints; ///< all checkerboards found
    vector<int> _vNumPointsPerImage;

    CvMat *_intrinsic_matrix, *_distortion_coeffs; // intrinsic matrices
    IplImage* _pUndistortionMapX, *_pUndistortionMapY;
    TransformMatrix _tProjection; // project matrix
    bool _bHasCalibration, _bClearData, _bTakeObservation;

  CheckerboardCalibration() : frame(NULL), _intrinsic_matrix(NULL), _distortion_coeffs(NULL), _pUndistortionMapX(NULL), _pUndistortionMapY(NULL), _bHasCalibration(false), _bClearData(false), _bTakeObservation(false)
    {
        _nh.param("display",display,1);

        int dimx, dimy;
        double fRectSize[2];
        string type;

        if( !_nh.getParam("grid_size_x",dimx) ) {
            ROS_ERROR("grid_size_x not defined");
            throw;
        }
        if( !_nh.getParam("grid_size_y",dimy) ) {
            ROS_ERROR("grid_size_y not defined");
            throw;
        }
        if( !_nh.getParam("rect_size_x",fRectSize[0]) ) {
            ROS_ERROR("rect_size_x not defined");
            throw;
        }
        if( !_nh.getParam("rect_size_y",fRectSize[1]) ) {
            ROS_ERROR("rect_size_y not defined");
            throw;
        }

        _checkerboard.griddims = cvSize(dimx,dimy);
        _checkerboard.grid3d.resize(dimx*dimy);
        int j=0;
        for(int y=0; y<dimy; ++y)
            for(int x=0; x<dimx; ++x)
                _checkerboard.grid3d[j++] = Vector(x*fRectSize[0], y*fRectSize[1], 0);

        if( _intrinsic_matrix == NULL )
            _intrinsic_matrix = cvCreateMat(3,3,CV_32FC1);
        if( _distortion_coeffs == NULL )
            _distortion_coeffs = cvCreateMat(4,1,CV_32FC1);

        if( display ) {
            cvNamedWindow("Checkerboard Detector", CV_WINDOW_AUTOSIZE);
            cvSetMouseCallback("Checkerboard Detector", MouseCallback, this);
            cvNamedWindow("Calibration Result", CV_WINDOW_AUTOSIZE);
            cvSetMouseCallback("Calibration Result", MouseCallback, this);
            cvStartWindowThread();
        }

        _sub = _nh.subscribe("image", 1, &CheckerboardCalibration::image_cb,this);
        _sub2 = _nh.subscribe("Image", 1, &CheckerboardCalibration::image_cb2,this);
    }
    ~CheckerboardCalibration()
    {
        if( frame )
            cvReleaseImage(&frame);
        if( _intrinsic_matrix )
            cvReleaseMat(&_intrinsic_matrix);
        if( _distortion_coeffs )
            cvReleaseMat(&_distortion_coeffs);
        if( _pUndistortionMapX )
            cvReleaseImage(&_pUndistortionMapX);
        if( _pUndistortionMapY )
            cvReleaseImage(&_pUndistortionMapY);
    }

private:
    void image_cb2(const sensor_msgs::ImageConstPtr& image_msg)
    {
        image_cb(image_msg);
    }
    void image_cb(const sensor_msgs::ImageConstPtr& image_msg)
    {
        try {
            _cvbridge = cv_bridge::toCvCopy(image_msg, sensor_msgs::image_encodings::MONO8);
        } catch (cv_bridge::Exception &e) {
            ROS_ERROR("failed to get image");
            return;
        }

        IplImage imggray = _cvbridge->image;
        IplImage *pimggray = &imggray;
        if( display ) {
            // copy the raw image
            if( frame != NULL && (frame->width != (int)pimggray->width || frame->height != (int)pimggray->height) ) {
                cvReleaseImage(&frame);
                frame = NULL;
            }
            if( frame == NULL )
                frame = cvCreateImage(cvSize(pimggray->width,pimggray->height),IPL_DEPTH_8U, 3);

            cvCvtColor(pimggray,frame,CV_GRAY2RGB);
        }

        int ncorners;
        _checkerboard.corners.resize(_checkerboard.grid3d.size()+64);
        int allfound = cvFindChessboardCorners( pimggray, _checkerboard.griddims, &_checkerboard.corners[0],
                                                &ncorners, CV_CALIB_CB_ADAPTIVE_THRESH );
        _checkerboard.corners.resize(ncorners);

        if(allfound && ncorners == (int)_checkerboard.grid3d.size()) {

            cvFindCornerSubPix(pimggray, &_checkerboard.corners[0], _checkerboard.corners.size(), cvSize(5,5),cvSize(-1,-1),
                               cvTermCriteria(CV_TERMCRIT_ITER,20,1e-2));
        }
        else
            _checkerboard.corners.resize(0);

        if( _bClearData ) {
            ROS_INFO("clearing current calibration data");
            _vAllPoints.resize(0);
            _vNumPointsPerImage.resize(0);
            _bHasCalibration = false;
            _bClearData = false;
        }

        if( _bTakeObservation ) {
            _bTakeObservation = false;

            if(allfound && ncorners == (int)_checkerboard.grid3d.size()) {

                for(vector<CvPoint2D32f>::iterator it = _checkerboard.corners.begin(); it != _checkerboard.corners.end(); ++it)
                    _vAllPoints.push_back(*it);
                _vNumPointsPerImage.push_back(_checkerboard.corners.size());

                ROS_INFO("calibrating");

                CvMat object_points, image_points, point_counts;

                vector<float> vobject_points;
                vobject_points.reserve(_vNumPointsPerImage.size()*3*_checkerboard.grid3d.size());
                for(size_t j = 0; j < _vNumPointsPerImage.size(); ++j) {
                    for(size_t i = 0; i < _checkerboard.grid3d.size(); ++i) {
                        vobject_points.push_back(_checkerboard.grid3d[i].x);
                        vobject_points.push_back(_checkerboard.grid3d[i].y);
                        vobject_points.push_back(_checkerboard.grid3d[i].z);
                    }
                }

                cvInitMatHeader(&object_points, vobject_points.size()/3,3,CV_32FC1, &vobject_points[0]);
                cvInitMatHeader(&image_points, _vAllPoints.size(), 2, CV_32FC1, &_vAllPoints[0]);
                cvInitMatHeader(&point_counts, _vNumPointsPerImage.size(), 1, CV_32SC1, &_vNumPointsPerImage[0]);

                CvMat* rotation_vectors = cvCreateMat(_vNumPointsPerImage.size(),3,CV_32FC1);
                CvMat* translation_vectors = cvCreateMat(_vNumPointsPerImage.size(),3,CV_32FC1);

                cvCalibrateCamera2(&object_points, &image_points,
                                   &point_counts, cvSize(frame->width,frame->height),
                                   _intrinsic_matrix, _distortion_coeffs,
                                   rotation_vectors, translation_vectors, 0);

                double err = 0;
                int off = 0;
                for(size_t i = 0; i < _vNumPointsPerImage.size(); ++i) {
                    CvMat cur_object_points, rotation_vector, translation_vector;

                    cvInitMatHeader(&cur_object_points, _vNumPointsPerImage[i],3,CV_32FC1, &vobject_points[0]);
                    cvInitMatHeader(&rotation_vector, 3, 1, CV_32FC1, &rotation_vectors->data.fl[3*i]);
                    cvInitMatHeader(&translation_vector, 3, 1, CV_32FC1, &translation_vectors->data.fl[3*i]);
                    CvMat* new_image_points = cvCreateMat(_vNumPointsPerImage[i], 2, CV_32FC1);
                    cvProjectPoints2(&cur_object_points, &rotation_vector, &translation_vector, _intrinsic_matrix,
                                     _distortion_coeffs, new_image_points);

                    for(int j = 0; j < _vNumPointsPerImage[i]; ++j)
                        err += SQR(new_image_points->data.fl[2*j]-_vAllPoints[off+j].x) + SQR(new_image_points->data.fl[2*j+1]-_vAllPoints[off+j].y);

                    cvReleaseMat(&new_image_points);
                    off += _vNumPointsPerImage[i];
                }
                err = sqrt(err/(double)_vAllPoints.size());

                ROS_INFO("calibration done, reprojection error = %f", (float)err);
                ROS_INFO("Intrinsic Matrix:");
                for(int i = 0; i < 3; ++i) {
                    ROS_INFO("%15f %15f %15f", _intrinsic_matrix->data.fl[3*i], _intrinsic_matrix->data.fl[3*i+1], _intrinsic_matrix->data.fl[3*i+2]);
                    _tProjection.m[4*i+0] = _intrinsic_matrix->data.fl[3*i+0];
                    _tProjection.m[4*i+1] = _intrinsic_matrix->data.fl[3*i+1];
                    _tProjection.m[4*i+2] = _intrinsic_matrix->data.fl[3*i+2];
                }
                ROS_INFO("distortion: %f %f %f %f", _distortion_coeffs->data.fl[0], _distortion_coeffs->data.fl[1], _distortion_coeffs->data.fl[2], _distortion_coeffs->data.fl[3]);

                cvReleaseMat(&rotation_vectors);
                cvReleaseMat(&translation_vectors);

                // create undistortion maps
                if( _pUndistortionMapX == NULL )
                    _pUndistortionMapX = cvCreateImage( cvSize(frame->width, frame->height), IPL_DEPTH_32F, 1);
                if( _pUndistortionMapY == NULL )
                    _pUndistortionMapY = cvCreateImage( cvSize(frame->width, frame->height), IPL_DEPTH_32F, 1);

#ifdef HAVE_CV_UNDISTORT_RECTIFY_MAP // for newer opencv versions, *have* to use cvInitUndistortRectifyMap
                float feye[9] = {1,0,0,0,1,0,0,0,1};
                CvMat eye = cvMat(3,3,CV_32FC1, feye);
                cvInitUndistortRectifyMap(_intrinsic_matrix,_distortion_coeffs,&eye,_intrinsic_matrix,_pUndistortionMapX, _pUndistortionMapY);
#else
                cvInitUndistortMap( _intrinsic_matrix, _distortion_coeffs, _pUndistortionMapX, _pUndistortionMapY );
#endif
                _bHasCalibration = true;
            }
            else
                ROS_WARN("no checkerboard found");
        }

        if( display ) {
            if( _bHasCalibration ) {
                IplImage* frame_undist = cvCloneImage(frame);
                IplImage* pimggray_undist = cvCloneImage(pimggray);

                cvRemap( pimggray, pimggray_undist, _pUndistortionMapX, _pUndistortionMapY, CV_INTER_LINEAR + CV_WARP_FILL_OUTLIERS);
                cvRemap( frame, frame_undist, _pUndistortionMapX, _pUndistortionMapY, CV_INTER_LINEAR + CV_WARP_FILL_OUTLIERS);

                int ncorners;
                vector<CvPoint2D32f> corners(_checkerboard.grid3d.size()+64);
                int allfound = cvFindChessboardCorners( pimggray_undist, _checkerboard.griddims, &corners[0],
                                                        &ncorners, CV_CALIB_CB_ADAPTIVE_THRESH );
                corners.resize(ncorners);

                if(allfound && ncorners == (int)_checkerboard.grid3d.size()) {
                    //cvCvtColor(pimggray,frame,CV_GRAY2RGB);
                    cvFindCornerSubPix(pimggray_undist, &corners[0], corners.size(), cvSize(5,5),cvSize(-1,-1),
                                       cvTermCriteria(CV_TERMCRIT_ITER,20,1e-2));

                    RaveTransform<float> tlocal = FindTransformation(corners, _checkerboard.grid3d);

                    CvSize& s = _checkerboard.griddims;
                    CvPoint X[4];
                    int inds[4] = {0, s.width-1, s.width*(s.height-1), s.width*s.height-1 };

                    for(int i = 0; i < 4; ++i) {
                        Vector p = _tProjection * tlocal * _checkerboard.grid3d[inds[i]];
                        X[i].x = (int)(p.x/p.z);
                        X[i].y = (int)(p.y/p.z);
                    }

                    // draw two lines
                    CvScalar col0 = CV_RGB(255,0,0);
                    CvScalar col1 = CV_RGB(0,255,0);
                    cvLine(frame_undist, X[0], X[1], col0, 1);
                    cvLine(frame_undist, X[0], X[2], col1, 1);

                    // draw all the points
                    for(size_t i = 0; i < _checkerboard.grid3d.size(); ++i) {
                        Vector p = _tProjection * tlocal * _checkerboard.grid3d[i];
                        int x = (int)(p.x/p.z);
                        int y = (int)(p.y/p.z);
                        cvCircle(frame_undist, cvPoint(x,y), 6, CV_RGB(0,0,0), 2);
                        cvCircle(frame_undist, cvPoint(x,y), 2, CV_RGB(0,0,0), 2);
                        cvCircle(frame_undist, cvPoint(x,y), 4, CV_RGB(128,128,0), 3);
                    }

                    cvCircle(frame_undist, X[0], 3, CV_RGB(255,255,128), 3);
                }

                cvShowImage("Calibration Result",frame_undist);
                cvReleaseImage(&frame_undist);
            }

            if(allfound && ncorners == (int)_checkerboard.grid3d.size())
                cvDrawChessboardCorners(frame, _checkerboard.griddims, &_checkerboard.corners[0], _checkerboard.corners.size(), 1);

            cvShowImage("Checkerboard Detector",frame);
        }
    }

    Transform FindTransformation(const vector<CvPoint2D32f> &imgpts, const vector<Vector> &objpts)
    {
        CvMat *objpoints = cvCreateMat(3,objpts.size(),CV_32FC1);
        for(size_t i=0; i<objpts.size(); ++i) {
            cvSetReal2D(objpoints, 0,i, objpts[i].x);
            cvSetReal2D(objpoints, 1,i, objpts[i].y);
            cvSetReal2D(objpoints, 2,i, objpts[i].z);
        }

        RaveTransform<float> pose;
        float fR3[3];
        CvMat R3, T3;
        cvInitMatHeader(&R3, 3, 1, CV_32FC1, fR3);
        cvInitMatHeader(&T3, 3, 1, CV_32FC1, &pose.trans.x);

        float kc[4] = {0};
        CvMat kcmat;
        cvInitMatHeader(&kcmat,1,4,CV_32FC1,kc);

        CvMat img_points;
        cvInitMatHeader(&img_points, 1,imgpts.size(), CV_32FC2, const_cast<CvPoint2D32f*>(&imgpts[0]));

        cvFindExtrinsicCameraParams2(objpoints, &img_points, _intrinsic_matrix, &kcmat, &R3, &T3);
        cvReleaseMat(&objpoints);

        double fang = sqrt(fR3[0]*fR3[0] + fR3[1]*fR3[1] + fR3[2]*fR3[2]);
        if( fang < 1e-6 ) {
            pose.rot.x = 1;
            pose.rot.y = 0;
            pose.rot.z = 0;
            pose.rot.w = 0;
        }
        else {
            double fmult = sin(fang/2)/fang;
            pose.rot.x = cos(fang/2);
            pose.rot.y = fR3[0]*fmult;
            pose.rot.z = fR3[1]*fmult;
            pose.rot.w = fR3[2]*fmult;
        }

        return pose;
    }

    static void MouseCallback(int event, int x, int y, int flags, void* param)
    {
        ((CheckerboardCalibration*)param)->_MouseCallback(event, x, y, flags);
    }

    void _MouseCallback(int event, int x, int y, int flags)
    {
        switch(event) {
        case CV_EVENT_RBUTTONDOWN:
            _bClearData = true;
            break;
        case CV_EVENT_MBUTTONDOWN:
            _bTakeObservation = true;
            break;
        }
    }
};

int main(int argc, char **argv)
{
    ros::init(argc,argv,"checkerboard_calibration");
    boost::shared_ptr<CheckerboardCalibration> checker(new CheckerboardCalibration());

    ros::spin();
    checker.reset();
    return 0;
}


text:
/*
 *  Copyright (c) 2004-present, Facebook, Inc.
 *  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. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "fboss/agent/test/TestUtils.h"

#include <boost/cast.hpp>
#include <thrift/lib/cpp2/protocol/Serializer.h>

#include "fboss/agent/AgentConfig.h"
#include "fboss/agent/ApplyThriftConfig.h"
#include "fboss/agent/RxPacket.h"
#include "fboss/agent/TunManager.h"
#include "fboss/agent/gen-cpp2/switch_config_types.h"
#include "fboss/agent/hw/mock/MockHwSwitch.h"
#include "fboss/agent/hw/mock/MockPlatform.h"
#include "fboss/agent/platforms/wedge/WedgePlatformInit.h"
#include "fboss/agent/state/Interface.h"
#include "fboss/agent/state/Port.h"
#include "fboss/agent/state/RouteNextHop.h"

#include "fboss/agent/state/SwitchState.h"
#include "fboss/agent/state/Vlan.h"
#include "fboss/agent/state/VlanMap.h"
#include "fboss/agent/test/HwTestHandle.h"
#include "fboss/agent/test/MockTunManager.h"

#include "fboss/agent/SwSwitchRouteUpdateWrapper.h"
#include "fboss/agent/rib/RoutingInformationBase.h"

#include <folly/Memory.h>
#include <folly/json.h>
#include <folly/logging/Init.h>
#include <chrono>
#include <optional>

using folly::ByteRange;
using folly::IOBuf;
using folly::IPAddress;
using folly::IPAddressV4;
using folly::IPAddressV6;
using folly::MacAddress;
using folly::StringPiece;
using folly::io::Cursor;
using std::make_shared;
using std::make_unique;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using ::testing::_;
using ::testing::ByMove;
using ::testing::NiceMock;
using ::testing::Return;

using namespace facebook::fboss;

namespace {

void initSwSwitchWithFlags(SwSwitch* sw, SwitchFlags flags) {
  if (flags & SwitchFlags::ENABLE_TUN) {
    // TODO(aeckert): I don't think this should be a first class
    // argument to SwSwitch::init() as unit tests are the only place
    // that pass in a TunManager to init(). Let's come up with a way
    // to mock the TunManager initialization instead of passing it in
    // like this.
    //
    // TODO(aeckert): Have MockTunManager hit the real TunManager
    // implementation if testing on actual hw
    auto mockTunMgr =
        std::make_unique<MockTunManager>(sw, sw->getBackgroundEvb());
    EXPECT_CALL(*mockTunMgr.get(), doProbe(_)).Times(1);
    sw->init(std::move(mockTunMgr), flags);
  } else {
    sw->init(nullptr, flags);
  }
}

unique_ptr<SwSwitch> createMockSw(
    const shared_ptr<SwitchState>& state,
    SwitchFlags flags) {
  auto platform = createMockPlatform();
  return setupMockSwitchWithoutHW(std::move(platform), state, flags);
}

shared_ptr<SwitchState> setAllPortState(
    const shared_ptr<SwitchState>& in,
    bool up) {
  auto newState = in->clone();
  auto newPortMap = newState->getPorts()->modify(&newState);
  for (auto port : *newPortMap) {
    auto newPort = port->clone();
    newPort->setOperState(up);
    newPort->setAdminState(
        up ? cfg::PortState::ENABLED : cfg::PortState::DISABLED);
    newPortMap->updatePort(newPort);
  }
  return newState;
}
cfg::SwitchConfig testConfigAImpl(bool isMhnic) {
  cfg::SwitchConfig cfg;
  static constexpr auto kPortCount = 20;

  cfg.ports_ref()->resize(kPortCount);
  for (int p = 0; p < kPortCount; ++p) {
    cfg.ports_ref()[p].logicalID_ref() = p + 1;
    cfg.ports_ref()[p].name_ref() = folly::to<string>("port", p + 1);
    if (isMhnic) {
      cfg.ports_ref()[p].state_ref() = cfg::PortState::ENABLED;
      cfg.ports_ref()[p].lookupClasses_ref() = {
          cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_0,
          cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_1,
          cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_2,
          cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_3,
          cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_4,
      };
      cfg.ports_ref()[p].speed_ref() = cfg::PortSpeed::TWENTYFIVEG;
      cfg.ports_ref()[p].profileID_ref() =
          cfg::PortProfileID::PROFILE_25G_1_NRZ_CL74_COPPER;
    } else {
      bool isControllingPort = (p % 4 == 0);
      if (isControllingPort) {
        cfg.ports_ref()[p].state_ref() = cfg::PortState::ENABLED;
        cfg.ports_ref()[p].speed_ref() = cfg::PortSpeed::HUNDREDG;
        cfg.ports_ref()[p].profileID_ref() =
            cfg::PortProfileID::PROFILE_100G_4_NRZ_CL91_COPPER;
      } else {
        cfg.ports_ref()[p].state_ref() = cfg::PortState::DISABLED;
        cfg.ports_ref()[p].speed_ref() = cfg::PortSpeed::TWENTYFIVEG;
        cfg.ports_ref()[p].profileID_ref() =
            cfg::PortProfileID::PROFILE_25G_1_NRZ_CL74_COPPER;
      }
    }
  }

  cfg.vlans_ref()->resize(2);
  cfg.vlans_ref()[0].id_ref() = 1;
  cfg.vlans_ref()[0].name_ref() = "Vlan1";
  cfg.vlans_ref()[0].intfID_ref() = 1;
  cfg.vlans_ref()[1].id_ref() = 55;
  cfg.vlans_ref()[1].name_ref() = "Vlan55";
  cfg.vlans_ref()[1].intfID_ref() = 55;

  cfg.vlanPorts_ref()->resize(20);
  for (int p = 0; p < kPortCount; ++p) {
    cfg.vlanPorts_ref()[p].logicalPort_ref() = p + 1;
    cfg.vlanPorts_ref()[p].vlanID_ref() = p < 11 ? 1 : 55;
  }

  cfg.interfaces_ref()->resize(2);
  cfg.interfaces_ref()[0].intfID_ref() = 1;
  cfg.interfaces_ref()[0].routerID_ref() = 0;
  cfg.interfaces_ref()[0].vlanID_ref() = 1;
  cfg.interfaces_ref()[0].name_ref() = "interface1";
  cfg.interfaces_ref()[0].mac_ref() = "00:02:00:00:00:01";
  cfg.interfaces_ref()[0].mtu_ref() = 9000;
  cfg.interfaces_ref()[0].ipAddresses_ref()->resize(4);
  cfg.interfaces_ref()[0].ipAddresses_ref()[0] = "10.0.0.1/24";
  cfg.interfaces_ref()[0].ipAddresses_ref()[1] = "192.168.0.1/24";
  cfg.interfaces_ref()[0].ipAddresses_ref()[2] = "2401:db00:2110:3001::0001/64";
  cfg.interfaces_ref()[0].ipAddresses_ref()[3] = "fe80::/64"; // link local

  cfg.interfaces_ref()[1].intfID_ref() = 55;
  cfg.interfaces_ref()[1].routerID_ref() = 0;
  cfg.interfaces_ref()[1].vlanID_ref() = 55;
  cfg.interfaces_ref()[1].name_ref() = "interface55";
  cfg.interfaces_ref()[1].mac_ref() = "00:02:00:00:00:55";
  cfg.interfaces_ref()[1].mtu_ref() = 9000;
  cfg.interfaces_ref()[1].ipAddresses_ref()->resize(4);
  cfg.interfaces_ref()[1].ipAddresses_ref()[0] = "10.0.55.1/24";
  cfg.interfaces_ref()[1].ipAddresses_ref()[1] = "192.168.55.1/24";
  cfg.interfaces_ref()[1].ipAddresses_ref()[2] = "2401:db00:2110:3055::0001/64";
  cfg.interfaces_ref()[1].ipAddresses_ref()[3] = "169.254.0.0/16"; // link local

  return cfg;
}

} // namespace

namespace facebook::fboss {

cfg::SwitchConfig testConfigA() {
  return testConfigAImpl(false);
}

cfg::SwitchConfig testConfigAWithLookupClasses() {
  return testConfigAImpl(true);
}

shared_ptr<SwitchState> bringAllPortsUp(const shared_ptr<SwitchState>& in) {
  return setAllPortState(in, true);
}
shared_ptr<SwitchState> bringAllPortsDown(const shared_ptr<SwitchState>& in) {
  return setAllPortState(in, false);
}

shared_ptr<SwitchState> publishAndApplyConfig(
    const shared_ptr<SwitchState>& state,
    const cfg::SwitchConfig* config,
    const Platform* platform,
    RoutingInformationBase* rib) {
  state->publish();
  return applyThriftConfig(state, config, platform, rib);
}

std::unique_ptr<SwSwitch> setupMockSwitchWithoutHW(
    std::unique_ptr<MockPlatform> platform,
    const std::shared_ptr<SwitchState>& state,
    SwitchFlags flags) {
  auto sw = make_unique<SwSwitch>(std::move(platform));
  HwInitResult ret;
  ret.switchState = state ? state : make_shared<SwitchState>();
  ret.bootType = BootType::COLD_BOOT;
  ret.rib = std::make_unique<RoutingInformationBase>();
  EXPECT_HW_CALL(sw, init(_, false)).WillOnce(Return(ByMove(std::move(ret))));
  initSwSwitchWithFlags(sw.get(), flags);
  waitForStateUpdates(sw.get());
  return sw;
}

unique_ptr<MockPlatform> createMockPlatform() {
  return make_unique<testing::NiceMock<MockPlatform>>();
}

unique_ptr<HwTestHandle> createTestHandle(
    const shared_ptr<SwitchState>& state,
    SwitchFlags flags) {
  auto sw = createMockSw(state, flags);
  auto platform = static_cast<MockPlatform*>(sw->getPlatform());
  auto handle = platform->createTestHandle(std::move(sw));
  handle->prepareForTesting();
  return handle;
}

unique_ptr<HwTestHandle> createTestHandle(
    cfg::SwitchConfig* config,
    SwitchFlags flags) {
  shared_ptr<SwitchState> initialState{nullptr};
  // Create the initial state, which only has the same number of ports with the
  // init config
  initialState = make_shared<SwitchState>();
  if (config) {
    for (const auto& port : *config->ports_ref()) {
      auto id = *port.logicalID_ref();
      initialState->registerPort(PortID(id), folly::to<string>("port", id));
    }
  }

  auto handle = createTestHandle(initialState, flags);
  auto sw = handle->getSw();

  if (config) {
    // Apply the thrift config
    sw->applyConfig("test_setup", *config);
  }
  return handle;
}

MockHwSwitch* getMockHw(SwSwitch* sw) {
  return boost::polymorphic_downcast<MockHwSwitch*>(sw->getHw());
}

MockPlatform* getMockPlatform(SwSwitch* sw) {
  return boost::polymorphic_downcast<MockPlatform*>(sw->getPlatform());
}

MockHwSwitch* getMockHw(std::unique_ptr<SwSwitch>& sw) {
  return boost::polymorphic_downcast<MockHwSwitch*>(sw->getHw());
}

MockPlatform* getMockPlatform(std::unique_ptr<SwSwitch>& sw) {
  return boost::polymorphic_downcast<MockPlatform*>(sw->getPlatform());
}

std::shared_ptr<SwitchState> waitForStateUpdates(SwSwitch* sw) {
  // All StateUpdates scheduled from this thread will be applied in order,
  // so we can simply perform a blocking no-op update.  When it is done
  // we can be sure that all previously scheduled updates have also been
  // applied.
  std::shared_ptr<SwitchState> snapshot{nullptr};
  auto snapshotUpdate = [&snapshot](const shared_ptr<SwitchState>& state)
      -> std::shared_ptr<SwitchState> {
    // take a snapshot of the current state, but don't modify state
    snapshot = state;
    return nullptr;
  };
  sw->updateStateBlocking("waitForStateUpdates", snapshotUpdate);
  return snapshot;
}

void waitForBackgroundThread(SwSwitch* sw) {
  auto* evb = sw->getBackgroundEvb();
  evb->runInEventBaseThreadAndWait([]() { return; });
}

void waitForNeighborCacheThread(SwSwitch* sw) {
  auto* evb = sw->getNeighborCacheEvb();
  evb->runInEventBaseThreadAndWait([]() { return; });
}

void waitForRibUpdates(SwSwitch* sw) {
  sw->getRouteUpdater().program();
}

shared_ptr<SwitchState> testStateA() {
  // Setup a default state object
  auto state = make_shared<SwitchState>();

  // Add VLAN 1, and ports 1-10 which belong to it.
  auto vlan1 = make_shared<Vlan>(VlanID(1), "Vlan1");
  state->addVlan(vlan1);
  for (int idx = 1; idx <= 10; ++idx) {
    state->registerPort(PortID(idx), folly::to<string>("port", idx));
    vlan1->addPort(PortID(idx), false);
    auto port = state->getPorts()->getPortIf(PortID(idx));
    port->addVlan(vlan1->getID(), false);
  }
  // Add VLAN 55, and ports 11-20 which belong to it.
  auto vlan55 = make_shared<Vlan>(VlanID(55), "Vlan55");
  state->addVlan(vlan55);
  for (int idx = 11; idx <= 20; ++idx) {
    state->registerPort(PortID(idx), folly::to<string>("port", idx));
    vlan55->addPort(PortID(idx), false);
    auto port = state->getPorts()->getPortIf(PortID(idx));
    port->addVlan(vlan55->getID(), false);
  }
  // Add Interface 1 to VLAN 1
  auto intf1 = make_shared<Interface>(
      InterfaceID(1),
      RouterID(0),
      VlanID(1),
      "interface1",
      MacAddress("00:02:00:00:00:01"),
      9000,
      false, /* is virtual */
      false /* is state_sync disabled */);
  Interface::Addresses addrs1;
  addrs1.emplace(IPAddress("10.0.0.1"), 24);
  addrs1.emplace(IPAddress("192.168.0.1"), 24);
  addrs1.emplace(IPAddress("169.254.0.0"), 16); // link local

  addrs1.emplace(IPAddress("2401:db00:2110:3001::0001"), 64);
  addrs1.emplace(IPAddress("fe80::"), 64); // link local

  intf1->setAddresses(addrs1);
  state->addIntf(intf1);
  vlan1->setInterfaceID(InterfaceID(1));

  // Add Interface 55 to VLAN 55
  auto intf55 = make_shared<Interface>(
      InterfaceID(55),
      RouterID(0),
      VlanID(55),
      "interface55",
      MacAddress("00:02:00:00:00:55"),
      9000,
      false, /* is virtual */
      false /* is state_sync disabled */);
  Interface::Addresses addrs55;
  addrs55.emplace(IPAddress("10.0.55.1"), 24);
  addrs55.emplace(IPAddress("192.168.55.1"), 24);
  addrs55.emplace(IPAddress("2401:db00:2110:3055::0001"), 64);
  intf55->setAddresses(addrs55);
  state->addIntf(intf55);
  vlan55->setInterfaceID(InterfaceID(55));

  return state;
}

shared_ptr<SwitchState> testStateAWithPortsUp() {
  return bringAllPortsUp(testStateA());
}

shared_ptr<SwitchState> testStateAWithLookupClasses() {
  auto newState = testStateAWithPortsUp()->clone();
  auto newPortMap = newState->getPorts()->modify(&newState);
  for (auto port : *newPortMap) {
    auto newPort = port->clone();
    newPort->setLookupClassesToDistributeTrafficOn({
        cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_0,
        cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_1,
        cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_2,
        cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_3,
        cfg::AclLookupClass::CLASS_QUEUE_PER_HOST_QUEUE_4,
    });
    newPortMap->updatePort(newPort);
  }

  return newState;
}

shared_ptr<SwitchState> testStateB() {
  // Setup a default state object
  auto state = make_shared<SwitchState>();

  // Add VLAN 1, and ports 1-9 which belong to it.
  auto vlan1 = make_shared<Vlan>(VlanID(1), "Vlan1");
  state->addVlan(vlan1);
  for (int idx = 1; idx <= 10; ++idx) {
    state->registerPort(PortID(idx), folly::to<string>("port", idx));
    vlan1->addPort(PortID(idx), false);
  }

  // Add Interface 1 to VLAN 1
  auto intf1 = make_shared<Interface>(
      InterfaceID(1),
      RouterID(0),
      VlanID(1),
      "interface1",
      MacAddress("00:02:00:00:00:01"),
      9000,
      false, /* is virtual */
      false /* is state_sync disabled */);
  Interface::Addresses addrs1;
  addrs1.emplace(IPAddress("10.0.0.1"), 24);
  addrs1.emplace(IPAddress("192.168.0.1"), 24);
  addrs1.emplace(IPAddress("2401:db00:2110:3001::0001"), 64);
  intf1->setAddresses(addrs1);
  state->addIntf(intf1);
  vlan1->setInterfaceID(InterfaceID(1));
  return state;
}

shared_ptr<SwitchState> testStateBWithPortsUp() {
  return bringAllPortsUp(testStateB());
}

std::string fbossHexDump(const IOBuf* buf) {
  Cursor cursor(buf);
  size_t length = cursor.totalLength();
  if (length == 0) {
    return "";
  }

  string result;
  result.reserve(length * 3);
  folly::format(&result, "{:02x}", cursor.read<uint8_t>());
  for (size_t n = 1; n < length; ++n) {
    folly::format(&result, " {:02x}", cursor.read<uint8_t>());
  }

  return result;
}

std::string fbossHexDump(const IOBuf& buf) {
  return fbossHexDump(&buf);
}

std::string fbossHexDump(folly::ByteRange buf) {
  IOBuf iobuf(IOBuf::WRAP_BUFFER, buf);
  return fbossHexDump(&iobuf);
}

std::string fbossHexDump(folly::StringPiece buf) {
  IOBuf iobuf(IOBuf::WRAP_BUFFER, ByteRange(buf));
  return fbossHexDump(&iobuf);
}

std::string fbossHexDump(const string& buf) {
  IOBuf iobuf(IOBuf::WRAP_BUFFER, ByteRange(StringPiece(buf)));
  return fbossHexDump(&iobuf);
}

TxPacketMatcher::TxPacketMatcher(StringPiece name, TxMatchFn fn)
    : name_(name.str()), fn_(std::move(fn)) {}

::testing::Matcher<TxPacketPtr> TxPacketMatcher::createMatcher(
    folly::StringPiece name,
    TxMatchFn&& fn) {
  return ::testing::MakeMatcher(new TxPacketMatcher(name, std::move(fn)));
}

bool TxPacketMatcher::MatchAndExplain(
    TxPacketPtr pkt,
    ::testing::MatchResultListener* l) const {
  try {
    fn_(pkt);
    return true;
  } catch (const std::exception& ex) {
    *l << ex.what();
    return false;
  }
}

void TxPacketMatcher::DescribeTo(std::ostream* os) const {
  *os << name_;
}

void TxPacketMatcher::DescribeNegationTo(std::ostream* os) const {
  *os << "not " << name_;
}

RxPacketMatcher::RxPacketMatcher(
    StringPiece name,
    InterfaceID dstIfID,
    RxMatchFn fn)
    : name_(name.str()), dstIfID_(dstIfID), fn_(std::move(fn)) {}

::testing::Matcher<RxMatchFnArgs> RxPacketMatcher::createMatcher(
    folly::StringPiece name,
    InterfaceID dstIfID,
    RxMatchFn&& fn) {
  return ::testing::MakeMatcher(
      new RxPacketMatcher(name, dstIfID, std::move(fn)));
}

bool RxPacketMatcher::MatchAndExplain(
    RxMatchFnArgs args,
    ::testing::MatchResultListener* l) const {
  auto dstIfID = std::get<0>(args);
  auto pkt = std::get<1>(args);

  try {
    if (dstIfID != dstIfID_) {
      throw FbossError(
          "Mismatching dstIfID. Expected ",
          dstIfID_,
          " but received ",
          dstIfID);
    }

    fn_(pkt.get());
    return true;
  } catch (const std::exception& ex) {
    *l << ex.what();
    return false;
  }
}

void RxPacketMatcher::DescribeTo(std::ostream* os) const {
  *os << name_;
}

void RxPacketMatcher::DescribeNegationTo(std::ostream* os) const {
  *os << "not " << name_;
}

RouteNextHopSet makeNextHops(
    std::vector<std::string> ipStrs,
    std::optional<LabelForwardingAction> mplsAction) {
  RouteNextHopSet nhops;
  for (const std::string& ip : ipStrs) {
    nhops.emplace(UnresolvedNextHop(IPAddress(ip), ECMP_WEIGHT, mplsAction));
  }
  return nhops;
}
RouteNextHopSet makeResolvedNextHops(
    std::vector<std::pair<InterfaceID, std::string>> intfAndIPs) {
  RouteNextHopSet nhops;
  for (auto intfAndIP : intfAndIPs) {
    nhops.emplace(ResolvedNextHop(
        IPAddress(intfAndIP.second), intfAndIP.first, ECMP_WEIGHT));
  }
  return nhops;
}

RoutePrefixV4 makePrefixV4(std::string str) {
  std::vector<std::string> vec;
  folly::split("/", str, vec);
  EXPECT_EQ(2, vec.size());
  auto prefix =
      RoutePrefixV4{IPAddressV4(vec.at(0)), folly::to<uint8_t>(vec.at(1))};
  return prefix;
}

RoutePrefixV6 makePrefixV6(std::string str) {
  std::vector<std::string> vec;
  folly::split("/", str, vec);
  EXPECT_EQ(2, vec.size());
  auto prefix =
      RoutePrefixV6{IPAddressV6(vec.at(0)), folly::to<uint8_t>(vec.at(1))};
  return prefix;
}

WaitForSwitchState::WaitForSwitchState(
    SwSwitch* sw,
    SwitchStatePredicate predicate,
    const std::string& name)
    : predicate_(std::move(predicate)), name_(name), sw_(sw) {
  sw_->registerStateObserver(this, name_);
}

WaitForSwitchState::~WaitForSwitchState() {
  sw_->unregisterStateObserver(this);
}

void WaitForSwitchState::stateUpdated(const StateDelta& delta) {
  if (predicate_(delta)) {
    {
      std::lock_guard<std::mutex> guard(mtx_);
      done_ = true;
    }
    cv_.notify_all();
  }
}

void programRoutes(
    const utility::RouteDistributionGenerator::RouteChunks& routeChunks,
    SwSwitch* sw) {
  auto updater = sw->getRouteUpdater();
  for (const auto& routeChunk : routeChunks) {
    for (const auto& route : routeChunk) {
      RouteNextHopSet nhops;
      for (const auto& nhop : route.nhops) {
        nhops.emplace(nhop);
      }
      updater.addRoute(
          RouterID(0),
          route.prefix.first,
          route.prefix.second,
          ClientID::BGPD,
          RouteNextHopEntry(nhops, AdminDistance::EBGP));
    }
  }
  updater.program();
}

void updateBlockedNeighbor(
    SwSwitch* sw,
    const std::vector<std::pair<VlanID, folly::IPAddress>>& blockNeighbors) {
  sw->updateStateBlocking(
      "Update blocked neighbors ",
      [=](const std::shared_ptr<SwitchState>& state) {
        std::shared_ptr<SwitchState> newState{state};

        auto newSwitchSettings = state->getSwitchSettings()->modify(&newState);
        newSwitchSettings->setBlockNeighbors(blockNeighbors);
        return newState;
      });

  waitForStateUpdates(sw);
  sw->getNeighborUpdater()->waitForPendingUpdates();
  waitForBackgroundThread(sw);
  waitForStateUpdates(sw);
}

void updateMacAddrsToBlock(
    SwSwitch* sw,
    const std::vector<std::pair<VlanID, folly::MacAddress>>& macAddrsToBlock) {
  sw->updateStateBlocking(
      "Update MAC addrs to block traffic to",
      [=](const std::shared_ptr<SwitchState>& state) {
        std::shared_ptr<SwitchState> newState{state};

        auto newSwitchSettings = state->getSwitchSettings()->modify(&newState);
        newSwitchSettings->setMacAddrsToBlock(macAddrsToBlock);
        return newState;
      });

  waitForStateUpdates(sw);
  sw->getNeighborUpdater()->waitForPendingUpdates();
  waitForBackgroundThread(sw);
  waitForStateUpdates(sw);
}

std::vector<std::shared_ptr<Port>> getPortsInLoopbackMode(
    const std::shared_ptr<SwitchState>& state) {
  std::vector<std::shared_ptr<Port>> lbPorts;
  for (auto port : *state->getPorts()) {
    if (port->getLoopbackMode() != cfg::PortLoopbackMode::NONE) {
      lbPorts.push_back(port);
    }
  }
  return lbPorts;
}

void preparedMockPortConfig(
    cfg::Port& portCfg,
    int32_t id,
    std::optional<std::string> name,
    cfg::PortState state) {
  portCfg.logicalID_ref() = id;
  portCfg.state_ref() = state;
  portCfg.name_ref() = name ? *name : fmt::format("port{}", id);
  // Always use 10G because all the platform ports from MockPlatform can
  // support such speed and profile
  portCfg.speed_ref() = cfg::PortSpeed::XG;
  portCfg.profileID_ref() = cfg::PortProfileID::PROFILE_10G_1_NRZ_NOFEC_COPPER;
}

} // namespace facebook::fboss

max_stars_repo_name: dgrnbrg-meta/fboss

max_issues_repo_name: dgrnbrg-meta/fboss

max_forks_repo_name: dgrnbrg-meta/fboss


text:
// BEGIN_COPYRIGHT
//
// Copyright 2009-2014 CRS4.
//
// 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.
//
// END_COPYRIGHT

#ifndef HADOOP_HDFS_COMMON_HPP
#define HADOOP_HDFS_COMMON_HPP

#include <string>
#include <exception>

#include "hdfs.h"

#ifdef __APPLE__
#include "mac_support.hpp"
#endif

#include <boost/python.hpp>

namespace bp = boost::python;

//+++++++++++++++++++++++++++++++++++++++++++++++++++++//
//                 hdfs_exception                      //
//+++++++++++++++++++++++++++++++++++++++++++++++++++++//

class hdfs_exception: public std::exception {
private:
  const std::string msg_;
public:
  hdfs_exception(std::string msg) : msg_(msg) {}
  virtual const char* what() const throw() {
    return msg_.c_str();
  }
  ~hdfs_exception() throw() {}
};

#endif // HADOOP_HDFS_COMMON_HPP

max_stars_repo_name: ZEMUSHKA/pydoop

max_issues_repo_name: ZEMUSHKA/pydoop

max_forks_repo_name: ZEMUSHKA/pydoop