text:
#include <iostream>
#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <pcl/point_cloud.h>
#include <pcl/conversions.h>
#include <pcl/common/common_headers.h>
#include <pcl/common/angles.h>
#include <pcl/common/transforms.h>
#include <pcl/ModelCoefficients.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/passthrough.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/filters/radius_outlier_removal.h>
#include <pcl/keypoints/harris_3d.h>

#include <pcl/point_types.h>
#include <pcl/console/time.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/normal_3d_omp.h>
#include <pcl/segmentation/conditional_euclidean_clustering.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/segmentation/region_growing.h>
#include <cstdlib>
#include <ctime>
#include <string>
#include <boost/make_shared.hpp>
#include <boost/assign/std/vector.hpp>
#include <pcl/surface/convex_hull.h>
#include <pcl/surface/concave_hull.h>
#include <pcl/filters/project_inliers.h>
#include <obstacle_processor/processed_box_data.h>
#include <obstacle_processor/processed_cylinder_data.h>
#include <obstacle_processor/processed_undefined_data.h>
#include <obstacle_processor/processed_wall_like_object_data.h>
#include <math.h>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <pcl/geometry/eigen.h>
#include <pcl/sample_consensus/ransac.h>
#include <fstream>
#include <pcl/surface/gp3.h>

using namespace boost::assign;
using namespace std;
using namespace obstacle_processor;
using namespace Eigen;
using namespace pcl;
typedef PointXYZRGB Point;
typedef Normal Normal;
typedef sensor_msgs::PointCloud2 PCloud2;
typedef ModelCoefficients MCoef;
typedef PointIndices PIndices;
double plane_seg_thresh, outliers_thresh, cluster_tol, point_min_z, point_max_z, dist_weight, thresh2, tolerance, dist_weight_circ, dist_thresh_circ, height_thresh_min, height_thresh_max;
float min_z, max_z, voxel_size, alfa;
bool rviz_out, cmd_out, transform_to_base_link;
string pc_topic;
int min_cluster, max_cluster, iter, meanK, K_search, iter2, iter_circ;
tf::TransformListener* tf_listener;

class ObstacleProcessor
{
  ros::NodeHandle nh;
  ros::Subscriber cloud_sub_;
  ros::Publisher pub_clusters, pub_cylinder, pub_front_plane, pub_projected, pub_projected_flat, pub_hull, pub_box, pub_undefined, pub_wall_like_object, pub_floor, pub_cloud, pub_top_planes, pub_backup;
  processed_box_data box_data;
  processed_cylinder_data cylinder_data;
  processed_undefined_data undefined_data;
  processed_wall_like_object_data wall_like_object_data;
  pcl::console::TicToc tt;

public:
  vector<double> transformToBaseLink(bool transform_to_base_link, Vector3f& centroid, geometry_msgs::PointStamped kinect_centroid)
  {
    if (transform_to_base_link)
    {
      geometry_msgs::PointStamped base_link_centroid;
      kinect_centroid.point.x = centroid(0);
      kinect_centroid.point.y = centroid(1);
      kinect_centroid.point.z = centroid(2);
      try
      {
        tf_listener->transformPoint("base_link", ros::Time(0), kinect_centroid, "camera", base_link_centroid);
      }
      catch (tf::TransformException& exc)
      {
        ROS_ERROR("    ! Error during transformation");
        cerr << exc.what() << endl;
      }
      centroid << base_link_centroid.point.x, base_link_centroid.point.y, base_link_centroid.point.z;
    }
    vector<double> centroid_vector(centroid.data(), centroid.data() + centroid.rows() * centroid.cols());
    return centroid_vector;
  }

  vector<double> projectAndProcess(bool hasTopPlaneParallel, bool& isCylinder, PointCloud<Point>::Ptr cloud,
                                   MCoef::Ptr projection_plane, PointCloud<Point>::Ptr project_all,
                                   PointCloud<Point>::Ptr project_flat_all,
                                   PointCloud<Point>::Ptr convex_hull_all, Vector3f& centroid)
  {
    vector<double> dims(2,0);
    PointCloud<Point>::Ptr cloud_project(new PointCloud<Point>), cloud_project_flat(new PointCloud<Point>),
                           cloud_convex_hull(new PointCloud<Point>);
    Point search_point;
    KdTreeFLANN<Point> search_tree;
    ProjectInliers<Point> project;
    ConvexHull<Point> convex_hull;
    Quaternionf quart;
    Affine3f transform(Affine3f::Identity());
    Matrix3f rot, inv_rot;
    Vector3f projection_plane_normal(projection_plane->values[0], projection_plane->values[1], projection_plane->values[2]);
    double min_area = 100000000;
    double area = 0;

    if (cmd_out) {
      ROS_INFO("Creating hull object for top box plane...");
      tt.tic();
    }
    // Project top plane into 2d, using floor model coefficients
    project.setModelType(SACMODEL_PLANE);
    project.setInputCloud(cloud);
    project.setModelCoefficients(projection_plane);
    project.filter(*cloud_project);
    if (rviz_out) *project_all += *cloud_project;

    // Rotate plane so that normal vector of projection is collinear with XY plane's normal
    quart.setFromTwoVectors(projection_plane_normal, Vector3f::UnitZ());
    Matrix3f plane_rot = quart.toRotationMatrix();
    Matrix3f inv_plane_rot = plane_rot.inverse();
    transform.rotate(plane_rot);
    transformPointCloud(*cloud_project, *cloud_project_flat, transform);
    if (rviz_out) *project_flat_all += *cloud_project_flat;

    // Find the convex hull
    convex_hull.setInputCloud(cloud_project_flat->makeShared());
    convex_hull.setDimension(2);
    convex_hull.reconstruct(*cloud_convex_hull);
    int top_plane_hull_points = cloud_convex_hull->points.size();
    if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

    // Searching for the minimum area for a given set of points to find dimensions
    if (cmd_out) {
      ROS_INFO("Searching the minimum area for a given set of points...");
      tt.tic();
      ROS_INFO("Top plane cloud hull: %3d", top_plane_hull_points);
    }
    for (size_t i=0; i<top_plane_hull_points; i++)
    {
      // For each pair of hull points, determine the angle to rotate coordinate axes
      PointCloud<Point>::Ptr transformed_hull(new PointCloud<Point>);

      double delta_y = cloud_convex_hull->points[(i+1)%top_plane_hull_points].y - cloud_convex_hull->points[i].y;
      double delta_x = cloud_convex_hull->points[(i+1)%top_plane_hull_points].x - cloud_convex_hull->points[i].x;
      double delta_l = sqrt((delta_x*delta_x) + (delta_y*delta_y));
      double sin_fi = delta_y / delta_l;
      double cos_fi = delta_x / delta_l;

      // Build rotation matrix from change of basis
      rot(0,0) = cos_fi;
      rot(0,1) = sin_fi;
      rot(0,2) = 0.0;
      rot(1,0) = -sin_fi;
      rot(1,1) = cos_fi;
      rot(1,2) = 0.0;
      rot(2,0) = 0.0;
      rot(2,1) = 0.0;
      rot(2,2) = 1.0;

      inv_rot = rot.inverse();

      double x_min = 1000.0;
      double x_max = -1000.0;
      double y_min = 1000.0;
      double y_max = -1000.0;
      for (size_t i=0; i<top_plane_hull_points; i++)
      {
        Point p;
        p.getVector3fMap() = rot * cloud_convex_hull->points[i].getVector3fMap();
        transformed_hull->push_back(p);
        if (p.x < x_min) x_min = p.x;
        if (p.x > x_max) x_max = p.x;
        if (p.y < y_min) y_min = p.y;
        if (p.y > y_max) y_max = p.y;
      }
      area = fabs(x_max-x_min)*fabs(y_max-y_min);

      if (area < min_area)
      {
        // raw_box_data[0] length of top plane
        dims[0] = fabs(x_max - x_min);

        // raw_box_data[1] width of top plane
        dims[1] = fabs(y_max - y_min);

        // Check an assumption on a long edge
        if (dims[0] < dims[1])
        {
          double temp = dims[0];
          dims[0] = dims[1];
          dims[1] = temp;
        }

        // Find the center of a box in kinect frame
        if (hasTopPlaneParallel)
        {
          centroid(0) = (x_max+x_min) / 2.0;
          centroid(1) = (y_max+y_min) / 2.0;
          centroid(2) = transformed_hull->points[0].z;
          centroid = inv_rot * centroid;
        }
        min_area = area;
      }
    }

    if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());
    search_tree.setInputCloud(cloud_convex_hull);
    double rad = (dims[1] + dims[0]) / 4;
    double dist;
    double devs;

    if (hasTopPlaneParallel)
    {
      search_point.x = centroid(0);
      search_point.y = centroid(1);
      search_point.z = centroid(2);
    }
    else
    {
      computeCentroid(*cloud_convex_hull, search_point);
    }
    search_point.r = 255;
    search_point.g = 0;
    search_point.b = 0;

