text:
#include <CGAL/boost/graph/Named_function_parameters.h>
#include <CGAL/assertions.h>
#include <boost/type_traits/is_same.hpp>

#include <cstdlib>

template <int i>
struct A
{
  A(int v):v(v){}
  int v;
};

template <int i, class T>
void check_same_type(T)
{
  static const bool b = boost::is_same< A<i>, T >::value;
  CGAL_static_assertion(b);
  assert(b);
}

template<class NamedParameters>
void test(const NamedParameters& np)
{
  using CGAL::parameters::get_parameter;

  // Test values

    // Named parameters that we use in CGAL
  assert(get_parameter(np, CGAL::internal_np::vertex_index).v == 0);
  assert(get_parameter(np, CGAL::internal_np::visitor).v == 1);
  assert(get_parameter(np, CGAL::internal_np::vertex_point).v == 2);
  assert(get_parameter(np, CGAL::internal_np::halfedge_index).v == 3);
  assert(get_parameter(np, CGAL::internal_np::edge_index).v == 4);
  assert(get_parameter(np, CGAL::internal_np::face_index).v == 5);

  assert(get_parameter(np, CGAL::internal_np::edge_is_constrained).v == 6);
  assert(get_parameter(np, CGAL::internal_np::first_index).v == 7);
  assert(get_parameter(np, CGAL::internal_np::number_of_iterations).v == 8);

  assert(get_parameter(np, CGAL::internal_np::METIS_options).v == 800000001);
  assert(get_parameter(np, CGAL::internal_np::vertex_partition_id).v == 800000002);
  assert(get_parameter(np, CGAL::internal_np::face_partition_id).v == 800000003);

  assert(get_parameter(np, CGAL::internal_np::vertex_to_vertex_output_iterator).v == 800000004);
  assert(get_parameter(np, CGAL::internal_np::halfedge_to_halfedge_output_iterator).v == 800000005);
  assert(get_parameter(np, CGAL::internal_np::face_to_face_output_iterator).v == 800000006);

  assert(get_parameter(np, CGAL::internal_np::vertex_to_vertex_map).v == 800000007);
  assert(get_parameter(np, CGAL::internal_np::halfedge_to_halfedge_map).v == 800000008);
  assert(get_parameter(np, CGAL::internal_np::face_to_face_map).v == 800000009);

  assert(get_parameter(np, CGAL::internal_np::implementation_tag).v == 800000010);
  assert(get_parameter(np, CGAL::internal_np::prevent_unselection).v == 800000011);

  assert(get_parameter(np, CGAL::internal_np::stream_precision).v == 800000012);

    // Named parameters that we use in the package 'Mesh_3'
  assert(get_parameter(np, CGAL::internal_np::vertex_feature_degree).v == 9);

    // Named parameters used in the package 'Polygon Mesh Processing'
  assert(get_parameter(np, CGAL::internal_np::geom_traits).v == 10);
  assert(get_parameter(np, CGAL::internal_np::vertex_incident_patches).v == 11);
  assert(get_parameter(np, CGAL::internal_np::density_control_factor).v == 12);
  assert(get_parameter(np, CGAL::internal_np::use_delaunay_triangulation).v == 13);
  assert(get_parameter(np, CGAL::internal_np::use_2d_constrained_delaunay_triangulation).v == 4573);
  assert(get_parameter(np, CGAL::internal_np::fairing_continuity).v == 14);
  assert(get_parameter(np, CGAL::internal_np::sparse_linear_solver).v == 15);
  assert(get_parameter(np, CGAL::internal_np::number_of_relaxation_steps).v == 16);
  assert(get_parameter(np, CGAL::internal_np::protect_constraints).v == 17);
  assert(get_parameter(np, CGAL::internal_np::relax_constraints).v == 18);
  assert(get_parameter(np, CGAL::internal_np::collapse_constraints).v == 43);
  assert(get_parameter(np, CGAL::internal_np::vertex_is_constrained).v == 19);
  assert(get_parameter(np, CGAL::internal_np::face_patch).v == 20);
  assert(get_parameter(np, CGAL::internal_np::random_uniform_sampling).v == 21);
  assert(get_parameter(np, CGAL::internal_np::grid_sampling).v == 22);
  assert(get_parameter(np, CGAL::internal_np::monte_carlo_sampling).v == 23);
  assert(get_parameter(np, CGAL::internal_np::do_sample_edges).v == 24);
  assert(get_parameter(np, CGAL::internal_np::do_sample_vertices).v == 25);
  assert(get_parameter(np, CGAL::internal_np::do_sample_faces).v == 26);
  assert(get_parameter(np, CGAL::internal_np::number_of_points_on_faces).v == 27);
  assert(get_parameter(np, CGAL::internal_np::number_of_points_per_face).v == 28);
  assert(get_parameter(np, CGAL::internal_np::grid_spacing).v == 29);
  assert(get_parameter(np, CGAL::internal_np::number_of_points_per_edge).v == 30);
  assert(get_parameter(np, CGAL::internal_np::number_of_points_on_edges).v == 31);
  assert(get_parameter(np, CGAL::internal_np::nb_points_per_area_unit).v == 32);
  assert(get_parameter(np, CGAL::internal_np::nb_points_per_distance_unit).v == 33);
  assert(get_parameter(np, CGAL::internal_np::throw_on_self_intersection).v == 43);
  assert(get_parameter(np, CGAL::internal_np::clip_volume).v == 44);
  assert(get_parameter(np, CGAL::internal_np::use_compact_clipper).v == 45);
  assert(get_parameter(np, CGAL::internal_np::erase_all_duplicates).v == 48);
  assert(get_parameter(np, CGAL::internal_np::require_same_orientation).v == 49);
  assert(get_parameter(np, CGAL::internal_np::use_bool_op_to_clip_surface).v == 50);
  assert(get_parameter(np, CGAL::internal_np::face_size_map).v == 52);
  assert(get_parameter(np, CGAL::internal_np::use_angle_smoothing).v == 53);
  assert(get_parameter(np, CGAL::internal_np::use_area_smoothing).v == 54);
  assert(get_parameter(np, CGAL::internal_np::use_Delaunay_flips).v == 55);
  assert(get_parameter(np, CGAL::internal_np::use_safety_constraints).v == 56);
  assert(get_parameter(np, CGAL::internal_np::area_threshold).v == 57);
  assert(get_parameter(np, CGAL::internal_np::volume_threshold).v == 58);
  assert(get_parameter(np, CGAL::internal_np::snapping_tolerance).v == 59);
  assert(get_parameter(np, CGAL::internal_np::dry_run).v == 60);
  assert(get_parameter(np, CGAL::internal_np::do_lock_mesh).v == 61);
  assert(get_parameter(np, CGAL::internal_np::halfedges_keeper).v == 62);
  assert(get_parameter(np, CGAL::internal_np::do_simplify_border).v == 64);
  assert(get_parameter(np, CGAL::internal_np::do_not_modify).v == 65);
  assert(get_parameter(np, CGAL::internal_np::allow_self_intersections).v == 66);
  assert(get_parameter(np, CGAL::internal_np::polyhedral_envelope_epsilon).v == 67);
  assert(get_parameter(np, CGAL::internal_np::maximum_number_of_faces).v == 78910);
  assert(get_parameter(np, CGAL::internal_np::non_manifold_feature_map).v == 60);
  assert(get_parameter(np, CGAL::internal_np::filter).v == 61);
  assert(get_parameter(np, CGAL::internal_np::face_epsilon_map).v == 62);

    // Named parameters that we use in the package 'Surface Mesh Simplification'
  assert(get_parameter(np, CGAL::internal_np::get_cost_policy).v == 34);
  assert(get_parameter(np, CGAL::internal_np::get_placement_policy).v == 35);

  // Named parameters that we use in the package 'Optimal_bounding_box'
  assert(get_parameter(np, CGAL::internal_np::use_convex_hull).v == 63);

    // To-be-documented named parameters
  assert(get_parameter(np, CGAL::internal_np::face_normal).v == 36);
  assert(get_parameter(np, CGAL::internal_np::random_seed).v == 37);
  assert(get_parameter(np, CGAL::internal_np::do_project).v == 38);

    // Internal named parameters
  assert(get_parameter(np, CGAL::internal_np::weight_calculator).v == 39);
  assert(get_parameter(np, CGAL::internal_np::preserve_genus).v == 40);
  assert(get_parameter(np, CGAL::internal_np::verbosity_level).v == 41);
  assert(get_parameter(np, CGAL::internal_np::use_binary_mode).v == 51);
  assert(get_parameter(np, CGAL::internal_np::projection_functor).v == 42);
  assert(get_parameter(np, CGAL::internal_np::apply_per_connected_component).v == 46);
  assert(get_parameter(np, CGAL::internal_np::output_iterator).v == 47);

  // Test types

    // Named parameters that we use in CGAL
  check_same_type<0>(get_parameter(np, CGAL::internal_np::vertex_index));
  check_same_type<1>(get_parameter(np, CGAL::internal_np::visitor));
  check_same_type<2>(get_parameter(np, CGAL::internal_np::vertex_point));
  check_same_type<3>(get_parameter(np, CGAL::internal_np::halfedge_index));
  check_same_type<4>(get_parameter(np, CGAL::internal_np::edge_index));
  check_same_type<5>(get_parameter(np, CGAL::internal_np::face_index));

  check_same_type<6>(get_parameter(np, CGAL::internal_np::edge_is_constrained));
  check_same_type<7>(get_parameter(np, CGAL::internal_np::first_index));
  check_same_type<8>(get_parameter(np, CGAL::internal_np::number_of_iterations));

  check_same_type<800000001>(get_parameter(np, CGAL::internal_np::METIS_options));
  check_same_type<800000002>(get_parameter(np, CGAL::internal_np::vertex_partition_id));
  check_same_type<800000003>(get_parameter(np, CGAL::internal_np::face_partition_id));
  check_same_type<800000004>(get_parameter(np, CGAL::internal_np::vertex_to_vertex_output_iterator));
  check_same_type<800000005>(get_parameter(np, CGAL::internal_np::halfedge_to_halfedge_output_iterator));
  check_same_type<800000006>(get_parameter(np, CGAL::internal_np::face_to_face_output_iterator));
  check_same_type<800000007>(get_parameter(np, CGAL::internal_np::vertex_to_vertex_map));
  check_same_type<800000008>(get_parameter(np, CGAL::internal_np::halfedge_to_halfedge_map));
  check_same_type<800000009>(get_parameter(np, CGAL::internal_np::face_to_face_map));
  check_same_type<800000010>(get_parameter(np, CGAL::internal_np::implementation_tag));
  check_same_type<800000011>(get_parameter(np, CGAL::internal_np::prevent_unselection));
  check_same_type<800000012>(get_parameter(np, CGAL::internal_np::stream_precision));

    // Named parameters that we use in the package 'Mesh_3'
  check_same_type<9>(get_parameter(np, CGAL::internal_np::vertex_feature_degree));

    // Named parameters used in the package 'Polygon Mesh Processing'
  check_same_type<10>(get_parameter(np, CGAL::internal_np::geom_traits));
  check_same_type<11>(get_parameter(np, CGAL::internal_np::vertex_incident_patches));
  check_same_type<12>(get_parameter(np, CGAL::internal_np::density_control_factor));
  check_same_type<13>(get_parameter(np, CGAL::internal_np::use_delaunay_triangulation));
  check_same_type<4573>(get_parameter(np, CGAL::internal_np::use_2d_constrained_delaunay_triangulation));
  check_same_type<14>(get_parameter(np, CGAL::internal_np::fairing_continuity));
  check_same_type<15>(get_parameter(np, CGAL::internal_np::sparse_linear_solver));
  check_same_type<16>(get_parameter(np, CGAL::internal_np::number_of_relaxation_steps));
  check_same_type<17>(get_parameter(np, CGAL::internal_np::protect_constraints));
  check_same_type<18>(get_parameter(np, CGAL::internal_np::relax_constraints));
  check_same_type<43>(get_parameter(np, CGAL::internal_np::collapse_constraints));
  check_same_type<19>(get_parameter(np, CGAL::internal_np::vertex_is_constrained));
  check_same_type<20>(get_parameter(np, CGAL::internal_np::face_patch));
  check_same_type<21>(get_parameter(np, CGAL::internal_np::random_uniform_sampling));
  check_same_type<22>(get_parameter(np, CGAL::internal_np::grid_sampling));
  check_same_type<23>(get_parameter(np, CGAL::internal_np::monte_carlo_sampling));
  check_same_type<24>(get_parameter(np, CGAL::internal_np::do_sample_edges));
  check_same_type<25>(get_parameter(np, CGAL::internal_np::do_sample_vertices));
  check_same_type<26>(get_parameter(np, CGAL::internal_np::do_sample_faces));
  check_same_type<27>(get_parameter(np, CGAL::internal_np::number_of_points_on_faces));
  check_same_type<28>(get_parameter(np, CGAL::internal_np::number_of_points_per_face));
  check_same_type<29>(get_parameter(np, CGAL::internal_np::grid_spacing));
  check_same_type<30>(get_parameter(np, CGAL::internal_np::number_of_points_per_edge));
  check_same_type<31>(get_parameter(np, CGAL::internal_np::number_of_points_on_edges));
  check_same_type<32>(get_parameter(np, CGAL::internal_np::nb_points_per_area_unit));
  check_same_type<33>(get_parameter(np, CGAL::internal_np::nb_points_per_distance_unit));
  check_same_type<43>(get_parameter(np, CGAL::internal_np::throw_on_self_intersection));
  check_same_type<44>(get_parameter(np, CGAL::internal_np::clip_volume));
  check_same_type<45>(get_parameter(np, CGAL::internal_np::use_compact_clipper));
  check_same_type<48>(get_parameter(np, CGAL::internal_np::erase_all_duplicates));
  check_same_type<49>(get_parameter(np, CGAL::internal_np::require_same_orientation));
  check_same_type<50>(get_parameter(np, CGAL::internal_np::use_bool_op_to_clip_surface));
  check_same_type<52>(get_parameter(np, CGAL::internal_np::face_size_map));
  check_same_type<53>(get_parameter(np, CGAL::internal_np::use_angle_smoothing));
  check_same_type<54>(get_parameter(np, CGAL::internal_np::use_area_smoothing));
  check_same_type<55>(get_parameter(np, CGAL::internal_np::use_Delaunay_flips));
  check_same_type<56>(get_parameter(np, CGAL::internal_np::use_safety_constraints));
  check_same_type<65>(get_parameter(np, CGAL::internal_np::do_not_modify));
  check_same_type<66>(get_parameter(np, CGAL::internal_np::allow_self_intersections));
  check_same_type<67>(get_parameter(np, CGAL::internal_np::polyhedral_envelope_epsilon));

  check_same_type<12340>(get_parameter(np, CGAL::internal_np::do_self_intersection_tests));
  check_same_type<12341>(get_parameter(np, CGAL::internal_np::do_orientation_tests));
  check_same_type<12342>(get_parameter(np, CGAL::internal_np::error_codes));
  check_same_type<12343>(get_parameter(np, CGAL::internal_np::volume_inclusions));
  check_same_type<12344>(get_parameter(np, CGAL::internal_np::face_connected_component_map));
  check_same_type<12345>(get_parameter(np, CGAL::internal_np::connected_component_id_to_volume_id));
  check_same_type<12346>(get_parameter(np, CGAL::internal_np::is_cc_outward_oriented));
  check_same_type<12347>(get_parameter(np, CGAL::internal_np::intersecting_volume_pairs_output_iterator));
  check_same_type<12348>(get_parameter(np, CGAL::internal_np::i_used_as_a_predicate));
  check_same_type<12349>(get_parameter(np, CGAL::internal_np::nesting_levels));
  check_same_type<12350>(get_parameter(np, CGAL::internal_np::i_used_for_volume_orientation));

  check_same_type<57>(get_parameter(np, CGAL::internal_np::area_threshold));
  check_same_type<58>(get_parameter(np, CGAL::internal_np::volume_threshold));
  check_same_type<59>(get_parameter(np, CGAL::internal_np::snapping_tolerance));
  check_same_type<60>(get_parameter(np, CGAL::internal_np::dry_run));
  check_same_type<61>(get_parameter(np, CGAL::internal_np::do_lock_mesh));
  check_same_type<62>(get_parameter(np, CGAL::internal_np::halfedges_keeper));
  check_same_type<64>(get_parameter(np, CGAL::internal_np::do_simplify_border));
  check_same_type<78910>(get_parameter(np, CGAL::internal_np::maximum_number_of_faces));
  check_same_type<60>(get_parameter(np, CGAL::internal_np::non_manifold_feature_map));
  check_same_type<61>(get_parameter(np, CGAL::internal_np::filter));
  check_same_type<62>(get_parameter(np, CGAL::internal_np::face_epsilon_map));

    // Named parameters that we use in the package 'Surface Mesh Simplification'
  check_same_type<34>(get_parameter(np, CGAL::internal_np::get_cost_policy));
  check_same_type<35>(get_parameter(np, CGAL::internal_np::get_placement_policy));

  // Named parameters that we use in the package 'Optimal_bounding_box'
  check_same_type<63>(get_parameter(np, CGAL::internal_np::use_convex_hull));

    // To-be-documented named parameters
  check_same_type<36>(get_parameter(np, CGAL::internal_np::face_normal));
  check_same_type<37>(get_parameter(np, CGAL::internal_np::random_seed));
  check_same_type<38>(get_parameter(np, CGAL::internal_np::do_project));
  check_same_type<456>(get_parameter(np, CGAL::internal_np::algorithm));

    // Internal named parameters
  check_same_type<39>(get_parameter(np, CGAL::internal_np::weight_calculator));
  check_same_type<40>(get_parameter(np, CGAL::internal_np::preserve_genus));
  check_same_type<41>(get_parameter(np, CGAL::internal_np::verbosity_level));
  check_same_type<51>(get_parameter(np, CGAL::internal_np::use_binary_mode));
  check_same_type<42>(get_parameter(np, CGAL::internal_np::projection_functor));
  check_same_type<46>(get_parameter(np, CGAL::internal_np::apply_per_connected_component));
  check_same_type<47>(get_parameter(np, CGAL::internal_np::output_iterator));

  // Named parameters used in the package 'Point Set Processing'
  check_same_type<9000>(get_parameter(np, CGAL::internal_np::point_map));
  check_same_type<9001>(get_parameter(np, CGAL::internal_np::query_point_map));
  check_same_type<9002>(get_parameter(np, CGAL::internal_np::normal_map));
  check_same_type<9003>(get_parameter(np, CGAL::internal_np::diagonalize_traits));
  check_same_type<9004>(get_parameter(np, CGAL::internal_np::svd_traits));
  check_same_type<9005>(get_parameter(np, CGAL::internal_np::callback));
  check_same_type<9006>(get_parameter(np, CGAL::internal_np::sharpness_angle));
  check_same_type<9007>(get_parameter(np, CGAL::internal_np::edge_sensitivity));
  check_same_type<9008>(get_parameter(np, CGAL::internal_np::neighbor_radius));
  check_same_type<9009>(get_parameter(np, CGAL::internal_np::number_of_output_points));
  check_same_type<9010>(get_parameter(np, CGAL::internal_np::size));
  check_same_type<9011>(get_parameter(np, CGAL::internal_np::maximum_variation));
  check_same_type<9012>(get_parameter(np, CGAL::internal_np::degree_fitting));
  check_same_type<9013>(get_parameter(np, CGAL::internal_np::degree_monge));
  check_same_type<9014>(get_parameter(np, CGAL::internal_np::threshold_percent));
  check_same_type<9015>(get_parameter(np, CGAL::internal_np::threshold_distance));
  check_same_type<9016>(get_parameter(np, CGAL::internal_np::attraction_factor));
  check_same_type<9017>(get_parameter(np, CGAL::internal_np::plane_map));
  check_same_type<9018>(get_parameter(np, CGAL::internal_np::plane_index_map));
  check_same_type<9019>(get_parameter(np, CGAL::internal_np::select_percentage));
  check_same_type<9020>(get_parameter(np, CGAL::internal_np::require_uniform_sampling));
  check_same_type<9021>(get_parameter(np, CGAL::internal_np::point_is_constrained));
  check_same_type<9022>(get_parameter(np, CGAL::internal_np::number_of_samples));
  check_same_type<9023>(get_parameter(np, CGAL::internal_np::accuracy));
  check_same_type<9024>(get_parameter(np, CGAL::internal_np::maximum_running_time));
  check_same_type<9025>(get_parameter(np, CGAL::internal_np::overlap));
  check_same_type<9026>(get_parameter(np, CGAL::internal_np::transformation));
  check_same_type<9027>(get_parameter(np, CGAL::internal_np::point_set_filters));
  check_same_type<9028>(get_parameter(np, CGAL::internal_np::matcher));
  check_same_type<9029>(get_parameter(np, CGAL::internal_np::outlier_filters));
  check_same_type<9030>(get_parameter(np, CGAL::internal_np::error_minimizer));
  check_same_type<9031>(get_parameter(np, CGAL::internal_np::transformation_checkers));
  check_same_type<9032>(get_parameter(np, CGAL::internal_np::inspector));
  check_same_type<9033>(get_parameter(np, CGAL::internal_np::logger));
  check_same_type<9034>(get_parameter(np, CGAL::internal_np::maximum_normal_deviation));
  check_same_type<9035>(get_parameter(np, CGAL::internal_np::scan_angle_map));
  check_same_type<9036>(get_parameter(np, CGAL::internal_np::scanline_id_map));
}

