<commit_before>#pragma once
//Verbose because clang/llvm pretend to have gnuc
#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wint-in-bool-context"
#endif
#include <Eigen/Dense>
#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER)
#pragma GCC diagnostic pop
#endif
#include <vector>
#include <map>
namespace mtao{
    template <typename T, int A, int B>
        using Matrix = Eigen::Matrix<T,A,B>;

    template <typename T, int A> using SquareMatrix = Matrix<T,A,A>;
    template <typename T> using MatrixX = SquareMatrix<T,Eigen::Dynamic>;

    template <typename T, int D> using Vector = Matrix<T,D,1>;
    template <typename T, int D> using RowVector = Matrix<T,1,D>;
    template <typename T> using VectorX = Vector<T,Eigen::Dynamic>;
    template <typename T> using RowVectorX = RowVector<T,Eigen::Dynamic>;

    template <typename T> using Vector2 = Vector<T,2>;
    template <typename T> using RowVector2 = RowVector<T,2>;

    template <typename T> using Vector3 = Vector<T,3>;
    template <typename T> using RowVector3 = RowVector<T,3>;

    template <typename T> using Vector4 = Vector<T,4>;
    template <typename T> using RowVector4 = RowVector<T,4>;

    template <typename T, int D> using ColVectors = Matrix<T,D, Eigen::Dynamic>;
    template <typename T, int D> using RowVectors = Matrix<T,Eigen::Dynamic, D>;

    using Mat3i = SquareMatrix<int,3> ;
    using Mat2i = SquareMatrix<int,2> ;
    using ColVecs4i = ColVectors<int,3> ;
    using ColVecs3i = ColVectors<int,3> ;
    using ColVecs2i = ColVectors<int,2> ;
    using RowVecs3i = RowVectors<int,3> ;
    using RowVecs2i = RowVectors<int,2> ;
    using Vec3i = Vector<int,3> ;
    using Vec2i = Vector<int,2> ;
    using MatXi = MatrixX<int> ;
    using VecXi = VectorX<int> ;
    using RowVecXi = RowVectorX<int> ;

    using Mat4f = SquareMatrix<float,4> ;
    using Mat3f = SquareMatrix<float,3> ;
    using Mat2f = SquareMatrix<float,2> ;
    using ColVecs4f = ColVectors<float,4> ;
    using ColVecs3f = ColVectors<float,3> ;
    using ColVecs2f = ColVectors<float,2> ;
    using RowVecs3f = RowVectors<float,3> ;
    using RowVecs2f = RowVectors<float,2> ;
    using Vec4f = Vector<float,4> ;
    using Vec3f = Vector<float,3> ;
    using Vec2f = Vector<float,2> ;
    using MatXf = MatrixX<float> ;
    using VecXf = VectorX<float> ;
    using RowVecXf = RowVectorX<float> ;

    using Mat4d = SquareMatrix<double,4> ;
    using Mat3d = SquareMatrix<double,3> ;
    using Mat2d = SquareMatrix<double,2> ;
    using ColVecs4d = ColVectors<double,4> ;
    using ColVecs3d = ColVectors<double,3> ;
    using ColVecs2d = ColVectors<double,2> ;
    using RowVecs3d = RowVectors<double,3> ;
    using RowVecs2d = RowVectors<double,2> ;
    using Vec4d = Vector<double,4> ;
    using Vec3d = Vector<double,3> ;
    using Vec2d = Vector<double,2> ;
    using MatXd = MatrixX<double> ;
    using VecXd = VectorX<double> ;
    using RowVecXd = RowVectorX<double> ;

    using Vec2i = Vector2<int>;
    using Vec3i = Vector3<int>;
    using Vec4i = Vector4<int>;

    //types packaged for a given embedded dimensions
    template <typename T, int D_>
        struct embedded_types {
            using Scalar = T;
            constexpr static int D = D_;
            template <int A, int B> using Matrix = Matrix<T,A,B>;
            template <int A> using SquareMatrix = SquareMatrix <T,A>;
            template <int A> using Vector = Vector <T,A>;
            using VectorD = Vector<D>;
            using SquareMatrixD = SquareMatrix<D>;

            using MatrixX = mtao::MatrixX<T>;
            using VectorX = mtao::VectorX<T>;

            template <int D> using ColVectors = Matrix<D, Eigen::Dynamic>;
            template <int D> using RowVectors = Matrix<Eigen::Dynamic, D>;

            template <int N> using ColVectorsD = Matrix<D,N>;
            template <int N> using RowVectorsD = Matrix<N, D>;
            using ColVectorsDX=ColVectorsD<Eigen::Dynamic>;
            using RowVectorsDX=RowVectorsD<Eigen::Dynamic>;
        };

    template <typename T>
        struct scalar_types {
            typedef Eigen::Matrix<T,2,1> Vec2;
            typedef Eigen::Matrix<T,3,1> Vec3;
            typedef Eigen::Matrix<T,Eigen::Dynamic,1> VecX;
            typedef Eigen::Matrix<T,2,2> Mat2;
            typedef Eigen::Matrix<T,3,3> Mat3;
            typedef Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> MatX;
        };
    template <int Dim>
        struct dim_types {
            typedef Eigen::Matrix<double,Dim,1> Vecf;
            typedef Eigen::Matrix<float,Dim,1> Vecd;
            typedef Eigen::Matrix<int,Dim,1> Veci;
            typedef Eigen::Matrix<double,Dim,Dim> Matf;
            typedef Eigen::Matrix<float,Dim,Dim> Matd;
        };
    template <typename T, int Dim>
        struct numerical_types {
            typedef Eigen::Matrix<T,Dim,1> Vec;
            typedef Eigen::Matrix<T,Dim,Dim> Mat;
        };

    namespace internal {
        template <typename T>
            struct allocator_selector {
                using type = std::allocator<T>;
            };

        template <typename T, int R, int C>
            struct allocator_selector<Eigen::Matrix<T,R,C>> {
                using type = Eigen::aligned_allocator<Eigen::Matrix<T,R,C>>;
            };
    }

    template <typename T>
        using allocator = typename internal::allocator_selector<T>::type;

    template <typename T, typename Allocator = mtao::allocator<T>>
        using vector = std::vector<T,Allocator>;

    template <typename Key, typename T, typename Compare=std::less<Key>, typename Allocator = mtao::allocator<T>>
        using map = std::map<Key,T,Compare,Allocator>;

    template <typename T>
        struct scalar_type {
            using type = T;
        };

    template <typename T, int R, int C>
        struct scalar_type<Eigen::Matrix<T,R,C>> {
            using type = T;
        };

    template <typename T>
    using scalar_type_t = typename scalar_type<T>::type;

}
<commit_msg>should fix map allocator tyope<commit_after>#pragma once
//Verbose because clang/llvm pretend to have gnuc
#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wint-in-bool-context"
#endif
#include <Eigen/Dense>
#if defined(__GNUC__) && !defined(__llvm__) && !defined(__INTEL_COMPILER)
#pragma GCC diagnostic pop
#endif
#include <vector>
#include <map>
namespace mtao{
    template <typename T, int A, int B>
        using Matrix = Eigen::Matrix<T,A,B>;

    template <typename T, int A> using SquareMatrix = Matrix<T,A,A>;
    template <typename T> using MatrixX = SquareMatrix<T,Eigen::Dynamic>;

    template <typename T, int D> using Vector = Matrix<T,D,1>;
    template <typename T, int D> using RowVector = Matrix<T,1,D>;
    template <typename T> using VectorX = Vector<T,Eigen::Dynamic>;
    template <typename T> using RowVectorX = RowVector<T,Eigen::Dynamic>;

    template <typename T> using Vector2 = Vector<T,2>;
    template <typename T> using RowVector2 = RowVector<T,2>;

    template <typename T> using Vector3 = Vector<T,3>;
    template <typename T> using RowVector3 = RowVector<T,3>;

    template <typename T> using Vector4 = Vector<T,4>;
    template <typename T> using RowVector4 = RowVector<T,4>;

    template <typename T, int D> using ColVectors = Matrix<T,D, Eigen::Dynamic>;
    template <typename T, int D> using RowVectors = Matrix<T,Eigen::Dynamic, D>;

    using Mat3i = SquareMatrix<int,3> ;
    using Mat2i = SquareMatrix<int,2> ;
    using ColVecs4i = ColVectors<int,3> ;
    using ColVecs3i = ColVectors<int,3> ;
    using ColVecs2i = ColVectors<int,2> ;
    using RowVecs3i = RowVectors<int,3> ;
    using RowVecs2i = RowVectors<int,2> ;
    using Vec3i = Vector<int,3> ;
    using Vec2i = Vector<int,2> ;
    using MatXi = MatrixX<int> ;
    using VecXi = VectorX<int> ;
    using RowVecXi = RowVectorX<int> ;

    using Mat4f = SquareMatrix<float,4> ;
    using Mat3f = SquareMatrix<float,3> ;
    using Mat2f = SquareMatrix<float,2> ;
    using ColVecs4f = ColVectors<float,4> ;
    using ColVecs3f = ColVectors<float,3> ;
    using ColVecs2f = ColVectors<float,2> ;
    using RowVecs3f = RowVectors<float,3> ;
    using RowVecs2f = RowVectors<float,2> ;
    using Vec4f = Vector<float,4> ;
    using Vec3f = Vector<float,3> ;
    using Vec2f = Vector<float,2> ;
    using MatXf = MatrixX<float> ;
    using VecXf = VectorX<float> ;
    using RowVecXf = RowVectorX<float> ;

    using Mat4d = SquareMatrix<double,4> ;
    using Mat3d = SquareMatrix<double,3> ;
    using Mat2d = SquareMatrix<double,2> ;
    using ColVecs4d = ColVectors<double,4> ;
    using ColVecs3d = ColVectors<double,3> ;
    using ColVecs2d = ColVectors<double,2> ;
    using RowVecs3d = RowVectors<double,3> ;
    using RowVecs2d = RowVectors<double,2> ;
    using Vec4d = Vector<double,4> ;
    using Vec3d = Vector<double,3> ;
    using Vec2d = Vector<double,2> ;
    using MatXd = MatrixX<double> ;
    using VecXd = VectorX<double> ;
    using RowVecXd = RowVectorX<double> ;

    using Vec2i = Vector2<int>;
    using Vec3i = Vector3<int>;
    using Vec4i = Vector4<int>;

    //types packaged for a given embedded dimensions
    template <typename T, int D_>
        struct embedded_types {
            using Scalar = T;
            constexpr static int D = D_;
            template <int A, int B> using Matrix = Matrix<T,A,B>;
            template <int A> using SquareMatrix = SquareMatrix <T,A>;
            template <int A> using Vector = Vector <T,A>;
            using VectorD = Vector<D>;
            using SquareMatrixD = SquareMatrix<D>;

            using MatrixX = mtao::MatrixX<T>;
            using VectorX = mtao::VectorX<T>;

            template <int D> using ColVectors = Matrix<D, Eigen::Dynamic>;
            template <int D> using RowVectors = Matrix<Eigen::Dynamic, D>;

            template <int N> using ColVectorsD = Matrix<D,N>;
            template <int N> using RowVectorsD = Matrix<N, D>;
            using ColVectorsDX=ColVectorsD<Eigen::Dynamic>;
            using RowVectorsDX=RowVectorsD<Eigen::Dynamic>;
        };

