text:
#include "CorePch.h"
#include <rtp++/mprtp/MpRtpMemberEntry.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <cpputil/Utility.h>
#include <rtp++/RtpTime.h>
#include <rtp++/mprtp/FlowSpecificMemberEntry.h>
#include <rtp++/mprtp/MpRtcp.h>
#include <rtp++/mprtp/MpRtp.h>
#include <rtp++/mprtp/MpRtpHeader.h>
#include <rtp++/rfc3550/Rfc3550.h>
#include <rtp++/rfc3611/Rfc3611.h>

namespace rtp_plus_plus
{
namespace mprtp
{

MpRtpMemberEntry::MpRtpMemberEntry()
{
  setMaxMisorder(MAX_MISORDER);
}

MpRtpMemberEntry::MpRtpMemberEntry(uint32_t uiSSRC)
  : MemberEntry( uiSSRC )
{
  setMaxMisorder(MAX_MISORDER);
  VLOG(5) << "Creating MPRTP member entry";
}

MpRtpMemberEntry::~MpRtpMemberEntry()
{
  VLOG(5) << "Destructor MPRTP member entry";
}

// override this to initialise flow specific sequence numbers
void MpRtpMemberEntry::init(const RtpPacket& rtpPacket)
{
  // init global sequence number space
  MemberEntry::init(rtpPacket);

  boost::optional<mprtp::MpRtpSubflowRtpHeader> pSubflowHeader = rtpPacket.getMpRtpSubflowHeader();
  if (pSubflowHeader)
  {
    uint16_t uiFlowId = pSubflowHeader->getFlowId();
    auto it = m_mFlowSpecificMap.find(uiFlowId);
    if (it == m_mFlowSpecificMap.end())
    {
      VLOG(2) << "First RTP packet: initialising MemberEntry " << hex(m_uiSSRC) << " for flow " << uiFlowId;
      m_mFlowSpecificMap[uiFlowId] = createFlowSpecificMemberEntry(uiFlowId);
      m_mFlowSpecificMap[uiFlowId]->initSequence(pSubflowHeader->getFlowSpecificSequenceNumber());
    }
  }
  else
  {
    LOG(WARNING) << "MPRTP packet has no header extension!";
  }

  /*
  // search for MPRTP header extension
  rfc5285::RtpHeaderExtension::ptr pHeaderExtension = rtpPacket.getHeader().getHeaderExtension();
  if (pHeaderExtension)
  {
    // Potentially expensive???: create a work around if this proves to be a problem
    MpRtpSubflowRtpHeader* pSubflowHeader = dynamic_cast<MpRtpSubflowRtpHeader*>(pHeaderExtension.get());
    if (pSubflowHeader)
    {
      uint16_t uiFlowId = pSubflowHeader->getFlowId();
      auto it = m_mFlowSpecificMap.find(uiFlowId);
      if (it == m_mFlowSpecificMap.end())
      {
        VLOG(2) << "First RTP packet: initialising MemberEntry " << hex(m_uiSSRC) << " for flow " << uiFlowId;
        m_mFlowSpecificMap[uiFlowId] = createFlowSpecificMemberEntry(uiFlowId);
        m_mFlowSpecificMap[uiFlowId]->initSequence(pSubflowHeader->getFlowSpecificSequenceNumber());
      }
    }
  }*/
}

void MpRtpMemberEntry::onMpRtcp( const MpRtcp& mprtcp )
{
// #define DEBUG_NTP
#ifdef DEBUG_NTP
  uint32_t uiNtpMsw = 0, uiNtpLsw = 0;
  split(mprtcp.getArrivalTimeNtp(), uiNtpMsw, uiNtpLsw);
  DLOG(INFO) << "NTP arrival time: " << hex(uiNtpMsw) << "." << hex(uiNtpLsw) << " " << convertNtpTimestampToPosixTime(mprtcp.getArrivalTimeNtp());
#endif

  MpRtcp::ReportMap_t mReports = mprtcp.getRtcpReportMap();
  std::for_each(mReports.begin(), mReports.end(), [=](MpRtcp::ReportPair_t& reportPair)
  {
    uint16_t uiFlowId = reportPair.first;
    MpRtcpReport report = reportPair.second;
    CompoundRtcpPacket vReports = report.getReports();
    std::for_each(vReports.begin(), vReports.end(), [=](RtcpPacketBase::ptr& pRtcpPacket)
    {
      RtcpPacketBase& packet = *(pRtcpPacket.get());
      // copy NTP arrival timestamp since the packet is contained inside the mprtcp message
      // and has not been timestamped
      packet.setArrivalTimeNtp(mprtcp.getArrivalTimeNtp());

      auto it = m_mFlowSpecificMap.find(uiFlowId);
      if (it == m_mFlowSpecificMap.end())
      {
        VLOG(2) << "Initialising MemberEntry " << hex(m_uiSSRC) << " for flow " << uiFlowId;
        m_mFlowSpecificMap[uiFlowId] = std::move(createFlowSpecificMemberEntry(uiFlowId));
      }

      switch (packet.getPacketType())
      {
      case rfc3550::PT_RTCP_SR:
        {
          VLOG(10) <<  "Processing MPRTP SR for flow id " << uiFlowId;
          rfc3550::RtcpSr& sr = const_cast<rfc3550::RtcpSr&>(static_cast<const rfc3550::RtcpSr&>(packet));
          m_mFlowSpecificMap[uiFlowId]->onSrReceived(sr);
          break;
        }
      case rfc3550::PT_RTCP_RR:
        {
          VLOG(10) <<  "Processing MPRTP RR for flow id " << uiFlowId;
          rfc3550::RtcpRr& rr = const_cast<rfc3550::RtcpRr&>(static_cast<const rfc3550::RtcpRr&>(packet));
          m_mFlowSpecificMap[uiFlowId]->onRrReceived(rr);
          break;
        }
      case rfc3611::PT_RTCP_XR:
        {
          VLOG(10) <<  "Processing MPRTP XR for flow id " << uiFlowId;
          rfc3611::RtcpXr& sr = const_cast<rfc3611::RtcpXr&>(static_cast<const rfc3611::RtcpXr&>(packet));
          m_mFlowSpecificMap[uiFlowId]->onXrReceived(sr);
          break;
        }
      }
    });
  });
}

std::unique_ptr<FlowSpecificMemberEntry> MpRtpMemberEntry::createFlowSpecificMemberEntry(uint16_t uiFlowId)
{
  std::unique_ptr<FlowSpecificMemberEntry> pEntry = std::unique_ptr<FlowSpecificMemberEntry>(new FlowSpecificMemberEntry(m_uiSSRC, uiFlowId));
  // Member entries need to know what the local SSRCs are
  // so that they can determine if a report is important
  // and needs to be processed
  for (auto uiSSRC: m_localSSRCs)
  {
    pEntry->addLocalSSRC(uiSSRC);
  }

  // setup forwarding of member updates
  pEntry->setUpdateCallback(std::bind(&MpRtpMemberEntry::onMemberUpdate, this, std::placeholders::_1));
  return pEntry;
}

void MpRtpMemberEntry::finaliseRRData()
{
  // call base class to finalise global RR data
  VLOG(10) << "Finalising MPRTP global data";
  MemberEntry::finaliseRRData();

  std::for_each(m_mFlowSpecificMap.begin(), m_mFlowSpecificMap.end(), [] (FlowSpecificMapEntry_t& pair)
  {
    VLOG(10) << "Finalising MPRTP subflow data: " << pair.first;
    pair.second->finaliseRRData();
  });
}

/// A receiver should call this method so that we can update the state according to the
/// RTCP packet received
void MpRtpMemberEntry::doReceiveRtpPacket(const RtpPacket& rtpPacket)
{
  // Can't call base class method here since multipath packets might never be in sequence and the update_seq algorithm
  // relies on receiving packets in sequence
  // MemberEntry::doReceiveRtpPacket(rtpPacket);
  // call base class method to process rtp packet
  // TODO: refactor
  // replicating base class code: the sequence number jumps on multiple paths
  // don't work with update_seq
  // Nor do the jitter calculations apply!
  m_tLastRtpPacketSent = boost::posix_time::microsec_clock::universal_time();
  m_tLastPacketSent = m_tLastRtpPacketSent;
  m_bIsSender = true;
  ++m_uiRtpPacketsReceivedDuringLastInterval;

  boost::optional<mprtp::MpRtpSubflowRtpHeader> pSubflowHeader = rtpPacket.getMpRtpSubflowHeader();
  if (pSubflowHeader)
  {
    uint16_t uiFlowId = pSubflowHeader->getFlowId();
    uint16_t uiFlowSpecificSequenceNumber = pSubflowHeader->getFlowSpecificSequenceNumber();
#ifdef DEBUG_MPRTP
    VLOG(2) << "Received packet with SN " << rtpPacket.getSequenceNumber()
            << " FlowId: " << uiFlowId
            << " FSSN: " << uiFlowSpecificSequenceNumber;
#endif
    auto it = m_mFlowSpecificMap.find(uiFlowId);
    if (it == m_mFlowSpecificMap.end())
    {
      m_mFlowSpecificMap[uiFlowId] = createFlowSpecificMemberEntry(uiFlowId);
      VLOG(2) << "First packet for member " << hex(m_uiSSRC) << " for flow " << uiFlowId;
      // first packet for flow
      m_mFlowSpecificMap[uiFlowId]->initSequence(uiFlowSpecificSequenceNumber);
    }
    else if (!m_mFlowSpecificMap[uiFlowId]->hasBeenIntialisedWithSN())
    {
      // This can occur if RTCP is received for a flow before RTP
      VLOG(2) << "First packet for member " << hex(m_uiSSRC) << " for flow " << uiFlowId;
      // first packet for flow
      m_mFlowSpecificMap[uiFlowId]->initSequence(uiFlowSpecificSequenceNumber);
    }

    // process RTP
    m_mFlowSpecificMap[uiFlowId]->processRtpPacket(uiFlowSpecificSequenceNumber, rtpPacket.getRtpTimestamp(), rtpPacket.getRtpArrivalTimestamp());
  }
  else
  {
    LOG(WARNING) << "MPRTP packet has no header extension!";
  }

  /*
  // search for MPRTP header extension
  rfc5285::RtpHeaderExtension::ptr pHeaderExtension = rtpPacket.getHeader().getHeaderExtension();
  if (pHeaderExtension)
  {
    // Potentially expensive???: create a work around if this proves to be a problem
    MpRtpSubflowRtpHeader* pSubflowHeader = dynamic_cast<MpRtpSubflowRtpHeader*>(pHeaderExtension.get());
    if (pSubflowHeader)
    {
      uint16_t uiFlowId = pSubflowHeader->getFlowId();
      uint16_t uiFlowSpecificSequenceNumber = pSubflowHeader->getFlowSpecificSequenceNumber();
#ifdef DEBUG_MPRTP
      VLOG(2) << "Received packet with SN " << rtpPacket.getSequenceNumber()
              << " FlowId: " << uiFlowId
              << " FSSN: " << uiFlowSpecificSequenceNumber;
#endif
      auto it = m_mFlowSpecificMap.find(uiFlowId);
      if (it == m_mFlowSpecificMap.end())
      {
        m_mFlowSpecificMap[uiFlowId] = createFlowSpecificMemberEntry(uiFlowId);
        VLOG(2) << "First packet for member " << hex(m_uiSSRC) << " for flow " << uiFlowId;
        // first packet for flow
        m_mFlowSpecificMap[uiFlowId]->initSequence(uiFlowSpecificSequenceNumber);
      }
      else if (!m_mFlowSpecificMap[uiFlowId]->hasBeenIntialisedWithSN())
      {
        // This can occur if RTCP is received for a flow before RTP
        VLOG(2) << "First packet for member " << hex(m_uiSSRC) << " for flow " << uiFlowId;
        // first packet for flow
        m_mFlowSpecificMap[uiFlowId]->initSequence(uiFlowSpecificSequenceNumber);
      }

      // process RTP
      m_mFlowSpecificMap[uiFlowId]->processRtpPacket(uiFlowSpecificSequenceNumber, rtpPacket.getRtpTimestamp(), rtpPacket.getRtpArrivalTimestamp());
    }
  }
  */
}

}
}


