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

#include "Facade.h"
#include "GraphSerializer.h"
#include "depend/ClassMetric.h"
#include "depend/ClassLoader.h"
#include "depend/UnitDependencyLoader.h"
#include "depend/EdgeSerializer.h"
#include "depend/MetricSerializer.h"
#include "depend/UnitMetrics.h"
#include "depend/UnitSerializer.h"
#include "depend/ExternalSerializer.h"
#include "depend/StronglyConnectedComponents.h"
#include "depend/StronglyConnectedComponentsSerializer.h"
#include "depend/UnitCache.h"
#include "depend/DotSerializer.h"
#include "depend/Filter.h"
#include "depend/TransitiveReductionFilter.h"
#include <boost/foreach.hpp>
#include <boost/bind.hpp>
#include <xeumeuleu/xml.hpp>
#include <boost/lexical_cast.hpp>
#include <set>

using namespace depend;

// -----------------------------------------------------------------------------
// Name: Facade constructor
// Created: SLI 2010-08-18
// -----------------------------------------------------------------------------
Facade::Facade( xml::xisubstream xis )
    : option_          ( ( xis >> xml::start( "configuration" ) ).content< std::string >( "dependencies" ) )
    , extend_          ( xis.content< bool >( "extend" ) )
    , filter_          ( new Filter( xis ) )
    , classLoader_     ( new ClassLoader() )
    , unitCache_       ( new UnitCache( *classLoader_ ) )
    , classMetric_     ( new ClassMetric( *classLoader_, *classLoader_ ) )
    , dependencyMetric_( new UnitDependencyLoader( xml::xifstream( xis.content< std::string >( "input" ) ) ) )
    , unitSerializer_  ( new UnitSerializer( *classLoader_ ) )
    , graphSerializer_ ( new GraphSerializer( xis ) )
{
    classLoader_->Subject< UnitObserver_ABC >::Register( *this );
    classLoader_->Process( xml::xifstream( xis.content< std::string >( "input" ) ) );
}

// -----------------------------------------------------------------------------
// Name: Facade destructor
// Created: SLI 2010-08-18
// -----------------------------------------------------------------------------
Facade::~Facade()
{
    classLoader_->Subject< UnitObserver_ABC >::Unregister( *this );
}

// -----------------------------------------------------------------------------
// Name: Facade::Process
// Created: SLI 2010-09-10
// -----------------------------------------------------------------------------
void Facade::Process( xml::xisubstream xis )
{
    std::string output;
    xis >> xml::start( "configuration" )
            >> xml::content( "output", output );
    if( xis.content< bool >( "all" ) )
        SerializeAll( output );
    else
        Serialize( output );
}

namespace
{
    class FilterExtender : public Filter_ABC, private DependencyVisitor_ABC
    {
    public:
        FilterExtender( const Visitable< DependencyVisitor_ABC >& metric, const Filter_ABC& filter )
            : filter_( filter )
        {
            metric.Apply( *this );
        }
        virtual bool Check( const std::string& module ) const
        {
            return CheckCore( module ) || extended_.find( module ) != extended_.end();
        }
        virtual bool CheckCore( const std::string& module ) const
        {
            return filter_.Check( module );
        }
    private:
        virtual void NotifyInternalDependency( const std::string& fromModule, const std::string& toModule, const std::string& /*context*/ )
        {
            if( filter_.Check( fromModule ) )
                extended_.insert( toModule );
            else if( filter_.Check( toModule ) )
                extended_.insert( fromModule );
        }
        virtual void NotifyExternalDependency( const std::string& /*fromModule*/, const std::string& /*toModule*/, const std::string& /*context*/ )
        {
            // NOTHING
        }
        const Filter_ABC& filter_;
        std::set< std::string > extended_;
    };
}

// -----------------------------------------------------------------------------
// Name: Facade::Serialize
// Created: SLI 2010-08-20
// -----------------------------------------------------------------------------
void Facade::Serialize( xml::xostream& xos )
{
    xos << xml::start( "report" );
    TransitiveReductionFilter transitive( *dependencyMetric_, *filter_ );
    FilterExtender extension( *dependencyMetric_, *filter_ );
    Filter_ABC& filter = extend_ ? static_cast< Filter_ABC& >( transitive ) : static_cast< Filter_ABC& >( extension );
    unitSerializer_->Serialize( xos, filter );
    ExternalSerializer( *dependencyMetric_, filter ).Serialize( xos );
    xos << xml::start( "graph" );
    EdgeSerializer( *dependencyMetric_, *unitCache_ ).Serialize( xos, filter );
    xos << xml::end;
    const UnitMetrics metrics( *unitCache_, *dependencyMetric_, *classMetric_ );
    MetricSerializer( metrics ).Serialize( xos, filter );
    StronglyConnectedComponents components( *dependencyMetric_, filter );
    StronglyConnectedComponentsSerializer( components ).Serialize( xos );
    xos << xml::end;
}

// -----------------------------------------------------------------------------
// Name: Facade::Serialize
// Created: SLI 2010-08-27
// -----------------------------------------------------------------------------
void Facade::Serialize( std::ostream& os )
{
    xml::xobufferstream xos;
    Serialize( static_cast< xml::xostream& >( xos ) );
    DotSerializer().Serialize( xos, os, boost::lexical_cast< DotOption >( option_ ) );
}

// -----------------------------------------------------------------------------
// Name: Facade::SerializeGraph
// Created: SLI 2010-08-27
// -----------------------------------------------------------------------------
void Facade::Serialize( const std::string& filename )
{
    std::ostringstream buffer;
    Serialize( buffer );
    graphSerializer_->Serialize( buffer.str(), filename );
}

namespace
{
    class SimpleFilter : public Filter_ABC
    {
    public:
        explicit SimpleFilter( const std::string& module )
            : module_( module )
        {}
        virtual bool Check( const std::string& module ) const
        {
            return module == module_;
        }
        virtual bool CheckCore( const std::string& module ) const
        {
            return module == module_;
        }
    private:
        const std::string module_;
    };
}

// -----------------------------------------------------------------------------
// Name: Facade::SerializeAll
// Created: SLI 2010-08-31
// -----------------------------------------------------------------------------
void Facade::SerializeAll( const std::string& filename )
{
    const std::string extension = filename.substr( filename.find_last_of( '.' ) + 1, std::string::npos );
    const std::string path = filename.substr( 0, filename.find_last_of( '.' ) );
    BOOST_FOREACH( const std::string& module, modules_ )
    {
        filter_.reset( new SimpleFilter( module ) ); // $$$$ _RC_ SLI 2010-09-06: not that great
        Serialize( path + "_" + module + "." + extension );
    }
}

// -----------------------------------------------------------------------------
// Name: Facade::NotifyUnit
// Created: SLI 2011-04-08
// -----------------------------------------------------------------------------
void Facade::NotifyUnit( const std::string& unit, const std::string& /*context*/ )
{
    modules_.push_back( unit );
}

max_stars_repo_name: vinsle/dependency-analysis

max_issues_repo_name: vinsle/dependency-analysis

max_forks_repo_name: vinsle/dependency-analysis


text:
//
// Created by joe on 24/01/16.
//

#include "xDisplay.h"

#include <X11/Xatom.h>

#include <boost/date_time/posix_time/posix_time.hpp>

using namespace osmMapper;
using namespace Cairo;
using namespace boost::interprocess;
using namespace boost::posix_time;
using namespace std;

xDisplay::xDisplay(int &x, int &y) : display(x, y), m_dsp(nullptr), m_da(), m_scr(nullptr), m_vis(nullptr), m_mq
        (nullptr), m_eventThread(), m_stopping(false) {
    createX11CairoSurface(&x, &y);
    m_width=x;
    m_height=y;
    cout << "X Display: " << m_width << "x" << m_height << endl;
    try {
        message_queue::remove("eventsQueue"); // Just in case
        //Create a message_queue.
        m_mq=make_shared<message_queue>(open_or_create, "eventsQueue", 100, sizeof(event));
    }
    catch (interprocess_exception &ex) {
        cout << "Fatal: couldn't construct with message queue" << endl;
        cout << ex.what() << endl;
        abort();
    }
    m_eventThread=std::thread(&xDisplay::pollEvents, this);
}

xDisplay::~xDisplay() {
    m_stopping=true;
    m_eventThread.join();
    message_queue::remove("eventsQueue"); // This can fail
    XCloseDisplay(m_dsp);
}

void xDisplay::pollEvents(void) {
    char keybuf[8];
    KeySym key;
    XEvent e;
    event newEvent {event::NONE, 0};
    int priority=0;

    XNextEvent(m_dsp, &e);
    while (!m_stopping) {
        switch (e.type) {
            case KeyPress:
                cout << "Got key press!" << endl;
                XLookupString(&e.xkey, keybuf, sizeof(keybuf), &key, NULL);
                newEvent.type=event::KEY;
                newEvent.value=key;
                m_mq->send(&newEvent, sizeof(newEvent), priority);
                break;
            case ButtonPress:
                cout << "Got button press!" << endl;
                newEvent.type=event::BUTTON;
                newEvent.value=0;
                m_mq->send(&newEvent, sizeof(newEvent), priority);
                break;
            default:
                fprintf(stderr, "Dropping unhandled XEvent.type = %d.\n", e.type);
                m_mq->send(&newEvent, sizeof(newEvent), priority);
                break;
        }
        XNextEvent(m_dsp, &e);
    }
}

event xDisplay::getEvent(const int timeoutInMs) {
    event newEvent {event::NONE, 0};
    unsigned int priority=0;
    unsigned long receivedBytes;

    if (timeoutInMs == 0) {
        m_mq->receive(&newEvent, sizeof(newEvent), receivedBytes, priority);
        if (sizeof(newEvent) != receivedBytes)
            newEvent.type=event::NONE;
    }
    else {
        ptime timeoutTime=microsec_clock::universal_time() + milliseconds(timeoutInMs);
        m_mq->timed_receive(&newEvent, sizeof(newEvent), receivedBytes, priority, timeoutTime);
        if (sizeof(newEvent) != receivedBytes)
            newEvent.type=event::NONE;
    }
    return newEvent;
}

