text:
#ifndef CDM_SDL2_HPP
#define CDM_SDL2_HPP

#include <cdm/cmake_generator.hpp>
#include <ventura/file_operations.hpp>
#include <ventura/run_process.hpp>
#include <boost/lexical_cast.hpp>
#include <silicium/sink/iterator_sink.hpp>

namespace cdm
{
	struct sdl2_paths
	{
		ventura::absolute_path include;
		ventura::absolute_path library;
		ventura::absolute_path main;
		ventura::absolute_path runtime_library;
	};

	inline sdl2_paths install_sdl2(ventura::absolute_path const &sdl2_source, ventura::absolute_path const &temporary,
	                               ventura::absolute_path const &install_root, ventura::absolute_path const &cmake_exe,
	                               unsigned make_parallelism, cdm::configuration const &target,
	                               Si::Sink<char, Si::success>::interface &output)
	{
		ventura::absolute_path const module_in_cache = install_root / "sdl2";
		if (!ventura::file_exists(module_in_cache, Si::throw_))
		{
			ventura::absolute_path const &build_dir = temporary / "build";
			ventura::absolute_path const &construction_site = temporary / "construction";
			ventura::create_directories(build_dir, Si::throw_);
			{
				std::vector<Si::noexcept_string> arguments;
				arguments.emplace_back("-DCMAKE_INSTALL_PREFIX=" + ventura::to_utf8_string(construction_site));
				arguments.emplace_back("-DSDL_STATIC=OFF");
				arguments.emplace_back("-DSDL_SHARED=ON");
				cdm::generate_default_cmake_generator_arguments(Si::make_container_sink(arguments), target);
				arguments.emplace_back(ventura::to_utf8_string(sdl2_source));
				int const rc = ventura::run_process(cmake_exe, arguments, build_dir, output,
				                                    std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(),
				                                    ventura::environment_inheritance::inherit)
				                   .get();
				if (rc != 0)
				{
					throw std::runtime_error("cmake configure failed");
				}
			}
			{
#ifdef _MSC_VER
				boost::ignore_unused_variable_warning(make_parallelism);
				std::vector<Si::os_string> arguments;
				arguments.emplace_back(SILICIUM_OS_STR("SDL2.sln"));
				arguments.emplace_back(SILICIUM_OS_STR("/build"));
				arguments.emplace_back(
#ifdef NDEBUG
				    SILICIUM_OS_STR("Release")
#else
				    SILICIUM_OS_STR("Debug")
#endif
				        );
				arguments.emplace_back(SILICIUM_OS_STR("/project"));
				arguments.emplace_back(SILICIUM_OS_STR("INSTALL"));
				int const rc = ventura::run_process(
				                   *ventura::absolute_path::create(
#if _MSC_VER == 1900
				                       "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\devenv.exe"
#elif _MSC_VER == 1800
				                       "C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\Common7\\IDE\\devenv.exe"
#else
#error unsupported version
#endif
				                       ),
				                   arguments, build_dir, output,
				                   std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(),
				                   ventura::environment_inheritance::inherit)
				                   .get();
				if (rc != 0)
				{
					throw std::runtime_error("cmake build failed");
				}
#else
				std::vector<Si::noexcept_string> arguments;
				cdm::generate_cmake_build_arguments(Si::make_container_sink(arguments), target);
				arguments.emplace_back("--");
#ifdef _WIN32
				boost::ignore_unused_variable_warning(make_parallelism);
#else
				arguments.emplace_back("-j" + boost::lexical_cast<Si::os_string>(make_parallelism));
#endif
				arguments.emplace_back("install");
				int const rc = ventura::run_process(cmake_exe, arguments, build_dir, output,
				                                    std::vector<std::pair<Si::os_char const *, Si::os_char const *>>(),
				                                    ventura::environment_inheritance::inherit)
				                   .get();
				if (rc != 0)
				{
					throw std::runtime_error("cmake build failed");
				}
#endif
			}
			ventura::rename(construction_site, module_in_cache, Si::throw_);
		}
		sdl2_paths result;
		result.include = module_in_cache / "include/SDL2";
		auto make_library_name = [](ventura::path::underlying_type const &stem, bool is_shared_object)
		{
#ifdef _MSC_VER
			Si::ignore_unused_variable_warning(is_shared_object);
#endif
			// clang-format 3.7 mis-formats the following expression.
			// clang-format off
			auto result =
#ifndef _MSC_VER
					"lib" +
#endif
					stem +
#ifdef _MSC_VER
					".lib"
#else
					(is_shared_object ? ".so" : ".a")
#endif
					;
			// clang-format on
			return *ventura::path_segment::create(ventura::path(std::move(result)));
		};
		auto lib_dir = module_in_cache / "lib";
		result.library = lib_dir / make_library_name("SDL2", true);
		result.main = lib_dir / make_library_name("SDL2main", false);
		result.runtime_library =
#ifdef _MSC_VER
		    module_in_cache / "bin" /
#ifndef _MSC_VER
		    "lib"
#endif
		    "SDL2."
#ifdef _MSC_VER
		    "dll"
#else
		    "so"
#endif
#else
		    result.library
#endif
		    ;
		auto require_file = [](ventura::absolute_path const &file)
		{
			if (!ventura::file_exists(file, Si::throw_))
			{
				throw std::runtime_error("Missing from SDL2 installation: " +
				                         ventura::to_utf8_string<std::string>(file));
			}
		};
		require_file(result.library);
		require_file(result.main);
		require_file(result.runtime_library);
		return result;
	}
}

#endif

ext: hpp

max_stars_repo_name: TyRoXx/cdm

max_issues_repo_name: TyRoXx/cdm

max_forks_repo_name: TyRoXx/cdm


text:
#define BOOST_TEST_MODULE assert

#include <boost/algorithm/cxx11/any_of.hpp>

#include <elle/assert.hh>
#include <elle/test.hh>

BOOST_AUTO_TEST_CASE(success)
{
  ELLE_ASSERT(true);
  try
  {
    throw std::runtime_error("foo");
  }
  catch(std::exception const& e)
  {}
  ELLE_ASSERT_NO_OTHER_EXCEPTION
}

static void an_other_exception()
{
  try
  {
    throw std::bad_alloc();
  }
  catch(std::bad_cast const& e)
  {}
  ELLE_ASSERT_NO_OTHER_EXCEPTION
}

BOOST_AUTO_TEST_CASE(failure)
{
  BOOST_CHECK_THROW(ELLE_ASSERT(false), elle::AssertError);
}

BOOST_AUTO_TEST_CASE(failure2)
{
  BOOST_CHECK_THROW(an_other_exception(), elle::AssertError);
}

BOOST_AUTO_TEST_CASE(success_eq)
{
  ELLE_ASSERT_EQ(42, 42);
}

BOOST_AUTO_TEST_CASE(failure_eq)
{
  BOOST_CHECK_THROW(ELLE_ASSERT_EQ(42, 51), elle::AssertError);
}

BOOST_AUTO_TEST_CASE(value)
{
  {
    auto v = std::make_unique<int>(1);
    // Check ENFORCE returns the tested value.
    ELLE_ENFORCE(v).reset(new int(2));
    BOOST_TEST(*v == 2);
  }
  // ENFORCE forwards rvalues as such.
  {
    auto p = ELLE_ENFORCE(std::make_unique<int>(42));
    BOOST_TEST(*p == 42);
  }
}

// Pacify -Wmissing-declarations.  Avoid unnamed namespace, it changes
// the names.
void f0();
void f1();
void f2();
void f3();

#define NO_INLINE ELLE_COMPILER_ATTRIBUTE_NO_INLINE

NO_INLINE void f0() { ELLE_ASSERT_EQ(42, 51); }; auto const line = __LINE__;
NO_INLINE void f1() { f0(); }
NO_INLINE void f2() { f1(); }
NO_INLINE void f3() { f2(); }

BOOST_AUTO_TEST_CASE(abort_callbacks)
{
  using boost::algorithm::any_of;

  auto err = elle::AssertError{};
  elle::on_abort([&err](elle::AssertError const& e)
    {
      err = e;
    });
  BOOST_CHECK_THROW(f3(), elle::AssertError);
  BOOST_TEST(err.what() ==
             elle::print("assertion '42 == 51 is false: (42=42, 51=51)' failed at %s:%s",
                         __FILE__, line));
  // At least clang does not seem to obey the NO_INLINE, and shows
  // only f0.
  BOOST_TEST_MESSAGE("Backtrace: " << *err.backtrace());
#if ELLE_HAVE_BACKTRACE
  BOOST_TEST(any_of(err.backtrace()->frames(),
                    [](auto const& frame)
                    {
                      return frame.symbol == "f0()";
                    }));
#endif
}

ext: cc

max_issues_repo_name: mefyl/elle

max_forks_repo_name: mefyl/elle


text:
#pragma once

#include "move.hpp"

#include <array>
#include <map>
#include <set>

#include "tl/expected.hpp"

#include <boost/optional.hpp>

namespace Aronda
{

static const std::size_t c_number_of_players = 2;

static const std::size_t c_number_of_squares = 25;

enum class InvalidMove
{
    TooManyStones,
    SquareLocked,
    SquareUnreachable
};

struct SquareState
{
    std::array<std::size_t, c_number_of_players> placed_stones;
    boost::optional<Player> player_locked;
};

using AdjacencyList_t = std::map<Square, std::set<Square>>;

bool operator==(const SquareState& ss1, const SquareState& ss2);

class Board
{
public:
    using ExpectedBoard = tl::expected<Board, InvalidMove>;

    /**
     * @brief construct an empty board
     */
    Board();

    SquareState squareState(const Square square) const;

