text:
#if not defined BEASTHTTP_REACTOR_SSL_SESSION_HXX
#define BEASTHTTP_REACTOR_SSL_SESSION_HXX

#include <http/base/cb.hxx>
#include <http/base/request_processor.hxx>
#include <http/base/queue.hxx>
#include <http/base/timer.hxx>
#include <http/base/regex.hxx>
#include <http/base/strand_stream.hxx>
#include <http/base/lockable.hxx>

#include <http/common/ssl/connection.hxx>
#include <http/common/detect.hxx>

#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core/flat_buffer.hpp>
#include <boost/beast/http/string_body.hpp>

#include <unordered_map>

#define BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE(router) \
    flesh_type(std::declval<boost::asio::ssl::context&>(), \
               std::declval<socket_type>(), \
               router.resource_map(), \
               router.method_map(), \
               router.regex_flags(), \
               &router.mutex(), \
               std::declval<buffer_type>(), \
               std::declval<_OnAction>()...)

#define BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE_LEGACY() \
    flesh_type(std::declval<boost::asio::ssl::context&>(), \
               std::declval<socket_type>(), \
               std::declval<std::shared_ptr<resource_map_type>>(), \
               std::declval<std::shared_ptr<method_map_type>>(), \
               std::declval<regex_flag_type>(), \
               std::declval<mutex_type*>(), \
               std::declval<buffer_type>(), \
               std::declval<_OnError>()...)