int main()
{
  test(CGAL::parameters::vertex_index_map(A<0>(0))
                         .visitor(A<1>(1))
                         .vertex_point_map(A<2>(2))
                         .halfedge_index_map(A<3>(3))
                         .edge_index_map(A<4>(4))
                         .face_index_map(A<5>(5))
                         .edge_is_constrained_map(A<6>(6))
                         .first_index(A<7>(7))
                         .number_of_iterations(A<8>(8))
                         .METIS_options(A<800000001>(800000001))
                         .vertex_partition_id_map(A<800000002>(800000002))
                         .face_partition_id_map(A<800000003>(800000003))
                         .vertex_to_vertex_output_iterator(A<800000004>(800000004))
                         .halfedge_to_halfedge_output_iterator(A<800000005>(800000005))
                         .face_to_face_output_iterator(A<800000006>(800000006))
                         .vertex_to_vertex_map(A<800000007>(800000007))
                         .halfedge_to_halfedge_map(A<800000008>(800000008))
                         .face_to_face_map(A<800000009>(800000009))
                         .implementation_tag(A<800000010>(800000010))
                         .prevent_unselection(A<800000011>(800000011))
                         .stream_precision(A<800000012>(800000012))
                         .vertex_feature_degree_map(A<9>(9))
                         .geom_traits(A<10>(10))
                         .vertex_incident_patches_map(A<11>(11))
                         .density_control_factor(A<12>(12))
                         .use_delaunay_triangulation(A<13>(13))
                         .use_2d_constrained_delaunay_triangulation(A<4573>(4573))
                         .fairing_continuity(A<14>(14))
                         .sparse_linear_solver(A<15>(15))
                         .number_of_relaxation_steps(A<16>(16))
                         .protect_constraints(A<17>(17))
                         .relax_constraints(A<18>(18))
                         .collapse_constraints(A<43>(43))
                         .vertex_is_constrained_map(A<19>(19))
                         .face_patch_map(A<20>(20))
                         .use_random_uniform_sampling(A<21>(21))
                         .use_grid_sampling(A<22>(22))
                         .use_monte_carlo_sampling(A<23>(23))
                         .do_sample_edges(A<24>(24))
                         .do_sample_vertices(A<25>(25))
                         .do_sample_faces(A<26>(26))
                         .number_of_points_on_faces(A<27>(27))
                         .number_of_points_per_face(A<28>(28))
                         .grid_spacing(A<29>(29))
                         .number_of_points_per_edge(A<30>(30))
                         .number_of_points_on_edges(A<31>(31))
                         .number_of_points_per_area_unit(A<32>(32))
                         .number_of_points_per_distance_unit(A<33>(33))
                         .get_cost(A<34>(34))
                         .get_placement(A<35>(35))
                         .face_normal_map(A<36>(36))
                         .random_seed(A<37>(37))
                         .do_project(A<38>(38))
                         .algorithm(A<456>(456))
                         .weight_calculator(A<39>(39))
                         .preserve_genus(A<40>(40))
                         .verbosity_level(A<41>(41))
                         .projection_functor(A<42>(42))
                         .throw_on_self_intersection(A<43>(43))
                         .clip_volume(A<44>(44))
                         .use_compact_clipper(A<45>(45))
                         .non_manifold_feature_map(A<60>(60))
                         .filter(A<61>(61))
                         .face_epsilon_map(A<62>(62))
                         .apply_per_connected_component(A<46>(46))
                         .output_iterator(A<47>(47))
                         .erase_all_duplicates(A<48>(48))
                         .require_same_orientation(A<49>(49))
                         .use_bool_op_to_clip_surface(A<50>(50))
                         .use_binary_mode(A<51>(51))
                         .face_size_map(A<52>(52))
                         .use_angle_smoothing(A<53>(53))
                         .use_area_smoothing(A<54>(54))
                         .use_Delaunay_flips(A<55>(55))
                         .use_safety_constraints(A<56>(56))
                         .do_self_intersection_tests(A<12340>(12340))
                         .do_orientation_tests(A<12341>(12341))
                         .error_codes(A<12342>(12342))
                         .volume_inclusions(A<12343>(12343))
                         .face_connected_component_map(A<12344>(12344))
                         .connected_component_id_to_volume_id(A<12345>(12345))
                         .is_cc_outward_oriented(A<12346>(12346))
                         .intersecting_volume_pairs_output_iterator(A<12347>(12347))
                         .i_used_as_a_predicate(A<12348>(12348))
                         .nesting_levels(A<12349>(12349))
                         .i_used_for_volume_orientation(A<12350>(12350))
                         .area_threshold(A<57>(57))
                         .volume_threshold(A<58>(58))
                         .snapping_tolerance(A<59>(59))
                         .dry_run(A<60>(60))
                         .do_lock_mesh(A<61>(61))
                         .halfedges_keeper(A<62>(62))
                         .use_convex_hull(A<63>(63))
                         .do_simplify_border(A<64>(64))
                         .do_not_modify(A<65>(65))
                         .allow_self_intersections(A<66>(66))
                         .polyhedral_envelope_epsilon(A<67>(67))
                         .point_map(A<9000>(9000))
                         .query_point_map(A<9001>(9001))
                         .normal_map(A<9002>(9002))
                         .diagonalize_traits(A<9003>(9003))
                         .svd_traits(A<9004>(9004))
                         .callback(A<9005>(9005))
                         .sharpness_angle(A<9006>(9006))
                         .edge_sensitivity(A<9007>(9007))
                         .neighbor_radius(A<9008>(9008))
                         .number_of_output_points(A<9009>(9009))
                         .size(A<9010>(9010))
                         .maximum_variation(A<9011>(9011))
                         .degree_fitting(A<9012>(9012))
                         .degree_monge(A<9013>(9013))
                         .threshold_percent(A<9014>(9014))
                         .threshold_distance(A<9015>(9015))
                         .attraction_factor(A<9016>(9016))
                         .plane_map(A<9017>(9017))
                         .plane_index_map(A<9018>(9018))
                         .select_percentage(A<9019>(9019))
                         .require_uniform_sampling(A<9020>(9020))
                         .point_is_constrained_map(A<9021>(9021))
                         .number_of_samples(A<9022>(9022))
                         .accuracy(A<9023>(9023))
                         .maximum_running_time(A<9024>(9024))
                         .overlap(A<9025>(9025))
                         .transformation(A<9026>(9026))
                         .point_set_filters(A<9027>(9027))
                         .matcher(A<9028>(9028))
                         .outlier_filters(A<9029>(9029))
                         .error_minimizer(A<9030>(9030))
                         .transformation_checkers(A<9031>(9031))
                         .inspector(A<9032>(9032))
                         .logger(A<9033>(9033))
                         .maximum_normal_deviation(A<9034>(9034))
                         .scan_angle_map(A<9035>(9035))
                         .scanline_id_map(A<9036>(9036))
                         .maximum_number_of_faces(A<78910>(78910))
       );
  return EXIT_SUCCESS;
}

