text:
/*=============================================================================
    Copyright (c) 2001-2003 Joel de Guzman

    Use, modification and distribution is 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)
==============================================================================*/
#if !defined(FUSION_SEQUENCE_DETAIL_TUPLE_ACCESS_RESULT_HPP)
#define FUSION_SEQUENCE_DETAIL_TUPLE_ACCESS_RESULT_HPP

#include <boost/spirit/fusion/detail/config.hpp>
#include <boost/spirit/fusion/detail/access.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/eval_if.hpp>

namespace boost { namespace fusion { namespace detail
{
    template <typename Tuple, int N>
    struct tuple_access_result
    {
        typedef mpl::at_c<FUSION_GET_TYPES(Tuple), N> element;
        typedef typename
            mpl::eval_if<
                is_const<Tuple>
              , cref_result<element>
              , ref_result<element>
            >::type
        type;
    };
}}}

#endif

max_stars_repo_name: schinmayee/nimbus

max_issues_repo_name: schinmayee/nimbus

max_forks_repo_name: schinmayee/nimbus


text:
/*
 * Stack.cpp
 *
 *  Created on: 24 Oct 2015
 *      Author: hieu
 */
#include <algorithm>
#include <boost/foreach.hpp>
#include "Stack.h"
#include "../Hypothesis.h"
#include "../Manager.h"
#include "../../Scores.h"
#include "../../System.h"

using namespace std;

namespace Moses2
{

namespace NSCubePruningBitmapStack
{
MiniStack::MiniStack(const Manager &mgr)
  :m_coll()
  ,m_sortedHypos(NULL)
{}

StackAdd MiniStack::Add(const Hypothesis *hypo)
{
  std::pair<_HCType::iterator, bool> addRet = m_coll.insert(hypo);

  // CHECK RECOMBINATION
  if (addRet.second) {
    // equiv hypo doesn't exists
    return StackAdd(true, NULL);
  } else {
    const Hypothesis *hypoExisting = *addRet.first;
    if (hypo->GetScores().GetTotalScore() > hypoExisting->GetScores().GetTotalScore()) {
      // incoming hypo is better than the one we have
      const Hypothesis *const &hypoExisting1 = *addRet.first;
      const Hypothesis *&hypoExisting2 = const_cast<const Hypothesis *&>(hypoExisting1);
      hypoExisting2 = hypo;

      return StackAdd(true, const_cast<Hypothesis*>(hypoExisting));
    } else {
      // already storing the best hypo. discard incoming hypo
      return StackAdd(false, const_cast<Hypothesis*>(hypo));
    }
  }

  assert(false);
}

Hypotheses &MiniStack::GetSortedAndPruneHypos(const Manager &mgr) const
{
  if (m_sortedHypos == NULL) {
    // create sortedHypos first
    MemPool &pool = mgr.GetPool();
    m_sortedHypos = new (pool.Allocate< Vector<const Hypothesis*> >()) Vector<const Hypothesis*>(pool, m_coll.size());

    size_t ind = 0;
    BOOST_FOREACH(const Hypothesis *hypo, m_coll) {
      (*m_sortedHypos)[ind] = hypo;
      ++ind;
    }

    SortAndPruneHypos(mgr);
  }

  return *m_sortedHypos;
}

void MiniStack::SortAndPruneHypos(const Manager &mgr) const
{
  size_t stackSize = mgr.system.stackSize;
  Recycler<Hypothesis*> &recycler = mgr.GetHypoRecycle();

  /*
  cerr << "UNSORTED hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
    const Hypothesis *hypo = hypos[i];
    cerr << *hypo << endl;
  }
  cerr << endl;
  */
  Hypotheses::iterator iterMiddle;
  iterMiddle = (stackSize == 0 || m_sortedHypos->size() < stackSize)
               ? m_sortedHypos->end()
               : m_sortedHypos->begin() + stackSize;

  std::partial_sort(m_sortedHypos->begin(), iterMiddle, m_sortedHypos->end(),
                    HypothesisFutureScoreOrderer());

  // prune
  if (stackSize && m_sortedHypos->size() > stackSize) {
    for (size_t i = stackSize; i < m_sortedHypos->size(); ++i) {
      Hypothesis *hypo = const_cast<Hypothesis*>((*m_sortedHypos)[i]);
      recycler.Recycle(hypo);
    }
    m_sortedHypos->resize(stackSize);
  }

  /*
  cerr << "sorted hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
    const Hypothesis *hypo = hypos[i];
    cerr << hypo << " " << *hypo << endl;
  }
  cerr << endl;
  */

}

void MiniStack::Clear()
{
  m_sortedHypos = NULL;
  m_coll.clear();
}

///////////////////////////////////////////////////////////////
Stack::Stack(const Manager &mgr)
  :m_mgr(mgr)
  ,m_coll()
  ,m_miniStackRecycler()
{
}

Stack::~Stack()
{
  // TODO Auto-generated destructor stub
}

void Stack::Add(const Hypothesis *hypo, Recycler<Hypothesis*> &hypoRecycle)
{
  HypoCoverageInternal key = &hypo->GetBitmap();
  StackAdd added = GetMiniStack(key).Add(hypo);

  if (added.toBeDeleted) {
    hypoRecycle.Recycle(added.toBeDeleted);
  }
}

std::vector<const Hypothesis*> Stack::GetBestHypos(size_t num) const
{
  std::vector<const Hypothesis*> ret;
  BOOST_FOREACH(const Coll::value_type &val, m_coll) {
    const MiniStack::_HCType &hypos = val.second->GetColl();
    ret.insert(ret.end(), hypos.begin(), hypos.end());
  }

  std::vector<const Hypothesis*>::iterator iterMiddle;
  iterMiddle = (num == 0 || ret.size() < num)
               ? ret.end()
               : ret.begin()+num;

  std::partial_sort(ret.begin(), iterMiddle, ret.end(),
                    HypothesisFutureScoreOrderer());

  return ret;
}

size_t Stack::GetHypoSize() const
{
  size_t ret = 0;
  BOOST_FOREACH(const Coll::value_type &val, m_coll) {
    const MiniStack::_HCType &hypos = val.second->GetColl();
    ret += hypos.size();
  }
  return ret;
}

MiniStack &Stack::GetMiniStack(const HypoCoverageInternal &key)
{
  MiniStack *ret;
  Coll::iterator iter = m_coll.find(key);
  if (iter == m_coll.end()) {
    if (m_miniStackRecycler.empty()) {
      ret = new (m_mgr.GetPool().Allocate<MiniStack>()) MiniStack(m_mgr);
    } else {
      ret = m_miniStackRecycler.back();
      ret->Clear();
      m_miniStackRecycler.pop_back();
    }

    m_coll[key] = ret;
  } else {
    ret = iter->second;
  }
  return *ret;
}

void Stack::Clear()
{
  BOOST_FOREACH(const Coll::value_type &val, m_coll) {
    MiniStack *miniStack = val.second;
    m_miniStackRecycler.push_back(miniStack);
  }

  m_coll.clear();
}

Stack::SortedHypos Stack::GetSortedAndPruneHypos(const Manager &mgr) const
{
  SortedHypos ret;

  MemPool &pool = mgr.GetPool();

  // prune and sort
  Hypotheses *allHypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool, GetHypoSize());
  size_t i = 0;

  BOOST_FOREACH(const Coll::value_type &val, m_coll) {
    const MiniStack *miniStack = val.second;
    const MiniStack::MiniStack::_HCType &hypos = miniStack->GetColl();

    BOOST_FOREACH(const Hypothesis *hypo, hypos) {
      (*allHypos)[i++] = hypo;
    }
  }

  SortAndPruneHypos(mgr, *allHypos);

  // divide hypos by [bitmap, last end pos]
  BOOST_FOREACH(const Hypothesis *hypo, *allHypos) {
    HypoCoverage key(&hypo->GetBitmap(), hypo->GetInputPath().range.GetEndPos());

    Hypotheses *hypos;
    SortedHypos::iterator iter;
    iter = ret.find(key);
    if (iter == ret.end()) {
      hypos = new (pool.Allocate<Hypotheses>()) Hypotheses(pool);
      ret[key] = hypos;
    } else {
      hypos = iter->second;
    }
    hypos->push_back(hypo);
  }

  return ret;
}

void Stack::SortAndPruneHypos(const Manager &mgr, Hypotheses &hypos) const
{
  size_t stackSize = mgr.system.stackSize;
  Recycler<Hypothesis*> &recycler = mgr.GetHypoRecycle();

  /*
  cerr << "UNSORTED hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
    const Hypothesis *hypo = hypos[i];
    cerr << *hypo << endl;
  }
  cerr << endl;
  */
  Hypotheses::iterator iterMiddle;
  iterMiddle = (stackSize == 0 || hypos.size() < stackSize)
               ? hypos.end()
               : hypos.begin() + stackSize;

  std::partial_sort(hypos.begin(), iterMiddle, hypos.end(),
                    HypothesisFutureScoreOrderer());

  // prune
  if (stackSize && hypos.size() > stackSize) {
    for (size_t i = stackSize; i < hypos.size(); ++i) {
      Hypothesis *hypo = const_cast<Hypothesis*>(hypos[i]);
      recycler.Recycle(hypo);
    }
    hypos.resize(stackSize);
  }

  /*
  cerr << "sorted hypos:" << endl;
  for (size_t i = 0; i < hypos.size(); ++i) {
    const Hypothesis *hypo = hypos[i];
    cerr << hypo << " " << *hypo << endl;
  }
  cerr << endl;
  */

}

void Stack::DebugCounts()
{
  /*
  cerr << "counts=";
  BOOST_FOREACH(const Coll::value_type &val, GetColl()) {
  	const NSCubePruning::MiniStack &miniStack = *val.second;
  	size_t count = miniStack.GetColl().size();
  	cerr << count << " ";
  }
  cerr << endl;
  */
}

}

}

ext: cpp


text:
/*****************************************************************************
 * reduce.cpp     Blitz++ array reduction example
 *
 * This example illustrates the array reduction functions provided by
 * Blitz++.  These functions reduce an N dimensional array (or array
 * expression) to an N-1 dimensional array expression by summing, taking
 * the mean, etc.  These array reductions are currently provided: sum,
 * mean, min, max, minIndex, maxIndex, product, count, any and all.
 *****************************************************************************/

#include <blitz/array.h>

BZ_USING_NAMESPACE(blitz)

int main()
{
    Array<int, 2> A(4,4);

    A = 3,  1,  2,  4,
        8, -1, -5,  3,
        0,  9, -1,  4,
        1,  3,  1,  2;

    cout << "A = " << A << endl;

    /*
     * Reduce the array A to a one-dimensional array, by summing/taking
     * the mean/etc. of each row.
     */

    Array<int, 1> z(4);
    Array<float, 1> z2(4);
    secondIndex j;

    z = sum(A, j);
    cout << "sum(A,j) = " << endl << z << endl;

    z2 = mean(A, j);
    cout << "mean(A,j) = " << endl << z2 << endl;

    z = min(A, j);
    cout << "min(A,j) = " << endl << z << endl;

    z = minIndex(A, j);
    cout << "minIndex(A, j) = " << endl << z << endl;

    z = max(A, j);
    cout << "max(A, j) = " << endl << z << endl;

    z = maxIndex(A, j);
    cout << "maxIndex(A, j) = " << endl << z << endl;

    z = first((A < 0), j);
    cout << "first((A < 0), j) = " << endl << z << endl;

    z = product(A, j);
    cout << "product(A, j) = " << endl << z << endl;

    z = count( (A > 0), j);
    cout << "count((A > 0), j) = " << endl << z << endl;

    z = any((abs(A) > 4), j);
    cout << "any((abs(A) > 4), j) = " << endl << z << endl;

    z = all(A > 0, j);
    cout << "all(A > 0, j) = " << endl << z << endl;

    return 0;
}

/*
 * Output
 */
#if 0
A = 4 x 4
         3         1         2         4
         8        -1        -5         3
         0         9        -1         4
         1         3         1         2

