text:
//
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BEAST_HTTP_HEADERS_PARSER_V1_HPP
#define BEAST_HTTP_HEADERS_PARSER_V1_HPP

#include <beast/http/basic_parser_v1.hpp>
#include <beast/http/concepts.hpp>
#include <beast/http/message.hpp>
#include <beast/core/error.hpp>
#include <boost/assert.hpp>
#include <string>
#include <type_traits>
#include <utility>

namespace beast {
namespace http {

namespace detail {

struct request_parser_base
{
    std::string method_;
    std::string uri_;
};

struct response_parser_base
{
    std::string reason_;
};

} // detail

/** A parser for a HTTP/1 request or response header.

    This class uses the HTTP/1 wire format parser to
    convert a series of octets into a request or
    response @ref header.

    @note A new instance of the parser is required for each message.
*/
template<bool isRequest, class Fields>
class header_parser_v1
    : public basic_parser_v1<isRequest,
        header_parser_v1<isRequest, Fields>>
    , private std::conditional<isRequest,
        detail::request_parser_base,
            detail::response_parser_base>::type
{
public:
    /// The type of the header this parser produces.
    using header_type = header<isRequest, Fields>;

private:
    // VFALCO Check Fields requirements?

    std::string field_;
    std::string value_;
    header_type h_;
    bool flush_ = false;

public:
    /// Default constructor
    header_parser_v1() = default;

    /// Move constructor
    header_parser_v1(header_parser_v1&&) = default;

    /// Copy constructor (disallowed)
    header_parser_v1(header_parser_v1 const&) = delete;

    /// Move assignment (disallowed)
    header_parser_v1& operator=(header_parser_v1&&) = delete;

    /// Copy assignment (disallowed)
    header_parser_v1& operator=(header_parser_v1 const&) = delete;

    /** Construct the parser.

        @param args Forwarded to the header constructor.
    */
#if GENERATING_DOCS
    template<class... Args>
    explicit
    header_parser_v1(Args&&... args);
#else
    template<class Arg1, class... ArgN,
        class = typename std::enable_if<! std::is_same<
            typename std::decay<Arg1>::type, header_parser_v1>::value>>
    explicit
    header_parser_v1(Arg1&& arg1, ArgN&&... argn)
        : h_(std::forward<Arg1>(arg1),
            std::forward<ArgN>(argn)...)
    {
    }
#endif

    /** Returns the parsed header

        Only valid if @ref complete would return `true`.
    */
    header_type const&
    get() const
    {
        return h_;
    }

    /** Returns the parsed header.

        Only valid if @ref complete would return `true`.
    */
    header_type&
    get()
    {
        return h_;
    }

    /** Returns ownership of the parsed header.

        Ownership is transferred to the caller. Only
        valid if @ref complete would return `true`.

        Requires:
            @ref header_type is @b MoveConstructible
    */
    header_type
    release()
    {
        static_assert(std::is_move_constructible<decltype(h_)>::value,
            "MoveConstructible requirements not met");
        return std::move(h_);
    }

private:
    friend class basic_parser_v1<isRequest, header_parser_v1>;

    void flush()
    {
        if(! flush_)
            return;
        flush_ = false;
        BOOST_ASSERT(! field_.empty());
        h_.fields.insert(field_, value_);
        field_.clear();
        value_.clear();
    }

    void on_start(error_code&)
    {
    }

    void on_method(boost::string_ref const& s, error_code&)
    {
        this->method_.append(s.data(), s.size());
    }

    void on_uri(boost::string_ref const& s, error_code&)
    {
        this->uri_.append(s.data(), s.size());
    }

    void on_reason(boost::string_ref const& s, error_code&)
    {
        this->reason_.append(s.data(), s.size());
    }

    void on_request_or_response(std::true_type)
    {
        h_.method = std::move(this->method_);
        h_.url = std::move(this->uri_);
    }

    void on_request_or_response(std::false_type)
    {
        h_.status = this->status_code();
        h_.reason = std::move(this->reason_);
    }

    void on_request(error_code& ec)
    {
        on_request_or_response(
            std::integral_constant<bool, isRequest>{});
    }

    void on_response(error_code& ec)
    {
        on_request_or_response(
            std::integral_constant<bool, isRequest>{});
    }

    void on_field(boost::string_ref const& s, error_code&)
    {
        flush();
        field_.append(s.data(), s.size());
    }

    void on_value(boost::string_ref const& s, error_code&)
    {
        value_.append(s.data(), s.size());
        flush_ = true;
    }

    void
    on_header(std::uint64_t, error_code&)
    {
        flush();
        h_.version = 10 * this->http_major() + this->http_minor();
    }

    body_what
    on_body_what(std::uint64_t, error_code&)
    {
        return body_what::pause;
    }

    void on_body(boost::string_ref const&, error_code&)
    {
    }

    void on_complete(error_code&)
    {
    }
};

} // http
} // beast

#endif

max_stars_repo_name: AgreeTechnology/ABC

max_issues_repo_name: AgreeTechnology/ABC

max_forks_repo_name: AgreeTechnology/ABC


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

#include <hpx/hpx.hpp>
#include <hpx/hpx_init.hpp>
#include <hpx/include/threads.hpp>
#include <hpx/util/lightweight_test.hpp>

#if HPX_ACTION_ARGUMENT_LIMIT < 10
#error "Please define HPX_ACTION_ARGUMENT_LIMIT to be at least 10."
#endif

#include <hpx/components/dataflow/dataflow.hpp>
#include <hpx/components/dataflow/dataflow_trigger.hpp>

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/repeat.hpp>
#include <boost/preprocessor/stringize.hpp>

using boost::program_options::variables_map;
using boost::program_options::options_description;
using boost::program_options::value;

// TODO: Make this test run in distributed.

///////////////////////////////////////////////////////////////////////////////
int f(int i, int j)
{
    return i + j;
}
typedef hpx::actions::action<int (*)(int, int), &f> f_action;
HPX_REGISTER_PLAIN_ACTION(f_action);

int h(int i, int j)
{
    return i + j;
}
typedef hpx::actions::action<int (*)(int, int), &h> h_action;
HPX_REGISTER_PLAIN_ACTION(h_action);

int g()
{
    int i = 9000;
    return ++i;
}
typedef hpx::actions::action<int (*)(), &g> g_action;
HPX_REGISTER_PLAIN_ACTION(g_action);

bool called_trigger = false;
void trigger()
{
    called_trigger = true;
}
typedef hpx::actions::action<void (*)(), &trigger> trigger_action;
HPX_REGISTER_PLAIN_ACTION(trigger_action);

boost::uint64_t id(boost::uint64_t i)
{
    //std::cout << i << "\n";
    return i;
}
typedef hpx::actions::action<boost::uint64_t (*)(boost::uint64_t), &id> id_action;
HPX_REGISTER_PLAIN_ACTION(id_action);

boost::uint64_t add(boost::uint64_t n1, boost::uint64_t n2)
{
    //std::cout << n1 << " + " << n2 << "\n";
    return n1 + n2;
}
typedef hpx::actions::action<
    boost::uint64_t (*)(boost::uint64_t, boost::uint64_t), &add> add_action;
HPX_REGISTER_PLAIN_ACTION(add_action);

///////////////////////////////////////////////////////////////////////////////
hpx::lcos::dataflow_base<boost::uint64_t> fib(boost::uint64_t n)
{
    if(n < 2)
        return hpx::lcos::dataflow<id_action>(hpx::find_here(), n);
    return hpx::lcos::dataflow<add_action>(hpx::find_here(), fib(n-1), fib(n-2));
}

#define M0(Z, N, D)                                                           \
    bool BOOST_PP_CAT(called_f, N) = false;                                   \
    void BOOST_PP_CAT(f, N)()                                                 \
    {                                                                         \
        BOOST_PP_CAT(called_f, N) = true;                                     \
    }                                                                         \
    typedef hpx::actions::action<void (*)(), &BOOST_PP_CAT(f, N)>       \
        BOOST_PP_CAT(BOOST_PP_CAT(f, N), action);                             \
    HPX_REGISTER_PLAIN_ACTION(BOOST_PP_CAT(BOOST_PP_CAT(f, N), action));      \
/**/

BOOST_PP_REPEAT(5, M0, _)

///////////////////////////////////////////////////////////////////////////////
int hpx_main(variables_map & vm)
{
    hpx::naming::id_type here = hpx::find_here();

    {
        boost::uint64_t n = 10;

        hpx::lcos::dataflow<g_action> a(here);
        hpx::lcos::dataflow<g_action> b(here);
        hpx::lcos::dataflow<f_action> c(here, a, b);

        // blocks until the result is delivered! (constructs a future and sets
        // this as the target of the dataflow)
        HPX_TEST_EQ(18002, c.get_future().get());

        HPX_TEST_EQ(55u, fib(n).get_future().get());

        HPX_TEST_EQ(n, hpx::lcos::dataflow<id_action>(here, n).get_future().get());
        hpx::lcos::dataflow_base<boost::uint64_t> d = hpx::lcos::dataflow<id_action>(here, n);
        HPX_TEST_EQ(n, d.get_future().get());

        HPX_TEST_EQ(9005, hpx::lcos::dataflow<h_action>(here, a, 4).get_future().get());
        HPX_TEST_EQ(9006, hpx::lcos::dataflow<h_action>(here, 5, b).get_future().get());
        HPX_TEST_EQ(9001, hpx::lcos::dataflow<g_action>(here,
            hpx::lcos::dataflow<trigger_action>(here)).get_future().get());
        HPX_TEST(called_trigger);
        called_trigger = false;

        std::vector<hpx::lcos::dataflow_base<void> > trigger;
        trigger.push_back(hpx::lcos::dataflow<f0action>(here));
        trigger.push_back(hpx::lcos::dataflow<f1action>(here));
        trigger.push_back(hpx::lcos::dataflow<f2action>(here));
        trigger.push_back(hpx::lcos::dataflow<f3action>(here));
        trigger.push_back(hpx::lcos::dataflow<f4action>(here));

        hpx::lcos::dataflow_trigger(here, trigger).get_future().get();
        HPX_TEST(called_f0);
        HPX_TEST(called_f1);
        HPX_TEST(called_f2);
        HPX_TEST(called_f3);
        HPX_TEST(called_f4);
        called_f0 = false;
        called_f1 = false;
        called_f2 = false;
        called_f3 = false;
        called_f4 = false;
        hpx::lcos::future<void> f0 = hpx::lcos::dataflow<f0action>(here).get_future();
        hpx::lcos::future<void> f1 = hpx::lcos::dataflow<f1action>(here).get_future();
        hpx::lcos::future<void> f2 = hpx::lcos::dataflow<f2action>(here).get_future();
        hpx::lcos::future<void> f3 = hpx::lcos::dataflow<f3action>(here).get_future();
        hpx::lcos::future<void> f4 = hpx::lcos::dataflow<f4action>(here).get_future();
        f0.get();
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        HPX_TEST(called_f0);
        HPX_TEST(called_f1);
        HPX_TEST(called_f2);
        HPX_TEST(called_f3);
        HPX_TEST(called_f4);

        /*
        hpx::lcos::dataflow<f9action>(
            here, hpx::lcos::dataflow_trigger(here, trigger)).get_future().get();
        HPX_TEST(called_f1);
        HPX_TEST(called_f2);
        HPX_TEST(called_f3);
        HPX_TEST(called_f4);
        HPX_TEST(called_f5);
        HPX_TEST(called_f6);
        HPX_TEST(called_f7);
        HPX_TEST(called_f8);
        HPX_TEST(called_f9);
        */

        //hpx::cout << "entering destruction test scope\n" << hpx::flush;
        {
            hpx::lcos::dataflow<f_action>(
                here
              , hpx::lcos::dataflow<g_action>(here)
              , hpx::lcos::dataflow<g_action>(here)
            ).get_future().get();

            hpx::lcos::dataflow<f1action>(
                here
              , hpx::lcos::dataflow<f2action>(
                    here
                  , hpx::lcos::dataflow<f3action>(
                        here
                      , hpx::lcos::dataflow<f4action>(
                            here
                        )
                    )
                )
            ).get_future().get();
        }
        //hpx::cout << "leaving destruction test scope\n" << hpx::flush;
    }
    //hpx::cout << "end of hpx_main\n" << hpx::flush;
    hpx::finalize();

    return hpx::util::report_errors();
}