#define BEASTHTTP_REACTOR_SSL_SESSION_CONTEXT_TRY_INVOKE_MEMBER(overload, ...) \
    std::declval<context<Flesh, context_policy::shared>>().flesh_p_->member(overload, ##__VA_ARGS__)

namespace _0xdead4ead {
namespace http {
namespace reactor {
namespace ssl {

template</*Prototype request message*/
         class Body = boost::beast::http::string_body,
         class Fields = boost::beast::http::basic_fields<std::allocator<char>>,
         /*Message's buffer*/
         class Buffer = boost::beast::flat_buffer,
         /*Connection param's*/
         class Protocol = boost::asio::ip::tcp,
         class Socket = boost::asio::basic_stream_socket<Protocol>,
         /*Timer param's*/
         class Clock = boost::asio::chrono::steady_clock,
         template<typename, typename...> class Timer = boost::asio::basic_waitable_timer,
         /*Callback list container*/
         template<typename> class Entry = std::function,
         template<typename, typename...> class Container = std::vector,
         /*Resources container*/
         template<typename Key, typename Value, typename... Args> class MethodMap = std::map,
         template<typename Key, typename Value, typename... Args> class ResourceMap = std::unordered_map,
         /*On error handler*/
         template<typename> class OnError = std::function,
         /*On timer expired handler*/
         template<typename> class OnTimer = std::function,
         /*On handshake handler*/
         template<typename> class OnHandshake = std::function>
class session
{
    using self_type = session;

    enum class context_policy { shared, weak };

    struct option
    {
        struct on_error{};
        struct on_timer{};
        struct socket{};
        struct ssl_stream{};
    };

public:

    template<class, context_policy>
    class context;

    class flesh;

    using flesh_type = flesh;

    using context_type = context<flesh_type, context_policy::shared>;

    using weak_context = context<flesh_type, context_policy::weak>;

    using resource_regex_type = std::string;

    using resource_type = boost::beast::string_view;

    using method_type = boost::beast::http::verb;

    using mutex_type = base::lockable::mutex_type;

    using body_type = Body;

    using fields_type = Fields;

    using cbexecutor_type = base::cb::executor;

    using request_type = boost::beast::http::request<body_type, fields_type>;

    template<class _Body, class _Fields>
    using response_type = boost::beast::http::response<_Body, _Fields>;

    using queue_type = base::queue<flesh>;

    using buffer_type = Buffer;

    using connection_type = common::ssl::connection<Socket, base::strand_stream::asio_type>;

    using socket_type = typename connection_type::socket_type;

    using ssl_stream_type = typename connection_type::ssl_stream_type;

    using timer_type = base::timer<Clock, Timer, base::strand_stream::asio_type>;

    using duration_type = typename timer_type::duration_type;

    using time_point_type = typename timer_type::time_point;

    using clock_type = typename timer_type::clock_type;

    using regex_type = base::regex;

    using regex_flag_type = typename regex_type::flag_type;

    using on_error_type = OnError<void (boost::system::error_code, boost::string_view)>;

    using on_handshake_type = OnHandshake<void (context_type)>;

    using on_timer_type = OnTimer<void (context_type)>;

    using storage_type = base::cb::storage<self_type, Entry, Container>;

    using resource_map_type = ResourceMap<resource_regex_type, std::shared_ptr<storage_type>>;

    using method_map_type = MethodMap<method_type, resource_map_type>;

    using shutdown_type = typename socket_type::shutdown_type;

    static_assert (base::traits::TryInvoke<on_timer_type, void(context_type)>::value,
                   "Invalid OnTimer handler type!");

    static_assert (base::traits::TryInvoke<on_handshake_type, void(context_type)>::value,
                   "Invalid OnHandshake handler type!");

    static_assert (base::traits::TryInvoke<on_error_type, void(boost::system::error_code, boost::string_view)>::value,
                   "Invalid OnError handler type!");

    class flesh : private base::strand_stream, base::request_processor<self_type>,
            public std::enable_shared_from_this<flesh>
    {
        using base_type = base::request_processor<self_type>;

        friend queue_type;

    public:

        flesh&
        handshake();

        flesh&
        handshake(duration_type const);

        flesh&
        handshake(time_point_type const);

        flesh&
        recv();

        flesh&
        recv(duration_type const);

        flesh&
        recv(time_point_type const);

        template<class _Body, class _Fields>
        flesh&
        send(response_type<_Body, _Fields>&);

        template<class _Body, class _Fields>
        flesh&
        send(response_type<_Body, _Fields>&&);

        template<class _Body, class _Fields>
        flesh&
        send(response_type<_Body, _Fields>&, duration_type const);

        template<class _Body, class _Fields>
        flesh&
        send(response_type<_Body, _Fields>&&, duration_type const);

        template<class _Body, class _Fields>
        flesh&
        send(response_type<_Body, _Fields>&, time_point_type const);

        template<class _Body, class _Fields>
        flesh&
        send(response_type<_Body, _Fields>&&, time_point_type const);

        template<class _Body, class _Fields>
        flesh&
        push(response_type<_Body, _Fields>&);

        template<class _Body, class _Fields>
        flesh&
        push(response_type<_Body, _Fields>&&);

        flesh&
        wait();

        flesh&
        wait(duration_type const);

        flesh&
        wait(time_point_type const);

        flesh&
        timer_cancel();

        flesh&
        eof();

        flesh&
        eof(duration_type const);

        flesh&
        eof(time_point_type const);

        void
        force_eof();

        void
        force_cls();

        template<class Handler>
        void
        member(typename option::on_error, Handler&&,
               typename std::enable_if<
               base::traits::TryInvoke<Handler,
               void(boost::system::error_code,
                    boost::string_view)>::value, int>::type = 0);

        template<class Handler>
        void
        member(typename option::on_timer, Handler&&,
               typename std::enable_if<
               base::traits::TryInvoke<Handler,
               void(context_type)>::value, int>::type = 0);

        socket_type&
        member(typename option::socket);

        ssl_stream_type&
        member(typename option::ssl_stream);

        explicit
        flesh(boost::asio::ssl::context&,
              socket_type&&,
              std::shared_ptr<resource_map_type> const&,
              std::shared_ptr<method_map_type> const&,
              regex_flag_type,
              mutex_type*,
              buffer_type&&);

        explicit
        flesh(int, boost::asio::ssl::context&,
              socket_type&&,
              std::shared_ptr<resource_map_type> const&,
              std::shared_ptr<method_map_type> const&,
              regex_flag_type,
              mutex_type*,
              buffer_type&&);

        template<class _OnHandshake>
        explicit
        flesh(boost::asio::ssl::context&,
              socket_type&&,
              std::shared_ptr<resource_map_type> const&,
              std::shared_ptr<method_map_type> const&,
              regex_flag_type,
              mutex_type*,
              buffer_type&&,
              _OnHandshake&&,
              typename std::enable_if<
              base::traits::TryInvoke<_OnHandshake,
              void(context_type)>::value, int>::type = 0);

        template<class _OnError>
        explicit
        flesh(int, boost::asio::ssl::context&,
              socket_type&&,
              std::shared_ptr<resource_map_type> const&,
              std::shared_ptr<method_map_type> const&,
              regex_flag_type,
              mutex_type*,
              buffer_type&&,
              _OnError&&,
              typename std::enable_if<
              base::traits::TryInvoke<_OnError,
              void(boost::system::error_code,
                   boost::string_view)>::value, int>::type = 0);

        template<class _OnHandshake, class _OnError>
        explicit
        flesh(boost::asio::ssl::context&,
              socket_type&&,
              std::shared_ptr<resource_map_type> const&,
              std::shared_ptr<method_map_type> const&,
              regex_flag_type,
              mutex_type*,
              buffer_type&&,
              _OnHandshake&&,
              _OnError&&,
              typename std::enable_if<
              base::traits::TryInvoke<_OnHandshake,
              void(context_type)>::value and
              base::traits::TryInvoke<_OnError,
              void(boost::system::error_code,
                   boost::string_view)>::value, int>::type = 0);

        template<class _OnHandshake, class _OnError, class _OnTimer>
        explicit
        flesh(boost::asio::ssl::context&,
              socket_type&&,
              std::shared_ptr<resource_map_type> const&,
              std::shared_ptr<method_map_type> const&,
              regex_flag_type,
              mutex_type*,
              buffer_type&&,
              _OnHandshake&&,
              _OnError&&,
              _OnTimer&&,
              typename std::enable_if<
              base::traits::TryInvoke<_OnHandshake,
              void(context_type)>::value and
              base::traits::TryInvoke<_OnError,
              void(boost::system::error_code,
                   boost::string_view)>::value and
              base::traits::TryInvoke<_OnTimer,
              void(context_type)>::value, int>::type = 0);

    private:

        void
        on_timer(boost::system::error_code);

        void
        on_handshake(boost::system::error_code, std::size_t);

        void
        on_shutdown(boost::system::error_code);

        void
        on_read(boost::system::error_code, std::size_t);

        void
        on_write(boost::system::error_code, std::size_t, bool);

        void
        do_handshake();

        void
        do_shutdown();

        template<class _Body, class _Fields>
        void
        do_write(response_type<_Body, _Fields>&);

        template<class _Body, class _Fields>
        void
        do_push(response_type<_Body, _Fields>&);

        void
        do_read();

        void
        do_eof();

        void
        do_force_eof(shutdown_type);

        void
        do_force_cls();

        void
        do_launch_timer();

        void
        do_timeout();

        void
        do_process_request();

        void
        do_timer_cancel();

        bool eof_ = false;

        mutex_type* router_mutex_;

        timer_type timer_;

        connection_type connection_;

        on_handshake_type on_handshake_;
        on_error_type on_error_;
        on_timer_type on_timer_;

        request_type request_;
        buffer_type buffer_;
        queue_type queue_;

    }; // class flesh

    template<class Flesh, context_policy policy>
    class context
    {
        std::shared_ptr<Flesh> flesh_p_;

        bool
        isOk()
        {
            return flesh_p_.operator bool();
        }

    public:

        struct set
        {
            template<class Handler>
            static auto
            on_error(context<Flesh, context_policy::shared> ctx, Handler&& handler) -> decltype (
                    BEASTHTTP_REACTOR_SSL_SESSION_CONTEXT_TRY_INVOKE_MEMBER(std::declval<typename option::on_error>(), std::declval<Handler>()))
            {
                ctx.flesh_p_->set_option(typename option::on_error(), std::forward<Handler>(handler));
            }

            template<class Handler>
            static auto
            on_timer(context<Flesh, context_policy::shared> ctx, Handler&& handler) -> decltype (
                    BEASTHTTP_REACTOR_SSL_SESSION_CONTEXT_TRY_INVOKE_MEMBER(std::declval<typename option::on_timer>(), std::declval<Handler>()))
            {
                ctx.flesh_p_->set_option(typename option::on_timer(), std::forward<Handler>(handler));
            }
        };

        friend struct set;

        context(Flesh& flesh)
            : flesh_p_{flesh.shared_from_this()}
        {
        }

        static context<Flesh, context_policy::shared>
        save(context<Flesh, context_policy::shared> other, bool& is_ok)
        {
            is_ok = other.isOk();

            return other;
        }

        context<Flesh, context_policy::weak>
        weak()
        {
            return context<Flesh, context_policy::weak>(flesh_p_);
        }

        socket_type&
        asio_socket() const
        {
            return flesh_p_->member(typename option::socket());
        }

        ssl_stream_type&
        beast_ssl_stream() const
        {
            return flesh_p_->member(typename option::ssl_stream());
        }

        void
        recv() const
        {
            flesh_p_->recv();
        }

        void
        recv(duration_type const duration) const
        {
            flesh_p_->recv(duration);
        }

        void
        recv(time_point_type const time_point) const
        {
            flesh_p_->recv(time_point);
        }

        template<class _Body, class _Fields>
        void
        send(response_type<_Body, _Fields>& response) const
        {
            flesh_p_->send(response);
        }

        template<class _Body, class _Fields>
        void
        send(response_type<_Body, _Fields>&& response) const
        {
            flesh_p_->send(std::move(response));
        }

        template<class _Body, class _Fields>
        void
        send(response_type<_Body, _Fields>& response,
             duration_type const duration) const
        {
            flesh_p_->send(response, duration);
        }

        template<class _Body, class _Fields>
        void
        send(response_type<_Body, _Fields>&& response,
             duration_type const duration) const
        {
            flesh_p_->send(std::move(response), duration);
        }

        template<class _Body, class _Fields>
        void
        send(response_type<_Body, _Fields>& response,
             time_point_type const time_point) const
        {
            flesh_p_->send(response, time_point);
        }

        template<class _Body, class _Fields>
        void
        send(response_type<_Body, _Fields>&& response,
             time_point_type const time_point) const
        {
            flesh_p_->send(std::move(response), time_point);
        }

        template<class _Body, class _Fields>
        void
        push(response_type<_Body, _Fields>& response) const
        {
            flesh_p_->push(response);
        }

        template<class _Body, class _Fields>
        void
        push(response_type<_Body, _Fields>&& response) const
        {
            flesh_p_->push(std::move(response));
        }

        void
        wait() const
        {
            flesh_p_->wait();
        }

        void
        wait(duration_type const duration) const
        {
            flesh_p_->wait(duration);
        }

        void
        wait(time_point_type const time_point) const
        {
            flesh_p_->wait(time_point);
        }

        void
        timer_cancel() const
        {
            flesh_p_->timer_cancel();
        }

        void
        eof() const
        {
            flesh_p_->eof();
        }

        void
        eof(duration_type const duration) const
        {
            flesh_p_->eof(duration);
        }

        void
        eof(time_point_type const time_point) const
        {
            flesh_p_->eof(time_point);
        }

        void
        force_eof() const
        {
            flesh_p_->force_eof();
        }

        void
        force_cls() const
        {
            flesh_p_->force_cls();
        }

    }; // class context<Flesh, context_policy::shared>

    template<class Flesh>
    class context<Flesh, context_policy::weak>
    {
        std::weak_ptr<Flesh> flesh_p_;

    public:

        context(std::shared_ptr<Flesh> flesh_p)
            : flesh_p_{flesh_p}
        {
        }

        bool
        expired() const
        {
            return flesh_p_.expired();
        }

        context<Flesh, context_policy::shared>
        load() const
        {
            return context<Flesh, context_policy::shared>(flesh_p_.lock());
        }

    }; // class context<Flesh, context_policy::weak>

    template<class Router, class... _OnAction>
    static auto
    handshake(boost::asio::ssl::context&, socket_type&&, Router const&, buffer_type&&,
              _OnAction&&...) -> typename std::decay<decltype (
            BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE(std::declval<Router const&>()),
            std::declval<context_type>())>::type;

    template<class Router, class... _OnAction>
    static auto
    handshake(boost::asio::ssl::context&, socket_type&&, Router const&,
              _OnAction&&...) -> typename std::decay<decltype (
            BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE(std::declval<Router const&>()),
            std::declval<context_type>())>::type;

    template<class Router, class TimePointOrDuration, class... _OnAction>
    static auto
    handshake(boost::asio::ssl::context&, socket_type&&, Router const&,
              TimePointOrDuration const, buffer_type&&, _OnAction&&...) -> typename std::decay<decltype (
            BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE(
                std::declval<Router const&>()).handshake(std::declval<TimePointOrDuration>()),
            std::declval<context_type>())>::type;

    template<class Router, class TimePointOrDuration, class... _OnAction>
    static auto
    handshake(boost::asio::ssl::context&, socket_type&&, Router const&,
              TimePointOrDuration const, _OnAction&&...) -> typename std::decay<decltype (
            BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE(
                std::declval<Router const&>()).handshake(std::declval<TimePointOrDuration>()),
            std::declval<context_type>())>::type;

    template<class... _OnError>
    static auto
    force_eof(boost::asio::ssl::context&, socket_type&&, _OnError&&...) -> decltype (
            void(BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE_LEGACY()));

    template<class... _OnError>
    static auto
    force_cls(boost::asio::ssl::context&, socket_type&&, _OnError&&...) -> decltype (
            void(BEASTHTTP_REACTOR_SSL_SESSION_TRY_INVOKE_FLESH_TYPE_LEGACY()));

}; // class session

namespace _default {

using session_type = session<>;

} // namespace _default
} // namespace ssl
} // namespace reactor
} // namespace http
} // namespace _0xdead4ead

#include <http/reactor/ssl/impl/session.hxx>

#endif // not defined BEASTHTTP_REACTOR_SSL_SESSION_HXX

ext: hxx

max_stars_repo_name: johnfindeed/BeastHttp

max_issues_repo_name: johnfindeed/BeastHttp

max_forks_repo_name: johnfindeed/BeastHttp


text:
//
// Created by Quentin Liardeaux on 10/4/19.
//

#ifndef BABEL_SERVER_SERVERHANDLER_HPP
#define BABEL_SERVER_SERVERHANDLER_HPP

#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <queue>
#include <map>

#include "../NotificationHandler.hpp"
#include "ServerCommunication.hpp"
#include "ServerRequest.hpp"
#include "ServerResponse.hpp"
#include "protocol.h"

class ServerHandler {
public:
    ServerHandler(const std::string &ipAddress, int port, boost::shared_ptr<NotificationHandler> notifHandler);
    ~ServerHandler();

    void start();
    void stop();

    void send(int id, std::map<std::string, void*> userInfo);

    const std::string &getIpAddress() const { return ipAddress_; }
    int getPort() const { return port_; }

private:
    boost::shared_ptr<NotificationHandler> notifHandler_;
    ServerCommunication communicationHandler_;
    ServerRequest requestsHandler_;
    boost::thread requestsThread_;
    boost::thread responsesThread_;
    boost::shared_ptr<boost::mutex> requestsMutex_;
    boost::shared_ptr<std::queue<Message>> requests_;
    boost::shared_ptr<boost::mutex> responsesMutex_;
    boost::shared_ptr<std::queue<Message>> responses_;
    ServerResponse *responsesHandler_;
    std::string ipAddress_;
    int port_;
};

#endif //BABEL_SERVER_SERVERHANDLER_HPP

ext: hpp

max_stars_repo_name: LiardeauxQ/Babel

max_issues_repo_name: LiardeauxQ/Babel

max_forks_repo_name: LiardeauxQ/Babel


text:
#include <gtest/gtest.h>

#include <cucumber-cpp/internal/step/StepMacros.hpp>
#include "../utils/CukeCommandsFixture.hpp"

#include <boost/config.hpp>

using namespace cucumber::internal;

using std::string;

class CukeCommandsTest : public CukeCommandsFixture {
protected:
    void addStepWithMatcher(const std::string &matcher) {
        addStepToManager<EmptyStep>(matcher);
    }
};

class CheckAllParameters : public GenericStep {
protected:
    static const int arg_0_int;
    static const double arg_1_double;
    static const string arg_2_string;
    static const string arg_3_string_with_spaces;

public:
    static InvokeArgs buildInvokeArgs() {
        InvokeArgs mixedArgs;
        mixedArgs.addArg(toString(arg_0_int));
        mixedArgs.addArg(toString(arg_1_double));
        mixedArgs.addArg(toString(arg_2_string));
        mixedArgs.addArg(toString(arg_3_string_with_spaces));
        return mixedArgs;
    }
};

const int CheckAllParameters::arg_0_int(42);
const double CheckAllParameters::arg_1_double(4.2);
const string CheckAllParameters::arg_2_string("fortytwo");
const string CheckAllParameters::arg_3_string_with_spaces("forty two");

class CheckAllParametersWithoutMacro : public CheckAllParameters {
public:
    void body() {
        EXPECT_EQ(arg_0_int, getArgs()->getInvokeArg<int>(0));
        EXPECT_EQ((double)arg_0_int, getArgs()->getInvokeArg<double>(0));
        EXPECT_NO_THROW(getArgs()->getInvokeArg<string>(0));

        EXPECT_EQ((int)arg_1_double, getArgs()->getInvokeArg<int>(1));
        EXPECT_EQ(arg_1_double, getArgs()->getInvokeArg<double>(1));
        EXPECT_NO_THROW(getArgs()->getInvokeArg<string>(1));

        EXPECT_THROW(getArgs()->getInvokeArg<int>(2), std::invalid_argument);
        EXPECT_THROW(getArgs()->getInvokeArg<double>(2), std::invalid_argument);
        EXPECT_EQ(arg_2_string, getArgs()->getInvokeArg<string>(2));

        EXPECT_THROW(getArgs()->getInvokeArg<int>(3), std::invalid_argument);
        EXPECT_THROW(getArgs()->getInvokeArg<double>(3), std::invalid_argument);
        EXPECT_EQ(arg_3_string_with_spaces, getArgs()->getInvokeArg<string>(3));
    }
};

class CheckAllParametersWithMacro : public CheckAllParameters {
public:
    void body() {
        REGEX_PARAM(int, got_arg_0_int);
        EXPECT_EQ(arg_0_int, got_arg_0_int);

        REGEX_PARAM(double, got_arg_1_double);
        EXPECT_EQ(arg_1_double, got_arg_1_double);

        REGEX_PARAM(string, got_arg_2_string);
        EXPECT_EQ(arg_2_string, got_arg_2_string);

        REGEX_PARAM(string, got_arg_3_string_with_spaces);
        EXPECT_EQ(arg_3_string_with_spaces, got_arg_3_string_with_spaces);
    }
};

#ifndef BOOST_NO_VARIADIC_TEMPLATES
class CheckAllParametersWithFuncArgs : public CheckAllParameters {
public:
    void bodyWithArgs(
            const int          got_arg_0_int
          , const double       got_arg_1_double
          , const std::string  got_arg_2_string
          , const std::string& got_arg_3_string_with_spaces
          ) {
        EXPECT_EQ(arg_0_int, got_arg_0_int);
        EXPECT_EQ(arg_1_double, got_arg_1_double);
        EXPECT_EQ(arg_2_string, got_arg_2_string);
        EXPECT_EQ(arg_3_string_with_spaces, got_arg_3_string_with_spaces);
    }

    void body() {
        return invokeWithArgs(*this, &CheckAllParametersWithFuncArgs::bodyWithArgs);
    }
};

TEST_F(CukeCommandsTest, invokeHandlesParametersWithFuncArgs) {
    // The real test is in TestClass::body()
    runStepBodyTest<CheckAllParametersWithFuncArgs>();
}
#endif

TEST_F(CukeCommandsTest, matchesCorrectly) {
    addStepWithMatcher(STATIC_MATCHER);
    MatchResult result = stepMatches(STATIC_MATCHER);
    EXPECT_EQ(stepId, result.getResultSet().at(0).stepInfo->id);
}

TEST_F(CukeCommandsTest, invokeHandlesParametersWithoutMacro) {
    // The real test is in TestClass::body()
    runStepBodyTest<CheckAllParametersWithoutMacro>();
}

TEST_F(CukeCommandsTest, invokeHandlesParametersWithMacro) {
    // The real test is in TestClass::body()
    runStepBodyTest<CheckAllParametersWithMacro>();
}

TEST_F(CukeCommandsTest, producesSnippetsEscapingTitle) {
    EXPECT_EQ("THEN(\"^x\\\\|y\\\"z$\") {\n"
              "    pending();\n"
              "}\n",
              snippetText("then","x|y\"z"));
}

TEST_F(CukeCommandsTest, escapesCaractersInRegexes) {
    //  abc|()[]{}^$*+?.\def  <=  abc\|\(\)\[\]\{\}\^\$\*\+\?\.\\def
    EXPECT_EQ("abc\\|\\(\\)\\[\\]\\{\\}\\^\\$\\*\\+\\?\\.\\\\def", escapeRegex("abc|()[]{}^$*+?.\\def"));
}

TEST_F(CukeCommandsTest, escapesCharactersInCStrings) {
    //  abc\"def\\ghi  <=  abc"def\ghi
    EXPECT_EQ("abc\\\"def\\\\ghi", escapeCString("abc\"def\\ghi"));
}

ext: cpp

max_stars_repo_name: meshell/cucumber-cpp

max_issues_repo_name: meshell/cucumber-cpp

max_forks_repo_name: meshell/cucumber-cpp


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2013-2021 Regents of the University of California.
 *
 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
 *
 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 *
 * You should have received copies of the GNU General Public License and GNU Lesser
 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 */

#ifndef NDN_CXX_UTIL_TIME_HPP
#define NDN_CXX_UTIL_TIME_HPP

#include "ndn-cxx/detail/common.hpp"

#include <boost/asio/wait_traits.hpp>
#include <boost/chrono.hpp>

namespace ndn {
namespace time {

template<typename Rep, typename Period>
using duration = boost::chrono::duration<Rep, Period>;

using boost::chrono::duration_cast;

// C++20
using days   = duration<int_fast32_t, boost::ratio<86400>>;
using weeks  = duration<int_fast32_t, boost::ratio<604800>>;
using months = duration<int_fast32_t, boost::ratio<2629746>>;
using years  = duration<int_fast32_t, boost::ratio<31556952>>;

// C++11
using hours        = boost::chrono::hours;
using minutes      = boost::chrono::minutes;
using seconds      = boost::chrono::seconds;
using milliseconds = boost::chrono::milliseconds;
using microseconds = boost::chrono::microseconds;
using nanoseconds  = boost::chrono::nanoseconds;

/** \return the absolute value of the duration d
 *  \note The function does not participate in the overload resolution
 *        unless std::numeric_limits<Rep>::is_signed is true.
 */
template<typename Rep, typename Period, typename = std::enable_if_t<std::numeric_limits<Rep>::is_signed>>
constexpr duration<Rep, Period>
abs(duration<Rep, Period> d)
{
  return d >= d.zero() ? d : -d;
}

} // namespace time

inline namespace literals {
inline namespace time_literals {

constexpr time::days
operator "" _day(unsigned long long days)
{
  return time::days{days};
}

constexpr time::duration<long double, time::days::period>
operator "" _day(long double days)
{
  return time::duration<long double, time::days::period>{days};
}

constexpr time::days
operator "" _days(unsigned long long days)
{
  return time::days{days};
}

constexpr time::duration<long double, time::days::period>
operator "" _days(long double days)
{
  return time::duration<long double, time::days::period>{days};
}

constexpr time::hours
operator "" _h(unsigned long long hrs)
{
  return time::hours{hrs};
}

constexpr time::duration<long double, time::hours::period>
operator "" _h(long double hrs)
{
  return time::duration<long double, time::hours::period>{hrs};
}

constexpr time::minutes
operator "" _min(unsigned long long mins)
{
  return time::minutes{mins};
}

constexpr time::duration<long double, time::minutes::period>
operator "" _min(long double mins)
{
  return time::duration<long double, time::minutes::period>{mins};
}

constexpr time::seconds
operator "" _s(unsigned long long secs)
{
  return time::seconds{secs};
}

constexpr time::duration<long double, time::seconds::period>
operator "" _s(long double secs)
{
  return time::duration<long double, time::seconds::period>{secs};
}

constexpr time::milliseconds
operator "" _ms(unsigned long long msecs)
{
  return time::milliseconds{msecs};
}

constexpr time::duration<long double, time::milliseconds::period>
operator "" _ms(long double msecs)
{
  return time::duration<long double, time::milliseconds::period>{msecs};
}

constexpr time::microseconds
operator "" _us(unsigned long long usecs)
{
  return time::microseconds{usecs};
}

constexpr time::duration<long double, time::microseconds::period>
operator "" _us(long double usecs)
{
  return time::duration<long double, time::microseconds::period>{usecs};
}

constexpr time::nanoseconds
operator "" _ns(unsigned long long nsecs)
{
  return time::nanoseconds{nsecs};
}

constexpr time::duration<long double, time::nanoseconds::period>
operator "" _ns(long double nsecs)
{
  return time::duration<long double, time::nanoseconds::period>{nsecs};
}

} // inline namespace time_literals
} // inline namespace literals

namespace time {

using namespace literals::time_literals;

/**
 * \brief System clock
 *
 * System clock represents the system-wide real time wall clock.
 *
 * It may not be monotonic: on most systems, the system time can be
 * adjusted at any moment. It is the only clock that has the ability
 * to be displayed and converted to/from UNIX timestamp.
 *
 * To get the current time:
 *
 *
 *     const auto now = system_clock::now();
 *
 *
 * To convert a time_point to/from UNIX timestamp:
 *
 *
 *     system_clock::time_point time = ...;
 *     uint64_t timestampInMilliseconds = toUnixTimestamp(time).count();
 *     system_clock::time_point time2 = fromUnixTimestamp(milliseconds(timestampInMilliseconds));
 *
 */
class system_clock
{
public:
  using duration   = boost::chrono::system_clock::duration;
  using rep        = duration::rep;
  using period     = duration::period;
  using time_point = boost::chrono::time_point<system_clock>;
  static constexpr bool is_steady = boost::chrono::system_clock::is_steady;

  using TimePoint = time_point;
  using Duration = duration;

  static time_point
  now() noexcept;

  static std::time_t
  to_time_t(const time_point& t) noexcept;

  static time_point
  from_time_t(std::time_t t) noexcept;
};

/**
 * \brief Steady clock
 *
 * Steady clock represents a monotonic clock. The time points of this
 * clock cannot decrease as physical time moves forward. This clock is
 * not related to wall clock time, and is best suitable for measuring
 * intervals.
 */
class steady_clock
{
public:
  using duration   = boost::chrono::steady_clock::duration;
  using rep        = duration::rep;
  using period     = duration::period;
  using time_point = boost::chrono::time_point<steady_clock>;
  static constexpr bool is_steady = true;

  using TimePoint = time_point;
  using Duration = duration;

  static time_point
  now() noexcept;

private:
  /**
   * \brief Trait function used in detail::SteadyTimer to select proper waiting time
   *
   * Mock time implementations should return the minimum value to ensure
   * that Boost.Asio doesn't perform any waiting on mock timers.
   *
   * @sa http://blog.think-async.com/2007/08/time-travel.html
   */
  static duration
  to_wait_duration(duration d);

  friend struct boost::asio::wait_traits<steady_clock>; // see steady-timer.hpp
};

/**
 * \brief Return a system_clock::time_point representing the UNIX time epoch,
 *        i.e., 00:00:00 UTC on 1 January 1970.
 */
const system_clock::time_point&
getUnixEpoch();

/**
 * \brief Convert system_clock::time_point to UNIX timestamp
 */
milliseconds
toUnixTimestamp(const system_clock::time_point& point);

/**
 * \brief Convert UNIX timestamp to system_clock::time_point
 */
system_clock::time_point
fromUnixTimestamp(milliseconds duration);

/**
 * \brief Convert to the ISO 8601 string representation, basic format (`YYYYMMDDTHHMMSS,fffffffff`).
 *
 * If \p timePoint does not contain any fractional seconds, the output format is `YYYYMMDDTHHMMSS`.
 *
 * Examples:
 *
 *   - with fractional nanoseconds:  20020131T100001,123456789
 *   - with fractional microseconds: 20020131T100001,123456
 *   - with fractional milliseconds: 20020131T100001,123
 *   - without fractional seconds:   20020131T100001
 */
std::string
toIsoString(const system_clock::time_point& timePoint);

/**
 * \brief Convert from the ISO 8601 basic string format (`YYYYMMDDTHHMMSS,fffffffff`)
 *        to the internal time format.
 *
 * Examples of accepted strings:
 *
 *   - with fractional nanoseconds:  20020131T100001,123456789
 *   - with fractional microseconds: 20020131T100001,123456
 *   - with fractional milliseconds: 20020131T100001,123
 *   - without fractional seconds:   20020131T100001
 */
system_clock::time_point
fromIsoString(const std::string& isoString);

/**
 * \brief Convert to the ISO 8601 string representation, extended format (`YYYY-MM-DDTHH:MM:SS,fffffffff`).
 */
std::string
toIsoExtendedString(const system_clock::time_point& timePoint);

/**
 * \brief Convert from the ISO 8601 extended string format (`YYYY-MM-DDTHH:MM:SS,fffffffff`)
 *        to the internal time format.
 */
system_clock::time_point
fromIsoExtendedString(const std::string& isoString);

/**
 * \brief Convert time point to string with specified format.
 *
 * By default, `%Y-%m-%d %H:%M:%S` is used, producing dates like
 * `2014-04-10 22:51:00`
 *
 * \param timePoint time point of system_clock
 * \param format desired output format (default: `%Y-%m-%d %H:%M:%S`)
 * \param locale desired locale (default: "C" locale)
 *
 * \sa https://www.boost.org/doc/libs/1_65_1/doc/html/date_time/date_time_io.html#date_time.format_flags
 *     describes possible formatting flags
 **/
std::string
toString(const system_clock::time_point& timePoint,
         const std::string& format = "%Y-%m-%d %H:%M:%S",
         const std::locale& locale = std::locale("C"));

/**
 * \brief Convert from string of specified format into time point.
 *
 * By default, `%Y-%m-%d %H:%M:%S` is used, accepting dates like
 * `2014-04-10 22:51:00`
 *
 * \param timePointStr string representing time point
 * \param format input output format (default: `%Y-%m-%d %H:%M:%S`)
 * \param locale input locale (default: "C" locale)
 *
 * \sa https://www.boost.org/doc/libs/1_65_1/doc/html/date_time/date_time_io.html#date_time.format_flags
 *     describes possible formatting flags
 */
system_clock::time_point
fromString(const std::string& timePointStr,
           const std::string& format = "%Y-%m-%d %H:%M:%S",
           const std::locale& locale = std::locale("C"));

} // namespace time
} // namespace ndn

namespace boost {
namespace chrono {

template<typename CharT>
struct clock_string<ndn::time::system_clock, CharT>
{
  static std::basic_string<CharT>
  since();
};

template<typename CharT>
struct clock_string<ndn::time::steady_clock, CharT>
{
  static std::basic_string<CharT>
  since();
};

extern template struct clock_string<ndn::time::system_clock, char>;
extern template struct clock_string<ndn::time::steady_clock, char>;

} // namespace chrono
} // namespace boost

#endif // NDN_CXX_UTIL_TIME_HPP

max_stars_repo_name: Pesa/ndn-cxx

max_issues_repo_name: Pesa/ndn-cxx

max_forks_repo_name: Pesa/ndn-cxx


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef FCPPT_VARIANT_HOLDS_TYPE_HPP_INCLUDED
#define FCPPT_VARIANT_HOLDS_TYPE_HPP_INCLUDED

#include <fcppt/variant/object_impl.hpp>
#include <fcppt/variant/size_type.hpp>
#include <fcppt/variant/detail/index_of.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/mpl/contains.hpp>
#include <fcppt/config/external_end.hpp>

namespace fcppt
{
namespace variant
{

/**
\brief Checks if a type is held by a variant

\ingroup fcpptvariant

The currently held type of a variant is the type passed to its
constructor or assignment operator. A type T can be held by a
variant<Set> if T is a member of Set.

This function checks if \a Type is held by \a _variant.

\tparam Type The type to check for which must be a possible type for the
variant

\tparam Elements The types of the variant

\param _variant The variant to check

\return If the type is held by the variant
*/
template<
	typename Type,
	typename Elements
>
inline
bool
holds_type(
	fcppt::variant::object<
		Elements
	> const &_variant
)
{
	static_assert(
		boost::mpl::contains<
			Elements,
			Type
		>::value,
		"Invalid Type in variant::holds_type"
	);

	return
		_variant.type_index()
		==
		fcppt::variant::detail::index_of<
			Elements,
			Type
		>::value;
}

}
}

#endif

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt


text:
/** @file
 *
 * This file is part of Boost, not part of Chaste per se.
 *
 * We use the <autogenerated> tag to ignore it from our Doxygen checker.
 *
 * This file is provided to users of Boost up to 1.63 inclusive and gives forward compatibility with
 * Boost 1.64-1.65 and hopefully beyond.
 * (An optimisation in exponential distributions was applied to boost in version 1.64,
 * which also affects normal distribution tails.)
 *
 * Minimal changes were made to the file to include it here, simply giving the class a unique name
 * and making it use the Chaste copy of exponential_distribution rather than the boost one.
 *
 */

/* boost random/gamma_distribution.hpp header file
 *
 * Copyright Jens Maurer 2002
 * Copyright Steven Watanabe 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)
 *
 * See http://www.boost.org for most recent version including documentation.
 *
 * $Id$
 *
 */

#ifndef BOOST_165_RANDOM_GAMMA_DISTRIBUTION_HPP
#define BOOST_165_RANDOM_GAMMA_DISTRIBUTION_HPP

#include <boost/assert.hpp>
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/limits.hpp>
#include <boost/random/detail/config.hpp>
//#include <boost/random/exponential_distribution.hpp> // swapped for chaste copy of exponential v1.65
#include <boost/static_assert.hpp>
#include <iosfwd>
#include <istream>
#include "Boost165ExponentialDistribution.hpp"

namespace boost
{
namespace random
{

    // The algorithm is taken from Knuth

    /**
 * The gamma distribution is a continuous distribution with two
 * parameters alpha and beta.  It produces values > 0.
 *
 * It has
 * \f$\displaystyle p(x) = x^{\alpha-1}\frac{e^{-x/\beta}}{\beta^\alpha\Gamma(\alpha)}\f$.
 */
    template <class RealType = double>
    class gamma_distribution_v165
    {
    public:
        typedef RealType input_type;
        typedef RealType result_type;

        class param_type
        {
        public:
            typedef gamma_distribution_v165 distribution_type;

            /**
         * Constructs a @c param_type object from the "alpha" and "beta"
         * parameters.
         *
         * Requires: alpha > 0 && beta > 0
         */
            param_type(const RealType& alpha_arg = RealType(1.0),
                       const RealType& beta_arg = RealType(1.0))
                    : _alpha(alpha_arg), _beta(beta_arg)
            {
            }

            /** Returns the "alpha" parameter of the distribution. */
            RealType alpha() const { return _alpha; }
            /** Returns the "beta" parameter of the distribution. */
            RealType beta() const { return _beta; }

#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
            /** Writes the parameters to a @c std::ostream. */
            template <class CharT, class Traits>
            friend std::basic_ostream<CharT, Traits>&
            operator<<(std::basic_ostream<CharT, Traits>& os,
                       const param_type& parm)
            {
                os << parm._alpha << ' ' << parm._beta;
                return os;
            }

            /** Reads the parameters from a @c std::istream. */
            template <class CharT, class Traits>
            friend std::basic_istream<CharT, Traits>&
            operator>>(std::basic_istream<CharT, Traits>& is, param_type& parm)
            {
                is >> parm._alpha >> std::ws >> parm._beta;
                return is;
            }
#endif

            /** Returns true if the two sets of parameters are the same. */
            friend bool operator==(const param_type& lhs, const param_type& rhs)
            {
                return lhs._alpha == rhs._alpha && lhs._beta == rhs._beta;
            }
            /** Returns true if the two sets fo parameters are different. */
            friend bool operator!=(const param_type& lhs, const param_type& rhs)
            {
                return !(lhs == rhs);
            }

        private:
            RealType _alpha;
            RealType _beta;
        };

#ifndef BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS
        BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);
#endif

        /**
     * Creates a new gamma_distribution with parameters "alpha" and "beta".
     *
     * Requires: alpha > 0 && beta > 0
     */
        explicit gamma_distribution_v165(const result_type& alpha_arg = result_type(1.0),
                                         const result_type& beta_arg = result_type(1.0))
                : _exp(result_type(1)), _alpha(alpha_arg), _beta(beta_arg)
        {
            BOOST_ASSERT(_alpha > result_type(0));
            BOOST_ASSERT(_beta > result_type(0));
            init();
        }

        /** Constructs a @c gamma_distribution from its parameters. */
        explicit gamma_distribution_v165(const param_type& parm)
                : _exp(result_type(1)), _alpha(parm.alpha()), _beta(parm.beta())
        {
            init();
        }

        // compiler-generated copy ctor and assignment operator are fine

        /** Returns the "alpha" paramter of the distribution. */
        RealType alpha() const { return _alpha; }
        /** Returns the "beta" parameter of the distribution. */
        RealType beta() const { return _beta; }
        /** Returns the smallest value that the distribution can produce. */
        RealType min BOOST_PREVENT_MACRO_SUBSTITUTION() const { return 0; }
        /* Returns the largest value that the distribution can produce. */
        RealType max BOOST_PREVENT_MACRO_SUBSTITUTION() const
        {
            return (std::numeric_limits<RealType>::infinity)();
        }

        /** Returns the parameters of the distribution. */
        param_type param() const { return param_type(_alpha, _beta); }
        /** Sets the parameters of the distribution. */
        void param(const param_type& parm)
        {
            _alpha = parm.alpha();
            _beta = parm.beta();
            init();
        }

        /**
     * Effects: Subsequent uses of the distribution do not depend
     * on values produced by any engine prior to invoking reset.
     */
        void reset() { _exp.reset(); }

        /**
     * Returns a random variate distributed according to
     * the gamma distribution.
     */
        template <class Engine>
        result_type operator()(Engine& eng)
        {
#ifndef BOOST_NO_STDC_NAMESPACE
            // allow for Koenig lookup
            using std::tan;
            using std::sqrt;
            using std::exp;
            using std::log;
            using std::pow;
#endif
            if (_alpha == result_type(1))
            {
                return _exp(eng) * _beta;
            }
            else if (_alpha > result_type(1))
            {
                // Can we have a boost::mathconst please?
                const result_type pi = result_type(3.14159265358979323846);
                for (;;)
                {
                    result_type y = tan(pi * uniform_01<RealType>()(eng));
                    result_type x = sqrt(result_type(2) * _alpha - result_type(1)) * y
                        + _alpha - result_type(1);
                    if (x <= result_type(0))
                        continue;
                    if (uniform_01<RealType>()(eng) > (result_type(1) + y * y) * exp((_alpha - result_type(1))
                                                                                * log(x / (_alpha - result_type(1)))
                                                                                - sqrt(result_type(2) * _alpha
                                                                                - result_type(1))
                                                                                * y))
                        continue;
                    return x * _beta;
                }
            }
            else /* alpha < 1.0 */
            {
                for (;;)
                {
                    result_type u = uniform_01<RealType>()(eng);
                    result_type y = _exp(eng);
                    result_type x, q;
                    if (u < _p)
                    {
                        x = exp(-y / _alpha);
                        q = _p * exp(-x);
                    }
                    else
                    {
                        x = result_type(1) + y;
                        q = _p + (result_type(1) - _p) * pow(x, _alpha - result_type(1));
                    }
                    if (u >= q)
                        continue;
                    return x * _beta;
                }
            }
        }

        template <class URNG>
        RealType operator()(URNG& urng, const param_type& parm) const
        {
            return gamma_distribution_v165(parm)(urng);
        }

#ifndef BOOST_RANDOM_NO_STREAM_OPERATORS
        /** Writes a @c gamma_distribution_v165 to a @c std::ostream. */
        template <class CharT, class Traits>
        friend std::basic_ostream<CharT, Traits>&
        operator<<(std::basic_ostream<CharT, Traits>& os,
                   const gamma_distribution_v165& gd)
        {
            os << gd.param();
            return os;
        }

        /** Reads a @c gamma_distribution from a @c std::istream. */
        template <class CharT, class Traits>
        friend std::basic_istream<CharT, Traits>&
        operator>>(std::basic_istream<CharT, Traits>& is, gamma_distribution_v165& gd)
        {
            gd.read(is);
            return is;
        }
#endif

        /**
     * Returns true if the two distributions will produce identical
     * sequences of random variates given equal generators.
     */
        friend bool operator==(const gamma_distribution_v165& lhs,
                               const gamma_distribution_v165& rhs)
        {
            return lhs._alpha == rhs._alpha
                && lhs._beta == rhs._beta
                && lhs._exp == rhs._exp;
        }

        /**
     * Returns true if the two distributions can produce different
     * sequences of random variates, given equal generators.
     */
        friend bool operator!=(const gamma_distribution_v165& lhs,
                               const gamma_distribution_v165& rhs)
        {
            return !(lhs == rhs);
        }

    private:
        /// \cond hide_private_members

        template <class CharT, class Traits>
        void read(std::basic_istream<CharT, Traits>& is)
        {
            param_type parm;
            if (is >> parm)
            {
                param(parm);
            }
        }

        void init()
        {
#ifndef BOOST_NO_STDC_NAMESPACE
            // allow for Koenig lookup
            using std::exp;
#endif
            _p = exp(result_type(1)) / (_alpha + exp(result_type(1)));
        }
        /// \endcond

        exponential_distribution_v165<RealType> _exp;
        result_type _alpha;
        result_type _beta;
        // some data precomputed from the parameters
        result_type _p;
    };

} // namespace random

} // namespace boost