sum(A,j) =
[         10         5        12         7 ]
mean(A,j) =
[        2.5      1.25         3      1.75 ]
min(A,j) =
[          1        -5        -1         1 ]
minIndex(A, j) =
[          1         2         2         0 ]
max(A, j) =
[          4         8         9         3 ]
maxIndex(A, j) =
[          3         0         1         1 ]
product(A, j) =
[         24       120         0         6 ]
count((A > 0), j) =
[          4         2         2         4 ]
any((abs(A) > 4), j) =
[          0         1         1         0 ]
all(A > 0, j) =
[          1         0         0         1 ]

#endif

max_stars_repo_name: fraguela/depspawn

max_issues_repo_name: MSV-Project/IBAMR

max_forks_repo_name: MSV-Project/IBAMR


text:
// Copyright Yamaha 2021
// MIT License
// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE

#ifndef CBR_CONTROL__INTEGRATOR_HPP_
#define CBR_CONTROL__INTEGRATOR_HPP_

#include <boost/hana/adapt_struct.hpp>

#include <cbr_utils/cyber_timer.hpp>

#include <memory>
#include <type_traits>
#include <utility>

namespace cbr
{

struct IntegratorParams
{
  bool saturate{false};
  double sat_min{-1.};
  double sat_max{1.};

  void check_correctness() const
  {
    if (sat_min > sat_max) {
      throw std::invalid_argument("sat_min must be less or equal to sat_max");
    }
  }
};

template<typename _clock_t = std::chrono::high_resolution_clock>
class Integrator
{
public:
  using clock_t = _clock_t;
  using timer_t = CyberTimerNoAvg<std::ratio<1>, double, clock_t>;

  Integrator() = default;
  Integrator(const Integrator &) = default;
  Integrator(Integrator &) = default;
  Integrator(Integrator &&) = default;
  Integrator & operator=(const Integrator &) = default;
  Integrator & operator=(Integrator &) = default;
  Integrator & operator=(Integrator &&) = default;
  ~Integrator() = default;

  template<typename T>
  explicit Integrator(T && clock, const IntegratorParams & prm = {}, const double valNm1 = 0.)
  : timer_(std::forward<T>(clock)),
    prm_(prm),
    valNm1_(valNm1)
  {
    prm_.check_correctness();
  }

  explicit Integrator(const IntegratorParams & prm, const double valNm1 = 0.)
  : prm_(prm),
    valNm1_(valNm1)
  {
    prm_.check_correctness();
  }

  template<typename T>
  Integrator(T && clock, const double valNm1)
  : timer_(std::forward<T>(clock)),
    valNm1_(valNm1)
  {}

  explicit Integrator(const double valNm1)
  : valNm1_(valNm1)
  {}

  template<typename T>
  void set_clock(T && clock)
  {
    timer_.set_clock(std::forward<T>(clock));
  }

  void set_params(const IntegratorParams & prm)
  {
    prm.check_correctness();
    prm_ = prm;
  }

  const IntegratorParams & get_params() const
  {
    return prm_;
  }

  const double & update(const double val, const typename timer_t::time_point tNow)
  {
    if (init_) {
      const double dt = timer_.toctic(tNow);

      valNm1_ += dt * val;

      if (prm_.saturate) {
        valNm1_ = std::clamp(valNm1_, prm_.sat_min, prm_.sat_max);
      }
    }

    init_ = true;
    timer_.tic(tNow);
    return valNm1_;
  }

  const double & update(const double val)
  {
    return update(val, timer_.now());
  }

  const double & operator()(const double val)
  {
    return update(val);
  }

  const double & getValue() const
  {
    return valNm1_;
  }

  const double & reset(const double val, const typename timer_t::time_point tNow)
  {
    valNm1_ = val;
    if (prm_.saturate) {
      valNm1_ = std::clamp(valNm1_, prm_.sat_min, prm_.sat_max);
    }
    timer_.tic(tNow);
    init_ = true;
    return valNm1_;
  }

  const double & reset(const typename timer_t::time_point tNow)
  {
    return reset(0., tNow);
  }

  const double & reset(const double val)
  {
    return reset(val, timer_.now());
  }

  const double & reset()
  {
    return reset(0., timer_.now());
  }

protected:
  timer_t timer_ = timer_t(clock_t{});
  IntegratorParams prm_;
  double valNm1_ = 0.;
  bool init_{false};
};

}  // namespace cbr

// cppcheck-suppress unknownMacro
BOOST_HANA_ADAPT_STRUCT(
  cbr::IntegratorParams,
  saturate,
  sat_min,
  sat_max
);

#endif  // CBR_CONTROL__INTEGRATOR_HPP_

ext: hpp


text:
/////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga  2006-2013
//
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_INTRUSIVE_ANY_HOOK_HPP
#define BOOST_INTRUSIVE_ANY_HOOK_HPP

#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/intrusive_fwd.hpp>
#include <boost/intrusive/detail/any_node_and_algorithms.hpp>
#include <boost/intrusive/options.hpp>
#include <boost/intrusive/detail/generic_hook.hpp>
#include <boost/intrusive/detail/mpl.hpp>
#include <boost/intrusive/pointer_rebind.hpp>

#if defined(BOOST_HAS_PRAGMA_ONCE)
#  pragma once
#endif

namespace boost {
namespace intrusive {

//! Helper metafunction to define a \c \c any_base_hook that yields to the same
//! type when the same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1 = void, class O2 = void, class O3 = void>
#endif
struct make_any_base_hook
{
   /// @cond
   typedef typename pack_options
      < hook_defaults,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3
      #else
      Options...
      #endif
      >::type packed_options;

   typedef generic_hook
   < any_algorithms<typename packed_options::void_pointer>
   , typename packed_options::tag
   , packed_options::link_mode
   , AnyBaseHookId
   > implementation_defined;
   /// @endcond
   typedef implementation_defined type;
};

//! Derive a class from this hook in order to store objects of that class
//! in an intrusive container.
//!
//! The hook admits the following options: \c tag<>, \c void_pointer<> and
//! \c link_mode<>.
//!
//! \c tag<> defines a tag to identify the node.
//! The same tag value can be used in different classes, but if a class is
//! derived from more than one \c any_base_hook, then each \c any_base_hook needs its
//! unique tag.
//!
//! \c link_mode<> will specify the linking mode of the hook (\c normal_link, \c safe_link).
//!
//! \c void_pointer<> is the pointer type that will be used internally in the hook
//! and the container configured to use this hook.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1, class O2, class O3>
#endif
class any_base_hook
   :  public make_any_base_hook
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      <O1, O2, O3>
      #else
      <Options...>
      #endif
      ::type
{
   #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
   public:
   //! Effects: If link_mode is or \c safe_link
   //!   initializes the node to an unlinked state.
   //!
   //! Throws: Nothing.
   any_base_hook();

   //! Effects: If link_mode is or \c safe_link
   //!   initializes the node to an unlinked state. The argument is ignored.
   //!
   //! Throws: Nothing.
   //!
   //! Rationale: Providing a copy-constructor
   //!   makes classes using the hook STL-compliant without forcing the
   //!   user to do some additional work. \c swap can be used to emulate
   //!   move-semantics.
   any_base_hook(const any_base_hook& );

   //! Effects: Empty function. The argument is ignored.
   //!
   //! Throws: Nothing.
   //!
   //! Rationale: Providing an assignment operator
   //!   makes classes using the hook STL-compliant without forcing the
   //!   user to do some additional work. \c swap can be used to emulate
   //!   move-semantics.
   any_base_hook& operator=(const any_base_hook& );

   //! Effects: If link_mode is \c normal_link, the destructor does
   //!   nothing (ie. no code is generated). If link_mode is \c safe_link and the
   //!   object is stored in a container an assertion is raised.
   //!
   //! Throws: Nothing.
   ~any_base_hook();

   //! Precondition: link_mode must be \c safe_link.
   //!
   //! Returns: true, if the node belongs to a container, false
   //!   otherwise. This function can be used to test whether \c container::iterator_to
   //!   will return a valid iterator.
   //!
   //! Complexity: Constant
   bool is_linked() const;
   #endif
};

//! Helper metafunction to define a \c \c any_member_hook that yields to the same
//! type when the same options (either explicitly or implicitly) are used.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1 = void, class O2 = void, class O3 = void>
#endif
struct make_any_member_hook
{
   /// @cond
   typedef typename pack_options
      < hook_defaults,
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      O1, O2, O3
      #else
      Options...
      #endif
      >::type packed_options;

   typedef generic_hook
   < any_algorithms<typename packed_options::void_pointer>
   , member_tag
   , packed_options::link_mode
   , NoBaseHookId
   > implementation_defined;
   /// @endcond
   typedef implementation_defined type;
};

//! Store this hook in a class to be inserted
//! in an intrusive container.
//!
//! The hook admits the following options: \c void_pointer<> and
//! \c link_mode<>.
//!
//! \c link_mode<> will specify the linking mode of the hook (\c normal_link or \c safe_link).
//!
//! \c void_pointer<> is the pointer type that will be used internally in the hook
//! and the container configured to use this hook.
#if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
template<class ...Options>
#else
template<class O1, class O2, class O3>
#endif
class any_member_hook
   :  public make_any_member_hook
      #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES)
      <O1, O2, O3>
      #else
      <Options...>
      #endif
      ::type
{
   #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED)
   public:
   //! Effects: If link_mode is or \c safe_link
   //!   initializes the node to an unlinked state.
   //!
   //! Throws: Nothing.
   any_member_hook();

   //! Effects: If link_mode is or \c safe_link
   //!   initializes the node to an unlinked state. The argument is ignored.
   //!
   //! Throws: Nothing.
   //!
   //! Rationale: Providing a copy-constructor
   //!   makes classes using the hook STL-compliant without forcing the
   //!   user to do some additional work. \c swap can be used to emulate
   //!   move-semantics.
   any_member_hook(const any_member_hook& );

   //! Effects: Empty function. The argument is ignored.
   //!
   //! Throws: Nothing.
   //!
   //! Rationale: Providing an assignment operator
   //!   makes classes using the hook STL-compliant without forcing the
   //!   user to do some additional work. \c swap can be used to emulate
   //!   move-semantics.
   any_member_hook& operator=(const any_member_hook& );

   //! Effects: If link_mode is \c normal_link, the destructor does
   //!   nothing (ie. no code is generated). If link_mode is \c safe_link and the
   //!   object is stored in a container an assertion is raised.
   //!
   //! Throws: Nothing.
   ~any_member_hook();

   //! Precondition: link_mode must be \c safe_link.
   //!
   //! Returns: true, if the node belongs to a container, false
   //!   otherwise. This function can be used to test whether \c container::iterator_to
   //!   will return a valid iterator.
   //!
   //! Complexity: Constant
   bool is_linked() const;
   #endif
};

/// @cond

namespace detail{

BOOST_INTRUSIVE_INTERNAL_STATIC_BOOL_IS_TRUE(old_proto_value_traits_base_hook, hooktags::is_base_hook)

//!This option setter specifies that the container
//!must use the specified base hook
template<class BasicHook, template <class> class NodeTraits>
struct any_to_some_hook
{
   typedef typename BasicHook::template pack<empty>::proto_value_traits old_proto_value_traits;

   template<class Base>
   struct pack : public Base
   {
      struct proto_value_traits
      {
         //proto_value_traits::hooktags::is_base_hook is used by get_value_traits
         //to detect base hooks, so mark it in case BasicHook has it.
         struct hooktags
         {
            static const bool is_base_hook = old_proto_value_traits_base_hook_bool_is_true
               <old_proto_value_traits>::value;
         };

         typedef old_proto_value_traits basic_hook_t;
         static const bool is_any_hook = true;