int main(int argc, char ** argv)
{
    options_description cmdline("usage: " HPX_APPLICATION_STRING " [options]");

    // We force this test to use several threads by default.
    using namespace boost::assign;
    std::vector<std::string> cfg;
    cfg += "hpx.os_threads=" +
        boost::lexical_cast<std::string>(hpx::threads::hardware_concurrency());

    // Initialize and run HPX
    return hpx::init(cmdline, argc, argv, cfg);
}

ext: cpp


text:
#include "input.h"

#include <unordered_set>

#include <boost/config.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/date_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>

#include "util/error_code.h"
#include "util/validation.h"
#include "calendar_visit.h"

rows::Problem util::LoadProblem(const std::string &problem_path, std::shared_ptr<rows::Printer> printer) {
    boost::filesystem::path problem_file(boost::filesystem::canonical(problem_path));
    std::ifstream problem_stream;
    problem_stream.open(problem_file.c_str());
    if (!problem_stream.is_open()) {
        throw util::ApplicationError((boost::format("Failed to open the file: %1%") % problem_file).str(),
                                     util::ErrorCode::ERROR);
    }

    nlohmann::json problem_json;
    try {
        problem_stream >> problem_json;
    } catch (...) {
        throw util::ApplicationError((boost::format("Failed to open the file: %1%") % problem_file).str(),
                                     boost::current_exception_diagnostic_information(),
                                     util::ErrorCode::ERROR);
    }

    try {
        rows::Problem::JsonLoader json_loader;
        const auto initial_problem = json_loader.Load(problem_json);

        std::vector<rows::CalendarVisit> visits_to_use;
        for (const auto &visit : initial_problem.visits()) {
            if (visit.duration().total_seconds() > 0) {
                visits_to_use.push_back(visit);
            }
        }

        LOG_IF(WARNING, visits_to_use.size() != initial_problem.visits().size()) << "Removed "
                                                                                << initial_problem.visits().size() -
                                                                                visits_to_use.size() << " visits ";

        return rows::Problem(std::move(visits_to_use), initial_problem.carers(), initial_problem.service_users());
    } catch (const std::domain_error &ex) {
        throw util::ApplicationError(
                (boost::format("Failed to parse the file %1% due to error: '%2%'") % problem_file %
                 ex.what()).str(),
                util::ErrorCode::ERROR);
    }
}

rows::Problem util::LoadReducedProblem(const std::string &problem_path,
                                       const std::string &scheduling_date_string,
                                       std::shared_ptr<rows::Printer> printer) {
    const auto problem = LoadProblem(problem_path, printer);

    const std::pair<boost::posix_time::ptime, boost::posix_time::ptime> timespan_pair = problem.Timespan();
    const auto begin_date = timespan_pair.first.date();
    const auto end_date = timespan_pair.second.date();

    if (scheduling_date_string.empty()) {
        if (begin_date < end_date) {
            printer->operator<<(
                    (boost::format("Problem contains records from several days."
                                   " The computed solution will be reduced to a single day: '%1%'")
                     % begin_date).str());

            return problem.Trim(timespan_pair.first, boost::posix_time::hours(24));
        }

        return problem;
    }

    const boost::posix_time::ptime scheduling_time{boost::gregorian::from_simple_string(scheduling_date_string)};
    const auto scheduling_date = scheduling_time.date();
    if (begin_date == end_date && begin_date == scheduling_date) {
        return problem;
    } else if (begin_date <= scheduling_date && scheduling_date <= end_date) {
        return problem.Trim(scheduling_time, boost::posix_time::hours(24));
    } else {
        throw util::ApplicationError(
                (boost::format("Scheduling day '%1%' does not fin into the interval ['%2%','%3%']")
                 % scheduling_date
                 % timespan_pair.first
                 % timespan_pair.second).str(),
                util::ErrorCode::ERROR);
    }
}

bool util::ValidateConsoleFormat(const char *flagname, const std::string &value) {
    std::string value_to_use{value};
    util::string::Strip(value_to_use);
    util::string::ToLower(value_to_use);
    return value_to_use == JSON_FORMAT || value_to_use == TEXT_FORMAT || value_to_use == LOG_FORMAT;
}

std::shared_ptr<rows::Printer> util::CreatePrinter(const std::string &format) {
    auto format_to_use = format;
    util::string::Strip(format_to_use);
    util::string::ToLower(format_to_use);
    if (format_to_use == JSON_FORMAT) {
        return std::make_shared<rows::JsonPrinter>();
    }

    if (format_to_use == TEXT_FORMAT) {
        return std::make_shared<rows::ConsolePrinter>();
    }

    if (format_to_use == LOG_FORMAT) {
        return std::make_shared<rows::LogPrinter>();
    }

    throw util::ApplicationError("Unknown console format.", util::ErrorCode::ERROR);
}

osrm::EngineConfig util::CreateEngineConfig(const std::string &maps_file) {
    osrm::EngineConfig config;
    config.storage_config = osrm::StorageConfig(maps_file);
    config.use_shared_memory = false;
    config.algorithm = osrm::EngineConfig::Algorithm::MLD;

    if (!config.IsValid()) {
        throw util::ApplicationError("Invalid Open Street Map engine configuration", util::ErrorCode::ERROR);
    }

    return config;
}

rows::Solution util::LoadSolution(const std::string &solution_path,
                                  const rows::Problem &problem,
                                  const boost::posix_time::time_duration &visit_time_window) {
    boost::filesystem::path solution_file(boost::filesystem::canonical(solution_path));
    std::ifstream solution_stream;
    solution_stream.open(solution_file.c_str());
    if (!solution_stream.is_open()) {
        throw util::ApplicationError((boost::format("Failed to open the file: %1%") % solution_file).str(),
                                     util::ErrorCode::ERROR);
    }

    rows::Solution original_solution;
    const std::string file_extension{solution_file.extension().string()};
    if (file_extension == ".json") {
        nlohmann::json solution_json;
        try {
            solution_stream >> solution_json;
        } catch (...) {
            throw util::ApplicationError((boost::format("Failed to open the file: %1%") % solution_file).str(),
                                         boost::current_exception_diagnostic_information(),
                                         util::ErrorCode::ERROR);
        }

        try {
            rows::Solution::JsonLoader json_loader;
            original_solution = json_loader.Load(solution_json);
        } catch (const std::domain_error &ex) {
            throw util::ApplicationError(
                    (boost::format("Failed to parse the file '%1%' due to error: '%2%'") % solution_file %
                     ex.what()).str(),
                    util::ErrorCode::ERROR);
        }
    } else if (file_extension == ".gexf") {
        rows::Solution::XmlLoader xml_loader;
        original_solution = xml_loader.Load(solution_file.string());
    } else {
        throw util::ApplicationError(
                (boost::format("Unknown file format: '%1%'. Use 'json' or 'gexf' format instead.")
                 % file_extension).str(), util::ErrorCode::ERROR);
    }

    const auto time_span = problem.Timespan();
    return original_solution.Trim(time_span.first - visit_time_window, time_span.second + visit_time_window);
}

boost::posix_time::time_duration util::GetTimeDurationOrDefault(const std::string &text,
                                                                boost::posix_time::time_duration default_value) {
    if (text.empty()) {
        return default_value;
    }
    return boost::posix_time::duration_from_string(text);
}

rows::HumanPlannerSchedule util::LoadHumanPlannerSchedule(const std::string &schedule_path) {
    std::ifstream stream;
    stream.open(schedule_path);
    if (!stream.is_open()) {
        throw util::ApplicationError((boost::format("Failed to open the file: %1%") % schedule_path).str(),
                                     util::ErrorCode::ERROR);
    }

    nlohmann::json json;
    try {
        stream >> json;
        return json.get<rows::HumanPlannerSchedule>();
    } catch (...) {
        throw util::ApplicationError((boost::format("Failed to open the file: %1%") % schedule_path).str(),
                                     boost::current_exception_diagnostic_information(),
                                     util::ErrorCode::ERROR);
    }
}

void util::string::Strip(std::string &text) {
    static const std::regex NON_PRINTABLE_CHARACTER_PATTERN{"[\\W]"};
    text = std::regex_replace(text, NON_PRINTABLE_CHARACTER_PATTERN, "");
}

void util::string::ToLower(std::string &text) {
    static const std::locale CURRENT_LOCALE("");

    std::transform(std::begin(text), std::end(text), std::begin(text),
                   [](auto character) {
                       return std::tolower(character, CURRENT_LOCALE);
                   });
}

max_stars_repo_name: pmateusz/cordia

max_issues_repo_name: pmateusz/cordia

max_forks_repo_name: pmateusz/cordia


text:
// -----------------------------------------------------------------------------
// Copyright (c) 2015-2018 Benjamin Buch
//
// https://github.com/bebuch/mitrax
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
// -----------------------------------------------------------------------------
#define BOOST_TEST_MODULE mitrax make_matrix
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>

#include <mitrax/matrix/view.hpp>

#include <array>
#include <vector>
#include <complex>
#include <iostream>

#define BT BOOST_TEST

using namespace mitrax;
using namespace mitrax::literals;

template < typename T >
auto rt_id(T&& v){
	return boost::typeindex::type_id_runtime(static_cast< T&& >(v));
}

template < typename T >
auto const id = boost::typeindex::type_id< T >();

template < typename Matrix, size_t RefC, size_t RefR >
constexpr bool check_fn(
	Matrix& m,
	value_type_t< Matrix > const(&ref)[RefR][RefC]
){
	using value_type = value_type_t< Matrix >;

	bool res = true;
	res &= m.cols() == cols< col_t(RefC) >();
	res &= m.rows() == rows< row_t(RefR) >();

	for(size_t y = 0; y < RefR; ++y){
		for(size_t x = 0; x < RefC; ++x){
			res &= m(c_t(x), r_t(y)) == ref[y][x];
		}
	}

	if constexpr(Matrix::ct_cols == 1_C || Matrix::ct_rows == 1_R){
		auto vec_ref =
			reinterpret_cast< value_type const(&)[RefC * RefR] >(ref);

		for(size_t i = 0; i < RefC * RefR; ++i){
			res &= m[d_t(i)] == vec_ref[i];
		}
	}

	if constexpr(Matrix::ct_cols == 1_C && Matrix::ct_rows == 1_R){
		res &= static_cast< value_type >(m) == ref[0][0];
	}

	return res;
}

template < typename M, col_t C, row_t R, size_t RefC, size_t RefR >
constexpr bool check(
	matrix< M, C, R > const& m,
	value_type_t< M > const(&ref)[RefR][RefC]
){
	return check_fn(m, ref);
}

template < typename M, col_t C, row_t R, size_t RefC, size_t RefR >
constexpr bool check(
	matrix< M, C, R >& m,
	value_type_t< M > const(&ref)[RefR][RefC]
){
	auto const& m_const = m;
	return check_fn(m, ref) && check(m_const, ref);
}

template < typename T >
struct fn_xy_t{
	template < typename T1, typename T2 >
	constexpr T operator()(T1 x, T2 y)const noexcept{
		return size_t(x) + size_t(y) * 10;
	}
};

template < typename T >
struct fn_x_t{
	template < typename T1 >
	constexpr T operator()(T1 i)const noexcept{
		return size_t(i) * 10;
	}
};

template < typename T >
struct fn_y_t{
	template < typename T1 >
	constexpr T operator()(T1 i)const noexcept{
		return size_t(i);
	}
};

template < typename T >
struct fn_i_t{
	template < typename T1 >
	constexpr T operator()(T1 i)const noexcept{
		return size_t(i) + size_t(i) * 10;
	}
};

BOOST_AUTO_TEST_SUITE(suite_make_matrix)

using types = boost::mpl::list< int, double, std::complex< float > >;

using objects = boost::mpl::list< int[4], std::array< int, 4 >, std::vector< int > >;

BOOST_AUTO_TEST_CASE_TEMPLATE(test_view_matrix_iter, Object, objects){
	using type = detail::view_matrix_impl< Object, true, 3_C, 3_R >;
	static_assert(has_iterator_fn_v< type >);
	static_assert(has_data_v< int*, type >);
	static_assert(has_iterator_fn_v< type const >);
	static_assert(has_data_v< int const*, type const >);

	using const_type = detail::const_view_matrix_impl< Object, true, 3_C, 3_R >;
	static_assert(has_iterator_fn_v< const_type >);
	static_assert(has_data_v< int const*, const_type >);
	static_assert(has_iterator_fn_v< const_type const >);
	static_assert(has_data_v< int const*, const_type const >);

	using non_const_t_only_const_data = detail::view_matrix_impl<
		detail::const_view_matrix_impl< Object, true, 3_C, 3_R >,
		true, 3_C, 3_R >;
	static_assert(has_iterator_fn_v< non_const_t_only_const_data >);
	static_assert(has_data_v< int const*, non_const_t_only_const_data >);
	static_assert(has_iterator_fn_v< non_const_t_only_const_data const >);
	static_assert(has_data_v< int const*, non_const_t_only_const_data const >);
}