#endif // BOOST_165_RANDOM_GAMMA_DISTRIBUTION_HPP


text:
#include "SignificantShapelets.hh"
#include "TimeSeries.hh"
#include "Utilities.hh"
#include "Version.hh"

#include "distances/DistanceFunctor.hh"
#include "distances/Lp.hh"
#include "distances/Minkowski.hh"

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

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>

#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>

#include <boost/log/utility/formatting_ostream.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>

#include <boost/make_shared.hpp>

#include <boost/program_options.hpp>

#include <boost/shared_ptr.hpp>

#include <boost/timer/timer.hpp>

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <stdexcept>
#include <vector>

#include <cmath>

// Adds colours to the output of the log. This is based on an example
// from StackOverflow [1].
//
// [1]: https://stackoverflow.com/a/38316911/1396991

void formatLogRecord( boost::log::record_view const& r, boost::log::formatting_ostream& o )
{
  namespace logging = boost::log;
  auto severity     = r[ logging::trivial::severity ];

  if( severity )
  {
    switch( severity.get() )
    {
    case logging::trivial::info:
      o << "\033[32m";
      break;
    case logging::trivial::warning:
      o << "\033[33m";
      break;
    case logging::trivial::error:
    case logging::trivial::fatal:
      o << "\033[31m";
      break;
    default:
      break;
    }
  }

  auto timeStamp = logging::extract<boost::posix_time::ptime>("TimeStamp", r);

  o << boost::posix_time::to_simple_string( *timeStamp ) << ": "
    << r[ logging::expressions::smessage ];

  // Restore the default colour
  if( severity )
    o << "\033[0m";
  // Silence compiler warnings if Boost.Log is not present in the
  // platform.
  (void) r;
  (void) o;
}

