text:
/*
@file
Defines experimental views.

@copyright Louis Dionne 2013-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_EXPERIMENTAL_VIEW_HPP
#define BOOST_HANA_EXPERIMENTAL_VIEW_HPP

#include <boost/hana/and.hpp>
#include <boost/hana/at.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/detail/decay.hpp>
#include <boost/hana/fold_left.hpp>
#include <boost/hana/functional/compose.hpp>
#include <boost/hana/functional/on.hpp>
#include <boost/hana/fwd/ap.hpp>
#include <boost/hana/fwd/concat.hpp>
#include <boost/hana/fwd/drop_front.hpp>
#include <boost/hana/fwd/empty.hpp>
#include <boost/hana/fwd/equal.hpp>
#include <boost/hana/fwd/flatten.hpp>
#include <boost/hana/fwd/is_empty.hpp>
#include <boost/hana/fwd/less.hpp>
#include <boost/hana/fwd/lift.hpp>
#include <boost/hana/fwd/transform.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/length.hpp>
#include <boost/hana/lexicographical_compare.hpp>
#include <boost/hana/range.hpp>
#include <boost/hana/tuple.hpp>
#include <boost/hana/unpack.hpp>

#include <cstddef>
#include <type_traits>
#include <utility>

// Pros of views
//     - No temporary container created between algorithms
//     - Lazy, so only the minimum is required
//
// Cons of views
//     - Reference semantics mean possibility for dangling references
//     - Lose the ability to move from temporary containers
//     - When fetching the members of a view multiple times, no caching is done.
//       So for example, `t = transform(xs, f); at_c<0>(t); at_c<0>(t)` will
//       compute `f(at_c<0>(xs))` twice.
//     - push_back creates a joint_view and a single_view. The single_view holds
//       the value as a member. When doing multiple push_backs, we end up with a
//         joint_view<xxx, joint_view<single_view<T>, joint_view<single_view<T>, ....>>>
//       which contains a reference to `xxx` and all the `T`s by value. Such a
//       "view" is not cheap to copy, which is inconsistent with the usual
//       expectations about views.

BOOST_HANA_NAMESPACE_BEGIN

namespace experimental {
    struct view_tag;

    namespace detail {
        template <typename Sequence>
        struct is_view {
            static constexpr bool value = false;
        };

        template <typename Sequence>
        using view_storage = typename std::conditional<
            detail::is_view<Sequence>::value, Sequence, Sequence&
        >::type;
    }

    //////////////////////////////////////////////////////////////////////////
    // sliced_view
    //////////////////////////////////////////////////////////////////////////
    template <typename Sequence, std::size_t ...indices>
    struct sliced_view_t {
        detail::view_storage<Sequence> sequence_;
        using hana_tag = view_tag;
    };

    template <typename Sequence, typename Indices>
    constexpr auto sliced(Sequence& sequence, Indices const& indices) {
        return hana::unpack(indices, [&](auto ...i) {
            return sliced_view_t<Sequence, decltype(i)::value...>{sequence};
        });
    }

    namespace detail {
        template <typename Sequence, std::size_t ...i>
        struct is_view<sliced_view_t<Sequence, i...>> {
            static constexpr bool value = true;
        };
    }

    //////////////////////////////////////////////////////////////////////////
    // transformed_view
    //////////////////////////////////////////////////////////////////////////
    template <typename Sequence, typename F>
    struct transformed_view_t {
        detail::view_storage<Sequence> sequence_;
        F f_;
        using hana_tag = view_tag;
    };

    template <typename Sequence, typename F>
    constexpr transformed_view_t<Sequence, typename hana::detail::decay<F>::type>
    transformed(Sequence& sequence, F&& f) {
        return {sequence, static_cast<F&&>(f)};
    }

    namespace detail {
        template <typename Sequence, typename F>
        struct is_view<transformed_view_t<Sequence, F>> {
            static constexpr bool value = true;
        };
    }

    //////////////////////////////////////////////////////////////////////////
    // filtered_view
    //////////////////////////////////////////////////////////////////////////
#if 0
    template <typename Sequence, typename Pred>
    using filtered_view_t = sliced_view_t<Sequence, detail::filtered_indices<...>>;

    template <typename Sequence, typename Pred>
    constexpr filtered_view_t<Sequence, Pred> filtered(Sequence& sequence, Pred&& pred) {
        return {sequence};
    }
#endif

    //////////////////////////////////////////////////////////////////////////
    // joined_view
    //////////////////////////////////////////////////////////////////////////
    template <typename Sequence1, typename Sequence2>
    struct joined_view_t {
        detail::view_storage<Sequence1> sequence1_;
        detail::view_storage<Sequence2> sequence2_;
        using hana_tag = view_tag;
    };

    struct make_joined_view_t {
        template <typename Sequence1, typename Sequence2>
        constexpr joined_view_t<Sequence1, Sequence2> operator()(Sequence1& s1, Sequence2& s2) const {
            return {s1, s2};
        }
    };
    constexpr make_joined_view_t joined{};

    namespace detail {
        template <typename Sequence1, typename Sequence2>
        struct is_view<joined_view_t<Sequence1, Sequence2>> {
            static constexpr bool value = true;
        };
    }

    //////////////////////////////////////////////////////////////////////////
    // single_view
    //////////////////////////////////////////////////////////////////////////
    template <typename T>
    struct single_view_t {
        T value_;
        using hana_tag = view_tag;
    };

    template <typename T>
    constexpr single_view_t<typename hana::detail::decay<T>::type> single_view(T&& t) {
        return {static_cast<T&&>(t)};
    }

    namespace detail {
        template <typename T>
        struct is_view<single_view_t<T>> {
            static constexpr bool value = true;
        };
    }

    //////////////////////////////////////////////////////////////////////////
    // empty_view
    //////////////////////////////////////////////////////////////////////////
    struct empty_view_t {
        using hana_tag = view_tag;
    };

    constexpr empty_view_t empty_view() {
        return {};
    }

    namespace detail {
        template <>
        struct is_view<empty_view_t> {
            static constexpr bool value = true;
        };
    }
} // end namespace experimental

//////////////////////////////////////////////////////////////////////////
// Foldable
//////////////////////////////////////////////////////////////////////////
template <>
struct unpack_impl<experimental::view_tag> {
    // sliced_view
    template <typename Sequence, std::size_t ...i, typename F>
    static constexpr decltype(auto)
    apply(experimental::sliced_view_t<Sequence, i...> view, F&& f) {
        (void)view; // Remove spurious unused variable warning with GCC
        return static_cast<F&&>(f)(hana::at_c<i>(view.sequence_)...);
    }

    // transformed_view
    template <typename Sequence, typename F, typename G>
    static constexpr decltype(auto)
    apply(experimental::transformed_view_t<Sequence, F> view, G&& g) {
        return hana::unpack(view.sequence_, hana::on(static_cast<G&&>(g), view.f_));
    }

    // joined_view
    template <typename View, typename F, std::size_t ...i1, std::size_t ...i2>
    static constexpr decltype(auto)
    unpack_joined(View view, F&& f, std::index_sequence<i1...>,
                                    std::index_sequence<i2...>)
    {
        (void)view; // Remove spurious unused variable warning with GCC
        return static_cast<F&&>(f)(hana::at_c<i1>(view.sequence1_)...,
                                   hana::at_c<i2>(view.sequence2_)...);
    }

    template <typename S1, typename S2, typename F>
    static constexpr decltype(auto)
    apply(experimental::joined_view_t<S1, S2> view, F&& f) {
        constexpr auto N1 = decltype(hana::length(view.sequence1_))::value;
        constexpr auto N2 = decltype(hana::length(view.sequence2_))::value;
        return unpack_joined(view, static_cast<F&&>(f),
                             std::make_index_sequence<N1>{},
                             std::make_index_sequence<N2>{});
    }

    // single_view
    template <typename T, typename F>
    static constexpr decltype(auto) apply(experimental::single_view_t<T> view, F&& f) {
        return static_cast<F&&>(f)(view.value_);
    }

    // empty_view
    template <typename F>
    static constexpr decltype(auto) apply(experimental::empty_view_t, F&& f) {
        return static_cast<F&&>(f)();
    }
};

//////////////////////////////////////////////////////////////////////////
// Iterable
//////////////////////////////////////////////////////////////////////////
template <>
struct at_impl<experimental::view_tag> {
    // sliced_view
    template <typename Sequence, std::size_t ...i, typename N>
    static constexpr decltype(auto)
    apply(experimental::sliced_view_t<Sequence, i...> view, N const&) {
        constexpr std::size_t indices[] = {i...};
        constexpr std::size_t n = indices[N::value];
        return hana::at_c<n>(view.sequence_);
    }

    // transformed_view
    template <typename Sequence, typename F, typename N>
    static constexpr decltype(auto)
    apply(experimental::transformed_view_t<Sequence, F> view, N const& n) {
        return view.f_(hana::at(view.sequence_, n));
    }

    // joined_view
    template <std::size_t Left, typename View, typename N>
    static constexpr decltype(auto) at_joined_view(View view, N const&, hana::true_) {
        return hana::at_c<N::value>(view.sequence1_);
    }

    template <std::size_t Left, typename View, typename N>
    static constexpr decltype(auto) at_joined_view(View view, N const&, hana::false_) {
        return hana::at_c<N::value - Left>(view.sequence2_);
    }

    template <typename S1, typename S2, typename N>
    static constexpr decltype(auto)
    apply(experimental::joined_view_t<S1, S2> view, N const& n) {
        constexpr auto Left = decltype(hana::length(view.sequence1_))::value;
        return at_joined_view<Left>(view, n, hana::bool_c<(N::value < Left)>);
    }

    // single_view
    template <typename T, typename N>
    static constexpr decltype(auto) apply(experimental::single_view_t<T> view, N const&) {
        static_assert(N::value == 0,
        "trying to fetch an out-of-bounds element in a hana::single_view");
        return view.value_;
    }

    // empty_view
    template <typename N>
    static constexpr decltype(auto) apply(experimental::empty_view_t, N const&) = delete;
};

template <>
struct length_impl<experimental::view_tag> {
    // sliced_view
    template <typename Sequence, std::size_t ...i>
    static constexpr auto
    apply(experimental::sliced_view_t<Sequence, i...>) {
        return hana::size_c<sizeof...(i)>;
    }

    // transformed_view
    template <typename Sequence, typename F>
    static constexpr auto apply(experimental::transformed_view_t<Sequence, F> view) {
        return hana::length(view.sequence_);
    }

    // joined_view
    template <typename S1, typename S2>
    static constexpr auto apply(experimental::joined_view_t<S1, S2> view) {
        return hana::size_c<
            decltype(hana::length(view.sequence1_))::value +
            decltype(hana::length(view.sequence2_))::value
        >;
    }

    // single_view
    template <typename T>
    static constexpr auto apply(experimental::single_view_t<T>) {
        return hana::size_c<1>;
    }

    // empty_view
    static constexpr auto apply(experimental::empty_view_t) {
        return hana::size_c<0>;
    }
};

template <>
struct is_empty_impl<experimental::view_tag> {
    // sliced_view
    template <typename Sequence, std::size_t ...i>
    static constexpr auto
    apply(experimental::sliced_view_t<Sequence, i...>) {
        return hana::bool_c<sizeof...(i) == 0>;
    }

    // transformed_view
    template <typename Sequence, typename F>
    static constexpr auto apply(experimental::transformed_view_t<Sequence, F> view) {
        return hana::is_empty(view.sequence_);
    }

    // joined_view
    template <typename S1, typename S2>
    static constexpr auto apply(experimental::joined_view_t<S1, S2> view) {
        return hana::and_(hana::is_empty(view.sequence1_),
                          hana::is_empty(view.sequence2_));
    }

    // single_view
    template <typename T>
    static constexpr auto apply(experimental::single_view_t<T>) {
        return hana::false_c;
    }

    // empty_view
    static constexpr auto apply(experimental::empty_view_t) {
        return hana::true_c;
    }
};

template <>
struct drop_front_impl<experimental::view_tag> {
    template <typename View, typename N>
    static constexpr auto apply(View view, N const&) {
        constexpr auto n = N::value;
        constexpr auto Length = decltype(hana::length(view))::value;
        return experimental::sliced(view, hana::range_c<std::size_t, n, Length>);
    }
};

//////////////////////////////////////////////////////////////////////////
// Functor
//////////////////////////////////////////////////////////////////////////
template <>
struct transform_impl<experimental::view_tag> {
    template <typename Sequence, typename F, typename G>
    static constexpr auto
    apply(experimental::transformed_view_t<Sequence, F> view, G&& g) {
        return experimental::transformed(view.sequence_,
                                         hana::compose(static_cast<G&&>(g), view.f_));
    }

    template <typename View, typename F>
    static constexpr auto apply(View view, F&& f) {
        return experimental::transformed(view, static_cast<F&&>(f));
    }
};

//////////////////////////////////////////////////////////////////////////
// Applicative
//////////////////////////////////////////////////////////////////////////
template <>
struct lift_impl<experimental::view_tag> {
    template <typename T>
    static constexpr auto apply(T&& t) {
        return experimental::single_view(static_cast<T&&>(t));
    }
};

template <>
struct ap_impl<experimental::view_tag> {
    template <typename F, typename X>
    static constexpr auto apply(F&& f, X&& x) {
        // TODO: Implement cleverly; we most likely need a cartesian_product
        //       view or something like that.
        return hana::ap(hana::to_tuple(f), hana::to_tuple(x));
    }
};

//////////////////////////////////////////////////////////////////////////
// Monad
//////////////////////////////////////////////////////////////////////////
template <>
struct flatten_impl<experimental::view_tag> {
    template <typename View>
    static constexpr auto apply(View view) {
        // TODO: Implement a flattened_view instead
        return hana::fold_left(view, experimental::empty_view(),
                                     experimental::joined);
    }
};

//////////////////////////////////////////////////////////////////////////
// MonadPlus
//////////////////////////////////////////////////////////////////////////
template <>
struct concat_impl<experimental::view_tag> {
    template <typename View1, typename View2>
    static constexpr auto apply(View1 view1, View2 view2) {
        return experimental::joined(view1, view2);
    }
};

template <>
struct empty_impl<experimental::view_tag> {
    static constexpr auto apply() {
        return experimental::empty_view();
    }
};

//////////////////////////////////////////////////////////////////////////
// Comparable
//////////////////////////////////////////////////////////////////////////
template <>
struct equal_impl<experimental::view_tag, experimental::view_tag> {
    template <typename View1, typename View2>
    static constexpr auto apply(View1 v1, View2 v2) {
        // TODO: Use a lexicographical comparison algorithm.
        return hana::equal(hana::to_tuple(v1), hana::to_tuple(v2));
    }
};

template <typename S>
struct equal_impl<experimental::view_tag, S, hana::when<hana::Sequence<S>::value>> {
    template <typename View1, typename Seq>
    static constexpr auto apply(View1 v1, Seq const& s) {
        // TODO: Use a lexicographical comparison algorithm.
        return hana::equal(hana::to_tuple(v1), hana::to_tuple(s));
    }
};

template <typename S>
struct equal_impl<S, experimental::view_tag, hana::when<hana::Sequence<S>::value>> {
    template <typename Seq, typename View2>
    static constexpr auto apply(Seq const& s, View2 v2) {
        // TODO: Use a lexicographical comparison algorithm.
        return hana::equal(hana::to_tuple(s), hana::to_tuple(v2));
    }
};

//////////////////////////////////////////////////////////////////////////
// Orderable
//////////////////////////////////////////////////////////////////////////
template <>
struct less_impl<experimental::view_tag, experimental::view_tag> {
    template <typename View1, typename View2>
    static constexpr auto apply(View1 v1, View2 v2) {
        return hana::lexicographical_compare(v1, v2);
    }
};

template <typename S>
struct less_impl<experimental::view_tag, S, hana::when<hana::Sequence<S>::value>> {
    template <typename View1, typename Seq>
    static constexpr auto apply(View1 v1, Seq const& s) {
        return hana::lexicographical_compare(v1, s);
    }
};

template <typename S>
struct less_impl<S, experimental::view_tag, hana::when<hana::Sequence<S>::value>> {
    template <typename Seq, typename View2>
    static constexpr auto apply(Seq const& s, View2 v2) {
        return hana::lexicographical_compare(s, v2);
    }
};

BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_EXPERIMENTAL_VIEW_HPP

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
// hpr-itl bicgstab.cpp: HPR Bi-Conjugate Gradient Stabilized algorithm
//
// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.

#include "common.hpp"

// enable posit arithmetic exceptions
#define POSIT_THROW_ARITHMETIC_EXCEPTION 1
#include <posit>

// MTL
#define MTL_VERBOSE_ITERATION
#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/itl/itl.hpp>
// defines all Krylov solvers
// CG, CGS, BiCG, BiCGStab, BiCGStab2, BiCGStab_ell, FSM, IDRs, GMRES TFQMR, QMR, PC

namespace hpr {
	template<typename Vector, size_t nbits, size_t es, size_t capacity = 10>
	sw::unum::posit<nbits, es> fused_dot(const Vector& x, const Vector& y) {
		sw::unum::quire<nbits, es, capacity> q = 0;
		size_t ix, iy, n = size(x);
		for (ix = 0, iy = 0; ix < n && iy < n; ix = ix + 1, iy = iy + 1) {
			q += sw::unum::quire_mul(x[ix], y[iy]);
		}
		sw::unum::posit<nbits, es> sum;
		convert(q.to_value(), sum);     // one and only rounding step of the fused-dot product
		return sum;
	}

	///  Bi-Conjugate Gradient Stabilized
	template < class LinearOperator, class HilbertSpaceX, class HilbertSpaceB,
		class Preconditioner, class Iteration >
		int bicgstab(const LinearOperator& A, HilbertSpaceX& x, const HilbertSpaceB& b,
			const Preconditioner& M, Iteration& iter)
	{
		typedef typename mtl::Collection<HilbertSpaceX>::value_type Scalar;
		typedef HilbertSpaceX                                       Vector;
		mtl::vampir_trace<7004> tracer;

		constexpr size_t nbits = Scalar::nbits;
		constexpr size_t es = Scalar::es;

		Scalar     rho_1(0), rho_2(0), alpha(0), beta(0), gamma, omega(0);
		Vector     p(resource(x)), phat(resource(x)), s(resource(x)), shat(resource(x)),
			t(resource(x)), v(resource(x)), r(resource(x)), rtilde(resource(x));

		r = b - A * x;
		rtilde = r;

		while (!iter.finished(r)) {
			++iter;
			rho_1 = fused_dot<Vector, nbits, es>(rtilde, r);
			MTL_THROW_IF(rho_1 == 0.0, itl::unexpected_orthogonality());

			if (iter.first())
				p = r;
			else {
				MTL_THROW_IF(omega == 0.0, itl::unexpected_orthogonality());
				beta = (rho_1 / rho_2) * (alpha / omega);
				p = r + beta * (p - omega * v);
			}
			phat = solve(M, p);
			v = A * phat;

			gamma = fused_dot<Vector, nbits, es>(rtilde, v);
			MTL_THROW_IF(gamma == 0.0, itl::unexpected_orthogonality());

			alpha = rho_1 / gamma;
			s = r - alpha * v;

			if (iter.finished(s)) {
				x += alpha * phat;
				break;
			}
			shat = solve(M, s);
			t = A * shat;
			omega = fused_dot<Vector, nbits, es>(t, s) / fused_dot<Vector, nbits, es>(t, t);

			x += omega * shat + alpha * phat;
			r = s - omega * t;

			rho_2 = rho_1;
		}
		return iter;
	}

} // namespace hpr

template<typename Scalar>
void regular_BiCGStab() {
	using namespace std;
	const size_t size = 40, N = size * size;

	using Matrix = mtl::mat::compressed2D< Scalar >;
	using Vector = mtl::vec::dense_vector< Scalar >;

	// Create a 1,600 x 1,600 matrix using a 5-point Laplacian stencil
	Matrix A(N, N);
	mtl::mat::laplacian_setup(A, size, size);

	// Create an ILU(0) preconditioner
	itl::pc::ilu_0< Matrix >        P(A);

	// Set b such that x == 1 is solution; start with x == 0
	mtl::vec::dense_vector<Scalar>       x(N, 1.0), b(N);
	b = A * x; x = 0;

	// Termination criterion: r < 1e-6 * b or N iterations
	itl::noisy_iteration< Scalar >  iter(b, 5, (Scalar)1.e-6);

	// Solve Ax == b with left preconditioner P
	itl::bicgstab(A, x, b, P, iter);
}

template<typename Scalar>
void fdp_BiCGStab() {
	using namespace std;
	const size_t size = 40, N = size * size;

	using Matrix = mtl::mat::compressed2D< Scalar >;
	using Vector = mtl::vec::dense_vector< Scalar >;

	// Create a 1,600 x 1,600 matrix using a 5-point Laplacian stencil
	Matrix A(N, N);
	mtl::mat::laplacian_setup(A, size, size);

	// Create an ILU(0) preconditioner
	itl::pc::ilu_0< Matrix >        P(A);

	// Set b such that x == 1 is solution; start with x == 0
	mtl::vec::dense_vector<Scalar>       x(N, 1.0), b(N);
	b = A * x; x = 0;

	// Termination criterion: r < 1e-6 * b or N iterations
	itl::noisy_iteration< Scalar >  iter(b, 5, 1.e-6);

	// Solve Ax == b with left preconditioner P
	hpr::bicgstab(A, x, b, P, iter);
}

int main(int, char**)
{
	using namespace std;
	using namespace mtl;

	constexpr size_t nbits = 32;
	constexpr size_t es = 2;

	using Scalar = sw::unum::posit<nbits, es>;

	regular_BiCGStab<float>();
	fdp_BiCGStab< sw::unum::posit<32, 2> >();
	fdp_BiCGStab< sw::unum::posit<24, 3> >();

    return 0;
}

void debugging() {
	using namespace std;
	using namespace mtl;

	constexpr size_t nbits = 32;
	constexpr size_t es = 2;

	using Scalar = sw::unum::posit<nbits, es>;

	{
		size_t nrElements = 4;
		std::vector<double> data = { -0.25, -0.25, 0.25, 0.25 };
		//std::vector<double> data = { 1, -1, 1, -1 };
		vec::dense_vector< double> dv(nrElements);
		vec::dense_vector< Scalar > pv(nrElements);
		{
			double n2 = 0;
			Scalar p2 = 0;
			int i = 0;
			for (auto v : data) {
				dv(i) = v;
				pv(i) = v;
				++i;
				n2 += v*v;
				cout << pretty_print(Scalar(v)*Scalar(v)) << endl;
				p2 += Scalar(v)*Scalar(v);
			}
			cout << "n2 = " << n2 << " sqrt(n2) = " << sqrt(n2) << endl;
			cout << "p2 = " << p2 << " sqrt(p2) = " << sqrt(p2) << endl;
		}
		cout << setprecision(10);
		cout << "data elements      = " << dv << endl;
		cout << "||vector<double>|| = " << two_norm(dv) << endl;
		cout << "||vector<posit>||  = " << two_norm(pv) << endl;

		//Scalar r = two_norm(pv);

		Scalar x = -0.25;
		Scalar a;
		a = abs(x);
		cout << "abs(-0.25) " << a << endl;
	}

	{
		std::vector<double> data = { -0.174422, +0.104777, +0.0490646, +0.0335677, -0.033611, +0.104777, +0.393583, +0.339555, +0.347771, +0.0403458, +0.0490646, +0.339555, +0.305213, +0.354414, +0.0556945, +0.0335677, +0.347771, +0.354414, +0.426084, +0.132617, -0.033611, +0.0403458, +0.0556945, +0.132617, -0.174422 };
		vec::dense_vector< double> dv(25);
		vec::dense_vector< Scalar > pv(25);

		// || r || = +44.4951

		{
			int i = 0;
			for (auto v : data) {
				dv(i) = v;
				pv(i) = v;
				++i;
			}
		}
		cout << "||vector<double>|| = " << two_norm(dv) << endl;
		cout << "||vector<posit>||  = " << two_norm(pv) << endl;

		Scalar r = two_norm(pv);
	}
}

ext: cpp

max_stars_repo_name: stillwater-sc/hpr-itl

max_issues_repo_name: stillwater-sc/hpr-itl

max_forks_repo_name: stillwater-sc/hpr-itl


text:
#pragma once
#include "terminalpp/ansi/protocol.hpp"
#include <boost/container_hash/hash.hpp>
#include <boost/operators.hpp>
#include <iosfwd>

namespace terminalpp {

//* =========================================================================
/// \brief Structure representing a normal ANSI 16-colour value
//* =========================================================================
struct low_colour
  : private boost::less_than_comparable<low_colour,
            boost::equality_comparable<low_colour>>
{
    //* =====================================================================
    /// \brief Constructs a low_colour with the "default" colour value.
    //* =====================================================================
    constexpr low_colour()
        : low_colour(terminalpp::ansi::graphics::colour::default_)
    {
    }

    //* =====================================================================
    /// \brief Constructs a low_colour from the passed-in ANSI colour.
    //* =====================================================================
    constexpr low_colour(terminalpp::ansi::graphics::colour colour)
        : value_(colour)
    {
    };

    //* =====================================================================
    /// \brief Hash function
    //* =====================================================================
    friend std::size_t hash_value(low_colour const &col) noexcept
    {
        std::size_t seed = 0;
        boost::hash_combine(
            seed,
            static_cast<
                std::underlying_type<decltype(col.value_)>::type
            >(col.value_));
        return seed;
    }

    terminalpp::ansi::graphics::colour value_;
};

//* =========================================================================
/// \brief Equality operator for low_colours.
//* =========================================================================
constexpr bool operator==(low_colour const &lhs, low_colour const &rhs)
{
    return lhs.value_ == rhs.value_;
}

//* =========================================================================
/// \brief Less-than operator for low_colours.
//* =========================================================================
constexpr bool operator<(low_colour const &lhs, low_colour const &rhs)
{
    return lhs.value_ < rhs.value_;
}

//* =========================================================================
/// \brief Streaming output operator for low_colours.  Prints the text
/// equivalent of the colour (e.g. red, blue, black)
//* =========================================================================
TERMINALPP_EXPORT
std::ostream &operator<<(std::ostream &out, low_colour const &col);

//* =========================================================================
/// \brief Structure representing the central 216 colours of a 256-colour
/// palette, where each colour channel is represented by a number in the
/// range 0..5.
//* =========================================================================
struct high_colour
  : private boost::less_than_comparable<high_colour,
            boost::equality_comparable<high_colour>>
{
    //* =====================================================================
    /// \brief Default constructs a high-colour with the value of pure black.
    //* =====================================================================
    constexpr high_colour()
      : high_colour(0, 0, 0)
    {
    }

    //* =====================================================================
    /// \brief Constructs a high_colour from the passed-in RGB values, each
    /// of which should be in the range 0-5.
    //* =====================================================================
    constexpr high_colour(
        byte red,
        byte green,
        byte blue)
      : value_(red * 36 + green * 6 + blue + 16)
    {
    }

    //* =====================================================================
    /// \brief Hash function
    //* =====================================================================
    friend std::size_t hash_value(high_colour const &col) noexcept
    {
        std::size_t seed = 0;
        boost::hash_combine(seed, col.value_);
        return seed;
    }

    byte value_;
};

//* =========================================================================
/// \brief Equality operator for high_colours.
//* =========================================================================
constexpr bool operator==(high_colour const &lhs, high_colour const &rhs)
{
    return lhs.value_ == rhs.value_;
}

//* =========================================================================
/// \brief Less-than operator for high_colours.
//* =========================================================================
constexpr bool operator<(high_colour const &lhs, high_colour const &rhs)
{
    return lhs.value_ < rhs.value_;
}

//* =========================================================================
/// \brief Streaming output operator for high_colours.  Prints the text
/// equivalent of the colour (e.g. #234, #512, etc.)
//* =========================================================================
TERMINALPP_EXPORT
std::ostream &operator<<(std::ostream &out, high_colour const &col);

//* =========================================================================
/// \brief Structure representing the 24 greyscale tones of a 256-colour
/// palette
//* =========================================================================
struct greyscale_colour
  : private boost::less_than_comparable<greyscale_colour,
            boost::equality_comparable<greyscale_colour>>
{
    //* =====================================================================
    /// \brief Default constructs a greyscale value with the darkest
    /// available grey.
    //* =====================================================================
    constexpr greyscale_colour()
      : shade_(0)
    {
    }

    //* =====================================================================
    /// \brief Constructs a greyscale value from the given shade, which
    /// should be in the range 0-23.
    //* =====================================================================
    constexpr explicit greyscale_colour(byte shade)
      : shade_(shade + 232)
    {
    }

    //* =====================================================================
    /// \brief Hash function
    //* =====================================================================
    friend std::size_t hash_value(greyscale_colour const &col) noexcept
    {
        std::size_t seed = 0;
        boost::hash_combine(seed, col.shade_);
        return seed;
    }

    byte shade_;
};

//* =========================================================================
/// \brief Equality operator for greyscale_colours.
//* =========================================================================
constexpr bool operator==(
    greyscale_colour const &lhs, greyscale_colour const &rhs)
{
    return lhs.shade_ == rhs.shade_;
}

//* =========================================================================
/// \brief Less-than operator for greyscale_colours.
//* =========================================================================
constexpr bool operator<(
    greyscale_colour const &lhs, greyscale_colour const &rhs)
{
    return lhs.shade_ < rhs.shade_;
}

//* =========================================================================
/// \brief Streaming output operator for greyscale_colours.  Prints the text
/// equivalent of the colour (e.g. #22, #00, etc.)
//* =========================================================================
TERMINALPP_EXPORT
std::ostream &operator<<(std::ostream &out, greyscale_colour const &col);

//* =========================================================================
/// \brief Structure representing a sum type of the available colour styles.
//* =========================================================================
struct colour
  : private boost::less_than_comparable<colour,
            boost::equality_comparable<colour>>
{
    //* =====================================================================
    /// \brief An enumeration of the possible colour types.
    //* =====================================================================
    enum class type : byte
    {
        low, high, greyscale
    };

    //* =====================================================================
    /// \brief Default constructs the colour with the "default" ANSI colour.
    //* =====================================================================
    constexpr colour()
      : colour(terminalpp::low_colour())
    {
    }

    //* =====================================================================
    /// \brief Constructs a colour with the passed low_colour value.
    //* =====================================================================
    constexpr colour(terminalpp::low_colour col)
      : low_colour_(std::move(col)),
        type_(type::low)
    {
    }

    //* =====================================================================
    /// \brief Constructs a colour with the passed high_colour value.
    //* =====================================================================
    constexpr colour(terminalpp::high_colour col)
      : high_colour_(std::move(col)),
        type_(type::high)
    {
    }

    //* =====================================================================
    /// \brief Constructs a colour with the passed greyscale_colour value.
    //* =====================================================================
    constexpr colour(terminalpp::greyscale_colour col)
      : greyscale_colour_(std::move(col)),
        type_(type::greyscale)
    {
    }

    //* =====================================================================
    /// \brief Copy constructor
    //* =====================================================================
    constexpr colour(terminalpp::ansi::graphics::colour col)
      : colour(terminalpp::low_colour(col))
    {
    }

    //* =====================================================================
    /// \brief Hash function
    //* =====================================================================
    friend std::size_t hash_value(colour const &col) noexcept
    {
        switch (col.type_)
        {
            case type::low : return hash_value(col.low_colour_);
            case type::high : return hash_value(col.high_colour_);
            case type::greyscale : return hash_value(col.greyscale_colour_);
            default : return 0;
        }
    }

    union
    {
        terminalpp::low_colour low_colour_;
        terminalpp::high_colour high_colour_;
        terminalpp::greyscale_colour greyscale_colour_;
    };

    type type_;
};

//* =========================================================================
/// \brief Equality operator for colours.
//* =========================================================================
constexpr bool operator==(colour const &lhs, colour const &rhs)
{
    return lhs.type_             == rhs.type_
        && lhs.type_             == colour::type::low
         ? lhs.low_colour_       == rhs.low_colour_
         : lhs.type_             == colour::type::high
         ? lhs.high_colour_      == rhs.high_colour_
         : lhs.type_             == colour::type::greyscale
         ? lhs.greyscale_colour_ == rhs.greyscale_colour_
         : false;
}

//* =========================================================================
/// \brief Less-than operator for colours.
//* =========================================================================
constexpr bool operator<(colour const &lhs, colour const &rhs)
{
    if (lhs.type_ < rhs.type_)
    {
        return true;
    }

    if (lhs.type_ == rhs.type_)
    {
        return lhs.type_ == colour::type::low
             ? lhs.low_colour_ < rhs.low_colour_
             : lhs.type_ == colour::type::high
             ? lhs.high_colour_ < rhs.high_colour_
             : lhs.type_ == colour::type::greyscale
             ? lhs.greyscale_colour_ < rhs.greyscale_colour_
             : false;
    }

    return false;
}

//* =========================================================================
/// \brief Streaming output operator for colours.  Prints the text equivalent
/// of the colour (e.g. "red", "#234", "#07", etc.)
//* =========================================================================
TERMINALPP_EXPORT
std::ostream &operator<<(std::ostream &out, colour const &col);

}

namespace std {

template <>
struct hash<terminalpp::low_colour>
{
    using argument_type = terminalpp::low_colour;
    using result_type = std::size_t;

    result_type operator()(argument_type const &col) const noexcept
    {
        return hash_value(col);
    }
};

template <>
struct hash<terminalpp::high_colour>
{
    using argument_type = terminalpp::high_colour;
    using result_type = std::size_t;

    result_type operator()(argument_type const &col) const noexcept
    {
        return hash_value(col);
    }
};

template <>
struct hash<terminalpp::greyscale_colour>
{
    using argument_type = terminalpp::greyscale_colour;
    using result_type = std::size_t;

    result_type operator()(argument_type const &col) const noexcept
    {
        return hash_value(col);
    }
};

template <>
struct hash<terminalpp::colour>
{
    using argument_type = terminalpp::colour;
    using result_type = std::size_t;

    result_type operator()(argument_type const &col) const noexcept
    {
        return hash_value(col);
    }
};

}

ext: hpp

max_stars_repo_name: ruszkait/terminalpp

max_issues_repo_name: p-ranav/terminalpp

max_forks_repo_name: p-ranav/terminalpp


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

#include "tools/string.h" // header to test

using namespace biosim;

BOOST_AUTO_TEST_SUITE(suite_string)

BOOST_AUTO_TEST_CASE(string_unique) {
  std::string s1, s2("a a a a");
  tools::char_function char_isspace = (int (*)(int)) & std::isspace;

  BOOST_CHECK(tools::get_unique_char_set_ignore(s1, char_isspace).empty());
  BOOST_CHECK(tools::get_unique_char_set_ignore(s2, char_isspace).size() == 1);

  BOOST_CHECK(tools::get_unique_char_set(s1).empty());
  BOOST_CHECK(tools::get_unique_char_set(s2).size() == 2);

  BOOST_CHECK(tools::get_unique_char_string_ignore(s1, char_isspace).empty());
  BOOST_CHECK(tools::get_unique_char_string_ignore(s2, char_isspace).size() == 1);

  BOOST_CHECK(tools::get_unique_char_string(s1).empty());
  BOOST_CHECK(tools::get_unique_char_string(s2).size() == 2);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: shze/biosim

max_issues_repo_name: shze/biosim

max_forks_repo_name: shze/biosim


text: #include <boost/compute/utility/wait_list.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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_ufunc_hpp_
#define boost_python_numpy_ufunc_hpp_

/**
 *  @brief Utilities to create ufunc-like broadcasting functions out of C++ functors.
 */

