text:
#include <chrono>
#include <shift/log/log_server.hpp>
#include <shift/math/vector.hpp>
#include <shift/core/exception.hpp>
#include <shift/core/algorithm.hpp>
#include <shift/core/at_exit_scope.hpp>
#include <shift/platform/environment.hpp>
#include <boost/test/unit_test.hpp>
#include <filesystem>
#include <fstream>
#include <array>

// struct init_current_working_path
//{
//  init_current_working_path() noexcept
//  {
//    using namespace std::filesystem;
//    try
//    {
//      current_path(path(shift::platform::environment::executable_path())
//                     .parent_path()
//                     .parent_path());
//    }
//    catch (...)
//    {
//      std::terminate();
//    }
//  }
//};
//
// static init_current_working_path init;
//
// namespace shift
//{
// namespace render
//{
//  namespace vk
//  {
//    struct swapchain_element
//    {
//      swapchain_element() = default;
//
//      swapchain_element(swapchain_element&&) = default;
//
//      swapchain_element& operator=(swapchain_element&&) = default;
//
//      boost::intrusive_ptr<vk::image> image;
//      boost::intrusive_ptr<vk::image_view> image_view;
//      boost::intrusive_ptr<vk::framebuffer> framebuffer;
//    };
//
//    class test_application
//    {
//    public:
//      void run();
//
//    protected:
//      ///
//      virtual const physical_device& select_physical_device(
//        const std::vector<physical_device>& devices);
//
//      ///
//      void create_resources();
//
//      ///
//      void destroy_resources();
//
//      ///
//      void resize_window();
//
//      ///
//      void create_init_command_buffer();
//
//      ///
//      void destroy_init_command_buffer();
//
//      ///
//      void flush_init_command_buffer();
//
//      ///
//      void create_swapchain();
//
//      ///
//      void destroy_swapchain();
//
//      ///
//      void create_depth_buffer();
//
//      ///
//      void destroy_depth_buffer();
//
//      ///
//      void create_pipeline();
//
//      ///
//      void destroy_pipeline();
//
//    private:
//      ///
//      void image_layout_transition(
//        vk::image& image, vk::image_aspect_flags aspect_mask,
//        vk::image_layout old_image_layout, vk::image_layout new_image_layout,
//        std::uint32_t source_queue_family_index = 0,
//        std::uint32_t destination_queue_family_index = 0);
//
//      bool _quit = false;
//      core::stack_ptr<vk::renderer> _renderer;
//      std::unique_ptr<vk::window> _window;
//      boost::intrusive_ptr<vk::device> _device;
//
//      std::vector<swapchain_element> _swapchain_elements;
//
//      boost::intrusive_ptr<vk::command_buffer> _init_command_buffer;
//
//      boost::intrusive_ptr<vk::image> _depth_image;
//      boost::intrusive_ptr<vk::image_view> _depth_image_view;
//
//      std::uint32_t _current_buffer = 0;
//    };
//
//    void test_application::run()
//    {
//      using namespace shift;
//      using namespace shift::render;
//
//      _renderer.create(1, "test.shift.render.vk", 1,
//                       vk::debug_flag::vk_standard_validation);
//      auto destroy_renderer =
//        core::make_at_exit_scope([&]() { _renderer.destroy(); });
//
//      const auto& physical_devices = _renderer->available_physical_devices();
//      // Query fine-grained feature support for these devices. If the app has
//      // specific feature requirements it should filter here unsupported
//      // devices.
//      _window = _renderer->create_window(
//        {100, 100}, {800u, 600u},
//        vk::window_flag::resizeable | vk::window_flag::decorated,
//        *physical_devices.front());
//      _window->on_close.connect([&]() { _quit = true; });
//      _window->on_resize.connect([&](math::vector<2, std::uint32_t> size) {
//        // destroy_application_resources();
//        resize_window();
//        // create_application_resources();
//      });
//      _window->on_key.connect(
//        [&](int key, int scancode, int action, int mods) {});
//      _window->on_mouse_button.connect(
//        [&](int button, int action, int mods) {});
//      _window->visible(true);
//      _window->create_surface();
//
//      _device = _renderer->create_device(*_window);
//
//      create_resources();
//
//      using namespace std::chrono;
//      // Main message processing loop.
//      auto start = high_resolution_clock::now();
//      auto now = start;
//      auto last_fps_update = start;
//      std::size_t fps_counter = 0;
//      while (!_quit && (now - start <= 30s))
//      {
//        // Wait for work to finish before updating MVP.
//        _device->wait_idle();
//
//        auto& primary_command_buffer = _window->primary_command_buffer();
//        primary_command_buffer.begin(vk::command_buffer_begin_info{});
//        primary_command_buffer.end();
//
//        _window->present();
//        _renderer->update();
//
//        glfwPollEvents();
//
//        now = high_resolution_clock::now();
//        ++fps_counter;
//        if (now - last_fps_update >= 1s)
//        {
//          shift::log::status()
//            << (fps_counter * 1000.0f /
//                duration_cast<milliseconds>(now - last_fps_update).count())
//            << " fps";
//          fps_counter = 0;
//          last_fps_update = now;
//        }
//      }
//
//      destroy_resources();
//    }
//
//    const physical_device& test_application::select_physical_device(
//      const std::vector<physical_device>& devices)
//    {
//      return devices.front();
//    }
//
//    void test_application::create_resources()
//    {
//      _device->create_resources();
//      create_init_command_buffer();
//      _window->create_swapchain(*_device);
//      create_swapchain();
//      create_depth_buffer();
//      create_pipeline();
//    }
//
//    void test_application::destroy_resources()
//    {
//      destroy_pipeline();
//      destroy_depth_buffer();
//      destroy_swapchain();
//      _window->destroy_swapchain();
//      destroy_init_command_buffer();
//      _device->destroy_resources();
//    }
//
//    void test_application::resize_window()
//    {
//      destroy_pipeline();
//      destroy_depth_buffer();
//      destroy_swapchain();
//      _swapchain_elements.clear();  // ?
//
//      _device->collect_garbage();
//      _window->create_swapchain(*_device);
//      create_swapchain();
//      create_depth_buffer();
//      create_pipeline();
//    }
//
//    void test_application::create_init_command_buffer()
//    {
//      BOOST_ASSERT(!_init_command_buffer);
//      _init_command_buffer =
//        _device->create_command_buffer(true,
//        vk::command_buffer_level::primary);
//      _init_command_buffer->begin(vk::command_buffer_begin_info(
//        /* flags */ vk::command_buffer_usage_flag::one_time_submit_bit,
//        /* inheritance_info */ nullptr));
//    }
//
//    void test_application::destroy_init_command_buffer()
//    {
//      _init_command_buffer.reset();
//    }
//
//    void test_application::flush_init_command_buffer()
//    {
//      BOOST_ASSERT(_init_command_buffer);
//
//      _init_command_buffer->end();
//
//      VkFence null_fence = VK_NULL_HANDLE;
//
//      vk_check(vk::queue_submit(
//        _device->graphics_queue().handle(), 1,
//        core::rvalue_address(vk::submit_info(
//          /* wait_semaphore_count */ 0,
//          /* wait_semaphores */ nullptr,
//          /* wait_dst_stage_mask */ nullptr,
//          /* command_buffer_count */ 1,
//          /* command_buffers */ &_init_command_buffer->handle(),
//          /* signal_semaphore_count */ 0,
//          /* signal_semaphores */ nullptr)),
//        null_fence));
//      _device->graphics_queue().wait_idle();
//
//      destroy_init_command_buffer();
//      create_init_command_buffer();
//    }
//
//    void test_application::create_swapchain()
//    {
//      // Extract images from swapchain.
//      auto& swapchain = _window->swapchain();
//      auto swapchain_images = swapchain.images();
//      _swapchain_elements.resize(swapchain.image_count());
//      for (auto i = 0u; i < _swapchain_elements.size(); ++i)
//      {
//        _swapchain_elements[i].image =
//          _device->create_image(swapchain.image_handle(i),
//          vk::image_type::_2d,
//                                swapchain.surface_format(),
//                                vk::extent_3d{swapchain.extent().width(),
//                                              swapchain.extent().height(),
//                                              1u},
//                                1u, 1u);
//
//        // Render loop will expect image to:
//        // - have been used before
//        // - be in vk::image_layout::present_src_khr layout
//        // - will change to COLOR_ATTACHMENT_OPTIMAL layout
//        // so init the image to that state.
//        _init_command_buffer->pipeline_barrier(
//          vk::pipeline_stage_flag::top_of_pipe_bit,
//          vk::pipeline_stage_flag::bottom_of_pipe_bit, 0,
//          vk::image_memory_barrier(
//            /* src_access_mask */ vk::access_flag::none,
//            /* dst_access_mask */ vk::access_flag::memory_read_bit,
//            /* old_layout */ vk::image_layout::undefined,
//            /* new_layout */ vk::image_layout::present_src_khr,
//            /* src_queue_family_index */
//            _device->graphics_queue_family_index(),
//            /* dst_queue_family_index */
//            _device->present_queue_family_index(),
//            /* image */ _swapchain_elements[i].image->handle(),
//            /* subresource_range */
//            vk::image_subresource_range(
//              /* aspect_mask */ vk::image_aspect_flag::color_bit,
//              /* base_mip_level */ 0,
//              /* level_count */ 1,
//              /* base_array_layer */ 0,
//              /* layer_count */ 1)));
//
//        _swapchain_elements[i].image_view = _device->create_image_view(
//          vk::image_view_create_info(
//            /* flags */ 0,
//            /* image */ _swapchain_elements[i].image->handle(),
//            /* view_type */ vk::image_view_type::_2d,
//            /* format */ _window->surface().format(),
//            /* components */
//            vk::component_mapping{
//              vk::component_swizzle::r, vk::component_swizzle::g,
//              vk::component_swizzle::b, vk::component_swizzle::a},
//            /* subresource_range */
//            vk::image_subresource_range(
//              /* aspect_mask */ vk::image_aspect_flag::color_bit,
//              /* base_mip_level */ 0,
//              /* level_count */ 1,
//              /* base_array_layer */ 0,
//              /* layer_count */ 1)),
//          *_swapchain_elements[i].image);
//      }
//    }
//
//    void test_application::destroy_swapchain()
//    {
//      /// ToDo: Simply clearing the vector should be sufficient.
//      _swapchain_elements.clear();
//    }
//
//    void test_application::create_depth_buffer()
//    {
//      // const VkFormat depth_format = vk::format::d16_unorm;
//      const vk::format depth_format = vk::format::d32_sfloat;
//      _depth_image = _device->create_image(vk::image_create_info(
//        /* flags */ vk::image_create_flag::none,
//        /* image_type */ vk::image_type::_2d,
//        /* format */ depth_format,
//        /* extent */
//        vk::extent_3d{_window->size().width, _window->size().height, 1u},
//        /* mip_levels */ 1,
//        /* array_layers */ 1,
//        /* samples */ vk::sample_count_flag::_1_bit,
//        /* tiling */ vk::image_tiling::optimal,
//        /* usage */ vk::image_usage_flag::depth_stencil_attachment_bit,
//        /* sharing_mode */ vk::sharing_mode::exclusive,
//        /* queue_family_index_count */ 0,
//        /* queue_family_indices */ nullptr,
//        /* initial_layout */ vk::image_layout::undefined));
//
//      _depth_image->allocate_storage(
//        vk::memory_property_flag::device_local_bit);
//
//      image_layout_transition(
//        *_depth_image, vk::image_aspect_flag::depth_bit,
//        vk::image_layout::undefined,
//        vk::image_layout::depth_stencil_attachment_optimal);
//
//      _depth_image_view = _device->create_image_view(
//        vk::image_view_create_info(
//          /* flags */ 0,
//          /* image */ _depth_image->handle(),
//          /* view_type */ vk::image_view_type::_2d,
//          /* format */ depth_format,
//          /* components */ vk::component_mapping{},
//          /* subresource_range */
//          vk::image_subresource_range(
//            /* aspect_mask */ vk::image_aspect_flag::depth_bit,
//            /* base_mip_level */ 0,
//            /* level_count */ 1,
//            /* base_array_layer */ 0,
//            /* layer_count */ 1)),
//        *_depth_image);
//    }
//
//    void test_application::destroy_depth_buffer()
//    {
//      _depth_image_view.reset();
//      _depth_image.reset();
//    }
//
//    void test_application::create_pipeline()
//    {
//      _window->create_pipeline();
//      flush_init_command_buffer();
//      _current_buffer = 0;
//    }
//
//    void test_application::destroy_pipeline()
//    {
//      _window->destroy_pipeline();
//    }
//
//    void test_application::image_layout_transition(
//      vk::image& image, vk::image_aspect_flags aspect_mask,
//      vk::image_layout old_image_layout, vk::image_layout new_image_layout,
//      std::uint32_t source_queue_family_index,
//      std::uint32_t destination_queue_family_index)
//    {
//      VkAccessFlags dst_access_mask;
//      /// ToDo: Review this automatic flag assignment logic.
//      if (new_image_layout == vk::image_layout::transfer_dst_optimal)
//      {
//        // Make sure anything that was copying from this image has completed
//        dst_access_mask = VK_ACCESS_TRANSFER_READ_BIT;
//      }
//      else if (new_image_layout == vk::image_layout::color_attachment_optimal)
//      {
//        dst_access_mask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
//      }
//      else if (new_image_layout ==
//               vk::image_layout::depth_stencil_attachment_optimal)
//      {
//        dst_access_mask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
//      }
//      else if (new_image_layout == vk::image_layout::shader_read_only_optimal)
//      {
//        // Make sure any Copy or CPU writes to image are flushed
//        dst_access_mask =
//          VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT;
//      }
//      else
//        dst_access_mask = 0;
//
//      _init_command_buffer->pipeline_barrier(
//        VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
//        0, vk::image_memory_barrier(
//          /* src_access_mask */ vk::access_flag::none,
//          /* dst_access_mask */ dst_access_mask,
//          /* old_layout */ old_image_layout,
//          /* new_layout */ new_image_layout,
//          /* src_queue_family_index */ source_queue_family_index,
//          /* dst_queue_family_index */ destination_queue_family_index,
//          /* image */ image.handle(),
//          /* subresource_range */
//          vk::image_subresource_range(
//            /* aspect_mask */ aspect_mask,
//            /* base_mip_level */ 0,
//            /* level_count */ 1,
//            /* base_array_layer */ 0,
//            /* layer_count */ 1)));
//    }
//  }
//}
//}
//
// using namespace shift;
//
// BOOST_AUTO_TEST_CASE(window_test)
//{
//  using namespace std::chrono;
//  using namespace shift::log;
//  using namespace shift::render;
//
//  log_server::create();
//  auto destroy_log_server =
//    shift::core::make_at_exit_scope([]() { log_server::destroy(); });
//  log_server::singleton_instance().add_console_sink();
//
//  shift::render::vk::test_application my_test_application;
//  my_test_application.run();
//}

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
//          Copyright Dean Michael Berris 2008.
// 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)

