text:
#pragma once

#include <armadillo>
#include "estructura_capas_red.cpp"

using namespace std;
using namespace arma;

namespace ic {

enum class tipoInicializacion {
	conjuntosAleatorios,
	patronesAlAzar
};

ivec asignarPatrones(const mat& patrones,
                     vector<rowvec> centroides)
{
	const int nPatrones = patrones.n_rows;
	const int nConjuntos = centroides.size();
	ivec tablaPatronConjunto;
	tablaPatronConjunto.set_size(nPatrones);

	for (int i = 0; i < nPatrones; ++i) {
		vec distancias;
		distancias.set_size(nConjuntos);

		for (int j = 0; j < nConjuntos; ++j) {
			distancias(j) = norm(patrones.row(i) - centroides[j]);
		}

		const int conjuntoGanador = distancias.index_min();
		tablaPatronConjunto(i) = conjuntoGanador;
	}

	return tablaPatronConjunto;
}

// patrones es una matriz que tiene un patrón en cada fila.
// Cada columna representa una dimensión.

// La función devuelve un pair.
// pair.first es un vector de STL que contiene los centroides de cada conjunto.
// pair.second es un vec de Armadillo que contiene el sigma de cada conjunto.
pair<vector<rowvec>, vec>
entrenarRadialPorLotes(const mat& patrones,
                       int nConjuntos,
                       tipoInicializacion tipo = tipoInicializacion::conjuntosAleatorios,
                       double sigma = 0)
{
	const int nPatrones = patrones.n_rows;

	ivec tablaPatronConjunto;
	tablaPatronConjunto.set_size(nPatrones);
	vector<rowvec> centroides;
	centroides.resize(nConjuntos);

	// 1. Inicialización
	switch (tipo) {
	case tipoInicializacion::conjuntosAleatorios: {
		// Se forman los k conjuntos con patrones elegidos aleatoriamente.
		// Se asigna la misma cantidad de patrones a cada conjunto.
		const uvec indicesMezclados = shuffle(linspace<uvec>(0, nPatrones - 1, nPatrones));
		int conjunto = 0;

		for (int i = 0; i < nPatrones; ++i) {
			// Los patrones no asignados se agregan a cada conjunto,
			// en round-robin.
			tablaPatronConjunto(indicesMezclados(i)) = conjunto;

			if (conjunto + 1 < nConjuntos)
				++conjunto;
			else
				conjunto = 0;
		}

		break;
	}

	case tipoInicializacion::patronesAlAzar: {
		// Se le asignan un patrón aleatorio a cada centroide.
		const uvec indicesMezclados = shuffle(linspace<uvec>(0, nPatrones - 1, nPatrones));
		for (int i = 0; i < nConjuntos; ++i)
			centroides[i] = patrones.row(indicesMezclados(i));

		// Asignar los patrones al conjunto que tiene el centroide mas cercano
		tablaPatronConjunto = asignarPatrones(patrones, centroides);

		break;
	}
	}

	// Bucle del k-medias
	while (true) {
		// 2. Calcular los centroides de cada conjunto
		for (int i = 0; i < nConjuntos; ++i) {
			// Se extraen los indices de los patrones correspondientes al conjunto i
			const uvec indicesConjunto = find(tablaPatronConjunto == i);

			if (!indicesConjunto.empty()) {
				// Se calcula el centroide a lo largo de los patrones del conjunto.
				const rowvec centroide = mean(patrones.rows(indicesConjunto));
				centroides[i] = centroide;
			}
		}

		// 3. Asignar los patrones al conjunto que tiene el centroide mas cercano
		const ivec nuevaTabla = asignarPatrones(patrones, centroides);

		// Detectar si hubo reasignaciones de patrones a conjuntos.
		// Si no hubo reasignaciones, terminamos.
		if (any(tablaPatronConjunto != nuevaTabla))
			tablaPatronConjunto = nuevaTabla;
		else
			break;
	}

	// Terminó el bucle de los k-medias.
	// Ahora hay que calcular el sigma dentro de cada conjunto.
	vec sigmas;
	sigmas.set_size(nConjuntos);

	for (int i = 0; i < nConjuntos; ++i) {
		// Se extraen los indices de los patrones correspondientes al conjunto i
		const uvec indicesConjunto = find(tablaPatronConjunto == i);

		// Se calcula el desvio a lo largo de los patrones del conjunto,
		// a lo largo de las diferentes dimensiones, y luego se saca
		// el promedio de estos desvíos.
		if (!indicesConjunto.empty()) {
            if (sigma == 0) {
                const rowvec desvios = stddev(patrones.rows(indicesConjunto));
                const double desvio = mean(desvios.t());
                sigmas[i] = desvio;
            }
            else {
                //            sigmas[i] = 1; // Para el Iris
                //            sigmas[i] = 100; // Para el Merval
                sigmas(i) = sigma; // Para pronostico con tuplas de 3 series
            }
		}
	}

	// Solo vamos a devolver los centroides y sigmas para los que el conjunto
	// correspondiente no está vacío.
	vector<rowvec> centroidesFinales;
	vec sigmasFinales;

	for (int i = 0; i < nConjuntos; ++i) {
		const uvec indicesConjunto = find(tablaPatronConjunto == i);

		if (!indicesConjunto.empty()) {
			centroidesFinales.push_back(centroides[i]);
			sigmasFinales.insert_rows(sigmasFinales.n_elem, vec{sigmas(i)});
		}
	}

	return {centroidesFinales, sigmasFinales};
}

struct ParametrosRBF {
	EstructuraCapasRed estructuraRed;
	int nEpocas;
	double tasaAprendizaje;
	double inercia;
	double toleranciaError;
};

double gaussiana(const rowvec& patron,
                 const rowvec& centroide,
                 double sigma)
{
	// TODO: Corroborar si hay que elevar la distancia al cuadrado
	return exp(-pow(norm(patron - centroide), 2) / (2 * sigma * sigma));
}

rowvec salidaRadial(const rowvec& patron,
                    vector<rowvec> centroides,
                    vec sigmas)
{
	rowvec salida;
	salida.set_size(centroides.size());

	for (unsigned int i = 0; i < centroides.size(); ++i) {
		salida(i) = gaussiana(patron, centroides[i], sigmas(i));
	}

	return salida;
}

} // namespace ic

istream& operator>>(istream& is, ic::ParametrosRBF& parametros)
{
	// Formato:
	// estructura: [3 2 1]
	// n_epocas: 200
	// tasa_entrenamiento: 0.1
	// inercia: 0.5
	// parametro_sigmoidea: 1
	// tolerancia_error: 5
	string str;

	// No chequeamos si la etiqueta de cada línea está bien o no. No nos importa
	is >> str >> parametros.estructuraRed
	    >> str >> parametros.nEpocas
	    >> str >> parametros.tasaAprendizaje
	    >> str >> parametros.inercia
	    >> str >> parametros.toleranciaError;

	// Control básico de valores de parámetros
	if (parametros.estructuraRed.size() != 2
	    || parametros.nEpocas <= 0
	    || parametros.tasaAprendizaje <= 0
	    || parametros.toleranciaError <= 0)
		is.clear(ios::failbit);

	return is;
}


text:
/*
    Copyright 2013 Christian Henning
    Use, modification and distribution are subject to the Boost Software License,
    Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt).
*/

#ifndef BOOST_GIL_IO_UNIT_TEST_CMP_VIEW_HPP
#define BOOST_GIL_IO_UNIT_TEST_CMP_VIEW_HPP

////////////////////////////////////////////////////////////////////////////////////////
/// \file
/// \brief
/// \author Christian Henning
///
/// \date   2013 \n
///
////////////////////////////////////////////////////////////////////////////////////////

#include <boost/gil/gil_all.hpp>

template< typename View_1, typename View_2 >
void cmp_view( const View_1& v1
             , const View_2& v2
             )
{
    if( v1.dimensions() != v2.dimensions() )
    {
        throw std::runtime_error( "Images are not equal." );
    }

    typename View_1::x_coord_t width  = v1.width();
    typename View_1::y_coord_t height = v1.height();

    for( typename View_1::y_coord_t y = 0; y < height; ++y )
    {
        const typename View_1::x_iterator src_it = v1.row_begin( y );
        const typename View_2::x_iterator dst_it = v2.row_begin( y );

        for( typename View_1::x_coord_t x = 0; x < width; ++x )
        {
            if( *src_it != *dst_it )
            {
                throw std::runtime_error( "Images are not equal." );
            }
        }
    }
}

#endif // BOOST_GIL_IO_UNIT_TEST_CMP_VIEW_HPP

ext: hpp

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
#ifndef BOOST_TEXT_DETAIL_ITERATOR_HPP
#define BOOST_TEXT_DETAIL_ITERATOR_HPP

#include <boost/text/config.hpp>
#include <boost/stl_interfaces/reverse_iterator.hpp>

#include <iterator>

namespace boost { namespace text { inline namespace v1 { namespace detail {

    using reverse_char_iterator = stl_interfaces::reverse_iterator<char *>;
    using const_reverse_char_iterator =
        stl_interfaces::reverse_iterator<char const *>;

    struct const_repeated_chars_iterator : stl_interfaces::iterator_interface<
                                               const_repeated_chars_iterator,
                                               std::random_access_iterator_tag,
                                               char,
                                               char>
    {
        constexpr const_repeated_chars_iterator() noexcept :
            first_(nullptr),
            size_(0),
            n_(0)
        {}
        constexpr const_repeated_chars_iterator(
            char const * first,
            difference_type size,
            difference_type n) noexcept :
            first_(first),
            size_(size),
            n_(n)
        {}

        constexpr char operator*() const noexcept { return first_[n_ % size_]; }

        BOOST_TEXT_CXX14_CONSTEXPR const_repeated_chars_iterator &
        operator+=(std::ptrdiff_t n) noexcept
        {
            n_ += n;
            return *this;
        }

        friend constexpr std::ptrdiff_t operator-(
            const_repeated_chars_iterator lhs,
            const_repeated_chars_iterator rhs) noexcept
        {
            return lhs.n_ - rhs.n_;
        }

    private:
        char const * first_;
        std::ptrdiff_t size_;
        std::ptrdiff_t n_;
    };

    using const_reverse_repeated_chars_iterator =
        stl_interfaces::reverse_iterator<const_repeated_chars_iterator>;

}}}}

#endif

max_stars_repo_name: eightysquirrels/text

max_issues_repo_name: eightysquirrels/text

max_forks_repo_name: eightysquirrels/text


text:
/*
 * SetupBase.hpp
 *
 *  Created on: 12.02.2019
 *      Author: tomlucas
 */

#ifndef SETUPS_SETUPBASE_HPP_
#define SETUPS_SETUPBASE_HPP_