         template<class VoidPtr>
         struct node_traits_from_voidptr
         {  typedef NodeTraits<VoidPtr> type;  };
      };
   };
};

}  //namespace detail{

/// @endcond

//!This option setter specifies that
//!any hook should behave as an slist hook
template<class BasicHook>
struct any_to_slist_hook
/// @cond
   :  public detail::any_to_some_hook<BasicHook, any_slist_node_traits>
/// @endcond
{};

//!This option setter specifies that
//!any hook should behave as an list hook
template<class BasicHook>
struct any_to_list_hook
/// @cond
   :  public detail::any_to_some_hook<BasicHook, any_list_node_traits>
/// @endcond
{};

//!This option setter specifies that
//!any hook should behave as a set hook
template<class BasicHook>
struct any_to_set_hook
/// @cond
   :  public detail::any_to_some_hook<BasicHook, any_rbtree_node_traits>
/// @endcond
{};

//!This option setter specifies that
//!any hook should behave as an avl_set hook
template<class BasicHook>
struct any_to_avl_set_hook
/// @cond
   :  public detail::any_to_some_hook<BasicHook, any_avltree_node_traits>
/// @endcond
{};

//!This option setter specifies that any
//!hook should behave as a bs_set hook
template<class BasicHook>
struct any_to_bs_set_hook
/// @cond
   :  public detail::any_to_some_hook<BasicHook, any_tree_node_traits>
/// @endcond
{};

//!This option setter specifies that any hook
//!should behave as an unordered set hook
template<class BasicHook>
struct any_to_unordered_set_hook
/// @cond
   :  public detail::any_to_some_hook<BasicHook, any_unordered_node_traits>
/// @endcond
{};

} //namespace intrusive
} //namespace boost

#include <boost/intrusive/detail/config_end.hpp>

#endif //BOOST_INTRUSIVE_ANY_HOOK_HPP

max_stars_repo_name: LazyPlanet/MX-Client

max_issues_repo_name: LazyPlanet/MX-Client

max_forks_repo_name: LazyPlanet/MX-Client


text:
#include <boost/python.hpp>
#include <boost/python/stl_iterator.hpp>

#include <onmt/Tokenizer.h>

namespace py = boost::python;

template <typename T>
static std::vector<T> to_std_vector(const py::object& iterable)
{
  return std::vector<T>(py::stl_input_iterator<T>(iterable),
                        py::stl_input_iterator<T>());
}

template <typename T>
static py::list to_py_list(const std::vector<T> vec)
{
  py::list list;
  for (const auto& elem : vec)
    list.append(elem);
  return list;
}

typedef std::vector<std::string> StringVec;

class TokenizerWrapper
{
public:
  TokenizerWrapper(const std::string& mode,
                   const std::string& bpe_model_path,
                   const std::string& joiner,
                   bool joiner_annotate,
                   bool joiner_new,
                   bool case_feature,
                   bool no_substitution,
                   bool segment_case,
                   bool segment_numbers,
                   bool segment_alphabet_change,
                   py::list segment_alphabet)
  {
    int flags = 0;
    if (joiner_annotate)
      flags |= onmt::Tokenizer::Flags::JoinerAnnotate;
    if (joiner_new)
      flags |= onmt::Tokenizer::Flags::JoinerNew;
    if (case_feature)
      flags |= onmt::Tokenizer::Flags::CaseFeature;
    if (no_substitution)
      flags |= onmt::Tokenizer::Flags::NoSubstitution;
    if (segment_case)
      flags |= onmt::Tokenizer::Flags::SegmentCase;
    if (segment_numbers)
      flags |= onmt::Tokenizer::Flags::SegmentNumbers;
    if (segment_alphabet_change)
      flags |= onmt::Tokenizer::Flags::SegmentAlphabetChange;

    _tokenizer = new onmt::Tokenizer(onmt::Tokenizer::mapMode.at(mode),
                                     flags, bpe_model_path, joiner);

    for (auto it = py::stl_input_iterator<std::string>(segment_alphabet);
         it != py::stl_input_iterator<std::string>(); it++)
      dynamic_cast<onmt::Tokenizer*>(_tokenizer)->add_alphabet_to_segment(*it);
  }

  ~TokenizerWrapper()
  {
    delete _tokenizer;
  }

  py::tuple tokenize(const std::string& text)
  {
    std::vector<std::string> words;
    std::vector<std::vector<std::string> > features;

    _tokenizer->tokenize(text, words, features);

    py::list words_list = to_py_list(words);

    if (features.empty())
      return py::make_tuple(words_list, py::object());
    else
    {
      std::vector<py::list> features_tmp;
      for (const auto& feature : features)
        features_tmp.push_back(to_py_list(feature));

      return py::make_tuple(words_list, to_py_list(features_tmp));
    }
  }

  std::string detokenize(const py::object& words, const py::object& features)
  {
    std::vector<std::string> words_vec = to_std_vector<std::string>(words);
    std::vector<std::vector<std::string> > features_vec;

    if (features != py::object())
    {
      for (auto it = py::stl_input_iterator<py::list>(features);
           it != py::stl_input_iterator<py::list>(); it++)
        features_vec.push_back(to_std_vector<std::string>(*it));
    }

    return _tokenizer->detokenize(words_vec, features_vec);
  }

private:
  onmt::ITokenizer* _tokenizer;
};

BOOST_PYTHON_MODULE(pyonmttok)
{
  py::class_<TokenizerWrapper>(
      "Tokenizer",
      py::init<std::string, std::string, std::string, bool, bool, bool, bool, bool, bool, bool, py::list>(
        (py::arg("bpe_model_path")="",
         py::arg("joiner")=onmt::Tokenizer::joiner_marker,
         py::arg("joiner_annotate")=false,
         py::arg("joiner_new")=false,
         py::arg("case_feature")=false,
         py::arg("no_substitution")=false,
         py::arg("segment_case")=false,
         py::arg("segment_numbers")=false,
         py::arg("segment_alphabet_change")=false,
         py::arg("segment_alphabet")=py::list())))
    .def("tokenize", &TokenizerWrapper::tokenize)
    .def("detokenize", &TokenizerWrapper::detokenize, (py::arg("features")=py::object()))
    ;
}

ext: cc

max_stars_repo_name: monsieurzhang/Tokenizer

max_issues_repo_name: monsieurzhang/Tokenizer

max_forks_repo_name: monsieurzhang/Tokenizer


text:
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <boost/scope_exit.hpp>
#include <fcntl.h>
#include <iostream>
#include <memory>
#include <string>
#include <sys/mman.h>
#include <sys/stat.h>

#include "PositionMap.h"

std::unique_ptr<PositionMap> read_map(const char* filename) {
  int fd = open(filename, O_RDONLY);
  if (fd == -1) {
    std::cerr << "open failed for file (" << filename
              << ") with error: " << strerror(errno) << std::endl;
    return nullptr;
  }
  struct stat buf;
  if (fstat(fd, &buf)) {
    std::cerr << "Cannot fstat file (" << filename
              << ") with error: " << strerror(errno) << std::endl;
    return nullptr;
  }
  uint8_t* mapping = (uint8_t*)mmap(
      nullptr, buf.st_size, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0);
  uint32_t magic = *(uint32_t*)mapping;
  mapping += sizeof(uint32_t);
  if (mapping == MAP_FAILED) {
    std::cerr << "mmap failed for file (" << filename
              << ") with error: " << strerror(errno) << std::endl;
    return nullptr;
  }
  BOOST_SCOPE_EXIT_ALL(=, &buf) {
    munmap(mapping, buf.st_size);
  };
  if (magic != 0xfaceb000) {
    std::cerr << "Magic number mismatch\n";
    return nullptr;
  }
  uint32_t version = *(uint32_t*)mapping;
  mapping += sizeof(uint32_t);
  if (version != 2) {
    std::cerr << "Version mismatch\n";
    return nullptr;
  }

  std::unique_ptr<PositionMap> map(new PositionMap());
  std::vector<std::string> string_pool;
  uint32_t spool_count = *(uint32_t*)mapping;
  mapping += sizeof(uint32_t);
  for (uint32_t i = 0; i < spool_count; ++i) {
    uint32_t ssize = *(uint32_t*)mapping;
    mapping += sizeof(uint32_t);
    map->string_pool.emplace_back((const char*)mapping, ssize);
    mapping += ssize;
  }
  uint32_t pos_count = *(uint32_t*)mapping;
  mapping += sizeof(uint32_t);
  map->positions.reset(new PositionItem[pos_count]);
  map->positions_size = pos_count;
  memcpy(map->positions.get(), mapping, pos_count * sizeof(PositionItem));
  return map;
}

std::vector<Position> get_stack(const PositionMap& map, int64_t idx) {
  std::vector<Position> stack;
  while (idx >= 0 && (size_t)idx < map.positions_size) {
    auto pi = map.positions[idx];
    stack.push_back(Position(map.string_pool[pi.class_id],
                             map.string_pool[pi.method_id],
                             map.string_pool[pi.file_id],
                             pi.line));
    idx = (int64_t)pi.parent - 1;
  }
  return stack;
}

max_stars_repo_name: parind/redex

max_issues_repo_name: parind/redex

max_forks_repo_name: parind/redex


text:
/******************************************************************************
 * Software License Agreement (BSD License)
 *
 * Copyright (c) 2016, Michal Drwiega (drwiega.michal@gmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     1. Redistributions of source code must retain the above copyright
 *        notice, this list of conditions and the following disclaimer.
 *     2. 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.
 *     3. Neither the name of the copyright holder nor the names of its
 *        contributors may 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
 * HOLDER 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.
 *****************************************************************************/
/**
 * @file   laserscan_kinect_node.cpp
 * @author Michal Drwiega (drwiega.michal@gmail.com)
 * @brief  laserscan_kinect package
 */

#include <laserscan_kinect/laserscan_kinect_node.h>
#include <boost/bind.hpp>

namespace laserscan_kinect {

//=================================================================================================
LaserScanKinectNode::LaserScanKinectNode(ros::NodeHandle& n, ros::NodeHandle& pnh) :
    pnh_(pnh), it_(n), srv_(pnh)
{
    std::lock_guard<std::mutex> lock(connect_mutex_);

    // Dynamic reconfigure server callback
    srv_.setCallback(boost::bind(&LaserScanKinectNode::reconfigureCb, this, _1, _2));

    // Subscription to depth image topic
    pub_ = n.advertise<sensor_msgs::LaserScan>("scan", 10,
                                               boost::bind(&LaserScanKinectNode::connectCb, this, _1),
                                               boost::bind(&LaserScanKinectNode::disconnectCb, this, _1));
}

//=================================================================================================
LaserScanKinectNode::~LaserScanKinectNode()
{
    sub_.shutdown();
}

//=================================================================================================
void LaserScanKinectNode::depthCb(const sensor_msgs::ImageConstPtr& depth_msg,
                                  const sensor_msgs::CameraInfoConstPtr& info_msg)
{
    try
    {
        sensor_msgs::LaserScanPtr laserscan_msg = converter_.getLaserScanMsg(depth_msg, info_msg);
        pub_.publish(laserscan_msg);
    }
    catch (std::runtime_error& e)
    {
        ROS_ERROR_THROTTLE(1.0, "Could not convert depth image to laserscan: %s", e.what());
    }
}

//=================================================================================================
void LaserScanKinectNode::connectCb(const ros::SingleSubscriberPublisher& pub)
{
    std::lock_guard<std::mutex> lock(connect_mutex_);

    if (!sub_ && pub_.getNumSubscribers() > 0)
    {
        ROS_DEBUG("Connecting to depth topic.");
        image_transport::TransportHints hints("raw", ros::TransportHints(), pnh_);
        sub_ = it_.subscribeCamera("image", 10, &LaserScanKinectNode::depthCb, this, hints);
    }
}

//=================================================================================================
void LaserScanKinectNode::disconnectCb(const ros::SingleSubscriberPublisher& pub)
{
    std::lock_guard<std::mutex> lock(connect_mutex_);

    if (pub_.getNumSubscribers() == 0)
    {
        ROS_DEBUG("Unsubscribing from depth topic.");
        sub_.shutdown();
    }
}

//=================================================================================================
void LaserScanKinectNode::reconfigureCb(laserscan_kinect::LaserscanKinectConfig& config,
                                        uint32_t level)
{
    converter_.setOutputFrame(config.output_frame_id);
    converter_.setRangeLimits(config.range_min, config.range_max);
    converter_.setScanHeight(config.scan_height);
    converter_.setDepthImgRowStep(config.depth_img_row_step);
    converter_.setCamModelUpdate(config.cam_model_update);

    converter_.setSensorMountHeight(config.sensor_mount_height);
    converter_.setSensorTiltAngle(config.sensor_tilt_angle);
    converter_.setGroundRemove(config.ground_remove_en);
    converter_.setGroundMargin(config.ground_margin);
    converter_.setTiltCompensation(config.tilt_compensation_en);

    converter_.setScanConfigurated(false);
}

//=================================================================================================
} // end of namespace