#include <boost/python.hpp>
#include <boost/python/numpy/numpy_object_mgr_traits.hpp>
#include <boost/python/numpy/dtype.hpp>
#include <boost/python/numpy/ndarray.hpp>
#include <boost/python/numpy/config.hpp>

namespace boost { namespace python { namespace numpy {

/**
 *  @brief A boost.python "object manager" (subclass of object) for PyArray_MultiIter.
 *
 *  multi_iter is a Python object, but a very low-level one.  It should generally only be used
 *  in loops of the form:
 *  @code
 *  while (iter.not_done()) {
 *      ...
 *      iter.next();
 *  }
 *  @endcode
 *
 *  @todo I can't tell if this type is exposed in Python anywhere; if it is, we should use that name.
 *        It's more dangerous than most object managers, however - maybe it actually belongs in
 *        a detail namespace?
 */
class BOOST_NUMPY_DECL multi_iter : public object
{
public:

  BOOST_PYTHON_FORWARD_OBJECT_CONSTRUCTORS(multi_iter, object);

  /// @brief Increment the iterator.
  void next();

  /// @brief Check if the iterator is at its end.
  bool not_done() const;

  /// @brief Return a pointer to the element of the nth broadcasted array.
  char * get_data(int n) const;

  /// @brief Return the number of dimensions of the broadcasted array expression.
  int get_nd() const;