    ExpectedBoard placeStone(const Move move) const;

    static std::size_t maxNumberOfStonesOnASquare(const Square square_index);

private:
    std::array<SquareState, c_number_of_squares> m_square_states;

    bool isSquareReachable(const Move move) const;

    static bool isSquareOnTheOutsideRing(const Square square);

    static std::set<Square> findNeighbours(const Square square);

    bool hasPlayerPlayerOnSquare(const Player player, const Square square) const;
};

} // namespace Aronda

max_stars_repo_name: julienlopez/Aronda

max_issues_repo_name: julienlopez/Aronda

max_forks_repo_name: julienlopez/Aronda


text:
/*==============================================================================
  Copyright (c) 2017, 2018 Matt Calabrese

  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 ARGOT_GEN_CONCEPT_BODY_DETAIL_PARSE_COMMA_HPP_
#define ARGOT_GEN_CONCEPT_BODY_DETAIL_PARSE_COMMA_HPP_

#include <boost/preprocessor/arithmetic/dec.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/tuple/pop_front.hpp>
#include <boost/preprocessor/variadic/elem.hpp>
#include <boost/preprocessor/variadic/size.hpp>
#include <boost/vmd/is_empty.hpp>

#define ARGOT_GEN_DETAIL_PARSE_COMMA_IMPL_SUCCESS( ... )                       \
value( comma_token, BOOST_PP_TUPLE_POP_FRONT( ( __VA_ARGS__ ) ) )

#define ARGOT_GEN_DETAIL_PARSE_COMMA_IMPL_FAILURE( ... )                       \
unexpected( soft(), ( comma_token ), ( __VA_ARGS__ ) )

#define ARGOT_GEN_DETAIL_PARSE_COMMA_IMPL( ... )                               \
BOOST_PP_IIF( BOOST_VMD_IS_EMPTY( BOOST_PP_VARIADIC_ELEM( 0, __VA_ARGS__ ) )   \
            , ARGOT_GEN_DETAIL_PARSE_COMMA_IMPL_SUCCESS                        \
            , ARGOT_GEN_DETAIL_PARSE_COMMA_IMPL_FAILURE                        \
            )( __VA_ARGS__ )

#define ARGOT_GEN_DETAIL_PARSE_COMMA( ... )                                    \
BOOST_PP_IF( BOOST_PP_DEC( BOOST_PP_VARIADIC_SIZE( __VA_ARGS__ ) )             \
           , ARGOT_GEN_DETAIL_PARSE_COMMA_IMPL                                 \
           , ARGOT_GEN_DETAIL_PARSE_COMMA_IMPL_FAILURE                         \
           )( __VA_ARGS__ )

#endif  // ARGOT_GEN_CONCEPT_BODY_DETAIL_PARSE_COMMA_HPP_

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
// Copyright Jim Bosch 2010-2012.
// Copyright Stefan Seefeld 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef boost_python_numpy_ndarray_hpp_
#define boost_python_numpy_ndarray_hpp_

/**
 *  @brief Object manager and various utilities for numpy.ndarray.
 */

#include <boost/python.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/python/numpy/numpy_object_mgr_traits.hpp>
#include <boost/python/numpy/dtype.hpp>
#include <vector>

namespace boost { namespace python { namespace numpy {

/**
 *  @brief A boost.python "object manager" (subclass of object) for numpy.ndarray.
 *
 *  @todo This could have a lot more functionality (like boost::python::numeric::array).
 *        Right now all that exists is what was needed to move raw data between C++ and Python.
 */
class ndarray : public object
{

  /**
   *  @brief An internal struct that's byte-compatible with PyArrayObject.
   *
   *  This is just a hack to allow inline access to this stuff while hiding numpy/arrayobject.h
   *  from the user.
   */
  struct array_struct
  {
    PyObject_HEAD
    char * data;
    int nd;
    Py_intptr_t * shape;
    Py_intptr_t * strides;
    PyObject * base;
    PyObject * descr;
    int flags;
    PyObject * weakreflist;
  };

  /// @brief Return the held Python object as an array_struct.
  array_struct * get_struct() const { return reinterpret_cast<array_struct*>(this->ptr()); }

public:

  /**
   *  @brief Enum to represent (some) of Numpy's internal flags.
   *
   *  These don't match the actual Numpy flag values; we can't get those without including
   *  numpy/arrayobject.h or copying them directly.  That's very unfortunate.
   *
   *  @todo I'm torn about whether this should be an enum.  It's very convenient to not
   *        make these simple integer values for overloading purposes, but the need to
   *        define every possible combination and custom bitwise operators is ugly.
   */
  enum bitflag
  {
    NONE=0x0, C_CONTIGUOUS=0x1, F_CONTIGUOUS=0x2, V_CONTIGUOUS=0x1|0x2,
    ALIGNED=0x4, WRITEABLE=0x8, BEHAVED=0x4|0x8,
    CARRAY_RO=0x1|0x4, CARRAY=0x1|0x4|0x8, CARRAY_MIS=0x1|0x8,
    FARRAY_RO=0x2|0x4, FARRAY=0x2|0x4|0x8, FARRAY_MIS=0x2|0x8,
    UPDATE_ALL=0x1|0x2|0x4, VARRAY=0x1|0x2|0x8, ALL=0x1|0x2|0x4|0x8
  };

  BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(ndarray, object);

  /// @brief Return a view of the scalar with the given dtype.
  ndarray view(dtype const & dt) const;

  /// @brief Copy the array, cast to a specified type.
  ndarray astype(dtype const & dt) const;

  /// @brief Copy the scalar (deep for all non-object fields).
  ndarray copy() const;

  /// @brief Return the size of the nth dimension.
  Py_intptr_t shape(int n) const { return get_shape()[n]; }

  /// @brief Return the stride of the nth dimension.
  Py_intptr_t strides(int n) const { return get_strides()[n]; }

  /**
   *  @brief Return the array's raw data pointer.
   *
   *  This returns char so stride math works properly on it.  It's pretty much
   *  expected that the user will have to reinterpret_cast it.
   */
  char * get_data() const { return get_struct()->data; }

  /// @brief Return the array's data-type descriptor object.
  dtype get_dtype() const;

  /// @brief Return the object that owns the array's data, or None if the array owns its own data.
  object get_base() const;

  /// @brief Set the object that owns the array's data.  Use with care.
  void set_base(object const & base);

  /// @brief Return the shape of the array as an array of integers (length == get_nd()).
  Py_intptr_t const * get_shape() const { return get_struct()->shape; }

  /// @brief Return the stride of the array as an array of integers (length == get_nd()).
  Py_intptr_t const * get_strides() const { return get_struct()->strides; }

  /// @brief Return the number of array dimensions.
  int get_nd() const { return get_struct()->nd; }

  /// @brief Return the array flags.
  bitflag get_flags() const;

  /// @brief Reverse the dimensions of the array.
  ndarray transpose() const;

  /// @brief Eliminate any unit-sized dimensions.
  ndarray squeeze() const;

  /// @brief Equivalent to self.reshape(*shape) in Python.
  ndarray reshape(python::tuple const & shape) const;