text:
#include "gcc.hpp"

#include <bunsan/static_initializer.hpp>

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

#include <unordered_map>

namespace bacs {
namespace system {
namespace builders {

namespace {
struct invalid_lang_error : virtual invalid_argument_error {};
}  // namespace

BUNSAN_STATIC_INITIALIZER(bacs_system_builders_gcc, {
  BUNSAN_FACTORY_REGISTER_TOKEN(builder, gcc,
                                [](const std::vector<std::string> &arguments) {
                                  return builder::make_shared<gcc>(arguments);
                                })
})

static const boost::regex positional("[^=]+"), key_value("([^=]+)=(.*)");

gcc::gcc(const std::vector<std::string> &arguments) : m_executable("gcc") {
  for (const std::string &arg : arguments) {
    boost::smatch match;
    if (boost::regex_match(arg, match, positional)) {
      BOOST_ASSERT(match.size() == 1);
      m_flags.push_back("-" + arg);
    } else if (boost::regex_match(arg, match, key_value)) {
      BOOST_ASSERT(match.size() == 3);
      const std::string key = match[1].str(), value = match[2].str();
      if (key == "optimize") {
        m_flags.push_back("-O" + value);
      } else if (key == "lang") {
        static const std::unordered_map<std::string, std::string> langs = {
            {"c", "gcc"},
            {"c++", "g++"},
            {"objective-c", "gcc"},    // TODO unchecked
            {"objective-c++", "g++"},  // TODO unchecked
            {"f77", "gfortran"},
            {"f95", "gfortran"},
            {"go", "gccgo"}};
        const auto iter = langs.find(value);
        if (iter == langs.end())
          BOOST_THROW_EXCEPTION(invalid_lang_error()
                                << invalid_lang_error::argument(value));
        m_executable = iter->second;
        m_flags.push_back("-x");
        m_flags.push_back(value);
      } else if (key == "std") {
        m_flags.push_back("-std=" + value);
      } else {
        BOOST_THROW_EXCEPTION(invalid_argument_error()
                              << invalid_argument_error::argument(arg));
      }
    } else {
      BOOST_THROW_EXCEPTION(invalid_argument_error()
                            << invalid_argument_error::argument(arg));
    }
  }
}

ProcessPointer gcc::create_process(const ProcessGroupPointer &process_group,
                                   const name_type &name) {
  const ProcessPointer process = process_group->createProcess(m_executable);
  process->setArguments(process->executable(), m_flags, name.source, "-o",
                        name.executable);
  return process;
}

}  // namespace builders
}  // namespace system
}  // namespace bacs


text:
#include <boost/algorithm/string.hpp>

#include "cover.hpp"
#include "parse.hpp"

ClosedRectangleQ load_square(const std::string& dir) {

    auto line = read_file(dir + "/square.txt");
    boost::trim(line);

    const auto coords = split(line, " ");

    if (coords.size() != 4) {
        std::ostringstream err{};
        err << "load_square: expected 4 coordinates, got " << coords.size();
        throw std::runtime_error(err.str());
    }

    const Rational x_min{coords.at(0)};
    const Rational x_max{coords.at(1)};

    const Rational y_min{coords.at(2)};
    const Rational y_max{coords.at(3)};

    const ClosedRectangleQ square{{x_min, x_max}, {y_min, y_max}};

    if (!square.is_square()) {
        throw std::runtime_error("load_square: not a square");
    }

    return square;
}

OpenConvexPolygonQ load_polygon(const std::string& dir) {

    auto polygon_str = read_file(dir + "/polygon.txt");
    boost::trim(polygon_str);

    std::vector<PointQ> vertices{};

    const auto lines = split(polygon_str, "\n");

    for (const auto& line : lines) {

        const auto coords = split(line, " ");

        if (coords.size() != 2) {
            std::ostringstream err{};
            err << "load_polygon: expected 2 coordinates, got " << coords.size();
            throw std::runtime_error(err.str());
        }

        const Rational x{coords.at(0)};
        const Rational y{coords.at(1)};

        vertices.emplace_back(x, y);
    }

    return OpenConvexPolygonQ{vertices};
}

std::vector<CodePair> load_singles(const std::string& dir) {

    // TODO rename to singles.txt
    auto singles_str = read_file(dir + "/stables.txt");
    boost::trim(singles_str);

    auto lines = split(singles_str, "\n");

    std::vector<CodePair> singles{};

    size_t i = 0;
    for (auto& line : lines) {

        // Makes it easier to parse
        boost::algorithm::replace_first(line, ":", ",");

        auto comps = split(line, ",");

        if (comps.size() != 3) {
            std::ostringstream err{};
            err << "load_singles: expected 3 components, got " << comps.size();
            throw std::runtime_error(err.str());
        }

        for (auto& str : comps) {
            boost::trim(str);
        }

        const auto index = boost::lexical_cast<size_t>(comps.at(0));
        const auto stable = parse_code_sequence(comps.at(1));
        const auto initial_angles = parse_initial_angles(comps.at(2));

        // The indices must be in order
        if (index != i) {
            std::ostringstream err{};
            err << "load_singles: mismatched indices: expected " << i << ", got " << index;
            throw std::runtime_error(err.str());
        }

        singles.emplace_back(stable, initial_angles);

        ++i;
    }

    return singles;
}

std::vector<TriplePair> load_triples(const std::string& dir) {

    auto triples_str = read_file(dir + "/triples.txt");
    boost::trim(triples_str);

    std::vector<TriplePair> triples{};

    auto lines = split(triples_str, "\n");

    size_t i = 0;
    for (auto& line : lines) {

        // Makes it easier to parse
        boost::algorithm::replace_first(line, ":", ",");
        boost::algorithm::replace_all(line, ";", ",");

        auto comps = split(line, ",");

        if (comps.size() != 7) {
            std::ostringstream err{};
            err << "load_triples: expected 7 components, got " << comps.size();
            throw std::runtime_error(err.str());
        }

        for (auto& str : comps) {
            boost::trim(str);
        }

        const auto index = boost::lexical_cast<size_t>(comps.at(0));

        const auto stable_neg_sequence = parse_code_sequence(comps.at(1));
        const auto stable_neg_angles = parse_initial_angles(comps.at(2));

        const auto unstable_sequence = parse_code_sequence(comps.at(3));
        const auto unstable_angles = parse_initial_angles(comps.at(4));

        const auto stable_pos_sequence = parse_code_sequence(comps.at(5));
        const auto stable_pos_angles = parse_initial_angles(comps.at(6));

        // The indices must be in order
        if (index != i) {
            std::ostringstream err{};
            err << "load_triples: mismatched indices: expected " << i << ", got " << index;
            throw std::runtime_error(err.str());
        }

        const CodePair stable_neg{stable_neg_sequence, stable_neg_angles};
        const CodePair unstable{unstable_sequence, unstable_angles};
        const CodePair stable_pos{stable_pos_sequence, stable_pos_angles};

        triples.emplace_back(stable_neg, unstable, stable_pos);

        ++i;
    }

    return triples;
}

template <typename It>
class Iterator final {

  private:
    It current;
    It end;

  public:
    explicit Iterator(const It start, const It end_)
        : current{start}, end{end_} {}

    const typename std::iterator_traits<It>::value_type& next() {
        if (current == end) {
            throw std::runtime_error("Iterator::next: iterator out of range");
        } else {
            return *current++;
        }
    }
};

static cover::Cover parse_cover(Iterator<std::vector<std::string>::const_iterator>& iter) {

    const auto& token = iter.next();

    if (token == "E") {
        return cover::Empty{};
    } else if (token == "S") {

        const auto& str = iter.next();
        const auto index = boost::lexical_cast<size_t>(str);

        return cover::Single{index};
    } else if (token == "T") {

        const auto& str = iter.next();
        const auto index = boost::lexical_cast<size_t>(str);

        return cover::Triple{index};
    } else if (token == "D") {

        auto cover0 = parse_cover(iter);
        auto cover1 = parse_cover(iter);
        auto cover2 = parse_cover(iter);
        auto cover3 = parse_cover(iter);

        return cover::Divide{std::move(cover0), std::move(cover1), std::move(cover2), std::move(cover3)};

    } else {
        throw std::runtime_error("parse_cover: unknown token: " + token);
    }
}

cover::Cover load_cover(const std::string& dir) {

    auto str = read_file(dir + "/cover.txt");
    boost::trim(str);

    const auto vec = split(str, " ");

    Iterator<std::vector<std::string>::const_iterator> iter{std::cbegin(vec), std::cend(vec)};

    return parse_cover(iter);
}

uint32_t load_digits(const std::string& dir) {

    // TODO change this to digits.txt
    auto str = read_file(dir + "/precision.txt");
    boost::trim(str);

    return boost::lexical_cast<uint32_t>(str);
}

max_stars_repo_name: wadymwadim/normandeau

max_issues_repo_name: wadymwadim/normandeau

max_forks_repo_name: wadymwadim/normandeau


text:
/*--------STD-------------*/
#include <sstream>

/*-----------BOOST TEST SUITE-------------*/
#define BOOST_TEST_MODULE sot_dynamic_constructor
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/output_test_stream.hpp>

/*-----------SOT DYNAMIC ------------*/
#include <sot/dynamic-pinocchio/dynamic-pinocchio.h>
#include <sot/core/debug.hh>

/*-----------DYNAMIC GRAPH ------------*/
#include <dynamic-graph/linear-algebra.h>
#include <sot/core/exception-abstract.hh>

/*-----------PINOCCHIO-------------*/
#include <pinocchio/multibody/model.hpp>
#include <pinocchio/parsers/urdf.hpp>

using namespace dynamicgraph::sot;

/* ----- TEST SIGNAL CLASS -----*/

BOOST_AUTO_TEST_CASE(constructor) {
  /*-----------------------CONSTRUCTOR-----------------------------------------*/
  DynamicPinocchio dynamic_("sot_dynamic_test");
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.jointPositionSIN.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::input(vector)::position"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.freeFlyerPositionSIN.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::input(vector)::ffposition"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.jointVelocitySIN.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::input(vector)::velocity"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.freeFlyerVelocitySIN.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::input(vector)::ffvelocity"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.jointAccelerationSIN.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::input(vector)::acceleration"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.freeFlyerAccelerationSIN.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::input(vector)::ffacceleration"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.newtonEulerSINTERN.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::intern(dummy)::newtoneuler"),
                    0);
  BOOST_CHECK_EQUAL(
      std::strcmp(dynamic_.zmpSOUT.getName().c_str(), "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::zmp"),
      0);
  BOOST_CHECK_EQUAL(
      std::strcmp(dynamic_.JcomSOUT.getName().c_str(), "sotDynamicPinocchio(sot_dynamic_test)::output(matrix)::Jcom"),
      0);
  BOOST_CHECK_EQUAL(
      std::strcmp(dynamic_.comSOUT.getName().c_str(), "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::com"),
      0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.inertiaSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(matrix)::inertia"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.footHeightSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(double)::footHeight"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.upperJlSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::upperJl"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.lowerJlSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::lowerJl"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.upperVlSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::upperVl"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.upperTlSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::upperTl"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.inertiaRotorSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(matrix)::inertiaRotor"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.MomentaSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::momenta"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.AngularMomentumSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::angularmomentum"),
                    0);
  BOOST_CHECK_EQUAL(std::strcmp(dynamic_.dynamicDriftSOUT.getName().c_str(),
                                "sotDynamicPinocchio(sot_dynamic_test)::output(vector)::dynamicDrift"),
                    0);
}