text:
/*
 * TrainUpdateParams.hpp
 *
 *  Created on: Feb 18, 2016
 *      Author: fm-simmobility
 */

#include <boost/random.hpp>
#include "entities/UpdateParams.hpp"
#include "metrics/Frame.hpp"

namespace sim_mob {

class TrainUpdateParams: public UpdateParams {
public:
    enum CURRENTCASE{NORMAL_CASE,STATION_CASE};
    TrainUpdateParams();
    virtual ~TrainUpdateParams();
    /**current speed*/
    double currentSpeed;
    /**tickSize in seconds*/
    double secondsInTick;
    /**time elapsed in the current tick (in seconds)*/
    double elapsedSeconds;
    /**current distance to next platform*/
    double disToNextPlatform;
    /**current distance to next train*/
    double disToNextTrain;
    /**current speed limit*/
    double currentSpeedLimit;
    /**current effective acceleration*/
    double currentAcelerate;
    /**current case*/
    double maxDecelerationToStopPoint;
    CURRENTCASE currCase;

    /**distance to next train*/
    double disToNext;
    double distanceToNextStopPoint;
    double movingDistance;

    /**
     * resets this update params.
     * @param now current timeslice in which reset is called
     */
    virtual void reset(timeslice now);
};

} /* namespace sim_mob */

ext: hpp


text:
/*
 * Copyright (c) 2017-2018 Tuukka Norri
 * This code is licensed under MIT license (see LICENSE for details).
 */

#ifndef VCF2MULTIALIGN_TYPES_HH
#define VCF2MULTIALIGN_TYPES_HH

#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <map>
#include <set>
#include <vector>

namespace vcf2multialign {
	typedef std::vector <char> vector_type;
	typedef std::set <std::size_t> variant_set;

	enum class output_type : std::uint8_t {
		SEQUENCE_FILES	= 0,
		VARIANT_GRAPH
	};

	struct sample_count
	{
		std::size_t handled_count{0};
		std::size_t total_count{0};

		void reset() { handled_count = 0; total_count = 0; }
	};

	typedef std::map <std::size_t, std::size_t> ploidy_map;
}

#endif

ext: hh


text:
// <KeyValue> -*- C++ -*-

#pragma once

#include <inttypes.h>
#include <vector>
#include <map>

#include <boost/mpl/for_each.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/variant.hpp>
#include <boost/foreach.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/static_assert.hpp>

#include "sparta/utils/SpartaException.hpp"

namespace sparta
{

    /* \brief Macro to make the variant type for the different types that a
     * KeyValue can be.  In addition, a type name string list is created
     * which is parsed and turned into a global type/name map for pretty
     * printing.  This is better than saying, your type 'y' doesn't match
     * type 'i'.
     */
    #define MAKE_VARIANT_OVER(...)                                      \
        typedef boost::mpl::vector<__VA_ARGS__> VectorofTypes;          \
        typedef boost::make_variant_over<VectorofTypes>::type ValueVar; \
        static const std::string type_names = #__VA_ARGS__;

    /*! The variant list that the KeyValue class will support.  To add a
     * new type, just add it to the end of this list.
     *
     * All elements in this list must:
     * \li Support default construction
     * \li Support assignment operator (=)
     * \li Support comparison operator (==) as a const qualified method. For
     * vector, this implies that the value_type supports operator== as a const
     * method as well.
     *
     * \warning If adding a new type that is not a copyable POD type, a
     * std::string, or a vector of POD types (or std::strings), code
     * will likely break. Never add [const]char* to this list; it creates
     */
    MAKE_VARIANT_OVER(bool,
                      int32_t,
                      uint32_t,
                      int64_t,
                      uint64_t,
                      double,
                      std::string,
                      std::vector<bool>,
                      std::vector<int32_t>,
                      std::vector<uint32_t>,
                      std::vector<int64_t>,
                      std::vector<uint64_t>,
                      std::vector<double>,
                      std::vector<std::string>);

    //! \brief The type-to-type name map.  Not really necessary, but useful.
    typedef std::map<std::string, std::string> TypeToTypeNameMap;

    /*!
     * \class KeyValue
     * \brief This class hold a key/value pair
     *
     *
     */
    class KeyValue
    {
    public:

        /*!
         * \brief Map of internal typeid names to C++ names.
         *
         * Used for looking up human-readable C++ names based on variant or
         * template types.
         *
         * \note This is used by Parameters for a type list
         */
        static TypeToTypeNameMap GBL_type_name_map;

        /*!
         * \brief Construct a Key/Value pair
         * \param key The key
         * \param val The ValueVar (can be anything of any of the above supported types)
         *
         * Example usage:
         * \code
         * KeyValue val1("unsigned integer", 10u);
         * KeyValue val2("float", 10.1);
         * KeyValue val3("string", "hello");
         * KeyValue val4("signed ", -10);
         * KeyValue val5("unsigned long", 10ull);
         * \endcode
         */
        template <class U>
        KeyValue(const std::string & key,
                 U val,
                 const std::string & desc="") :
            key_(key), value_(val), desc_(desc)
        {

            // Why am I allowed to do this?.
            // Variant constructor is to agressive. Holds type as bool.
            //ValueVar x((const char*)"12345");
            //std::cout << x.type().name() << std::endl;
            //std::cout << boost::get<const char*>(x) << std::endl;

            // While this is not valid:
            //ValueVar xv(std::pair<int,int>());
            //std::cout << boost::get<std::pair<int,int> >(xv).size() << std::endl;
        }

        /*!
         * \brief Get the key
         * \return The key
         */
        std::string getKey() const {
            return key_;
        }

        /*!
         * \brief Set the description
         * \param desc The description of this key/value pair
         */
        void setDesc(const std::string& desc) {
            desc_ = desc;
        }

        /*!
         * \brief Get the Description
         * \return The Description
         */
        std::string getDesc() const {
            return key_;
        }

        /*!
         * \brief Get the value of this key/value
         * \return The value of this key/value pair
         * \throw boost::bad_get if the type requested does not match the type of the key
         *
         * A painful way to get to the value of the key/value.
         * Example usage:
         * \code
         * KeyValue val1("unsigned integer", 10u);
         * unsigned int val = val1.getValue<unsigned int>();
         * \endcode
         */
        template<class T>
        const T getValue() const {
            try {
                return boost::get<T>(value_);
            }
            catch(const boost::bad_get & e) {
                std::string whatitis = "unknown";
                std::string whatyouwanted = "unknown";
                TypeToTypeNameMap::const_iterator it = GBL_type_name_map.find(value_.type().name());
                if(it != GBL_type_name_map.end()) {
                    whatitis = (*it).second;
                }
                it = GBL_type_name_map.find(typeid(T).name());
                if(it != GBL_type_name_map.end()) {
                    whatyouwanted = (*it).second;
                }
                std::cerr << "ERROR: Attempt to get a '" << whatyouwanted
                          << "' (" << typeid(T).name() << ") type on KeyValue '"
                          << key_ << "' that's a '" << whatitis << "'" << std::endl;
                throw;
            }
        }

        /*!
         * \brief Assign a new value to this object
         * \return
         * \throw SpartaException if value specified cannot be assigned to the
         * internal variant.
         * \note This method is NOT restricted to the current held value type.
         * Other types can be specified
         */
        template<class T>
        void operator=(const T& rhp) {
            value_ = rhp;
        }

        /*!
         * \brief Cast operator for the key/value
         * \return The value of this key/value pair, if the types match
         * \throw boost::bad_get if the type requested does not match the type of the key
         *
         * A fast way to get to the value of the key/value.
         * Example usage:
         * \code
         * KeyValue val1("unsigned integer", 10u);
         * unsigned int val = val1;
         * \endcode
         */
        template<class T>
        operator T() const {
            return getValue<T>();
        }

        /*!
         * \brief Determines if there is a known compiler-independent typename for type \a T
         * \tparam T Type for which a name will be looked up
         * \return true if a name is found for type \a T
         */
        template <typename T>
        static bool hasTypeNameFor() {
            TypeToTypeNameMap::const_iterator it = GBL_type_name_map.find(typeid(T).name());
            if(it != GBL_type_name_map.end()) {
                return true;
            }
            return false;
        }

        /*!
         * \brief Determines if there is a known compiler-independent typename for type \a T
         * \tparam T Type for which a name will be looked up
         * \return Name associated with type \a T.
         * \throw SpartaException if no name was found associated with type \a T
         */
        template <typename T>
        static const std::string& lookupTypeName() {
            TypeToTypeNameMap::const_iterator it = GBL_type_name_map.find(typeid(T).name());
            if(it != GBL_type_name_map.end()) {
                return (*it).second;
            }
            SpartaException e("Could not get compiler-independent type name for \"");
            e << typeid(T).name() << "\". Valid type keys are:";
            for(TypeToTypeNameMap::value_type& p : GBL_type_name_map){
                e << " " << p.first << ":" << p.second << " ";
            }
            throw e;
        }

        //! Visitor class for looking up type name
        class TypeNameVisitor : public boost::static_visitor<const std::string&>
        {
        public:
            template <typename T>
            const std::string& operator()(const T&) const { return lookupTypeName<T>(); }
        };

        /*!
         * \brief Gets the compiler-independent readable type string of the value
         * currently held.
         * \return compiler-independent type name.
         * \throw SpartaException if held variant type is not a known type. This
         * indicates a serious error.
         * \note This is not necessarily what would be returned from typeid() or
         * Variant::type().
         */
        const std::string& getTypeName() const {
            return boost::apply_visitor(TypeNameVisitor(), value_);
        }

    protected:

        /*!
         * \brief Gets a reference to the value currently held by this object
         * if the correct template type is specified.
         * \tparam T type to get current value as. This nmust be the type
         * described by getTypeName or an exception will likely be thrown
         * \warning Getting the reference to the held value is dangerous. This
         * reference is invalidated if the held type (type of value_) changes.
         * \warning discard this reference as quickly as possible.
         * \return reference to the value currenty held in this variant.
         * \throw boost::bad_get if T does not match the current held type.
         */
        template<class T>
        T& getValueRef_() {
            try {
                return boost::get<T&>(value_);
            }
            catch(const boost::bad_get & e) {
                throw throwBadGet_<T>(e);
            }
        }