#define RUNNING (zavi::osg_viz::running)
#include <Eigen/Core>

#include <osg/ShapeDrawable>
#include <osg/PolygonMode>

#include "../OSG_VIZ/osg_viz.hpp"

#include "../Estimators/PseudoMeasurements.hpp"
#include "../OSG_VIZ/ErrorEllipse.hpp"
#include <ZaviConfig.hpp>
namespace zavi
::setups {

}
//setups

#endif /* SETUPS_SETUPBASE_HPP_ */


text:
/*=============================================================================
    Copyright (c) 2010 Tim Blechmann

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

#ifndef COMMON_HEAP_TESTS_HPP_INCLUDED
#define COMMON_HEAP_TESTS_HPP_INCLUDED

#include <algorithm>
#include <vector>

#include <boost/concept/assert.hpp>
#include <boost/concept_archetype.hpp>
#include <boost/shared_ptr.hpp>

#include <boost/heap/heap_concepts.hpp>

#ifdef BOOST_NO_CXX98_RANDOM_SHUFFLE
#include <cstdlib>
#include <iterator>

template<class RandomIt>
void random_shuffle(RandomIt first, RandomIt last)
{
    typedef typename std::iterator_traits<RandomIt>::difference_type difference_type;
    difference_type n = last - first;
    for (difference_type i = n-1; i > 0; --i) {
        difference_type j = std::rand() % (i + 1);
        if (j != i) {
		   using std::swap;
           swap(first[i], first[j]);
        }
    }
}

#else

using std::random_shuffle;

#endif

typedef boost::default_constructible_archetype<
        boost::less_than_comparable_archetype<
        boost::copy_constructible_archetype<
        boost::assignable_archetype<
        > > > > test_value_type;

typedef std::vector<int> test_data;
const int test_size = 32;

struct dummy_run
{
    static void run(void)
    {}
};

test_data make_test_data(int size, int offset = 0, int strive = 1)
{
    test_data ret;

    for (int i = 0; i != size; ++i)
        ret.push_back(i * strive + offset);
    return ret;
}

template <typename pri_queue, typename data_container>
void check_q(pri_queue & q, data_container const & expected)
{
    BOOST_REQUIRE_EQUAL(q.size(), expected.size());

    for (unsigned int i = 0; i != expected.size(); ++i)
    {
        BOOST_REQUIRE_EQUAL(q.size(), expected.size() - i);
        BOOST_REQUIRE_EQUAL(q.top(), expected[expected.size()-1-i]);
        q.pop();
    }

    BOOST_REQUIRE(q.empty());
}

template <typename pri_queue, typename data_container>
void fill_q(pri_queue & q, data_container const & data)
{
    for (unsigned int i = 0; i != data.size(); ++i)
        q.push(data[i]);
}

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <typename pri_queue, typename data_container>
void fill_emplace_q(pri_queue & q, data_container const & data)
{
    for (unsigned int i = 0; i != data.size(); ++i) {
        typename pri_queue::value_type value = data[i];
        q.emplace(std::move(value));
    }
}
#endif

template <typename pri_queue>
void pri_queue_test_sequential_push(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);
        fill_q(q, data);
        check_q(q, data);
    }
}

template <typename pri_queue>
void pri_queue_test_sequential_reverse_push(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);
        std::reverse(data.begin(), data.end());
        fill_q(q, data);
        std::reverse(data.begin(), data.end());
        check_q(q, data);
    }
}

template <typename pri_queue>
void pri_queue_test_emplace(void)
{
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);
        std::reverse(data.begin(), data.end());
        fill_emplace_q(q, data);
        std::reverse(data.begin(), data.end());
        check_q(q, data);
    }
#endif
}

template <typename pri_queue>
void pri_queue_test_random_push(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);

        test_data shuffled (data);
        random_shuffle(shuffled.begin(), shuffled.end());

        fill_q(q, shuffled);

        check_q(q, data);
    }
}

template <typename pri_queue>
void pri_queue_test_copyconstructor(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);
        fill_q(q, data);

        pri_queue r(q);

        check_q(r, data);
    }
}

template <typename pri_queue>
void pri_queue_test_assignment(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);
        fill_q(q, data);

        pri_queue r;
        r = q;

        check_q(r, data);
    }
}

template <typename pri_queue>
void pri_queue_test_moveconstructor(void)
{
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    pri_queue q;
    test_data data = make_test_data(test_size);
    fill_q(q, data);

    pri_queue r(std::move(q));

    check_q(r, data);
    BOOST_REQUIRE(q.empty());
#endif
}

template <typename pri_queue>
void pri_queue_test_move_assignment(void)
{
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    pri_queue q;
    test_data data = make_test_data(test_size);
    fill_q(q, data);

    pri_queue r;
    r = std::move(q);

    check_q(r, data);
    BOOST_REQUIRE(q.empty());
#endif
}

template <typename pri_queue>
void pri_queue_test_swap(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);
        test_data shuffled (data);
        random_shuffle(shuffled.begin(), shuffled.end());
        fill_q(q, shuffled);

        pri_queue r;

        q.swap(r);
        check_q(r, data);
        BOOST_REQUIRE(q.empty());
    }
}

template <typename pri_queue>
void pri_queue_test_iterators(void)
{
    for (int i = 0; i != test_size; ++i) {
        test_data data = make_test_data(test_size);
        test_data shuffled (data);
        random_shuffle(shuffled.begin(), shuffled.end());
        pri_queue q;
        BOOST_REQUIRE(q.begin() == q.end());
        fill_q(q, shuffled);

        for (unsigned long j = 0; j != data.size(); ++j)
            BOOST_REQUIRE(std::find(q.begin(), q.end(), data[j]) != q.end());

        for (unsigned long j = 0; j != data.size(); ++j)
            BOOST_REQUIRE(std::find(q.begin(), q.end(), data[j] + data.size()) == q.end());

        test_data data_from_queue(q.begin(), q.end());
        std::sort(data_from_queue.begin(), data_from_queue.end());

        BOOST_REQUIRE(data == data_from_queue);

        for (unsigned long j = 0; j != data.size(); ++j) {
            BOOST_REQUIRE_EQUAL((long)std::distance(q.begin(), q.end()), (long)(data.size() - j));
            q.pop();
        }
    }
}

template <typename pri_queue>
void pri_queue_test_ordered_iterators(void)
{
    for (int i = 0; i != test_size; ++i) {
        test_data data = make_test_data(i);
        test_data shuffled (data);
        random_shuffle(shuffled.begin(), shuffled.end());
        pri_queue q;
        BOOST_REQUIRE(q.ordered_begin() == q.ordered_end());
        fill_q(q, shuffled);

        test_data data_from_queue(q.ordered_begin(), q.ordered_end());
        std::reverse(data_from_queue.begin(), data_from_queue.end());
        BOOST_REQUIRE(data == data_from_queue);

        for (unsigned long j = 0; j != data.size(); ++j)
            BOOST_REQUIRE(std::find(q.ordered_begin(), q.ordered_end(), data[j]) != q.ordered_end());

        for (unsigned long j = 0; j != data.size(); ++j)
            BOOST_REQUIRE(std::find(q.ordered_begin(), q.ordered_end(), data[j] + data.size()) == q.ordered_end());

        for (unsigned long j = 0; j != data.size(); ++j) {
            BOOST_REQUIRE_EQUAL((long)std::distance(q.begin(), q.end()), (long)(data.size() - j));
            q.pop();
        }
    }
}

template <typename pri_queue>
void pri_queue_test_equality(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q, r;
        test_data data = make_test_data(i);
        fill_q(q, data);
        std::reverse(data.begin(), data.end());
        fill_q(r, data);

        BOOST_REQUIRE(r == q);
    }
}

template <typename pri_queue>
void pri_queue_test_inequality(void)
{
    for (int i = 1; i != test_size; ++i)
    {
        pri_queue q, r;
        test_data data = make_test_data(i);
        fill_q(q, data);
        data[0] = data.back() + 1;
        fill_q(r, data);

        BOOST_REQUIRE(r != q);
    }
}

template <typename pri_queue>
void pri_queue_test_less(void)
{
    for (int i = 1; i != test_size; ++i)
    {
        pri_queue q, r;
        test_data data = make_test_data(i);
        test_data r_data(data);
        r_data.pop_back();

        fill_q(q, data);
        fill_q(r, r_data);

        BOOST_REQUIRE(r < q);
    }

    for (int i = 1; i != test_size; ++i)
    {
        pri_queue q, r;
        test_data data = make_test_data(i);
        test_data r_data(data);
        data.push_back(data.back() + 1);

        fill_q(q, data);
        fill_q(r, r_data);

        BOOST_REQUIRE(r < q);
    }

    for (int i = 1; i != test_size; ++i)
    {
        pri_queue q, r;
        test_data data = make_test_data(i);
        test_data r_data(data);

        data.back() += 1;

        fill_q(q, data);
        fill_q(r, r_data);

        BOOST_REQUIRE(r < q);
    }

    for (int i = 1; i != test_size; ++i)
    {
        pri_queue q, r;
        test_data data = make_test_data(i);
        test_data r_data(data);

        r_data.front() -= 1;

        fill_q(q, data);
        fill_q(r, r_data);

        BOOST_REQUIRE(r < q);
    }

}

template <typename pri_queue>
void pri_queue_test_clear(void)
{
    for (int i = 0; i != test_size; ++i)
    {
        pri_queue q;
        test_data data = make_test_data(i);
        fill_q(q, data);

        q.clear();
        BOOST_REQUIRE(q.size() == 0);
        BOOST_REQUIRE(q.empty());
    }
}

template <typename pri_queue>
void run_concept_check(void)
{
    BOOST_CONCEPT_ASSERT((boost::heap::PriorityQueue<pri_queue>));
}

template <typename pri_queue>
void run_common_heap_tests(void)
{
    pri_queue_test_sequential_push<pri_queue>();
    pri_queue_test_sequential_reverse_push<pri_queue>();
    pri_queue_test_random_push<pri_queue>();
    pri_queue_test_equality<pri_queue>();
    pri_queue_test_inequality<pri_queue>();
    pri_queue_test_less<pri_queue>();
    pri_queue_test_clear<pri_queue>();

    pri_queue_test_emplace<pri_queue>();
}

template <typename pri_queue>
void run_iterator_heap_tests(void)
{
    pri_queue_test_iterators<pri_queue>();
}

template <typename pri_queue>
void run_copyable_heap_tests(void)
{
    pri_queue_test_copyconstructor <pri_queue>();
    pri_queue_test_assignment<pri_queue>();
    pri_queue_test_swap<pri_queue>();
}

template <typename pri_queue>
void run_moveable_heap_tests(void)
{
    pri_queue_test_moveconstructor <pri_queue>();
    pri_queue_test_move_assignment <pri_queue>();
}

template <typename pri_queue>
void run_reserve_heap_tests(void)
{
    test_data data = make_test_data(test_size);
    pri_queue q;
    q.reserve(6);
    fill_q(q, data);

    check_q(q, data);
}

template <typename pri_queue>
void run_leak_check_test(void)
{
    pri_queue q;
    q.push(boost::shared_ptr<int>(new int(0)));
}

struct less_with_T
{
    typedef int T;
    bool operator()(const int& a, const int& b) const
    {
        return a < b;
    }
};

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)

class thing {
public:
    thing( int a_, int b_, int c_ ) : a(a_), b(b_), c(c_) {}
public:
    int a;
    int b;
    int c;
};

class cmpthings {
public:
    bool operator() ( const thing& lhs, const thing& rhs ) const  {
        return lhs.a > rhs.a;
    }
    bool operator() ( const thing& lhs, const thing& rhs ) {
        return lhs.a > rhs.a;
    }
};

#define RUN_EMPLACE_TEST(HEAP_TYPE)                                     \
    do {                                                                \
        cmpthings ord;                                                  \
        boost::heap::HEAP_TYPE<thing, boost::heap::compare<cmpthings> > vpq(ord); \
        vpq.emplace(5, 6, 7);                                           \
        boost::heap::HEAP_TYPE<thing, boost::heap::compare<cmpthings>, boost::heap::stable<true> > vpq2(ord); \
        vpq2.emplace(5, 6, 7);                                          \
    } while(0);

#else
#define RUN_EMPLACE_TEST(HEAP_TYPE)
#endif

#endif // COMMON_HEAP_TESTS_HPP_INCLUDED


text: #include <boost/chrono/io/time_point_io.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (C) 2015, Pawel Tomulik <ptomulik@meil.pw.edu.pl>
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#define BOOST_TEST_MODULE test_txpl_ast_expr3

#include <txpl/test_config.hpp>
#include <boost/test/unit_test.hpp>

#ifndef TXPL_TEST_SKIP_AST_EXPR3

#include <txpl/ast/expr3.hpp>
#include <txpl/ast/unary_expr.hpp>
#include <txpl/ast/literal.hpp>
#include <txpl/ast/squash_heads.hpp>
#include <boost/variant/get.hpp>

BOOST_AUTO_TEST_CASE(test__expr3__unary_expr)
{
  using namespace txpl::ast;
  using boost::get;

  typedef const char* Iterator; // this should be token iterator in fact
  typedef unary_expr<Iterator>::operator_type operator_type;

  literal<Iterator> l2;
  literal<Iterator> l1;
  expr<Iterator, value<>, 3ul> e;
  unary_expr<Iterator> u1;
  unary_expr<Iterator> u2;
  {
    typedef basic_types<>::char_type char_type;
    l1.value = char_type{'a'};
    u1.operator_ = static_cast<operator_type>('+');
    squash_heads(u1.expr) = l1;
    e.expr = u1;
    char_type x = char_type{'z'};
    BOOST_CHECK_NO_THROW(u2 = get<unary_expr<Iterator> >(e.expr));
    BOOST_CHECK_NO_THROW(l2 = get<literal<Iterator> >(squash_heads(u2.expr)));
    BOOST_CHECK_NO_THROW(x = get<char_type>(l2.value));
    BOOST_CHECK_EQUAL(x, 'a');
  }
}

#else
BOOST_AUTO_TEST_CASE(dummy)
{
  using namespace txpl::ast;
  BOOST_CHECK(true);
}
#endif

ext: cpp

max_stars_repo_name: ptomulik/txpl

max_issues_repo_name: ptomulik/txpl

max_forks_repo_name: ptomulik/txpl


text:
/**
* Main file. Parse the parameters and start all the threads.
**/
#ifdef _WIN32
#include <conio.h>
#include <Windows.h>
#endif