max_stars_repo_name: antoniospg/cgal

max_issues_repo_name: antoniospg/cgal

max_forks_repo_name: antoniospg/cgal


text:
//  Copyright John Maddock 2006.
//  Copyright Paul A. Bristow 2007.

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

#include <boost/math/tools/minima.hpp>
#include <boost/test/included/test_exec_monitor.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/math/special_functions/gamma.hpp>

template <class T>
struct poly_test
{
   // minima is at (3,4):
   T operator()(const T& v)
   {
      T a = v - 3;
      return 3 * a * a + 4;
   }
};

template <class T>
void test_minima(T, const char* /* name */)
{
   std::pair<T, T> m = boost::math::tools::brent_find_minima(poly_test<T>(), T(-10), T(10), 50);
   BOOST_CHECK_CLOSE(m.first, T(3), T(0.001));
   BOOST_CHECK_CLOSE(m.second, T(4), T(0.001));

   T (*fp)(T);
#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)
   fp = boost::math::lgamma<T>;
#else
   fp = boost::math::lgamma;
#endif

   m = boost::math::tools::brent_find_minima(fp, T(0.5), T(10), 50);
   BOOST_CHECK_CLOSE(m.first, T(1.461632), T(0.1));
#if defined(BOOST_MATH_NO_DEDUCED_FUNCTION_POINTERS)
   fp = boost::math::tgamma<T>;
#else
   fp = boost::math::tgamma;
#endif
   m = boost::math::tools::brent_find_minima(fp, T(0.5), T(10), 50);
   BOOST_CHECK_CLOSE(m.first, T(1.461632), T(0.1));
}

int test_main(int, char* [])
{
   test_minima(0.1f, "float");
   test_minima(0.1, "double");
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
   test_minima(0.1L, "long double");
#endif
   return 0;
}

ext: cpp


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_IMPL_SERIALIZER_IPP
#define BOOST_HTTP_PROTO_IMPL_SERIALIZER_IPP

#include <boost/http_proto/serializer.hpp>

namespace boost {
namespace http_proto {

/*

38 chars:
Content-Length: 18446744073709551615rn
12345678901234567890123456789012345678
         1         2         3       3

Transfer-Encoding:
*/
serializer::
~serializer()
{
    if(buf_)
        delete[] buf_;
}

serializer::
serializer(
    context& ctx) noexcept
    : ctx_(ctx)
{
    (void)ctx_;
    (void)cap_;
    (void)size_;
}

//------------------------------------------------

void
serializer::
set_header(
    header_info const& hi) noexcept
{
    hi_ = hi;
    if(! hi_.meta)
    {
        // TODO
        // generate metadata
    }
}

void
serializer::
set_body(
    void const*,
    std::size_t) noexcept
{
}

void
serializer::
reset() noexcept
{
}

void
serializer::
clear() noexcept
{
}

const_buffer_pair
serializer::
prepare(
    error_code& ec)
{
    ec = {};
    const_buffer_pair p;
    p.data[0] = hs_.data();
    p.size[0] = hs_.size();
    p.data[1] = bs_.data();
    p.size[1] = bs_.size();
    return p;
}

void
serializer::
consume(
    std::size_t) noexcept
{
}

//------------------------------------------------
//
//
//
//------------------------------------------------

void
serializer_::
clear() noexcept
{
    hs_ = {};
}

void
serializer_::
reserve(std::size_t bytes)
{
    (void)bytes;
}

void
serializer_::
reset(header_info const& hi)
{
    hs_ = { hi.data, hi.size };
}

void
serializer_::
reset_for_head(
    header_info const& hi)
{
    // TODO
    hs_ = { hi.data, hi.size };
}

bool
serializer_::
is_complete() const noexcept
{
    return
        hs_.empty() &&
        bs_.empty();
}

void
serializer_::
attach_body(string_view body)
{
    bs_ = body;
}

void
serializer_::
attach_extensions(
    string_view extensions)
{
    // TODO
    (void)extensions;
}

void
serializer_::
attach_end_of_body()
{
    // TODO
}

void
serializer_::
attach_end_of_body(
    fields_view const& trailers)
{
    // TODO
    (void)trailers;
}

void
serializer_::
flush()
{
    // TODO
    // VFALCO What do we flush here?
}

void
serializer_::
consume(std::size_t bytes)
{
    if(! hs_.empty())
    {
        if(bytes < hs_.size())
        {
            hs_.remove_prefix(bytes);
            return;
        }
        bytes -= hs_.size();
        hs_ = {};
    }

    BOOST_ASSERT(bytes <= bs_.size());
    if(bytes < bs_.size())
    {
        bs_.remove_prefix(bytes);
        return;
    }
    bs_ = {};

    // is_complete_ = true; ?
}

buffers
serializer_::
prepare(error_code& ec)
{
    // TODO
    (void)ec;
    return {};
}

buffers
serializer_::
prepare(
    std::size_t bytes,
    error_code& ec)
{
    // TODO
    (void)bytes;
    (void)ec;
    return {};
}

string_view
serializer_::
peek_output() const noexcept
{
    // TODO
    return {};
}

} // http_proto
} // boost

#endif

ext: ipp


text:
#include <sys/stat.h>

#include <fstream>
#include <memory>
#include <string>

#include <boost/random.hpp>

#include "counter.h"
#include "frontends/p4/toP4/toP4.h"
#include "pruner_util.h"