#define BOOST_TEST_MODULE HTTP message test
#include <boost/config/warning_disable.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/network/protocol/http.hpp>
// #include <boost/network/protocol/http/traits.hpp>
#include <algorithm>

using namespace boost::network;

typedef boost::mpl::list<tags::http_default_8bit_tcp_resolve, tags::http_default_8bit_udp_resolve, tags::http_keepalive_8bit_tcp_resolve, tags::http_keepalive_8bit_udp_resolve> tag_types;

struct fixtures {
};

BOOST_FIXTURE_TEST_SUITE(http_message_test_suite, fixtures)

BOOST_AUTO_TEST_CASE_TEMPLATE (request_constructor_test, T, tag_types) {
    http::basic_request<T> request("http://boost.org");
    BOOST_CHECK_EQUAL ( request.host() , "boost.org" );
    BOOST_CHECK_EQUAL ( request.port() , 80u );
    BOOST_CHECK_EQUAL ( request.path() , "/" );
}

BOOST_AUTO_TEST_CASE_TEMPLATE (request_copy_constructor_test, T, tag_types) {
    http::basic_request<T> request("http://boost.org/handler.php");
    request << header("Content-Type", "text/plain")
            << body("Hello, World!")
        ;
    http::basic_request<T> copy(request);
    BOOST_CHECK_EQUAL ( copy.host(), request.host() );
    BOOST_CHECK_EQUAL ( copy.port(), request.port() );
    BOOST_CHECK_EQUAL ( request.path(), request.path() );
    BOOST_CHECK_EQUAL ( body(request), body(copy) );
}

BOOST_AUTO_TEST_CASE_TEMPLATE (request_assignment_test, T, tag_types) {
    http::basic_request<T> request("http://boost.org/handler.php");
    request << header("Content-Type", "text/plain")
            << body("Hello, World!")
        ;
    http::basic_request<T> copy;
    copy = request;
    BOOST_CHECK_EQUAL ( copy.host(), request.host() );
    BOOST_CHECK_EQUAL ( copy.port(), request.port() );
    BOOST_CHECK_EQUAL ( request.path(), request.path() );
    BOOST_CHECK_EQUAL ( body(request), body(copy) );
}

BOOST_AUTO_TEST_CASE_TEMPLATE (request_swap_test, T, tag_types) {
    boost::network::http::basic_request<T> request("http://boost.org/");
    boost::network::http::basic_request<T> other;
    swap(other, request); // ADL
    BOOST_CHECK_EQUAL ( request.host(), "" );
    BOOST_CHECK_EQUAL ( request.port(), 80u );
    BOOST_CHECK_EQUAL ( request.path(), "/" );
    BOOST_CHECK_EQUAL ( other.host(), "boost.org" );
    BOOST_CHECK_EQUAL ( other.port(), 80u );
    BOOST_CHECK_EQUAL ( other.path(), "/" );
}

BOOST_AUTO_TEST_CASE_TEMPLATE (response_constructor_test, T, tag_types) {
    http::basic_response<T> response;
    BOOST_CHECK_EQUAL ( body(response), std::string() );
}

BOOST_AUTO_TEST_CASE_TEMPLATE (response_copy_construct_test, T, tag_types) {
    http::basic_response<T> response;
    response.version() = "HTTP/1.1";
    response.status() = 200;
    response.status_message() = "OK";
    response << body("The quick brown fox jumps over the lazy dog");
    http::basic_response<T> copy(response);
    BOOST_CHECK_EQUAL ( response.version(), copy.version() );
    BOOST_CHECK_EQUAL ( response.status(), copy.status() );
    BOOST_CHECK_EQUAL ( response.status_message(), copy.status_message() );
    BOOST_CHECK_EQUAL ( body(response), body(copy) );
}

BOOST_AUTO_TEST_CASE_TEMPLATE (response_assignment_construct_test, T, tag_types) {
    http::basic_response<T> response;
    response.version() = "HTTP/1.1";
    response.status() = 200;
    response.status_message() = "OK";
    response << body("The quick brown fox jumps over the lazy dog");
    http::basic_response<T> copy;
    copy = response;
    BOOST_CHECK_EQUAL ( response.version(), copy.version() );
    BOOST_CHECK_EQUAL ( response.status(), copy.status() );
    BOOST_CHECK_EQUAL ( response.status_message(), copy.status_message() );
    BOOST_CHECK_EQUAL ( body(response), body(copy) );
}