BOOST_AUTO_TEST_CASE(test_view_matrix_iter2){
}

BOOST_AUTO_TEST_CASE_TEMPLATE(test_view_matrix_types, Object, objects){
	using detail::view_matrix_impl;
	using detail::const_view_matrix_impl;

	BT((
		id< view_matrix< Object, true, 1_C, 4_R > > ==
		id< matrix< view_matrix_impl< Object, true, 1_C, 4_R >, 1_C, 4_R > >
	));

	BT((
		id< view_bitmap< Object, true > > ==
		id< bitmap< view_matrix_impl< Object, true, 0_C, 0_R > > >
	));

	BT((
		id< view_col_vector< Object, true, 4_R > > ==
		id< col_vector< view_matrix_impl< Object, true, 1_C, 4_R >, 4_R > >
	));

	BT((
		id< view_col_vector< Object, true, 4_R > > ==
		id< matrix< view_matrix_impl< Object, true, 1_C, 4_R >, 1_C, 4_R > >
	));

	BT((
		id< view_row_vector< Object, true, 4_C > > ==
		id< row_vector< view_matrix_impl< Object, true, 4_C, 1_R >, 4_C > >
	));

	BT((
		id< view_row_vector< Object, true, 4_C > > ==
		id< matrix< view_matrix_impl< Object, true, 4_C, 1_R >, 4_C, 1_R > >
	));

	BT((
		id< view_square_matrix< Object, true, 2_D > > ==
		id< square_matrix< view_matrix_impl< Object, true, 2_C, 2_R >, 2_D > >
	));

	BT((
		id< view_square_matrix< Object, true, 2_D > > ==
		id< matrix< view_matrix_impl< Object, true, 2_C, 2_R >, 2_C, 2_R > >
	));

	BT((
		id< const_view_matrix< Object, true, 1_C, 4_R > > ==
		id< matrix< const_view_matrix_impl< Object, true, 1_C, 4_R >,
			1_C, 4_R > >
	));

	BT((
		id< const_view_bitmap< Object, true > > ==
		id< bitmap< const_view_matrix_impl< Object, true, 0_C, 0_R > > >
	));

	BT((
		id< const_view_col_vector< Object, true, 4_R > > ==
		id< col_vector< const_view_matrix_impl< Object, true, 1_C, 4_R >,
			4_R > >
	));

	BT((
		id< const_view_col_vector< Object, true, 4_R > > ==
		id< matrix< const_view_matrix_impl< Object, true, 1_C, 4_R >,
			1_C, 4_R > >
	));

	BT((
		id< const_view_row_vector< Object, true, 4_C > > ==
		id< row_vector< const_view_matrix_impl< Object, true, 4_C, 1_R >,
			4_C > >
	));

	BT((
		id< const_view_row_vector< Object, true, 4_C > > ==
		id< matrix< const_view_matrix_impl< Object, true, 4_C, 1_R >,
			4_C, 1_R > >
	));

	BT((
		id< const_view_square_matrix< Object, true, 2_D > > ==
		id< square_matrix< const_view_matrix_impl< Object, true, 2_C, 2_R >,
			2_D > >
	));

	BT((
		id< const_view_square_matrix< Object, true, 2_D > > ==
		id< matrix< const_view_matrix_impl< Object, true, 2_C, 2_R >,
			2_C, 2_R > >
	));
}

BOOST_AUTO_TEST_CASE_TEMPLATE(test_view_matrix_3x3, T, types){
	T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
	T init_ca[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
	std::array< T, 9 > init_a{{0, 1, 2, 3, 4, 5, 6, 7, 8}};
	std::vector< T > init_v{0, 1, 2, 3, 4, 5, 6, 7, 8};

	auto m01 = make_view_matrix(3_CS, 3_RS, init_ca);
	auto m02 = make_view_matrix(3_CD, 3_RS, init_ca);
	auto m03 = make_view_matrix(3_CS, 3_RD, init_ca);
	auto m04 = make_view_matrix(3_CD, 3_RD, init_ca);
	auto m05 = make_view_matrix(dim_pair(3_CS, 3_RS), init_ca);
	auto m06 = make_view_matrix(dim_pair(3_CD, 3_RS), init_ca);
	auto m07 = make_view_matrix(dim_pair(3_CS, 3_RD), init_ca);
	auto m08 = make_view_matrix(dim_pair(3_CD, 3_RD), init_ca);
	auto m09 = make_view_matrix(3_DS, init_ca);
	auto m10 = make_view_matrix(3_DD, init_ca);
	auto m11 = make_view_matrix(dim_pair(3_DS), init_ca);
	auto m12 = make_view_matrix(dim_pair(3_DD), init_ca);

	auto m13 = make_view_matrix(3_CS, 3_RS, init_a);
	auto m14 = make_view_matrix(3_CD, 3_RS, init_a);
	auto m15 = make_view_matrix(3_CS, 3_RD, init_a);
	auto m16 = make_view_matrix(3_CD, 3_RD, init_a);
	auto m17 = make_view_matrix(dim_pair(3_CS, 3_RS), init_a);
	auto m18 = make_view_matrix(dim_pair(3_CD, 3_RS), init_a);
	auto m19 = make_view_matrix(dim_pair(3_CS, 3_RD), init_a);
	auto m20 = make_view_matrix(dim_pair(3_CD, 3_RD), init_a);
	auto m21 = make_view_matrix(3_DS, init_a);
	auto m22 = make_view_matrix(3_DD, init_a);
	auto m23 = make_view_matrix(dim_pair(3_DS), init_a);
	auto m24 = make_view_matrix(dim_pair(3_DD), init_a);

	auto m25 = make_view_matrix(3_CS, 3_RS, init_v);
	auto m26 = make_view_matrix(3_CD, 3_RS, init_v);
	auto m27 = make_view_matrix(3_CS, 3_RD, init_v);
	auto m28 = make_view_matrix(3_CD, 3_RD, init_v);
	auto m29 = make_view_matrix(dim_pair(3_CS, 3_RS), init_v);
	auto m30 = make_view_matrix(dim_pair(3_CD, 3_RS), init_v);
	auto m31 = make_view_matrix(dim_pair(3_CS, 3_RD), init_v);
	auto m32 = make_view_matrix(dim_pair(3_CD, 3_RD), init_v);
	auto m33 = make_view_matrix(3_DS, init_v);
	auto m34 = make_view_matrix(3_DD, init_v);
	auto m35 = make_view_matrix(dim_pair(3_DS), init_v);
	auto m36 = make_view_matrix(dim_pair(3_DD), init_v);

	BT((rt_id(m01) == id< view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m02) == id< view_matrix< T[9], true, 0_C, 3_R > >));
	BT((rt_id(m03) == id< view_matrix< T[9], true, 3_C, 0_R > >));
	BT((rt_id(m04) == id< view_matrix< T[9], true, 0_C, 0_R > >));
	BT((rt_id(m05) == id< view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m06) == id< view_matrix< T[9], true, 0_C, 3_R > >));
	BT((rt_id(m07) == id< view_matrix< T[9], true, 3_C, 0_R > >));
	BT((rt_id(m08) == id< view_matrix< T[9], true, 0_C, 0_R > >));
	BT((rt_id(m09) == id< view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m10) == id< view_matrix< T[9], true, 0_C, 0_R > >));
	BT((rt_id(m11) == id< view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m12) == id< view_matrix< T[9], true, 0_C, 0_R > >));

	using array = std::array< T, 9 >;
	BT((rt_id(m13) == id< view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m14) == id< view_matrix< array, true, 0_C, 3_R > >));
	BT((rt_id(m15) == id< view_matrix< array, true, 3_C, 0_R > >));
	BT((rt_id(m16) == id< view_matrix< array, true, 0_C, 0_R > >));
	BT((rt_id(m17) == id< view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m18) == id< view_matrix< array, true, 0_C, 3_R > >));
	BT((rt_id(m19) == id< view_matrix< array, true, 3_C, 0_R > >));
	BT((rt_id(m20) == id< view_matrix< array, true, 0_C, 0_R > >));
	BT((rt_id(m21) == id< view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m22) == id< view_matrix< array, true, 0_C, 0_R > >));
	BT((rt_id(m23) == id< view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m24) == id< view_matrix< array, true, 0_C, 0_R > >));

	using vector = std::vector< T >;
	BT((rt_id(m25) == id< view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m26) == id< view_matrix< vector, true, 0_C, 3_R > >));
	BT((rt_id(m27) == id< view_matrix< vector, true, 3_C, 0_R > >));
	BT((rt_id(m28) == id< view_matrix< vector, true, 0_C, 0_R > >));
	BT((rt_id(m29) == id< view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m30) == id< view_matrix< vector, true, 0_C, 3_R > >));
	BT((rt_id(m31) == id< view_matrix< vector, true, 3_C, 0_R > >));
	BT((rt_id(m32) == id< view_matrix< vector, true, 0_C, 0_R > >));
	BT((rt_id(m33) == id< view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m34) == id< view_matrix< vector, true, 0_C, 0_R > >));
	BT((rt_id(m35) == id< view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m36) == id< view_matrix< vector, true, 0_C, 0_R > >));

	BT((check(m01, ref_i)));
	BT((check(m02, ref_i)));
	BT((check(m03, ref_i)));
	BT((check(m04, ref_i)));
	BT((check(m05, ref_i)));
	BT((check(m06, ref_i)));
	BT((check(m07, ref_i)));
	BT((check(m08, ref_i)));
	BT((check(m09, ref_i)));
	BT((check(m10, ref_i)));
	BT((check(m11, ref_i)));
	BT((check(m12, ref_i)));

	BT((check(m13, ref_i)));
	BT((check(m14, ref_i)));
	BT((check(m15, ref_i)));
	BT((check(m16, ref_i)));
	BT((check(m17, ref_i)));
	BT((check(m18, ref_i)));
	BT((check(m19, ref_i)));
	BT((check(m20, ref_i)));
	BT((check(m21, ref_i)));
	BT((check(m22, ref_i)));
	BT((check(m23, ref_i)));
	BT((check(m24, ref_i)));

	BT((check(m25, ref_i)));
	BT((check(m26, ref_i)));
	BT((check(m27, ref_i)));
	BT((check(m28, ref_i)));
	BT((check(m29, ref_i)));
	BT((check(m30, ref_i)));
	BT((check(m31, ref_i)));
	BT((check(m32, ref_i)));
	BT((check(m33, ref_i)));
	BT((check(m34, ref_i)));
	BT((check(m35, ref_i)));
	BT((check(m36, ref_i)));
}