    for (int i=0; i<top_plane_hull_points; i++)
    {
      dist = euclideanDistance(cloud_convex_hull->points[i], search_point);
      devs += fabs(rad - dist);
    }
    devs /= top_plane_hull_points;
    cloud_convex_hull->points.push_back(search_point);
    centroid = inv_plane_rot * centroid;
    if (rviz_out) *convex_hull_all += *cloud_convex_hull;
    isCylinder = devs < 0.01? true: false;
    return dims;
  }

  vector<double> findMinMax3D(PointCloud<Point>::Ptr cloud_in)
  {
    vector<double> data(6,0);
    data[0] = 1000;
    data[1] = 1000;
    data[2] = 1000;
    data[3] = -1000;
    data[4] = -1000;
    data[5] = -1000;

    for (size_t i=0; i < cloud_in->points.size(); i++)
    {
      if(cloud_in->points[i].x <= data[0])
        data[0] = cloud_in->points[i].x;
      else if(cloud_in->points[i].y <= data[1] )
        data[1] = cloud_in->points[i].y;
      else if(cloud_in->points[i].z <= data[2] )
        data[2] = cloud_in->points[i].z;
      else if(cloud_in->points[i].x >= data[3] )
        data[3] = cloud_in->points[i].x;
      else if(cloud_in->points[i].y >= data[4] )
        data[4] = cloud_in->points[i].y;
      else if(cloud_in->points[i].z >= data[5] )
        data[5] = cloud_in->points[i].z;
    }
    return data;
  }

  float angleBetweenPlanes(Vector3f plane1_norm, Vector3f plane2_norm)
  {
    float angle = acos(plane1_norm.dot(plane2_norm)) / M_PI*180;
    if (cmd_out) ROS_INFO("# Plane 1 normal: (%3.3f, %3.3f, %3.3f)\n# Plane 2 normal: (%3.3f, %3.3f, %3.3f)\n# Angle between planes: %3.3f deg", plane1_norm(0), plane1_norm(1), plane1_norm(2), plane2_norm(0), plane2_norm(1), plane2_norm(2), angle);
    return angle;
  }

  bool isPerpendicularToPlane(bool wallDetection, Vector3f plane1_norm, Vector3f plane2_norm, float& angleY)
  {
    Vector3f Y_vector(0.0, -1.0, 0.0);
    plane1_norm(2) = fabs(plane1_norm(2));
    plane2_norm(2) = fabs(plane2_norm(2));
    float angle = this->angleBetweenPlanes(plane1_norm, plane2_norm);
    float angleY_temp = this->angleBetweenPlanes(plane1_norm, Y_vector);
    angleY = wallDetection? angleY_temp: (angleY_temp < 45? angleY_temp: fabs(90 - angleY_temp));
    if (((fabs(angle) < 90 + tolerance) && (fabs(angle) > 90 - tolerance)))
      return true;
    return false;
  }

  bool isTopParallelPlane(MCoef::Ptr plane1, MCoef::Ptr plane2, double height, double z_dim)
  {
    Vector3f plane1_normal(plane1->values[0], plane1->values[1], plane1->values[2]);
    Vector3f plane2_normal(plane2->values[0], plane2->values[1], plane2->values[2]);
    float angle = this->angleBetweenPlanes(plane1_normal, plane2_normal);
    bool result = false;
    if (fabs(angle) < tolerance || fabs(angle-180) < tolerance)
    {
      result = true;
      if (height / z_dim < 0.5)
      {
        result = false;
      }
    }
    return result;
  }

  void setParams(const ros::NodeHandle& nh)
  {
    nh.getParam("/obstacle_processor_node/min_z", min_z);
    nh.getParam("/obstacle_processor_node/max_z", max_z);
    nh.getParam("/obstacle_processor_node/iter", iter);
    nh.getParam("/obstacle_processor_node/voxel_size", voxel_size);
    nh.getParam("/obstacle_processor_node/cluster_tol", cluster_tol);
    nh.getParam("/obstacle_processor_node/min_cluster", min_cluster);
    nh.getParam("/obstacle_processor_node/max_cluster", max_cluster);
    nh.getParam("/obstacle_processor_node/plane_seg_thresh", plane_seg_thresh);
    nh.getParam("/obstacle_processor_node/outliers_thresh", outliers_thresh);
    nh.getParam("/obstacle_processor_node/meanK", meanK);
    nh.getParam("/obstacle_processor_node/point_min_z", point_min_z);
    nh.getParam("/obstacle_processor_node/point_max_z", point_max_z);
    nh.getParam("/obstacle_processor_node/dist_weight", dist_weight);
    nh.getParam("/obstacle_processor_node/iter2", iter2);
    nh.getParam("/obstacle_processor_node/thresh2", thresh2);
    nh.getParam("/obstacle_processor_node/tolerance", tolerance);
    nh.getParam("/obstacle_processor_node/K_search", K_search);
    nh.getParam("/obstacle_processor_node/rviz_out", rviz_out);
    nh.getParam("/obstacle_processor_node/cmd_out", cmd_out);
    nh.getParam("/obstacle_processor_node/transform_to_base_link", transform_to_base_link);
    nh.getParam("/obstacle_processor_node/dist_weight_circ", dist_weight_circ);
    nh.getParam("/obstacle_processor_node/dist_thresh_circ", dist_thresh_circ);
    nh.getParam("/obstacle_processor_node/height_thresh_min", height_thresh_min);
    nh.getParam("/obstacle_processor_node/height_thresh_max", height_thresh_max);
    nh.getParam("/obstacle_processor_node/iter_circ", iter_circ);
  }
  ObstacleProcessor(ros::NodeHandle nh_): nh(nh_)
  {
    nh.getParam("/obstacle_processor_node/pc_topic", pc_topic);
    cloud_sub_=nh.subscribe(pc_topic, 1, &ObstacleProcessor::cloud_cb, this);
    pub_clusters = nh.advertise<PCloud2>("/clusters", 1);
    pub_backup = nh.advertise<PCloud2>("/clusters_backup", 1);
    pub_cloud = nh.advertise<PCloud2>("/cloud", 1);
    pub_top_planes = nh.advertise<PCloud2>("/top_planes", 1);
    pub_projected = nh.advertise<PCloud2>("/projected_planes", 1);
    pub_projected_flat = nh.advertise<PCloud2>("/projected_planes_flat", 1);
    pub_hull = nh.advertise<PCloud2>("/convex_hulls", 1);
    pub_front_plane = nh.advertise<PCloud2>("/front_planes", 1);
    pub_box = nh.advertise<processed_box_data>("/box_data", 1, true);
    pub_cylinder = nh.advertise<processed_cylinder_data>("/cylinder_data", 1, true);
    pub_undefined = nh.advertise<processed_undefined_data>("/undefined_data", 1, true);
    pub_wall_like_object = nh.advertise<processed_wall_like_object_data>("/wall_like_object_data", 1, true);
    pub_floor = nh.advertise<PCloud2>("/cloud_floor", 1, true);
  }

  void cloud_cb(const sensor_msgs::PointCloud2ConstPtr &input)
  {
    this->setParams(nh);
    PointCloud<Point>::Ptr cloud_input(new PointCloud<Point>), cloud_downsampled(new PointCloud<Point>),
                           cloud_processed(new PointCloud<Point>), cloud_filtered(new PointCloud<Point>),
                           cloud_clusters(new PointCloud<Point>), cloud_floor(new PointCloud<Point>),
                           cloud_top_plane_all(new PointCloud<Point>), front_plane_all(new PointCloud<Point>),
                           top_plane_project_all(new PointCloud<Point>), top_plane_project_flat_all(new PointCloud<Point>),
                           top_plane_convex_hull_all(new PointCloud<Point>), cloud_cluster_all(new PointCloud<Point>);
    PCloud2::Ptr cloud_out(new PCloud2), backup_out(new PCloud2), clusters_out(new PCloud2), top_planes_out(new PCloud2),
                 projected_out(new PCloud2), projected_flat_out(new PCloud2), convex_hull_out(new PCloud2),
                 front_planes_out(new PCloud2), cloud_floor_out(new PCloud2);
    geometry_msgs::PointStamped kinect_centroid;
    kinect_centroid.header.frame_id = "camera";
    kinect_centroid.header.stamp = input->header.stamp;
    MCoef::Ptr coefficients_floor(new MCoef);
    PIndices::Ptr inliers_floor(new PIndices);
    SACSegmentation<Point> seg;
    SACSegmentationFromNormals<Point, Normal> seg_norm;
    ExtractIndices<Normal> extract_normals;
    StatisticalOutlierRemoval<Point> sor;
    NormalEstimationOMP<Point, Normal> ne;
    search::KdTree<Point>::Ptr tree(new search::KdTree<Point>);
    PassThrough<Point> pass_filter;
    VoxelGrid<Point> voxel;
    ExtractIndices<Point> extract;
    vector<PIndices> clusters_indices;
    EuclideanClusterExtraction<Point> ec_ext;
    Quaternionf quart;
    Affine3f transform_glob(Affine3f::Identity());
    Affine3f trans_glob(Affine3f::Identity());
    srand((int)time(0));

    fromROSMsg(*input, *cloud_input);

    if (cmd_out) {
      ROS_INFO("Pass filtering...");
      tt.tic();
    }
    pass_filter.setInputCloud(cloud_input);
    pass_filter.setFilterFieldName("z");
    pass_filter.setFilterLimits(min_z, max_z);
    pass_filter.filter(*cloud_filtered);
    if (cmd_out) ROS_INFO("Done: %3.3f ms, points = %3d", tt.toc(), cloud_filtered->points.size());

    if (cmd_out) {
      ROS_INFO("Downsampling...");
      tt.tic();
    }
    voxel.setInputCloud(cloud_filtered);
    voxel.setLeafSize(voxel_size, voxel_size, voxel_size);
    voxel.setDownsampleAllData(true);
    voxel.filter(*cloud_downsampled);
    if (cmd_out) ROS_INFO("Done: %3.3f ms, points = %3d", tt.toc(), cloud_downsampled->points.size());

    if (cmd_out) {
      ROS_INFO("Starting ground plane segmentation...");
      tt.tic();
    }
    seg.setModelType(SACMODEL_PERPENDICULAR_PLANE);
    seg.setMethodType(SAC_RANSAC);
    seg.setOptimizeCoefficients(true);
    seg.setMaxIterations(iter);
    seg.setEpsAngle(7.5 * (M_PI / 180));
    seg.setAxis(Vector3f(0.0, cos(alfa), sin(alfa)));
    seg.setDistanceThreshold(plane_seg_thresh);
    seg.setInputCloud(cloud_downsampled);
    seg.segment(*inliers_floor, *coefficients_floor);

    if (inliers_floor->indices.size() == 0)
    {
      ROS_ERROR("Couldn't estimate a planar model from dataset!");
      return;
    }
    Vector3f floor_normal(coefficients_floor->values[0], coefficients_floor->values[1], coefficients_floor->values[2]);
    if (cmd_out) {
      ROS_INFO("Ground plane's normal: (%3.3f, %3.3f, %3.3f)", floor_normal[0], floor_normal[1], floor_normal[2]);
      ROS_INFO("Ground plane's size: %3d", inliers_floor->indices.size());
    }

    // Extract the planar inliers from input
    extract.setInputCloud(cloud_downsampled);
    extract.setIndices(inliers_floor);
    extract.setNegative(false);
    extract.filter(*cloud_floor);
    extract.setNegative(true);
    extract.filter(*cloud_processed);
    if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

    // Rotate so that z axis is colinear with floor normal
    if (cmd_out) {
      ROS_INFO("Rotating and translating point clouds...");
      tt.tic();
    }
    quart.setFromTwoVectors(floor_normal, Vector3f::UnitZ());
    Matrix3f rot_glob = quart.toRotationMatrix();
    Matrix3f rot_glob_inv = rot_glob.inverse();
    transform_glob.rotate(rot_glob);
    transformPointCloud(*cloud_processed, *cloud_processed, transform_glob);
    transformPointCloud(*cloud_floor, *cloud_floor, transform_glob);

    // Translate so that an origin is situated on a floor plane
    trans_glob.translation() << 0.0, 0.0, -1*(cloud_floor->points[0].z);
    transformPointCloud(*cloud_processed, *cloud_processed, trans_glob);
    transformPointCloud(*cloud_floor, *cloud_floor, trans_glob);
    if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

    if (cmd_out) {
      ROS_INFO("Obtaining model coef of ground plane...");
      tt.tic();
    }
    seg.setModelType(pcl::SACMODEL_PLANE);
    seg.setMethodType(pcl::SAC_RANSAC);
    seg.setMaxIterations(iter);
    seg.setDistanceThreshold(plane_seg_thresh);
    seg.setInputCloud(cloud_floor);
    seg.segment(*inliers_floor, *coefficients_floor);
    Vector4f floor_coef(coefficients_floor->values[0], coefficients_floor->values[1], coefficients_floor->values[2], coefficients_floor->values[3]);
    floor_normal << coefficients_floor->values[0], coefficients_floor->values[1], coefficients_floor->values[2];
    if (cmd_out) ROS_INFO("Ground plane's coef after transformation: (%3.3f, %3.3f, %3.3f, %3.3f)", floor_normal(0), floor_normal(0), floor_normal(0), coefficients_floor->values[3]);
    if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

    // Creating the KdTree object for the search method of the extraction
    if (cmd_out) {
      ROS_INFO("Starting cluster extraction...");
      tt.tic();
    }
    ec_ext.setClusterTolerance(cluster_tol);
    ec_ext.setMinClusterSize(min_cluster);
    ec_ext.setMaxClusterSize(max_cluster);
    ec_ext.setSearchMethod(tree);
    ec_ext.setInputCloud(cloud_processed);
    ec_ext.extract(clusters_indices);
    if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

    for (vector<PIndices>::const_iterator it = clusters_indices.begin(); it != clusters_indices.end(); ++it)
    {
      search::KdTree<Point>::Ptr cluster_tree(new search::KdTree<Point>);
      PointCloud<Normal>::Ptr cluster_normals(new PointCloud<Normal>), normals_copy(new PointCloud<Normal>),
                              normals_copy_new(new PointCloud<Normal>);
      PointCloud<Point>::Ptr cluster_copy(new PointCloud<Point>), cluster_copy_new(new PointCloud<Point>),
                             cloud_top_plane(new PointCloud<Point>), front_plane(new PointCloud<Point>),
                             cloud_cluster(new PointCloud<Point>), cloud_cluster_backup(new PointCloud<Point>);
      MCoef::Ptr coef_top_plane(new MCoef), coef_front_plane(new MCoef);
      PIndices::Ptr inliers_top_plane(new PIndices), inliers_front_plane(new PIndices);
      vector<double> cluster_dims, dims(2,0), centroid_vector;
      Vector3f centroid(0, 0, 0), front_plane_norm(0.0, 0.0, 0.0), z_vector(0.0, 0.0, 1.0);
      double h = 0;
      float fi = 0;
      double *height = &h;
      float *frontAngle = &fi;
      bool isWallLike = false, hasPlane = true, isCylinder = false, hasParallelPlaneToFloor = false;
      double pointsCount = 0.0, pointsCountHeight = 0.0, cluster_size;
      int r = rand()%255, g = rand()%255, b = rand()%255;

      if (cmd_out) {
        ROS_INFO("Applying filter to a cluster...");
        tt.tic();
      }
      for (vector<int>::const_iterator point_it = it->indices.begin(); point_it != it->indices.end(); ++point_it)
      {
        Point p = cloud_processed->points[*point_it];
        if ((p.z > point_min_z) & (p.z < point_max_z)) ++pointsCount;
        if ((p.z > height_thresh_min) & (p.z < height_thresh_max)) ++pointsCountHeight;
        cloud_cluster->points.push_back(p);
        if (rviz_out) {
          p.r = r;
          p.g = g;
          p.b = b;
          cloud_cluster_backup->points.push_back(p);
        }
      }
      cluster_size = cloud_cluster->points.size();
      if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

      if (cluster_size > 12000)
      {
        isWallLike = true;
      }
      else
      {
        if (((pointsCount / cluster_size) < 0.25) && ((pointsCountHeight / cluster_size) > 0.025))
        {
          // Remove outliers
          if (cmd_out) {
            ROS_INFO("  Cluster size = %3.3f", cluster_size);
            ROS_INFO("Removing outliers...");
            tt.tic();
          }
          sor.setInputCloud(cloud_cluster);
          sor.setMeanK(meanK);
          sor.setStddevMulThresh(outliers_thresh);
          sor.filter(*cloud_cluster);
          cluster_size = cloud_cluster->points.size();
          if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

          // Normal estimation
          if (rviz_out) *cloud_cluster_all += *cloud_cluster_backup;
          if (cmd_out) {
            ROS_INFO("Estimating cluster normals...");
            tt.tic();
          }
          ne.setSearchMethod(cluster_tree);
          ne.setInputCloud(cloud_cluster);
          ne.setKSearch(K_search);
          ne.compute(*cluster_normals);
          if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

          // Copying clouds
          if (cmd_out) {
            ROS_INFO("Creating shallow copies of cluster and normal clouds...");
            tt.tic();
          }
          copyPointCloud(*cloud_cluster, *cluster_copy);
          copyPointCloud(*cloud_cluster, *cluster_copy_new);
          copyPointCloud(*cluster_normals, *normals_copy);
          copyPointCloud(*cluster_normals, *normals_copy_new);
          if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());

          // Checking the wall-like condition
          if (cluster_size > 2500)
          {
            if (cmd_out) {
              ROS_INFO("Checking the wall-like object condition...");
              tt.tic();
            }
            seg_norm.setModelType(SACMODEL_NORMAL_PLANE);
            seg_norm.setNormalDistanceWeight(dist_weight);
            seg_norm.setMethodType(SAC_RANSAC);
            seg_norm.setMaxIterations(iter2);
            seg_norm.setDistanceThreshold(thresh2);
            seg_norm.setInputCloud(cloud_cluster);
            seg_norm.setInputNormals(cluster_normals);
            seg_norm.segment(*inliers_front_plane, *coef_front_plane);
            extract.setInputCloud(cloud_cluster);
            extract.setIndices(inliers_front_plane);
            extract.setNegative(false);
            extract.filter(*front_plane);
            if (front_plane->points.size() / cluster_size > 0.65)
            {
              front_plane_norm << coef_front_plane->values[0], coef_front_plane->values[1], coef_front_plane->values[2];
              if (this->isPerpendicularToPlane(true, front_plane_norm, z_vector, *frontAngle))
              {
                if (cmd_out) ROS_INFO("Found frontal plane: (%3.3f, %3.3f, %3.3f, %3.3f), size = %3d", front_plane_norm(0), front_plane_norm(1), front_plane_norm(2), coef_front_plane->values[3], front_plane->points.size());
                isWallLike = true;
              }
            }
            else
            {
              if (cmd_out) ROS_INFO("No frontal plane found...");
            }
            if (cmd_out) ROS_INFO("Done: %3.3f ms", tt.toc());
          }
        }
        else
        {
          continue;
        }
      }

      if (!isWallLike)
      {
        cluster_dims = this->findMinMax3D(cloud_cluster);
        double x_dim = fabs(cluster_dims[3] - cluster_dims[0]);
        double z_dim = fabs(cluster_dims[5] - cluster_dims[2]);
        if (cmd_out) {
          ROS_INFO("Searching for a top plane... ");
          tt.tic();
        }
        // Searching for a top plane
        do
        {
          seg_norm.setModelType(SACMODEL_NORMAL_PLANE);
          seg_norm.setNormalDistanceWeight(dist_weight);
          seg_norm.setMethodType(SAC_RANSAC);
          seg_norm.setMaxIterations(iter2);
          seg_norm.setDistanceThreshold(thresh2);
          seg_norm.setOptimizeCoefficients(true);
          seg_norm.setInputCloud(cloud_cluster);
          seg_norm.setInputNormals(cluster_normals);
          seg_norm.segment(*inliers_top_plane, *coef_top_plane);

          extract.setInputCloud(cloud_cluster);
          extract.setIndices(inliers_top_plane);
          extract.setNegative(false);
          extract.filter(*cloud_top_plane);
          // Check if top plane was found
          if (cloud_top_plane->points.size() / cluster_size > 0.05)
          {
            // Estimate height
            double height_temp;
            double size = cloud_top_plane->points.size();
            double sum_height = 0;
            Point p;
            for (size_t i=0; i < size; i++)
            {
              p = cloud_top_plane->points[i];
              height_temp = 1000;
              height_temp = pointToPlaneDistance(p, floor_coef);
              sum_height += height_temp;
            }
            *height = sum_height / size;
            // Check whether found plane is parallel to the floor
            if (this->isTopParallelPlane(coefficients_floor, coef_top_plane, *height, z_dim))
            {
              hasPlane = false;
              hasParallelPlaneToFloor = true;
              if (rviz_out) *cloud_top_plane_all += *cloud_top_plane;
            }
            else {
              extract.setNegative(true);
              extract.filter(*cloud_cluster);
              extract_normals.setNegative(true);
              extract_normals.setInputCloud(cluster_normals);
              extract_normals.setIndices(inliers_top_plane);
              extract_normals.filter(*cluster_normals);
            }
          }
          else
          {
            if (cmd_out) ROS_INFO("Cannot find plane parallel to the ground plane");
            hasPlane = false;
          }
        } while(hasPlane);
        if (cmd_out) ROS_INFO("Done: %3.2f ms.", tt.toc());

        if (hasParallelPlaneToFloor)
        {
          dims = this->projectAndProcess(hasParallelPlaneToFloor, isCylinder, cloud_top_plane, coefficients_floor, top_plane_project_all, top_plane_project_flat_all, top_plane_convex_hull_all, centroid);
          centroid(2) = *height / 2.0;
          centroid = rot_glob_inv * (centroid - trans_glob.translation());
          centroid_vector = this->transformToBaseLink(transform_to_base_link, centroid, kinect_centroid);

          if (isCylinder)
          {
            hasPlane = true;
            double ratio;
            double area = *height * dims[1];
            double ratio_med = 0;
            int count = 0;
            double area_ratio = area / ((2 * area) + (dims[1] * dims[1]));
            if (cmd_out) {
              ROS_INFO("Searching for planes perpendicular to the ground plane... ");
              tt.tic();
            }
            do
            {
              seg_norm.setModelType(SACMODEL_NORMAL_PLANE);
              seg_norm.setNormalDistanceWeight(dist_weight_circ);
              seg_norm.setMethodType(SAC_RANSAC);
              seg_norm.setMaxIterations(iter_circ);
              seg_norm.setDistanceThreshold(dist_thresh_circ);
              seg_norm.setInputCloud(cluster_copy_new);
              seg_norm.setInputNormals(normals_copy_new);
              seg_norm.segment(*inliers_front_plane, *coef_front_plane);
              extract.setInputCloud(cluster_copy_new);
              extract.setIndices(inliers_front_plane);
              extract.setNegative(false);
              extract.filter(*front_plane);
              ratio = ((double) front_plane->points.size()) / cluster_size;
              if (ratio > (0.15 * area_ratio))
              {
                front_plane_norm << coef_front_plane->values[0], coef_front_plane->values[1], coef_front_plane->values[2];
                if (this->isPerpendicularToPlane(false, front_plane_norm, z_vector, *frontAngle))
                {
                  count++;
                  ratio_med += ratio;
                }
                extract.setNegative(true);
                extract.filter(*cluster_copy_new);
                extract_normals.setNegative(true);
                extract_normals.setInputCloud(normals_copy_new);
                extract_normals.setIndices(inliers_front_plane);
                extract_normals.filter(*normals_copy_new);
              }
              else
              {
                if (cmd_out) ROS_INFO("Cannot find plane perpendicular to the ground plane");
                hasPlane = false;
              }
            } while(hasPlane);
            if (cmd_out) ROS_INFO("Done: %3.2f ms.", tt.toc());
            ratio_med /= count;
            ratio_med /= area_ratio;
            if (ratio_med > 0)
              isCylinder = ratio_med < 0.45? true: false;
          }

          if (isCylinder)
          {
            if (cmd_out) ROS_INFO("# Found CYLINDRICAL OBJECT:\n# Radius = %3.3f\n# height = %3.3f\n# Centroid: (%3.3f, %3.3f, %3.3f)", (dims[1]+dims[0]) / 4, *height, centroid(0), centroid(1), centroid(2));
            cylinder_data.radius = (dims[1]+dims[0]) / 4;
            cylinder_data.height = *height;
            cylinder_data.centroid = centroid_vector;
            pub_cylinder.publish(cylinder_data);
          }
          else
          {
            hasPlane = true;
            if (cmd_out) {
              ROS_INFO("Searching for a frontal plane... ");
              tt.tic();
            }
            // Searching for a frontal plane
            do
            {
              seg_norm.setModelType(SACMODEL_NORMAL_PLANE);
              seg_norm.setNormalDistanceWeight(dist_weight);
              seg_norm.setMethodType(SAC_RANSAC);
              seg_norm.setMaxIterations(iter2);
              seg_norm.setDistanceThreshold(thresh2);
              seg_norm.setInputCloud(cluster_copy);
              seg_norm.setInputNormals(normals_copy);
              seg_norm.segment(*inliers_front_plane, *coef_front_plane);
              extract.setInputCloud(cluster_copy);
              extract.setIndices(inliers_front_plane);
              extract.setNegative(false);
              extract.filter(*front_plane);
              if (front_plane->points.size() / cluster_size > 0.1)
              {
                front_plane_norm << coef_front_plane->values[0], coef_front_plane->values[1], coef_front_plane->values[2];
                if (this->isPerpendicularToPlane(false, front_plane_norm, z_vector, *frontAngle))
                {
                  hasPlane = false;
                  if (rviz_out) *front_plane_all += *front_plane;
                }
                else
                {
                  extract.setNegative(true);
                  extract.filter(*cluster_copy);
                  extract_normals.setNegative(true);
                  extract_normals.setInputCloud(normals_copy);
                  extract_normals.setIndices(inliers_front_plane);
                  extract_normals.filter(*normals_copy);
                }
              }
              else
              {
                if (cmd_out) ROS_INFO("No frontal plane found...");
                hasPlane = false;
              }

            } while (hasPlane);
            if (cmd_out) {
              ROS_INFO("Done: %3.2f ms.", tt.toc());
              ROS_INFO("Found BOX-LIKE OBJECT:\n# Length = %3.3f\n# Width = %3.3f\n# Height = %3.3f"
                       "\n# Frontal angle = %3.3f\n# Centroid: (%3.3f, %3.3f, %3.3f)",
                       dims[0], dims[1], *height, *frontAngle, centroid(0), centroid(1), centroid(2));
            }
            box_data.length = dims[0];
            box_data.width = dims[1];
            box_data.height = *height;
            box_data.angle = *frontAngle;
            box_data.centroid = centroid_vector;
            pub_box.publish(box_data);
          }
        }
        else
        {
          // Estimate object's profile
          vector<double> profile(2,0);
          Point p;
          profile += (x_dim, z_dim);
          dims = this->projectAndProcess(hasParallelPlaneToFloor, isCylinder, cluster_copy, coefficients_floor, top_plane_project_all, top_plane_project_flat_all, top_plane_convex_hull_all, centroid);
          computeCentroid(*cluster_copy, p);
          centroid << p.x, p.y, p.z;
          centroid = rot_glob_inv * (centroid - trans_glob.translation());
          centroid_vector = this->transformToBaseLink(transform_to_base_link, centroid, kinect_centroid);
          if (!isCylinder)
          {
            if (cmd_out) ROS_INFO("# Found UNDEFINED OBJECT:\n# Profile = (%3.3f, %3.3f)"
                                  "\n# Length = %3.3f\n# Width = %3.3f\n# Centroid: (%3.3f, %3.3f, %3.3f)",
                                  x_dim, z_dim, dims[0], dims[1], centroid(0), centroid(1), centroid(2));
            undefined_data.profile = profile;
            undefined_data.centroid = centroid_vector;
            undefined_data.length = dims[0];
            undefined_data.width = dims[1];
            pub_undefined.publish(undefined_data);
          }
          else
          {
            if (cmd_out) ROS_INFO("Found CYLINDRICAL OBJECT\n# Radius = %3.3f\n# Height = %3.3f"
                                  "\n# Centroid: (%3.3f, %3.3f, %3.3f)",
                                  (dims[1]+dims[0]) / 4, *height, centroid(0), centroid(1), centroid(2));
            cylinder_data.radius = (dims[1]+dims[0]) / 4;
            cylinder_data.height = z_dim;
            cylinder_data.centroid = centroid_vector;
            pub_cylinder.publish(cylinder_data);
          }
        }
      }
      else
      {
        Point p;
        cluster_dims = this->findMinMax3D(front_plane->makeShared());
        double x_dim = fabs(cluster_dims[3] - cluster_dims[0]);
        double y_dim = fabs(cluster_dims[4] - cluster_dims[1]);
        double z_dim = fabs(cluster_dims[5] - cluster_dims[2]);
        double length = *frontAngle > 45? y_dim / cos(fabs(90 - *frontAngle) * (M_PI / 180)):
                                          x_dim / cos(*frontAngle * (M_PI / 180));
        double width = x_dim < y_dim? x_dim: y_dim;
        computeCentroid(*front_plane, p);
        centroid << p.x, p.y, p.z;
        centroid = rot_glob_inv * (centroid - trans_glob.translation());
        centroid_vector = this->transformToBaseLink(transform_to_base_link, centroid, kinect_centroid);
        if (cmd_out) ROS_INFO("# Found WALL-LIKE OBJECT:\n# Length = %3.3f\n# Width = %3.3f\n# Height = %3.3f"
                              "\n# Frontal angle = %3.3f\n# Centroid: (%3.3f, %3.3f, %3.3f)",
                              length, width, z_dim, *frontAngle, centroid(0), centroid(1), centroid(2));
        wall_like_object_data.centroid = centroid_vector;
        wall_like_object_data.length = length;
        wall_like_object_data.width = width;
        wall_like_object_data.height = z_dim;
        wall_like_object_data.angle = *frontAngle;
        pub_wall_like_object.publish(wall_like_object_data);
      }
      *cloud_clusters += *cloud_cluster;
      if (cmd_out) cerr << "\n---------------------------------------\n";
    }
    if (rviz_out)
    {
      if (cmd_out) {
        ROS_INFO("Publishing additional topics...");
        tt.tic();
      }
      string topic = "kinect2_ir_optical_frame";
      toROSMsg(*cloud_clusters, *clusters_out);
      toROSMsg(*top_plane_project_all, *projected_out);
      toROSMsg(*top_plane_project_flat_all, *projected_flat_out);
      toROSMsg(*top_plane_convex_hull_all, *convex_hull_out);
      toROSMsg(*cloud_floor, *cloud_floor_out);
      toROSMsg(*cloud_top_plane_all, *top_planes_out);
      toROSMsg(*cloud_processed, *cloud_out);
      toROSMsg(*cloud_cluster_all, *backup_out);
      toROSMsg(*front_plane_all, *front_planes_out);

      cloud_floor_out->header.frame_id = topic;
      backup_out->header.frame_id = topic;
      clusters_out->header.frame_id = topic;
      top_planes_out->header.frame_id = topic;
      cloud_out->header.frame_id = topic;
      projected_out->header.frame_id = topic;
      projected_flat_out->header.frame_id = topic;
      convex_hull_out->header.frame_id = topic;
      front_planes_out->header.frame_id = topic;

      pub_floor.publish(cloud_floor_out);
      pub_backup.publish(backup_out);
      pub_cloud.publish(cloud_out);
      pub_clusters.publish(clusters_out);
      pub_top_planes.publish(top_planes_out);
      pub_hull.publish(convex_hull_out);
      pub_projected.publish(projected_out);
      pub_projected_flat.publish(projected_flat_out);
      pub_front_plane.publish(front_planes_out);
      if (cmd_out) {
        ROS_INFO("Done: %3.3f ms", tt.toc());
        cerr << "\n***************************************\n";
      }
    }
  }

};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "obstacle_processor_node");
  fstream f;
  string line;
  tf::TransformListener lr(ros::Duration(10));
  tf_listener = &lr;
  alfa = 0;
  f.open("cal_data.dat");
  if (!f.is_open())
  {
    cerr << "Error while reading a calibration data!\n";
    return -1;
  }
  getline(f, line);
  alfa = atof(line.c_str());
  f.close();
  if (alfa == 0) return -1;
  ros::NodeHandle nh;
  cerr << "Read successfully from cal data = " << alfa << "\n";
  ObstacleProcessor cs(nh);
  ros::spin();
}