max_stars_repo_name: jmirabel/sot-dynamic-pinocchio

max_issues_repo_name: jmirabel/sot-dynamic-pinocchio

max_forks_repo_name: jmirabel/sot-dynamic-pinocchio


text:
#include "middleware_delayer.h"
#include <boost/asio.hpp>
#include "logger/logger.h"

namespace Middleware
{

Delayer::Delayer(boost::asio::io_context& ioc) : ioc(ioc)
{
    logger = Logger::get("Middleware.Delayer");
}

void Delayer::operator()(Session&& session, std::shared_ptr<Chain> chain)
{
    logger->info("Processing {}", session.req);

    auto timer = std::make_shared<boost::asio::steady_timer>(ioc);

    auto self = shared_from_this();

    // respond after timer fires
    timer->expires_after(std::chrono::seconds(1));
    timer->async_wait([self, this, timer, session{std::move(session)}, chain]
                      (const boost::system::error_code&) mutable
        {
            logger->info("Async Delay Completed {}", session.req);

            session.resp.status(Stalk::Status::ok)
                .set("test-header", "test-header-value");

            // Move to the next middleware
            chain->process(std::move(session));
        });
}

} // namespace Middleware

max_stars_repo_name: pykel/stalk-api-example

max_issues_repo_name: pykel/stalk-api-example

max_forks_repo_name: pykel/stalk-api-example


text:
// Copyright Matt Overby 2022.
// Distributed under the MIT License.

#ifndef MCL_EIGENMAP_HPP
#define MCL_EIGENMAP_HPP 1

#include <Eigen/Dense>
#include <stdexcept>

namespace mcl
{

template <typename DerivedM, typename DerivedV>
static inline void mat_to_vec(
    const Eigen::PlainObjectBase<DerivedM> &M,
    Eigen::PlainObjectBase<DerivedV> &V)
{
    typedef typename Eigen::PlainObjectBase<DerivedM>::Scalar Scalar;
    int nr = M.rows();
    int nc = M.cols();
    if (V.size() != nr*nc) {
        V.resize(nr*nc);
    }

    if (M.derived().IsRowMajor)
    {
        V = Eigen::Map<DerivedV>((Scalar*)M.data(), M.size());
        return;
    }

    for (int c=0; c<nc; ++c) {
        for (int r=0; r<nr; ++r) {
            V[r*nc+c] = M(r,c);
        }
    }
}

// Matrix must be sized ahead of time
template <typename DerivedM, typename DerivedV>
static inline void vec_to_mat(
    const Eigen::PlainObjectBase<DerivedV> &V,
    Eigen::PlainObjectBase<DerivedM> &M)
{
    typedef typename Eigen::PlainObjectBase<DerivedV>::Scalar Scalar;
    if (M.cols()<1 || M.size() != V.size()) {
        throw std::runtime_error("mcl::vec_to_mat: M not correct size");
    }

    if (M.derived().IsRowMajor)
    {
        M = Eigen::Map<DerivedM>((Scalar*)V.data(), M.rows(), M.cols());
        return;
    }

    // Column major, need loop.
    int nr = M.rows();
    int nc = M.cols();
    for (int c=0; c<nc; ++c) {
        for (int r=0; r<nr; ++r) {
            M(r,c) = V[r*nc+c];
        }
    }
}

} // ns mcl

#endif

max_stars_repo_name: mattoverby/mclgeom

max_issues_repo_name: mattoverby/mclgeom

max_forks_repo_name: mattoverby/mclgeom


text:
//
// This runs the testing logic.
//
#define BOOST_TEST_MODULE CUDATest
#define EPSILON 0.001
#include "../CUDA/AFCUDA.h"
#include <boost/test/included/unit_test.hpp>
#include "TestCUDAMathExtensions.h"
#include "TestCUDACurve.h"
#include "TestCUDAResult.h"
#include "TestCUDABSOptionValuation.h"

max_stars_repo_name: adamjoshuagray/AcceleratedFinance

max_issues_repo_name: adamjoshuagray/AcceleratedFinance

max_forks_repo_name: adamjoshuagray/AcceleratedFinance


text:
#include <frovedis.hpp>
#include <frovedis/matrix/pblas_wrapper.hpp>

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

using namespace frovedis;
using namespace std;

BOOST_AUTO_TEST_CASE( frovedis_test )
{
    int argc = 1;
    char** argv = NULL;
    use_frovedis use(argc, argv);

    // dot product of two distributed std::vectors'
    std::vector<float> x = {1,2,3,4};
    std::vector<float> y = {1,2,3,4};
    auto xbm = vec_to_bcm<float> (x); // distributed vector x
    auto ybm = vec_to_bcm<float> (y); // distrubuted vector y
    auto d = dot<float> (xbm,ybm); // d = xbm.ybm
    BOOST_CHECK (d == 30);

    auto bm = make_blockcyclic_matrix_load<float> ("./sample_4x4");

    // checking dot() operation
    auto row1 = make_row_vector<float> (bm,1);
    auto row2 = make_row_vector<float> (bm,2);

    // checking whether the dot operation successfully taken place
    auto r = dot<float>(row1, row2); // r = row1 . row2
    BOOST_CHECK (r == 2);
}

max_stars_repo_name: XpressAI/frovedis

max_issues_repo_name: XpressAI/frovedis

max_forks_repo_name: XpressAI/frovedis


text:
// Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.

// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef UUID_3DCF6B90AE0E11DE9A315BE555D89593
#define UUID_3DCF6B90AE0E11DE9A315BE555D89593

#include <boost/qvm/inline.hpp>
#include <boost/qvm/mat_traits_array.hpp>
#include <boost/qvm/static_assert.hpp>

namespace boost {
namespace qvm {
namespace qvm_detail {
template <int N> struct det_size {};

template <class M>
BOOST_QVM_INLINE_TRIVIAL typename mat_traits<M>::scalar_type
determinant_impl_(M const &a, det_size<2>) {
  return mat_traits<M>::template read_element<0, 0>(a) *
             mat_traits<M>::template read_element<1, 1>(a) -
         mat_traits<M>::template read_element<1, 0>(a) *
             mat_traits<M>::template read_element<0, 1>(a);
}

template <class M, int N>
BOOST_QVM_INLINE_RECURSION typename mat_traits<M>::scalar_type
determinant_impl_(M const &a, det_size<N>) {
  typedef typename mat_traits<M>::scalar_type T;
  T m[N - 1][N - 1];
  T det = T(0);
  for (int j1 = 0; j1 != N; ++j1) {
    for (int i = 1; i != N; ++i) {
      int j2 = 0;
      for (int j = 0; j != N; ++j) {
        if (j == j1)
          continue;
        m[i - 1][j2] = mat_traits<M>::read_element_idx(i, j, a);
        ++j2;
      }
    }
    T d = determinant_impl_(m, det_size<N - 1>());
    if (j1 & 1)
      d = -d;
    det += mat_traits<M>::read_element_idx(0, j1, a) * d;
  }
  return det;
}

template <class M>
BOOST_QVM_INLINE_TRIVIAL typename mat_traits<M>::scalar_type
determinant_impl(M const &a) {
  BOOST_QVM_STATIC_ASSERT(mat_traits<M>::rows == mat_traits<M>::cols);
  return determinant_impl_(a, det_size<mat_traits<M>::rows>());
}
} // namespace qvm_detail
} // namespace qvm
} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
//  lock-free freelist
//
//  Copyright (C) 2008-2013 Tim Blechmann
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_LOCKFREE_FREELIST_HPP_INCLUDED
#define BOOST_LOCKFREE_FREELIST_HPP_INCLUDED

#include <limits>
#include <memory>

#include <boost/array.hpp>
#include <boost/config.hpp>
#include <boost/cstdint.hpp>
#include <boost/noncopyable.hpp>
#include <boost/static_assert.hpp>

#include <boost/lockfree/detail/atomic.hpp>
#include <boost/lockfree/detail/parameter.hpp>
#include <boost/lockfree/detail/tagged_ptr.hpp>

#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4100) // unreferenced formal parameter
#pragma warning(disable: 4127) // conditional expression is constant
#endif

namespace boost    {
namespace lockfree {
namespace detail   {

template <typename T,
          typename Alloc = std::allocator<T>
         >
class freelist_stack:
    Alloc
{
    struct freelist_node
    {
        tagged_ptr<freelist_node> next;
    };

    typedef tagged_ptr<freelist_node> tagged_node_ptr;

public:
    typedef tagged_ptr<T> tagged_node_handle;

    template <typename Allocator>
    freelist_stack (Allocator const & alloc, std::size_t n = 0):
        Alloc(alloc),
        pool_(tagged_node_ptr(NULL))
    {
        for (std::size_t i = 0; i != n; ++i) {
            T * node = Alloc::allocate(1);
#ifdef BOOST_LOCKFREE_FREELIST_INIT_RUNS_DTOR
            destruct<false>(node);
#else
            deallocate<false>(node);
#endif
        }
    }

    template <bool ThreadSafe>
    void reserve (std::size_t count)
    {
        for (std::size_t i = 0; i != count; ++i) {
            T * node = Alloc::allocate(1);
            deallocate<ThreadSafe>(node);
        }
    }

    template <bool ThreadSafe, bool Bounded>
    T * construct (void)
    {
        T * node = allocate<ThreadSafe, Bounded>();
        if (node)
            new(node) T();
        return node;
    }

    template <bool ThreadSafe, bool Bounded, typename ArgumentType>
    T * construct (ArgumentType const & arg)
    {
        T * node = allocate<ThreadSafe, Bounded>();
        if (node)
            new(node) T(arg);
        return node;
    }

    template <bool ThreadSafe, bool Bounded, typename ArgumentType1, typename ArgumentType2>
    T * construct (ArgumentType1 const & arg1, ArgumentType2 const & arg2)
    {
        T * node = allocate<ThreadSafe, Bounded>();
        if (node)
            new(node) T(arg1, arg2);
        return node;
    }

    template <bool ThreadSafe>
    void destruct (tagged_node_handle tagged_ptr)
    {
        T * n = tagged_ptr.get_ptr();
        n->~T();
        deallocate<ThreadSafe>(n);
    }

    template <bool ThreadSafe>
    void destruct (T * n)
    {
        n->~T();
        deallocate<ThreadSafe>(n);
    }

    ~freelist_stack(void)
    {
        tagged_node_ptr current = pool_.load();

        while (current) {
            freelist_node * current_ptr = current.get_ptr();
            if (current_ptr)
                current = current_ptr->next;
            Alloc::deallocate((T*)current_ptr, 1);
        }
    }

    bool is_lock_free(void) const
    {
        return pool_.is_lock_free();
    }

    T * get_handle(T * pointer) const
    {
        return pointer;
    }

    T * get_handle(tagged_node_handle const & handle) const
    {
        return get_pointer(handle);
    }

    T * get_pointer(tagged_node_handle const & tptr) const
    {
        return tptr.get_ptr();
    }

    T * get_pointer(T * pointer) const
    {
        return pointer;
    }

    T * null_handle(void) const
    {
        return NULL;
    }

protected: // allow use from subclasses
    template <bool ThreadSafe, bool Bounded>
    T * allocate (void)
    {
        if (ThreadSafe)
            return allocate_impl<Bounded>();
        else
            return allocate_impl_unsafe<Bounded>();
    }

private:
    template <bool Bounded>
    T * allocate_impl (void)
    {
        tagged_node_ptr old_pool = pool_.load(memory_order_consume);

        for(;;) {
            if (!old_pool.get_ptr()) {
                if (!Bounded)
                    return Alloc::allocate(1);
                else
                    return 0;
            }

            freelist_node * new_pool_ptr = old_pool->next.get_ptr();
            tagged_node_ptr new_pool (new_pool_ptr, old_pool.get_next_tag());

            if (pool_.compare_exchange_weak(old_pool, new_pool)) {
                void * ptr = old_pool.get_ptr();
                return reinterpret_cast<T*>(ptr);
            }
        }
    }

    template <bool Bounded>
    T * allocate_impl_unsafe (void)
    {
        tagged_node_ptr old_pool = pool_.load(memory_order_relaxed);

        if (!old_pool.get_ptr()) {
            if (!Bounded)
                return Alloc::allocate(1);
            else
                return 0;
        }

        freelist_node * new_pool_ptr = old_pool->next.get_ptr();
        tagged_node_ptr new_pool (new_pool_ptr, old_pool.get_next_tag());

        pool_.store(new_pool, memory_order_relaxed);
        void * ptr = old_pool.get_ptr();
        return reinterpret_cast<T*>(ptr);
    }

protected:
    template <bool ThreadSafe>
    void deallocate (T * n)
    {
        if (ThreadSafe)
            deallocate_impl(n);
        else
            deallocate_impl_unsafe(n);
    }

private:
    void deallocate_impl (T * n)
    {
        void * node = n;
        tagged_node_ptr old_pool = pool_.load(memory_order_consume);
        freelist_node * new_pool_ptr = reinterpret_cast<freelist_node*>(node);

        for(;;) {
            tagged_node_ptr new_pool (new_pool_ptr, old_pool.get_tag());
            new_pool->next.set_ptr(old_pool.get_ptr());

            if (pool_.compare_exchange_weak(old_pool, new_pool))
                return;
        }
    }

    void deallocate_impl_unsafe (T * n)
    {
        void * node = n;
        tagged_node_ptr old_pool = pool_.load(memory_order_relaxed);
        freelist_node * new_pool_ptr = reinterpret_cast<freelist_node*>(node);

        tagged_node_ptr new_pool (new_pool_ptr, old_pool.get_tag());
        new_pool->next.set_ptr(old_pool.get_ptr());

        pool_.store(new_pool, memory_order_relaxed);
    }

    atomic<tagged_node_ptr> pool_;
};

class tagged_index
{
public:
    typedef boost::uint16_t tag_t;
    typedef boost::uint16_t index_t;