BOOST_AUTO_TEST_CASE_TEMPLATE(test_view_matrix_3x3_const, T, types){
	static constexpr T ref_i[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
	static T init_ca[9] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
	static std::array< T, 9 > init_a{{0, 1, 2, 3, 4, 5, 6, 7, 8}};
	static std::vector< T > init_v{0, 1, 2, 3, 4, 5, 6, 7, 8};

	constexpr auto m01 = make_const_view_matrix(3_CS, 3_RS, init_ca);
	auto m02 = make_const_view_matrix(3_CD, 3_RS, init_ca);
	auto m03 = make_const_view_matrix(3_CS, 3_RD, init_ca);
	auto m04 = make_const_view_matrix(3_CD, 3_RD, init_ca);
	constexpr auto m05 = make_const_view_matrix(dim_pair(3_CS, 3_RS), init_ca);
	auto m06 = make_const_view_matrix(dim_pair(3_CD, 3_RS), init_ca);
	auto m07 = make_const_view_matrix(dim_pair(3_CS, 3_RD), init_ca);
	auto m08 = make_const_view_matrix(dim_pair(3_CD, 3_RD), init_ca);
	constexpr auto m09 = make_const_view_matrix(3_DS, init_ca);
	auto m10 = make_const_view_matrix(3_DD, init_ca);
	constexpr auto m11 = make_const_view_matrix(dim_pair(3_DS), init_ca);
	auto m12 = make_const_view_matrix(dim_pair(3_DD), init_ca);

	auto m13 = make_const_view_matrix(3_CS, 3_RS, init_a);
	auto m14 = make_const_view_matrix(3_CD, 3_RS, init_a);
	auto m15 = make_const_view_matrix(3_CS, 3_RD, init_a);
	auto m16 = make_const_view_matrix(3_CD, 3_RD, init_a);
	auto m17 = make_const_view_matrix(dim_pair(3_CS, 3_RS), init_a);
	auto m18 = make_const_view_matrix(dim_pair(3_CD, 3_RS), init_a);
	auto m19 = make_const_view_matrix(dim_pair(3_CS, 3_RD), init_a);
	auto m20 = make_const_view_matrix(dim_pair(3_CD, 3_RD), init_a);
	auto m21 = make_const_view_matrix(3_DS, init_a);
	auto m22 = make_const_view_matrix(3_DD, init_a);
	auto m23 = make_const_view_matrix(dim_pair(3_DS), init_a);
	auto m24 = make_const_view_matrix(dim_pair(3_DD), init_a);

	auto m25 = make_const_view_matrix(3_CS, 3_RS, init_v);
	auto m26 = make_const_view_matrix(3_CD, 3_RS, init_v);
	auto m27 = make_const_view_matrix(3_CS, 3_RD, init_v);
	auto m28 = make_const_view_matrix(3_CD, 3_RD, init_v);
	auto m29 = make_const_view_matrix(dim_pair(3_CS, 3_RS), init_v);
	auto m30 = make_const_view_matrix(dim_pair(3_CD, 3_RS), init_v);
	auto m31 = make_const_view_matrix(dim_pair(3_CS, 3_RD), init_v);
	auto m32 = make_const_view_matrix(dim_pair(3_CD, 3_RD), init_v);
	auto m33 = make_const_view_matrix(3_DS, init_v);
	auto m34 = make_const_view_matrix(3_DD, init_v);
	auto m35 = make_const_view_matrix(dim_pair(3_DS), init_v);
	auto m36 = make_const_view_matrix(dim_pair(3_DD), init_v);

	BT((rt_id(m01) == id< const_view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m02) == id< const_view_matrix< T[9], true, 0_C, 3_R > >));
	BT((rt_id(m03) == id< const_view_matrix< T[9], true, 3_C, 0_R > >));
	BT((rt_id(m04) == id< const_view_matrix< T[9], true, 0_C, 0_R > >));
	BT((rt_id(m05) == id< const_view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m06) == id< const_view_matrix< T[9], true, 0_C, 3_R > >));
	BT((rt_id(m07) == id< const_view_matrix< T[9], true, 3_C, 0_R > >));
	BT((rt_id(m08) == id< const_view_matrix< T[9], true, 0_C, 0_R > >));
	BT((rt_id(m09) == id< const_view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m10) == id< const_view_matrix< T[9], true, 0_C, 0_R > >));
	BT((rt_id(m11) == id< const_view_matrix< T[9], true, 3_C, 3_R > >));
	BT((rt_id(m12) == id< const_view_matrix< T[9], true, 0_C, 0_R > >));

	using array = std::array< T, 9 >;
	BT((rt_id(m13) == id< const_view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m14) == id< const_view_matrix< array, true, 0_C, 3_R > >));
	BT((rt_id(m15) == id< const_view_matrix< array, true, 3_C, 0_R > >));
	BT((rt_id(m16) == id< const_view_matrix< array, true, 0_C, 0_R > >));
	BT((rt_id(m17) == id< const_view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m18) == id< const_view_matrix< array, true, 0_C, 3_R > >));
	BT((rt_id(m19) == id< const_view_matrix< array, true, 3_C, 0_R > >));
	BT((rt_id(m20) == id< const_view_matrix< array, true, 0_C, 0_R > >));
	BT((rt_id(m21) == id< const_view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m22) == id< const_view_matrix< array, true, 0_C, 0_R > >));
	BT((rt_id(m23) == id< const_view_matrix< array, true, 3_C, 3_R > >));
	BT((rt_id(m24) == id< const_view_matrix< array, true, 0_C, 0_R > >));

	using vector = std::vector< T >;
	BT((rt_id(m25) == id< const_view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m26) == id< const_view_matrix< vector, true, 0_C, 3_R > >));
	BT((rt_id(m27) == id< const_view_matrix< vector, true, 3_C, 0_R > >));
	BT((rt_id(m28) == id< const_view_matrix< vector, true, 0_C, 0_R > >));
	BT((rt_id(m29) == id< const_view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m30) == id< const_view_matrix< vector, true, 0_C, 3_R > >));
	BT((rt_id(m31) == id< const_view_matrix< vector, true, 3_C, 0_R > >));
	BT((rt_id(m32) == id< const_view_matrix< vector, true, 0_C, 0_R > >));
	BT((rt_id(m33) == id< const_view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m34) == id< const_view_matrix< vector, true, 0_C, 0_R > >));
	BT((rt_id(m35) == id< const_view_matrix< vector, true, 3_C, 3_R > >));
	BT((rt_id(m36) == id< const_view_matrix< vector, true, 0_C, 0_R > >));

	BT((check(m01, ref_i)));
	BT((check(m02, ref_i)));
	BT((check(m03, ref_i)));
	BT((check(m04, ref_i)));
	BT((check(m05, ref_i)));
	BT((check(m06, ref_i)));
	BT((check(m07, ref_i)));
	BT((check(m08, ref_i)));
	BT((check(m09, ref_i)));
	BT((check(m10, ref_i)));
	BT((check(m11, ref_i)));
	BT((check(m12, ref_i)));

	BT((check(m13, ref_i)));
	BT((check(m14, ref_i)));
	BT((check(m15, ref_i)));
	BT((check(m16, ref_i)));
	BT((check(m17, ref_i)));
	BT((check(m18, ref_i)));
	BT((check(m19, ref_i)));
	BT((check(m20, ref_i)));
	BT((check(m21, ref_i)));
	BT((check(m22, ref_i)));
	BT((check(m23, ref_i)));
	BT((check(m24, ref_i)));

	BT((check(m25, ref_i)));
	BT((check(m26, ref_i)));
	BT((check(m27, ref_i)));
	BT((check(m28, ref_i)));
	BT((check(m29, ref_i)));
	BT((check(m30, ref_i)));
	BT((check(m31, ref_i)));
	BT((check(m32, ref_i)));
	BT((check(m33, ref_i)));
	BT((check(m34, ref_i)));
	BT((check(m35, ref_i)));
	BT((check(m36, ref_i)));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: bebuch/Mitrax

max_issues_repo_name: bebuch/Mitrax

max_forks_repo_name: bebuch/Mitrax


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#include "sha1.h"

//#pragma warning (push)
//#pragma warning (disable:4245)
//#pragma warning (disable:4244)
#include <boost\uuid\sha1.hpp>
//#pragma warning (pop)

namespace mira
{
    using sha1_t = boost::uuids::detail::sha1;

    std::array<unsigned int, 5> sha1(const void* data, size_t size)
    {
        sha1_t computer;
        computer.process_bytes(data, size);

        sha1_t::digest_type digest;
        computer.get_digest(digest);
        return{ digest[0], digest[1], digest[2], digest[3], digest[4] };
    }

    struct continuous_sha1::impl
    {
        sha1_t computer;
    };

    continuous_sha1::continuous_sha1()
        : m_impl{ std::make_unique<impl>() }
    {}

    continuous_sha1::~continuous_sha1() = default;
    continuous_sha1::continuous_sha1(continuous_sha1&&) = default;
    continuous_sha1& continuous_sha1::operator=(continuous_sha1&&) = default;

    void continuous_sha1::process(const void* data, size_t size)
    {
        m_impl->computer.process_bytes(data, size);
    }

    std::array<unsigned int, 5> continuous_sha1::get_digest() const
    {
        sha1_t::digest_type digest;
        m_impl->computer.get_digest(digest);
        return{ digest[0], digest[1], digest[2], digest[3], digest[4] };
    }
}

max_stars_repo_name: syntheticmagus/mageslam

max_issues_repo_name: syntheticmagus/mageslam

max_forks_repo_name: syntheticmagus/mageslam


text:
// Copyright 2018 Your Name <your_email>

#ifndef INCLUDE_HEADER_HPP_
#define INCLUDE_HEADER_HPP_

#include <iostream>
#include <boost/asio.hpp>
#include <boost/date_time.hpp>
#include <boost/thread.hpp>
#include <chrono>
#include <thread>
#include <unistd.h>
#include <string>

#define BOOST_ASIO_SEPARATE_COMPILATION

class Client {
public:
    Client() : ep(boost::asio::ip::address::
                  from_string("127.0.0.1"), 1024), sock(service) {
        sock.connect(ep);
        getLogin();
        mainLoop();
    }

private:
    void mainLoop() {
        std::thread pingThread(pinging, &sock);
        while (true) {
            std::string s;
            std::cout << "entering: ";
            std::cin >> s;
            s.push_back('\n');
            sock.write_some(boost::asio::buffer(s));
            sock.read_some(boost::asio::buffer(s));
            if (s == "bye\n") {
                sock.close();
                std::cout << "GOOD BYE!" << std::endl;
                return;
            }
            std::cout << "answer: " << s << std::endl;
        }
    }

    static void pinging(boost::asio::ip::tcp::socket *sock) {
        const std::string PING = "ping\n";
        while (true) {
            sleep(std::rand() % 8);
            try {
                sock->write_some(boost::asio::buffer(PING));
            } catch (...) {
                return;
            }
        }
    }

    void getLogin() {
        std::string answer;
        while (answer != LOGIN_OK) {
            std::cout << "Your login is: " << login << std::endl;
            login.push_back('\n');
            sock.write_some(boost::asio::buffer(login));
            char c[32];
            sock.read_some(boost::asio::buffer(c));
            answer = c;
            std::cout << "answer: '" << answer << "'" << std::endl;
        }
    }

public:
    std::string login = "Dellvin";

private:
    boost::asio::io_service service;
    boost::asio::ip::tcp::endpoint ep;
    boost::asio::ip::tcp::socket sock;
    const std::string LOGIN_OK = "login_ok\n";
};

#endif // INCLUDE_HEADER_HPP_

ext: hpp


text:
#include <boost/test/unit_test.hpp>

#include "Engine/Game.h"
#include "Base64/Base64.h"

BOOST_AUTO_TEST_CASE( TestGameSerialize )
{
    auto home = Implbits::IPlayer::CreateSpec();
    home->SetIdentity( "homeidstring" );
    home->SetType( Implbits::PLAYER_LOCAL );
    home->SetTeam( Implbits::TEAM_HOME );
    home->SetColor( 192929 );
    auto away = Implbits::IPlayer::CreateSpec();
    away->SetIdentity( "awayidstring" );
    away->SetType( Implbits::PLAYER_REMOTE );
    away->SetTeam( Implbits::TEAM_AWAY );
    away->SetColor( 233 );
    auto game = Implbits::Game::CreateNewGame( Implbits::DefaultGameIdInitiator, home, away );
    auto tiles = game->GetTiles();
    std::string encoding = json_spirit::write( game->JsonEncode() );
    json_spirit::mValue value;
    BOOST_REQUIRE( json_spirit::read( encoding, value ) );
    BOOST_REQUIRE( value.type() == json_spirit::obj_type );
    auto gamedec = Implbits::Game::Create();
    gamedec->JsonDecode( value.get_obj() );
    auto tilesdec = gamedec->GetTiles();
    BOOST_CHECK( game.get() != gamedec.get() );
    BOOST_CHECK( game->GetSerializer() != gamedec->GetSerializer() );
    BOOST_CHECK( game->GetSerializer() == "" );
    BOOST_CHECK( game->GetHomePlayer()->GetIdentity() == gamedec->GetSerializer() );
    BOOST_CHECK( game->GetId() == gamedec->GetId() );
    BOOST_CHECK( game->GetGameBoard()->Encode() == gamedec->GetGameBoard()->Encode() );
    BOOST_CHECK( game->GetFriendlyName() == gamedec->GetFriendlyName() );
    BOOST_REQUIRE( tiles.size() == tilesdec.size() );
    for ( size_t i = 0; i < tiles.size(); i++ )
    {
        BOOST_CHECK( tiles[i]->GetId() == tilesdec[i]->GetId() );
        BOOST_CHECK( tiles[i]->GetOwner() == tilesdec[i]->GetOwner() );
        BOOST_CHECK( tiles[i]->GetPos() == tilesdec[i]->GetPos() );
    }
    BOOST_CHECK( game->GetHomePlayer()->GetIdentity() == gamedec->GetHomePlayer()->GetIdentity() );
    BOOST_CHECK( game->GetHomePlayer()->GetColor() == gamedec->GetHomePlayer()->GetColor() );
    BOOST_CHECK( game->GetHomePlayer()->GetTeam() == gamedec->GetHomePlayer()->GetTeam() );
    BOOST_CHECK( game->GetTurn() == gamedec->GetTurn() );
}