  /// @brief Return the shape of the broadcasted array expression as an array of integers.
  Py_intptr_t const * get_shape() const;

  /// @brief Return the shape of the broadcasted array expression in the nth dimension.
  Py_intptr_t shape(int n) const;

};

/// @brief Construct a multi_iter over a single sequence or scalar object.
BOOST_NUMPY_DECL multi_iter make_multi_iter(object const & a1);

/// @brief Construct a multi_iter by broadcasting two objects.
BOOST_NUMPY_DECL multi_iter make_multi_iter(object const & a1, object const & a2);

/// @brief Construct a multi_iter by broadcasting three objects.
BOOST_NUMPY_DECL multi_iter make_multi_iter(object const & a1, object const & a2, object const & a3);

/**
 *  @brief Helps wrap a C++ functor taking a single scalar argument as a broadcasting ufunc-like
 *         Python object.
 *
 *  Typical usage looks like this:
 *  @code
 *  struct TimesPI
 *  {
 *    typedef double argument_type;
 *    typedef double result_type;
 *    double operator()(double input) const { return input * M_PI; }
 *  };
 *
 *  BOOST_PYTHON_MODULE(example)
 *  {
 *    class_< TimesPI >("TimesPI")
 *      .def("__call__", unary_ufunc<TimesPI>::make());
 *  }
 *  @endcode
 *
 */
template <typename TUnaryFunctor,
          typename TArgument=typename TUnaryFunctor::argument_type,
          typename TResult=typename TUnaryFunctor::result_type>
struct unary_ufunc
{