void setupLogging()
{
  namespace logging = boost::log;
  auto core         = logging::core::get();

  logging::add_common_attributes();

  boost::shared_ptr<logging::sinks::text_ostream_backend> backend
    = boost::make_shared<logging::sinks::text_ostream_backend>();

  backend->add_stream(
    boost::shared_ptr<std::ostream>( &std::clog, []( std::ostream* ) {} )
  );

  backend->auto_flush( true );

  using Sink = logging::sinks::synchronous_sink<logging::sinks::text_ostream_backend>;
  boost::shared_ptr<Sink> sink( new Sink( backend ) );

  sink->set_formatter( &formatLogRecord );
  core->add_sink( sink );
}

std::shared_ptr<DistanceFunctor> selectDistance( const std::string& name )
{
  auto position = name.find( ':' );
  auto metric   = name.substr( 0, position );
  auto power    = position != std::string::npos ? name.substr( position + 1 ) : std::string();
  auto p        = power.empty() ? 2.0 : std::stod( power );

  if( metric == "minkowski" )
    return std::make_shared<MinkowskiDistance>( p );

  else if( metric == "lp" )
    return std::make_shared<LpDistance>( p );

  // Fall back to the default distance here instead of selecting one
  // that does not fit.
  return std::make_shared<MinkowskiDistance>( 2.0 );
}

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

  using namespace boost::program_options;

  bool allShapelets         = false;
  bool standardize          = false;
  bool disablePruning       = false;
  bool mergeTables          = false;
  bool quiet                = false;
  bool removeDuplicates     = false;
  bool withPseudocounts     = false;

  unsigned m = 0; // minimum pattern length
  unsigned M = 0; // maximum pattern length
  unsigned s = 0; // stride
  unsigned l = 0; // label index in time series
  unsigned k = 0; // number of significant shapelets to keep

  std::string excludeColumns;
  std::string distance;
  std::string input;
  std::string output = "-";

  options_description description( "Available options" );
  description.add_options()
    ("help,h"                 , "Show help")
    ("standardize"            , "Standardize data" )
    ("all,a"                  , "Report all shapelets, not just the most significant ones")
    ("merge-tables,t"         , "Merge equal contingency tables")
    ("disable-pruning,p"      , "Disable pruning criterion" )
    ("remove-duplicates,r"    , "Remove duplicates" )
    ("with-pseudocounts,c"    , "Use pseudocounts in contingency tables" )
    ("quiet,q"                , "Disables progress bar" )
    ("min-length,m"           , value<unsigned>( &m )->default_value( 10 ), "Minimum candidate pattern length" )
    ("max-length,M"           , value<unsigned>( &M )->default_value(  0 ), "Maximum candidate pattern length" )
    ("stride,s"               , value<unsigned>( &s )->default_value(  1 ), "Stride" )
    ("label-index,l"          , value<unsigned>( &l )->default_value(  0 ), "Index of label in time series" )
    ("keep,k"                 , value<unsigned>( &k )->default_value(  0 ), "Maximum number of shapelets to keep (0 = unlimited" )
    ("distance,d"             , value<std::string>( &distance )           , "Use non-standard distance function")
    ("exclude-columns,e"      , value<std::string>( &excludeColumns )     , "Columns to exclude for shapelet processing" )
    ("input,i"                , value<std::string>( &input )              , "Training file" )
    ("output,o"               , value<std::string>( &output )             , "Output file (specify '-' for stdout)" );

  positional_options_description positionalOptions;
  positionalOptions.add( "input", 1 );

  variables_map variables;

  store( command_line_parser( argc, argv )
      .options( description )
      .positional( positionalOptions )
      .run(),
    variables );
  notify( variables );

  if( variables.count("help") )
  {
    std::cerr << description << "\n";
    return 0;
  }

  BOOST_LOG_TRIVIAL(info) << "S3M (" << GIT_COMMIT_ID << ")";

  if( variables.count("all") )
  {
    allShapelets = true;

    BOOST_LOG_TRIVIAL(warning) << "You are requesting *all* shapelets to be reported, even insignificant ones";
  }

  if( variables.count("disable-pruning") )
    disablePruning = true;

  if( variables.count("merge-tables") )
    mergeTables = true;

  if( variables.count("quiet") )
    quiet = true;

  if( variables.count("remove-duplicates") )
    removeDuplicates = true;

  if( variables.count("standardize") )
    standardize = true;

  if( variables.count( "with-pseudocounts" ) )
    withPseudocounts = true;

  // Show usage information if no input file has been specified. This is
  // nicer than just ending the program with an exception.
  if( input.empty() )
  {
    std::cerr << "No input file was specified. S3M needs at least an input file\n"
              << "to perform shapelet extraction.\n\n"
              << description << "\n";

    return 0;
  }

  // 1. Read training data ---------------------------------------------

  BOOST_LOG_TRIVIAL(info) << "Loading input from " << input;

  std::vector<unsigned> excludedColumns;
  if( !excludeColumns.empty() )
  {
    BOOST_LOG_TRIVIAL(info) <<  "Excluding the following columns in addition to the label column: "
                            << excludeColumns;

    // Excluded columns can be separated by commas, colons, and
    // semicolons, or a mixture of them.
    auto tokens = split( excludeColumns, std::string( "[,:;]+" ) );
    for( auto&& token : tokens )
    {
      auto value = convert<unsigned>( token );
      excludedColumns.emplace_back( value );
    }
  }

  auto data         = readData( input, l, excludedColumns );
  auto&& timeSeries = data.first;
  auto&& labels     = data.second;

  BOOST_LOG_TRIVIAL(info) << "Read "
                          << timeSeries.size()
                          << " time series from training input file";

  double mu    = 0.0;
  double sigma = 1.0;

  if( standardize )
  {
    BOOST_LOG_TRIVIAL(info) << "Starting data standardization";

    // Store the parameters in order to undo the standardization
    // procedure afterwards.
    std::tie( mu, sigma )
      = standardizeData( timeSeries );

    BOOST_LOG_TRIVIAL(info) << "Finished data standardization";
  }

  // 2. Perform the extraction -----------------------------------------

  boost::timer::cpu_timer timer;

  // Use a fixed window size if only a single parameter has been
  // specified
  if( m > M )
    M = m;

  BOOST_LOG_TRIVIAL(info) << "Extracting shapelets with length "
                          << "[" << m << ":" << M << "]";

  std::vector<long double> thresholds;
  SignificantShapelets significantShapelets( m, M, s );

  // Only set the distance if the user requested a specific one. Else,
  // the default implementation is much faster.
  if( !distance.empty() )
    significantShapelets.setDistance( selectDistance( distance) );

  significantShapelets.disablePruning( disablePruning );             // enable/disable pruning
  significantShapelets.mergeTables( mergeTables );                   // enable/disable merging of contingency tables
  significantShapelets.quiet( quiet );                               // enable/disable progress bar display
  significantShapelets.removeDuplicates( removeDuplicates );         // enable/disable duplicate removal upon extraction
  significantShapelets.reportAllShapelets( allShapelets );           // enable/disable pruning based on significance threshold
  significantShapelets.withPseudocounts( withPseudocounts );         // enable use of pseudocounts for contingency tables

  long double p_tarone = 0.0;
  auto shapelets       = significantShapelets( timeSeries,
                                               labels,
                                               p_tarone,
                                               thresholds );

  timer.stop();

  if( standardize )
  {
    using SignificantShapelet = SignificantShapelets::SignificantShapelet;

    std::transform(
      shapelets.begin(), shapelets.end(), shapelets.begin(),
        [&mu, &sigma] ( SignificantShapelet ss )
        {
          using ValueType  = typename TimeSeries::ValueType;
          auto && shapelet = ss.shapelet;

          std::transform( shapelet.begin(), shapelet.end(), shapelet.begin(),
            [&mu, &sigma] ( ValueType x )
            {
              return (x * sigma) + mu;
            }
          );

          return ss;
        }
    );
  }

  if( withPseudocounts )
    BOOST_LOG_TRIVIAL(info) << "Using pseudocounts for contingency table calculation";

  // 3. Output ---------------------------------------------------------
  //
  // The fiddling with the pointer below is only required in order to
  // be able to handle both file outputs and outputs to `stdout`. C++
  // makes this a very strange case to handle.

  {
    std::ostream* out = &std::cout;
    std::ofstream fout;
    if( output != "-" and not output.empty() )
    {
      fout.open( output );
      out = &fout;
    }

    *out << std::setprecision( 32 );

    *out << "{\n"
         << "  \"parameters\": {\n"
         << "    \"min_length\": "  << m << ",\n"
         << "    \"max_length\": "  << M << ",\n"
         << "    \"stride\": "      << s << ",\n"
         << "    \"standardize\": " << std::boolalpha << standardize << std::noboolalpha << ",\n";

    // Only add this section if we deviated from the default distance.
    // We do not want to clutter up the output.
    if( !distance.empty() )
    {
      // This is a *little* bit inefficient since we already set the
      // functor above, but I do not want to write yet another 'get'
      // function for the significant shapelets class.
      auto functor = selectDistance( distance);

      *out << "    \"distance\": " << "\"" << functor->name() << "\",\n";
    }

    *out << "    \"p_tarone\": "    << p_tarone << ",\n"
         << "    \"version\": "     << "\"" << GIT_COMMIT_ID << "\"\n"
         << "  },\n"
         << "  \"shapelets\": [\n";

    if( k != 0 && k < shapelets.size() )
      shapelets.resize( k );

    for( auto it = shapelets.begin(); it != shapelets.end(); ++it )
    {
      if( it != shapelets.begin() )
        *out << ",\n";

      *out << *it;
    }

    *out << "  ]\n"
         << "}\n";
  }

  BOOST_LOG_TRIVIAL(info) << "Finished shapelet extraction. Total time:" << timer.format() << "\n";
}