  /**
   *  @brief If the array contains only a single element, return it as an array scalar; otherwise return
   *         the array.
   *
   *  @internal This is simply a call to PyArray_Return();
   */
  object scalarize() const;
};

/**
 *  @brief Construct a new array with the given shape and data type, with data initialized to zero.
 */
ndarray zeros(python::tuple const & shape, dtype const & dt);
ndarray zeros(int nd, Py_intptr_t const * shape, dtype const & dt);

/**
 *  @brief Construct a new array with the given shape and data type, with data left uninitialized.
 */
ndarray empty(python::tuple const & shape, dtype const & dt);
ndarray empty(int nd, Py_intptr_t const * shape, dtype const & dt);

/**
 *  @brief Construct a new array from an arbitrary Python sequence.
 *
 *  @todo This does't seem to handle ndarray subtypes the same way that "numpy.array" does in Python.
 */
ndarray array(object const & obj);
ndarray array(object const & obj, dtype const & dt);

namespace detail
{

ndarray from_data_impl(void * data,
		       dtype const & dt,
		       std::vector<Py_intptr_t> const & shape,
		       std::vector<Py_intptr_t> const & strides,
		       object const & owner,
		       bool writeable);

template <typename Container>
ndarray from_data_impl(void * data,
		       dtype const & dt,
		       Container shape,
		       Container strides,
		       object const & owner,
		       bool writeable,
		       typename boost::enable_if< boost::is_integral<typename Container::value_type> >::type * enabled = NULL)
{
  std::vector<Py_intptr_t> shape_(shape.begin(),shape.end());
  std::vector<Py_intptr_t> strides_(strides.begin(), strides.end());
  return from_data_impl(data, dt, shape_, strides_, owner, writeable);
}

ndarray from_data_impl(void * data,
		       dtype const & dt,
		       object const & shape,
		       object const & strides,
		       object const & owner,
		       bool writeable);

} // namespace boost::python::numpy::detail

/**
 *  @brief Construct a new ndarray object from a raw pointer.
 *
 *  @param[in] data    Raw pointer to the first element of the array.
 *  @param[in] dt      Data type descriptor.  Often retrieved with dtype::get_builtin().
 *  @param[in] shape   Shape of the array as STL container of integers; must have begin() and end().
 *  @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
 *  @param[in] owner   An arbitray Python object that owns that data pointer.  The array object will
 *                     keep a reference to the object, and decrement it's reference count when the
 *                     array goes out of scope.  Pass None at your own peril.
 *
 *  @todo Should probably take ranges of iterators rather than actual container objects.
 */
template <typename Container>
inline ndarray from_data(void * data,
			 dtype const & dt,
			 Container shape,
			 Container strides,
			 python::object const & owner)
{
  return numpy::detail::from_data_impl(data, dt, shape, strides, owner, true);
}

/**
 *  @brief Construct a new ndarray object from a raw pointer.
 *
 *  @param[in] data    Raw pointer to the first element of the array.
 *  @param[in] dt      Data type descriptor.  Often retrieved with dtype::get_builtin().
 *  @param[in] shape   Shape of the array as STL container of integers; must have begin() and end().
 *  @param[in] strides Shape of the array as STL container of integers; must have begin() and end().
 *  @param[in] owner   An arbitray Python object that owns that data pointer.  The array object will
 *                     keep a reference to the object, and decrement it's reference count when the
 *                     array goes out of scope.  Pass None at your own peril.
 *
 *  This overload takes a const void pointer and sets the "writeable" flag of the array to false.
 *
 *  @todo Should probably take ranges of iterators rather than actual container objects.
 */
template <typename Container>
inline ndarray from_data(void const * data,
			 dtype const & dt,
			 Container shape,
			 Container strides,
			 python::object const & owner)
{
  return numpy::detail::from_data_impl(const_cast<void*>(data), dt, shape, strides, owner, false);
}

/**
 *  @brief Transform an arbitrary object into a numpy array with the given requirements.
 *
 *  @param[in] obj     An arbitrary python object to convert.  Arrays that meet the requirements
 *                     will be passed through directly.
 *  @param[in] dt      Data type descriptor.  Often retrieved with dtype::get_builtin().
 *  @param[in] nd_min  Minimum number of dimensions.
 *  @param[in] nd_max  Maximum number of dimensions.
 *  @param[in] flags   Bitwise OR of flags specifying additional requirements.
 */
ndarray from_object(object const & obj, dtype const & dt,
                    int nd_min, int nd_max, ndarray::bitflag flags=ndarray::NONE);

inline ndarray from_object(object const & obj, dtype const & dt,
                           int nd, ndarray::bitflag flags=ndarray::NONE)
{
  return from_object(obj, dt, nd, nd, flags);
}

inline ndarray from_object(object const & obj, dtype const & dt, ndarray::bitflag flags=ndarray::NONE)
{
  return from_object(obj, dt, 0, 0, flags);
}

ndarray from_object(object const & obj, int nd_min, int nd_max,
                    ndarray::bitflag flags=ndarray::NONE);

inline ndarray from_object(object const & obj, int nd, ndarray::bitflag flags=ndarray::NONE)
{
  return from_object(obj, nd, nd, flags);
}

inline ndarray from_object(object const & obj, ndarray::bitflag flags=ndarray::NONE)
{
  return from_object(obj, 0, 0, flags);
}

inline ndarray::bitflag operator|(ndarray::bitflag a, ndarray::bitflag b)
{
  return ndarray::bitflag(int(a) | int(b));
}

inline ndarray::bitflag operator&(ndarray::bitflag a, ndarray::bitflag b)
{
  return ndarray::bitflag(int(a) & int(b));
}

} // namespace boost::python::numpy

namespace converter
{

NUMPY_OBJECT_MANAGER_TRAITS(numpy::ndarray);

}}} // namespace boost::python::converter

#endif


text:
#include "graph_executor.h"

#include <boost/format.hpp>

#include "graph.h"
#include "graph_node.h"
#include "graph_validator.h"
#include "composite_data_buffer.h"

namespace noises
{
    GraphExecutor::GraphExecutor(const Graph &graph) : graph_(graph)
    {

    }

    const Graph& GraphExecutor::graph()
    {
        return graph_;
    }

    GraphOutputs GraphExecutor::execute()
    {
        auto validation = validate_graph();
        if(!validation)
            throw std::logic_error("Could not execute graph. It is invalid.");

        get_topological_order();
        buffer_stack_.resize(topological_order_.size());

        return execute_internal();
    }

    GraphOutputs GraphExecutor::execute_internal()
    {
        while(buffer_stack_.size() > 1)
        {
            std::vector<int> current_nodes_to_calculate = topological_order_.back();

            for(int node_id : current_nodes_to_calculate)
            {
                execute_node(node_id);
            }

            // Release any memory we don't need any more
            topological_order_.pop_back();
            buffer_stack_.pop_back();
        }

        GraphOutputs outputs;

        for(const GraphNode& output : graph_.output_nodes())
        {
            // Attribute length is irrelevant here
            outputs.add(output.name(), extract_buffer(get_buffer(output.id())));
        }

        return outputs;
    }

    void GraphExecutor::execute_node(int node_id)
    {
        const GraphNode& node = *graph_.get_node_by_id(node_id);
        auto buffers = get_node_dependency_buffers(node);

        CompositeDataBuffer input_buffer;
        std::vector<unsigned char> empty_buffer;

        add_attribute_dependencies(input_buffer, node, buffers, empty_buffer);
        add_uniform_dependencies(input_buffer, node, buffers);

        DataBuffer& output_buffer = get_buffer(node.id(), input_buffer.attribute_info());

        output_buffer.add(node.outputs());

        node.execute_uniforms(input_buffer, output_buffer);

        DataBuffer::size_type attribute_length = output_buffer.attribute_info().length();

        for(DataBuffer::size_type i = 0; i < attribute_length; i++)
        {
            node.execute_attributes(input_buffer, output_buffer, i);
        }
    }

    void GraphExecutor::add_attribute_dependencies(CompositeDataBuffer &input_buffer, const GraphNode &node,
                                                   std::unordered_map<int, std::reference_wrapper<DataBuffer>>& buffers, std::vector<unsigned char>& empty_buffer)
    {
        for(const InputSocket& attribute_socket : node.inputs().attribute_sockets())
        {
            auto possible_connection = attribute_socket.connection();
            if(possible_connection)
            {
                const Connection& connection = *possible_connection;
                const OutputSocket& output_socket = connection.output();
                const GraphNode* dependency_node = output_socket.parent();
                int dependency_id = dependency_node->id();

                DataBuffer& dependency_buffer = buffers.at(dependency_id);
                input_buffer.add_attribute(connection.data_type(), dependency_buffer.get_memory_block(output_socket.index()), dependency_buffer.attribute_info());
                continue;
            }

            // If it's graph internal node and doesn't have an input connection, assume it's an input to the graph manually
            if(!(node.is_graph_internal_node() && attribute_socket.optional()))
            {
                input_buffer.add_attribute(ConnectionDataType::undefined(), empty_buffer, AttributeInfo());
                continue;
            }

            auto graph_input = graph_.get_input_buffer(node.name());
            if(graph_input)
            {
                const DataBuffer& input_attribute_buffer = graph_input->get();
                input_buffer.add_attribute(input_attribute_buffer.get_attribute_type(0), input_attribute_buffer.get_memory_block(0), input_attribute_buffer.attribute_info());
            }
            else
            {
                input_buffer.add_attribute(ConnectionDataType::undefined(), empty_buffer, AttributeInfo());
            }
        }

        assert(input_buffer.num_attributes() == node.inputs().attribute_sockets().size());
    }

    void GraphExecutor::add_uniform_dependencies(CompositeDataBuffer &input_buffer, const GraphNode &node,
                                                 std::unordered_map<int, std::reference_wrapper<DataBuffer>>& buffers)
    {
        for(const InputSocket& uniform_socket : node.inputs().uniform_sockets())
        {
            auto possible_connection = uniform_socket.connection();
            if(possible_connection)
            {
                const Connection& connection = *possible_connection;
                const OutputSocket& output_socket = connection.output();
                const GraphNode* dependency_node = output_socket.parent();
                int dependency_id = dependency_node->id();

                DataBuffer& dependency_buffer = buffers.at(dependency_id);
                input_buffer.add_uniform(connection.data_type(), dependency_buffer.get_uniform_raw(output_socket, connection.data_type()));
                continue;
            }

            if(!(node.is_graph_internal_node() && uniform_socket.optional()))
            {
                input_buffer.add_uniform(ConnectionDataType::undefined(), nullptr);
                continue;
            }

            auto graph_input = graph_.get_input_buffer(node.name());
            if(graph_input)
            {
                const DataBuffer& input_uniform_buffer = graph_input->get();
                input_buffer.add_uniform(input_uniform_buffer.get_uniform_type(0), input_uniform_buffer.get_uniform_block(0));
            }
            else
            {
                input_buffer.add_uniform(ConnectionDataType::undefined(), nullptr);
            }
        }

        assert(input_buffer.num_uniforms() == node.inputs().uniform_sockets().size());
    }

    std::unordered_map<int, std::reference_wrapper<DataBuffer>> GraphExecutor::get_node_dependency_buffers(const GraphNode &node)
    {
        std::unordered_map<int, std::reference_wrapper<DataBuffer>> out;

        auto dependencies = get_node_dependencies(node);
        for(int dependency_id : dependencies)
        {
            DataBuffer& buffer = get_buffer(dependency_id);
            out.emplace(std::make_pair(dependency_id, std::ref(buffer)));
        }

        return out;
    }

    std::vector<int> GraphExecutor::get_node_dependencies(const GraphNode& node)
    {
        std::vector<int> out;
        for(const InputSocket& socket : node.inputs().all_sockets())
        {
            auto possible_connection = socket.connection();
            if(possible_connection)
            {
                const Connection& connection = *possible_connection;
                int dependency_id = connection.output().parent()->id();

                if(std::find(out.begin(), out.end(), dependency_id) == out.end())
                    out.push_back(dependency_id);
            }
        }
        return out;
    }