text:
#include "../benchmarks_general.h"

#include <Fastor/Fastor.h>
#include <Eigen/Core>
#include <Eigen/Dense>

template<typename T, size_t M, size_t N>
void benchmark_inverse_eigen() {
    using namespace Eigen;
    Matrix<T,M,N,RowMajor> a;
    a.setConstant(3);
    Eigen::Matrix<T,N,M,RowMajor> c = a.inverse();
    benchmarks_general::unused(c);
}

template<typename T, size_t M, size_t N>
void benchmark_inverse_fastor() {
    using namespace Fastor;
    Tensor<T,M,N> a(3);
    Tensor<T,N,M> c = inverse(a);
    benchmarks_general::unused(c);
}

template<typename T, size_t M>
void benchmark_run() {

    using benchmarks_general::println;
    using benchmarks_general::rtimeit;

    println("Testing size (M, N)", M, M,'\n');

    double etime = rtimeit(static_cast<void (*)()>(&benchmark_inverse_eigen<T,M,M>));
    double ftime = rtimeit(static_cast<void (*)()>(&benchmark_inverse_fastor<T,M,M>));

    println("Elapsed time -> Eigen, Fastor\n", etime, ftime,'\n');
}

template<size_t step, size_t from, size_t to>
struct benchmark_generate {
    template<typename T>
    static inline void generate() {
        benchmark_run<T,from>();
        benchmark_generate<step,from+step,to>::template generate<T>();
    }
};
template<size_t step, size_t from>
struct benchmark_generate<step,from,from> {
    template<typename T>
    static inline void generate() {
        benchmark_run<T,from>();
    }
};