  /**
   *  @brief A C++ function with object arguments that broadcasts its arguments before
   *         passing them to the underlying C++ functor.
   */
  static object call(TUnaryFunctor & self, object const & input, object const & output)
  {
    dtype in_dtype = dtype::get_builtin<TArgument>();
    dtype out_dtype = dtype::get_builtin<TResult>();
    ndarray in_array = from_object(input, in_dtype, ndarray::ALIGNED);
    ndarray out_array = ! output.is_none() ?
      from_object(output, out_dtype, ndarray::ALIGNED | ndarray::WRITEABLE)
      : zeros(in_array.get_nd(), in_array.get_shape(), out_dtype);
    multi_iter iter = make_multi_iter(in_array, out_array);
    while (iter.not_done())
    {
      TArgument * argument = reinterpret_cast<TArgument*>(iter.get_data(0));
      TResult * result = reinterpret_cast<TResult*>(iter.get_data(1));
      *result = self(*argument);
      iter.next();
    }
    return out_array.scalarize();
  }

  /**
   *  @brief Construct a boost.python function object from call() with reasonable keyword names.
   *
   *  Users will often want to specify their own keyword names with the same signature, but this
   *  is a convenient shortcut.
   */
  static object make()
  {
    return make_function(call, default_call_policies(), (arg("input"), arg("output")=object()));
  }
};

/**
 *  @brief Helps wrap a C++ functor taking a pair of scalar arguments as a broadcasting ufunc-like
 *         Python object.
 *
 *  Typical usage looks like this:
 *  @code
 *  struct CosSum
 *  {
 *    typedef double first_argument_type;
 *    typedef double second_argument_type;
 *    typedef double result_type;
 *    double operator()(double input1, double input2) const { return std::cos(input1 + input2); }
 *  };
 *
 *  BOOST_PYTHON_MODULE(example)
 *  {
 *    class_< CosSum >("CosSum")
 *      .def("__call__", binary_ufunc<CosSum>::make());
 *  }
 *  @endcode
 *
 */
template <typename TBinaryFunctor,
          typename TArgument1=typename TBinaryFunctor::first_argument_type,
          typename TArgument2=typename TBinaryFunctor::second_argument_type,
          typename TResult=typename TBinaryFunctor::result_type>
struct binary_ufunc
{

  static object
  call(TBinaryFunctor & self, object const & input1, object const & input2,
       object const & output)
  {
    dtype in1_dtype = dtype::get_builtin<TArgument1>();
    dtype in2_dtype = dtype::get_builtin<TArgument2>();
    dtype out_dtype = dtype::get_builtin<TResult>();
    ndarray in1_array = from_object(input1, in1_dtype, ndarray::ALIGNED);
    ndarray in2_array = from_object(input2, in2_dtype, ndarray::ALIGNED);
    multi_iter iter = make_multi_iter(in1_array, in2_array);
    ndarray out_array = !output.is_none()
      ? from_object(output, out_dtype, ndarray::ALIGNED | ndarray::WRITEABLE)
      : zeros(iter.get_nd(), iter.get_shape(), out_dtype);
    iter = make_multi_iter(in1_array, in2_array, out_array);
    while (iter.not_done())
    {
      TArgument1 * argument1 = reinterpret_cast<TArgument1*>(iter.get_data(0));
      TArgument2 * argument2 = reinterpret_cast<TArgument2*>(iter.get_data(1));
      TResult * result = reinterpret_cast<TResult*>(iter.get_data(2));
      *result = self(*argument1, *argument2);
      iter.next();
    }
    return out_array.scalarize();
  }