    template <typename T>
        struct scalar_types {
            typedef Eigen::Matrix<T,2,1> Vec2;
            typedef Eigen::Matrix<T,3,1> Vec3;
            typedef Eigen::Matrix<T,Eigen::Dynamic,1> VecX;
            typedef Eigen::Matrix<T,2,2> Mat2;
            typedef Eigen::Matrix<T,3,3> Mat3;
            typedef Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> MatX;
        };
    template <int Dim>
        struct dim_types {
            typedef Eigen::Matrix<double,Dim,1> Vecf;
            typedef Eigen::Matrix<float,Dim,1> Vecd;
            typedef Eigen::Matrix<int,Dim,1> Veci;
            typedef Eigen::Matrix<double,Dim,Dim> Matf;
            typedef Eigen::Matrix<float,Dim,Dim> Matd;
        };
    template <typename T, int Dim>
        struct numerical_types {
            typedef Eigen::Matrix<T,Dim,1> Vec;
            typedef Eigen::Matrix<T,Dim,Dim> Mat;
        };

    namespace internal {
        template <typename T>
            struct allocator_selector {
                using type = std::allocator<T>;
            };

        template <typename T, int R, int C>
            struct allocator_selector<Eigen::Matrix<T,R,C>> {
                using type = Eigen::aligned_allocator<Eigen::Matrix<T,R,C>>;
            };
    }

    template <typename T>
        using allocator = typename internal::allocator_selector<T>::type;

    template <typename T, typename Allocator = mtao::allocator<T>>
        using vector = std::vector<T,Allocator>;

    template <typename Key, typename T, typename Compare=std::less<Key>, typename Allocator = mtao::allocator<std::pair<const Key,T>>>
        using map = std::map<Key,T,Compare,Allocator>;

    template <typename T>
        struct scalar_type {
            using type = T;
        };

    template <typename T, int R, int C>
        struct scalar_type<Eigen::Matrix<T,R,C>> {
            using type = T;
        };

    template <typename T>
    using scalar_type_t = typename scalar_type<T>::type;

}
<|endoftext|>


<commit_before>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Thoralf Klein
 * Written (W) 2013 Soumyajit De
 */

#include <shogun/lib/common.h>
#include <shogun/lib/SGVector.h>
#include <shogun/mathematics/Math.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(CMath, qsort_test)
{
	// testing qsort on list of zero elements
	CMath::qsort((int32_t *)NULL, 0);

	// testing qsort on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	CMath::qsort(v1, 1);
	SG_FREE(v1);
}

TEST(CMath, qsort_ptr_test)
{
	// testing qsort on list of zero pointers
	CMath::qsort((int32_t **)NULL, 0);

	// testing qsort on list of one pointer
	int32_t ** v1 = SG_CALLOC(int32_t *, 1);
	CMath::qsort(v1, 1);
	SG_FREE(v1);
}

TEST(CMath, qsort_index_test)
{
	// testing qsort_index on list of zero elements
	CMath::qsort_index((int32_t *)NULL, (int32_t *)NULL, 0);

	// testing qsort_index on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	int32_t * i1 = SG_CALLOC(int32_t, 1);
	CMath::qsort_index(v1, i1, 1);
	SG_FREE(v1);
	SG_FREE(i1);
}

TEST(CMath, qsort_backward_index_test)
{
	// testing qsort_backward_index on list of zero elements
	CMath::qsort_backward_index((int32_t *)NULL, (int32_t *)NULL, 0);

	// testing qsort_backward_index on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	int32_t * i1 = SG_CALLOC(int32_t, 1);
	CMath::qsort_backward_index(v1, i1, 1);
	SG_FREE(v1);
	SG_FREE(i1);
}

TEST(CMath, parallel_qsort_index_test)
{
	// testing parallel_qsort_index on list of zero elements
	CMath::parallel_qsort_index((int32_t *)NULL, (int32_t *)NULL, 0, 8);

	// testing parallel_qsort_index on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	int32_t * i1 = SG_CALLOC(int32_t, 1);
	CMath::parallel_qsort_index(v1, i1, 1, 8);
	SG_FREE(v1);
	SG_FREE(i1);
}

TEST(CMath, float64_tests)
{
	// round, ceil, floor
	EXPECT_NEAR(CMath::round(7.5), 8.0, 1E-15);
	EXPECT_NEAR(CMath::round(7.5-1E-15), 7.0, 1E-15);
	EXPECT_NEAR(CMath::floor(8-1E-15), 7.0, 1E-15);
	EXPECT_NEAR(CMath::ceil(7+1E-15), 8.0, 1E-15);

	float64_t a=5.78123516567856743364;
	// x^2, x^(1/2)
	EXPECT_NEAR(CMath::sq(a), 33.42268004087848964900, 1E-15);
	EXPECT_NEAR(CMath::sqrt(33.42268004087848964900), a, 1E-15);
	EXPECT_NEAR(CMath::pow(a, 2), 33.42268004087848964900, 1E-15);
	EXPECT_NEAR(CMath::pow(33.42268004087848964900, 0.5), a, 1E-15);

	// e^x, log_{b}(x)
	EXPECT_NEAR(CMath::exp(a), 324.15933372813628920994, 1E-15);
	EXPECT_NEAR(CMath::log2(a), 2.53137775864743908016, 1E-15);
	EXPECT_NEAR(CMath::log10(a), 0.76202063570953693095, 1E-15);

	// exp and log identities
	EXPECT_NEAR(CMath::log(CMath::exp(a)), a, 1E-15);
	EXPECT_NEAR(CMath::exp(CMath::log(a)), a, 1E-15);

	// trigonometric functions
	EXPECT_NEAR(CMath::sin(a), -0.48113603605414501097, 1E-15);
	EXPECT_NEAR(CMath::sinh(a), 162.07812441272406545067, 1E-13);
	EXPECT_NEAR(CMath::asin(a-5.0), 0.89664205584230471935, 1E-15);
	EXPECT_NEAR(CMath::cos(a), 0.87664594609802681813, 1E-15);
	EXPECT_NEAR(CMath::cosh(a), 162.08120931541219533756, 1E-15);
	EXPECT_NEAR(CMath::acos(a-5.0), 0.67415427095259194967, 1E-15);
	EXPECT_NEAR(CMath::tan(a), -0.54883734784344084812, 1E-15);
	EXPECT_NEAR(CMath::tanh(a), 0.99998096693194016282, 1E-15);
	EXPECT_NEAR(CMath::atan(a), 1.39951769800256187182, 1E-15);

	// trigonometric identities
	EXPECT_NEAR(CMath::sq(CMath::sin(a))+CMath::sq(CMath::cos(a)),
		1.0, 1E-15);
	EXPECT_NEAR(CMath::sq(1.0/CMath::cos(a))-CMath::sq(CMath::tan(a)),
		1.0, 1E-15);
	EXPECT_NEAR(CMath::sq(1.0/CMath::sin(a))-CMath::sq(1.0/CMath::tan(a)),
		1.0, 1E-15);

	// misc
	SGVector<float64_t> vec(10);
	for (index_t i=0; i<10; ++i)
	{
		vec[i]=i%2==0 ? i : 0.0;
	}
	EXPECT_EQ(CMath::get_num_nonzero(vec.vector, 10), 4);
}

TEST(CMath, linspace_test)
{
	// Number of points used to divide the interval
	int32_t n = 100;
	// Start and end of the interval
	float64_t start = 0.0, end = 1.0;

	SGVector<float64_t> vec(100);
	CMath::linspace(vec.vector, start, end, n);

	// The first and last elements are tested outside the loop, because
	// linspace sets them directly using the arguments
	EXPECT_EQ(vec[0], start);
	EXPECT_EQ(vec[n-1], end);

	float64_t val = start;
	for (index_t i = 1; i < n-1; ++i)
	{
		val += (end-start)/(n-1);
		EXPECT_EQ(vec[i], val);
	}
}

TEST(CMath, log_sum_exp)
{
	SGVector<float64_t> values(3);
	values.range_fill();
	EXPECT_NEAR(CMath::log_sum_exp(values), 2.4076059644443801, 1e-15);
}

TEST(CMath, log_mean_exp)
{
	SGVector<float64_t> values(3);
	values.range_fill();
	EXPECT_NEAR(CMath::log_mean_exp(values), 1.3089936757762706, 1e-15);
}

TEST(CMath, strtofloat)
{
	float32_t float_result = 0;
	EXPECT_TRUE(CMath::strtof("nan", &float_result));
	EXPECT_TRUE(CMath::is_nan(float_result));

	EXPECT_TRUE(CMath::strtof("inf", &float_result));
	EXPECT_TRUE(CMath::is_infinity(float_result));

	EXPECT_TRUE(CMath::strtof("-inf", &float_result));
	EXPECT_DOUBLE_EQ(-CMath::INFTY, float_result);

	EXPECT_TRUE(CMath::strtof("1.2345", &float_result));
	EXPECT_FLOAT_EQ(1.2345, float_result);
}

TEST(CMath, strtodouble)
{
	float64_t double_result = 0;
	EXPECT_TRUE(CMath::strtod("nan", &double_result));
	EXPECT_TRUE(CMath::is_nan(double_result));

	EXPECT_TRUE(CMath::strtod("inf", &double_result));
	EXPECT_TRUE(CMath::is_infinity(double_result));

	EXPECT_TRUE(CMath::strtod("-inf", &double_result));
	EXPECT_DOUBLE_EQ(-CMath::INFTY, double_result);

	EXPECT_TRUE(CMath::strtod("1.234567890123", &double_result));
	EXPECT_DOUBLE_EQ(1.234567890123, double_result);
}

TEST(CMath, strtolongdouble)
{
	floatmax_t long_double_result = 0;
	EXPECT_TRUE(CMath::strtold("nan", &long_double_result));
	EXPECT_TRUE(CMath::is_nan(long_double_result));

	EXPECT_TRUE(CMath::strtold("inf", &long_double_result));
	EXPECT_TRUE(CMath::is_infinity(long_double_result));

	EXPECT_TRUE(CMath::strtold("-inf", &long_double_result));
	EXPECT_DOUBLE_EQ(-CMath::INFTY, long_double_result);

	EXPECT_TRUE(CMath::strtold("1.234567890123", &long_double_result));
	EXPECT_EQ(long_double_result, 1.234567890123);
}
<commit_msg>attempt fix for build error<commit_after>/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 2013 Thoralf Klein
 * Written (W) 2013 Soumyajit De
 */

#include <shogun/lib/common.h>
#include <shogun/lib/SGVector.h>
#include <shogun/mathematics/Math.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(CMath, qsort_test)
{
	// testing qsort on list of zero elements
	CMath::qsort((int32_t *)NULL, 0);

	// testing qsort on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	CMath::qsort(v1, 1);
	SG_FREE(v1);
}

TEST(CMath, qsort_ptr_test)
{
	// testing qsort on list of zero pointers
	CMath::qsort((int32_t **)NULL, 0);

	// testing qsort on list of one pointer
	int32_t ** v1 = SG_CALLOC(int32_t *, 1);
	CMath::qsort(v1, 1);
	SG_FREE(v1);
}

TEST(CMath, qsort_index_test)
{
	// testing qsort_index on list of zero elements
	CMath::qsort_index((int32_t *)NULL, (int32_t *)NULL, 0);

	// testing qsort_index on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	int32_t * i1 = SG_CALLOC(int32_t, 1);
	CMath::qsort_index(v1, i1, 1);
	SG_FREE(v1);
	SG_FREE(i1);
}

TEST(CMath, qsort_backward_index_test)
{
	// testing qsort_backward_index on list of zero elements
	CMath::qsort_backward_index((int32_t *)NULL, (int32_t *)NULL, 0);

	// testing qsort_backward_index on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	int32_t * i1 = SG_CALLOC(int32_t, 1);
	CMath::qsort_backward_index(v1, i1, 1);
	SG_FREE(v1);
	SG_FREE(i1);
}