namespace P4PRUNER {

static boost::random::mt19937 rng;

void set_seed(int64_t seed) { rng = boost::mt19937(seed); }

int64_t get_rnd_int(int64_t min, int64_t max) {
    boost::random::uniform_int_distribution<int64_t> distribution(min, max);
    return distribution(rng);
}

double get_rnd_pct() {
    boost::random::uniform_real_distribution<double> distribution(0.0, 1.0);
    return distribution(rng);
}

bool file_exists(cstring file_path) {
    struct stat buffer;
    INFO("Checking if " << file_path << " exists.");
    if (stat(file_path, &buffer) != 0) {
        return false;
    }
    return true;
}

void create_dir(cstring folder_path) {
    int ret;
    cstring cmd = "mkdir -p ";
    cmd += folder_path;
    ret = system(cmd);
    if (ret) {
        ::warning("Creating folder %s failed.", folder_path);
    }
}

void remove_file(cstring file_path) {
    int ret;
    cstring cmd = "rm -rf ";
    cmd += file_path;
    ret = system(cmd);
    if (ret) {
        ::warning("Removing file or folder %s failed.", file_path);
    }
}

cstring get_file_stem(cstring file_path) {
    cstring file_stem;
    cstring stripped_name = P4PRUNER::remove_extension(file_path);

    const char *pos = stripped_name.findlast('/');
    // check if there even is a parent directory
    if (!pos) {
        return stripped_name;
    }
    size_t idx = (size_t)(pos - stripped_name);
    if (idx != std::string::npos)
        file_stem = stripped_name.substr(idx + 1);
    else
        file_stem = stripped_name;

    return file_stem;
}

cstring get_parent(cstring file_path) {
    cstring file_stem;
    cstring stripped_name = P4PRUNER::remove_extension(file_path);

    const char *pos = stripped_name.findlast('/');
    // check if there even is a parent directory
    if (!pos) {
        return stripped_name;
    }
    size_t idx = (size_t)(pos - stripped_name);
    if (idx != std::string::npos)
        file_stem = stripped_name.substr(0, idx);
    else
        file_stem = "";

    return file_stem;
}

cstring remove_extension(cstring file_path) {
    // find the last dot
    const char *last_dot = file_path.findlast('.');
    // there is no dot in this string, just return the full name
    if (not last_dot) {
        return file_path;
    }
    // otherwise get the index, remove the dot
    size_t idx = (size_t)(last_dot - file_path);
    return file_path.substr(0, idx);
}

ExitInfo get_exit_info(cstring name, P4PRUNER::PrunerConfig pruner_conf) {
    ExitInfo exit_info;
    INFO("Checking exit code.");

    if (pruner_conf.err_type == ErrorType::SemanticBug) {
        cstring command = pruner_conf.validation_bin;
        command += " -i ";
        command += name;
        // set the output dir
        command += " -o ";
        command += pruner_conf.working_dir;
        // suppress output
        command += " -ll CRITICAL ";
        command += " -p ";
        command += pruner_conf.compiler;
        if (pruner_conf.allow_undef) {
            command += " -u ";
        }
        auto exit_code = system(command.c_str());
        exit_info.exit_code = WEXITSTATUS(exit_code);
        exit_info.err_msg = cstring("");

    } else {
        INFO("Trying get_crash_exit_info now");
        exit_info = get_crash_exit_info(name, pruner_conf);
    }
    return exit_info;
}

ExitInfo get_crash_exit_info(cstring name, P4PRUNER::PrunerConfig pruner_conf) {
    // The crash bugs variant of get_exit_code
    ExitInfo exit_info;
    cstring include_dir = get_parent(pruner_conf.compiler) + "/../../p4include";
    cstring command = "P4C_16_INCLUDE_PATH=" + include_dir + " ";
    command += pruner_conf.compiler;
    command += " --Wdisable ";
    command += name;
    // Apparently popen doesn't like stderr hence redirecting stderr to
    // stdout
    command += " 2>&1";
    // set the include path to the right directory
    char buffer[1000];
    cstring result = "";
    FILE *pipe = popen(command, "r");
    bool done = false;
    char *saveptr = NULL;
    int newlines = 0;
    try {
        while (fgets(buffer, sizeof buffer, pipe) != NULL && !done) {
            for (int i = 0; i < 1000; i++) {
                if (buffer[i] == '\n') {
                    newlines++;
                    break;
                    if (newlines > 1) {
                        // ignoring the first line
                        strtok_r(buffer, "\n", &saveptr);
                        result += strtok_r(NULL, "\n", &saveptr);

                        done = true;
                        break;
                    }
                }
            }

            result += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    auto exit_code = pclose(pipe);
    exit_info.exit_code = WEXITSTATUS(exit_code);
    exit_info.err_msg = result;
    return exit_info;
}

ErrorType classify_bug(ExitInfo exit_info) {
    int exit_code = exit_info.exit_code;

    if (exit_code == EXIT_TEST_VALIDATION) {
        return ErrorType::SemanticBug;
    } else if (exit_code == EXIT_TEST_SUCCESS) {
        return ErrorType::Success;
    } else if (exit_code == EXIT_TEST_UNDEFINED) {
        return ErrorType::Undefined;
    } else {
        cstring comp = exit_info.err_msg.find("Compiler Bug");

        if (!comp.isNullOrEmpty()) {
            INFO("Crash bug");
            return ErrorType::CrashBug;
        }
        cstring err_msg = exit_info.err_msg.find("error");

        if (!err_msg.isNullOrEmpty()) {
            return ErrorType::Error;
        }
        return ErrorType::Unknown;
    }
}

void emit_p4_program(const IR::P4Program *program, cstring prog_name) {
    auto temp_f = new std::ofstream(prog_name);
    P4::ToP4 *temp_p4 = new P4::ToP4(temp_f, false);
    program->apply(*temp_p4);
    temp_f->close();
}

void print_p4_program(const IR::P4Program *program) {
    P4::ToP4 *print_p4 = new P4::ToP4(&std::cout, false);
    program->apply(*print_p4);
}

bool compare_files(const IR::P4Program *prog_before,
                   const IR::P4Program *prog_after) {
    auto before_stream = new std::stringstream;
    auto after_stream = new std::stringstream;

    P4::ToP4 *before = new P4::ToP4(before_stream, false);
    prog_before->apply(*before);

    P4::ToP4 *after = new P4::ToP4(after_stream, false);
    prog_after->apply(*after);

    return before_stream->str() == after_stream->str();
}

double measure_size(const IR::P4Program *prog) {
    auto prog_stream = new std::stringstream;
    P4::ToP4 *toP4 = new P4::ToP4(prog_stream, false);
    prog->apply(*toP4);
    return prog_stream->str().length();
}

uint64_t count_statements(const IR::P4Program *prog) {
    Counter *counter = new Counter();
    prog->apply(*counter);
    return counter->statements;
}

double measure_pct(const IR::P4Program *prog_before,
                   const IR::P4Program *prog_after) {
    double before_len = measure_size(prog_before);

    return (before_len - measure_size(prog_after)) * (100.0 / before_len);
}

int check_pruned_program(const IR::P4Program **orig_program,
                         const IR::P4Program *pruned_program,
                         P4PRUNER::PrunerConfig pruner_conf) {
    cstring out_file =
        pruner_conf.working_dir + get_file_stem(pruner_conf.out_file_name);
    // append a .p4 suffix
    out_file += ".p4";
    emit_p4_program(pruned_program, out_file);
    if (compare_files(pruned_program, *orig_program)) {
        INFO("File has not changed. Skipping analysis.");
        return EXIT_SUCCESS;
    }
    int exit_code = get_exit_info(out_file, pruner_conf).exit_code;
    // if got the right exit code, then modify the original program, if not
    // then choose a smaller bank of statements to remove now.
    if (exit_code != pruner_conf.exit_code) {
        INFO("FAILED");
        return EXIT_FAILURE;
    } else {
        INFO("PASSED: Reduced by " << measure_pct(*orig_program, pruned_program)
                                   << " %")
        *orig_program = pruned_program;
        return EXIT_SUCCESS;
    }
}

}  // namespace P4PRUNER


text:
#include "boost_asio_msvc.h"

#include <iostream>
#include <string>
#include <atomic>
#include <thread>
#include <chrono>
#include <exception>
#include <boost/program_options.hpp>

#include "utils.hpp"
#include "padding_atomic.hpp"

#define DEFAULT_PACKET_SIZE 32
#define MAX_PACKET_SIZE     (128 * 1024)

enum http_server_mode_t {
    http_server_mode,
    echo_server_mode,
};

std::string g_server_ip;
std::string g_server_port;

uint32_t g_mode         = http_server_mode_t::http_server_mode;
uint32_t g_nodelay      = 0;
uint32_t g_need_echo    = 1;
uint32_t g_packet_size  = 64;

std::string g_mode_str      = "echo";
std::string g_nodelay_str   = "false";

namespace jimi {

extern padding_atomic<uint64_t> g_query_count;
extern padding_atomic<uint32_t> g_client_count;

extern padding_atomic<uint64_t> g_recv_bytes;
extern padding_atomic<uint64_t> g_send_bytes;

} // namespace jimi

jimi::padding_atomic<uint64_t> jimi::g_query_count(0);
jimi::padding_atomic<uint32_t> jimi::g_client_count(0);

jimi::padding_atomic<uint64_t> jimi::g_recv_bytes(0);
jimi::padding_atomic<uint64_t> jimi::g_send_bytes(0);

struct Foo
{
    int i;
    char buf[43];
};

int foo_test(int i, Foo & foo)
{
    printf("foo_test(), i = %d, foo & = 0x%p\n", i, &foo);
    return 0;
}

void run_decay_test()
{
    printf("typeid( std::decay<std::function<void()>> ).name() = %s\n", typeid(std::decay< std::function<void()> >::type).name());
    printf("typeid( std::decay<std::function<void(Foo &)>> ).name() = %s\n", typeid(std::decay< std::function<void(Foo &)> >::type).name());
    printf("typeid( std::decay<std::function<int(Foo &)>> ).name() = %s\n", typeid(std::decay< std::function<int(Foo &)> >::type).name());
    printf("typeid( std::function<int(Foo &)> ).name() = %s\n", typeid(std::function<int(Foo &)>).name());
    printf("typeid( std::function<int(int, int)> ).name() = %s\n", typeid(std::function<int(int, int)>).name());
    printf("typeid( std::function<int(int, Foo &)> ).name() = %s\n", typeid(std::function<int(int, Foo &)>).name());
    printf("typeid( std::function<int(int, const Foo &)> ).name() = %s\n", typeid(std::function<int(int, const Foo &)>).name());
    printf("\n");
}

void run_padding_atomic_test()
{
    printf("is_inheritable<Foo>::value = %d\n", jimi::detail::is_inheritable<Foo>::value);
    printf("is_inheritable<Foo &>::value = %d\n", jimi::detail::is_inheritable<Foo &>::value);
    printf("is_inheritable<Foo *>::value = %d\n", jimi::detail::is_inheritable<Foo *>::value);
    printf("is_inheritable<volatile Foo>::value = %d\n", jimi::detail::is_inheritable<volatile Foo>::value);
    printf("is_inheritable<int>::value = %d\n", jimi::detail::is_inheritable<int>::value);
    printf("is_inheritable<volatile int>::value = %d\n", jimi::detail::is_inheritable<volatile int>::value);
    printf("is_inheritable< std::function<void()> >::value = %d\n", jimi::detail::is_inheritable< std::function<void()> >::value);
    printf("is_inheritable< std::function<void(Foo)> >::value = %d\n", jimi::detail::is_inheritable< std::function<void(Foo)> >::value);
    printf("\n");

    printf("is_inheritable_decay<Foo>::value = %d\n", jimi::detail::is_inheritable_decay<Foo>::value);
    printf("is_inheritable_decay<Foo &>::value = %d\n", jimi::detail::is_inheritable_decay<Foo &>::value);
    printf("is_inheritable_decay<Foo *>::value = %d\n", jimi::detail::is_inheritable_decay<Foo *>::value);
    printf("is_inheritable_decay<volatile Foo>::value = %d\n", jimi::detail::is_inheritable_decay<volatile Foo>::value);
    printf("is_inheritable_decay<int>::value = %d\n", jimi::detail::is_inheritable_decay<int>::value);
    printf("is_inheritable_decay<volatile int>::value = %d\n", jimi::detail::is_inheritable_decay<volatile int>::value);
    printf("is_inheritable_decay< std::function<void()> >::value = %d\n", jimi::detail::is_inheritable_decay< std::function<void()> >::value);
    printf("is_inheritable_decay< std::function<void(Foo)> >::value = %d\n", jimi::detail::is_inheritable_decay< std::function<void(Foo)> >::value);
    printf("\n");

    Foo foo;
    foo.i = 2;
    foo.buf[0] = { 0 };

    jimi::padding_atomic<int> counter(4);
    printf("jimi::padding_atomic<int> ounter(4) = %d\n", counter.load(std::memory_order_relaxed));
    printf("\n");

    std::atomic<Foo> atomic_foo;
    printf("sizeof(Foo) = %u\n", (uint32_t)sizeof(Foo));
    printf("sizeof(std::atomic<Foo>) = %u\n", (uint32_t)sizeof(std::atomic<Foo>));
    printf("std::atomic<Foo> atomic_foo(foo) = 0x%p\n", &atomic_foo);
    atomic_foo = foo;
    printf("\n");

    jimi::padding_atomic<Foo> counter_foo(foo);
    printf("sizeof(Foo) = %u\n", (uint32_t)sizeof(Foo));
    printf("jimi::padding_atomic<Foo>::kSizeOfData = %u\n", (uint32_t)jimi::padding_atomic<Foo>::kSizeOfData);
    printf("jimi::padding_atomic<Foo>::kPaddingBytes = %u\n", (uint32_t)jimi::padding_atomic<Foo>::kPaddingBytes);
    printf("sizeof(jimi::padding_atomic<Foo>) = %u\n", (uint32_t)sizeof(jimi::padding_atomic<Foo>));
    printf("jimi::padding_atomic<Foo> counter_foo(foo) = 0x%p\n", &counter_foo);
    printf("\n");

    counter_foo = foo;
    counter_foo.store(foo);

    jimi::padding_atomic<Foo>::value_type & foo_val = counter_foo.get();
    foo_val.i = 10;
    foo_val.buf[0] = 'A';
    foo_val.buf[1] = 'B';
    foo_val.buf[2] = 'C';
    foo_val.buf[3] = '\0';
    printf("jimi::padding_atomic<Foo> = 0x%p\n", &counter_foo);
    printf("& Foo = 0x%p\n", &foo_val);
    printf("& Foo.i = 0x%p, Foo.i = %d\n", &foo_val.i, foo_val.i);
    printf("& Foo.buf = 0x%p, Foo.buf[0] = '%c'\n", &foo_val.buf[0], foo_val.buf[0]);
    printf("\n");

    jimi::padding_atomic_wrapper<int> counter_wrapper(8);
    printf("jimi::padding_atomic<int> counter_wrapper(8) = %d\n", counter_wrapper.atomic.load(std::memory_order_relaxed));
    counter_wrapper = 6;
    printf("jimi::padding_atomic<int> counter_wrapper(6) = %d\n", counter_wrapper.atomic.load(std::memory_order_relaxed));
    printf("\n");

    jimi::padding_atomic_wrapper<Foo> wrapper_foo(foo);
    printf("sizeof(Foo) = %u\n", (uint32_t)sizeof(Foo));
    printf("jimi::padding_atomic_wrapper<Foo>::kSizeOfData = %u\n", (uint32_t)jimi::padding_atomic_wrapper<Foo>::kSizeOfData);
    printf("jimi::padding_atomic_wrapper<Foo>::kPaddingBytes = %u\n", (uint32_t)jimi::padding_atomic_wrapper<Foo>::kPaddingBytes);
    printf("sizeof(jimi::padding_atomic_wrapper<Foo>) = %u\n", (uint32_t)sizeof(jimi::padding_atomic_wrapper<Foo>));
    printf("jimi::padding_atomic_wrapper<Foo> wrapper_foo(foo) = 0x%p\n", &wrapper_foo);
    printf("\n");

    wrapper_foo = foo;
    wrapper_foo.atomic.store(foo);

    jimi::padding_atomic_wrapper<Foo>::value_type & foo_atomic = wrapper_foo.get();
    foo_atomic.i = 20;
    foo_atomic.buf[0] = 'a';
    foo_atomic.buf[1] = 'b';
    foo_atomic.buf[2] = 'c';
    foo_atomic.buf[3] = '\0';
    printf("jimi::padding_atomic_wrapper<Foo> = 0x%p\n", &wrapper_foo);
    printf("& Foo = 0x%p\n", &foo_atomic);
    printf("& Foo.i = 0x%p, Foo.i = %d\n", &foo_atomic.i, foo_atomic.i);
    printf("& Foo.buf = 0x%p, Foo.buf[0] = '%c'\n", &foo_atomic.buf[0], foo_atomic.buf[0]);
    printf("\n");

    printf("\n");
}

void run_http_server(const std::string & host, const std::string & port,
                     uint32_t packet_size, uint32_t thread_num,
                     bool confirm = false)
{
    //
}

void run_http_server_ex(const std::string & host, const std::string & port,
                        uint32_t packet_size, uint32_t thread_num,
                        bool confirm = false)
{
    //
}

void make_spaces(std::string & spaces, std::size_t size)
{
    spaces = "";
    for (std::size_t i = 0; i < size; ++i)
        spaces += " ";
}

void print_usage(const std::string & app_name, const boost::program_options::options_description & options_desc)
{
    std::string leader_spaces;
    make_spaces(leader_spaces, app_name.size());

    std::cerr << std::endl;
    std::cerr << options_desc << std::endl;

    std::cerr << "Usage: " << std::endl << std::endl
              << "  " << app_name.c_str()      << " --host=<host> --port=<port> --mode=<mode> --test=<test>" << std::endl
              << "  " << leader_spaces.c_str() << " [--pipeline=1] [--packet_size=64] [--thread-num=0]" << std::endl
              << std::endl
              << "For example: " << std::endl << std::endl
              << "  " << app_name.c_str()      << " --host=127.0.0.1 --port=9000 --mode=echo --test=pingpong" << std::endl
              << "  " << leader_spaces.c_str() << " --pipeline=10 --packet-size=64 --thread-num=8" << std::endl
              << std::endl
              << "  " << app_name.c_str() << " -s 127.0.0.1 -p 9000 -m echo -t pingpong -l 10 -k 64 -n 8" << std::endl;
    std::cerr << std::endl;
}

int main(int argc, char * argv[])
{
    std::string app_name;
    std::string server_ip, server_port;
    std::string mode_str, test_str, nodelay_str, cmd, cmd_value;
    int32_t mode = 0;
    int32_t pipeline = 1, packet_size = 0, thread_num = 0, need_echo = 1;

    namespace options = boost::program_options;
    options::options_description desc("Command list");
    desc.add_options()
        ("help,h",                                                                                "usage info")
        ("host,s",          options::value<std::string>(&server_ip)->default_value("127.0.0.1"),    "server host or ip address")
        ("port,p",          options::value<std::string>(&server_port)->default_value("9000"),       "server port")
        ("mode,m",          options::value<std::string>(&mode_str)->default_value("http"),          "server mode = [http]")
        ("packet-size,k",   options::value<int32_t>(&packet_size)->default_value(64),               "packet size")
        ("thread-num,n",    options::value<int32_t>(&thread_num)->default_value(0),                 "thread numbers")
        ("nodelay,y",       options::value<std::string>(&nodelay_str)->default_value("false"),      "TCP socket nodelay = [0 or 1, true or false]")
        ("echo,e",          options::value<int32_t>(&need_echo)->default_value(1),                  "whether the server need echo")
        ("pipeline,l",      options::value<int32_t>(&pipeline)->default_value(1),                   "pipeline numbers")
        ;

    // parse command line
    options::variables_map args_map;
    try {
        options::store(options::parse_command_line(argc, argv, desc), args_map);
    }
    catch (const std::exception & ex) {
        std::cout << "Exception is: " << ex.what() << std::endl;
    }
    options::notify(args_map);

    app_name = get_app_name(argv[0]);

    // help
    if (args_map.count("help") > 0) {
        print_usage(app_name, desc);
        exit(EXIT_FAILURE);
    }

    // host
    if (args_map.count("host") > 0) {
        server_ip = args_map["host"].as<std::string>();
    }
    std::cout << "host: " << server_ip.c_str() << std::endl;
    if (!is_valid_ip_v4(server_ip)) {
        std::cerr << "Error: ip address \"" << server_ip.c_str() << "\" format is wrong." << std::endl;
        exit(EXIT_FAILURE);
    }

    // port
    if (args_map.count("port") > 0) {
        server_port = args_map["port"].as<std::string>();
    }
    std::cout << "port: " << server_port.c_str() << std::endl;
    if (!is_socket_port(server_port)) {
        std::cerr << "Error: port [" << server_port.c_str() << "] number must be range in (0, 65535]." << std::endl;
        exit(EXIT_FAILURE);
    }

    // mode
    if (args_map.count("mode") > 0) {
        mode_str = args_map["mode"].as<std::string>();
    }

    // Get the mode info
    if (mode_str == "echo") {
        g_mode = echo_server_mode;
        g_mode_str = "Http Echo Server";
    }
    else {
        // Default mode
        g_mode = http_server_mode;
        g_mode_str = "Http Server";
    }
    std::cout << "mode str:  " << mode_str.c_str() << std::endl;
    std::cout << "mode info: " << g_mode_str.c_str() << std::endl;

    // packet-size
    if (args_map.count("packet-size") > 0) {
        packet_size = args_map["packet-size"].as<int32_t>();
    }
    if (packet_size <= 0)
        packet_size = DEFAULT_PACKET_SIZE;
    if (packet_size > MAX_PACKET_SIZE) {
        packet_size = MAX_PACKET_SIZE;
        std::cerr << "Warnning: packet_size = " << packet_size << " can not set to more than "
                  << MAX_PACKET_SIZE << " bytes [MAX_PACKET_SIZE]." << std::endl;
    }
    g_packet_size = packet_size;
    std::cout << "packet-size: " << packet_size << std::endl;

    // thread-num
    if (args_map.count("thread-num") > 0) {
        thread_num = args_map["thread-num"].as<int32_t>();
    }
    std::cout << "thread-num: " << thread_num << std::endl;
    if (thread_num <= 0) {
        thread_num = std::thread::hardware_concurrency();
        std::cout << ">>> thread-num: std::thread::hardware_concurrency() = " << thread_num << std::endl;
    }

    // nodelay
    if (args_map.count("nodelay") > 0) {
        nodelay_str = args_map["nodelay"].as<std::string>();
    }
    if (nodelay_str == "1" || nodelay_str == "true") {
        g_nodelay = 1;
        g_nodelay_str = "true";
    }
    else {
        g_nodelay = 0;
        g_nodelay_str = "false";
    }
    std::cout << "TCP scoket no-delay: " << g_nodelay_str.c_str() << std::endl;

    // Run the server
    std::cout << std::endl;
    std::cout << app_name.c_str() << " begin ..." << std::endl;
    std::cout << std::endl;
    std::cout << "listen " << server_ip.c_str() << ":" << server_port.c_str() << std::endl;
    std::cout << "mode: " << mode_str.c_str() << std::endl;
    std::cout << "packet_size: " << packet_size << ", thread_num: " << thread_num << std::endl;
    std::cout << std::endl;

    if (mode == http_server_mode) {
        run_http_server(server_ip, server_port, packet_size, thread_num);
    }
    else if (mode == echo_server_mode) {
        // TODO: echo server
        std::cout << "TODO: echo_server_mode." << std::endl;
    }
    else {
        run_http_server_ex(server_ip, server_port, packet_size, thread_num);
    }

#if 0
    run_padding_atomic_test();
#endif

#ifdef _WIN32
    ::system("pause");
#endif
    return 0;
}


text:
#ifndef boost_xml_dom_text_hpp_
#define boost_xml_dom_text_hpp_

#include <boost/xml/dom/node.hpp>

namespace boost
{
namespace xml
{
namespace dom
{

template <typename S> class element;

template <typename S>
class text : public node<S>
{
friend class element<S>;
public:
  S content() const;
  void set_content(S const &);

// private:
  text(xmlNode *a) : node<S>(a) {}
};

template <typename S>
S text<S>::content() const
{
  xmlChar *content = xmlNodeGetContent(this->impl());
  S retn = converter<S>::out(content);
  xmlFree(content);
  return retn;
}

template <typename S>
void text<S>::set_content(S const &content)
{
  xmlSetContent(this->impl(), converter<S>::in(content));
}

} // namespace boost::xml::dom
} // namespace boost::xml
} // namespace boost

#endif

ext: hpp


text:
/*
 * Copyright 2016 Jacopo Urbani
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 <kognac/utils.h>

/**** MEMORY STATISTICS ****/
#if defined(_WIN32)
#include <windows.h>
#include <psapi.h>
#elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__))
#include <unistd.h>
#include <sys/resource.h>

#if defined(__APPLE__) && defined(__MACH__)
#include <mach/mach.h>
#include <sys/types.h>
#include <sys/sysctl.h>

#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__)))
#include <fcntl.h>
#include <procfs.h>

#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
#include <stdio.h>
#endif
#else
#error "I don't know which OS it is being used. Cannot optimize the code..."
#endif

#include <kognac/lz4io.h>

#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/log/trivial.hpp>

#include <algorithm>
#include <vector>
#include <string>

namespace fs = boost::filesystem;

using namespace std;

int Utils::numBytes(long number) {
    long max = 32;
    if (number < 0) {
        BOOST_LOG_TRIVIAL(error) << "Negative number " << number;
    }
    for (int i = 1; i <= 8; i++) {
        if (number < max) {
            return i;
        }
        max *= 256;
    }
    BOOST_LOG_TRIVIAL(error) << "Number is too large: " << number;
    return -1;
}

int Utils::numBytesFixedLength(long number) {
    uint8_t bytes = 0;
    do {
        bytes++;
        number = number >> 8;
    } while (number > 0);
    return bytes;
}

int Utils::numBytes2(long number) {
    int nbytes = 0;
    do {
        number >>= 7;
        nbytes++;
    } while (number > 0);
    return nbytes;
}

int Utils::decode_int(char* buffer, int offset) {
    int n = (buffer[offset++] & 0xFF) << 24;
    n += (buffer[offset++] & 0xFF) << 16;
    n += (buffer[offset++] & 0xFF) << 8;
    n += buffer[offset] & 0xFF;
    return n;
}

int Utils::decode_int(const char* buffer) {
    int n = (buffer[0] & 0xFF) << 24;
    n += (buffer[1] & 0xFF) << 16;
    n += (buffer[2] & 0xFF) << 8;
    n += buffer[3] & 0xFF;
    return n;
}

void Utils::encode_int(char* buffer, int offset, int n) {
    buffer[offset++] = (n >> 24) & 0xFF;
    buffer[offset++] = (n >> 16) & 0xFF;
    buffer[offset++] = (n >> 8) & 0xFF;
    buffer[offset++] = n & 0xFF;
}

void Utils::encode_int(char* buffer, int n) {
    buffer[0] = (n >> 24) & 0xFF;
    buffer[1] = (n >> 16) & 0xFF;
    buffer[2] = (n >> 8) & 0xFF;
    buffer[3] = n & 0xFF;
}

int Utils::decode_intLE(char* buffer, int offset) {
    int n = buffer[offset++] & 0xFF;
    n += (buffer[offset++] & 0xFF) << 8;
    n += (buffer[offset++] & 0xFF) << 16;
    n += (buffer[offset] & 0xFF) << 24;
    return n;
}

void Utils::encode_intLE(char* buffer, int offset, int n) {
    buffer[offset++] = n & 0xFF;
    buffer[offset++] = (n >> 8) & 0xFF;
    buffer[offset++] = (n >> 16) & 0xFF;
    buffer[offset++] = (n >> 24) & 0xFF;
}

long Utils::decode_long(char* buffer, int offset) {
    long n = (long) (buffer[offset++]) << 56;
    n += (long) (buffer[offset++] & 0xFF) << 48;
    n += (long) (buffer[offset++] & 0xFF) << 40;
    n += (long) (buffer[offset++] & 0xFF) << 32;
    n += (long) (buffer[offset++] & 0xFF) << 24;
    n += (buffer[offset++] & 0xFF) << 16;
    n += (buffer[offset++] & 0xFF) << 8;
    n += buffer[offset] & 0xFF;
    return n;
}

long Utils::decode_longFixedBytes(const char* buffer, const uint8_t nbytes) {
    uint8_t offset = 0;
    long n = 0;
    switch (nbytes) {
        case 1:
            n += buffer[offset] & 0xFF;
            break;
        case 2:
            n += (buffer[offset++] & 0xFF) << 8;
            n += buffer[offset] & 0xFF;
            break;
        case 3:
            n += (buffer[offset++] & 0xFF) << 16;
            n += (buffer[offset++] & 0xFF) << 8;
            n += buffer[offset] & 0xFF;
            break;
        case 4:
            n += (long) (buffer[offset++] & 0xFF) << 24;
            n += (buffer[offset++] & 0xFF) << 16;
            n += (buffer[offset++] & 0xFF) << 8;
            n += buffer[offset] & 0xFF;
            break;
        case 5:
            n += (long) (buffer[offset++] & 0xFF) << 32;
            n += (long) (buffer[offset++] & 0xFF) << 24;
            n += (buffer[offset++] & 0xFF) << 16;
            n += (buffer[offset++] & 0xFF) << 8;
            n += buffer[offset] & 0xFF;
            break;
        case 6:
            n += (long) (buffer[offset++] & 0xFF) << 40;
            n += (long) (buffer[offset++] & 0xFF) << 32;
            n += (long) (buffer[offset++] & 0xFF) << 24;
            n += (buffer[offset++] & 0xFF) << 16;
            n += (buffer[offset++] & 0xFF) << 8;
            n += buffer[offset] & 0xFF;
            break;
        case 7:
            n += (long) (buffer[offset++] & 0xFF) << 48;
            n += (long) (buffer[offset++] & 0xFF) << 40;
            n += (long) (buffer[offset++] & 0xFF) << 32;
            n += (long) (buffer[offset++] & 0xFF) << 24;
            n += (buffer[offset++] & 0xFF) << 16;
            n += (buffer[offset++] & 0xFF) << 8;
            n += buffer[offset] & 0xFF;
            break;
        case 8:
            n += (long) (buffer[offset++]) << 56;
            n += (long) (buffer[offset++] & 0xFF) << 48;
            n += (long) (buffer[offset++] & 0xFF) << 40;
            n += (long) (buffer[offset++] & 0xFF) << 32;
            n += (long) (buffer[offset++] & 0xFF) << 24;
            n += (buffer[offset++] & 0xFF) << 16;
            n += (buffer[offset++] & 0xFF) << 8;
            n += buffer[offset] & 0xFF;
            break;
    }
    return n;
}

long Utils::decode_long(const char* buffer) {
    long n = (long) (buffer[0]) << 56;
    n += (long) (buffer[1] & 0xFF) << 48;
    n += (long) (buffer[2] & 0xFF) << 40;
    n += (long) (buffer[3] & 0xFF) << 32;
    n += (long) (buffer[4] & 0xFF) << 24;
    n += (buffer[5] & 0xFF) << 16;
    n += (buffer[6] & 0xFF) << 8;
    n += buffer[7] & 0xFF;
    return n;
}

void Utils::encode_long(char* buffer, int offset, long n) {
    buffer[offset++] = (n >> 56) & 0xFF;
    buffer[offset++] = (n >> 48) & 0xFF;
    buffer[offset++] = (n >> 40) & 0xFF;
    buffer[offset++] = (n >> 32) & 0xFF;
    buffer[offset++] = (n >> 24) & 0xFF;
    buffer[offset++] = (n >> 16) & 0xFF;
    buffer[offset++] = (n >> 8) & 0xFF;
    buffer[offset++] = n & 0xFF;
}

void Utils::encode_long(char* buffer, long n) {
    buffer[0] = (n >> 56) & 0xFF;
    buffer[1] = (n >> 48) & 0xFF;
    buffer[2] = (n >> 40) & 0xFF;
    buffer[3] = (n >> 32) & 0xFF;
    buffer[4] = (n >> 24) & 0xFF;
    buffer[5] = (n >> 16) & 0xFF;
    buffer[6] = (n >> 8) & 0xFF;
    buffer[7] = n & 0xFF;
}

void Utils::encode_longNBytes(char* buffer, const uint8_t nbytes,
        const uint64_t n) {
    uint8_t offset = 0;
    switch (nbytes) {
        case 1:
            buffer[offset] = n & 0xFF;
            break;
        case 2:
            buffer[offset++] = (n >> 8) & 0xFF;
            buffer[offset++] = n & 0xFF;
            break;
        case 3:
            buffer[offset++] = (n >> 16) & 0xFF;
            buffer[offset++] = (n >> 8) & 0xFF;
            buffer[offset++] = n & 0xFF;
            break;
        case 4:
            buffer[offset++] = (n >> 24) & 0xFF;
            buffer[offset++] = (n >> 16) & 0xFF;
            buffer[offset++] = (n >> 8) & 0xFF;
            buffer[offset++] = n & 0xFF;
            break;
        case 5:
            buffer[offset++] = (n >> 32) & 0xFF;
            buffer[offset++] = (n >> 24) & 0xFF;
            buffer[offset++] = (n >> 16) & 0xFF;
            buffer[offset++] = (n >> 8) & 0xFF;
            buffer[offset++] = n & 0xFF;
            break;
        case 6:
            buffer[offset++] = (n >> 40) & 0xFF;
            buffer[offset++] = (n >> 32) & 0xFF;
            buffer[offset++] = (n >> 24) & 0xFF;
            buffer[offset++] = (n >> 16) & 0xFF;
            buffer[offset++] = (n >> 8) & 0xFF;
            buffer[offset++] = n & 0xFF;
            break;
        case 7:
            buffer[offset++] = (n >> 48) & 0xFF;
            buffer[offset++] = (n >> 40) & 0xFF;
            buffer[offset++] = (n >> 32) & 0xFF;
            buffer[offset++] = (n >> 24) & 0xFF;
            buffer[offset++] = (n >> 16) & 0xFF;
            buffer[offset++] = (n >> 8) & 0xFF;
            buffer[offset++] = n & 0xFF;
            break;
        case 8:
            buffer[offset++] = (n >> 56) & 0xFF;
            buffer[offset++] = (n >> 48) & 0xFF;
            buffer[offset++] = (n >> 40) & 0xFF;
            buffer[offset++] = (n >> 32) & 0xFF;
            buffer[offset++] = (n >> 24) & 0xFF;
            buffer[offset++] = (n >> 16) & 0xFF;
            buffer[offset++] = (n >> 8) & 0xFF;
            buffer[offset++] = n & 0xFF;
            break;
        default:
            throw 10;
    }
}

long Utils::decode_longWithHeader(char* buffer) {
    long n = (long) (buffer[0] & 0x7F) << 49;
    n += (long) (buffer[1] & 0x7F) << 42;
    n += (long) (buffer[2] & 0x7F) << 35;
    n += (long) (buffer[3] & 0x7F) << 28;
    n += (long) (buffer[4] & 0x7F) << 21;
    n += (buffer[5] & 0x7F) << 14;
    n += (buffer[6] & 0x7F) << 7;
    n += buffer[7] & 0x7F;
    return n;
}

void Utils::encode_longWithHeader0(char* buffer, long n) {

    if (n < 0) {
        BOOST_LOG_TRIVIAL(error) << "Number is negative";
        exit(1);
    }

    buffer[0] = (n >> 49) & 0x7F;
    buffer[1] = (n >> 42) & 0x7F;
    buffer[2] = (n >> 35) & 0x7F;
    buffer[3] = (n >> 28) & 0x7F;
    buffer[4] = (n >> 21) & 0x7F;
    buffer[5] = (n >> 14) & 0x7F;
    buffer[6] = (n >> 7) & 0x7F;
    buffer[7] = n & 0x7F;
}

void Utils::encode_longWithHeader1(char* buffer, long n) {

    if (n < 0) {
        BOOST_LOG_TRIVIAL(error) << "Number is negative";
        exit(1);
    }

    buffer[0] = ((n >> 49) | 0x80) & 0xFF;
    buffer[1] = ((n >> 42) | 0x80) & 0xFF;
    buffer[2] = ((n >> 35) | 0x80) & 0xFF;
    buffer[3] = ((n >> 28) | 0x80) & 0xFF;
    buffer[4] = ((n >> 21) | 0x80) & 0xFF;
    buffer[5] = ((n >> 14) | 0x80) & 0xFF;
    buffer[6] = ((n >> 7) | 0x80) & 0xFF;
    buffer[7] = (n | 0x80) & 0xFF;
}

//long Utils::decode_long(char* buffer, int offset, const char nbytes) {
//  long n = 0;
//  for (int i = nbytes - 1; i >= 0; i--) {
//      n += (long) (buffer[offset++] & 0xFF) << i * 8;
//  }
//  return n;
//}

short Utils::decode_short(const char* buffer, int offset) {
    return (short) (((buffer[offset] & 0xFF) << 8) + (buffer[offset + 1] & 0xFF));
}

void Utils::encode_short(char* buffer, int offset, int n) {
    buffer[offset++] = (n >> 8) & 0xFF;
    buffer[offset++] = n & 0xFF;
}

void Utils::encode_short(char* buffer, int n) {
    buffer[0] = (n >> 8) & 0xFF;
    buffer[1] = n & 0xFF;
}

long Utils::decode_vlong(char* buffer, int *offset) {
    int pos = *offset;
    int first = buffer[pos++];
    int nbytes = ((first & 255) >> 5) + 1;
    long retval = (first & 31);

    switch (nbytes) {
        case 2:
            retval += (buffer[pos++] & 255) << 5;
            break;
        case 3:
            retval += (buffer[pos++] & 255) << 5;
            retval += (buffer[pos++] & 255) << 13;
            break;
        case 4:
            retval += (buffer[pos++] & 255) << 5;
            retval += (buffer[pos++] & 255) << 13;
            retval += (buffer[pos++] & 255) << 21;
            break;
        case 5:
            retval += (buffer[pos++] & 255) << 5;
            retval += (buffer[pos++] & 255) << 13;
            retval += (buffer[pos++] & 255) << 21;
            retval += (long) (buffer[pos++] & 255) << 29;
            break;
        case 6:
            retval += (buffer[pos++] & 255) << 5;
            retval += (buffer[pos++] & 255) << 13;
            retval += (buffer[pos++] & 255) << 21;
            retval += (long) (buffer[pos++] & 255) << 29;
            retval += (long) (buffer[pos++] & 255) << 37;
            break;
        case 7:
            retval += (buffer[pos++] & 255) << 5;
            retval += (buffer[pos++] & 255) << 13;
            retval += (buffer[pos++] & 255) << 21;
            retval += (long) (buffer[pos++] & 255) << 29;
            retval += (long) (buffer[pos++] & 255) << 37;
            retval += (long) (buffer[pos++] & 255) << 45;
            break;
        case 8:
            retval += (buffer[pos++] & 255) << 5;
            retval += (buffer[pos++] & 255) << 13;
            retval += (buffer[pos++] & 255) << 21;
            retval += (long) (buffer[pos++] & 255) << 29;
            retval += (long) (buffer[pos++] & 255) << 37;
            retval += (long) (buffer[pos++] & 255) << 45;
            retval += (long) (buffer[pos++] & 255) << 53;
            break;
    }
    *offset = pos;
    return retval;
}

int Utils::encode_vlong(char* buffer, int offset, long n) {
    int nbytes = numBytes(n);
    buffer[offset++] = (((nbytes - 1) << 5) + ((int) n & 31));
    n >>= 5;
    for (int i = 1; i < nbytes; i++) {
        buffer[offset++] = ((int) n & 255);
        n >>= 8;
    }
    return offset;
}

uint16_t Utils::encode_vlong(char* buffer, long n) {
    int nbytes = numBytes(n);
    int offset = 0;
    buffer[offset++] = (((nbytes - 1) << 5) + ((int) n & 31));
    n >>= 5;
    for (int i = 1; i < nbytes; i++) {
        buffer[offset++] = ((int) n & 255);
        n >>= 8;
    }
    return nbytes;
}
//short Utils::decode_vshort(char* buffer, int *offset) {
//  char n = buffer[(*offset)++];
//  if (n < 0) {
//      short return_value = (short) ((n & 127) << 8);
//      return_value += buffer[(*offset)++] & 255;
//      return return_value;
//  } else {
//      return n;
//  }
//}

//int Utils::decode_vint(char* buffer, int *offset) {
//  int n = 0;
//  int pos = *offset;
//  int b = buffer[pos++];
//  n = b & 63;
//  int nbytes = (b >> 6) & 3;
//  switch (nbytes) {
//  case 1:
//      n += (buffer[pos++] & 255) << 6;
//      break;
//  case 2:
//      n += (buffer[pos++] & 255) << 6;
//      n += (buffer[pos++] & 255) << 14;
//      break;
//  case 3:
//      n += (buffer[pos++] & 255) << 6;
//      n += (buffer[pos++] & 255) << 14;
//      n += (buffer[pos++] & 255) << 22;
//      break;
//  }
//  *offset = pos;
//  return n;
//}

int Utils::decode_vint2(char* buffer, int *offset) {
    int pos = *offset;
    int number = buffer[pos++];
    if (number < 0) {
        int longNumber = number & 127;
        int shiftBytes = 7;
        do {
            number = buffer[pos++];
            longNumber += ((number & 127) << shiftBytes);
            shiftBytes += 7;
        } while (number < 0);
        *offset = pos;
        return longNumber;
    } else {
        *offset = pos;
        return number;
    }
}

int Utils::encode_vlong2(char* buffer, int offset, long n) {
    if (n < 0) {
        BOOST_LOG_TRIVIAL(error) << "Number is negative. This is not allowed with vlong2";
        throw 10;
    }

    if (n < 128) { // One byte is enough
        buffer[offset++] = n;
        return offset;
    } else {
        int bytesToStore = 64 - numberOfLeadingZeros((unsigned long)n);
        while (bytesToStore > 7) {
            buffer[offset++] = ((n & 127) + 128);
            n >>= 7;
            bytesToStore -= 7;
        }
        buffer[offset++] = n & 127;
    }
    return offset;
}

uint16_t Utils::encode_vlong2(char* buffer, long n) {
    if (n < 0) {
        BOOST_LOG_TRIVIAL(error) << "Number is negative. This is not allowed with vlong2";
        throw 10;
    }

    if (n < 128) { // One byte is enough
        buffer[0] = n;
        return 1;
    } else {
        int bytesToStore = 64 - numberOfLeadingZeros((unsigned long)n);
        uint16_t offset = 0;
        while (bytesToStore > 7) {
            buffer[offset++] = ((n & 127) + 128);
            n >>= 7;
            bytesToStore -= 7;
        }
        buffer[offset++] = n & 127;
        return offset;
    }
}

void Utils::encode_vlong2_fixedLen(char* buffer, long n, const uint8_t len) {
    char *beginbuffer = buffer;

    if (n < 128) { // One byte is enough
        *buffer = n;
    } else {
        int neededBits = 64 - numberOfLeadingZeros((unsigned long)n);
        while (neededBits > 7) {
            *buffer = ((n & 127) + 128);
            n >>= 7;
            buffer++;
            neededBits -= 7;
        }
        *buffer = n & 127;
    }
    buffer++;
    int remBytes = len - (buffer - beginbuffer);
    while (--remBytes >= 0) {
        *buffer = 128;
        buffer++;
    }
    assert((buffer - beginbuffer) == len);

}

int Utils::encode_vlong2_fast(uint8_t *out, uint64_t x) {
    int i, j;
    for (i = 9; i > 0; i--) {
        if (x & 127ULL << i * 7) break;
    }
    for (j = 0; j <= i; j++)
        out[j] = ((x >> ((i - j) * 7)) & 127) | 128;

    out[i] ^= 128;
    return i;
}

uint64_t Utils::decode_vlong2_fast(uint8_t *in) {
    uint64_t r = 0;

    do {
        r = (r << 7) | (uint64_t)(*in & 127);
    } while (*in++ & 128);

    return r;
}

long Utils::decode_vlong2(const char* buffer, int *offset) {
    int pos = *offset;
    int shift = 7;
    long n = buffer[pos] & 127;
    while (buffer[pos++] < 0) {
        n += (long) (buffer[pos] & 127) << shift;
        shift += 7;
    }
    *offset = pos;
    return n;
}

long Utils::decode_vlongWithHeader0(char* buffer, const int end, int *p) {
    int pos = 0;
    int shift = 7;
    long n = buffer[pos++] & 127;
    while (pos < end && ((buffer[pos] & 128) == 0)) {
        n += (long) (buffer[pos++] & 127) << shift;
        shift += 7;
    }
    *p = pos;
    return n;
}

long Utils::decode_vlongWithHeader1(char* buffer, const int end, int *p) {
    int pos = 0;
    int shift = 7;
    long n = buffer[pos++] & 127;
    while (pos < end && buffer[pos] < 0) {
        n += (long) (buffer[pos++] & 127) << shift;
        shift += 7;
    }
    *p = pos;
    return n;
}

int Utils::encode_vlongWithHeader0(char* buffer, long n) {
    if (n < 0) {
        BOOST_LOG_TRIVIAL(error) << "Number is negative";
        return -1;
    }

    int i = 0;
    do {
        buffer[i++] = n & 127;
        n >>= 7;
    } while (n > 0);
    return i;
}

int Utils::encode_vlongWithHeader1(char* buffer, long n) {
    if (n < 0) {
        BOOST_LOG_TRIVIAL(error) << "Number is negative";
        return -1;
    }

    int i = 0;
    do {
        buffer[i++] = ( n | 128 ) & 0xFF;
        n >>= 7;
    } while (n > 0);
    return i;
}

int Utils::encode_vint2(char* buffer, int offset, int n) {
    if (n < 128) { // One byte is enough
        buffer[offset++] = n;
        return offset;
    } else {
        int bytesToStore = 32 - numberOfLeadingZeros((unsigned int) n);
        while (bytesToStore > 7) {
            buffer[offset++] = ((n & 127) + 128);
            n >>= 7;
            bytesToStore -= 7;
        }
        buffer[offset++] = (n & 127);
    }
    return offset;
}

int Utils::commonPrefix(tTerm *o1, int s1, int e1, tTerm *o2, int s2, int e2) {
    int len = 0;
    for (int i = s1, j = s2; i < e1 && j < e2; i++, j++) {
        if (o1[i] != o2[j]) {
            return len;
        }
        ++len;
    }
    return len;
}

int Utils::compare(const char* o1, int s1, int e1, const char* o2, int s2,
        int e2) {
    for (int i = s1, j = s2; i < e1 && j < e2; i++, j++) {
        if (o1[i] != o2[j]) {
            return ((int)o1[i] & 0xff) - ((int) o2[j] & 0xff);
        }
    }
    return (e1 - s1) - (e2 - s2);
}

int Utils::prefixEquals(char* o1, int len1, char* o2, int len2) {
    int i = 0;
    for (; i < len1 && i < len2; i++) {
        if (o1[i] != o2[i]) {
            return ((int) o1[i] & 0xff) - ((int) o2[i] & 0xff);
        }
    }
    if (i == len1) {
        return 0;
    } else {
        return 1;
    }
}

int Utils::prefixEquals(char* o1, int len, char* o2) {
    int i = 0;
    for (; i < len && o2[i] != '\0'; i++) {
        if (o1[i] != o2[i]) {
            return ((int) o1[i] & 0xff) - ((int) o2[i] & 0xff);
        }
    }
    if (i == len) {
        return 0;
    } else {
        return 1;
    }
}

double Utils::get_max_mem() {
    struct rusage rusage;
    getrusage(RUSAGE_SELF, &rusage);
    double memory = 0.0;
#if defined(__APPLE__) && defined(__MACH__)
    memory = (double) rusage.ru_maxrss / 1024 / 1024;
#else
    memory = (double)rusage.ru_maxrss / 1024;
#endif
    return memory;
}

long Utils::getSystemMemory() {
#if defined(__APPLE__) && defined(__MACH__)
    int mib[2];
    mib[0] = CTL_HW;
    mib[1] = HW_MEMSIZE;
    int64_t size = 0;
    size_t len = sizeof(size);
    sysctl(mib, 2, &size, &len, NULL, 0);
    return size;
#else
    long pages = sysconf(_SC_PHYS_PAGES);
    long page_size = sysconf(_SC_PAGE_SIZE);
    return pages * page_size;
#endif
}

long Utils::getUsedMemory() {
#if defined(_WIN32)
    /* Windows -------------------------------------------------- */
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    return (size_t)info.WorkingSetSize;

#elif defined(__APPLE__) && defined(__MACH__)
    /* OSX ------------------------------------------------------ */
    struct mach_task_basic_info info;
    mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
    if (task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, (task_info_t) &info,
                &infoCount) != KERN_SUCCESS)
        return (size_t) 0L; /* Can't access? */
    return (size_t) info.resident_size;

#elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
    /* Linux ---------------------------------------------------- */
    long rss = 0L;
    FILE* fp = NULL;
    if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL )
        return (size_t)0L; /* Can't open? */
    if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) {
        fclose( fp );
        return (size_t)0L; /* Can't read? */
    }
    fclose( fp );
    return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE);