#include <iostream>
#include "controller.h"

#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>

#include "../common/settings.h"

int main(int argc, char *argv[])
{
	if(argc<3)
	{
		std::cout << "Start with qstream [target_server url] [bandwidth in bytes/s]" << std::endl;
		return 0;
	}
	// Start input, tracker and controller thread and connect them to each other
	Input *input=new Input(argv[1]);
	boost::thread input_thread(boost::ref(*input));
	input_thread.yield();

	//90% of available bandwidth for exploitation
	Tracker *tracker=new Tracker(tracker_port, (unsigned int)((float)atoi(argv[2])*0.9f+0.5f));
	Controller *controller=new Controller(input, tracker, (unsigned int)atoi(argv[2]) );
	tracker->setController(controller);
	tracker->setInput(input);

	boost::thread tracker_thread(boost::ref(*tracker));
	tracker_thread.yield();

#ifdef _WIN32
	boost::thread controller_thread(boost::ref(*controller));
	controller_thread.yield();

	while(true)
	{
		Sleep(10);
		if( _kbhit()!=0 )
		{
			tracker->visualize_trees();
		}
	}
#else
	//Start the controller thread in the main thread
	(*controller)();
#endif
}

max_stars_repo_name: uroni/qstream

max_issues_repo_name: uroni/qstream

max_forks_repo_name: uroni/qstream


text:
#ifndef STAN_MATH_TEST_FIXTURE_ODE_FHO_HPP
#define STAN_MATH_TEST_FIXTURE_ODE_FHO_HPP

#include <stan/math/rev.hpp>
#include <boost/numeric/odeint.hpp>
#include <gtest/gtest.h>
#include <test/unit/math/rev/functor/test_fixture_ode.hpp>
#include <test/unit/util.hpp>
#include <iostream>
#include <sstream>
#include <vector>
#include <limits>
#include <string>

template <typename T>
struct forced_harm_osc_base {
  struct forced_harm_osc {
    template <typename T0, typename T1, typename T2>
    inline Eigen::Matrix<stan::return_type_t<T0, T1, T2>, -1, 1> operator()(
        const T0& t_in, const T1& y_in, std::ostream* msgs,
        const T2& theta) const {
      if (y_in.size() != 2)
        throw std::domain_error(
            "this function was called with inconsistent state");

      Eigen::Matrix<stan::return_type_t<T0, T1, T2>, -1, 1> res(2);
      res << y_in(1),
          -y_in(0) * sin(theta.at(1) * t_in) - theta.at(0) * y_in(1);

      return res;
    }
  };

  forced_harm_osc f;

  using T_t = std::tuple_element_t<2, T>;
  using T_y = std::tuple_element_t<3, T>;
  using T_p = std::tuple_element_t<4, T>;

  std::vector<T_p> theta;
  Eigen::Matrix<T_y, -1, 1> y0;
  double t0;
  std::vector<T_t> ts;
  double rtol;
  double atol;
  int max_num_step;

  forced_harm_osc_base()
      : theta{0.15, 0.25},
        y0(2),
        t0(0),
        ts(100),
        rtol(1.e-6),
        atol(1.e-8),
        max_num_step(100000) {
    y0 << 1.0, 0.0;
    for (size_t i = 0; i < ts.size(); ++i) {
      ts[i] = t0 + 0.1 * (i + 1);
    }
  }

  std::vector<T_t>& times() { return ts; }
  Eigen::Matrix<T_y, -1, 1> init() { return y0; }
  std::vector<T_p> param() { return theta; }
};

/**
 * Inheriting base type, various fixtures differs by the type of ODE
 * functor used in apply_solver calls, intended for
 * different kind of tests.
 *
 */
template <typename T>
struct forced_harm_osc_ts_test
    : public forced_harm_osc_base<T>,
      public ODETestFixture<forced_harm_osc_ts_test<T>> {
  forced_harm_osc_ts_test() : forced_harm_osc_base<T>() {}

  auto apply_solver() {
    std::tuple_element_t<0, T> sol;
    return sol(this->f, this->y0, this->t0, this->ts, nullptr, this->theta);
  }

  template <typename T1, typename T2>
  auto apply_solver(T1&& init, T2&& theta_in) {
    std::tuple_element_t<0, T> sol;
    return sol(this->f, init, this->t0, this->ts, nullptr, theta_in);
  }

  auto apply_solver_tol() {
    std::tuple_element_t<1, T> sol;
    return sol(this->f, this->y0, this->t0, this->ts, this->rtol, this->atol,
               this->max_num_step, nullptr, this->theta);
  }

  template <typename Ttime, typename T1>
  auto eval_rhs(const Ttime& t, const T1& y) {
    return this->f(t, y, nullptr, this->theta);
  }
};

#endif


text:
/**
 * Copyright (c) 2019 Melown Technologies SE
 *
 * 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.
 *
 * 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 HOLDER 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 semantic_gpkg_hpp_included_
#define semantic_gpkg_hpp_included_

#include <memory>

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

#include "math/extent.hpp"

#include "geo/srsdef.hpp"

#include "world.hpp"

namespace semantic {

/** Semantic world as a georeferenced dataset.
 *
 *  Write support only for GeoPackage format (GPKG).
 *  Read support for any OGR-supported dataset with matching format.
 */
class GeoPackage {
public:
    /** Opens existing (read-only) dataset.
     */
    GeoPackage(const boost::filesystem::path &path);

    /** Creates new dataset.
     */
    GeoPackage(const boost::filesystem::path &path
               , const geo::SrsDefinition &srs);

    ~GeoPackage();

    GeoPackage(GeoPackage&&) = default;
    GeoPackage& operator=(GeoPackage&&) = default;

    const geo::SrsDefinition& srs() const;

    /** Get dataset extents.
     */
    math::Extents2 extents() const;

    /** Add (sub) world to this dataset. Must be in write mode.
     */
    void add(const World &world);

    /** Query descriptor.
     */
    struct Query {
        Query() {};

        /** Extents. Defaults to whole world. Extents are in srs.
         */
        boost::optional<math::Extents2> extents;

        /** Query SRS. Defaults to dataset SRS.
         */
        boost::optional<geo::SrsDefinition> srs;

        /** Used when query SRS is different from dataset SRS.
         */
        std::size_t segmentsPerExtentEdge = 4;
    };

    World world(const Query &query = {}) const;

    /** Returns vertical extent matching query.
     */
    math::Extent verticalExtent(const Query &query = {}) const;

    struct Detail;

private:
    std::unique_ptr<Detail> detail_;
};

} // namespace semantic

#endif // semantic_gpkg_hpp_included_

max_stars_repo_name: melowntech/libsemantic

max_issues_repo_name: melowntech/libsemantic

max_forks_repo_name: melowntech/libsemantic


text:
#pragma once

#include "SimpleXML/xmlify/sxml_fusion.hpp"
#include "SimpleXML/xml_parse/sxml_parse_fusion.hpp"