    /** uninitialized constructor */
    tagged_index(void) BOOST_NOEXCEPT //: index(0), tag(0)
    {}

    /** copy constructor */
#ifdef BOOST_NO_CXX11_DEFAULTED_FUNCTIONS
    tagged_index(tagged_index const & rhs):
        index(rhs.index), tag(rhs.tag)
    {}
#else
    tagged_index(tagged_index const & rhs) = default;
#endif

    explicit tagged_index(index_t i, tag_t t = 0):
        index(i), tag(t)
    {}

    /** index access */
    /* @{ */
    index_t get_index() const
    {
        return index;
    }

    void set_index(index_t i)
    {
        index = i;
    }
    /* @} */

    /** tag access */
    /* @{ */
    tag_t get_tag() const
    {
        return tag;
    }

    tag_t get_next_tag() const
    {
        tag_t next = (get_tag() + 1) & (std::numeric_limits<tag_t>::max)();
        return next;
    }

    void set_tag(tag_t t)
    {
        tag = t;
    }
    /* @} */

    bool operator==(tagged_index const & rhs) const
    {
        return (index == rhs.index) && (tag == rhs.tag);
    }

    bool operator!=(tagged_index const & rhs) const
    {
        return !operator==(rhs);
    }

protected:
    index_t index;
    tag_t tag;
};

template <typename T,
          std::size_t size>
struct compiletime_sized_freelist_storage
{
    // array-based freelists only support a 16bit address space.
    BOOST_STATIC_ASSERT(size < 65536);

    boost::array<char, size * sizeof(T)> data;

    // unused ... only for API purposes
    template <typename Allocator>
    compiletime_sized_freelist_storage(Allocator const & /* alloc */, std::size_t /* count */)
    {}

    T * nodes(void) const
    {
        return reinterpret_cast<T*>(const_cast<char*>(data.data()));
    }

    std::size_t node_count(void) const
    {
        return size;
    }
};

template <typename T,
          typename Alloc = std::allocator<T> >
struct runtime_sized_freelist_storage:
    Alloc
{
    T * nodes_;
    std::size_t node_count_;

    template <typename Allocator>
    runtime_sized_freelist_storage(Allocator const & alloc, std::size_t count):
        Alloc(alloc), node_count_(count)
    {
        if (count > 65535)
            boost::throw_exception(std::runtime_error("boost.lockfree: freelist size is limited to a maximum of 65535 objects"));
        nodes_ = Alloc::allocate(count);
    }

    ~runtime_sized_freelist_storage(void)
    {
        Alloc::deallocate(nodes_, node_count_);
    }

    T * nodes(void) const
    {
        return nodes_;
    }

    std::size_t node_count(void) const
    {
        return node_count_;
    }
};

template <typename T,
          typename NodeStorage = runtime_sized_freelist_storage<T>
         >
class fixed_size_freelist:
    NodeStorage
{
    struct freelist_node
    {
        tagged_index next;
    };

    typedef tagged_index::index_t index_t;

    void initialize(void)
    {
        T * nodes = NodeStorage::nodes();
        for (std::size_t i = 0; i != NodeStorage::node_count(); ++i) {
            tagged_index * next_index = reinterpret_cast<tagged_index*>(nodes + i);
            next_index->set_index(null_handle());

#ifdef BOOST_LOCKFREE_FREELIST_INIT_RUNS_DTOR
            destruct<false>(nodes + i);
#else
            deallocate<false>(static_cast<index_t>(i));
#endif
        }
    }

public:
    typedef tagged_index tagged_node_handle;

    template <typename Allocator>
    fixed_size_freelist (Allocator const & alloc, std::size_t count):
        NodeStorage(alloc, count),
        pool_(tagged_index(static_cast<index_t>(count), 0))
    {
        initialize();
    }

    fixed_size_freelist (void):
        pool_(tagged_index(NodeStorage::node_count(), 0))
    {
        initialize();
    }

    template <bool ThreadSafe, bool Bounded>
    T * construct (void)
    {
        index_t node_index = allocate<ThreadSafe>();
        if (node_index == null_handle())
            return NULL;

        T * node = NodeStorage::nodes() + node_index;
        new(node) T();
        return node;
    }

    template <bool ThreadSafe, bool Bounded, typename ArgumentType>
    T * construct (ArgumentType const & arg)
    {
        index_t node_index = allocate<ThreadSafe>();
        if (node_index == null_handle())
            return NULL;

        T * node = NodeStorage::nodes() + node_index;
        new(node) T(arg);
        return node;
    }

    template <bool ThreadSafe, bool Bounded, typename ArgumentType1, typename ArgumentType2>
    T * construct (ArgumentType1 const & arg1, ArgumentType2 const & arg2)
    {
        index_t node_index = allocate<ThreadSafe>();
        if (node_index == null_handle())
            return NULL;

        T * node = NodeStorage::nodes() + node_index;
        new(node) T(arg1, arg2);
        return node;
    }

    template <bool ThreadSafe>
    void destruct (tagged_node_handle tagged_index)
    {
        index_t index = tagged_index.get_index();
        T * n = NodeStorage::nodes() + index;
        n->~T();
        deallocate<ThreadSafe>(index);
    }

    template <bool ThreadSafe>
    void destruct (T * n)
    {
        n->~T();
        deallocate<ThreadSafe>(n - NodeStorage::nodes());
    }

    bool is_lock_free(void) const
    {
        return pool_.is_lock_free();
    }

    index_t null_handle(void) const
    {
        return static_cast<index_t>(NodeStorage::node_count());
    }

    index_t get_handle(T * pointer) const
    {
        if (pointer == NULL)
            return null_handle();
        else
            return static_cast<index_t>(pointer - NodeStorage::nodes());
    }

    index_t get_handle(tagged_node_handle const & handle) const
    {
        return handle.get_index();
    }

    T * get_pointer(tagged_node_handle const & tptr) const
    {
        return get_pointer(tptr.get_index());
    }

    T * get_pointer(index_t index) const
    {
        if (index == null_handle())
            return 0;
        else
            return NodeStorage::nodes() + index;
    }

    T * get_pointer(T * ptr) const
    {
        return ptr;
    }

protected: // allow use from subclasses
    template <bool ThreadSafe>
    index_t allocate (void)
    {
        if (ThreadSafe)
            return allocate_impl();
        else
            return allocate_impl_unsafe();
    }

private:
    index_t allocate_impl (void)
    {
        tagged_index old_pool = pool_.load(memory_order_consume);

        for(;;) {
            index_t index = old_pool.get_index();
            if (index == null_handle())
                return index;

            T * old_node = NodeStorage::nodes() + index;
            tagged_index * next_index = reinterpret_cast<tagged_index*>(old_node);

            tagged_index new_pool(next_index->get_index(), old_pool.get_next_tag());

            if (pool_.compare_exchange_weak(old_pool, new_pool))
                return old_pool.get_index();
        }
    }

    index_t allocate_impl_unsafe (void)
    {
        tagged_index old_pool = pool_.load(memory_order_consume);

        index_t index = old_pool.get_index();
        if (index == null_handle())
            return index;

        T * old_node = NodeStorage::nodes() + index;
        tagged_index * next_index = reinterpret_cast<tagged_index*>(old_node);

        tagged_index new_pool(next_index->get_index(), old_pool.get_next_tag());

        pool_.store(new_pool, memory_order_relaxed);
        return old_pool.get_index();
    }

    template <bool ThreadSafe>
    void deallocate (index_t index)
    {
        if (ThreadSafe)
            deallocate_impl(index);
        else
            deallocate_impl_unsafe(index);
    }

    void deallocate_impl (index_t index)
    {
        freelist_node * new_pool_node = reinterpret_cast<freelist_node*>(NodeStorage::nodes() + index);
        tagged_index old_pool = pool_.load(memory_order_consume);

        for(;;) {
            tagged_index new_pool (index, old_pool.get_tag());
            new_pool_node->next.set_index(old_pool.get_index());

            if (pool_.compare_exchange_weak(old_pool, new_pool))
                return;
        }
    }

    void deallocate_impl_unsafe (index_t index)
    {
        freelist_node * new_pool_node = reinterpret_cast<freelist_node*>(NodeStorage::nodes() + index);
        tagged_index old_pool = pool_.load(memory_order_consume);

        tagged_index new_pool (index, old_pool.get_tag());
        new_pool_node->next.set_index(old_pool.get_index());

        pool_.store(new_pool);
    }

    atomic<tagged_index> pool_;
};

template <typename T,
          typename Alloc,
          bool IsCompileTimeSized,
          bool IsFixedSize,
          std::size_t Capacity
          >
struct select_freelist
{
    typedef typename mpl::if_c<IsCompileTimeSized,
                               compiletime_sized_freelist_storage<T, Capacity>,
                               runtime_sized_freelist_storage<T, Alloc>
                              >::type fixed_sized_storage_type;

    typedef typename mpl::if_c<IsCompileTimeSized || IsFixedSize,
                               fixed_size_freelist<T, fixed_sized_storage_type>,
                               freelist_stack<T, Alloc>
                              >::type type;
};

template <typename T, bool IsNodeBased>
struct select_tagged_handle
{
    typedef typename mpl::if_c<IsNodeBased,
                               tagged_ptr<T>,
                               tagged_index
                              >::type tagged_handle_type;

    typedef typename mpl::if_c<IsNodeBased,
                               T*,
                               typename tagged_index::index_t
                              >::type handle_type;
};

} /* namespace detail */
} /* namespace lockfree */
} /* namespace boost */

#if defined(_MSC_VER)
#pragma warning(pop)
#endif

#endif /* BOOST_LOCKFREE_FREELIST_HPP_INCLUDED */