ext: cc


text:
#ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_HPP
#define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_HPP

#include <stan/math/prim/meta.hpp>
#include <boost/math/special_functions/beta.hpp>

namespace stan {
namespace math {

inline double inc_beta(double a, double b, double x) {
  using boost::math::ibeta;
  return ibeta(a, b, x);
}

}  // namespace math
}  // namespace stan
#endif

max_stars_repo_name: alashworth/stan-monorepo

max_issues_repo_name: alashworth/stan-monorepo

max_forks_repo_name: alashworth/stan-monorepo


text:
#include <iostream>
#include <algorithm>
#include <boost/lambda/lambda.hpp>

#define SizeOf(array) (sizeof(array)/sizeof(array[0]))

int main()
{
	int array[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, };

	int label = 4;
	const int* isCL = std::find_if(array, array + SizeOf(array), boost::lambda::_1 == label);

	if (isCL != &array[10]) {
		std::cout << *isCL << std::endl;
		std::cout << SizeOf(array) << std::endl;
	} else {
		std::cout << "UnFound" << std::endl;
	}
}

max_stars_repo_name: taku-xhift/labo

max_issues_repo_name: taku-xhift/labo

max_forks_repo_name: taku-xhift/labo


text:
#ifndef SKYLARK_EXCEPTION_HPP
#define SKYLARK_EXCEPTION_HPP