void xDisplay::fullscreen(Display *dpy, Window win) {
    Atom atoms[2]={XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", False), None};
    XChangeProperty(dpy, win, XInternAtom(dpy, "_NET_WM_STATE", False),
                    XA_ATOM, 32, PropModeReplace, (unsigned char *) atoms, 1);
}

/*! Open an X11 window and create a cairo surface base on that window. If x and
 * y are set to 0 the function opens a full screen window and stores to window
 * dimensions to x and y.
 * @param x Pointer to width of window.
 * @param y Pointer to height of window.
 * @return Returns a pointer to a valid Xlib cairo surface. The function does
 * not return on error (exit(3)).
 */
void xDisplay::createX11CairoSurface(int *x, int *y) {
    int screen;

    XInitThreads();
    if ((m_dsp=XOpenDisplay(NULL)) == NULL)
        exit(1);
    screen=DefaultScreen(m_dsp);
    m_scr=DefaultScreenOfDisplay(m_dsp);
    m_vis=DefaultVisual(m_dsp, screen);
    if (!*x || !*y) {
        *x=WidthOfScreen(m_scr), *y=HeightOfScreen(m_scr);
        m_da=XCreateSimpleWindow(m_dsp, DefaultRootWindow(m_dsp), 0, 0, *x, *y, 0, 0, 0);
        fullscreen(m_dsp, m_da);
    }
    else
        m_da=XCreateSimpleWindow(m_dsp, DefaultRootWindow(m_dsp), 0, 0, *x, *y, 0, 0, 0);
    XSelectInput(m_dsp, m_da, ButtonPressMask | KeyPressMask);
    XMapWindow(m_dsp, m_da);
    m_surface=XlibSurface::create(m_dsp, m_da, m_vis, *x, *y);
    m_context=Context::create(m_surface);
}

void xDisplay::fullSize(bool full) {
}

int xDisplay::width(void) const {
    return m_width;
}

int xDisplay::height(void) const {
    return m_height;
}

void xDisplay::startDrawing(void) {
    m_context->set_antialias(ANTIALIAS_GRAY);
    m_context->push_group();
    m_context->set_source_rgb(m_background.r, m_background.g, m_background.b);
    m_context->paint();
}

void xDisplay::finishDrawing(void) {
    m_context->pop_group_to_source();
    m_context->paint();
    m_surface->flush();
    XSync(m_dsp, false); // Yuk. I think m_surface->flush is supposed to do this but I found this needed...
}

void xDisplay::startPath(const screenPoint &startPos, const colour_t &colour, const double thickness, bool filled) {
    m_context->set_line_width(thickness);
    m_context->set_source_rgb(colour.r, colour.g, colour.b);
    m_context->set_line_cap(LINE_CAP_ROUND);
    m_context->set_line_join(LINE_JOIN_ROUND);
    m_context->move_to(startPos.x(), startPos.y());
}

void xDisplay::endPath(void) {
    m_context->stroke();
}

void xDisplay::drawLine(const screenPoint &from, const screenPoint &to) {
#ifdef OSM_DEBUG
    cout << "From " << from.x() << "x" << from.y() << endl;
    cout << "To " << to.x() << "x" << to.y() << endl;
#endif

    if (to == from)
        return;

    // Draw it
    m_context->move_to(from.x(), from.y());
    m_context->line_to(to.x(), to.y());
}

ext: cpp

max_stars_repo_name: JRutledg/osmRR

max_issues_repo_name: JRutledg/osmRR

max_forks_repo_name: JRutledg/osmRR


text:
//          Copyright Rein Halbersma 2010-2020.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <dctl/core/rules/russian.hpp>       // russian
#include <dctl/core/rules/type_traits.hpp>         // is_backward_pawn_jump, is_long_ranged_king, jumpsep, is_passing_promotion, is_trivial_precedence
#include <boost/test/unit_test.hpp>     // BOOST_AUTO_TEST_SUITE, BOOST_AUTO_TEST_CASE, BOOST_AUTO_TEST_SUITE_END

using namespace dctl::core;

BOOST_AUTO_TEST_SUITE(RulesRussian)

using T = russian;

BOOST_AUTO_TEST_CASE(RuleTraits)
{
        static_assert(is_backward_pawn_jump_v<T>);
        static_assert(is_long_ranged_king_v<T>);

        static_assert(jumpsep_v<T> == ':');
        static_assert(is_passing_promotion_v<T>);

        static_assert(is_trivial_precedence_v<T>);
}

BOOST_AUTO_TEST_SUITE_END()


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

/**
 * @brief Boost.Spirit based BibTeX parser.
 * @file bibtexreader.hpp
 * @author Sergiu Deitsch
 * @version 0.1
 */

#ifndef BIBTEXREADER_HPP
#define BIBTEXREADER_HPP

#pragma once

#include <istream>
#include <string>

#include <boost/fusion/include/vector.hpp>
#include <boost/io/ios_state.hpp>
#include <boost/mpl/and.hpp>
#include <boost/range.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/utility/enable_if.hpp>

#include "bibtexentry.hpp"

namespace bibtex {

/**
 * @brief Single BibTeX entry reader.
 *
 * @tparam ForwardIterator Input sequence iterator type.
 * @tparam Skipper Skipper type.
 */
template <class ForwardIterator, class Skipper>
class BibTeXReader
    : public boost::spirit::qi::grammar<ForwardIterator, BibTeXEntry(), Skipper>
{
public:
    BibTeXReader()
        : BibTeXReader::base_type(start_, "single BibTeX entry")
    {
        using namespace boost::spirit;
        namespace ph = boost::phoenix;
        namespace sn = detail::encoding;

        escapedBrace.add
            ("\\{", '{')
            ("\\}", '}')
            ;
        escapedQuote.add
            ("\\\"", '"')
            ;

        tag_ = +detail::encoding::alnum;
        entryKey_ = qi::lexeme[+(~qi::char_(',') - sn::space)];
        key_ = qi::lexeme[+(~qi::char_("=,})") - sn::space)];

        escapedText_
            = !qi::lit('{') >> +(escapedBrace | ~qi::char_("{}"))
            ;

        quoteText_
            = +(escapedQuote | ~qi::char_("\"{}"))
            ;

        innerBraceText_
            %=
            qi::as_string
            [
                qi::char_('{')
                >>
                    *(innerBraceText_ | escapedText_)
                >>
                qi::char_('}')
            ]
            |
            escapedText_
            ;

        innerQuoteText_
            %=
            qi::as_string
            [
                qi::char_('{')
                >>
                    *(innerQuoteText_ | escapedText_)
                >>
                qi::char_('}')
            ]
            |
            quoteText_
            ;

        quoted_
            = qi::lexeme
            [
                ( '"' >> *innerQuoteText_ >> '"' )
                |
                ( '{' >> *innerBraceText_ >> '}' )
            ]
            [
                _val = ph::accumulate(_1, ph::construct<std::string>())
            ]
            ;

        value_
            = quoted_
            | +~qi::char_(",})#")
            ;

        values_
            = value_ % '#'
            ;

        field_
            = key_ >> '=' >> values_
            ;

        fields_ = -(field_ % ',');

        body_
            = -entryKey_ >> ',' // tolerate an empty key
            >> fields_
            >> -qi::lit(',') // accept a trailing comma
            ;

        generic_
            =
            '@' >> tag_
            [
                ph::at_c<0>(_val) = _1
            ]
            >>
            (
                ('{' >> body_ >> '}')
                |
                ('(' >> body_ >> ')')
            )
            [
                ph::at_c<1>(_val) = ph::at_c<0>(_1),
                ph::at_c<2>(_val) = ph::at_c<1>(_1)
            ]
            ;

        string_
            =
            '@' >> sn::no_case
            [
                qi::string("string")
                [
                    ph::at_c<0>(_val) = _1
                ]
            ]
            >>
            (
                ('{' >> field_ >> '}')
                |
                ('(' >> field_ >> ')')
            )
            [
                ph::assign(ph::bind(&BibTeXEntry::fields, _val), 1, _1)
            ]
            ;

        simple_
            =
            '@' >> sn::no_case
            [
                (
                    sn::string("comment")
                    |
                    sn::string("include")
                    |
                    sn::string("preamble")
                )
                [
                    ph::at_c<0>(_val) = _1
                ]
            ]
            >>
            (
                ('{' >> values_ >> '}')
                |
                ('(' >> values_ >> ')')
            )
            [
                ph::assign(ph::bind(&BibTeXEntry::fields, _val), 1,
                    ph::construct<KeyValue>
                        (ph::construct<KeyValue::first_type>(), _1))
            ]
            ;

        entry_
            = string_
            | simple_
            | generic_
            ;

        junk_
            = *~qi::lit('@')
            ;

        start_
            = junk_ >> entry_
            ;
    }

private:
    typedef boost::spirit::qi::rule<ForwardIterator, std::string(), Skipper>
        StringRule;
    typedef boost::spirit::qi::rule<ForwardIterator, std::string()>
        SimpleStringRule;

    boost::spirit::qi::rule<ForwardIterator, BibTeXEntry(), Skipper> generic_;
    boost::spirit::qi::rule<ForwardIterator, BibTeXEntry(), Skipper> include_;
    boost::spirit::qi::rule<ForwardIterator, BibTeXEntry(), Skipper> simple_;
    boost::spirit::qi::rule<ForwardIterator, BibTeXEntry(), Skipper> start_;
    boost::spirit::qi::rule<ForwardIterator, BibTeXEntry(), Skipper> string_;
    boost::spirit::qi::rule<ForwardIterator, BibTeXEntry(), Skipper> entry_;
    boost::spirit::qi::rule<ForwardIterator, ValueVector(), Skipper> values_;
    boost::spirit::qi::rule<ForwardIterator, Skipper> junk_;
    boost::spirit::qi::rule<ForwardIterator,
        boost::fusion::vector<boost::optional<std::string>,
        KeyValueVector>(), Skipper> body_;
    boost::spirit::qi::rule<ForwardIterator, KeyValue(), Skipper> field_;
    boost::spirit::qi::rule<ForwardIterator, KeyValueVector(), Skipper>
        fields_;
    boost::spirit::qi::symbols<char, char> escapedBrace;
    boost::spirit::qi::symbols<char, char> escapedQuote;
    StringRule quoted_;
    StringRule entryKey_;
    StringRule key_;
    StringRule tag_;
    StringRule value_;
    SimpleStringRule innerBraceText_;
    SimpleStringRule escapedText_;
    SimpleStringRule innerQuoteText_;
    SimpleStringRule quoteText_;
};

template<class ForwardIterator, class Skipper>
inline bool read(ForwardIterator first, ForwardIterator last, Skipper& skipper,
                  BibTeXEntry& entry)
{
    BibTeXReader<ForwardIterator, Skipper> parser;
    return boost::spirit::qi::phrase_parse(first, last, parser, skipper, entry);
}

template<class ForwardIterator, class Skipper, class Container>
inline bool read(ForwardIterator first, ForwardIterator last, Skipper& skipper,
    Container& entries, boost::enable_if<boost::is_same<
        typename Container::value_type, BibTeXEntry> >* /*dummy*/ = NULL)
{
    BibTeXReader<ForwardIterator, Skipper> parser;
    return boost::spirit::qi::phrase_parse(first, last, *parser, skipper,
        entries);
}

template<class ForwardRange, class Skipper>
inline bool read(const ForwardRange& range, Skipper& /*skipper*/,
                 BibTeXEntry& entry)
{
    return read(boost::const_begin(range), boost::const_end(range), entry);
}

template<class ForwardRange, class Skipper, class Container>
inline bool read(
    const ForwardRange& range, Skipper& /*skipper*/, Container& entries,
    boost::enable_if<
        boost::is_same<typename Container::value_type, BibTeXEntry> >* /*dummy*/
    = NULL)
{
    return read(boost::const_begin(range), boost::const_end(range), entries);
}

template<class ForwardIterator>
inline bool read(ForwardIterator first, ForwardIterator last,
                 BibTeXEntry& entry)
{
    return read(first, last, bibtex::space, entry);
}

template<class ForwardIterator, class Container>
inline bool read(ForwardIterator first, ForwardIterator last,
    Container& entries, boost::enable_if<boost::is_same<
        typename Container::value_type, BibTeXEntry> >* /*dummy*/ = NULL)
{
    return read(first, last, bibtex::space, entries);
}

template<class ForwardRange>
inline bool read(const ForwardRange& range, BibTeXEntry& entry,
    typename boost::enable_if<
        boost::has_range_iterator<ForwardRange> >::type* /*dummy*/ = NULL)
{
    return read(range, bibtex::space, entry);
}

template<class ForwardRange, class Container>
inline bool read(const ForwardRange& range, Container& entries,
    typename boost::enable_if<
        boost::has_range_iterator<ForwardRange> >::type* /*dummy*/ = NULL)
{
    return read(range, bibtex::space, entries);
}

template<class E, class T>
inline bool read(std::basic_istream<E, T>& in, BibTeXEntry& e)
{
    boost::io::ios_flags_saver saver(in);
    in.unsetf(std::ios_base::skipws);

    typedef boost::spirit::basic_istream_iterator<E> istream_iterator;
    return read(istream_iterator(in), istream_iterator(), e);
}

template<class E, class T, class Container>
inline bool read(std::basic_istream<E, T>& in, Container& entries)
{
    boost::io::ios_flags_saver saver(in);
    in.unsetf(std::ios_base::skipws);

    typedef boost::spirit::basic_istream_iterator<E> istream_iterator;
    return read(istream_iterator(in), istream_iterator(), entries);
}

template<class E, class T>
inline std::basic_istream<E, T>& operator>>(std::basic_istream<E, T>& in,
    BibTeXEntry& entry)
{
    read(in, entry);
    return in;
}

template<class E, class T, class Range>
inline typename boost::enable_if<
    boost::mpl::and_<
        boost::has_range_iterator<Range>,
        boost::is_same<typename Range::value_type, BibTeXEntry>
    >, std::basic_istream<E, T>
>::type& operator>>(std::basic_istream<E, T>& in, Range& entries)
{
    read(in, entries);
    return in;
}

} // namespace bibtex

#endif // BIBTEXREADER_HPP

ext: hpp

max_stars_repo_name: sergiud/bibtex-spirit

max_issues_repo_name: sergiud/bibtex-spirit

max_forks_repo_name: sergiud/bibtex-spirit


text:
//---------------------------------------------------------------------------//
//!
//! \file   tstAtomicMassUnit.cpp
//! \author Alex Robinson
//! \brief  The atomic mass unit unit tests
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <iostream>

// Boost Includes
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/cgs/mass.hpp>
#include <boost/units/systems/si/mass.hpp>

// FRENSIE Includes
#include "Utility_AtomicMassUnit.hpp"

using namespace Utility::Units;
namespace si = boost::units::si;
namespace cgs = boost::units::cgs;

//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
// Check that the atomic mass unit can be initialized
BOOST_AUTO_TEST_CASE( initialize )
{
  boost::units::quantity<Utility::Units::AtomicMass> mass( 1.0*amu );

  BOOST_CHECK_EQUAL( mass.value(), 1.0 );

  mass = 2.0*amu;

  BOOST_CHECK_EQUAL( mass.value(), 2.0 );
}

//---------------------------------------------------------------------------//
// Check that the atomic mass unit can be initialized from cgs and si units
BOOST_AUTO_TEST_CASE( initialize_from_cgs_si )
{
  boost::units::quantity<Utility::Units::AtomicMass> mass_cgs( 1.0*cgs::gram );

  boost::units::quantity<Utility::Units::AtomicMass> mass_si( 1.0*si::kilogram );

  BOOST_CHECK_CLOSE_FRACTION( mass_cgs.value(),
                              6.0221408585491615e+23,
                              1e-15 );
  BOOST_CHECK_CLOSE_FRACTION( mass_si.value(),
                              6.0221408585491615e+26,
                              1e-15 );
}

//---------------------------------------------------------------------------//
// Check that the cgs and si units can be initialized from the atomic mass u.
BOOST_AUTO_TEST_CASE( initialize_cgs_si )
{
  boost::units::quantity<cgs::mass> cgs_mass( 1.0*amu );

  boost::units::quantity<si::mass> si_mass( 1.0*amu );

  BOOST_CHECK_CLOSE_FRACTION( cgs_mass.value(),
                              1.660539040e-24,
                              1e-15 );
  BOOST_CHECK_CLOSE_FRACTION( si_mass.value(),
                              1.660539040e-27,
                              1e-15 );
}

//---------------------------------------------------------------------------//
// end tstAtomicMassUnit.cpp
//---------------------------------------------------------------------------//


text:
#include "src/cservice.h"
#include <getopt.h>

#include <boost/multiprecision/cpp_dec_float.hpp>
#include "src/cdecimal128.h"

//多线程测试
void ja()
{
  double a = 0.0;
  for(uint64_t i = 0; i < 500000000; i ++) {
	  a += sin(i * 1.05);
  }
  cout << "ja:" << a << endl;
}
void bar(int x)
{
	double a = 0.0;
	for(uint64_t i = 0; i < 300000000; i ++) {
		a += cos(i * 1.05);
	}
	cout << "bar:" << x << " " << a << endl;
}

double sin_a(double a) {
	return sin(a);
}

// 函数调用
int64_t increment (const int64_t& x) {return x + 1;}

void PrepareLunarCalendarData()
{
	CFile file;
	std::string path = "D:\\MyProgram\\VCS\\trunk\\LunarCalendarData\\";
	char buf[11];
	std::string data;
	for(uint16_t i = 1901; i < 1902; i ++) {
		sprintf(buf, "T%dc.txt", i);
		file.Open(path + buf, CFile::ONLY_READ);
		file.ReadAll(data);
		cout << data.c_str() << endl;
		file.Close();
	}
}

void test()
{
	cout << strlen("Failed to open the file (%s) as '%s' mode. ") << endl;

//        const char FileOpenModes[4][4] = {"rb", "wb+", "rb+", "ab+"};
//        FILE* fp = fopen("./aa.txt", FileOpenModes[0]);
//        char buf[10];
//        fread(buf, 1, 10, fp);
//        fclose(fp);
//        cout << buf << endl;

//        fstream fs;
//        fs.open("./data.txt", ios::in);
//        char buf[20];
//        fs.read(buf, 10);
//        fs.close();
//        cout << fs.gcount() << endl;

	//写文件
//		CFile file;
//		file.Open("./aa.txt", CFile::ONLYWRITE);
//		file.Write(string("hgjghj[]"));
//		file.Close();

	// 读文件
//        CFile file;
//		string filedata;
//		file.Open("./aa.txt", CFile::ONLYREAD);
//		//file.ReadAll(filedata);
//		file.GetLine(filedata,100);
//		file.Close();
//		cout << filedata << ", " << filedata.size() << endl;

	/*VCString a(5);
	a = "abcdefgh";
	VCString b("14");
	a = b + "??";cout << a.GetString() << endl;
	a = "";
	a += "6d;;sgfd[fl";
	string c = VCString(":abcd:");
	a += c;
	cout << a.GetString() << endl;*/
	//cout << a[2344] << endl;

	//多线程测试
//        std::thread first (ja);     // spawn new thread that calls ja()
//        std::thread second (bar,0);  // spawn new thread that calls bar(0)

//        std::cout << "main, ja and bar now execute concurrently...\n";

//        // synchronize threads:
//        first.join();                // pauses until first finishes
//        second.join();               // pauses until second finishes

//        std::cout << "ja and bar completed.\n";

	//cout << (double)(CTime::Duration(ja)) * CTime::Ratio() << endl;

	/*auto t1 = CTime::Now();
	double a = 1.0;
	for (uint64_t i = 0; i < 10000000; i++)
		a = sin_a(a);
	auto t2 = CTime::Now();
	cout << a << endl;
	cout << (t2 - t1) * CTime::TimeRatio << endl;*/

	CTime::DateTime dt;
	dt.Year = 2100;
	dt.Month = 12;
	dt.Day = 31;
	CTime::DateTime time = CTime::LunarCalendar(CTime::MakeSolarTime(dt));
	cout << endl << CTime::ToString(time) << endl;
	cout << CTime::ToString(CTime::SolarCalendar((int64_t)CTime::CurrentTime() + CTime::GetLocalTimeDifference())) << endl;
	cout << CTime::GetLocalTimeDifference() << endl;
	CTime::DateTime lunardt;
	lunardt.Year = 2019;
	lunardt.Month = 6;
	lunardt.Day = 1;
	lunardt.Leap = 0;
	cout << CTime::ToString(CTime::SolarCalendar(CTime::MakeLunarTime(lunardt))) << endl;

	vector<string> exts(explode("jpg|png|gif", '|'));
	for (size_t i = 0; i < exts.size(); i++)
		cout << exts[i] << endl;
	vector<string> tags(explode("html, body; header; table", "; "));
	for (size_t i = 0; i < tags.size(); i++)
		cout << tags[i] << endl;
	set<std::string> exts2(explode_set("jpg|png|gif", '|'));
	for (auto it = exts2.begin(); it != exts2.end(); it++)
		cout << *it << endl;
	set<std::string> tags2(explode_set("html, menu; meta; div; p", "; "));
	for (auto it = tags2.begin(); it != tags2.end(); it++)
		cout << *it << endl;

	// 测试GetLine函数
	/*CFile file;
	string data;
	file.Open("aaaa.txt", CFile::ONLY_READ);
	file.ReadAll(data);
	cout << data.data() << endl;*/

	//PrepareLunarCalendarData();

	// 转码
	/*VCharset cs(VCharset::UTF8, VCharset::GBK);
	VCString source = "生成";
	VCString des;
	cs.Convert(source, des);
	cout << des.GetString() << endl;*/

	// sqlite
//		sqlite3 * pDB = NULL;
//		int nRes = sqlite3_open("./test.db", &pDB);
//		if (nRes != SQLITE_OK) {
//			cout << "Open database fail: " << sqlite3_errmsg(pDB);
//		}
//		else {
//			sqlite3_close(pDB);
//		}

	// 测试zlib
/*		int ret, flush;
	unsigned have;
	z_stream strm;
	unsigned char in[16384];
	unsigned char out[16384];
	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;
	ret = deflateInit(&strm, 9);*/

	// 测试数组交换数据
	/*VVector<double> x(5), y(10);
	x[0] = 1.1;
	y[0] = 2.2;
	x.Swap(y);
	cout << x[0] << " " << y[0] << endl;*/

	/*VCharset cs(VCharset::UTF8, VCharset::BIG5);
	string udata;
	wstring data;
	VCString path("D:\\MyProgram\\VCS\\trunk\\LunarCalendarData\\");
	for (uint16_t i = 1901; i < 1902; ++i) {
		VCString filename(11);
		sprintf((char*)filename.GetPointer(), "T%dc.txt", i);
		filename.SetLength(10);
		CFile file;
		file.Open(path + filename, CFile::ONLYREAD);
		file.ReadAll(udata);
		//cs.Convert(udata, data);
		data = VCodeConversion::utf8_to_wstring(udata);
		file.Close();
		cout << data.size() << endl;
	}*/

	cout << CRandom()(0, 100) << endl;
	cout << CRandom()(10, 'a', 'z') << endl;

	cout << endl;
	//cout << CFile::FileSize("./main.obj") << endl;
	//cout << CTime::ToString(CTime::SolarCalendar(CFileSystem::LastModifyTime("./main.obj") + CTime::GetLocalTimeDifference())) << endl;
	//cout << CFileSystem::RemoveFile("D:\\MyProgram\\Release\\VCS\\.qmake.stash") << endl;
	//cout << CFileSystem::CreateDirectories("D:\\tt\\tt2");
	//CFileSystem::Rename("D:\\MyProgram\\Release\\VCS\\aa.txt", "D:\\MyProgram\\Release\\VCS\\bb.txt");
	/*cout << endl;
	vector<string> files;
	CFileSystem::ReadDirectoryOnlyFile("D:\\MyProgram\\VCS\\trunk\\x64\\Release\\", files, false, "pdb|log");
	for (auto it = files.begin(); it != files.end(); it++) {
		cout << *it << endl;
	}
	cout << endl;
	vector<string> allfiles;
	CFileSystem::ReadDirectoryAllFiles("D:\\MyProgram\\VCS\\trunk\\", allfiles, false, "cpp");
	for (auto it = allfiles.begin(); it != allfiles.end(); it++) {
		cout << *it << endl;
	}
	cout << endl;
	vector<string> allfilesdirs;
	CFileSystem::ReadDirectoryAll("D:\\MyProgram\\VCS\\trunk\\x64\\Release\\", allfilesdirs, false);
	for (auto it = allfilesdirs.begin(); it != allfilesdirs.end(); it++) {
		cout << *it << endl;
	}*/
	//CFileSystem::CopyDirectory("D:\\MyProgram\\VCS\\trunk\\x64\\Release\\aaa", "D:\\MyProgram\\VCS\\trunk\\x64\\Release\\bbb");

	/*CString str = " \n1 2 3  ";
	CString str_2 = str.trim();
	cout << str_2 << ", length " << str_2.size() << endl;
	CString str_3 = str.ltrim();
	cout << str_3 << ", length " << str_3.size() << endl;
	CString str_4 = str_3.rtrim();
	cout << str_4 << ", length " << str_4.size() << endl;*/
	string str_5("\n\n a b  c \t");
	ltrim(str_5);
	rtrim(str_5);
	cout << str_5 << ", length" << str_5.size() << endl;
	string str_6("\t aa bb \n");
	trim(str_6);
	cout << str_6 << ", length" << str_6.size() << endl;
	string str_7("  \t\na1 b2 c3\n\r ");
	cout << trim_copy(str_7) << endl;

	cout << pad_left_copy("Alien", 10, "-=") << endl;
	cout << pad_right_copy("Alien", 6, "___") << endl;

	cout << sizeof(long long) << " " << sizeof(double) << " " << sizeof(long double) << " " << sizeof(__int128_t) << " " << sizeof(__uint128_t) << endl;
	// long double常量浮点数后面应当加上L，float后面加上F，不加为double
	long double ld_num = 1.99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999L;
	cout << sin(ld_num) << endl;
	/*uint1024_t myUnsignedInt1024 = 1024;
	uint512_t myUnsignedInt512 = 512;
	uint256_t myUnsignedInt256("5343643654645643439579347502302730823740174032875032874032847085");
	cout << myUnsignedInt1024 + myUnsignedInt512 << " " << myUnsignedInt256 << endl;
	cout << setprecision(numeric_limits<long double>::max_digits10) << numeric_limits<long double>::max_digits10 << ", " << numeric_limits<long double>::min() << ", " << numeric_limits<long double>::max() << endl;
	cout << sizeof(chrono::high_resolution_clock::rep) << " " << chrono::high_resolution_clock::period::num << " " << chrono::high_resolution_clock::period::den << endl;
	//dynamic_bitset aaaa(4096);
	__uint128_t testnum = 110156546734858ULL;
	testnum *= testnum;
	cout << num_to_string(testnum) << endl;
	__int128_t testnum_neg = -110156546734858LL;
	cout << num_to_string(testnum_neg) << endl;
	number<cpp_dec_float<200> > high_prec_num("435804385043495727493284793274932857439569479238759465942750284370259340535.043580439504395043");
	cout << std::setprecision(std::numeric_limits<number<cpp_dec_float<200> >>::max_digits10) << log(high_prec_num) << endl;*/

	CFile file2;
	file2.Open("./test.txt", CFile::ONLY_WRITE);
	file2.Write(iconv("的非官方大哥", CIconv::CHARSET_UTF8,  CIconv::CHARSET_GBK));
	file2.Close();

	cout << sizeof(wchar_t) << endl;
	string str_8 = "a汉字b";
	string str_9 = iconv(str_8, CIconv::CHARSET_UTF8,  CIconv::CHARSET_GBK);
	cout << str_8.size() << " " << str_9.size() << " " << strlen(str_8, CIconv::CHARSET_UTF8) << " " << strlen(str_9, CIconv::CHARSET_GBK) << endl;
	cout << std::string::npos << " " << substr("abcefg", 2, -2) << endl;
	cout << iconv(substr("的非官方大哥", 1, -1, CIconv::CHARSET_UTF8), CIconv::CHARSET_UTF8,  CIconv::CHARSET_GBK) << endl;
	cout << substr(iconv("他人让他和规范化", CIconv::CHARSET_UTF8,  CIconv::CHARSET_GBK), 3, 50, CIconv::CHARSET_GBK) << endl;

	cout << base64_encode(sha1("abc", true)) << endl;
	cout << base64_encode(md5("abc", true)) << endl;
	cout << sha1("abcdefg") << endl;

	cout << num_to_string(stolll("123456789")) << "," << num_to_string(stolll("-123456789")) << "," << num_to_string(stoulll("1234567890987654321")) << endl;

	CFixedMemoryStorage<uint32_t> table;
	table.Test();

	map<string, int> test_map;
	test_map["a"] = 1;
	test_map["b"] = 2;
	test_map["c"] = 3;
	test_map["d"] = 4;
	test_map["e"] = 5;
	test_map["f"] = 6;
	for(auto it = test_map.begin(); it != test_map.end(); )
	{
		if(it->second == 2 || it->second == 5)
	   {
			test_map.erase(it++);
	   }else
	   {
			it->second += 2;
			++it;
	   }
	}
	for(auto it = test_map.begin(); it != test_map.end(); it++) {
		cout << it->first << ":" << it->second << endl;
	}

	/*CPack pack;
	mpz_int test_mpzint("-123456789");
	pack.Put(test_mpzint);
	mpz_int test_mpzint2;
	pack.Get(test_mpzint2);
	cout << "test_mpzint:" << test_mpzint2 << endl;
	pack.Clear();
	mpq_rational test_mpqrat("123/-456");
	pack.Put(test_mpqrat);
	mpq_rational test_mpqrat2;
	pack.Get(test_mpqrat2);
	cout << "test_mpqrat:" << test_mpqrat2 << endl;*/

	/*uint32_t charnum;
	string trunstr("的非官方大哥");
	truncate(trunstr, 14, charnum, CIconv::CHARSET_UTF8);
	cout << iconv(trunstr, CIconv::CHARSET_UTF8,  CIconv::CHARSET_GBK) << ":" << charnum << "," << strlen(trunstr, CIconv::CHARSET_UTF8) << "," << trunstr.size() << endl;*/

	cout << num_limits<__int128_t>::min() << "," << num_limits<__int128_t>::max() << endl;
	//cout << numeric_limits<int128_t>::min() << "," << numeric_limits<int128_t>::max() << endl;
	cout << num_limits<__uint128_t>::min() << "," << num_limits<__uint128_t>::max() << endl;
	//cout << numeric_limits<uint128_t>::min() << "," << numeric_limits<uint128_t>::max() << endl;
	cout << setiosflags(ios::scientific) << setprecision(numeric_limits<float>::digits10) << numeric_limits<float>::min() << "," << numeric_limits<float>::max() << endl;
	cout << setiosflags(ios::scientific) << setprecision(numeric_limits<double>::digits10) << numeric_limits<double>::min() << "," << numeric_limits<double>::max() << endl;
	cout << setiosflags(ios::scientific) << setprecision(numeric_limits<long double>::digits10) << numeric_limits<long double>::min() << "," << numeric_limits<long double>::max() << endl;

	cout << "uint32 product:" << uint64_t(num_limits<uint32_t>::max()) * uint64_t(num_limits<uint32_t>::max()) << endl;
	cout << thread::hardware_concurrency() << endl;

	//cout << regex_match("20M", regex("\\d+(K|M|G)?")) << "," << regex_match("20", regex("\\d+(K|M|G)?")) << "," << regex_match("20aa", regex("\\d+(K|M|G)?")) << endl;

	CAny any(static_cast<int8_t>(8));
	cout << "any:" << (int)any.ToInt8() << endl;
	cout << sizeof(CAny::Data) << endl;

	/*auto t1 = CTime::Now();
	int a;
	//boost::any b = 233423;
	//CAny b = 233423;
	for(int i = 0; i < 10000000; i ++) {
		//boost::any a = 233423 + i;
		CAny a = 233423 + i;
		//num_to_string(233423 + i);
		//int a = 233423 + i;
		//int a = stol("233423");
		//a = static_cast<int>(b);
		//a = boost::any_cast<int>(b);
	}
	auto t2 = CTime::Now();
	cout << a << endl;
	cout << (t2 - t1) * CTime::TimeRatio << endl;*/

	{
		CDateTime v(2019, 6, 27, 7561, 2001);
		uint16_t hour = static_cast<uint16_t>(v.Time / 3600);
		uint16_t leftseconds = v.Time % 3600;
		uint16_t minute = leftseconds / 60;
		uint16_t second = leftseconds % 60;
		cout << num_to_string(v.Year) + "-" + num_to_string(v.Month) + "-" + num_to_string(v.Day) + " " +
				num_to_string(hour) + ":" + num_to_string(minute) + ":" + num_to_string(second) + "." +
				num_to_string(v.Fraction) << endl;
	}
	{
		int64_t v = 7561ULL * CTime::NanoTime + 4534545ULL;
		long double ldv = static_cast<long double>(v) / CTime::NanoTime;
		v = static_cast<int64_t>(ldv);
		double fraction = static_cast<double>(::fabs(ldv - v));
		int64_t hour = v / 3600;
		int32_t leftseconds = v % 3600;
		int32_t minute = leftseconds / 60;
		int32_t second = leftseconds % 60;
		cout << num_to_string(hour) + ":" + pad_left_copy(num_to_string(::abs(minute)), 2, '0') + ":" + pad_left_copy(num_to_string(::abs(second)), 2, '0') + "." + num_to_string(fraction) << endl;
	}

	CDatabase db;
	/*// 创建数据库
	db.Create("./testdb");*/
	/*
	// 添加用户
	db.Open("./testdb");
	db.AddUser("mzt", "123456", 1, "127.0.0.1", bitset<8>(255));
	*/

	// 创建表
	/*db.Open("./testdb/nosql/test");
	vector<CRawField> fields;
	fields.emplace_back(CRawField("id", FT_SERIAL32));
	fields.emplace_back(CRawField("createdtime", FT_TIMESTAMP, true, true, "CURRENT_TIMESTAMP"));
	fields.emplace_back(CRawField("updatedtime", FT_TIMESTAMP, true, true, "CURRENT_TIMESTAMP", true, "CURRENT_TIMESTAMP"));
	fields.emplace_back(CRawField("title", FT_CHAR, true, false, "", false, "", 200));
	fields.emplace_back(CRawField("content", FT_CHAR, true, false, "", false, "", 10000));
	fields.emplace_back(CRawField("price", FT_FLOAT64));
	fields.emplace_back(CRawField("hits", FT_UINT32, true, true, "0"));
	vector<CIndex> indexes;
	indexes.emplace_back(CIndex("id", IT_PRIMARY, IM_BTREE, vector<string>{"id"}));
	db.CreateTable("testtable", TT_FIXMEMORY, fields, indexes);
	db.Close();*/
	/*db.Open("./testdb");
	db.LoadTable("testtable");
	db.Close();*/

	/*if (std::regex_match ("-234.3", std::regex("^[+-]?(\\d+|(\\d*[\\.]\\d+)|(\\d+[\\.]\\d*))([eE][+-]?\\d+)?$") ))
		std::cout << "string literal matched\n";
	if (std::regex_match ("-234.3e-2", std::regex("^[+-]?(\\d+|(\\d*[\\.]\\d+)|(\\d+[\\.]\\d*))([eE][+-]?\\d+)?$") ))
		std::cout << "string literal matched\n";*/

	cout << std::numeric_limits<float>::digits10 << "," << std::numeric_limits<double>::digits10 << "," << FLT128_DIG << endl;
	cout << std::to_string((float)1.1) << "," << num_to_string((float)1.1) << "," << num_to_string((double)1.1) << "," << num_to_string((__float128)1.1) << endl;

	list<int> li;
	for(int i = 0; i < 6; i++) {
		li.push_back(i);
	}
	cout << li.size() << endl;
	for(auto it = li.begin(); it != li.end();) {
		auto del_it = it;
		it++;
		li.erase(del_it);
	}
	cout << li.size() << endl;

	map<int, int> intmap;
	for(int i = 0; i < 10; i++) {
		intmap.insert(pair<int, int>(i + 1, i));
	}
	cout << intmap.size() << endl;
	for(auto it = intmap.begin(); it != intmap.end();) {
		auto del_it = it;
		it++;
		intmap.erase(del_it);
	}
	cout << intmap.size() << endl;

//	auto threadstarttime = CTime::Now();
	/*vector<string> teststringvector(4);
	thread thpool[4];
	for(size_t i = 0; i < 4; i++) {
		string* str = &teststringvector[i];
		thpool[i] = thread([str]() {
			for(size_t j = 0; j < 10000000; j++) {
				*str = "teststring_" + to_string(j);
			}
		});
	}
	for(size_t i = 0; i < 4; i++) {
		thpool[i].join();
	}*/
	/*string test1, test2, test3, test4;
	thread th1, th2, th3, th4;
	th1 = thread([&test1]() {
		for(size_t j = 0; j < 10000000; j++) {
			test1 = "teststring_" + to_string(j);
		}
	});
	th2 = thread([&test2]() {
		for(size_t j = 0; j < 10000000; j++) {
			test2 = "teststring_" + to_string(j);
		}
	});
	th3 = thread([&test3]() {
		for(size_t j = 0; j < 10000000; j++) {
			test3 = "teststring_" + to_string(j);
		}
	});
	th4 = thread([&test4]() {
		for(size_t j = 0; j < 10000000; j++) {
			test4 = "teststring_" + to_string(j);
		}
	});
	th1.join();
	th2.join();
	th3.join();
	th4.join();*/
//	auto threadendtime = CTime::Now();
//	cout << "  " << (threadendtime - threadstarttime) * CTime::TimeRatio << endl;
}

void test2()
{
	boost::multiprecision::cpp_dec_float_100 b = 2;
	cout << b * b * 3 << endl;
	/*cout << "a0:"; CDecimal128 a0("123", 8, 2);
	cout << "a1:"; CDecimal128 a1("123.456", 8, 1);
	cout << "a2:"; CDecimal128 a2("123.4446", 8, 2);
	cout << "a3:"; CDecimal128 a3("123.446", 8, 3);
	cout << "a4:"; CDecimal128 a4("123.446", 10, 6);
	cout << "a5:"; CDecimal128 a5("12345", 5, -2);
	cout << "a6:"; CDecimal128 a6("12355", 5, -2);
	cout << "a7:"; CDecimal128 a7("12345.678", 5, -5);
	cout << "a8:"; CDecimal128 a8("82345.678", 5, -5);
	cout << "a9:"; CDecimal128 a9("182345.678", 5, -5);*/
	cout << num_to_string(num_limits<__uint128_t>::max()).size() << endl;
//		CDecimal128 aa(-3);
//		aa.Set(__int128_t(12345678));
//		aa.Set(__int128_t(12345178));
//		aa.Set(__int128_t(-12345678));
//		aa.Set(__int128_t(-12345178));
//		aa.Set(__uint128_t(12345678));
//		CDecimal128 aa2(3);
//		aa2.Set(__uint128_t(12345678));
	//CDecimal128 aa2(127);
	//aa2.Set(__int128_t(9999999));
//		__int128_t ss = -1;
//		for(int i = 0; i < 100; i++)
//			ss *= 10;
//		cout << ss << endl;
	CDecimal128 abc(0);
	abc.Set("1234.567");
	cout << abc.ToString() << endl;
	cout << abc.ToString(true) << endl;
	abc.Set("-1234.56");
	cout << abc.ToString() << endl;
	cout << abc.ToString(true) << endl;
	abc.Set("1234");
	cout << abc.ToString() << endl;
	cout << abc.ToString(true) << endl;
	CDecimal128 abc2(-3);
	abc2.Set("1234567.890");
	cout << abc2.ToString() << endl;
	abc2.Set("-1234567.890");
	cout << abc2.ToString() << endl;
	abc2.Set("1234560");
	cout << abc2.ToString() << endl;
	cout << endl;
	cout << num_limits<__int128_t>::min() << endl << num_limits<__int128_t>::max() << endl;
	CDecimal128 abc3(-127);
	abc3.Set("1.23e140");
	cout << abc3.ToString() << endl;

	CDecimal128 abc4(-10);
	abc4 = "-1.23456789";
	cout << abc4.ToString(true, 4) << endl;
	abc4 = "1.23";
	cout << abc4.ToString(false, 3) << endl;
	abc4 = "0.001298755346562";
	cout << abc4.ToString(false) << endl;
	CDecimal128 abc5(-2);
	abc5 = "123456789";
	cout << abc5.ToString(true, -3) << endl;

	CDecimal128 a1(4), a2(6);
	a1 = "11.223344";
	a2 = "100.6666666666666";
	cout << (a1 + a2).ToString() << endl;
	cout << (a1 - a2).ToString() << endl;
}

void test3()
{
	map<int, int> a;
	a[1] = 11;
	a[2] = 22;
	a[3] = 33;
	auto it = a.find(2);
	it->second = 222;
	cout << a[2] << endl;
}

int main(int argc, char *argv[])
{
	//test3();
	try {
		string programdir = boost::filesystem::initial_path().string();
		string programpath = argv[0];
		if(programpath.substr(0, programdir.size()) != programdir) {
			if(programpath.substr(0, 2) == string(".") + DIRECTORY_SEPARATOR) {
				programpath.erase(0, 2);
			}
			size_t pos = programpath.find_last_of(DIRECTORY_SEPARATOR);
			bool isroot;
#if defined(_WIN32)
			isroot = ':' == programpath[1];
#else
			isroot = '/' == programpath[0];
#endif
			if(isroot) {
				programdir = programpath.substr(0, pos);
			}
			else {
				if(string::npos != pos) {
					programdir += DIRECTORY_SEPARATOR + programpath.substr(0, pos);
					programpath = programdir + DIRECTORY_SEPARATOR + programpath.substr(pos + 1);
				}
				else {
					programpath = programdir + DIRECTORY_SEPARATOR + programpath;
				}
			}
		}
		CService::ProgramDir = programdir;
		CLog::Instance(programdir);

		int opt;
		char short_options[] = "hi:s";
		static struct option long_options[] =
		{
			{"help", no_argument, nullptr, 'h'},
			{"inifile", required_argument, nullptr, 'i'},
			{"showinfo",  no_argument, nullptr, 's'},
#if defined(_WIN32)
			{"install",  required_argument, nullptr, 1},
			{"uninstall",  required_argument, nullptr, 2},
			{"ntservice",  required_argument, nullptr, 3},
#endif
			{nullptr, 0, nullptr, 0}
		};

#if defined(_WIN32)
		int oper = 0;
		string servicename;
#endif
		while((opt = getopt_long(argc, argv, short_options, long_options, nullptr))!= -1)
		{
			switch(opt) {
			case 'h':
				cout << endl << "-h or --help: show command list" << endl
					 << "-i or --inifile file: default ini file is under the path of moondb file." << endl
					 << "--install: install windows service" << endl
					 << "--uninstall: uninstall windows service" << endl;
				exit(0);
			case 'i':
				CService::ConfigFile = optarg;
				break;
			case 's':
				CService::ShowInfo = true;
				break;
#if defined(_WIN32)
			case 1:
			case 2:
			case 3:
				oper = opt;
				servicename = optarg;
				break;
#endif
			}
		}
		if(CService::ConfigFile.size() == 0) {
			TriggerError("Please input ini file (eg. moondb.xml) in the command line.");
		}
#if defined(_WIN32)
		if(oper == 1) {
			CService::Install(programpath, CService::ConfigFile, servicename);
			return 0;
		}
		else if(oper == 2) {
			CService::Uninstall(servicename);
			return 0;
		}
		else if(oper == 3) {
			CService::ServiceName = servicename;
			CService::IsService = true;
			CService::ShowInfo = false;
			CService::Start();
			return 0;
		}
#endif
		CService::Main(static_cast<unsigned long>(argc), argv);
	}
	catch(invalid_argument& e) {
		//TriggerError("Invalid command line parameter (invalid_argument: " + string(optarg) + " " + e.what() + ").");
		cout << "Invalid command line parameter (invalid_argument: " + string(optarg) + " " + e.what() + ")." << endl;
	}
	catch(exception& e)
	{
		cout << e.what() << endl;
	}
	return 0;
}

max_stars_repo_name: zzccttu/moondb

max_issues_repo_name: zzccttu/moondb

max_forks_repo_name: zzccttu/moondb


text:
// Copyright (c) 2021 Jan Marjanovic
// Released under the MIT license (see COPYING.MIT for the terms)

#include <algorithm>
#include <chrono>
#include <iostream>
#include <list>
#include <thread>
#include <variant>

#include <boost/program_options.hpp>

#include "AxiProxy.hpp"
#include "Udmabuf.hpp"
#include "UioDevice.hpp"
#include "UioUtilities.hpp"

namespace po = boost::program_options;

namespace std {
std::ostream &operator<<(std::ostream &os, const std::vector<uint32_t> xs) {
  bool first = true;
  os << "std::vector<uint32_t>{";
  for (auto x : xs) {
    if (first) {
      first = false;
    } else {
      os << ", ";
    }
    os << x;
  }
  os << "}";
  return os;
}
} // namespace std

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

  std::string zynq_if;
  uint32_t axi_prot, axi_cache, axi_user;
  bool use_osync;
  std::vector<uint32_t> data;
  std::vector<uint32_t> DATA_DEFAULT_VAL{10, 20, 30, 40};
  constexpr int DATA_LEN = 4;

  po::options_description desc("Control AXI Proxy\n\nArguments");

  // clang-format off
  desc.add_options()
    ("help", "display this help text and exit")
    ("interface",
        po::value<std::string>(&zynq_if)->default_value("hp"),
        "Zynq interface (\"hp\", \"hpc\", \"acp\")")
    ("data",
        po::value<std::vector<uint32_t>>(&data)
          ->multitoken()
          ->default_value(DATA_DEFAULT_VAL),
        "data to write (and read) over the proxy")
    ("use-osync",
        po::bool_switch(&use_osync),
        "Use O_SYNC when opening the u-dma-buf buffer")
    ("axi-prot",
        po::value<uint32_t>(&axi_prot)->default_value(0),
        "AXI AxPROT signal value")
    ("axi-cache",
        po::value<uint32_t>(&axi_cache)->default_value(0),
        "AXI AxCACHE signal value")
    ("axi-user",
        po::value<uint32_t>(&axi_user)->default_value(0),
        "AXI AxUSER signal value")
    ;
  // clang-format on

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

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

  if (data.size() != DATA_LEN) {
    std::cout << "Data should be 4 but it is " << data.size()
              << " elements long\n";
    return EXIT_FAILURE;
  }

  uint32_t udmabuf_flags = 0;

  if (use_osync) {
    udmabuf_flags |= O_SYNC;
  }

  Udmabuf udmabuf{"axi:udmabuf@0x0", udmabuf_flags};

  static std::vector<UioDevice> uios = UioUtilities::get_all_uios();
  std::sort(std::begin(uios), std::end(uios),
            [](const UioDevice &a, const UioDevice &b) -> bool {
              return a.addr < b.addr;
            });

  std::unordered_map<std::string, AxiProxy> axi_proxies;

  for (auto &uio : uios) {
    std::cout << uio << "\n";
    if (uio.name == "AxiProxy") {
      axi_proxies.emplace(uio.note, uio);
    }
  }

  AxiProxy &axi_proxy = axi_proxies.at(zynq_if);
  axi_proxy.print_info();
  axi_proxy.config_axi(axi_cache, axi_prot, axi_user);

  uint64_t phys_addr = udmabuf.get_phys_addr();
  std::array<uint32_t, DATA_LEN> arr;
  std::copy_n(data.begin(), DATA_LEN, arr.begin());
  uint32_t dur_wr = axi_proxy.write(phys_addr, arr);

  std::cout << "SW read, HW written:\n";
  for (int i = 0; i < DATA_LEN; i++) {
    uint32_t sw_read = udmabuf.rd32(i * 4);
    std::cout << "  " << sw_read << ", " << data[i] << "\n";
    if (sw_read != data[i]) {
      throw std::runtime_error("Readback value does not match");
    }
  }

  std::array<uint32_t, DATA_LEN> readback;
  uint32_t dur_rd = axi_proxy.read(phys_addr, readback);

  std::cout << "readback, expected:\n";
  for (int i = 0; i < DATA_LEN; i++) {
    std::cout << "  " << readback[i] << ", " << data[i] << "\n";
    if (readback[i] != data[i]) {
      throw std::runtime_error("Readback value does not match");
    }
  }

  std::cout << "stats: dur_wr = " << dur_wr << ", dur_rd = " << dur_rd << "\n";
}


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