BOOST_AUTO_TEST_CASE( TestGameSerializeB64 )
{
    auto home = Implbits::IPlayer::CreateSpec();
    home->SetIdentity( "fartyface" );
    home->SetType( Implbits::PLAYER_LOCAL );
    home->SetTeam( Implbits::TEAM_HOME );
    home->SetColor( 192929 );
    auto away = Implbits::IPlayer::CreateSpec();
    away->SetIdentity( "buggerbutt" );
    away->SetType( Implbits::PLAYER_COMPUTER );
    away->SetTeam( Implbits::TEAM_AWAY );
    away->SetColor( 233 );
    auto game = Implbits::Game::CreateNewGame( Implbits::DefaultGameIdInitiator, home, away );
    auto tiles = game->GetTiles();
    std::string encoding = json_spirit::write( game->JsonEncode() );
    std::string b64 = b64::Base64EncodeFromString( encoding );
    auto gamedec = Implbits::Game::LoadGame( b64 );
    auto tilesdec = gamedec->GetTiles();
    BOOST_CHECK( game.get() != gamedec.get() );
    BOOST_CHECK( game->GetId() == gamedec->GetId() );
    BOOST_CHECK( game->GetGameBoard()->Encode() == gamedec->GetGameBoard()->Encode() );
    BOOST_CHECK( game->GetFriendlyName() == gamedec->GetFriendlyName() );
    BOOST_REQUIRE( tiles.size() == tilesdec.size() );
    for ( size_t i = 0; i < tiles.size(); i++ )
    {
        BOOST_CHECK( tiles[i]->GetId() == tilesdec[i]->GetId() );
        BOOST_CHECK( tiles[i]->GetOwner() == tilesdec[i]->GetOwner() );
        BOOST_CHECK( tiles[i]->GetPos() == tilesdec[i]->GetPos() );
    }
    BOOST_CHECK( game->GetHomePlayer()->GetIdentity() == gamedec->GetHomePlayer()->GetIdentity() );
    BOOST_CHECK( game->GetHomePlayer()->GetColor() == gamedec->GetHomePlayer()->GetColor() );
    BOOST_CHECK( game->GetHomePlayer()->GetTeam() == gamedec->GetHomePlayer()->GetTeam() );
}

max_stars_repo_name: petrsnd/tetrad

max_issues_repo_name: petrsnd/tetrad

max_forks_repo_name: petrsnd/tetrad


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

#include <commander/algorithm.hpp>

#include <boost/test/unit_test.hpp>

#include <tuple>
#include <utility>
#include <vector>

BOOST_AUTO_TEST_CASE( tuple_visit_disjunction )
{
    std::vector<std::tuple<bool, uint32_t>> results;

    auto call_always_false = [&results](const auto& item) -> bool {
        results.emplace_back(false, item);
        return false;
    };
    auto call_only_4 = [&results](const auto& item) -> bool {
        results.emplace_back((uint32_t(item) == 4), item);
        return (uint32_t(item) == 4);
    };
    auto call_only_6 = [&results](const auto& item) -> bool {
        results.emplace_back((uint32_t(item) == 6), item);
        return (uint32_t(item) == 6);
    };

    std::tuple<uint8_t, uint16_t, uint32_t> tuple_of_ints   = {0, 1, 2};
    std::tuple<float, double, long double>  tuple_of_floats = {3.3, 4.4, 5.5};
    std::tuple<uint64_t>                    tuple_uint64_t  = {6};

    {
        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_always_false, tuple_of_ints) == false);
        BOOST_CHECK(results.size() == 3);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 0));
        BOOST_CHECK(results.at(1) == std::forward_as_tuple(false, 1));
        BOOST_CHECK(results.at(2) == std::forward_as_tuple(false, 2));

        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_always_false, tuple_of_ints, tuple_of_floats) == false);
        BOOST_CHECK(results.size() == 6);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 0));
        BOOST_CHECK(results.at(1) == std::forward_as_tuple(false, 1));
        BOOST_CHECK(results.at(2) == std::forward_as_tuple(false, 2));
        BOOST_CHECK(results.at(3) == std::forward_as_tuple(false, 3));
        BOOST_CHECK(results.at(4) == std::forward_as_tuple(false, 4));
        BOOST_CHECK(results.at(5) == std::forward_as_tuple(false, 5));
    }

    {
        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_only_4, tuple_of_ints) == false);
        BOOST_CHECK(results.size() == 3);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 0));
        BOOST_CHECK(results.at(1) == std::forward_as_tuple(false, 1));
        BOOST_CHECK(results.at(2) == std::forward_as_tuple(false, 2));

        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_only_4, tuple_of_ints, tuple_of_floats) == true);
        BOOST_CHECK(results.size() == 5);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 0));
        BOOST_CHECK(results.at(1) == std::forward_as_tuple(false, 1));
        BOOST_CHECK(results.at(2) == std::forward_as_tuple(false, 2));
        BOOST_CHECK(results.at(3) == std::forward_as_tuple(false, 3));
        BOOST_CHECK(results.at(4) == std::forward_as_tuple(true, 4));
    }

    {
        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_always_false, tuple_uint64_t) == false);
        BOOST_CHECK(results.size() == 1);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 6));

        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_always_false, tuple_uint64_t, tuple_of_ints) == false);
        BOOST_CHECK(results.size() == 4);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 6));
        BOOST_CHECK(results.at(1) == std::forward_as_tuple(false, 0));
        BOOST_CHECK(results.at(2) == std::forward_as_tuple(false, 1));
        BOOST_CHECK(results.at(3) == std::forward_as_tuple(false, 2));

        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_always_false, tuple_of_ints, tuple_uint64_t) == false);
        BOOST_CHECK(results.size() == 4);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 0));
        BOOST_CHECK(results.at(1) == std::forward_as_tuple(false, 1));
        BOOST_CHECK(results.at(2) == std::forward_as_tuple(false, 2));
        BOOST_CHECK(results.at(3) == std::forward_as_tuple(false, 6));
    }

    {
        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_only_6, tuple_uint64_t) == true);
        BOOST_CHECK(results.size() == 1);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(true, 6));

        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_only_6, tuple_uint64_t, tuple_of_ints) == true);
        BOOST_CHECK(results.size() == 1);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(true, 6));

        results.clear();
        BOOST_CHECK(commander::tuple_visit_disjunction(call_only_6, tuple_of_ints, tuple_uint64_t) == true);
        BOOST_CHECK(results.size() == 4);
        BOOST_CHECK(results.at(0) == std::forward_as_tuple(false, 0));
        BOOST_CHECK(results.at(1) == std::forward_as_tuple(false, 1));
        BOOST_CHECK(results.at(2) == std::forward_as_tuple(false, 2));
        BOOST_CHECK(results.at(3) == std::forward_as_tuple(true, 6));
    }
}

max_stars_repo_name: daishe/commander

max_issues_repo_name: daishe/commander

max_forks_repo_name: daishe/commander


text:
/*********************************************************************************
 *   Copyright (C) 2006-2013 by Sebastian Gniazdowski                            *
 *   All Rights reserved.                                                        *
 *                                                                               *
 *   Redistribution and use in source and binary forms, with or without          *
 *   modification, are permitted provided that the following conditions          *
 *   are met:                                                                    *
 *   1. Redistributions of source code must retain the above copyright           *
 *      notice, this list of conditions and the following disclaimer.            *
 *   2. Redistributions in binary form must reproduce the above copyright        *
 *      notice, this list of conditions and the following disclaimer in the      *
 *      documentation and/or other materials provided with the distribution.     *
 *   3. Neither the name of the Keyfrog 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 REGENTS 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 REGENTS 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.                                                                *
 *********************************************************************************/

#if HAVE_CONFIG_H
#include <config.h>
#endif

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include "EventFilter.h"
#include "RawEvent.h"
#include "Event.h"
#include "Common.h"
#include "TermCode.h"
#include <sys/types.h>
#include "Debug.h"

#include <list>

using namespace std;
using namespace keyfrog::TermCodes;
using namespace boost;

namespace keyfrog {
    /**
     * Takes and saves window cache as reference,
     * no new object is being created.
     *
     * @param wim Window cache, as reference
     */
    EventFilter::EventFilter(KfWindowCache & wim, ProcessManager & pm) : m_wim(wim), m_pm(pm) {
        m_wim.setDisplay(m_eventMonitor.ctrlDisplay());
    }

    /**
    */
    EventFilter::~EventFilter() {
    }

    bool EventFilter::connect(string displayName) {
        return m_eventMonitor.connect(displayName);
    }
    /**
     * All subsystems are started, ie. EventMonitor.
     */
    void EventFilter::start() {
        m_eventMonitor.start();
    }

    /**
     * All key catching subsystems are started.
     */
    void EventFilter::stop() {
        m_eventMonitor.stop();
    }

    /**
     * Fetches queued raw events from EventMonitor,
     * converts them to higher level events.
     */
    void EventFilter::processEvents() {
        // Get only preprocessed raw events,
        // do not start processing of new ones
        while(m_eventMonitor.numEvents()) {
            RawEvent rawEvent = m_eventMonitor.nextEvent();
            Event event;
            Window window;
            // Fields required to set: time, type, groupId
            event.setTime(rawEvent.time());
            switch(rawEvent.type()) {
                case KeyPress:
                    event.setType(kfKeyPress);
                    window = rawEvent.event().u.keyButtonPointer.event;
                    event.setDestWin(window);
                    setGroupId(event, window);
                    break;
                case DestroyNotify:
                    event.setType(kfDestroyNotify);
                    window = rawEvent.event().u.destroyNotify.window;
                    event.setDestWin(window);
                    break;
                case FocusIn:
                    event.setType(kfFocusIn);
                    break;
                default:
                    // This should not happen
                    _err("Unrecognized event type [%d]", rawEvent.type());
#ifdef _KF_DEBUG
                    throw std::exception();
#endif
            }
            m_events.push_back(event);
        }
    }

    /**
     * Receives and adds new event into internal queue
     */
    void EventFilter::waitForEvents() {
        while(m_events.size() == 0) {
            m_eventMonitor.waitForEvents();
            processEvents();
        }
    }

    /**
     * Event is removed from internal queue
     * @return Next buffered event
     */
    Event EventFilter::nextEvent() {
        if(numEvents() == 0)
            waitForEvents();
        Event event = m_events.front();
        m_events.pop_front();
        return event;
    }

    /**
     * Traverses all groups looking for a match
     */
    void EventFilter::setGroupId(Event & event, Window window) {
        int gid = -1;
        event.setGroupId(-1);

        m_wim.setDisplay(m_eventMonitor.ctrlDisplay());
        if(!m_wim.findAndUseWindow(window)) {
            return;
        }

        string className = m_wim.fetchClassName();

        // Detect terminal, then match against child unix processes
        // TODO: database (external?) of uncommon terminals
        int pid = -1;
        if ( iends_with( className, "term" ) || iends_with( className, "rxvt" )
                || iends_with( className, "konsole" ) || iends_with( className, "xterminal" )
           ) {
            // It's terminal, so we want to check sub-sub-process (TODO: any odd cases?)
            _dbg("Terminal window!");
            pid = m_wim.fetchClientPid();
            if(pid != -1 && pid != 0)
                gid = matchTermProc(pid);
        }

        // Match against process name that owns the Window
        // TODO: use against OSX native windows
        if( gid == -1 ) {
            pid = m_wim.fetchClientPid();
            if(pid != -1 && pid != 0)
                gid = matchProc(pid);
        }

        // Third check: window class name
        // TODO: handle empty class name (e.g. OSX native window -- or better to simulate X11 class name?)
        // TODO: skip match against terminals? should be configurable
        if( gid == -1 ) {
            // Does class name match any group?
            gid = matchWindowClass(className);
        }

        if( gid != -1 )
            _dbg( "Match group (%s%d%s)", cboldRed, gid, creset );
        else
            _dbg( "No match (%s)(pid:%d)", className.c_str(), pid );

        event.setGroupId( gid );
    }