  static object make()
  {
    return make_function(call, default_call_policies(),
			    (arg("input1"), arg("input2"), arg("output")=object()));
  }

};

} // namespace boost::python::numpy

namespace converter
{

NUMPY_OBJECT_MANAGER_TRAITS(numpy::multi_iter);

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

#endif


text:
// This file is part of the dune-xt project:
//   https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Andreas Buhr    (2014)
//   Felix Schindler (2012 - 2014, 2016 - 2017)
//   René Fritze     (2011 - 2012, 2014 - 2019)
//   Tobias Leibner  (2014, 2016 - 2020)

#include <boost/config.hpp>

// Please sort these alphabetically!
#if defined(BOOST_CLANG) && BOOST_CLANG
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wall"
#  pragma GCC diagnostic ignored "-Wcovered-switch-default"
#  pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor"
#  pragma GCC diagnostic ignored "-Wdeprecated"
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#  pragma GCC diagnostic ignored "-Wdeprecated-register"
#  pragma GCC diagnostic ignored "-Wdisabled-macro-expansion"
#  pragma GCC diagnostic ignored "-Wextra"
#  pragma GCC diagnostic ignored "-Wfloat-equal"
#  pragma GCC diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#  pragma GCC diagnostic ignored "-Wignored-qualifiers"
#  pragma GCC diagnostic ignored "-Wlogical-not-parentheses"
#  pragma GCC diagnostic ignored "-Wlogical-op-parentheses"
#  pragma GCC diagnostic ignored "-Wmismatched-tags"
#  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#  pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#  pragma GCC diagnostic ignored "-Woverloaded-virtual"
#  pragma GCC diagnostic ignored "-Wpedantic"
#  pragma GCC diagnostic ignored "-Wredundant-decls"
#  pragma GCC diagnostic ignored "-Wreorder"
#  pragma GCC diagnostic ignored "-Wreturn-stack-address"
#  pragma GCC diagnostic ignored "-Wshadow"
#  pragma GCC diagnostic ignored "-Wshorten-64-to-32"
#  pragma GCC diagnostic ignored "-Wswitch-enum"
#  pragma GCC diagnostic ignored "-Wtype-limits"
#  pragma GCC diagnostic ignored "-Wundef"
#  pragma GCC diagnostic ignored "-Wuninitialized"
#  pragma GCC diagnostic ignored "-Wunreachable-code"
#  pragma GCC diagnostic ignored "-Wunused-const-variable"
#  pragma GCC diagnostic ignored "-Wunused-parameter"
#  pragma GCC diagnostic ignored "-Wunused-private-field"
#  pragma GCC diagnostic ignored "-Wused-but-marked-unused"
#elif defined(BOOST_GCC) && BOOST_GCC
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wall"
#  pragma GCC diagnostic ignored "-Wattributes"
#  if (__GNUC__ > 8)
#    pragma GCC diagnostic ignored "-Wdeprecated-copy"
#  endif
#  pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#  pragma GCC diagnostic ignored "-Wextra"
#  pragma GCC diagnostic ignored "-Wfloat-equal"
#  pragma GCC diagnostic ignored "-Wignored-qualifiers"
#  pragma GCC diagnostic ignored "-Wlogical-op"
#  if (__GNUC__ > 5)
#    pragma GCC diagnostic ignored "-Wmisleading-indentation"
#  endif
#  pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#  pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#  pragma GCC diagnostic ignored "-Woverloaded-virtual"
#  pragma GCC diagnostic ignored "-Wpedantic"
#  pragma GCC diagnostic ignored "-Wredundant-decls"
#  pragma GCC diagnostic ignored "-Wreorder"
#  pragma GCC diagnostic ignored "-Wshadow"
#  pragma GCC diagnostic ignored "-Wswitch-enum"
#  pragma GCC diagnostic ignored "-Wtype-limits"
#  pragma GCC diagnostic ignored "-Wundef"
#  pragma GCC diagnostic ignored "-Wuninitialized"
#  pragma GCC diagnostic ignored "-Wunreachable-code"
#  pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#  pragma GCC diagnostic ignored "-Wunused-parameter"
#elif defined(BOOST_INTEL) && BOOST_INTEL
#  pragma warning push
#  pragma warning disable 177 187 654 1011 2259 2282
#endif

ext: hh

max_stars_repo_name: dune-community/dune-xt

max_issues_repo_name: dune-community/dune-xt

max_forks_repo_name: dune-community/dune-xt


text:
/*!
 * @file
 * This file defines `boost::mpl::reachable_set`.
 */

#ifndef BOOST_MPL_REACHABLE_SET_HPP
#define BOOST_MPL_REACHABLE_SET_HPP

#include <boost/mpl/adjacent_vertices_of.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/filter_view.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/has_key.hpp>
#include <boost/mpl/insert.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/set.hpp>
#include <boost/mpl/vector.hpp>

namespace boost { namespace mpl {
namespace reachable_set_detail {
    template <typename Graph>
    struct impl {
        template <typename Vertex, typename Seen>
        struct unseen_adjacent_vertices {
            using type = filter_view<
                typename adjacent_vertices_of<Graph, Vertex>::type,
                not_<has_key<Seen, _1>>
            >;
        };

        template <typename Seen, typename ToVisit, bool=empty<ToVisit>::value>
        struct apply {
            using Vertex = typename front<ToVisit>::type;

            using NewToVisit = typename pop_front<ToVisit>::type;
            using NewSeen = typename insert<Seen, Vertex>::type;

            using type = typename apply<
                NewSeen,
                typename insert_range<
                    NewToVisit,
                    typename end<NewToVisit>::type,
                    typename unseen_adjacent_vertices<Vertex, NewSeen>::type
                >::type
            >::type;
        };

        template <typename Seen, typename ToVisit>
        struct apply<Seen, ToVisit, true> {
            using type = Seen;
        };
    };
} // end namespace reachable_set_detail

//! Return the set of all the vertices that are reachable from a `Vertex`.
template <typename Graph, typename Vertex>
struct reachable_set
    : reachable_set_detail::impl<
        Graph
    >::template apply<typename set<>::type, typename vector<Vertex>::type>
{ };
}} // end namespace boost::mpl

#endif // !BOOST_MPL_REACHABLE_SET_HPP


text:
// Copyright Jim Bosch & Ankit Daftery 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)

#include <boost/python/numpy.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/vector_c.hpp>

namespace p = boost::python;
namespace np = boost::python::numpy;

struct ArrayFiller
{

  typedef boost::mpl::vector< short, int, float, std::complex<double> > TypeSequence;
  typedef boost::mpl::vector_c< int, 1, 2 > DimSequence;

  explicit ArrayFiller(np::ndarray const & arg) : argument(arg) {}

  template <typename T, int N>
  void apply() const
  {
    if (N == 1)
    {
      char * p = argument.get_data();
      int stride = argument.strides(0);
      int size = argument.shape(0);
      for (int n = 0; n != size; ++n, p += stride)
	*reinterpret_cast<T*>(p) = static_cast<T>(n);
    }
    else
    {
      char * row_p = argument.get_data();
      int row_stride = argument.strides(0);
      int col_stride = argument.strides(1);
      int rows = argument.shape(0);
      int cols = argument.shape(1);
      int i = 0;
      for (int n = 0; n != rows; ++n, row_p += row_stride)
      {
	char * col_p = row_p;
	for (int m = 0; m != cols; ++i, ++m, col_p += col_stride)
	  *reinterpret_cast<T*>(col_p) = static_cast<T>(i);
      }
    }
  }

  np::ndarray argument;
};

void fill(np::ndarray const & arg)
{
  ArrayFiller filler(arg);
  np::invoke_matching_array<ArrayFiller::TypeSequence, ArrayFiller::DimSequence >(arg, filler);
}

BOOST_PYTHON_MODULE(templates_ext)
{
  np::initialize();
  p::def("fill", fill);
}


text:
/*
 * Copyright (C) 2018 CESNET, https://photonics.cesnet.cz/
 * Copyright (C) 2018 FIT CVUT, https://fit.cvut.cz/
 *
 * Written by Václav Kubernát <kubervac@fit.cvut.cz>
 *
*/
#include <atomic>
#include <boost/algorithm/string.hpp>
#include <docopt.h>
#include <iostream>
#include <optional>
#include <replxx.hxx>
#include <sstream>
#include "NETCONF_CLI_VERSION.h"
#include "interpreter.hpp"
#include "proxy_datastore.hpp"
#include "yang_schema.hpp"
#if defined(SYSREPO_CLI)
#include "sysrepo_access.hpp"
#define PROGRAM_NAME "sysrepo-cli"
static const auto usage = R"(CLI interface to sysrepo

Usage:
  sysrepo-cli [-d <datastore_target>]
  sysrepo-cli (-h | --help)
  sysrepo-cli --version

Options:
  -d <datastore_target>   can be "running", "startup" or "operational" [default: operational])";
#elif defined(YANG_CLI)
#include <boost/spirit/home/x3.hpp>
#include <filesystem>
#include "yang_access.hpp"
#define PROGRAM_NAME "yang-cli"
static const auto usage = R"(CLI interface for creating local YANG data instances

  The <schema_file_or_module_name> argument is treated as a file name if a file
  with such a path exists, otherwise it's treated as a module name. Search dirs
  will be used to find a schema for that module.

Usage:
  yang-cli [--configonly] [-s <search_dir>] [-e enable_features]... [-i data_file]... <schema_file_or_module_name>...
  yang-cli (-h | --help)
  yang-cli --version

Options:
  -s <search_dir>       Set search for schema lookup
  -e <enable_features>  Feature to enable after modules are loaded. This option can be supplied more than once. Format: <module_name>:<feature>
  -i <data_file>        File to import data from
  --configonly          Disable editing of operational data)";
#elif defined(NETCONF_CLI)
// FIXME: improve usage
static const auto usage = R"(CLI interface for NETCONF

Usage:
  netconf-cli [-v] [-d <datastore_target>] [-p <port>] <host>
  netconf-cli [-v] [-d <datastore_target>] --socket <path>
  netconf-cli (-h | --help)
  netconf-cli --version

Options:
  -v         enable verbose mode
  -p <port>  port number [default: 830]
  -d <datastore_target>   can be "running", "startup" or "operational" [default: operational])";
#include "cli-netconf.hpp"
#include "netconf_access.hpp"
#define PROGRAM_NAME "netconf-cli"
// FIXME: this should be replaced by C++20 std::jthread at some point
struct PoorMansJThread {
    ~PoorMansJThread()
    {
        if (thread.joinable()) {
            thread.join();
        }
    }
    std::thread thread;
};
#else
#error "Unknown CLI backend"
#endif

const auto HISTORY_FILE_NAME = PROGRAM_NAME "_history";