    DataBuffer& GraphExecutor::get_buffer(int node_id, AttributeInfo buffer_attribute_info)
    {
        // Get the stack position in topological_order_
        // Start at -1 because first iteration (for a size of 1) increments it to 0
        int i = -1;
        auto it = topological_order_.begin();
        for(; it != topological_order_.end(); ++it)
        {
            i++;
            if(std::find(it->begin(), it->end(), node_id) != it->end())
                break;
        }

        if(it == topological_order_.end())
        {
            // If it's not in the topological order any more, try just searching through the buffer stack
            for(auto& buffer_level : buffer_stack_)
            {
                for(auto& pair : buffer_level)
                {
                    if(std::get<0>(pair) == node_id)
                    {
                        return *std::get<1>(pair);
                    }
                }
            }

            throw std::logic_error("Could not find a position for node " + boost::lexical_cast<std::string>(node_id) + " in the topological_order_");
        }

        // Find the (stack level - 1) in buffer_stack_
        // Stack level -1 because we need (stack level)'s buffer in (stack level - 1)
        auto it_j = buffer_stack_.begin();
        for(int j = 1; j < i; ++j, ++it_j) { }

        if(it_j == buffer_stack_.end())
            throw std::logic_error("Could not find a position for node " + boost::lexical_cast<std::string>(node_id) + " in the buffer_stack_");

        auto& buffer_level = *it_j;

        // Fint the matching node_id in the pair in the buffer level vector
        auto it_q = buffer_level.begin();
        for(; it_q != buffer_level.end(); ++it_q)
        {
            if(std::get<0>(*it_q) == node_id)
                break;
        }

        if(it_q == buffer_level.end())
        {
            // We need to allocate a new buffer
            std::unique_ptr<DataBuffer> buffer(new DataBuffer(buffer_attribute_info));
            DataBuffer& buffer_ref = *buffer;

            auto pair = std::make_pair(node_id, std::move(buffer));
            buffer_level.push_back(std::move(pair));

            return buffer_ref;
        }
        else
        {
            auto& pair = *it_q;
            return *std::get<1>(pair);
        }
    }

    std::unique_ptr<DataBuffer> GraphExecutor::extract_buffer(const DataBuffer &buffer)
    {
        std::unique_ptr<DataBuffer> out;

        for(auto& buffer_level : buffer_stack_)
        {
            for(auto& pair : buffer_level)
            {
                std::unique_ptr<DataBuffer>& pair_ptr = std::get<1>(pair);
                if(pair_ptr.get() == &buffer)
                {
                    std::swap(out, pair_ptr);
                }
            }
        }

        if(!out)
            throw std::logic_error("DataBuffer wasn't in buffer stack??");

        return out;
    }

    ValidationResults GraphExecutor::validate_graph() const
    {
        GraphValidator validator(graph_);
        return validator.validate();
    }

    void GraphExecutor::get_topological_order()
    {
        std::deque<std::vector<int>> out;

        // Push a dummy first because it looks to (stack level + 1) as the storage space
        out.push_back(std::vector<int>());

        std::vector<int> root;
        for(const GraphNode& output_node : graph_.output_nodes())
        {
            root.push_back(output_node.id());
        }
        out.push_back(root);

        // Won't run infinitely because the graph has been validated as non-cyclic
        while(true)
        {
            std::vector<int> next_stack_layer;

            for(int node_id : out.back())
            {
                const GraphNode& node = *graph_.get_node_by_id(node_id);

                for(const InputSocket& socket : node.inputs().all_sockets())
                {
                    auto possible_connection = socket.connection();
                    if(possible_connection)
                    {
                        const Connection& connection = *possible_connection;
                        const GraphNode* connection_output = connection.output().parent();

                        int id = connection_output->id();

                        if(std::find(next_stack_layer.begin(), next_stack_layer.end(), id) == next_stack_layer.end())
                            next_stack_layer.push_back(id);
                    }
                }
            }

            if(next_stack_layer.size() > 0)
            {
                out.push_back(next_stack_layer);
            }
            else break;
        }

        topological_order_ = out;
    }
}

ext: cpp

max_stars_repo_name: SneakyMax/NoiseStudio

max_issues_repo_name: SneakyMax/NoiseStudio

max_forks_repo_name: SneakyMax/NoiseStudio


text:
/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed
 * under the MIT license. See the license file LICENSE.
 */

#include <iostream>
#include <string>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/visualization/point_cloud_color_handlers.h>

#include "rtDDPvMF/rtDDPvMF.hpp"
//#include "rtDDPvMF/realtimeDDPvMF_openni.hpp"
#include "bbTrans/lower_bound_S3.h"
#include "bbTrans/upper_bound_indep_S3.h"
#include "bbTrans/upper_bound_convex_S3.h"
#include "bbTrans/branch_and_bound.h"
#include "bbTrans/vmf_mm.h"
#include "bbTrans/node.h"
#include "dpOptTrans/dp_vmf_opt_rot.h"
#include "dpOptTrans/pc_helper.h"

#include <boost/program_options.hpp>
namespace po = boost::program_options;

bool ComputevMFMMfromDepth(
  shared_ptr<RtDDPvMF> pRtDDPvMF,
  const CfgRtDDPvMF& cfg,
    const std::string& path, bool display,
    cv::Mat *dI,
    cv::Mat *gI,
    std::vector<::bb::vMF<3>>* vmfs) {

  std::cout<<"reading depth image from "<<path<<std::endl;
  cv::Mat depth = cv::imread(path, CV_LOAD_IMAGE_ANYDEPTH);
  std::cout<<"type: "<<int(depth.type()) <<" != "<<int(CV_16U) <<std::endl;

  string pathRgb(path);
  pathRgb.replace(path.length()-5,1,"rgb");
  std::cout<<"reading rgb image from "<<pathRgb<<std::endl;
  cv::Mat gray = cv::imread(pathRgb, CV_LOAD_IMAGE_GRAYSCALE);
  cv::Mat rgb = cv::imread(pathRgb);
  *gI = gray;

  if (display) {
    cv::Mat dI(depth.rows,depth.cols,CV_8UC1);
    depth.convertTo(dI,CV_8UC1,255./4000.,-19.);
    cv::imshow("d",dI);
    cv::imshow("rgb",rgb);
    cv::waitKey(0);
  }
  cv::Mat nI;
  cv::Mat zI;
  cv::Mat Iout;
  MatrixXf centroids;
  VectorXf concentrations;
  VectorXf proportions;

//  uint32_t T = 10;
//  for(uint32_t i=0; i<T; ++i)
  pRtDDPvMF->compute(reinterpret_cast<uint16_t*>(depth.data),
      depth.cols,depth.rows);
  Iout = pRtDDPvMF->overlaySeg(rgb,false,true);
  *dI = pRtDDPvMF->smoothDepthImg();
  //      cv::Mat Iout = pRtDDPvMF->overlaySeg(gray);
  if(display) {
    nI = pRtDDPvMF->normalsImg();
    zI = pRtDDPvMF->labelsImg(true);
    cv::waitKey(0);
  }
  centroids = pRtDDPvMF->GetCentroids();
  const VectorXu z = pRtDDPvMF->labels();
  uint32_t K = pRtDDPvMF->GetK();
  proportions = pRtDDPvMF->GetCounts();
  proportions /= proportions.sum();
  std::cout << "counts and proportions: " << std::endl;
  std::cout << pRtDDPvMF->GetCounts().transpose() << " normalized: "
    << proportions.transpose() << std::endl;
  concentrations = VectorXf::Zero(K);

  cv::Mat normals = pRtDDPvMF->normalsImgRaw();
  depth = pRtDDPvMF->smoothDepth();
  MatrixXf xSum = MatrixXf::Zero(3,K);
  for (uint32_t i=0; i<normals.cols; ++i)
    for (uint32_t j=0; j<normals.rows; ++j)
      if(z(normals.cols*j +i) < K) {
        Eigen::Map<Matrix<float,3,1> > q(&(normals.at<cv::Vec3f>(j,i)[0]));
        float d = depth.at<float>(j,i);
        float scale = d/cfg.f_d;
        xSum.col(z(normals.cols*j +i)) += q*scale;
      }
  std::cout<< pRtDDPvMF->GetxSums() << " vs weighted: " << xSum << std::endl;
  for (uint32_t k = 0; k < K; ++k) {
    concentrations(k) = (xSum.col(k)).norm();
    std::cout << xSum.col(k).transpose() << " || " <<  xSum.col(k).norm() << std::endl;
  }

  if(display)  {
    cv::imshow("dS",*dI);
    cv::imshow("normals",nI);
    cv::imshow("zI",zI);
    cv::imshow("out",Iout);
    cv::waitKey(0);
  }
  *dI = depth;

  for(uint32_t k=0; k<centroids.cols(); ++k) {
    vmfs->push_back(::bb::vMF<3>(centroids.col(k).cast<double>(),
          concentrations(k), proportions(k)));
  }
  return true;
};

pcl::PointCloud<pcl::PointXYZI>::Ptr DepthImageToPc(const cv::Mat& dI, const cv::Mat& gI, float f_d, const Eigen::Quaterniond q) {
  pcl::PointCloud<pcl::PointXYZI>::Ptr pc(new
      pcl::PointCloud<pcl::PointXYZI>(dI.cols, dI.rows));
  for (uint32_t i=0; i<dI.rows; ++i)
    for (uint32_t j=0; j<dI.cols; ++j) {
//      std::cout << dI.at<float>(i,j) << " ";
      pc->at(j,i).intensity = static_cast<float>(gI.at<uint8_t>(i,j))/255.;
//      std::cout << pc->at(j,i).intensity << " " << uint32_t(gI.at<uint8_t>(i,j)) << "; " ;
      pc->at(j,i).z = dI.at<float>(i,j);
      pc->at(j,i).x = (j-float(dI.cols-1.)*0.5) * pc->at(j,i).z / f_d;
      pc->at(j,i).y = (i-float(dI.rows-1.)*0.5) * pc->at(j,i).z / f_d;
      Eigen::Map<Matrix<float,3,1>> p(&(pc->at(j,i).x));
      p = q._transformVector(p.cast<double>()).cast<float>();
    }
  pc->is_dense = false;
  return pc;
}