int main () {

#ifdef RUN_SINGLE
    benchmark_generate<8,8,128>::template generate<float>();
#else
    benchmark_generate<8,8,128>::template generate<double>();
#endif

    return 0;
}

ext: cpp

max_stars_repo_name: mablanchard/Fastor

max_issues_repo_name: manodeep/Fastor

max_forks_repo_name: manodeep/Fastor


text:
/* Copyright (c) 2014 Vinícius dos Santos Oliveira

   Distributed under the Boost Software License, Version 1.0. (See accompanying
   file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */

#ifndef BOOST_HTTP_POLYMORPHIC_SERVER_SOCKET_HPP
#define BOOST_HTTP_POLYMORPHIC_SERVER_SOCKET_HPP

#include <cstdint>

#include <string>

#include <boost/utility/string_ref.hpp>

#include <boost/http/polymorphic_socket_base.hpp>

namespace boost {
namespace http {

class polymorphic_server_socket: public polymorphic_socket_base
{
public:
    typedef std::string method_server_type;
    typedef std::string path_server_type;
    typedef boost::string_ref reason_phrase_server_type;

    // ### ABI-stable interface ###
    virtual bool write_response_native_stream() const = 0;
    virtual void async_read_request(std::string &method, std::string &path,
                                    message &message,
                                    callback_type handler) = 0;
    virtual void async_write_response(std::uint_fast16_t status_code,
                                      const boost::string_ref &reason_phrase,
                                      const message &message,
                                      callback_type handler) = 0;
    virtual void async_write_response_continue(callback_type handler) = 0;
    virtual void async_write_response_metadata(std::uint_fast16_t status_code,
                                               const boost::string_ref
                                               &reason_phrase,
                                               const message &message,
                                               callback_type handler) = 0;