int main(int argc, char* argv[])
{
    auto args = docopt::docopt(usage,
                               {argv + 1, argv + argc},
                               true,
                               PROGRAM_NAME " " NETCONF_CLI_VERSION,
                               true);
    WritableOps writableOps = WritableOps::No;

    using replxx::Replxx;
    Replxx lineEditor;
    std::atomic<int> backendReturnCode = 0;

    // For some reason, GCC10 still needs [[maybe_unused]] because of conditional compilation...
    [[maybe_unused]] auto datastoreTarget = DatastoreTarget::Operational;
    if (const auto& ds = args["-d"]) {
        if (ds.asString() == "startup") {
            datastoreTarget = DatastoreTarget::Startup;
        } else if (ds.asString() == "running") {
            datastoreTarget = DatastoreTarget::Running;
        } else if (ds.asString() == "operational") {
            datastoreTarget = DatastoreTarget::Operational;
        } else {
            std::cerr << PROGRAM_NAME << ": unknown datastore target: " << ds.asString() << "\n";
            return 1;
        }
    }

    auto datastoreTargetString = args["-d"] ? args["-d"].asString() : std::string("operational");

#if defined(SYSREPO_CLI)
    auto datastore = std::make_shared<SysrepoAccess>();
    std::cout << "Connected to sysrepo [datastore target: " << datastoreTargetString << "]" << std::endl;
#elif defined(YANG_CLI)
    auto datastore = std::make_shared<YangAccess>();
    if (args["--configonly"].asBool()) {
        writableOps = WritableOps::No;
    } else {
        writableOps = WritableOps::Yes;
        std::cout << "ops is writable" << std::endl;
    }
    if (const auto& search_dir = args["-s"]) {
        datastore->addSchemaDir(search_dir.asString());
    }
    for (const auto& schemaFile : args["<schema_file_or_module_name>"].asStringList()) {
        if (std::filesystem::exists(schemaFile)) {
            datastore->addSchemaFile(schemaFile);
        } else if (schemaFile.find('/') == std::string::npos) { // Module names cannot have a slash
            datastore->loadModule(schemaFile);
        } else {
            std::cerr << "Cannot load YANG module " << schemaFile << "\n";
        }
    }
    if (const auto& enableFeatures = args["-e"]) {
        namespace x3 = boost::spirit::x3;
        auto grammar = +(x3::char_-":") >> ":" >> +(x3::char_-":");
        for (const auto& enableFeature : enableFeatures.asStringList()) {
            std::pair<std::string, std::string> parsed;
            auto it = enableFeature.begin();
            auto res = x3::parse(it, enableFeature.cend(), grammar, parsed);
            if (!res || it != enableFeature.cend()) {
                std::cerr << "Error parsing feature enable flags: " << enableFeature << "\n";
                return 1;
            }
            try {
                datastore->enableFeature(parsed.first, parsed.second);
            } catch (std::runtime_error& ex) {
                std::cerr << ex.what() << "\n";
                return 1;
            }
        }
    }
    if (const auto& dataFiles = args["-i"]) {
        for (const auto& dataFile : dataFiles.asStringList()) {
            datastore->addDataFile(dataFile);
        }
    }
#elif defined(NETCONF_CLI)
    auto verbose = args.at("-v").asBool();
    if (verbose) {
        NetconfAccess::setNcLogLevel(NC_VERB_DEBUG);
    }

    SshProcess process;
    PoorMansJThread processWatcher;
    std::shared_ptr<NetconfAccess> datastore;

    if (args.at("--socket").asBool()) {
        try {
            datastore = std::make_shared<NetconfAccess>(args.at("<path>").asString());
        } catch (std::runtime_error& ex) {
            std::cerr << "UNIX socket connection failed: " << ex.what() << std::endl;
            return 1;
        }
    } else {
        try {
            process = sshProcess(args.at("<host>").asString(), args.at("-p").asString());
            processWatcher.thread = std::thread{std::thread{[&process, &lineEditor, &backendReturnCode] () {
                process.process.wait();
                backendReturnCode = process.process.exit_code();
                // CTRL-U clears from the cursor to the start of the line
                // CTRL-K clears from the cursor to the end of the line
                // CTRL-D send EOF
                lineEditor.emulate_key_press(replxx::Replxx::KEY::control('U'));
                lineEditor.emulate_key_press(replxx::Replxx::KEY::control('K'));
                lineEditor.emulate_key_press(replxx::Replxx::KEY::control('D'));
            }}};
            datastore = std::make_shared<NetconfAccess>(process.std_out.native_source(), process.std_in.native_sink());
        } catch (std::runtime_error& ex) {
            std::cerr << "SSH connection failed: " << ex.what() << std::endl;
            return 1;
        }
    }
    std::cout << "Connected via NETCONF [datastore target: " << datastoreTargetString << "]" << std::endl;
#else
#error "Unknown CLI backend"
#endif

    datastore->setTarget(datastoreTarget);

#if defined(SYSREPO_CLI) || defined(NETCONF_CLI)
    auto createTemporaryDatastore = [](const std::shared_ptr<DatastoreAccess>& datastore) {
        return std::make_shared<YangAccess>(std::static_pointer_cast<YangSchema>(datastore->schema()));
    };
#elif defined(YANG_CLI)
    auto createTemporaryDatastore = [](const std::shared_ptr<DatastoreAccess>&) {
        return nullptr;
    };
#endif

    ProxyDatastore proxyDatastore(datastore, createTemporaryDatastore);
    auto dataQuery = std::make_shared<DataQuery>(*datastore);
    Parser parser(datastore->schema(), writableOps, dataQuery);

    lineEditor.bind_key(Replxx::KEY::meta(Replxx::KEY::BACKSPACE), [&lineEditor](const auto& code) {
        return lineEditor.invoke(Replxx::ACTION::KILL_TO_BEGINING_OF_WORD, code);
    });
    lineEditor.bind_key(Replxx::KEY::control('W'), [&lineEditor](const auto& code) {
        return lineEditor.invoke(Replxx::ACTION::KILL_TO_WHITESPACE_ON_LEFT, code);
    });

    lineEditor.set_word_break_characters("\t _[]/:'\"=-%");

    lineEditor.set_completion_callback([&parser](const std::string& input, int& context) {
        std::stringstream stream;
        Completions completions;
        try {
            completions = parser.completeCommand(input, stream);
        } catch (std::exception& ex) {
            std::cerr << "Error while completing: " << ex.what() << "\n";
        }

        std::vector<replxx::Replxx::Completion> res;
        std::copy(completions.m_completions.begin(), completions.m_completions.end(), std::back_inserter(res));
        context = completions.m_contextLength;
        return res;
    });

    std::optional<std::string> historyFile;
    if (auto xdgHome = getenv("XDG_DATA_HOME")) {
        historyFile = std::string(xdgHome) + "/" + HISTORY_FILE_NAME;
    } else if (auto home = getenv("HOME")) {
        historyFile = std::string(home) + "/.local/share/" + HISTORY_FILE_NAME;
    }

    if (historyFile) {
        lineEditor.history_load(historyFile.value());
    }

    while (backendReturnCode == 0) {
        auto fullContextPath = parser.currentNode();
        std::string prompt;
        if (auto activeRpcPath = proxyDatastore.inputDatastorePath()) {
            auto rpcPrefixLength = activeRpcPath->size();
            prompt = "(prepare: " + *activeRpcPath + ") " + fullContextPath.substr(rpcPrefixLength);
        } else {
            prompt = fullContextPath;
        }

        prompt += "> ";

        auto line = lineEditor.input(prompt);
        if (!line) {
            // If user pressed CTRL-C to abort the line, errno gets set to EAGAIN.
            // If user pressed CTRL-D (for EOF), errno doesn't get set to EAGAIN, so we exit the program.
            // I have no idea why replxx uses errno for this.
            if (errno == EAGAIN) {
                continue;
            } else {
                break;
            }
        }

        std::locale C_locale("C");
        std::string_view view{line};
        if (std::all_of(view.begin(), view.end(),
                        [C_locale](const auto c) { return std::isspace(c, C_locale);})) {
            continue;
        }

        try {
            command_ cmd = parser.parseCommand(line, std::cout);
            boost::apply_visitor(Interpreter(parser, proxyDatastore), cmd);
        } catch (InvalidCommandException& ex) {
            std::cerr << ex.what() << std::endl;
        } catch (DatastoreException& ex) {
            std::cerr << ex.what() << std::endl;
        } catch (std::runtime_error& ex) {
            std::cerr << ex.what() << std::endl;
        } catch (std::logic_error& ex) {
            std::cerr << ex.what() << std::endl;
        }

        lineEditor.history_add(line);
    }

    if (historyFile) {
        lineEditor.history_save(historyFile.value());
    }

    return backendReturnCode;
}

max_stars_repo_name: CESNET/netconf-cli

max_issues_repo_name: CESNET/netconf-cli

max_forks_repo_name: CESNET/netconf-cli


text:
/* Copyright © 2017 Apple Inc. All rights reserved.
 *
 * Use of this source code is governed by a BSD-3-clause license that can
 * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
 */
#define BOOST_TEST_MODULE
#include <boost/test/unit_test.hpp>
#include <util/test_macros.hpp>
#include <vector>
#include <string>
#include <random/random.hpp>
#include <sframe/testing_utils.hpp>
#include <util/testing_utils.hpp>

#include <unity/toolkits/sparse_similarity/neighbor_search.hpp>
#include <util/cityhash_tc.hpp>
#include <logger/assertions.hpp>

#include "generate_sparse_data.hpp"

using namespace turi;

static double calc_similarity(
    const sparse_sim::jaccard&,
    const std::vector<std::pair<size_t, double> >& x1,
    const std::vector<std::pair<size_t, double> >& x2) {

  double v12 = 0;
  double v1 = 0, v2 = 0;

  auto it_1 = x1.begin();
  auto it_2 = x2.begin();

  size_t biggest_idx = std::numeric_limits<size_t>::max();

  while(it_1 != x1.end() || it_2 != x2.end()) {

    size_t it_2_index = it_2 != x2.end() ? it_2->first : biggest_idx;
    while(it_1 != x1.end() && it_1->first < it_2_index) {
      v1 += (it_1->second != 0 ? 1 : 0);
      ++it_1;
    }

    size_t it_1_index = it_1 != x1.end() ? it_1->first : biggest_idx;
    while(it_2 != x2.end() && it_2->first < it_1_index) {
      v2 += (it_2->second != 0 ? 1 : 0);
      ++it_2;
    }

    while(it_1 != x1.end() && it_2 != x2.end() && it_1->first == it_2->first) {
      v1 += (it_1->second != 0 ? 1 : 0);
      v2 += (it_2->second != 0 ? 1 : 0);
      v12 += (it_1->second != 0 && it_2->second != 0) ? 1 : 0;
      ++it_1, ++it_2;
    }
  }

  return (v1 + v2 == 0) ? 0 : v12 / (v1 + v2 - v12);
}