BOOST_AUTO_TEST_CASE_TEMPLATE (response_swap_test, T, tag_types) {
    http::basic_response<T> response;
    response.version() = "HTTP/1.1";
    response.status() = 200;
    response.status_message() = "OK";
    response << boost::network::body("RESPONSE");
    boost::network::http::basic_response<T> swapped;
    BOOST_REQUIRE_NO_THROW(swap(response, swapped));
    BOOST_CHECK_EQUAL ( response.version(), std::string() );
    BOOST_CHECK_EQUAL ( response.status(), 0u );
    BOOST_CHECK_EQUAL ( response.status_message(), std::string() );
    BOOST_CHECK_EQUAL ( boost::network::body(response), std::string() );
    BOOST_CHECK_EQUAL ( swapped.version(), std::string("HTTP/1.1") );
    BOOST_CHECK_EQUAL ( swapped.status(), 200u );
    BOOST_CHECK_EQUAL ( swapped.status_message(), std::string("OK") );
    BOOST_CHECK_EQUAL ( boost::network::body(swapped), std::string("RESPONSE") );
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: mclow/cpp-netlib

max_issues_repo_name: mclow/cpp-netlib

max_forks_repo_name: mclow/cpp-netlib


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
// Copyright (c) 2022 Alan de Freitas (alandefreitas@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/url
//

#ifndef BOOST_URL_DETAIL_PARAMS_ITERATOR_IMPL_HPP
#define BOOST_URL_DETAIL_PARAMS_ITERATOR_IMPL_HPP

#include <boost/url/string_view.hpp>
#include <boost/url/params_view.hpp>
#include <string>

namespace boost {
namespace urls {
namespace detail {

struct params_iterator_impl
{
    std::size_t i_ = 0;
    char const* begin_ = nullptr;
    char const* pos_ = nullptr;
    std::size_t nk_ = 0;
    std::size_t nv_ = 0;
    char const* end_ = nullptr;
    const_string::factory a_;

    BOOST_URL_DECL
    void scan() noexcept;

    BOOST_URL_DECL
    params_iterator_impl(
        string_view s,
        const_string::factory a) noexcept;

    // end ctor
    BOOST_URL_DECL
    params_iterator_impl(
        string_view s,
        std::size_t nparam,
        int,
        const_string::factory a) noexcept;

    params_iterator_impl() = default;

    params_iterator_impl(
        params_iterator_impl const&) noexcept = default;

    params_iterator_impl& operator=(
        params_iterator_impl const&) noexcept = default;

    string_view
    encoded_key() const noexcept;

    BOOST_URL_DECL
    params_view::reference
    dereference() const noexcept;

    BOOST_URL_DECL
    void
    increment() noexcept;

    bool
    equal(
        params_iterator_impl const& other) const noexcept
    {
        BOOST_ASSERT(begin_ == other.begin_);
        BOOST_ASSERT(end_ == other.end_);
        return
            pos_ == other.pos_ &&
            i_ == other.i_;
    }
};

} // detail
} // urls
} // boost

#endif

ext: hpp

max_stars_repo_name: abitmore/url

max_issues_repo_name: abitmore/url

max_forks_repo_name: abitmore/url


text:
#pragma once
#ifndef BASIS_ANGULAR_HPP
#define BASIS_ANGULAR_HPP

// c++ libraries
#include <ostream>
//eigen
#include <Eigen/Dense>
// symmetry functions
#include "src/nnp/cutoff.hpp"
#include "src/nnp/symm_angular.hpp"
// serialize
#include "src/mem/serialize.hpp"

#ifndef BASIS_ANGULAR_PRINT_FUNC
#define BASIS_ANGULAR_PRINT_FUNC 0
#endif

struct BasisA{
private:
	double rc_;//cutoff radius
	double norm_;//normalization factor
	PhiAN phiAN_;//type of angular functions
	cutoff::Norm normT_;//normalization scheme
	int nfA_;//number of angular functions
	cutoff::Func* cutoff_;//cutoff function
	PhiA** fA_;//angular functions
	Eigen::VectorXd symm_;//symmetry function
public:
	//==== constructors/destructors ====
	BasisA():normT_(cutoff::Norm::UNKNOWN),phiAN_(PhiAN::UNKNOWN),nfA_(0),fA_(NULL),cutoff_(NULL){}
	BasisA(const BasisA& basisA);
	~BasisA();

	//==== operators ====
	BasisA& operator=(const BasisA& basisA);
	friend std::ostream& operator<<(std::ostream& out, const BasisA& basisA);

	//==== initialization ====
	void init_G3(int nA, cutoff::Norm norm, cutoff::Name tcut, double rcut);
	void init_G4(int nA, cutoff::Norm norm, cutoff::Name tcut, double rcut);

	//==== reading/writing ====
	static void write(const char* file,const BasisA& basis);
	static void read(const char* file, BasisA& basis);
	static void write(FILE* writer,const BasisA& basis);
	static void read(FILE* writer, BasisA& basis);

	//==== member access ====
	cutoff::Func* cutoff(){return cutoff_;}
	const cutoff::Func* cutoff()const{return cutoff_;}
	double& rc(){return rc_;}
	const double& rc()const{return rc_;}
	const int& nfA()const{return nfA_;}
	PhiAN& phiAN(){return phiAN_;}
	const PhiAN& phiAN()const{return phiAN_;}
	cutoff::Norm& normT(){return normT_;}
	const cutoff::Norm& normT()const{return normT_;}
	PhiA& fA(int i){return *fA_[i];}
	const PhiA& fA(int i)const{return *fA_[i];}
	Eigen::VectorXd& symm(){return symm_;}
	const Eigen::VectorXd& symm()const{return symm_;}

	//==== member functions ====
	void clear();
	void symm(double cos, const double d[3]);
	void force(double& phi, double* eta, double cos, const double d[3], const double* dEdG)const;

	//==== static functions ====
	static double norm(cutoff::Norm normT, double rc);
};

bool operator==(const BasisA& basis1, const BasisA& basis2);
inline bool operator!=(const BasisA& basis1, const BasisA& basis2){return !(basis1==basis2);}

namespace serialize{

	//**********************************************
	// byte measures
	//**********************************************

	template <> int nbytes(const BasisA& obj);

	//**********************************************
	// packing
	//**********************************************

	template <> int pack(const BasisA& obj, char* arr);

	//**********************************************
	// unpacking
	//**********************************************

	template <> int unpack(BasisA& obj, const char* arr);

}

#endif

max_stars_repo_name: markdellostritto/AtomNN

max_issues_repo_name: markdellostritto/AtomNN

max_forks_repo_name: markdellostritto/AtomNN


text:
/*
 * Imu.hpp
 *
 *  Created on: Apr 30, 2021
 *      Author: jelavice
 */

#pragma once
#include <Eigen/Dense>
#include "icp_localization/common/time.hpp"

#include <sensor_msgs/Imu.h>

namespace icp_loco {

template<typename FloatType>
class ImuReading
{
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  using Vector = Eigen::Matrix<FloatType, 3, 1>;
  using Quaternion = Eigen::Quaternion<FloatType>;
  ImuReading()
      : ImuReading(Vector::Zero(), Vector::Zero(), Quaternion::Identity())
  {
  }
  ImuReading(const Vector& lin, const Vector& ang)
      : ImuReading(lin, ang, Quaternion::Identity())
  {
  }

  ImuReading(const Vector& lin, const Vector& ang, const Quaternion &q)
      : acc_(lin),
        angVel_(ang),
        q_(q)
  {
  }

  template<typename OtherType>
  ImuReading<OtherType> cast() const
  {
    return ImuReading<OtherType>(acc_.template cast<OtherType>(),
                                 angVel_.template cast<OtherType>(), q_.template cast<OtherType>());
  }

  const Vector& acceleration() const
  {
    return acc_;
  }
  const Vector& angularVelocity() const
  {
    return angVel_;
  }
  const Quaternion& rotation() const
  {
    return q_;
  }

  Vector& acceleration()
  {
    return acc_;
  }
  Vector& angularVelocity()
  {
    return angVel_;
  }
  Quaternion& rotation()
  {
    return q_;
  }

  std::string asString() const{
    const double kRadToDeg = 180.0 / M_PI;

    const std::string acc  =  string_format("acc:[%f, %f, %f]", acc_.x(), acc_.y(), acc_.z());
    const std::string angVel  =  string_format("angVel:[%f, %f, %f]", angVel_.x(), angVel_.y(), angVel_.z());
    const std::string rot = string_format("q:[%f, %f, %f, %f]",q_.x(), q_.y(), q_.z(), q_.w());
    const auto rpy = toRPY(q_) * kRadToDeg;
    const std::string rpyString = string_format("rpy (deg):[%f, %f, %f]",rpy.x(), rpy.y(),rpy.z());
    return acc + " ; " +angVel + " ; " + rot + " ; " + rpyString;
  }

 private:
  Vector acc_;
  Vector angVel_;
  Quaternion q_;
};

using ImuReadingd = ImuReading<double>;
using ImuReadingf = ImuReading<float>;

struct TimestampedImuReading
{
  Time time_;
  ImuReadingd imu_;
};

TimestampedImuReading interpolate(const TimestampedImuReading& start, const TimestampedImuReading& end,
                             const Time &time);

TimestampedImuReading fromRos(const sensor_msgs::Imu &msg);

} // namespace icp_loco


text:
#ifndef PEPLUS_DETAIL_FACADES_BASERELOCATIONFACADE_HPP_
#define PEPLUS_DETAIL_FACADES_BASERELOCATIONFACADE_HPP_

#include <peplus/headers.hpp>
#include <peplus/detail/entry_range.hpp>
#include <peplus/detail/image_helpers.hpp>
#include <peplus/detail/image_offset.hpp>
#include <peplus/detail/transform_range.hpp>

#include <boost/endian/conversion.hpp>

#include <tuple>

namespace peplus::detail {

struct RelocationEntry
{
	WORD          type;
	VirtualOffset address;
};

class rel_type_offset_to_relocation_entry_transformer
{
public:
	explicit rel_type_offset_to_relocation_entry_transformer(VirtualOffset relbase)
		: _base_rva { relbase } {}

	RelocationEntry operator()(WORD type_offset) const
	{
		RelocationEntry relocation_entry;
		const auto reloc_offset = type_offset & ((2 << 12) - 1);
		relocation_entry.address = _base_rva + reloc_offset;
		relocation_entry.type = (type_offset & ((2 << 4) - 1)) >> 12;
		return relocation_entry;
	}

private:
	VirtualOffset _base_rva;
};

template <class Image, class Offset = typename Image::offset_type>
class BaseRelocationFacade : public PointedValue<Offset, BaseRelocation>
{
public:
	using offset_type = Offset;

	using RelTypeOffsetRange = EntryRange <
		Image, read_pointed_value<read_trivial_le_value<WORD>>,
		fixed_distance_advance_pointer_policy<constexpr_<sizeof(WORD)>>,
		fixed_distance_stop_iteration_policy<runtime_param<0>>,
		std::size_t
	>;

	using RelocationEntryRange = TransformRange <
		rel_type_offset_to_relocation_entry_transformer,
		RelTypeOffsetRange
	>;

	BaseRelocationFacade(const Image & image, offset_type offset);

	RelocationEntryRange entries() const;

private:
	RelTypeOffsetRange type_offsets() const;

	const Image * _image;
};

template <class Image, class Offset = typename Image::offset_type>
BaseRelocation read_base_relocation_from_image(const Image & image, Offset offset)
{
	BaseRelocation base_relocation;
	image_do_read(image, offset, sizeof(BaseRelocation), &base_relocation);
	boost::endian::little_to_native_inplace(base_relocation.virtual_address);
	boost::endian::little_to_native_inplace(base_relocation.size_of_block  );
	return base_relocation;
}

template <class Image, class Offset>
BaseRelocationFacade<Image, Offset>::BaseRelocationFacade(const Image & image, offset_type offset)
	: PointedValue<Offset, BaseRelocation> { offset, read_base_relocation_from_image(image, offset) }
	, _image { &image } {}

template <class Image, class Offset>
auto BaseRelocationFacade<Image, Offset>::entries() const -> RelocationEntryRange
{
	const VirtualOffset reloc_base { this->virtual_address };
	rel_type_offset_to_relocation_entry_transformer to_relocation_entries { reloc_base };
	return RelocationEntryRange(type_offsets(), std::move(to_relocation_entries));
}

template <class Image, class Offset>
auto BaseRelocationFacade<Image, Offset>::type_offsets() const -> RelTypeOffsetRange
{
	const offset_type reltypes_offset = this->offset() + offsetof(BaseRelocation, type_offset);
	const std::size_t reltypes_size = this->size_of_block - offsetof(BaseRelocation, type_offset);
	return RelTypeOffsetRange(*_image, reltypes_offset, reltypes_size);
}

}

#endif


text:
// Copyright Daniel Wallin, David Abrahams 2005.
// 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 PARAMETER_REQUIREMENTS_050331_HPP
#define PARAMETER_REQUIREMENTS_050331_HPP

#include <boost/parameter/aux_/pack/parameter_requirements.hpp>

#endif  // include guard

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
#include <string.h>
#include <error.h>
#include <time.h>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include "misc_log_ex.h"
#include "timings.h"

#define N_EXPECTED_FIELDS (8+11)

TimingsDatabase::TimingsDatabase()
{
}

TimingsDatabase::TimingsDatabase(const std::string &filename):
  filename(filename)
{
  load();
}

TimingsDatabase::~TimingsDatabase()
{
  save();
}

bool TimingsDatabase::load()
{
  instances.clear();

  if (filename.empty())
    return true;

  FILE *f = fopen(filename.c_str(), "r");
  if (!f)
  {
    MDEBUG("Failed to load timings file " << filename << ": " << strerror(errno));
    return false;
  }
  while (1)
  {
    char s[4096];
    if (!fgets(s, sizeof(s), f))
      break;
    char *tab = strchr(s, '\t');
    if (!tab)
    {
      MWARNING("Bad format: no tab found");
      continue;
    }
    const std::string name = std::string(s, tab - s);
    std::vector<std::string> fields;
    char *ptr = tab + 1;
    boost::split(fields, ptr, boost::is_any_of(" "));
    if (fields.size() != N_EXPECTED_FIELDS)
    {
      MERROR("Bad format: wrong number of fields: got " << fields.size() << " expected " << N_EXPECTED_FIELDS);
      continue;
    }

    instance i;

    unsigned int idx = 0;
    i.t = atoi(fields[idx++].c_str());
    i.npoints = atoi(fields[idx++].c_str());
    i.min = atof(fields[idx++].c_str());
    i.max = atof(fields[idx++].c_str());
    i.mean = atof(fields[idx++].c_str());
    i.median = atof(fields[idx++].c_str());
    i.stddev = atof(fields[idx++].c_str());
    i.npskew = atof(fields[idx++].c_str());
    i.deciles.reserve(11);
    for (int n = 0; n < 11; ++n)
    {
      i.deciles.push_back(atoi(fields[idx++].c_str()));
    }
    instances.insert(std::make_pair(name, i));
  }
  fclose(f);
  return true;
}

bool TimingsDatabase::save()
{
  if (filename.empty())
    return true;

  FILE *f = fopen(filename.c_str(), "w");
  if (!f)
  {
    MERROR("Failed to write to file " << filename << ": " << strerror(errno));
    return false;
  }
  for (const auto &i: instances)
  {
    fprintf(f, "%s", i.first.c_str());
    fprintf(f, "\t%lu", (unsigned long)i.second.t);
    fprintf(f, " %zu", i.second.npoints);
    fprintf(f, " %f", i.second.min);
    fprintf(f, " %f", i.second.max);
    fprintf(f, " %f", i.second.mean);
    fprintf(f, " %f", i.second.median);
    fprintf(f, " %f", i.second.stddev);
    fprintf(f, " %f", i.second.npskew);
    for (uint64_t v: i.second.deciles)
      fprintf(f, " %lu", (unsigned long)v);
    fputc('\n', f);
  }
  fclose(f);
  return true;
}

std::vector<TimingsDatabase::instance> TimingsDatabase::get(const char *name) const
{
  std::vector<instance> ret;
  auto range = instances.equal_range(name);
  for (auto i = range.first; i != range.second; ++i)
    ret.push_back(i->second);
  std::sort(ret.begin(), ret.end(), [](const instance &e0, const instance &e1){ return e0.t < e1.t; });
  return ret;
}

void TimingsDatabase::add(const char *name, const instance &i)
{
  instances.insert(std::make_pair(name, i));
}

ext: cc

max_stars_repo_name: Jasonhcwong/monero

max_issues_repo_name: Jasonhcwong/monero

max_forks_repo_name: Jasonhcwong/monero


text: #include <boost/fiber/recursive_mutex.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/peer_id.hpp>
#include <boost/python.hpp>
#include "bytes.hpp"

long get_hash(boost::python::object o)
{
    using namespace boost::python;
    return PyObject_Hash(str(o).ptr());
}

using namespace libtorrent;

bytes big_number_bytes(const big_number& bn) {
    return bytes(bn.to_string());
}

void bind_big_number()
{
    using namespace boost::python;
    using namespace libtorrent;

    class_<big_number>("big_number")
        .def(self == self)
        .def(self != self)
        .def(self < self)
        .def(self_ns::str(self))
        .def(init<char const*>())
        .def("clear", &big_number::clear)
        .def("is_all_zeros", &big_number::is_all_zeros)
        .def("to_bytes", big_number_bytes)
        .def("__hash__", get_hash)
        ;
}


text: #include <boost/geometry/util/order_as_direction.hpp>


text:
#pragma once

#include <Eigen/Core>

namespace bold
{
  class ImageLabelData;
  class SequentialTimer;

  /**
   * Abstract base class for classes that process labelled pixel data.
   */
  class ImagePassHandler
  {
  protected:
    ImagePassHandler(std::string id)
      : d_id(id)
    {}

  public:
    virtual ~ImagePassHandler() = default;

    virtual void process(ImageLabelData const& labelData, SequentialTimer& timer) = 0;

    std::string const& id() const { return d_id; };

  private:
    std::string d_id;
  };
}

ext: hh

max_stars_repo_name: drewnoakes/bold-humanoid

max_issues_repo_name: drewnoakes/bold-humanoid

max_forks_repo_name: drewnoakes/bold-humanoid


text:
#ifndef SAVE_EIGEN_HPP
#define SAVE_EIGEN_HPP

#include <cstdio>
#include <cstdint>
#include <Eigen/Core>

inline void save_eigen(const Eigen::VectorXd &x, const char *name)
{
    std::FILE *ofile = fopen(name, "wb");
    int64_t sz = x.rows();

    fwrite(&sz, sizeof(sz), 1, ofile);
    fwrite(x.data(), sizeof(double), x.rows(), ofile);
    fclose(ofile);
}

#endif // SAVE_EIGEN_HPP

max_stars_repo_name: slmcbane/Le-TO

max_issues_repo_name: slmcbane/Le-TO

max_forks_repo_name: slmcbane/Le-TO


text:
#include "problemes.h"
#include "arithmetique.h"

#include <fstream>
#include <boost/algorithm/string.hpp>

typedef long long nombre;
typedef std::vector<nombre> vecteur;
typedef boost::rational<nombre> fraction;
typedef std::pair<nombre, nombre> paire;

namespace {
    fraction aire(const paire &A, const paire &B, const paire &C) {
        nombre abc = (B.first - A.first) * (C.second - A.second) - (C.first - A.first) * (B.second - A.second);
        if (abc < 0)
            abc = -abc;
        return fraction(abc, 2);
    }

    bool contient(const paire &A, const paire &B, const paire &C) {
        static const paire O = std::make_pair(0, 0);
        const fraction ABC = aire(A, B, C);
        const fraction OBC = aire(O, B, C);
        const fraction AOC = aire(A, O, C);
        const fraction ABO = aire(A, B, O);

        return (ABC == OBC + AOC + ABO);
    }
}

ENREGISTRER_PROBLEME(102, "Triangle containment") {
    // Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a
    // triangle is formed.
    //
    // Consider the following two triangles:
    //
    //                                  A(-340,495), B(-153,-910), C(835,-947)
    //
    //                                  X(-175,41), Y(-421,-714), Z(574,-645)
    //
    // It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.
    //
    // Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of
    // one thousand "random" triangles, find the number of triangles for which the interior contains the origin.
    //
    // NOTE: The first two examples in the file represent the triangles in the example given above.
    std::ifstream ifs("data/p102_triangles.txt");
    nombre resultat = 0;
    std::string ligne;
    while (ifs >> ligne) {
        std::vector<std::string> v;
        boost::split(v, ligne, boost::is_any_of(","));
        const paire A(stoll(v[0]), stoll(v[1]));
        const paire B(stoll(v[2]), stoll(v[3]));
        const paire C(stoll(v[4]), stoll(v[5]));
        if (contient(A, B, C))
            ++resultat;
    }
    return std::to_string(resultat);
}

max_stars_repo_name: ZongoForSpeed/ProjectEuler

max_issues_repo_name: ZongoForSpeed/ProjectEuler

max_forks_repo_name: ZongoForSpeed/ProjectEuler


text:
#include <iostream>
#include <iomanip>
#include <Eigen/Dense>
#include <ctime>
#include <chrono>
#include <map>
#include <random>
#include <cstdio> // popen
#include <cstring> // memset

#include "Neural_Net.hpp"
#include "FNN_Model.hpp"
#include "MNIST_Parser.hpp"
#include "gnuplot_i.hpp"

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

  /*std::vector<unsigned int> layers;
  layers.push_back(1);
  layers.push_back(1);
  FNN_Model my_net(layers);

  std::vector<Eigen::MatrixXd> weights;
  std::vector<Eigen::MatrixXd> bias;
  weights.push_back(Eigen::MatrixXd());
  weights.push_back(Eigen::MatrixXd::Constant(1, 1, 2.0));
  bias.push_back(Eigen::MatrixXd());
  bias.push_back(Eigen::MatrixXd::Constant(1, 1, 2.0));
  my_net.Manual_Set_FNN(weights, bias);
  Eigen::MatrixXd input = Eigen::MatrixXd::Constant(1, 1, 1);
  Eigen::MatrixXd output = Eigen::MatrixXd::Constant(1, 1, 0);
  Eigen::MatrixXd eval_input = Eigen::MatrixXd::Constant(1, 1, 1);
  Eigen::MatrixXd eval_output = Eigen::MatrixXd::Constant(1, 1, 0);

  int goOn=1;
  int ch = 0;
  while(goOn)
  {
    ch = wait_for_key();
    if (ch == 'q')
    {
      goOn = 0;
      my_net.train_thread.wait();
    }
    else if (ch == 'c') {
      my_net.train(input, output, 300, 1, 0.15, eval_input, eval_output);
    }
  }*/

     MNIST_Parser my_parser;
     Eigen::MatrixXd train_images(0, 0);
     Eigen::MatrixXd train_labels(0, 0);
     Eigen::MatrixXd eval_images(0, 0);
     Eigen::MatrixXd eval_labels(0, 0);
     std::cout << "Reading MNIST data ..." << std::endl;
     my_parser.read_train_img(train_images);
     my_parser.read_train_label(train_labels);
     my_parser.read_eval_img(eval_images);
     my_parser.read_eval_label(eval_labels);
  //std::cout << train_images.col(1) << std::endl;

  std::vector<unsigned int> layers;
  layers.push_back(784);
  layers.push_back(30);
  layers.push_back(10);
  FNN_Model my_net(layers);
  std::cout << "Training Forward Neural Net ..." << std::endl;
  my_net.train(train_images, train_labels, 30, 10, 3.0, eval_images, eval_labels);

  /*
     std::vector<unsigned int> layers;
     layers.push_back(2);
     layers.push_back(3);
     layers.push_back(1);
     FNN_Model my_net(layers);
     my_net.print_FNN();
     */

  return 0;
}