#else
    /* AIX, BSD, Solaris, and Unknown OS ------------------------ */
    return (size_t)0L; /* Unsupported. */
#endif
}

long Utils::getIOReadChars() {
#if defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
    std::ifstream file("/proc/self/io");
    std::string line;
    while (std::getline(file, line)) {
        string::size_type loc = line.find("rchar", 0);
        if (loc != string::npos) {
            string number = line.substr(7);
            return stol(number);
        }
    }
    return (size_t)0L;
#else
    return (size_t)0L; /* Unsupported. */
#endif
}

long Utils::getIOReadBytes() {
#if defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
    std::ifstream file("/proc/self/io");
    std::string line;
    while (std::getline(file, line)) {
        string::size_type loc = line.find("read_bytes", 0);
        if (loc != string::npos) {
            string number = line.substr(12);
            return stol(number);
        }
    }
    return (size_t)0L;
#else
    return -1; /* Unsupported. */
#endif
}

long long unsigned Utils::getCPUCounter() {
    unsigned a, d;

    __asm__ volatile("rdtsc" : "=a" (a), "=d" (d));

    return ((unsigned long long)a) | (((unsigned long long)d) << 32);;
}

vector<string> Utils::getFilesWithPrefix(string dir, string prefix) {
    vector<string> files;
    for (fs::directory_iterator itr(dir); itr != fs::directory_iterator();
            ++itr) {
        if (fs::is_regular_file(itr->status())) {
            string s = itr->path().filename().string();
            if (boost::algorithm::starts_with(s, prefix)) {
                files.push_back(s);
            }
        }
    }
    return files;
}