#include <boost/exception/all.hpp>

#include <exception>
#include <string>

const char* const skylark_errmsg[] = {
    "Skylark failure"
    , "Skylark failed while communicating (MPI)"
    , "Skylark failed in a call to Elemental"
    , "Skylark failed due to a unsupported matrix distribution"
    , "Skylark failed in a call to CombBLAS"
    , "Skylark failed in sketching layer"
    , "Skylark failed in nla operation"
    , "Skylark failed when allocating memory in a sketch"
    , "Skylark failed in a call into the Random123 layer"
    , "Skylark failed due to a unsupported base operation"
    , "Skylark failed in I/O calls"
    , "Skylark failed because invalid parameter was passed"
    , "Skylark failed because base classes were used incorrectly"
    , "Skylark failed in ml operation"
};

/// resolves an error_code to a human readable failure message
const char* skylark_strerror(int error_code) {
    return skylark_errmsg[error_code - 100];
}

/// macro defining the beginning of a try block
#define SKYLARK_BEGIN_TRY() try {

/// macro defining the end of a try block
#define SKYLARK_END_TRY()   }

/// throw a skylark exception including file/line information
#define SKYLARK_THROW_EXCEPTION(x) \
    BOOST_THROW_EXCEPTION(x);

/// print exception details to stderr
#define SKYLARK_PRINT_EXCEPTION_DETAILS(ex) \
    std::cerr << boost::diagnostic_information(ex) << std::endl;