#include <hpx/config.hpp>
#include <hpx/include/runtime.hpp>

#include "webserver.hpp"

#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <sstream>

#include "resources/resources.hpp"

using namespace hpx::opencl::examples::mandelbrot;
using boost::asio::ip::tcp;

static size_t num_requests = 0;
static size_t num_answers = 0;
static size_t num_aborted = 0;

webserver::webserver(unsigned short port, requesthandler* req_handler_)
    : req_handler(req_handler_),
      io_service(),
      acceptor(io_service, tcp::endpoint(tcp::v4(), port)),
      strand(io_service) {}

// This struct is used for automatic registration and unregistration of
// non-hpx threads
struct registration_wrapper {
  registration_wrapper(hpx::runtime* rt, char const* name) : rt_(rt) {
    // Register this thread with HPX, this should be done once for
    // each external OS-thread intended to invoke HPX functionality.
    // Calling this function more than once will silently fail (will
    // return false).
    rt_->register_thread(name);
  }
  ~registration_wrapper() {
    // Unregister the thread from HPX, this should be done once in the
    // end before the external thread exists.
    rt_->unregister_thread();
  }

  hpx::runtime* rt_;
};

void webserver::dont_close_socket(boost::any keepalive_data) {
  std::cout << "Packets: " << num_answers << "/" << num_aborted << "/"
            << num_requests << " - "
            << (num_requests - num_answers - num_aborted) << " lost"
            << std::endl;
}