        /*!
         * \brief Gets a const reference to the value currently held by this
         * object if the correct template type is specified.
         * \overload getValueRef_
         */
        template<class T>
        const T& getValueRef_() const {
            try {
                return boost::get<const T&>(value_);
            }
            catch(const boost::bad_get & e) {
                throw throwBadGet_<T>(e);
            }
        }

    private:

        /*!
         * \brief Print a message the type-mismatch in boost::get that presumably
         * caused it to fail.
         * \tparam Type of value that caused the 'get' to fail
         * \param e Exception generated by boost::get.
         * \note Returns a bad get but never reaches the return statement. GCC
         * did not understand that a function (getValueRef_) which called this
         * method did not actually need any return type since this method always
         * throws.
         * \throw The boost_bad get exception passed in; always.
         */
        template<class T>
        const boost::bad_get& throwBadGet_(const boost::bad_get& e) const {
            std::string whatitis = "unknown";
            std::string whatyouwanted = "unknown";
            TypeToTypeNameMap::const_iterator it = GBL_type_name_map.find(value_.type().name());
            if(it != GBL_type_name_map.end()) {
                whatitis = (*it).second;
            }
            it = GBL_type_name_map.find(typeid(T).name());
            if(it != GBL_type_name_map.end()) {
                whatyouwanted = (*it).second;
            }
            std::cerr << "ERROR: Attempt to get a '" << whatyouwanted
                      << "' (" << typeid(T).name() << ") type on KeyValue '"
                      << key_ << "' that's a '" << whatitis << "'" << std::endl;
            throw e;
        }

        const std::string key_;
        ValueVar value_;
        std::string desc_;
    }; // KeyValue

} // namespace sparta

//! \brief Required in simulator source to define some globals.
#define SPARTA_KVPAIR_BODY \
    namespace sparta                                                      \
    {                                                                   \
        struct NameMapper                                               \
        {                                                               \
            template<class type>                                        \
            void operator()(type) {                                     \
                assert(current_type_ != tok_.end());                    \
                KeyValue::GBL_type_name_map[typeid(type).name()] = boost::trim_left_copy(*current_type_); \
                ++current_type_;                                        \
        }                                                               \
                                                                        \
        NameMapper() : tok_(type_names, boost::char_separator<char>(",")) \
        {                                                               \
            current_type_ = tok_.begin();                               \
            boost::mpl::for_each<ValueVar::types>(*this);                  \
        }                                                               \
                                                                        \
    private:                                                            \
        boost::tokenizer<boost::char_separator<char> >::iterator current_type_; \
        boost::tokenizer<boost::char_separator<char> > tok_;            \
    };                                                                  \
                                                                        \
    TypeToTypeNameMap KeyValue::GBL_type_name_map;                      \
    static NameMapper mapper;                                           \
    }


text:
#ifndef PROTOC_READER_HPP
#define PROTOC_READER_HPP

///////////////////////////////////////////////////////////////////////////////
//
// http://protoc.sourceforge.net/
//
// Copyright (C) 2013 Bjorn Reese <breese@users.sourceforge.net>
//
// Permission to use, copy, modify, and 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.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
// CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
//
///////////////////////////////////////////////////////////////////////////////

#include <cstddef> // std::size_t
#include <string>
#include <boost/range/iterator_range.hpp>
#include <protoc/token.hpp>

namespace protoc
{

class reader
{
public:
    typedef const unsigned char value_type;
    typedef value_type * pointer;
    typedef std::size_t size_type;
    typedef boost::iterator_range<pointer> range_type;

    virtual ~reader() {}

    virtual token::value type() const = 0;
    virtual size_type size() const = 0;
    virtual bool next() = 0;
    virtual bool next(token::value) = 0;
    virtual void next_sibling() = 0;

    // FIXME: Consider a visitor instead (and standalone get() function ala variant::get)
    virtual bool get_bool() const = 0;
    virtual int get_int() const = 0;
    virtual long long get_long_long() const = 0;
    virtual double get_double() const = 0;
    virtual std::string get_string() const = 0;
    virtual range_type get_range() const = 0;
};

} // namespace protoc

#endif // PROTOC_READER_HPP


text:
#ifndef SM_UNCERTAIN_TRANSFORMATION_HPP
#define SM_UNCERTAIN_TRANSFORMATION_HPP

#include <boost/serialization/base_object.hpp>
#include "Transformation.hpp"
#include "UncertainHomogeneousPoint.hpp"

namespace sm {
namespace kinematics {

class UncertainTransformation : public Transformation {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    typedef Eigen::Matrix<double, 6, 6> covariance_t;
    ///
    /// Default constructor. The transformation and uncertainty will
    /// both be set to identity.
    ///
    UncertainTransformation();

    UncertainTransformation(const Eigen::Matrix4d& T, const covariance_t& U);

    UncertainTransformation(const Eigen::Matrix4d& T, double diagonalTranslationVariance,
                            double diagonalRotationVariance);

    UncertainTransformation(const Eigen::Vector4d& q_a_b, const Eigen::Vector3d& t_a_b_a, const covariance_t& U);

    UncertainTransformation(const Eigen::Vector4d& q_a_b, const Eigen::Vector3d& t_a_b_a,
                            double diagonalTranslationVariance, double diagonalRotationVariance);

    UncertainTransformation(const Transformation& T, const covariance_t& U);

    UncertainTransformation(const Transformation& T, double diagonalTranslationVariance,
                            double diagonalRotationVariance);

    /// \brief Initialize with zero uncertainty
    UncertainTransformation(const Transformation& T);
    /// \brief Initialize with zero uncertainty
    UncertainTransformation(const Eigen::Matrix4d& T);
    /// \brief Initialize with zero uncertainty
    UncertainTransformation(const Eigen::Vector4d& q_a_b, const Eigen::Vector3d& t_a_b_a);

    virtual ~UncertainTransformation();

    virtual UncertainTransformation operator*(const UncertainTransformation& rhs) const;
    UncertainTransformation operator*(const Transformation& rhs) const;
    UncertainHomogeneousPoint operator*(const HomogeneousPoint& rhs) const;

    Eigen::Vector3d operator*(const Eigen::Vector3d& rhs) const { return Transformation::operator*(rhs); }
    Eigen::Vector4d operator*(const Eigen::Vector4d& rhs) const { return Transformation::operator*(rhs); }

    virtual UncertainHomogeneousPoint operator*(const UncertainHomogeneousPoint& rhs) const;

    Transformation toTransformation() const;
    UncertainTransformation inverse() const;

    const covariance_t& U() const;

    /// \brief hhis gets the uncertainty based on the "oplus" function for updating the transformation matrix.
    covariance_t UOplus() const;

    /// \brief This sets the uncertainty directly.
    void setU(const covariance_t& U);

    /// \brief This sets the uncertainty based on the "oplus" function for updating the transformation matrix.
    /// This is a different uncertainty than that carried around by the class, so one should be careful.
    void setUOplus(const covariance_t& oplusU);

    // Set this to a random transformation.
    virtual void setRandom();

    virtual void setRandom(double translationMaxMeters, double rotationMaxRadians);

    bool isBinaryEqual(const UncertainTransformation& rhs) const;

    enum { CLASS_SERIALIZATION_VERSION = 0 };
    BOOST_SERIALIZATION_SPLIT_MEMBER()
    template <class Archive>
    void save(Archive& ar, const unsigned int version) const;
    template <class Archive>
    void load(Archive& ar, const unsigned int version);

  private:
    covariance_t _U;
};

template <class Archive>
void UncertainTransformation::save(Archive& ar, const unsigned int /* version */) const {
    using ::boost::serialization::make_nvp;
    ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(Transformation);
    ar << make_nvp("_U", _U);  // BOOST_SERIALIZATION_NVP(_U);
}

template <class Archive>
void UncertainTransformation::load(Archive& ar, const unsigned int version) {
    SM_ASSERT_LE(std::runtime_error, version, (unsigned int)CLASS_SERIALIZATION_VERSION,
                 "Unsupported serialization version");

    using ::boost::serialization::make_nvp;
    ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(Transformation);
    ar >> make_nvp("_U", _U);  // BOOST_SERIALIZATION_NVP(_U);
}

}  // namespace kinematics
}  // namespace sm

BOOST_CLASS_VERSION(sm::kinematics::UncertainTransformation,
                    sm::kinematics::UncertainTransformation::CLASS_SERIALIZATION_VERSION);

#endif /* SM_UNCERTAIN_TRANSFORMATION_HPP */

max_stars_repo_name: chengfzy/kalibr

max_issues_repo_name: chengfzy/kalibr

max_forks_repo_name: chengfzy/kalibr


text:
#define BOOST_TEST_DYN_LINK
#ifdef STAND_ALONE
#   define BOOST_TEST_MODULE Main
#endif
#include <boost/test/unit_test.hpp>

#include "DummyClass.h"
#include "config/ConfigurationTestConfigs.h"

BOOST_AUTO_TEST_SUITE(Configuration_Test_Suite)

BOOST_AUTO_TEST_CASE(Configuration_No_Resources_Required) {
	corm::BeanManager manager;
	corm::ConfigurationWrapper<NoResourceTestConfig> wrapper(&manager);
	BOOST_CHECK(wrapper.areResourcesSatisfied());

	NoResourceTestConfig* config = (NoResourceTestConfig*) wrapper.buildConfig();
	BOOST_CHECK_EQUAL(0, config->numTimesPostConstructCalled);
	BOOST_CHECK_EQUAL(0, config->numTimesProvideBeansCalled);
	config->initialize();
	BOOST_CHECK_EQUAL(1, config->numTimesPostConstructCalled);
	BOOST_CHECK_EQUAL(1, config->numTimesProvideBeansCalled);
	delete(config);
}

BOOST_AUTO_TEST_CASE(Configuration_Without_Required_Resources) {
	corm::BeanManager manager;
	corm::ConfigurationWrapper<MissingResourcesTestConfig> wrapper(&manager);
	BOOST_CHECK(!wrapper.areResourcesSatisfied());
	BOOST_REQUIRE_THROW(wrapper.buildConfig(), corm::ConfigurationMissingResourcesException);
}