TEST(CMath, parallel_qsort_index_test)
{
	// testing parallel_qsort_index on list of zero elements
	CMath::parallel_qsort_index((int32_t *)NULL, (int32_t *)NULL, 0, 8);

	// testing parallel_qsort_index on list of one element
	int32_t * v1 = SG_CALLOC(int32_t, 1);
	int32_t * i1 = SG_CALLOC(int32_t, 1);
	CMath::parallel_qsort_index(v1, i1, 1, 8);
	SG_FREE(v1);
	SG_FREE(i1);
}

TEST(CMath, float64_tests)
{
	// round, ceil, floor
	EXPECT_NEAR(CMath::round(7.5), 8.0, 1E-15);
	EXPECT_NEAR(CMath::round(7.5-1E-15), 7.0, 1E-15);
	EXPECT_NEAR(CMath::floor(8-1E-15), 7.0, 1E-15);
	EXPECT_NEAR(CMath::ceil(7+1E-15), 8.0, 1E-15);

	float64_t a=5.78123516567856743364;
	// x^2, x^(1/2)
	EXPECT_NEAR(CMath::sq(a), 33.42268004087848964900, 1E-15);
	EXPECT_NEAR(CMath::sqrt(33.42268004087848964900), a, 1E-15);
	EXPECT_NEAR(CMath::pow(a, 2), 33.42268004087848964900, 1E-15);
	EXPECT_NEAR(CMath::pow(33.42268004087848964900, 0.5), a, 1E-15);

	// e^x, log_{b}(x)
	EXPECT_NEAR(CMath::exp(a), 324.15933372813628920994, 1E-15);
	EXPECT_NEAR(CMath::log2(a), 2.53137775864743908016, 1E-15);
	EXPECT_NEAR(CMath::log10(a), 0.76202063570953693095, 1E-15);

	// exp and log identities
	EXPECT_NEAR(CMath::log(CMath::exp(a)), a, 1E-15);
	EXPECT_NEAR(CMath::exp(CMath::log(a)), a, 1E-15);

	// trigonometric functions
	EXPECT_NEAR(CMath::sin(a), -0.48113603605414501097, 1E-15);
	EXPECT_NEAR(CMath::sinh(a), 162.07812441272406545067, 1E-13);
	EXPECT_NEAR(CMath::asin(a-5.0), 0.89664205584230471935, 1E-15);
	EXPECT_NEAR(CMath::cos(a), 0.87664594609802681813, 1E-15);
	EXPECT_NEAR(CMath::cosh(a), 162.08120931541219533756, 1E-15);
	EXPECT_NEAR(CMath::acos(a-5.0), 0.67415427095259194967, 1E-15);
	EXPECT_NEAR(CMath::tan(a), -0.54883734784344084812, 1E-15);
	EXPECT_NEAR(CMath::tanh(a), 0.99998096693194016282, 1E-15);
	EXPECT_NEAR(CMath::atan(a), 1.39951769800256187182, 1E-15);

	// trigonometric identities
	EXPECT_NEAR(CMath::sq(CMath::sin(a))+CMath::sq(CMath::cos(a)),
		1.0, 1E-15);
	EXPECT_NEAR(CMath::sq(1.0/CMath::cos(a))-CMath::sq(CMath::tan(a)),
		1.0, 1E-15);
	EXPECT_NEAR(CMath::sq(1.0/CMath::sin(a))-CMath::sq(1.0/CMath::tan(a)),
		1.0, 1E-15);

	// misc
	SGVector<float64_t> vec(10);
	for (index_t i=0; i<10; ++i)
	{
		vec[i]=i%2==0 ? i : 0.0;
	}
	EXPECT_EQ(CMath::get_num_nonzero(vec.vector, 10), 4);
}

TEST(CMath, linspace_test)
{
	// Number of points used to divide the interval
	int32_t n = 100;
	// Start and end of the interval
	float64_t start = 0.0, end = 1.0;

	SGVector<float64_t> vec(100);
	CMath::linspace(vec.vector, start, end, n);

	// The first and last elements are tested outside the loop, because
	// linspace sets them directly using the arguments
	EXPECT_EQ(vec[0], start);
	EXPECT_EQ(vec[n-1], end);

	float64_t val = start;
	for (index_t i = 1; i < n-1; ++i)
	{
		val += (end-start)/(n-1);
		EXPECT_EQ(vec[i], val);
	}
}

TEST(CMath, log_sum_exp)
{
	SGVector<float64_t> values(3);
	values.range_fill();
	EXPECT_NEAR(CMath::log_sum_exp(values), 2.4076059644443801, 1e-15);
}

TEST(CMath, log_mean_exp)
{
	SGVector<float64_t> values(3);
	values.range_fill();
	EXPECT_NEAR(CMath::log_mean_exp(values), 1.3089936757762706, 1e-15);
}

TEST(CMath, strtofloat)
{
	float32_t float_result = 0;
	EXPECT_TRUE(CMath::strtof("nan", &float_result));
	EXPECT_TRUE(CMath::is_nan(float_result));

	EXPECT_TRUE(CMath::strtof("inf", &float_result));
	EXPECT_TRUE(CMath::is_infinity(float_result));

	EXPECT_TRUE(CMath::strtof("-inf", &float_result));
	EXPECT_DOUBLE_EQ(-CMath::INFTY, float_result);

	EXPECT_TRUE(CMath::strtof("1.2345", &float_result));
	EXPECT_FLOAT_EQ(1.2345, float_result);
}

TEST(CMath, strtodouble)
{
	float64_t double_result = 0;
	EXPECT_TRUE(CMath::strtod("nan", &double_result));
	EXPECT_TRUE(CMath::is_nan(double_result));

	EXPECT_TRUE(CMath::strtod("inf", &double_result));
	EXPECT_TRUE(CMath::is_infinity(double_result));

	EXPECT_TRUE(CMath::strtod("-inf", &double_result));
	EXPECT_DOUBLE_EQ(-CMath::INFTY, double_result);

	EXPECT_TRUE(CMath::strtod("1.234567890123", &double_result));
	EXPECT_DOUBLE_EQ(1.234567890123, double_result);
}

TEST(CMath, strtolongdouble)
{
	floatmax_t long_double_result = 0;
	EXPECT_TRUE(CMath::strtold("nan", &long_double_result));
	EXPECT_TRUE(CMath::is_nan(long_double_result));

	EXPECT_TRUE(CMath::strtold("inf", &long_double_result));
	EXPECT_TRUE(CMath::is_infinity(long_double_result));

	EXPECT_TRUE(CMath::strtold("-inf", &long_double_result));
	EXPECT_DOUBLE_EQ(-CMath::INFTY, long_double_result);

	EXPECT_TRUE(CMath::strtold("1.234567890123", &long_double_result));
	EXPECT_DOUBLE_EQ(1.234567890123, long_double_result);
}
<|endoftext|>