void webserver::close_socket(std::shared_ptr<tcp::socket> socket,
                             boost::any keepalive_data) {
  socket->close();
}

void webserver::send_server_error_and_close(
    std::shared_ptr<tcp::socket> socket) {
  // std::cout << "aborted" << std::endl;
  num_aborted++;

  std::shared_ptr<std::string> response = std::make_shared<std::string>(
      "HTTP/1.0 500 Server Error\r\n"
      "Connection: Close\r\n"
      "\r\n");

  boost::asio::async_write(*socket, boost::asio::buffer(*response),
                           strand.wrap(boost::bind(&webserver::close_socket,
                                                   this, socket, response)));
}

void webserver::send_not_found_and_close(std::shared_ptr<tcp::socket> socket) {
  std::shared_ptr<std::string> response = std::make_shared<std::string>(
      "HTTP/1.0 404 Not Found\r\n"
      "Connection: Close\r\n"
      "\r\n");

  boost::asio::async_write(*socket, boost::asio::buffer(*response),
                           strand.wrap(boost::bind(&webserver::close_socket,
                                                   this, socket, response)));
}

void webserver::send_bad_request_and_close(
    std::shared_ptr<tcp::socket> socket) {
  std::shared_ptr<std::string> response = std::make_shared<std::string>(
      "HTTP/1.0 400 Bad Request\r\n"
      "Connection: Close\r\n"
      "\r\n");

  boost::asio::async_write(*socket, boost::asio::buffer(*response),
                           strand.wrap(boost::bind(&webserver::close_socket,
                                                   this, socket, response)));
}