#include <boost/optional.hpp>
#include <string>
#include <vector>
#include <iosfwd>

namespace AttenderTest
{
    namespace TestFile
    {
        struct HeaderEntry : public SXML::Parsable <HeaderEntry>
                           , public SXML::Xmlifiable <HeaderEntry>
        {
            SXML::Attribute <std::string> key;
            SXML::Content <std::string> value;
        };

        struct Header : public SXML::Parsable <Header>
                      , public SXML::Xmlifiable <Header>
        {
            std::vector <HeaderEntry> entry; // wanna put into plural, but would be weird in XML.
        };

        struct Request : public SXML::Parsable <Request>
                       , public SXML::Xmlifiable <Request>
        {
            boost::optional <std::string> method; // defaults to GET
            boost::optional <std::string> url; // defaults to /
            std::string protocol;
            std::string version;
            boost::optional <Header> header;
            boost::optional <std::string> body;
        };

        struct Response : public SXML::Parsable <Response>
                        , public SXML::Xmlifiable <Response>
        {
            boost::optional <std::string> body; // ignored if not set
            boost::optional <int> code; // ignored if not set
            boost::optional <Header> header; // ignored if not set
        };

        struct Test : public SXML::Parsable <Test>
                    , public SXML::Xmlifiable <Test>
        {
            Request request;
            Response response;
        };
    }

    TestFile::Test loadTestFromStream(std::istream& stream);
}

BOOST_FUSION_ADAPT_STRUCT
(
    AttenderTest::TestFile::HeaderEntry,
    key, value
)

BOOST_FUSION_ADAPT_STRUCT
(
    AttenderTest::TestFile::Header,
    entry
)

BOOST_FUSION_ADAPT_STRUCT
(
    AttenderTest::TestFile::Request,
    method, url, protocol, version, header, body
)

BOOST_FUSION_ADAPT_STRUCT
(
    AttenderTest::TestFile::Response,
    body, code, header
)

BOOST_FUSION_ADAPT_STRUCT
(
    AttenderTest::TestFile::Test,
    request, response
)