/// print the exception trace (if available) to stderr
#define SKYLARK_PRINT_EXCEPTION_TRACE(ex) \
    if (const std::string *trace = \
            boost::get_error_info<skylark::base::stack_trace>(ex)) { \
        std::cerr << *trace << std::endl; \
    }

// catch and print message
#define SKYLARK_CATCH_AND_PRINT(p) \
    catch (const skylark::base::skylark_exception& ex) { \
        if (p == true) SKYLARK_PRINT_EXCEPTION_DETAILS(ex); \
    } \

/// catch a Skylark exception and returns an error code
#define SKYLARK_CATCH_AND_RETURN_ERROR_CODE() \
    catch (const skylark::base::skylark_exception& ex) { \
        if (int const *c = \
                boost::get_error_info<skylark::base::error_code>(ex)) { \
            return *c; \
        } \
    }

/// catch a Skylark exception, keep a pointer to it, and returns an error code
#define SKYLARK_CATCH_COPY_AND_RETURN_ERROR_CODE(ptr) \
    catch (const skylark::base::skylark_exception& ex) { \
        ptr = boost::current_exception();                \
        if (int const *c = \
                boost::get_error_info<skylark::base::error_code>(ex)) { \
            return *c; \
        } \
    }

namespace skylark {
namespace base {

/// predefined structure for error code
typedef boost::error_info<struct tag_error_code, int>         error_code;
/// predefined structure for error msg
typedef boost::error_info<struct tag_error_msg,  std::string> error_msg;

/// predefined structure for trace error (appends messages)
typedef boost::error_info<struct tag_stack_trace,  std::string> stack_trace;
typedef boost::error_info<struct tag_append_trace, std::string> append_trace;

/// define a base exception
struct skylark_exception : virtual boost::exception, virtual std::exception {
    skylark_exception() {
        *this << error_code(100);
    }

    skylark_exception& operator<< (const append_trace& rhs) {
        std::string trace_value = "";

        if (const std::string *cur_trace =
            boost::get_error_info<stack_trace, skylark_exception>(*this) ) {
            trace_value.append(*cur_trace);
            trace_value.append("\n");
        }

        trace_value.append(rhs.value());
        *this << stack_trace(trace_value);
        return *this;
    }
};

/// exceptions thrown by Elemental
struct elemental_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    elemental_exception() {
        *this << error_code(102);
    }
};

/// exceptions thrown by CombBLAS
struct combblas_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    combblas_exception() {
        *this << error_code(104);
    }
};

/// exceptions thrown by Boost MPI
struct mpi_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    mpi_exception() {
        *this << error_code(101);
    }
};

/// exceptions in the sketch layer
struct sketch_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    sketch_exception() {
        *this << error_code(105);
    }
};

/// exceptions in the nla layer
struct nla_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    nla_exception() {
        *this << error_code(106);
    }
};

/// exceptions in the ml layer
struct ml_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    ml_exception() {
        *this << error_code(113);
    }
};

/// exceptions in the Random123 layer
struct random123_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    random123_exception() {
        *this << error_code(108);
    }
};

/// exceptions when doing I/O
struct io_exception : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    io_exception() {
        *this << error_code(110);
    }
};

/// exceptions for allocating memory in sketch layer
struct allocation_exception : virtual sketch_exception  {
 public:
    using sketch_exception::operator<<;

    allocation_exception() {
        *this << error_code(107);
    }
};

/// exceptions for unsupported matrix distributions in Elemental
struct unsupported_matrix_distribution : virtual elemental_exception {
 public:
    using elemental_exception::operator<<;

    unsupported_matrix_distribution() {
        *this << error_code(103);
    }
};

/// exceptions for unsupported base operation
struct unsupported_base_operation : virtual elemental_exception {
 public:
    using skylark_exception::operator<<;

    unsupported_base_operation() {
        *this << error_code(109);
    }
};

/// exceptions for invalid parameters passed
struct invalid_parameters : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    invalid_parameters() {
        *this << error_code(111);
    }
};

/// exceptions for invalid usage of base classes (runtime check that detects
/// bugs)
struct invalid_usage : virtual skylark_exception {
 public:
    using skylark_exception::operator<<;

    invalid_usage() {
        *this << error_code(112);
    }
};

}  // namespace base
}  // namespace skylark

#endif  // SKYLARK_EXCEPTION_HPP

max_stars_repo_name: xdata-skylark/libskylark

max_issues_repo_name: xdata-skylark/libskylark

max_forks_repo_name: xdata-skylark/libskylark


text:
#pragma  once

#include <blockchain/Types.hpp>
#include <blockchain/StorageTypes.hpp>
#include <blockchain/WithdrawTypes.hpp>
#include <fc/optional.hpp>
#include <string>
#include <vector>
#include <set>
#include <boost/uuid/sha1.hpp>

#define PRINTABLE_CHAR(chr) \
if (chr >= 0 && chr <= 9)  \
    chr = chr + '0'; \
else \
    chr = chr + 'a' - 10;

using namespace hsrcore::blockchain;

namespace hsrcore {
    namespace blockchain{

        enum ContractApiType
        {
            chain = 1,
            offline = 2,
            event = 3
        };

        enum ContractState
        {
            valid = 1,
            deleted = 2
        };

        enum ContractLevel
        {
            temp = 1,
            forever = 2
        };

        static std::string to_printable_hex(unsigned char chr)
        {
            unsigned char high = chr >> 4;
            unsigned char low = chr & 0x0F;
            char tmp[16];

            PRINTABLE_CHAR(high);
            PRINTABLE_CHAR(low);

            snprintf(tmp, sizeof(tmp), "%c%c", high, low);
            return string(tmp);
        }

        //the code-related detail of contract
        struct Code
        {
            std::set<std::string> abi;
            std::set<std::string> offline_abi;
            std::set<std::string> events;
            std::map<std::string, fc::enum_type<fc::unsigned_int, hsrcore::blockchain::StorageValueTypes>> storage_properties;
            std::vector<ContractChar> byte_code;
            std::string code_hash;
            Code(const fc::path&);
            Code();
            void SetApis(char* module_apis[], int count, int api_type);
            bool valid() const;
			std::string GetHash() const ;
        };

        struct CodePrintAble
        {
            std::set<std::string> abi;
            std::set<std::string> offline_abi;
            std::set<std::string> events;
            std::map<std::string, std::string> printable_storage_properties;
            std::string printable_code;
            std::string code_hash;

            CodePrintAble(){}

            CodePrintAble(const Code& code) : abi(code.abi), offline_abi(code.offline_abi), events(code.events), code_hash(code.code_hash)
            {
                unsigned char* code_buf = (unsigned char*)malloc(code.byte_code.size());
                FC_ASSERT(code_buf, "malloc failed");

                for (int i = 0; i < code.byte_code.size(); ++i)
                {
                    code_buf[i] = code.byte_code[i];
                    printable_code = printable_code + to_printable_hex(code_buf[i]);
                }

                for (const auto& storage_info : code.storage_properties)
                {
                    std::string storage_type = "unknown type";
                    auto iter = storage_type_map.find(storage_info.second);
                    if (iter != storage_type_map.end())
                        storage_type = iter->second;

                    printable_storage_properties.insert(make_pair(storage_info.first, storage_type));
                }

                free(code_buf);
            }
        };

        //front declaration for typedef
        class ChainInterface;
        struct  ContractEntry;
        struct ContractStorageEntry;
		struct ContractIdEntry;
        //use fc optional to hold the return value
        typedef fc::optional<ContractEntry> oContractEntry;
		typedef fc::optional<ContractIdEntry> oContractIdEntry;
        typedef fc::optional<ContractStorageEntry> oContractStorage;
        typedef fc::optional<ContractIdType> oContractIdType;

        //contract information
        struct  ContractEntry
        {
            ContractName  contract_name; // contract name
            ContractIdType  id; //contract address
            fc::enum_type<fc::unsigned_int, ContractLevel> level = ContractLevel::temp; //the level of the contract
            PublicKeyType owner; //the owner of the contract
            fc::enum_type<fc::unsigned_int, ContractState> state = ContractState::valid; //contract state
            std::string description; //the description of contract
            Code code; // code-related of contract
            fc::optional<uint64_t>    reserved;
            TransactionIdType trx_id;
			fc::time_point register_time;
            //the address string, contain contract address prefix
            std::string id_to_base58()const;

            // database related functions
            static oContractEntry lookup(const ChainInterface&, const ContractIdType&);
            static oContractEntry lookup(const ChainInterface&, const ContractName&);
            static void store(ChainInterface&, const ContractIdType&, const ContractEntry&);
            static void remove(ChainInterface&, const ContractIdType&);

        };