std::string webserver::read_filename_from_request(std::string line) {
  // vars
  const std::string string_GET("GET ");
  const std::string string_HTTP("HTTP/");
  size_t pos;

  // if request doesn't start with "GET ", send error
  if (line.compare(0, string_GET.length(), string_GET) != 0) {
    // send error
    return "";
  }

  // cut away "GET "
  line = line.substr(string_GET.length());

  // find the next space
  pos = line.find(' ');
  if (pos == line.npos) {
    // send error
    return "";
  }

  // take request filename
  std::string filename = line.substr(0, pos);

  // cut away filename
  line = line.substr(pos + 1);

  // ensure it's a http request
  if (line.compare(0, string_HTTP.length(), string_HTTP) != 0) {
    // send error
    return "";
  }

  return filename;
}

struct send_data_data {
  std::string header;
  std::string footer;
  std::shared_ptr<std::vector<char>> data;
  std::vector<boost::asio::const_buffer> buffers;
};

void webserver::send_data(std::shared_ptr<tcp::socket> socket,
                          const char* content_type,
                          std::shared_ptr<std::vector<char>> data) {
  num_answers++;

  // store all the data that we need to keep alive
  std::shared_ptr<send_data_data> keep_alive_data =
      std::make_shared<send_data_data>();

  // keep data ptr alive
  keep_alive_data->data = data;

  // vector to keep data alive
  std::shared_ptr<std::vector<boost::any>> keep_ =
      std::make_shared<std::vector<boost::any>>();

  // generate header
  std::stringstream ss;
  ss << "HTTP/1.0 200 OK\r\n"
     << "Content-Type: " << content_type << "\r\n"
     << "Content-Length: " << data->size() << "\r\n"
     << "Connection: Keep-Alive\r\n"
     //<< "Connection: Close\r\n"
     << "\r\n";
  keep_alive_data->header = ss.str();

  // generate footer
  keep_alive_data->footer = "\r\n\r\n";

  // put everything in buffers
  keep_alive_data->buffers.push_back(
      boost::asio::buffer(keep_alive_data->header));
  keep_alive_data->buffers.push_back(boost::asio::buffer(
      keep_alive_data->data->data(), keep_alive_data->data->size()));
  keep_alive_data->buffers.push_back(
      boost::asio::buffer(keep_alive_data->footer));

  boost::asio::async_write(
      *socket, keep_alive_data->buffers,
      strand.wrap(
          boost::bind(&webserver::dont_close_socket, this, keep_alive_data)));
}