text:
#include "PositiveEvaluator.h"

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

#include <string.h>

namespace sf1r
{
namespace Recommend
{

const int PositiveEvaluator::LINE_SIZE = 512;

void PositiveEvaluator::load(const std::string& path)
{
    if (!boost::filesystem::exists(path))
        return;
    if (in_.is_open())
        in_.close();
    in_.open(path.c_str(), std::ifstream::in);
}

bool PositiveEvaluator::next()
{
    memset(cLine_, 0, LINE_SIZE);
    return in_.getline(cLine_, LINE_SIZE);
}

const EvaluateItem& PositiveEvaluator::get() const
{
    std::string sLine(cLine_);
    std::size_t pos = sLine.find("\t");
    if (std::string::npos != pos)
    {
        item_->userQuery_ = sLine.substr(0, pos);
        item_->correct_ = sLine.substr(pos + 1);
    }
    return *item_;
}

bool PositiveEvaluator::isValid(const std::string& path)
{
    const boost::filesystem::path p(path);
    //std::cout<<boost::filesystem::extension(p)<<"\n";
    return ".pos" == boost::filesystem::extension(p);
}

}
}


text:
#pragma once

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

namespace cilantro {
    static std::vector<size_t> getPointToClusterIndexMap(const std::vector<std::vector<size_t>> &cluster_to_point,
                                                         size_t num_points)
    {
        std::vector<size_t> point_to_segment(num_points, cluster_to_point.size());
        for (size_t i = 0; i < cluster_to_point.size(); i++) {
            for (size_t j = 0; j < cluster_to_point[i].size(); j++) {
                point_to_segment[cluster_to_point[i][j]] = i;
            }
        }
        return point_to_segment;
    }

    static std::vector<std::vector<size_t>> getClusterToPointIndicesMap(const std::vector<size_t> &point_to_cluster,
                                                                        size_t num_clusters)
    {
        std::vector<std::vector<size_t>> segment_to_point(num_clusters);
        for (size_t i = 0; i < point_to_cluster.size(); i++) {
            segment_to_point[point_to_cluster[i]].emplace_back(i);
        }
        return segment_to_point;
    }

    static std::vector<size_t> getUnlabeledPointIndices(const std::vector<std::vector<size_t>> &cluster_to_point,
                                                        const std::vector<size_t> &point_to_cluster)
    {
        const size_t no_label = cluster_to_point.size();
        std::vector<size_t> res;
        res.reserve(point_to_cluster.size());
        for (size_t i = 0; i < point_to_cluster.size(); i++) {
            if (point_to_cluster[i] == no_label) res.emplace_back(i);
        }
        return res;
    }

    // CRTP base class that holds clustering results and accessors
    template <typename Derived = void>
    class ClusteringBase {
    public:
        EIGEN_MAKE_ALIGNED_OPERATOR_NEW

        inline const std::vector<std::vector<size_t>>& getClusterToPointIndicesMap() const { return cluster_to_point_indices_map_; }

        inline const std::vector<size_t>& getPointToClusterIndexMap() const { return point_to_cluster_index_map_; }

        inline size_t getNumberOfClusters() const { return cluster_to_point_indices_map_.size(); }

        inline size_t getNumberOfPoints() const { return point_to_cluster_index_map_.size(); }

        inline std::vector<size_t> getUnlabeledPointIndices() const {
            return cilantro::getUnlabeledPointIndices(cluster_to_point_indices_map_, point_to_cluster_index_map_);
        }

    protected:
        std::vector<std::vector<size_t>> cluster_to_point_indices_map_;
        std::vector<size_t> point_to_cluster_index_map_;
    };
}

max_stars_repo_name: wannesvanloock/cilantro

max_issues_repo_name: aabin/cilantro

max_forks_repo_name: aabin/cilantro


text:
// Copyright 2019 Hans Dembinski
//
// 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)

//[ guide_axis_circular

#include <boost/histogram/axis.hpp>
#include <limits>

int main() {
  using namespace boost::histogram;

  // make a circular regular axis ... [0, 180), [180, 360), [0, 180) ....
  using opts = decltype(axis::option::overflow | axis::option::circular);
  auto r = axis::regular<double, use_default, use_default, opts>{2, 0., 360.};
  assert(r.index(-180) == 1);
  assert(r.index(0) == 0);
  assert(r.index(180) == 1);
  assert(r.index(360) == 0);
  assert(r.index(540) == 1);
  assert(r.index(720) == 0);
  // special values are mapped to the overflow bin index
  assert(r.index(std::numeric_limits<double>::infinity()) == 2);
  assert(r.index(-std::numeric_limits<double>::infinity()) == 2);
  assert(r.index(std::numeric_limits<double>::quiet_NaN()) == 2);

  // since the regular axis is the most common circular axis, there exists an alias
  auto c = axis::circular<>{2, 0., 360.};
  assert(r == c);

  // make a circular integer axis
  auto i = axis::integer<int, use_default, axis::option::circular_t>{1, 4};
  assert(i.index(0) == 2);
  assert(i.index(1) == 0);
  assert(i.index(2) == 1);
  assert(i.index(3) == 2);
  assert(i.index(4) == 0);
  assert(i.index(5) == 1);
}

//]

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
/**
 * @file
 * @brief Implementation of linear Lagrangian finite elements for the Dirichlet
 *        problem for the Laplacian
 * @author Ralf Hiptmair
 * @date   October 2018
 * @copyright MIT License
 */

#include <cmath>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include <lf/assemble/assemble.h>
#include <lf/geometry/geometry.h>
#include <lf/io/io.h>
#include <lf/mesh/hybrid2d/hybrid2d.h>
#include <lf/refinement/refinement.h>
#include "lf/fe/fe.h"
#include "lf/mesh/test_utils/test_meshes.h"
#include "lf/mesh/utils/utils.h"

static unsigned int dbg_ctrl = 0;
const unsigned int dbg_dofh = 1;
const unsigned int dbg_mesh = 2;
const unsigned int dbg_mat = 4;
const unsigned int dbg_vec = 8;
const unsigned int dbg_bdf = 16;
const unsigned int dbg_elim = 32;
const unsigned int dbg_basic = 64;
const unsigned int dbg_trp = 128;

/**
 * @brief Build a vector of boundary flags for degrees of freedom
 *
 * @param dofh Local-to-global mapper managing indexing for shape
 * functions
 * @return boolean vector of boundary flags, whose length agrees with the
 *         number of global shape functions managed by `dofh`.
 *
 * Every global shape functions belongs to a unique mesh entity. If that
 * entity is contained in the boundary of the mesh, then the flag array
 * entry with the index of the global shape function is set to `true`,
 * otherwise to `false`.
 */
std::vector<bool> flagBoundaryDOFs(const lf::assemble::DofHandler &dofh) {
  const lf::base::size_type N{dofh.NoDofs()};
  // Flag all entities on the boundary
  auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(dofh.Mesh())};
  // Run through all global shape functions and check whether
  // they are associated with an entity on the boundary. Store
  // this information in a boolean vector
  std::vector<bool> tmp_bd_flags(N, false);
  for (lf::assemble::gdof_idx_t dofnum = 0; dofnum < N; ++dofnum) {
    const lf::mesh::Entity &dof_entity{dofh.Entity(dofnum)};
    tmp_bd_flags[dofnum] = bd_flags(dof_entity);
    SWITCHEDSTATEMENT(
        dbg_ctrl, dbg_bdf,
        std::cout << "FBD: dof " << dofnum << "@ " << dof_entity << " ["
                  << dofh.Mesh()->Index(dof_entity) << "] ";
        if (tmp_bd_flags[dofnum]) { std::cout << "ON BOUNDARY"; } std::cout
        << std::endl);
  }
  return tmp_bd_flags;
}

/** @brief Eliminate degrees of freedom located on the boundary
 *
 * No longer in use. Replaced with lf::assemble::fix_flagged_solution_components
 */
void eliminateBoundaryDofs(const std::vector<bool> &tmp_bd_flags,
                           lf::assemble::COOMatrix<double> *A) {
  const lf::base::size_type N = tmp_bd_flags.size();
  LF_ASSERT_MSG((A->cols() == N) && (A->rows() == N),
                "Matrix dimension mismath");

  // Remove rows associated with dofs on the boundary
  auto new_last = std::remove_if(
      A->triplets().begin(), A->triplets().end(),
      [&tmp_bd_flags](lf::assemble::COOMatrix<double>::Triplet &triplet) {
        SWITCHEDSTATEMENT(dbg_ctrl, dbg_elim, if (tmp_bd_flags[triplet.row()]) {
          std::cout << "EBD: removing " << triplet.row() << ',' << triplet.col()
                    << "[" << triplet.value() << "]" << std::endl;
        });
        return tmp_bd_flags[triplet.row()];
      });
  A->triplets().erase(new_last, A->triplets().end());
  // Add unit diagonal entries to rows belonging to dofs on the boundary
  for (lf::assemble::gdof_idx_t dofnum = 0; dofnum < N; ++dofnum) {
    if (tmp_bd_flags[dofnum]) {
      A->AddToEntry(dofnum, dofnum, 1.0);
    }
  }
}

/** @brief Insert sampled values from Dirichlet data into right hand side
 * vector
 *
 */
void insertDirichletDataRHS(const std::vector<bool> &tmp_bd_flags,
                            Eigen::VectorXd *rhs,
                            const Eigen::VectorXd &dirichlet_values) {
  const lf::base::size_type N = tmp_bd_flags.size();
  LF_VERIFY_MSG((rhs->size() == N), "rhs vector size mismatch");
  LF_VERIFY_MSG((dirichlet_values.size() == N), "data vector size mismatch");

  for (lf::assemble::gdof_idx_t dofnum = 0; dofnum < N; ++dofnum) {
    if (tmp_bd_flags[dofnum]) {
      // Shape function associated with the boundary
      (*rhs)[dofnum] = dirichlet_values[dofnum];
    }
  }
}

/** @brief Solves Dirichlet problem for the Laplacian
 *
 * @tparam SOLFUNC functor providing boundary values/exact solution
 * @tparam RHSFUNC functor for right hand side source function
 * @param mesh reference to the mesh on which the FE solution is to be
 * computed
 * @param u functor object for solution, also used to sample Dirichlet
 * data
 * @param f object supplying right-hand-side source function
 *
 * @return L2 norm of the nodal error, which is just the L2 norm of the
 *         discretization error approximated by means of the the 2D
 * trapezoidal rule.
 */