<commit_before>/**
 * @file _httplibcurl.cpp
 * @brief Internal definitions of the Http libcurl thread
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012-2013, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "_httplibcurl.h"

#include "httpheaders.h"
#include "bufferarray.h"
#include "_httpoprequest.h"
#include "_httppolicy.h"

#include "llhttpstatuscodes.h"

namespace LLCore
{

HttpLibcurl::HttpLibcurl(HttpService * service)
	: mService(service),
	  mPolicyCount(0),
	  mMultiHandles(NULL)
{}

HttpLibcurl::~HttpLibcurl()
{
	shutdown();

	mService = NULL;
}

void HttpLibcurl::shutdown()
{
	while (! mActiveOps.empty())
	{
		HttpOpRequest * op(* mActiveOps.begin());
		mActiveOps.erase(mActiveOps.begin());

		cancelRequest(op);
		op->release();
	}

	if (mMultiHandles)
	{
		for (int policy_class(0); policy_class < mPolicyCount; ++policy_class)
		{
			if (mMultiHandles[policy_class])
			{
				curl_multi_cleanup(mMultiHandles[policy_class]);
				mMultiHandles[policy_class] = 0;
			}
		}

		delete [] mMultiHandles;
		mMultiHandles = NULL;
	}

	mPolicyCount = 0;
}

void HttpLibcurl::start(int policy_count)
{
	llassert_always(policy_count <= HTTP_POLICY_CLASS_LIMIT);
	llassert_always(! mMultiHandles);					// One-time call only

	mPolicyCount = policy_count;
	mMultiHandles = new CURLM * [mPolicyCount];
	for (int policy_class(0); policy_class < mPolicyCount; ++policy_class)
	{
		mMultiHandles[policy_class] = curl_multi_init();
	}
}

// Give libcurl some cycles, invoke it's callbacks, process
// completed requests finalizing or issuing retries as needed.
//
// If active list goes empty *and* we didn't queue any
// requests for retry, we return a request for a hard
// sleep otherwise ask for a normal polling interval.
HttpService::ELoopSpeed HttpLibcurl::processTransport()
{
	HttpService::ELoopSpeed	ret(HttpService::REQUEST_SLEEP);

	// Give libcurl some cycles to do I/O & callbacks
	for (int policy_class(0); policy_class < mPolicyCount; ++policy_class)
	{
		if (! mMultiHandles[policy_class])
			continue;

		int running(0);
		CURLMcode status(CURLM_CALL_MULTI_PERFORM);
		do
		{
			running = 0;
			status = curl_multi_perform(mMultiHandles[policy_class], &running);
		}
		while (0 != running && CURLM_CALL_MULTI_PERFORM == status);

		// Run completion on anything done
		CURLMsg * msg(NULL);
		int msgs_in_queue(0);
		while ((msg = curl_multi_info_read(mMultiHandles[policy_class], &msgs_in_queue)))
		{
			if (CURLMSG_DONE == msg->msg)
			{
				CURL * handle(msg->easy_handle);
				CURLcode result(msg->data.result);

				if (completeRequest(mMultiHandles[policy_class], handle, result))
				{
					// Request is still active, don't get too sleepy
					ret = HttpService::NORMAL;
				}
				handle = NULL;			// No longer valid on return
			}
			else if (CURLMSG_NONE == msg->msg)
			{
				// Ignore this... it shouldn't mean anything.
				;
			}
			else
			{
				LL_WARNS_ONCE("CoreHttp") << "Unexpected message from libcurl.  Msg code:  "
										  << msg->msg
										  << LL_ENDL;
			}
			msgs_in_queue = 0;
		}
	}

	if (! mActiveOps.empty())
	{
		ret = HttpService::NORMAL;
	}
	return ret;
}

// Caller has provided us with a ref count on op.
void HttpLibcurl::addOp(HttpOpRequest * op)
{
	llassert_always(op->mReqPolicy < mPolicyCount);
	llassert_always(mMultiHandles[op->mReqPolicy] != NULL);

	// Create standard handle
	if (! op->prepareRequest(mService))
	{
		// Couldn't issue request, fail with notification
		// *TODO:  Need failure path
		return;
	}

	// Make the request live
	curl_multi_add_handle(mMultiHandles[op->mReqPolicy], op->mCurlHandle);
	op->mCurlActive = true;

	if (op->mTracing > HTTP_TRACE_OFF)
	{
		HttpPolicy & policy(mService->getPolicy());

		LL_INFOS("CoreHttp") << "TRACE, ToActiveQueue, Handle:  "
							 << static_cast<HttpHandle>(op)
							 << ", Actives:  " << mActiveOps.size()
							 << ", Readies:  " << policy.getReadyCount(op->mReqPolicy)
							 << LL_ENDL;
	}

	// On success, make operation active
	mActiveOps.insert(op);
}

// Implements the transport part of any cancel operation.
// See if the handle is an active operation and if so,
// use the more complicated transport-based cancelation
// method to kill the request.
bool HttpLibcurl::cancel(HttpHandle handle)
{
	HttpOpRequest * op(static_cast<HttpOpRequest *>(handle));
	active_set_t::iterator it(mActiveOps.find(op));
	if (mActiveOps.end() == it)
	{
		return false;
	}

	// Cancel request
	cancelRequest(op);

	// Drop references
	mActiveOps.erase(it);
	op->release();

	return true;
}

// *NOTE:  cancelRequest logic parallels completeRequest logic.
// Keep them synchronized as necessary.  Caller is expected to
// remove the op from the active list and release the op *after*
// calling this method.  It must be called first to deliver the
// op to the reply queue with refcount intact.
void HttpLibcurl::cancelRequest(HttpOpRequest * op)
{
	// Deactivate request
	op->mCurlActive = false;

	// Detach from multi and recycle handle
	curl_multi_remove_handle(mMultiHandles[op->mReqPolicy], op->mCurlHandle);
	curl_easy_cleanup(op->mCurlHandle);
	op->mCurlHandle = NULL;

	// Tracing
	if (op->mTracing > HTTP_TRACE_OFF)
	{
		LL_INFOS("CoreHttp") << "TRACE, RequestCanceled, Handle:  "
							 << static_cast<HttpHandle>(op)
							 << ", Status:  " << op->mStatus.toHex()
							 << LL_ENDL;
	}

	// Cancel op and deliver for notification
	op->cancel();
}

// *NOTE:  cancelRequest logic parallels completeRequest logic.
// Keep them synchronized as necessary.
bool HttpLibcurl::completeRequest(CURLM * multi_handle, CURL * handle, CURLcode status)
{
	HttpOpRequest * op(NULL);
	curl_easy_getinfo(handle, CURLINFO_PRIVATE, &op);

	if (handle != op->mCurlHandle || ! op->mCurlActive)
	{
		LL_WARNS("CoreHttp") << "libcurl handle and HttpOpRequest handle in disagreement or inactive request."
							 << "  Handle:  " << static_cast<HttpHandle>(handle)
							 << LL_ENDL;
		return false;
	}

	active_set_t::iterator it(mActiveOps.find(op));
	if (mActiveOps.end() == it)
	{
		LL_WARNS("CoreHttp") << "libcurl completion for request not on active list.  Continuing."
							 << "  Handle:  " << static_cast<HttpHandle>(handle)
							 << LL_ENDL;
		return false;
	}

	// Deactivate request
	mActiveOps.erase(it);
	op->mCurlActive = false;

	// Set final status of request if it hasn't failed by other mechanisms yet
	if (op->mStatus)
	{
		op->mStatus = HttpStatus(HttpStatus::EXT_CURL_EASY, status);
	}
	if (op->mStatus)
	{
		int http_status(HTTP_OK);

		curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_status);
		if (http_status >= 100 && http_status <= 999)
		{
			char * cont_type(NULL);
			curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &cont_type);
			if (cont_type)
			{
				op->mReplyConType = cont_type;
			}
			op->mStatus = HttpStatus(http_status);
		}
		else
		{
			LL_WARNS("CoreHttp") << "Invalid HTTP response code ("
								 << http_status << ") received from server."
								 << LL_ENDL;
			op->mStatus = HttpStatus(HttpStatus::LLCORE, HE_INVALID_HTTP_STATUS);
		}
	}

	// Detach from multi and recycle handle
	curl_multi_remove_handle(multi_handle, handle);
	curl_easy_cleanup(handle);
	op->mCurlHandle = NULL;

	// Tracing
	if (op->mTracing > HTTP_TRACE_OFF)
	{
		LL_INFOS("CoreHttp") << "TRACE, RequestComplete, Handle:  "
							 << static_cast<HttpHandle>(op)
							 << ", Status:  " << op->mStatus.toHex()
							 << LL_ENDL;
	}

	// Dispatch to next stage
	HttpPolicy & policy(mService->getPolicy());
	bool still_active(policy.stageAfterCompletion(op));

	return still_active;
}

int HttpLibcurl::getActiveCount() const
{
	return mActiveOps.size();
}

int HttpLibcurl::getActiveCountInClass(int policy_class) const
{
	int count(0);

	for (active_set_t::const_iterator iter(mActiveOps.begin());
		 mActiveOps.end() != iter;
		 ++iter)
	{
		if ((*iter)->mReqPolicy == policy_class)
		{
			++count;
		}
	}

	return count;
}

// ---------------------------------------
// Free functions
// ---------------------------------------

struct curl_slist * append_headers_to_slist(const HttpHeaders * headers, struct curl_slist * slist)
{
	const HttpHeaders::const_iterator end(headers->end());
	for (HttpHeaders::const_iterator it(headers->begin()); end != it; ++it)
	{
		static const char sep[] = ": ";
		std::string header;
		header.reserve((*it).first.size() + (*it).second.size() + sizeof(sep));
		header.append((*it).first);
		header.append(sep);
		header.append((*it).second);

		slist = curl_slist_append(slist, header.c_str());
	}
	return slist;
}

}  // end namespace LLCore
<commit_msg>SH-4371  Reduce 22mS inter-conenction latency on HTTP operations. Simple change dropped this value by 7-10mS or so.  Any time we complete an operation on a transport pass, arrange to skip the run-loop sleep so that we fill a possible empty slot as quickly as possible.  With pipelining, this kind of thing should become unnecessary but for now, we'll do this to increase throughput.<commit_after>/**
 * @file _httplibcurl.cpp
 * @brief Internal definitions of the Http libcurl thread
 *
 * $LicenseInfo:firstyear=2012&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2012-2013, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "_httplibcurl.h"

#include "httpheaders.h"
#include "bufferarray.h"
#include "_httpoprequest.h"
#include "_httppolicy.h"

#include "llhttpstatuscodes.h"

namespace LLCore
{

HttpLibcurl::HttpLibcurl(HttpService * service)
	: mService(service),
	  mPolicyCount(0),
	  mMultiHandles(NULL)
{}

HttpLibcurl::~HttpLibcurl()
{
	shutdown();

	mService = NULL;
}

void HttpLibcurl::shutdown()
{
	while (! mActiveOps.empty())
	{
		HttpOpRequest * op(* mActiveOps.begin());
		mActiveOps.erase(mActiveOps.begin());

		cancelRequest(op);
		op->release();
	}

	if (mMultiHandles)
	{
		for (int policy_class(0); policy_class < mPolicyCount; ++policy_class)
		{
			if (mMultiHandles[policy_class])
			{
				curl_multi_cleanup(mMultiHandles[policy_class]);
				mMultiHandles[policy_class] = 0;
			}
		}

		delete [] mMultiHandles;
		mMultiHandles = NULL;
	}

	mPolicyCount = 0;
}

void HttpLibcurl::start(int policy_count)
{
	llassert_always(policy_count <= HTTP_POLICY_CLASS_LIMIT);
	llassert_always(! mMultiHandles);					// One-time call only

	mPolicyCount = policy_count;
	mMultiHandles = new CURLM * [mPolicyCount];
	for (int policy_class(0); policy_class < mPolicyCount; ++policy_class)
	{
		mMultiHandles[policy_class] = curl_multi_init();
	}
}

// Give libcurl some cycles, invoke it's callbacks, process
// completed requests finalizing or issuing retries as needed.
//
// If active list goes empty *and* we didn't queue any
// requests for retry, we return a request for a hard
// sleep otherwise ask for a normal polling interval.
HttpService::ELoopSpeed HttpLibcurl::processTransport()
{
	HttpService::ELoopSpeed	ret(HttpService::REQUEST_SLEEP);

	// Give libcurl some cycles to do I/O & callbacks
	for (int policy_class(0); policy_class < mPolicyCount; ++policy_class)
	{
		if (! mMultiHandles[policy_class])
			continue;

		int running(0);
		CURLMcode status(CURLM_CALL_MULTI_PERFORM);
		do
		{
			running = 0;
			status = curl_multi_perform(mMultiHandles[policy_class], &running);
		}
		while (0 != running && CURLM_CALL_MULTI_PERFORM == status);

		// Run completion on anything done
		CURLMsg * msg(NULL);
		int msgs_in_queue(0);
		while ((msg = curl_multi_info_read(mMultiHandles[policy_class], &msgs_in_queue)))
		{
			if (CURLMSG_DONE == msg->msg)
			{
				CURL * handle(msg->easy_handle);
				CURLcode result(msg->data.result);

				completeRequest(mMultiHandles[policy_class], handle, result);
				handle = NULL;					// No longer valid on return
				ret = HttpService::NORMAL;		// If anything completes, we may have a free slot.
												// Turning around quickly reduces connection gap by 7-10mS.
			}
			else if (CURLMSG_NONE == msg->msg)
			{
				// Ignore this... it shouldn't mean anything.
				;
			}
			else
			{
				LL_WARNS_ONCE("CoreHttp") << "Unexpected message from libcurl.  Msg code:  "
										  << msg->msg
										  << LL_ENDL;
			}
			msgs_in_queue = 0;
		}
	}

	if (! mActiveOps.empty())
	{
		ret = HttpService::NORMAL;
	}
	return ret;
}

// Caller has provided us with a ref count on op.
void HttpLibcurl::addOp(HttpOpRequest * op)
{
	llassert_always(op->mReqPolicy < mPolicyCount);
	llassert_always(mMultiHandles[op->mReqPolicy] != NULL);

	// Create standard handle
	if (! op->prepareRequest(mService))
	{
		// Couldn't issue request, fail with notification
		// *TODO:  Need failure path
		return;
	}

	// Make the request live
	curl_multi_add_handle(mMultiHandles[op->mReqPolicy], op->mCurlHandle);
	op->mCurlActive = true;

	if (op->mTracing > HTTP_TRACE_OFF)
	{
		HttpPolicy & policy(mService->getPolicy());

		LL_INFOS("CoreHttp") << "TRACE, ToActiveQueue, Handle:  "
							 << static_cast<HttpHandle>(op)
							 << ", Actives:  " << mActiveOps.size()
							 << ", Readies:  " << policy.getReadyCount(op->mReqPolicy)
							 << LL_ENDL;
	}

	// On success, make operation active
	mActiveOps.insert(op);
}

// Implements the transport part of any cancel operation.
// See if the handle is an active operation and if so,
// use the more complicated transport-based cancelation
// method to kill the request.
bool HttpLibcurl::cancel(HttpHandle handle)
{
	HttpOpRequest * op(static_cast<HttpOpRequest *>(handle));
	active_set_t::iterator it(mActiveOps.find(op));
	if (mActiveOps.end() == it)
	{
		return false;
	}

	// Cancel request
	cancelRequest(op);

	// Drop references
	mActiveOps.erase(it);
	op->release();

	return true;
}

// *NOTE:  cancelRequest logic parallels completeRequest logic.
// Keep them synchronized as necessary.  Caller is expected to
// remove the op from the active list and release the op *after*
// calling this method.  It must be called first to deliver the
// op to the reply queue with refcount intact.
void HttpLibcurl::cancelRequest(HttpOpRequest * op)
{
	// Deactivate request
	op->mCurlActive = false;

	// Detach from multi and recycle handle
	curl_multi_remove_handle(mMultiHandles[op->mReqPolicy], op->mCurlHandle);
	curl_easy_cleanup(op->mCurlHandle);
	op->mCurlHandle = NULL;

	// Tracing
	if (op->mTracing > HTTP_TRACE_OFF)
	{
		LL_INFOS("CoreHttp") << "TRACE, RequestCanceled, Handle:  "
							 << static_cast<HttpHandle>(op)
							 << ", Status:  " << op->mStatus.toHex()
							 << LL_ENDL;
	}

	// Cancel op and deliver for notification
	op->cancel();
}

// *NOTE:  cancelRequest logic parallels completeRequest logic.
// Keep them synchronized as necessary.
bool HttpLibcurl::completeRequest(CURLM * multi_handle, CURL * handle, CURLcode status)
{
	HttpOpRequest * op(NULL);
	curl_easy_getinfo(handle, CURLINFO_PRIVATE, &op);

	if (handle != op->mCurlHandle || ! op->mCurlActive)
	{
		LL_WARNS("CoreHttp") << "libcurl handle and HttpOpRequest handle in disagreement or inactive request."
							 << "  Handle:  " << static_cast<HttpHandle>(handle)
							 << LL_ENDL;
		return false;
	}

	active_set_t::iterator it(mActiveOps.find(op));
	if (mActiveOps.end() == it)
	{
		LL_WARNS("CoreHttp") << "libcurl completion for request not on active list.  Continuing."
							 << "  Handle:  " << static_cast<HttpHandle>(handle)
							 << LL_ENDL;
		return false;
	}

	// Deactivate request
	mActiveOps.erase(it);
	op->mCurlActive = false;

	// Set final status of request if it hasn't failed by other mechanisms yet
	if (op->mStatus)
	{
		op->mStatus = HttpStatus(HttpStatus::EXT_CURL_EASY, status);
	}
	if (op->mStatus)
	{
		int http_status(HTTP_OK);

		curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &http_status);
		if (http_status >= 100 && http_status <= 999)
		{
			char * cont_type(NULL);
			curl_easy_getinfo(handle, CURLINFO_CONTENT_TYPE, &cont_type);
			if (cont_type)
			{
				op->mReplyConType = cont_type;
			}
			op->mStatus = HttpStatus(http_status);
		}
		else
		{
			LL_WARNS("CoreHttp") << "Invalid HTTP response code ("
								 << http_status << ") received from server."
								 << LL_ENDL;
			op->mStatus = HttpStatus(HttpStatus::LLCORE, HE_INVALID_HTTP_STATUS);
		}
	}

	// Detach from multi and recycle handle
	curl_multi_remove_handle(multi_handle, handle);
	curl_easy_cleanup(handle);
	op->mCurlHandle = NULL;

	// Tracing
	if (op->mTracing > HTTP_TRACE_OFF)
	{
		LL_INFOS("CoreHttp") << "TRACE, RequestComplete, Handle:  "
							 << static_cast<HttpHandle>(op)
							 << ", Status:  " << op->mStatus.toHex()
							 << LL_ENDL;
	}

	// Dispatch to next stage
	HttpPolicy & policy(mService->getPolicy());
	bool still_active(policy.stageAfterCompletion(op));

	return still_active;
}

int HttpLibcurl::getActiveCount() const
{
	return mActiveOps.size();
}

int HttpLibcurl::getActiveCountInClass(int policy_class) const
{
	int count(0);

	for (active_set_t::const_iterator iter(mActiveOps.begin());
		 mActiveOps.end() != iter;
		 ++iter)
	{
		if ((*iter)->mReqPolicy == policy_class)
		{
			++count;
		}
	}

	return count;
}

// ---------------------------------------
// Free functions
// ---------------------------------------

struct curl_slist * append_headers_to_slist(const HttpHeaders * headers, struct curl_slist * slist)
{
	const HttpHeaders::const_iterator end(headers->end());
	for (HttpHeaders::const_iterator it(headers->begin()); end != it; ++it)
	{
		static const char sep[] = ": ";
		std::string header;
		header.reserve((*it).first.size() + (*it).second.size() + sizeof(sep));
		header.append((*it).first);
		header.append(sep);
		header.append((*it).second);

		slist = curl_slist_append(slist, header.c_str());
	}
	return slist;
}

}  // end namespace LLCore
<|endoftext|>


<commit_before>///
/// @file    popcount64.hpp
/// @brief   Count the number of 1 bits inside a 64-bit word.
///          If HAVE_POPCNT is defined then popcount64(x) uses the
///          POPCNT instruction (requires SSE4.2 for x86 & x64).
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

/// Include header generated by Autotools
#ifdef HAVE_CONFIG_H
  #include <config.h>
#endif

#if !defined(__STDC_CONSTANT_MACROS)
  #define __STDC_CONSTANT_MACROS
#endif

#include <stdint.h>

#if defined(HAVE_POPCNT)

#if defined(_MSC_VER) && defined(_WIN64)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u64(x);
}

#elif defined(_MSC_VER) && defined(_WIN32)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u32((uint32_t) x) +
         _mm_popcnt_u32((uint32_t)(x >> 32));
}

#elif defined(HAVE___BUILTIN_POPCOUNTLL)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcountll(x);
}

#elif defined(HAVE___BUILTIN_POPCOUNT)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcount((uint32_t) x) +
         __builtin_popcount((uint32_t)(x >> 32));
}

#else /* Error */