    int EventFilter::matchWindowClass(string & className) {
        int gid = -1;
        list<Group> & groups = m_filterConfig.groups();

        // Walk through ALL groups (and then iterate over class names, which may not exist)
        bool matched = false;
        for(list<Group>::iterator grp = groups.begin(); grp != groups.end(); ++grp) {
            const list<string> & wndClasses = grp->windowClasses();
            // Walk through windowClasses
            if( wndClasses.size() > 0 ) {
                _ldbg("Window Class Compare");
            }
            for ( list<string>::const_iterator clp = wndClasses.begin(); clp != wndClasses.end(); ++clp ) {
                // Case insensitive compare
                _qldbg(" %s == %s,", clp->c_str(), className.c_str());
                if( string_eq_ci( (*clp), className ) ) {
                    matched = true;
                    // Set matched group
                    gid = grp->id();
                    break;
                }
            }
            if( wndClasses.size() > 0 ) {
                _qdbg("");
            }
            if(matched)
                break;
        }
        return gid;
    }

    int EventFilter::matchTermProc(pid_t pid) {
        int gid = -1;
        const list<Group> & groups = m_filterConfig.groups();

        // Fetch the set of descendant processes
        set< pair<pid_t, string> > dprocs = m_pm.processTree().fetchDescendants(pid);

        // Walk through ALL groups (and then iterate over proc names, which may not exist)
        bool matched = false;
        for ( list<Group>::const_iterator grp = groups.begin(); grp != groups.end(); ++grp ) {
            const list<string> & termProcs = grp->termProcs();

            // Iterate through term proc names
            // TODO: correct term proc match must be at leaf process?
            for( list<string>::const_iterator tpit = termProcs.begin(); tpit != termProcs.end(); ++tpit ) {

                // Compare proc names in group with fetched sub processes of terminal
                _ldbg("TermProc Compare");
                for(set< pair<pid_t, string> >::iterator it = dprocs.begin(); it != dprocs.end(); ++it) {
                    _qldbg(" %s == %s,", tpit->c_str(), it->second.c_str());
                    if( string_eq_ci( (*tpit), it->second ) ) {
                        matched = true;
                        gid = grp->id();
                        break;
                    }
                }
                _qdbg("");
                if(matched)
                    break;
            }
            if(matched)
                break;
        }

        return gid;
    }

    int EventFilter::matchProc(pid_t pid) {
        int gid = -1;
        const list<Group> & groups = m_filterConfig.groups();
        const std::string & procName = m_pm.processTree().fetchName( pid );

        // Walk through ALL groups (and then iterate over proc names, which may not exist)
        bool matched = false;
        for ( list<Group>::const_iterator grp = groups.begin(); grp != groups.end(); ++grp ) {
            const list<string> & procs = grp->procs();

            // Iterate through proc names
            for ( list<string>::const_iterator pit = procs.begin(); pit != procs.end(); ++pit ) {
                // Compare proc names in group with proc name of given pid
                _dbg( "ProcCompare %s == %s", pit->c_str(), procName.c_str() );
                if( string_eq_ci( (*pit), procName ) ) {
                    matched = true;
                    gid = grp->id();
                    break;
                }
            }
            if(matched)
                break;
        }

        return gid;
    }
}

max_stars_repo_name: NorthIsMirror/keyfrog

max_issues_repo_name: NorthIsMirror/keyfrog

max_forks_repo_name: NorthIsMirror/keyfrog


text:
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>

#include <boost/mpl/vector.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/quote.hpp>
#include <boost/mpl/protect.hpp>
#include <boost/mpl/bind.hpp>
#include <boost/mpl/list.hpp>

#include <cmath>
#include <boost/safe_float.hpp>
#include <boost/safe_float/convenience.hpp>
#include <boost/safe_float/policy/check_subtraction_overflow.hpp>
#include <boost/safe_float/policy/check_subtraction_underflow.hpp>
#include <boost/safe_float/policy/check_subtraction_inexact.hpp>
#include <boost/safe_float/policy/check_subtraction_invalid_result.hpp>

//types to be tested
using test_types=boost::mpl::list<
    float, double, long double
>;

using namespace boost::safe_float;

/**
  This test suite checks different policies on subtraction operations using default parameters for the other policies.
  */
BOOST_AUTO_TEST_SUITE( safe_float_subtraction_test_suite )

BOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_throws_on_overflow, FPT, test_types){
    // define two FPT numbers suppose to positive overflow
    FPT a = std::numeric_limits<FPT>::max();
    FPT b = std::numeric_limits<FPT>::lowest();
    // check FPT overflows to inf after subtract
    BOOST_CHECK(std::isinf(a-b));

    // construct safe_float version of the same two numbers
    safe_float<FPT, policy::check_subtraction_overflow> c(std::numeric_limits<FPT>::max());
    safe_float<FPT, policy::check_subtraction_overflow> d(std::numeric_limits<FPT>::lowest());

    // check the subtraction throws
    BOOST_CHECK_THROW(c-d, std::exception);

    // define two FPT numbers suppose to negative overflow
    FPT e = std::numeric_limits<FPT>::lowest();
    FPT f = std::numeric_limits<FPT>::max();
    // check FPT overflows to inf after add
    BOOST_CHECK(std::isinf(e-f));

    // construct safe_float version of the same two numbers
    safe_float<FPT, policy::check_subtraction_overflow> g(std::numeric_limits<FPT>::lowest());
    safe_float<FPT, policy::check_subtraction_overflow> h(std::numeric_limits<FPT>::max());

    // check the subtraction throws
    BOOST_CHECK_THROW(g-h, std::exception);
}

BOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_inexact_rounding, FPT, test_types){
    // define two FPT numbers suppose to round the result inexactly
    FPT a = std::numeric_limits<FPT>::min();
    FPT b = pow(2, std::numeric_limits<FPT>::digits);

    // check substracting a from b is a new value.
    BOOST_CHECK(b-a == b);

    // construct safe_float version of the same two numbers
    safe_float<FPT, policy::check_subtraction_inexact> c(std::numeric_limits<FPT>::min());
    safe_float<FPT, policy::check_subtraction_inexact> d((FPT)pow(2, std::numeric_limits<FPT>::digits));

    // check the subtraction throws
    BOOST_CHECK_THROW(d-c, std::exception);
}

BOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_underflow, FPT, test_types){
    // define two FPT numbers suppose to underflow
    FPT a, b, c;
    if (std::is_same<FPT, float>()) {
        a = 4.01254977e-38f;
        b = 4.01254949e-38f;

        BOOST_CHECK(std::isnormal(a));
        BOOST_CHECK(std::isnormal(b));

        //check the subtraction produces an denormal result (considered underflow)
        c = a - b;
        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;

        // construct safe_float version of the same two numbers
        safe_float<FPT, policy::check_subtraction_underflow> d(a);
        safe_float<FPT, policy::check_subtraction_underflow> e(b);

        // check the subtraction throws
        BOOST_CHECK_THROW(d-e, std::exception);
    } else if (std::is_same<FPT, double>()) {
        a =  2.2250738585072019e-308;
        b =  2.2250738585072014e-308;

        BOOST_CHECK(std::isnormal(a));
        BOOST_CHECK(std::isnormal(b));

        //check the subtraction produces an denormal result (considered underflow)
        c = a - b;
        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;

        // construct safe_float version of the same two numbers
        safe_float<FPT, policy::check_subtraction_underflow> d(a);
        safe_float<FPT, policy::check_subtraction_underflow> e(b);

        // check the subtraction throws
        BOOST_CHECK_THROW(d-e, std::exception);
    } else if (std::is_same<FPT, long double>()) {
        a = 3.40132972460942461217e-4932l;
        b = 3.40132972460942461181e-4932l;

        BOOST_CHECK(std::isnormal(a));
        BOOST_CHECK(std::isnormal(b));

        //check the subtraction produces an denormal result (considered underflow)
        c = a - b;
        BOOST_CHECK( std::fpclassify( c ) == FP_SUBNORMAL ) ;

        // construct safe_float version of the same two numbers
        safe_float<FPT, policy::check_subtraction_underflow> d(a);
        safe_float<FPT, policy::check_subtraction_underflow> e(b);

        // check the subtraction throws
        BOOST_CHECK_THROW(d-e, std::exception);
    } else {
        BOOST_ERROR("underflow test only implemented for double so far");
    }
}

BOOST_AUTO_TEST_CASE_TEMPLATE( safe_float_subtraction_invalid_result, FPT, test_types){
    // define two FPT numbers suppose to produce a NAN
    FPT a = std::numeric_limits<FPT>::infinity();
    FPT b = std::numeric_limits<FPT>::infinity();

    // check adding produced NaN
    BOOST_CHECK(std::isnan(a-b));

    // construct safe_float version of the same two numbers
    safe_float<FPT, policy::check_subtraction_invalid_result> c(std::numeric_limits<FPT>::infinity());
    safe_float<FPT, policy::check_subtraction_invalid_result> d((std::numeric_limits<FPT>::infinity()));

    // check the subtraction throws
    BOOST_CHECK_THROW(c-d, std::exception);
}

BOOST_AUTO_TEST_SUITE_END()


text:
/********************************************************************************
 *
 * This file is part of the Geneva library collection. The following license
 * applies to this file:
 *
 * ------------------------------------------------------------------------------
 * Licensed 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.
 * ------------------------------------------------------------------------------
 *
 * Note that other files in the Geneva library collection may use a different
 * license. Please see the licensing information in each file.
 *
 ********************************************************************************
 *
 * Geneva was started by Dr. Rüdiger Berlich and was later maintained together
 * with Dr. Ariel Garcia under the auspices of Gemfony scientific. For further
 * information on Gemfony scientific, see http://www.gemfomy.eu .
 *
 * The majority of files in Geneva was released under the Apache license v2.0
 * in February 2020.
 *
 * See the NOTICE file in the top-level directory of the Geneva library
 * collection for a list of contributors and copyright information.
 *
 ********************************************************************************/

#pragma once

// Global checks, defines and includes needed for all of Geneva
#include "common/GGlobalDefines.hpp"

// Standard header files go here

// Boost header files go here
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/variant.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/export.hpp>

// Geneva header files go here
#include "common/GFixedSizePriorityQueueT.hpp"
#include "geneva/GenevaHelperFunctions.hpp"
#include "geneva/GParameterSet.hpp"

namespace Gem {
namespace Geneva {

/******************************************************************************/
/**
 * This class implements a fixed size priority queue for GParameterSet objects,
 * based on the maximization/minimization property and the current fitness of
 * the objects.
 */
class GParameterSetFixedSizePriorityQueue
    : public Gem::Common::GFixedSizePriorityQueueT<GParameterSet>
{
    ///////////////////////////////////////////////////////////////////////
    friend class boost::serialization::access;

    template<typename Archive>
    void serialize(Archive &ar, const unsigned int) {
        using boost::serialization::make_nvp;

        ar
        & make_nvp(
            "GFSPQ"
            , boost::serialization::base_object<Gem::Common::GFixedSizePriorityQueueT<GParameterSet>>(*this));
    }
    ///////////////////////////////////////////////////////////////////////

public:
    /** @brief The default constructor */
    G_API_GENEVA GParameterSetFixedSizePriorityQueue() = default;

    /** @brief Initialization with the maximum size */
    explicit G_API_GENEVA GParameterSetFixedSizePriorityQueue(const std::size_t &);
    /** @brief The copy constructor */
    G_API_GENEVA GParameterSetFixedSizePriorityQueue(const GParameterSetFixedSizePriorityQueue &cp) = default;
    /** @brief The destructor */
    G_API_GENEVA ~GParameterSetFixedSizePriorityQueue() override = default;

    /** @brief Checks whether no item has the dirty flag set */
    G_API_GENEVA bool allClean(std::size_t &) const;
    /** @brief Emits information about the "dirty flag" of all items */
    G_API_GENEVA std::string getCleanStatus() const;

    /** @brief Adds the items in the items_cnt container to the queue */
    void add(
        std::vector<std::shared_ptr<GParameterSet>> const &items_cnt
        , bool do_clone
        , bool replace
    ) override;

    /** @brief Adds a single item to the queue */
    void add(
        std::shared_ptr<GParameterSet> const& item
        , bool do_clone
    ) override;

protected:
    /***************************************************************************/
    /** @brief Loads the data of another population */
    G_API_GENEVA void load_(const Gem::Common::GFixedSizePriorityQueueT<GParameterSet> *) override;

    /** @brief Allow access to this classes compare_ function */
    friend void Gem::Common::compare_base_t<GParameterSetFixedSizePriorityQueue>(
        GParameterSetFixedSizePriorityQueue const &
        , GParameterSetFixedSizePriorityQueue const &
        , Gem::Common::GToken &
    );

    /** @brief Searches for compliance with expectations with respect to another object of the same type */
    G_API_GENEVA void compare_(
        const Gem::Common::GFixedSizePriorityQueueT<GParameterSet> & // the other object
        , const Gem::Common::expectation & // the expectation for this object, e.g. equality
        , const double & // the limit for allowed deviations of floating point types
    ) const override;

    /** @brief Evaluates a single work item, so that it can be sorted */
    G_API_GENEVA double evaluation(const std::shared_ptr<GParameterSet> &) const override;
    /** @brief Returns a unique id for a work item */
    G_API_GENEVA std::string id(const std::shared_ptr<GParameterSet> &) const override;

    /** @brief Applies modifications to this object. This is needed for testing purposes */
    G_API_GENEVA bool modify_GUnitTests_() override;
    /** @brief Performs self tests that are expected to succeed. This is needed for testing purposes */
    G_API_GENEVA void specificTestsNoFailureExpected_GUnitTests_() override;
    /** @brief Performs self tests that are expected to fail. This is needed for testing purposes */
    G_API_GENEVA void specificTestsFailuresExpected_GUnitTests_() override;

private:
    /** @brief Emits a name for this class / object */
    G_API_GENEVA std::string name_() const override;
    /** @brief Creates a deep clone of this object */
    G_API_GENEVA Gem::Common::GFixedSizePriorityQueueT<GParameterSet> *clone_() const override;
};

/******************************************************************************/

} /* namespace Geneva */
} /* namespace Gem */