		struct  ContractIdEntry
		{
			ContractIdType id;
			ContractIdEntry() {}
			ContractIdEntry(const ContractIdType &id):id(id) {}

			// database related functions
			static oContractIdEntry lookup(const ChainInterface&, const ContractName&);
			static void store(ChainInterface&, const ContractName&, const ContractIdEntry&);
			static void remove(ChainInterface&, const ContractName&);

		};

        struct ContractEntryPrintable
        {
            ContractName  contract_name; // contract name
            string  id; //contract address
            fc::enum_type<fc::unsigned_int, ContractLevel> level = ContractLevel::temp; //the level of the contract
            PublicKeyType owner; //the owner of the contract
            Address owner_address;  //the owner address of the contract
            string owner_name;  //the owner name of the contract
            fc::enum_type<fc::unsigned_int, ContractState> state = ContractState::valid; //contract state
            std::string description; //the description of contract
            CodePrintAble code_printable; // code-related of contract
            fc::optional<uint64_t>    reserved;
            TransactionIdType trx_id;

            ContractEntryPrintable(){}

            ContractEntryPrintable(const ContractEntry& entry) : contract_name(entry.contract_name), id(entry.id.AddressToString(AddressType::contract_address)), level(entry.level),
                owner(entry.owner), owner_address(entry.owner), state(entry.state), description(entry.description), code_printable(entry.code), reserved(entry.reserved),
                trx_id(entry.trx_id) {}
        };

        //contract storage
        struct ContractStorageEntry
        {
            //std::vector<ContractChar> contract_storage;
            ContractIdType  id; //contract address
            std::map<std::string, StorageDataType> contract_storages;

            static oContractStorage lookup(const ChainInterface&, const ContractIdType&);
            static void store(ChainInterface&, const ContractIdType&, const ContractStorageEntry&);
            static void remove(ChainInterface&, const ContractIdType&);

        };
		struct  ResultTIdEntry;
		typedef fc::optional<ResultTIdEntry> oResultTIdEntry;
		struct ResultTIdEntry
		{
			TransactionIdType res;
			ResultTIdEntry();
			ResultTIdEntry(const TransactionIdType& id);
			static oResultTIdEntry lookup(const ChainInterface&, const TransactionIdType&);
			static void store(ChainInterface&, const TransactionIdType& , const ResultTIdEntry&);
			static void remove(ChainInterface&, const TransactionIdType&);
		};
		struct RequestIdEntry;
		typedef fc::optional<RequestIdEntry> oRequestIdEntry;
		struct RequestIdEntry
		{
			TransactionIdType req;
			RequestIdEntry();
			RequestIdEntry(const TransactionIdType& id);
			static oRequestIdEntry lookup(const ChainInterface&, const TransactionIdType&);
			static void store(ChainInterface&, const TransactionIdType&, const RequestIdEntry&);
			static void remove(ChainInterface&, const TransactionIdType&);

		};
		struct ContractTrxEntry;
		typedef fc::optional<ContractTrxEntry> oContractTrxEntry;
		struct ContractTrxEntry
		{
			TransactionIdType trx_id;
			ContractTrxEntry();
			ContractTrxEntry(const TransactionIdType& id);
			static oContractTrxEntry lookup(const ChainInterface&, const ContractIdType&);
			static void store(ChainInterface&, const ContractIdType&,const ContractTrxEntry&);
			static void remove(ChainInterface&, const ContractIdType&);
		};
		struct ContractinTrxEntry;
		typedef fc::optional<ContractinTrxEntry> oContractinTrxEntry;
		struct ContractinTrxEntry
		{
			ContractIdType contract_id;
			ContractinTrxEntry();
			ContractinTrxEntry(const ContractIdType& id);
			static oContractinTrxEntry lookup(const ChainInterface&, const TransactionIdType&);
			static void store(ChainInterface&, const TransactionIdType&, const ContractinTrxEntry&);
			static void remove(ChainInterface&, const TransactionIdType&);
		};
        class ContractDbInterface
        {

            friend struct ContractEntry;
            friend struct ContractStorageEntry;
			friend struct ResultTIdEntry;
			friend struct RequestIdEntry;
			friend struct ContractinTrxEntry;
			friend struct ContractTrxEntry;
			friend struct ContractIdEntry;
            //lookup related
			virtual oContractIdEntry contractid_lookup_by_name(const ContractName&)const =0;
            virtual  oContractEntry  contract_lookup_by_id(const ContractIdType&)const = 0;
            virtual  oContractEntry  contract_lookup_by_name(const ContractName&)const = 0;
            virtual oContractStorage contractstorage_lookup_by_id(const ContractIdType&)const = 0;
			virtual oResultTIdEntry contract_lookup_resultid_by_reqestid(const TransactionIdType&)const = 0;
			virtual oRequestIdEntry contract_lookup_requestid_by_resultid(const TransactionIdType&)const = 0;
			virtual oContractinTrxEntry contract_lookup_contractid_by_trxid(const TransactionIdType&)const = 0;
			virtual oContractTrxEntry contract_lookup_trxid_by_contract_id(const ContractIdType&)const = 0;

			//insert related
			virtual void contractname_insert_into_id_map(const ContractName&, const ContractIdEntry&)=0;
            virtual void contract_insert_into_id_map(const ContractIdType&, const ContractEntry&) = 0;
            //virtual void contract_insert_into_name_map(const ContractName&, const ContractIdType&) = 0;
            virtual void contractstorage_insert_into_id_map(const ContractIdType&, const ContractStorageEntry&) = 0;
			virtual void contract_store_resultid_by_reqestid(const TransactionIdType& req, const ResultTIdEntry& res) = 0;
			virtual void contract_store_requestid_by_resultid(const TransactionIdType& req, const RequestIdEntry& res) = 0;
			virtual void contract_store_contractid_by_trxid(const TransactionIdType& id, const ContractinTrxEntry& res) = 0;
			virtual void contract_store_trxid_by_contractid(const ContractIdType& id, const ContractTrxEntry & res) = 0;
			//erase related
			virtual void contractname_erase_from_id_map(const ContractName&) =0;
            virtual void contract_erase_from_id_map(const ContractIdType&) = 0;
            //virtual void contract_erase_from_name_map(const ContractName&) = 0;
            virtual void contractstorage_erase_from_id_map(const ContractIdType&) = 0;
			virtual void contract_erase_resultid_by_reqestid(const TransactionIdType& req) = 0;
			virtual void contract_erase_requestid_by_resultid(const TransactionIdType& req) = 0;
			virtual void contract_erase_trxid_by_contract_id(const ContractIdType&) = 0;
			virtual void contract_erase_contractid_by_trxid(const TransactionIdType& req) = 0;

        };
    }
}

FC_REFLECT_ENUM(hsrcore::blockchain::ContractApiType,
    (chain)
    (offline)
    (event)
    )

    FC_REFLECT_ENUM(hsrcore::blockchain::ContractState,
    (valid)
    (deleted)
    )

    FC_REFLECT_ENUM(hsrcore::blockchain::ContractLevel,
    (temp)
    (forever)
    )

    FC_REFLECT(hsrcore::blockchain::Code,
    (abi)
    (offline_abi)
    (events)
    (storage_properties)
    (byte_code)
    (code_hash)
    )

    FC_REFLECT(hsrcore::blockchain::CodePrintAble,
    (abi)
    (offline_abi)
    (events)
    (printable_storage_properties)
    (printable_code)
    (code_hash)
    )

    FC_REFLECT(hsrcore::blockchain::ContractEntry,
    (contract_name)
    (id)
    (level)
    (owner)
    (state)
    (description)
    (code)
    (reserved)
    (trx_id)
    )
	FC_REFLECT(hsrcore::blockchain::ContractIdEntry,
	(id)

	)

    FC_REFLECT(hsrcore::blockchain::ContractEntryPrintable,
    (contract_name)
    (id)
    (level)
    (owner)
    (owner_address)
    (owner_name)
    (state)
    (description)
    (code_printable)
    (reserved)
    (trx_id)
    )

    FC_REFLECT(hsrcore::blockchain::ContractStorageEntry, (id)(contract_storages))
	FC_REFLECT(hsrcore::blockchain::ResultTIdEntry, (res))
	FC_REFLECT(hsrcore::blockchain::RequestIdEntry, (req))
	FC_REFLECT(hsrcore::blockchain::ContractTrxEntry, (trx_id))
	FC_REFLECT(hsrcore::blockchain::ContractinTrxEntry, (contract_id))


text: #include <boost/mpl/aux_/preprocessed/no_ttp/bitor.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//
// MIT License
//
// Copyright 2019-2020
//
// 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.
//
#define BOOST_TEST_MODULE test_suite_cpu_interrupts_v2

#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/test/unit_test.hpp>
#include <vector>

#include "cartridge.hh"
#include "debugger.hh"
#include "log.hh"
#include "nes.hh"

namespace bt = boost::unit_test;
namespace fs = boost::filesystem;

using format = boost::format;

BOOST_AUTO_TEST_CASE(test_suite_nes_test) {
  auto const argc = bt::framework::master_test_suite().argc;
  if (argc <= 1) {
    BOOST_CHECK_MESSAGE(false, "missing required test arguments");
    return;
  }
  auto const argv = bt::framework::master_test_suite().argv;
  auto const file_path = argv[1];

  fs::path const trace_path = fs::temp_directory_path() / fs::unique_path();

  LOG_DEBUG << "test arguments : "
            << "binary [" << file_path << "] "
            << "trace [" << trace_path << "]";

  jones::nes nes(file_path);
  jones::debugger debugger(nes);

  if (nes.power()) {
    nes.run(300);
  }
}

max_stars_repo_name: JonForShort/nes-emulator

max_issues_repo_name: JonForShort/nes-emulator

max_forks_repo_name: JonForShort/nes-emulator


text: #include <boost/proto/functional/range/end.hpp>