int main(int argc, char** argv) {
  // Declare the supported options.
  po::options_description desc("Allowed options");
  desc.add_options()
    ("help,h", "produce help message")
    ("lambdaDeg,l", po::value<double>(), "lambda in degree for dp and ddp")
    ("in_a,a", po::value<string>(), "path to first input file")
    ("in_b,b", po::value<string>(), "path to second input file")
    ("out,o", po::value<string>(), "path to output file")
    ("display,d", "display results")
    ("B,B", po::value<int>(), "B for guided filter")
    ("eps", po::value<float>(), "eps for guided filter")
    ("f_d,f", po::value<float>(), "focal length of depth camera")
    ;

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

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

  CfgRtDDPvMF cfg;
  cfg.f_d = 540.;
  cfg.beta = 1e5;
  cfg.nFramesSurvive_ = 1; // DPvMFMM
  cfg.pathOut = std::string("../results/");
  double lambdaDeg = 93.;
  if(vm.count("lambdaDeg")) lambdaDeg = vm["lambdaDeg"].as<double>();

  cfg.lambdaFromDeg(lambdaDeg);
  cfg.QfromFrames2Survive(cfg.nFramesSurvive_);

  string pathA = "";
  string pathB = "";
  //  string mode = "";
  cudaPcl::CfgSmoothNormals cfgNormals;
  cfgNormals.f_d = 540.;
  cfgNormals.eps = 0.2*0.2;
  cfgNormals.B = 9;
  cfgNormals.compress = true;
  //  if(vm.count("mode")) mode = vm["mode"].as<string>();
  if(vm.count("in_a")) pathA = vm["in_a"].as<string>();
  if(vm.count("in_b")) pathB = vm["in_b"].as<string>();
  if(vm.count("eps")) cfgNormals.eps = vm["eps"].as<float>();
  if(vm.count("f_d")) cfgNormals.f_d = vm["f_d"].as<float>();
  if(vm.count("B")) cfgNormals.B = uint32_t( vm["B"].as<int>());

  findCudaDevice(argc,(const char**)argv);

  std::cout<<"rtDDPvMFmeans lambdaDeg="<<cfg.lambdaDeg_<<" beta="<<cfg.beta
    <<"nFramesSurvive="<<cfg.nFramesSurvive_<<std::endl;
  std::cout<<"output path: "<<cfg.pathOut<<std::endl;

  std::vector<bb::vMF<3>> vmfs_A;

  cv::Mat dIa, gIa;
  shared_ptr<RtDDPvMF> pRtDDPvMF_A;
  pRtDDPvMF_A = shared_ptr<RtDDPvMF>(new RtDDPvMF(cfg,cfgNormals));
  ComputevMFMMfromDepth(pRtDDPvMF_A, cfg, pathA, vm.count("display"), &dIa, &gIa, &vmfs_A);
  bb::vMFMM<3> vmf_mm_A(vmfs_A);

  cv::Mat dIb, gIb;
  std::vector<bb::vMF<3>> vmfs_B;
  shared_ptr<RtDDPvMF> pRtDDPvMF_B;
  pRtDDPvMF_B = shared_ptr<RtDDPvMF>(new RtDDPvMF(cfg,cfgNormals));
  ComputevMFMMfromDepth(pRtDDPvMF_B, cfg, pathB, vm.count("display"), &dIb, &gIb, &vmfs_B);
  bb::vMFMM<3> vmf_mm_B(vmfs_B);

  std::cout << "A:" << std::endl;
  for (uint32_t i=0; i<vmf_mm_A.GetK(); ++i)
    std::cout << vmf_mm_A.Get(i).GetMu().transpose()
      << " tau " << vmf_mm_A.Get(i).GetTau()
      << " pi " << vmf_mm_A.Get(i).GetPi() << std::endl;

  std::cout << "B:" << std::endl;
  for (uint32_t i=0; i<vmf_mm_B.GetK(); ++i)
    std::cout << vmf_mm_B.Get(i).GetMu().transpose()
      << " tau " << vmf_mm_B.Get(i).GetTau()
      << " pi " << vmf_mm_B.Get(i).GetPi() << std::endl;

  std::list<bb::NodeS3> nodes = bb::GenerateNotesThatTessellateS3();
  bb::LowerBoundS3 lower_bound(vmf_mm_A, vmf_mm_B);
  bb::UpperBoundIndepS3 upper_bound(vmf_mm_A, vmf_mm_B);
  bb::UpperBoundConvexS3 upper_bound_convexity(vmf_mm_A, vmf_mm_B);

  bb::BranchAndBound<bb::NodeS3> bb(lower_bound, upper_bound_convexity);
  double eps = 1e-4 / 180. * M_PI;
  uint32_t max_lvl = 60;
  uint32_t max_it = 300;
  bb::NodeS3 node_star = bb.Compute(nodes, eps, max_lvl, max_it);

  std::cout << "optimum quaternion: "
    << node_star.GetTetrahedron().GetCenter().transpose()
    << std::endl;

  Eigen::Quaterniond q0;
  Eigen::Quaterniond qStar = node_star.GetTetrahedron().GetCenterQuaternion();
  pcl::PointCloud<pcl::PointXYZI>::Ptr pcA(DepthImageToPc(dIa, gIa, cfg.f_d, q0));
  pcl::PointCloud<pcl::PointXYZI>::Ptr pcB(DepthImageToPc(dIb, gIb, cfg.f_d, qStar));
  std::cout << pcA->width << " " << pcA->height << std::endl;
  std::cout << pcB->width << " " << pcB->height << std::endl;

  boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
  viewer->initCameraParameters ();
//  int v1(0);
//  viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);
  viewer->setBackgroundColor (0, 0, 0);
//  viewer_->setBackgroundColor (255, 255, 255);
  viewer->addCoordinateSystem (1.0);
  pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZI> rgbA(pcA,"intensity");
  pcl::visualization::PointCloudColorHandlerGenericField<pcl::PointXYZI> rgbB(pcB,"intensity");
  viewer->addPointCloud<pcl::PointXYZI> (pcA, rgbA, "sample cloud1");
  viewer->addPointCloud<pcl::PointXYZI> (pcB, rgbB, "sample cloud2");

  while (!viewer->wasStopped ())
  {
    viewer->spinOnce (100);
    boost::this_thread::sleep (boost::posix_time::microseconds (100000));
  }

  if(vm.count("out"))
  {
    std::cout<<" writing out put to "<<std::endl
      <<(vm["out"].as<string>()+"_rgbLabels.png")<<std::endl
      <<vm["out"].as<string>()+"_cRmf.csv"<<std::endl;
//    cv::imwrite(vm["out"].as<string>()+"_rgbLabels.png",Iout);
//    ofstream out((vm["out"].as<string>()+"_cRmf.csv").data(),
//        ofstream::out);
//    for(uint32_t i=0; i<centroids.rows();++i)
//    {
//      for(uint32_t j=0; j<centroids.cols()-1;++j)
//        out << centroids(i,j)<<" ";
//      out << centroids(i,centroids.cols()-1)<<std::endl;
//    }
//    for(uint32_t i=0; i<concentrations.size()-1;++i)
//      out << concentrations(i) << " ";
//    out << concentrations(concentrations.size()-1) << std::endl;
//    for(uint32_t i=0; i<proportions.size()-1;++i)
//      out << proportions(i) << " ";
//    out << proportions(proportions.size()-1) << std::endl;
//    out.close();
  }
  std::cout<<cudaDeviceReset()<<std::endl;
  return (0);
}

max_stars_repo_name: jstraub/dpOptTrans

max_issues_repo_name: jstraub/dpOptTrans

max_forks_repo_name: jstraub/dpOptTrans


text:
// Copyright 2017, 2018 Peter Dimov.
// Distributed under the Boost Software License, Version 1.0.

#include <boost/hash2/fnv1a.hpp>
#include <boost/hash2/siphash.hpp>
#include <boost/hash2/xxhash.hpp>
#include <boost/hash2/spooky2.hpp>
#include <boost/hash2/md5.hpp>
#include <boost/hash2/sha1.hpp>
#include <boost/hash2/murmur3.hpp>
#include <boost/hash2/hash_append.hpp>
#include <boost/hash2/get_integral_result.hpp>
#include <boost/chrono.hpp>
#include <boost/core/demangle.hpp>
#include <typeinfo>
#include <cstddef>
#include <cstdio>
#include <string>
#include <limits>
#include <cmath>

template<class R, class H> void test_( int N )
{
    typedef boost::chrono::steady_clock clock_type;

    clock_type::time_point t1 = clock_type::now();

    double r = 0;

    H h;

    for( int i = 0; i < N; ++i )
    {
        using boost::hash2::get_integral_result;
        r += get_integral_result<R>( h.result() );
        r += 0.5;
    }

    clock_type::time_point t2 = clock_type::now();

    long long ms = boost::chrono::duration_cast<boost::chrono::milliseconds>( t2 - t1 ).count();

    r /= N;

    // Standard deviation of Bates distribution
    double stddev = static_cast<double>( std::numeric_limits<R>::max() ) - static_cast<double>( std::numeric_limits<R>::min() ) / std::sqrt( 12.0 * N );

    r /= stddev;

    printf( "%s: r=%e, %lld ms\n", boost::core::demangle( typeid(H).name() ).c_str(), r, ms );
}