#if defined(_MSC_VER)
  #pragma error( "POPCOUNT not supported, remove \"/D HAVE_POPCNT\" from Makefile.msvc" )
#else
  #error "POPCOUNT not supported, don't use --enable-popcount"
#endif

#endif /* HAVE_POPCNT */

#elif !defined(HAVE_POPCNT)

/// Count the number of 1 bits in x.
/// This implementation uses only 12 arithmetic operations.
/// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
///
inline uint64_t popcount64(uint64_t x)
{
  const uint64_t m1  = UINT64_C(0x5555555555555555);
  const uint64_t m2  = UINT64_C(0x3333333333333333);
  const uint64_t m4  = UINT64_C(0x0f0f0f0f0f0f0f0f);
  const uint64_t h01 = UINT64_C(0x0101010101010101);

  x -= (x >> 1) & m1;
  x = (x & m2) + ((x >> 2) & m2);
  x = (x + (x >> 4)) & m4;
  return (x * h01) >> 56;
}

#endif
<commit_msg>Update popcount64.hpp<commit_after>///
/// @file    popcount64.hpp
/// @brief   Count the number of 1 bits inside a 64-bit word.
///          If HAVE_POPCNT is defined then popcount64(x) uses the
///          POPCNT instruction (requires SSE4.2 for x86 & x64).
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

/// Include header generated by Autotools
#ifdef HAVE_CONFIG_H
  #include <config.h>
#endif

#if !defined(__STDC_CONSTANT_MACROS)
  #define __STDC_CONSTANT_MACROS
#endif

#include <stdint.h>

#if defined(HAVE_POPCNT)

#if defined(_MSC_VER) && defined(_WIN64)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u64(x);
}

#elif defined(_MSC_VER) && defined(_WIN32)

#include <nmmintrin.h>

inline uint64_t popcount64(uint64_t x)
{
  return _mm_popcnt_u32((uint32_t) x) +
         _mm_popcnt_u32((uint32_t)(x >> 32));
}

#elif defined(HAVE___BUILTIN_POPCOUNTLL)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcountll(x);
}

#elif defined(HAVE___BUILTIN_POPCOUNT)

inline uint64_t popcount64(uint64_t x)
{
  return __builtin_popcount((uint32_t) x) +
         __builtin_popcount((uint32_t)(x >> 32));
}

#else /* Error */

#if defined(_MSC_VER)
  #pragma error( "POPCNT not supported, remove \"/D HAVE_POPCNT\" from Makefile.msvc" )
#else
  #error "POPCNT not supported, don't use --enable-popcnt"
#endif

#endif /* HAVE_POPCNT */

#elif !defined(HAVE_POPCNT)

/// Count the number of 1 bits in x.
/// This implementation uses only 12 arithmetic operations.
/// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
///
inline uint64_t popcount64(uint64_t x)
{
  const uint64_t m1  = UINT64_C(0x5555555555555555);
  const uint64_t m2  = UINT64_C(0x3333333333333333);
  const uint64_t m4  = UINT64_C(0x0f0f0f0f0f0f0f0f);
  const uint64_t h01 = UINT64_C(0x0101010101010101);

  x -= (x >> 1) & m1;
  x = (x & m2) + ((x >> 2) & m2);
  x = (x + (x >> 4)) & m4;
  return (x * h01) >> 56;
}

#endif
<|endoftext|>


<commit_before>///
/// @file  primecount.hpp
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License.
///

#ifndef PRIMECOUNT_HPP
#define PRIMECOUNT_HPP

#include <stdexcept>
#include <string>
#include <stdint.h>

#define PRIMECOUNT_VERSION "3.4"
#define PRIMECOUNT_VERSION_MAJOR 3
#define PRIMECOUNT_VERSION_MINOR 4

namespace primecount {

class primecount_error : public std::runtime_error
{
public:
  primecount_error(const std::string& msg)
    : std::runtime_error(msg)
  { }
};

/// Alias for the fastest prime counting function in primecount.
int64_t pi(int64_t x);

/// 128-bit prime counting function.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
/// @param expr  Integer arithmetic expression e.g. "1000", "10^22"
/// @pre   expr  <= get_max_x()
///
std::string pi(const std::string& x);

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x);

/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x);

/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x);

/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x);

/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x);

/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x);

/// Calculate the nth prime using a combination of the counting
/// function and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
/// @pre n <= 216289611853439384
///
int64_t nth_prime(int64_t n);

/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a);

/// Calculate the offset logarithmic integral which is a very accurate
/// approximation of the number of primes below x.
/// @post Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
int64_t Li(int64_t x);

/// Calculate the inverse logarithmic integral Li^-1(x) which is
/// a very accurate approximation of the nth prime.
/// @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316
///
int64_t Li_inverse(int64_t x);

/// Enable/disable printing status information during computation.
void set_print_status(bool print_status);

/// Set the number of threads.
void set_num_threads(int num_threads);

/// Get the currently set number of threads.
int get_num_threads();

/// Largest integer supported by pi(const std::string& x).
/// The return type is a string as max may be a 128-bit integer
/// which is not supported by some compilers.
/// @param alpha Tuning factor used in LMO type algorithms.
/// @return for 32-bit CPUs: 2^63-1,
///         for 64-bit CPUs: max >= 10^27
///
std::string get_max_x(double alpha = 1.0);

/// Get the primecount version number, in the form “i.j”.
std::string primecount_version();

} // namespace

#endif
<commit_msg>Update version to 3.5<commit_after>///
/// @file  primecount.hpp
///
/// Copyright (C) 2016 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License.
///

#ifndef PRIMECOUNT_HPP
#define PRIMECOUNT_HPP

#include <stdexcept>
#include <string>
#include <stdint.h>

#define PRIMECOUNT_VERSION "3.5"
#define PRIMECOUNT_VERSION_MAJOR 3
#define PRIMECOUNT_VERSION_MINOR 5

namespace primecount {

class primecount_error : public std::runtime_error
{
public:
  primecount_error(const std::string& msg)
    : std::runtime_error(msg)
  { }
};

/// Alias for the fastest prime counting function in primecount.
int64_t pi(int64_t x);

/// 128-bit prime counting function.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
/// @param expr  Integer arithmetic expression e.g. "1000", "10^22"
/// @pre   expr  <= get_max_x()
///
std::string pi(const std::string& x);

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x);

/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x);

/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x);

/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x);

/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x);

/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x);

/// Calculate the nth prime using a combination of the counting
/// function and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
/// @pre n <= 216289611853439384
///
int64_t nth_prime(int64_t n);