BOOST_CLASS_EXPORT_KEY(Gem::Geneva::GParameterSetFixedSizePriorityQueue)


text:
#define ARMA_ALLOW_FAKE_GCC
#define ARMA_NO_DEBUG

#include "TimeSeries.hpp"

#include <armadillo>
#include <cmath>
#include <iostream>
#include <string>

using namespace arma;

namespace TimeSeries {

/*
 * Discretize Normal for given grid.
 */
vec discretizeNormal(vec grid,
    const double mean,
    const double sigma,
    bool cutTails)
{
  uword sz = grid.n_elem;
  vec prs(sz);

  if (sz == 1) {
    [[unlikely]] prs(0) = 1.0;
    return prs;
  } else if (sz == 2) {
    [[unlikely]] prs(0) = normcdf((grid(0) + grid(1)) / 2.0, mean, sigma);
    prs(1) = 1.0 - prs(0);
    return prs;
  }

#pragma omp parallel for
  for (uword ix = 1; ix < sz - 1; ++ix)
    prs(ix) = normcdf((grid(ix) + grid(ix + 1)) / 2.0, mean, sigma) - normcdf((grid(ix - 1) + grid(ix)) / 2.0, mean, sigma);

  if (cutTails) {
    const double stepOut = (grid(1) - grid(0)) / 2.0;
    prs(0) = normcdf(grid(0) + stepOut, mean, sigma) - normcdf(grid(0) - stepOut, mean, sigma);
    prs(sz - 1) = normcdf(grid(sz - 1) + stepOut, mean, sigma) - normcdf(grid(sz - 1) - stepOut, mean, sigma);

    prs /= sum(prs);
  } else {
    prs(0) = normcdf((grid(0) + grid(1)) / 2.0, mean, sigma);
    prs(sz - 1) = 1.0 - normcdf((grid(sz - 2) + grid(sz - 1)) / 2.0, mean, sigma);
  }

  return prs;
}

/*
 * Discretize Normal over uniformly spaced grid
 * spanning +/- pmSigma standard deviations.
 */
DiscreteRV
discretizeNormal(const double mean,
    const double sigma,
    const uword n_elem,
    const double pmSigma,
    bool cutTails)
{
  DiscreteRV drv;
  if (n_elem == 1) {
    drv.support = { mean };
    drv.probabilities = { 1.0 };
  } else {
    [[likely]] drv.support = linspace<vec>(mean - pmSigma * sigma, mean + pmSigma * sigma, n_elem);
    drv.probabilities = discretizeNormal(drv.support, mean, sigma, cutTails);
  }
  return drv;
}

/*
 *
 * VAR(1)
 *
 */
const MvNormal
VAR::conditional(vec& current) const
{
  MvNormal mvn;
  mvn.mean = m_intercept + m_rho * current;
  mvn.varCovar = m_sigma;
  return mvn;
}

void VAR::findStationary()
{
  const cx_vec theEigs = eig_gen(m_rho);
  if (any(abs(theEigs) >= 1.0)) {
    [[unlikely]] cout << "Eigenvalues exceeding 1 in abs value. Nonstationary."
                      << endl;
    is_stationary = false;
    m_statMean.reset();
    m_statSigma.reset();
    return;
  }

  is_stationary = true;

  const mat eyeRho = eye(m_size, m_size) - m_rho;
  m_statMean = solve(eyeRho, m_intercept);

  const mat kprod = kron(m_rho, m_rho);
  const mat theEye(kprod.n_rows, kprod.n_cols, fill::eye);
  const vec vecSigma = m_sigma.as_col();
  const vec tmp = solve(theEye - kprod, vecSigma);
  m_statSigma = reshape(tmp, m_rho.n_rows, m_rho.n_cols);
}

vec& VAR::stationaryMean()
{
  if (m_statMean.is_empty())
    findStationary();
  return m_statMean;
}

mat& VAR::stationarySigma()
{
  if (m_statSigma.is_empty())
    findStationary();
  return m_statSigma;
}

bool VAR::stationaryQ()
{
  if (m_statMean.is_empty())
    findStationary();
  return is_stationary;
}

void VAR::print()
{
  cout << "Intercept: " << endl;
  intercept().print();
  cout << "Rho: " << endl;
  rho().print();
  cout << "Sigma: " << endl;
  sigma().print();

  cout << "Stationary: " << endl;
  stationaryMean().print();
  cout << "Stationary Sigma: " << endl;
  stationarySigma().print();
}

/*
 *
 * Markov Chain
 *
 */
MarkovChain::MarkovChain(const AR process,
    const uword sz,
    const double pmMCsd,
    bool expSupport)
{
  m_size = sz;
  double pMean = process.stationaryMean();
  double pSd = process.stationarySigma();
  if (sz == 1)
    m_support = { pMean };
  else
    [[likely]] m_support = linspace<rowvec>(pMean - pmMCsd * pSd, pMean + pmMCsd * pSd, sz);

  m_tran.set_size(sz, sz);
#pragma omp parallel for
  for (uword rIx = 0; rIx < sz; ++rIx) {
    double condMean = process.intercept() + process.rho() * m_support(rIx);
    vec condPrs = discretizeNormal(m_support.t(), condMean, process.sigma());
    m_tran.row(rIx) = condPrs.t();
  }

  if (expSupport)
    m_support = exp(m_support);
}

rowvec
stationaryDistribution(const mat& transitionMatrix)
{
  cx_vec eigval;
  cx_mat eigvec;

  const mat tranT = transitionMatrix.t();
  const sp_mat sp_ver(tranT);

  eigs_opts opts;
  // opts.tol = 1.0E-6;
  eigs_gen(eigval, eigvec, sp_ver, 1, 1.0001, opts);

  const uword unitEigIx = (abs(abs(eigval) - 1.0)).index_min();

  cout << "Stationary eigenvalue " << eigval(unitEigIx) << endl;

  const rowvec stat = abs(eigvec.col(unitEigIx)).t();
  return stat / sum(stat);
}

uvec simulateChain(const mat& transitionMatrix,
    const uword initState,
    const uword simSz)
{
  const mat cumMat = cumsum(transitionMatrix, 1);
  const uword sz = transitionMatrix.n_rows;

  uvec state(simSz);

  state(0) = initState;
  const vec draws(simSz, fill::randu);
  for (uword tIx = 1; tIx < simSz; ++tIx) {
    uword newState = 0;
    for (uword stateIx = 1; stateIx < sz; ++stateIx)
      if (cumMat(state(tIx - 1), stateIx) > draws(tIx)) {
        newState = stateIx;
        break;
      }
    state(tIx) = newState;
  }

  return state;
}

const rowvec&
MarkovChain::stationary()
{
  if (m_stationary.is_empty()) {
    m_stationary = stationaryDistribution(m_tran);
  }

  return m_stationary;
}

void MarkovChain::save(const std::string fname) const
{
  m_support.save(hdf5_name(fname, "MC/support", hdf5_opts::replace));
  m_stationary.save(hdf5_name(fname, "MC/stationary", hdf5_opts::replace));
  m_tran.save(hdf5_name(fname, "MC/transitions", hdf5_opts::replace));
}

void MarkovChain::print() const
{ /* TODO */
}

void trimMarkovChain(mat& grids, mat& transition)
{
  /*
   * Based on Gordon 2020 wip.
   */
  rowvec probs = stationaryDistribution(transition);
  uword sz = probs.n_elem;

  uvec removePoints;
  uword removeCount = 0;
  for (uword ix = 0; ix < sz; ++ix)
    if (probs(ix) <= minPr) {
      [[likely]] removePoints.resize(removeCount + 1);
      removePoints(removeCount) = ix;
      removeCount++;
    }

  uword newSz = sz - removeCount;
  cout << "Removing " << removeCount << " points out of " << sz << "." << endl;

  grids.shed_rows(removePoints);
  transition.shed_rows(removePoints);
  transition.shed_cols(removePoints);
#pragma omp parallel for
  for (uword fIx = 0; fIx < newSz; ++fIx)
    transition.row(fIx) = transition.row(fIx) / sum(transition.row(fIx));
}

/*
 *
 * Discretized VAR(1)
 *
 */
void DiscreteVAR::impl(bool trimGrids, OrthoMethod method)
{
  // Sizing
  m_size = m_var.size();
  m_flatSize = prod(m_supportSizes);
  m_grids.set_size(m_flatSize, m_size);
  umat m_map(m_flatSize, m_size);

  OrthogonalizedVAR ortho(m_var, method);
  mat LL = ortho.getSupportRotationMatrix();
  VAR orthog = ortho.getVAR();

  const vec Atilde = orthog.intercept();
  const mat Btilde = orthog.rho();
  const vec DD = orthog.sigma().diag();

  const vec uncondE = orthog.stationaryMean();
  const vec uncondV = orthog.stationarySigma().diag();

  // Prepare logical grids
  field<vec> m_orthogGrids(m_size);
#pragma omp parallel for
  for (uword vIx = 0; vIx < m_size; ++vIx)
    if (m_supportSizes(vIx) > 1) {
      [[likely]] m_orthogGrids(vIx) = linspace<vec>(
          uncondE(vIx) - pmSd * sqrt(uncondV(vIx)),
          uncondE(vIx) + pmSd * sqrt(uncondV(vIx)),
          m_supportSizes(vIx));
    } else {
      m_orthogGrids(vIx) = { uncondE(vIx) };
    }

    // Prepare flat grids
#pragma omp parallel for
  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {
    uword tmp = flatIx;
    for (uword vIx = 0; vIx < m_size; ++vIx) {
      const vec logical = m_orthogGrids(vIx);
      m_map(flatIx, vIx) = tmp % m_supportSizes(vIx);
      m_grids(flatIx, vIx) = logical(m_map(flatIx, vIx));
      tmp = tmp / m_supportSizes(vIx);
    }
  }

  // Transition matrix
  m_tran.set_size(m_flatSize, m_flatSize);
  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {
    const rowvec tmpVal = m_grids.row(flatIx);
    const vec condMeans = Atilde + Btilde * tmpVal.t();
    const vec condSd = sqrt(DD);
    field<vec> condPrs(m_size);
#pragma omp parallel for
    for (uword vIx = 0; vIx < m_size; ++vIx)
      condPrs(vIx) = discretizeNormal(m_orthogGrids(vIx), condMeans(vIx), condSd(vIx));

#pragma omp parallel for
    for (uword flatPrIx = 0; flatPrIx < m_flatSize; ++flatPrIx) {
      double goPr = 1.0;
      for (uword vPrIx = 0; vPrIx < m_size; ++vPrIx) {
        vec tmpDist = condPrs(vPrIx);
        goPr *= tmpDist(m_map(flatPrIx, vPrIx));
      }
      m_tran(flatIx, flatPrIx) = goPr;
    }
  }

  // Adjust grids
  m_grids = (LL * m_grids.t()).t();

  if (trimGrids) {
    trimMarkovChain(m_grids, m_tran);
    m_flatSize = m_tran.n_rows;
  }

  // Finding midIx
  vec distances(m_flatSize);
  const vec target = m_var.stationaryMean();
#pragma omp parallel for
  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {
    const vec tmp = target - m_grids.row(flatIx).t();
    distances(flatIx) = sum(tmp % tmp);
  }
  m_midIx = distances.index_min();
}

void DiscreteVAR::print() const
{
  cout << "Grid:" << endl;
  m_grids.print();
  cout << endl
       << "Transition matrix: " << endl;
  m_tran.print();
}

void DiscreteVAR::save(const std::string fname) const
{
  uvec tmp = { m_midIx };
  tmp.save(hdf5_name(fname, "DVAR/midIx", hdf5_opts::replace));
  m_grids.save(hdf5_name(fname, "DVAR/grids", hdf5_opts::replace));
  m_tran.save(hdf5_name(fname, "DVAR/transitions", hdf5_opts::replace));
  m_var.intercept().save(
      hdf5_name(fname, "DVAR/varIntercept", hdf5_opts::replace));
  m_var.rho().save(hdf5_name(fname, "DVAR/varRho", hdf5_opts::replace));
  m_var.sigma().save(hdf5_name(fname, "DVAR/varSigma", hdf5_opts::replace));
}

/*
 *
 * Stochastic volatility VAR
 *
 */
void DiscreteStochVolVAR::impl(bool trimGrids)
{
  m_size = m_var.size();
  uword justDimsSz = prod(m_supportSizes);
  m_flatSize = justDimsSz * m_volGridSize;
  m_grids.set_size(m_flatSize, m_size + 1);
  umat m_map(m_flatSize, m_size + 1);

  const MarkovChain volMC(m_vol, m_volGridSize, pmSd, true);
  const rowvec& vols = volMC.support();
  const mat& volTran = volMC.transition();

  OrthogonalizedVAR ortho(m_var); // Default to Cholesky
  mat rotationLL = ortho.getSupportRotationMatrix();
  VAR orthog = ortho.getVAR();
  const vec uncondE = orthog.stationaryMean();
  const vec uncondV = orthog.stationarySigma().diag();

  const vec Atilde = orthog.intercept();
  const mat Btilde = orthog.rho();
  const vec DD = orthog.sigma().diag();

  // Prepare logical grids
  field<vec> m_orthogGrids(m_size, m_volGridSize);
#pragma omp parallel for collapse(2)
  for (uword volIx = 0; volIx < m_volGridSize; ++volIx)
    for (uword iIx = 0; iIx < m_size; ++iIx)
      if (m_supportSizes(iIx) > 1) {
        [[likely]] m_orthogGrids(iIx, volIx) = linspace<vec>(
            uncondE(iIx) - pmSd * vols(volIx) * sqrt(uncondV(iIx)),
            uncondE(iIx) + pmSd * vols(volIx) * sqrt(uncondV(iIx)),
            m_supportSizes(iIx));
      } else {
        m_orthogGrids(iIx, volIx) = { uncondE(iIx) };
      }

      // Prepare flat grids
#pragma omp parallel for collapse(2)
  for (uword volIx = 0; volIx < m_volGridSize; ++volIx) {
    for (uword flatIx = 0; flatIx < justDimsSz; ++flatIx) {
      uword withV = justDimsSz * volIx + flatIx;

      m_map(withV, m_size) = volIx;
      m_grids(withV, m_size) = vols(volIx);

      uword tmp = flatIx;
      for (uword iIx = 0; iIx < m_size; ++iIx) {
        const vec logical = m_orthogGrids(iIx, volIx);
        m_map(withV, iIx) = tmp % m_supportSizes(iIx);
        m_grids(withV, iIx) = logical(m_map(withV, iIx));
        tmp /= m_supportSizes(iIx);
      }
    }
  }

  // Transition matrix
  m_tran.set_size(m_flatSize, m_flatSize);
  m_tran.fill(0.0);
#pragma omp parallel for
  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {
    const uword thisVolIx = m_map(flatIx, m_size);
    const rowvec thisValues = m_grids.row(flatIx).head(m_size);
    const vec condMeans = Atilde + Btilde * thisValues.t();
    const vec condSdReference = sqrt(DD);

    field<vec> condPrs(m_size);
    for (uword iIx = 0; iIx < m_size; ++iIx)
      condPrs(iIx) = discretizeNormal(m_orthogGrids(iIx, thisVolIx), condMeans(iIx), vols(thisVolIx) * condSdReference(iIx));

    for (uword flatPrIx = 0; flatPrIx < m_flatSize; ++flatPrIx) {
      double goPr = 1.0;
      for (uword iiIx = 0; iiIx < m_size; ++iiIx) {
        const vec condPrVec = condPrs(iiIx);
        goPr *= condPrVec(m_map(flatPrIx, iiIx));
      }
      const uword vPrIx = m_map(flatPrIx, m_size);
      m_tran(flatIx, flatPrIx) = goPr * volTran(thisVolIx, vPrIx);
    }
  }

  // Adjust grids
  m_grids.cols(0, m_size - 1) = (rotationLL * m_grids.cols(0, m_size - 1).t()).t();

  if (trimGrids) {
    [[likely]] trimMarkovChain(m_grids, m_tran);
    m_flatSize = m_tran.n_rows;
  }

  // Finding midIx
  vec distances(m_flatSize);
  vec uncondEextended(m_size + 1);
  uncondEextended.head(m_size) = m_var.stationaryMean();
  uncondEextended(m_size) = vols(m_volGridSize / 2);
#pragma omp parallel for
  for (uword flatIx = 0; flatIx < m_flatSize; ++flatIx) {
    const vec tmp = uncondEextended - m_grids.row(flatIx).t();
    distances(flatIx) = sum(tmp % tmp);
  }
  m_midIx = distances.index_min();
}

void DiscreteStochVolVAR::save(const std::string fname) const
{
  uvec tmp = { m_midIx };
  tmp.save(hdf5_name(fname, "DsvVAR/midIx", hdf5_opts::replace));
  m_grids.save(hdf5_name(fname, "DsvVAR/grids", hdf5_opts::replace));
  m_tran.save(hdf5_name(fname, "DsvVAR/transitions", hdf5_opts::replace));
  m_var.intercept().save(
      hdf5_name(fname, "DsvVAR/varIntercept", hdf5_opts::replace));
  m_var.rho().save(hdf5_name(fname, "DsvVAR/varRho", hdf5_opts::replace));
  m_var.sigma().save(hdf5_name(fname, "DsvVAR/varSigma", hdf5_opts::replace));

  vec volAR = { m_vol.intercept(), m_vol.rho(), m_vol.sigma() };
  volAR.save(
      hdf5_name(fname, "DsvVAR/volatilityAR1params", hdf5_opts::replace));
}

void DiscreteStochVolVAR::print() const
{ /* TODO */
}

} // namespace TimeSeries