    virtual ~polymorphic_server_socket() = default;

    // ### wrappers for the ASIO's extensible model ###
    template<class CompletionToken>
    typename asio::async_result<
        typename asio::handler_type<CompletionToken,
                                    void(system::error_code)>::type>::type
    async_read_request(std::string &method, std::string &path,
                       message &message, CompletionToken &&token);

    template<class CompletionToken>
    typename asio::async_result<
        typename asio::handler_type<CompletionToken,
                                    void(system::error_code)>::type>::type
    async_write_response(std::uint_fast16_t status_code,
                         const boost::string_ref &reason_phrase,
                         const message &message, CompletionToken &&token);

    template<class CompletionToken>
    typename asio::async_result<
        typename asio::handler_type<CompletionToken,
                                    void(system::error_code)>::type>::type
    async_write_response_continue(CompletionToken &&token);

    template<class CompletionToken>
    typename asio::async_result<
        typename asio::handler_type<CompletionToken,
                                    void(system::error_code)>::type>::type
    async_write_response_metadata(std::uint_fast16_t status_code,
                                  const boost::string_ref &reason_phrase,
                                  const message &message,
                                  CompletionToken &&token);
};

} // namespace http
} // namespace boost

#include "polymorphic_server_socket-inl.hpp"

#endif // BOOST_HTTP_POLYMORPHIC_SERVER_SOCKET_HPP

ext: hpp


text:
// FILE NAME:       $HeadURL: svn+ssh://svn.cm.aol.com/advertising/adlearn/gen1/trunk/lib/cpp/DataProxy/test/ParameterTranslatorTest.cpp $
//
// REVISION:        $Revision: 305155 $
//
// COPYRIGHT:       (c) 2006 Advertising.com All Rights Reserved.
//
// LAST UPDATED:    $Date: 2014-10-02 20:00:32 -0400 (Thu, 02 Oct 2014) $
// UPDATED BY:      $Author: sstrick $

#include "ShellExecutor.hpp"
#include "ParameterTranslatorTest.hpp"
#include "FileUtilities.hpp"
#include "TempDirectory.hpp"
#include "ProxyUtilities.hpp"
#include "ProxyTestHelpers.hpp"
#include "AssertThrowWithMessage.hpp"
#include "MVUtility.hpp"
#include "UniqueIdGenerator.hpp"
#include "DateTime.hpp"
#include <fstream>
#include <boost/regex.hpp>
#include <boost/lexical_cast.hpp>

CPPUNIT_TEST_SUITE_REGISTRATION( ParameterTranslatorTest );
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION( ParameterTranslatorTest, "ParameterTranslatorTest" );

ParameterTranslatorTest::ParameterTranslatorTest()
:	m_pTempDir(NULL)
{
}

ParameterTranslatorTest::~ParameterTranslatorTest()
{
}

void ParameterTranslatorTest::setUp()
{
	XMLPlatformUtils::Initialize();
	m_pTempDir.reset( new TempDirectory() );
}

void ParameterTranslatorTest::tearDown()
{
	//XMLPlatformUtils::Terminate();
	m_pTempDir.reset( NULL );
}

void ParameterTranslatorTest::testGarbageChildren()
{
	std::stringstream xmlContents;
	xmlContents << "<Whatever >"
				<< " <TranslateParameters>"
				<< "  <garbage />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	std::vector<xercesc::DOMNode*> nodes;
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), XMLUtilitiesException, ".*/XMLUtilities.cpp:\\d+: Found invalid child: garbage in node: TranslateParameters" );

	xmlContents.str("");
	xmlContents << "<Whatever >"
				<< " <TranslateParameters garbage=\"true\">"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), XMLUtilitiesException,
		".*/XMLUtilities.cpp:\\d+: Found invalid attribute: garbage in node: TranslateParameters" );

	xmlContents.str("");
	xmlContents << "<Whatever >"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"name1\" garbage=\"true\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), XMLUtilitiesException,
		".*/XMLUtilities.cpp:\\d+: Found invalid attribute: garbage in node: Parameter" );
}

void ParameterTranslatorTest::testNoTranslate()
{
	std::stringstream xmlContents;
	xmlContents << "<Whatever />";
	std::vector<xercesc::DOMNode*> nodes;
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator( *nodes[0] );

	std::map< std::string, std::string > inputParameters;
	std::map< std::string, std::string > translatedParameters;

	// to be sure it no longer exists after translation
	translatedParameters["oldParam"] = "value0";

	inputParameters["param1"] = "value1";
	inputParameters["param2"] = "value2";
	inputParameters["param3"] = "value3";
	inputParameters["param4"] = "value4";
	inputParameters["param5"] = "value5";

	CPPUNIT_ASSERT_NO_THROW( translator.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( size_t(5), translatedParameters.size() );
	std::map< std::string, std::string >::const_iterator iter = translatedParameters.begin();
	CPPUNIT_ASSERT( iter != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string("param1"), iter->first );
	CPPUNIT_ASSERT_EQUAL( std::string("value1"), iter->second );
	++iter;
	CPPUNIT_ASSERT( iter != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string("param2"), iter->first );
	CPPUNIT_ASSERT_EQUAL( std::string("value2"), iter->second );
	++iter;
	CPPUNIT_ASSERT( iter != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string("param3"), iter->first );
	CPPUNIT_ASSERT_EQUAL( std::string("value3"), iter->second );
	++iter;
	CPPUNIT_ASSERT( iter != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string("param4"), iter->first );
	CPPUNIT_ASSERT_EQUAL( std::string("value4"), iter->second );
	++iter;
	CPPUNIT_ASSERT( iter != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string("param5"), iter->first );
	CPPUNIT_ASSERT_EQUAL( std::string("value5"), iter->second );
	++iter;
	CPPUNIT_ASSERT( iter == translatedParameters.end() );
}

void ParameterTranslatorTest::testTranslate()
{
	std::stringstream xmlContents;
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"aaaa\" translatedName=\"param11\" />"	// aaaa will be renamed to param11
				<< "  <Parameter name=\"zzzz\" translatedName=\"param11\" />"	// zzzz will be renamed to param11
				<< "  <Parameter name=\"s1\" translatedName=\"silenced01\" />"	// s1 will be renamed to silenced01, which is silenced
				<< "  <Parameter name=\"param01\" translatedName=\"renamed01\" />"	// param01 will be renamed to renamed01
				<< "  <Parameter name=\"param02\" />"								// param02 will be removed
				<< "  <Parameter name=\"param03\" translatedName=\"renamed03\" />"	// param03 will be renamed to renamed03
				<< "  <Parameter name=\"renamed03\" valueTranslator=\"VALUE03_%v\" valueDefault=\"DEFAULT03\" />"	// renamed03 will be translated to VALUE03_<value> if it exists; otherwise defaulted to DEFAULT03
				<< "  <Parameter name=\"param04\" valueTranslator=\"`echo -n %v | sed 's/alu/ALU/' | sed 's/04/Four/'`\" />" // translated
				<< "  <Parameter name=\"missing01\" valueTranslator=\"`missingVal01`\"/>"	// will not be present so no translation
				<< "  <Parameter name=\"missing02\" valueTranslator=\"missingVal02\"/>"	// will not be present so no translation
				<< "  <Parameter name=\"param05\" valueDefault=\"`echo -n \\`value05\\``\" />" // how to have a default w/ backticks
				<< "  <Parameter name=\"param06\" valueDefault=\"default06\" />" // param06 defaults to default06
				<< "  <Parameter name=\"param07\" valueDefault=\"default07\" />" // param07 defaults to default07
				<< "  <Parameter name=\"param08\" valueDefault=\"`echo -n default08`\" />" // param08 defaults to default08 (through expression)
				<< "  <Parameter name=\"param09\" valueOverride=\"override09\" />" // param09 overrides to override09
				<< "  <Parameter name=\"param10\" valueOverride=\"`echo -n override10`\" />" // param10 overrides to override10
				<< "  <Parameter name=\"silenced01\" />" // silence01 will be removed
				<< " </TranslateParameters>"
				<< "</Whatever>";
	std::vector<xercesc::DOMNode*> nodes;
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator( *nodes[0] );

	std::map< std::string, std::string > inputParameters;
	std::map< std::string, std::string > translatedParameters;

	CPPUNIT_ASSERT_NO_THROW( translator.Translate( inputParameters, translatedParameters ) );
	std::map< std::string, std::string > expectedParameters;
	expectedParameters["renamed03"] = "DEFAULT03";
	expectedParameters["param05"] = "`value05`";
	expectedParameters["param06"] = "default06";
	expectedParameters["param07"] = "default07";
	expectedParameters["param08"] = "default08";
	expectedParameters["param09"] = "override09";
	expectedParameters["param10"] = "override10";
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	// to be sure it no longer exists after translation
	translatedParameters["oldParam"] = "value0";

	inputParameters["param01"] = "value01";
	inputParameters["param02"] = "value02";
	inputParameters["param03"] = "value03";
	inputParameters["param04"] = "value04";
	inputParameters["param06"] = "value06";
	inputParameters["param09"] = "value09";
	inputParameters["aaaa"] = "aaaaValue";
	inputParameters["zzzz"] = "zzzzValue";
	inputParameters["param11"] = "value11";
	inputParameters["s1"] = "shouldBeMissing01";

	CPPUNIT_ASSERT_NO_THROW( translator.Translate( inputParameters, translatedParameters ) );
	expectedParameters.clear();
	expectedParameters["renamed01"] = "value01";	// param01 renamed to renamed01
	expectedParameters["renamed03"] = "VALUE03_value03";	// param03 renamed to renamed03 and value translated to literal
	expectedParameters["param04"] = "vALUeFour";	// value translated via expression
	expectedParameters["param05"] = "`value05`";	// value defaulted via expression
	expectedParameters["param06"] = "value06";		// value not defaulted since already provided
	expectedParameters["param07"] = "default07";	// value defaulted to literal
	expectedParameters["param08"] = "default08";	// value defaulted via expression
	expectedParameters["param09"] = "override09";	// value overriden to literal
	expectedParameters["param10"] = "override10";	// value overriden via expression
	expectedParameters["param11"] = "value11";		// value taken from the translate-to target, not from the source(s)
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );
}

void ParameterTranslatorTest::testTranslateDerived()
{
	// case 1: derivedParam will only be derived if it is not provided
	std::stringstream xmlContents;
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"sourceParam\" valueOverride=\"sourceParamValue\" />"
				<< "  <Parameter name=\"derivedParam\" valueSource=\"sourceParam\" valueTranslator=\"derived from: %v\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	std::vector<xercesc::DOMNode*> nodes;
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator1( *nodes[0] );

	std::map< std::string, std::string > inputParameters;
	std::map< std::string, std::string > translatedParameters;

	CPPUNIT_ASSERT_NO_THROW( translator1.Translate( inputParameters, translatedParameters ) );
	std::map< std::string, std::string > expectedParameters;
	expectedParameters["sourceParam"] = "sourceParamValue";
	expectedParameters["derivedParam"] = "derived from: sourceParamValue";
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	translatedParameters.clear();
	inputParameters["derivedParam"] = "originalValue";
	expectedParameters["derivedParam"] = "originalValue";
	CPPUNIT_ASSERT_NO_THROW( translator1.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	// case 1a: derivedParam will only be derived if it is not provided
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"derivedParam\" valueDefault=\"not present\" valueSource=\"sourceParam\" valueTranslator=\"derived from: %v\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator1a( *nodes[0] );

	inputParameters.clear();

	CPPUNIT_ASSERT_NO_THROW( translator1a.Translate( inputParameters, translatedParameters ) );
	expectedParameters.clear();
	expectedParameters["derivedParam"] = "not present";
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	translatedParameters.clear();
	inputParameters["sourceParam"] = "my source";
	expectedParameters["sourceParam"] = "my source";
	expectedParameters["derivedParam"] = "derived from: my source";
	CPPUNIT_ASSERT_NO_THROW( translator1a.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	// case 2: derivedParam will always use the derived value
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"sourceParam\" valueOverride=\"sourceParamValue\" />"
				<< "  <Parameter name=\"derivedParam\" valueSource=\"sourceParam\" valueOverride=\"`echo -n 'derived from: %v'`\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator2( *nodes[0] );

	inputParameters.clear();
	translatedParameters.clear();
	expectedParameters.clear();
	expectedParameters["sourceParam"] = "sourceParamValue";
	expectedParameters["derivedParam"] = "derived from: sourceParamValue";
	CPPUNIT_ASSERT_NO_THROW( translator2.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	translatedParameters.clear();
	inputParameters["derivedParam"] = "willNotAppear";
	CPPUNIT_ASSERT_NO_THROW( translator2.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	// case 3: derivedParam will not appear if its source doesn't appear
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"derivedParam\" valueSource=\"sourceParam\" valueOverride=\"derived from: %v\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator3( *nodes[0] );

	inputParameters.clear();
	translatedParameters.clear();
	expectedParameters.clear();
	CPPUNIT_ASSERT_NO_THROW( translator3.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"derivedParam\" valueSource=\"sourceParam\" valueTranslator=\"derived from: %v\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator4( *nodes[0] );

	inputParameters.clear();
	translatedParameters.clear();
	expectedParameters.clear();
	CPPUNIT_ASSERT_NO_THROW( translator4.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	// case 4: valueSource is several parameters (using dollar-substitution)
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"sourceParam1\" valueOverride=\"value1\" />"
				<< "  <Parameter name=\"sourceParam2\" valueOverride=\"value2\" />"
				<< "  <Parameter name=\"sourceParam3\" valueOverride=\"value3\" />"
				<< "  <Parameter name=\"derivedParam\" valueSource=\"*\" valueOverride=\"1: ${sourceParam1} 2: ${sourceParam2} 3: ${sourceParam3}\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator5( *nodes[0] );

	inputParameters.clear();
	translatedParameters.clear();
	expectedParameters.clear();
	expectedParameters["sourceParam1"] = "value1";
	expectedParameters["sourceParam2"] = "value2";
	expectedParameters["sourceParam3"] = "value3";
	expectedParameters["derivedParam"] = "1: value1 2: value2 3: value3";
	CPPUNIT_ASSERT_NO_THROW( translator5.Translate( inputParameters, translatedParameters ) );
	CPPUNIT_ASSERT_EQUAL( ProxyUtilities::ToString( expectedParameters ), ProxyUtilities::ToString( translatedParameters ) );

	// case 5: a parameter is referenced but not specified (with the multiple-sources flag only!)
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"sourceParam1\" valueOverride=\"value1\" />"
				//MISSING: << "  <Parameter name=\"sourceParam2\" valueOverride=\"value2\" />"
				<< "  <Parameter name=\"sourceParam3\" valueOverride=\"value3\" />"
				<< "  <Parameter name=\"derivedParam\" valueSource=\"*\" valueOverride=\"1: ${sourceParam1} 2: ${sourceParam2} 3: ${sourceParam3}\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator6( *nodes[0] );

	inputParameters.clear();
	translatedParameters.clear();
	expectedParameters.clear();
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( translator6.Translate( inputParameters, translatedParameters ), ProxyUtilitiesException,
		".*:\\d+: The following parameters are referenced, but are not specified in the parameters: sourceParam2" );
}

void ParameterTranslatorTest::testBadEvalCommand()
{
	// case 1: command doesn't exist
	std::stringstream xmlContents;
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param01\" valueOverride=\"`this_command_better_not_exist`\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	std::vector<xercesc::DOMNode*> nodes;
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator( *nodes[0] );

	std::map< std::string, std::string > inputParameters;
	std::map< std::string, std::string > translatedParameters;

	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( translator.Translate( inputParameters, translatedParameters ), ParameterTranslatorException,
		".*:\\d+: Evaluation command returned non-zero return code: 127\\. Command was: this_command_better_not_exist. Standard Error: .*" );

	// case 2: timeout
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters evalTimeout=\"-1\" >"	// essentially disallow eval commands
				<< "  <Parameter name=\"param01\" valueOverride=\"`sleep 2 && echo -n 10`\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator2( *nodes[0] );

	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( translator2.Translate( inputParameters, translatedParameters ), TimeoutException,
		".*\\.cpp:\\d+: The command 'sleep 2 && echo -n 10' failed to finish after -1 seconds\\. Wrote 0 bytes to standard input\\. Read 0 bytes from standard output\\. Read 0 bytes from standard error\\." );
}

void ParameterTranslatorTest::testIllegalConfig()
{
	std::stringstream xmlContents;
	std::vector<xercesc::DOMNode*> nodes;

	// case 1: Cannot supply name translation & value translation on the same node
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" translatedName=\"newParam1\" valueTranslator=\"newValue1\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: If translating the name of a parameter, cannot also provide a value manipulator.*" );

	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" translatedName=\"newParam1\" valueDefault=\"defaultValue1\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: If translating the name of a parameter, cannot also provide a value manipulator.*" );

	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" translatedName=\"newParam1\" valueOverride=\"overrideValue1\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: If translating the name of a parameter, cannot also provide a value manipulator.*" );

	// case 2: Cannot provide value translator & value override on the same node
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueTranslator=\"translatedParam1\" valueOverride=\"overrideValue1\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Cannot provide a value override and a value translator\\. Violating parameter: param1" );

	// case 3: Cannot provide value default & value override on the same node
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueDefault=\"defaultParam1\" valueOverride=\"overrideValue1\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Cannot provide a value override and a value default\\. Violating parameter: param1" );

	// case 4: Cannot provide name translation with more than one jump
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param2\" translatedName=\"param3\" />"
				<< "  <Parameter name=\"param1\" translatedName=\"param2\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Parameter name translations must not be chained. Violating chain: param1->param2->param3" );

	// case 5: Cannot provide same Parameter name on two lines
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" translatedName=\"param3\" />"
				<< "  <Parameter name=\"param1\" translatedName=\"param2\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Translation of parameter 'param1' is ambiguous" );

	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" translatedName=\"PARAM1\" />"
				<< "  <Parameter name=\"param1\" valueOverride=\"override1\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Translation of parameter 'param1' is ambiguous" );

	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueDefault=\"default1\" />"
				<< "  <Parameter name=\"param1\" valueOverride=\"override1\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Translation of parameter 'param1' is ambiguous" );

	// case 6: Cannot provide valueSource alone
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueSource=\"param3\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Parameters with a value source must have an override or translator supplied\\. Violating parameter: param1" );

	// case 7: Cannot provide valueSource with a name translator
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueSource=\"param3\" translatedName=\"newParam\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Cannot provide a value source when translating a parameter name\\. Violating parameter: param1" );

	// case 8: Cannot provide valueSource with a value default
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueSource=\"param3\" valueDefault=\"newParam\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Cannot provide a value source and a value default\\. Violating parameter: param1" );

	// case 9: Cannot make derived values derive from other derived values
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueSource=\"param3\" valueTranslator=\"%v\" />"
				<< "  <Parameter name=\"param2\" valueSource=\"param1\" valueTranslator=\"%v\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Cannot make values derive from other derived values. Violating parameters: param2 derives from param1, which derives from param3" );

	// case 9b: same, but with multiple-sources flag
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueSource=\"param2\" valueTranslator=\"%v\" />"
				<< "  <Parameter name=\"param2\" valueSource=\"*\" valueTranslator=\"p1: ${param1}, p3: ${param3}, p4: ${param4}\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Cannot make values derive from other derived values. Violating parameters: param1 derives from param2, which derives from param1, param3, param4" );

	// case 9c: same, but both are derived from multiple sources
	xmlContents.str("");
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"param1\" valueSource=\"*\" valueTranslator=\"p2: ${param2}\" />"
				<< "  <Parameter name=\"param2\" valueSource=\"*\" valueTranslator=\"p1: ${param1} p3: ${param3}\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	CPPUNIT_ASSERT_THROW_WITH_MESSAGE( ParameterTranslator translator( *nodes[0] ), ParameterTranslatorException,
		".*:\\d+: Cannot make values derive from other derived values. Violating parameters: param1 derives from param2, which derives from param1, param3" );
}

void ParameterTranslatorTest::testTranslateBuiltIn()
{
	std::stringstream xmlContents;
	xmlContents << "<Whatever>"
				<< " <TranslateParameters>"
				<< "  <Parameter name=\"host\" valueDefault=\"[hostname]\" />"
				<< "  <Parameter name=\"instance\" valueDefault=\"[instance]\" />"
				<< "  <Parameter name=\"unixtime1\" valueDefault=\"[datetime:%s]\" />"
				<< "  <Parameter name=\"unixtime2\" valueDefault=\"[datetime %s]\" />"
				<< "  <Parameter name=\"dm-datetime1\" valueDefault=\"[datetime]\" />"
				<< "  <Parameter name=\"dm-datetime2\" valueDefault=\"[datetime:%Y%m%dT%H%M%S]\" />"
				<< "  <Parameter name=\"unknown-datetime\" valueDefault=\"[datetime blah]\" />"
				<< "  <Parameter name=\"guid\" valueDefault=\"[guid]\" />"
				<< "  <Parameter name=\"pid\" valueDefault=\"[pid]\" />"
				<< "  <Parameter name=\"unkown1\" valueDefault=\"[cpu]\" />"
				<< "  <Parameter name=\"unkown2\" valueDefault=\"[mem]\" />"
				<< "  <Parameter name=\"md5value\" valueDefault=\"[md5]\" />"
				<< "  <Parameter name=\"bytecount\" valueDefault=\"[byteCount]\" />"
				<< " </TranslateParameters>"
				<< "</Whatever>";
	std::vector<xercesc::DOMNode*> nodes;
	ProxyTestHelpers::GetDataNodes( m_pTempDir->GetDirectoryName(), xmlContents.str(), "Whatever", nodes );
	CPPUNIT_ASSERT_EQUAL( size_t(1), nodes.size() );
	ParameterTranslator translator( *nodes[0] );

	std::map< std::string, std::string > inputParameters;
	std::map< std::string, std::string > translatedParameters;

	DateTime before;
	CPPUNIT_ASSERT_NO_THROW( translator.Translate( inputParameters, translatedParameters ) );
	DateTime after;
	CPPUNIT_ASSERT_EQUAL( size_t( 13 ), translatedParameters.size() );
	std::map< std::string, std::string >::const_iterator findIter;
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "host" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( MVUtility::GetHostName(), findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "instance" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "unixtime1" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT( before.GetFormattedString( "%s" ) <= findIter->second );
	CPPUNIT_ASSERT( after.GetFormattedString( "%s" ) >= findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "unixtime2" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT( before.GetFormattedString( "%s" ) <= findIter->second );
	CPPUNIT_ASSERT( after.GetFormattedString( "%s" ) >= findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "dm-datetime1" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT( before.GetFormattedString( "%Y%m%dT%H%M%S" ) <= findIter->second );
	CPPUNIT_ASSERT( after.GetFormattedString( "%Y%m%dT%H%M%S" ) >= findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "dm-datetime2" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT( before.GetFormattedString( "%Y%m%dT%H%M%S" ) <= findIter->second );
	CPPUNIT_ASSERT( after.GetFormattedString( "%Y%m%dT%H%M%S" ) >= findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "unknown-datetime" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string( "blah" ), findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "guid" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_MESSAGE( findIter->second, UniqueIdGenerator::IsValidUniqueIdString( findIter->second ) );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "pid" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( boost::lexical_cast< std::string >( ::getpid() ), findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "unkown1" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string( "cpu-unknown" ), findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "unkown2" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string( "mem-unknown" ), findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "md5value" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( std::string( "" ), findIter->second );

	std::string str("abcdefg");
	std::istringstream data(str);
	data.seekg(1);
	CPPUNIT_ASSERT_NO_THROW( translator.TranslateDelayedParameters( translatedParameters, data ) );
	CPPUNIT_ASSERT_EQUAL( std::streampos( 1 ), data.tellg() );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "md5value" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( MVUtility::GetMD5(str.substr(1,str.size()-1)), findIter->second );
	CPPUNIT_ASSERT( ( findIter = translatedParameters.find( "bytecount" ) ) != translatedParameters.end() );
	CPPUNIT_ASSERT_EQUAL( boost::lexical_cast< std::string >( str.size()-1 ), findIter->second );
}

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary


text:
// Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// 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)

//  VC++ 8.0 warns on usage of certain Standard Library and API functions that
//  can be cause buffer overruns or other possible security issues if misused.
//  See http://msdn.microsoft.com/msdnmag/issues/05/05/SafeCandC/default.aspx
//  But the wording of the warning is misleading and unsettling, there are no
//  portable alternative functions, and VC++ 8.0's own libraries use the
//  functions in question. So turn off the warnings.
#define _CRT_SECURE_NO_DEPRECATE
#define _SCL_SECURE_NO_DEPRECATE

// Boost.Bimap Example
//-----------------------------------------------------------------------------

#include <boost/config.hpp>

#include <iostream>

#include <boost/range/functions.hpp>
#include <boost/range/metafunctions.hpp>

//[ code_bimap_and_boost_range_functions

template< class ForwardReadableRange, class UnaryFunctor >
UnaryFunctor for_each(const ForwardReadableRange & r, UnaryFunctor func)
{
    typedef typename
    boost::range_const_iterator<ForwardReadableRange>::type const_iterator;

    for(const_iterator i= boost::begin(r), iend= boost::end(r); i!=iend; ++i )
    {
        func(*i);
    }

    return func;
}

template< class ForwardReadableRange, class Predicate >
typename boost::range_difference<ForwardReadableRange>::type
    count_if(const ForwardReadableRange & r, Predicate pred)
{
    typedef typename
    boost::range_const_iterator<ForwardReadableRange>::type const_iterator;

    typename boost::range_difference<ForwardReadableRange>::type c = 0;

    for( const_iterator i = boost::begin(r), iend = boost::end(r); i != iend; ++i )
    {
        if( pred(*i) ) ++c;
    }

    return c;
}
//]

#include <boost/bimap/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <boost/bimap/support/lambda.hpp>
#include <boost/bind.hpp>

using namespace boost::bimaps;
using namespace boost;

//[ code_bimap_and_boost_range

struct pair_printer
{
    pair_printer(std::ostream & o) : os(o) {}
    template< class Pair >
    void operator()(const Pair & p)
    {
        os << "(" << p.first << "," << p.second << ")";
    }
    private:
    std::ostream & os;
};

struct second_extractor
{
    template< class Pair >
    const typename Pair::second_type & operator()(const Pair & p)
    {
        return p.second;
    }
};

int main()
{
    typedef bimap< double, multiset_of<int> > bm_type;

    bm_type bm;
    bm.insert( bm_type::value_type(2.5 , 1) );
    bm.insert( bm_type::value_type(3.1 , 2) );
    //...
    bm.insert( bm_type::value_type(6.4 , 4) );
    bm.insert( bm_type::value_type(1.7 , 2) );

    // Print all the elements of the left map view

    for_each( bm.left, pair_printer(std::cout) );

    // Print a range of elements of the right map view

    for_each( bm.right.range( 2 <= _key, _key < 6 ), pair_printer(std::cout) );

    // Count the number of elements where the data is equal to 2 from a
    // range of elements of the left map view

    count_if( bm.left.range( 2.3 < _key, _key < 5.4 ),
              bind<int>( second_extractor(), _1 ) == 2 );

    return 0;
}
//]

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include <shift/parser/proto/proto.hpp>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/test/unit_test.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include <iostream>
#include <sstream>
#include "test.hpp"

using namespace shift;
using namespace shift::parser;
using namespace shift::parser::proto;

BOOST_AUTO_TEST_CASE(enum_valids)
{
  proto::document document;

  test_parser_and_ast(
    R"(
enum foo : var_uint_t
{
})",
    "enum_valids_1.pro2");

  while (test_parser_and_ast(document,
                             R"(
enum foo : var_uint_t
{
  a,
  b
})",
                             "enum_valids_2.pro2"))
  {
    const auto& enumerations = document.root().enumerations;
    BOOST_CHECK_EQUAL(enumerations.size(), 1);
    if (enumerations.size() != 1)
      break;
    (void)enumerations.find("foo");
    break;
  }

  while (test_parser_and_ast(document,
                             R"(
enum foo : var_uint_t
{
  a = 2,
  b = 4
})",
                             "enum_valids_3.pro2"))
  {
    break;
  }

  while (test_parser_and_ast(document,
                             R"(
enum foo : var_uint_t
{
  a = 2,
  b
})",
                             "enum_valids_4.pro2"))
  {
    break;
  }

  while (test_parser_and_ast(document,
                             R"(
enum foo : var_uint_t
{
  a,
  b = 4
})",
                             "enum_valids_5.pro2"))
  {
    break;
  }
}

BOOST_AUTO_TEST_CASE(enum_templates)
{
  test_parser_and_ast(
    R"(
enum foo<> : var_uint_t {})",
    "enum_templates_1.pro2",
    R"(enum_templates_1.pro2(2): error P1121: parse error: Expected list of template parameters.
enum foo<> : var_uint_t {}
         ^
)");

  test_parser_and_ast(
    R"(
enum foo<typename T> : T {})",
    "enum_templates_2.pro2");

  test_parser_and_ast(
    R"(
enum foo<var_uint_t N> : var_uint_t { value = N })",
    "enum_templates_3.pro2");

  test_parser_and_ast(
    R"(
enum foo<typename T, T N> : T { value = N })",
    "enum_templates_4.pro2");
}

BOOST_AUTO_TEST_CASE(enum_errors)
{
  test_parser_and_ast(
    R"(enum foo)", "enum_errors_1.pro2",
    R"(enum_errors_1.pro2(1): error P1102: parse error: Expected colon (':').
enum foo
        ^
)");
  test_parser_and_ast(
    R"(enum foo :)", "enum_errors_2.pro2",
    R"(enum_errors_2.pro2(1): error P1120: parse error: Expected type path.
enum foo :
          ^
)");

  test_parser_and_ast(
    R"(
enum foo : var_uint_t
{
  a,
  b,
})",
    "enum_errors_3.pro2",
    R"(enum_errors_3.pro2(5): error P1109: parse error: Expected closing curly bracket ('}').
  b,
   ^
)");

  test_parser_and_ast(
    R"(
enum foo : var_uint_t
{
  a = 1,
  b = 2,
})",
    "enum_errors_4.pro2",
    R"(enum_errors_4.pro2(5): error P1109: parse error: Expected closing curly bracket ('}').
  b = 2,
       ^
)");
}

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
// Copyright (C) 2011, 2012  Google Inc.
//
// This file is part of YouCompleteMe.
//
// YouCompleteMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// YouCompleteMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with YouCompleteMe.  If not, see <http://www.gnu.org/licenses/>.

#include "CandidateRepository.h"
#include "Candidate.h"
#include "standard.h"
#include "Utils.h"

#include <boost/thread/locks.hpp>
#include <boost/algorithm/string.hpp>
#include <locale>

#ifdef USE_CLANG_COMPLETER
#  include "ClangCompleter/CompletionData.h"
#endif // USE_CLANG_COMPLETER

namespace YouCompleteMe {

using boost::all;
using boost::is_print;

boost::mutex CandidateRepository::singleton_mutex_;
CandidateRepository *CandidateRepository::instance_ = NULL;

CandidateRepository &CandidateRepository::Instance() {
  boost::lock_guard< boost::mutex > locker( singleton_mutex_ );

  if ( !instance_ ) {
    static CandidateRepository repo;
    instance_ = &repo;
  }

  return *instance_;
}

int CandidateRepository::NumStoredCandidates() {
  boost::lock_guard< boost::mutex > locker( holder_mutex_ );
  return candidate_holder_.size();
}

std::vector< const Candidate * > CandidateRepository::GetCandidatesForStrings(
  const std::vector< std::string > &strings ) {
  std::vector< const Candidate * > candidates;
  candidates.reserve( strings.size() );

  {
    boost::lock_guard< boost::mutex > locker( holder_mutex_ );

    foreach ( const std::string & candidate_text, strings ) {
      const std::string &validated_candidate_text =
        all( candidate_text, is_print( std::locale::classic() ) ) ?
        candidate_text :
        empty_;

      const Candidate *&candidate = GetValueElseInsert(
                                      candidate_holder_,
                                      validated_candidate_text,
                                      NULL );

      if ( !candidate )
        candidate = new Candidate( validated_candidate_text );

      candidates.push_back( candidate );
    }
  }

  return candidates;
}

#ifdef USE_CLANG_COMPLETER

std::vector< const Candidate * > CandidateRepository::GetCandidatesForStrings(
  const std::vector< CompletionData > &datas ) {
  std::vector< const Candidate * > candidates;
  candidates.reserve( datas.size() );

  {
    boost::lock_guard< boost::mutex > locker( holder_mutex_ );

    foreach ( const CompletionData & data, datas ) {
      const Candidate *&candidate = GetValueElseInsert( candidate_holder_,
                                                        data.original_string_,
                                                        NULL );

      if ( !candidate )
        candidate = new Candidate( data.original_string_ );

      candidates.push_back( candidate );
    }
  }

  return candidates;
}

#endif // USE_CLANG_COMPLETER

CandidateRepository::~CandidateRepository() {
  foreach ( const CandidateHolder::value_type & pair,
            candidate_holder_ ) {
    delete pair.second;
  }
}

} // namespace YouCompleteMe

max_stars_repo_name: akrehl/dotfiles

max_issues_repo_name: akrehl/dotfiles

max_forks_repo_name: akrehl/dotfiles


text:
#pragma once

#include <scorum/chain/schema/scorum_object_types.hpp>

#include <boost/multi_index/composite_key.hpp>

namespace scorum {
namespace witness {

using namespace scorum::chain;

#ifndef WITNESS_SPACE_ID
#define WITNESS_SPACE_ID 12
#endif

enum witness_plugin_object_type
{
    account_bandwidth_object_type = (WITNESS_SPACE_ID << 8),
    reserve_ratio_object_type
};

enum bandwidth_type
{
    post, ///< Rate limiting posting reward eligibility over time
    forum, ///< Rate limiting for all forum related actins
    market ///< Rate limiting for all other actions
};

class account_bandwidth_object : public object<account_bandwidth_object_type, account_bandwidth_object>
{
public:
    CHAINBASE_DEFAULT_CONSTRUCTOR(account_bandwidth_object)

    id_type id;

    account_name_type account;
    bandwidth_type type;
    share_type average_bandwidth;
    share_type lifetime_bandwidth;
    time_point_sec last_bandwidth_update;
};

typedef oid<account_bandwidth_object> account_bandwidth_id_type;

class reserve_ratio_object : public object<reserve_ratio_object_type, reserve_ratio_object>
{
public:
    CHAINBASE_DEFAULT_CONSTRUCTOR(reserve_ratio_object)

    id_type id;

    /**
     *  Average block size is updated every block to be:
     *
     *     average_block_size = (99 * average_block_size + new_block_size) / 100
     *
     *  This property is used to update the current_reserve_ratio to maintain approximately
     *  50% or less utilization of network capacity.
     */
    int32_t average_block_size = 0;

    /**
     *   Any time average_block_size <= 50% maximum_block_size this value grows by 1 until it
     *   reaches SCORUM_MAX_RESERVE_RATIO.  Any time average_block_size is greater than
     *   50% it falls by 1%.  Upward adjustments happen once per round, downward adjustments
     *   happen every block.
     */
    int64_t current_reserve_ratio = 1;

    /**
     * The maximum bandwidth the blockchain can support is:
     *
     *    max_bandwidth = maximum_block_size * SCORUM_BANDWIDTH_AVERAGE_WINDOW_SECONDS / SCORUM_BLOCK_INTERVAL
     *
     * The maximum virtual bandwidth is:
     *
     *    max_bandwidth * current_reserve_ratio
     */
    uint128_t max_virtual_bandwidth = 0;
};

typedef oid<reserve_ratio_object> reserve_ratio_id_type;

struct by_account_bandwidth_type;

typedef shared_multi_index_container<account_bandwidth_object,
                                     indexed_by<ordered_unique<tag<by_id>,
                                                               member<account_bandwidth_object,
                                                                      account_bandwidth_id_type,
                                                                      &account_bandwidth_object::id>>,
                                                ordered_unique<tag<by_account_bandwidth_type>,
                                                               composite_key<account_bandwidth_object,
                                                                             member<account_bandwidth_object,
                                                                                account_name_type,
                                                                                &account_bandwidth_object::account>,
                                                                             member<account_bandwidth_object,
                                                                                bandwidth_type,
                                                                                &account_bandwidth_object::type>>>>>
    account_bandwidth_index;

typedef shared_multi_index_container<reserve_ratio_object,
                                     indexed_by<ordered_unique<tag<by_id>,
                                                               member<reserve_ratio_object,
                                                                      reserve_ratio_id_type,
                                                                      &reserve_ratio_object::id>>>>
    reserve_ratio_index;
}
} // scorum::witness

// clang-format off

FC_REFLECT_ENUM(scorum::witness::bandwidth_type, (post)(forum)(market))

FC_REFLECT(scorum::witness::account_bandwidth_object,
    (id)(account)(type)(average_bandwidth)(lifetime_bandwidth)(last_bandwidth_update))
CHAINBASE_SET_INDEX_TYPE(scorum::witness::account_bandwidth_object, scorum::witness::account_bandwidth_index)

FC_REFLECT(
    scorum::witness::reserve_ratio_object, (id)(average_block_size)(current_reserve_ratio)(max_virtual_bandwidth))
CHAINBASE_SET_INDEX_TYPE(scorum::witness::reserve_ratio_object, scorum::witness::reserve_ratio_index)

// clang-format on

max_stars_repo_name: scorum/scorum

max_issues_repo_name: Scorum/Scorum

max_forks_repo_name: Scorum/Scorum


text:
// Index cin words by line number.
// Output sorted by number of occurrences.
// Remove duplicate line occurences.
#include <algorithm>
#include <iostream>
#include <locale>
#include <map>
#include <numeric>
#include <set>
#include <vector>
#include <string>
#include <boost/algorithm/string.hpp>

using std::cin;         using std::getline;
using std::cout;        using std::find_if;
using std::istream;     using std::isspace;
using std::map;         using std::set;
using std::string;
using std::vector;

typedef map<string, set<int> > sindex;

// Split a string by whitespace.
vector<string> splitspace(const string& s)
{
    vector<string> res;
    return boost::split(res, s, boost::is_any_of(" \t\n"),
        boost::token_compress_on);
}

// Read from cin, keeping a map of which lines each word occurs in.
sindex xref(istream& in,
    vector<string> findwords(const string&) = splitspace)
{
    sindex table;
    string line;
    int line_num = 0;
    while(getline(in, line)) {
        ++line_num;
        vector<string> words = findwords(line);
        for(vector<string>::const_iterator it = words.begin();
            it != words.end(); ++it)
                table[*it].insert(line_num);
    }
    return table;
}

int main()
{
    sindex table = xref(cin);

    // Sort table ids by number of counts.
    // First, get the vector of keys.
    vector<string> keys;
    for (sindex::const_iterator it = table.begin(); it != table.end(); ++it)
        keys.push_back(it->first);

    // Now, sort it by number of lines in the value.
    std::sort(keys.begin(), keys.end(),
        [&table](string& s1, string& s2){
            return table[s1].size() < table[s2].size();
        });

    for (vector<string>::const_iterator it = keys.begin();
        it != keys.end(); ++it) {
        cout << *it << " ";
        for (set<int>::const_iterator strit = table[*it].begin();
            strit != table[*it].end(); ++strit)
            cout << *strit << " ";
        cout << std::endl;
    }
}


text:
#ifndef FETCHER_HPP
#define FETCHER_HPP

#include "tile.hpp"
#include "either.hpp"

#include <stdexcept>
#include <memory>
#include <future>
#include <boost/optional.hpp>

namespace avecado {

/* Status codes for fetch errors. Because they're an easy short-hand, we
 * model them on HTTP status codes. This means it should be pretty easy
 * to figure out at a glance what the status is when debugging.
 */
enum class fetch_status : std::uint16_t {
  /* for when the request was malformed in some way, e.g: x or y out of
   * range for the given z. */
  bad_request = 400,
  /* requested tile could not be found, possibly it does not exist. */
  not_found = 404,
  /* an unspecified and unexpected kind of error occurred. it may, or
   * may not, be temporary. */
  server_error = 500,
  /* something along the way didn't implement something that was
   * required to complete the request. */
  not_implemented = 501,
};

/* Describes the error encountered while fetching a tile.
 */
struct fetch_error {
  fetch_status status;
};

typedef either<std::unique_ptr<tile>, fetch_error> fetch_response;

/* Interface for objects which fetch tiles from sources.
 */
struct fetcher {
   virtual ~fetcher();

   // fetches a tile from the source, returning either a
   // tile which contains the (z, x, y) tile or an error.
  virtual std::future<fetch_response> operator()(int z, int x, int y) = 0;
};

} // namespace avecado

#endif /* FETCHER_HPP */

max_stars_repo_name: zerebubuth/avecado

max_issues_repo_name: zerebubuth/avecado

max_forks_repo_name: zerebubuth/avecado