text:
//==================================================================================================
/*!

  Copyright 2016 NumScale SAS
  Copyright 2016 J.T Lapreste

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/constant/minexponent.hpp>
#include <boost/simd/pack.hpp>
#include <algorithm>

#include <simd_test.hpp>

STF_CASE_TPL( "Check Minexponent behavior"
            , (double)(float)
              (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t)
              (std::int8_t )(std::int16_t )(std::int32_t )(std::int64_t )
            )
{
  namespace bs =  boost::simd;
  using pack_t  = bs::pack<T>;
  using hpack_t = bs::pack<T,pack_t::static_size/2>;
  using dpack_t = bs::pack<T,pack_t::static_size*2>;

  auto are_correct = [](T e) { return e == bs::Minexponent<T>(); };

  auto pack  = bs::Minexponent<pack_t>();
  auto hpack = bs::Minexponent<hpack_t>();
  auto dpack = bs::Minexponent<dpack_t>();

  STF_EXPECT(( std::all_of(pack.begin() , pack.end(), are_correct ) ));
  STF_EXPECT(( std::all_of(hpack.begin(),hpack.end(), are_correct ) ));
  STF_EXPECT(( std::all_of(dpack.begin(),dpack.end(), are_correct ) ));
}


text:
#include <cmath>

#include <tf/transform_datatypes.h>

#include <urdf_parser/urdf_parser.h>

#include <boost/assign.hpp>
#include <ros/console.h>

#include <wm_mecanum_base_controller/wm_mecanum_base_controller.h>

#define PI 3.1415926535

namespace wm_mecanum_base_controller_ns
{
    WMMecanumBaseController::WMMecanumBaseController():
        command_struct_()
        ,dk_x_{1.0/4, -1.0/4, 1.0/4, -1.0/4}
        ,dk_y_{-1.0/4, -1.0/4, 1.0/4, 1.0/4}
        ,dk_yaw_{-1.0/(4*(self.alpha+self.beta)), -1.0/(4*(self.alpha+self.beta)), -1.0/(4*(self.alpha+self.beta)), -1.0/(4*(self.alpha+self.beta))}
        ,x_linear_speed_(0.0)
        ,y_linear_speed_(0.0)
        ,angular_speed_(0.0)
        ,lin_max_vel_(0.0)
        ,ang_max_vel_(0.0)
        ,robot_pose_x_(0.0)
        ,robot_pose_y_(0.0)
        ,robot_pose_orientation_(0.0)
        ,x_wheel_to_center_(0.0)
        ,y_wheel_to_center_(0.0)
        ,wheel_radius_(0.0)
        ,gb_ratio_(0.0)
        ,cmd_vel_timeout_(0.5)
        ,base_frame_id_("base_link")
        ,read_state_(false)
        ,i_front_left_vel_(0)
        ,i_front_right_vel_(1)
        ,i_rear_left_vel_(2)
        ,i_rear_right_vel_(3)
        ,enable_odom_tf_(false)
        {}

    bool WMMecanumBaseController::init(hardware_interface::VelocityJointInterface* hw,
      ros::NodeHandle& root_nh,
      ros::NodeHandle &controller_nh)
    {
        const std::string complete_ns = controller_nh.getNamespace();
        std::size_t id = complete_ns.find_last_of("/");
        name_ = complete_ns.substr(id + 1);

        // get parameters //
        // x axis distance between wheel axis and the robot's centroid
        controller_nh.param<double>("x_wheel_to_center", x_wheel_to_center_, 0.31 );

        // y axis distance between wheel radial median and the robot'S centroid
        controller_nh.param<double>("y_wheel_to_center", y_wheel_to_center_, 0.30 );

        // Wheel radius
        controller_nh.param<double>("wheel_radius", wheel_radius_, 0.075 );

        // Gear box ration
        controller_nh.param<double>("gb_ratio_", gb_ratio_, 15.0);

        // max linear velocity, in m/s
        controller_nh.param<double>("lin_max_vel", lin_max_vel_ , 1.0);

        // max angular velocity, in rad/s
        controller_nh.param<double>("ang_max_vel", ang_max_vel_, 1.0);

        // Get joint names from the parameter server
        controller_nh.param("front_left_wheel_joint", front_left_wheel_name_, front_left_wheel_name_);
        ROS_INFO_STREAM_NAMED(name_, "Front left wheel joint  is : " << front_left_wheel_name_);

        // Get joint names from the parameter server
        controller_nh.param("front_right_wheel_joint", front_right_wheel_name_, front_right_wheel_name_);
        ROS_INFO_STREAM_NAMED(name_, "Front right wheel joint  is : " << front_right_wheel_name_);

        // Get joint names from the parameter server
        controller_nh.param("rear_left_wheel_joint", rear_left_wheel_name_, rear_left_wheel_name_);
        ROS_INFO_STREAM_NAMED(name_, "rear left wheel joint  is : " << rear_left_wheel_name_);

        // Get joint names from the parameter server
        controller_nh.param("rear_right_wheel_joint", rear_right_wheel_name_, rear_right_wheel_name_);
        ROS_INFO_STREAM_NAMED(name_, "Front right wheel joint  is : " << rear_right_wheel_name_);

        // Odometry related:
        double publish_rate;
        controller_nh.param("publish_rate", publish_rate, 50.0);
        ROS_INFO_STREAM_NAMED(name_, "Controller state will be published at "
                               << publish_rate << "Hz.");
        publish_period_ = ros::Duration(1.0 / publish_rate);

        // Twist command related:
        controller_nh.param("cmd_vel_timeout", cmd_vel_timeout_, cmd_vel_timeout_);
        ROS_INFO_STREAM_NAMED(name_, "Velocity commands will be considered old if they are older than "
                              << cmd_vel_timeout_ << "s.");

        controller_nh.param("base_frame_id", base_frame_id_, base_frame_id_);
        ROS_INFO_STREAM_NAMED(name_, "Base frame_id set to " << base_frame_id_);

        controller_nh.param("enable_odom_tf", enable_odom_tf_, enable_odom_tf_);
        ROS_INFO_STREAM_NAMED(name_, "Publishing to tf is " << (enable_odom_tf_?"enabled":"disabled"));

        // Get handle of the joint
        front_left_wheel_joint_    = hw->getHandle(front_left_wheel_name_);  // throws on failure
        front_right_wheel_joint_    = hw->getHandle(front_right_wheel_name_);  // throws on failure
        rear_left_wheel_joint_    = hw->getHandle(rear_left_wheel_name_);  // throws on failure
        rear_right_wheel_joint_    = hw->getHandle(rear_right_wheel_name_);  // throws on failure

        // Start realtime state publisher
        controller_state_publisher_.reset(
        new realtime_tools::RealtimePublisher<control_msgs::JointControllerState>(controller_nh, "state", 1));

        setOdomPubFields(root_nh, controller_nh);

        sub_command_ = controller_nh.subscribe("cmd_vel", 1, &WMMecanumBaseController::cmdVelCallback, this);
        sub_joint_state_ = controller_nh.subscribe<sensor_msgs::JointState>("/joint_states", 1, &WMMecanumBaseController::jointStateCallback, this);

        // Initialize joint indexes according to joint names
        if (read_state_)
        {
            std::vector<std::string> joint_names = joint_state_.name;
            i_front_left_vel_ = find(joint_names.begin(), joint_names.end(), std::string(front_left_wheel_name_)) - joint_names.begin();
            i_front_right_vel_= find(joint_names.begin(), joint_names.end(), std::string(front_right_wheel_name_)) - joint_names.begin();
            i_rear_left_vel_  = find(joint_names.begin(), joint_names.end(), std::string(rear_left_wheel_name_)) - joint_names.begin();
            i_rear_right_vel_ = find(joint_names.begin(), joint_names.end(),std:: string(rear_right_wheel_name_)) - joint_names.begin();
            return 0;
        }
        else
        {
    	  ROS_INFO("Joint State not received");
    	  return -1;
        }

        return true;
    }

    // TODO update Odometry
    void WMMecanumBaseController::updateOdometry(const ros::Time& time)
    {
        // Compute Position

        // Linear speed of each wheel

        if(read_state_)
        {
            // x axis linear velocity
            // multiply by -1.0 because of wiring
            x_linear_speed_ = -1.0 / gb_ratio_ * wheel_radius_ * (dk_x_[0]*joint_state_.velocity[i_front_left_vel_] +
                                                                  dk_x_[1]*joint_state_.velocity[i_front_right_vel_] +
                                                                  dk_x_[2]*joint_state_.velocity[i_rear_left_vel_] +
                                                                  dk_x_[3]*joint_state_.velocity[i_rear_right_vel_]);

            // y axis linear velocity
            // multiply by -1.0 because of wiring
            y_linear_speed_ = -1.0 / gb_ratio_ * wheel_radius_ * (dk_y_[0]*joint_state_.velocity[i_front_left_vel_] +
                                                                  dk_y_[1]*joint_state_.velocity[i_front_right_vel_] +
                                                                  dk_y_[2]*joint_state_.velocity[i_rear_left_vel_] +
                                                                  dk_y_[3]*joint_state_.velocity[i_rear_right_vel_]);

            // yaw angular velocity
            // multiply by -1.0 because of wiring
            angular_speed_ = -1.0 / gb_ratio_ * wheel_radius_ * (dk_yaw_[0]*joint_state_.velocity[i_front_left_vel_] +
                                                       dk_yaw_[1]*joint_state_.velocity[i_front_right_vel_] +
                                                       dk_yaw_[2]*joint_state_.velocity[i_rear_left_vel_] +
                                                       dk_yaw_[3]*joint_state_.velocity[i_rear_right_vel_]);

            // update pose orientation
            // convert orientation to RPY
            // euler = [roll, pitch, yaw]
            euler = tf_conversions.transformations.euler_from_quaternion([self.pose.orientation.x,
                    self.pose.orientation.y,
                    self.pose.orientation.z,
                    self.pose.orientation.w])

        }
    }

    // Publish robot odometry tf and topic depending
    void WMMecanumBaseController::publishOdometry(const ros::Time& time)
    {
       // Populate odom message and publish
        if (odom_pub_->trylock())
        {
            // Compute and store orientation info
            const geometry_msgs::Quaternion orientation(
            tf::createQuaternionMsgFromYaw(robot_pose_orientation_));

              odom_pub_->msg_.header.stamp = time;
	          odom_pub_->msg_.pose.pose.position.x = robot_pose_x_;
	          odom_pub_->msg_.pose.pose.position.y =robot_pose_y_;
	          odom_pub_->msg_.pose.pose.orientation = orientation;
              odom_pub_->msg_.twist.twist.linear.x  = x_linear_speed_;
            odom_pub_->msg_.twist.twist.linear.y  = y_linear_speed_;
              odom_pub_->msg_.twist.twist.angular.z = angular_speed_;
              odom_pub_->unlockAndPublish();
        }

        // Publish tf /odom frame
        if (enable_odom_tf_ && tf_odom_pub_->trylock())
        {
            // Compute and store orientation info
            const geometry_msgs::Quaternion orientation(
                    tf::createQuaternionMsgFromYaw(robot_pose_orientation_));

            geometry_msgs::TransformStamped& odom_frame = tf_odom_pub_->msg_.transforms[0];
            odom_frame.header.stamp = time;
            odom_frame.transform.translation.x = robot_pose_x_;
            odom_frame.transform.translation.y = robot_pose_y_;
            odom_frame.transform.rotation = orientation;
            tf_odom_pub_->unlockAndPublish();
        }
    }

    void WMMecanumBaseController::update(const ros::Time& time, const ros::Duration& period)
    {
        // Update and Publish odometry message
        if (last_state_publish_time_ + publish_period_ < time)
        {
            last_state_publish_time_ += publish_period_;

            // TODO odometry desabled for now
            //updateOdometry(time);
            //publishOdometry(time);
        }

        // MOVE ROBOT
        // Retreive current velocity command and time step:
        Commands curr_cmd = *(command_.readFromRT());
        const double dt = (time - curr_cmd.stamp).toSec();
        double W[4] = {0.0, 0.0, 0.0, 0.0};

        // Brake if cmd_vel has timeout:
        if (dt > cmd_vel_timeout_)
        {
            brake();
        }

        // Limit velocities and accelerations:
        const double cmd_dt(period.toSec());

        //limiter_lin_.limit(curr_cmd.lin, last0_cmd_.lin, last1_cmd_.lin, cmd_dt);
        //limiter_ang_.limit(curr_cmd.ang, last0_cmd_.ang, last1_cmd_.ang, cmd_dt);

        last1_cmd_ = last0_cmd_;
        last0_cmd_ = curr_cmd;

        InverseKinematics(&curr_cmd, W);

        front_left_wheel_joint_.setCommand(W[0]);
        front_right_wheel_joint_.setCommand(W[1]);
        rear_left_wheel_joint_.setCommand(W[2]);
        rear_right_wheel_joint_.setCommand(W[3]);
    }

    void WMMecanumBaseController::InverseKinematics(struct Commands * cmd, double W[4])
    {
        // Reference:
        // Maulana, E.; Muslim, M.A.; Hendrayawan, V.,
        // "Inverse kinematic implementation of four-wheels mecanum drive mobile robot using stepper motors,"
        //  in Intelligent Technology and Its Applications (ISITIA), 2015 International Seminar on ,
        // vol., no., pp.51-56, 20-21 May 2015

        // linear velocity
        double vLinear = sqrt(pow(cmd->lin.x,2) + pow(cmd->lin.y,2));

        if(vLinear > lin_max_vel_)
        {
            vLinear = lin_max_vel_;
        }

        // movement orientation
        double Heading = atan2(cmd->lin.y, cmd->lin.x);

        // x axis linear velocity
        double x_vel = vLinear * cos(Heading);
        // y axis linear velocity
        double y_vel = vLinear * sin(Heading);

        // YAW axis rotational velocity
        double ang_vel = cmd->ang.z;

        if(pow(ang_vel,2) > pow(ang_max_vel_,2))
        {
            ang_vel =  ang_max_vel_ * ang_vel / abs(ang_vel);
        }

        // Inverse Kinematics matrix
        double J[4][3] = {{1, -1, -1*(x_wheel_to_center_ + y_wheel_to_center_)},
                          {1, 1, (x_wheel_to_center_ + y_wheel_to_center_)},
                          {1, 1, -1*(x_wheel_to_center_ + y_wheel_to_center_)},
                          {1, -1, (x_wheel_to_center_ + y_wheel_to_center_)}};

        // wheel angular velocity, in rad/s
        W[4] = {0.0, 0.0, 0.0, 0.0};

        // x y and angular velocity
        double V[3] = {x_vel, y_vel, ang_vel};

        // matrix multiplaction
        for(int i = 0; i < 3; i++)
        {
            for(int k = 0; k < 4; k++)
            {
                W[i] += J[i][k] * V[k];
            }
            W[i] = W[i] * 1/gb_ratio_ * 1/wheel_radius_;
        }
    }

    void WMMecanumBaseController::starting(const ros::Time& time)
    {
        brake();

        // Register starting time used to keep fixed rate
        last_state_publish_time_ = time;
    }

    void WMMecanumBaseController::stopping(const ros::Time& /*time*/)
    {
        brake();
    }

    void WMMecanumBaseController::brake()
    {
        front_left_wheel_joint_.setCommand(0.0);
        front_right_wheel_joint_.setCommand(0.0);
        front_left_wheel_joint_.setCommand(0.0);
        front_right_wheel_joint_.setCommand(0.0);
    }

    // Topic command
    void MWMecanumBaseController::jointStateCallback(const sensor_msgs::JointStateConstPtr &msg)
    {
        joint_state_ = *msg;
        read_state_ = true;
    }

    void WMMecanumBaseController::cmdVelCallback(const geometry_msgs::Twist& command)
    {
        command_struct_.ang.z   = command.angular.z;
        command_struct_.lin.x   = command.linear.x;
        command_struct_.stamp = ros::Time::now();
        command_.writeFromNonRT (command_struct_);

        ROS_DEBUG_STREAM_NAMED(name_,
                               "Added values to command. "
                               << "Ang: "   << command_struct_.ang.z << ", "
                               << "Lin: "   << command_struct_.lin.x << ", "
                               << "Stamp: " << command_struct_.stamp);
    }

    void WMMecanumBaseController::setOdomPubFields(ros::NodeHandle& root_nh, ros::NodeHandle& controller_nh)
    {
        // Get and check params for covariances
        XmlRpc::XmlRpcValue pose_cov_list;
        controller_nh.getParam("pose_covariance_diagonal", pose_cov_list);
        ROS_ASSERT(pose_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
        ROS_ASSERT(pose_cov_list.size() == 6);
        for (int i = 0; i < pose_cov_list.size(); ++i)
            ROS_ASSERT(pose_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);

        XmlRpc::XmlRpcValue twist_cov_list;
        controller_nh.getParam("twist_covariance_diagonal", twist_cov_list);
        ROS_ASSERT(twist_cov_list.getType() == XmlRpc::XmlRpcValue::TypeArray);
        ROS_ASSERT(twist_cov_list.size() == 6);
        for (int i = 0; i < twist_cov_list.size(); ++i)
            ROS_ASSERT(twist_cov_list[i].getType() == XmlRpc::XmlRpcValue::TypeDouble);

        // Setup odometry realtime publisher + odom message constant fields
        odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100));
        odom_pub_->msg_.header.frame_id = "odom";
        odom_pub_->msg_.child_frame_id = base_frame_id_;
        odom_pub_->msg_.pose.pose.position.z = 0;
        odom_pub_->msg_.pose.covariance = boost::assign::list_of
                (static_cast<double>(pose_cov_list[0])) (0)  (0)  (0)  (0)  (0)
                (0)  (static_cast<double>(pose_cov_list[1])) (0)  (0)  (0)  (0)
                (0)  (0)  (static_cast<double>(pose_cov_list[2])) (0)  (0)  (0)
                (0)  (0)  (0)  (static_cast<double>(pose_cov_list[3])) (0)  (0)
                (0)  (0)  (0)  (0)  (static_cast<double>(pose_cov_list[4])) (0)
                (0)  (0)  (0)  (0)  (0)  (static_cast<double>(pose_cov_list[5]));
        odom_pub_->msg_.twist.twist.linear.y  = 0;
        odom_pub_->msg_.twist.twist.linear.z  = 0;
        odom_pub_->msg_.twist.twist.angular.x = 0;
        odom_pub_->msg_.twist.twist.angular.y = 0;
        odom_pub_->msg_.twist.covariance = boost::assign::list_of
                (static_cast<double>(twist_cov_list[0])) (0)  (0)  (0)  (0)  (0)
                (0)  (static_cast<double>(twist_cov_list[1])) (0)  (0)  (0)  (0)
                (0)  (0)  (static_cast<double>(twist_cov_list[2])) (0)  (0)  (0)
                (0)  (0)  (0)  (static_cast<double>(twist_cov_list[3])) (0)  (0)
                (0)  (0)  (0)  (0)  (static_cast<double>(twist_cov_list[4])) (0)
                (0)  (0)  (0)  (0)  (0)  (static_cast<double>(twist_cov_list[5]));
        tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(root_nh, "/tf", 100));
        tf_odom_pub_->msg_.transforms.resize(1);
        tf_odom_pub_->msg_.transforms[0].transform.translation.z = 0.0;
        tf_odom_pub_->msg_.transforms[0].child_frame_id = base_frame_id_;
        tf_odom_pub_->msg_.transforms[0].header.frame_id = "odom";
    }

} // namespace wm_mecanum_base_controller_ns