/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a);

/// Calculate the offset logarithmic integral which is a very accurate
/// approximation of the number of primes below x.
/// @post Li(x) > pi(x) for 24 <= x <= ~ 10^316
///
int64_t Li(int64_t x);

/// Calculate the inverse logarithmic integral Li^-1(x) which is
/// a very accurate approximation of the nth prime.
/// @post Li_inverse(x) < nth_prime(x) for 7 <= x <= ~ 10^316
///
int64_t Li_inverse(int64_t x);

/// Enable/disable printing status information during computation.
void set_print_status(bool print_status);

/// Set the number of threads.
void set_num_threads(int num_threads);

/// Get the currently set number of threads.
int get_num_threads();

/// Largest integer supported by pi(const std::string& x).
/// The return type is a string as max may be a 128-bit integer
/// which is not supported by some compilers.
/// @param alpha Tuning factor used in LMO type algorithms.
/// @return for 32-bit CPUs: 2^63-1,
///         for 64-bit CPUs: max >= 10^27
///
std::string get_max_x(double alpha = 1.0);

/// Get the primecount version number, in the form “i.j”.
std::string primecount_version();

} // namespace

#endif
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

class complex_t
{
private:
	double a;
	double b;
public:
	complex_t();

	complex_t(double x, double y);

	complex_t(const complex_t&cop);

	double a_();
	double b_();

	complex_t operator * (const complex_t& c2) const;
	complex_t operator / (const complex_t& c2) const;
	complex_t operator += (const complex_t& c2); const
	complex_t operator -= (const complex_t& c2) const;
	complex_t operator *= (const complex_t& c2) const;
	complex_t operator /= (const complex_t& c2) const;
	complex_t operator = (const complex_t& result) const;
	bool operator == (const complex_t& c2) const;
	friend istream& operator >> (istream&cin, complex_t& result);
	friend ostream& operator << (ostream&cout, complex_t& result);
};
<commit_msg>Update сomplex_t.hpp<commit_after>#include <iostream>

using namespace std;

class complex_t
{
private:
	double a;
	double b;
public:
	complex_t();

	complex_t(double x, double y);

	complex_t(const complex_t&cop);

	const double a_();
	const double b_();

	complex_t operator * (const complex_t& c2) const;
	complex_t operator / (const complex_t& c2) const;
	complex_t operator += (const complex_t& c2); const
	complex_t operator -= (const complex_t& c2) const;
	complex_t operator *= (const complex_t& c2) const;
	complex_t operator /= (const complex_t& c2) const;
	complex_t operator = (const complex_t& result) const;
	bool operator == (const complex_t& c2) const;
	friend istream& operator >> (istream&cin, complex_t& result);
	friend ostream& operator << (ostream&cout, complex_t& result);
};
<|endoftext|>


<commit_before>// vial.cc

#include "stdsneezy.h"
#include "obj_vial.h"

TVial::TVial() :
  TBaseCup()
{
}

TVial::TVial(const TVial &a) :
  TBaseCup(a)
{
}

TVial & TVial::operator=(const TVial &a)
{
  if (this == &a) return *this;
  TBaseCup::operator=(a);
  return *this;
}

TVial::~TVial()
{
}

void TVial::getBestVial(TVial **best)
{
  if (getDrinkType() != LIQ_HOLYWATER)
    return;

  if (getDrinkUnits() <= 0)
    return;

  if (!*best)
    *best = this;

  if (getDrinkUnits() > (*best)->getDrinkUnits())
    *best = this;

  return;
}

int TVial::rentCost() const
{
  int num = TBaseCup::rentCost();

  if (!getDrinkUnits())
    return 0;

  if (getDrinkType() != LIQ_HOLYWATER)
    return num;

  num *= getDrinkUnits();
  num /= max(1, getMaxDrinkUnits());
  return num;
}

int TVial::objectSell(TBeing *ch, TMonster *keeper)
{
  char buf[256];

  sprintf(buf, "%s I'm sorry, I don't purchase vials.", ch->getName());
  keeper->doTell(buf);
  return TRUE;
}

bool TVial::objectRepair(TBeing *ch, TMonster *repair, silentTypeT silent)
{
  if (!silent) {
    char buf[256];

    sprintf(buf, "%s you might wanna take that somewhere else!", fname(ch->name).c_str());
    repair->doTell(buf);
  }
  return TRUE;
}

int TVial::suggestedPrice() const
{
  // c.f. balance notes for this
  if (getDrinkType() != LIQ_HOLYWATER)
    return TBaseCup::suggestedPrice();

  return (int) (133.34 * (float) getMaxDrinkUnits() + 0.5);
}

void TVial::lowCheck()
{
  int ap = suggestedPrice();
  if (ap != obj_flags.cost && ap) {
    vlogf(LOG_LOW, "vial (%s:%d) has a bad price (%d).  should be (%d)",
         getName(), objVnum(), obj_flags.cost, ap);
    obj_flags.cost = ap;
  }

  TBaseCup::lowCheck();
}
<commit_msg>allowed purchasing of full vials with holy water<commit_after>// vial.cc

#include "stdsneezy.h"
#include "obj_vial.h"

TVial::TVial() :
  TBaseCup()
{
}

TVial::TVial(const TVial &a) :
  TBaseCup(a)
{
}

TVial & TVial::operator=(const TVial &a)
{
  if (this == &a) return *this;
  TBaseCup::operator=(a);
  return *this;
}

TVial::~TVial()
{
}

void TVial::getBestVial(TVial **best)
{
  if (getDrinkType() != LIQ_HOLYWATER)
    return;

  if (getDrinkUnits() <= 0)
    return;

  if (!*best)
    *best = this;

  if (getDrinkUnits() > (*best)->getDrinkUnits())
    *best = this;

  return;
}

int TVial::rentCost() const
{
  int num = TBaseCup::rentCost();

  if (!getDrinkUnits())
    return 0;

  if (getDrinkType() != LIQ_HOLYWATER)
    return num;

  num *= getDrinkUnits();
  num /= max(1, getMaxDrinkUnits());
  return num;
}

int TVial::objectSell(TBeing *ch, TMonster *keeper)
{
  string buf;

  if(getDrinkType()!=LIQ_HOLYWATER){
    ssprintf(buf, "%s Hey, that's not holy water!.", ch->getName());
    keeper->doTell(buf.c_str());
    return TRUE;
  }

  if(getDrinkUnits()!=getMaxDrinkUnits()){
    ssprintf(buf, "%s I only purchase full vials.", ch->getName());
    keeper->doTell(buf.c_str());
    return TRUE;
  }

  return FALSE;
}

bool TVial::objectRepair(TBeing *ch, TMonster *repair, silentTypeT silent)
{
  if (!silent) {
    char buf[256];

    sprintf(buf, "%s you might wanna take that somewhere else!", fname(ch->name).c_str());
    repair->doTell(buf);
  }
  return TRUE;
}

int TVial::suggestedPrice() const
{
  // c.f. balance notes for this
  if (getDrinkType() != LIQ_HOLYWATER)
    return TBaseCup::suggestedPrice();

  return (int) (133.34 * (float) getMaxDrinkUnits() + 0.5);
}

void TVial::lowCheck()
{
  int ap = suggestedPrice();
  if (ap != obj_flags.cost && ap) {
    vlogf(LOG_LOW, "vial (%s:%d) has a bad price (%d).  should be (%d)",
         getName(), objVnum(), obj_flags.cost, ap);
    obj_flags.cost = ap;
  }

  TBaseCup::lowCheck();
}
<|endoftext|>


<commit_before>// Test Suite for geos::precision::CommonBits class.

// tut
#include <tut/tut.hpp>
// geos
#include <geos/constants.h>
#include <geos/precision/CommonBits.h>
// std

using geos::precision::CommonBits;

namespace tut {
// Common data used by tests
struct test_commonbits_data {};

typedef test_group<test_commonbits_data> group;
typedef group::object object;

group test_commonbits_group("geos::precision::CommonBits");

// getBit from zero.
template<>
template<>
void object::test<1>
()
{
    constexpr int64 val = 0ull;
    for(int i = 0; i < 64; i++) {
        ensure_equals(CommonBits::getBit(val, i), 0);
    }
}

// getBit from all ones.
template<>
template<>
void object::test<2>
()
{
    constexpr int64 val = 0xffffffffffffffffull;
    for(int i = 0; i < 64; i++) {
        ensure_equals(CommonBits::getBit(val, i), 1);
    }
}

// getBit check high versus low bits.
template<>
template<>
void object::test<3>
()
{
    constexpr int64 val = 0xffffffff00000000ull;
    ensure_equals(CommonBits::getBit(val, 0), 0);
    ensure_equals(CommonBits::getBit(val, 63), 1);
}

// zeroLowerBits.
template<>
template<>
void object::test<4>()
{
    constexpr int64 val = static_cast<int64>(0xffffffffffffffffull);
    ensure_equals(sizeof(val), 8);

    ensure_equals(CommonBits::zeroLowerBits(val, -1), 0);
    ensure_equals(CommonBits::zeroLowerBits(val, 0), 0);
    ensure_equals(CommonBits::zeroLowerBits(val, 1), -2);
    ensure_equals(CommonBits::zeroLowerBits(val, 2), -4);
    ensure_equals(CommonBits::zeroLowerBits(val, 16), -65536);
    ensure_equals(CommonBits::zeroLowerBits(val, 31), -2147483648ll);
    ensure_equals(CommonBits::zeroLowerBits(val, 32), -4294967296ll);
    ensure_equals(CommonBits::zeroLowerBits(val, 62), -4611686018427387904ll);
    ensure_equals(static_cast<uint64_t>(CommonBits::zeroLowerBits(val, 62)), 0xc000000000000000ull);
    ensure_equals(static_cast<uint64_t>(CommonBits::zeroLowerBits(val, 63)), 9223372036854775808ull);
    ensure_equals(static_cast<uint64_t>(CommonBits::zeroLowerBits(val, 63)), 0x8000000000000000ull);
    ensure_equals(CommonBits::zeroLowerBits(val, 64), 0);
    ensure_equals(CommonBits::zeroLowerBits(val, 10000), 0);
}

} // namespace tut
<commit_msg>Match test to behaviour in no-op case (leave -1 in place)<commit_after>// Test Suite for geos::precision::CommonBits class.

// tut
#include <tut/tut.hpp>
// geos
#include <geos/constants.h>
#include <geos/precision/CommonBits.h>
// std

using geos::precision::CommonBits;