vector<string> Utils::getFiles(string dir, bool ignoreExtension) {
    vector<string> files;
    if (!ignoreExtension) {
        for (fs::directory_iterator itr(dir); itr != fs::directory_iterator();
                ++itr) {
            if (fs::is_regular_file(itr->status())
                    && itr->path().filename().string()[0] != '.') {
                string s = itr->path().string();
                files.push_back(s);
            }
        }
    } else {
        std::set<string> s_files;
        for (fs::directory_iterator itr(dir); itr != fs::directory_iterator();
                ++itr) {
            if (fs::is_regular_file(itr->status())
                    && itr->path().filename().string()[0] != '.') {
                string s = itr->path().string();
                //Remove the extension
                s_files.insert(itr->path().parent_path().string() + "/" + itr->path().stem().string());
            }
        }
        for (auto s : s_files) {
            files.push_back(s);
        }
    }
    return files;
}

vector<string> Utils::getSubdirs(string dir) {
    vector<string> files;
    for (fs::directory_iterator itr(dir); itr != fs::directory_iterator();
            ++itr) {
        if (fs::is_directory(itr->status())
                && itr->path().filename().string()[0] != '.') {
            string s = itr->path().string();
            files.push_back(s);
        }
    }
    return files;
}

int Utils::getNumberPhysicalCores() {
    return sysconf( _SC_NPROCESSORS_ONLN);
}