void webserver::send_data(std::shared_ptr<tcp::socket> socket,
                          const char* content_type, const char* data,
                          size_t data_size) {
  // store all the data that we need to keep alive
  std::shared_ptr<send_data_data> keep_alive_data =
      std::make_shared<send_data_data>();

  // generate header
  std::stringstream ss;
  ss << "HTTP/1.0 200 OK\r\n"
     << "Content-Type: " << content_type << "\r\n"
     << "Content-Length: " << data_size << "\r\n"
     << "Connection: Keep-Alive\r\n"
     //       << "Connection: Close\r\n"
     << "\r\n";
  keep_alive_data->header = ss.str();

  // generate footer
  keep_alive_data->footer = "\r\n\r\n";

  // put everything in buffers
  keep_alive_data->buffers.push_back(
      boost::asio::buffer(keep_alive_data->header));
  keep_alive_data->buffers.push_back(boost::asio::buffer(data, data_size));
  keep_alive_data->buffers.push_back(
      boost::asio::buffer(keep_alive_data->footer));

  boost::asio::async_write(
      *socket, keep_alive_data->buffers,
      strand.wrap(
          boost::bind(&webserver::dont_close_socket, this, keep_alive_data)));
}

static std::vector<long> parse_request(std::string uri) {
  // create empty vector
  std::vector<long> ret;

  // remove '/'
  if (uri.size() < 1) return ret;
  if (uri[0] != '/') return ret;
  uri = uri.substr(1);

  size_t pos;

  // split first number
  pos = uri.find('/');
  if (pos == uri.npos) return ret;
  std::string zoom_string = uri.substr(0, pos);
  uri = uri.substr(pos + 1);

  // split second number
  pos = uri.find('/');
  if (pos == uri.npos) return ret;
  std::string pos_x_string = uri.substr(0, pos);
  uri = uri.substr(pos + 1);

  // split third number
  pos = uri.find('.');
  if (pos == uri.npos) return ret;
  std::string pos_y_string = uri.substr(0, pos);
  uri = uri.substr(pos + 1);

  // check for correct file format requested
  if (uri.compare("png") != 0) return ret;

  // convert strings to long
  long zoom_raw;
  long pos_x_raw;
  long pos_y_raw;
  try {
    zoom_raw = std::stol(zoom_string);
    pos_x_raw = std::stol(pos_x_string);
    pos_y_raw = std::stol(pos_y_string);
  } catch (std::exception e) {
    return ret;
  }

  // create result vector
  ret.push_back(zoom_raw);
  ret.push_back(pos_x_raw);
  ret.push_back(pos_y_raw);

  return ret;
}

void webserver::process_request(std::shared_ptr<tcp::socket> socket,
                                std::string filename) {
  // std::cout << "process_request: " << filename << std::endl;

  // send main website if requested
  if (filename == "/") {
    send_data(socket, "text/html; charset=utf-8", mandelbrot_html,
              mandelbrot_html_len);
    return;
  }

  // send favicon if requested
  if (filename == "/favicon.ico") {
    send_data(socket, "image/x-icon", mandelbrot_ico, mandelbrot_ico_len);
    return;
  }

  // if filename is empty, send "bad request"
  if (filename == "") {
    send_bad_request_and_close(socket);
    return;
  }

  // parse the filename to see if it is an image request
  std::vector<long> img_coords = parse_request(filename);

  // send 'not found' if it is not an image request
  if (img_coords.size() != 3) {
    send_not_found_and_close(socket);
    return;
  }

  // create a new request
  std::shared_ptr<request> img_request = std::make_shared<request>();

  // set coords
  img_request->zoom = img_coords[0];
  img_request->posx = img_coords[1];
  img_request->posy = img_coords[2];

  // set user-ip
  img_request->user_ip = socket->remote_endpoint().address().to_string();

  // set aborted callback
  img_request->abort = strand.wrap(
      boost::bind(&webserver::send_server_error_and_close, this, socket));

  // set stillValid callback
  img_request->stillValid =
      boost::bind(&webserver::is_socket_still_connected, this, socket);

  // set done callback
  img_request->done = strand.wrap(
      boost::bind(&webserver::send_data, this, socket, "image/png", _1));

  num_requests++;
  // submit the request
  req_handler->submit_request(img_request);
}

bool webserver::is_socket_still_connected(std::shared_ptr<tcp::socket> socket) {
  return socket->is_open();
}

void webserver::new_line_read_callback(
    const boost::system::error_code& error, size_t bytes_transferred,
    std::shared_ptr<tcp::socket> socket,
    std::shared_ptr<boost::asio::streambuf> buffer, size_t lines_read,
    std::string requested_file) {
  // check for errors
  if (error) {
    std::cout << error.message() << std::endl;
    // on error, close socket and return without querying the next line read
    socket->close();
    return;
  }

  // create an input stream from buffer
  std::istream instream(&(*buffer));

  // create a string to hold the read line
  std::string line;

  // read data to the string
  std::getline(instream, line);

  // remove whitespace at front and end of string
  boost::algorithm::trim(line);

  // if this is the first line, read query information from it
  if (lines_read == 0) {
    // read filename from line
    std::string filename = read_filename_from_request(line);
    if (filename == "") {
      // send error
      send_bad_request_and_close(socket);
      return;
    }

    // remember filename
    requested_file = filename;

  }
  // if this is the last line, process the request
  else if (line.size() == 0) {
    // process the request
    process_request(socket, requested_file);

    // continue reading lines, could be persistent socket
    start_reading_line_from_socket(buffer, socket, 0, "");

    return;
  }

  // query the next line
  start_reading_line_from_socket(buffer, socket, lines_read + 1,
                                 requested_file);
}

