text:
/*
**  Copyright (C) 2012 Aldebaran Robotics
**  See COPYING for the license
*/
#include <cstring>

#include <qi/assert.hpp>
#include <qi/signature.hpp>
#include <qi/type/typeinterface.hpp>
#include <qi/jsoncodec.hpp>
#include <boost/make_shared.hpp>
#include "signatureconvertor.hpp"

qiLogCategory("qitype.signature");

namespace qi {

  static std::string makeTupleAnnotation(const std::string& name, const std::vector<std::string>& annotations) {
    std::string res;

    if (name.empty() && annotations.empty())
      return res;
    res += '<';
    res += name;
    for (unsigned i = 0; i < annotations.size(); ++i)
      res += ',' + annotations[i];
    res += '>';
    return res;
  }

  qi::Signature makeListSignature(const qi::Signature &element) {
    std::string res;
    res += (char)Signature::Type_List;
    res += element.toString();
    res += (char)Signature::Type_List_End;
    return qi::Signature(res);
  }

  qi::Signature makeVarArgsSignature(const qi::Signature &element) {
    std::string res;
    res += (char)Signature::Type_VarArgs;
    res += element.toString();
    return qi::Signature(res);
  }

  qi::Signature makeKwArgsSignature(const qi::Signature &element) {
    std::string res;
    res += (char)Signature::Type_KwArgs;
    res += element.toString();
    return qi::Signature(res);
  }

  qi::Signature makeTupleSignature(const qi::Signature &element) {
    std::string res;
    res += (char)Signature::Type_Tuple;
    res += element.toString();
    res += (char)Signature::Type_Tuple_End;
    return qi::Signature(res);
  }

  qi::Signature makeMapSignature(const qi::Signature &key, const qi::Signature &value) {
    std::string res;
    res += (char)Signature::Type_Map;
    res += key.toString();
    res += value.toString();
    res += (char)Signature::Type_Map_End;
    return qi::Signature(res);
  }

  qi::Signature makeTupleSignature(const std::vector<qi::AnyReference>& vgv, bool resolve, const std::string &name, const std::vector<std::string>& names)
  {
    std::string res;
    res += (char)Signature::Type_Tuple;
    for (unsigned int i = 0; i < vgv.size(); ++i)
      res += vgv[i].signature(resolve).toString();
    res += (char)Signature::Type_Tuple_End;
    if (names.size() == vgv.size())
      res += makeTupleAnnotation(name, names);
    return qi::Signature(res);
  }

  qi::Signature makeTupleSignature(const std::vector<TypeInterface*>& vt, const std::string &name, const std::vector<std::string>& names)
  {
    std::string res;
    res += (char)Signature::Type_Tuple;
    for (unsigned int i = 0; i < vt.size(); ++i)
      res += vt[i]->signature().toString();
    res += (char)Signature::Type_Tuple_End;
    if (names.size() == vt.size())
      res += makeTupleAnnotation(name, names);
    return qi::Signature(res);
  }

  qi::Signature makeOptionalSignature(const qi::Signature& value)
  {
    const std::string res = [&]() {
      std::stringstream s;
      s << static_cast<char>(Signature::Type_Optional) << value.toString();
      return s.str();
    }();
    return qi::Signature(res);
  }

  float Signature::isConvertibleTo(const qi::Signature& b) const
  {
    /* The returned float is just a basic heuristic, it does not handle:
     * - comparison between integral types
     * - Weaker error score for deeper (in containers) struct.
     */
    float error = 0.f;
    float childErr = 1.0f;
    const auto calculateFactor = [&] {
      return childErr * (1.f - error / 100.f);
    };
    static const char numeric[] = "bcCwWiIlLfd";
    static const char integral[] = "bcCwWiIlL";
    static const char floating[] = "fd";
    static const char container[] = "[{(";

    Signature::Type s = type();
    Signature::Type d = b.type();

    //varargs are just vector, handle them that way
    if (s == Type_VarArgs)
      s = Type_List;
    if (d == Type_VarArgs)
      d = Type_List;
    if (d == Type_Void)
      return calculateFactor();
    if (d == Type_Unknown)
    {
      // We cannot anwser the question for unknown types. So let it pass
      // and the conversion code will decide.
      // Type_Unknown is not serializable anyway.
      if (s != Type_Unknown)
        error += 10.f; // Weird but can happen with object pointers
      return calculateFactor();
    }

    if (d == Type_Dynamic || // Dynamic can convert to whatever
        s == Type_None) // None means parent is empty container
    {
      error += 5.f; // big malus for dynamic
      return calculateFactor();
    }

    // Source is convertible to an optional if source's type is convertible to the destination
    // optional value type or if source's type is void. For instance, int is convertible to
    // optional<int>, but also int is convertible to optional<dynamic>
    if (d == Type_Optional)
    {
      // If source is also an optional then we are performing a optional to optional conversion.
      // By design this is allowed if source value type is convertible to dest value type.
      if (s == Type_Optional)
        return children()[0].isConvertibleTo(b.children()[0]);

      // Converting void to optional means constructing an empty optional. This design choice was
      // made to simplify conversion from language bindings where types are not explicit (like
      // python).
      else if (s == Type_Void)
        return calculateFactor();

      return isConvertibleTo(b.children()[0]);
    }
    else if (s == Type_Optional)
    {
      // The case where dest is dynamic is already handled above, and is the same for optionals:
      // converting optionals to dynamic is allowed, but converting optionals to anything else is
      // not.
      return 0.f;
    }

    // Main switch on source sig
    if (strchr(numeric, s))
    { // Numeric
      if (!strchr(numeric, d))
        return 0.f;
      // Distance heuristic
      if (strchr(integral, s) && strchr(floating, d))
        error += 2.f; // integral->float
      if (strchr(floating, s) && strchr(integral, d))
        error += 3.f; // float->integral
      if (s!= 'b' && d == 'b')
        error += 4.f; // ->bool
    }
    else if (strchr(container, s))
    { // Container, list or map
      if (d != s)
        return 0.f; // Must be same container
      if (children().size() != b.children().size())
      {
        if (s != Type_Tuple)
          return 0.f;
        // Special case for same-named tuples that might be compatible
        std::string aSrc = annotation();
        std::string aDst = b.annotation();
        // This mode is recommended only for tests where it is more
        // conveniant to have differently named structs
        static bool requireSameName = qi::os::getenv("QI_IGNORE_STRUCT_NAME").empty();
        if (!requireSameName)
          return (aSrc.empty() || aDst.empty()) ? 0.f : 0.1f;

        size_t pSrc = aSrc.find_first_of(",");
        size_t pDst = aDst.find_first_of(",");
        if (pSrc == pDst && pSrc != aSrc.npos && !memcmp(aSrc.data(), aDst.data(), pSrc))
          return 0.1f;

        return 0.f;
      }
      SignatureVector::const_iterator its;
      SignatureVector::const_iterator itd;
      itd = b.children().begin();
      for (its = children().begin(); its != children().end(); ++its, ++itd) {
        float childRes = its->isConvertibleTo(*itd);
        if (childRes == 0.f)
          return 0.f; // Just check subtype compatibility
        // we got this far, if there is an error in child, make it lower
        // [s] -> m should have a greater convertibility than [s] -> [m]
        childErr *= 1.0f - (1.0f - childRes) * 0.95f;
      }
      QI_ASSERT(its==children().end() && itd==b.children().end()); // we already exited on size mismatch
    }
    else if (d != s)
      return 0.f;
    return calculateFactor();
  }

  Signature Signature::fromType(Signature::Type t)
  {
    char res[2] = { (char)t, 0};
    return Signature(res);
  }

  //find a open char, starting from end, finishing at start
  static size_t _find_begin(const std::string &str, size_t start, char open, char close)
  {
    int count = 0; // start at 0

    if (str.size() == 0) {
      qiLogDebug() << "_find_begin error: given signature is empty.";
      return std::string::npos;
    }

    size_t i = str.size() - 1;

    if (str[i] != close) {
      qiLogDebug() << "_find_begin error:" << str << "(" << i << ") is not " << close;
      return std::string::npos;
    }

    while (i > start)
    { // update count with current before testing
      if (str[i] == close)
        ++count;
      else if (str[i] == open)
        --count;
      if (!count)
        return i;
      --i;
    }
    return std::string::npos;
  }

  static size_t _find_end(const std::string &str, size_t index, char copen, char close)
  {
    int         count  = 0;

    if (str[index] != copen) {
      qiLogDebug() << "_find_end error:" << str << "(" << index << ") is not " << copen;
      return std::string::npos;
    }

    while ((index < str.size()))
    {
      if (str[index] == copen)
        count++;
      if (str[index] == close)
        count--;
      if (count == 0)
        return index;
      index++;
    }
    return std::string::npos;
  }

  class SignaturePrivate {
  public:
    void parseChildren(const std::string &signature, size_t index);
    void eatChildren(const std::string &signature, size_t idxStart, size_t expectedEnd, int elementCount);
    void init(const std::string &signature, size_t begin, size_t end);

    std::string            _signature;
    std::vector<Signature> _children;
  };

  static size_t findNext(const std::string &signature, size_t index) {

    if (index >= signature.size())
      return std::string::npos;

    //verify that the current signature is correct
    switch(static_cast<qi::Signature::Type>(signature[index]))
    {
      case qi::Signature::Type_Void:
      case qi::Signature::Type_Bool:
      case qi::Signature::Type_Int8:
      case qi::Signature::Type_UInt8:
      case qi::Signature::Type_Int16:
      case qi::Signature::Type_UInt16:
      case qi::Signature::Type_Int32:
      case qi::Signature::Type_UInt32:
      case qi::Signature::Type_Int64:
      case qi::Signature::Type_UInt64:
      case qi::Signature::Type_Float:
      case qi::Signature::Type_Double:
      case qi::Signature::Type_String:
      case qi::Signature::Type_Dynamic:
      case qi::Signature::Type_Raw:
      case qi::Signature::Type_Object:
      case qi::Signature::Type_Unknown:
      case qi::Signature::Type_None:
        index++;
        break;
      case qi::Signature::Type_List:
        index = _find_end(signature, index, '[', ']');
        if (index == std::string::npos)
          return std::string::npos;
        index++;
        break;
      case qi::Signature::Type_VarArgs:
      case qi::Signature::Type_KwArgs:
      case qi::Signature::Type_Optional:
        index++;
        index = findNext(signature, index);
        if (index == std::string::npos)
          return std::string::npos;
        break;
      case qi::Signature::Type_Map:
        index = _find_end(signature, index, '{', '}');
        if (index == std::string::npos)
          return std::string::npos;
        index++;
        break;
      case qi::Signature::Type_Tuple:
        index = _find_end(signature, index, '(', ')');
        if (index == std::string::npos)
          return std::string::npos;
        index++;
        break;
      default:
        qiLogDebug() << "Signature element is invalid: '" << signature << "'";
        return std::string::npos;
    }
    // handle annotation
    if (index < signature.size() && signature[index] == '<')
    {
      index = _find_end(signature, index, '<', '>');
      if (index == std::string::npos)
        return std::string::npos;
      index++;
    }
    return index;
  }

  void SignaturePrivate::eatChildren(const std::string &signature, size_t idxStart, size_t expectedEnd, int elementCount = -1) {
    int i = 0;

    //empty tuple, move on!
    if (elementCount == -1 || elementCount == 0) {
      if (idxStart == expectedEnd)
        return;
    }
    //iterate over each subelement.
    while (true) {
      size_t idxStop = findNext(signature, idxStart);
      _children.push_back(qi::Signature(signature, idxStart, idxStop));
      ++i;
      //ouch too far..
      if (idxStop > expectedEnd) {
        std::stringstream ss;
        ss << "Bad element for signature '" << signature << "' at pos:" << idxStart << " (gone too far)";
        throw std::runtime_error(ss.str());
      }
      if (elementCount == -1) {
        //check if it's the last item.
        if (idxStop == expectedEnd)
          return;
      } else if (elementCount == i) {
        //we have the good number of item, are we at the good position?
        if (idxStop != expectedEnd) {
          std::stringstream ss;
          ss << "Bad element for signature '" << signature << "' at pos:" << idxStart;
          throw std::runtime_error(ss.str());
        }
        return;
      }
      if (idxStart == idxStop)
        throw std::runtime_error("Infinite loop detected..");
      idxStart = idxStop;
    }
  }