template<class R> void test( int N )
{
    printf( "Integral result type `%s`:\n\n", boost::core::demangle( typeid(R).name() ).c_str() );

    test_<R, boost::hash2::fnv1a_32>( N );
    test_<R, boost::hash2::fnv1a_64>( N );
    test_<R, boost::hash2::murmur3_32>( N );
    test_<R, boost::hash2::murmur3_128>( N );
    test_<R, boost::hash2::xxhash_32>( N );
    test_<R, boost::hash2::xxhash_64>( N );
    test_<R, boost::hash2::spooky2_128>( N );
    test_<R, boost::hash2::siphash_32>( N );
    test_<R, boost::hash2::siphash_64>( N );
    test_<R, boost::hash2::md5_128>( N );
    test_<R, boost::hash2::sha1_160>( N );
    test_<R, boost::hash2::hmac_md5_128>( N );
    test_<R, boost::hash2::hmac_sha1_160>( N );

    puts( "" );
}

int main()
{
    int const N = 64 * 1024 * 1024;

    test<signed char>( N );
    test<short>( N );
    test<int>( N );
    test<long long>( N );
}


text:
#include <stdexcept>
#include <system_error>
#include <condition_variable>

#include <boost/range/adaptor/map.hpp>

#include <grpc++/grpc++.h>

#include "underworlds.grpc.pb.h"

#include "uwds.hpp"
#include "scene.hpp"
#include "nodes.hpp"

using grpc::Channel;
using grpc::Status;

using namespace std;
using namespace uwds;

Nodes::Nodes(Context& ctxt):_ctxt(ctxt),
                            _remote_communication_running(true),
                            _remote_communication_thread(&Nodes::_remote_communication, this)
{

}

Nodes::~Nodes() {
    _remote_communication_running = false;
    _remote_communication_thread.join();
}

ConstNodePtr Nodes::operator[](const string& id) const {

    if (!has(id)) {
        auto node = _fetch(id); // side-effect: adds the node to _nodes
        if (node) return node; // if !node, the at(id) will throw an out_of_range
    }

    return at(id);

}

NodePtr Nodes::operator[](const string& id) {

    if (!has(id)) {
        auto node = _fetch(id); // side-effect: adds the node to _nodes
        if (node) return node; // if !node, the at(id) will throw an out_of_range
    }

    return at(id);

}

set<weak_ptr<Node>> Nodes::from_name(const string& name) {

    set<weak_ptr<Node>> result;

    for (const auto& kv : _nodes) {
        if (kv.second->name() == name) result.insert(kv.second);
    }

    return result;
}

const shared_ptr<const Node> Nodes::_fetch(const string& id) const {

    cout << "Fetching node " << id << endl;
    underworlds::NodeInContext request;
    request.mutable_context()->set_client(_ctxt._myself.id());
    request.mutable_context()->set_world(_scene.lock()->_world);
    request.mutable_node()->set_id(id);

    underworlds::Node reply;

    grpc::ClientContext context;

    // The actual RPC.
    Status status = _ctxt._server->getNode(&context, request, &reply);

    // Act upon its status.
    if (status.ok()) {

        auto node = make_shared<Node>(Node::deserialize(reply, _scene));
        _nodes[node->id()] = node;
        return node;

    } else {
        throw system_error(error_code(status.error_code(),generic_category()), status.error_message());
    }

}

shared_ptr<Node> Nodes::_fetch(const string& id) {

    cout << "Fetching node " << id << endl;
    underworlds::NodeInContext request;
    request.mutable_context()->set_client(_ctxt._myself.id());
    request.mutable_context()->set_world(_scene.lock()->_world);
    request.mutable_node()->set_id(id);

    underworlds::Node reply;

    grpc::ClientContext context;

    // The actual RPC.
    Status status = _ctxt._server->getNode(&context, request, &reply);

    // Act upon its status.
    if (status.ok()) {

        auto node = make_shared<Node>(Node::deserialize(reply, _scene));
        _nodes[node->id()] = node;
        return node;

    } else {
        return nullptr;
    }

}

void Nodes::_add_node(shared_ptr<Node> node) {
    _nodes[node->id()] = node;
}

void Nodes::_remote_communication() {

    while(_remote_communication_running) {

        weak_ptr<const Node> node;
        auto res = _locally_dirty_nodes.pop_timed(node, chrono::milliseconds(25));

        if (res != cv_status::timeout) {
            cout << "Pushing node " << node << endl;
        }
    }
}


text: #include <boost/interprocess/sync/interprocess_mutex.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//=============================================================================================================
/**
 * @file     coregsettingsview.cpp
 * @author   Ruben Dörfel <doerfelruben@aol.com>
 * @since    0.1.6
 * @date     August, 2020
 *
 * @section  LICENSE
 *
 * Copyright (C) 2020, Ruben Dörfel. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
 *       following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
 *       the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of MNE-CPP authors 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.
 *
 *
 * @brief    CoregSettingsView class definition.
 *
 */

# define M_PI           3.14159265358979323846  /* pi */

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "coregsettingsview.h"
#include "ui_coregsettingsview.h"

#include <fiff/fiff_stream.h>
#include <fiff/fiff_coord_trans.h>

#include <iostream>

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QSettings>
#include <QDebug>
#include <QFileInfo>
#include <QFileDialog>
#include <QMessageBox>
#include <QVector3D>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

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

//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace DISPLIB;
using namespace Eigen;

//=============================================================================================================
// DEFINE GLOBAL METHODS
//=============================================================================================================

//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

CoregSettingsView::CoregSettingsView(const QString& sSettingsPath,
                                     QWidget *parent,
                                     Qt::WindowFlags f)