static double calc_similarity(
    const sparse_sim::cosine&,
    const std::vector<std::pair<size_t, double> >& x1,
    const std::vector<std::pair<size_t, double> >& x2) {

  double v12 = 0;
  double v1 = 0, v2 = 0;

  auto it_1 = x1.begin();
  auto it_2 = x2.begin();

  size_t biggest_idx = std::numeric_limits<size_t>::max();

  while(it_1 != x1.end() || it_2 != x2.end()) {

    size_t it_2_index = it_2 != x2.end() ? it_2->first : biggest_idx;
    while(it_1 != x1.end() && it_1->first < it_2_index) {
      v1 += std::pow(it_1->second, 2);
      ++it_1;
    }

    size_t it_1_index = it_1 != x1.end() ? it_1->first : biggest_idx;
    while(it_2 != x2.end() && it_2->first < it_1_index) {
      v2 += std::pow(it_2->second, 2);
      ++it_2;
    }

    while(it_1 != x1.end() && it_2 != x2.end() && it_1->first == it_2->first) {
      v1 += std::pow(it_1->second, 2);
      v2 += std::pow(it_2->second, 2);
      v12 += it_1->second * it_2->second;
      ++it_1, ++it_2;
    }
  }

  return v12 / std::max(1e-16, std::sqrt(v1 * v2));
}

////////////////////////////////////////////////////////////////////////////////

template <typename Similarity, typename T>
void run_test(const std::vector<std::vector<std::pair<size_t, T> > >& data_1,
              const std::vector<std::vector<std::pair<size_t, T> > >& data_2) {

  Similarity similarity;

  auto data_1_sa = make_testing_sarray(data_1);
  auto data_2_sa = make_testing_sarray(data_2);

  if(&data_1 == &data_2) {
    data_2_sa = data_1_sa;
  }

  size_t n = data_1.size();
  size_t m = data_2.size();

  size_t num_dimensions = 0;
  for(const auto& row : data_1) {
    for(const auto& p : row) {
      num_dimensions = std::max(num_dimensions, p.first + 1);
    }
  }

  for(const auto& row : data_2) {
    for(const auto& p : row) {
      num_dimensions = std::max(num_dimensions, p.first + 1);
    }
  }

  // Set the max memory usage
  size_t max_memory_usage = (sizeof(double) * num_dimensions
                             * (std::max<size_t>(16, (data_2.size() / 16))));

  std::vector<int> hit(n * m, false);

  auto process_function_full = [&](size_t ref_idx, size_t query_idx, double value) {
    DASSERT_LT(ref_idx, n);
    DASSERT_LT(query_idx, m);

    size_t idx = ref_idx * m + query_idx;

    ASSERT_FALSE(hit[idx]);

    hit[idx] = true;

    TURI_ATTRIBUTE_UNUSED_NDEBUG double calc_sim = calc_similarity(
      similarity, data_1[ref_idx], data_2[query_idx]);
    DASSERT_DELTA(calc_sim, value, 2e-5);
  };

  // Don't skip things.
  auto skip_pair = [](size_t, size_t) { return false; };

  all_pairs_similarity(data_1_sa, data_2_sa, similarity,
                       process_function_full, max_memory_usage, skip_pair);

  TURI_ATTRIBUTE_UNUSED_NDEBUG auto bool_not = [](bool x) { return !x; };
  DASSERT_TRUE(std::count_if(hit.begin(), hit.end(), bool_not) == 0);

  ////////////////////////////////////////////////////////////////////////////////
  // Now, test that masks are used correctly.

  auto test_mask = [&](const dense_bitset& query_mask) {

    hit.assign(n*m, false);

    auto process_function_dense_bitset = [&](size_t ref_idx, size_t query_idx, double value) {
      DASSERT_LT(ref_idx, n);
      DASSERT_LT(query_idx, m);

      size_t idx = ref_idx * m + query_idx;

      DASSERT_TRUE(query_mask.get(query_idx));
      DASSERT_FALSE(hit[idx]);

      hit[idx] = true;

      TURI_ATTRIBUTE_UNUSED_NDEBUG double calc_sim = calc_similarity(
        similarity, data_1[ref_idx], data_2[query_idx]);
      DASSERT_TRUE(query_mask.get(query_idx));
      DASSERT_DELTA(calc_sim, value, 2e-5);
    };

    all_pairs_similarity(data_1_sa, data_2_sa, similarity,
                         process_function_dense_bitset, max_memory_usage, skip_pair, &query_mask);

    // Make sure we've only queried the ones with the mask on.
    for(size_t i = 0; i < n; ++i) {
      for(size_t j = 0; j < m; ++j) {
        TURI_ATTRIBUTE_UNUSED_NDEBUG size_t idx = i * m + j;

        if(query_mask.get(j)) {
          DASSERT_TRUE(hit[idx]);
        } else {
          DASSERT_FALSE(hit[idx]);
        }
      }
    }
  };

  {
    dense_bitset query_mask(m);

    // Make sure it works with no entries at all.
    test_mask(query_mask);

    query_mask.invert();

    // Make sure it works with all entries.
    test_mask(query_mask);

  }

  // Make sure it works with a random subset
  if(m >= 2) {
    dense_bitset query_mask(m);

    query_mask.set_bit(1);

    // Make sure it works with no entries at all.
    for(size_t i = 2; i < m; ++i) {
      if(random::fast_uniform<int>(0, 1) == 0) {
        query_mask.set_bit(i);
      }
    }

    test_mask(query_mask);
  }
}

////////////////////////////////////////////////////////////////////////////////

template <typename Similarity>
void run_random_test(size_t n, size_t m, double p,
                     bool allow_negative, bool binary) {

  // Determanistic seed for this test.
  random::seed(n*m + 1000000000*allow_negative + 3000000000*binary + size_t(100000000*p));

  auto data_1 = generate(n, m, p, allow_negative, binary);
  auto data_2 = generate(n, m, p, allow_negative, binary);

  run_test<Similarity>(data_1, data_1);
  run_test<Similarity>(data_2, data_2);
  run_test<Similarity>(data_1, data_2);
}

////////////////////////////////////////////////////////////////////////////////

struct item_sim_all_pairs_test {
 public:

  void test_simple_1_jaccard() {

    std::vector<std::vector<std::pair<size_t, double> > > data
        = { { {0, 1}, {1, 1}, {2, 1} } };

    run_test<sparse_sim::jaccard>(data, data);
  }

  void test_simple_2_jaccard() {

    std::vector<std::vector<std::pair<size_t, double> > > data_1
        = { { {0, 1}, {1, 1}, {2, 1} } };
    std::vector<std::vector<std::pair<size_t, double> > > data_2
        = { { {0, 1}, {1, 1}, {3, 1} } };

    run_test<sparse_sim::jaccard>(data_1, data_2);
  }

  void test_simple_3_jaccard() {

    std::vector<std::vector<std::pair<size_t, double> > > data_1
        = { { {0, 1}, {1, 1}, {2, 1} },
            { {0, 1}, {1, 1}, {3, 1} } };
    std::vector<std::vector<std::pair<size_t, double> > > data_2
        = { { {0, 1}, {1, 1}, {3, 1} },
            { {0, 1}, {4, 1} } };

    run_test<sparse_sim::jaccard>(data_1, data_2);
  }

  void test_simple_1_cosine() {

    std::vector<std::vector<std::pair<size_t, double> > > data
        = { { {0, 1}, {1, 0.5}, {2, -0.5} } };

    run_test<sparse_sim::cosine>(data, data);
  }

  void test_simple_2_cosine() {

    std::vector<std::vector<std::pair<size_t, double> > > data_1
        = { { {0, 1}, {1, 0.5}, {2, 0.4} } };
    std::vector<std::vector<std::pair<size_t, double> > > data_2
        = { { {0, 1}, {1, 0.2}, {3, -1} } };

    run_test<sparse_sim::cosine>(data_1, data_2);
  }

  void test_simple_3_cosine() {

    std::vector<std::vector<std::pair<size_t, double> > > data_1
        = { { {0, 1}, {1, 1}, {2, 0.5} },
            { {0, -0.5}, {1, 0.1}, {3, 0.2} } };
    std::vector<std::vector<std::pair<size_t, double> > > data_2
        = { { {0, 1}, {1, 0.1}, {3, 1} },
            { {0, 0.1}, {4, 0.3} } };

    run_test<sparse_sim::cosine>(data_1, data_2);
  }

  void test_random_1_jaccard_20m20() {
    run_random_test<sparse_sim::jaccard>(20, 20, 0.5, false, true);
  }

  void test_random_2_jaccard_100m100() {
    run_random_test<sparse_sim::jaccard>(100, 100, 0.25, false, true);
  }

  void test_random_3_jaccard_1000m25() {
    run_random_test<sparse_sim::jaccard>(1000, 25, 0.25, false, true);
  }

  void test_random_1_cosine_20m20() {
    run_random_test<sparse_sim::cosine>(20, 20, 0.5, true, false);
  }

  void test_random_2_cosine_100m100() {
    run_random_test<sparse_sim::cosine>(100, 100, 0.25, true, false);
  }

  void test_random_3_cosine_1000m25() {
    run_random_test<sparse_sim::cosine>(1000, 25, 0.25, true, false);
  }

};

BOOST_FIXTURE_TEST_SUITE(_item_sim_all_pairs_test, item_sim_all_pairs_test)
BOOST_AUTO_TEST_CASE(test_simple_1_jaccard) {
  item_sim_all_pairs_test::test_simple_1_jaccard();
}
BOOST_AUTO_TEST_CASE(test_simple_2_jaccard) {
  item_sim_all_pairs_test::test_simple_2_jaccard();
}
BOOST_AUTO_TEST_CASE(test_simple_3_jaccard) {
  item_sim_all_pairs_test::test_simple_3_jaccard();
}
BOOST_AUTO_TEST_CASE(test_simple_1_cosine) {
  item_sim_all_pairs_test::test_simple_1_cosine();
}
BOOST_AUTO_TEST_CASE(test_simple_2_cosine) {
  item_sim_all_pairs_test::test_simple_2_cosine();
}
BOOST_AUTO_TEST_CASE(test_simple_3_cosine) {
  item_sim_all_pairs_test::test_simple_3_cosine();
}
BOOST_AUTO_TEST_CASE(test_random_1_jaccard_20m20) {
  item_sim_all_pairs_test::test_random_1_jaccard_20m20();
}
BOOST_AUTO_TEST_CASE(test_random_2_jaccard_100m100) {
  item_sim_all_pairs_test::test_random_2_jaccard_100m100();
}
BOOST_AUTO_TEST_CASE(test_random_3_jaccard_1000m25) {
  item_sim_all_pairs_test::test_random_3_jaccard_1000m25();
}
BOOST_AUTO_TEST_CASE(test_random_1_cosine_20m20) {
  item_sim_all_pairs_test::test_random_1_cosine_20m20();
}
BOOST_AUTO_TEST_CASE(test_random_2_cosine_100m100) {
  item_sim_all_pairs_test::test_random_2_cosine_100m100();
}
BOOST_AUTO_TEST_CASE(test_random_3_cosine_1000m25) {
  item_sim_all_pairs_test::test_random_3_cosine_1000m25();
}
BOOST_AUTO_TEST_SUITE_END()

ext: cxx

max_stars_repo_name: LeeCenY/turicreate