max_stars_repo_name: gabrielgggg/DiscretizeVAR

max_issues_repo_name: gabrielgggg/DiscretizeVAR

max_forks_repo_name: gabrielgggg/DiscretizeVAR


text:
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <fstream>
#include <iostream>

#include "account.h"
#include "algo.h"
#include "database.h"
#include "exchange_connectivity.h"
#include "logger.h"
#include "market_data.h"
#include "position.h"
#include "security.h"
#include "server.h"

namespace bpo = boost::program_options;
namespace fs = boost::filesystem;
using opentrade::AlgoManager;
using opentrade::ExchangeConnectivityManager;
using opentrade::MarketDataManager;
using opentrade::PositionManager;

int main(int argc, char *argv[]) {
  std::string config_file_path;
  std::string log_config_file_path;
  std::string db_url;
  uint16_t db_pool_size;
  bool disable_rms;
  bool db_create_tables;
  int io_threads;
  int algo_threads;
  int port;
  try {
    bpo::options_description config("Configuration");
    config.add_options()("help,h", "produce help message")(
        "config_file,c",
        bpo::value<std::string>(&config_file_path)
            ->default_value("opentrade.conf"),
        "config file path")("log_config_file,l",
                            bpo::value<std::string>(&log_config_file_path)
                                ->default_value("log.conf"),
                            "log4cxx config file path")(
        "db_url", bpo::value<std::string>(&db_url), "database connection url")(
        "db_create_tables",
        bpo::value<bool>(&db_create_tables)->default_value(false),
        "create database tables")(
        "db_pool_size", bpo::value<uint16_t>(&db_pool_size)->default_value(4),
        "database connection pool size")(
        "port", bpo::value<int>(&port)->default_value(9111), "listen port")(
        "io_threads", bpo::value<int>(&io_threads)->default_value(1),
        "number of web server io threads")(
        "algo_threads", bpo::value<int>(&algo_threads)->default_value(1),
        "number of algo threads")(
        "disable_rms", bpo::value<bool>(&disable_rms)->default_value(false),
        "whether disable rms");

    bpo::options_description config_file_options;
    config_file_options.add(config);
    bpo::variables_map vm;

    bpo::store(bpo::parse_command_line(argc, argv, config), vm);
    bpo::notify(vm);
    if (vm.count("help")) {
      std::cerr << config << std::endl;
      return 1;
    }

    std::ifstream ifs(config_file_path.c_str());
    if (ifs) {
      bpo::store(parse_config_file(ifs, config_file_options, true), vm);
    } else {
      std::cerr << config_file_path << " not found" << std::endl;
      return 1;
    }

    bpo::store(bpo::parse_command_line(argc, argv, config), vm);
    bpo::notify(vm);  // make command line option higher priority
  } catch (bpo::error &e) {
    std::cerr << "Bad Options: " << e.what() << std::endl;
    return 1;
  }

  if (!std::ifstream(log_config_file_path.c_str()).good()) {
    std::ofstream(log_config_file_path)
        .write(opentrade::kDefaultLogConf, strlen(opentrade::kDefaultLogConf));
  }

  opentrade::Logger::Initialize("opentrade", log_config_file_path);

  auto path = fs::path(".") / "store";
  if (!fs::exists(path)) {
    fs::create_directory(path);
  }

  if (db_url.empty()) {
    LOG_ERROR("db_url not configured");
    return 1;
  }

  opentrade::Database::Initialize(db_url, db_pool_size, db_create_tables);
  opentrade::SecurityManager::Initialize();
  AlgoManager::Initialize();

  boost::property_tree::ptree prop_tree;
  boost::property_tree::ini_parser::read_ini(config_file_path, prop_tree);
  for (auto &section : prop_tree) {
    if (!section.second.size()) continue;
    auto section_name = section.first;
    opentrade::Adapter::StrMap params;
    for (auto &item : section.second) {
      auto name = item.first;
      boost::to_lower(name);
      params[name] = item.second.data();
    }
    auto sofile = params["sofile"];
    if (sofile.empty()) continue;
    params.erase("sofile");
    auto adapter = opentrade::Adapter::Load(sofile);
    adapter->set_name(section_name);
    adapter->set_config(params);
    if (adapter->GetVersion() != opentrade::kApiVersion) {
      LOG_FATAL("Version mismatch");
    }
    if (section_name.find("md_") == 0) {
      auto md = dynamic_cast<opentrade::MarketDataAdapter *>(adapter);
      if (!md) LOG_FATAL("Failed to create MarketDataAdapter");
      MarketDataManager::Instance().Add(md);
    } else if (section_name.find("ec_") == 0) {
      auto ec = dynamic_cast<opentrade::ExchangeConnectivityAdapter *>(adapter);
      if (!ec) LOG_FATAL("Failed to create ExchangeConnectivityAdapter");
      ExchangeConnectivityManager::Instance().Add(ec);
    } else {
      auto algo = dynamic_cast<opentrade::Algo *>(adapter);
      if (!algo) LOG_FATAL("Failed to create Algo");
      AlgoManager::Instance().Add(algo);
    }
  }

  opentrade::AccountManager::Initialize();
  PositionManager::Initialize();
  opentrade::GlobalOrderBook::Initialize();
  for (auto &p : MarketDataManager::Instance().adapters()) {
    p.second->Start();
  }
  for (auto &p : ExchangeConnectivityManager::Instance().adapters()) {
    p.second->Start();
  }
  for (auto &p : AlgoManager::Instance().adapters()) {
    p.second->Start();
  }

  PositionManager::Instance().UpdatePnl();
  AlgoManager::Instance().Run(algo_threads);
  opentrade::Server::Start(port, io_threads);

  return 0;
}

ext: cc