text:
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------

Copyright (c) 2006-2015, assimp team
All rights reserved.

Redistribution and use of this software 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 assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.

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 ASSIMP_BUILD_NO_EXPORT
#ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER

#include "glTFExporter.h"
#include "Exceptional.h"
#include "StringComparison.h"
#include "ByteSwapper.h"

#include <assimp/version.h>
#include <assimp/IOSystem.hpp>
#include <assimp/Exporter.hpp>
#include <assimp/material.h>
#include <assimp/scene.h>

#include <boost/foreach.hpp>
#include <boost/scoped_ptr.hpp>

#define RAPIDJSON_HAS_STDSTRING 1
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>

#include "glTFFileData.h"
#include "glTFUtil.h"

using namespace rapidjson;

using namespace Assimp;
using namespace Assimp::glTF;

namespace Assimp {

    // ------------------------------------------------------------------------------------------------
    // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
    void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
    {
        // invoke the exporter
        glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
    }

    // ------------------------------------------------------------------------------------------------
    // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
    void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
    {
        // invoke the exporter
        glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
    }

} // end of namespace Assimp

class glTFSceneExporter
{
    typedef std::gltf_unordered_map<std::string, int> IdMap;

    Document& mDoc;
    MemoryPoolAllocator<>& mAl;

    const aiScene* mScene;

    std::string mRootNodeId;

    std::vector<std::string> mMeshIds;

    IdMap mUsedIds;

public:
    glTFSceneExporter(Document& doc, const aiScene* pScene)
        : mDoc(doc)
        , mAl(doc.GetAllocator())
        , mScene(pScene)
    {
        doc.SetObject();

        for (unsigned int i = 0; i < pScene->mNumAnimations; ++i) {

        }

        for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {

        }

        for (unsigned int i = 0; i < pScene->mNumLights; ++i) {

        }

        for (unsigned int i = 0; i < pScene->mNumLights; ++i) {

        }

        for (unsigned int i = 0; i < pScene->mNumMaterials; ++i) {

        }

        AddMeshes();

        for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {

        }

        AddNodes();

        CreateScene();
    }

    inline void Pushf(Value& val, float f)
    {
        val.PushBack(Value(f).Move(), mAl);
    }

    inline void SetMatrix(Value& v, const aiMatrix4x4& m)
    {
        v.SetArray();
        v.Reserve(16, mAl);

        Pushf(v, m.a1); Pushf(v, m.b1); Pushf(v, m.c1); Pushf(v, m.d1);
        Pushf(v, m.a2); Pushf(v, m.b2); Pushf(v, m.c2); Pushf(v, m.d2);
        Pushf(v, m.a3); Pushf(v, m.b3); Pushf(v, m.c3); Pushf(v, m.d3);
        Pushf(v, m.a4); Pushf(v, m.b4); Pushf(v, m.c4); Pushf(v, m.d4);
    }

    void AddMeshes()
    {
        if (mScene->mNumMeshes == 0) return;

        Value meshes;
        meshes.SetObject();

        mMeshIds.reserve(mScene->mNumMeshes);
        for (unsigned int i = 0; i < mScene->mNumMeshes; ++i) {
            aiMesh* m = mScene->mMeshes[i];
            std::string meshId = FindID(m->mName, "mesh");
            mMeshIds.push_back(meshId);

            Value mesh;
            mesh.SetObject();
            {
                Value primitives;
                primitives.SetObject();

                mesh.AddMember("primitives", primitives, mAl);
            }

            meshes.AddMember(StringRef(mMeshIds.back()), mesh, mAl);
        }

        mDoc.AddMember("meshes", meshes, mAl);
    }

    void AddNodes()
    {
        if (!mScene->mRootNode) return;

        Value nodes;
        nodes.SetObject();

        mRootNodeId = AddNode(nodes, mScene->mRootNode);

        mDoc.AddMember("nodes", nodes, mAl);
    }

    std::string AddNode(Value& nodes, const aiNode* n)
    {
        std::string nodeId = FindID(n->mName, "node");

        Value node;
        node.SetObject();

        if (!n->mTransformation.IsIdentity()) {
            Value matrix;
            SetMatrix(matrix, n->mTransformation);
            node.AddMember("matrix", matrix, mAl);
        }

        if (n->mNumMeshes > 0) {
            Value meshes;
            meshes.SetArray();
            for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
                meshes.PushBack(StringRef(mMeshIds[n->mMeshes[i]]), mAl);
            }
            node.AddMember("meshes", meshes, mAl);
        }

        if (n->mNumChildren > 0) {
            Value children;
            children.SetArray();
            for (unsigned int i = 0; i < n->mNumChildren; ++i) {
                std::string id = AddNode(nodes, n->mChildren[i]);
                children.PushBack(Value(id, mAl).Move(), mAl);
            }
            node.AddMember("children", children, mAl);
        }

        nodes.AddMember(Value(nodeId, mAl).Move(), node, mAl);

        return nodeId;
    }

    void CreateScene()
    {
        const char* sceneName = "defaultScene";

        mDoc.AddMember("scene", Value(sceneName, mAl).Move(), mAl);

        Value scenes;
        scenes.SetObject();
        {
            Value scene;
            scene.SetObject();
            {
                Value nodes;
                nodes.SetArray();

                if (!mRootNodeId.empty()) {
                    nodes.PushBack(StringRef(mRootNodeId), mAl);
                }

                scene.AddMember("nodes", nodes, mAl);
            }
            scenes.AddMember(Value(sceneName, mAl).Move(), scene, mAl);
        }
        mDoc.AddMember("scenes", scenes, mAl);
    }

    std::string FindID(const aiString& str, const char* suffix)
    {
        std::string id = str.C_Str();

        IdMap::iterator it;

        do {
            if (!id.empty()) {
                it = mUsedIds.find(id);
                if (it == mUsedIds.end()) break;

                id += "-";
            }

            id += suffix;

            it = mUsedIds.find(id);
            if (it == mUsedIds.end()) break;

            char buffer[256];
            int offset = sprintf(buffer, "%s-", id.c_str());
            for (int i = 0; it == mUsedIds.end(); ++i) {
                ASSIMP_itoa10(buffer + offset, sizeof(buffer), i);

                id = buffer;
                it = mUsedIds.find(id);
            }
        } while (false); // fake loop to allow using "break"

        mUsedIds[id] = true;
        return id;
    }
};

glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
                           const ExportProperties* pProperties, bool isBinary)
    : mFilename(filename)
    , mIOSystem(pIOSystem)
    , mScene(pScene)
    , mProperties(pProperties)
    , mIsBinary(isBinary)
{
    boost::scoped_ptr<IOStream> outfile(pIOSystem->Open(mFilename, "wt"));
    if (outfile == 0) {
        throw DeadlyExportError("Could not open output file: " + std::string(mFilename));
    }

    if (isBinary) {
        // we will write the header later, skip its size
        outfile->Seek(sizeof(GLB_Header), aiOrigin_SET);
    }

    Document doc;
    StringBuffer docBuffer;
    {
        glTFSceneExporter exportScene(doc, mScene);

        bool pretty = true;
        if (!isBinary && pretty) {
            PrettyWriter<StringBuffer> writer(docBuffer);
            doc.Accept(writer);
        }
        else {
            Writer<StringBuffer> writer(docBuffer);
            doc.Accept(writer);
        }
    }

    if (outfile->Write(docBuffer.GetString(), docBuffer.GetSize(), 1) != 1) {
        throw DeadlyExportError("Failed to write scene data!");
    }

    if (isBinary) {
        WriteBinaryData(outfile.get(), docBuffer.GetSize());
    }
}

void glTFExporter::WriteBinaryData(IOStream* outfile, std::size_t sceneLength)
{
    //
    // write the body data
    //

    if (!mBodyData.empty()) {
        std::size_t bodyOffset = sizeof(GLB_Header) + sceneLength;
        bodyOffset = (bodyOffset + 3) & ~3; // Round up to next multiple of 4

        outfile->Seek(bodyOffset, aiOrigin_SET);

        if (outfile->Write(&mBodyData[0], mBodyData.size(), 1) != 1) {
            throw DeadlyExportError("Failed to write body data!");
        }
    }

    //
    // write the header
    //

    outfile->Seek(0, aiOrigin_SET);

    GLB_Header header;
    memcpy(header.magic, AI_GLB_MAGIC_NUMBER, sizeof(header.magic));

    header.version = 1;
    AI_SWAP4(header.version);

    header.length = sizeof(header) + sceneLength + mBodyData.size();
    AI_SWAP4(header.length);

    header.sceneLength = sceneLength;
    AI_SWAP4(header.sceneLength);

    header.sceneFormat = SceneFormat_JSON;
    AI_SWAP4(header.sceneFormat);

    if (outfile->Write(&header, sizeof(header), 1) != 1) {
        throw DeadlyExportError("Failed to write the header!");
    }
}

#endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
#endif // ASSIMP_BUILD_NO_EXPORT


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// QuickBook Example

// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.

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

//[crosses
//` Checks if two geometries crosses

#include <iostream>

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

namespace bg = boost::geometry; /*< Convenient namespace alias >*/

int main()
{
    // Checks if the two geometries (here, a polygon and a linestring) crosses or not.
    bg::model::polygon<bg::model::d2::point_xy<double> > poly;
    bg::read_wkt("POLYGON((0 0,0 3,3 3,3 0,0 0))", poly);
    bg::model::linestring<bg::model::d2::point_xy<double> > line1;
    bg::read_wkt("LINESTRING(1 1,2 2,4 4)", line1);
    bool check_crosses = bg::crosses(poly, line1);
    if (check_crosses) {
         std::cout << "Crosses: Yes" << std::endl;
    } else {
        std::cout << "Crosses: No" << std::endl;
    }

    // Edge case: linestring just touches the polygon but doesn't crosses it.
    bg::model::linestring<bg::model::d2::point_xy<double> > line2;
    bg::read_wkt("LINESTRING(1 1,1 2,1 3)", line2);
    check_crosses = bg::crosses(poly, line2);
    if (check_crosses) {
         std::cout << "Crosses: Yes" << std::endl;
    } else {
        std::cout << "Crosses: No" << std::endl;
    }

    return 0;
}

//]

//[crosses_output
/*`
Output:
[pre
Crosses: Yes
Crosses: No

[$img/algorithms/crosses.png]

]
*/
//]