  void SignaturePrivate::parseChildren(const std::string &signature, size_t index) {
    if (index >= signature.size())
      throw std::runtime_error("Invalid index");

    //verify that the current signature is correct
    switch(static_cast<qi::Signature::Type>(signature[index]))
    {
      case qi::Signature::Type_Void:
      case qi::Signature::Type_Bool:
      case qi::Signature::Type_Int8:
      case qi::Signature::Type_UInt8:
      case qi::Signature::Type_Int16:
      case qi::Signature::Type_UInt16:
      case qi::Signature::Type_Int32:
      case qi::Signature::Type_UInt32:
      case qi::Signature::Type_Int64:
      case qi::Signature::Type_UInt64:
      case qi::Signature::Type_Float:
      case qi::Signature::Type_Double:
      case qi::Signature::Type_String:
      case qi::Signature::Type_Dynamic:
      case qi::Signature::Type_Raw:
      case qi::Signature::Type_Object:
      case qi::Signature::Type_Unknown:
      case qi::Signature::Type_None:
        return;
      case qi::Signature::Type_List: {
        const auto index_should_stop = _find_end(signature, index, '[', ']');
        eatChildren(signature, index + 1, index_should_stop, 1);
        break;
      }
      case qi::Signature::Type_KwArgs:
      case qi::Signature::Type_VarArgs:
      case qi::Signature::Type_Optional:
      {
        const auto index_should_stop = findNext(signature, index);
        eatChildren(signature, index + 1, index_should_stop, 1);
        break;
      }
      case qi::Signature::Type_Map: {
        const auto index_should_stop = _find_end(signature, index, '{', '}');
        eatChildren(signature, index + 1, index_should_stop, 2);
        break;
      }
      case qi::Signature::Type_Tuple: {
        const auto index_should_stop = _find_end(signature, index, '(', ')');
        eatChildren(signature, index + 1, index_should_stop);
        break;
      }
      default: {
        std::stringstream ss;
        ss << "Signature element is invalid: '" << signature << "'";
        throw std::runtime_error(ss.str());
      }
    }
  }

  //empty signature are invalid
  void SignaturePrivate::init(const std::string &signature, size_t begin, size_t end) {
    size_t index = findNext(signature, begin);
    if (index != end) {
      throw std::runtime_error("Invalid signature");
    }
    parseChildren(signature, begin);
    _signature.assign(signature, begin, end - begin);
  }

  Signature::Signature()
    : _p(boost::make_shared<SignaturePrivate>())
  {
  }

  Signature::Signature(const char *signature)
    : _p(boost::make_shared<SignaturePrivate>())
  {
    _p->_signature.assign(signature);
    _p->init(_p->_signature, 0, _p->_signature.size());
  }

  Signature::Signature(const std::string &signature)
    : _p(boost::make_shared<SignaturePrivate>())
  {
    _p->init(signature, 0, signature.size());
  }

  Signature::Signature(const std::string &signature, size_t begin, size_t end)
    : _p(boost::make_shared<SignaturePrivate>())
  {
    _p->init(signature, begin, end);
  }

  bool Signature::isValid() const {
    return type() != qi::Signature::Type_None;
  }

  const std::string& Signature::toString() const {
    return _p->_signature;
  }

  bool Signature::hasChildren() const {
    return children().size() != 0;
  }

  const SignatureVector& Signature::children() const {
    return _p->_children;
  }

  std::string Signature::annotation()const {
    if (_p->_signature.empty())
      return std::string();
    if (_p->_signature[_p->_signature.length()-1] != '>')
      return std::string();
    size_t begin = _find_begin(_p->_signature, 0, '<', '>');
    if (begin != std::string::npos)
      return std::string(_p->_signature.substr(begin + 1, _p->_signature.size() - begin - 2));
    return std::string();
  }

  std::string Signature::toPrettySignature() const {
    if (!isValid())
      return std::string("Invalid");
    SignatureConvertor sc(this);
    return sc.signature();
  }

  Signature::Type Signature::type() const {
    if (_p->_signature.empty())
      return Type_None;
    return static_cast<Type>(_p->_signature[0]);
  }

  //TODO: There is many Room for improvement HERE
  std::vector<std::string> signatureSplit(const std::string &fullSignature) {
    std::vector<std::string> ret;
    std::string retSig;
    std::string parSig;
    std::string funcName;

    size_t idx1 = fullSignature.find("::");
    if (idx1 != fullSignature.npos) {
      // If :: are given, expect parameter tuple.
      if (fullSignature.find("(") == fullSignature.npos || fullSignature.find(")") == fullSignature.npos)
        throw std::runtime_error("Signature " + fullSignature + " is not valid");

      funcName = fullSignature.substr(0, idx1);
      // we should have a valid signature
      qi::Signature parent("(" + fullSignature.substr(idx1+2) + ")");
      const qi::SignatureVector& childs = parent.children();

      // Expect valid signatures.
      if (fullSignature.substr(idx1+2) == "" || parent.isValid() == false)
        throw std::runtime_error("Signature " + fullSignature + " is not valid");

      if (childs.size() == 2)
      {
        retSig = childs.at(0).toString();
        parSig = childs.at(1).toString();
      }
      else if (childs.size() == 1)
        parSig = childs.at(0).toString();
    } else {
      funcName = fullSignature;
    }
    ret.push_back(retSig);
    ret.push_back(funcName);
    ret.push_back(parSig);
    return ret;
  }

  AnyValue Signature::toData() const
  {
    AnyValueVector res;
    std::string t;
    t += (char)type();
    res.push_back(AnyValue::from(t));
    if (hasChildren()) {
      const SignatureVector& cvec = children();
      SignatureVector::const_iterator it;
      AnyValueVector sub;
      for (it = cvec.begin(); it != cvec.end(); ++it) {
        sub.push_back(it->toData());
      }
      res.push_back(AnyValue::from(sub));
    }
    else
      res.push_back(AnyValue::from(AnyValueVector()));
    res.push_back(AnyValue::from(annotation()));
    return AnyValue::from(res);
  }

  //compare signature without taking annotation into account
  bool operator==(const Signature& lhs, const Signature& rhs)
  {
    if (lhs.type() != rhs.type())
      return false;
    if (lhs.children().size() != rhs.children().size())
      return false;
    SignatureVector::const_iterator it;
    SignatureVector::const_iterator it2;
    it2 = lhs.children().begin();
    for (it = rhs.children().begin(); it != rhs.children().end(); ++it) {
      if (it2 == lhs.children().end()) //not the same number of elements
        return false;
      if (it->type() != it2->type()) //different types
        return false;
      if (*it != *it2) //different children
        return false;
      ++it2;
    }
    return true;
  }

}

char* signature_to_json(const char* sig)
{
  static char* resc = nullptr;
  std::string res;
  try {
    qi::Signature s(sig);
    res = qi::encodeJSON(s.toData());
  } catch (const std::exception& e) {
    qiLogVerbose() << e.what();
    return  nullptr;
  }
  free(resc);
  resc = qi::os::strdup(res.c_str());
  return resc;
}

max_stars_repo_name: arntanguy/libqi

max_issues_repo_name: arntanguy/libqi

max_forks_repo_name: arntanguy/libqi


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/memory/aligned_input_range.hpp>
#include <boost/simd/memory/allocator.hpp>
#include <boost/simd/memory/dynarray.hpp>
#include <boost/simd/sdk/simd/pack.hpp>
#include <boost/simd/include/functions/splat.hpp>
#include <boost/range.hpp>

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/tests/exceptions.hpp>

#include <vector>

template<typename Range, typename Out>
inline Out mycopy(Range const& r, Out dst)
{
  typedef typename std::iterator_traits<Out>::value_type T;
  typedef typename boost::range_iterator<Range>::type it_t;

  it_t begin = boost::begin(r);
  it_t end = boost::end(r);

  for(; begin != end; ++begin) *dst++ = T(*begin);

  return dst;
}

NT2_TEST_CASE_TPL(distance, BOOST_SIMD_TYPES)
{
  using std::iterator_traits;
  using boost::simd::aligned_input_range;
  using boost::simd::pack;
  using boost::simd::allocator;

  std::vector<T, allocator<T> > data(pack<T>::static_size*3);

  NT2_TEST_EQUAL( std::distance ( boost::begin(aligned_input_range(data))
                                , boost::end(aligned_input_range(data))
                                )
                , 3
                );
}

NT2_TEST_CASE_TPL(size_check, BOOST_SIMD_TYPES)
{
  using std::iterator_traits;
  using boost::simd::aligned_input_range;
  using boost::simd::pack;
  using boost::simd::allocator;
  using boost::begin;
  using boost::end;

  std::vector<T, allocator<T> > data(pack<T>::static_size*3-1);
  NT2_TEST_ASSERT( aligned_input_range(data) );
}

NT2_TEST_CASE_TPL(iteration, BOOST_SIMD_TYPES)
{
  using std::iterator_traits;
  using boost::simd::aligned_input_range;
  using boost::simd::allocator;
  using boost::simd::dynarray;
  using boost::simd::pack;
  using boost::simd::splat;
  using boost::begin;
  using boost::end;

  dynarray< pack<T> > dst(3);
  dynarray< pack<T> > ref(3);
  std::vector<T, allocator<T> > data(pack<T>::static_size*3);

  for(std::size_t i=0;i<data.size();i++)
    data[i] = i/pack<T>::static_size+1;

  for(std::size_t i=0;i<ref.size();i++)
    ref[i] = splat< pack<T> >(i+1);

  mycopy( aligned_input_range(data), dst.begin());

  NT2_TEST_EQUAL( ref, dst );
}

ext: cpp


text:
// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

// Includes ====================================================================
#include <Magick++/Drawable.h>

// Declarations ================================================================
#include <Magick++.h>

// Using =======================================================================
using namespace boost::python;

namespace  {

struct Magick_DrawableTextDecoration_Wrapper: Magick::DrawableTextDecoration
{
    Magick_DrawableTextDecoration_Wrapper(PyObject* py_self_, MagickCore::DecorationType p0):
        Magick::DrawableTextDecoration(p0), py_self(py_self_) {}

    Magick_DrawableTextDecoration_Wrapper(PyObject* py_self_, const Magick::DrawableTextDecoration& p0):
        Magick::DrawableTextDecoration(p0), py_self(py_self_) {}

    PyObject* py_self;
};

}// namespace

// Module ======================================================================
void Export_pyste_src_DrawableTextDecoration()
{
    class_< Magick::DrawableTextDecoration, Magick_DrawableTextDecoration_Wrapper >("DrawableTextDecoration", init< MagickCore::DecorationType >())
        .def(init< const Magick::DrawableTextDecoration& >())
        .def("decoration", (void (Magick::DrawableTextDecoration::*)(MagickCore::DecorationType) )&Magick::DrawableTextDecoration::decoration)
        .def("decoration", (MagickCore::DecorationType (Magick::DrawableTextDecoration::*)() const)&Magick::DrawableTextDecoration::decoration)
    ;
implicitly_convertible<Magick::DrawableTextDecoration,Magick::Drawable>();
}

max_stars_repo_name: jeikabu/lumberyard

max_issues_repo_name: jeikabu/lumberyard

max_forks_repo_name: jeikabu/lumberyard


text:
//
// Created by 范炜东 on 2019/4/22.
//

#include <iostream>
#include <boost/program_options.hpp>
#include <Poco/AutoPtr.h>
#include <Poco/Logger.h>
#include <Poco/Util/LoggingConfigurator.h>
#include <Poco/Util/PropertyFileConfiguration.h>

using Poco::AutoPtr;
using Poco::Logger;
using Poco::Util::LoggingConfigurator;
using Poco::Util::PropertyFileConfiguration;