max_stars_repo_name: kwon-young/Millenium-Neural-Net

max_issues_repo_name: kwon-young/Millenium-Neural-Net

max_forks_repo_name: kwon-young/Millenium-Neural-Net


text:
/* bid_request_endpoint_test.cc
   Eric Robert, 9 May 2013
   Copyright (c) 2013 Datacratic Inc.  All rights reserved.

   Tool to test a bid request endpoint.
*/

#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

#include "rtbkit/core/router/router.h"
#include "rtbkit/core/agent_configuration/agent_configuration_service.h"
#include "rtbkit/core/banker/null_banker.h"
#include "rtbkit/testing/test_agent.h"

#include "jml/utils/file_functions.h"

using namespace Datacratic;
using namespace RTBKIT;

static Json::Value loadJsonFromFile(const std::string & filename) {
    ML::File_Read_Buffer buf(filename);
    return Json::parse(std::string(buf.start(), buf.end()));
}

int main(int argc, char ** argv) {
    using namespace boost::program_options;

    int recordCount = 1000;
    std::string recordFile;
    std::string exchangeConfigurationFile = "rtbkit/examples/router-config.json";

    options_description endpoint_options("Bid request endpoint options");
    endpoint_options.add_options()
        ("record-request,r", value<std::string>(&recordFile),
         "filename prefix to record incoming bid request")
        ("record-count,n", value<int>(&recordCount),
         "number of bid request recorded by file")
        ("exchange-configuration,x", value<std::string>(&exchangeConfigurationFile),
         "configuration file with exchange data");

    options_description all_opt;
    all_opt
        .add(endpoint_options);
    all_opt.add_options()
        ("help,h", "print this message");

    variables_map vm;
    store(command_line_parser(argc, argv)
          .options(all_opt)
          .run(),
          vm);
    notify(vm);

    if(vm.count("help")) {
        std::cerr << all_opt << std::endl;
        exit(1);
    }

    std::shared_ptr<ServiceProxies> proxies(new ServiceProxies());

    // The agent config service lets the router know how our agent is
    // configured
    AgentConfigurationService agentConfig(proxies, "config");
    agentConfig.unsafeDisableMonitor();
    agentConfig.init();
    agentConfig.bindTcp();
    agentConfig.start();

    // We need a router for our exchange connector to work
    Router router(proxies, "router");
    router.unsafeDisableMonitor();
    router.init();

    // Set a null banker that blindly approves all bids so that we can
    // bid.
    router.setBanker(std::make_shared<NullBanker>(true));

    // Configure exchange connectors
    Json::Value exchangeConfiguration = loadJsonFromFile(exchangeConfigurationFile);
    router.initExchanges(exchangeConfiguration);
    router.initFilters();

    // Start the router up
    router.bindTcp();
    router.start();

    router.forAllExchanges([&](std::shared_ptr<ExchangeConnector> const & item) {
        item->enableUntil(Date::positiveInfinity());
        if(!recordFile.empty()) {
            std::string filename = item->exchangeName() + "-" + recordFile;
            item->startRequestLogging(filename, recordCount);
        }
    });

    // This is our bidding agent, that actually calculates the bid price
    TestAgent agent(proxies, "agent");

    agent.onBidRequest = [&] (
            double timestamp,
            const Id & id,
            std::shared_ptr<BidRequest> br,
            Bids bids,
            double timeLeftMs,
            const Json::Value & augmentations,
            const WinCostModel & wcm)
        {
            Bid& bid = bids[0];

            bid.bid(bid.availableCreatives[0], USD_CPM(1.234));
            agent.doBid(id, bids, Json::Value(), wcm);

            ML::atomic_inc(agent.numBidRequests);
            std::cerr << "bid count=" << agent.numBidRequests << std::endl;
        };

    agent.init();
    agent.start();
    agent.configure();

    for(;;) {
        ML::sleep(10.0);

        std::cerr << "----------[ REPORT ]----------" << std::endl;
        proxies->events->dump(std::cerr);
    }
}

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: TuanTranEngineer/rtbkit

max_forks_repo_name: TuanTranEngineer/rtbkit


text:
#include <ql/quantlib.hpp>

#include <boost/make_shared.hpp>

using namespace QuantLib;

int example01() {

    try {

        Date refDate(13, November, 2013);
        Date settlDate = TARGET().advance(refDate, 2 * Days);
        Settings::instance().evaluationDate() = refDate;

        Handle<Quote> rateLevel(new SimpleQuote(0.03));
        Handle<YieldTermStructure> yts(
            new FlatForward(refDate, rateLevel, Actual365Fixed()));

        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts));
        boost::shared_ptr<SwapIndex> swapIndex(
            new EuriborSwapIsdaFixA(10 * Years, yts));

        iborIndex->addFixing(refDate, 0.0200);
        swapIndex->addFixing(refDate, 0.0315);

        // Handle<Quote> volatilityLevel(new SimpleQuote(0.30));
        // Handle<SwaptionVolatilityStructure> swaptionVol(
        //     new ConstantSwaptionVolatility(refDate, TARGET(), Following,
        //                                    volatilityLevel,
        // Actual365Fixed()));

        Handle<SwaptionVolatilityStructure> swaptionVol(
            new SingleSabrSwaptionVolatility(refDate, TARGET(), Following, 0.05,
                                             0.80, -0.30, 0.20,
                                             Actual365Fixed(), swapIndex));

        // Real strike = 0.0001;
        // while(strike < 1.0) {
        //     std::cout << strike << " " <<
        // swaptionVol->volatility(10.0,10.0,strike) << std::endl;
        //     strike += 0.0010;
        // }
        // return 0;

        Date termDate = TARGET().advance(settlDate, 10 * Years);

        Schedule sched1(settlDate, termDate, 1 * Years, TARGET(),
                        ModifiedFollowing, ModifiedFollowing,
                        DateGeneration::Forward, false);
        Schedule sched2(settlDate, termDate, 6 * Months, TARGET(),
                        ModifiedFollowing, ModifiedFollowing,
                        DateGeneration::Forward, false);

        Real nominal = 100000.0;

        boost::shared_ptr<FloatFloatSwap> cmsswap(
            new FloatFloatSwap( // CMS Swap
                VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,
                Thirty360(), sched2, iborIndex, Actual360(), false, false, 1.0,
                0.00, Null<Real>(), Null<Real>(), 1.0, 0.00267294));

        // boost::shared_ptr<FloatFloatSwap> cmsswap(new FloatFloatSwap(  //
        // Reversed Floored CMS Swap
        //     VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,
        //     Thirty360(), sched2, iborIndex, Actual360(),
        //     false,false,-1.0,0.03,Null<Real>(),0.0,1.0,0.0));

        // boost::shared_ptr<FloatFloatSwap> cmsswap(new FloatFloatSwap( // fix
        // float swap as FloatFloatSwap instrument
        //     VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,
        //     Thirty360(), sched2, iborIndex, Actual360(),
        //     false,false,0.0,0.05,Null<Real>(),Null<Real>(),1.0,0.0));

        std::vector<Date> exerciseDates;
        std::vector<Date> sigmaSteps;
        std::vector<Real> sigma;

        sigma.push_back(0.01);
        for (Size i = 1; i < sched1.size() - 1; i++) {
            exerciseDates.push_back(swapIndex->fixingDate(sched1[i]));
            sigmaSteps.push_back(exerciseDates.back());
            sigma.push_back(0.01);
        }

        // double v[] =
        // {0.01,0.0115446,0.0111677,0.0113092,0.0112404,0.0111856,0.0111218,0.0110547,0.0112791,0.00945792};
        // sigma = std::vector<Real>(v,v+10);

        // boost::shared_ptr<FloatFloatSwap> underlying(new FloatFloatSwap(
        //     VanillaSwap::Receiver, nominal, nominal, sched1, swapIndex,
        //     Thirty360(), sched2, iborIndex, Actual360(),
        //     false,false,1.0,0.0,Null<Real>(),Null<Real>(),1.0,0.00267294));

        boost::shared_ptr<Exercise> exercise(
            new BermudanExercise(exerciseDates));
        boost::shared_ptr<FloatFloatSwaption> callRight(
            new FloatFloatSwaption(cmsswap, exercise));

        std::vector<Date> cmsFixingDates(exerciseDates);
        std::vector<Period> cmsTenors(exerciseDates.size(), 10 * Years);

        Handle<Quote> reversionLevel(new SimpleQuote(0.02));

        boost::shared_ptr<NumericHaganPricer> haganPricer(
            new NumericHaganPricer(swaptionVol,
                                   GFunctionFactory::NonParallelShifts,
                                   reversionLevel));
        setCouponPricer(cmsswap->leg(0), haganPricer);

        // hull white model (change the model->calibrate call below)
        std::vector<Date> sigmaSteps2(sigmaSteps.begin(), sigmaSteps.end() - 1);
        std::vector<Real> sigma2(sigma.begin(), sigma.end() - 1);
        // boost::shared_ptr<Gsr> model(new
        // Gsr(yts,sigmaSteps2,sigma2,reversionLevel->value()));
        boost::shared_ptr<Gaussian1dModel> model2(
            new Gsr(yts, sigmaSteps2, sigma2, reversionLevel->value()));

        Handle<SwaptionVolatilityStructure> hwVol(
            new Gaussian1dSwaptionVolatility(model2, swapIndex));
        Real moneyIn[] = { 0.20, 0.50, 0.75, 1.0, 1.5, 2.0, 5.0, 10.0 };
        std::vector<Real> money(moneyIn, moneyIn + 8);

        // markov model (change the model->calibrate call below)
        // boost::math::ntl::RR::SetPrecision(113);
        boost::shared_ptr<MarkovFunctional> model(new MarkovFunctional(
            yts, reversionLevel->value(), sigmaSteps, sigma, swaptionVol,
            cmsFixingDates, cmsTenors,
            swapIndex // set vol structure for mf here
            /*,MarkovFunctional::ModelSettings().withAdjustments(
                MarkovFunctional::ModelSettings::SabrSmile |
                MarkovFunctional::ModelSettings::
                    SmileExponentialExtrapolation)
                    .withSmileMoneynessCheckpoints(money)*/));

        boost::shared_ptr<Gaussian1dFloatFloatSwaptionEngine> floatEngine(
            new Gaussian1dFloatFloatSwaptionEngine(model));

        callRight->setPricingEngine(floatEngine);

        std::cout << "determine cal basket" << std::endl;

        boost::shared_ptr<Gaussian1dSwaptionEngine> stdEngine(
            new Gaussian1dSwaptionEngine(model));

        boost::shared_ptr<SwapIndex> swapBase(
            new EuriborSwapIsdaFixA(30 * Years, yts));

        LevenbergMarquardt opt;
        EndCriteria ec(2000, 500, 1E-8, 1E-8, 1E-8);

        Size iteration = 0;
        while (iteration < 1) { // set number of iterations here ...
            std::vector<boost::shared_ptr<CalibrationHelper> > basket =
                callRight->calibrationBasket(
                    swapBase, *swaptionVol, // set vol structure for basket here
                    // BasketGeneratingEngine::Naive
                    BasketGeneratingEngine::MaturityStrikeByDeltaGamma);

            for (Size i = 0; i < basket.size(); i++)
                basket[i]->setPricingEngine(stdEngine);
            model->calibrate(basket, opt, ec); // for markov
            // model->calibrate(basket, opt, ec, Constraint(),
            // std::vector<Real>(), model->FixedReversions()); // for gsr

            std::cout << "option date & maturity date & nominal & strike & "
                         "model vol \\\\" << std::endl;
            for (Size i = 0; i < basket.size(); i++) {
                boost::shared_ptr<SwaptionHelper> h =
                    boost::dynamic_pointer_cast<SwaptionHelper>(basket[i]);
                std::cout << exerciseDates[i] << " & "
                          << h->underlyingSwap()->fixedSchedule().dates().back()
                          << " & " << h->underlyingSwap()->nominal() << " & "
                          << h->underlyingSwap()->fixedRate() << " & "
                          << model->volatility()[i] << " \\\\" << std::endl;
            }
            std::cout << model->volatility().back() << std::endl;
            iteration++;
        }

        Real analyticSwapNpv = CashFlows::npv(cmsswap->leg(1), **yts, false) -
                               CashFlows::npv(cmsswap->leg(0), **yts, false);
        Real callRightNpv = callRight->NPV();
        Real firstCouponNpv = -cmsswap->leg(0)[0]->amount() *
                                  yts->discount(cmsswap->leg(0)[0]->date()) +
                              cmsswap->leg(1)[0]->amount() *
                                  yts->discount(cmsswap->leg(1)[0]->date());
        Real underlyingNpv =
            callRight->result<Real>("underlyingValue") + firstCouponNpv;

        std::cout << "Swap Npv (Hagan)     & " << analyticSwapNpv << "\\\\"
                  << std::endl;
        std::cout << "Call Right Npv (MF)  & " << callRightNpv << "\\\\"
                  << std::endl;
        std::cout << "Underlying Npv (MF)  & " << underlyingNpv << "\\\\"
                  << std::endl;
        std::cout << "fair margin swap & "
                  << -analyticSwapNpv / CashFlows::bps(cmsswap->leg(1), **yts,
                                                       false) << std::endl;

        // std::cout << "Model trace : " << std::endl << model->modelOutputs()
        // << std::endl;

        return 0;
    }
    catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cerr << "unknown error" << std::endl;
        return 1;
    }
}