max_stars_repo_name: jkerkela/geometry

max_issues_repo_name: jkerkela/geometry


text:
#include <string>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <cstdlib>
#include <boost/filesystem.hpp>
#include <boost/timer.hpp>
#include <boost/foreach.hpp>
#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/program_options.hpp>
#include <boost/make_shared.hpp>
#include <opencv2/opencv.hpp>

#include "kinect_view.h"
#include "kinect_calibration.h"

using namespace kinect_merge;
using kinect_capture::CHerreraCalibration;
namespace po = boost::program_options;

#ifdef DEBUG
void print_matrix(const cv::Mat &m) {
    for(int i = 0; i < m.rows; i++) {
        for(int j = 0; j < m.cols; j++) {
            std::cout << m.at<float>(i, j) << " ";
        }
        std::cout << std::endl;
    }
}
#endif

static void print_usage(std::string program_name, po::options_description desc) {
    std::cerr << "Usage: " << program_name << " [options] capture_dir output_file" << std::endl;
    std::cerr << desc << std::endl;
}

static void parse_options(int argc, const char **argv, po::variables_map &vm) {
    po::options_description desc;
    desc.add_options()
        ("help,h",              "display this help and exit")
        ("connectivity,c",      boost::program_options::value<std::string>(),
                                "OpenCV YAML file containing the view connectivity matrix C")
        ("debug,d",             "output debug files")
        ("covscalexy",          boost::program_options::value<float>()->default_value(DEFAULT_COVARIANCE_SCALE_XY),
                                "scale factor for measurement x- and y-variances")
        ("covscalez",           boost::program_options::value<float>()->default_value(DEFAULT_COVARIANCE_SCALE_Z),
                                "scale factor for measurement z-variance")
        ("capture_dir",         "directory to read the capture data from")
        ("output_file",         "PLY file to write the resulting point cloud to");

    po::positional_options_description pd;
    pd.add("capture_dir", 1);
    pd.add("output_file", 1);

    po::parsed_options parsed = po::basic_command_line_parser<char>(argc, argv).options(desc)
                                                                               .allow_unregistered()
                                                                               .positional(pd)
                                                                               .run();
    po::store(parsed, vm);
    po::notify(vm);

    if(vm.count("help") || !vm.count("capture_dir") || !vm.count("output_file")) {
        print_usage(argv[0], desc);
        exit(0);
    }
}

// Load all disparity, extrinsic and color image files for views from the given directory.
//
// The files must be named 0000-d.pgm, 0000-p.yml, 0000-r.jpg, 0001-d.pgm etc.
// The color image file can alternatively be named 0000-c1.ppm.
static void load_views(const std::string &capture_dir,
                       boost::ptr_vector<CView> &views,
                       float covariance_scale_xy,
                       float covariance_scale_z,
                       CKinectCalibration &calibration) {
    int view_idx = 0;
    while(true) {
        std::ostringstream view_file_base_stream;
        view_file_base_stream << capture_dir;
        view_file_base_stream << "/";
        view_file_base_stream << std::setfill('0') << std::setw(4) << view_idx;
        std::string view_file_base = view_file_base_stream.str();

        // The color file can be in JPG or PPM format.

        std::string disparity_file = view_file_base + "-d.pgm";
        std::string extrinsic_file = view_file_base + "-p.yml";
        std::string jpg_color_file = view_file_base + "-r.jpg";
        std::string ppm_color_file = view_file_base + "-c1.ppm";

        std::string color_file;
        if(boost::filesystem::exists(jpg_color_file)) {
            color_file = jpg_color_file;
        } else if(boost::filesystem::exists(ppm_color_file)) {
            color_file = ppm_color_file;
        }

        if(!boost::filesystem::exists(disparity_file) ||
           !boost::filesystem::exists(extrinsic_file) ||
           color_file.empty()) {
            break;
        }

        views.push_back(new CView(extrinsic_file,
                                  disparity_file,
                                  color_file,
                                  covariance_scale_xy,
                                  covariance_scale_z,
                                  calibration));
        std::cout << "." << std::flush; // Progress output
        view_idx++;
    }
}

// Output a percentage indicating the progress of a process.
static void print_progress(int current_index, int num_indices) {
    std::cout << (int)((float)current_index / num_indices * 100) << " %" << std::flush << "\r";
}

// Write a point cloud from a vector into a file in the PLY ASCII format.
template<typename point_ptr>
static void output_point_cloud(const std::vector<point_ptr> &point_cloud, const std::string &filename) {
    std::cout << "Writing point cloud to " << filename << std::endl;

    std::ofstream ply_file(filename.c_str());

    if(!ply_file) {
        std::cerr << "Error opening output file" << std::endl;
        exit(1);
    }

    ply_file << "ply" << std::endl;
    ply_file << "format ascii 1.0" << std::endl;
    ply_file << "element vertex " << point_cloud.size() << std::endl;
    ply_file << "property float x" << std::endl;
    ply_file << "property float y" << std::endl;
    ply_file << "property float z" << std::endl;
    ply_file << "property uchar red" << std::endl;
    ply_file << "property uchar green" << std::endl;
    ply_file << "property uchar blue" << std::endl;
    ply_file << "end_header" << std::endl;
    for(unsigned int i = 0; i < point_cloud.size(); i++) {
        if((i & 0xffff) == 0) {
            print_progress(i, point_cloud.size());
        }

        point_ptr p = point_cloud[i];
        cv::Matx<unsigned char, 3, 1> color = p->get_color();
        ply_file << p->pos(0) << " " << p->pos(1) << " " << p->pos(2) << " ";
        ply_file << static_cast<int>(color(2)) << " "
                 << static_cast<int>(color(1)) << " "
                 << static_cast<int>(color(0)) << std::endl;

        if(!ply_file) {
            std::cerr << "Error writing point cloud" << std::endl;
            exit(2);
        }
    }
    ply_file.close();
}

// Statistics functions

template<typename T>
static float sum(const std::vector<T> &values) {
    return std::accumulate(values.begin(), values.end(), 0.0);
}

template<typename T>
static float average(const std::vector<T> &values) {
    return sum(values) / values.size();
}

template<typename T>
static float minimum(const std::vector<T> &values) {
    return *std::min_element(values.begin(), values.end());
}

template<typename T>
static float maximum(const std::vector<T> &values) {
    return *std::max_element(values.begin(), values.end());
}

int main(int argc, const char **argv) {
    po::variables_map vm;
    parse_options(argc, argv, vm);

    bool debug = vm.count("debug");
    std::string capture_dir = vm["capture_dir"].as<std::string>();
    std::string output_file = vm["output_file"].as<std::string>();
    float covariance_scale_xy = vm["covscalexy"].as<float>();
    float covariance_scale_z = vm["covscalez"].as<float>();

    // Statistics variables
    float time_loading_stat;
    std::vector<float> time_merging_stats;
    std::vector<float> num_missing_stats;
    std::vector<float> num_added_stats;

    if(!boost::filesystem::exists("calib.yml")) {
        std::cerr << "calib.yml does not exist" << std::endl;
        exit(9);
    }

    CHerreraCalibration calibration;
    calibration.load("calib.yml");

    boost::ptr_vector<CView> views;
    std::cout << "Loading views" << std::flush;
    boost::timer timer;
    load_views(capture_dir, views, covariance_scale_xy, covariance_scale_z, calibration);
    time_loading_stat = timer.elapsed();
    std::cout << views.size() << " views" << std::endl;

    unsigned int first_view = 0;
    unsigned int last_view = views.size();

    if(debug) {
        // Output all the points overlayed in one cloud.
        std::vector<CPoint::const_ptr> overlayed_point_cloud;
        std::cout << "Overlaying point clouds" << std::endl;

        for(unsigned int i = first_view; i < last_view; i++) {
            print_progress(i, views.size());
            views[i].insert_into_point_cloud(overlayed_point_cloud);
        }
        output_point_cloud<CPoint::const_ptr>(overlayed_point_cloud, "overlayed.ply");
    }

    // Get a view connectivity matrix.
    cv::Mat view_connectivity;
    if(vm.count("connectivity")) {
        std::string connectivity_file = vm["connectivity"].as<std::string>();

        if(!boost::filesystem::exists(connectivity_file)) {
            std::cerr << "Connectivity file " << connectivity_file << " does not exist" << std::endl;
            exit(8);
        }

        try {
            cv::FileStorage fs(connectivity_file, cv::FileStorage::READ);
            cv::Mat temp;
            fs["C"] >> temp;
            temp.convertTo(view_connectivity, cv::DataType<bool>::type);
        } catch(cv::Exception &e) {
            std::cerr << "Error reading connectivity matrix: " << e.what() << std::endl;
            exit(7);
        }
    } else {
        view_connectivity = cv::Mat_<bool>::ones(views.size(), views.size());
    }

    if(static_cast<unsigned int>(view_connectivity.rows) < views.size() ||
       static_cast<unsigned int>(view_connectivity.cols) < views.size()) {
        std::cerr << "Connectivity matrix has dimensions " << view_connectivity.cols << "x" << view_connectivity.rows
                  << " instead of " << views.size() << "x" << views.size() << std::endl;
        exit(8);
    }

    std::cout << "Merging views" << std::endl;
    std::vector<CPoint::ptr> global_point_cloud;
    for(unsigned int view_idx = first_view; view_idx < last_view; view_idx++) {
        print_progress(view_idx, views.size());

        timer.restart();
        CView &view = views[view_idx];
        view.merge(views,
                   view_idx,
                   view_connectivity,
                   global_point_cloud);

        // Collect statistics.
        float num_pixels = IMAGE_WIDTH * IMAGE_HEIGHT;
        time_merging_stats.push_back(timer.elapsed());
        num_missing_stats.push_back(view.get_num_missing());
        num_added_stats.push_back(view.get_num_added() / (num_pixels - view.get_num_missing()) * 100);

#ifdef DEBUG
        if(debug) {
            // Output images showing the computed depth values.

            cv::Matx<float, IMAGE_HEIGHT, IMAGE_WIDTH> depthmap;
            float max_depth = 0;
            for(int v = 0; v < IMAGE_HEIGHT; v++) {
                for(int u = 0; u < IMAGE_WIDTH; u++) {
                    float depth = view.has_measurement(u, v) && view.measurement_accepted[v][u]
                                ? view.get_depth(u, v)
                                : 0;
                    if(depth > max_depth) {
                        max_depth = depth;
                    }
                    depthmap(v, u) = depth;
                }
            }

            depthmap = depthmap * (1 / max_depth) * 255;

            std::ostringstream depthmap_filename;
            depthmap_filename << "depthmap-" << view_idx << ".png";
            cv::imwrite(depthmap_filename.str(), depthmap);

            // Output images showing the state of each point.

            cv::Mat state(IMAGE_HEIGHT, IMAGE_WIDTH, CV_8UC3);
            for(int v = 0; v < IMAGE_HEIGHT; v++) {
                for(int u = 0; u < IMAGE_WIDTH; u++) {
                    cv::Vec3b color; // in BGR format
                    if(view.has_measurement(u, v)) {
                        if(view.measurement_used[v][u]) {
                            // The point was used to refine an existing point.
                            color[0] = 128;
                            color[1] = 255;
                            color[2] = 128;
                        } else {
                            // The point was added to the cloud.
                            color[0] = 255;
                            color[1] = 128;
                            color[2] = 128;
                        }
                    } else {
                        // There was no measurement for the pixel.
                        color[0] = 213;
                        color[1] = 213;
                        color[2] = 213;
                    }
                    state.at<cv::Vec3b>(v, u) = color;
                }
            }

            std::ostringstream state_filename;
            state_filename<< "state-" << view_idx << ".png";
            cv::imwrite(state_filename.str(), state);
        }
#endif
    }
    output_point_cloud<CPoint::ptr>(global_point_cloud, output_file);

    // Output statistics.
    unsigned int num_pixels = IMAGE_WIDTH * IMAGE_HEIGHT;
    unsigned int num_original_points = (last_view - first_view) * num_pixels - sum(num_missing_stats);
    unsigned int num_resulting_points = global_point_cloud.size();
    std::cout << "Statistics:" << std::endl;
    std::cout << "Loading views: avg " << time_loading_stat / views.size() << " s" << std::endl;
    std::cout << "Merging views: avg " << average(time_merging_stats) << " s, min " << minimum(time_merging_stats) << " s, max " << maximum(time_merging_stats) << " s" << std::endl;
    std::cout << "Missing measurements: avg " << average(num_missing_stats) / num_pixels * 100 << " %, min " << minimum(num_missing_stats) / num_pixels * 100 << " %, max " << maximum(num_missing_stats) / num_pixels * 100 << " %" << std::endl;
    std::cout << "Added points: avg " << average(num_added_stats) << " %, min " << minimum(num_added_stats) << " %, max " << maximum(num_added_stats) << " %" << std::endl;
    std::cout << "Points in the original cloud: " << num_original_points << std::endl;
    std::cout << "Points in the resulting cloud: " << num_resulting_points << std::endl;
    std::cout << "Ratio: " << (float)num_resulting_points / num_original_points * 100 << " %" << std::endl;

    return 0;
}

