text:
// Copyright 2015 Peter Dimov.
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt

#if defined(_MSC_VER)
#pragma warning( disable: 4244 ) // 'initializing': conversion from 'int' to 'char', possible loss of data
#endif

#include <boost/mp11/tuple.hpp>
#include <boost/core/lightweight_test.hpp>
#include <tuple>
#include <memory>
#include <utility>
#include <array>

int main()
{
    using boost::mp11::tuple_for_each;

    {
        std::tuple<int, short, char> tp{ 1, 2, 3 };

        {
            int s = 0;

            tuple_for_each( tp, [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }

        {
            int s = 0;

            tuple_for_each( std::move(tp), [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }
    }

    {
        std::tuple<int, short, char> const tp{ 1, 2, 3 };

        {
            int s = 0;

            tuple_for_each( tp, [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }

        {
            int s = 0;

            tuple_for_each( std::move(tp), [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }
    }

#if defined( __clang_major__ ) && __clang_major__ == 3 && __clang_minor__ < 8
#else

    {
        std::tuple<std::unique_ptr<int>, std::unique_ptr<int>, std::unique_ptr<int>> tp{ std::unique_ptr<int>(new int(1)), std::unique_ptr<int>(new int(2)), std::unique_ptr<int>(new int(3)) };

        int s = 0;

        tuple_for_each( std::move(tp), [&]( std::unique_ptr<int> p ){ s = s * 10 + *p; } );

        BOOST_TEST_EQ( s, 123 );
    }

#endif

    {
        std::pair<int, short> tp{ 1, 2 };

        {
            int s = 0;

            tuple_for_each( tp, [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 12 );
        }

        {
            int s = 0;

            tuple_for_each( std::move(tp), [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 12 );
        }
    }

    {
        std::pair<int, short> const tp{ 1, 2 };

        {
            int s = 0;

            tuple_for_each( tp, [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 12 );
        }

        {
            int s = 0;

            tuple_for_each( std::move(tp), [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 12 );
        }
    }

    {
        std::array<int, 3> tp{{ 1, 2, 3 }};

        {
            int s = 0;

            tuple_for_each( tp, [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }

        {
            int s = 0;

            tuple_for_each( std::move(tp), [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }
    }

    {
        std::array<int, 3> const tp{{ 1, 2, 3 }};

        {
            int s = 0;

            tuple_for_each( tp, [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }

        {
            int s = 0;

            tuple_for_each( std::move(tp), [&]( int x ){ s = s * 10 + x; } );

            BOOST_TEST_EQ( s, 123 );
        }
    }

    {
        std::tuple<> tp;

        BOOST_TEST_EQ( tuple_for_each( tp, 11 ), 11 );
        BOOST_TEST_EQ( tuple_for_each( std::move( tp ), 12 ), 12 );
    }

    {
        std::array<int, 0> tp;

        BOOST_TEST_EQ( tuple_for_each( tp, 11 ), 11 );
        BOOST_TEST_EQ( tuple_for_each( std::move( tp ), 12 ), 12 );
    }

    return boost::report_errors();
}


text:
// Copyright (c) 2015-2018 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#ifndef htslib_sam_facade_hpp
#define htslib_sam_facade_hpp

#include <string>
#include <vector>
#include <unordered_map>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <utility>

#include <boost/filesystem/path.hpp>
#include <boost/optional.hpp>

#include "htslib/hts.h"
#include "htslib/sam.h"

#include "basics/aligned_read.hpp"
#include "read_reader_impl.hpp"

namespace octopus {

class GenomicRegion;
class ContigRegion;

namespace io {

class HtslibSamFacade : public IReadReaderImpl
{
public:
    using Path = boost::filesystem::path;

    using IReadReaderImpl::SampleName;
    using IReadReaderImpl::ReadContainer;
    using IReadReaderImpl::SampleReadMap;
    using IReadReaderImpl::PositionList;

    using NucleotideSequence = AlignedRead::NucleotideSequence;

    using ReadGroupIdType = std::string;

    HtslibSamFacade() = delete;

    HtslibSamFacade(Path file_path);
    HtslibSamFacade(Path sam_out, Path sam_template);

    HtslibSamFacade(const HtslibSamFacade&)            = delete;
    HtslibSamFacade& operator=(const HtslibSamFacade&) = delete;
    HtslibSamFacade(HtslibSamFacade&&)                 = default;
    HtslibSamFacade& operator=(HtslibSamFacade&&)      = default;

    ~HtslibSamFacade() override;

    bool is_open() const noexcept override;
    void open() override;
    void close() override;

    std::vector<SampleName> extract_samples() const override;
    std::vector<ReadGroupIdType> extract_read_groups(const SampleName& sample) const override;

    bool has_reads(const GenomicRegion& region) const override;
    bool has_reads(const SampleName& sample,
                   const GenomicRegion& region) const override;
    bool has_reads(const std::vector<SampleName>& samples,
                   const GenomicRegion& region) const override;

    std::size_t count_reads(const GenomicRegion& region) const override;
    std::size_t count_reads(const SampleName& sample,
                            const GenomicRegion& region) const override;
    std::size_t count_reads(const std::vector<SampleName>& samples,
                            const GenomicRegion& region) const override;

    PositionList extract_read_positions(const GenomicRegion& region,
                                        std::size_t max_reads) const override;
    PositionList extract_read_positions(const SampleName& sample,
                                        const GenomicRegion& region,
                                        std::size_t max_reads) const override;
    PositionList extract_read_positions(const std::vector<SampleName>& samples,
                                        const GenomicRegion& region,
                                        std::size_t max_reads) const override;

    SampleReadMap fetch_reads(const GenomicRegion& region) const override;
    ReadContainer fetch_reads(const SampleName& sample,
                              const GenomicRegion& region) const override;
    SampleReadMap fetch_reads(const std::vector<SampleName>& samples,
                              const GenomicRegion& region) const override;

    GenomicRegion::Size reference_size(const GenomicRegion::ContigName& contig) const override;
    std::vector<GenomicRegion::ContigName> reference_contigs() const override;
    boost::optional<std::vector<GenomicRegion::ContigName>> mapped_contigs() const override;

    void write(const AlignedRead& read);

private:
    using HtsTid = std::int32_t;

    static constexpr std::size_t defaultReserve_ {10'000'000};

    struct HtsFileDeleter
    {
        void operator()(htsFile* file) const { hts_close(file); }
    };
    struct HtsHeaderDeleter
    {
        void operator()(bam_hdr_t* header) const { bam_hdr_destroy(header); }
    };
    struct HtsIndexDeleter
    {
        void operator()(hts_idx_t* index) const { hts_idx_destroy(index); }
    };
    struct HtsBam1Deleter
    {
        void operator()(bam1_t* b) const { bam_destroy1(b); }
    };

    class HtslibIterator
    {
    public:
        HtslibIterator() = delete;

        HtslibIterator(const HtslibSamFacade& hts_facade, const GenomicRegion& region);
        HtslibIterator(const HtslibSamFacade& hts_facade, const GenomicRegion::ContigName& contig);

        HtslibIterator(const HtslibIterator&) = delete;
        HtslibIterator& operator=(const HtslibIterator&) = delete;

        ~HtslibIterator() noexcept = default;

        bool operator++();
        AlignedRead operator*() const;

        HtslibSamFacade::ReadGroupIdType read_group() const;

        bool is_good() const noexcept;
        std::size_t begin() const noexcept;

    private:
        struct HtsIteratorDeleter
        {
            void operator()(hts_itr_t* iterator) const { sam_itr_destroy(iterator); }
        };
        struct HtsBam1Deleter
        {
            void operator()(bam1_t* b) const { bam_destroy1(b); }
        };

        const HtslibSamFacade& hts_facade_;

        std::unique_ptr<hts_itr_t, HtsIteratorDeleter> hts_iterator_;
        std::unique_ptr<bam1_t, HtsBam1Deleter> hts_bam1_;
    };

    Path file_path_;

    std::unique_ptr<htsFile, HtsFileDeleter> hts_file_;
    std::unique_ptr<bam_hdr_t, HtsHeaderDeleter> hts_header_;
    std::unique_ptr<hts_idx_t, HtsIndexDeleter> hts_index_;

    std::unordered_map<GenomicRegion::ContigName, HtsTid> hts_targets_;
    std::unordered_map<HtsTid, GenomicRegion::ContigName> contig_names_;
    std::unordered_map<ReadGroupIdType, SampleName> sample_names_;

    std::vector<SampleName> samples_;

    void init_maps();
    HtsTid get_htslib_target(const GenomicRegion::ContigName& contig) const;
    const GenomicRegion::ContigName& get_contig_name(HtsTid target) const;
    std::uint64_t get_num_mapped_reads(const GenomicRegion::ContigName& contig) const;
    ReadContainer fetch_all_reads(const GenomicRegion& region) const;
    void write(const AlignedRead& read, bam1_t* result) const;
};

} // namespace io
} // namespace octopus

#endif

ext: hpp

max_stars_repo_name: gmagoon/octopus

max_issues_repo_name: gmagoon/octopus

max_forks_repo_name: gmagoon/octopus


text:
#include <cctbx/boost_python/flex_fwd.h>

#include <boost/python/class.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/return_by_value.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <boost/python/iterator.hpp>

#include <cctbx/xray/parameter_map.h>
#include <cctbx/xray/scatterer.h>

namespace cctbx { namespace xray { namespace boost_python {

struct parameter_indices_wrapper
{
  typedef parameter_indices wt;

  static int invariable() {
    return wt::invariable;
  }

  static void wrap() {
    using namespace boost::python;
    class_<wt>("parameter_indices", no_init)
      .add_static_property("invariable", invariable)
      .def_readonly("site", &wt::site)
      .def_readonly("u_iso", &wt::u_iso)
      .def_readonly("u_aniso", &wt::u_aniso)
      .def_readonly("occupancy", &wt::occupancy)
      .def_readonly("fp", &wt::fp)
      .def_readonly("fdp", &wt::fdp)
      ;
  }
};

template <class XRayScattererType>
struct parameter_map_wrapper
{
  typedef parameter_map<XRayScattererType> wt;

  static void wrap(char const *name) {
    using namespace boost::python;
    typedef return_value_policy<copy_const_reference> ccr;
    typedef return_value_policy<return_by_value> rbv;
    class_<wt>("parameter_map", no_init)
      .def(init<af::const_ref<typename wt::xray_scatterer_type> const &>((
            arg("scatterers"))))
      .def("add_independent_scalar", &wt::add_independent_scalar)
      .def("__len__", &wt::size)
      .def("__getitem__", &wt::operator[], ccr())
      .def("__iter__", iterator<wt, ccr>())
      .add_property("n_parameters", &wt::n_parameters)
      .add_property("n_scatterers", &wt::n_scatterers)
      ;
  }
};

void wrap_parameter_map() {
  parameter_indices_wrapper::wrap();
  parameter_map_wrapper<xray::scatterer<> >::wrap("parameter_map");
}

}}}

ext: cpp


text:
#include <sleip/dynamic_array.hpp>

#include <boost/core/lightweight_test.hpp>

void
test_equality()
{
  auto const a = sleip::dynamic_array<int>{1, 2, 3, 4, 5};
  auto const b = a;
  auto const c = sleip::dynamic_array<int>{1, 2, 3, 2, 1};

  BOOST_ASSERT((a == b));
  BOOST_ASSERT(!(a == c));

  BOOST_ASSERT(!(a != b));
  BOOST_ASSERT((a != c));
}

void
test_greater_than_less_than()
{
  auto const a = sleip::dynamic_array<int>{1, 2, 3, 4, 5};
  auto const b = a;
  auto const c = sleip::dynamic_array<int>{0, 1, 2, 1, 0};

  // test that c is less than a and that a is not less than c
  //
  BOOST_ASSERT((c < a));
  BOOST_ASSERT(!(a < c));

  // test that c is not greater than a and that a is greater than c
  //
  BOOST_ASSERT(!(c > a));
  BOOST_ASSERT((a > c));

  // test that a is not greater or less than b
  //
  BOOST_ASSERT(!(a > b));
  BOOST_ASSERT(!(a < b));

  // test that a is less than/greater than or equal to b
  //
  BOOST_ASSERT((a <= b));
  BOOST_ASSERT((a >= b));

  // test that c is less than or equal to a and that a is not less than or equal to c
  //
  BOOST_ASSERT((c <= a));
  BOOST_ASSERT(!(a <= c));

  // test that c is not greater than or equal t o a and that a is greater than or equal to c
  //
  BOOST_ASSERT(!(c >= a));
  BOOST_ASSERT((a >= c));
}

int
main()
{
  test_equality();
  test_greater_than_less_than();

  return boost::report_errors();
}


text:
// ------------------------------------ //
#include "GlobalCEFHandler.h"

#include "GUI/GuiCEFApplication.h"

#include "include/cef_app.h"

#include <boost/filesystem.hpp>

#include <iostream>
using namespace Leviathan;
// ------------------------------------ //

DLLEXPORT bool Leviathan::GlobalCEFHandler::CEFFirstCheckChildProcess(
    int argcount, char* args[], int& returnvalue,
    std::shared_ptr<CEFApplicationKeeper>& keeper, const std::string& logname
#ifdef _WIN32
#ifdef CEF_ENABLE_SANDBOX
    ,
    CefScopedSandboxInfo& windowssandbox
#endif
    ,
    HINSTANCE hInstance
#endif // _WIN32
)
{
    // Check for no graphics mode //
    for(int i = 0; i < argcount; ++i) {
        if(std::string_view(args[i]).find("--nogui") != std::string_view::npos) {
            // No gui commandline specified //
            std::cout << "Not using CEF because --nogui is specified" << std::endl;
            return false;
        }
    }

    // Run CEF startup //
    keeper = std::make_shared<CEFApplicationKeeper>();

    void* windows_sandbox_info = nullptr;

#ifdef CEF_ENABLE_SANDBOX
    windows_sandbox_info = &sandbox;
#endif

    // Provide CEF with command-line arguments //
#ifdef _WIN32
    CefMainArgs main_args(hInstance);
#else
    // Make a copy of the args to not have CEF mess with them
    std::vector<char*> cefArgs;
    std::vector<std::string> cefArgData;

    cefArgs.resize(argcount);
    cefArgData.reserve(argcount);

    for(int i = 0; i < argcount; ++i) {

        cefArgData.push_back(args[i]);
        cefArgs[i] = cefArgData.back().data();
    }

    CefMainArgs main_args(cefArgs.size(), cefArgs.data());
    // CefMainArgs main_args(argcount, args);
#endif // _WIN32

    // Callback object //
    keeper->CEFApp = CefRefPtr<GUI::CefApplication>(new GUI::CefApplication());

    // Check are we a sub process //
    int exit_code = CefExecuteProcess(main_args, keeper->CEFApp.get(), windows_sandbox_info);
    if(exit_code >= 0) {
        // This was a sub process //
        returnvalue = exit_code;

        return true;
    }

    // Specify CEF global settings here.
    CefSettings settings;

    // Apparently this "just works" on non-windows platforms
#if !defined(CEF_ENABLE_SANDBOX) && defined(_WIN32)
    settings.no_sandbox = true;
#endif

    try {
        CefString(&settings.locales_dir_path) =
            boost::filesystem::canonical("Data/locales").wstring();

        const auto currentCanonical = boost::filesystem::canonical("./").wstring();

        // CefString(&settings.resources_dir_path) = currentCanonical;

        CefString(&settings.log_file) =
            currentCanonical + Convert::Utf8ToUtf16("/" + logname + "LogCEF.txt");

        const auto cachePath = currentCanonical + L"/Data/Cache/CEF";
        boost::filesystem::create_directories(cachePath);

        CefString(&settings.cache_path) = cachePath;

    } catch(const boost::filesystem::filesystem_error& e) {

        std::stringstream msg;
        msg << "Error missing file or accessing cache location: " << e.what() << "\n";

        std::ofstream write(std::string("Leviathan_start_failure_") +
#ifdef __linux
                            std::to_string(::getpid()) +
#endif //__linux
                            ".txt");
        write << msg.str();
        write << "Args are (" << argcount << ")" << std::endl;
        for(int i = 0; i < argcount; ++i)
            write << args[i] << std::endl;
        write << std::endl;
        write.close();

        std::cout << msg.str();
        abort();
    }

    // TODO: log_severity
    // settings.log_severity = cef_log_severity_t::LOGSEVERITY_DEBUG;

    // TODO: user agent

    settings.windowless_rendering_enabled = true;

    settings.external_message_pump = true;

    // Apparently this is missing from the windows version but not the linux version. For some
    // reason?
    // settings.single_process = false;

    // // Enable remote debugging
    // settings.remote_debugging_port = 9090;

    // Only works on windows
    // And the OnPaint assumes it is on the main thread so this doesn't work at all
    settings.multi_threaded_message_loop = false;

    // Initialize CEF.
    CefInitialize(main_args, settings, keeper->CEFApp.get(), windows_sandbox_info);

    CEFInitialized = true;

    AccessToThese = keeper.get();

    // Wasn't a sub process //
    return false;
}
// ------------------------------------ //
DLLEXPORT void Leviathan::GlobalCEFHandler::CEFLastThingInProgram()
{
    if(!CEFInitialized)
        return;

    // Close it down //
    CefShutdown();

    // The automatic templates remove the need for this message, which won't be logged anyway
    // std::cout << "CEF shutdown called" << std::endl;
}
// ------------------------------------ //
DLLEXPORT void Leviathan::GlobalCEFHandler::DoCEFMessageLoopWork()
{
    if(!CEFInitialized) {
        LOG_ERROR("DoCEFMessageLoopWork called before CEF is initialized");
        return;
    }

    CefDoMessageLoopWork();
}
// ------------------------------------ //
DLLEXPORT CEFApplicationKeeper* Leviathan::GlobalCEFHandler::GetCEFObjects()
{
    return AccessToThese;
}

DLLEXPORT void Leviathan::GlobalCEFHandler::RegisterCustomJavaScriptQueryHandler(
    std::shared_ptr<GUI::JSAsyncCustom> ptr)
{
    std::unique_lock<std::recursive_mutex> guard(JSCustomMutex);

    // Add it //
    CustomJSHandlers.push_back(ptr);

    // Notify all //
    for(size_t i = 0; i < JSAsynToNotify.size(); i++) {
        GUARD_LOCK_OTHER_NAME(JSAsynToNotify[i], guard2);
        JSAsynToNotify[i]->RegisterNewCustom(guard2, ptr);
    }

    // Things created after this will automatically retrieve the ones that are registered
    // before it is created
}

DLLEXPORT void Leviathan::GlobalCEFHandler::UnRegisterCustomJavaScriptQueryHandler(
    GUI::JSAsyncCustom* toremove)
{
    std::unique_lock<std::recursive_mutex> guard(JSCustomMutex);

    // Notify all objects //
    for(size_t i = 0; i < JSAsynToNotify.size(); i++) {
        JSAsynToNotify[i]->UnregisterCustom(toremove);
    }

    // Compare pointers and remove it //
    for(size_t i = 0; i < CustomJSHandlers.size(); i++) {
        if(CustomJSHandlers[i].get() == toremove) {

            CustomJSHandlers.erase(CustomJSHandlers.begin() + i);
            return;
        }
    }
}

DLLEXPORT const std::vector<std::shared_ptr<GUI::JSAsyncCustom>>&
    Leviathan::GlobalCEFHandler::GetRegisteredCustomHandlers()
{
    return CustomJSHandlers;
}

DLLEXPORT void Leviathan::GlobalCEFHandler::RegisterJSAsync(GUI::LeviathanJavaScriptAsync* ptr)
{
    std::unique_lock<std::recursive_mutex> guard(JSCustomMutex);

    JSAsynToNotify.push_back(ptr);
}

DLLEXPORT void Leviathan::GlobalCEFHandler::UnRegisterJSAsync(
    GUI::LeviathanJavaScriptAsync* ptr)
{
    std::unique_lock<std::recursive_mutex> guard(JSCustomMutex);

    for(size_t i = 0; i < JSAsynToNotify.size(); i++) {

        if(JSAsynToNotify[i] == ptr) {

            JSAsynToNotify.erase(JSAsynToNotify.begin() + i);
            return;
        }
    }
}

std::recursive_mutex Leviathan::GlobalCEFHandler::JSCustomMutex;

std::vector<GUI::LeviathanJavaScriptAsync*> Leviathan::GlobalCEFHandler::JSAsynToNotify;

std::vector<std::shared_ptr<GUI::JSAsyncCustom>> Leviathan::GlobalCEFHandler::CustomJSHandlers;

CEFApplicationKeeper* Leviathan::GlobalCEFHandler::AccessToThese = NULL;

bool Leviathan::GlobalCEFHandler::CEFInitialized = false;

// ------------------------------------ //
DLLEXPORT void GlobalCEFHandler::RegisterCustomExtension(
    std::shared_ptr<GUI::CustomExtension> extension)
{
    CustomExtensions.push_back(extension);
    AccessToThese->CEFApp->RegisterCustomExtension(extension);
}

DLLEXPORT bool GlobalCEFHandler::HandleCustomExtensionProcessMessage(
    CefRefPtr<CefBrowser> browser, CefProcessId source_process,
    CefRefPtr<CefProcessMessage> message)
{
    // Pass to the extensions until it is handled //
    for(const auto& ext : CustomExtensions) {

        if(ext->MessageHandler) {

            if(ext->MessageHandler->OnProcessMessageReceived(browser, source_process, message))
                return true;
        }
    }

    return false;
}

std::vector<std::shared_ptr<GUI::CustomExtension>> GlobalCEFHandler::CustomExtensions;

// ------------------ CEFSandboxInfoKeeper ------------------ //
DLLEXPORT Leviathan::CEFApplicationKeeper::CEFApplicationKeeper() {}

DLLEXPORT Leviathan::CEFApplicationKeeper::~CEFApplicationKeeper() {}
// ------------------------------------ //
DLLEXPORT CefRefPtr<GUI::CefApplication> Leviathan::CEFApplicationKeeper::GetCEFApp() const
{
    return CEFApp;
}

max_stars_repo_name: hhyyrylainen/Leviathan

max_issues_repo_name: hhyyrylainen/Leviathan

max_forks_repo_name: hhyyrylainen/Leviathan


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

#ifndef KAGOME_PRIMITIVES_BLOCK_HEADER_HPP
#define KAGOME_PRIMITIVES_BLOCK_HEADER_HPP

#include <type_traits>
#include <vector>

#include <boost/multiprecision/cpp_int.hpp>
#include "common/blob.hpp"
#include "primitives/common.hpp"
#include "primitives/compact_integer.hpp"
#include "primitives/digest.hpp"

namespace kagome::primitives {
  /**
   * @struct BlockHeader represents header of a block
   */
  struct BlockHeader {
    BlockHash parent_hash{};       ///< 32-byte Blake2s hash of parent header
    BlockNumber number = 0u;       ///< index of current block in the chain
    common::Hash256 state_root{};  ///< root of the Merkle tree
    common::Hash256 extrinsics_root{};  ///< field for validation integrity
    Digest digest{};                    ///< chain-specific auxiliary data

    bool operator==(const BlockHeader &rhs) const {
      return std::tie(parent_hash, number, state_root, extrinsics_root, digest)
             == std::tie(rhs.parent_hash,
                         rhs.number,
                         rhs.state_root,
                         rhs.extrinsics_root,
                         rhs.digest);
    }

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

  /**
   * @brief outputs object of type BlockHeader to stream
   * @tparam Stream output stream type
   * @param s stream reference
   * @param v value to output
   * @return reference to stream
   */
  template <class Stream,
            typename = std::enable_if_t<Stream::is_encoder_stream>>
  Stream &operator<<(Stream &s, const BlockHeader &bh) {
    return s << bh.parent_hash << CompactInteger(bh.number) << bh.state_root
             << bh.extrinsics_root << bh.digest;
  }

  /**
   * @brief decodes object of type BlockHeader from stream
   * @tparam Stream input stream type
   * @param s stream reference
   * @param v value to output
   * @return reference to stream
   */
  template <class Stream,
            typename = std::enable_if_t<Stream::is_decoder_stream>>
  Stream &operator>>(Stream &s, BlockHeader &bh) {
    CompactInteger number_compact;
    s >> bh.parent_hash >> number_compact >> bh.state_root >> bh.extrinsics_root
        >> bh.digest;
    bh.number = number_compact.convert_to<BlockNumber>();
    return s;
  }
}  // namespace kagome::primitives

#endif  // KAGOME_PRIMITIVES_BLOCK_HEADER_HPP

max_stars_repo_name: FlorianFranzen/kagome

max_issues_repo_name: FlorianFranzen/kagome

max_forks_repo_name: FlorianFranzen/kagome


text:
// Copyright (c) 2016 Klemens D. Morgenstern
//
// 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 BOOST_PROCESS_EXTENSIONS_HPP_
#define BOOST_PROCESS_EXTENSIONS_HPP_

#include <boost/process/detail/handler.hpp>
#include <boost/process/detail/used_handles.hpp>

#if defined(BOOST_WINDOWS_API)
#include <boost/process/detail/windows/executor.hpp>
#include <boost/process/detail/windows/async_handler.hpp>
#include <boost/process/detail/windows/asio_fwd.hpp>
#else
#include <boost/process/detail/posix/executor.hpp>
#include <boost/process/detail/posix/async_handler.hpp>
#include <boost/process/detail/posix/asio_fwd.hpp>
#endif

/** \file boost/process/extend.hpp
 *
 * This header which provides the types and functions provided for custom extensions.
 *
 * \xmlonly
   Please refer to the <link linkend="boost_process.extend">tutorial</link> for more details.
   \endxmlonly
 */

namespace boost {
namespace process {
namespace detail {
template<typename Tuple>
inline asio::io_context& get_io_context(const Tuple & tup);
}

///Namespace for extensions \attention This is experimental.
namespace extend {

#if defined(BOOST_WINDOWS_API)

template<typename Char, typename Sequence>
using windows_executor = ::boost::process::detail::windows::executor<Char, Sequence>;
template<typename Sequence>
struct posix_executor;

#elif defined(BOOST_POSIX_API)

template<typename Sequence>
using posix_executor = ::boost::process::detail::posix::executor<Sequence>;
template<typename Char, typename Sequence>
struct windows_executor;

#endif

using ::boost::process::detail::handler;
using ::boost::process::detail::api::require_io_context;
using ::boost::process::detail::api::async_handler;
using ::boost::process::detail::get_io_context;
using ::boost::process::detail::get_last_error;
using ::boost::process::detail::throw_last_error;
using ::boost::process::detail::uses_handles;
using ::boost::process::detail::foreach_used_handle;
using ::boost::process::detail::get_used_handles;

///This handler is invoked before the process in launched, to setup parameters. The required signature is `void(Exec &)`, where `Exec` is a template parameter.
constexpr boost::process::detail::make_handler_t<boost::process::detail::on_setup_>   on_setup;
///This handler is invoked if an error occured. The required signature is `void(auto & exec, const std::error_code&)`, where `Exec` is a template parameter.
constexpr boost::process::detail::make_handler_t<boost::process::detail::on_error_>   on_error;
///This handler is invoked if launching the process has succeeded. The required signature is `void(auto & exec)`, where `Exec` is a template parameter.
constexpr boost::process::detail::make_handler_t<boost::process::detail::on_success_> on_success;

#if defined(BOOST_POSIX_API) || defined(BOOST_PROCESS_DOXYGEN)
///This handler is invoked if the fork failed. The required signature is `void(auto & exec)`, where `Exec` is a template parameter. \note Only available on posix.
constexpr ::boost::process::detail::make_handler_t<::boost::process::detail::posix::on_fork_error_  >   on_fork_error;
///This handler is invoked if the fork succeeded. The required signature is `void(Exec &)`, where `Exec` is a template parameter. \note Only available on posix.
constexpr ::boost::process::detail::make_handler_t<::boost::process::detail::posix::on_exec_setup_  >   on_exec_setup;
///This handler is invoked if the exec call errored. The required signature is `void(auto & exec)`, where `Exec` is a template parameter. \note Only available on posix.
constexpr ::boost::process::detail::make_handler_t<::boost::process::detail::posix::on_exec_error_  >   on_exec_error;
#endif

#if defined(BOOST_PROCESS_DOXYGEN)
///Helper function to get the last error code system-independent
inline std::error_code get_last_error();

///Helper function to get and throw the last system error.
/// \throws boost::process::process_error
/// \param msg A message to add to the error code.
inline void throw_last_error(const std::string & msg);
///\overload void throw_last_error(const std::string & msg)
inline void throw_last_error();

/** This function gets the io_context from the initializer sequence.
 *
 * \attention Yields a compile-time error if no `io_context` is provided.
 * \param seq The Sequence of the initializer.
 */
template<typename Sequence>
inline asio::io_context& get_io_context(const Sequence & seq);

/** This class is the base for every initializer, to be used for extensions.
 *
 *  The usage is done through compile-time polymorphism, so that the required
 *  functions can be overloaded.
 *
 * \note None of the function need to be `const`.
 *
 */
struct handler
{
    ///This function is invoked before the process launch. \note It is not required to be const.
    template <class Executor>
    void on_setup(Executor&) const {}

    /** This function is invoked if an error occured while trying to launch the process.
     * \note It is not required to be const.
     */
    template <class Executor>
    void on_error(Executor&, const std::error_code &) const {}

    /** This function is invoked if the process was successfully launched.
     * \note It is not required to be const.
     */
    template <class Executor>
    void on_success(Executor&) const {}

    /**This function is invoked if an error occured during the call of `fork`.
     * \note This function will only be called on posix.
     */
    template<typename Executor>
    void on_fork_error  (Executor &, const std::error_code&) const {}

    /**This function is invoked if the call of `fork` was successful, before
     * calling `execve`.
     * \note This function will only be called on posix.
     * \attention It will be invoked from the new process.
     */
    template<typename Executor>
    void on_exec_setup  (Executor &) const {}

    /**This function is invoked if the call of `execve` failed.
     * \note This function will only be called on posix.
     * \attention It will be invoked from the new process.
     */
    template<typename Executor>
    void on_exec_error  (Executor &, const std::error_code&) const {}

};

/** Inheriting the class will tell the launching process that an `io_context` is
 * needed. This should always be used when \ref get_io_context is used.
 *
 */
struct require_io_context {};
/** Inheriting this class will tell the launching function, that an event handler
 * shall be invoked when the process exits. This automatically does also inherit
 * \ref require_io_context.
 *
 * You must add the following function to your implementation:
 *
 \code{.cpp}
template<typename Executor>
std::function<void(int, const std::error_code&)> on_exit_handler(Executor & exec)
{
    auto handler_ = this->handler;
    return [handler_](int exit_code, const std::error_code & ec)
           {
                handler_(static_cast<int>(exit_code), ec);
           };

}
 \endcode

 The callback will be obtained by calling this function on setup and it will be
 invoked when the process exits.

 *
 * \warning Cannot be used with \ref boost::process::spawn
 */
struct async_handler : handler, require_io_context
{

};

///The posix executor type.
/** This type represents the posix executor and can be used for overloading in a custom handler.
 * \note It is an alias for the implementation on posix, and a forward-declaration on windows.
 *
 * \tparam Sequence The used initializer-sequence, it is fulfills the boost.fusion [sequence](http://www.boost.org/doc/libs/master/libs/fusion/doc/html/fusion/sequence.html) concept.

\xmlonly
As information for extension development, here is the structure of the process launching (in pseudo-code and uml)
<xi:include href="posix_pseudocode.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/>

<mediaobject>
<caption>
<para>The sequence if when no error occurs.</para>
</caption>
<imageobject>
<imagedata fileref="boost_process/posix_success.svg"/>
</imageobject>
</mediaobject>

<mediaobject>
<caption>
<para>The sequence if the execution fails.</para>
</caption>
<imageobject>
<imagedata fileref="boost_process/posix_exec_err.svg"/>
</imageobject>
</mediaobject>

<mediaobject>
<caption>
<para>The sequence if the fork fails.</para>
</caption>
<imageobject>
<imagedata fileref="boost_process/posix_fork_err.svg"/>
</imageobject>
</mediaobject>

\endxmlonly

\note Error handling if execve fails is done through a pipe, unless \ref ignore_error is used.

 */
template<typename Sequence>
struct posix_executor
{
    ///A reference to the actual initializer-sequence
     Sequence & seq;
    ///A pointer to the name of the executable.
     const char * exe      = nullptr;
     ///A pointer to the argument-vector.
     char *const* cmd_line = nullptr;
     ///A pointer to the environment variables, as default it is set to [environ](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html)
     char **env      = ::environ;
     ///The pid of the process - it will be -1 before invoking [fork](http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html), and after forking either 0 for the new process or a positive value if in the current process. */
     pid_t pid = -1;
     ///This shared-pointer holds the exit code. It's done this way, so it can be shared between an `asio::io_context` and \ref child.
     std::shared_ptr<std::atomic<int>> exit_status = std::make_shared<std::atomic<int>>(still_active);

     ///This function returns a const reference to the error state of the executor.
     const std::error_code & error() const;

     ///This function can be used to report an error to the executor. This will be handled according to the configuration of the executor, i.e. it
     /// might throw an exception. \note This is the required way to handle errors in initializers.
     void set_error(const std::error_code &ec, const std::string &msg);
     ///\overload void set_error(const std::error_code &ec, const std::string &msg);
     void set_error(const std::error_code &ec, const char* msg);
};

///The windows executor type.
/** This type represents the posix executor and can be used for overloading in a custom handler.
 *
 * \note It is an alias for the implementation on posix, and a forward-declaration on windows.
 * \tparam Sequence The used initializer-sequence, it is fulfills the boost.fusion [sequence](http://www.boost.org/doc/libs/master/libs/fusion/doc/html/fusion/sequence.html) concept.
 * \tparam Char The used char-type, either `char` or `wchar_t`.
 *

\xmlonly
As information for extension development, here is the structure of the process launching (in pseudo-code and uml)<xi:include href="windows_pseudocode.xml" xmlns:xi="http://www.w3.org/2001/XInclude"/>
<mediaobject>
<caption>
<para>The sequence for windows process creation.</para>
</caption>
<imageobject>
<imagedata fileref="boost_process/windows_exec.svg"/>
</imageobject>
</mediaobject>
\endxmlonly

 */

template<typename Char, typename Sequence>
struct windows_executor
{
    ///A reference to the actual initializer-sequence
     Sequence & seq;

     ///A pointer to the name of the executable. It's null by default.
     const Char * exe      = nullptr;
     ///A pointer to the argument-vector. Must be set by some initializer.
     char  Char* cmd_line = nullptr;
     ///A pointer to the environment variables. It's null by default.
     char  Char* env      = nullptr;
     ///A pointer to the working directory. It's null by default.
     const Char * work_dir = nullptr;

     ///A pointer to the process-attributes of type [SECURITY_ATTRIBUTES](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379560.aspx). It's null by default.
     ::boost::detail::winapi::LPSECURITY_ATTRIBUTES_ proc_attrs   = nullptr;
     ///A pointer to the thread-attributes of type [SECURITY_ATTRIBUTES](https://msdn.microsoft.com/en-us/library/windows/desktop/aa379560.aspx). It' null by default.
     ::boost::detail::winapi::LPSECURITY_ATTRIBUTES_ thread_attrs = nullptr;
     ///A logical bool value setting whether handles shall be inherited or not.
     ::boost::detail::winapi::BOOL_ inherit_handles = false;

     ///The element holding the process-information after process creation. The type is [PROCESS_INFORMATION](https://msdn.microsoft.com/en-us/library/windows/desktop/ms684873.aspx)
     ::boost::detail::winapi::PROCESS_INFORMATION_ proc_info{nullptr, nullptr, 0,0};

     ///This shared-pointer holds the exit code. It's done this way, so it can be shared between an `asio::io_context` and \ref child.
     std::shared_ptr<std::atomic<int>> exit_status = std::make_shared<std::atomic<int>>(still_active);

     ///This function returns a const reference to the error state of the executor.
     const std::error_code & error() const;

     ///This function can be used to report an error to the executor. This will be handled according to the configuration of the executor, i.e. it
     /// might throw an exception. \note This is the required way to handle errors in initializers.
     void set_error(const std::error_code &ec, const std::string &msg);
     ///\overload void set_error(const std::error_code &ec, const std::string &msg);
     void set_error(const std::error_code &ec, const char* msg);

     ///The creation flags of the process
    ::boost::detail::winapi::DWORD_ creation_flags;
    ///The type of the [startup-info](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331.aspx), depending on the char-type.
    typedef typename detail::startup_info<Char>::type    startup_info_t;
    ///The type of the [extended startup-info](https://msdn.microsoft.com/de-de/library/windows/desktop/ms686329.aspx), depending the char-type; only defined with winapi-version equal or higher than 6.
    typedef typename detail::startup_info_ex<Char>::type startup_info_ex_t;
    ///This function switches the information, so that the extended structure is used. \note It's only defined with winapi-version equal or higher than 6.
    void set_startup_info_ex();
    ///This element is an instance or a reference (if \ref startup_info_ex exists) to the [startup-info](https://msdn.microsoft.com/en-us/library/windows/desktop/ms686331.aspx) for the process.
    startup_info_t startup_info;
    ///This element is the instance of the  [extended startup-info](https://msdn.microsoft.com/de-de/library/windows/desktop/ms686329.aspx). It is only available with a winapi-version equal or highter than 6.
    startup_info_ex_t  startup_info_ex;
};

#endif

}
}
}

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


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

#ifndef __LZR_U901_RANGE_TO_POINT_CONVERTER_HPP__
#define __LZR_U901_RANGE_TO_POINT_CONVERTER_HPP__

#include <vector>

#include <Eigen/Core>
#include <Eigen/Geometry>

#include "scan.hpp"

namespace lzr_u901 {

class range_to_point_converter
{
	typedef Eigen::Vector3f point;
	typedef std::vector<point, Eigen::aligned_allocator<point> > directions;

public:
	range_to_point_converter()
	{
		populate_directions_table();
	}

	template<typename RangesContainer, typename PointHandler>
	void convert(scan::plane_t plane, const RangesContainer &ranges, PointHandler h) const
	{
		typename RangesContainer::const_iterator r = ranges.begin();
		directions::const_iterator d = direction_table[plane].begin();

		for (; r != ranges.end() && d != direction_table[plane].end(); ++r, ++d)
		{
			float r_meters = scan::range_to_meters(*r);
			point p = *d * r_meters;
			h(p.x(), p.y(), p.z(), r_meters);
		}
	}

private:
	static scan::rad plane_angle_increment()
	{
		return -2. * M_PI/180.;
	}

	void populate_directions_table()
	{
		directions not_rotated;
		not_rotated.reserve(scan::NUM_RANGES_PER_PLANE);
		float t = scan::angle_min();
		for (unsigned k = 0; k < scan::NUM_RANGES_PER_PLANE; ++k, t += scan::angle_increment())
		{
			not_rotated.push_back(point(cos(t), sin(t), 0));
		}

		for (unsigned p = scan::PLANE_0; p < scan::NUM_PLANES; ++p)
		{
			directions &tab = direction_table[p];
			tab.reserve(scan::NUM_RANGES_PER_PLANE);

			Eigen::AngleAxis<float> rot(p * plane_angle_increment(), point(0., 1., 0.));

			for (directions::const_iterator i = not_rotated.begin();
				 i != not_rotated.end(); ++i)
				tab.push_back(rot * *i);
		}
	}

	directions direction_table[scan::NUM_PLANES];
};

} // namespace lzr_u901

#endif // __LZR_U901_RANGE_TO_POINT_CONVERTER_HPP__

max_stars_repo_name: UniOL-AMT/uol-robotino-ros-groovy

max_issues_repo_name: UniOL-AMT/uol-robotino-ros-groovy

max_forks_repo_name: UniOL-AMT/uol-robotino-ros-groovy


text:
/**
 * Test for the KalmanFilter class with 1D projectile motion.
 *
 * @author: Hayk Martirosyan
 * @date: 2014.11.15
 */
#include <ros/ros.h>
#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include "kalman.hpp"

#include <people_msgs/PositionMeasurement.h>
#include <visualization_msgs/Marker.h>

template <typename T> std::string tostr(const T& t)
{
    std::ostringstream os; os<<t; return os.str();
}

static std::string fixed_frame = "odom";

class KalmanTracker{
private:
    ros::Rate r;
    ros::Subscriber person_pos_sub;
    ros::Publisher markers_pub,text_pub,estimate_pos_pub;
    ros::NodeHandle nh1;
    ros::Time start,now;
    Eigen::VectorXd x,y;
    Eigen::MatrixXd A; // System dynamics matrix
    Eigen::MatrixXd C; // Output matrix
    Eigen::MatrixXd Q; // Process noise covariance
    Eigen::MatrixXd R; // Measurement noise covariance
    Eigen::MatrixXd P; // Estimate error covariance
    KalmanFilter estimate_X,estimate_Y;
    int n; // Number of states
    int m; // Number of measurements
    int init_f,update_f;
    double dt; // Time step
    double t; // Time
public:
    KalmanTracker(ros::NodeHandle nh):
    nh1(nh),r(10),n(3),m(1),dt(1.0/10),init_f(0)
    {
        x = Eigen::VectorXd(n);
        y = Eigen::VectorXd(n);
        A = Eigen::MatrixXd(n,n);
        C = Eigen::MatrixXd(m,n);
        Q = Eigen::MatrixXd(n,n);
        R = Eigen::MatrixXd(m,m);
        P = Eigen::MatrixXd(n,n);
        // Discrete LTI projectile motion, measuring position only
        A << 1, dt, 1/2*dt*dt, 0, 1, dt, 0, 0, 1;
        C << 1, 0, 0;
        // Reasonable covariance matrices
        Q << .05, .05, .0, .05, .05, .0, .0, .0, .0;
        R << 5;
        P << .1, .1, .1, .1, 10000, 10, .1, 10, 100;
        estimate_X=KalmanFilter(dt,A, C, Q, R, P);
        estimate_Y=KalmanFilter(dt,A, C, Q, R, P);
        estimate_X.init(0,x);
        estimate_Y.init(0,y);
        //start = now = ros::Time::now();
        person_pos_sub = nh1.subscribe("filter_measurement",1,&KalmanTracker::msgCallback_PeopleTracker, this);
        markers_pub = nh1.advertise<visualization_msgs::Marker>("filter_marker", 20);//Output of KF
        estimate_pos_pub = nh1.advertise<people_msgs::PositionMeasurement>("estimate_pos", 20);
        //text_pub = nh1.advertise<visualization_msgs::Marker>("tracking_text", 20);
        //estimate_pos_pub = nh1.advertise<geometry_msgs::PoseStamped>("human_pose", 20);

        std::cout << "A: \n" << A << std::endl;
        std::cout << "C: \n" << C << std::endl;
        std::cout << "Q: \n" << Q << std::endl;
        std::cout << "R: \n" << R << std::endl;
        std::cout << "P: \n" << P << std::endl;
  }

    void msgCallback_PeopleTracker(const people_msgs::PositionMeasurement::ConstPtr& msg )
    {
        if(msg->initialization == 1){
        // Best guess of initial states
            std::cout<<"---Initialization---"<<std::endl;
            //start = now = ros::Time::now();
            x <<msg->pos.x, 0.0, 0.0;
            estimate_X.init(t,x);
            y << msg->pos.y, 0.0, 0.0;
            estimate_Y.init(t,y);
            init_f=1;
        }
        else if(init_f==1){
            //now = ros::Time::now();
            std::cout<<"Update position"<<std::endl;
            Eigen::VectorXd z(m);
            z <<msg->pos.x;
            estimate_X.update(z);
            z <<msg->pos.y;
            estimate_Y.update(z);
        }

        //std::cout <<"x_hat=" << estimate_X.state().transpose()<<std::endl;
        //std::cout <<"y_hat=" << estimate_Y.state().transpose()<<std::endl;

        visualization_msgs::Marker m;
        m.header.stamp = ros::Time::now();
        m.header.frame_id = fixed_frame;
        m.type = m.SPHERE;
        m.scale.x = .6;
        m.scale.y = .6;
        m.scale.z = .6;
        m.color.a = 0.2;
        m.color.g = 0.5;
        m.pose.position.x = estimate_X.state()[0];
        m.pose.position.y = estimate_Y.state()[0];

        people_msgs::PositionMeasurement estimate_pos;
        estimate_pos.header.stamp = ros::Time::now();
        estimate_pos.header.frame_id = fixed_frame;
        estimate_pos.name = "tracking";
        estimate_pos.pos.x = estimate_X.state()[0];
        estimate_pos.pos.y = estimate_Y.state()[0];
        estimate_pos.pos.z = 0;
        //std::cout<<estimate_X.cov()<<std::endl;
        estimate_pos.covariance[0] = (estimate_X.cov()(0,0)+estimate_Y.cov()(0,0))/2;
        estimate_pos.covariance[1] = 0.0;
        estimate_pos.covariance[2] = 0.0;
        estimate_pos.covariance[3] = 0.0;
        estimate_pos.covariance[4] = (estimate_X.cov()(1,1)+estimate_Y.cov()(1,1))/2;
        estimate_pos.covariance[5] = 0.0;
        estimate_pos.covariance[6] = 0.0;
        estimate_pos.covariance[7] = 0.0;
        estimate_pos.covariance[8] = (estimate_X.cov()(2,2)+estimate_Y.cov()(2,2))/2;

        if(init_f==1){
            markers_pub.publish(m);
            estimate_pos_pub.publish(estimate_pos);
        }
    //r.sleep();
    }
};

// 購読者ノードのメイン関数
int main(int argc, char **argv)
{
    // ノード名の初期化
    ros::init(argc, argv, "person_tracking_filter_kalman");
    // ROSシステムとの通信のためのノードのハンドルを宣言
    ros::NodeHandle nh;
    KalmanTracker kt(nh);
    ros::spin();
    return 0;
}


text:
#include <algorithm>

#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

#include "Indices.h"

template <typename Archive>
void Indices::serialize(Archive & ar, unsigned int const version) {
  if (version > 0) {
  } else {
  }
  ar & indices;
}

template void Indices::serialize<boost::archive::text_oarchive>(boost::archive::text_oarchive&, unsigned int const);
template void Indices::serialize<boost::archive::text_iarchive>(boost::archive::text_iarchive&, unsigned int const);

bool Indices::SortIndexVector(std::vector<Index> & vec) {
  Indices ind (vec);
  bool ret = ind.Sort();
  vec = ind.get_vector();
  return ret;
}

Indices::Indices(std::initializer_list<Index> list) : indices(list) { }

Indices::Indices(std::initializer_list<char> list) {
  indices.resize(list.size());
  std::transform(list.begin(), list.end(), indices.begin(),
    [](auto c) {
      return static_cast<Index>(c - 97);
    });
}

Indices::Indices(std::vector<Index> vec) : indices(vec) { }

Indices::Indices(std::set<Index> set)    : indices(set.begin(), set.end()) { }

Indices::Indices(Indices const & other) : indices(other.indices) { }

Indices::Indices(Indices const & other, std::map<Index, Index> const & exchange_map) : indices(std::vector<Index>()){
  for (Index index : other.indices) {
    indices.push_back(exchange_map.at(index));
  }
}

std::vector<Index> Indices::get_vector() const {
  return indices;
}

void Indices::SortAndMakeUnique() {
  std::sort(indices.begin(), indices.end());
  indices.resize(std::distance(indices.begin(), std::unique(indices.begin(), indices.end())));
}

bool Indices::Sort() {
  if (indices.empty()) {
    return true;
  }
  unsigned int swap_counter = 0;
  bool swapped;
  do {
    swapped = false;
    for (size_t counter = 0; counter < indices.size() - 1; ++counter) {
      if (indices[counter] > indices[counter + 1]) {
        std::swap(indices[counter], indices[counter + 1]);
        swapped = true;
        swap_counter += 1;
      }
    }
  } while (swapped);
  return (swap_counter % 2 == 0) ? true : false;
}

size_t Indices::size() const { return indices.size(); }
Index Indices::at(size_t pos) const { return indices.at(pos); }

std::string const Indices::ToString() const {
  std::string return_string("");
  return_string += "{ ";
  for (auto index : indices) {
    return_string += alphabet[static_cast<int>(index)];
    return_string += " ";
  }
  return_string += "}";

  return return_string;
}

Indices Indices::Permutation(std::vector<size_t> const & permutation) const {
  if (indices.empty()) {
    return (Indices());
  }

  Indices indices_new = *this;

  for (size_t counter = 0; counter < indices.size(); ++counter) {
    indices_new.indices[counter] = indices[permutation[counter]];
  }

  return indices_new;
}

Indices Indices::SubIndices(size_t start, size_t len) const {
  Indices indices_ret;
  indices_ret.indices = std::vector<Index>(indices.begin() + start, indices.begin() + start + len);
  return indices_ret;
}

Indices Indices::Overlap(Indices const & other) const {
  Indices ret;

  std::for_each(this->indices.cbegin(), this->indices.cend(),
    [&ret, &other] (auto const & a) mutable {
      if (std::find(other.indices.cbegin(), other.indices.cend(), a) != other.indices.end()) {
        ret.indices.push_back(a);
      }
    });

  ret.SortAndMakeUnique();

  return ret;
}

void Indices::Replace(Index const i_old, Index const i_new) {
  std::replace(indices.begin(), indices.end(), i_old, i_new);
}

bool Indices::operator== (Indices const & other) const { return indices == other.indices; }
bool Indices::operator!= (Indices const & other) const { return !(*this == other); }
bool Indices::operator< (Indices const & other) const { return indices < other.indices; }

max_stars_repo_name: nilsalex/tensor-algebra

max_issues_repo_name: nilsalex/tensor-algebra

max_forks_repo_name: nilsalex/tensor-algebra


text:
#ifndef CSVFUNCTION_H
#define CSVFUNCTION_H

#include <iostream>
#include <fstream>
#include <sstream>
#include "IntrogressionSimulations.h"
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/filesystem.hpp>
#include <stdio.h>
#include <iomanip>
#include <chrono>
#include "random.h"

#ifdef _OPENMP
    #include <omp.h>
#endif

enum nameofstream {Parametersoff, Dataoff, AlleleFrequencyoff_mean, AlleleFrequencyoff_var};

void CSV_WriteOutput(std::ofstream arrayofstream[4], const Parameters &pars, SimData &SimulationData){

    using namespace boost::accumulators;
    // Parameters output
    for (int i = 0; i < 2; ++i)
    {
        arrayofstream[Parametersoff] << "NINIT" << i << arrayofstream[Parametersoff].fill() << pars.NINIT[i] << std::endl;
    }
    arrayofstream[Parametersoff] << "NGEN" << arrayofstream[Parametersoff].fill() << pars.NGEN << std::endl;
    arrayofstream[Parametersoff] << "NLOCI" << arrayofstream[Parametersoff].fill() << pars.NLOCI << std::endl;
    arrayofstream[Parametersoff] << "NREP" << arrayofstream[Parametersoff].fill() << pars.NREP << std::endl;
    arrayofstream[Parametersoff] << "MUTATIONRATE" << arrayofstream[Parametersoff].fill() << pars.MUTATIONRATE << std::endl;
    arrayofstream[Parametersoff] << "RECOMBINATIONRATE" << arrayofstream[Parametersoff].fill() << pars.RECOMBINATIONRATE << std::endl;
    arrayofstream[Parametersoff] << "CARRYINGCAPACITY" << arrayofstream[Parametersoff].fill() << pars.K << std::endl;
    arrayofstream[Parametersoff] << "BIRTHRATE" << arrayofstream[Parametersoff].fill() << pars.BIRTHRATE << std::endl;
    arrayofstream[Parametersoff] << "DEATHRATEA" << arrayofstream[Parametersoff].fill() << pars.DEATHRATEA << std::endl;
    arrayofstream[Parametersoff] << "DEATHRATEa" << arrayofstream[Parametersoff].fill() << pars.DEATHRATEa << std::endl;
    arrayofstream[Parametersoff] << std::endl;

    //Simulation output
    arrayofstream[Dataoff]
    << "Generation" << arrayofstream[Dataoff].fill()
    << "AVG_popsize" << arrayofstream[Dataoff].fill()
    << "AVG_major0" << arrayofstream[Dataoff].fill()
    << "AVG_major1" << arrayofstream[Dataoff].fill()
    << "AVG_introgressed0" << arrayofstream[Dataoff].fill()
    << "AVG_introgressed1" << arrayofstream[Dataoff].fill()
    << "VAR_popsize" << arrayofstream[Dataoff].fill()
    << "VAR_major0" << arrayofstream[Dataoff].fill()
    << "VAR_major1" << arrayofstream[Dataoff].fill()
    << "VAR_introgressed0" << arrayofstream[Dataoff].fill()
    << "VAR_introgressed1" << std::endl;

    for(int i = 0; i < pars.NGEN; ++i){
        accumulator_set<int, stats<tag::mean, tag::variance > > popsize;
        accumulator_set<int, stats<tag::mean, tag::variance > > major0;
        accumulator_set<int, stats<tag::mean, tag::variance > > major1;
        accumulator_set<double, stats<tag::mean, tag::variance > > introgressed0;
        accumulator_set<double, stats<tag::mean, tag::variance > > introgressed1;

        ///FINISH ANALYSIS OF THE GENOTYPE RESCUE PER LOCUS PART.
        for(int j = 0; j < pars.NREP; ++j){
            popsize(SimulationData.DataSet[j]->popsize[i]);
            major0(SimulationData.DataSet[j]->major0[i]);
            major1(SimulationData.DataSet[j]->major1[i]);
            introgressed0(SimulationData.DataSet[j]->introgressed0[i]);
            introgressed1(SimulationData.DataSet[j]->introgressed1[i]);
        }

        arrayofstream[Dataoff]
        << i << arrayofstream[Dataoff].fill()
        << mean(popsize) << arrayofstream[Dataoff].fill()
        << (double)mean(major0) << arrayofstream[Dataoff].fill()
        << (double)mean(major1) << arrayofstream[Dataoff].fill()
        << mean(introgressed0) << arrayofstream[Dataoff].fill()
        << mean(introgressed1) << arrayofstream[Dataoff].fill()

        << variance(popsize) << arrayofstream[Dataoff].fill()
        << (double)variance(major0) << arrayofstream[Dataoff].fill()
        << (double)variance(major1) << arrayofstream[Dataoff].fill()
        << variance(introgressed0)<< arrayofstream[Dataoff].fill()
        << variance(introgressed1) << arrayofstream[Dataoff].fill() << std::endl;
    };

    for(int i = 0; i < pars.NGEN; ++i){
        arrayofstream[AlleleFrequencyoff_mean] << i << arrayofstream[AlleleFrequencyoff_mean].fill();
        arrayofstream[AlleleFrequencyoff_var] << i << arrayofstream[AlleleFrequencyoff_var].fill();
        for(int l = 0; l < pars.NLOCI; ++l)
        {
            accumulator_set<double, stats<tag::mean, tag::variance > > locus;
            for(int r = 0; r < pars.NREP; ++r)
            {
                locus((double)SimulationData.DataSet[r]->allele0[i][l] / ((double)SimulationData.DataSet[r]->popsize[i]));
            }
            arrayofstream[AlleleFrequencyoff_mean] << mean(locus)  << arrayofstream[AlleleFrequencyoff_mean].fill();
            arrayofstream[AlleleFrequencyoff_var] << variance(locus) << arrayofstream[AlleleFrequencyoff_var].fill();
        }
        arrayofstream[AlleleFrequencyoff_mean] << std::endl;
        arrayofstream[AlleleFrequencyoff_var] << std::endl;
    }

    // Cleanup
    for(int i = 0; i < pars.NREP; ++i){
        delete SimulationData.DataSet[i];
    }
}

std::string CreateOutputStreams(std::ofstream arrayofstream[4]){

    std::string CurrentWorkingDirectory = boost::filesystem::current_path().c_str();
    CurrentWorkingDirectory.append("/data");

    auto t = std::time(nullptr);
    auto tm = *std::localtime(&t);
    std::ostringstream oss;
    oss << std::put_time(&tm, "%d-%m-%Y-%H-%M-%S");
    std::string str = oss.str();

    std::string MainOutputFolder = CurrentWorkingDirectory;
    MainOutputFolder.append("/");
    MainOutputFolder.append(str);

    boost::filesystem::create_directories(MainOutputFolder.c_str());

    std::string ParameterOutput = MainOutputFolder;
    ParameterOutput.append("/Parameters.csv");

    arrayofstream[Parametersoff].open(ParameterOutput);
    arrayofstream[Parametersoff].fill(',');

    std::string DataOutput = MainOutputFolder;
    DataOutput.append("/Data.csv");

    std::string AlleleFOutput_mean = MainOutputFolder;
    std::string AlleleFOutput_var = MainOutputFolder;

    AlleleFOutput_mean.append("/AlleleF_mean.csv");
    AlleleFOutput_var.append("/AlleleF_var.csv");

    arrayofstream[Dataoff].open(DataOutput);
    arrayofstream[AlleleFrequencyoff_mean].open(AlleleFOutput_mean);
    arrayofstream[AlleleFrequencyoff_var].open(AlleleFOutput_var);
    arrayofstream[Dataoff].fill(',');
    arrayofstream[AlleleFrequencyoff_mean].fill(',');
    arrayofstream[AlleleFrequencyoff_var].fill(',');

    return MainOutputFolder;
}

int main(int argc, char *argv[]){
    // Initialize simulation
    rnd::set_seed();
    const Parameters GlobalPars(argc, argv);

    SimData SimulationData;
    // Run nrep successful simulations
    // auto start = std::chrono::high_resolution_clock::now();
    #ifdef _OPENMP
        printf("Parallel activated : Number of threads=%i\n",omp_get_max_threads());
    #endif

    #pragma omp parallel for schedule(static)
    for(int task = 0; task < GlobalPars.NREP; ++task){
        while(RunSimulation(GlobalPars, SimulationData)==false);
    }
    // auto finish = std::chrono::high_resolution_clock::now();

    // Write outputfiles
    std::ofstream arrayofstream[4];
    CreateOutputStreams(arrayofstream);
	CSV_WriteOutput(arrayofstream, GlobalPars, SimulationData);

    /*
    // Cleanup
    for(int i = 0; i < GlobalPars.NREP; ++i){
        delete SimulationData.DataSet[i];
    }
    */

    /*
    std::chrono::duration<double> elapsed = finish-start;
    std::cout << "Elapsed time: " << elapsed.count() << " s" << std::endl;
    */
    return 0;
}

#endif

max_stars_repo_name: freekdh/GeneticRescue

max_issues_repo_name: freekdh/GeneticRescue

max_forks_repo_name: freekdh/Introgression


text:
#include "gtest/gtest.h"

#include <boost/bimap.hpp>

#include "opencv2/opencv.hpp"
#include "utils/utils.hpp"
#include <unordered_map>

using namespace cv;
using namespace std;

Mat formatTransformationMat2(const Mat transformation_matrix)
{
    cv::Mat m = cv::Mat::ones(2, 3, CV_64F);
    m.at<double>(0, 0) = transformation_matrix.at<double>(0, 0);
    m.at<double>(0, 1) = transformation_matrix.at<double>(0, 1);
    m.at<double>(0, 2) = transformation_matrix.at<double>(0, 2);
    m.at<double>(1, 0) = transformation_matrix.at<double>(1, 0);
    m.at<double>(1, 1) = transformation_matrix.at<double>(1, 1);
    m.at<double>(1, 2) = transformation_matrix.at<double>(1, 2);
    return m;
}

void runTheTest()
{

//    //load the image
//    //apply a big transformation to it, resize the image if you have to
//    //create a getKeyPointsFunction you can call from the c++ side
//
//    double rotation = 0;
//    double scale = 1;
//    Mat inputImage = cv::imread("./input/lennaWithGreenDots.jpg");
//    for (int j = 0; j < 4; j++){
//        for (int i = 0; i<360; i+= 1){
//            Mat transformationMartix;
//            Size newImageSize;
//            tie(transformationMartix, newImageSize) = calcTransformationMatrix(inputImage.size(), rotation+i, scale*(j+1));
//            cout << "Size: " << newImageSize << endl;
//            cout << "The output mat: " << endl;
//            cout << Mat(transformationMartix) << endl;
//
//            Mat outputImage(newImageSize.height, newImageSize.width, CV_8UC3, Scalar(0,0,0));
//            warpAffine(inputImage, outputImage, formatTransformationMat2(transformationMartix), outputImage.size());
//            imshow("output", outputImage);
//            waitKey(1);
//        }
//    }
//    waitKey();
////    //Then apply it
////    //Then get the keypoints for both images
////    //Then calc the transformation matrix and project both keypoints to both...
////    //Then calc all the stats...

}

TEST(accuracyTest, basic) {
//    runTheTest();

}

TEST(utilsTest, getTheKeypointsTest) {
//    Mat inputImage = cv::imread("./input/rick1.jpg");
//    auto keypoints = getKeypoints(inputImage);
//    drawKeypoints(keypoints, inputImage);
//    cv::imshow("here...", inputImage);
//    cv::waitKey();
//    cout << "Number of keypoints: " << keypoints.size() << endl;
}

TEST(utilsTest, fullKeypointTest) {
//    Mat inputImage = cv::imread("./input/rick1.jpg");
//    auto keypointsForImageOne = getKeypoints(inputImage);
//    convertKeypointsVectorToMat
}

TEST(utilsTest, testingTheConvertingOfKeypoints) {
//    Mat inputImage = cv::imread("./input/rick1.jpg");
//    auto keypointsForImageOne = getKeypoints(inputImage);
//    Mat res = convertKeypointsVectorToMat(keypointsForImageOne);
//    //Mat res = cv::Mat::zeros(1,1, 1);
//    cout << "the resultant matrix" << endl;
//    cout << res << endl;
//    applyTransformationMatrixToKeypointVector(keypointsForImageOne, );
}

typedef std::unordered_map<Keypoint, Keypoint> MatchingKeypointMap;

MatchingKeypointMap getMatchingKeypointsTwoWayMap(vector<Keypoint> image1Keypoints, vector<Keypoint> image2Keypoints, cv::Mat transformationMatFromImage1To2)
{
    MatchingKeypointMap result;
    vector<Keypoint> oneToTwo = applyTransformationMatrixToKeypointVector(image1Keypoints, transformationMatFromImage1To2);

    double threshold = 2.0;
    for (auto keypointFromImage2 : image2Keypoints)
    {
        //check the dist
        for (unsigned int i = 0; i < oneToTwo.size(); i++)
        {
            if (getKeypointDistance(keypointFromImage2, oneToTwo[i]) < threshold)
            {
                auto keyPointFromImage1 = image1Keypoints[i];
                result.insert({keyPointFromImage1, keypointFromImage2});
            }
        }
    }

    return result;
}

typedef std::unordered_map<Triangle, Triangle> MatchingTriangleMap;

tuple<vector<Keypoint>, vector<Keypoint>> splitKeypointMap(MatchingKeypointMap map){
    vector<Keypoint> kp1;
    vector<Keypoint> kp2;

    for (auto entry: map)
    {
        kp1.push_back(entry.first);
        kp2.push_back(entry.second);
    }
    return tuple<vector<Keypoint>, vector<Keypoint>>(kp1, kp2);
}

Triangle convertTriangleUsingMap(Triangle triangle, MatchingKeypointMap oneToTwo) {
    vector<Keypoint> result;
    for (auto kp: triangle.toKeypoints())
    {
        result.push_back(oneToTwo[kp]);
    }
    return result;
}

MatchingTriangleMap buildMatchingTriMap(vector<Triangle> tris1, vector<Triangle> tris2, MatchingKeypointMap unorderedMap) {
    MatchingTriangleMap result;
    for (auto tri1: tris1)
    {
        for (auto tri2: tris2)
        {
            Triangle tri1Convert = convertTriangleUsingMap(tri1, unorderedMap);
            if (tri1Convert == tri2)
            {
                result.insert({tri1, tri2});
                break;
            }
        }
    }

    return result;
}

MatchingTriangleMap getMatchingTriangleTwoWayMap(MatchingKeypointMap oneToTwo) {

    vector<Keypoint> image1Kp;
    vector<Keypoint> image2Kp;
    tie(image1Kp, image2Kp) = splitKeypointMap(oneToTwo);

    auto tris1 = buildTrianglesFromKeypoints(image1Kp);
    auto tris2 = buildTrianglesFromKeypoints(image2Kp);

    return buildMatchingTriMap(tris1, tris2, oneToTwo);
}

unsigned long xorshf962(void) {          //period 2^96-1
    unsigned long t;
    x ^= x << 16;
    x ^= x >> 5;
    x ^= x << 1;

    t = x;
    x = y;
    y = z;
    z = t ^ x ^ y;

    return z;
}

void dumpMathcingKeypointTestingInfoToJson(unsigned int count, unsigned int totalCount, unsigned int cout,
                                           MatchingKeypointMap map, unsigned int imagesCount, unsigned int image1Count,
                                           unsigned int image2Count, unsigned int trianglesTotalCount,
                                           unsigned int image2TrianglesTotalCount)
{
    //dump it!!!

}

TEST(utilsTest, testingTheConvertingOfKeypoints2)
{
    double rotation = 45;
    double scale = 2;
    Mat inputImage = cv::imread("./input/lennaWithGreenDots.jpg");
    Mat transformationMartix;
    Size newImageSize;
    tie(transformationMartix, newImageSize) = calcTransformationMatrix(inputImage.size(), rotation, scale);

    Mat outputImage(newImageSize.height, newImageSize.width, CV_8UC3, Scalar(0,0,0));
    warpAffine(inputImage, outputImage, formatTransformationMat2(transformationMartix), outputImage.size());

    auto keypointsImage1 = getKeypoints(inputImage);
    auto keypointsImage2 = getKeypoints(outputImage);

    vector<Keypoint> oneToTwo = applyTransformationMatrixToKeypointVector(keypointsImage1, transformationMartix);
    vector<Keypoint> twoToOne = applyTransformationMatrixToKeypointVector(keypointsImage2, transformationMartix.inv());

    drawKeypoints(keypointsImage1, inputImage);
    drawKeypoints(twoToOne, inputImage, cv::Scalar(0,255,0));
    drawKeypoints(keypointsImage2, outputImage);
    drawKeypoints(oneToTwo, outputImage, cv::Scalar(0,255,0));
    auto tempMap = getMatchingKeypointsTwoWayMap(keypointsImage1, keypointsImage2, transformationMartix);

    cout << "Number of matching keypints:   " << tempMap.size() << endl;
    cout << "Number of keypoints in image1: " << keypointsImage1.size() << " image2: " << keypointsImage2.size() << endl;
    cout << "average:   " << ((keypointsImage1.size() + keypointsImage2.size())/2) << endl;
    cout << "%average:  " << 100.0*(float)(tempMap.size())/(float)((keypointsImage1.size() + keypointsImage2.size())/2) << "%" << endl;

    for (auto entry : tempMap)
    {
        drawSingleKeypoint(entry.first, inputImage, cv::Scalar(255,0,0));
        drawSingleKeypoint(entry.second, outputImage, cv::Scalar(255,0,0));
    }

    cv::imwrite("image1_keypoints.jpg", inputImage);
    cv::imwrite("image2_keypoints.jpg", outputImage);

    MatchingTriangleMap tempTriangleMap = getMatchingTriangleTwoWayMap(tempMap);
    auto allTrisImage1 = buildTrianglesFromKeypoints(keypointsImage1);
    auto allTrisImage2 = buildTrianglesFromKeypoints(keypointsImage2);

    vector<Keypoint> image1Kp;
    vector<Keypoint> image2Kp;
    tie(image1Kp, image2Kp) = splitKeypointMap(tempMap);

    auto tris1 = buildTrianglesFromKeypoints(image1Kp);
    auto tris2 = buildTrianglesFromKeypoints(image2Kp);

    cout << "Number of matching Triangles:   " << tempTriangleMap.size() << endl;
    cout << "Number of Triangles made of matching points in image1: " << tris1.size() << " image2: " << tris2.size() << endl;
    cout << "average:  " << ((tris1.size() + tris2.size())/2) << endl;
    cout << "%average: " << 100.0*(float)(tempTriangleMap.size())/(float)((tris1.size() + tris2.size())/2) << "%" << endl;
    cout << "Number of Triangles in image1: " << allTrisImage1.size() << " image2: " << allTrisImage2.size() << endl;
    cout << "average:  " << ((allTrisImage1.size() + allTrisImage2.size())/2) << endl;
    cout << "%average: " << 100.0*(float)(tempTriangleMap.size())/(float)((allTrisImage1.size() + allTrisImage2.size())/2) << "%" << endl;

    for (auto entry: tempTriangleMap)
    {
        bool setColour = true;
        int r = (int) xorshf962();
        int g = (int) xorshf962();
        int b = (int) xorshf962();
        cv::Scalar colour(b,g,r);
        drawSingleTriangleOntoImage(entry.first, inputImage, setColour, colour);
        drawSingleTriangleOntoImage(entry.second, outputImage, setColour, colour);
    }

    //keypoints
    unsigned int matchingKeypointsCount = tempMap.size();
    unsigned int image1KeypointsTotalCount = keypointsImage1.size();
    unsigned int image2KeypointsTotalCout = keypointsImage2.size();
    auto matchingKeypoints = tempMap;

    //triangles
    unsigned int matchingTrianglesInBothImagesCount = tempTriangleMap.size();
    unsigned int trianglesMadeOfMatchingKeypointsInImage1Count = tris1.size();
    unsigned int trianglesMadeOfMatchingKeypointsInImage2Count = tris2.size();
    unsigned int image1TrianglesTotalCount = allTrisImage1.size();
    unsigned int image2TrianglesTotalCount = allTrisImage2.size();
    auto matchingTriangles = tempTriangleMap;

    dumpMathcingKeypointTestingInfoToJson(matchingKeypointsCount, image1KeypointsTotalCount, image2KeypointsTotalCout,
                                          matchingKeypoints, matchingTrianglesInBothImagesCount, trianglesMadeOfMatchingKeypointsInImage1Count,
                                          trianglesMadeOfMatchingKeypointsInImage2Count, image1TrianglesTotalCount, image2TrianglesTotalCount );

    cv::imwrite("image1_triangles.jpg", inputImage);
    cv::imwrite("image2_triangles.jpg", outputImage);
//    cv::waitKey();
}


text:
#include <iostream>
#include <Eigen/Sparse>
#include <Eigen/SparseLU>
#include <Eigen/OrderingMethods>
#include <yaml-cpp/yaml.h>
#include "NumpySaver.hpp"

constexpr double alpha = 1 / 137.035399; // unitless;
constexpr double hbarc = 197.3269631;    // MeV*fm;
constexpr double c = 299792458;          // m/s

typedef std::complex<double> mattype;
constexpr std::complex<double> I(0, 1);

YAML::Node
get_config(int argc, char const *argv[])
{
    YAML::Node config;
    switch (argc)
    {
    case 2:
        config = YAML::LoadFile(argv[1]);
        break;
    default:
        config = YAML::LoadFile("config.yaml");
        break;
    }
    return config;
}

/**
 * @brief Get the potential at each point in r.
 *
 * This is not yet a good implementation, since I am still learning eigen.
 * There is a lot of optimizing potential.
 *
 * @param r in fm
 * @param R0 in fm
 * @param V0 in MeV
 * @param Z1 number of protons
 * @param Z2 number of protons
 * @return potential in MeV
 */
Eigen::ArrayXd get_potential_middle(Eigen::ArrayXd &r, double V0, double Z1, double Z2)
{
    Eigen::ArrayXd pot(r.rows() + 1);

    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;

    for (unsigned int i = 1; i < pot.rows() - 1; i++)
    {
        pot[i] = alpha * hbarc * Z1 * Z2 * 2 / (r[i - 1] + r[i]);
    }
    pot[pot.rows() - 1] = 0;

    return pot;
}

Eigen::ArrayXd get_potential_integral(Eigen::ArrayXd &r, double V0, double Z1, double Z2)
{
    Eigen::ArrayXd pot(r.rows() + 1);

    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;

    for (unsigned int i = 1; i < pot.rows() - 1; i++)
    {
        pot[i] = alpha * hbarc * Z1 * Z2 * std::log(r[i] / r[i - 1]) / (r[i] - r[i - 1]);
    }
    pot[pot.rows() - 1] = 0;

    return pot;
}

Eigen::ArrayXd get_middle_points(Eigen::ArrayXd &r)
{
    Eigen::ArrayXd m(r.size() - 1);
    for (int i = 0; i < m.size(); i++)
        m[i] = (r[i] + r[i + 1]) / 2;
    return m;
}

Eigen::ArrayXd get_potential_realistic(Eigen::ArrayXd &r, double V0, double Z1, double Z2, double R0)
{
    Eigen::ArrayXd pot(r.rows() + 1);
    auto mid = get_middle_points(r);

    double a = 0.55;

    for (unsigned int i = 0; i < pot.rows() - 2; i++)
    {
        pot[i] = V0 * (1 + std::cosh(R0 / a)) / (std::cosh(mid[i] / a) + std::cosh(R0 / a));
        if (mid[i] >= R0)
            pot[i] += alpha * hbarc * Z1 * Z2 / (mid[i]);
        else
            pot[i] += alpha * hbarc * Z1 * Z2 / (2 * R0) * (3 - std::pow(mid[i] / R0, 2));
    }
    pot[pot.rows() - 2] = 0;
    pot[pot.rows() - 1] = 0;

    return pot;
}

Eigen::ArrayXd get_potential_left(Eigen::ArrayXd &r, double V0, double Z1, double Z2)
{
    Eigen::ArrayXd pot(r.rows() + 1);

    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;

    for (unsigned int i = 1; i < pot.rows(); i++)
    {
        pot[i] = alpha * hbarc * Z1 * Z2 / r[i - 1];
    }

    return pot;
}

Eigen::ArrayXd get_potential_right(Eigen::ArrayXd &r, double V0, double Z1, double Z2)
{
    Eigen::ArrayXd pot(r.rows() + 1);

    pot[0] = alpha * hbarc * Z1 * Z2 / r[0] + V0;

    for (unsigned int i = 1; i < pot.rows() - 1; i++)
    {
        pot[i] = alpha * hbarc * Z1 * Z2 / r[i];
    }

    pot[pot.rows() - 1] = 0;

    return pot;
}

Eigen::SparseMatrix<mattype> get_matrix(Eigen::ArrayXcd &k, Eigen::ArrayXd &r)
{
    int N = r.size() - 1;
    auto matrix = Eigen::SparseMatrix<mattype>(2 * N + 3, 2 * N + 3);

    // 2N+2 equations, 4 coefficients in each row, +1 A constraint -2 last boundary
    matrix.reserve(4 * (2 * N + 2) + 1 - 2);

    matrix.insert(0, 0) = 1;

    for (int i = 0; i < N; i++)
    {
        auto j = 2 * i + 1;
        matrix.insert(j, j - 1) = std::exp(I * k[i] * r[i]);
        matrix.insert(j, j) = std::exp(-I * k[i] * r[i]);
        matrix.insert(j, j + 1) = -std::exp(I * k[i + 1] * r[i]);
        matrix.insert(j, j + 2) = -std::exp(-I * k[i + 1] * r[i]);

        matrix.insert(j + 1, j - 1) = I * k[i] * std::exp(I * k[i] * r[i]);
        matrix.insert(j + 1, j) = -I * k[i] * std::exp(-I * k[i] * r[i]);
        matrix.insert(j + 1, j + 1) = -I * k[i + 1] * std::exp(I * k[i + 1] * r[i]);
        matrix.insert(j + 1, j + 2) = I * k[i + 1] * std::exp(-I * k[i + 1] * r[i]);
    }

    matrix.insert(2 * N + 1, 2 * N) = std::exp(I * k[N] * r[N]);
    matrix.insert(2 * N + 1, 2 * N + 1) = std::exp(-I * k[N] * r[N]);
    matrix.insert(2 * N + 1, 2 * N + 2) = -std::exp(I * k[N + 1] * r[N]);

    matrix.insert(2 * N + 2, 2 * N) = I * k[N] * std::exp(I * k[N] * r[N]);
    matrix.insert(2 * N + 2, 2 * N + 1) = -I * k[N] * std::exp(-I * k[N] * r[N]);
    matrix.insert(2 * N + 2, 2 * N + 2) = -I * k[N + 1] * std::exp(I * k[N + 1] * r[N]);

    return matrix;
}

Eigen::ArrayXd get_pdf(Eigen::VectorXcd &sol, Eigen::ArrayXcd &k, Eigen::ArrayXd &r, Eigen::ArrayXd &r_plot)
{
    Eigen::ArrayXd pdf(r_plot.size());
    int i_k = 0;

    auto this_k = k[0];
    auto this_r = r[0];
    auto this_A = sol[0];
    auto this_B = sol[1];
    for (int i = 0; i < pdf.size(); i++)
    {
        while (r_plot[i] > this_r)
        {
            i_k++;
            this_k = k[i_k];
            this_r = r[i_k];
            this_A = sol[2 * i_k];
            this_B = sol[2 * i_k + 1];
        }
        pdf[i] = std::norm(this_A * std::exp(I * this_k * r_plot[i]) + this_B * std::exp(-I * this_k * r_plot[i]));
    }
    return pdf;
}

Eigen::VectorXcd get_rhs(int N)
{
    Eigen::VectorXcd vec = Eigen::VectorXcd::Zero(2 * N + 3);
    vec[0] = 1;
    return vec;
}

void run_simulation(YAML::Node &simulation_settings, YAML::Node &data)
{
    auto N = simulation_settings["N"].as<int>();
    auto R0 = simulation_settings["R0"].as<double>();
    auto R_last = simulation_settings["R_last"].as<double>();
    auto V0 = simulation_settings["V0"].as<double>();
    auto E_bind_alpha = simulation_settings["E_bind_alpha"].as<double>();
    auto pot_method = simulation_settings["pot_method"].as<std::string>();

    auto name = simulation_settings["Name"].as<std::string>();

    std::cout << "Simulation Setting: " << name << "\n"
              << std::endl;

    for (std::size_t i = 0; i < data.size(); i++)
    {
        auto A_parent = data[i]["A_parent"].as<double>();
        auto Z_parent = data[i]["Z_parent"].as<double>();
        auto E_bind_p = data[i]["E_bind_p"].as<double>();
        auto E_bind_d = data[i]["E_bind_d"].as<double>();
        auto half_life_lit = data[i]["half_life"].as<double>();

        auto symbol = data[i]["Symbol"].as<std::string>();

        auto E_alpha = E_bind_p - E_bind_d - E_bind_alpha;

        double A_daughter = A_parent - 4;
        double Z_daughter = Z_parent - 2;
        double m_alpha = 3727.379;

        auto R0_this = R0 * std::pow(A_daughter, 1. / 3.);

        // lets first construct the r array as it is constant for every nucleus
        Eigen::ArrayXd r;
        if (pot_method == "realistic")
            r = Eigen::ArrayXd::LinSpaced(N + 1, 0, R_last);
        else
            r = Eigen::ArrayXd::LinSpaced(N + 1, R0_this, R_last);

        Eigen::ArrayXcd pot;
        if (pot_method == "middle")
        {
            pot = get_potential_middle(r, V0, Z_daughter, 2); // MeV
        }
        else if (pot_method == "left")
        {
            pot = get_potential_left(r, V0, Z_daughter, 2); // MeV
        }
        else if (pot_method == "right")
        {
            pot = get_potential_right(r, V0, Z_daughter, 2); // MeV
        }
        else if (pot_method == "integrate")
        {
            pot = get_potential_integral(r, V0, Z_daughter, 2); // MeV
        }
        else if (pot_method == "realistic")
        {
            pot = get_potential_realistic(r, V0, Z_daughter, 2, R0_this); // MeV
        }
        else
        {
            std::cerr << "Warning! Unkown potential method: " << pot_method << std::endl;
            pot = get_potential_middle(r, V0, Z_daughter, 2); // MeV
        }

        Eigen::ArrayXcd k = (2 * m_alpha * (E_alpha - pot)).sqrt() / hbarc;

        // Save potential to plot it!
        Eigen::ArrayXd r_pot(r.size() + 1);
        if (pot_method == "realistic")
        {
            r_pot << 0, get_middle_points(r), r(Eigen::last);
        }
        else
        {
            r_pot << 0, r;
        }
        NumpySaver(std::string("build/output/" + name + "-" + symbol + "-pot.npy")) << r_pot << pot.real();

        auto mat = get_matrix(k, r);
        auto b = get_rhs(N);

        Eigen::SparseLU<Eigen::SparseMatrix<mattype>, Eigen::COLAMDOrdering<int>> solver;
        // Compute the ordering permutation vector from the structural pattern of A
        solver.analyzePattern(mat);
        // Compute the numerical factorization
        solver.factorize(mat);
        // Use the factors to solve the linear system
        Eigen::VectorXcd x = solver.solve(b);

        // R and T factor
        double R = std::norm(x(1));
        double T = std::norm(x(Eigen::last)) * std::abs(k(Eigen::last)) / std::abs(k[0]);
        // check if R+T=1
        if (std::abs(R + T - 1) > 1e-3)
        {
            std::cerr << "Warning! R+T not equal to 1; R+T = " << R + T << "\n";
        }

        // plot pdf
        Eigen::ArrayXd r_plot = Eigen::ArrayXd::LinSpaced(1000, 0, R_last);
        auto pdf = get_pdf(x, k, r, r_plot);

        NumpySaver pdf_saver(std::string("build/output/" + name + "-" + symbol + "-pdf.npy")); // << r_plot << pdf;
        pdf_saver.setPrecision(15);
        pdf_saver << r_plot << pdf;

        double v = std::sqrt(2 * E_alpha / m_alpha) * c;              // m/s
        double half_life = std::log(2) * 2 * R0_this / T / v * 1e-15; // s

        std::cerr << "Lifetime of " << symbol << " " << half_life << "s (Difference to literature value of "
                  << (half_life / half_life_lit - 1) * 100 << "%)" << std::endl;
    }
}

int main(int argc, char const *argv[])
{
    auto config = get_config(argc, argv);
    auto data = config["data"];

    for (std::size_t i = 0; i < config["simulation_settings"].size(); i++)
    {
        std::cout << "##################################\n"
                  << "# Running Simulation " << i + 1 << "/" << config["simulation_settings"].size()
                  << "\n##################################\n";
        auto settings = config["simulation_settings"][i];
        run_simulation(settings, data);
        std::cout << "\n\n";
    }

    return 0;
}


text:
#ifndef LTF_RAII_FIRM_HANDLE_HPP_
#define LTF_RAII_FIRM_HANDLE_HPP_

#include <boost/utility.hpp>
#include <libfirm/firm.h>

namespace ltf
{
    // TODO: define useful copy semantics
    // RAII wrapper for firm, to ensure proper cleanup.
    class FirmHandle : boost::noncopyable
    {
    public:
        FirmHandle(const firm_parameter_t *params);
        ~FirmHandle();
    };
}

#endif // LTF_RAII_FIRM_HANDLE_HPP_

max_stars_repo_name: libfirm/LlvmToFirm

max_issues_repo_name: libfirm/LlvmToFirm

max_forks_repo_name: libfirm/LlvmToFirm


text:
/*=============================================================================
    Copyright (c) 2014 Christoph Weiss

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(FUSION_HASH_23072014_1017)
#define FUSION_HASH_23072014_1017

#include <boost/functional/hash.hpp>
#include <boost/fusion/algorithm/iteration/fold.hpp>
#include <boost/fusion/support/is_sequence.hpp>
#include <boost/utility/enable_if.hpp>

namespace boost { namespace fusion
{
    namespace hashing
    {
        struct hash_combine_fold
        {
            typedef std::size_t result_type;
            template<typename T>
            inline std::size_t operator()(std::size_t seed, T const& v)
            {
                boost::hash_combine(seed, v);
                return seed;
            }
        };

        template <typename Seq>
        inline typename
        boost::enable_if<traits::is_sequence<Seq>, std::size_t>::type
        hash_value(Seq const& seq)
        {
            return fold(seq, 0, hash_combine_fold());
        }
    }

    using hashing::hash_value;
}}

#endif

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
#include <strToSockaddr.h>
#include <boost/python.hpp>
using namespace boost::python;

void export_strToSockkaddr()
{
  class_<StrToSockaddr, bases<Element>, boost::shared_ptr<StrToSockaddr>, boost::noncopyable>
        ("StrToSockaddr", init<std::string, unsigned>())
    .def("class_name", &StrToSockaddr::class_name)
    .def("processing", &StrToSockaddr::processing)
    .def("flow_code",  &StrToSockaddr::flow_code)
  ;
}


text:
#include <catch2/catch.hpp>

#include <wavm/WAVMWasmModule.h>
#include <boost/filesystem.hpp>
#include <faabric/util/func.h>
#include "utils.h"

using namespace wasm;

namespace tests {
    TEST_CASE("Test serializing and restoring module", "[wasm]") {
        cleanSystem();

        std::string user = "demo";
        std::string function = "zygote_check";
        faabric::Message m = faabric::util::messageFactory(user, function);

        std::string mode;
        SECTION("In memory") {
            mode = "memory";
        }

        SECTION("In file") {
            mode = "file";
        }

        SECTION("In state") {
            mode = "state";
        }

        std::vector<uint8_t> memoryData;

        std::string stateKey = "serialTest";
        size_t stateSize;

        // Prepare output file
        std::string filePath = "/tmp/faasm_serialised";
        if (boost::filesystem::exists(filePath.c_str())) {
            boost::filesystem::remove(filePath.c_str());
        }

        // Create the full module
        wasm::WAVMWasmModule moduleA;
        moduleA.bindToFunction(m);

        if (mode == "memory") {
            // Serialise to memory
            memoryData = moduleA.snapshotToMemory();
        } else if (mode == "file") {
            // Serialise to file
            moduleA.snapshotToFile(filePath);
        } else {
            // Serialise to state
            stateSize = moduleA.snapshotToState(stateKey);
        }

        // Create the module to be restored but don't execute zygote
        wasm::WAVMWasmModule moduleB;
        moduleB.bindToFunctionNoZygote(m);

        // Restore from cross-host data
        if (mode == "memory") {
            moduleB.restoreFromMemory(memoryData);
        } else if (mode == "file") {
            moduleB.restoreFromFile(filePath);
        } else {
            moduleB.restoreFromState(stateKey, stateSize);
        }

        // Execute both
        bool successA = moduleA.execute(m);
        REQUIRE(successA);

        bool successB = moduleB.execute(m);
        REQUIRE(successB);
    }
}

max_stars_repo_name: J-Heinemann/faasm

max_issues_repo_name: J-Heinemann/faasm

max_forks_repo_name: J-Heinemann/faasm


text:
#ifndef SPARSETENSOR_EINSUM_UTIL_UNDIRECTEDGRAPH_HPP
#define SPARSETENSOR_EINSUM_UTIL_UNDIRECTEDGRAPH_HPP

#include <vector>

#include <boost/container/flat_set.hpp>
#include <robin_hood.h>

#include <Dice/hash/DiceHash.hpp>

namespace einsum::internal::util {

	/**
	 * Simple undirected Graph implementation.
	 * @tparam T type of the nodes.
	 */
	template<typename T>
	class UndirectedGraph {
	public:
		using NodeSet = boost::container::flat_set<T>;
		/**
		 * New empty UndirectedGraph.
		 */
		UndirectedGraph() = default;

	private:
		/**
		 * Set of all nodes.
		 */
		NodeSet nodes{};
		/**
		 * Set of all directed edges. (a,a)-edged are allowed.
		 */
		robin_hood::unordered_node_map<T, NodeSet, Dice::hash::DiceHash<T>> edges{};

	public:
		/**
		 * Adds all edges between the given nodes (complete graph).
		 * @param nodes nodes to span the complete graph.
		 */
		template<typename C>
		void addCompleteGraph(const C &new_nodes) noexcept {
			// add all combinations

			NodeSet new_nodes_set{new_nodes.begin(), new_nodes.end()};

			for (const T &node_a : new_nodes_set)
				for (const T &node_b : new_nodes_set)
					addEdge(node_a, node_b);
		}

		/**
		 * Add a undirected edge between two nodes.
		 * @param node_a first node
		 * @param node_b second node
		 */
		void addEdge(T node_a, T node_b) noexcept {
			// insert edge from a to b
			nodes.insert(node_a);
			NodeSet &adjacent_nodes_x = edges[node_a];
			adjacent_nodes_x.insert(node_b);

			// insert edge from b to a
			nodes.insert(node_b);
			NodeSet &adjacent_nodes_y = edges[node_b];
			adjacent_nodes_y.insert(node_a);
		}

		/**
		 * Get all connected components e.g. all sets of nodes that are reachable form each other.
		 * @return set of connected components.
		 */
		[[nodiscard]] std::vector<NodeSet> getConnectedComponents() const noexcept {
			// this is basically a breadth first search
			NodeSet unfinished_nodes{this->nodes};

			NodeSet open_nodes{};

			std::vector<NodeSet> connected_components{};

			while (not unfinished_nodes.empty()) {
				NodeSet connected_component{};

				T first_node = *unfinished_nodes.begin();
				open_nodes.insert(first_node);
				connected_component.insert(first_node);
				unfinished_nodes.erase(first_node);

				while (not open_nodes.empty()) {
					T node = *open_nodes.begin();
					open_nodes.erase(node);
					const NodeSet &adjacent_nodes = edges.at(node);
					for (T adj_node : adjacent_nodes) {
						if (unfinished_nodes.count(adj_node)) {
							connected_component.insert(adj_node);
							open_nodes.insert(adj_node);
							unfinished_nodes.erase(adj_node);
						}
					}
				}

				connected_components.emplace_back(connected_component);
			}

			return connected_components;
		}

		/**
		 * Get all neignbors of a node.
		 * @param node the node.
		 * @return the neigbors.
		 */
		NodeSet neighbors(const T node) const noexcept {
			return edges.at(node);
		}

		/**
		 * Get all nodes.
		 * @return all nodes.
		 */
		NodeSet getNodes() const noexcept {
			return nodes;
		}

		/**
		 * Resets the graph to an empty graph.
		 */
		void clear() {
			nodes.clear();
			edges.clear();
		}

		/**
		 * Iterator of the nodes.
		 * @return Node iterator
		 */
		typename NodeSet::const_iterator cbegin() const noexcept {
			return nodes.cbegin();
		};

		/**
		 * End of nodes Iterator.
		 * @return iterator end
		 */
		typename NodeSet::const_iterator cend() const noexcept {
			return nodes.cend();
		};
	};

}

#endif //SPARSETENSOR_EINSUM_UTIL_UNDIRECTEDGRAPH_HPP

max_stars_repo_name: lennartaustenfeld/hypertrie

max_issues_repo_name: lennartaustenfeld/hypertrie

max_forks_repo_name: lennartaustenfeld/hypertrie