int example02() {

    try {

        Date refDate(13, November, 2013);
        Date settlDate = TARGET().advance(refDate, 2 * Days);
        Settings::instance().evaluationDate() = refDate;

        Handle<Quote> rateLevel(new SimpleQuote(0.03));
        Handle<YieldTermStructure> yts(
            new FlatForward(refDate, rateLevel, Actual365Fixed()));

        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts));
        boost::shared_ptr<SwapIndex> swapIndex(
            new EuriborSwapIsdaFixA(10 * Years, yts));

        iborIndex->addFixing(refDate, 0.0200);
        swapIndex->addFixing(refDate, 0.0315);

        // Handle<Quote> volatilityLevel(new SimpleQuote(0.20)); // vol here !
        // Handle<SwaptionVolatilityStructure> swaptionVol(
        //     new ConstantSwaptionVolatility(refDate, TARGET(), Following,
        //                                    volatilityLevel, Actual365Fixed()));

        Handle<SwaptionVolatilityStructure> swaptionVol(
            new SingleSabrSwaptionVolatility(refDate, TARGET(), Following,
        0.10,
                                             0.80, -0.30, 0.40,
                                             Actual365Fixed(), swapIndex));

        // Real strike = 0.0001;
        // while(strike < 0.50) {
        //     std::cout << strike << " " <<
        // swaptionVol->volatility(10.0,10.0,strike) << std::endl;
        //     strike += 0.0050;
        // }
        // return 0;

        Date termDate = TARGET().advance(settlDate, 10 * Years);

        Schedule sched1(settlDate, termDate, 1 * Years, TARGET(),
                        ModifiedFollowing, ModifiedFollowing,
                        DateGeneration::Forward, false);
        Schedule sched2(settlDate, termDate, 6 * Months, TARGET(),
                        ModifiedFollowing, ModifiedFollowing,
                        DateGeneration::Forward, false);

        Real nominal = 100000.0;

        boost::shared_ptr<FloatFloatSwap> cmsswap(
            new FloatFloatSwap( // CMS Swap
                VanillaSwap::Payer, nominal, nominal, sched1, swapIndex,
                Thirty360(), sched2, iborIndex, Actual360(), false, false, 1.0,
                0.00, Null<Real>(), Null<Real>(), 1.0, 0.0));

        Handle<Quote> reversionLevel(new SimpleQuote(0.01)); // reversion here !

        boost::shared_ptr<NumericHaganPricer> haganPricerN(
            new NumericHaganPricer(swaptionVol,
                                   GFunctionFactory::Standard,
                                   reversionLevel));
        boost::shared_ptr<AnalyticHaganPricer> haganPricerA(
            new AnalyticHaganPricer(swaptionVol,
                                    GFunctionFactory::Standard,
                                    reversionLevel));

        // auto integrator =
        // boost::make_shared<GaussLobattoIntegral>(1000,1E-4);

        boost::shared_ptr<LinearTsrPricer> tsrPricer(new LinearTsrPricer(
            swaptionVol, reversionLevel, Handle<YieldTermStructure>(),
            LinearTsrPricer::Settings().withRateBound(0.0, 1.0)
            //.withVegaRatio(0.01)
            ));

        boost::shared_ptr<CmsReplicationPricer> replPricer(
            new CmsReplicationPricer(swaptionVol, reversionLevel));

        Real strike = 0.0001;
        while (strike <= 0.1000) {

            auto tmpCap = boost::shared_ptr<CappedFlooredCoupon>(new CappedFlooredCmsCoupon(
                Date(13, November, 2023), 100000.0, Date(13, November, 2022),
                Date(13, November, 2023), 2, swapIndex, 1.0, 0.0, strike,
                Null<Rate>(), Date(), Date(), DayCounter(), false));
            auto cap = boost::make_shared<StrippedCappedFlooredCoupon>(tmpCap);
            auto tmpFloor = boost::shared_ptr<CappedFlooredCoupon>(
                new CappedFlooredCmsCoupon(
                    Date(13, November, 2023), 100000.0,
                    Date(13, November, 2022), Date(13, November, 2023), 2,
                    swapIndex, 1.0, 0.0, Null<Real>(), strike, Date(), Date(),
                    DayCounter(), false));
            auto floor = boost::make_shared<StrippedCappedFlooredCoupon>(tmpFloor);
            auto swaplet = boost::shared_ptr<CappedFlooredCmsCoupon>(
                new CappedFlooredCmsCoupon(
                    Date(13, November, 2023), 100000.0,
                    Date(13, November, 2022), Date(13, November, 2023), 2,
                    swapIndex, 1.0, 0.0, Null<Rate>(), Null<Rate>(), Date(),
                    Date(), DayCounter(), false));

            cap->setPricer(tsrPricer);
            floor->setPricer(tsrPricer);
            swaplet->setPricer(tsrPricer);
            Real cap1 = cap->adjustedFixing();
            Real floor1 = floor->adjustedFixing();
            Real swaplet1 = swaplet->adjustedFixing();

            // cap->setPricer(haganPricerN);
            // floor->setPricer(haganPricerN);
            // swaplet->setPricer(haganPricerN);
            // Real cap2 = cap->adjustedFixing();
            // Real floor2 = floor->adjustedFixing();
            // Real swaplet2 = swaplet->adjustedFixing();
            // cap->setPricer(replPricer);
            // floor->setPricer(replPricer);
            // swaplet->setPricer(replPricer);
            // Real cap2 = 0.0;//cap->adjustedFixing();
            // Real floor2 = 0.0;//floor->adjustedFixing();
            // Real swaplet2 = 0.0;//swaplet->adjustedFixing();

            // cap->setPricer(tsrPricer);
            // floor->setPricer(tsrPricer);
            // swaplet->setPricer(tsrPricer);
            // Real cap3 = cap->adjustedFixing();
            // Real floor3 = floor->adjustedFixing();
            // Real swaplet3 = swaplet->adjustedFixing();

            // std::cout << strike << " " << cap1 << " "
            //           << " " << floor1 << " "
            //           << (cap1 - floor1 - (swaplet1 - strike)) << std::endl;

            strike += 0.0001;
        }

        return 0;
    }
    catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cerr << "unknown error" << std::endl;
        return 1;
    }
}

int example03() {

    try {

        Date refDate(13, November, 2013);
        Date settlDate = TARGET().advance(refDate, 2 * Days);
        Settings::instance().evaluationDate() = refDate;

        Handle<Quote> rateLevel1(new SimpleQuote(0.0350));
        Handle<Quote> rateLevel2(new SimpleQuote(0.0300));
        Handle<YieldTermStructure> yts1(
            new FlatForward(refDate, rateLevel1, Actual365Fixed()));
        Handle<YieldTermStructure> yts2(
            new FlatForward(refDate, rateLevel2, Actual365Fixed()));

        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts1));
        boost::shared_ptr<SwapIndex> swapIndex1(
            new EuriborSwapIsdaFixA(10 * Years, yts1));
        boost::shared_ptr<SwapIndex> swapIndex2(
            new EuriborSwapIsdaFixA(2 * Years, yts2));

        boost::shared_ptr<SwapSpreadIndex> swapSpreadIndex(
            new SwapSpreadIndex("cms10_2", swapIndex1, swapIndex2));

        Handle<Quote> volatilityLevel(new SimpleQuote(0.40)); // vol here !
        Handle<SwaptionVolatilityStructure> swaptionVol(
            new ConstantSwaptionVolatility(refDate, TARGET(), Following,
                                           volatilityLevel, Actual365Fixed()));

        // Handle<SwaptionVolatilityStructure> swaptionVol(
        //     new SingleSabrSwaptionVolatility(refDate, TARGET(), Following,
        // 0.15,
        //                                      0.80, -0.30, 0.20,
        //                                      Actual365Fixed(), swapIndex));

        Handle<Quote> reversionLevel(new SimpleQuote(0.00)); // reversion here !

        boost::shared_ptr<LinearTsrPricer> tsrPricer(new LinearTsrPricer(
            swaptionVol, reversionLevel, Handle<YieldTermStructure>(),
            LinearTsrPricer::Settings().withRateBound(0.0, 1.0)
            //.withVegaRatio(0.01)
            ));

        Handle<Quote> correlation(new SimpleQuote(0.20)); // correlation here

        boost::shared_ptr<CappedFlooredCoupon> tmpSpreadCoupon(
            new CappedFlooredCmsSpreadCoupon(
                Date(13, November, 2034), 1.0, Date(13, November, 2033),
                Date(13, November, 2034), 2, swapSpreadIndex, 1.0, 0.0,
                Null<Real>(), 0.0050, Date(), Date(), DayCounter(), false));

        boost::shared_ptr<StrippedCappedFlooredCoupon> spreadCoupon =
            boost::make_shared<StrippedCappedFlooredCoupon>(tmpSpreadCoupon);

        // boost::shared_ptr<CmsSpreadCoupon> spreadCoupon(new CmsSpreadCoupon(
        //     Date(13, November, 2024), 1.0, Date(13, November, 2023),
        //     Date(13, November, 2024), 2, swapSpreadIndex, 1.0, 0.0,
        //     Date(), Date(), DayCounter(),false));

        std::cout << "integration_points;rate" << std::setprecision(16)
                  << std::endl;
        for (Size i = 4; i < 64; i++) {

            boost::shared_ptr<LognormalCmsSpreadPricer> spreadPricer(
                new LognormalCmsSpreadPricer(tsrPricer, correlation,
                                             Handle<YieldTermStructure>(), i));

            spreadCoupon->setPricer(spreadPricer);

            std::cout << i << ";" << spreadCoupon->rate() << std::endl;
        }

        return 0;
    }
    catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cerr << "unknown error" << std::endl;
        return 1;
    }
}