template <typename SOLFUNC, typename RHSFUNC>
double L2ErrorLinearFEDirichletLaplacian(
    const std::shared_ptr<const lf::mesh::Mesh> &mesh_p, SOLFUNC &&u,
    RHSFUNC &&f) {
  LF_ASSERT_MSG(mesh_p != nullptr, "Invalid mesh pointer");
  LF_ASSERT_MSG((mesh_p->DimMesh() == 2) && (mesh_p->DimWorld() == 2),
                "For 2D planar meshes only!");
  // Debugging output
  SWITCHEDSTATEMENT(
      dbg_ctrl, dbg_basic,
      std::cout << "Dirichlet Laplacian: Linear FE L2 error on mesh with "
                << mesh_p->Size(0) << " cells, " << mesh_p->Size(1)
                << " edges, " << mesh_p->Size(2) << " nodes" << std::endl;)
  SWITCHEDSTATEMENT(
      dbg_ctrl, dbg_mesh,
      const int tmp_mesh_ctrl = lf::mesh::hybrid2d::Mesh::output_ctrl_;
      lf::mesh::hybrid2d::Mesh::output_ctrl_ = 100;
      lf::mesh::utils::PrintInfo(*mesh_p, std::cout);
      lf::mesh::hybrid2d::Mesh::output_ctrl_ = tmp_mesh_ctrl);
  // Initialize objects for local computations
  lf::fe::LinearFELaplaceElementMatrix loc_mat_laplace{};
  lf::fe::LinearFELocalLoadVector<double, decltype(f)> loc_vec_sample(f);
  // Initialization of index mapping for linear finite elements
  lf::assemble::UniformFEDofHandler loc_glob_map(
      mesh_p, {{lf::base::RefEl::kPoint(), 1}});
  SWITCHEDSTATEMENT(dbg_ctrl, dbg_dofh,
                    std::cout << loc_glob_map << std::endl;);
  // Dimension of finite element space
  const lf::assemble::size_type N_dofs(loc_glob_map.NoDofs());
  // Matrix in triplet format holding Galerkin matrix
  lf::assemble::COOMatrix<double> mat(N_dofs, N_dofs);
  // Building the Galerkin matrix (trial space = test space)
  // This Galerkin matrix is oblivious of Dirichlet boundary conditions
  mat = lf::assemble::AssembleMatrixLocally<lf::assemble::COOMatrix<double>>(
      0, loc_glob_map, loc_mat_laplace);
  // Debugging output
  SWITCHEDSTATEMENT(dbg_ctrl, dbg_trp, mat.PrintInfo(std::cout));
  SWITCHEDSTATEMENT(dbg_ctrl, dbg_mat,
                    std::cout << "Full " << mat.rows() << 'x' << mat.cols()
                              << " stiffness matrix, " << mat.triplets().size()
                              << " tripets:\n"
                              << mat.makeDense() << std::endl);

  // Filling the right-hand-side vector
  auto rhsvec = lf::assemble::AssembleVectorLocally<Eigen::VectorXd>(
      0, loc_glob_map, loc_vec_sample);
  // Sample Dirichlet date from the exact solution
  Eigen::VectorXd dirichlet_data(loc_glob_map.NoDofs());
  const Eigen::Matrix<double, 0, 1> ref_coord{
      Eigen::Matrix<double, 0, 1>::Zero(0, 1)};
  for (const lf::mesh::Entity &node : mesh_p->Entities(mesh_p->DimMesh())) {
    LF_ASSERT_MSG(node.RefEl() == lf::base::RefEl::kPoint(),
                  "Wrong topological type for a node");
    const Eigen::Vector2d point = node.Geometry()->Global(ref_coord);
    const lf::assemble::size_type num_int_dof =
        loc_glob_map.NoInteriorDofs(node);
    LF_ASSERT_MSG(num_int_dof == 1, "Node with " << num_int_dof << " dof");
    const lf::base::RandomAccessRange<const lf::assemble::gdof_idx_t> gsf_idx(
        loc_glob_map.InteriorGlobalDofIndices(node));
    const lf::assemble::gdof_idx_t node_dof_idx = gsf_idx[0];
    dirichlet_data[node_dof_idx] = u(point);
  }

  // modify linear system in order to take into account boundary data
  std::vector<bool> tmp_bd_flags{flagBoundaryDOFs(loc_glob_map)};
  // >> Old version
  // eliminateBoundaryDofs(tmp_bd_flags, mat);
  // insertDirichletDataRHS(tmp_bd_flags, rhsvec, dirichlet_data);
  // Identify dof indices associated with the boundary
  // >>
  // >> Equivalent new versions
  lf::assemble::fix_flagged_solution_comp_alt<double>(
      [&tmp_bd_flags,
       &dirichlet_data](lf::assemble::gdof_idx_t i) -> std::pair<bool, double> {
        LF_ASSERT_MSG((i < tmp_bd_flags.size()) && (i < dirichlet_data.size()),
                      "Illegal index " << i);
        return std::make_pair(tmp_bd_flags[i], dirichlet_data[i]);
      },
      mat, rhsvec);
  // lf::assemble::fix_flagged_solution_components<double>(
  //   tmp_bd_flags, dirichlet_data, mat, rhsvec);
  // >>
  // Debugging output
  SWITCHEDSTATEMENT(dbg_ctrl, dbg_mat,
                    std::cout << "Reduced " << mat.rows() << 'x' << mat.cols()
                              << " stiffness matrix, " << mat.triplets().size()
                              << " triplets:\n"
                              << mat.makeDense() << std::endl);

  // Initialize sparse matrix
  Eigen::SparseMatrix<double> stiffness_matrix(mat.makeSparse());
  // Solve linear system
  Eigen::SparseLU<Eigen::SparseMatrix<double>> solver;
  solver.compute(stiffness_matrix);
  Eigen::VectorXd sol_vec = solver.solve(rhsvec);
  if (solver.info() != Eigen::Success) {
    std::cout << "solver failed!" << std::endl;
  }

  // Compute the norm of nodal error cell by cell
  double nodal_err = 0.0;
  for (const lf::mesh::Entity &cell : mesh_p->Entities(0)) {
    const lf::base::RandomAccessRange<const lf::assemble::gdof_idx_t>
        cell_dof_idx(loc_glob_map.GlobalDofIndices(cell));
    LF_ASSERT_MSG(loc_glob_map.NoLocalDofs(cell) == cell.RefEl().NumNodes(),
                  "Inconsistent node number");
    const lf::base::size_type num_nodes = cell.RefEl().NumNodes();
    double sum = 0.0;
    for (int k = 0; k < num_nodes; ++k) {
      sum += std::pow(
          sol_vec[cell_dof_idx[k]] - dirichlet_data[cell_dof_idx[k]], 2);
    }
    nodal_err += lf::geometry::Volume(*cell.Geometry()) * (sum / num_nodes);
  }
  return std::sqrt(nodal_err);
}

/** @brief Solves Dirichlet problem for the Laplacian on a sequence of
 *         regularly refined meshes
 * @param coarse_mesh_p pointer to coarsest mesh
 * @param reflevels number of refinements
 * @param u exact solution of the boundary value problem
 * @param f right hand side source function
 * @return L2 norms of discretization errors on each refinement level
 *
 */
template <typename SOLFUNCTOR, typename RHSFUNCTOR>
std::vector<double> SolveDirLaplSeqMesh(
    std::shared_ptr<lf::mesh::Mesh> coarse_mesh_p, unsigned int reflevels,
    SOLFUNCTOR &&u, RHSFUNCTOR &&f) {
  // Prepare for creating a hierarchy of meshes
  std::shared_ptr<lf::mesh::hybrid2d::MeshFactory> mesh_factory_ptr =
      std::make_shared<lf::mesh::hybrid2d::MeshFactory>(2);
  lf::refinement::MeshHierarchy multi_mesh(std::move(coarse_mesh_p),
                                           mesh_factory_ptr);

  // Perform several steps of regular refinement of the given mesh
  for (int refstep = 0; refstep < reflevels; ++refstep) {
    multi_mesh.RefineRegular(/*lf::refinement::RefPat::rp_barycentric*/);
  }
  // Solve Dirichlet boundary value problem on every level
  lf::assemble::size_type L = multi_mesh.NumLevels();
  std::vector<double> errors(L);
  for (int level = 0; level < L; level++) {
    errors.push_back(
        L2ErrorLinearFEDirichletLaplacian(multi_mesh.getMesh(level), u, f));
  }
  return errors;
}

int main(int argc, const char **argv) {
  // Pointer to the current mesh
  std::shared_ptr<lf::mesh::Mesh> mesh_p;

  // Processing command line arguments
  bool verbose = false;
  namespace po = boost::program_options;
  po::options_description desc("Allowed options");
  // clang-format off
  desc.add_options()
  ("help,h", "-h -v -f <filename> -s <selection>")
  ("filename,f", "File to load coarse mesh from ")
  ("selector,s", po::value<int>()->default_value(0), "Selection of test mesh")
  ("reflevels,r", po::value<int>()->default_value(2), "Number of refinement levels")
  ("bvpsel,b", po::value<int>()->default_value(0),
   "Selector for Dirichlet data and rhs function")
  ("verbose,v", po::bool_switch(&verbose),"Enable verbose mode");
  // clang-format on
  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  if (vm.count("help") > 0) {
    std::cout << desc << std::endl;
    std::cout << "Internal variables that can be set by name=value args"
              << std::endl;
    lf::base::ListCtrlVars(std::cout);
  } else {
    lf::base::ReadCtrVarsCmdArgs(argc, argv);
    std::cout << "*** Solving Dirichlet problems for the Laplacian ***"
              << std::endl;
    // Retrieve number of degrees of freedom for each entity type from
    // command line arguments
    if (vm.count("filename") > 0) {
      // A filename was specified
      std::string filename{vm["filename"].as<std::string>()};
      if (filename.length() > 0) {
        std::cout << "Reading mesh from file " << filename << std::endl;
        boost::filesystem::path here = __FILE__;
        auto mesh_file_path = here.parent_path() / filename.c_str();
        auto mesh_factory =
            std::make_unique<lf::mesh::hybrid2d::MeshFactory>(2);
        lf::io::GmshReader reader(std::move(mesh_factory),
                                  mesh_file_path.string());
        mesh_p = reader.mesh();
      }
    } else {
      std::cout << "No mesh file supplied, using GenerateHybrid2DTestMesh()"
                << std::endl;
      if (vm.count("selector") > 0) {
        const int selector = vm["selector"].as<int>();
        std::cout << "Using test mesh no " << selector << std::endl;
        if ((selector >= 0) && (selector <= 4)) {
          mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(selector);
        }
      }
    }
    // Set number of refinement levels
    unsigned int reflevels = 2;
    if (vm.count("reflevels") > 0) {
      reflevels = vm["reflevels"].as<int>();
    }
    unsigned int bvpsel = 0;
    if (vm.count("bvpsel") > 0) {
      bvpsel = vm["bvpsel"].as<int>();
    }
    if (mesh_p == nullptr) {
      // Default mesh
      std::cout << "Using default mesh; test mesh 0" << std::endl;
      mesh_p = lf::mesh::test_utils::GenerateHybrid2DTestMesh(0);
    }
    // At this point a pointer to the mesh is stored in mesh_p
    // Output summary information about the coarsest mesh
    std::cout << "Coarse mesh: " << mesh_p->Size(0) << " cells, "
              << mesh_p->Size(1) << " edges, " << mesh_p->Size(2) << " vertices"
              << std::endl;
    std::cout << reflevels << " refinement levels requested" << std::endl;

    // Problem data provided by function pointers
    std::function<double(const Eigen::Vector2d &)> u, f;

    // Initialize the problem data
    std::cout << "Problem setting " << bvpsel << " selected" << std::endl;
    switch (bvpsel) {
      case 0: {
        // A linear solution, no error, if contained in FE space
        f = [](const Eigen::Vector2d &) { return 0.0; };
        u = [](const Eigen::Vector2d &x) { return (x[0] + 2.0 * x[1]); };
        break;
      }
      case 1: {
        // Quadratic polynomial solution
        f = [](const Eigen::Vector2d &) { return -4.0; };
        u = [](const Eigen::Vector2d &x) {
          return (std::pow(x[0], 2) + std::pow(x[1], 2));
        };
        break;
      }
      default: {
        LF_VERIFY_MSG(false, "Illegal problem number");
        break;
      }
    }

    // Set debugging switches
    lf::fe::LinearFELaplaceElementMatrix::dbg_ctrl = 0;
    // LinearFELaplaceElementMatrix::dbg_geo |
    // LinearFELaplaceElementMatrix::dbg_locmat;
    lf::fe::LinearFELocalLoadVector<double, decltype(f)>::dbg_ctrl = 0;
    lf::assemble::DofHandler::output_ctrl_ = 6;
    dbg_ctrl = dbg_basic;  // | dbg_mat | dbg_mesh | dbg_dofh | dbg_trp;
    // lf::assemble::ass_mat_dbg_ctrl = 255;

    // Compute finite element solution and error
    auto L2errs = SolveDirLaplSeqMesh(mesh_p, reflevels, u, f);
    int level = 0;
    for (auto &err : L2errs) {
      std::cout << "L2 rrror on level " << level << " = " << err << std::endl;
      level++;
    }
  }
  return 0;
}

max_stars_repo_name: Cryoris/lehrfempp

max_issues_repo_name: Cryoris/lehrfempp

max_forks_repo_name: Cryoris/lehrfempp