max_issues_repo_name: LeeCenY/turicreate

max_forks_repo_name: ZeroInfinite/turicreate


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#include <iostream>
#include <cmath>
#include <boost/numeric/mtl/vector/dense_vector.hpp>
#include <boost/numeric/mtl/vector/parameter.hpp>
#include <boost/numeric/mtl/operation/operators.hpp>
#include <boost/numeric/mtl/operation/dot.hpp>
#include <boost/numeric/mtl/operation/pow.hpp>

using namespace std;

template <typename Vector>
void one_d_iteration(char const* name, Vector & vector, size_t check_index, typename Vector::value_type check)
{
    namespace traits = mtl::traits;
    typename traits::index<Vector>::type                               index(vector);
    typename traits::value<Vector>::type                               value(vector);
    typedef  mtl::tag::nz                                              tag;
    typedef typename traits::range_generator<tag, Vector>::type        cursor_type;
    typedef typename traits::range_generator<tag, Vector>::complexity  complexity;

    cout << name << "\nElements: " << complexity() << '\n';
    for (cursor_type cursor = mtl::begin<tag>(vector), cend = mtl::end<tag>(vector); cursor != cend; ++cursor) {
	// cout << "vector[" << index(*cursor) << "] = " << value(*cursor) << '\n';
	if (index(*cursor) == check_index && value(*cursor) != check)
	    throw "wrong check value";
    }
}

template <typename VectorU, typename VectorV, typename VectorW>
void test(VectorU& u, VectorV& v, VectorW& w, const char* name)
{
    u= 3.0; v= 4.0; w= 5.0;

    std::cout << "\n\n";
    one_d_iteration(name, u, 2, (typename VectorU::value_type)(3.0));

    std::cout << name << "  --- u= v + w:" << std::endl;
    u= v + w;
    cout << "u: " << u << std::endl;
    MTL_THROW_IF(u[0] != 9.0, mtl::runtime_error("wrong"));

    std::cout << name << "  --- u= ele_prod(v, w):" << std::endl;
    u= ele_prod(v, w);
    cout << "u: " << u << std::endl;
    MTL_THROW_IF(u[0] != 20.0, mtl::runtime_error("wrong"));

    std::cout << name << "  --- u= ele_prod(v, w) + w:" << std::endl;
    u= ele_prod(v, w) + w;
    cout << "u: " << u << std::endl;
    MTL_THROW_IF(u[0] != 25.0, mtl::runtime_error("wrong"));

    std::cout << name << "  --- u= ele_quot(v, w):" << std::endl;
    u= ele_quot(v, w);
    cout << "u: " << u << std::endl;
    MTL_THROW_IF(abs(u[0] - 0.8) > 0.01, mtl::runtime_error("wrong"));

    std::cout << name << "  --- u= ele_quot(v+w, w):" << std::endl;
    u= ele_quot(v+w, w);
    cout << "u: " << u << std::endl;
    MTL_THROW_IF(abs(u[0] - 1.8) > 0.01, mtl::runtime_error("wrong"));

    std::cout << name << "  --- u= v + w + v + w:" << std::endl;
    u= v + w + v + w;
    cout << "u: " << u << std::endl;
    MTL_THROW_IF(u[0] != 18.0, mtl::runtime_error("wrong"));

    std::cout << name << "  --- u= w + (v= w + w);:" << std::endl;
    u= w + (v= w + w);
    cout << "u: " << u << "v: " << v << std::endl;
    MTL_THROW_IF(v[0] != 10.0, mtl::runtime_error("v wrong"));
    MTL_THROW_IF(u[0] != 15.0, mtl::runtime_error("u wrong"));

    std::cout << name << "  --- u= (v= w + w) + v;:" << std::endl;
    v= 4.0; w= 5.0; u= (v= w + w) + v;
    cout << "u: " << u << "v: " << v << std::endl;
    MTL_THROW_IF(v[0] != 10.0, mtl::runtime_error("v wrong"));
    MTL_THROW_IF(u[0] != 20.0, mtl::runtime_error("u wrong"));

    std::cout << name << "  --- w= 4; u-= (v= w + w) - w;:" << std::endl;
    w= 4; u-= (v= w + w) - w;
    cout << "u: " << u << "v: " << v << std::endl;
    MTL_THROW_IF(v[0] != 8.0, mtl::runtime_error("v wrong"));
    MTL_THROW_IF(u[0] != 16.0, mtl::runtime_error("u wrong")); // for -=

    std::cout << name << "  --- v= 3*u + 4*w;:" << std::endl;
    v= 3*u + 4*w;
    cout << "v: " << v << std::endl;
    MTL_THROW_IF(v[0] != 64.0, mtl::runtime_error("v wrong"));

    std::cout << name << "  --- u= 3; v= 4; u+= v+= 3.0 * (w= 5);:" << std::endl;
    u= 3; v= 4;
    u+= v+= 3.0 * (w= 5.0);
    cout << "u: " << u << "v: " << v << std::endl;
    MTL_THROW_IF(v[0] != 19.0, mtl::runtime_error("v wrong"));
    MTL_THROW_IF(u[0] != 22.0, mtl::runtime_error("u wrong"));

    std::cout << name << "  --- u= 3; v= 4; w=5; u+= (v*= 3.0) + (w*= 2.0);:" << std::endl;
    u= 3; v= 4; w=5; u+= (v*= 3.0) + (w*= 2.0);
    cout << "u: " << u << "v: " << v << "w: " << w << std::endl;
    MTL_THROW_IF(v[0] != 12.0, mtl::runtime_error("v wrong"));
    MTL_THROW_IF(w[0] != 10.0, mtl::runtime_error("v wrong"));
    MTL_THROW_IF(u[0] != 25.0, mtl::runtime_error("u wrong"));

    std::cout << name << "  --- u= 3; v= 4; w=5; u+= dot(v, w) * w;:" << std::endl;
    u= 3; v= 4; w=5; u+= dot(v, w) * w;
    cout << "u: " << u << "v: " << v << "w: " << w << std::endl;
    MTL_THROW_IF(u[0] != 503.0, mtl::runtime_error("u wrong"));

    std::cout << name << "  --- u+= dot<12>(v, w) * w;:" << std::endl;
    u+= mtl::dot<12>(v, w) * w;
    cout << "u: " << u << "v: " << v << "w: " << w << std::endl;
    MTL_THROW_IF(u[0] != 1003.0, mtl::runtime_error("u wrong"));

    std::cout << name << "  --- u= pow(v, 2.0); // with v= 1, 2, 3, 4, 5;" << std::endl;
    v= 1, 2, 3, 4, 5;
    u= pow(v, 2.0);
    cout << "u: " << u << "v: " << v << std::endl;
    MTL_THROW_IF(abs(u[4] - 25) > 0.0001, mtl::runtime_error("u wrong"));
}

int main(int , char**)
{
    using mtl::vec::parameters;
    using namespace mtl;

    dense_vector<float>   u(5), v(5), w(5);
    dense_vector<double>  x(5), y(5), z(5);
    dense_vector<std::complex<double> >  xc(5), yc(5), zc(5);

    std::cout << "Testing vector operations\n";

    test(u, v, w, "test float");
    test(x, y, z, "test double");
    test(u, x, y, "test float, double mixed");
#if 0
    // test is not designed for complex
    test(xc, yc, zc, "test complex<double>");
    test(x, yc, zc, "test complex<double>, double mixed");
#endif

    dense_vector<float, parameters<row_major> >   ur(5), vr(5), wr(5);
    test(ur, vr, wr, "test float in row vector");

    // test(ur, v, wr, "test float in mixed vector (shouldn't work)");

    return 0;
}


text:
//  Copyright (c) 2006-2009, Bernhard Reiter
//
//  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)

/** @file   iterative_algorithms.hpp
 *
 * Some iterative algorithm versions that are identical for all *order cursors
 * (as we are just calling the appropriate traversal function that are
 * defined in the respective *order.hpp files).
 */

#ifndef BOOST_TREE_DETAIL_ITERATIVE_ALGORITHMS_HPP
#define BOOST_TREE_DETAIL_ITERATIVE_ALGORITHMS_HPP

#include <boost/tree/coupling_cursor.hpp>

#include <boost/tree/preorder_algorithms.hpp>
#include <boost/tree/inorder_algorithms.hpp>
#include <boost/tree/postorder_algorithms.hpp>

#include <boost/tree/root_tracking_cursor.hpp>

#include <boost/tree/cursor_concepts.hpp>

#include <boost/concept/requires.hpp>

namespace boost {
namespace tree {
namespace detail {

// .base() !!!
template <class Order, class Cursor, class Op>
BOOST_CONCEPT_REQUIRES(
    ((DescendingCursor<Cursor>))
    ((AscendingCursor<Cursor>)), // FIXME: Also RootTrackingCursor?
    (Op)) // return type
for_each(Order, Cursor s, Cursor s2, Op f, ascending_vertical_traversal_tag)
{
    while (s!=s2) {
        f(*s);
        successor(Order(), s);
    }
    return f;
}

template <class Order, class Cursor, class Op>
BOOST_CONCEPT_REQUIRES(
    ((DescendingCursor<Cursor>))
    ((AscendingCursor<Cursor>)),
    (Op)) // return type
for_each(Order, Cursor is, Op f, ascending_vertical_traversal_tag)
{
    root_tracking_cursor<Cursor> s(is);
    root_tracking_cursor<Cursor> s2(is);
    to_first(Order(), s);
//    to_last(Order(), s2);
//    return detail::for_each(Order(), s, s2, f, ascending_vertical_traversal_tag());
    do {
        f(*s);
    } while (successor(Order(), s));
    return f;
}

template <class Order, class InCursor, class OutCursor, class Op>
BOOST_CONCEPT_REQUIRES(
    ((DescendingCursor<InCursor>))
    ((AscendingCursor<InCursor>))
    ((DescendingCursor<OutCursor>))
    ((AscendingCursor<OutCursor>)),
    (OutCursor)) // return type
transform (Order, InCursor is, OutCursor t, Op op
                   , ascending_vertical_traversal_tag)
{
    root_tracking_cursor<InCursor> s(is);
    root_tracking_cursor<InCursor> s2(s);

    boost::tree::coupling_cursor< root_tracking_cursor<InCursor>, OutCursor > cc(s, t);

    to_first(Order(), cc);
    to_last(Order(), s2);

    while (cc.in()!=s2) {
        *cc.out() = op(*cc.in());
        successor(Order(), cc);
    }
    return cc.out();
}

} // namespace detail
} // namespace tree
} // namespace boost

#endif //BOOST_TREE_DETAIL_ITERATIVE_ALGORITHMS_HPP

max_stars_repo_name: grafikrobot/tree

max_issues_repo_name: grafikrobot/tree

max_forks_repo_name: grafikrobot/tree