long Utils::quickSelect(long *vector, int size, int k) {
    std::vector<long> supportVector(vector, vector + size);
    std::nth_element(supportVector.begin(), supportVector.begin() + k,
            supportVector.end());
    return supportVector[k];
    //  if (start == end)
    //          return vector[start];
    //      int j = partition(vector, start, end);
    //      int length = j - start + 1;
    //      if (length == k)
    //          return vector[j];
    //      else if (k < length)
    //          return quickSelect(vector, start, j - 1, k);
    //      else
    //          return quickSelect(vector, j + 1, end, k - length);
}

long Utils::getNBytes(std::string input) {
    if (fs::is_directory(input)) {
        long size = 0;
        for (fs::directory_iterator itr(input); itr != fs::directory_iterator();
                ++itr) {
            if (fs::is_regular(itr->path())) {
                size += fs::file_size(itr->path());
            }
        }
        return size;
    } else {
        return fs::file_size(fs::path(input));
    }
}

bool Utils::isCompressed(std::string input) {
    if (fs::is_directory(input)) {
        bool isCompressed = false;
        for (fs::directory_iterator itr(input); itr != fs::directory_iterator();
                ++itr) {
            if (fs::is_regular(itr->path())) {
                if (itr->path().extension() == string(".gz"))
                    isCompressed = true;
            }
        }
        return isCompressed;
    } else {
        return fs::path(input).extension() == string(".gz");
    }
}

//int partition(long* input, int start, int end) {
//  int pivot = input[end];
//
//  while (start < end) {
//      while (input[start] < pivot)
//          start++;
//
//      while (input[end] > pivot)
//          end--;
//
//      if (input[start] == input[end])
//          start++;
//      else if (start < end) {
//          int tmp = input[start];
//          input[start] = input[end];
//          input[end] = tmp;
//      }
//  }
//
//  return end;
//}

max_stars_repo_name: tangina-sultana/knowledgegraph

max_issues_repo_name: tangina-sultana/knowledgegraph

max_forks_repo_name: tangina-sultana/knowledgegraph


text:
#pragma once
/*!	\file	real.hpp
	\brief	Real classes declarations.
	\author	Garth Santor
	\date	2021-10-29
	\copyright	Garth Santor, Trinh Han

=============================================================
Declarations of the Real classes derived from Operand.  Includes
the subclasses Pi and E.

=============================================================
Revision History
-------------------------------------------------------------

Version 2021.10.26
	C++ 20 validated

Version 2019.11.05
	C++ 17 cleanup

Version 2014.10.29
	C++ 11 refactor.
	Switched value_type to boost::multiprecision::cpp_dec_float_100

Version 2012.11.13
	C++ 11 cleanup

Version 2010.11.09
	Switched boost::shared_ptr<> to std::shared_ptr<>.
	Added TOKEN_PTR_TYPE macro.

Version 2009.11.25
	Alpha release.

=============================================================

Copyright Garth Santor/Trinh Han

The copyright to the computer program(s) herein
is the property of Garth Santor/Trinh Han, Canada.
The program(s) may be used and/or copied only with
the written permission of Garth Santor/Trinh Han
or in accordance with the terms and conditions
stipulated in the agreement/contract under which
the program(s) have been supplied.
=============================================================*/

#include <ee/operand.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/math/constants/constants.hpp>

/*! Real number token. */
class Real : public Operand {
public:
	DEF_POINTER_TYPE(Real)
	using value_type = boost::multiprecision::number<boost::multiprecision::cpp_dec_float<1000, int32_t, void>>;
private:
	value_type	value_;
public:
	Real(value_type value = value_type(0)) : value_(value) { }
	[[nodiscard]] value_type	value() const { return value_; };
	[[nodiscard]] string_type	str() const override;
};

/*! Pi constant token. */
class Pi : public Real {
public:
	Pi() : Real(boost::math::constants::pi<value_type>()) { }
};

/*! Euler constant token. */
class E : public Real {
public:
	E() : Real(boost::math::constants::e<value_type>()) { }
};

max_stars_repo_name: ygor-rezende/Expression-Evaluator

max_issues_repo_name: ygor-rezende/Expression-Evaluator