int example04() {

    try {

        Date refDate(13, November, 2013);
        Date settlDate = TARGET().advance(refDate, 2 * Days);
        Settings::instance().evaluationDate() = refDate;

        Handle<Quote> rateLevel1(new SimpleQuote(0.0350));
        Handle<YieldTermStructure> yts1(
            new FlatForward(refDate, rateLevel1, Actual365Fixed()));
        Handle<Quote> rateLevel2(new SimpleQuote(0.0300));
        Handle<YieldTermStructure> yts2(
            new FlatForward(refDate, rateLevel2, Actual365Fixed()));

        boost::shared_ptr<IborIndex> iborIndex(new Euribor(6 * Months, yts1));
        boost::shared_ptr<SwapIndex> swapIndex1(
            new EuriborSwapIsdaFixA(10 * Years, yts1));
        boost::shared_ptr<SwapIndex> swapIndex2(
            new EuriborSwapIsdaFixA(2 * Years, yts2));

        boost::shared_ptr<SwapSpreadIndex> swapSpreadIndex(
            new SwapSpreadIndex("cms10_2", swapIndex1, swapIndex2));

        Handle<Quote> volatilityLevel(new SimpleQuote(0.40)); // vol here !
        Handle<SwaptionVolatilityStructure> swaptionVol(
            new ConstantSwaptionVolatility(refDate, TARGET(), Following,
                                           volatilityLevel, Actual365Fixed()));

        Handle<Quote> reversionLevel(new SimpleQuote(0.00)); // reversion here !

        Schedule sched(settlDate, settlDate + 10 * Years, 1 * Years, TARGET(),
                       ModifiedFollowing, ModifiedFollowing,
                       DateGeneration::Backward, false);

        boost::shared_ptr<FloatFloatSwap> underlying(new FloatFloatSwap(VanillaSwap::Payer,
                                                                        100.0,100.0,
                                                                        sched,iborIndex,Actual360(),
                                                                        sched,swapSpreadIndex,Thirty360(),
                                                                        false,
                                                                        false));

        std::vector<Date> callDates = sched.dates();

        std::cout << "call dates:" << std::endl;
        for(Size i=0;i<callDates.size();i++)
            std::cout << callDates[i] << std::endl;

        boost::shared_ptr<Exercise> exercise = boost::make_shared<BermudanExercise>(callDates);

        boost::shared_ptr<FloatFloatSwaption> swaption = boost::make_shared<FloatFloatSwaption>(underlying,exercise);

        std::vector<Date> volStepDates;
        std::vector<Real> vols(1,0.01);

        boost::shared_ptr<Gaussian1dModel> model = boost::make_shared<Gsr>(yts1,volStepDates,
                                                                           vols,0.01);

        boost::shared_ptr<Gaussian1dFloatFloatSwaptionEngine> engine =
            boost::make_shared<Gaussian1dFloatFloatSwaptionEngine>(
                model, 64, 7.0, true, false, Handle<Quote>(),
                Handle<YieldTermStructure>(), false,
                Gaussian1dFloatFloatSwaptionEngine::Naive);

        swaption->setPricingEngine(engine);

        std::cout << "swaption npv = " << swaption->NPV() << std::endl;

        std::vector<Real> probs = swaption->result<std::vector<Real> >("probabilities");
        for(Size i=0;i<probs.size();i++) {
            std::cout << i << " => " << probs[i] << std::endl;
        }

    }
    catch (std::exception &e) {
        std::cerr << e.what() << std::endl;
        return 1;
    }
    catch (...) {
        std::cerr << "unknown error" << std::endl;
        return 1;
    }

    return 0;

}

int main(int, char * []) {

    return example02();

}

max_forks_repo_name: pcaspers/quantlib


text:
#include <boost/pool/simple_segregated_storage.hpp>
#include <vector>
#include <cstddef>