namespace tut {
// Common data used by tests
struct test_commonbits_data {};

typedef test_group<test_commonbits_data> group;
typedef group::object object;

group test_commonbits_group("geos::precision::CommonBits");

// getBit from zero.
template<>
template<>
void object::test<1>
()
{
    constexpr int64 val = 0ull;
    for(int i = 0; i < 64; i++) {
        ensure_equals(CommonBits::getBit(val, i), 0);
    }
}

// getBit from all ones.
template<>
template<>
void object::test<2>
()
{
    constexpr int64 val = 0xffffffffffffffffull;
    for(int i = 0; i < 64; i++) {
        ensure_equals(CommonBits::getBit(val, i), 1);
    }
}

// getBit check high versus low bits.
template<>
template<>
void object::test<3>
()
{
    constexpr int64 val = 0xffffffff00000000ull;
    ensure_equals(CommonBits::getBit(val, 0), 0);
    ensure_equals(CommonBits::getBit(val, 63), 1);
}

// zeroLowerBits.
template<>
template<>
void object::test<4>()
{
    constexpr int64 val = static_cast<int64>(0xffffffffffffffffull);
    ensure_equals(sizeof(val), 8);

    ensure_equals(CommonBits::zeroLowerBits(val, -1), 0);
    ensure_equals(CommonBits::zeroLowerBits(val, 0), -1);
    ensure_equals(CommonBits::zeroLowerBits(val, 1), -2);
    ensure_equals(CommonBits::zeroLowerBits(val, 2), -4);
    ensure_equals(CommonBits::zeroLowerBits(val, 16), -65536);
    ensure_equals(CommonBits::zeroLowerBits(val, 31), -2147483648ll);
    ensure_equals(CommonBits::zeroLowerBits(val, 32), -4294967296ll);
    ensure_equals(CommonBits::zeroLowerBits(val, 62), -4611686018427387904ll);
    ensure_equals(static_cast<uint64_t>(CommonBits::zeroLowerBits(val, 62)), 0xc000000000000000ull);
    ensure_equals(static_cast<uint64_t>(CommonBits::zeroLowerBits(val, 63)), 9223372036854775808ull);
    ensure_equals(static_cast<uint64_t>(CommonBits::zeroLowerBits(val, 63)), 0x8000000000000000ull);
    ensure_equals(CommonBits::zeroLowerBits(val, 64), 0);
    ensure_equals(CommonBits::zeroLowerBits(val, 10000), 0);
}

} // namespace tut
<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"

using namespace std;

void chain :: readAndStoreFromFile(char* fileName)
{
	//This function reads integers from the file given by fileName then store them in the chain

}

void chain :: eraseModuloValue(int theInt)
{
	//This function erases all the entries from the list which are multiple of theInt

}

void chain :: oddAndEvenOrdering()
{
	//This function reorders the list such a way that all odd numbers precede all even numbers.
	//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.

}

void chain :: reverse()
{
	//Reverses the list

}

chain :: chain(int initialCapacity)
{
	//Constructor
	if(initialCapacity < 1)
	{
		ostringstream s;
		s << "Initial capacity = " << initialCapacity << " Must be > 0";
		throw illegalParameterValue(s.str());
	}

	firstNode = NULL;
	listSize = 0;

}

chain :: ~chain()
{
	//Destructor. Delete all nodes in chain

	while(firstNode != NULL)
	{
		//delete firstNode
		chainNode* nextNode = firstNode->next;
		delete firstNode;
		firstNode = nextNode;

	}

}

int* chain :: get(int theIndex) const
{
	//Return element whose index is theIndex.
	//Throw illegalIndex exception if no such element.
	try{
		checkIndex(theIndex);
	}
	catch(illegalIndex &e){
		e.outputMessage();
		return NULL;
	}

	chainNode* currentNode = firstNode;
	for(int i=0;i<theIndex;i++)
		currentNode = currentNode->next;

	return &currentNode->element;

}

int chain :: indexOf(const int& theElement) const
{
	//Return index of first occurrence of theElement.
	//Return -1 of theElement not in list.

	chainNode* currentNode = firstNode;
	int index = 0;
	while(currentNode != NULL && currentNode->element != theElement)
	{
		//move to the next node
		currentNode = currentNode->next;
		index++;

	}

	//make sure we found matching element
	if(currentNode == NULL)
		return -1;

	else
		return index;

}

void chain :: erase(int theIndex)
{
	//Delete the element whose index is theIndex.
	//Throw illegalIndex exception if no such element.

	try{
		checkIndex(theIndex);
	}
	catch(illegalIndex &e){
		e.outputMessage();
		return;
	}

	chainNode* deleteNode;
	if(theIndex == 0)
	{
		//remove first node from chain
		deleteNode = firstNode;
		firstNode = firstNode->next;

	}
	else
	{
		//use p to get to predecessor of desired node
		chainNode* p = firstNode;
		for(int i=0;i<theIndex-1;i++)
			p = p->next;

		deleteNode = p->next;
		p->next = p->next->next; //remove deleteNode from chain

	}

	listSize--;
	delete deleteNode;

}

void chain :: insert(int theIndex, const int& theElement)
{
	//Insert theElement so that its index is theIndex.
	try{
   		if (theIndex < 0 || theIndex > listSize)
   		{// invalid index

			ostringstream s;
    			s << "index = " << theIndex << " size = " << listSize;
    			throw illegalIndex(s.str());
		}
	}
	catch(illegalIndex &e){
		e.outputMessage();
		return;
	}

	if(theIndex == 0)
		//insert at front
		firstNode = new chainNode(theElement, firstNode);
	else
	{
		chainNode *p = firstNode;
		for(int i=0;i<theIndex-1;i++)
			p = p->next;

		//insert after p
		p->next = new chainNode(theElement, p->next);

	}

	listSize++;

}

void chain :: output() const
{
	//Put the list into the output.

	for(int i=0;i<listSize;i++)
		cout << *this->get(i) << " ";
	cout<<endl;

}

void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
 // listSize - 1.

   	if (theIndex < 0 || theIndex >= listSize){
		ostringstream s;
    		s << "index = " << theIndex << " size = "
                    << listSize<<", the input index is invalid";
    		throw illegalIndex(s.str());
	}

}
<commit_msg>Update chain.cpp<commit_after>#include <iostream>
#include <sstream>
#include "Myexception.h"
#include "chain.h"

using namespace std;

void chain :: readAndStoreFromFile(char* fileName)
{
	//This function reads integers from the file given by fileName then store them in the chain

	std::ifstream data(filename);
	std::string line;

	while(std::getline(data,line))
		td::stringstream    str(line);
		td::string          text;

		td::getline(str,text,'=');

		double   value;
		tr >> value;
	}

}

void chain :: eraseModuloValue(int theInt)
{
	//This function erases all the entries from the list which are multiple of theInt

}

void chain :: oddAndEvenOrdering()
{
	//This function reorders the list such a way that all odd numbers precede all even numbers.
	//Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.

}

void chain :: reverse()
{
	//Reverses the list

}

chain :: chain(int initialCapacity)
{
	//Constructor
	if(initialCapacity < 1)
	{
		ostringstream s;
		s << "Initial capacity = " << initialCapacity << " Must be > 0";
		throw illegalParameterValue(s.str());
	}

	firstNode = NULL;
	listSize = 0;

}

chain :: ~chain()
{
	//Destructor. Delete all nodes in chain

	while(firstNode != NULL)
	{
		//delete firstNode
		chainNode* nextNode = firstNode->next;
		delete firstNode;
		firstNode = nextNode;

	}

}

int* chain :: get(int theIndex) const
{
	//Return element whose index is theIndex.
	//Throw illegalIndex exception if no such element.
	try{
		checkIndex(theIndex);
	}
	catch(illegalIndex &e){
		e.outputMessage();
		return NULL;
	}

	chainNode* currentNode = firstNode;
	for(int i=0;i<theIndex;i++)
		currentNode = currentNode->next;

	return &currentNode->element;

}

int chain :: indexOf(const int& theElement) const
{
	//Return index of first occurrence of theElement.
	//Return -1 of theElement not in list.

	chainNode* currentNode = firstNode;
	int index = 0;
	while(currentNode != NULL && currentNode->element != theElement)
	{
		//move to the next node
		currentNode = currentNode->next;
		index++;

	}

	//make sure we found matching element
	if(currentNode == NULL)
		return -1;

	else
		return index;

}

void chain :: erase(int theIndex)
{
	//Delete the element whose index is theIndex.
	//Throw illegalIndex exception if no such element.

	try{
		checkIndex(theIndex);
	}
	catch(illegalIndex &e){
		e.outputMessage();
		return;
	}

	chainNode* deleteNode;
	if(theIndex == 0)
	{
		//remove first node from chain
		deleteNode = firstNode;
		firstNode = firstNode->next;

	}
	else
	{
		//use p to get to predecessor of desired node
		chainNode* p = firstNode;
		for(int i=0;i<theIndex-1;i++)
			p = p->next;

		deleteNode = p->next;
		p->next = p->next->next; //remove deleteNode from chain

	}

	listSize--;
	delete deleteNode;

}

void chain :: insert(int theIndex, const int& theElement)
{
	//Insert theElement so that its index is theIndex.
	try{
   		if (theIndex < 0 || theIndex > listSize)
   		{// invalid index

			ostringstream s;
    			s << "index = " << theIndex << " size = " << listSize;
    			throw illegalIndex(s.str());
		}
	}
	catch(illegalIndex &e){
		e.outputMessage();
		return;
	}

	if(theIndex == 0)
		//insert at front
		firstNode = new chainNode(theElement, firstNode);
	else
	{
		chainNode *p = firstNode;
		for(int i=0;i<theIndex-1;i++)
			p = p->next;

		//insert after p
		p->next = new chainNode(theElement, p->next);

	}

	listSize++;

}

void chain :: output() const
{
	//Put the list into the output.

	for(int i=0;i<listSize;i++)
		cout << *this->get(i) << " ";
	cout<<endl;

}

void chain::checkIndex(int theIndex) const
{
// Verify that theIndex is between 0 and
 // listSize - 1.

   	if (theIndex < 0 || theIndex >= listSize){
		ostringstream s;
    		s << "index = " << theIndex << " size = "
                    << listSize<<", the input index is invalid";
    		throw illegalIndex(s.str());
	}

}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/

#include "merconstants.h"
#include "merrunconfiguration.h"
#include "merdeployconfiguration.h"
#include "projectexplorer/kitinformation.h"

#include <projectexplorer/target.h>
#include <projectexplorer/project.h>
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/deployconfiguration.h>
#include <projectexplorer/kitinformation.h>

namespace Mer {
namespace Internal {

MerRunConfiguration::MerRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id,
                                         const QString &proFilePath)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, id, proFilePath)
{
    ctor();
}

MerRunConfiguration::MerRunConfiguration(ProjectExplorer::Target *parent,
                                         MerRunConfiguration *source)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, source)
{
    ctor();
}

void MerRunConfiguration::ctor()
{
    connect(target(),SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)),this,SIGNAL(enabledChanged()));
}

QString MerRunConfiguration::disabledReason() const
{
    if(m_disabledReason.isEmpty())
        return RemoteLinuxRunConfiguration::disabledReason();
    else
        return m_disabledReason;
}

bool MerRunConfiguration::isEnabled() const
{
    //TODO Hack

    ProjectExplorer::DeployConfiguration* conf = target()->activeDeployConfiguration();
    if(target()->kit())
    {
        if(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target()->kit()) == Constants::MER_DEVICE_TYPE_ARM
            && conf->id() == MerMb2RpmBuildConfiguration::configurationId()) {
            m_disabledReason = tr("This deployment method does not support run configuration");
            return false;
        }
    }

    return RemoteLinuxRunConfiguration::isEnabled();
}

QString MerRunConfiguration::defaultRemoteExecutableFilePath() const
{
    ProjectExplorer::DeployConfiguration* conf = target()->activeDeployConfiguration();
    if (!conf) return QString();

    QString executable = RemoteLinuxRunConfiguration::defaultRemoteExecutableFilePath();
    if (conf->id() == MerRsyncDeployConfiguration::configurationId()) {
        QString projectName = target()->project()->displayName();
        return QLatin1String("/opt/sdk/") + projectName + executable;
    }

    if (conf->id() == MerRpmDeployConfiguration::configurationId()) {
        //TODO:
        return executable;
    }

    return executable;
}