max_forks_repo_name: ygor-rezende/Expression-Evaluator


text:
#include "CampaignRevenueVectorStreamTransformer.hpp"
#include "MVLogger.hpp"
#include "LargeStringStream.hpp"
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/bind.hpp>
#include <set>

namespace
{
	const std::string DELIMITER( "," );
	const std::string REQUIRED_HEADER_FIELD_1( "Campaign ID" );
	const std::string REQUIRED_HEADER_FIELD_2( "Rate Type" );
	const std::string REQUIRED_HEADER_FIELD_3( "Inventory Event" );
	const std::string REQUIRED_HEADER_FIELD_4( "Rate" );

	typedef struct campaign_revenue_vector
	{
		bool bNonEmpty; // This bool helps us omit output rows where there is no data.
		std::string strUnitType;
		std::string strCostPerUnit;
		std::string strClickHardTarget;
		std::string strActionHardTarget;
		std::string strIndexedImpressions;
		std::string strIndexedClicks;
		std::string strIndexedActions;
		std::string strCostPerImpression;
		std::string strCostPerClick;
		std::string strCostPerAction;
	} CampaignRevenueVectorDataStruct;

	// This function validates the header (ensuring that the required header fields exist), and then returns
	// a map providing the index within the vector to the required header name.
	std::map< std::string, int > ObtainHeaderIndexMap( std::vector< std::string > vectorHeaderFields )
	{
		std::map< std::string, int > mapFieldToVectorIndex;

		std::set<std::string> setRequiredHeaderFields;
		setRequiredHeaderFields.insert( REQUIRED_HEADER_FIELD_1 );
		setRequiredHeaderFields.insert( REQUIRED_HEADER_FIELD_2 );
		setRequiredHeaderFields.insert( REQUIRED_HEADER_FIELD_3 );
		setRequiredHeaderFields.insert( REQUIRED_HEADER_FIELD_4 );

		// trim all the strings in the header field vector
		std::for_each( vectorHeaderFields.begin(), vectorHeaderFields.end(),
			boost::bind( &boost::trim<std::string>, _1, std::locale() ) );

		// check to see if we can find all the required header fields
		std::set<std::string >::const_iterator setIter = setRequiredHeaderFields.begin();
	    for( ; setIter != setRequiredHeaderFields.end(); ++setIter )
	    {
			std::vector<std::string >::const_iterator vecIter;
			vecIter = find( vectorHeaderFields.begin(), vectorHeaderFields.end(), *setIter );

			// a required header field was not found, throw an exception
			if( vecIter == vectorHeaderFields.end() )
			{
				MV_THROW( CampaignRevenueVectorStreamTransformerException, "Invalid Input Data, Missing Required Header Field" );
			}

			// add this found field and its corresponding vector index to our map
			mapFieldToVectorIndex[ *vecIter ] = (vecIter - vectorHeaderFields.begin());
		}

		return mapFieldToVectorIndex;
	}

	// This simply sets a string value if it is empty, otherwise throws an exception due to a duplicate key.
	void UpdateStringValueIfEmpty( std::string &i_rStringToUpdate, std::string i_strValue )
	{
		if( !i_rStringToUpdate.empty() )
		{
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Invalid Input Data, Duplicate {Campaign ID,Rate Type,InventoryType} Key Found" );
		}

		i_rStringToUpdate = i_strValue;
	}

	// This returns a pointer to either a newly inserted CRV Struct or one that already exists for the given Campaign ID
	CampaignRevenueVectorDataStruct * ObtainCRVStructToUpdate( std::map< int, CampaignRevenueVectorDataStruct > & i_rCRVMap,
		std::string i_strCampaignID )
	{
		int nCampaignID = atoi(i_strCampaignID.c_str());
		std::map< int, CampaignRevenueVectorDataStruct >::iterator iter;

		iter = i_rCRVMap.find(nCampaignID);

		CampaignRevenueVectorDataStruct emptyCRVStruct;
		emptyCRVStruct.bNonEmpty = false;

		// Add campaign to the map
		if( iter == i_rCRVMap.end() )
		{
			return &(i_rCRVMap.insert( std::pair<int,CampaignRevenueVectorDataStruct>(nCampaignID, emptyCRVStruct) ).first->second);
		}
		// Update existing campaign in the map
		else
		{
			return &(iter->second);
		}
	}

	// This updates the map that contains all of the transformed data that will eventually be produced with pre-transformed
	// input from the current data row.  The map is from a Campaign ID to the rest of the CRV data structure.  This
	// also validates the information in the input data row.
	void UpdateCRVMap( std::map< int, CampaignRevenueVectorDataStruct > & i_rCRVMap, std::string i_strCampaignID,
		std::string i_strRateType, std::string i_strInventoryEvent, std::string i_strRate )
	{
		// check for missing values
		if( i_strCampaignID.empty() )
		{
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Missing Data, Campaign ID" );
		}
		else if( i_strRateType.empty() )
		{
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Missing Data, Rate Type" );
		}
		else if( i_strInventoryEvent.empty() )
		{
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Missing Data, Inventory Event" );
		}
		else if( i_strRate.empty() )
		{
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Missing Data, Rate" );
		}

		// check for invalid inventory type here, so that below we can assume that we have one of the three valid types
		if( i_strInventoryEvent != "I" && i_strInventoryEvent != "C" && i_strInventoryEvent != "A" )
		{
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Invalid Input Data, Inventory Event must be one of I,C,A" );
		}

		CampaignRevenueVectorDataStruct *pCRVStructToUpdate = ObtainCRVStructToUpdate( i_rCRVMap, i_strCampaignID );

		if( i_strRateType == "R" )
		{
			pCRVStructToUpdate->bNonEmpty = true;

			if( !pCRVStructToUpdate->strUnitType.empty() )
			{
				// there is already a Rate Type R for this campaign, update if necessary based on the conflict
				// resolution rules:
				//
				// 1. If there is single positive value - that is used, and the corresponding inventory event is used as the unit type.
				// 2. If there are multiple positive values then prefer the Rate associated with the 'A' type over the Rate associated
				// with the 'C' type and prefer the Rate associated with the 'C' type over the Rate associated with the 'I' type and
				// the corresponding inventory event is used as the unit type.

				double fExistingCostPerUnit = atof(pCRVStructToUpdate->strCostPerUnit.c_str());
				double fCurrentRate = atof(i_strRate.c_str());

				// if not empty, positive values always trump non-positives
				if( fExistingCostPerUnit <= 0 && fCurrentRate > 0 )
				{
					pCRVStructToUpdate->strUnitType = i_strInventoryEvent;
					pCRVStructToUpdate->strCostPerUnit = i_strRate;
				}
				// otherwise, we must prioritize based on A > C > I
				else
				{
					// this check should work since A, C, I priority ordering is alphabetical (smaller values trump larger ones)
					if( i_strInventoryEvent[0] < pCRVStructToUpdate->strUnitType[0] )
					{
						pCRVStructToUpdate->strUnitType = i_strInventoryEvent;
						pCRVStructToUpdate->strCostPerUnit = i_strRate;
					}
				}
			}
			// No conflict, just update
			else
			{
				pCRVStructToUpdate->strUnitType = i_strInventoryEvent;
				pCRVStructToUpdate->strCostPerUnit = i_strRate;
			}

			// Update the rest of the CRV Struct
			if( i_strInventoryEvent == "I" )
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strCostPerImpression, i_strRate );
			}
			else if( i_strInventoryEvent == "C" )
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strCostPerClick, i_strRate );
			}
			else
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strCostPerAction, i_strRate );
			}
		}
		else if( i_strRateType == "T" )
		{
			pCRVStructToUpdate->bNonEmpty = true;

			if( i_strInventoryEvent == "I" )
			{
				MV_THROW( CampaignRevenueVectorStreamTransformerException, "Invalid Input Data, Rate Type T not valid with Inventory Type I" );
			}
			else if( i_strInventoryEvent == "C" )
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strClickHardTarget, i_strRate );
			}
			else
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strActionHardTarget, i_strRate );
			}
		}
		else if( i_strRateType == "X" )
		{
			pCRVStructToUpdate->bNonEmpty = true;

			if( i_strInventoryEvent == "I" )
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strIndexedImpressions, i_strRate );
			}
			else if( i_strInventoryEvent == "C" )
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strIndexedClicks, i_strRate );
			}
			else
			{
				UpdateStringValueIfEmpty( pCRVStructToUpdate->strIndexedActions, i_strRate );
			}
		}
		else if( i_strRateType == "E" )
		{
			// do nothing here other than check to see that the Inventory Event is A
			if( i_strInventoryEvent != "A" )
			{
				MV_THROW( CampaignRevenueVectorStreamTransformerException, "Invalid Input Data, Rate Type E only valid with Inventory Type A" );
			}
		}
		else if( i_strRateType != "O" )
		{
			// unrecognized Rate Type
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Invalid Input Data, Rate Type must be one of R,O,T,X,E" );
		}
	}
}

CampaignRevenueVectorStreamTransformer::CampaignRevenueVectorStreamTransformer()
{
}

CampaignRevenueVectorStreamTransformer::~CampaignRevenueVectorStreamTransformer()
{
}

boost::shared_ptr< std::istream > CampaignRevenueVectorStreamTransformer::TransformInput( boost::shared_ptr< std::istream > i_pInputStream, const std::map< std::string, std::string >& i_rParameters )
{
	std::large_stringstream* pRawResult = new std::large_stringstream();
	boost::shared_ptr< std::istream > pResult( pRawResult );

	std::map< int, CampaignRevenueVectorDataStruct > mapCRV; // maps Campaign ID to the CampaignRevenueVector data

	// form the output header
	std::string outputHeader = "campaign_id,unit_type,cost_per_unit,click_hard_target,action_hard_target,indexed_impressions," \
		"indexed_clicks,indexed_actions,cost_per_impression,cost_per_click,cost_per_action";
	MVLOGGER( "root.lib.DataProxy.DataProxyClient.StreamTransformers.CampaignRevenueVector.TransformCampaignRevenueVector.OutputHeader",
		"Output format will be: '" << outputHeader << "'" );

	// read a line from the input to get the input header
	std::string inputHeader;
	std::getline( *i_pInputStream, inputHeader );
	std::vector< std::string > vectorHeaderFields;
	boost::iter_split( vectorHeaderFields, inputHeader, boost::first_finder(DELIMITER) );

	size_t nNumHeaderFields = vectorHeaderFields.size();

	std::map< std::string, int > mapHeaderFieldToIndex = ObtainHeaderIndexMap( vectorHeaderFields );

	int nCampaignIDIndex = mapHeaderFieldToIndex[REQUIRED_HEADER_FIELD_1];
	int nRateTypeIDIndex = mapHeaderFieldToIndex[REQUIRED_HEADER_FIELD_2];
	int nInventoryEventIndex = mapHeaderFieldToIndex[REQUIRED_HEADER_FIELD_3];
	int nRateIndex = mapHeaderFieldToIndex[REQUIRED_HEADER_FIELD_4];

	// output the header
	*pRawResult << outputHeader << std::endl;

	// Now, we process each data row
	while( i_pInputStream->peek() != EOF )
	{
		std::string inputRow;
		std::getline( *i_pInputStream, inputRow );
		std::vector< std::string > vectorFields;
		boost::iter_split( vectorFields, inputRow, boost::first_finder(DELIMITER) );

		if( vectorFields.size() != nNumHeaderFields )
		{
			MV_THROW( CampaignRevenueVectorStreamTransformerException, "Invalid Input Data, Number of Row Fields and Header Fields Are Mismatched" );
		}

		std::string strCampaignID = vectorFields[nCampaignIDIndex];
		std::string strRateType = vectorFields[nRateTypeIDIndex];
		std::string strInventoryEvent = vectorFields[nInventoryEventIndex];
		std::string strRate = vectorFields[nRateIndex];

		UpdateCRVMap( mapCRV, strCampaignID, strRateType, strInventoryEvent, strRate );
	}

	std::map<int, CampaignRevenueVectorDataStruct>::const_iterator iter;

	for( iter = mapCRV.begin(); iter != mapCRV.end(); ++iter )
	{
		int nCurrentCampaignID = iter->first;
		CampaignRevenueVectorDataStruct currentCRV = iter->second;

		if( currentCRV.bNonEmpty )
		{
			*pRawResult << nCurrentCampaignID << DELIMITER
					 << currentCRV.strUnitType << DELIMITER
					 << currentCRV.strCostPerUnit << DELIMITER
					 << currentCRV.strClickHardTarget << DELIMITER
					 << currentCRV.strActionHardTarget << DELIMITER
					 << currentCRV.strIndexedImpressions << DELIMITER
					 << currentCRV.strIndexedClicks << DELIMITER
					 << currentCRV.strIndexedActions << DELIMITER
					 << currentCRV.strCostPerImpression << DELIMITER
					 << currentCRV.strCostPerClick << DELIMITER
					 << currentCRV.strCostPerAction << std::endl;
		}
	}

	pRawResult->flush();
	return pResult;
}

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary