text:
#include <util_coo_matrix.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>

BOOST_AUTO_TEST_SUITE(coo_matrix);

BOOST_AUTO_TEST_CASE(incremental_insert)
{
  util::COOMatrix<float> A;

  BOOST_CHECK_EQUAL(A.nzeros(), 0u );
  BOOST_CHECK_EQUAL(A.rows(), 0u );
  BOOST_CHECK_EQUAL(A.cols(), 0u );

  BOOST_CHECK_NO_THROW( A.init(5u, 5u, 3u) );
  BOOST_CHECK_EQUAL(A.nzeros(), 0u );
  BOOST_CHECK_EQUAL(A.rows(), 5u );
  BOOST_CHECK_EQUAL(A.cols(), 5u );

  BOOST_CHECK( A.insert(0u, 0u, 1.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 1u );

  BOOST_CHECK( A.insert(0u, 1u, 2.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 2u );

  BOOST_CHECK( A.insert(0u, 2u, 3.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 3u );

  BOOST_CHECK( A.insert(1u, 0u, 4.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 4u );

  BOOST_CHECK( A.insert(1u, 1u, 5.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 5u );

  BOOST_CHECK( A.insert(1u, 2u, 6.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 6u );

  BOOST_CHECK( A.insert(2u, 0u, 7.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 7u );

  BOOST_CHECK( A.insert(2u, 1u, 8.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 8u );

  BOOST_CHECK( A.insert(2u, 2u, 9.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 9u );

  BOOST_CHECK( A.insert(3u, 0u, 10.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 10u );

  BOOST_CHECK( A.insert(3u, 1u, 11.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 11u );

  BOOST_CHECK( A.insert(3u, 2u, 12.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 12u );

  BOOST_CHECK( A.insert(4u, 0u, 13.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 13u );

  BOOST_CHECK( A.insert(4u, 1u, 14.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 14u );

  BOOST_CHECK( A.insert(4u, 2u, 15.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 15u );

  std::cout << util::to_string(A) << std::endl;
}

BOOST_AUTO_TEST_CASE(backward_insert)
{
  util::COOMatrix<float> A;

  BOOST_CHECK_EQUAL(A.nzeros(), 0u );
  BOOST_CHECK_EQUAL(A.rows(), 0u );
  BOOST_CHECK_EQUAL(A.cols(), 0u );

  BOOST_CHECK_NO_THROW( A.init(5u,5u, 3u) );
  BOOST_CHECK_EQUAL(A.nzeros(), 0u );
  BOOST_CHECK_EQUAL(A.rows(), 5u );
  BOOST_CHECK_EQUAL(A.cols(), 5u );

  BOOST_CHECK( A.insert(4u, 2u, 15.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 1u );

  BOOST_CHECK( A.insert(4u, 1u, 14.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 2u );

  BOOST_CHECK( A.insert(4u, 0u, 13.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 3u );

  BOOST_CHECK( A.insert(3u, 2u, 12.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 4u );

  BOOST_CHECK( A.insert(3u, 1u, 11.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 5u );

  BOOST_CHECK( A.insert(3u, 0u, 10.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 6u );

  BOOST_CHECK( A.insert(2u, 2u, 9.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 7u );

  BOOST_CHECK( A.insert(2u, 1u, 8.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 8u );

  BOOST_CHECK( A.insert(2u, 0u, 7.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 9u );

  BOOST_CHECK( A.insert(1u, 2u, 6.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 10u );

  BOOST_CHECK( A.insert(1u, 1u, 5.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 11u );

  BOOST_CHECK( A.insert(1u, 0u, 4.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 12u );

  BOOST_CHECK( A.insert(0u, 2u, 3.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 13u );

  BOOST_CHECK( A.insert(0u, 1u, 2.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 14u );

  BOOST_CHECK( A.insert(0u, 0u, 1.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 15u );

  std::cout << util::to_string(A) << std::endl;

}

BOOST_AUTO_TEST_CASE(inside_insert)
{
  util::COOMatrix<float> A;

  BOOST_CHECK_NO_THROW( A.init(5u,5u, 3u) );

  BOOST_CHECK( A.insert(0u, 0u, 1.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 1u );

  BOOST_CHECK( A.insert(0u, 1u, 2.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 2u );

  BOOST_CHECK( A.insert(4u, 1u, 14.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 3u );

  BOOST_CHECK( A.insert(4u, 2u, 15.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 4u );

  BOOST_CHECK( A.insert(0u, 2u, 3.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 5u );

  BOOST_CHECK( A.insert(1u, 0u, 4.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 6u );

  BOOST_CHECK( A.insert(1u, 1u, 5.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 7u );

  BOOST_CHECK( A.insert(3u, 0u, 10.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 8u );

  BOOST_CHECK( A.insert(3u, 1u, 11.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 9u );

  BOOST_CHECK( A.insert(3u, 2u, 12.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 10u );

  BOOST_CHECK( A.insert(4u, 0u, 13.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 11u );

  BOOST_CHECK( A.insert(2u, 2u, 9.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 12u );

  BOOST_CHECK( A.insert(2u, 1u, 8.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 13u );

  BOOST_CHECK( A.insert(2u, 0u, 7.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 14u );

  BOOST_CHECK( A.insert(1u, 2u, 6.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 15u );

  std::cout << util::to_string(A) << std::endl;
}

BOOST_AUTO_TEST_CASE(auto_growth)
{
  util::COOMatrix<float> A;

  BOOST_CHECK_NO_THROW( A.init(5u, 5u, 1u) );
  BOOST_CHECK_EQUAL(A.nzeros(), 0u );
  BOOST_CHECK_EQUAL(A.rows(), 5u );
  BOOST_CHECK_EQUAL(A.cols(), 5u );

  BOOST_CHECK( A.insert(0u, 0u, 1.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 1u );

  BOOST_CHECK( A.insert(0u, 1u, 2.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 2u );

  BOOST_CHECK( A.insert(0u, 2u, 3.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 3u );

  BOOST_CHECK( A.insert(1u, 0u, 4.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 4u );

  BOOST_CHECK( A.insert(1u, 1u, 5.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 5u );

  BOOST_CHECK( A.insert(1u, 2u, 6.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 6u );

  BOOST_CHECK( A.insert(2u, 0u, 7.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 7u );

  BOOST_CHECK( A.insert(2u, 1u, 8.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 8u );

  BOOST_CHECK( A.insert(2u, 2u, 9.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 9u );

  BOOST_CHECK( A.insert(3u, 0u, 10.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 10u );

  BOOST_CHECK( A.insert(3u, 1u, 11.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 11u );

  BOOST_CHECK( A.insert(3u, 2u, 12.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 12u );

  BOOST_CHECK( A.insert(4u, 0u, 13.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 13u );

  BOOST_CHECK( A.insert(4u, 1u, 14.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 14u );

  BOOST_CHECK( A.insert(4u, 2u, 15.0f) );
  BOOST_CHECK_EQUAL(A.nzeros(), 15u );

  std::cout << util::to_string(A) << std::endl;
}

BOOST_AUTO_TEST_CASE(transpose)
{
  util::COOMatrix<float> A;

  BOOST_CHECK_NO_THROW( A.init(5u, 5u, 3u) );
  BOOST_CHECK( A.insert(0u, 0u, 1.0f) );
  BOOST_CHECK( A.insert(0u, 1u, 2.0f) );
  BOOST_CHECK( A.insert(0u, 2u, 3.0f) );
  BOOST_CHECK( A.insert(1u, 0u, 4.0f) );
  BOOST_CHECK( A.insert(1u, 1u, 5.0f) );
  BOOST_CHECK( A.insert(1u, 2u, 6.0f) );
  BOOST_CHECK( A.insert(2u, 0u, 7.0f) );
  BOOST_CHECK( A.insert(2u, 1u, 8.0f) );
  BOOST_CHECK( A.insert(2u, 2u, 9.0f) );
  BOOST_CHECK( A.insert(3u, 0u, 10.0f) );
  BOOST_CHECK( A.insert(3u, 1u, 11.0f) );
  BOOST_CHECK( A.insert(3u, 2u, 12.0f) );
  BOOST_CHECK( A.insert(4u, 0u, 13.0f) );
  BOOST_CHECK( A.insert(4u, 1u, 14.0f) );
  BOOST_CHECK( A.insert(4u, 2u, 15.0f) );

  std::cout << util::to_string(A) << std::endl;

  util::COOMatrix<float> At = util::transpose(A);

  std::cout << util::to_string(At) << std::endl;

  BOOST_CHECK_EQUAL(At.row_indices()[0],  0u );
  BOOST_CHECK_EQUAL(At.row_indices()[1],  0u );
  BOOST_CHECK_EQUAL(At.row_indices()[2],  0u );
  BOOST_CHECK_EQUAL(At.row_indices()[3],  0u );
  BOOST_CHECK_EQUAL(At.row_indices()[4],  0u );
  BOOST_CHECK_EQUAL(At.row_indices()[5],  1u );
  BOOST_CHECK_EQUAL(At.row_indices()[6],  1u );
  BOOST_CHECK_EQUAL(At.row_indices()[7],  1u );
  BOOST_CHECK_EQUAL(At.row_indices()[8],  1u );
  BOOST_CHECK_EQUAL(At.row_indices()[9],  1u );
  BOOST_CHECK_EQUAL(At.row_indices()[10], 2u );
  BOOST_CHECK_EQUAL(At.row_indices()[11], 2u );
  BOOST_CHECK_EQUAL(At.row_indices()[12], 2u );
  BOOST_CHECK_EQUAL(At.row_indices()[13], 2u );
  BOOST_CHECK_EQUAL(At.row_indices()[14], 2u );

  BOOST_CHECK_EQUAL(At.column_indices()[0],  0u );
  BOOST_CHECK_EQUAL(At.column_indices()[1],  1u );
  BOOST_CHECK_EQUAL(At.column_indices()[2],  2u );
  BOOST_CHECK_EQUAL(At.column_indices()[3],  3u );
  BOOST_CHECK_EQUAL(At.column_indices()[4],  4u );
  BOOST_CHECK_EQUAL(At.column_indices()[5],  0u );
  BOOST_CHECK_EQUAL(At.column_indices()[6],  1u );
  BOOST_CHECK_EQUAL(At.column_indices()[7],  2u );
  BOOST_CHECK_EQUAL(At.column_indices()[8],  3u );
  BOOST_CHECK_EQUAL(At.column_indices()[9],  4u );
  BOOST_CHECK_EQUAL(At.column_indices()[10], 0u );
  BOOST_CHECK_EQUAL(At.column_indices()[11], 1u );
  BOOST_CHECK_EQUAL(At.column_indices()[12], 2u );
  BOOST_CHECK_EQUAL(At.column_indices()[13], 3u );
  BOOST_CHECK_EQUAL(At.column_indices()[14], 4u );

  BOOST_CHECK_CLOSE(At.values()[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[1],  4.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[2],  7.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[3],  10.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[4],  13.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[5],  2.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[6],  5.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[7],  8.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[8],  11.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[9],  14.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[10], 3.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[11], 6.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[12], 9.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[13], 12.0, 0.01 );
  BOOST_CHECK_CLOSE(At.values()[14], 15.0, 0.01 );
}

BOOST_AUTO_TEST_CASE(zero_matrix)
{
  util::COOMatrix<float> A = util::make_zero<float>(5u);

  std::cout << util::to_string(A) << std::endl;

  BOOST_CHECK_EQUAL(A.is_zero(), true);
}

BOOST_AUTO_TEST_CASE(identity_matrix)
{
  util::COOMatrix<float> A = util::make_identity<float>(5u);

  std::cout << util::to_string(A) << std::endl;

  BOOST_CHECK_EQUAL(A.row_indices()[0],  0u );
  BOOST_CHECK_EQUAL(A.row_indices()[1],  1u );
  BOOST_CHECK_EQUAL(A.row_indices()[2],  2u );
  BOOST_CHECK_EQUAL(A.row_indices()[3],  3u );
  BOOST_CHECK_EQUAL(A.row_indices()[4],  4u );

  BOOST_CHECK_EQUAL(A.column_indices()[0],  0u );
  BOOST_CHECK_EQUAL(A.column_indices()[1],  1u );
  BOOST_CHECK_EQUAL(A.column_indices()[2],  2u );
  BOOST_CHECK_EQUAL(A.column_indices()[3],  3u );
  BOOST_CHECK_EQUAL(A.column_indices()[4],  4u );

  BOOST_CHECK_CLOSE(A.values()[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(A.values()[1],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(A.values()[2],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(A.values()[3],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(A.values()[4],  1.0, 0.01 );
}

BOOST_AUTO_TEST_CASE(make_from_blocks)
{
  util::COOMatrix<float> A = util::make_identity<float>(2u);
  util::COOMatrix<float> C = util::make_identity<float>(3u);

  util::COOMatrix<float> B;

  B.init(2u, 3u, 2u);

  B.insert(0u, 0u, 2.0f);
  B.insert(0u, 1u, 3.0f);
  B.insert(1u, 1u, 4.0f);
  B.insert(1u, 2u, 5.0f);

  util::COOMatrix<float> K = util::make_from_blocks(A, B, C);

  std::cout << util::to_string(K) << std::endl;

  //   1  0   2  3  0
  //   0  1   0  4  5
  //   2  0   1  0  0
  //   3  4   0  1  0
  //   0  5   0  0  1

  BOOST_CHECK_EQUAL(K.row_indices()[0],  0u );
  BOOST_CHECK_EQUAL(K.row_indices()[1],  0u );
  BOOST_CHECK_EQUAL(K.row_indices()[2],  0u );
  BOOST_CHECK_EQUAL(K.row_indices()[3],  1u );
  BOOST_CHECK_EQUAL(K.row_indices()[4],  1u );
  BOOST_CHECK_EQUAL(K.row_indices()[5],  1u );
  BOOST_CHECK_EQUAL(K.row_indices()[6],  2u );
  BOOST_CHECK_EQUAL(K.row_indices()[7],  2u );
  BOOST_CHECK_EQUAL(K.row_indices()[8],  3u );
  BOOST_CHECK_EQUAL(K.row_indices()[9],  3u );
  BOOST_CHECK_EQUAL(K.row_indices()[10],  3u );
  BOOST_CHECK_EQUAL(K.row_indices()[11],  4u );
  BOOST_CHECK_EQUAL(K.row_indices()[12],  4u );

  BOOST_CHECK_EQUAL(K.column_indices()[0],  0u );
  BOOST_CHECK_EQUAL(K.column_indices()[1],  2u );
  BOOST_CHECK_EQUAL(K.column_indices()[2],  3u );
  BOOST_CHECK_EQUAL(K.column_indices()[3],  1u );
  BOOST_CHECK_EQUAL(K.column_indices()[4],  3u );
  BOOST_CHECK_EQUAL(K.column_indices()[5],  4u );
  BOOST_CHECK_EQUAL(K.column_indices()[6],  0u );
  BOOST_CHECK_EQUAL(K.column_indices()[7],  2u );
  BOOST_CHECK_EQUAL(K.column_indices()[8],  0u );
  BOOST_CHECK_EQUAL(K.column_indices()[9],  1u );
  BOOST_CHECK_EQUAL(K.column_indices()[10],  3u );
  BOOST_CHECK_EQUAL(K.column_indices()[11],  1u );
  BOOST_CHECK_EQUAL(K.column_indices()[12],  4u );

  BOOST_CHECK_CLOSE(K.values()[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(K.values()[1],  2.0, 0.01 );
  BOOST_CHECK_CLOSE(K.values()[2],  3.0, 0.01 );
  BOOST_CHECK_CLOSE(K.values()[3],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(K.values()[4],  4.0, 0.01 );
  BOOST_CHECK_CLOSE(K.values()[5],  5.0, 0.01 );
  BOOST_CHECK_CLOSE(K.values()[6],  2.0, 0.01 );
  BOOST_CHECK_CLOSE(K.values()[7],  1.0, 0.01);
  BOOST_CHECK_CLOSE(K.values()[8],  3.0, 0.01);
  BOOST_CHECK_CLOSE(K.values()[9],  4.0, 0.01);
  BOOST_CHECK_CLOSE(K.values()[10],  1.0, 0.01);
  BOOST_CHECK_CLOSE(K.values()[11],  5.0, 0.01);
  BOOST_CHECK_CLOSE(K.values()[12],  1.0, 0.01);

  std::vector<double> a;
  std::vector<double> b;

  a.resize(2,1.0);
  b.resize(2,2.0);
  std::vector<double> c = util::make_from_blocks(a, b);

  BOOST_CHECK_EQUAL(c.size(), 4u );

  BOOST_CHECK_CLOSE(c[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(c[1],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(c[2],  2.0, 0.01 );
  BOOST_CHECK_CLOSE(c[3],  2.0, 0.01 );
}

BOOST_AUTO_TEST_CASE(split_into_blocks)
{
  std::vector<double> c;
  c.resize(6);

  c[0] = 1.0;
  c[1] = 2.0;
  c[2] = 3.0;
  c[3] = 4.0;
  c[4] = 5.0;
  c[5] = 6.0;

  std::vector<double> a;
  std::vector<double> b;

  util::split_into_blocks(c, a, b, false);

  BOOST_CHECK_EQUAL(a.size(), 3u );
  BOOST_CHECK_CLOSE(a[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(a[1],  2.0, 0.01 );
  BOOST_CHECK_CLOSE(a[2],  3.0, 0.01 );

  BOOST_CHECK_EQUAL(b.size(), 3u );
  BOOST_CHECK_CLOSE(b[0],  4.0, 0.01 );
  BOOST_CHECK_CLOSE(b[1],  5.0, 0.01 );
  BOOST_CHECK_CLOSE(b[2],  6.0, 0.01 );

  util::split_into_blocks(c, a, b, true);

  BOOST_CHECK_EQUAL(a.size(), 3u );
  BOOST_CHECK_CLOSE(a[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(a[1],  3.0, 0.01 );
  BOOST_CHECK_CLOSE(a[2],  5.0, 0.01 );

  BOOST_CHECK_EQUAL(b.size(), 3u );
  BOOST_CHECK_CLOSE(b[0],  2.0, 0.01 );
  BOOST_CHECK_CLOSE(b[1],  4.0, 0.01 );
  BOOST_CHECK_CLOSE(b[2],  6.0, 0.01 );

  util::split_into_blocks(c, 2, a, b);

  BOOST_CHECK_EQUAL(a.size(), 2u );
  BOOST_CHECK_CLOSE(a[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(a[1],  2.0, 0.01 );

  BOOST_CHECK_EQUAL(b.size(), 4u );
  BOOST_CHECK_CLOSE(b[0],  3.0, 0.01 );
  BOOST_CHECK_CLOSE(b[1],  4.0, 0.01 );
  BOOST_CHECK_CLOSE(b[2],  5.0, 0.01 );
  BOOST_CHECK_CLOSE(b[3],  6.0, 0.01 );
}

BOOST_AUTO_TEST_CASE(add_sub_add_to)
{
  std::vector<double> a;
  a.resize(6);

  a[0] = 1.0;
  a[1] = 2.0;
  a[2] = 3.0;
  a[3] = 4.0;
  a[4] = 5.0;
  a[5] = 6.0;

  std::vector<double> b;
  b.resize(6);

  b[5] = 1.0;
  b[4] = 2.0;
  b[3] = 3.0;
  b[2] = 4.0;
  b[1] = 5.0;
  b[0] = 6.0;

  std::vector<double> c = util::add(a, b);
  std::vector<double> d = util::sub(a, b);

  BOOST_CHECK_EQUAL(c.size(), 6u );
  BOOST_CHECK_CLOSE(c[0],  7.0, 0.01 );
  BOOST_CHECK_CLOSE(c[1],  7.0, 0.01 );
  BOOST_CHECK_CLOSE(c[2],  7.0, 0.01 );
  BOOST_CHECK_CLOSE(c[3],  7.0, 0.01 );
  BOOST_CHECK_CLOSE(c[4],  7.0, 0.01 );
  BOOST_CHECK_CLOSE(c[5],  7.0, 0.01 );

  BOOST_CHECK_EQUAL(d.size(), 6u );
  BOOST_CHECK_CLOSE(d[0],  -5.0, 0.01 );
  BOOST_CHECK_CLOSE(d[1],  -3.0, 0.01 );
  BOOST_CHECK_CLOSE(d[2],  -1.0, 0.01 );
  BOOST_CHECK_CLOSE(d[3],   1.0, 0.01 );
  BOOST_CHECK_CLOSE(d[4],   3.0, 0.01 );
  BOOST_CHECK_CLOSE(d[5],   5.0, 0.01 );

  util::add_to(d, b);

  BOOST_CHECK_EQUAL(d.size(), 6u );
  BOOST_CHECK_CLOSE(d[0],  1.0, 0.01 );
  BOOST_CHECK_CLOSE(d[1],  2.0, 0.01 );
  BOOST_CHECK_CLOSE(d[2],  3.0, 0.01 );
  BOOST_CHECK_CLOSE(d[3],  4.0, 0.01 );
  BOOST_CHECK_CLOSE(d[4],  5.0, 0.01 );
  BOOST_CHECK_CLOSE(d[5],  6.0, 0.01 );

  std::vector<double> e = util::neg(a);
  BOOST_CHECK_EQUAL(e.size(), 6u );
  BOOST_CHECK_CLOSE(e[0],  -1.0, 0.01 );
  BOOST_CHECK_CLOSE(e[1],  -2.0, 0.01 );
  BOOST_CHECK_CLOSE(e[2],  -3.0, 0.01 );
  BOOST_CHECK_CLOSE(e[3],  -4.0, 0.01 );
  BOOST_CHECK_CLOSE(e[4],  -5.0, 0.01 );
  BOOST_CHECK_CLOSE(e[5],  -6.0, 0.01 );

}

BOOST_AUTO_TEST_CASE(dot_test)
{
  std::vector<double> a;
  a.resize(6);

  std::vector<double> b;
  b.resize(6);

  a[0] = 1.0;
  a[1] = 2.0;
  a[2] = 3.0;
  a[3] = 4.0;
  a[4] = 5.0;
  a[5] = 6.0;

  b[0] = 6.0;
  b[1] = 5.0;
  b[2] = 4.0;
  b[3] = 3.0;
  b[4] = 2.0;
  b[5] = 1.0;

  double test = util::dot(a,b);

  BOOST_CHECK_CLOSE(test,  56.0, 0.01 );
}

BOOST_AUTO_TEST_CASE(mul_mul_add)
{
  util::COOMatrix<double> A;

  A.init(5u, 5u, 3u);

//   1  2  3  0  0
//   0  4  5  6  0
//   0  0  7  8  9
//  10 11 12  0  0
//   0 13 14 15  0

  A.insert(0u, 0u, 1.0f);
  A.insert(0u, 1u, 2.0f);
  A.insert(0u, 2u, 3.0f);

  A.insert(1u, 1u, 4.0f);
  A.insert(1u, 2u, 5.0f);
  A.insert(1u, 3u, 6.0f);

  A.insert(2u, 2u, 7.0f);
  A.insert(2u, 3u, 8.0f);
  A.insert(2u, 4u, 9.0f);

  A.insert(3u, 0u, 10.0f);
  A.insert(3u, 1u, 11.0f);
  A.insert(3u, 2u, 12.0f);

  A.insert(4u, 1u, 13.0f);
  A.insert(4u, 2u, 14.0f);
  A.insert(4u, 3u, 15.0f);

  util::COOMatrix<double> B = util::mul(A,2.0);

  BOOST_CHECK_EQUAL(B.row_indices()[0],  0u );
  BOOST_CHECK_EQUAL(B.row_indices()[1],  0u );
  BOOST_CHECK_EQUAL(B.row_indices()[2],  0u );
  BOOST_CHECK_EQUAL(B.row_indices()[3],  1u );
  BOOST_CHECK_EQUAL(B.row_indices()[4],  1u );
  BOOST_CHECK_EQUAL(B.row_indices()[5],  1u );
  BOOST_CHECK_EQUAL(B.row_indices()[6],  2u );
  BOOST_CHECK_EQUAL(B.row_indices()[7],  2u );
  BOOST_CHECK_EQUAL(B.row_indices()[8],  2u );
  BOOST_CHECK_EQUAL(B.row_indices()[9],  3u );
  BOOST_CHECK_EQUAL(B.row_indices()[10], 3u );
  BOOST_CHECK_EQUAL(B.row_indices()[11], 3u );
  BOOST_CHECK_EQUAL(B.row_indices()[12], 4u );
  BOOST_CHECK_EQUAL(B.row_indices()[13], 4u );
  BOOST_CHECK_EQUAL(B.row_indices()[14], 4u );

  BOOST_CHECK_EQUAL(B.column_indices()[0],  0u );
  BOOST_CHECK_EQUAL(B.column_indices()[1],  1u );
  BOOST_CHECK_EQUAL(B.column_indices()[2],  2u );
  BOOST_CHECK_EQUAL(B.column_indices()[3],  1u );
  BOOST_CHECK_EQUAL(B.column_indices()[4],  2u );
  BOOST_CHECK_EQUAL(B.column_indices()[5],  3u );
  BOOST_CHECK_EQUAL(B.column_indices()[6],  2u );
  BOOST_CHECK_EQUAL(B.column_indices()[7],  3u );
  BOOST_CHECK_EQUAL(B.column_indices()[8],  4u );
  BOOST_CHECK_EQUAL(B.column_indices()[9],  0u );
  BOOST_CHECK_EQUAL(B.column_indices()[10], 1u );
  BOOST_CHECK_EQUAL(B.column_indices()[11], 2u );
  BOOST_CHECK_EQUAL(B.column_indices()[12], 1u );
  BOOST_CHECK_EQUAL(B.column_indices()[13], 2u );
  BOOST_CHECK_EQUAL(B.column_indices()[14], 3u );

  BOOST_CHECK_CLOSE(B.values()[0],  2.0*1.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[1],  2.0*2.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[2],  2.0*3.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[3],  2.0*4.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[4],  2.0*5.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[5],  2.0*6.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[6],  2.0*7.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[7],  2.0*8.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[8],  2.0*9.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[9],  2.0*10.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[10], 2.0*11.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[11], 2.0*12.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[12], 2.0*13.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[13], 2.0*14.0, 0.01 );
  BOOST_CHECK_CLOSE(B.values()[14], 2.0*15.0, 0.01 );

  util::COOMatrix<double> C = util::add(A,B);

  BOOST_CHECK_EQUAL(C.row_indices()[0],  0u );
  BOOST_CHECK_EQUAL(C.row_indices()[1],  0u );
  BOOST_CHECK_EQUAL(C.row_indices()[2],  0u );
  BOOST_CHECK_EQUAL(C.row_indices()[3],  1u );
  BOOST_CHECK_EQUAL(C.row_indices()[4],  1u );
  BOOST_CHECK_EQUAL(C.row_indices()[5],  1u );
  BOOST_CHECK_EQUAL(C.row_indices()[6],  2u );
  BOOST_CHECK_EQUAL(C.row_indices()[7],  2u );
  BOOST_CHECK_EQUAL(C.row_indices()[8],  2u );
  BOOST_CHECK_EQUAL(C.row_indices()[9],  3u );
  BOOST_CHECK_EQUAL(C.row_indices()[10], 3u );
  BOOST_CHECK_EQUAL(C.row_indices()[11], 3u );
  BOOST_CHECK_EQUAL(C.row_indices()[12], 4u );
  BOOST_CHECK_EQUAL(C.row_indices()[13], 4u );
  BOOST_CHECK_EQUAL(C.row_indices()[14], 4u );

  BOOST_CHECK_EQUAL(C.column_indices()[0],  0u );
  BOOST_CHECK_EQUAL(C.column_indices()[1],  1u );
  BOOST_CHECK_EQUAL(C.column_indices()[2],  2u );
  BOOST_CHECK_EQUAL(C.column_indices()[3],  1u );
  BOOST_CHECK_EQUAL(C.column_indices()[4],  2u );
  BOOST_CHECK_EQUAL(C.column_indices()[5],  3u );
  BOOST_CHECK_EQUAL(C.column_indices()[6],  2u );
  BOOST_CHECK_EQUAL(C.column_indices()[7],  3u );
  BOOST_CHECK_EQUAL(C.column_indices()[8],  4u );
  BOOST_CHECK_EQUAL(C.column_indices()[9],  0u );
  BOOST_CHECK_EQUAL(C.column_indices()[10], 1u );
  BOOST_CHECK_EQUAL(C.column_indices()[11], 2u );
  BOOST_CHECK_EQUAL(C.column_indices()[12], 1u );
  BOOST_CHECK_EQUAL(C.column_indices()[13], 2u );
  BOOST_CHECK_EQUAL(C.column_indices()[14], 3u );

  BOOST_CHECK_CLOSE(C.values()[0],  3.0*1.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[1],  3.0*2.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[2],  3.0*3.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[3],  3.0*4.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[4],  3.0*5.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[5],  3.0*6.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[6],  3.0*7.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[7],  3.0*8.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[8],  3.0*9.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[9],  3.0*10.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[10], 3.0*11.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[11], 3.0*12.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[12], 3.0*13.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[13], 3.0*14.0, 0.01 );
  BOOST_CHECK_CLOSE(C.values()[14], 3.0*15.0, 0.01 );

  std::vector<double> x;
  x.resize(5u,0.0);

  x[1] = 1.0;

  std::vector<double> y = util::mul(A,x);

  BOOST_CHECK_CLOSE(y[0],   2.0, 0.01 );
  BOOST_CHECK_CLOSE(y[1],   4.0, 0.01 );
  BOOST_CHECK_CLOSE(y[2],   0.0, 0.01 );
  BOOST_CHECK_CLOSE(y[3],  11.0, 0.01 );
  BOOST_CHECK_CLOSE(y[4],  13.0, 0.01 );
}

BOOST_AUTO_TEST_SUITE_END();

max_forks_repo_name: misztal/GRIT


text:
/*
 * Copyright (c) 2014 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <iostream>

#include <boost/test/unit_test.hpp>

#include <pkmn/types/pokemon_text.hpp>

BOOST_AUTO_TEST_CASE(multibyte_to_wide)
{
    std::string test_str("Test string");
    pkmn::pokemon_text test_pkmntext(test_str);
    std::wstring test_wstr(L"Test string");
    std::wstring wide_output(test_pkmntext.std_wstring());

    BOOST_CHECK(test_wstr == wide_output);
}

BOOST_AUTO_TEST_CASE(wide_to_multibyte)
{
    std::wstring test_wstr(L"Test string");
    pkmn::pokemon_text test_pkmntext(test_wstr);
    std::string test_str("Test string");
    std::string multibyte_output(test_pkmntext.std_string());

    BOOST_CHECK(test_str == multibyte_output);
}

BOOST_AUTO_TEST_CASE(multibyte_to_multibyte)
{
    std::string test_str("Test string");
    pkmn::pokemon_text test_pkmntext(test_str);
    BOOST_CHECK(test_str == test_pkmntext.std_string());
}

BOOST_AUTO_TEST_CASE(wide_to_wide)
{
    std::wstring test_wstr(L"Test string");
    pkmn::pokemon_text test_pkmntext(test_wstr);
    BOOST_CHECK(test_wstr == test_pkmntext.std_wstring());
}

BOOST_AUTO_TEST_CASE(comparison_operator)
{
    pkmn::pokemon_text test_pkmntext1("Test string");
    pkmn::pokemon_text test_pkmntext2("Test string");
    BOOST_CHECK(test_pkmntext1 == test_pkmntext2);
}

ext: cpp


text:
/* adcpp_eigen.hpp
 *
 *  Created on: 21 Aug 2019
 *      Author: Fabian Meyer
 *     License: MIT
 */

#ifndef ADCPP_ADCPP_EIGEN_HPP_
#define ADCPP_ADCPP_EIGEN_HPP_

#include <adcpp/adcpp.hpp>
#include <Eigen/Core>

#define ADCPP_GEN_NUMTRAITS(T) \
    template<>\
    struct NumTraits<T>\
    {\
        using ValueType = T::Scalar;\
        using Real = T;\
        using NonInteger = T;\
        using Nested = T;\
        using Literal = T;\
        enum {\
            IsInteger = std::is_integral<ValueType>::value ? 1 : 0,\
            IsSigned = std::is_signed<ValueType>::value ? 1 : 0,\
            IsComplex = 0,\
            RequireInitialization = 1,\
            ReadCost = 1,\
            AddCost = 3,\
            MulCost = 3\
        };\
        static Real epsilon()\
        {\
            return Real(std::numeric_limits<ValueType>::epsilon());\
        }\
        static Real highest()\
        {\
            return Real(std::numeric_limits<ValueType>::max());\
        }\
        static Real lowest()\
        {\
            return Real(std::numeric_limits<ValueType>::min());\
        }\
        static Real min_exponent()\
        {\
            return Real(std::numeric_limits<ValueType>::min_exponent);\
        }\
        static Real max_exponent()\
        {\
            return Real(std::numeric_limits<ValueType>::max_exponent);\
        }\
        static Real digits()\
        {\
            return Real(std::numeric_limits<ValueType>::digits);\
        }\
        static Real digits10()\
        {\
            return Real(std::numeric_limits<ValueType>::digits10);\
        }\
    }

namespace Eigen
{
    ADCPP_GEN_NUMTRAITS(adcpp::fwd::Double);
    ADCPP_GEN_NUMTRAITS(adcpp::fwd::Float);

    ADCPP_GEN_NUMTRAITS(adcpp::bwd::Double);
    ADCPP_GEN_NUMTRAITS(adcpp::bwd::Float);
}

namespace adcpp
{
namespace fwd
{
    typedef Eigen::Matrix<Double, Eigen::Dynamic, Eigen::Dynamic> MatrixXd;
    typedef Eigen::Matrix<Double, 2, 2> Matrix2d;
    typedef Eigen::Matrix<Double, 3, 3> Matrix3d;
    typedef Eigen::Matrix<Double, 4, 4> Matrix4d;
    typedef Eigen::Matrix<Double, 5, 5> Matrix5d;

    typedef Eigen::Matrix<Double, Eigen::Dynamic, 1> VectorXd;
    typedef Eigen::Matrix<Double, 2, 1> Vector2d;
    typedef Eigen::Matrix<Double, 3, 1> Vector3d;
    typedef Eigen::Matrix<Double, 4, 1> Vector4d;
    typedef Eigen::Matrix<Double, 5, 1> Vector5d;

    typedef Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic> MatrixXf;
    typedef Eigen::Matrix<Float, 2, 2> Matrix2f;
    typedef Eigen::Matrix<Float, 3, 3> Matrix3f;
    typedef Eigen::Matrix<Float, 4, 4> Matrix4f;
    typedef Eigen::Matrix<Float, 5, 5> Matrix5f;

    typedef Eigen::Matrix<Float, Eigen::Dynamic, 1> VectorXf;
    typedef Eigen::Matrix<Float, 2, 1> Vector2f;
    typedef Eigen::Matrix<Float, 3, 1> Vector3f;
    typedef Eigen::Matrix<Float, 4, 1> Vector4f;
    typedef Eigen::Matrix<Float, 5, 1> Vector5f;
}

namespace bwd
{
    typedef Eigen::Matrix<Double, Eigen::Dynamic, Eigen::Dynamic> MatrixXd;
    typedef Eigen::Matrix<Double, 2, 2> Matrix2d;
    typedef Eigen::Matrix<Double, 3, 3> Matrix3d;
    typedef Eigen::Matrix<Double, 4, 4> Matrix4d;
    typedef Eigen::Matrix<Double, 5, 5> Matrix5d;

    typedef Eigen::Matrix<Double, Eigen::Dynamic, 1> VectorXd;
    typedef Eigen::Matrix<Double, 2, 1> Vector2d;
    typedef Eigen::Matrix<Double, 3, 1> Vector3d;
    typedef Eigen::Matrix<Double, 4, 1> Vector4d;
    typedef Eigen::Matrix<Double, 5, 1> Vector5d;

    typedef Eigen::Matrix<Float, Eigen::Dynamic, Eigen::Dynamic> MatrixXf;
    typedef Eigen::Matrix<Float, 2, 2> Matrix2f;
    typedef Eigen::Matrix<Float, 3, 3> Matrix3f;
    typedef Eigen::Matrix<Float, 4, 4> Matrix4f;
    typedef Eigen::Matrix<Float, 5, 5> Matrix5f;

    typedef Eigen::Matrix<Float, Eigen::Dynamic, 1> VectorXf;
    typedef Eigen::Matrix<Float, 2, 1> Vector2f;
    typedef Eigen::Matrix<Float, 3, 1> Vector3f;
    typedef Eigen::Matrix<Float, 4, 1> Vector4f;
    typedef Eigen::Matrix<Float, 5, 1> Vector5f;

    template<typename Scalar, typename DerivedA, typename DerivedB>
    inline void gradient(const Eigen::MatrixBase<DerivedA> &x,
        const Number<Scalar> &f,
        Eigen::MatrixBase<DerivedB> &grad)
    {
        assert(grad.size() == x.size());

        typename bwd::Number<Scalar>::DerivativeMap derivative;
        f.derivative(derivative);

        grad.setZero();
        for(long int i = 0; i < x.size(); ++i)
        {
            if(derivative.contains(x(i)))
                grad(i) = derivative(x(i));
        }
    }

    template<typename DerivedA, typename DerivedB, typename DerivedC>
    inline void jacobian(const Eigen::MatrixBase<DerivedA> &x,
        const Eigen::MatrixBase<DerivedB> &f,
        Eigen::MatrixBase<DerivedC> &jac)
    {
        assert(jac.rows() == f.size());
        assert(jac.cols() == x.size());

        typename Eigen::MatrixBase<DerivedB>::Scalar::DerivativeMap derivative;
        jac.setZero();
        for(long int i = 0; i < f.size(); ++i)
        {
            f(i).derivative(derivative);
            for(long int j = 0; j < x.size(); ++j)
            {
                if(derivative.contains(x(j)))
                    jac(i, j) = derivative(x(j));
            }
        }
    }
}
}

#endif

ext: hpp

max_stars_repo_name: Rookfighter/algorithmic-differentiation


text:
#include <Eigen/Dense>
#include <iostream>

int main(int, char *[]) {
  // AngleAxisf aa = Quaternionf(..);
  Eigen::VectorXd vq(4);
  vq[0] = 1.0;
  vq[1] = 0.0;
  vq(2) = 0.0;
  vq(3) = 0.0;
  Eigen::Matrix<float, 4, 1> coe;
  Eigen::Matrix<float, 3, 3> R;
  Eigen::Quaternionf q(2.0, 0.1, 0.3, 4.0);  // wxyz
  coe = q.coeffs();
  std::cout << coe << std::endl;  // xyzw

  Eigen::Vector3f vec = q.vec();  // xyz
  std::cout << vec << std::endl;

  Eigen::AngleAxisf aa;
  Eigen::Matrix3f mat;
  Eigen::Quaternionf qm(mat);
  Eigen::Quaternionf qa(aa);

  Eigen::Quaternionf qw;
  qw.setIdentity();  // important
  R = qw.toRotationMatrix();
  qw = qw * q;
  qw = qw.normalized();  //规范化
  std::cout << R << std::endl;
  qw = qw.Identity();  // 1 0 0 0 or qw.setIdentity();
  std::cout << qw.w() << "  " << qw.x() << "  " << qw.y() << "  " << qw.z()
            << std::endl;
  qw = qw.inverse();
  std::cout << qw.w() << "  " << qw.x() << "  " << qw.y() << "  " << qw.z()
            << std::endl;

  Eigen::Vector3f w1;
  w1 << 1, 2, 3;
  Eigen::Vector3f w2;
  w2 << 2, 3, 4;
  qw = qw.Identity();
  qw = qw.setFromTwoVectors(w1, w2);  //出来的norm=1--姿态四元数
  std::cout << qw.squaredNorm() << std::endl;  // norm^2  .norm()
  q.setIdentity();
  qw = qw.normalized();
  q = q.normalized();
  q = q.inverse();
  std::cout << q.angularDistance(qw) << std::endl;  //必须先规范化
  std::cout << qw.dot(q) << std::endl;              // dot product 内积
  std::cout << qw.w() << "  " << qw.x() << "  " << qw.y() << "  " << qw.z()
            << std::endl;
  std::cout << q.w() << "  " << q.x() << "  " << q.y() << "  " << q.z()
            << std::endl;

  // std::cout<<q;
  std::cout << std::endl;
  for (int size = 1; size <= 4; ++size) {
    Eigen::MatrixXi m(size, size + 1);    // a (size)x(size+1)-matrix of int's
    for (int j = 0; j < m.cols(); ++j)    // loop over columns
      for (int i = 0; i < m.rows(); ++i)  // loop over rows
        m(i, j) = i + j * m.rows();       // to access matrix coefficients,
    // use operator()(int,int)
    std::cout << m << "\n\n";
  }
  Eigen::VectorXf v(4);  // a vector of 4 float's
  // to access vector coefficients, use either operator () or operator []
  v[0] = 1;
  v[1] = 2;
  v(2) = 3;
  v(3) = 4;
  std::cout << "\nv:\n" << v << std::endl;
}


text:
/*
 * MIT License
 *
 * Copyright (c) 2020 ETJump team <zero@etjump.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "etj_result_set_formatter.h"
#include <algorithm>
#include <numeric>
#include <boost/algorithm/string/case_conv.hpp>

Utilities::ResultSetFormatter::ResultSetFormatter()
{
}

Utilities::ResultSetFormatter::~ResultSetFormatter()
{
}

std::string Utilities::ResultSetFormatter::toString(std::vector<std::string> headers, std::vector<std::map<std::string, std::string>> rows, int pageSize, int page)
{
	if (rows.size() == 0)
	{
		return "";
	}
	std::map<std::string, unsigned> maxColumnWidths;
	for (const auto & header : headers)
	{
		maxColumnWidths[header] = header.length();
	}

	const unsigned maxChars = 80;
	for (int rowIdx = 0, rowLength = rows.size(); rowIdx < rowLength; ++rowIdx)
	{
		auto row = rows[rowIdx];

		for (const auto & header : headers)
		{
			auto iter = row.find(header);
			if (iter != end(row))
			{
                maxColumnWidths[header] = std::max(
                            std::max(maxColumnWidths[header],
                                static_cast<unsigned int>(header.length())),
                                    static_cast<unsigned int>(iter->second.length()));
				if (maxColumnWidths[header] > maxChars)
				{
					maxColumnWidths[header] = maxChars;
				}
			} else
			{
                maxColumnWidths[header] = std::max(
                            maxColumnWidths[header],
                                static_cast<unsigned int>(std::to_string(rows.size()).size()));
			}
		}
	}

	std::string buffer;
	for (const auto & header : headers)
	{
		buffer += header + std::string(maxColumnWidths[header] - header.length(), ' ') + "  ";
	}
	buffer += "\n";

	for (const auto & header : headers)
	{
		buffer += std::string(header.length(), '-') + std::string(maxColumnWidths[header] - header.length() + 2, ' ');
	}
	buffer += "\n";

	int current = 0;
	int startingIndex = pageSize * page;
	int endingIndex = pageSize * (page + 1);
	for (const auto & row : rows)
	{
		if (current < startingIndex)
		{
			++current;
			continue;
		}
		if (current >= endingIndex)
		{
			break;
		}
		auto charsBefore = 0;
		for (const auto & header : headers)
		{
			const auto iter = row.find(header);
			if (iter == end(row))
			{
				auto lwrCase = boost::to_lower_copy(header);
				if (lwrCase == "index" || lwrCase == "idx" || lwrCase == "i")
				{
                    maxColumnWidths[header] = std::max(
                                maxColumnWidths[header], static_cast<unsigned int>(header.length()));
					auto extraChars = maxColumnWidths[header];
					auto index = std::to_string(current + 1);
					buffer += index + std::string(maxColumnWidths[header] - index.length() + 2, ' ');
				} else
				{
					buffer += std::string(maxColumnWidths[header] + 2, ' ');
				}
			} else
			{
				auto toBePrinted = iter->second;
				if (iter->second.length() > maxChars)
				{
					toBePrinted = iter->second.substr(0, maxChars);
					toBePrinted[maxChars - 3] = '.';
					toBePrinted[maxChars - 2] = '.';
					toBePrinted[maxChars - 1] = '.';
				}

				buffer += toBePrinted + std::string(maxColumnWidths[iter->first] - toBePrinted.length() + 2, ' ');
			}
		}
		buffer += "\n";
		++current;
	}

	return buffer;
}

unsigned Utilities::ResultSetFormatter::totalWidth(std::map<std::string, unsigned> columnWidths)
{
	auto sum = 0;
	for (const auto & column : columnWidths)
	{
		sum += column.second;
	}
	return sum + (columnWidths.size() - 1) * 2;
}

max_stars_repo_name: jackeri/etjump

max_issues_repo_name: jackeri/etjump

max_forks_repo_name: jackeri/etjump


text:
#ifndef UTILS_HPP
#define UTILS_HPP

#include "graph.hpp"
#include "units.hpp"

#include <boost/graph/connected_components.hpp>

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>

#include <cassert>
#include <iostream>
#include <list>
#include <map>
#include <random>
#include <set>
#include <string>
#include <vector>

namespace ba = boost::accumulators;

// The accumulator with double values.
typedef ba::accumulator_set<double, ba::stats<ba::tag::min,
                                              ba::tag::mean,
                                              ba::tag::max,
                                              ba::tag::variance> >
dbl_acc;

/**
 * Generate a random number from min to max, including both min and
 * max.
 */
template<typename E>
int
get_random_int(int min, int max, E &eng)
{
  std::uniform_int_distribution<> d(min, max);
  return d(eng);
}

// Calculate the cost of the path.
template<typename Graph, typename Container>
typename boost::property_map<Graph, boost::edge_weight_t>::value_type
get_path_length(const Graph &g, const Container &con)
{
  using ew = boost::edge_weight_t;
  using w = typename boost::property_map<Graph, ew>::value_type;

  auto c = std::accumulate(con.begin(), con.end(), w{},
                           [g](const auto &c, const auto &e)
                           {
                             auto o = boost::get(boost::edge_weight,
                                                 g, e);
                             return c + o;
                           });
  return c;
}

// Calculate the cost of a path.
template<typename Graph>
auto
get_cost(const Graph &g, const CU_Path<Graph> &p)
{
  return p.first.count() * get_path_length(g, p.second);
}

/**
 * Interpret a string, and return the matched enum.
 */
template <typename T>
T
interpret(const std::string &name, const std::string &text,
          const std::map <std::string, T> &m)
{
  auto i = m.find (text);

  if (i == m.end ())
    {
      std::cerr << "Wrong value of " << name << ".  Choose one of:";
      for (auto &p: m)
        std::cerr << " " << p.first;
      std::cerr << std::endl;
      exit (1);
    }

  return i->second;
}

/**
 * Find the SU that is available along the path.
 */
SU
find_path_su(const graph &g, const path &p);

/**
 * This is the << operator for a pair.
 */
template <typename A, typename B>
std::ostream &operator << (std::ostream &os, const std::pair<A, B> &p)
{
  os << "pair(" << p.first << ", " << p.second << ")";
  return os;
}

/**
 * This is the << operator for a cupath.
 */
std::ostream &operator << (std::ostream &os, const cupath &p);

/**
 * This is the << operator for a vector.
 */
template <typename T>
std::ostream &operator << (std::ostream &os, const std::vector<T> &v)
{
  typename std::vector<T>::const_iterator i = v.begin();

  os << "[";

  while(i != v.end())
    {
      os << *i;
      if (++i != v.end())
        os << ", ";
    }

  os << "]";

  return os;
}

/**
 * This is the << operator for a set.
 */
template <typename T>
std::ostream &operator << (std::ostream &os, const std::set<T> &v)
{
  typename std::set<T>::const_iterator i = v.begin();

  os << "{";

  while(i != v.end())
    {
      os << *i;
      if (++i != v.end())
        os << ", ";
    }

  os << "}";

  return os;
}

/**
 * This is the << operator for a list.
 */
template <typename T>
std::ostream &operator << (std::ostream &os, const std::list<T> &v)
{
  typename std::list<T>::const_iterator i = v.begin();

  os << "(";

  while(i != v.end())
    {
      os << *i;
      if (++i != v.end())
        os << ", ";
    }

  os << ")";

  return os;
}

/**
 * This is the << operator for a map.
 */
template <typename K, typename V>
std::ostream &operator << (std::ostream &os, const std::map<K, V> &m)
{
  for(auto const &e: m)
    os << e.first << " -> " << e.second << std::endl;

  return os;
}

/**
 * True if the graph is connected.
 *
 * @return: true if the graph is connected, false otherwise.
 */
template<typename G>
bool
is_connected(const G &g)
{
  int c[boost::num_vertices(g)];

  // "num" is the number of connected components.
  int num = boost::connected_components(g, c);

  return num == 1;
}

/**
 * Get a random element from a container.
 */
template <typename C, typename E>
auto
get_random_element(const C &c, E &eng)
{
  assert(!c.empty());

  typename C::const_iterator i = c.begin();
  std::advance(i, get_random_int(0, c.size() - 1, eng));

  return *i;
}

/**
 * Generate a random node pair.
 */
template<typename G, typename E>
std::pair<typename G::vertex_descriptor,
	  typename G::vertex_descriptor>
random_node_pair(const G &g, E &eng)
{
  typedef typename G::vertex_descriptor vertex;
  typedef typename G::vertex_iterator vertex_i;

  vertex_i begin = vertices(g).first;
  int n = num_vertices(g);

  int src_n = get_random_int(0, n - 1, eng);
  vertex_i src_i = begin;
  std::advance(src_i, src_n);
  vertex src = *src_i;

  // Choose any number between 0 and n - 1, but not src_n.
  int dst_n = get_random_int(0, n - 2, eng);
  if (dst_n == src_n)
    dst_n = n - 1;
  vertex_i dst_i = begin;
  std::advance(dst_i, dst_n);
  vertex dst = *dst_i;

  return std::make_pair(src, dst);
}

template<typename G>
double
calculate_utilization(const G &g)
{
  ba::accumulator_set<double, ba::stats<ba::tag::mean> > load_acc;

  typename G::edge_iterator ei, ee;
  for (tie(ei, ee) = edges(g); ei != ee; ++ei)
    {
      // Total available units.
      int tsc = boost::get(boost::edge_nou, g, *ei);
      // Currenlty available units.
      int asc = boost::get(boost::edge_su, g, *ei).count();
      // The link load.
      double load = double(tsc - asc) / tsc;
      load_acc(load);
    }

  return ba::mean(load_acc);
}

bool
vertex_in_path(const graph &g, const path &p, vertex v);

/**
 * Sets the units property on edges.
 */
template<typename G>
void
set_units(G &g, unsigned units)
{
  SU su = {{0, units}};

  // Total units property map.
  typename boost::property_map<G, boost::edge_nou_t>::type
    tpm = get(boost::edge_nou_t(), g);
  // Available units property map.
  typename boost::property_map<G, boost::edge_su_t>::type
    apm = get(boost::edge_su_t(), g);

  typename G::edge_iterator ei, ee;
  for (tie(ei, ee) = edges(g); ei != ee; ++ei)
    {
      tpm[*ei] = units;
      apm[*ei] = su;
    }
}

// For the shortest paths between all node pairs, calculate the
// statistics for hops and lengths.
void
calc_sp_stats(const graph &g, dbl_acc &hop_acc, dbl_acc &len_acc);

// Calculate the mean connection arrival time for the given mean
// number of hops of a shortest path (mnh), the mean holding time
// (mht) of a connection, the mean number of units of a connection,
// and the offered load (ol).
double
calc_mcat(const graph &g, double mnh, double mht, double mnu,
          double ol);

bool
load_graphviz(const std::string &file_name, graph &g);

#endif /* UTILS_HPP */

max_stars_repo_name: iszczesniak/gd

max_issues_repo_name: iszczesniak/gd

max_forks_repo_name: iszczesniak/gd


text:
#include <boost/mpl/assert.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/sdk/simd/pack.hpp>
#include <boost/type_traits/is_same.hpp>

using boost::is_same;
using nt2::meta::as_integer;

using nt2::uint32_t;
using nt2::int32_t;
using nt2::simd::pack;

int main()
{
  BOOST_MPL_ASSERT(( is_same<int32_t,       as_integer<float>::type>            ));
  BOOST_MPL_ASSERT(( is_same<uint32_t,      as_integer<float, unsigned>::type>  ));
  BOOST_MPL_ASSERT(( is_same<int32_t,       as_integer<uint32_t, signed>::type> ));
  BOOST_MPL_ASSERT(( is_same<pack<int32_t>, as_integer< pack<float> >::type>    ));
}


text:
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include "cetlib_except/exception.h"
#include "DbService/inc/DbSql.hh"
#include "DbTables/inc/DbUtil.hh"

mu2e::DbSql::DbSql():_conn(nullptr),_verbose(0) {
}

//*********************************************************

int mu2e::DbSql::connect() {

  if(_id.name().empty()) {
      throw cet::exception("DBSQL_DBID NOT_SET")
	<< "DbSql found the DbId was not set\n";
  }

  std::string command;
  command.append(" host="+_id.host());
  command.append(" port="+_id.port());
  command.append(" dbname="+_id.name());
  //command.append(" user="+_user);
  //command.append(" password="+_pass);
		 //sslmode=require  krbsrvname

  _conn = PQconnectdb(command.c_str());
  if(_verbose>1) {
    std::cout << "DbSql opened connection, status: "
	      << PQerrorMessage(_conn) << std::endl;
  }

  if (_conn) {
    if (PQstatus(_conn) != CONNECTION_OK) {
      throw cet::exception("DBSQL_CONNECTION_FAILED")
	<< "DbSql connection failed " << PQerrorMessage(_conn) << "\n";
      return 1;
    }
  }
  return 0;
}

//*********************************************************

int mu2e::DbSql::disconnect() {
  if (_conn) {
    PQfinish(_conn);
    if(_verbose>1) {
      std::cout << "DbSql closed connection, status: "
		<< PQerrorMessage(_conn) << std::endl;
    }
  }

  return 0;
}

//*********************************************************

int mu2e::DbSql::execute(const std::string& command, std::string& result) {
  result.clear();
  PGresult* res = PQexec(_conn,command.c_str());
  if(_verbose>1) {
    std::cout << "\nDbSql execute command:\n" << command << "\n"
	      << "status message: " << PQerrorMessage(_conn) << "\n";
  }

  if (PQresultStatus(res) != PGRES_COMMAND_OK &&
      PQresultStatus(res) != PGRES_TUPLES_OK) {
    std::string msg(PQerrorMessage(_conn));
    PQclear(res);
    std::cout << " DbSql execute ERROR: " << msg << std::endl;
    disconnect();
    return 1;
  }

  size_t nrow = PQntuples(res);
  size_t ncol = PQnfields(res);
  if(_verbose>5) {
    std::cout << "DbSql execute returned: " << nrow << " rows and "
	      << ncol << " columns" << std::endl;
  }

  for(size_t r=0; r<nrow; r++) {
    for(size_t c=0; c<ncol; c++) {
      result.append(PQgetvalue(res,r,c));
      if(c<ncol-1) result.append(",");
    }
    result.append("\n");
  }

  if(_verbose>5) {
    std::cout << "DbSql execute result ("<< result.size()<<" char):\n" << result << std::endl;
  }
  return 0;
}

ext: cc

max_stars_repo_name: lborrel/Offline

max_issues_repo_name: lborrel/Offline

max_forks_repo_name: lborrel/Offline


text:
/*  $Id: bullcutter.cpp 667 2011-02-14 22:13:45Z anders.e.e.wallin $
 *
 *  Copyright 2010 Anders Wallin (anders.e.e.wallin "at" gmail.com)
 *
 *  This file is part of OpenCAMlib.
 *
 *  OpenCAMlib 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.
 *
 *  OpenCAMlib 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with OpenCAMlib.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <boost/foreach.hpp>

#include "bullcutter.h"
#include "numeric.h"
#include "ellipse.h"

namespace ocl
{

BullCutter::BullCutter() {
    std::cout << " usage: BullCutter( double diameter, double corner_radius, double length ) \n";
    assert(0);
}

BullCutter::BullCutter(double d, double r, double l) {
    diameter = d;               assert( d > 0.0 );
    radius = d/2.0;        // total cutter radius
    radius1 = d/2.0 - r;   // cylindrical middle part radius
    radius2 = r;                assert( radius1 > 0.0 ); // corner radius
    length = l;                 assert( l > 0.0 );
    xy_normal_length = radius1;
    normal_length = radius2;
    center_height = radius2;
}

MillingCutter* BullCutter::offsetCutter(double d) const {
    return new BullCutter(diameter+2*d, radius2+d, length+d) ;
}

// height of cutter at radius r
double BullCutter::height(double r) const {
    if ( r <= radius1 )
        return 0.0; // cylinder
    else if ( r <= radius )
        return radius2 - sqrt( square(radius2) - square(r-radius1) ); // toroid
    else {
        assert(0);
        return -1;
    }
}

// width of cutter at height h
double BullCutter::width(double h) const {
    return ( h >= radius2 ) ? radius : radius1 + sqrt(square(radius2)-square(radius2-h)) ;
}

// drop-cutter: vertex and facet are handled in base-class

// drop-cutter: Toroidal cutter edge-test
CC_CLZ_Pair BullCutter::singleEdgeDropCanonical( const Point& u1, const Point& u2 ) const {
    if ( isZero_tol( u1.z - u2.z ) ) {  // horizontal edge special case
        return CC_CLZ_Pair( 0 , u1.z - height(u1.y) );
    } else { // the general offset-ellipse case
        double b_axis = radius2;                            // short axis of ellipse = radius2
        double theta = atan( (u2.z - u1.z) / (u2.x-u1.x) ); // theta is the slope of the line
        double a_axis = fabs( radius2/sin(theta) );         // long axis of ellipse = radius2/sin(theta)
        Point ellcenter(0,u1.y,0);
        Ellipse e = Ellipse( ellcenter, a_axis, b_axis, radius1);
        int iters = e.solver_brent();
        assert( iters < 200 );
        e.setEllipsePositionHi(u1,u2); // this selects either EllipsePosition1 or EllipsePosition2 and sets it to EllipsePosition_hi
        // pseudo cc-point on the ellipse/cylinder, in the CL=origo system
        Point ell_ccp = e.ePointHi();         assert( fabs( ell_ccp.xyNorm() - radius1 ) < 1E-5); // ell_ccp should be on the cylinder-circle
        Point cc_tmp_u = ell_ccp.closestPoint(u1,u2); // find real cc-point
        return CC_CLZ_Pair( cc_tmp_u.x , e.getCenterZ()-radius2);
    }
}

// push-cutter: vertex and facet handled by base-class

bool BullCutter::generalEdgePush(const Fiber& f, Interval& i,  const Point& p1, const Point& p2) const {
    //std::cout << " BullCutter::generalEdgePush() \n";
    bool result = false;

    if ( isZero_tol( (p2-p1).xyNorm() ) ) { // this would be a vertical edge
        return result;
    }

    if ( isZero_tol( p2.z-p1.z ) ) // this would be a horizontal edge
        return result;
    assert( fabs(p2.z-p1.z) > 0.0 ); // no horiz edges allowed hereafter

    // p1+t*(p2-p1) = f.p1.z+radius2   =>
    double tplane = (f.p1.z + radius2 - p1.z ) / (p2.z-p1.z); // intersect edge with plane at z = ufp1.z
    Point ell_center = p1+tplane*(p2-p1);
    assert( isZero_tol( fabs(ell_center.z - (f.p1.z+radius2)) ) );
    Point major_dir = (p2-p1);
    assert( major_dir.xyNorm() > 0.0 );

    major_dir.z = 0;
    major_dir.xyNormalize();
    Point minor_dir = major_dir.xyPerp();
    double theta = atan( (p2.z - p1.z) / (p2-p1).xyNorm() );
    double major_length = fabs( radius2/sin(theta) ) ;
    double minor_length = radius2;
    AlignedEllipse e(ell_center, major_length, minor_length, radius1,  major_dir, minor_dir );
    if ( e.aligned_solver( f ) ) { // now we want the offset-ellipse point to lie on the fiber
        Point pseudo_cc  = e.ePoint1(); // pseudo cc-point on ellipse and cylinder
        Point pseudo_cc2 = e.ePoint2();
        CCPoint cc  = pseudo_cc.closestPoint(p1,p2);
        CCPoint cc2 = pseudo_cc2.closestPoint(p1,p2);
        cc.type  = EDGE_POS;
        cc2.type = EDGE_POS;
        Point cl  = e.oePoint1() - Point(0,0,center_height);
        assert( isZero_tol( fabs(cl.z - f.p1.z)) );
        Point cl2 = e.oePoint2() - Point(0,0,center_height);
        assert( isZero_tol( fabs(cl2.z - f.p1.z)) );
        double cl_t  = f.tval(cl);
        double cl_t2 = f.tval(cl2);
        if ( i.update_ifCCinEdgeAndTrue( cl_t, cc, p1, p2, true ) )
            result = true;
        if ( i.update_ifCCinEdgeAndTrue( cl_t2, cc2, p1, p2, true ) )
            result = true;
    }
    //std::cout << " BullCutter::generalEdgePush() DONE result= " << result << "\n";
    return result;
}

std::string BullCutter::str() const {
    std::ostringstream o;
    o << *this;
    return o.str();
}

std::ostream& operator<<(std::ostream &stream, BullCutter c) {
  stream << "BullCutter(d=" << c.diameter << ", r1=" << c.radius1 << " r2=" << c.radius2 << ", L=" << c.length <<  ")";
  return stream;
}

} // end namespace
// end file bullcutter.cpp


text:
//
// #include "daw/filtered_range.h"
// #include <cstdlib>
// #include <iostream>
// #include <list>
// #include <string>
//
// int main( int argc, char **arv ) {
// 	std::vector<int> test_values = { 100, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 55, 3, 7, 22, 11 };
// 	std::vector<int> test_values2 = { 200, 201, 201, 199, 220, 100 };
//
// 	using namespace daw::range;
// 	auto tmp = create_filtered_range( test_values )
// 		.where( is_any_of( is_equal( 1 ), is_equal( 7 ), is_even<int>( ) ) )
// 		.append( test_values2.begin( ), test_values2.end( ) )
// 		.stable_unique( ).for_each( display_item<int>( ) )
// 		.call([]( const daw::range::FilteredRange<int>& ) { std::cout << "-----\n"; })
// 		.sort( ).for_each( display_item<int>( ) );
//
// 	std::cout << "has 5 " << tmp.contains( 5 ) << "\n";
// 	std::cout << "has 4 " << tmp.contains( 4 ) << "\n";
//
// 	std::cout << "---------\n";
// 	daw::range::create_filtered_range( test_values ).append( test_values2.begin( ), test_values2.end( ) ).duplicates( ).for_each( display_item<int>( ) );
//
// 	std::list<std::string> test_values3 = { "blah", "blah blah", "hello world", "He's the hero Gotham deserves, but not the one it needs right now. So we'll hunt him. Because he can take it. Because he's not our hero. He's a silent guardian, a watchful protector. A dark knight." };
//
// 	auto tmp2 = create_filtered_range( test_values3 ).where( []( const std::string& value ) { return std::string::npos != value.find( "deserve" ); } ).for_each( display_item<std::string>( ) );
//
// 	system( "PAUSE" );
// 	return EXIT_SUCCESS;
// }
//
//
//
//
#include <iterator>
using std::begin;
using std::end;

template<typename Container>
Container copy_of( Container container ) {
	return container;
}

template<typename Container1, typename Container2>
bool are_different( const Container1& container1, const Container2& container2 ) {
	return !std::equal( begin( container1 ), end( container1 ), begin( container2 ) );
}

#define BOOST_TEST_MODULE FilteredRangeTest
#include <boost/test/unit_test.hpp>

#include <algorithm>
#include "daw/filtered_range.h"
#include <string>

using namespace daw::range;

template<typename Container>
struct HasMutated {
	HasMutated( const Container& container ): m_container( container ) { }

	template<typename Container2>
	bool operator()( const Container2& container ) {
		return are_different( m_container, container );
	}
private:
	const Container& m_container;
};

BOOST_AUTO_TEST_CASE( int_test ) {
	const std::vector<int> test_values = { 100, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 55, 3, 7, 22, 11 };
	const std::vector<int> test_values2 = { 200, 201, 201, 199, 220, 100 };

	HasMutated<std::vector<int>> has_mutated( test_values );

	using std::begin;
	using std::end;

	// create_filtered_range, to_vector
	{
		auto test_vals = copy_of( test_values );
		auto tmp = create_filtered_range( test_vals ).to_vector( );
		if( are_different( test_values, tmp ) ) {
			BOOST_FAIL( "create_filtered_range and/or to_vector do not work" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "create_filtered_range and/or to_vector mutated the underlying container" );
		}
	}

	// copy_to
	{
		auto test_vals = copy_of( test_values );
		auto tmp_vec = std::vector<int>( test_vals.size( ), 0 );
		create_filtered_range( test_vals ).copy_to( begin( tmp_vec ), end( tmp_vec ) );
		if( are_different( test_values, tmp_vec ) ) {
			BOOST_FAIL( "copy_to did not copy values properly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "create_filtered_range and/or to_vector mutated the underlying container" );
		}
	}

	// append
	{
		auto test_vals = copy_of( test_values );
		auto test_vals2 = copy_of( test_values2 );
		auto tmp = create_filtered_range( test_vals ).append( begin( test_vals2 ), end( test_vals2 ) ).to_vector( );
		auto tmp_vec = copy_of( test_values );
		auto tmp_vec2 = copy_of( test_values2 );
		tmp_vec.insert( end( tmp_vec ), begin( tmp_vec2 ), end( tmp_vec2 ) );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "append did not work" );
		}
		if( has_mutated( test_vals ) || are_different( test_values2, test_vals2 ) ) {
			BOOST_FAIL( "append mutated the underlying container" );
		}
	}

	// where, clear_where
	{
		auto test_vals = copy_of( test_values );
		auto tmp = create_filtered_range( test_vals );

		if( tmp.where( []( const int& value ) { return false; } ).to_vector( ).size( ) != 0 ) {
			BOOST_FAIL( "where did not function.  Should have filtered all values but some remained" );
		}
		if( tmp.where( []( const int& value ) { return true; } ).to_vector( ).size( ) != test_vals.size( ) ) {
			BOOST_FAIL( "where did not function.  Should have filtered none of the values but the sizes do not match" );
		}

		tmp = tmp.where( []( const int& value ) { return false; } );
		if( tmp.to_vector( ).size( ) != 0 ) {
			BOOST_FAIL( "where did not function.  Should have filtered all values but some remained" );
		}

		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "where has mutated the underlying container" );
		}

		tmp = tmp.clear_where( );
		if( tmp.to_vector( ).size( ) != test_vals.size( ) ) {
			BOOST_FAIL( "clear_where did not function.  Should have filtered none of the values but the sizes do not match" );
		}

		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "clear_where has mutated the underlying container" );
		}

	}

	// for_each
	{
		auto test_vals = copy_of( test_values );
		auto tmp = create_filtered_range( test_vals );
		int sum1 = 0;
		for( auto& val : test_vals ) { sum1 += val; }

		int sum2 = 0;
		tmp.for_each( [&sum2]( const int& val ) { sum2 += val; } );
		if( sum1 != sum2 ) {
			BOOST_FAIL( "for_each does not access all elements" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "for_each has mutated the underlying container when it should not have" );
		}

		// Test mutating elements
		tmp = create_filtered_range( test_vals );
		sum2 = 0;
		tmp.for_each( []( int& val ) { val = 1; } );
		tmp.for_each( [&sum2]( const int& val ) { sum2 += val; } );
		if( sum2 != test_vals.size( ) ) {
			BOOST_FAIL( "for_each did not allow mutation of all values" );
		}

		auto tmp_vec = tmp.to_vector( );
		if( !has_mutated( test_vals ) ) {
			BOOST_FAIL( "for_each has not mutated the underlying container when it should have" );
		}
	}

	// sort
	{
		auto test_vals = copy_of( test_values );

		auto tmp_vec = copy_of( test_values );
		std::sort( begin( tmp_vec ), end( tmp_vec ) );

		auto tmp = create_filtered_range( test_vals ).sort( ).to_vector( );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "sort did not function correctly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "sort has mutated the underlying container" );
		}
	}

	// stable_sort
	{
		auto test_vals = copy_of( test_values );

		auto tmp_vec = copy_of( test_values );
		std::stable_sort( begin( tmp_vec ), end( tmp_vec ) );

		auto tmp = create_filtered_range( test_vals ).stable_sort( ).to_vector( );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "stable_sort did not function correctly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "stable_sort has mutated the underlying container" );
		}
	}

	// unique
	{
		auto test_vals = copy_of( test_values );

		auto tmp_vec = copy_of( test_values );
		auto new_last = std::unique( begin( tmp_vec ), end( tmp_vec ) );
		tmp_vec.erase( new_last, end( tmp_vec ) );

		auto tmp = create_filtered_range( test_vals ).unique( ).to_vector( );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "unique did not function correctly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "unique has mutated the underlying container" );
		}
	}

	// sorted_unique
	{
		auto test_vals = copy_of( test_values );

		auto tmp_vec = copy_of( test_values );
		std::sort( begin( tmp_vec ), end( tmp_vec ) );
		auto new_last = std::unique( begin( tmp_vec ), end( tmp_vec ) );
		tmp_vec.erase( new_last, end( tmp_vec ) );

		auto tmp = create_filtered_range( test_vals ).sorted_unique( ).to_vector( );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "sorted_unique did not function correctly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "sorted_unique has mutated the underlying container" );
		}
	}

	// stable_unique
	// TODO: create test case
	{

	}

	// partition
	{
		auto is_even = []( const int& value ) { return 0 == value % 2; };
		auto test_vals = copy_of( test_values );

		auto tmp_vec = copy_of( test_values );
		std::partition( begin( tmp_vec ), end( tmp_vec ), is_even );

		auto tmp = create_filtered_range( test_vals ).partition( is_even ).to_vector( );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "partition did not function correctly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "partition has mutated the underlying container" );
		}
	}

	// stable_partition
	{
		auto is_even = []( const int& value ) { return 0 == value % 2; };
		auto test_vals = copy_of( test_values );

		auto tmp_vec = copy_of( test_values );
		std::stable_partition( begin( tmp_vec ), end( tmp_vec ), is_even );

		auto tmp = create_filtered_range( test_vals ).stable_partition( is_even ).to_vector( );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "stable_partition did not function correctly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "stable_partition has mutated the underlying container" );
		}
	}

	// reverse
	{
		auto test_vals = copy_of( test_values );
		auto tmp_vec = copy_of( test_values );
		std::reverse( begin( tmp_vec ), end( tmp_vec ) );

		auto tmp = create_filtered_range( test_vals ).reverse( ).to_vector( );
		if( are_different( tmp, tmp_vec ) ) {
			BOOST_FAIL( "reverse did not function correctly" );
		}
		if( has_mutated( test_vals ) ) {
			BOOST_FAIL( "reverse has mutated the underlying container" );
		}
	}

	// random_shuffle
	// TODO: add test
	{

	}

	// replace
	{
		int old_val = 3;
		int new_val = 1000;

		auto tmp_vec = copy_of( test_values );
		auto num_old = std::count( begin( tmp_vec ), end( tmp_vec ), old_val );
		std::replace( begin( tmp_vec ), end( tmp_vec ), old_val, new_val );
		auto num_new = std::count( begin( tmp_vec ), end( tmp_vec ), new_val );
		assert( num_old == num_new );

		auto test_vals = copy_of( test_values );
		auto tmp = create_filtered_range( test_values ).replace( old_val, new_val ).to_vector( );
		if( num_new != std::count( begin( tmp ), end( tmp ), new_val ) ) {
			BOOST_FAIL( "replace did not function correctly" );
		}
		if( !has_mutated( test_vals ) ) {
			BOOST_FAIL( "replace has not mutated the underlying container but it should have" );
		}
	}

	// is_even
	{
		auto test_vals = copy_of( test_values );
		for( auto& value : create_filtered_range( test_vals ).where( is_even<int>( ) ).to_vector( ) ) {
			if( 0 != value % 2 ) {
				BOOST_FAIL( "FilteredRange.where or is_even did not work" );
			}
		}
	}

	// is_odd
	{
		auto test_vals = copy_of( test_values );
		for( auto& value : create_filtered_range( test_vals ).where( is_odd<int>( ) ).to_vector( ) ) {
			if( 0 == value % 2 ) {
				BOOST_FAIL( "FilteredRange.where or is_even did not work" );
			}
		}
	}
}

max_stars_repo_name: beached/FilteredRange

max_issues_repo_name: beached/FilteredRange

max_forks_repo_name: beached/FilteredRange


text:
/*
 * lru_container_test.cpp
 *
 *  Created on: Aug 30, 2015
 *      Author: zmij
 */

#include <gtest/gtest.h>
#include <thread>

#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <tip/lru-cache/lru_cache.hpp>

TEST(LruContainer, KeyValue)
{
//	typedef concept_check::cache_traits< std::string, int,
//			std::chrono::high_resolution_clock::time_point, void >::cache_base_type
	typedef tip::util::lru_cache<std::string, int>
				str_cache_type;
	str_cache_type cache;
	cache.put(0, "zero");
	cache.put(1, "one");
	cache.put(2, "two");
	cache.put(3, "three");
	cache.put(4, "four");
	cache.put(5, "five");
	cache.put(6, "six");
	cache.put(7, "seven");
	cache.put(8, "eight");
	cache.put(9, "nine");
	EXPECT_EQ(10, cache.size());
	cache.shrink(5);
	EXPECT_TRUE(cache.exists(9));
	EXPECT_TRUE(cache.exists(8));
	EXPECT_TRUE(cache.exists(7));
	EXPECT_TRUE(cache.exists(6));
	EXPECT_TRUE(cache.exists(5));
	EXPECT_FALSE(cache.exists(4));
	EXPECT_FALSE(cache.exists(3));
	EXPECT_FALSE(cache.exists(2));
	EXPECT_FALSE(cache.exists(1));
	EXPECT_FALSE(cache.exists(0));

	std::this_thread::sleep_for(std::chrono::milliseconds(100));

	cache.get(9);
	cache.get(6);

	std::this_thread::sleep_for(std::chrono::milliseconds(100));

	cache.expire(std::chrono::milliseconds(150));
	EXPECT_TRUE(cache.exists(9));
	EXPECT_TRUE(cache.exists(6));

	EXPECT_FALSE(cache.exists(8));
	EXPECT_FALSE(cache.exists(7));
	EXPECT_FALSE(cache.exists(5));

	cache.expire(std::chrono::milliseconds(10));
	EXPECT_TRUE(cache.empty());
}

TEST(LruContainer, KeyExtractor)
{
//	typedef tip::util::lru_cache< std::function< int(int) > >
	typedef tip::util::lru_cache<int, std::function< int(int) >>
			int_cache_type;
	int_cache_type cache([](int a) { return a; } );
	cache.put(0);
	cache.put(1);
	cache.put(2);
	cache.put(3);
	cache.put(4);
	cache.put(5);
	cache.put(6);
	cache.put(7);
	cache.put(8);
	cache.put(9);
	EXPECT_EQ(10, cache.size());
	cache.shrink(5);
	EXPECT_TRUE(cache.exists(9));
	EXPECT_TRUE(cache.exists(8));
	EXPECT_TRUE(cache.exists(7));
	EXPECT_TRUE(cache.exists(6));
	EXPECT_TRUE(cache.exists(5));
	EXPECT_FALSE(cache.exists(4));
	EXPECT_FALSE(cache.exists(3));
	EXPECT_FALSE(cache.exists(2));
	EXPECT_FALSE(cache.exists(1));
	EXPECT_FALSE(cache.exists(0));

	std::this_thread::sleep_for(std::chrono::milliseconds(100));

	cache.get(9);
	cache.get(6);

	std::this_thread::sleep_for(std::chrono::milliseconds(100));

	cache.expire(std::chrono::milliseconds(150));
	EXPECT_TRUE(cache.exists(9));
	EXPECT_TRUE(cache.exists(6));

	EXPECT_FALSE(cache.exists(8));
	EXPECT_FALSE(cache.exists(7));
	EXPECT_FALSE(cache.exists(5));

	cache.expire(std::chrono::milliseconds(10));
	EXPECT_TRUE(cache.empty());
}

max_stars_repo_name: zmij/tip-lru

max_issues_repo_name: zmij/tip-lru

max_forks_repo_name: zmij/tip-lru


text:
/*
   Copyright 2020-2021 The Silkworm Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <atomic>
#include <csignal>
#include <filesystem>
#include <queue>
#include <string>
#include <thread>

#include <boost/signals2.hpp>
#include <ethash/keccak.hpp>

#include <silkworm/chain/config.hpp>
#include <silkworm/common/log.hpp>
#include <silkworm/concurrency/worker.hpp>
#include <silkworm/crypto/ecdsa.hpp>
#include <silkworm/db/access_layer.hpp>
#include <silkworm/db/stages.hpp>
#include <silkworm/db/util.hpp>
#include <silkworm/etl/collector.hpp>
#include <silkworm/types/block.hpp>

#ifndef SILKWORM_STAGEDSYNC_RECOVERY_WORKER_HPP_
#define SILKWORM_STAGEDSYNC_RECOVERY_WORKER_HPP_

namespace silkworm::stagedsync::recovery {

/**
 * @brief A thread worker dedicated at recovering public keys from
 * transaction signatures
 */
class RecoveryWorker final : public silkworm::Worker {
  public:
    RecoveryWorker(uint32_t id, size_t data_size);

    // Recovery package
    struct Package {
        uint64_t block_num;
        ethash::hash256 hash;
        bool odd_y_parity;
        uint8_t signature[64];
    };

    enum class Status {
        Idle = 0,
        Working = 1,
        ResultsReady = 2,
        Error = 3,
        Aborted = 4,
    };

    // Provides a container of packages to process
    void set_work(uint32_t batch_id, std::unique_ptr<std::vector<Package>> batch);

    uint32_t get_id() const;
    uint32_t get_batch_id() const;
    std::string get_error(void) const;
    Status get_status(void) const;

    // Pull results from worker
    bool pull_results(Status status, std::vector<std::pair<uint64_t, iovec>>& out);

    // Signal to connected handlers the task has completed
    boost::signals2::signal<void(RecoveryWorker* sender, uint32_t batch_id)> signal_completed;

  private:
    const uint32_t id_;                                  // Current worker identifier
    uint32_t batch_id_{0};                               // Running batch identifier
    std::unique_ptr<std::vector<Package>> batch_;        // Batch to process
    size_t data_size_;                                   // Size of the recovery data buffer
    uint8_t* data_{nullptr};                             // Pointer to data where rsults are stored
    std::vector<std::pair<uint64_t, iovec>> results_{};  // Results per block pointing to data area
    std::string last_error_{};                           // Description of last error occurrence
    std::atomic<Status> status_{Status::Idle};           // Status of worker

    // Basic work loop (overrides Worker::work())
    void work() final;
};

}  // namespace silkworm::stagedsync::recovery

#endif

max_stars_repo_name: gelfand/silkworm

max_issues_repo_name: gelfand/silkworm

max_forks_repo_name: gelfand/silkworm


text:
//  (C) Copyright Boost.org 2001. Permission to copy, use, modify, sell and
//  distribute this software is granted provided this copyright notice appears
//  in all copies. This software is provided "as is" without express or implied
//  warranty, and with no claim as to its suitability for any purpose.

//  See http://www.boost.org for most recent version.

//  IBM/Aix specific config options:

#define BOOST_PLATFORM "IBM Aix"

#define BOOST_HAS_UNISTD_H
#define BOOST_HAS_NL_TYPES_H
#define BOOST_HAS_NANOSLEEP
#define BOOST_HAS_CLOCK_GETTIME

// This needs support in "boost/cstdint.hpp" exactly like FreeBSD.
// This platform has header named <inttypes.h> which includes all
// the things needed.
#define BOOST_HAS_STDINT_H

// Threading API's:
#define BOOST_HAS_PTHREADS
#define BOOST_HAS_PTHREAD_DELAY_NP
#define BOOST_HAS_SCHED_YIELD
//#define BOOST_HAS_PTHREAD_YIELD

// boilerplate code:
#include <boost/config/posix_features.hpp>