int main()
{
  boost::simple_segregated_storage<std::size_t> storage;
  std::vector<char> v(1024);
  storage.add_block(&v.front(), v.size(), 256);

  int *i = static_cast<int*>(storage.malloc());
  *i = 1;

  int *j = static_cast<int*>(storage.malloc_n(1, 512));
  j[10] = 2;

  storage.free(i);
  storage.free_n(j, 1, 512);
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text: #include <boost/hana/adjust.hpp>


text:
#pragma once

#include <boost/detail/atomic_count.hpp>

namespace xul {

class atomic_count
{
public:
    atomic_count() : m_count(0)
    {
    }
#if 1
    long operator++()
    {
        return ++m_count;
    }

    long operator--()
    {
        return --m_count;
    }

    operator long() const
    {
        return m_count;
    }
#endif
private:
    boost::detail::atomic_count m_count;
};

}

#define XUL_IMPLENEBT_COBJECT_REF(name)    \
    long name##_add_ref(const name* obj) { return ++(obj->refcount); } \
    long name##_release_ref(const name* obj) { --(obj->refcount); long count = obj->refcount; if (count <= 0) { delete obj; } return count; } \
    long name##_get_ref_count(const name* obj) { return obj->refcount; }; \
    long cobject_add_ref(const name* obj) { return name##_add_ref(obj); } \
    long cobject_release_ref(const name* obj) { return name##_release_ref(obj); }

#define XUL_COBJECT_HEADER() \
    mutable xul::atomic_count refcount

max_stars_repo_name: hindsights/xul

max_issues_repo_name: hindsights/xul

max_forks_repo_name: hindsights/xul


text:
#pragma once

#include "argparse.hpp"
#include "random.hpp"

#include <algorithm>
#include <boost/container_hash/hash.hpp>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#define t1_prefix "O_"
#define t2_prefix "R_"

// get base random alias which is auto seeded and has static API and internal
// state
using Random = effolkronium::random_static;

struct Pos {
  int x;
  int y;

  Pos() {
    x = 0;
    y = 0;
  }
  Pos(int x1, int y1) {
    x = x1;
    y = y1;
  }
};

struct Segment {
  Pos a;
  Pos b;
  Segment(Pos a1, Pos b1) {
    a = a1;
    b = b1;
  }
  bool intersects(Segment &s2);
};

bool Segment::intersects(Segment &s2) {
  return ((a.x < s2.a.x && b.x > s2.b.x) || (a.x > s2.a.x && b.x < s2.b.x) ||
          (a.x == s2.a.x && b.x == s2.b.x)) &&
         ((a.y < s2.a.y && b.y > s2.b.y) || (a.y > s2.a.y && b.y < s2.b.y) ||
          (a.y == s2.a.y && b.y == s2.b.y));
}

struct Node {
  unsigned int id;
  Pos pos;
  // std::string label;
  std::unordered_set<int> connections;
  bool is_t1;

  Node() { is_t1 = true; };

  std::string as_dot() {
    std::string dot = "  ";
    if (is_t1) {
      dot += t1_prefix + std::to_string(id) + " [color = blue, ";
    } else {
      dot += t2_prefix + std::to_string(id) + " [color = red, ";
    }
    // dot += "label = " + label + ", "
    dot += "pos = \"" + std::to_string(pos.x) + "," + std::to_string(pos.y) +
           "!\"];\n";
    return dot;
  }
};

struct Edge {
  unsigned int from;
  unsigned int to;
  int weight;
  Edge(int f, int t, int w) {
    from = f;
    to = t;
    weight = w;
  }

  std::string as_dot() {
    std::string dot = "  ";
    dot += t1_prefix + std::to_string(from) + " -- " + t2_prefix +
           std::to_string(to);
    dot += "[label = \"" + std::to_string(weight) + "\"];\n";
    return dot;
  }
};

struct Bipartate {

  unsigned int score;
  std::unordered_map<int, Node> t1;
  std::unordered_map<int, Node> t2;
  std::vector<Edge> edges;
  std::unordered_map<std::pair<int, int>, int, boost::hash<std::pair<int, int>>>
      positions;
  Bipartate(std::string csv_name);
  Bipartate(){};
  void write_dot(std::string file_name);
  Bipartate mutate(uint8_t chance);
  void calc_score();
  bool is_adjacent(int x, int y);

  // Overloading "<" operator based on score
  bool operator<(const Bipartate &rhs) const { return score < rhs.score; }
  auto &operator()(bool c) {
    if (c) {
      return t1;
    }
    return t2;
  }
};

Bipartate::Bipartate(std::string csv_name) {

  // https://stackoverflow.com/questions/48994605/csv-data-into-a-2d-array-of-integers
  std::ifstream f;
  f.open(csv_name);

  // Number of lines read
  unsigned int n_row = 0;

  // Buffer to hold one row, one value
  std::string row, val;
  std::vector<std::vector<int>> array;

  // Read one row at a time
  while (std::getline(f, row)) {
    std::stringstream s(row);

    // Initialise t1 at n_row
    t1[n_row].id = n_row;

    // Column index
    unsigned int n_col = 0;

    // Read one , delimitted value at a time
    while (getline(s, val, ',')) {
      int weight = std::stoi(val);

      // Initialise t2 at n_col
      t2[n_col].id = n_col;

      // If linked
      if (weight) {

        // Add connection from t1 to t2
        t1[n_row].connections.insert(n_col);

        // Add connection from t2 to t1
        t2[n_col].connections.insert(n_row);

        // Add edge from t1 to t2
        edges.push_back(Edge(n_row, n_col, weight));
      }
      n_col++;
    }
    n_row++;
  }

  // First tower
  // "Random" order based on unordered_map
  int x = 0;
  int y = 0;
  for (auto &it : t1) {
    positions[{x, y}] = it.first;
    it.second.pos = Pos(x, y);
    y++;
  }

  // Second tower, next to first
  x++;
  y = 0;

  // "Random" order based on unordered_map
  for (auto &it : t2) {
    positions[{x, y}] = it.first;
    it.second.pos = Pos(x, y);
    it.second.is_t1 = false;
    y++;
  }
  write_dot("input.dot");
}

bool Bipartate::is_adjacent(int x, int y) {

  return positions.contains({x, y + 1}) || positions.contains({x, y - 1}) ||
         positions.contains({x + 1, y}) || positions.contains({x - 1, y});
}

Bipartate Bipartate::mutate(uint8_t chance) {

  // Make a copy as the result we will return
  Bipartate bm(*this);

  for (bool c : {true, false}) {
    for (auto &it : bm(c)) {

      // Should this node mutate?
      if (Random::get<uint8_t>(1, 100) < chance) {

        uint8_t mutation = Random::get<uint8_t>(1, 3);

        int x = it.second.pos.x;
        int y = it.second.pos.y;

        switch (mutation) {

          // Move vertically
        case 1:

          // Swap with neighbour above/below
          if (is_adjacent(x, y)) {
            int new_y = Random::get<bool>() ? y + 1 : y - 1;

            it.second.pos.y = new_y;
            if (bm.positions.contains({x, new_y})) {
              bm(c)[bm.positions[{x, new_y}]].pos.y = y;
              bm.positions[{x, y}] = bm(c)[bm.positions[{x, new_y}]].id;
            }
            bm.positions[{x, new_y}] = it.second.id;
          }
          break;

          // Move horizontally
        case 2:

          // Swap with to right
          if (Random::get<bool>() && is_adjacent(x + 2, y)) {
            it.second.pos.x = x + 2;
            if (bm.positions.contains({x + 2, y})) {
              bm(c)[bm.positions[{x + 2, y}]].pos.x = x;
              bm.positions[{x, y}] = bm(c)[bm.positions[{x + 2, y}]].id;
            }
            bm.positions[{x + 2, y}] = it.second.id;
          }
          // Swap with neighbour to left
          else if (is_adjacent(x - 2, y)) {
            it.second.pos.x = x - 2;
            if (bm.positions.contains({x - 2, y})) {
              bm(c)[bm.positions[{x - 2, y}]].pos.x = x;
              bm.positions[{x, y}] = bm(c)[bm.positions[{x - 2, y}]].id;
            }
            bm.positions[{x - 2, y}] = it.second.id;
          }
          break;

          // Move to front
        case 3:
          if (it.second.connections.size() > 0) {
            int move_to = *(Random::get(it.second.connections));
            int new_y = bm(!c)[move_to].pos.y;
            it.second.pos.y = new_y;
            if (bm.positions.contains({x, new_y})) {
              bm(c)[bm.positions[{x, new_y}]].pos.y = y;
              bm.positions[{x, y}] = bm(c)[bm.positions[{x, new_y}]].id;
            }
            bm.positions[{x, new_y}] = it.second.id;
          }
          break;
          // case 4:
          //   std::cout << "Swap Randomly\n";
          //   break;
        }
      }
    }
  }
  bm.calc_score();
  return bm;
}

void Bipartate::write_dot(std::string file_name) {
  std::ofstream f;
  f.open(file_name);
  std::cout << "Writing " << file_name << std::endl;
  f << "graph autograph {\n";

  // Nodes
  f << std::endl;
  f << "  // Nodes\n";
  for (auto &it : t1) {
    f << it.second.as_dot();
  }
  for (auto &it : t2) {
    f << it.second.as_dot();
  }

  // Edges
  f << std::endl;
  f << "  // Edges\n";
  for (Edge e : edges) {
    f << e.as_dot();
  }

  f << "\n}\n";
  f.close();
  return;
}

// Calculate score to optimise
void Bipartate::calc_score() {

  score = 0;
  for (unsigned int i = 0; i < edges.size(); ++i) {
    Segment s1(t1[edges[i].from].pos, t2[edges[i].to].pos);
    for (unsigned int j = i + 1; j < edges.size(); ++j) {
      Segment s2(t1[edges[j].from].pos, t2[edges[j].to].pos);
      score += s1.intersects(s2);
    }
  }
}

struct Generation {

  // What generation we are on
  int n_generation;

  unsigned int default_probability;
  unsigned int default_n_gens;
  unsigned int default_n_specimen;
  unsigned int default_output;

  // All Graphs of this generation
  std::vector<Bipartate> specimen;

  // Scores of in this generation
  unsigned int worst_score;
  // double percentile_25; // 25th percentile
  unsigned int median_score; // 50th percentile
  // double percentile_75; // 75th percentile
  unsigned int best_score;

  // Name of CSV that this was initially created from
  std::string csv_name;

  Generation(int argc, char **argv);
  void evolve(unsigned int n_specimen, uint8_t chance);
  void write_dot(bool all);
  void advance(unsigned int n_specimen, uint8_t chance);
  void advance_n_gens(unsigned int n_gens, unsigned int n_specimen,
                      uint8_t chance);
};

void Generation::advance(unsigned int n_specimen, uint8_t chance) {

  // std::cout << "Going from Generation " << n_generation;
  // std::cout << " to Generation " << ++n_generation << std::endl;
  evolve(n_specimen, chance);
}

void Generation::advance_n_gens(unsigned int n_gens = 0,
                                unsigned int n_specimen = 0,
                                uint8_t chance = 0) {

  if (!n_gens || !n_specimen || !chance) {
    n_gens = default_n_gens;
    n_specimen = default_n_specimen;
    chance = default_probability;
  }

  for (unsigned int i = 0; i <= n_gens; i++) {
    if (!(i % default_output)) {
      std::cout << "Best score for Generation " << n_generation << ": ";
      std::cout << specimen[0].score << std::endl;
      write_dot(false);
    }
    evolve(n_specimen, chance);
  }
}

Generation::Generation(int argc, char **argv) {

  n_generation = 0;

  // Create parser for arguments using argparse.
  // From https://github.com/p-ranav/argparse
  argparse::ArgumentParser arguments("autograph", "1.0");

  // Positional argument accepting CSV file
  arguments.add_argument("CSV").default_value("none").help(
      "File path: CSV file");

  // Optional argument
  arguments.add_argument("-s", "--n_specimen")
      .default_value(static_cast<unsigned int>(1000))
      .scan<'u', unsigned int>()
      .help("Integer: Number of specimen per generation");

  // Optional argument
  arguments.add_argument("-g", "--n_generations")
      .default_value(static_cast<unsigned int>(1000))
      .scan<'u', unsigned int>()
      .help("Integer: Number of generations");

  // Optional argument
  arguments.add_argument("-p", "--probability")
      .default_value(static_cast<unsigned int>(50))
      .scan<'u', unsigned int>()
      .help("Integer between 0 and 100: Proportion of mutations");

  // Optional argument
  arguments.add_argument("-o", "--output")
      .default_value(static_cast<unsigned int>(100))
      .scan<'u', unsigned int>()
      .help("Integer: Output best every n generations");

  // Parse command line arguments
  try {
    arguments.parse_args(argc, argv);
  } catch (const std::runtime_error &err) {
    std::cerr << "ERROR: " << err.what() << std::endl;
    std::cerr << arguments;
    std::exit(1);
  }

  // Print names of CSV provided
  if (arguments.is_used("CSV")) {
    csv_name = arguments.get<std::string>("CSV");
    std::cout << "Importing data from from file " << csv_name << std::endl;

  } else {

    // CSV file not provided
    std::cerr << arguments << std::endl;
    std::cerr << "ERROR: No CSV file provided!" << std::endl;
    _Exit(16);
  }

  std::cout << std::endl;
  default_n_specimen = arguments.get<unsigned int>("-s");
  default_probability = arguments.get<unsigned int>("-p");
  default_n_gens = arguments.get<unsigned int>("-g");
  default_output = arguments.get<unsigned int>("-o");

  std::cout << "n_specimen: " << default_n_specimen << std::endl;
  std::cout << "n_generations: " << default_n_gens << std::endl;
  std::cout << "mutation probability: " << default_probability << std::endl;
  std::cout << "output every n generations: " << default_output << std::endl;
  std::cout << std::endl;

  Bipartate b1(csv_name);
  b1.calc_score();
  specimen.push_back(b1);
  std::cout << "number of nodes: ";
  std::cout << std::to_string(b1.t1.size() + b1.t2.size()) << std::endl;
  std::cout << "number of edges: " << std::to_string(b1.edges.size());
  std::cout << std::endl;
  std::cout << "Score for Generation 0: " << b1.score << std::endl;
  std::cout << std::endl;
}

void Generation::evolve(unsigned int n_specimen, uint8_t chance) {

  // Killing by chance
  unsigned int n_size = specimen.size();

  std::vector<Bipartate> specimen_copy;

  for (unsigned int i = 0; i < n_size; i++) {
    if (i < Random::get<uint8_t>(1, n_size)) {
      specimen_copy.push_back(specimen[i]);
    }
  }

  // Replace specimen with copy
  specimen.clear();
  specimen = specimen_copy;
  specimen_copy.clear();

  unsigned int i = 0;
  n_size = specimen.size();
  while (n_size < n_specimen) {
    specimen.push_back(specimen[i].mutate(chance));
    i++;
    n_size++;
  }
  std::sort(specimen.begin(), specimen.end());
  n_generation++;
}

void Generation::write_dot(bool all) {
  specimen[0].write_dot("best_gen_" + std::to_string(n_generation) + ".dot");

  if (all) {
    for (unsigned int i = 1; i < specimen.size(); ++i) {
      specimen[i].write_dot("specimen_" + std::to_string(i) + ".dot");
    }
  }
}

max_stars_repo_name: adisidev/autograph

max_issues_repo_name: adisidev/autograph

max_forks_repo_name: adisidev/autograph


text:
#include "server/api/url_parser.hpp"

#include <fstream>

// needed for BOOST_CHECK_EQUAL
namespace osrm
{
namespace server
{
namespace api
{
std::ostream &operator<<(std::ostream &out, const osrm::server::api::ParsedURL &url)
{
    out << url.service << ", " << url.version << ", " << url.profile << ", " << url.query;

    return out;
}
} // namespace api
} // namespace server
} // namespace osrm

#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>

#define CHECK_EQUAL_RANGE(R1, R2)                                                                  \
    BOOST_CHECK_EQUAL_COLLECTIONS(R1.begin(), R1.end(), R2.begin(), R2.end());

BOOST_AUTO_TEST_SUITE(api_url_parser)

using namespace osrm;
using namespace osrm::server;

// returns distance to front
std::size_t testInvalidURL(std::string url)
{
    auto iter = url.begin();
    auto result = api::parseURL(iter, url.end());
    BOOST_CHECK(!result);
    return std::distance(url.begin(), iter);
}

BOOST_AUTO_TEST_CASE(invalid_urls)
{
    BOOST_CHECK_EQUAL(testInvalidURL("/route/"), 7UL);
    BOOST_CHECK_EQUAL(testInvalidURL("/route/bla"), 7UL);
    BOOST_CHECK_EQUAL(testInvalidURL("/route/1/1,2;3;4"), 7UL);
    BOOST_CHECK_EQUAL(testInvalidURL("/route/v1/pro[]file/1,2;3,4"), 13UL);
    BOOST_CHECK_EQUAL(testInvalidURL("/route/v1/profile"), 17UL);
    BOOST_CHECK_EQUAL(testInvalidURL("/route/v1/profile/"), 18UL);
}

BOOST_AUTO_TEST_CASE(valid_urls)
{
    api::ParsedURL reference_1{"route", 1, "profile", "0,1;2,3;4,5?options=value&foo=bar", 18UL};
    auto result_1 = api::parseURL("/route/v1/profile/0,1;2,3;4,5?options=value&foo=bar");
    BOOST_CHECK(result_1);
    BOOST_CHECK_EQUAL(reference_1.service, result_1->service);
    BOOST_CHECK_EQUAL(reference_1.version, result_1->version);
    BOOST_CHECK_EQUAL(reference_1.profile, result_1->profile);
    CHECK_EQUAL_RANGE(reference_1.query, result_1->query);
    BOOST_CHECK_EQUAL(reference_1.prefix_length, result_1->prefix_length);

    // no options
    api::ParsedURL reference_2{"route", 1, "profile", "0,1;2,3;4,5", 18UL};
    auto result_2 = api::parseURL("/route/v1/profile/0,1;2,3;4,5");
    BOOST_CHECK(result_2);
    BOOST_CHECK_EQUAL(reference_2.service, result_2->service);
    BOOST_CHECK_EQUAL(reference_2.version, result_2->version);
    BOOST_CHECK_EQUAL(reference_2.profile, result_2->profile);
    CHECK_EQUAL_RANGE(reference_2.query, result_2->query);
    BOOST_CHECK_EQUAL(reference_2.prefix_length, result_2->prefix_length);

    // one coordinate
    std::vector<util::Coordinate> coords_3 = {
        util::Coordinate{util::FloatLongitude{0}, util::FloatLatitude{1}},
    };
    api::ParsedURL reference_3{"route", 1, "profile", "0,1", 18UL};
    auto result_3 = api::parseURL("/route/v1/profile/0,1");
    BOOST_CHECK(result_3);
    BOOST_CHECK_EQUAL(reference_3.service, result_3->service);
    BOOST_CHECK_EQUAL(reference_3.version, result_3->version);
    BOOST_CHECK_EQUAL(reference_3.profile, result_3->profile);
    CHECK_EQUAL_RANGE(reference_3.query, result_3->query);
    BOOST_CHECK_EQUAL(reference_3.prefix_length, result_3->prefix_length);

    // polyline
    api::ParsedURL reference_5{"route", 1, "profile", "polyline(_ibE?_seK_seK_seK_seK)?", 18UL};
    auto result_5 = api::parseURL("/route/v1/profile/polyline(_ibE?_seK_seK_seK_seK)?");
    BOOST_CHECK(result_5);
    BOOST_CHECK_EQUAL(reference_5.service, result_5->service);
    BOOST_CHECK_EQUAL(reference_5.version, result_5->version);
    BOOST_CHECK_EQUAL(reference_5.profile, result_5->profile);
    CHECK_EQUAL_RANGE(reference_5.query, result_5->query);
    BOOST_CHECK_EQUAL(reference_5.prefix_length, result_5->prefix_length);

    // polyline6
    api::ParsedURL reference_6{"route", 1, "profile", "polyline6(_ibE?_seK_seK_seK_seK)?", 18UL};
    auto result_6 = api::parseURL("/route/v1/profile/polyline6(_ibE?_seK_seK_seK_seK)?");
    BOOST_CHECK(result_6);
    BOOST_CHECK_EQUAL(reference_6.service, result_6->service);
    BOOST_CHECK_EQUAL(reference_6.version, result_6->version);
    BOOST_CHECK_EQUAL(reference_6.profile, result_6->profile);
    CHECK_EQUAL_RANGE(reference_6.query, result_6->query);
    BOOST_CHECK_EQUAL(reference_6.prefix_length, result_6->prefix_length);

    // tile
    api::ParsedURL reference_7{"route", 1, "profile", "tile(1,2,3).mvt", 18UL};
    auto result_7 = api::parseURL("/route/v1/profile/tile(1,2,3).mvt");
    BOOST_CHECK(result_7);
    BOOST_CHECK_EQUAL(reference_7.service, result_7->service);
    BOOST_CHECK_EQUAL(reference_7.version, result_7->version);
    BOOST_CHECK_EQUAL(reference_7.profile, result_7->profile);
    CHECK_EQUAL_RANGE(reference_7.query, result_7->query);
    BOOST_CHECK_EQUAL(reference_7.prefix_length, result_7->prefix_length);

    // polyline with %HEX
    api::ParsedURL reference_8{
        "match", 1, "car", "polyline(}jmwFz~ubMyCa@`@yDJqE)?你好&\n \"%~", 14UL};
    auto result_8 = api::parseURL(
        "/match/v1/car/polyline(%7DjmwFz~ubMyCa@%60@yDJqE)?%e4%bd%a0%e5%a5%bd&%0A%20%22%25%7e");
    BOOST_CHECK(result_8);
    BOOST_CHECK_EQUAL(reference_8.service, result_8->service);
    BOOST_CHECK_EQUAL(reference_8.version, result_8->version);
    BOOST_CHECK_EQUAL(reference_8.profile, result_8->profile);
    CHECK_EQUAL_RANGE(reference_8.query, result_8->query);
    BOOST_CHECK_EQUAL(reference_8.prefix_length, result_8->prefix_length);

    // profile with special characters
    api::ParsedURL reference_9{
        "route", 1, "foo-bar_baz.profile", "0,1;2,3;4,5?options=value&foo=bar", 30UL};
    auto result_9 =
        api::parseURL("/route/v1/foo-bar_baz.profile/0,1;2,3;4,5?options=value&foo=bar");
    BOOST_CHECK(result_9);
    BOOST_CHECK_EQUAL(reference_9.service, result_9->service);
    BOOST_CHECK_EQUAL(reference_9.version, result_9->version);
    BOOST_CHECK_EQUAL(reference_9.profile, result_9->profile);
    CHECK_EQUAL_RANGE(reference_9.query, result_9->query);
    BOOST_CHECK_EQUAL(reference_9.prefix_length, result_9->prefix_length);
}

BOOST_AUTO_TEST_SUITE_END()


text:
#define BOOST_TEST_MODULE cart_communicator

#include <boost/test/included/unit_test.hpp>
#include <mpl/mpl.hpp>

bool cart_communicator_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  mpl::cart_communicator::sizes sizes(
      {{0, mpl::cart_communicator::periodic}, {0, mpl::cart_communicator::nonperiodic}});
  mpl::cart_communicator comm_c(comm_world, mpl::dims_create(comm_world.size(), sizes));
  if (comm_c.dim() != 2)
    return false;
  int rank{comm_c.rank()};
  int size{comm_c.size()};
  auto coords{comm_c.coords()};
  if (comm_c.rank(coords) != rank)
    return false;
  auto dims{comm_c.dims()};
  if (dims[0] * dims[1] != comm_c.size())
    return false;
  auto p{comm_c.is_periodic()};
  if (not(p[0] == mpl::cart_communicator::periodic and
          p[1] == mpl::cart_communicator::nonperiodic))
    return false;
  auto ranks{comm_c.shift(0, 1)};
  ++coords[0];
  if (coords[0] >= dims[0])
    coords[0] = 0;
  int dest1{comm_c.rank(coords)};
  coords[0] -= 2;
  if (coords[0] < 0)
    coords[0] += dims[0];
  int source1{comm_c.rank(coords)};
  if (not(ranks.source == source1 and ranks.dest == dest1))
    return false;
  {
    double x = 1;
    std::vector<double> y(4, 0.);
    comm_c.neighbor_allgather(x, y.data());
    if ((y[0] != 0 and y[0] != 1) or (y[1] != 0 and y[1] != 1) or (y[2] != 0 and y[2] != 1) or
        (y[3] != 0 and y[3] != 1))
      return false;
  }
  {
    std::vector<double> x(4, rank + 1.0);
    std::vector<double> y(4, 0.0);
    comm_c.neighbor_alltoall(x.data(), y.data());
    auto ranks0{comm_c.shift(0, 1)};
    auto ranks1{comm_c.shift(1, 1)};
    if (ranks0.source != mpl::proc_null and y[0] != ranks0.source + 1.)
      return false;
    if (ranks0.dest != mpl::proc_null and y[1] != ranks0.dest + 1.)
      return false;
    if (ranks1.source != mpl::proc_null and y[2] != ranks1.source + 1.)
      return false;
    if (ranks1.dest != mpl::proc_null and y[3] != ranks1.dest + 1.)
      return false;
  }
  {
    std::vector<double> x(4, rank + 1.0);
    std::vector<double> y(4, 0.0);
    mpl::layouts<double> ls;
    ls.push_back(mpl::indexed_layout<double>({{1, 0}}));
    ls.push_back(mpl::indexed_layout<double>({{1, 1}}));
    ls.push_back(mpl::indexed_layout<double>({{1, 2}}));
    ls.push_back(mpl::indexed_layout<double>({{1, 3}}));
    comm_c.neighbor_alltoallv(x.data(), ls, y.data(), ls);
    auto ranks0{comm_c.shift(0, 1)};
    auto ranks1{comm_c.shift(1, 1)};
    if (ranks0.source != mpl::proc_null and y[0] != ranks0.source + 1.)
      return false;
    if (ranks0.dest != mpl::proc_null and y[1] != ranks0.dest + 1.)
      return false;
    if (ranks1.source != mpl::proc_null and y[2] != ranks1.source + 1.)
      return false;
    if (ranks1.dest != mpl::proc_null and y[3] != ranks1.dest + 1.)
      return false;
  }
  return true;
}

BOOST_AUTO_TEST_CASE(cart_communicator) {
  BOOST_TEST(cart_communicator_test());
}

max_stars_repo_name: jacobmerson/mpl

max_issues_repo_name: jacobmerson/mpl

max_forks_repo_name: jacobmerson/mpl


text:
// Copyright (c) 2019 The Bitcoin SV developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "config.h"
#include "txn_double_spend_detector.h"
#include "txn_validation_data.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

namespace {
    // Create an orphan txn
	TxInputDataSPtr CreateTxnWithNInputs(
                        TxSource source,
                        size_t nNumInputs) {
        CKey key;
        key.MakeNewKey(true);

        CMutableTransaction tx;
        tx.vin.resize(nNumInputs);
        for (size_t i=0; i<nNumInputs; i++) {
            tx.vin[i].prevout = COutPoint(InsecureRand256(), 0);
            tx.vin[i].scriptSig << OP_1;
        }
        tx.vout.resize(1);
        tx.vout[0].nValue = 1 * CENT;
        tx.vout[0].scriptPubKey =
            GetScriptForDestination(key.GetPubKey().GetID());
        // Return a shared object with txn's input data
        return std::make_shared<CTxInputData>(
                                    source,                   // tx source
                                    MakeTransactionRef(tx));  // a pointer to the tx
    }
}

BOOST_FIXTURE_TEST_SUITE(test_double_spend_detector, TestingSetup)

BOOST_AUTO_TEST_CASE(test_detector_creation) {
    // Create detector object.
    std::shared_ptr<CTxnDoubleSpendDetector> dsDetector {
        std::make_shared<CTxnDoubleSpendDetector>()
    };
    BOOST_REQUIRE(dsDetector);
}

BOOST_AUTO_TEST_CASE(test_detector_insert_txn_inputs) {
    // Create detector object.
    std::shared_ptr<CTxnDoubleSpendDetector> dsDetector {
        std::make_shared<CTxnDoubleSpendDetector>()
    };

    auto txnInputData1 = CreateTxnWithNInputs(TxSource::p2p, 10);
    const CTransaction &tx1 = *txnInputData1->mpTx;
    auto txnInputData2 = CreateTxnWithNInputs(TxSource::p2p, 10);
    const CTransaction &tx2 = *txnInputData2->mpTx;
    auto txnInputData3 = CreateTxnWithNInputs(TxSource::p2p, 10);
    const CTransaction &tx3 = *txnInputData3->mpTx;

    BOOST_REQUIRE(dsDetector->getDoubleSpendTxns().empty());
    // tx1 checks
    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData1));
    BOOST_REQUIRE(!dsDetector->insertTxnInputs(txnInputData1));
    // tx2 checks
    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData2));
    BOOST_REQUIRE(!dsDetector->insertTxnInputs(txnInputData2));
    // tx3 checks
    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData3));
    BOOST_REQUIRE(!dsDetector->insertTxnInputs(txnInputData3));
    // At this moment there should be 3 entries
    BOOST_REQUIRE(3 == dsDetector->getDoubleSpendTxns().size());
    // An empty set returned when called again
    BOOST_REQUIRE(dsDetector->getDoubleSpendTxns().empty());

    auto nTxnsVinSize = tx1.vin.size() + tx2.vin.size() + tx3.vin.size();
    BOOST_CHECK(dsDetector->getKnownSpendsSize() == nTxnsVinSize);
}