max_stars_repo_name: tomikyos/kinect-merge

max_issues_repo_name: tomikyos/kinect-merge

max_forks_repo_name: tomikyos/kinect-merge


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

#include "cli_tests_fixture.hpp"

#include <fc/crypto/hex.hpp>

namespace account_create_tests
{
using namespace cli;

BOOST_FIXTURE_TEST_SUITE( account_create_tests, cli_tests_fixture )

BOOST_AUTO_TEST_CASE(create_account_with_pubkey_test)
{
    const string registrar = owner;
    const string referrer = registrar;

    auto key_info = connection->api()->suggest_brain_key();
    public_key_type pub_key = key_info.pub_key;

    BOOST_REQUIRE_NO_THROW(connection->api()->create_account_with_brain_key((std::string)pub_key, "alice", registrar, referrer, true));

    auto alice = connection->api()->get_account("alice");

    BOOST_CHECK_EQUAL(alice.name, "alice");

    key_info = connection->api()->suggest_brain_key();
    pub_key = key_info.pub_key;

    auto pub_key_hex = fc::to_hex(pub_key.key_data.begin(), pub_key.key_data.size());

    BOOST_REQUIRE_NO_THROW(connection->api()->create_account_with_brain_key(pub_key_hex, "bob", registrar, referrer, true));

    auto bob = connection->api()->get_account("bob");

    BOOST_CHECK_EQUAL(bob.name, "bob");
}

BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: totalgames/playchain-core

max_issues_repo_name: totalgames/playchain-core

max_forks_repo_name: totalgames/playchain-core


text:
/// \file   agent.cpp
///
/// \brief
///
/// \authors    Maarten P. Scholl
/// \date       2017-11-24
/// \copyright  Copyright 2017-2019 The Institute for New Economic Thinking,
///             Oxford Martin School, University of Oxford
///
///             Licensed under the Apache License, Version 2.0 (the "License");
///             you may not use this file except in compliance with the License.
///             You may obtain a copy of the License at
///
///                 http://www.apache.org/licenses/LICENSE-2.0
///
///             Unless required by applicable law or agreed to in writing,
///             software distributed under the License is distributed on an "AS
///             IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
///             express or implied. See the License for the specific language
///             governing permissions and limitations under the License.
///
///             You may obtain instructions to fulfill the attribution
///             requirements in CITATION.cff
///
#include <boost/serialization/export.hpp>

#include <esl/agent.hpp>

namespace esl {

    agent::agent() : agent(identity<agent>())
    {}

    agent::agent(identity<agent> i)
    : entity<agent>(std::move(i)), communicator()
    {}

    agent::agent(const agent &o) : agent(o.identifier)
    {}

    simulation::time_point agent::act(simulation::time_interval step,
                                      std::seed_seq &seed)
    {
        (void) seed;
        return step.upper;
    }
}  // namespace esl

BOOST_CLASS_TRACKING(esl::agent, boost::serialization::track_always)

BOOST_CLASS_EXPORT(esl::identity<esl::agent>);

BOOST_CLASS_EXPORT(esl::agent);

#ifdef WITH_PYTHON
#include <boost/python.hpp>
#include <boost/python/enum.hpp>
#include <esl/interaction/message.hpp>

namespace esl {
    using namespace boost::python;

    BOOST_PYTHON_MODULE(agent)
    {
        class_<agent, bases<entity<agent>, interaction::communicator>>(
            "agent", init<identity<agent>>());
    }
}  // namespace esl

#endif  // WITH_PYTHON


text:
//  Copyright (c) 2013 Jeroen Habraken
//
//  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 HPX_COMPONENTS_SECURITY_SERVER_SECRET_KEY_HPP
#define HPX_COMPONENTS_SECURITY_SERVER_SECRET_KEY_HPP

#include <hpx/hpx_fwd.hpp>
#include <hpx/exception.hpp>

#include <boost/array.hpp>
#include <boost/io/ios_state.hpp>

#include <sodium.h>

#include "public_key.hpp"
#include "signed_type.hpp"

namespace hpx { namespace components { namespace security
{
#if defined(_MSC_VER)
#  pragma pack(push, 1)
#endif

    class secret_key
    {
    public:
        secret_key(public_key & public_key)
        {
            crypto_sign_keypair(public_key.bytes_.c_array(), bytes_.c_array());
        }

        template <typename T>
        signed_type<T> sign(T const & type, error_code& ec = throws) const
        {
            signed_type<T> signed_type;
            unsigned long long signed_type_length;

            if (crypto_sign(
                    signed_type.begin(),
                    &signed_type_length,
                    type.begin(),
                    type.size(),
                    bytes_.data()) != 0)
            {
                HPX_THROWS_IF(
                    ec
                  , hpx::security_error
                  , "secret_key::sign"
                  , "Failed to sign type"
                )
                return signed_type;
            }

            if (type.size() + crypto_sign_BYTES != signed_type_length)
            {
                HPX_THROWS_IF(
                    ec
                  , hpx::security_error
                  , "secret_key::sign"
                  , "Signature of incorrect length"
                )
                return signed_type;
            }

            if (&ec != &throws)
                ec = make_success_code();

            return signed_type;
        }

        friend std::ostream & operator<<(std::ostream & os,
                                         secret_key const & secret_key)
        {
            boost::io::ios_flags_saver ifs(os);

            os << "<secret_key \"";

            for (std::size_t i = 0; i < crypto_sign_SECRETKEYBYTES; ++i)
            {
                os << std::hex
                   << std::nouppercase
                   << std::setfill('0')
                   << std::setw(2)
                   << static_cast<unsigned int>(secret_key.bytes_[i]);
            }

            return os << "\">";
        }

    private:
        boost::array<
            unsigned char, crypto_sign_SECRETKEYBYTES
        > bytes_;
    };

#if defined(_MSC_VER)
#  pragma pack(pop)
#endif
}}}

#endif

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text:
/*
 * Copyright (c) 2015 Cryptonomex, Inc., and contributors.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Any modified source or binaries are used only with the BitShares network.
 *
 * 2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 3. 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.
 *
 * 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 HOLDER 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.
 *
 */
#pragma once
#pragma GCC diagnostic ignored "-Wunknown-pragmas"

#include <fc/thread/thread.hpp>

#include <boost/signals2.hpp>

#include <QObject>

namespace fc { namespace http {
class websocket_client;
}}

class ChainDataModel;
class OperationBuilder;
class OperationBase;
class Transaction;
class Wallet;
class GrapheneApplication : public QObject {
   Q_OBJECT

   Q_PROPERTY(ChainDataModel* model READ model CONSTANT)
   Q_PROPERTY(OperationBuilder* operationBuilder READ operationBuilder CONSTANT)
   Q_PROPERTY(Wallet* wallet READ wallet CONSTANT)
   Q_PROPERTY(bool isConnected READ isConnected NOTIFY isConnectedChanged)

   fc::thread        m_thread;
   ChainDataModel*   m_model = nullptr;
   Wallet*           m_wallet = nullptr;
   OperationBuilder* m_operationBuilder = nullptr;
   bool              m_isConnected = false;

   boost::signals2::scoped_connection m_connectionClosed;

   std::shared_ptr<fc::http::websocket_client> m_client;
   fc::future<void> m_done;

   void setIsConnected(bool v);

protected Q_SLOTS:
   void execute(const std::function<void()>&)const;

public:
   GrapheneApplication(QObject* parent = nullptr);
   ~GrapheneApplication();

   Wallet* wallet()const { return m_wallet; }

   ChainDataModel* model() const {
      return m_model;
   }
   OperationBuilder* operationBuilder() const {
      return m_operationBuilder;
   }

   Q_INVOKABLE void start(QString apiUrl,
                          QString user,
                          QString pass);

   bool isConnected() const
   {
      return m_isConnected;
   }

   Q_INVOKABLE static QString defaultDataPath();

   /// Convenience method to get a Transaction in QML. Caller takes ownership of the new Transaction.
   Q_INVOKABLE Transaction* createTransaction() const;
   Q_INVOKABLE void signTransaction(Transaction* transaction) const;

Q_SIGNALS:
   void exceptionThrown(QString message);
   void loginFailed();
   void isConnectedChanged(bool isConnected);
   void queueExecute(const std::function<void()>&);
};