int main(int argc, char *argv[]) {
  boost::program_options::options_description cmdline_options("命令行参数");
  cmdline_options.add_options()
          ("help", "帮助信息")
          ("config-file", boost::program_options::value<std::string>(), "设置自定义配置文件");
  try {
    boost::program_options::variables_map vm;
    boost::program_options::store(boost::program_options::parse_command_line(argc, argv, cmdline_options), vm);
    boost::program_options::notify(vm);
    if (vm.count("help")) {
      std::cout << cmdline_options << std::endl;
      return 1;
    }

    if (argc < 2) {
      std::cerr << "Missing configuration path!" << std::endl;
      return -1;
    }
    std::string properties_file = vm["config-file"].as<std::string>() + "log.properties";
    std::cout << "Loading configuration file: " << properties_file << std::endl;
    AutoPtr<PropertyFileConfiguration> pConf = new PropertyFileConfiguration(properties_file);
    LoggingConfigurator cfg;
    cfg.configure(pConf);

    Logger &basic = Logger::root();
    Logger &chat = Logger::get("chat");
    Logger &server = Logger::get("server");

    // 输出到屏幕
    basic.error("root error", __FILE__, __LINE__);
    basic.information("root information", __FILE__, __LINE__);

    // 输出到文件
    chat.information("chat information", __FILE__, __LINE__);
    chat.debug("chat debug", __FILE__, __LINE__);

    // 输出到文件 & 文件自动备份
    for (int i = 0; i < 20; i++)
      server.information("server error", __FILE__, __LINE__);

  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

ext: cc

max_stars_repo_name: silvermagic/Practice

max_issues_repo_name: silvermagic/Practice

max_forks_repo_name: silvermagic/Practice


text:
// Copyright (c) 2015
// Author: Chrono Law
#include <std.hpp>
using namespace std;

#define BOOST_ASIO_DISABLE_STD_CHRONO
//#define BOOST_ASIO_ENABLE_HANDLER_TRACKING
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/asio.hpp>
using namespace boost::asio;
using namespace boost::system;

class client
{
    typedef client                        this_type;
    typedef ip::tcp::endpoint           endpoint_type;
    typedef ip::address               address_type;
    typedef ip::tcp::socket             socket_type;
    typedef shared_ptr<socket_type>   sock_ptr;
    typedef vector<char>                buffer_type;
private:
    io_service                          m_io;
    buffer_type                         m_buf;
    endpoint_type                       m_ep;
public:
    client():
        //m_buf(100,0),
        m_buf(5,0),
        m_ep(address_type::from_string("127.0.0.1"), 6688)
    {
        start();
    }

    void run()
    {
        m_io.run();
    }

    //void start()
    //{
    //    sock_ptr sock(new socket_type (m_io));
    //    sock->async_connect(m_ep,
    //            bind(&this_type::conn_handler,this,
    //                boost::asio::placeholders::error, sock));
    //}

    void start()
    {
        sock_ptr sock(new socket_type (m_io));

        //function<void(const error_code&,std::size_t)> handler =
        //    [this, sock, handler](const error_code& ec, std::size_t)
        //    {
        //        if (ec)
        //        {   return;     }
        //        cout << &m_buf[0] << endl;

        //        //sock->async_read_some(buffer(m_buf), handler);
        //    };

        sock->async_connect(m_ep,
            [this, sock](const error_code& ec)
            {
                if (ec)
                {   return;     }

                sock->async_read_some(buffer(m_buf),
                    [this, sock](const error_code& ec,std::size_t)
                    {
                        read_handler(ec, sock);
                    }
                );
            }
        );
    }

    void conn_handler(const error_code& ec, sock_ptr sock)
    {
        if (ec)
        {   return;     }

        cout << "recive from " << sock->remote_endpoint().address();

        sock->async_read_some(buffer(m_buf),
                bind(&client::read_handler, this,
                    boost::asio::placeholders::error,
                    //boost::asio::placeholders::bytes_transferred,
                    sock));

        //start();
    }
    void read_handler(const error_code& ec, /*std::size_t n,*/ sock_ptr sock)
    {
        if (ec)
        {   return;     }
        cout << &m_buf[0] << endl;

        sock->async_read_some(buffer(m_buf),
                bind(&client::read_handler, this,
                    boost::asio::placeholders::error,
                    //boost::asio::placeholders::bytes_transferred,
                    sock));
    }
};

int main()
{
    cout << "client start." << endl;
    client cl;
    cl.run();

}


text:
#include "pch.hpp"
#include <string>
#include <boost/algorithm/string/replace.hpp>
#include "opstruct.h"

std::wstring operation::debugTreeInternal(const std::wstring& curOp) const
{
    std::wstring dbgMsg(L"- ");
    dbgMsg.append(curOp);
    dbgMsg.append(L"\r\n");
    dbgMsg.append(operandA->debugTree());
    dbgMsg.append(L"\r\n");
    dbgMsg.append(operandB->debugTree());
    boost::algorithm::replace_all(dbgMsg, L"\r\n", L"\r\n   ");
    return dbgMsg;
}
void operation::reorderTree()
{
    if (operandA->getPriorityClass() > operandB->getPriorityClass())
        std::swap(operandA,operandB);
    operandA->reorderTree();
    operandB->reorderTree();
};
unsigned __int32 operation::getPriorityClass() const
{
    unsigned __int32 classA, classB;
    classA = operandA->getPriorityClass();
    classB = operandB->getPriorityClass();
    if (classA > classB)
        return classA;
    return classB;

};
operation::operation(std::shared_ptr<criterion> a, std::shared_ptr<criterion> b) : operandA(a), operandB(b)
{}
BOOL andAndClass::include(FileData &file) const
{
    if (this->operandA->include(file) && this->operandB->include(file))
        return true;
    return false;
}
unsigned int andAndClass::directoryCheck(const std::wstring& directory) const
{
    unsigned int resA, resB;
    resA = operandA->directoryCheck(directory);
    resB = operandB->directoryCheck(directory);
    if (resA == DIRECTORY_DONTCARE && resB == DIRECTORY_DONTCARE)
        return DIRECTORY_DONTCARE;
    if (resA == DIRECTORY_DONTCARE)
        return resB;
    if (resB == DIRECTORY_DONTCARE)
        return resA;
    return resA && resB;
}
andAndClass::andAndClass(std::shared_ptr<criterion> a, std::shared_ptr<criterion> b) : operation(a, b)
{}
std::wstring andAndClass::debugTree() const
{
    return debugTreeInternal(L"AND");
}
BOOL orAndClass::include(FileData &file) const
{
    if (this->operandA->include(file))
        return true;
    if (this->operandB->include(file))
        return true;
    return false;
}
unsigned int orAndClass::directoryCheck(const std::wstring& directory) const
{
    unsigned int resA, resB;
    resA = operandA->directoryCheck(directory);
    resB = operandB->directoryCheck(directory);
    if (resA == DIRECTORY_DONTCARE && resB == DIRECTORY_DONTCARE)
        return DIRECTORY_DONTCARE;
    if (resA == DIRECTORY_DONTCARE)
        return resB;
    if (resB == DIRECTORY_DONTCARE)
        return resA;
    return resA || resB;
}
orAndClass::orAndClass(std::shared_ptr<criterion> a, std::shared_ptr<criterion> b) : operation(a, b)
{}
std::wstring orAndClass::debugTree() const
{
    return debugTreeInternal(L"OR");
}
BOOL xorAndClass::include(FileData &file) const
{
    BOOL resA = this->operandA->include(file);
    BOOL resB = this->operandB->include(file);
    return (resA || resB) && !(resA && resB);
}
unsigned int xorAndClass::directoryCheck(const std::wstring& directory) const
{
    unsigned int resA, resB;
    resA = operandA->directoryCheck(directory);
    resB = operandB->directoryCheck(directory);
    if (resA == DIRECTORY_DONTCARE && resB == DIRECTORY_DONTCARE)
        return DIRECTORY_DONTCARE;
    if (resA == DIRECTORY_DONTCARE)
        return resB;
    if (resB == DIRECTORY_DONTCARE)
        return resA;
    return (resA || resB) && !(resA && resB);
}
xorAndClass::xorAndClass(std::shared_ptr<criterion> a, std::shared_ptr<criterion> b) : operation(a, b)
{}
std::wstring xorAndClass::debugTree() const
{
    return debugTreeInternal(L"XOR");
}
void notAndClass::reorderTree()
{
    operand->reorderTree();
}
unsigned __int32 notAndClass::getPriorityClass() const
{
    return operand->getPriorityClass();
}
BOOL notAndClass::include(FileData &file) const
{
    return !(operand->include(file));
}
unsigned int notAndClass::directoryCheck(const std::wstring& directory) const
{
    switch(operand->directoryCheck(directory))
    {
    case DIRECTORY_DONTCARE:
    case DIRECTORY_INCLUDE:
        return DIRECTORY_DONTCARE;
    case DIRECTORY_EXCLUDE:
        return DIRECTORY_INCLUDE;
    }
    return DIRECTORY_DONTCARE;
}
notAndClass::notAndClass(std::shared_ptr<criterion> a) : operand(a)
{}
std::wstring notAndClass::debugTree() const
{
    std::wstring dbgMsg(L"- NOT\r\n");
    dbgMsg.append(operand->debugTree());
    boost::algorithm::replace_all(dbgMsg, L"\r\n", L"\r\n   ");
    return dbgMsg;
}
void bracketClass::reorderTree()
{
    std::sort(expr.begin(), expr.end(),criterionByPriorityClass);
}
unsigned __int32 bracketClass::getPriorityClass() const
{
    //Create a vector with the same size as the expression
    std::vector<__int32> priNumbers(expr.size());
    //Transform the expression items into priority numbers
    std::transform(expr.begin(), expr.end(), priNumbers.begin(), getPriorityFunctor);
    return *(std::max_element(priNumbers.begin(), priNumbers.end()));
}
BOOL bracketClass::include(FileData &file) const
{
    for (register unsigned int idx = 0; idx < expr.size(); idx++)
        if (!expr[idx]->include(file))
            return FALSE;
    return TRUE;
}
unsigned int bracketClass::directoryCheck(const std::wstring& directory)
{
    bool allDontcares = true;
    for (register unsigned int idx = 0; idx < expr.size(); idx++)
    {
        if (!expr[idx]->directoryCheck(directory))
            return DIRECTORY_EXCLUDE;
        if (expr[idx]->directoryCheck(directory) == DIRECTORY_INCLUDE)
            allDontcares = false;
    }
    if (allDontcares)
        return DIRECTORY_DONTCARE;
    else
        return DIRECTORY_INCLUDE;
}
bracketClass::bracketClass(std::vector<std::shared_ptr<criterion> > exprA): expr(exprA)
{
    assert(expr.size() > 1);
}
std::wstring bracketClass::debugTree() const
{
    std::wstring dbgMsg(L"- BRACKET\r\n");
    for (std::vector<std::shared_ptr<criterion> >::const_iterator it = expr.begin(); it != expr.end(); it++)
    {
        dbgMsg.append((*it)->debugTree());
        if (it + 1 != expr.end())
            dbgMsg.append(L"\r\n");
    }
    boost::algorithm::replace_all(dbgMsg, L"\r\n", L"\r\n   ");
    return dbgMsg;
}
void ifClass::reorderTree()
{
    condVal->reorderTree();
    tVal->reorderTree();
    if (fVal)
        fVal->reorderTree();
}
unsigned __int32 ifClass::getPriorityClass() const
{
    unsigned __int32 condValClass, tValClass, fValClass;
    condValClass = condVal->getPriorityClass();
    tValClass = tVal->getPriorityClass();
    if (fVal)
        fValClass = fVal->getPriorityClass();
    else
        fValClass = 0; //Min value means it won't matter in following comparison.
    if (condValClass >= tValClass)
    {
        if (condValClass >= fValClass)
            return condValClass;
        else
            return fValClass;
    } else
    {
        if (tValClass >= fValClass)
            return tValClass;
        else
            return fValClass;
    }
}
BOOL ifClass::include(FileData &file) const
{
    if (condVal->include(file))  //If we have this item
    {
        return tVal->include(file); //Return valueIfTrue
    } else                      //Otherwise
    {
        if (!fVal)              //If there is no ELSE item,
            return true;        //assume true
        return fVal->include(file); //Otherwise return value of the
                                //else part of the node.
    }
}
unsigned int ifClass::directoryCheck(const std::wstring& directory) const
{
    if (condVal->directoryCheck(directory))    //See rationale in include() method
    {
        return tVal->directoryCheck(directory);
    } else
    {
        if (!fVal)
            return DIRECTORY_DONTCARE;
        return fVal->directoryCheck(directory);
    }
}
ifClass::ifClass(std::shared_ptr<criterion> condition,std::shared_ptr<criterion> valueIfTrue,std::shared_ptr<criterion> valueIfFalse)
    : condVal(condition), tVal(valueIfTrue), fVal(valueIfFalse)
{}
std::wstring ifClass::debugTree() const
{
    std::wstring result;

    std::wstring condMsg(L"- IF\r\n");
    condMsg.append(condVal->debugTree());
    boost::algorithm::replace_all(condMsg, L"\r\n", L"\r\n   ");
    result.assign(condMsg);
    result.append(L"\r\n");

    std::wstring thenMsg(L"- THEN\r\n");
    thenMsg.append(tVal->debugTree());
    boost::algorithm::replace_all(thenMsg, L"\r\n", L"\r\n   ");
    result.append(thenMsg);

    std::wstring elseMsg;
    if (fVal)
    {
        result.append(L"\r\n");
        elseMsg.assign(L"- ELSE\r\n");
        elseMsg.append(fVal->debugTree());
        boost::algorithm::replace_all(elseMsg, L"\r\n", L"\r\n   ");
        result.append(elseMsg);
    }

    return result;
}

void operation::makeNonRecursive()
{
    operandA->makeNonRecursive();
    operandB->makeNonRecursive();
}

void notAndClass::makeNonRecursive()
{
    operand->makeNonRecursive();
}

void bracketClass::makeNonRecursive()
{
    for (std::vector<std::shared_ptr<criterion> >::iterator it = expr.begin(); it != expr.end(); it++)
    {
        (*it)->makeNonRecursive();
    }
}

void ifClass::makeNonRecursive()
{
    condVal->makeNonRecursive();
    tVal->makeNonRecursive();
    if (fVal.get())
        fVal->makeNonRecursive();
}

max_stars_repo_name: BillyONeal/pevFind

max_issues_repo_name: BillyONeal/pevFind

max_forks_repo_name: BillyONeal/pevFind


text:
#ifndef __PAUTH_TYPES_HPP__
#define __PAUTH_TYPES_HPP__

#include "molecular.hpp"
#include <armadillo>
#include <tuple>

namespace pauth {

class metropolis;
class abstract_potential;

using callback = std::function<void(const metropolis &)>;
using stopping_criterion = std::function<bool(const metropolis &)>;
using data_accessor = std::function<const arma::mat &(const metropolis &)>;
using value_accessor = std::function<double(const metropolis &)>;

using metric = std::tuple<
                std::function<arma::vec(const arma::vec&, const arma::vec&,
                                     const arma::vec&)>,
                std::function<double(const arma::vec&, const arma::vec&,
                                     const arma::vec&)>
               >;
using bc_ret = std::tuple<bool, arma::vec>;
using bc = std::function<bc_ret(metropolis &, const size_t, arma::vec&)>;
using trial_move_generator = std::function<arma::vec(const arma::mat&, const size_t)>;
using acc = std::function<bool(const metropolis &, const double, const double)>;
using seed_gen = std::function<unsigned()>;

} // namespace pauth

/*! \brief Helper function for printing the integer value of an enum class
 *
 * \param   value   Enumeration value
 * \return          Enumeration value converted to integer
 */
template <typename Enumeration>
auto as_integer(Enumeration const value) ->
    typename std::underlying_type<Enumeration>::type {

  return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}

#endif

ext: hpp

max_stars_repo_name: grasingerm/port-authority

max_issues_repo_name: grasingerm/port-authority

max_forks_repo_name: grasingerm/port-authority


text:
/*
 * patReadChoiceSetFromKML.cc
 *
 *  Created on: May 3, 2012
 *      Author: jchen
 */

#include "patReadChoiceSetFromKML.h"
#include "kml/dom.h"
#include "kml/base/file.h"
#include "patException.h"
#include "patLogProbaToProba.h"
#include "patSampleDiscreteDistribution.h"
#include <xmlwrapp/xmlwrapp.h>
#include <boost/xpressive/xpressive.hpp>
#include "patRandomNumber.h"
#include <map>
#include "patChoiceSet.h"
using namespace std;
using kmldom::FeaturePtr;
using kmldom::KmlPtr;
using kmldom::ElementPtr;
using kmldom::FolderPtr;

using namespace boost::xpressive;
patReadChoiceSetFromKML::patReadChoiceSetFromKML(
		const patNetworkElements* a_network) :
		m_network(a_network) {
}

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

map<patOd, patChoiceSet> patReadChoiceSetFromKML::read(string file_name, const patRandomNumber& rnd) {
	map<patOd, patChoiceSet> ods;
	xml::tree_parser parser(file_name.c_str());

	if (!parser) {
		WARNING("Error while parsing " << file_name);
		throw RuntimeException("no file is given");

	}
	//DEBUG_MESSAGE("file loaded");
	xml::document &doc = parser.get_document();

	xml::node root_node = doc.get_root_node();
//	xml::node::node_type the_type = root_node.get_type();
	xml::node::iterator root_iter(root_node.begin());
	xml::node::iterator root_end(root_node.end());

	for (; root_iter != root_end; ++root_iter) {
		if (string(root_iter->get_name()) != string("Document")) {
			continue;
		}
		xml::node::iterator doc_node = root_iter;
		//DEBUG_MESSAGE(doc_node->get_name());
		xml::node::iterator paths_folder;
		for (xml::node::iterator od_iter = doc_node->begin();
				od_iter != doc_node->end(); ++od_iter) {
			if (od_iter->is_text()) {
				continue;
			}

			if (string(od_iter->get_name()) == string("Folder")) {
				patOd od;
				vector<patMultiModalPath> paths;
				vector<double> log_weights;
				patChoiceSet od_choice_set;
				unsigned nbr_paths = 0;
				for (xml::node::iterator path_iter = od_iter->begin();
						path_iter != od_iter->end(); ++path_iter) {
					if (path_iter->is_text()) {
						continue;
					}

					if (string(path_iter->get_name()) == string("name")) {
						string od_name = path_iter->get_content();
						sregex rex = sregex::compile("(\\d+)-(\\d+)");
						smatch what;

						if (regex_search(od_name, what, rex)) {

							int origin_id = atoi(what[1].str().c_str());
							int dest_id = atoi(what[2].str().c_str());
							const patNode* origin_node = m_network->getNode(
									origin_id);
							const patNode* dest_node = m_network->getNode(
									dest_id);
							if (origin_node == NULL || dest_node == NULL) {
								throw RuntimeException("NULL NODE POINTER");
							}
//							DEBUG_MESSAGE(origin_id<<"-"<<dest_id);
							od = patOd(origin_node, dest_node);
							od_choice_set.setOD(origin_node, dest_node);

						} else {
							WARNING("not od given");
							throw RuntimeException("not od given");
						}

					} else if (string(path_iter->get_name())
							== string("Folder")) {

						patMultiModalPath new_path;
						int count;
						double log_weight;
						for (xml::node::iterator road_iter = path_iter->begin();
								road_iter != path_iter->end(); ++road_iter) {

							if (road_iter->is_text()) {
								continue;
							} else if (string(road_iter->get_name())
									== string("description")) {
								string path_desc = road_iter->get_content();
								sregex rex = sregex::compile("count: (\\d+)");
								smatch what;

								if (regex_search(path_desc, what, rex)) {

									count = atoi(what[1].str().c_str());
//									DEBUG_MESSAGE(count);
								} else {
									throw RuntimeException(
											"not path count given");
								}
								sregex rex_log_weight = sregex::compile(
										"logweight: ([\\-\\+]?\\d+(\\.\\d+)?)");
								smatch what_log_weight;

								if (regex_search(path_desc, what_log_weight,
										rex_log_weight)) {
//									DEBUG_MESSAGE(what_log_weight[1]);
									log_weight = atof(
											what_log_weight[1].str().c_str());
//									DEBUG_MESSAGE(log_weight);
								} else {
									throw RuntimeException(
											"not path log weight given");
								}
//								DEBUG_MESSAGE(count<<","<<log_weight);
							} else if (string(road_iter->get_name())
									== string("Folder")) {
								for (xml::node::iterator arc_iter =
										road_iter->begin();
										arc_iter != road_iter->end();
										++arc_iter) {

									if (arc_iter->is_text()) {
										continue;
									} else if (string(arc_iter->get_name())
											== string("Folder")) {
										for (xml::node::iterator placemark_iter =
												arc_iter->begin();
												placemark_iter
														!= arc_iter->end();
												++placemark_iter) {
											if (placemark_iter->is_text()) {
												continue;
											} else if (string(
													placemark_iter->get_name())
													== string("Placemark")) {

												for (xml::node::iterator desc_iter =
														placemark_iter->begin();
														desc_iter
																!= placemark_iter->end();
														++desc_iter) {

													if (desc_iter->is_text()) {
														continue;
													} else if (string(
															desc_iter->get_name())
															== string(
																	"description")) {
														string arc_desc =
																desc_iter->get_content();
														sregex rex =
																sregex::compile(
																		"(\\d+)->(\\d+)");
														smatch what;

														if (regex_search(
																arc_desc, what,
																rex)) {

															unsigned long up_node_id(
																	atoi(
																			what[1].str().c_str()));
															unsigned long down_node_id(
																	atoi(
																			what[2].str().c_str()));
															//DEBUG_MESSAGE(link_id<<":"<<up_node_id<<"-"<<down_node_id);

															const patNode* up_node =
																	m_network->getNode(
																			up_node_id);
															const patNode* down_node =
																	m_network->getNode(
																			down_node_id);
															if (up_node
																	== NULL) {
																WARNING(
																		"node not found: " << up_node_id);
																throw RuntimeException(
																		"node not found");
															}
															if (down_node
																	== NULL) {
																WARNING(
																		"node not found: " << down_node_id);
																throw RuntimeException(
																		"node not found");
															}
															const patArc* new_arc =
																	m_network->findArcByNodes(
																			up_node,
																			down_node);
															if (new_arc
																	== NULL) {
																WARNING(
																		"arc not found: " << up_node_id << "-" << down_node_id);
																throw RuntimeException(
																		"arc not found");
															} else {

																if (new_path.addRoadTravelToBack(
																		new_arc)
																		== false) {

																	throw RuntimeException(
																			"not valid path");
																}
															}
														}

													}
												}
											}
										}

									}
								}
							}
						}
						new_path.computeLength();
						new_path.generateOd();
//						DEBUG_MESSAGE(new_path.computeLength());
//						DEBUG_MESSAGE(new_path. generateOd());
//						DEBUG_MESSAGE(count<<","<<log_weight);
//						if (count == 0) {
//							count = 1;
//						}
//						for (unsigned count_iter = 0; count_iter < count;
//								++count_iter) {
//							paths.push_back(new_path);
//							log_weights.push_back(log_weight);
//						}
//						nbr_paths += count;
						od_choice_set.addPath(new_path, log_weight, count);
//						++nbr_paths;
//						if (nbr_paths
//								>= patNBParameters::the()->choiceSetInBiogemeData) {
//							continue;
//						}
					}
				}
//				DEBUG_MESSAGE(od);
//				DEBUG_MESSAGE(paths.size());
//				patChoiceSet od_chocie_set;
//				od_chocie_set.setOd(od);
////				DEBUG_MESSAGE(od.getOrigin()->getUserId()<<","<<od.getDestination()->getUserId());
//				if (paths.size() > sampled_count) {
////					DEBUG_MESSAGE("random sample the choice set: "<<sampled_count<<"<"<<paths.size() );
//					vector<double> probas(paths.size(), 1.0);
////					DEBUG_MESSAGE(probas.size()<<","<<log_weights.size());
//					vector<unsigned int> sampled_path_indics =
//							patSampleDiscreteDistribution::sampleWithOutReplaceMent(
//									probas, sampled_count, rnd);
//
////					DEBUG_MESSAGE(sampled_path_indics.size());
//					for (vector<unsigned int>::iterator sample_iter =
//							sampled_path_indics.begin();
//							sample_iter != sampled_path_indics.end();
//							++sample_iter) {
//
//						od_choice_set.addPath(paths[*sample_iter],
//								log_weights[*sample_iter], 1);
//					}
////					DEBUG_MESSAGE("OK");
//				} else {
//					od_chocie_set.setOd(od);
//					for (unsigned int sample_iter = 0;
//							sample_iter < paths.size(); ++sample_iter) {
////						DEBUG_MESSAGE(sample_iter);
//						od_choice_set.addPath(paths[sample_iter],
//								log_weights[sample_iter], 1);
//					}
//				}
				ods[od] = od_choice_set;
			}
		}

	}
	return ods;
}

max_stars_repo_name: godosou/smaroute

max_issues_repo_name: godosou/smaroute

max_forks_repo_name: godosou/smaroute


text:
#include <iostream>
#include <fstream>

#include <boost/program_options.hpp>
#include <crazyflie_cpp/Crazyflie.h>

std::istream& operator>>(std::istream& in, Crazyflie::BootloaderTarget& target)
{
  std::string token;
  in >> token;
  if (token == "stm32")
    target = Crazyflie::TargetSTM32;
  else if (token == "nrf51")
    target = Crazyflie::TargetNRF51;
  else throw boost::program_options::validation_error(boost::program_options::validation_error::invalid_option_value);
  return in;
}

enum Mode
{
  FlashAndVerify,
  FlashOnly,
  VerifyOnly,
};

std::istream& operator>>(std::istream& in, Mode& mode)
{
  std::string token;
  in >> token;
  if (token == "flashAndVerify")
    mode = FlashAndVerify;
  else if (token == "flashOnly")
    mode = FlashOnly;
  else if (token == "verifyOnly")
    mode = VerifyOnly;
  else throw boost::program_options::validation_error(boost::program_options::validation_error::invalid_option_value);
  return in;
}

int main(int argc, char **argv)
{

  std::string fileName;
  std::string uri;
  std::string defaultUri("radio://0/0/2M");
  Crazyflie::BootloaderTarget target;
  Mode mode = FlashAndVerify;

  namespace po = boost::program_options;

  po::options_description desc("Allowed options");
  desc.add_options()
    ("help", "produce help message")
    ("target", po::value<Crazyflie::BootloaderTarget>(&target)->required(), "target {stm32,nrf51}")
    ("filename", po::value<std::string>(&fileName)->required(), "file to flash")
    ("uri", po::value<std::string>(&uri)->default_value(defaultUri), "unique ressource identifier")
    ("mode", po::value<Mode>(&mode)->default_value(mode), "mode {default=flashAndVerify, flashOnly, verifyOnly}")
  ;

  try
  {
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
      std::cout << desc << "\n";
      return 0;
    }
  }
  catch(po::error& e)
  {
    std::cerr << e.what() << std::endl << std::endl;
    std::cerr << desc << std::endl;
    return 1;
  }

  try
  {
    bool success = true;
    if (uri != defaultUri) {
      // std::cout << "Reboot to Bootloader...";
      Crazyflie cf(uri);
      uint64_t address = cf.rebootToBootloader();
      // std::cout << "...Done" << std::endl;

      char addr[17];
      std::sprintf(addr, "%lx", address);
      defaultUri += "/" + std::string(addr);
    }

    std::ifstream stream(fileName.c_str(), std::ios::binary);
    if (!stream.good()) {
      std::cerr << "Couldn't open " << fileName << "!" << std::endl;
      return 1;
    }
    std::vector<uint8_t> targetData((
      std::istreambuf_iterator<char>(stream)),
      (std::istreambuf_iterator<char>()));

    Crazyflie cf(defaultUri);

    if (mode == FlashAndVerify || mode == FlashOnly) {
      // std::cout << "Flashing " << targetData.size() / 1024 << " kB" << std::endl;
      cf.writeFlash(target, targetData);
    }
    if (mode == FlashAndVerify || mode == VerifyOnly) {
      // std::cout << "Reading " << targetData.size() / 1024 << " kB" << std::endl;
      std::vector<uint8_t> currentData;
      cf.readFlash(target, targetData.size(), currentData);
      std::ofstream dbg("data.bin", std::ios::binary);
      dbg.write((char*)currentData.data(), currentData.size());
      if (memcmp(targetData.data(), currentData.data(), targetData.size()) == 0) {
        // std::cout << "Verification successful!" << std::endl;
      } else {
        std::cout << "Verification NOT successful!" << std::endl;
        success = false;
      }
    }

    // std::cout << "Reboot to firmware" << std::endl;
    cf.reboot();

    if (success) {
      return 0;
    }
    return 1;
  }
  catch(std::exception& e)
  {
    std::cerr << e.what() << std::endl;
    return 1;
  }
}


text:
#pragma once

#include <tuple>
#include <boost/utility/string_ref.hpp>
#include <iod/utils.hh>
#include <iod/sio_utils.hh>
#include <iod/tuple_utils.hh>

namespace sl
{

  template <typename T>
  auto symbol_tuple_to_sio(const std::tuple<>*, T content)
  {
    return content;
  }

  template <typename S1, typename T, typename... S>
  auto symbol_tuple_to_sio(const std::tuple<S1, S...>*, T content)
  {
    return D(S1() = symbol_tuple_to_sio((std::tuple<S...>*)0, content));
  }

  inline auto filter_symbols_from_tuple(std::tuple<> /*path*/)
  {
    return std::tuple<>();
  }

  template <typename T1, typename... T>
  auto filter_symbols_from_tuple(std::tuple<T1, T...> path)
  {
    return iod::tuple_filter<iod::is_symbol>(path);
  }

  using boost::string_ref;
}

ext: hh


text:
#include <boost/python.hpp>
using namespace boost::python;
#include <iostream>
struct World
{
    World(std::string msg_): msg(msg_) {}
    std::string greet()
    {
        return msg;
    }
    std::string msg;
};

/// ///
BOOST_PYTHON_MODULE(mfw)
{
    class_<World>("World", init<std::string>())
        .def("greet", &World::greet)
    ;
}


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

#include <graphene/app/config_util.hpp>
#include <graphene/chain/config.hpp>

#include <fc/exception/exception.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/string.hpp>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>

#include <fstream>

namespace bpo = boost::program_options;

class deduplicator {
public:
   deduplicator() :
         modifier(nullptr) {
   }

   deduplicator(const boost::shared_ptr<bpo::option_description> (*mod_fn)(const boost::shared_ptr<bpo::option_description> &)) :
         modifier(mod_fn) {
   }

   const boost::shared_ptr<bpo::option_description> next(const boost::shared_ptr<bpo::option_description> &o) {
      const std::string name = o->long_name();
      if (seen.find(name) != seen.end())
         return nullptr;
      seen.insert(name);
      return modifier ? modifier(o) : o;
   }

private:
   boost::container::flat_set<std::string> seen;
   const boost::shared_ptr<bpo::option_description> (*modifier)(const boost::shared_ptr<bpo::option_description> &);
};

// Currently, you can only specify the filenames and logging levels, which
// are all most users would want to change.  At a later time, options can
// be added to control rotation intervals, compression, and other seldom-
// used features
static void write_default_logging_config_to_stream(std::ostream &out) {
   out << "# declare an appender named \"stderr\" that writes messages to the console\n"
          "[log.console_appender.stderr]\n"
          "stream=std_error\n\n"
          "# declare an appender named \"default\" that writes messages to default.log\n"
          "[log.file_appender.default]\n"
          "# filename can be absolute or relative to this config file\n"
          "filename=logs/default/default.log\n"
          "# Rotate log every ? minutes, if leave out default to 60\n"
          "rotation_interval=60\n"
          "# how long will logs be kept (in days), if leave out default to 1\n"
          "rotation_limit=7\n\n"
          "# declare an appender named \"p2p\" that writes messages to p2p.log\n"
          "[log.file_appender.p2p]\n"
          "# filename can be absolute or relative to this config file\n"
          "filename=logs/p2p/p2p.log\n"
          "# Rotate log every ? minutes, if leave out default to 60\n"
          "rotation_interval=60\n"
          "# how long will logs be kept (in days), if leave out default to 1\n"
          "rotation_limit=7\n\n"
          "# declare an appender named \"rpc\" that writes messages to rpc.log\n"
          "[log.file_appender.rpc]\n"
          "# filename can be absolute or relative to this config file\n"
          "filename=logs/rpc/rpc.log\n"
          "# Rotate log every ? minutes, if leave out default to 60\n"
          "rotation_interval=60\n"
          "# how long will logs be kept (in days), if leave out default to 1\n"
          "rotation_limit=7\n\n"
          "# route any messages logged to the default logger to the \"stderr\" appender and\n"
          "# \"default\" appender we declared above, if they are info level or higher\n"
          "[logger.default]\n"
          "level=info\n"
          "appenders=stderr,default\n\n"
          "# route messages sent to the \"p2p\" logger to the \"p2p\" appender declared above\n"
          "[logger.p2p]\n"
          "level=warn\n"
          "appenders=p2p\n\n"
          "# route messages sent to the \"rpc\" logger to the \"rpc\" appender declared above\n"
          "[logger.rpc]\n"
          "level=error\n"
          "appenders=rpc\n\n";
}

// logging config is too complicated to be parsed by boost::program_options,
// so we do it by hand
static fc::optional<fc::logging_config> load_logging_config_from_ini_file(const fc::path &config_ini_filename) {
   try {
      fc::logging_config logging_config;
      bool found_logging_config = false;

      boost::property_tree::ptree config_ini_tree;
      boost::property_tree::ini_parser::read_ini(config_ini_filename.preferred_string().c_str(), config_ini_tree);
      for (const auto &section : config_ini_tree) {
         const std::string &section_name = section.first;
         const boost::property_tree::ptree &section_tree = section.second;

         const std::string console_appender_section_prefix = "log.console_appender.";
         const std::string file_appender_section_prefix = "log.file_appender.";
         const std::string logger_section_prefix = "logger.";

         if (boost::starts_with(section_name, console_appender_section_prefix)) {
            std::string console_appender_name = section_name.substr(console_appender_section_prefix.length());
            std::string stream_name = section_tree.get<std::string>("stream");

            // construct a default console appender config here
            // stdout/stderr will be taken from ini file, everything else hard-coded here
            fc::console_appender::config console_appender_config;
            console_appender_config.level_colors.emplace_back(
                  fc::console_appender::level_color(fc::log_level::debug,
                                                    fc::console_appender::color::green));
            console_appender_config.level_colors.emplace_back(
                  fc::console_appender::level_color(fc::log_level::warn,
                                                    fc::console_appender::color::brown));
            console_appender_config.level_colors.emplace_back(
                  fc::console_appender::level_color(fc::log_level::error,
                                                    fc::console_appender::color::cyan));
            console_appender_config.stream = fc::variant(stream_name).as<fc::console_appender::stream::type>(GRAPHENE_MAX_NESTED_OBJECTS);
            logging_config.appenders.push_back(fc::appender_config(console_appender_name, "console", fc::variant(console_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
            found_logging_config = true;
         } else if (boost::starts_with(section_name, file_appender_section_prefix)) {
            std::string file_appender_name = section_name.substr(file_appender_section_prefix.length());
            fc::path file_name = section_tree.get<std::string>("filename");
            if (file_name.is_relative())
               file_name = fc::absolute(config_ini_filename).parent_path() / file_name;

            int interval = section_tree.get_optional<int>("rotation_interval").get_value_or(60);
            int limit = section_tree.get_optional<int>("rotation_limit").get_value_or(1);

            // construct a default file appender config here
            // filename will be taken from ini file, everything else hard-coded here
            fc::file_appender::config file_appender_config;
            file_appender_config.filename = file_name;
            file_appender_config.flush = true;
            file_appender_config.rotate = true;
            file_appender_config.rotation_interval = fc::minutes(interval);
            file_appender_config.rotation_limit = fc::days(limit);
            logging_config.appenders.push_back(fc::appender_config(file_appender_name, "file", fc::variant(file_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
            found_logging_config = true;
         } else if (boost::starts_with(section_name, logger_section_prefix)) {
            std::string logger_name = section_name.substr(logger_section_prefix.length());
            std::string level_string = section_tree.get<std::string>("level");
            std::string appenders_string = section_tree.get<std::string>("appenders");
            fc::logger_config logger_config(logger_name);
            logger_config.level = fc::variant(level_string).as<fc::log_level>(5);
            boost::split(logger_config.appenders, appenders_string,
                         boost::is_any_of(" ,"),
                         boost::token_compress_on);
            logging_config.loggers.push_back(logger_config);
            found_logging_config = true;
         }
      }
      if (found_logging_config)
         return logging_config;
      else
         return fc::optional<fc::logging_config>();
   }
   FC_RETHROW_EXCEPTIONS(warn, "")
}

static const boost::shared_ptr<bpo::option_description> new_option_description(const std::string &name, const bpo::value_semantic *value, const std::string &description) {
   bpo::options_description helper("");
   helper.add_options()(name.c_str(), value, description.c_str());
   return helper.options()[0];
}

static void load_config_file(const fc::path &config_ini_path, const bpo::options_description &cfg_options,
                             bpo::variables_map &options) {
   deduplicator dedup;
   bpo::options_description unique_options("Graphene Witness Node");
   for( const boost::shared_ptr<bpo::option_description>& opt : cfg_options.options() ) {
      const boost::shared_ptr<bpo::option_description> od = dedup.next(opt);
      if (!od)
         continue;
      unique_options.add(od);
   }

   // get the basic options
   bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(),
                                           unique_options, true),
              options);
}

static bool load_logging_config_file(const fc::path &config_ini_path) {
   // try to get logging options from the config file.
   try {
      fc::optional<fc::logging_config> logging_config = load_logging_config_from_ini_file(config_ini_path);
      if (logging_config) {
         fc::configure_logging(*logging_config);
         return true;
      }
   } catch (const fc::exception &ex) {
      wlog("Error parsing logging config from logging config file ${config}, using default config", ("config", config_ini_path.preferred_string()));
   }
   return false;
}

static void create_new_config_file(const fc::path &config_ini_path, const fc::path &data_dir,
                                   const bpo::options_description &cfg_options) {
   ilog("Writing new config file at ${path}", ("path", config_ini_path));
   if (!fc::exists(data_dir))
      fc::create_directories(data_dir);

   auto modify_option_defaults = [](const boost::shared_ptr<bpo::option_description> &o) -> const boost::shared_ptr<bpo::option_description> {
      const std::string &name = o->long_name();
      if (name == "partial-operations")
         return new_option_description(name, bpo::value<bool>()->default_value(true), o->description());
      if (name == "max-ops-per-account")
         return new_option_description(name, bpo::value<int>()->default_value(100), o->description());
      return o;
   };
   deduplicator dedup(modify_option_defaults);
   std::ofstream out_cfg(config_ini_path.preferred_string());
   std::string plugin_header_surrounding( 78, '=' );
   for( const boost::shared_ptr<bpo::option_description>& opt : cfg_options.options() ) {
      const boost::shared_ptr<bpo::option_description> od = dedup.next(opt);
      if (!od)
         continue;

      if (od->long_name().find("plugin-cfg-header-") == 0) // it's a plugin header
      {
         out_cfg << "\n";
         out_cfg << "# " << plugin_header_surrounding << "\n";
         out_cfg << "# " << od->description() << "\n";
         out_cfg << "# " << plugin_header_surrounding << "\n";
         out_cfg << "\n";
         continue;
      }

      if (!od->description().empty())
         out_cfg << "# " << od->description() << "\n";
      boost::any store;
      if (!od->semantic()->apply_default(store))
         out_cfg << "# " << od->long_name() << " = \n";
      else {
         auto example = od->format_parameter();
         if (example.empty())
            // This is a boolean switch
            out_cfg << od->long_name() << " = "
                    << "false\n";
         else {
            // The string is formatted "arg (=<interesting part>)"
            example.erase(0, 6);
            example.erase(example.length() - 1);
            out_cfg << od->long_name() << " = " << example << "\n";
         }
      }
      out_cfg << "\n";
   }

   out_cfg << "\n"
           << "# " << plugin_header_surrounding << "\n"
           << "# logging options\n"
           << "# " << plugin_header_surrounding << "\n"
           << "#\n"
           << "# Logging configuration is loaded from logging.ini by default.\n"
           << "# If logging.ini exists, logging configuration added in this file will be ignored.\n";
   out_cfg.close();
}

static void create_logging_config_file(const fc::path &config_ini_path, const fc::path &data_dir) {
   ilog("Writing new config file at ${path}", ("path", config_ini_path));
   if (!exists(data_dir)) {
      create_directories(data_dir);
   }

   std::ofstream out_cfg(config_ini_path.preferred_string());
   write_default_logging_config_to_stream(out_cfg);
   out_cfg.close();
}

namespace graphene { namespace app {

void load_configuration_options(const fc::path &data_dir, const bpo::options_description &cfg_options, bpo::variables_map &options) {
   const auto config_ini_path = data_dir / "config.ini";
   const auto logging_ini_path = data_dir / "logging.ini";

   if (!exists(config_ini_path) && fc::exists(logging_ini_path)) {
      // this is an uncommon case
      create_new_config_file(config_ini_path, data_dir, cfg_options);
   } else if (!exists(config_ini_path)) {
      // create default config.ini and logging.ini
      create_new_config_file(config_ini_path, data_dir, cfg_options);
      create_logging_config_file(logging_ini_path, data_dir);
   }

   // load witness node configuration
   load_config_file(config_ini_path, cfg_options, options);

   // load logging configuration
   if (fc::exists(logging_ini_path)) {
      load_logging_config_file(logging_ini_path);
   } else {
      // this is the legacy config.ini case
      load_logging_config_file(config_ini_path);
   }
}

}} // namespace graphene::app

max_stars_repo_name: dapp-protocols/peerplays

max_issues_repo_name: dapp-protocols/peerplays

max_forks_repo_name: dapp-protocols/peerplays


text:
/*
 * ----------------------------------
 * Copyright (c) 2021 Prashant K. Jha
 * ----------------------------------
 *
 * Distributed under the Boost Software License, Version 1.0. (See accompanying
 * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#include <PeriDEMConfig.h>

// HPX includes
#include <hpx/hpx_init.hpp>                     // Need main source file
#include <hpx/util/high_resolution_clock.hpp>

// std includes
#include <boost/program_options.hpp>            // program options
#include <iostream>

// PeriDEM includes
#include "inp/input.h"                          // Input class
#include "model/dem/demModel.h"                 // Model class

int hpx_main(boost::program_options::variables_map& vm)
{
  // display Help
  if (vm.count("help")) {
    std::cout << "To run the simulation: \n"
              << "PeriDEM -i input.yaml --hpx:threads=n" << "\n";
    return hpx::finalize();
  }

  // read input file
  std::string filename;
  if (vm.count("input-file"))
    filename = vm["input-file"].as<std::string>();

  if (filename.empty()) {
    std::cerr << "PeriDEM" << " (Version " << MAJOR_VERSION <<
    		"." << MINOR_VERSION << "." << UPDATE_VERSION <<
			") -i input.yaml --hpx:threads=n" << std::endl;
    return hpx::finalize();
  }

  // print program version
  std::cout << "PeriDEM"
            << " (Version " << MAJOR_VERSION << "." << MINOR_VERSION << "."
            << UPDATE_VERSION << ")" << std::endl;

  // current time
  std::uint64_t begin = hpx::util::high_resolution_clock::now();

  // read input data
  auto *deck = new inp::Input(filename);

  // check which model to run
  if (deck->isPeriDEM()) {
    model::DEMModel dem(deck);
    dem.run(deck);
  } else {
    std::cout << "PeriDEM model not found in input file.\n";
  }

  // get time elapsed
  std::uint64_t end = hpx::util::high_resolution_clock::now();
  double elapsed_secs = double(end - begin) / 1.0e9;

  std::cout << "Total simulation time (s) = " << elapsed_secs
            << std::endl;
  return hpx::finalize();
}

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

  boost::program_options::options_description desc("Allowed options");
  desc.add_options()("help", "produce help message")(
      "input-file,i", boost::program_options::value<std::string>(),
      "Configuration file");

  return hpx::init(desc, argc, argv);
}

max_stars_repo_name: gitter-badger/PeriDEM

max_issues_repo_name: gitter-badger/PeriDEM

max_forks_repo_name: gitter-badger/PeriDEM


text:
#pragma once

#include <boost/filesystem/operations.hpp>
#include "config_source.hxx"
#include "config_scheme.hxx"

namespace application_layer::config
{
	// A configuration source that loads configuration data from
	// a json file.
	class file_source
		: public config_source
	{
		public:
			file_source(const boost::filesystem::path& p_path);

			file_source(const file_source&) = default;
			file_source(file_source&&) = default;

			file_source& operator=(const file_source&) = default;
			file_source& operator=(file_source&&) = default;

		public:
			virtual auto populate(boost::property_tree::ptree&)
				-> boost::property_tree::ptree& override;

		protected:
			boost::filesystem::path m_Path{ };	//< Path to configuration file. We could retrieve this from the path
												//  manager, but we want to keep dependencies between classes as small
												//	as possible.
	};
}

ext: hxx

max_issues_repo_name: nshcat/roguelike

max_forks_repo_name: nshcat/roguelike


text:
#include <my_class.hpp>
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE( my_test )
{
    my_class test_object( "qwerty" );

    BOOST_CHECK( test_object.is_valid() );
}

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#include <string>

#include <boost/program_options.hpp>

#include "CmdLine.hpp"

namespace po = boost::program_options;

CmdLine::CmdLine(int argCount, char **argVar){

  try{
    po::options_description desc("Allowed options");
    desc.add_options()
    ("help,h", "Prints help message.")
    ("val,v", po::value<double>(&val)->required(), "Test value to be printed.");

    po::variables_map vm;

    try{

      po::store(po::parse_command_line(argCount, argVar, desc), vm);

      if(vm.count("help")){
        std::cout << "\n\n" << desc << "\n\n" << std::endl;
        exit(0);
      }

      po::notify(vm);

    }

    // catch any errors in boost argument parsing.
    catch(po::error& e){
      std::cout << "\nerror: " << e.what() << std::endl;
      std::cout << "\n\n" << "Usage: ./test -v <value>" << std::endl;
      std::cout << "\nFor additional options type: ./test -h\n" << std::endl;
      exit(EXIT_FAILURE);
    }

  }

  // catch any other exceptions/errors in standard argument parsing.
  catch(std::exception& e){
    std::cout << std::endl << e.what() << std::endl;
    exit(EXIT_FAILURE);
  }

}

max_stars_repo_name: pblischak/boost-docker-test

max_issues_repo_name: pblischak/boost-docker-test

max_forks_repo_name: pblischak/boost-docker-test


text:
/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2019  David Shah <david@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <algorithm>
#include <boost/optional.hpp>
#include <iterator>
#include <queue>
#include <unordered_set>
#include "cells.h"
#include "chain_utils.h"
#include "design_utils.h"
#include "log.h"
#include "nextpnr.h"
#include "pack.h"
#include "pins.h"

NEXTPNR_NAMESPACE_BEGIN

void XC7Packer::prepare_clocking()
{
    log_info("Preparing clocking...\n");
    std::unordered_map<IdString, IdString> upgrade;
    upgrade[ctx->id("MMCME2_BASIC")] = ctx->id("MMCME2_ADV");
    upgrade[ctx->id("PLLE2_BASIC")] = ctx->id("PLLE2_ADV");

    for (auto cell : sorted(ctx->cells)) {
        CellInfo *ci = cell.second;
        if (upgrade.count(ci->type)) {
            IdString new_type = upgrade.at(ci->type);
            ci->type = new_type;
        } else if (ci->type == ctx->id("BUFG")) {
            ci->type = ctx->id("BUFGCTRL");
            rename_port(ctx, ci, ctx->id("I"), ctx->id("I0"));
            tie_port(ci, "CE0", true, true);
            tie_port(ci, "S0", true, true);
            tie_port(ci, "S1", false, true);
            tie_port(ci, "IGNORE0", true, true);
        } else if (ci->type == ctx->id("BUFGCE")) {
            ci->type = ctx->id("BUFGCTRL");
            rename_port(ctx, ci, ctx->id("I"), ctx->id("I0"));
            rename_port(ctx, ci, ctx->id("CE"), ctx->id("CE0"));
            tie_port(ci, "S0", true, true);
            tie_port(ci, "S1", false, true);
            tie_port(ci, "IGNORE0", true, true);
        }
        if (ci->attrs.count(ctx->id("BEL")))
            used_bels.insert(ctx->getBelByName(ctx->id(ci->attrs.at(ctx->id("BEL")).as_string())));
    }
}

void XC7Packer::pack_plls()
{
    log_info("Packing PLLs...\n");

    auto set_default = [](CellInfo *ci, IdString param, const Property &value) {
        if (!ci->params.count(param))
            ci->params[param] = value;
    };

    std::unordered_map<IdString, XFormRule> pll_rules;
    pll_rules[ctx->id("MMCME2_ADV")].new_type = ctx->id("MMCME2_ADV_MMCME2_ADV");
    pll_rules[ctx->id("PLLE2_ADV")].new_type = ctx->id("PLLE2_ADV_PLLE2_ADV");
    generic_xform(pll_rules);
    for (auto cell : sorted(ctx->cells)) {
        CellInfo *ci = cell.second;
        // Preplace PLLs to make use of dedicated/short routing paths
        if (ci->type == id_MMCM_MMCM_TOP || ci->type == id_PLL_PLL_TOP)
            try_preplace(ci, ctx->id("CLKIN1"));
        if (ci->type == id_MMCM_MMCM_TOP) {
            // Fixup parameters
            for (int i = 1; i <= 2; i++)
                set_default(ci, ctx->id("CLKIN" + std::to_string(i) + "_PERIOD"), Property("0.0"));
            for (int i = 0; i <= 6; i++) {
                set_default(ci, ctx->id("CLKOUT" + std::to_string(i) + "_CASCADE"), Property("FALSE"));
                set_default(ci, ctx->id("CLKOUT" + std::to_string(i) + "_DIVIDE"), Property(1));
                set_default(ci, ctx->id("CLKOUT" + std::to_string(i) + "_DUTY_CYCLE"), Property("0.5"));
                set_default(ci, ctx->id("CLKOUT" + std::to_string(i) + "_PHASE"), Property(0));
                set_default(ci, ctx->id("CLKOUT" + std::to_string(i) + "_USE_FINE_PS"), Property("FALSE"));
            }
            set_default(ci, ctx->id("COMPENSATION"), Property("INTERNAL"));

            // Fixup routing
            if (str_or_default(ci->params, ctx->id("COMPENSATION"), "INTERNAL") == "INTERNAL") {
                disconnect_port(ctx, ci, ctx->id("CLKFBIN"));
                connect_port(ctx, ctx->nets[ctx->id("$PACKER_VCC_NET")].get(), ci, ctx->id("CLKFBIN"));
            }
        }
    }
}

void XC7Packer::pack_gbs()
{
    log_info("Packing global buffers...\n");
    std::unordered_map<IdString, XFormRule> gb_rules;
    gb_rules[id_BUFGCTRL].new_type = id_BUFGCTRL;
    gb_rules[ctx->id("BUFGCTRL")].new_type = ctx->id("BUFGCTRL");

    generic_xform(gb_rules);

    // Preplace global buffers to make use of dedicated/short routing
    for (auto cell : sorted(ctx->cells)) {
        CellInfo *ci = cell.second;
        if (ci->type == id_BUFGCTRL)
            try_preplace(ci, ctx->id("I0"));
        if (ci->type == ctx->id("BUFG_BUFG"))
            try_preplace(ci, ctx->id("I"));
    }
}

void XC7Packer::pack_clocking()
{
    pack_plls();
    pack_gbs();
}

NEXTPNR_NAMESPACE_END

max_stars_repo_name: Xiretza/nextpnr-xilinx

max_issues_repo_name: Xiretza/nextpnr-xilinx

max_forks_repo_name: Xiretza/nextpnr-xilinx


text:
//  boost process_timer.cpp  -----------------------------------------------------------//

//  Copyright Beman Dawes 1994, 2006, 2008
//  Copyright 2009-2010 Vicente J. Botet Escriba

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  See http://www.boost.org/libs/chrono for documentation.

//--------------------------------------------------------------------------------------//
#ifndef BOOST_CHRONO_DETAIL_INLINED_WIN_PROCESS_CLOCK_HPP
#define BOOST_CHRONO_DETAIL_INLINED_WIN_PROCESS_CLOCK_HPP

#include <boost/chrono/config.hpp>
#include <boost/chrono/system_clocks.hpp>
#include <boost/chrono/process_times.hpp>
#include <cassert>

#include <boost/detail/win/GetLastError.hpp>
#include <boost/detail/win/GetCurrentProcess.hpp>
#include <boost/detail/win/GetProcessTimes.hpp>

namespace boost
{
namespace chrono
{

void process_clock::now( process_times & times_, system::error_code & ec )
{

    //  note that Windows uses 100 nanosecond ticks for FILETIME
    boost::detail::win32::FILETIME_ creation, exit, user_time, system_time;

    times_.real = duration( steady_clock::now().time_since_epoch().count() );

  #ifdef UNDER_CE
  // Windows CE does not support GetProcessTimes
    assert( 0 && "GetProcessTimes not supported under Windows CE" );
  times_.real = times_.system = times_.user = nanoseconds(-1);
  #else
    if ( boost::detail::win32::GetProcessTimes(
            boost::detail::win32::GetCurrentProcess(), &creation, &exit,
            &system_time, &user_time ) )
    {
        if (!BOOST_CHRONO_IS_THROWS(ec))
        {
            ec.clear();
        }
        times_.user   = duration(
          ((static_cast<time_point::rep>(user_time.dwHighDateTime) << 32)
            | user_time.dwLowDateTime) * 100 );

        times_.system = duration(
          ((static_cast<time_point::rep>(system_time.dwHighDateTime) << 32)
            | system_time.dwLowDateTime) * 100 );
    }
    else
    {
        boost::detail::win32::DWORD_ cause = boost::detail::win32::GetLastError();
        if (BOOST_CHRONO_IS_THROWS(ec))
        {
            boost::throw_exception(
                    system::system_error(
                            cause,
                            BOOST_CHRONO_SYSTEM_CATEGORY,
                            "chrono::process_clock" ));
        }
        else
        {
            ec.assign( cause, BOOST_CHRONO_SYSTEM_CATEGORY );
            times_.real = times_.system = times_.user = nanoseconds(-1);
        }
    }
  #endif
}
} // namespace chrono
} // namespace boost

#endif

max_stars_repo_name: zigaosolin/Raytracer

max_issues_repo_name: zigaosolin/Raytracer

max_forks_repo_name: zigaosolin/Raytracer


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.

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

#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_INTERSECTION_POINTS_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_INTERSECTION_POINTS_HPP

#include <cstddef>

#include <boost/geometry/algorithms/convert.hpp>
#include <boost/geometry/algorithms/detail/overlay/get_turns.hpp>

#include <boost/geometry/geometries/segment.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace get_intersection_points
{

template
<
    typename Point1,
    typename Point2,
    typename TurnInfo
>
struct get_turn_without_info
{
    typedef strategy_intersection
        <
            typename cs_tag<typename TurnInfo::point_type>::type,
            Point1,
            Point2,
            typename TurnInfo::point_type
        > si;

    typedef typename si::segment_intersection_strategy_type strategy;

    template <typename OutputIterator>
    static inline OutputIterator apply(
                Point1 const& pi, Point1 const& pj, Point1 const& pk,
                Point2 const& qi, Point2 const& qj, Point2 const& qk,
                TurnInfo const& tp_model,
                OutputIterator out)
    {
        typedef model::referring_segment<Point1 const> segment_type1;
        typedef model::referring_segment<Point1 const> segment_type2;
        segment_type1 p1(pi, pj), p2(pj, pk);
        segment_type2 q1(qi, qj), q2(qj, qk);

        //
        typename strategy::return_type result = strategy::apply(p1, q1);

        for (std::size_t i = 0; i < result.template get<0>().count; i++)
        {

            TurnInfo tp;
            geometry::convert(result.template get<0>().intersections[i], tp.point);
            *out++ = tp;
        }

        return out;
    }
};

}} // namespace detail::get_intersection_points
#endif // DOXYGEN_NO_DETAIL

template
<
    typename Geometry1,
    typename Geometry2,
    typename Turns
>
inline void get_intersection_points(Geometry1 const& geometry1,
            Geometry2 const& geometry2,
            Turns& turns)
{
    concept::check_concepts_and_equal_dimensions<Geometry1 const, Geometry2 const>();

    typedef detail::get_intersection_points::get_turn_without_info
                        <
                            typename point_type<Geometry1>::type,
                            typename point_type<Geometry2>::type,
                            typename boost::range_value<Turns>::type
                        > TurnPolicy;

    typedef typename strategy_intersection
        <
            typename cs_tag<Geometry1>::type,
            Geometry1,
            Geometry2,
            typename boost::range_value<Turns>::type
        >::segment_intersection_strategy_type segment_intersection_strategy_type;

    detail::get_turns::no_interrupt_policy interrupt_policy;

    boost::mpl::if_c
        <
            reverse_dispatch<Geometry1, Geometry2>::type::value,
            dispatch::get_turns_reversed
            <
                typename tag<Geometry1>::type,
                typename tag<Geometry2>::type,
                Geometry1, Geometry2,
                false, false,
                Turns, TurnPolicy,
                //segment_intersection_strategy_type,
                detail::get_turns::no_interrupt_policy
            >,
            dispatch::get_turns
            <
                typename tag<Geometry1>::type,
                typename tag<Geometry2>::type,
                Geometry1, Geometry2,
                false, false,
                Turns, TurnPolicy,
                //segment_intersection_strategy_type,
                detail::get_turns::no_interrupt_policy
            >
        >::type::apply(
            0, geometry1,
            1, geometry2,
            turns, interrupt_policy);
}

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_OVERLAY_GET_INTERSECTION_POINTS_HPP


text:
#pragma once

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

#include <photon_propagator/geometry.hpp>
#include <photon_propagator/device_structs/optical_module_line.h>

class Cells{
public:

  Cells();

  void to_device();
  cells* __device_ptr;

private:

  // load this and push to the device
  std::vector<optical_module_line> om_lines_;

  std::map<int, optical_module_line> optical_module_lines_;

  void configure(const Geometry& geometry, float dom_radius);
};


text:
/**
 * BCL to FASTQ file converter
 * Copyright (c) 2007-2017 Illumina, Inc.
 *
 * This software is covered by the accompanying EULA
 * and certain third party copyright/licenses, and any user of this
 * source file is bound by the terms therein.
 *
 * \file CycleInfo.cpp
 *
 * \brief Implementation of cycle metadata.
 *
 * \author Marek Balint
 */

#include <sstream>

#include <boost/format.hpp>

#include "layout/CycleInfo.hh"

namespace bcl2fastq {

namespace layout {

CycleInfo::CycleInfo(common::CycleNumber number)
: number_(number)
{
}

common::CycleNumber CycleInfo::getNumber() const
{
    return number_;
}

} // namespace layout

} // namespace bcl2fastq


text:
/*! \file meshlist.cpp
    \brief アルゴンに対して、分子動力学シミュレーションを行うクラスの宣言

    Copyright ©  2017 @dc1394 All Rights Reserved.
    This software is released under the BSD 2-Clause License.
*/

#include "meshlist.h"
#include <algorithm>        // for std::fill
#include <boost/assert.hpp> // for BOOST_ASSERT

namespace moleculardynamics {
    MeshList::MeshList(double periodiclen) : periodiclen_(periodiclen)
    {
        auto const SL = SystemParam::RCUTOFF + SystemParam::MARGIN;

        m_ = static_cast<std::int32_t>(periodiclen / SL) - 1;
        mesh_size_ = static_cast<double>(periodiclen) / m_;

        BOOST_ASSERT(m_ > 2);
        BOOST_ASSERT(mesh_size_ > SL);

        number_of_mesh_ = m_ * m_ * m_;
        count_.resize(number_of_mesh_);
        indexes_.resize(number_of_mesh_);
    }

    void MeshList::make_pair(SystemParam::myatomvector & atoms, SystemParam::mypairvector & pairs)
    {
        pairs.clear();

        auto const pn = atoms.size();

        std::vector<std::int32_t> particle_position(pn, 0);
        std::vector<std::int32_t> pointer(number_of_mesh_, 0);

        std::fill(count_.begin(), count_.end(), 0);

        auto const im = 1.0 / mesh_size_;
        for (auto i = 0; i < pn; i++) {
            auto ix = static_cast<std::int32_t>(atoms[i].r[0] * im);
            auto iy = static_cast<std::int32_t>(atoms[i].r[1] * im);
            auto iz = static_cast<std::int32_t>(atoms[i].r[2] * im);

            if (ix < 0) {
                ix += m_;
            }
            else if (ix >= m_) {
                ix -= m_;
            }

            if (iy < 0) {
                iy += m_;
            }
            else if (iy >= m_) {
                iy -= m_;
            }
            if (iz < 0) {
                iz += m_;
            }
            else if (iz >= m_) {
                iz -= m_;
            }

            auto const index = ix + iy * m_ + iz * m_ * m_;

            BOOST_ASSERT(index >= 0);
            BOOST_ASSERT(index < number_of_mesh_);

            count_[index]++;
            particle_position[i] = index;
        }

        indexes_[0] = 0;
        auto sum = 0;

        for (auto i = 0; i < number_of_mesh_ - 1; i++) {
            sum += count_[i];
            indexes_[i + 1] = sum;
        }

        for (auto i = 0; i < pn; i++) {
            auto const pos = particle_position[i];
            auto const j = indexes_[pos] + pointer[pos];
            sorted_buffer[j] = i;
            ++pointer[pos];
        }

        for (auto i = 0; i < number_of_mesh_; i++) {
            search(i, atoms, pairs);
        }
    }

    void MeshList::search_other(std::int32_t id, std::int32_t ix, std::int32_t iy, std::int32_t iz, SystemParam::myatomvector & atoms, SystemParam::mypairvector & pairs)
    {
        if (ix < 0) {
            ix += m_;
        }
        else if (ix >= m_) {
            ix -= m_;
        }

        if (iy < 0) {
            iy += m_;
        }
        else if (iy >= m_) {
            iy -= m_;
        }

        if (iz < 0) {
            iz += m_;
        }
        else if (iz >= m_) {
            iz -= m_;
        }

        auto const id2 = ix + iy * m_ + iz * m_ * m_;

        for (auto k = indexes_[id]; k < indexes_[id] + count_[id]; k++) {
            for (auto m_ = indexes_[id2]; m_ < indexes_[id2] + count_[id2]; m_++) {
                auto const i = sorted_buffer[k];
                auto const j = sorted_buffer[m_];

                Eigen::Vector4d d = atoms[j].r - atoms[i].r;

                SystemParam::adjust_periodic(d, periodiclen_);

                if (d.squaredNorm() <= SystemParam::ML2) {
                    pairs.push_back(std::make_pair(i, j));
                }
            }
        }
    }

    void MeshList::search(std::int32_t id, SystemParam::myatomvector & atoms, SystemParam::mypairvector & pairs)
    {
        auto const ix = id % m_;
        auto const iy = (id / m_) % m_;
        auto const iz = (id / m_ / m_);

        search_other(id, ix + 1, iy, iz, atoms, pairs);
        search_other(id, ix - 1, iy + 1, iz, atoms, pairs);
        search_other(id, ix, iy + 1, iz, atoms, pairs);
        search_other(id, ix + 1, iy + 1, iz, atoms, pairs);

        search_other(id, ix - 1, iy, iz + 1, atoms, pairs);
        search_other(id, ix, iy, iz + 1, atoms, pairs);
        search_other(id, ix + 1, iy, iz + 1, atoms, pairs);

        search_other(id, ix - 1, iy - 1, iz + 1, atoms, pairs);
        search_other(id, ix, iy - 1, iz + 1, atoms, pairs);
        search_other(id, ix + 1, iy - 1, iz + 1, atoms, pairs);

        search_other(id, ix - 1, iy + 1, iz + 1, atoms, pairs);
        search_other(id, ix, iy + 1, iz + 1, atoms, pairs);
        search_other(id, ix + 1, iy + 1, iz + 1, atoms, pairs);

        // Registration of self box
        auto const si = indexes_[id];
        auto const n = count_[id];

        for (auto k = si; k < si + n - 1; k++) {
            for (auto m_ = k + 1; m_ < si + n; m_++) {
                auto const i = sorted_buffer[k];
                auto const j = sorted_buffer[m_];

                Eigen::Vector4d d = atoms[j].r - atoms[i].r;

                SystemParam::adjust_periodic(d, periodiclen_);

                if (d.squaredNorm() <= SystemParam::ML2) {
                    pairs.push_back(std::make_pair(i, j));
                }
            }
        }
    }
}


text:
//
// Copyright Antoine Leblanc 2010 - 2015
// Distributed under the MIT license.
//
// http://nauths.fr
// http://github.com/nicuveo
// mailto://antoine.jp.leblanc@gmail.com
//

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Includes

#include <cstdlib>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include "nauths/saw/saw.hh"

//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
// Implementation

using namespace saw;

BOOST_AUTO_TEST_SUITE(value)

BOOST_AUTO_TEST_CASE(value_00)
{
  Value v1;
  Value v2 = Value(Null());

  BOOST_REQUIRE(v1.null());
  BOOST_REQUIRE_EQUAL(Integer(0), v1.as_integer());
  BOOST_REQUIRE_EQUAL(Float(0),   v1.as_float()  );
  BOOST_REQUIRE_EQUAL(Text(),     v1.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob(),     v1.as_blob()   );

  BOOST_REQUIRE(v2.null());
  BOOST_REQUIRE_EQUAL(Integer(0), v2.as_integer());
  BOOST_REQUIRE_EQUAL(Float(0),   v2.as_float()  );
  BOOST_REQUIRE_EQUAL(Text(),     v2.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob(),     v2.as_blob()   );
}

BOOST_AUTO_TEST_CASE(value_01)
{
  Value v(Integer(1234));

  BOOST_REQUIRE(not v.null());
  BOOST_REQUIRE_EQUAL(Integer(1234), v.as_integer());
  BOOST_REQUIRE_EQUAL(Float(1234),   v.as_float()  );
  BOOST_REQUIRE_EQUAL(Text("1234"),  v.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob("1234"),  v.as_blob()   );
}

BOOST_AUTO_TEST_CASE(value_02)
{
  Value v1(Float(2345));
  Value v2(2345.f);
  Value v3(2345.);

  BOOST_REQUIRE(not v1.null());
  BOOST_REQUIRE_EQUAL(Integer(2345), v1.as_integer());
  BOOST_REQUIRE_EQUAL(Float(2345),   v1.as_float()  );
  BOOST_REQUIRE_EQUAL(Text("2345"),  v1.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob("2345"),  v1.as_blob()   );

  BOOST_REQUIRE(not v2.null());
  BOOST_REQUIRE_EQUAL(Integer(2345), v2.as_integer());
  BOOST_REQUIRE_EQUAL(Float(2345),   v2.as_float()  );
  BOOST_REQUIRE_EQUAL(Text("2345"),  v2.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob("2345"),  v2.as_blob()   );

  BOOST_REQUIRE(not v3.null());
  BOOST_REQUIRE_EQUAL(Integer(2345), v3.as_integer());
  BOOST_REQUIRE_EQUAL(Float(2345),   v3.as_float()  );
  BOOST_REQUIRE_EQUAL(Text("2345"),  v3.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob("2345"),  v3.as_blob()   );
}

BOOST_AUTO_TEST_CASE(value_03)
{
  Value v(Text("3456"));

  BOOST_REQUIRE(not v.null());
  BOOST_REQUIRE_EQUAL(Integer(3456), v.as_integer());
  BOOST_REQUIRE_EQUAL(Float(3456),   v.as_float()  );
  BOOST_REQUIRE_EQUAL(Text("3456"),  v.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob("3456"),  v.as_blob()   );
}

BOOST_AUTO_TEST_CASE(value_04)
{
  Value v(Blob("4567"));

  BOOST_REQUIRE(not v.null());
  BOOST_REQUIRE_EQUAL(Integer(4567), v.as_integer());
  BOOST_REQUIRE_EQUAL(Float(4567),   v.as_float()  );
  BOOST_REQUIRE_EQUAL(Text("4567"),  v.as_text()   );
  BOOST_REQUIRE_EQUAL(Blob("4567"),  v.as_blob()   );
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: nicuveo/SAW

max_issues_repo_name: nicuveo/SAW

max_forks_repo_name: nicuveo/SAW


text:
// Copyright University of Warwick 2014
// 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)

// Authors:
// John Back

/*! \file LpcBranch.hh
    \brief File containing the declaration of the LpcBranch class
*/

/*! \class LpcBranch
    \brief Class that stores the result of a branch of the main principal curve
*/

#ifndef LPC_BRANCH_HH
#define LPC_BRANCH_HH

#include "LACE/LpcAbsCurve.hh"

#include "LACE/LpcPathLength.hh"
#include "LACE/LpcPoint.hh"

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

class LpcBranch : public LpcAbsCurve {

public:

    //! Constructor storing the local principal curve branch result
    /*!
      \param [in] index The index number of the lpc branch
      \param [in] startPoint The scaled starting position for the branch
      \param [in] lpcPoints The calculated scaled branch points
      \param [in] eigenVectors The largest eigenvectors (row = lpc point, col = x,y,z,...)
      \param [in] cosAngles The cosine of the angles between adjacent eigenvectors
      \param [in] lpcPath The cumulative path length object along the curve
      \param [in] rho The ratio of the eigenvalues (2nd/1st) for each branch point
      \param [in] c0 The adjusted kernel function denominator exponent scale factors
      \param [in] highRhoPoints The scaled local neighbourhood points when rho > rho0 (~0.4)
      \param [in] theHits The pointer to the constant hit collection used to find the curve
      \param [in] flag The status flag set to be the index of the main curve
     */
    LpcBranch(int index, const LpcPoint& startPoint,
	      const std::vector<LpcPoint>& lpcPoints,
	      const Eigen::MatrixXd& eigenVectors,
	      const Eigen::VectorXd& cosAngles,
	      const LpcPathLength& lpcPath,
	      const Eigen::VectorXd& rho,
	      const Eigen::VectorXd& c0,
	      const std::vector<LpcPoint>& highRhoPoints,
	      const LpcHitCollection* theHits,
	      int flag);

    //! Empty constructor
    LpcBranch();

    //! Destructor
    virtual ~LpcBranch();

protected:

private:

    //! Copy constructor
    LpcBranch(const LpcBranch& other);

    //! Assignment operator
    LpcBranch& operator=(const LpcBranch& other);
};

#endif

max_stars_repo_name: petrmanek/LACE

max_issues_repo_name: petrmanek/LACE

max_forks_repo_name: petrmanek/LACE