: AbstractView(parent, f)
, m_pUi(new Ui::CoregSettingsViewWidget)
{
    m_sSettingsPath = sSettingsPath;
    m_pUi->setupUi(this);

    loadSettings();

    // Connect File loading and saving
    connect(m_pUi->m_qPushButton_LoadFid, &QPushButton::released,
            this, &CoregSettingsView::onLoadFidFile);
    connect(m_pUi->m_qPushButton_StoreFid, &QPushButton::released,
            this, &CoregSettingsView::onStoreFidFile);
    connect(m_pUi->m_qPushButton_LoadDig, &QPushButton::released,
            this, &CoregSettingsView::onLoadDigFile);
    connect(m_pUi->m_qPushButton_LoadTrans, &QPushButton::released,
            this, &CoregSettingsView::onLoadTrans);
    connect(m_pUi->m_qPushButton_StoreTrans, &QPushButton::released,
            this, &CoregSettingsView::onStoreTrans);
    connect(m_pUi->m_qComboBox_BemItems, &QComboBox::currentTextChanged,
            this, &CoregSettingsView::changeSelectedBem, Qt::UniqueConnection);

    connect(m_pUi->m_qComboBox_BemItems, &QComboBox::currentTextChanged,
            this, &CoregSettingsView::changeSelectedBem, Qt::UniqueConnection);
    connect(m_pUi->m_qComboBox_BemItems, &QComboBox::currentTextChanged,
            this, &CoregSettingsView::changeSelectedBem, Qt::UniqueConnection);

    // Connect Fiducial Pickings
    connect(m_pUi->m_qCheckBox_PickFiducials, &QCheckBox::stateChanged,
            this, &CoregSettingsView::onPickingStatus);
    connect(m_pUi->m_qRadioButton_LPA, &QCheckBox::toggled,
            this, &CoregSettingsView::onFiducialChanged);
    connect(m_pUi->m_qRadioButton_NAS, &QCheckBox::toggled,
            this, &CoregSettingsView::onFiducialChanged);
    connect(m_pUi->m_qRadioButton_RPA, &QCheckBox::toggled,
            this, &CoregSettingsView::onFiducialChanged);
    onPickingStatus();

    // connect icp settings
    connect(m_pUi->m_qPushButton_FitFiducials, &QPushButton::released,
            this, &CoregSettingsView::onFitFiducials);
    connect(m_pUi->m_qPushButton_FitICP, &QPushButton::released,
            this, &CoregSettingsView::onFitICP);

    // connect adjustment settings
    connect(m_pUi->m_qDoubleSpinBox_ScalingX, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_ScalingY, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_ScalingZ, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_RotX, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_RotY, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_RotZ, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_TransX, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_TransY, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qDoubleSpinBox_TransZ, static_cast<void (QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
            this, &CoregSettingsView::transParamChanged);
    connect(m_pUi->m_qComboBox_ScalingMode, &QComboBox::currentTextChanged,
            this, &CoregSettingsView::onScalingModeChanges, Qt::UniqueConnection);
    onScalingModeChanges();

    // set button infos
    setToolTipInfo();
}

//=============================================================================================================

CoregSettingsView::~CoregSettingsView()
{
    saveSettings();
    delete m_pUi;
}

//=============================================================================================================

void CoregSettingsView::saveSettings()
{
    if(m_sSettingsPath.isEmpty()) {
        return;
    }

    // Save Settings
    QSettings settings("MNECPP");

}

//=============================================================================================================

void CoregSettingsView::loadSettings()
{
    if(m_sSettingsPath.isEmpty()) {
        return;
    }

    // Load Settings
    QSettings settings("MNECPP");

}

//=============================================================================================================

void CoregSettingsView::updateGuiMode(GuiMode mode)
{
    switch(mode) {
    case GuiMode::Clinical:
        break;
    default: // default is research mode
        break;
    }
}

//=============================================================================================================

void CoregSettingsView::updateProcessingMode(ProcessingMode mode)
{
    switch(mode) {
    case ProcessingMode::Offline:
        break;
    default: // default is realtime mode
        break;
    }
}

//=============================================================================================================

void CoregSettingsView::setToolTipInfo()
{
    m_pUi->m_qComboBox_BemItems->setToolTip("Select the Bem to use for coregistration. Load the Bem via: File->Open");
    m_pUi->m_qPushButton_LoadFid->setToolTip("Optional. Load the fiducials from file.");
    m_pUi->m_qPushButton_StoreFid->setToolTip("Store the fiducials to file.");
    m_pUi->m_qPushButton_LoadDig->setToolTip("Load the digitizers from file.");
    m_pUi->m_qPushButton_LoadTrans->setToolTip("Optional. Load the coordinate transformation from file.");
    m_pUi->m_qPushButton_StoreTrans->setToolTip("Store the coordinate transformation to file.");

    m_pUi->m_qDoubleSpinBox_WeightRpa->setToolTip("The weight for the RPA.");
    m_pUi->m_qDoubleSpinBox_WeightLpa->setToolTip("The weight for the LPA.");
    m_pUi->m_qDoubleSpinBox_WeightNas->setToolTip("The weight for the Nasion.");
    m_pUi->m_qDoubleSpinBox_WeightEEG->setToolTip("The weight for the EEG points.");
    m_pUi->m_qDoubleSpinBox_WeightHPI->setToolTip("The weight for the HPI points.");
    m_pUi->m_qDoubleSpinBox_WeightHSP->setToolTip("The weight for the HSP points. HSP = Head Shape Points");
    m_pUi->m_qCheckBox_HSP->setToolTip("Wheater to use the HSP points for the Coregistration. HSP = Head Shape Points");
    m_pUi->m_qCheckBox_EEG->setToolTip("Wheater to use the EEG points for the Coregistration.");
    m_pUi->m_qCheckBox_HPI->setToolTip("Wheater to use the HPI points for the Coregistration.");
    m_pUi->m_qSpinBox_MaxDist->setToolTip("The maximum allowed distace between head surface and digitizer cloud. This is used to discard outliers.");

    m_pUi->m_qCheckBox_AutoScale->setToolTip("Wheater to use automatic scaling for the fiducial alignment.");
    m_pUi->m_qDoubleSpinBox_Converge->setToolTip("The convergence limit for the ICP algorithm.");
    m_pUi->m_qSpinBox_MaxIter->setToolTip("The maximum number of iterations for the ICP algorithm.");
    m_pUi->m_qPushButton_FitFiducials->setToolTip("Fiducial alignment. Apply this step before using the ICP algorithm to get a better first guess.");
    m_pUi->m_qPushButton_FitICP->setToolTip("Co-Registration with the ICP algorithm.");
    m_pUi->m_qLabel_RMSE->setToolTip("The Root-Mean-Square-Error of the distance between closest point and digigizer in mm");
    m_pUi->m_qComboBox_ScalingMode->setToolTip("The scaling Mode. None - No scaling is applied; Uniform - same scaling for x,y,z-axis; 3-Axis - scaling on each axis.");
    m_pUi->m_qDoubleSpinBox_ScalingX->setToolTip("Scaling to apply in x-direction.");
    m_pUi->m_qDoubleSpinBox_ScalingY->setToolTip("Scaling to apply in y-direction.");
    m_pUi->m_qDoubleSpinBox_ScalingZ->setToolTip("Scaling to apply in z-direction.");

    m_pUi->m_qDoubleSpinBox_RotX->setToolTip("Rotation arround x-axis.");
    m_pUi->m_qDoubleSpinBox_RotY->setToolTip("Rotation arround y-axis.");
    m_pUi->m_qDoubleSpinBox_RotZ->setToolTip("Rotation arround z-axis.");

    m_pUi->m_qDoubleSpinBox_TransX->setToolTip("Translation to apply in x-direction.");
    m_pUi->m_qDoubleSpinBox_TransY->setToolTip("Translation to apply in y-direction.");
    m_pUi->m_qDoubleSpinBox_TransZ->setToolTip("Translation to apply in z-direction.");

}

//=============================================================================================================

void CoregSettingsView::onLoadFidFile()
{
    QString sFileName = QFileDialog::getOpenFileName(this,
                                                     tr("Select fiducials"),
                                                     QString(),
                                                     tr("Fif Files (*.fif)"));

    if (sFileName.isEmpty()) {
        return;
    } else {
        emit fidFileChanged(sFileName);
    }
}

//=============================================================================================================

void CoregSettingsView::onPickingStatus()
{
    bool bState = m_pUi->m_qCheckBox_PickFiducials->isChecked();
    if(bState) {
        m_pUi->m_qWidget_ResultFiducials->setEnabled(true);
        emit pickFiducials(true);
    } else {
        m_pUi->m_qWidget_ResultFiducials->setEnabled(false);
        emit pickFiducials(false);
    }
    return;
}

//=============================================================================================================

void CoregSettingsView::setFiducials(const QVector3D vecPosition)
{
    QVector3D vecTemp;
    // store incoming vector
    if(m_pUi->m_qRadioButton_LPA->isChecked()) {
        m_vecLPA = vecPosition;

        // step to next fiducial
        m_pUi->m_qRadioButton_NAS->setChecked(true);
        vecTemp = m_vecNAS;
        onFiducialChanged();
    } else if (m_pUi->m_qRadioButton_NAS->isChecked()) {
        m_vecNAS = vecPosition;

        // step to next fiducial
        m_pUi->m_qRadioButton_RPA->setChecked(true);
        vecTemp = m_vecRPA;
        onFiducialChanged();
    } else {
        m_vecRPA = vecPosition;

        // step to next fiducial
        m_pUi->m_qRadioButton_LPA->setChecked(true);
        vecTemp = m_vecLPA;
        onFiducialChanged();
    }

    // floor(vecAxialPosition[0]*100)/100 makes sure to only take 2 decimal positions
    m_pUi->m_qLineEdit_FidX->setText(QString::number(floor(vecTemp[0]*100)/100 * 1000) + " mm" );
    m_pUi->m_qLineEdit_FidY->setText(QString::number(floor(vecTemp[1]*100)/100 * 1000) + " mm" );
    m_pUi->m_qLineEdit_FidZ->setText(QString::number(floor(vecTemp[2]*100)/100 * 1000) + " mm" );
    return;
}

//=============================================================================================================

void CoregSettingsView::onFiducialChanged()
{
    QVector3D vecTemp;
    if(m_pUi->m_qRadioButton_LPA->isChecked()) {
        vecTemp = m_vecLPA;
        emit fiducialChanged(FIFFV_POINT_LPA);
    } else if (m_pUi->m_qRadioButton_NAS->isChecked()) {
        vecTemp = m_vecNAS;
        emit fiducialChanged(FIFFV_POINT_NASION);
    } else {
        vecTemp = m_vecRPA;
        emit fiducialChanged(FIFFV_POINT_RPA);
    }

    // floor(vecAxialPosition[0]*100)/100 makes sure to only take 2 decimal positions
    m_pUi->m_qLineEdit_FidX->setText(QString::number(floor(vecTemp[0]*100)/100 * 1000) + " mm" );
    m_pUi->m_qLineEdit_FidY->setText(QString::number(floor(vecTemp[1]*100)/100 * 1000) + " mm" );
    m_pUi->m_qLineEdit_FidZ->setText(QString::number(floor(vecTemp[2]*100)/100 * 1000) + " mm" );
    return;
}

//=============================================================================================================

void CoregSettingsView::onStoreFidFile()
{
    QString sFileName = QFileDialog::getSaveFileName(Q_NULLPTR,
                                                     tr("Save Fiducials"), "",
                                                     tr("Fif file (*fiducials.fif)"));

    if (sFileName.isEmpty()) {
        return;
    } else {
        emit fidStoreFileChanged(sFileName);
    }
}

//=============================================================================================================

void CoregSettingsView::onLoadDigFile()
{
    QString sFileName = QFileDialog::getOpenFileName(this,
                                                     tr("Select digitizer file"),
                                                     QString(),
                                                     tr("Fif Files (*.fif)"));

    if (sFileName.isEmpty()) {
        return;
    } else {
        emit digFileChanged(sFileName);
    }
}

//=============================================================================================================

void CoregSettingsView::onLoadTrans()
{
    QString sFileName = QFileDialog::getOpenFileName(this,
                                                     tr("Select Transformation"),
                                                     QString(),
                                                     tr("Fif Files (*-trans.fif)"));

    if (sFileName.isEmpty()) {
        return;
    } else {
        emit loadTrans(sFileName);
    }
}

//=============================================================================================================

void CoregSettingsView::onStoreTrans()
{
    QString sFileName = QFileDialog::getSaveFileName(Q_NULLPTR,
                                                     tr("Save Transformation"), "",
                                                     tr("Fif file (*-trans.fif)"));

    if (sFileName.isEmpty()) {
        return;
    } else{
        emit storeTrans(sFileName);
    }
}

//=============================================================================================================

int CoregSettingsView::getCurrentFiducial()
{
    // choose to use other points as well
    if(m_pUi->m_qRadioButton_LPA->isChecked()) {
        return FIFFV_POINT_LPA;
    } else if(m_pUi->m_qRadioButton_NAS->isChecked()) {
        return FIFFV_POINT_NASION;
    } else if(m_pUi->m_qRadioButton_RPA->isChecked()) {
        return FIFFV_POINT_RPA;
    };
    return -1;
}

//=============================================================================================================

int CoregSettingsView::getMaxIter()
{
    return m_pUi->m_qSpinBox_MaxIter->value();
}

//=============================================================================================================

float CoregSettingsView::getConvergence()
{
    return m_pUi->m_qDoubleSpinBox_Converge->value()/1000;
}

//=============================================================================================================

bool CoregSettingsView::getAutoScale()
{
    return m_pUi->m_qCheckBox_AutoScale->isChecked();
}

//=============================================================================================================

float CoregSettingsView::getWeightLPA()
{
    return m_pUi->m_qDoubleSpinBox_WeightLpa->text().toFloat();
}

//=============================================================================================================

float CoregSettingsView::getWeightRPA()
{
    return m_pUi->m_qDoubleSpinBox_WeightRpa->text().toFloat();
}

//=============================================================================================================

float CoregSettingsView::getWeightNAS()
{
    return m_pUi->m_qDoubleSpinBox_WeightNas->text().toFloat();
}

//=============================================================================================================

float CoregSettingsView::getWeightEEG()
{
    return m_pUi->m_qDoubleSpinBox_WeightEEG->text().toFloat();
}

//=============================================================================================================

float CoregSettingsView::getWeightHPI()
{
    return m_pUi->m_qDoubleSpinBox_WeightHPI->text().toFloat();
}

//=============================================================================================================

float CoregSettingsView::getWeightHSP()
{
    return m_pUi->m_qDoubleSpinBox_WeightHSP->text().toFloat();
}

//=============================================================================================================

float CoregSettingsView::getOmmitDistance()
{
    return static_cast<float>(m_pUi->m_qSpinBox_MaxDist->value())/1000.0;
}

//=============================================================================================================

QList<int> CoregSettingsView::getDigitizerCheckState()
{
    // always use cardinal points
    QList<int> lPicks({FIFFV_POINT_CARDINAL});

    // choose to use other points as well
    if(m_pUi->m_qCheckBox_EEG) {
        lPicks << FIFFV_POINT_EEG;
    }
    if(m_pUi->m_qCheckBox_HPI) {
        lPicks << FIFFV_POINT_HPI;
    }
    if(m_pUi->m_qCheckBox_HSP) {
        lPicks << FIFFV_POINT_EXTRA;
    }
    return lPicks;
}

//=============================================================================================================

void CoregSettingsView::clearSelectionBem()
{
    // block to avoid action loop
    QSignalBlocker blockerComboBox(m_pUi->m_qComboBox_BemItems);
    m_pUi->m_qComboBox_BemItems->clear();
}

//=============================================================================================================

void CoregSettingsView::addSelectionBem(const QString& sBemName)
{
    m_pUi->m_qComboBox_BemItems->addItem(sBemName);
}

//=============================================================================================================

QString CoregSettingsView::getCurrentSelectedBem()
{
    return m_pUi->m_qComboBox_BemItems->currentText();
}

//=============================================================================================================

void CoregSettingsView::setOmittedPoints(const int iN)
{
    m_pUi->m_qLabel_NOmitted->setText(QString::number(iN));
}

//=============================================================================================================

void CoregSettingsView::setRMSE(const float fRMSE)
{
    m_pUi->m_qLabel_RMSE->setText(QString::number(fRMSE*1000) + " mm");
}

//=============================================================================================================

void CoregSettingsView::setTransParams(const Vector3f& vecTrans,
                                       const Vector3f& vecRot,
                                       const Vector3f& vecScale)
{
    // block signals to avoid action loop
    QSignalBlocker blockerTransX(m_pUi->m_qDoubleSpinBox_TransX);
    QSignalBlocker blockerTransY(m_pUi->m_qDoubleSpinBox_TransY);
    QSignalBlocker blockerTransZ(m_pUi->m_qDoubleSpinBox_TransZ);
    QSignalBlocker blockerRotX(m_pUi->m_qDoubleSpinBox_RotX);
    QSignalBlocker blockerRotY(m_pUi->m_qDoubleSpinBox_RotY);
    QSignalBlocker blockerRotZ(m_pUi->m_qDoubleSpinBox_RotZ);
    QSignalBlocker blockerScaleX(m_pUi->m_qDoubleSpinBox_ScalingX);
    QSignalBlocker blockerScaleY(m_pUi->m_qDoubleSpinBox_ScalingY);
    QSignalBlocker blockerScaleZ(m_pUi->m_qDoubleSpinBox_ScalingZ);

    m_pUi->m_qDoubleSpinBox_TransX->setValue(vecTrans(0)*1000);
    m_pUi->m_qDoubleSpinBox_TransY->setValue(vecTrans(1)*1000);
    m_pUi->m_qDoubleSpinBox_TransZ->setValue(vecTrans(2)*1000);

    // Inverted order due to euler rotation
    m_pUi->m_qDoubleSpinBox_RotX->setValue(vecRot(2)*180/M_PI);
    m_pUi->m_qDoubleSpinBox_RotY->setValue(vecRot(1)*180/M_PI);
    m_pUi->m_qDoubleSpinBox_RotZ->setValue(vecRot(0)*180/M_PI);

    m_pUi->m_qDoubleSpinBox_ScalingX->setValue(vecScale(2));
    m_pUi->m_qDoubleSpinBox_ScalingY->setValue(vecScale(1));
    m_pUi->m_qDoubleSpinBox_ScalingZ->setValue(vecScale(0));
}

//=============================================================================================================

void CoregSettingsView::getTransParams(Vector3f& vecRot,
                                       Vector3f& vecTrans,
                                       Vector3f& vecScale)
{
    vecTrans(0) = m_pUi->m_qDoubleSpinBox_TransX->value()/1000.0;
    vecTrans(1) = m_pUi->m_qDoubleSpinBox_TransY->value()/1000.0;
    vecTrans(2) = m_pUi->m_qDoubleSpinBox_TransZ->value()/1000.0;

    // Inverted order due to euler rotation
    vecRot(2) = m_pUi->m_qDoubleSpinBox_RotX->value() * M_PI/180.0;
    vecRot(1) = m_pUi->m_qDoubleSpinBox_RotY->value() * M_PI/180.0;
    vecRot(0) = m_pUi->m_qDoubleSpinBox_RotZ->value() * M_PI/180.0;

    // apply different scaling modes
    if (m_pUi->m_qComboBox_ScalingMode->currentText() == "Uniform") {
        vecScale.fill(m_pUi->m_qDoubleSpinBox_ScalingX->value());
    } else if (m_pUi->m_qComboBox_ScalingMode->currentText() == "3-Axis") {
        vecScale(0) = m_pUi->m_qDoubleSpinBox_ScalingX->value();
        vecScale(1) = m_pUi->m_qDoubleSpinBox_ScalingY->value();
        vecScale(2) = m_pUi->m_qDoubleSpinBox_ScalingZ->value();
    } else {
        vecScale.fill(1);
    }

    return;
}

//=============================================================================================================

void CoregSettingsView::onScalingModeChanges()
{
    // apply different scaling modes
    if (m_pUi->m_qComboBox_ScalingMode->currentText() == "Uniform") {
        m_pUi->m_qDoubleSpinBox_ScalingX->setEnabled(true);
        m_pUi->m_qDoubleSpinBox_ScalingY->setEnabled(false);
        m_pUi->m_qDoubleSpinBox_ScalingZ->setEnabled(false);
    } else if (m_pUi->m_qComboBox_ScalingMode->currentText() == "3-Axis") {
        m_pUi->m_qDoubleSpinBox_ScalingX->setEnabled(true);
        m_pUi->m_qDoubleSpinBox_ScalingY->setEnabled(true);
        m_pUi->m_qDoubleSpinBox_ScalingZ->setEnabled(true);
    } else {
        m_pUi->m_qDoubleSpinBox_ScalingX->setEnabled(false);
        m_pUi->m_qDoubleSpinBox_ScalingY->setEnabled(false);
        m_pUi->m_qDoubleSpinBox_ScalingZ->setEnabled(false);
    }
    return;
}

//=============================================================================================================

void CoregSettingsView::onFitFiducials()
{
    m_pUi->m_qCheckBox_PickFiducials->setChecked(false);
    emit fitFiducials();
}

//=============================================================================================================

void CoregSettingsView::onFitICP()
{
    m_pUi->m_qCheckBox_PickFiducials->setChecked(false);
    emit fitICP();
}

max_stars_repo_name: ultrapre/mne-cpp

max_issues_repo_name: ultrapre/mne-cpp

max_forks_repo_name: ultrapre/mne-cpp


text:
/*
 * File: include/commonpp/net/http/detail/validators.hpp
 * Part of commonpp.
 *
 * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the
 * project root).
 *
 * Copyright (c) 2015 Thomas Sanchez.  All rights reserved.
 *
 */

#pragma once
#include <string>

#include <boost/algorithm/string.hpp>

#include <commonpp/core/LoggingInterface.hpp>
#include <commonpp/core/string/stringify.hpp>
#include <commonpp/net/http/URL.hpp>

#include "logger.hpp"

namespace commonpp
{
namespace net
{
namespace http
{
namespace detail
{

struct NullValidator
{
    template <typename K, typename V>
    static bool validate(const K&, const V&)
    {
        return true;
    }
};

struct NullSerializer
{
    static std::string key(std::string key)
    {
        return key;
    }

    static std::string value(std::string value)
    {
        return value;
    }
};

struct HeaderValidator
{
    static bool validate(const std::string& key, const std::string&)
    {
        if (boost::iequals(key, "Content-Length"))
        {
            LOG(http_net_logger, warning)
                << "Content-Length is handled by the library";
            return false;
        }
        return true;
    }
};

struct QuerySerializer
{
    static std::string key(const std::string& key)
    {
        return url_encode(key);
    }

    static std::string value(const std::string& value)
    {
        return url_encode(value);
    }
};

} // namespace detail
} // namespace http
} // namespace net
} // namespace commonpp