BOOST_AUTO_TEST_CASE(test_detector_insert_txn_inputs2) {
    // Create detector object.
    std::shared_ptr<CTxnDoubleSpendDetector> dsDetector {
        std::make_shared<CTxnDoubleSpendDetector>()
    };

    auto txnInputData1 = CreateTxnWithNInputs(TxSource::p2p, 10);
    const CTransaction &tx1 = *txnInputData1->mpTx;
    auto txnInputData2 = CreateTxnWithNInputs(TxSource::p2p, 10);
    const CTransaction &tx2 = *txnInputData2->mpTx;

    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData1));
    // Assign tx1's input as the first input of tx2
    const_cast<COutPoint&>(tx2.vin[0].prevout) = const_cast<COutPoint&>(tx1.vin[0].prevout);
    BOOST_REQUIRE(!dsDetector->insertTxnInputs(txnInputData2));

    BOOST_CHECK(dsDetector->getKnownSpendsSize() == tx1.vin.size());
    // Check if we are able to add tx2 after conflicting inputs were removed
    dsDetector->removeTxnInputs(tx1);
    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData2));
}

BOOST_AUTO_TEST_CASE(test_detector_remove_txn_inputs) {
    // Create detector object.
    std::shared_ptr<CTxnDoubleSpendDetector> dsDetector {
        std::make_shared<CTxnDoubleSpendDetector>()
    };

    auto txnInputData1 = CreateTxnWithNInputs(TxSource::p2p, 10000);
    const CTransaction &tx1 = *txnInputData1->mpTx;
    auto txnInputData2 = CreateTxnWithNInputs(TxSource::p2p, 10);
    const CTransaction &tx2 = *txnInputData2->mpTx;
    // Insert tx1
    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData1));
    BOOST_CHECK(dsDetector->getKnownSpendsSize() == tx1.vin.size());
    // Try to remove inputs from a non existing txn
    dsDetector->removeTxnInputs(tx2);
    BOOST_CHECK(dsDetector->getKnownSpendsSize() == tx1.vin.size());
    // Add inputs from tx2
    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData2));
    BOOST_CHECK(dsDetector->getKnownSpendsSize() == tx1.vin.size() + tx2.vin.size());
    // Remove inputs from tx2
    dsDetector->removeTxnInputs(tx2);
    BOOST_CHECK(dsDetector->getKnownSpendsSize() == tx1.vin.size());
}

BOOST_AUTO_TEST_CASE(test_detector_clear_txn_inputs) {
    // Create detector object.
    std::shared_ptr<CTxnDoubleSpendDetector> dsDetector {
        std::make_shared<CTxnDoubleSpendDetector>()
    };

    auto txnInputData1 = CreateTxnWithNInputs(TxSource::p2p, 10000);
    const CTransaction &tx1 = *txnInputData1->mpTx;
    // Insert tx1
    BOOST_REQUIRE(dsDetector->insertTxnInputs(txnInputData1));
    BOOST_CHECK(dsDetector->getKnownSpendsSize() == tx1.vin.size());
    dsDetector->clear();
    BOOST_CHECK(dsDetector->getKnownSpendsSize() == 0);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: neuromancer/bitcoin-sv

max_issues_repo_name: neuromancer/bitcoin-sv

max_forks_repo_name: neuromancer/bitcoin-sv


text:
// Copyright PA Knowledge Ltd 2021
// MIT License. For licence terms see LICENCE.md file.

#ifndef UDPCLIENT_HPP
#define UDPCLIENT_HPP

#include <boost/asio/ip/udp.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/buffer.hpp>
#include "UdpClientInterface.hpp"

class UdpClient : public UdpClientInterface
{
public:
  explicit UdpClient(const std::string& address, std::uint16_t port);
  void send(ConstSocketBuffers inputBuffers) override;

private:
  boost::asio::io_service io_context;
  boost::asio::ip::udp::socket s;
  boost::asio::ip::udp::endpoint endpoints;

  boost::asio::ip::udp::endpoint findEndpoints(const std::string& address, std::uint16_t port);
};

#endif //UDPCLIENT_HPP

max_stars_repo_name: oakdoor/enterprisediodefiletransfer

max_issues_repo_name: oakdoor/enterprisediodefiletransfer

max_forks_repo_name: oakdoor/enterprisediodefiletransfer