// TODO: Temporary workaround for lipstick QML issue
// Opens unlock the phone befeore running app
// Remove me !
QString MerRunConfiguration::commandPrefix() const
{
    return RemoteLinuxRunConfiguration::commandPrefix();
//    return QString::fromLatin1("/usr/sbin/mcetool -Don;").append(
//                RemoteLinuxRunConfiguration::commandPrefix());
}

} // Internal
} // Mer
<commit_msg>Mer runconfiguration uses faketty to get logs from application<commit_after>/****************************************************************************
**
** Copyright (C) 2012 - 2013 Jolla Ltd.
** Contact: http://jolla.com/
**
** This file is part of Qt Creator.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Digia.
**
****************************************************************************/

#include "merconstants.h"
#include "merrunconfiguration.h"
#include "merdeployconfiguration.h"
#include <remotelinux/remotelinuxenvironmentaspect.h>
#include "projectexplorer/kitinformation.h"

#include <projectexplorer/target.h>
#include <projectexplorer/project.h>
#include <projectexplorer/deploymentdata.h>
#include <projectexplorer/deployconfiguration.h>
#include <projectexplorer/kitinformation.h>

namespace Mer {
namespace Internal {

MerRunConfiguration::MerRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id,
                                         const QString &proFilePath)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, id, proFilePath)
{
    ctor();
}

MerRunConfiguration::MerRunConfiguration(ProjectExplorer::Target *parent,
                                         MerRunConfiguration *source)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, source)
{
    ctor();
}

void MerRunConfiguration::ctor()
{
    connect(target(),SIGNAL(activeDeployConfigurationChanged(ProjectExplorer::DeployConfiguration*)),this,SIGNAL(enabledChanged()));
}

QString MerRunConfiguration::disabledReason() const
{
    if(m_disabledReason.isEmpty())
        return RemoteLinuxRunConfiguration::disabledReason();
    else
        return m_disabledReason;
}

bool MerRunConfiguration::isEnabled() const
{
    //TODO Hack

    ProjectExplorer::DeployConfiguration* conf = target()->activeDeployConfiguration();
    if(target()->kit())
    {
        if(ProjectExplorer::DeviceTypeKitInformation::deviceTypeId(target()->kit()) == Constants::MER_DEVICE_TYPE_ARM
            && conf->id() == MerMb2RpmBuildConfiguration::configurationId()) {
            m_disabledReason = tr("This deployment method does not support run configuration");
            return false;
        }
    }

    return RemoteLinuxRunConfiguration::isEnabled();
}

QString MerRunConfiguration::defaultRemoteExecutableFilePath() const
{
    ProjectExplorer::DeployConfiguration* conf = target()->activeDeployConfiguration();
    if (!conf) return QString();

    QString executable = RemoteLinuxRunConfiguration::defaultRemoteExecutableFilePath();
    if (conf->id() == MerRsyncDeployConfiguration::configurationId()) {
        QString projectName = target()->project()->displayName();
        return QLatin1String("/opt/sdk/") + projectName + executable;
    }

    if (conf->id() == MerRpmDeployConfiguration::configurationId()) {
        //TODO:
        return executable;
    }

    return executable;
}

// TODO: Temporary workaround for lipstick QML issue
// Opens unlock the phone befeore running app
// Remove me !
QString MerRunConfiguration::commandPrefix() const
{
  /*
   * The full command prefix will look something like this:
   *
   * test -f /etc/profile && source /etc/profile;test -f
   * $HOME/.profile && source $HOME/.profile; faketty() {
   * /usr/bin/script -qfc "$(printf "'%s' " "$@")" /dev/null; };
   * DISPLAY=:0.0 faketty
   *
   * The reason to use the faketty function to start the program is
   * that Mer qtbase is only logging to console when the program is
   * run from a tty. We need the console logs in order to show them in
   * QtC.
   *
   * TODO remove this if/when there's a better way to capture console
   * logs.
   *
   */

  RemoteLinux::RemoteLinuxEnvironmentAspect *aspect =
    extraAspect<RemoteLinux::RemoteLinuxEnvironmentAspect>();
  QTC_ASSERT(aspect, return QString());

  // source the profile scripts
  QString etcprofile = RemoteLinuxRunConfiguration::environmentPreparationCommand();

  // faketty bash function
  QString fakettyfunc = QString::fromLatin1("faketty() { /usr/bin/script -qfc \"$(printf \"'%s' \" \"$@\")\" /dev/null; }");

  // runenvironment as in RemoteLinuxRunConfiguration
  QString runenvironment = QString::fromLatin1("DISPLAY=:0.0 %1")
    .arg(aspect->userEnvironmentChangesAsString());

  // the actual call to faketty, this must be given before the command itself
  QString fakettycmd = QString::fromLatin1("faketty");

  return QString::fromLatin1("%1; %2; %3 %4")
    .arg(etcprofile, fakettyfunc, runenvironment, fakettycmd);

//    return QString::fromLatin1("/usr/sbin/mcetool -Don;").append(
//                RemoteLinuxRunConfiguration::commandPrefix());
}

} // Internal
} // Mer
<|endoftext|>


<commit_before>/**************************************************************************
**
** Copyright (C) 2012 - 2014 BlackBerry Limited. All rights reserved.
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qnxrunconfiguration.h"
#include "qnxconstants.h"

#include <remotelinux/remotelinuxrunconfigurationwidget.h>
#include <utils/environment.h>

#include <QLabel>
#include <QLineEdit>

using namespace Qnx;
using namespace Qnx::Internal;

namespace {
const char QtLibPathKey[] = "Qt4ProjectManager.QnxRunConfiguration.QtLibPath";
}

QnxRunConfiguration::QnxRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id, const QString &proFilePath)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, id, proFilePath)
{
}

QnxRunConfiguration::QnxRunConfiguration(ProjectExplorer::Target *parent, QnxRunConfiguration *source)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, source)
    , m_qtLibPath(source->m_qtLibPath)
{
}

void QnxRunConfiguration::setQtLibPath(const QString &path)
{
    m_qtLibPath = path;
}

Utils::Environment QnxRunConfiguration::environment() const
{
    Utils::Environment env = RemoteLinuxRunConfiguration::environment();
    if (!m_qtLibPath.isEmpty()) {
        env.appendOrSet(QLatin1String("LD_LIBRARY_PATH"),
                        m_qtLibPath + QLatin1String("/lib:$LD_LIBRARY_PATH"));
        env.appendOrSet(QLatin1String("QML_IMPORT_PATH"),
                        m_qtLibPath + QLatin1String("/imports:$QML_IMPORT_PATH"));
        env.appendOrSet(QLatin1String("QML2_IMPORT_PATH"),
                        m_qtLibPath + QLatin1String("/qml:$QML2_IMPORT_PATH"));
        env.appendOrSet(QLatin1String("QT_PLUGIN_PATH"),
                        m_qtLibPath + QLatin1String("/plugins:$QT_PLUGIN_PATH"));
        env.appendOrSet(QLatin1String("QT_QPA_FONTDIR"),
                        m_qtLibPath + QLatin1String("/lib/fonts:$QT_QPA_FONTDIR"));
    }

    return env;
}

QWidget *QnxRunConfiguration::createConfigurationWidget()
{
    RemoteLinux::RemoteLinuxRunConfigurationWidget *rcWidget =
            qobject_cast<RemoteLinux::RemoteLinuxRunConfigurationWidget *>(RemoteLinux::RemoteLinuxRunConfiguration::createConfigurationWidget());

    QLabel *label = new QLabel(tr("Path to Qt libraries on device:"));
    QLineEdit *lineEdit = new QLineEdit(m_qtLibPath);

    connect(lineEdit, SIGNAL(textChanged(QString)), this, SLOT(setQtLibPath(QString)));

    rcWidget->addFormLayoutRow(label, lineEdit);

    return rcWidget;
}

QVariantMap QnxRunConfiguration::toMap() const
{
    QVariantMap map(RemoteLinux::RemoteLinuxRunConfiguration::toMap());
    map.insert(QLatin1String(QtLibPathKey), m_qtLibPath);
    return map;
}

bool QnxRunConfiguration::fromMap(const QVariantMap &map)
{
    if (!RemoteLinux::RemoteLinuxRunConfiguration::fromMap(map))
        return false;

    setQtLibPath(map.value(QLatin1String(QtLibPathKey)).toString());
    return true;
}
<commit_msg>Qnx: Correctly set QT_QPA_FONTDIR<commit_after>/**************************************************************************
**
** Copyright (C) 2012 - 2014 BlackBerry Limited. All rights reserved.
**
** Contact: BlackBerry (qt@blackberry.com)
** Contact: KDAB (info@kdab.com)
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "qnxrunconfiguration.h"
#include "qnxconstants.h"

#include <remotelinux/remotelinuxrunconfigurationwidget.h>
#include <utils/environment.h>

#include <QLabel>
#include <QLineEdit>

using namespace Qnx;
using namespace Qnx::Internal;

namespace {
const char QtLibPathKey[] = "Qt4ProjectManager.QnxRunConfiguration.QtLibPath";
}

QnxRunConfiguration::QnxRunConfiguration(ProjectExplorer::Target *parent, const Core::Id id, const QString &proFilePath)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, id, proFilePath)
{
}

QnxRunConfiguration::QnxRunConfiguration(ProjectExplorer::Target *parent, QnxRunConfiguration *source)
    : RemoteLinux::RemoteLinuxRunConfiguration(parent, source)
    , m_qtLibPath(source->m_qtLibPath)
{
}

void QnxRunConfiguration::setQtLibPath(const QString &path)
{
    m_qtLibPath = path;
}

Utils::Environment QnxRunConfiguration::environment() const
{
    Utils::Environment env = RemoteLinuxRunConfiguration::environment();
    if (!m_qtLibPath.isEmpty()) {
        env.appendOrSet(QLatin1String("LD_LIBRARY_PATH"),
                        m_qtLibPath + QLatin1String("/lib:$LD_LIBRARY_PATH"));
        env.appendOrSet(QLatin1String("QML_IMPORT_PATH"),
                        m_qtLibPath + QLatin1String("/imports:$QML_IMPORT_PATH"));
        env.appendOrSet(QLatin1String("QML2_IMPORT_PATH"),
                        m_qtLibPath + QLatin1String("/qml:$QML2_IMPORT_PATH"));
        env.appendOrSet(QLatin1String("QT_PLUGIN_PATH"),
                        m_qtLibPath + QLatin1String("/plugins:$QT_PLUGIN_PATH"));
        env.set(QLatin1String("QT_QPA_FONTDIR"),
                        m_qtLibPath + QLatin1String("/lib/fonts"));
    }

    return env;
}

QWidget *QnxRunConfiguration::createConfigurationWidget()
{
    RemoteLinux::RemoteLinuxRunConfigurationWidget *rcWidget =
            qobject_cast<RemoteLinux::RemoteLinuxRunConfigurationWidget *>(RemoteLinux::RemoteLinuxRunConfiguration::createConfigurationWidget());

    QLabel *label = new QLabel(tr("Path to Qt libraries on device:"));
    QLineEdit *lineEdit = new QLineEdit(m_qtLibPath);

    connect(lineEdit, SIGNAL(textChanged(QString)), this, SLOT(setQtLibPath(QString)));

    rcWidget->addFormLayoutRow(label, lineEdit);

    return rcWidget;
}

QVariantMap QnxRunConfiguration::toMap() const
{
    QVariantMap map(RemoteLinux::RemoteLinuxRunConfiguration::toMap());
    map.insert(QLatin1String(QtLibPathKey), m_qtLibPath);
    return map;
}

bool QnxRunConfiguration::fromMap(const QVariantMap &map)
{
    if (!RemoteLinux::RemoteLinuxRunConfiguration::fromMap(map))
        return false;

    setQtLibPath(map.value(QLatin1String(QtLibPathKey)).toString());
    return true;
}
<|endoftext|>