void webserver::start_reading_line_from_socket(
    std::shared_ptr<boost::asio::streambuf> buffer,
    std::shared_ptr<tcp::socket> socket, size_t num_lines_already_read,
    std::string requested_file) {
  // connect the buffer to the stream and register data callback
  boost::asio::async_read_until(
      *socket, *buffer, "\n",
      strand.wrap(boost::bind(&webserver::new_line_read_callback, this,
                              boost::asio::placeholders::error,
                              boost::asio::placeholders::bytes_transferred,
                              socket, buffer, num_lines_already_read,
                              requested_file)));
}

void webserver::new_connection_callback(const boost::system::error_code& error,
                                        std::shared_ptr<tcp::socket> socket) {
  // start listening for another connection, to enable multiple connections
  // at once
  start_listening_for_new_connection();

  // check for error
  if (error) {
    // print error message
    std::cerr << "Webserver: Error while waiting for new connection: "
              << error.message() << std::endl;

    // drop this connection
    return;
  }

  // create a new buffer for the tcp data stream
  std::shared_ptr<boost::asio::streambuf> buffer =
      std::make_shared<boost::asio::streambuf>();

  // connect buffer to socket and start reading
  start_reading_line_from_socket(buffer, socket, 0, "");
}

void webserver::start_listening_for_new_connection() {
  // create new socket
  std::shared_ptr<tcp::socket> connected_socket =
      std::make_shared<tcp::socket>(io_service);

  // register socket and callback, to wait for new connection
  acceptor.async_accept(
      *connected_socket,
      strand.wrap(boost::bind(&webserver::new_connection_callback, this,
                              boost::asio::placeholders::error,
                              connected_socket)));
}

void webserver::external_start(hpx::runtime* rt) {
  // register this thread to hpx
  registration_wrapper wrap(rt, "asio_webserver");

  // register callback for new connections
  start_listening_for_new_connection();

  // start the io_service
  io_service.run();
}

void webserver::start() {
  // forward this call to an external os thread
  asio_thread = hpx::compat::thread(hpx::util::bind(
      &webserver::external_start, this, hpx::get_runtime_ptr()));
}

void webserver::stop() {
  // stop the io service
  io_service.stop();

  // wait for the operating system thread to finish
  asio_thread.join();
}

max_stars_repo_name: STEllAR-GROUP/hpxcl

max_issues_repo_name: STEllAR-GROUP/hpxcl

max_forks_repo_name: STEllAR-GROUP/hpxcl


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

#include <boost/parameter/config.hpp>

#if (BOOST_PARAMETER_MAX_ARITY < 10)
#error Define BOOST_PARAMETER_MAX_ARITY as 10 or greater.
#endif

#include <boost/parameter.hpp>

namespace test {

    BOOST_PARAMETER_NAME(in(lrc0))
    BOOST_PARAMETER_NAME(out(lr0))
    BOOST_PARAMETER_NAME(in(rrc0))
#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
    BOOST_PARAMETER_NAME(consume(rr0))
#else
    BOOST_PARAMETER_NAME(rr0)
#endif
    BOOST_PARAMETER_NAME(in(lrc1))
    BOOST_PARAMETER_NAME(out(lr1))
    BOOST_PARAMETER_NAME(in(rrc1))
    BOOST_PARAMETER_NAME(in(lrc2))
    BOOST_PARAMETER_NAME(out(lr2))
    BOOST_PARAMETER_NAME(rr2)

    struct g_parameters
      : boost::parameter::parameters<
            boost::parameter::required<test::tag::lrc0>
          , boost::parameter::required<test::tag::lr0>
          , boost::parameter::required<test::tag::rrc0>
          , boost::parameter::required<test::tag::rr0>
          , boost::parameter::required<test::tag::lrc1>
          , boost::parameter::required<test::tag::lr1>
          , boost::parameter::required<test::tag::rrc1>
          , boost::parameter::optional<test::tag::lrc2>
          , boost::parameter::optional<test::tag::lr2>
          , boost::parameter::optional<test::tag::rr2>
        >
    {
    };
} // namespace test

#include <boost/parameter/macros.hpp>
#include <boost/core/lightweight_test.hpp>
#include "evaluate_category.hpp"

namespace test {

    struct C
    {
        BOOST_PARAMETER_MEMFUN(static int, evaluate, 7, 10, g_parameters)
        {
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference_to_const
              , U::evaluate_category<0>(p[test::_lrc0])
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference
              , U::evaluate_category<0>(p[test::_lr0])
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference_to_const
              , U::evaluate_category<1>(p[test::_lrc1])
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference
              , U::evaluate_category<1>(p[test::_lr1])
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference_to_const
              , U::evaluate_category<2>(
                    p[test::_lrc2 | test::lvalue_const_bitset<2>()]
                )
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference
              , U::evaluate_category<2>(
                    p[test::_lr2 || test::lvalue_bitset_function<2>()]
                )
            );
#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
            BOOST_TEST_EQ(
                test::passed_by_rvalue_reference_to_const
              , U::evaluate_category<0>(p[test::_rrc0])
            );
            BOOST_TEST_EQ(
                test::passed_by_rvalue_reference
              , U::evaluate_category<0>(p[test::_rr0])
            );
            BOOST_TEST_EQ(
                test::passed_by_rvalue_reference_to_const
              , U::evaluate_category<1>(p[test::_rrc1])
            );
            BOOST_TEST_EQ(
                test::passed_by_rvalue_reference
              , U::evaluate_category<2>(
                    p[test::_rr2 || test::rvalue_bitset_function<2>()]
                )
            );
#else   // !defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference_to_const
              , U::evaluate_category<0>(p[test::_rrc0])
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference_to_const
              , U::evaluate_category<0>(p[test::_rr0])
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference_to_const
              , U::evaluate_category<1>(p[test::_rrc1])
            );
            BOOST_TEST_EQ(
                test::passed_by_lvalue_reference_to_const
              , U::evaluate_category<2>(
                    p[test::_rr2 || test::rvalue_bitset_function<2>()]
                )
            );
#endif  // BOOST_PARAMETER_HAS_PERFECT_FORWARDING

            return 0;
        }
    };
} // namespace test

#if !defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING)
#include <boost/core/ref.hpp>
#endif

int main()
{
#if defined(BOOST_PARAMETER_HAS_PERFECT_FORWARDING) || \
    (10 < BOOST_PARAMETER_EXPONENTIAL_OVERLOAD_THRESHOLD_ARITY)
    test::C::evaluate(
        test::lvalue_const_bitset<0>()
      , test::lvalue_bitset<0>()
      , test::rvalue_const_bitset<0>()
      , test::rvalue_bitset<0>()
      , test::lvalue_const_bitset<1>()
      , test::lvalue_bitset<1>()
      , test::rvalue_const_bitset<1>()
    );
    test::C::evaluate(
        test::lvalue_const_bitset<0>()
      , test::lvalue_bitset<0>()
      , test::rvalue_const_bitset<0>()
      , test::rvalue_bitset<0>()
      , test::lvalue_const_bitset<1>()
      , test::lvalue_bitset<1>()
      , test::rvalue_const_bitset<1>()
      , test::lvalue_const_bitset<2>()
      , test::lvalue_bitset<2>()
      , test::rvalue_bitset<2>()
    );
#else   // no perfect forwarding support and no exponential overloads
    test::C::evaluate(
        test::lvalue_const_bitset<0>()
      , boost::ref(test::lvalue_bitset<0>())
      , test::rvalue_const_bitset<0>()
      , test::rvalue_bitset<0>()
      , test::lvalue_const_bitset<1>()
      , boost::ref(test::lvalue_bitset<1>())
      , test::rvalue_const_bitset<1>()
    );
    test::C::evaluate(
        test::lvalue_const_bitset<0>()
      , boost::ref(test::lvalue_bitset<0>())
      , test::rvalue_const_bitset<0>()
      , test::rvalue_bitset<0>()
      , test::lvalue_const_bitset<1>()
      , boost::ref(test::lvalue_bitset<1>())
      , test::rvalue_const_bitset<1>()
      , test::lvalue_const_bitset<2>()
      , boost::ref(test::lvalue_bitset<2>())
      , test::rvalue_bitset<2>()
    );
#endif  // perfect forwarding support, or exponential overloads
    return boost::report_errors();
}


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

#include "util/disk-info.h"

#ifdef __APPLE__
#include <sys/mount.h>
#else
#include <sys/vfs.h>
#endif
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/join.hpp>
#include <iostream>
#include <fstream>
#include <sstream>

#include "util/debug-util.h"

#include "common/names.h"

using boost::algorithm::is_any_of;
using boost::algorithm::split;
using boost::algorithm::token_compress_on;
using boost::algorithm::trim;
using boost::algorithm::trim_right_if;

namespace impala {

bool DiskInfo::initialized_;
vector<DiskInfo::Disk> DiskInfo::disks_;
map<dev_t, int> DiskInfo::device_id_to_disk_id_;
map<string, int> DiskInfo::disk_name_to_disk_id_;

// Parses /proc/partitions to get the number of disks.  A bit of looking around
// seems to indicate this as the best way to do this.
// TODO: is there not something better than this?
void DiskInfo::GetDeviceNames() {
  // Format of this file is:
  //    major, minor, #blocks, name
  // We are only interesting in name which is formatted as device_name<partition #>
  // The same device will show up multiple times for each partition (e.g. sda1, sda2).
  ifstream partitions("/proc/partitions", ios::in);
  while (partitions.good() && !partitions.eof()) {
    string line;
    getline(partitions, line);
    trim(line);

    vector<string> fields;
    split(fields, line, is_any_of(" "), token_compress_on);
    if (fields.size() != 4) continue;
    string name = fields[3];
    if (name == "name") continue;

    // Remove the partition# from the name.  e.g. sda2 --> sda
    trim_right_if(name, is_any_of("0123456789"));

    // Create a mapping of all device ids (one per partition) to the disk id.
    int major_dev_id = atoi(fields[0].c_str());
    int minor_dev_id = atoi(fields[1].c_str());
    dev_t dev = makedev(major_dev_id, minor_dev_id);
    DCHECK(device_id_to_disk_id_.find(dev) == device_id_to_disk_id_.end());

    int disk_id = -1;
    map<string, int>::iterator it = disk_name_to_disk_id_.find(name);
    if (it == disk_name_to_disk_id_.end()) {
      // First time seeing this disk
      disk_id = disks_.size();
      disks_.push_back(Disk(name, disk_id));
      disk_name_to_disk_id_[name] = disk_id;
    } else {
      disk_id = it->second;
    }
    device_id_to_disk_id_[dev] = disk_id;
  }

  if (partitions.is_open()) partitions.close();

  if (disks_.empty()) {
    // If all else fails, return 1
    LOG(WARNING) << "Could not determine number of disks on this machine.";
    disks_.push_back(Disk("sda", 0));
    return;
  }

  // Determine if the disk is rotational or not.
  for (int i = 0; i < disks_.size(); ++i) {
    // We can check if it is rotational by reading:
    // /sys/block/<device>/queue/rotational
    // If the file is missing or has unexpected data, default to rotational.
    stringstream ss;
    ss << "/sys/block/" << disks_[i].name << "/queue/rotational";
    ifstream rotational(ss.str().c_str(), ios::in);
    if (rotational.good()) {
      string line;
      getline(rotational, line);
      if (line == "0") disks_[i].is_rotational = false;
    }
    if (rotational.is_open()) rotational.close();
  }
}

void DiskInfo::Init() {
  GetDeviceNames();
  initialized_ = true;
}

int DiskInfo::disk_id(const char* path) {
  struct stat s;
  stat(path, &s);
  map<dev_t, int>::iterator it = device_id_to_disk_id_.find(s.st_dev);
  if (it == device_id_to_disk_id_.end()) return -1;
  return it->second;
}

string DiskInfo::DebugString() {
  DCHECK(initialized_);
  stringstream stream;
  stream << "Disk Info: " << endl;
  stream << "  Num disks " << num_disks() << ": " << endl;
  for (int i = 0; i < disks_.size(); ++i) {
    stream << "    " << disks_[i].name
           << " (rotational=" << (disks_[i].is_rotational ? "true" : "false") << ")\n";
  }
  stream << endl;
  return stream.str();
}

}