BOOST_AUTO_TEST_CASE(Provider_and_Consumer) {
	corm::BeanManager manager;
	// The Consumer config cannot be initialized
	corm::ConfigurationWrapper<ConsumerTestConfig> consumerWrapper(&manager);
	BOOST_CHECK(!consumerWrapper.areResourcesSatisfied());

	// The provider can be initialized
	corm::ConfigurationWrapper<ProviderTestConfig> providerWrapper(&manager);
	BOOST_CHECK(providerWrapper.areResourcesSatisfied());
	ProviderTestConfig* provider = (ProviderTestConfig*) providerWrapper.buildConfig();
	provider->initialize();

	// Now can initialize the consumer
	BOOST_CHECK(consumerWrapper.areResourcesSatisfied());
	ConsumerTestConfig* consumer = (ConsumerTestConfig*) consumerWrapper.buildConfig();
	consumer->initialize();

	// Verify that the values are correct
	BOOST_CHECK_EQUAL(provider->getSomeIntValuePtr(), consumer->getProviderSomeIntValue());
	BOOST_CHECK_EQUAL(manager.getBean<DummyClass*>("providerDummyClassSingleton"), consumer->getProviderDummyClassSingleton());

	delete(provider);
	delete(consumer);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: cancech/CORM

max_issues_repo_name: cancech/CORM

max_forks_repo_name: cancech/CORM


text:
#include <boost/test/unit_test.hpp>
#include <eosio/chain/abi_serializer.hpp>
#include <eosio/chain/permission_object.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/testing/tester.hpp>

using namespace eosio;
using namespace eosio::chain;
using namespace eosio::testing;
using namespace fc;

BOOST_AUTO_TEST_SUITE(talk_tests)

BOOST_AUTO_TEST_CASE(post) try {
    tester t{setup_policy::none};

    // Load contract
    t.create_account(N(talk));
    t.set_code(N(talk), read_wasm("contract/talk/talk.wasm"));
    t.set_abi(N(talk), read_abi("contract/talk/talk.abi").data());
    t.produce_block();

    // Create users
    t.create_account(N(john));
    t.create_account(N(jane));

    // Test "post" action
    t.push_action(
        N(talk), N(post), N(john),
        mutable_variant_object //
        ("id", 1)              //
        ("reply_to", 0)        //
        ("user", "john")       //
        ("content", "post 1")  //
    );
    t.push_action(
        N(talk), N(post), N(jane),
        mutable_variant_object //
        ("id", 2)              //
        ("reply_to", 0)        //
        ("user", "jane")       //
        ("content", "post 2")  //
    );
    t.push_action(
        N(talk), N(post), N(john),
        mutable_variant_object       //
        ("id", 3)                    //
        ("reply_to", 2)              //
        ("user", "john")             //
        ("content", "post 3: reply") //
    );

    // Can't reply to non-existing message
    BOOST_CHECK_THROW(
        [&] {
            t.push_action(
                N(talk), N(post), N(john),
                mutable_variant_object       //
                ("id", 4)                    //
                ("reply_to", 99)             //
                ("user", "john")             //
                ("content", "post 3: reply") //
            );
        }(),
        fc::exception);
}
FC_LOG_AND_RETHROW()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: colinsteidtmann/EOSIO-TicTacToe

max_issues_repo_name: colinsteidtmann/EOSIO-TicTacToe

max_forks_repo_name: colinsteidtmann/EOSIO-TicTacToe


text:
//  Copyright (c) 2001-2011 Hartmut Kaiser
//  Copyright (c) 2001-2011 Joel de Guzman
//  Copyright (c)      2010 Bryce Lelbach
//  Copyright (c)      2011 Thomas Heller
//
//  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)

#if !defined(BOOST_SPIRIT_LEX_ARGUMENT_JUNE_07_2009_1106AM)
#define BOOST_SPIRIT_LEX_ARGUMENT_JUNE_07_2009_1106AM

#if defined(_MSC_VER)
#pragma once
#endif

#include <boost/spirit/home/support/string_traits.hpp>
#include <boost/spirit/home/lex/argument_phoenix.hpp>
#include <boost/fusion/include/at.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/phoenix/core/actor.hpp>
#include <boost/phoenix/core/argument.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_reference.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace boost { namespace spirit { namespace lex
{
    ///////////////////////////////////////////////////////////////////////////
    //  The state_getter is a Phoenix actor used to access the name of the
    //  current lexer state by calling get_state_name() on the context (which
    //  is the 5th parameter to any lexer semantic actions).
    //
    //  This Phoenix actor is invoked whenever the placeholder '_state' is used
    //  as a rvalue inside a lexer semantic action:
    //
    //      lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
    //      this->self = identifier [ std::cout << _state ];
    //
    //  The example shows how to print the lexer state after matching a token
    //  'identifier'.
    struct state_getter
    {
        typedef mpl::true_ no_nullary;

        template <typename Env>
        struct result
        {
            typedef
                typename remove_reference<
                   typename remove_const<
                        typename mpl::at_c<typename Env::args_type, 4>::type
                    >::type
                >::type
            context_type;

            typedef typename context_type::state_name_type type;
        };

        template <typename Env>
        typename result<Env>::type
        eval(Env const& env) const
        {
            return fusion::at_c<4>(env.args()).get_state_name();
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  The state_setter is a Phoenix actor used to change the name of the
    //  current lexer state by calling set_state_name() on the context (which
    //  is the 5th parameter to any lexer semantic actions).
    //
    //  This Phoenix actor is invoked whenever the placeholder '_state' is used
    //  as a lvalue inside a lexer semantic action:
    //
    //      lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
    //      this->self = identifier [ _state = "SOME_LEXER_STATE" ];
    //
    //  The example shows how to change the lexer state after matching a token
    //  'identifier'.
    template <typename Actor>
    struct state_setter
    {
        typedef mpl::true_ no_nullary;

        template <typename Env>
        struct result
        {
            typedef void type;
        };

        template <typename Env>
        void eval(Env const& env) const
        {
            fusion::at_c<4>(env.args()).set_state_name(
                traits::get_c_string(actor_.eval(env)));
        }

        state_setter(Actor const& actor)
          : actor_(actor) {}

        Actor actor_;
    };

    ///////////////////////////////////////////////////////////////////////////
    //  The value_getter is used to create the _val placeholder, which is a
    //  Phoenix actor used to access the value of the current token.
    //
    //  This Phoenix actor is invoked whenever the placeholder '_val' is used
    //  as a rvalue inside a lexer semantic action:
    //
    //      lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
    //      this->self = identifier [ std::cout << _val ];
    //
    //  The example shows how to use _val to print the identifier name (which
    //  is the initial token value).
    struct value_getter
    {
        typedef mpl::true_ no_nullary;

        template <typename Env>
        struct result
        {
            typedef
                typename remove_reference<
                   typename remove_const<
                        typename mpl::at_c<typename Env::args_type, 4>::type
                    >::type
                >::type
            context_type;

            typedef typename context_type::get_value_type type;
        };

        template <typename Env>
        typename result<Env>::type
        eval(Env const& env) const
        {
            return fusion::at_c<4>(env.args()).get_value();
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    //  The value_setter is a Phoenix actor used to change the name of the
    //  current lexer state by calling set_state_name() on the context (which
    //  is the 5th parameter to any lexer semantic actions).
    //
    //  This Phoenix actor is invoked whenever the placeholder '_val' is used
    //  as a lvalue inside a lexer semantic action:
    //
    //      lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
    //      this->self = identifier [ _val = "identifier" ];
    //
    //  The example shows how to change the token value after matching a token
    //  'identifier'.
    template <typename Actor>
    struct value_setter
    {
        typedef mpl::true_ no_nullary;

        template <typename Env>
        struct result
        {
            typedef void type;
        };

        template <typename Env>
        void eval(Env const& env) const
        {
            fusion::at_c<4>(env.args()).set_value(actor_.eval(env));
        }

        value_setter(Actor const& actor)
          : actor_(actor) {}

        Actor actor_;
    };

    ///////////////////////////////////////////////////////////////////////////
    //  The eoi_getter is used to create the _eoi placeholder, which is a
    //  Phoenix actor used to access the end of input iterator pointing to the
    //  end of the underlying input sequence.
    //
    //  This actor is invoked whenever the placeholder '_eoi' is used in a
    //  lexer semantic action:
    //
    //      lex::token_def<> identifier = "[a-zA-Z_][a-zA-Z0-9_]*";
    //      this->self = identifier
    //          [ std::cout << construct_<std::string>(_end, _eoi) ];
    //
    //  The example shows how to use _eoi to print all remaining input after
    //  matching a token 'identifier'.
    struct eoi_getter
    {
        typedef mpl::true_ no_nullary;

        template <typename Env>
        struct result
        {
            typedef
                typename remove_reference<
                   typename remove_const<
                        typename mpl::at_c<typename Env::args_type, 4>::type
                    >::type
                >::type
            context_type;

            typedef typename context_type::base_iterator_type const& type;
        };

        template <typename Env>
        typename result<Env>::type
        eval(Env const& env) const
        {
            return fusion::at_c<4>(env.args()).get_eoi();
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    // '_start' and '_end' may be used to access the start and the end of
    // the matched sequence of the current token
    typedef phoenix::arg_names::_1_type _start_type;
    typedef phoenix::arg_names::_2_type _end_type;
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
    _start_type const _start = _start_type();
    _end_type const _end = _end_type();
#endif

    // We are reusing the placeholder '_pass' to access and change the pass
    // status of the current match (see support/argument.hpp for its
    // definition).
    // typedef phoenix::arg_names::_3_type _pass_type;
    using boost::spirit::_pass_type;
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
    using boost::spirit::_pass;
#endif

    // '_tokenid' may be used to access and change the tokenid of the current
    // token
    typedef phoenix::arg_names::_4_type _tokenid_type;
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
    _tokenid_type const _tokenid = _tokenid_type();
#endif

    typedef phoenix::actor<value_context> _val_type;
    typedef phoenix::actor<state_context> _state_type;
    typedef phoenix::actor<eoi_getter> _eoi_type;
#ifndef BOOST_SPIRIT_NO_PREDEFINED_TERMINALS
    // '_val' may be used to access and change the token value of the current
    // token
    _val_type const _val = _val_type();
    // _state may be used to access and change the name of the current lexer
    // state
    _state_type const _state = _state_type();
    // '_eoi' may be used to access the end of input iterator of the input
    // stream used by the lexer to match tokens from
    _eoi_type const _eoi = _eoi_type();
#endif
}}}

#undef SPIRIT_DECLARE_ARG
#endif


text:
#pragma once
#include <graphene/protocol/operations.hpp>
#include <graphene/db/generic_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <fc/uint128.hpp>
#include <graphene/chain/database.hpp>

#include <iostream>

namespace graphene { namespace chain {

   /**
    * @class witnesses_info_object
    * @ingroup object
    * @ingroup protocol
    *
    * This object contains info about witnesses
    */
   class witnesses_info_object : public abstract_object<witnesses_info_object>
   {
   public:
      static const uint8_t space_id = protocol_ids;
      static const uint8_t type_id  = witnesses_info_object_type;

      // all fee rewards between two maintenance times
      share_type witness_fees_reward_edc_amount;

      // all signed blocks between two MT
      int64_t all_blocks_reward_count = 0;

      flat_set<account_id_type> exc_accounts_blocks;
      flat_set<account_id_type> exc_accounts_fees;

      settings_id_type get_id() { return id; }
   };

}}

MAP_OBJECT_ID_TO_TYPE(graphene::chain::witnesses_info_object)

FC_REFLECT_TYPENAME( graphene::chain::witnesses_info_object )

GRAPHENE_DECLARE_EXTERNAL_SERIALIZATION( graphene::chain::witnesses_info_object )

max_stars_repo_name: EDCBlockchain/blockchain


text:
// Copyright (C) 2014 Massachusetts Institute of Technology, Lincoln Laboratory
// License: Boost Software License   See LICENSE.txt for the full license.
// Authors: Davis E. King (davis@dlib.net)

#include <dlib/matrix.h>
#include <mitie/named_entity_extractor.h>
#include <string>

using namespace dlib;
using namespace std;
using namespace mitie;

#define ARG_4_DEFAULT ""

string classname;
named_entity_extractor ner;
bool did_init = false;

void mex_function (
    const std::vector<std::string>& tokens,
    std::vector<matrix<double,1> >& entities,
    std::vector<std::string>& labels,
    const std::string& model_filename
)
{
    if (!did_init)
    {
        if (model_filename == "")
            throw dlib::error("You need to give a MITIE ner model file as the second argument the first time you call this function.");

        dlib::deserialize(model_filename) >> classname >> ner;
        did_init = true;
    }

    std::vector<pair<unsigned long, unsigned long> > chunks;
    std::vector<unsigned long> chunk_tags;
    // Now detect all the entities in the tokens.  The output of this function is a set of
    // "chunks" of tokens, each a named entity.
    ner(tokens, chunks, chunk_tags);

    const std::vector<string> tagstr = ner.get_tag_name_strings();
    entities.clear();
    labels.clear();
    // copy the entities into the output variables
    for (unsigned int i = 0; i < chunks.size(); ++i)
    {
        labels.push_back(tagstr[chunk_tags[i]]);
        const unsigned long length = chunks[i].second-chunks[i].first;
        entities.push_back(linspace(chunks[i].first+1, chunks[i].second, length));
    }
}

#include "mex_wrapper.cpp"

max_stars_repo_name: maxmert/nlp-mitie

max_issues_repo_name: maxmert/nlp-mitie

max_forks_repo_name: maxmert/nlp-mitie


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_IS_NLTZ_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_IS_NLTZ_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-predicates

    This function object returns @ref True if x is not less than @ref Zero else returns @ref False.

    @par Header <boost/simd/function/is_nltz.hpp>

    @par Note

     Using `is_nltz(x)` is similar to: `!(x < 0)`

    @par Example:

      @snippet is_nltz.cpp is_nltz

    @par Possible output:

      @snippet is_nltz.txt is_nltz

  **/
  as_logical_t<Value> is_nltz(Value const& x);
} }
#endif

#include <boost/simd/function/scalar/is_nltz.hpp>
#include <boost/simd/function/simd/is_nltz.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
//  Copyright 2015 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.

#define BOOST_CHRONO_VERION 2
#include <iostream>
#include <boost/chrono/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>

// a custom clock
// here based on boost's own system_clock
class MyMillenniumClock
{
public:
  typedef boost::chrono::system_clock::rep rep;
  typedef boost::chrono::system_clock::period period;
  typedef boost::chrono::duration<rep, period> duration;
  typedef boost::chrono::time_point<MyMillenniumClock> time_point;

  BOOST_STATIC_CONSTEXPR bool is_steady = boost::chrono::system_clock::is_steady;

public:
  /// Returns a time_point representing the current value of the clock.
  static time_point now() {
    return time_point(boost::chrono::system_clock::now().time_since_epoch() - boost::chrono::hours(30*365));
  }
};

namespace boost
{
  namespace chrono
  {
    template <class CharT>
    struct clock_string<MyMillenniumClock, CharT>
    {
      static std::basic_string<CharT> name() {
        static const CharT a[] = {'M', 'y', 'M', 'i', 'l', 'l', 'e', 'n', 'n', 'i', 'u', 'm', 'C', 'l', 'o', 'c', 'k'};
        return std::basic_string<CharT>(a, a + sizeof(a)/sizeof(a[0]));
      }
      static std::basic_string<CharT> since() {
        static const CharT a[] = {' ', 's', 'i', 'n', 'c', 'e', ' ', 'y', 'e', 'a', 'r', ' ', '2', 'k'};
        return std::basic_string<CharT>(a, a + sizeof(a)/sizeof(a[0]));
      }
    };
  }
}

template <typename CharT, typename TPUFacet>
std::basic_string<CharT> get_epoch_custom(MyMillenniumClock, TPUFacet&)
{
  return boost::chrono::clock_string<MyMillenniumClock,CharT>::since();
}

int main()
{
    std::cout << boost::chrono::steady_clock::now() << std::endl;
    std::cout << MyMillenniumClock::now() << std::endl;
    return 0;
}


text:
// TestMarketData.cpp

#ifndef _MSC_VER
#define BOOST_TEST_DYN_LINK
#endif
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE test_market_data

#include "../tools/MarketData.hpp"
#include "../tools/Authentication.hpp"
#include "../tools/FileReadingUtilities.hpp"

#include <boost/test/unit_test.hpp>
#include <string>
#include <iostream>

BOOST_AUTO_TEST_SUITE(test_market_data)

BOOST_AUTO_TEST_CASE(price_check)
{
	// we need to set the access token first
	tools::Authentication::setup();

	// check multiple stocks at once
	std::vector<double> prices;

	std::vector<std::string> stocks = {"AMZN", "AAPL", "BA", "VGT"};
	BOOST_CHECK_NO_THROW(prices = tools::MarketData::getPrices(stocks));

	for (size_t i = 0; i < prices.size(); i++)
	{
		std::cout << stocks[i] << ": $" << prices[i] << std::endl;
	}
}

BOOST_AUTO_TEST_CASE(market_is_open)
{
	bool result;

	// will throw on malformed JSON response
	BOOST_CHECK_NO_THROW(result = tools::MarketData::isOpen());

	std::cout << "Market open? " << result << std::endl;
}

BOOST_AUTO_TEST_CASE(IEX_key_stats)
{
	std::vector<double> keyStats;
	std::vector<std::string> interestedFields = {"marketcap", "dividendYield", "peRatioHigh", "peRatioLow"};

	BOOST_CHECK_NO_THROW(keyStats = tools::MarketData::getKeyStats("AAPL", interestedFields));

	// print results
	for (size_t i = 0; i < keyStats.size(); i++)
	{
		std::cout << interestedFields[i] << ": " << keyStats[i] << std::endl;
	}
}

BOOST_AUTO_TEST_CASE(calculate_RSI)
{
	double rsi;

	BOOST_CHECK_NO_THROW(rsi = tools::MarketData::getRSI("AAPL"));

	std::cout << "RSI of AAPL: " << rsi << std::endl;
}

BOOST_AUTO_TEST_CASE(PE_ratio)
{
	double peRatio;
	BOOST_CHECK_NO_THROW(peRatio = tools::MarketData::getPE("AAPL"));
	std::cout << "PE of AAPL: " << peRatio << std::endl;
}

BOOST_AUTO_TEST_CASE(todays_change_in_percentage)
{
	double change;
	BOOST_CHECK_NO_THROW(change = tools::MarketData::getTodayChangePercentage("AAPL"));
	std::cout << "Today % change in AAPL: " << change << std::endl;
}

BOOST_AUTO_TEST_CASE(latest_headline)
{
	std::string aapl="aapl", ba="ba", mmm="mmm";
	BOOST_CHECK_NO_THROW(aapl = tools::MarketData::getLatestHeadlines(aapl, 1));
	BOOST_CHECK_NO_THROW(ba = tools::MarketData::getLatestHeadlines(ba, 1));
	BOOST_CHECK_NO_THROW(mmm = tools::MarketData::getLatestHeadlines(mmm, 1));

	std::cout << "Apple headline: " << aapl << std::endl;
	std::cout << "Boing headline: " << ba << std::endl;
	std::cout << "3M headline: " << mmm << std::endl;
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: joshuakarbi/trader

max_issues_repo_name: joshuakarbi/trader

max_forks_repo_name: joshuakarbi/trader


text:
/**
 * @file
 * This file is part of SeisSol.
 *
 * @author Carsten Uphoff (c.uphoff AT tum.de, http://www5.in.tum.de/wiki/index.php/Carsten_Uphoff,_M.Sc.)
 * @author Sebastian Wolf (wolf.sebastian AT in.tum.de, https://www5.in.tum.de/wiki/index.php/Sebastian_Wolf,_M.Sc.)
 *
 * @section LICENSE
 * Copyright (c) 2015 - 2020, SeisSol Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * @section DESCRIPTION
 **/

#ifndef MODEL_COMMON_HPP_
#define MODEL_COMMON_HPP_

#include <Eigen/Eigen>

#include "utils/logger.h"
#include "Initializer/typedefs.hpp"
#include "generated_code/init.h"
#include "Geometry/MeshTools.h"
#include "Numerical_aux/Transformation.h"

#include "Model/common_datastructures.hpp"

namespace seissol {
  namespace model {
    using Matrix99 = Eigen::Matrix<double, 9, 9>;

    bool testIfAcoustic(real mu);

    template<typename Tmaterial, typename Tmatrix>
    void getTransposedCoefficientMatrix( Tmaterial const& i_material,
                                         unsigned         i_dim,
                                         Tmatrix&         o_M )
    { o_M.setZero(); }

    template<typename Tmaterial, typename T>
    void getTransposedSourceCoefficientTensor(  Tmaterial const& material,
                                                T& E);

    template<typename Tmaterial, typename Tloc, typename Tneigh>
    void getTransposedGodunovState( Tmaterial const&  local,
                                    Tmaterial const&  neighbor,
                                    FaceType          faceType,
                                    Tloc&             QgodLocal,
                                    Tneigh&           QgodNeighbor );

    template<typename T>
    void getTransposedFreeSurfaceGodunovState( bool isAcoustic,
                                               T& QgodLocal,
                                               T& QgodNeighbor,
                                               Eigen::Matrix<double, 9, 9>& R);

    template<typename T>
    void getPlaneWaveOperator( T const& material,
                               double const n[3],
                               std::complex<double> Mdata[NUMBER_OF_QUANTITIES*NUMBER_OF_QUANTITIES] );

    template<typename T, typename S>
    void initializeSpecificLocalData( T const&,
                                      S* LocalData ) {}

    template<typename T, typename S>
    void initializeSpecificNeighborData(  T const&,
                                          S* NeighborData ) {}

    /*
     * Calculates the so called Bond matrix. Anisotropic materials are characterized by
     * 21 different material parameters. Due to the directional dependence of anisotropic
     * materials the parameters are not independet of the choice of the coordinate system.
     * The Bond matrix transforms materials from one orthogonal coordinate system to
     * another one.
     * c.f. 10.1111/j.1365-246X.2007.03381.x
     */
    void getBondMatrix( VrtxCoords const i_normal,
                        VrtxCoords const i_tangent1,
                        VrtxCoords const i_tangent2,
                        real* o_N );

    void getFaceRotationMatrix( VrtxCoords const i_normal,
                                VrtxCoords const i_tangent1,
                                VrtxCoords const i_tangent2,
                                init::T::view::type& o_T,
                                init::Tinv::view::type& o_Tinv );
  }
}

template<typename T>
void seissol::model::getPlaneWaveOperator(  T const& material,
                                            double const n[3],
                                            std::complex<double> Mdata[NUMBER_OF_QUANTITIES*NUMBER_OF_QUANTITIES] )
{
  yateto::DenseTensorView<2,std::complex<double>> M(Mdata, {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES});
  M.setZero();

  double data[NUMBER_OF_QUANTITIES * NUMBER_OF_QUANTITIES];
  yateto::DenseTensorView<2,double> Coeff(data, {NUMBER_OF_QUANTITIES, NUMBER_OF_QUANTITIES});

  for (unsigned d = 0; d < 3; ++d) {
    Coeff.setZero();
    getTransposedCoefficientMatrix(material, d, Coeff);

    for (unsigned i = 0; i < NUMBER_OF_QUANTITIES; ++i) {
      for (unsigned j = 0; j < NUMBER_OF_QUANTITIES; ++j) {
        M(i,j) += n[d] * Coeff(j,i);
      }
    }
  }
}

template<typename T>
void seissol::model::getTransposedFreeSurfaceGodunovState( bool      isAcoustic,
                                                           T&        QgodLocal,
                                                           T&        QgodNeighbor,
                                                           Eigen::Matrix<double, 9, 9>& R)
{
  for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
      QgodNeighbor(i,j) = std::numeric_limits<double>::signaling_NaN();
    }
  }

  QgodLocal.setZero();
  if (isAcoustic) {
    // Acoustic material only has one traction (=pressure) and one velocity comp.
    // relevant to the Riemann problem
    QgodLocal(0, 6) = -1 * R(6,0) * 1/R(0,0); // S
    QgodLocal(6, 6) = 1.0;
  } else {
    std::array<int, 3> traction_indices = {0,3,5};
    std::array<int, 3> velocity_indices = {6,7,8};
    using Matrix33 = Eigen::Matrix<double, 3, 3>;
    Matrix33 R11 = R(traction_indices, {0,1,2});
    Matrix33 R21 = R(velocity_indices, {0,1,2});
    Matrix33 S = (-(R21 * R11.inverse())).eval();

    //set lower left block
    int row = 0;
    for (auto &t: traction_indices) {
      int col = 0;
      for (auto &v: velocity_indices) {
        QgodLocal(t, v) = S(row, col);
        col++;
      }
      row++;
    }

    //set lower right block
    for (auto &v : velocity_indices) {
      QgodLocal(v, v) = 1.0;
    }
  }
}

#endif

max_stars_repo_name: VMPW/SeisSol

max_issues_repo_name: VMPW/SeisSol

max_forks_repo_name: VMPW/SeisSol


text:
#include "test_registrator.h"
#include <time_tracker.h>

#include <boost/thread.hpp>

using namespace system_utilities::common;
using namespace std::chrono;

namespace system_utilities
{
	namespace tests_
	{
		namespace common
		{
			void time_tracker_constructor_tests()
			{
				BOOST_CHECK_NO_THROW( time_tracker< milliseconds > tt );
				time_tracker< milliseconds > tt;
				BOOST_CHECK_NO_THROW( tt.reset() );
			}
			void time_tracker_milliseconds_tests()
			{
				{
					time_tracker< milliseconds > tt;
					BOOST_CHECK_EQUAL( tt.elapsed(), static_cast< size_t >( 0 ) );
				}
				{
					static const size_t time_to_sleep = 1;
					time_tracker< milliseconds > tt;
					long long old_time = tt.elapsed();
					for ( size_t i = 0 ; i < 5 ; ++i )
					{
						boost::this_thread::sleep( boost::posix_time::milliseconds( time_to_sleep ) );
						BOOST_CHECK_EQUAL( tt.elapsed() > old_time, true );
						old_time = tt.elapsed();
					}
				}
			}
			void time_tracker_seconds_tests()
			{
				{
					time_tracker< seconds > tt;
					BOOST_CHECK_EQUAL( tt.elapsed(), static_cast< size_t >( 0 ) );
				}
				{
					time_tracker< seconds > tt;
					for ( size_t i = 0 ; i < 3 ; ++i )
					{
						boost::this_thread::sleep( boost::posix_time::milliseconds( 1001 ) );
						BOOST_CHECK_EQUAL( tt.elapsed() >= (i + 1), true );
						BOOST_CHECK_EQUAL( tt.elapsed() < (i + 1) + 2, true );
					}
				}
			}
		}
	}
}


text:
#include "source.hpp"
#include "sink.hpp"
#include "except.hpp"
#include <boost/exception/errinfo_file_name.hpp>
#include <iostream>

#define NEPTOOLS_LOG_NAME "source"
#include "logger_helper.hpp"

namespace Neptools
{

namespace
{

template <typename T>
struct UnixLike : public Source::Provider
{
    UnixLike(LowIo io, boost::filesystem::path file_name, FilePosition size)
        : Source::Provider{std::move(file_name), size}, io{std::move(io)} {}
    ~UnixLike();

    void Pread(FilePosition offs, Byte* buf, FileMemSize len) override;
    void EnsureChunk(FilePosition i);

    LowIo io;
};

struct MmapProvider final : public UnixLike<MmapProvider>
{
    MmapProvider(LowIo&& fd, boost::filesystem::path file_name,
                 FilePosition size);

    static FileMemSize CHUNK_SIZE;
    void* ReadChunk(FilePosition offs, FileMemSize size);
    void DeleteChunk(size_t i);
};

struct UnixProvider final : public UnixLike<UnixProvider>
{
    //using UnixLike::UnixLike;
    // workaround clang bug...
    UnixProvider(LowIo&& io, boost::filesystem::path file_name, FilePosition size)
        : UnixLike{std::move(io), file_name, size} {}

    static FileMemSize CHUNK_SIZE;
    void* ReadChunk(FilePosition offs, FileMemSize size);
    void DeleteChunk(size_t i);
};

}

Source Source::FromFile(boost::filesystem::path fname)
{
    return AddInfo(
        &FromFile_,
        [&](auto& e) { e << boost::errinfo_file_name{fname.string()}; },
        fname);
}

Source Source::FromFile_(boost::filesystem::path fname)
{
    LowIo io{fname.c_str(), false};

    FilePosition size = io.GetSize();

    SmartPtr<Provider> p;
    try { p = MakeSmart<MmapProvider>(std::move(io), fname.string(), size); }
    catch (const std::system_error& e)
    {
        WARN << "Mmap failed, falling back to normal reading: "
             << ExceptionToString() << std::endl;
        p = MakeSmart<UnixProvider>(std::move(io), fname.string(), size);
    }
    return {MakeNotNull(std::move(p)), size};
}

void Source::Pread_(FilePosition offs, Byte* buf, FileMemSize len) const
{
    offs += offset;
    while (len)
    {
        if (p->LruGet(offs))
        {
            auto& x = p->lru[0];
            auto buf_offs = offs - x.offset;
            auto to_cpy = std::min(len, x.size - buf_offs);
            memcpy(buf, x.ptr + buf_offs, to_cpy);
            offs += to_cpy;
            buf += to_cpy;
            len -= to_cpy;
        }
        else
            return p->Pread(offs, buf, len);
    }
}

Source::BufEntry Source::GetTemporaryEntry(FilePosition offs) const
{
    if (p->LruGet(offs)) return p->lru[0];
    p->Pread(offs, nullptr, 0);
    NEPTOOLS_ASSERT(p->lru[0].offset <= offs &&
                    p->lru[0].offset + p->lru[0].size > offs);
    return p->lru[0];
}

void Source::Provider::LruPush(Byte* ptr, FilePosition offset, FileMemSize size)
{
    memmove(&lru[1], &lru[0], sizeof(BufEntry)*(lru.size()-1));
    lru[0].ptr = ptr;
    lru[0].offset = offset;
    lru[0].size = size;
}

bool Source::Provider::LruGet(FilePosition offs)
{
    for (size_t i = 0; i < lru.size(); ++i)
    {
        auto x = lru[i];
        if (x.offset <= offs && x.offset + x.size > offs)
        {
            memmove(&lru[1], &lru[0], sizeof(BufEntry)*i);
            lru[0] = x;
            return true;
        }
    }
    return false;
}

template <typename T>
UnixLike<T>::~UnixLike()
{
    for (size_t i = 0; i < lru.size(); ++i)
        if (lru[i].size)
            static_cast<T*>(this)->DeleteChunk(i);
}

template <typename T>
void UnixLike<T>::Pread(FilePosition offs, Byte* buf, FileMemSize len)
{
    NEPTOOLS_ASSERT(io.fd != NEPTOOLS_INVALID_FD);
    if (len > static_cast<T*>(this)->CHUNK_SIZE)
        return io.Pread(buf, len, offs);

    if (len == 0) EnsureChunk(offs); // TODO: GetTemporaryEntry hack
    while (len)
    {
        EnsureChunk(offs);
        auto buf_offs = offs - lru[0].offset;
        auto to_cpy = std::min(len, lru[0].size - buf_offs);
        memcpy(buf, lru[0].ptr + buf_offs, to_cpy);
        buf += to_cpy;
        offs += to_cpy;
        len -= to_cpy;
    }
}

template <typename T>
void UnixLike<T>::EnsureChunk(FilePosition offs)
{
    auto const CHUNK_SIZE = static_cast<T*>(this)->CHUNK_SIZE;
    auto ch_offs = offs/CHUNK_SIZE*CHUNK_SIZE;
    if (LruGet(offs)) return;

    auto size = std::min(CHUNK_SIZE, this->size-ch_offs);
    auto x = static_cast<T*>(this)->ReadChunk(ch_offs, size);
    static_cast<T*>(this)->DeleteChunk(lru.size()-1);
    LruPush(static_cast<Byte*>(x), ch_offs, size);
}

FileMemSize MmapProvider::CHUNK_SIZE = LowIo::MMAP_CHUNK;
MmapProvider::MmapProvider(
    LowIo&& io, boost::filesystem::path file_name, FilePosition size)
    : UnixLike{{}, std::move(file_name), size}
{
    size_t to_map = size < LowIo::MMAP_LIMIT ? size : LowIo::MMAP_CHUNK;

    io.PrepareMmap(false);
    void* ptr = io.Mmap(0, to_map, false);
#ifndef WINDOWS
    if (to_map == size)
    {
        close(io.fd);
        io.fd = -1;
    }
#endif
    this->io = std::move(io);

    lru[0].ptr = static_cast<Byte*>(ptr);
    lru[0].offset = 0;
    lru[0].size = to_map;
}

void* MmapProvider::ReadChunk(FilePosition offs, FileMemSize size)
{
    return io.Mmap(offs, size, false);
}

void MmapProvider::DeleteChunk(size_t i)
{
    if (lru[i].ptr)
        io.Munmap(lru[i].ptr, lru[i].size);
}

FilePosition UnixProvider::CHUNK_SIZE = LowIo::MEM_CHUNK;

void* UnixProvider::ReadChunk(FilePosition offs, FileMemSize size)
{
    std::unique_ptr<Byte[]> x{new Byte[size]};
    io.Pread(x.get(), size, offs);
    return x.release();
}

void UnixProvider::DeleteChunk(size_t i)
{
    delete[] lru[i].ptr;
}

void DumpableSource::Inspect_(std::ostream& os) const
{
    auto flags = os.flags();
    os << std::hex << "bin(";
    DumpBytes(os, GetFileName().generic_string());
    os << ", 0x" << GetOffset() << ", 0x" << GetSize() << ")";
    os.flags(flags);
}

void DumpableSource::Dump_(Sink& sink) const
{
    auto offset = GetOffset();
    auto rem_size = GetSize();
    while (rem_size)
    {
        auto x = GetTemporaryEntry(offset);
        NEPTOOLS_ASSERT(x.offset <= offset);
        auto ptroff = offset - x.offset;
        auto size = std::min(rem_size, x.size - ptroff);
        sink.Write({x.ptr + ptroff, size});
        offset += size;
        rem_size -= size;
    }
}

std::string to_string(const UsedSource& src)
{
    std::stringstream ss;
    ss << "[Source] = ";
    DumpableSource{src.value()}.Inspect(ss);
    ss << ", pos: " << src.value().Tell() << '\n';
    return ss.str();
}

}

max_stars_repo_name: clienthax/neptools

max_issues_repo_name: clienthax/neptools

max_forks_repo_name: clienthax/neptools


text:
#include <bts/utilities/string_escape.hpp>
#include <fc/optional.hpp>
#include <fc/filesystem.hpp>
#include <fc/io/json.hpp>
#include <fc/variant_object.hpp>
#include <fc/reflect/variant.hpp>
#include <fc/exception/exception.hpp>
#include <fc/log/logger.hpp>
#include <fc/io/stdio.hpp>
#include <fc/io/buffered_iostream.hpp>

#include <bts/client/messages.hpp>
#include <bts/net/message.hpp>

#include <boost/program_options.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/tokenizer.hpp>

#include <iostream>
#include <fstream>
#include <list>
#include <set>

int main(int argc, char*argv[])
{
  for (;;)
  {
    fc::variant json_as_variant;
    try
    {
      fc::buffered_istream istream(fc::cin_ptr);
      json_as_variant = fc::json::from_stream(istream);
    }
    catch (const fc::eof_exception& e)
    {
      elog("EOF, exiting");
      return 0;
    }
    catch (const fc::exception& e)
    {
      elog("Error parsing json: ${what}", ("what", e.to_string()));
      continue;
    }

    fc::variant_object json_as_variant_object;
    try
    {
      json_as_variant_object = json_as_variant.get_object();
    }
    catch (const fc::exception& e)
    {
      elog("Error interpreting json as object: ${what}", ("what", e.to_string()));
      continue;
    }

    if (json_as_variant_object.contains("trx"))
    {
      ilog("Object contains the key 'trx', assuming it is a trx_message");
      bts::client::trx_message trx_msg;
      try
      {
        trx_msg = json_as_variant.as<bts::client::trx_message>();
      }
      catch (const fc::exception& e)
      {
        elog("Error interpreting json as bts::client::trx_message: ${what}", ("what", e.to_string()));
      }

      ilog("Parsed bts::client::trx_message with id ${msg_id} containing transaction ${trx_id}",
        ("msg_id", bts::net::message(trx_msg).id())("trx_id", trx_msg.trx.id()));
    }
  }

#if 0

  // parse command-line options
  boost::program_options::options_description option_config("Allowed options");
  option_config.add_options()("help",                                                             "display this help message")
                             ("prologue"    ,  boost::program_options::value<std::string>(), "Add the contents of this file to start of generated C++ source")
                             ("epilogue"    ,  boost::program_options::value<std::string>(), "Add the contents of this file to end   of generated C++ source")
                             ("json"        ,  boost::program_options::value<std::string>(), "The json file to convert to C++ source code")
                             ("out"         ,  boost::program_options::value<std::string>(), "The file to generate");
  boost::program_options::variables_map option_variables;
  try
  {
    boost::program_options::store(boost::program_options::command_line_parser(argc, argv).
      options(option_config).run(), option_variables);
    boost::program_options::notify(option_variables);
  }
  catch (boost::program_options::error&)
  {
    std::cerr << "Error parsing command-line options\n\n";
    std::cerr << option_config << "\n";
    return 1;
  }
#endif
  return 0;
}

max_stars_repo_name: emfrias/bitshares

max_issues_repo_name: emfrias/bitshares

max_forks_repo_name: emfrias/bitshares


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2009. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
//[doc_managed_construction_info
#include <boost/interprocess/managed_shared_memory.hpp>
#include <cassert>
#include <cstring>
//<-
#include "../test/get_process_id_name.hpp"
//->

class my_class
{
   //...
};

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

   //Remove shared memory on construction and destruction
   struct shm_remove
   {
   //<-
   #if 1
      shm_remove() { shared_memory_object::remove(test::get_process_id_name()); }
      ~shm_remove(){ shared_memory_object::remove(test::get_process_id_name()); }
   #else
   //->
      shm_remove() { shared_memory_object::remove("MySharedMemory"); }
      ~shm_remove(){ shared_memory_object::remove("MySharedMemory"); }
   //<-
   #endif
   //->
   } remover;

   //<-
   #if 1
   managed_shared_memory managed_shm(create_only, test::get_process_id_name(), 10000*sizeof(std::size_t));
   #else
   //->
   managed_shared_memory managed_shm(create_only, "MySharedMemory", 10000*sizeof(std::size_t));
   //<-
   #endif
   //->

   //Construct objects
   my_class *named_object  = managed_shm.construct<my_class>("Object name")[1]();
   my_class *unique_object = managed_shm.construct<my_class>(unique_instance)[2]();
   my_class *anon_object   = managed_shm.construct<my_class>(anonymous_instance)[3]();

   //Now test "get_instance_name" function.
   assert(0 == std::strcmp(managed_shared_memory::get_instance_name(named_object), "Object name"));
   assert(0 == managed_shared_memory::get_instance_name(unique_object));
   assert(0 == managed_shared_memory::get_instance_name(anon_object));

   //Now test "get_instance_type" function.
   assert(named_type     == managed_shared_memory::get_instance_type(named_object));
   assert(unique_type    == managed_shared_memory::get_instance_type(unique_object));
   assert(anonymous_type == managed_shared_memory::get_instance_type(anon_object));

   //Now test "get_instance_length" function.
   assert(1 == managed_shared_memory::get_instance_length(named_object));
   assert(2 == managed_shared_memory::get_instance_length(unique_object));
   assert(3 == managed_shared_memory::get_instance_length(anon_object));

   managed_shm.destroy_ptr(named_object);
   managed_shm.destroy_ptr(unique_object);
   managed_shm.destroy_ptr(anon_object);
   return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#ifndef KAGOME_CORE_PRIMITIVES_TRANSACTION_VALIDITY_HPP
#define KAGOME_CORE_PRIMITIVES_TRANSACTION_VALIDITY_HPP

#include <cstdint>
#include <vector>

#include <boost/variant.hpp>
#include <outcome/outcome.hpp>
#include "primitives/transaction.hpp"

namespace kagome::primitives {

  /**
   * @brief Information concerning a valid transaction.
   *
   * This is the same structure as in
   * https://github.com/paritytech/substrate/blob/a31c01b398d958ccf0a24d8c1c11fb073df66212/core/sr-primitives/src/transaction_validity.rs#L178
   */
  struct ValidTransaction {
    /**
     * @brief Priority of the transaction.
     * Priority determines the ordering of two transactions that have all
     * their dependencies (required tags) satisfied.
     */
    Transaction::Priority priority{};

    /**
     * @brief Transaction dependencies
     * A non-empty list signifies that some other transactions which provide
     * given tags are required to be included before that one.
     */
    std::vector<Transaction::Tag> requires;

    /**
     * @brief Provided tags
     * A list of tags this transaction provides. Successfuly importing the
     * transaction will enable other transactions that depend on (require)
     * those tags to be included as well. Provided and requried tags allow
     * Substrate to build a dependency graph of transactions and import them
     * in the right (linear) order.
     */
    std::vector<Transaction::Tag> provides;

    /**
     * @brief Transaction longevity
     * Longevity describes minimum number of blocks the validity is correct.
     * After this period transaction should be removed from the pool or
     * revalidated.
     */
    Transaction::Longevity longevity{};

    /**
     * @brief A flag indicating if the transaction should be propagated to other
     * peers. By setting `false` here the transaction will still be considered
     * for including in blocks that are authored on the current node, but will
     * never be sent to other peers.
     */
    bool propagate{};

    bool operator==(const ValidTransaction &rhs) const {
      return priority == rhs.priority and requires == rhs.requires
             and provides == rhs.provides and longevity == rhs.longevity
             and propagate == rhs.propagate;
    }

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

  /// Transaction is invalid. Details are described by the error code.
  enum class InvalidTransaction : uint8_t {
    /// The call of the transaction is not expected.
    Call = 1,
    /// General error to do with the inability to pay some fees (e.g. account
    /// balance too low).
    Payment,
    /// General error to do with the transaction not yet being valid (e.g. nonce
    /// too high).
    Future,
    /// General error to do with the transaction being outdated (e.g. nonce too
    /// low).
    Stale,
    /// General error to do with the transaction's proofs (e.g. signature).
    BadProof,
    /// The transaction birth block is ancient.
    AncientBirthBlock,
    /// The transaction would exhaust the resources of current block.
    ///
    /// The transaction might be valid, but there are not enough resources left
    /// in the current block.
    ExhaustsResources,
    /// Any other custom invalid validity that is not covered by this enum.
    Custom
  };

  template <class Stream,
            typename = std::enable_if_t<Stream::is_encoder_stream>>
  Stream &operator<<(Stream &s, const InvalidTransaction &v) {
    // -1 is needed for compatibility with Rust; indices of error codes start
    // from 0 there, while in kagome they must start from 1 because of
    // std::error_code policy
    return s << static_cast<uint8_t>(v) - 1;
  }

  template <class Stream,
            typename = std::enable_if_t<Stream::is_decoder_stream>>
  Stream &operator>>(Stream &s, InvalidTransaction &v) {
    uint8_t value = 0u;
    s >> value;

    // increment is needed for compatibility with Rust; indices of error codes
    // start from 0 there, while in kagome they must start from 1 because of
    // std::error_code policy
    value++;
    if (value > static_cast<uint8_t>(InvalidTransaction::ExhaustsResources)) {
      v = InvalidTransaction::Custom;
    } else {
      v = static_cast<InvalidTransaction>(value);
    }
    return s;
  }

  /// An unknown transaction validity.
  enum class UnknownTransaction : uint8_t {
    /// Could not lookup some information that is required to validate the
    /// transaction.
    CannotLookup = 1,
    /// No validator found for the given unsigned transaction.
    NoUnsignedValidator,
    /// Any other custom unknown validity that is not covered by this enum.
    Custom
  };

  template <class Stream,
            typename = std::enable_if_t<Stream::is_encoder_stream>>
  Stream &operator<<(Stream &s, const UnknownTransaction &v) {
    // -1 is needed for compatibility with Rust; indices of error codes start
    // from 0 there, while in kagome they must start from 1 because of
    // std::error_code policy
    return s << static_cast<uint8_t>(v) - 1;
  }

  template <class Stream,
            typename = std::enable_if_t<Stream::is_decoder_stream>>
  Stream &operator>>(Stream &s, UnknownTransaction &v) {
    uint8_t value = 0u;
    s >> value;

    // increment is needed for compatibility with Rust; indices of error codes
    // start from 0 there, while in kagome they must start from 1 because of
    // std::error_code policy
    value++;
    if (value > static_cast<uint8_t>(UnknownTransaction::NoUnsignedValidator)) {
      v = UnknownTransaction::Custom;
    } else {
      v = static_cast<UnknownTransaction>(value);
    }
    return s;
  }

  using TransactionValidityError =
      boost::variant<InvalidTransaction, UnknownTransaction>;

  /**
   * Information on a transaction's validity and, if valid, on how it relate to
   * other transactions.
   */
  using TransactionValidity =
      boost::variant<ValidTransaction, TransactionValidityError>;

  /**
   * @brief outputs object of type Valid to stream
   * @tparam Stream stream type
   * @param s stream reference
   * @param v value to output
   * @return reference to stream
   */
  template <class Stream,
            typename = std::enable_if_t<Stream::is_encoder_stream>>
  Stream &operator<<(Stream &s, const ValidTransaction &v) {
    return s << v.priority << v.requires << v.provides << v.longevity
             << v.propagate;
  }
  /**
   * @brief decodes object of type Valid from stream
   * @tparam Stream input stream type
   * @param s stream reference
   * @param v value to decode
   * @return reference to stream
   */
  template <class Stream,
            typename = std::enable_if_t<Stream::is_decoder_stream>>
  Stream &operator>>(Stream &s, ValidTransaction &v) {
    return s >> v.priority >> v.requires >> v.provides >> v.longevity
           >> v.propagate;
  }
}  // namespace kagome::primitives

OUTCOME_HPP_DECLARE_ERROR(kagome::primitives, InvalidTransaction)
OUTCOME_HPP_DECLARE_ERROR(kagome::primitives, UnknownTransaction)

#endif  // KAGOME_CORE_PRIMITIVES_TRANSACTION_VALIDITY_HPP

max_stars_repo_name: FlorianFranzen/kagome

max_issues_repo_name: FlorianFranzen/kagome

max_forks_repo_name: FlorianFranzen/kagome


text:
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_CORE_DETAIL_STREAM_BASE_HPP
#define BOOST_BEAST_CORE_DETAIL_STREAM_BASE_HPP

#include <boost/asio/steady_timer.hpp>
#include <boost/assert.hpp>
#include <boost/core/exchange.hpp>
#include <chrono>
#include <cstdint>
#include <utility>

namespace boost {
namespace beast {
namespace detail {

struct any_endpoint
{
    template<class Error, class Endpoint>
    bool
    operator()(
        Error const&, Endpoint const&) const noexcept
    {
        return true;
    }
};

struct stream_base
{
    using clock_type = std::chrono::steady_clock;
    using time_point = typename
        std::chrono::steady_clock::time_point;
    using tick_type = std::uint64_t;

    struct op_state
    {
        net::steady_timer timer;    // for timing out
        tick_type tick = 0;         // counts waits
        bool pending = false;       // if op is pending
        bool timeout = false;       // if timed out

        template<class... Args>
        explicit
        op_state(Args&&... args)
            : timer(std::forward<Args>(args)...)
        {
        }
    };

    class pending_guard
    {
        bool& b_;
        bool clear_ = true;

    public:
        ~pending_guard()
        {
            if(clear_)
                b_ = false;
        }

        explicit
        pending_guard(bool& b)
            : b_(b)
        {
            BOOST_ASSERT(! b_);
            b_ = true;
        }

        pending_guard(
            pending_guard&& other) noexcept
            : b_(other.b_)
            , clear_(boost::exchange(
                other.clear_, false))
        {
        }

        void
        reset()
        {
            BOOST_ASSERT(clear_);
            b_ = false;
            clear_ = false;
        }
    };

    static time_point never() noexcept
    {
        return (time_point::max)();
    }

    static std::size_t constexpr no_limit =
        (std::numeric_limits<std::size_t>::max)();
};

} // detail
} // beast
} // boost

#endif

max_stars_repo_name: Netis/packet-agent

max_issues_repo_name: Netis/packet-agent

max_forks_repo_name: Netis/packet-agent


text:
// This is an advanced implementation of the algorithm described in the
// following paper:
//    C. Hertzberg,  R.  Wagner,  U.  Frese,  and  L.  Schroder.  Integratinggeneric   sensor   fusion   algorithms with
//    sound   state   representationsthrough  encapsulation  of  manifolds. CoRR,  vol.  abs/1107.1119,  2011.[Online].
//    Available: http://arxiv.org/abs/1107.1119

/*
 *  Copyright (c) 2019--2023, The University of Hong Kong
 *  All rights reserved.
 *
 *  Modifier: Dongjiao HE <hdj65822@connect.hku.hk>
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Universitaet Bremen nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

/*
 *  Copyright (c) 2008--2011, Universitaet Bremen
 *  All rights reserved.
 *
 *  Author: Christoph Hertzberg <chtz@informatik.uni-bremen.de>
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the Universitaet Bremen nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * @file mtk/src/mtkmath.hpp
 * @brief several math utility functions.
 */

#ifndef MTKMATH_H_
#define MTKMATH_H_

#include <cmath>

#include <boost/math/tools/precision.hpp>

#include "../types/vect.hpp"

#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif

namespace MTK {

namespace internal {

template <class Manifold>
struct traits {
    typedef typename Manifold::scalar scalar;
    enum { DOF = Manifold::DOF };
    typedef vect<DOF, scalar> vectorized_type;
    typedef Eigen::Matrix<scalar, DOF, DOF> matrix_type;
};

template <>
struct traits<float> : traits<Scalar<float> > {};
template <>
struct traits<double> : traits<Scalar<double> > {};

}  // namespace internal

/**
 * \defgroup MTKMath Mathematical helper functions
 */
//@{

//! constant @f$ \pi @f$
const double pi = M_PI;

template <class scalar>
inline scalar tolerance();

template <>
inline float tolerance<float>() {
    return 1e-5f;
}
template <>
inline double tolerance<double>() {
    return 1e-11;
}

/**
 * normalize @a x to @f$[-bound, bound] @f$.
 *
 * result for @f$ x = bound + 2\cdot n\cdot bound @f$ is arbitrary @f$\pm bound @f$.
 */
template <class scalar>
inline scalar normalize(scalar x, scalar bound) {  // not used
    if (std::fabs(x) <= bound) return x;
    int r = (int)(x * (scalar(1.0) / bound));
    return x - ((r + (r >> 31) + 1) & ~1) * bound;
}

/**
 * Calculate cosine and sinc of sqrt(x2).
 * @param x2 the squared angle must be non-negative
 * @return a pair containing cos and sinc of sqrt(x2)
 */
template <class scalar>
std::pair<scalar, scalar> cos_sinc_sqrt(const scalar& x2) {
    using std::cos;
    using std::sin;
    using std::sqrt;
    static scalar const taylor_0_bound = boost::math::tools::epsilon<scalar>();
    static scalar const taylor_2_bound = sqrt(taylor_0_bound);
    static scalar const taylor_n_bound = sqrt(taylor_2_bound);

    assert(x2 >= 0 && "argument must be non-negative");

    // FIXME check if bigger bounds are possible
    if (x2 >= taylor_n_bound) {
        // slow fall-back solution
        scalar x = sqrt(x2);
        return std::make_pair(cos(x), sin(x) / x);  // x is greater than 0.
    }

    // FIXME Replace by Horner-Scheme (4 instead of 5 FLOP/term, numerically more stable, theoretically cos and sinc can
    // be calculated in parallel using SSE2 mulpd/addpd)
    // TODO Find optimal coefficients using Remez algorithm
    static scalar const inv[] = {1 / 3., 1 / 4., 1 / 5., 1 / 6., 1 / 7., 1 / 8., 1 / 9.};
    scalar cosi = 1., sinc = 1;
    scalar term = -1 / 2. * x2;
    for (int i = 0; i < 3; ++i) {
        cosi += term;
        term *= inv[2 * i];
        sinc += term;
        term *= -inv[2 * i + 1] * x2;
    }

    return std::make_pair(cosi, sinc);
}

template <typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> hat(const Base& v) {
    Eigen::Matrix<typename Base::scalar, 3, 3> res;
    res << 0, -v[2], v[1], v[2], 0, -v[0], -v[1], v[0], 0;
    return res;
}

template <typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> A_inv_trans(const Base& v) {
    Eigen::Matrix<typename Base::scalar, 3, 3> res;
    if (v.norm() > MTK::tolerance<typename Base::scalar>()) {
        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() + 0.5 * hat<Base>(v) +
              (1 - v.norm() * std::cos(v.norm() / 2) / 2 / std::sin(v.norm() / 2)) * hat(v) * hat(v) / v.squaredNorm();

    } else {
        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();
    }

    return res;
}

template <typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> A_inv(const Base& v) {
    Eigen::Matrix<typename Base::scalar, 3, 3> res;
    if (v.norm() > MTK::tolerance<typename Base::scalar>()) {
        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() - 0.5 * hat<Base>(v) +
              (1 - v.norm() * std::cos(v.norm() / 2) / 2 / std::sin(v.norm() / 2)) * hat(v) * hat(v) / v.squaredNorm();

    } else {
        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();
    }

    return res;
}

template <typename scalar>
Eigen::Matrix<scalar, 2, 3> S2_w_expw_(Eigen::Matrix<scalar, 2, 1> v, scalar length) {
    Eigen::Matrix<scalar, 2, 3> res;
    scalar norm = std::sqrt(v[0] * v[0] + v[1] * v[1]);
    if (norm < MTK::tolerance<scalar>()) {
        res = Eigen::Matrix<scalar, 2, 3>::Zero();
        res(0, 1) = 1;
        res(1, 2) = 1;
        res /= length;
    } else {
        res << -v[0] * (1 / norm - 1 / std::tan(norm)) / std::sin(norm), norm / std::sin(norm), 0,
            -v[1] * (1 / norm - 1 / std::tan(norm)) / std::sin(norm), 0, norm / std::sin(norm);
        res /= length;
    }
}

template <typename Base>
Eigen::Matrix<typename Base::scalar, 3, 3> A_matrix(const Base& v) {
    Eigen::Matrix<typename Base::scalar, 3, 3> res;
    double squaredNorm = v[0] * v[0] + v[1] * v[1] + v[2] * v[2];
    double norm = std::sqrt(squaredNorm);
    if (norm < MTK::tolerance<typename Base::scalar>()) {
        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity();
    } else {
        res = Eigen::Matrix<typename Base::scalar, 3, 3>::Identity() + (1 - std::cos(norm)) / squaredNorm * hat(v) +
              (1 - std::sin(norm) / norm) / squaredNorm * hat(v) * hat(v);
    }
    return res;
}

template <class scalar, int n>
scalar exp(vectview<scalar, n> result, vectview<const scalar, n> vec, const scalar& scale = 1) {
    scalar norm2 = vec.squaredNorm();
    std::pair<scalar, scalar> cos_sinc = cos_sinc_sqrt(scale * scale * norm2);
    scalar mult = cos_sinc.second * scale;
    result = mult * vec;
    return cos_sinc.first;
}

/**
 * Inverse function to @c exp.
 *
 * @param result @c vectview to the result
 * @param w      scalar part of input
 * @param vec    vector part of input
 * @param scale  scale result by this value
 * @param plus_minus_periodicity if true values @f$[w, vec]@f$ and @f$[-w, -vec]@f$ give the same result
 */
template <class scalar, int n>
void log(vectview<scalar, n> result, const scalar& w, const vectview<const scalar, n> vec, const scalar& scale,
         bool plus_minus_periodicity) {
    // FIXME implement optimized case for vec.squaredNorm() <= tolerance() * (w*w) via Rational Remez approximation ~>
    // only one division
    scalar nv = vec.norm();
    if (nv < tolerance<scalar>()) {
        if (!plus_minus_periodicity && w < 0) {
            // find the maximal entry:
            int i;
            nv = vec.cwiseAbs().maxCoeff(&i);
            result = scale * std::atan2(nv, w) * vect<n, scalar>::Unit(i);
            return;
        }
        nv = tolerance<scalar>();
    }
    scalar s = scale / nv * (plus_minus_periodicity ? std::atan(nv / w) : std::atan2(nv, w));

    result = s * vec;
}

}  // namespace MTK

#endif /* MTKMATH_H_ */

max_stars_repo_name: xiaotaw/faster-lio

max_issues_repo_name: xiaotaw/faster-lio

max_forks_repo_name: xiaotaw/faster-lio