ext: cc

max_stars_repo_name: suifengzhuliu/impala

max_issues_repo_name: suifengzhuliu/impala

max_forks_repo_name: suifengzhuliu/impala


text:
/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2013, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  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 Willow Garage 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.
 *********************************************************************/

/* Author: Acorn Pooley, Ioan Sucan */

#include <moveit/collision_detection/world_diff.h>
#include <boost/bind.hpp>

collision_detection::WorldDiff::~WorldDiff()
{
  WorldPtr old_world = world_.lock();
  if (old_world)
    old_world->removeObserver(observer_handle_);
}

collision_detection::WorldDiff::WorldDiff()
{
}

collision_detection::WorldDiff::WorldDiff(const WorldPtr& world) : world_(world)
{
  observer_handle_ = world->addObserver(boost::bind(&WorldDiff::notify, this, _1, _2));
}

collision_detection::WorldDiff::WorldDiff(WorldDiff& other)
{
  WorldPtr world = other.world_.lock();
  if (world)
  {
    changes_ = other.changes_;

    std::weak_ptr<World>(world).swap(world_);
    observer_handle_ = world->addObserver(boost::bind(&WorldDiff::notify, this, _1, _2));
  }
}

void collision_detection::WorldDiff::reset()
{
  clearChanges();

  WorldPtr old_world = world_.lock();
  if (old_world)
    old_world->removeObserver(observer_handle_);

  world_.reset();
}

void collision_detection::WorldDiff::reset(const WorldPtr& world)
{
  clearChanges();

  WorldPtr old_world = world_.lock();
  if (old_world)
    old_world->removeObserver(observer_handle_);

  std::weak_ptr<World>(world).swap(world_);
  observer_handle_ = world->addObserver(boost::bind(&WorldDiff::notify, this, _1, _2));
}

void collision_detection::WorldDiff::setWorld(const WorldPtr& world)
{
  WorldPtr old_world = world_.lock();
  if (old_world)
  {
    old_world->notifyObserverAllObjects(observer_handle_, World::DESTROY);
    old_world->removeObserver(observer_handle_);
  }

  std::weak_ptr<World>(world).swap(world_);

  observer_handle_ = world->addObserver(boost::bind(&WorldDiff::notify, this, _1, _2));
  world->notifyObserverAllObjects(observer_handle_, World::CREATE | World::ADD_SHAPE);
}

void collision_detection::WorldDiff::clearChanges()
{
  changes_.clear();
}

void collision_detection::WorldDiff::notify(const World::ObjectConstPtr& obj, World::Action action)
{
  World::Action& a = changes_[obj->id_];
  if (action == World::DESTROY)
    a = World::DESTROY;
  else
    a = a | action;
}

max_stars_repo_name: henningkayser/moveit

max_issues_repo_name: henningkayser/moveit

max_forks_repo_name: henningkayser/moveit


text:
#include "aikido/planner/vectorfield/VectorFieldPlanner.hpp"

#include <boost/numeric/odeint.hpp>

#include "aikido/constraint/TestableIntersection.hpp"
#include "aikido/constraint/dart/JointStateSpaceHelpers.hpp"
#include "aikido/planner/vectorfield/MoveEndEffectorOffsetVectorField.hpp"
#include "aikido/planner/vectorfield/MoveEndEffectorPoseVectorField.hpp"
#include "aikido/planner/vectorfield/VectorFieldUtil.hpp"
#include "aikido/statespace/dart/MetaSkeletonStateSaver.hpp"
#include "aikido/trajectory/Spline.hpp"

#include "detail/VectorFieldIntegrator.hpp"
#include "detail/VectorFieldPlannerExceptions.hpp"

using aikido::planner::vectorfield::MoveEndEffectorOffsetVectorField;
using aikido::planner::vectorfield::MoveEndEffectorPoseVectorField;
using aikido::planner::vectorfield::detail::VectorFieldIntegrator;
using aikido::statespace::dart::MetaSkeletonStateSaver;

namespace aikido {
namespace planner {
namespace vectorfield {

constexpr double integrationTimeInterval = 10.0;

//==============================================================================
aikido::trajectory::UniqueInterpolatedPtr followVectorField(
    const aikido::planner::vectorfield::VectorField& vectorField,
    const aikido::statespace::StateSpace::State& startState,
    const aikido::constraint::Testable& constraint,
    std::chrono::duration<double> timelimit,
    double initialStepSize,
    double checkConstraintResolution,
    planner::Planner::Result* result)
{
  using namespace std::placeholders;
  using errorStepper = boost::numeric::odeint::runge_kutta_dopri5<
      Eigen::VectorXd,
      double,
      Eigen::VectorXd,
      double,
      boost::numeric::odeint::vector_space_algebra>;

  std::size_t dimension = vectorField.getStateSpace()->getDimension();
  auto integrator = std::make_shared<detail::VectorFieldIntegrator>(
      &vectorField, &constraint, timelimit.count(), checkConstraintResolution);

  integrator->start();

  try
  {
    Eigen::VectorXd initialQ(dimension);
    vectorField.getStateSpace()->logMap(&startState, initialQ);
    // The current implementation works only in real vector spaces.

    // Integrate the vector field to get a configuration space path.
    boost::numeric::odeint::integrate_adaptive(
        errorStepper(),
        std::bind(
            &detail::VectorFieldIntegrator::step,
            integrator,
            std::placeholders::_1,
            std::placeholders::_2,
            std::placeholders::_3),
        initialQ,
        0.,
        integrationTimeInterval,
        initialStepSize,
        std::bind(
            &detail::VectorFieldIntegrator::check,
            integrator,
            std::placeholders::_1,
            std::placeholders::_2));
  }
  // VectorFieldTerminated is an exception that is raised internally to
  // terminate
  // integration, which does not indicate that an error has occurred.
  catch (const detail::VectorFieldTerminated& e)
  {
    if (result)
    {
      result->setMessage(e.what());
    }
  }
  catch (const detail::VectorFieldError& e)
  {
    dtwarn << e.what() << std::endl;
    if (result)
    {
      result->setMessage(e.what());
    }
    return nullptr;
  }

  if (integrator->getCacheIndex() <= 1)
  {
    // no enough waypoints cached to make a trajectory output.
    if (result)
    {
      result->setMessage("No segment cached.");
    }
    return nullptr;
  }

  std::vector<detail::Knot> newKnots(
      integrator->getKnots().begin(),
      integrator->getKnots().begin() + integrator->getCacheIndex());
  // See https://github.com/personalrobotics/aikido/issues/512
  // auto outputTrajectory
  //     = detail::convertToSpline(newKnots, vectorField.getStateSpace());
  auto outputTrajectory
      = detail::convertToInterpolated(newKnots, vectorField.getStateSpace());

  // evaluate constraint satisfaction on last piece of trajectory
  double lastEvaluationTime = integrator->getLastEvaluationTime();
  if (outputTrajectory->getEndTime() > lastEvaluationTime)
  {
    if (!vectorField.evaluateTrajectory(
            *outputTrajectory,
            &constraint,
            checkConstraintResolution,
            lastEvaluationTime,
            true))
    {
      result->setMessage("Constraint violated.");
      return nullptr;
    }
  }
  return outputTrajectory;
}

//==============================================================================
aikido::trajectory::UniqueInterpolatedPtr planToEndEffectorOffset(
    const aikido::statespace::dart::ConstMetaSkeletonStateSpacePtr& stateSpace,
    const statespace::dart::MetaSkeletonStateSpace::State& startState,
    dart::dynamics::MetaSkeletonPtr metaskeleton,
    const dart::dynamics::ConstBodyNodePtr& bn,
    const aikido::constraint::ConstTestablePtr& constraint,
    const Eigen::Vector3d& direction,
    double minDistance,
    double maxDistance,
    double positionTolerance,
    double angularTolerance,
    double initialStepSize,
    double jointLimitTolerance,
    double constraintCheckResolution,
    std::chrono::duration<double> timelimit,
    planner::Planner::Result* result)
{
  // ensure that no two planners run at the same time
  if (metaskeleton->getNumBodyNodes() == 0)
  {
    throw std::runtime_error("MetaSkeleton doesn't have any body nodes.");
  }
  auto robot = metaskeleton->getBodyNode(0)->getSkeleton();
  std::lock_guard<std::mutex> lock(robot->getMutex());
  // TODO(JS): The above code should be replaced by
  // std::lock_guard<std::mutex> lock(metaskeleton->getLockableReference())
  // once https://github.com/dartsim/dart/pull/1011 is released.

  // TODO: Check compatibility between MetaSkeleton and MetaSkeletonStateSpace

  // Save the current state of the space
  auto saver = MetaSkeletonStateSaver(
      metaskeleton, MetaSkeletonStateSaver::Options::POSITIONS);
  DART_UNUSED(saver);

  stateSpace->setState(metaskeleton.get(), &startState);

  auto vectorfield
      = dart::common::make_aligned_shared<MoveEndEffectorOffsetVectorField>(
          stateSpace,
          metaskeleton,
          bn,
          direction,
          minDistance,
          maxDistance,
          positionTolerance,
          angularTolerance,
          initialStepSize,
          jointLimitTolerance);

  auto compoundConstraint
      = std::make_shared<constraint::TestableIntersection>(stateSpace);
  compoundConstraint->addConstraint(constraint);
  compoundConstraint->addConstraint(
      constraint::dart::createTestableBounds(stateSpace));
  return followVectorField(
      *vectorfield,
      startState,
      *compoundConstraint,
      timelimit,
      initialStepSize,
      constraintCheckResolution,
      result);
}

//==============================================================================
aikido::trajectory::UniqueInterpolatedPtr planToEndEffectorPose(
    const aikido::statespace::dart::MetaSkeletonStateSpacePtr& stateSpace,
    dart::dynamics::MetaSkeletonPtr metaskeleton,
    const dart::dynamics::BodyNodePtr& bn,
    const aikido::constraint::TestablePtr& constraint,
    const Eigen::Isometry3d& goalPose,
    double poseErrorTolerance,
    double conversionRatioInGeodesicDistance,
    double initialStepSize,
    double jointLimitTolerance,
    double constraintCheckResolution,
    std::chrono::duration<double> timelimit,
    planner::Planner::Result* result)
{
  // TODO: Check compatibility between MetaSkeleton and MetaSkeletonStateSpace

  // Save the current state of the space
  auto saver = MetaSkeletonStateSaver(
      metaskeleton, MetaSkeletonStateSaver::Options::POSITIONS);
  DART_UNUSED(saver);

  auto vectorfield
      = dart::common::make_aligned_shared<MoveEndEffectorPoseVectorField>(
          stateSpace,
          metaskeleton,
          bn,
          goalPose,
          poseErrorTolerance,
          conversionRatioInGeodesicDistance,
          initialStepSize,
          jointLimitTolerance);

  auto compoundConstraint
      = std::make_shared<aikido::constraint::TestableIntersection>(stateSpace);
  compoundConstraint->addConstraint(constraint);
  compoundConstraint->addConstraint(
      constraint::dart::createTestableBounds(stateSpace));

  auto startState
      = stateSpace->getScopedStateFromMetaSkeleton(metaskeleton.get());
  return followVectorField(
      *vectorfield,
      *startState,
      *compoundConstraint,
      timelimit,
      initialStepSize,
      constraintCheckResolution,
      result);
}

} // namespace vectorfield
} // namespace planner
} // namespace aikido