text:
//
// Created by Nicholas Newdigate on 18/07/2020.
//

#ifndef TEENSYAUDIO_LAUNCHCTRL_TEST_TEST_POLYPHONIC
#define TEENSYAUDIO_LAUNCHCTRL_TEST_TEST_POLYPHONIC

#define BOOST_AUTO_TEST_MAIN
#define BOOST_TEST_MODULE ResamplingReaderTests
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include "polyphonicfixture.h"
#include <Audio.h>

BOOST_AUTO_TEST_SUITE(test_polyphony)

    BOOST_FIXTURE_TEST_CASE(basic_test, PolyphonicFixture) {
        AudioPlaySdWav wav1;
        AudioPlaySdWav wav2;
        AudioPlaySdWav wav3;
        AudioPlaySdWav wav4;

        polyphonic<AudioPlaySdWav> poly;

        poly.addVoice(wav1);
        poly.addVoice(wav2);
        poly.addVoice(wav3);
        poly.addVoice(wav4);

        AudioPlaySdWav *one = poly.useVoice();
        AudioPlaySdWav *two = poly.useVoice();
        AudioPlaySdWav *three = poly.useVoice();
        AudioPlaySdWav *four = poly.useVoice();
        AudioPlaySdWav *five = poly.useVoice();

        BOOST_CHECK_EQUAL(five, nullptr);

        poly.freeVoice(one);
        five = poly.useVoice();
        BOOST_CHECK_NE(five, nullptr);
    }

BOOST_AUTO_TEST_SUITE_END()

#endif //TEENSYAUDIO_LAUNCHCTRL_TEST_TEST_POLYPHONIC

max_stars_repo_name: newdigate/teensy-audio-launch-ctrl

max_issues_repo_name: newdigate/teensy-audio-launch-ctrl

max_forks_repo_name: newdigate/teensy-audio-launch-ctrl


text:
#include <boost/fusion/adapted.hpp>
#include <boost/fusion/algorithm.hpp>
#include <boost/fusion/container.hpp>
#include <boost/fusion/functional.hpp>
#include <boost/fusion/iterator.hpp>
#include <boost/fusion/mpl.hpp>
#include <boost/fusion/sequence.hpp>
#include <boost/fusion/support.hpp>
#include <boost/fusion/tuple.hpp>
#include <boost/fusion/view.hpp>

int
main ()
{
  return 0;
}

ext: cpp


text:
#ifndef CMBML__READER_STATE_MACHINE__HPP_
#define CMBML__READER_STATE_MACHINE__HPP_

#include <boost/msm-lite.hpp>

#include <cmbml/behavior/reader_state_machine_actions.hpp>
#include <cmbml/behavior/reader_state_machine_events.hpp>

namespace cmbml {

  template<typename ReaderT>
  struct BestEffortStatelessReaderMsm {
    // Best-effort Stateless Reader specialization
    auto configure() {
      using boost::msm::lite::state;
      using boost::msm::lite::event;
      using namespace cmbml::reader_events;

      state<class initial> initial_s;
      state<class waiting> waiting_s;
      state<class final_> final_s;

      return boost::msm::lite::make_transition_table(
        *initial_s + event<reader_created<ReaderT>>                             = waiting_s,
        waiting_s  + event<data_received<ReaderT>> / on_data_received_stateless = waiting_s,
        waiting_s  + event<reader_deleted<ReaderT>>                             = final_s
      );
    }
  };

  template<typename ReaderT>
  struct BestEffortStatefulReaderMsm {
    auto configure() {
      using boost::msm::lite::state;
      using boost::msm::lite::event;
      using namespace cmbml::reader_events;

      state<class initial> initial_s;
      state<class waiting> waiting_s;
      state<class final_> final_s;

      return boost::msm::lite::make_transition_table(
        *initial_s + event<reader_created<ReaderT>> / on_reader_created         = waiting_s,
        waiting_s  + event<data_received<ReaderT>>  / on_data_received_stateful = waiting_s,
        *waiting_s  + event<reader_deleted<ReaderT>> / on_reader_deleted         = final_s
      );
    }
  };

  template<typename ReaderT, typename Transport>
  struct ReliableStatefulReaderMsm {

    auto configure() {
      using boost::msm::lite::event;
      using boost::msm::lite::on_entry;
      using boost::msm::lite::state;
      using namespace cmbml::reader_events;

      state<class initial> initial_s;
      state<class waiting> waiting_s;
      state<class may_ack> may_ack_s;
      state<class must_ack> must_ack_s;
      state<class initial2> initial2_s;
      state<class ready> ready_s;
      state<class any> any_s;
      state<class final_> final_s;

      return boost::msm::lite::make_transition_table(
        *initial_s  + event<reader_created<ReaderT>> / on_reader_created = waiting_s,

        waiting_s   + event<heartbeat_received> [not_final_guard] = must_ack_s,
        waiting_s   + event<heartbeat_received> [not_live_guard]  = may_ack_s,
        waiting_s   + event<heartbeat_received>                   = waiting_s,
        may_ack_s   + event<missing_changes_empty>                = waiting_s,
        may_ack_s   + event<missing_changes_not_empty>            = must_ack_s,
        must_ack_s  + on_entry / on_must_ack_entry,  // TODO
        must_ack_s  + event<heartbeat_response_delay<Transport>> / on_heartbeat_response_delay = waiting_s,

        *initial2_s + event<reader_created<ReaderT>>               = ready_s,

        ready_s     + event<heartbeat_received>     / on_heartbeat = ready_s,
        ready_s     + event<data_received<ReaderT>> / on_data      = ready_s,
        ready_s     + event<gap_received>           / on_gap       = ready_s,

        *any_s  + event<reader_deleted<ReaderT>> / on_reader_deleted = final_s
      );
    }

  };

}

#endif  // CMBML__READER_STATE_MACHINE__HPP_

ext: hpp

max_stars_repo_name: osrf/cmbml

max_issues_repo_name: osrf/cmbml

max_forks_repo_name: osrf/cmbml


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_TOOLBOX_OPERATOR_FUNCTIONS_SIMD_VMX_ALTIVEC_DIVIDES_HPP_INCLUDED
#define BOOST_SIMD_TOOLBOX_OPERATOR_FUNCTIONS_SIMD_VMX_ALTIVEC_DIVIDES_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_VMX_SUPPORT

////////////////////////////////////////////////////////////////////////////////
// Altivec division algorithm are long-ass. Let's hide them for clarity purpose
////////////////////////////////////////////////////////////////////////////////
#include <boost/simd/toolbox/operator/functions/divides.hpp>
#include <boost/simd/toolbox/operator/functions/simd/vmx/altivec/impl/divides_float.hpp>
//#include <boost/simd/toolbox/operator/functions/simd/vmx/altivec/impl/divides_int32.hpp>
//#include <boost/simd/toolbox/operator/functions/simd/vmx/altivec/impl/divides_int16.hpp>
//#include <boost/simd/toolbox/operator/functions/simd/vmx/altivec/impl/divides_int8.hpp>

#endif
#endif


text:
#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>

//#include <iostream>
#include <thread>
//#include <pcl/io/pcd_io.h>
//#include <pcl/point_types.h>
#include <pcl/registration/ndt.h>                // ndt配准文件头
#include <pcl/filters/approximate_voxel_grid.h>  // 滤波文件头
#include <pcl/visualization/pcl_visualizer.h>

#include "study_registration.h"

using namespace std::chrono_literals;

void Study_Registration::test_Icp()
{
    // 定义输入和输出点云
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in(new pcl::PointCloud<pcl::PointXYZ>);
    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_out(new pcl::PointCloud<pcl::PointXYZ>);

    // 随机填充无序点云
    cloud_in->width = 5;
    cloud_in->height = 1;
    cloud_in->is_dense = false;
    cloud_in->points.resize(cloud_in->width * cloud_in->height);
    for (size_t i = 0; i < cloud_in->points.size(); ++i) {
        cloud_in->points[i].x = 1024 * rand() / (RAND_MAX + 1.0f);
        cloud_in->points[i].y = 1024 * rand() / (RAND_MAX + 1.0f);
        cloud_in->points[i].z = 1024 * rand() / (RAND_MAX + 1.0f);
    }
    std::cout << "Saved " << cloud_in->points.size() << " data points to input:"
              << std::endl;
    for (size_t i = 0; i < cloud_in->points.size(); ++i)
        std::cout << "    " <<
                     cloud_in->points[i].x << " " << cloud_in->points[i].y << " " <<
                     cloud_in->points[i].z << std::endl;
    *cloud_out = *cloud_in;
    std::cout << "size:" << cloud_out->points.size() << std::endl;

    // 在点云上执行简单的刚性变换，将cloud_out中的x平移0.7f米，然后再次输出数据值。
    for (size_t i = 0; i < cloud_in->points.size(); ++i)
        cloud_out->points[i].x = cloud_in->points[i].x + 0.7f;
    // 打印这些点
    std::cout << "Transformed " << cloud_in->points.size() << " data points:"
              << std::endl;
    for (size_t i = 0; i < cloud_out->points.size(); ++i)
        std::cout << "    " << cloud_out->points[i].x << " " <<
                     cloud_out->points[i].y << " " << cloud_out->points[i].z << std::endl;

    // 创建IterativeClosestPoint的实例
    // setInputSource将cloud_in作为输入点云
    // setInputTarget将平移后的cloud_out作为目标点云
    pcl::IterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> icp;
    icp.setInputSource(cloud_in);
    icp.setInputTarget(cloud_out);

    // 创建一个 pcl::PointCloud<pcl::PointXYZ>实例 Final 对象,存储配准变换后的源点云,
    // 应用 ICP 算法后, IterativeClosestPoint 能够保存结果点云集,如果这两个点云匹配正确的话
    // （即仅对其中一个应用某种刚体变换，就可以得到两个在同一坐标系下相同的点云）,那么 icp. hasConverged()= 1 (true),
    // 然后会输出最终变换矩阵的匹配分数和变换矩阵等信息。
    pcl::PointCloud<pcl::PointXYZ> Final;
    icp.align(Final);
    std::cout << "has converged:" << icp.hasConverged() << " score: " <<
                 icp.getFitnessScore() << std::endl;
    const pcl::Registration<pcl::PointXYZ, pcl::PointXYZ, float>::Matrix4 &matrix = icp.getFinalTransformation();
    std::cout << matrix << std::endl;
}

void Study_Registration::test_ndt(){
    // Loading first scan of room.
    pcl::PointCloud<pcl::PointXYZ>::Ptr target_cloud(new pcl::PointCloud<pcl::PointXYZ>);
    if (pcl::io::loadPCDFile<pcl::PointXYZ>("data-master/tutorials/room_scan1.pcd", *target_cloud) == -1) {
        PCL_ERROR ("Couldn't read file room_scan1.pcd \n");
        return;
    }
    std::cout << "Loaded " << target_cloud->size() << " data points from room_scan1.pcd" << std::endl;

    // Loading second scan of room from new perspective.
    pcl::PointCloud<pcl::PointXYZ>::Ptr input_cloud(new pcl::PointCloud<pcl::PointXYZ>);
    if (pcl::io::loadPCDFile<pcl::PointXYZ>("data-master/tutorials/room_scan2.pcd", *input_cloud) == -1) {
        PCL_ERROR ("Couldn't read file room_scan2.pcd \n");
        return;
    }
    std::cout << "Loaded " << input_cloud->size() << " data points from room_scan2.pcd" << std::endl;

    //将输入扫描过滤到原始尺寸的大约 10% 以提高配准速度。
    // Filtering input scan to roughly 10% of original size to increase speed of registration.
    pcl::PointCloud<pcl::PointXYZ>::Ptr filtered_cloud(new pcl::PointCloud<pcl::PointXYZ>);
    pcl::ApproximateVoxelGrid<pcl::PointXYZ> approximate_voxel_filter;
    approximate_voxel_filter.setLeafSize(0.2, 0.2, 0.2);//体素大小。小立方体
    approximate_voxel_filter.setInputCloud(input_cloud);
    approximate_voxel_filter.filter(*filtered_cloud);
    std::cout << "Filtered cloud contains " << filtered_cloud->size()
              << " data points from room_scan2.pcd" << std::endl;

    // Initializing Normal Distributions Transform (NDT).
    pcl::NormalDistributionsTransform<pcl::PointXYZ, pcl::PointXYZ> ndt;

    //NDT 算法使用一个体素化数据结构和More-Thuente 线搜索
    // Setting scale dependent NDT parameters
    // Setting minimum transformation difference for termination condition.
    //设置终止条件的最小变化差
    ndt.setTransformationEpsilon(0.01);
    // Setting maximum step size for More-Thuente line search.
    ndt.setStepSize(0.1);
    //Setting Resolution of NDT grid structure (VoxelGridCovariance). 体素网格
    ndt.setResolution(1.0);

    // Setting max number of registration iterations.
    ndt.setMaximumIterations(35);//最大迭代次数

    // Setting point cloud to be aligned.
    ndt.setInputSource(filtered_cloud);
    // Setting point cloud to be aligned to.
    //目标点云target_cloud不需要进行滤波处理，因为NDT算法在目标点云对应的体素Voxel网格数据结构计算时，
    //不使用单个点，而是使用体素的点。即已做了降采样处理
    ndt.setInputTarget(target_cloud);

    //设置使用机器人测距法得到的粗略初始变换矩阵
    // Set initial alignment estimate found using robot odometry.
    Eigen::AngleAxisf init_rotation(0.6931, Eigen::Vector3f::UnitZ());
    Eigen::Translation3f init_translation(1.79387, 0, 0);
    Eigen::Matrix4f init_guess = (init_translation * init_rotation).matrix();

    // Calculating required rigid transform to align the input cloud to the target cloud.
    pcl::PointCloud<pcl::PointXYZ>::Ptr output_cloud(new pcl::PointCloud<pcl::PointXYZ>);
    //求出input_cloud变换到target_cloud的变换矩阵
    ndt.align(*output_cloud, init_guess);

    std::cout << "Normal Distributions Transform has converged:" << ndt.hasConverged()
              << " score: " << ndt.getFitnessScore() << std::endl;

    // Transforming unfiltered, input cloud using found transform.
    pcl::transformPointCloud(*input_cloud, *output_cloud, ndt.getFinalTransformation());

    // Saving transformed input cloud.
    pcl::io::savePCDFileASCII("room_scan2_transformed.pcd", *output_cloud);

    // Initializing point cloud visualizer
    pcl::visualization::PCLVisualizer::Ptr
            viewer_final(new pcl::visualization::PCLVisualizer("3D Viewer"));
    viewer_final->setBackgroundColor(0, 0, 0);

    // Coloring and visualizing target cloud (red).
    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>
            target_color(target_cloud, 255, 0, 0);
    viewer_final->addPointCloud<pcl::PointXYZ>(target_cloud, target_color, "target cloud");
    viewer_final->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE,
                                                   1, "target cloud");

    // Coloring and visualizing transformed input cloud (green).
    pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ>
            output_color(output_cloud, 0, 255, 0);
    viewer_final->addPointCloud<pcl::PointXYZ>(output_cloud, output_color, "output cloud");
    viewer_final->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE,
                                                   1, "output cloud");

    // Starting visualizer
    viewer_final->addCoordinateSystem(1.0, "global");
    viewer_final->initCameraParameters();

    // Wait until visualizer window is closed.
    while (!viewer_final->wasStopped()) {
        viewer_final->spinOnce(100);
        std::this_thread::sleep_for(100ms);
    }
}

#include <Eigen/Core>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/time.h>
#include <pcl/console/print.h>
#include <pcl/features/normal_3d_omp.h>
#include <pcl/features/fpfh_omp.h>
#include <pcl/filters/filter.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/io/pcd_io.h>
#include <pcl/registration/icp.h>
#include <pcl/registration/sample_consensus_prerejective.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/visualization/pcl_visualizer.h>

// 首先从定义类型开始，以免使代码混乱
// Types
typedef pcl::PointNormal PointNT;
typedef pcl::PointCloud<PointNT> PointCloudT;
typedef pcl::FPFHSignature33 FeatureT;
typedef pcl::FPFHEstimationOMP<PointNT,PointNT,FeatureT> FeatureEstimationT;
typedef pcl::PointCloud<FeatureT> FeatureCloudT;
typedef pcl::visualization::PointCloudColorHandlerCustom<PointNT> ColorHandlerT;

//./alignment-prerejective ./data/chef.pcd ./data/rs1.pcd
void Study_Registration::test_robust(int argc, char ** argv){
    // 然后，我们实例化必要的数据容器，检查输入参数并加载对象和场景点云。
    // Point clouds
    PointCloudT::Ptr object (new PointCloudT);
    PointCloudT::Ptr object_aligned (new PointCloudT);
    PointCloudT::Ptr scene (new PointCloudT);
    FeatureCloudT::Ptr object_features (new FeatureCloudT);
    FeatureCloudT::Ptr scene_features (new FeatureCloudT);

    // Get input object and scene
    if (argc != 3)
    {
        pcl::console::print_error ("Syntax is: %s object.pcd scene.pcd\n", argv[0]);
        return;
    }

    // Load object and scene
    pcl::console::print_highlight ("Loading point clouds...\n");
    if (pcl::io::loadPCDFile<PointNT> (argv[1], *object) < 0 ||
            pcl::io::loadPCDFile<PointNT> (argv[2], *scene) < 0)
    {
        pcl::console::print_error ("Error loading object/scene file!\n");
        return;
    }

    // 1, 降采样 Downsample
    // 为了加快处理速度，我们使用PCL的：pcl::VoxelGrid类将对象和场景点云的采样率下采样至5 mm。
    pcl::console::print_highlight ("Downsampling...\n");
    pcl::VoxelGrid<PointNT> grid;
    const float leaf = 0.005f;
    grid.setLeafSize (leaf, leaf, leaf);
    grid.setInputCloud (object);
    grid.filter (*object);
    grid.setInputCloud (scene);
    grid.filter (*scene);

    // Estimate normals for scene
    //2, 估计场景法线 Estimate normals for scene
    pcl::console::print_highlight ("Estimating scene normals...\n");
    pcl::NormalEstimationOMP<PointNT,PointNT> nest;
    nest.setRadiusSearch (0.01);
    nest.setInputCloud (scene);
    nest.compute (*scene);

    // 3, 特征估计 Estimate features
    // 对于下采样点云中的每个点，我们现在使用PCL的pcl::FPFHEstimationOMP<>类来计算用于对齐过程中用于匹配的快速点特征直方图（FPFH）描述符。
    pcl::console::print_highlight ("Estimating features...\n");
    FeatureEstimationT fest;
    fest.setRadiusSearch (0.025);
    fest.setInputCloud (object);
    fest.setInputNormals (object);
    fest.compute (*object_features);
    fest.setInputCloud (scene);
    fest.setInputNormals (scene);
    fest.compute (*scene_features);

    // Perform alignment
    // SampleConsensusPrerejective 实现了有效的RANSAC姿势估计循环
    pcl::console::print_highlight ("Starting alignment...\n");
    pcl::SampleConsensusPrerejective<PointNT,PointNT,FeatureT> align;
    align.setInputSource (object);
    align.setSourceFeatures (object_features);
    align.setInputTarget (scene);
    align.setTargetFeatures (scene_features);
    align.setMaximumIterations (50000); // Number of RANSAC iterations
    align.setNumberOfSamples (3); // Number of points to sample for generating/prerejecting a pose
    align.setCorrespondenceRandomness (5); // Number of nearest features to use
    align.setSimilarityThreshold (0.9f); // Polygonal edge length similarity threshold
    align.setMaxCorrespondenceDistance (2.5f * leaf); // Inlier threshold
    align.setInlierFraction (0.25f); // Required inlier fraction for accepting a pose hypothesis
    {
        pcl::ScopeTime t("Alignment");
        align.align (*object_aligned);
    }

    if (align.hasConverged ())
    {
        // Print results
        printf ("\n");
        Eigen::Matrix4f transformation = align.getFinalTransformation ();
        pcl::console::print_info ("    | %6.3f %6.3f %6.3f | \n", transformation (0,0), transformation (0,1), transformation (0,2));
        pcl::console::print_info ("R = | %6.3f %6.3f %6.3f | \n", transformation (1,0), transformation (1,1), transformation (1,2));
        pcl::console::print_info ("    | %6.3f %6.3f %6.3f | \n", transformation (2,0), transformation (2,1), transformation (2,2));
        pcl::console::print_info ("\n");
        pcl::console::print_info ("t = < %0.3f, %0.3f, %0.3f >\n", transformation (0,3), transformation (1,3), transformation (2,3));
        pcl::console::print_info ("\n");
        pcl::console::print_info ("Inliers: %i/%i\n", align.getInliers ().size (), object->size ());

        // Show alignment
        pcl::visualization::PCLVisualizer visu("Alignment");
        visu.addPointCloud (scene, ColorHandlerT (scene, 0.0, 255.0, 0.0), "scene");
        visu.addPointCloud (object_aligned, ColorHandlerT (object_aligned, 0.0, 0.0, 255.0), "object_aligned");
        visu.spin ();
    }
    else
    {
        pcl::console::print_error ("Alignment failed!\n");
        return;
    }
}

void Study_Registration::test_robust_default(){
    const char* in[3];
    in[0] = "test_robust.exe";
    in[1] = "D:/Program Files (x86)/PCL 1.9.1/share/doc/pcl-1.9/tutorials/sources/alignment_prerejective/chef.pcd";
    in[2] = "D:/Program Files (x86)/PCL 1.9.1/share/doc/pcl-1.9/tutorials/sources/alignment_prerejective/rs1.pcd";

    char** chs = (char**)in;
    test_robust(3, chs);
}

//-----------------------------------------------------
#include <string>

#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl/registration/icp.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/console/time.h>   // TicToc

typedef pcl::PointXYZ PointT2;
typedef pcl::PointCloud<PointT2> PointCloudT2;

bool next_iteration = false;

static void
print4x4Matrix (const Eigen::Matrix4d & matrix)
{
    printf ("Rotation matrix :\n");
    printf ("    | %6.3f %6.3f %6.3f | \n", matrix (0, 0), matrix (0, 1), matrix (0, 2));
    printf ("R = | %6.3f %6.3f %6.3f | \n", matrix (1, 0), matrix (1, 1), matrix (1, 2));
    printf ("    | %6.3f %6.3f %6.3f | \n", matrix (2, 0), matrix (2, 1), matrix (2, 2));
    printf ("Translation vector :\n");
    printf ("t = < %6.3f, %6.3f, %6.3f >\n\n", matrix (0, 3), matrix (1, 3), matrix (2, 3));
}
/**
 * 此函数是查看器的回调。 当查看器窗口位于顶部时，只要按任意键，就会调用此函数。 如果碰到“空格”； 将布尔值设置为true。
 * @param event
 * @param nothing
 */
static void
keyboardEventOccurred (const pcl::visualization::KeyboardEvent& event,
                       void*)
{
    if (event.getKeySym () == "space" && event.keyDown ())
        next_iteration = true;
}

//./interactive_icp monkey.ply 1
void Study_Registration::test_interactive_icp(int argc, char** argv)
{
    // The point clouds we will be using
    PointCloudT2::Ptr cloud_in (new PointCloudT2);  // Original point cloud
    PointCloudT2::Ptr cloud_tr (new PointCloudT2);  // Transformed point cloud
    PointCloudT2::Ptr cloud_icp (new PointCloudT2);  // ICP output point cloud

//    我们检查程序的参数，设置初始ICP迭代的次数，然后尝试加载PLY文件。
    // Checking program arguments
    if (argc < 2)
    {
        printf ("Usage :\n");
        printf ("\t\t%s file.ply number_of_ICP_iterations\n", argv[0]);
        PCL_ERROR ("Provide one ply file.\n");
        return;
    }

    int iterations = 1;  // Default number of ICP iterations
    if (argc > 2)
    {
        // If the user passed the number of iteration as an argument
        iterations = atoi (argv[2]);
        if (iterations < 1)
        {
            PCL_ERROR ("Number of initial iterations must be >= 1\n");
            return;
        }
    }

    pcl::console::TicToc time;
    time.tic ();
    if (pcl::io::loadPLYFile (argv[1], *cloud_in) < 0)
    {
        PCL_ERROR ("Error loading cloud %s.\n", argv[1]);
        return;
    }
    std::cout << "\nLoaded file " << argv[1] << " (" << cloud_in->size () << " points) in " << time.toc () << " ms\n" << std::endl;

    // 我们使用刚性矩阵变换来变换原始点云。
    // cloud_in包含原始点云。
    // cloud_tr和cloud_icp包含平移/旋转的点云。
    // cloud_tr是我们将用于显示的备份（绿点云）。

    // Defining a rotation matrix and translation vector
    Eigen::Matrix4d transformation_matrix = Eigen::Matrix4d::Identity ();

    // A rotation matrix (see https://en.wikipedia.org/wiki/Rotation_matrix)
    double theta = M_PI / 8;  // The angle of rotation in radians
    transformation_matrix (0, 0) = std::cos (theta);
    transformation_matrix (0, 1) = -sin (theta);
    transformation_matrix (1, 0) = sin (theta);
    transformation_matrix (1, 1) = std::cos (theta);

    // A translation on Z axis (0.4 meters)
    transformation_matrix (2, 3) = 0.4;

    // Display in terminal the transformation matrix
    std::cout << "Applying this rigid transformation to: cloud_in -> cloud_icp" << std::endl;
    print4x4Matrix (transformation_matrix);

    // Executing the transformation
    pcl::transformPointCloud (*cloud_in, *cloud_icp, transformation_matrix);
    *cloud_tr = *cloud_icp;  // We backup cloud_icp into cloud_tr for later use

    // 这是ICP对象的创建。 我们设置ICP算法的参数。
    // setMaximumIterations（iterations）设置要执行的初始迭代次数（默认值为1）。
    // 然后，我们将点云转换为cloud_icp。 第一次对齐后，我们将在下一次使用该ICP对象时（当用户按下“空格”时）将ICP最大迭代次数设置为1。

    // The Iterative Closest Point algorithm
    time.tic ();
    pcl::IterativeClosestPoint<PointT2, PointT2> icp;
    icp.setMaximumIterations (iterations);
    icp.setInputSource (cloud_icp);
    icp.setInputTarget (cloud_in);
    icp.align (*cloud_icp);
    icp.setMaximumIterations (1);  // We set this variable to 1 for the next time we will call .align () function
    std::cout << "Applied " << iterations << " ICP iteration(s) in " << time.toc () << " ms" << std::endl;

    // 检查ICP算法是否收敛； 否则退出程序。 如果返回true，我们将转换矩阵存储在4x4矩阵中，然后打印刚性矩阵转换。
    if (icp.hasConverged ())
    {
        std::cout << "\nICP has converged, score is " << icp.getFitnessScore () << std::endl;
        std::cout << "\nICP transformation " << iterations << " : cloud_icp -> cloud_in" << std::endl;
        transformation_matrix = icp.getFinalTransformation ().cast<double>();
        print4x4Matrix (transformation_matrix);
    }
    else
    {
        PCL_ERROR ("\nICP has not converged.\n");
        return;
    }

    // Visualization
    pcl::visualization::PCLVisualizer viewer ("ICP demo");
    // Create two vertically separated viewports
    int v1 (0);
    int v2 (1);
    viewer.createViewPort (0.0, 0.0, 0.5, 1.0, v1);
    viewer.createViewPort (0.5, 0.0, 1.0, 1.0, v2);

    // The color we will be using
    float bckgr_gray_level = 0.0;  // Black
    float txt_gray_lvl = 1.0 - bckgr_gray_level;

    // Original point cloud is white
    pcl::visualization::PointCloudColorHandlerCustom<PointT2> cloud_in_color_h (cloud_in, (int) 255 * txt_gray_lvl, (int) 255 * txt_gray_lvl,
                                                                               (int) 255 * txt_gray_lvl);
    viewer.addPointCloud (cloud_in, cloud_in_color_h, "cloud_in_v1", v1);
    viewer.addPointCloud (cloud_in, cloud_in_color_h, "cloud_in_v2", v2);

    // Transformed point cloud is green
    pcl::visualization::PointCloudColorHandlerCustom<PointT2> cloud_tr_color_h (cloud_tr, 20, 180, 20);
    viewer.addPointCloud (cloud_tr, cloud_tr_color_h, "cloud_tr_v1", v1);

    // ICP aligned point cloud is red
    pcl::visualization::PointCloudColorHandlerCustom<PointT2> cloud_icp_color_h (cloud_icp, 180, 20, 20);
    viewer.addPointCloud (cloud_icp, cloud_icp_color_h, "cloud_icp_v2", v2);

    // Adding text descriptions in each viewport
    viewer.addText ("White: Original point cloud\nGreen: Matrix transformed point cloud", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "icp_info_1", v1);
    viewer.addText ("White: Original point cloud\nRed: ICP aligned point cloud", 10, 15, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "icp_info_2", v2);

    std::stringstream ss;
    ss << iterations;
    std::string iterations_cnt = "ICP iterations = " + ss.str ();
    viewer.addText (iterations_cnt, 10, 60, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "iterations_cnt", v2);

    // Set background color
    viewer.setBackgroundColor (bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v1);
    viewer.setBackgroundColor (bckgr_gray_level, bckgr_gray_level, bckgr_gray_level, v2);

    // Set camera position and orientation
    viewer.setCameraPosition (-3.68332, 2.94092, 5.71266, 0.289847, 0.921947, -0.256907, 0);
    viewer.setSize (1280, 1024);  // Visualiser window size

    // Register keyboard callback :
    viewer.registerKeyboardCallback (&keyboardEventOccurred, (void*) NULL);

    // Display the visualiser
    while (!viewer.wasStopped ())
    {
        viewer.spinOnce ();

        // The user pressed "space" :
        if (next_iteration)
        {
            // The Iterative Closest Point algorithm
            time.tic ();
            // 如果用户按下键盘上的任意键，则会调用keyboardEventOccurred函数。 此功能检查键是否为“空格”。
            // 如果是，则全局布尔值next_iteration设置为true，从而允许查看器循环输入代码的下一部分：调用ICP对象以进行对齐。
            // 记住，我们已经配置了该对象输入/输出云，并且之前通过setMaximumIterations将最大迭代次数设置为1。

            icp.align (*cloud_icp);
            std::cout << "Applied 1 ICP iteration in " << time.toc () << " ms" << std::endl;

            // 和以前一样，我们检查ICP是否收敛，如果不收敛，则退出程序。
            if (icp.hasConverged ())
            {
                // printf（“ 033 [11A”）; 在终端增加11行以覆盖显示的最后一个矩阵是一个小技巧。
                // 简而言之，它允许替换文本而不是编写新行； 使输出更具可读性。 我们增加迭代次数以更新可视化器中的文本值。
                printf ("\033[11A");  // Go up 11 lines in terminal output.
                printf ("\nICP has converged, score is %+.0e\n", icp.getFitnessScore ());

                // 这意味着，如果您已经完成了10次迭代，则此函数返回矩阵以将点云从迭代10转换为11。
                std::cout << "\nICP transformation " << ++iterations << " : cloud_icp -> cloud_in" << std::endl;

                // 函数getFinalTransformation（）返回在迭代过程中完成的刚性矩阵转换（此处为1次迭代）。
                transformation_matrix *= icp.getFinalTransformation ().cast<double>();  // WARNING /!\ This is not accurate! For "educational" purpose only!
                print4x4Matrix (transformation_matrix);  // Print the transformation between original pose and current pose

                ss.str ("");
                ss << iterations;
                std::string iterations_cnt = "ICP iterations = " + ss.str ();
                viewer.updateText (iterations_cnt, 10, 60, 16, txt_gray_lvl, txt_gray_lvl, txt_gray_lvl, "iterations_cnt");
                viewer.updatePointCloud (cloud_icp, cloud_icp_color_h, "cloud_icp_v2");
            }
            else
            {
                PCL_ERROR ("\nICP has not converged.\n");
                return;
            }

            //这不是我们想要的。 如果我们将最后一个矩阵与新矩阵相乘，那么结果就是从开始到当前迭代的转换矩阵。
        }
        next_iteration = false;
    }
}


text:
<<<<<<< HEAD
/*    Copyright (c) 2010-2018, Delft University of Technology
=======
/*    Copyright (c) 2010-2019, Delft University of Technology
>>>>>>> origin/master
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 *
 *    References
 *      Burden, R.L., Faires, J.D. Numerical Analysis, 7th Edition, Books/Cole, 2001.
 *      Montenbruck, O., Gill, E. Satellite Orbits: Models, Methods, Applications, Springer, 2005.
 *
 *    Notes
 *      There might be a problem with the RKF78 and DOPRI8 integrators, as the coefficients do not
 *      meet the required conditions to the tolerance achieved for all the other Runge-Kutta-type
 *      integrators tested (1.0e-14 versus 1.0e-15 for the other integrators). This should be
 *      looked into further to ensure that there are no bugs introduced in the coefficients
 *      used.
 *
 */

#define BOOST_TEST_MAIN

#include <cmath>

#include <boost/test/unit_test.hpp>

#include "Tudat/Basics/testMacros.h"

#include "Tudat/Mathematics/NumericalIntegrators/rungeKuttaCoefficients.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_runge_kutta_coefficients )

using numerical_integrators::RungeKuttaCoefficients;

void checkValidityOfCoefficientSet( const RungeKuttaCoefficients::CoefficientSets& coefficientSet,
                                    const double tolerance )
{
    // Declare coefficient set.
    RungeKuttaCoefficients coefficients;
    coefficients = coefficients.get( coefficientSet );

    // Check that the sum of the b-coefficients for both the integrated order and the
    // error-checking order is one.
    TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
                Eigen::VectorXd::Constant( 2, 1.0 ),
                coefficients.bCoefficients.rowwise( ).sum( ), tolerance );

    // Check that the first c-coefficient is zero.
    BOOST_CHECK_SMALL( coefficients.cCoefficients( 0 ), tolerance );

    // Check that the c-coefficient/a-coefficient relation holds.
    for ( int i = 1; i < coefficients.cCoefficients.size( ); i++ )
    {
        if ( std::fabs( coefficients.cCoefficients( i ) ) < tolerance )
        {
            BOOST_CHECK_SMALL( coefficients.aCoefficients.row( i ).sum( ), tolerance );
        }

        else
        {
            BOOST_CHECK_CLOSE_FRACTION( coefficients.cCoefficients( i ),
                                        coefficients.aCoefficients.row( i ).sum( ), tolerance );
        }
    }
}

BOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg45Coefficients )
{
    // Check validity of Runge-Kutta-Fehlberg 45 coefficients.
    checkValidityOfCoefficientSet( RungeKuttaCoefficients::rungeKuttaFehlberg45, 1.0e-15 );
}

BOOST_AUTO_TEST_CASE( testRungeKuttaFehlberg78Coefficients )
{
    // Check validity of Runge-Kutta-Fehlberg 78 coefficients.
    // Note, for some reason, the RKF78 set fails the unit test when the tolerance in
    // checkValidityOfCoefficientSet() is set to lower than this value (rows 8 and 9 of
    // aCoefficients matrix sum does not correspond to cCoefficient counterpart with tolerance less
    // than 1.0e-14).
    checkValidityOfCoefficientSet( RungeKuttaCoefficients::rungeKuttaFehlberg78, 1.0e-14 );
}

BOOST_AUTO_TEST_CASE( testRungeKutta87DormandAndPrinceCoefficients )
{
    // Check validity of Runge-Kutta 87 (Dormand and Prince) coefficients.
    // Note, for some reason, the DOPRI8 set fails the unit test when the tolerance in
    // checkValidityOfCoefficientSet() is set to lower than this value (row 10 of aCoefficients
    // matrix sum does not correspond to cCoefficient counterpart with tolerance less than
    // 1.0e-14).
    checkValidityOfCoefficientSet( RungeKuttaCoefficients::rungeKutta87DormandPrince, 1.0e-14 );
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests
} // namespace tudat

max_stars_repo_name: ViktorJordanov/tudat

max_issues_repo_name: ViktorJordanov/tudat

max_forks_repo_name: ViktorJordanov/tudat


text:
//  boost/timer/config.hpp  -----------------------------------------------------------//

//  Copyright Beman Dawes 2003, 2006, 2011

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  See http://www.boost.org/libs/timer for documentation.

#ifndef BOOST_TIMER_CONFIG_HPP
#define BOOST_TIMER_CONFIG_HPP

#include <boost/config.hpp>

#include <boost/system/api_config.hpp>

// This header implements separate compilation features as described in
// http://www.boost.org/more/separate_compilation.html

//  enable dynamic or static linking as requested --------------------------------------//

#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_TIMER_DYN_LINK)
# if defined(BOOST_TIMER_SOURCE)
#   define BOOST_TIMER_DECL BOOST_SYMBOL_EXPORT
# else
#   define BOOST_TIMER_DECL BOOST_SYMBOL_IMPORT
# endif
#else
# define BOOST_TIMER_DECL
#endif

//  enable automatic library variant selection  ----------------------------------------//

#if !defined(BOOST_TIMER_SOURCE) && !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_TIMER_NO_LIB)
//
// Set the name of our library, this will get undef'ed by auto_link.hpp
// once it's done with it:
//
#define BOOST_LIB_NAME boost_timer
//
// If we're importing code from a dll, then tell auto_link.hpp about it:
//
#if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_TIMER_DYN_LINK)
#  define BOOST_DYN_LINK
#endif
//
// And include the header that does the work:
//
#include <boost/config/auto_link.hpp>
#endif  // auto-linking disabled

#endif // BOOST_TIMER_CONFIG_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo


text:
//
// Copyright 2018 - 2020 (C). Alex Robenko. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "BitfieldField.h"

#include <type_traits>

#include <boost/algorithm/string.hpp>

#include "Generator.h"
#include "common.h"

namespace ba = boost::algorithm;

namespace commsdsl2comms
{

namespace
{

const std::string MembersDefTemplate =
    "/// @brief Scope for all the member fields of\n"
    "///     @ref #^#CLASS_NAME#$# bitfield.\n"
    "#^#EXTRA_PREFIX#$#\n"
    "struct #^#CLASS_NAME#$#Members\n"
    "{\n"
    "    #^#MEMBERS_DEFS#$#\n"
    "    /// @brief All members bundled in @b std::tuple.\n"
    "    using All =\n"
    "        std::tuple<\n"
    "           #^#MEMBERS#$#\n"
    "        >;\n"
    "};\n";

const std::string MembersOptionsTemplate =
    "/// @brief Extra options for all the member fields of\n"
    "///     @ref #^#SCOPE#$##^#CLASS_NAME#$# bitfield.\n"
    "struct #^#CLASS_NAME#$#Members#^#EXT#$#\n"
    "{\n"
    "    #^#OPTIONS#$#\n"
    "};\n";

const std::string ClassTemplate(
    "#^#MEMBERS_STRUCT_DEF#$#\n"
    "#^#PREFIX#$#"
    "class #^#CLASS_NAME#$# : public\n"
    "    comms::field::Bitfield<\n"
    "        #^#PROT_NAMESPACE#$#::field::FieldBase<#^#FIELD_BASE_PARAMS#$#>,\n"
    "        typename #^#ORIG_CLASS_NAME#$#Members#^#MEMBERS_OPT#$#::All#^#COMMA#$#\n"
    "        #^#FIELD_OPTS#$#\n"
    "    >\n"
    "{\n"
    "    using Base = \n"
    "        comms::field::Bitfield<\n"
    "            #^#PROT_NAMESPACE#$#::field::FieldBase<#^#FIELD_BASE_PARAMS#$#>,\n"
    "            typename #^#ORIG_CLASS_NAME#$#Members#^#MEMBERS_OPT#$#::All#^#COMMA#$#\n"
    "            #^#FIELD_OPTS#$#\n"
    "        >;\n"
    "public:\n"
    "    #^#ACCESS#$#\n"
    "    #^#PUBLIC#$#\n"
    "    #^#NAME#$#\n"
    "    #^#READ#$#\n"
    "    #^#WRITE#$#\n"
    "    #^#LENGTH#$#\n"
    "    #^#VALID#$#\n"
    "    #^#REFRESH#$#\n"
    "#^#PROTECTED#$#\n"
    "#^#PRIVATE#$#\n"
    "};\n"
);

} // namespace

bool BitfieldField::prepareImpl()
{
    auto obj = bitfieldFieldDslObj();
    auto members = obj.members();
    m_members.reserve(members.size());
    for (auto& m : members) {
        auto ptr = create(generator(), m);
        if (!ptr) {
            static constexpr bool Should_not_happen = false;
            static_cast<void>(Should_not_happen);
            assert(Should_not_happen);
            return false;
        }

        ptr->setMemberChild();
        if (!ptr->prepare(obj.sinceVersion())) {
            return false;
        }

        m_members.push_back(std::move(ptr));
    }
    return true;
}

void BitfieldField::updateIncludesImpl(IncludesList& includes) const
{
    static const IncludesList List = {
        "comms/field/Bitfield.h",
        "<tuple>"
    };

    common::mergeIncludes(List, includes);

    for (auto& m : m_members) {
        m->updateIncludes(includes);
    }
}

void BitfieldField::updateIncludesCommonImpl(IncludesList& includes) const
{
    for (auto& m : m_members) {
        m->updateIncludesCommon(includes);
    }
}

void BitfieldField::updatePluginIncludesImpl(Field::IncludesList& includes) const
{
    for (auto& m : m_members) {
        m->updatePluginIncludes(includes);
    }
}

std::string BitfieldField::getClassDefinitionImpl(
    const std::string& scope,
    const std::string& className) const
{
    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("PREFIX", getClassPrefix(className)));
    replacements.insert(std::make_pair("CLASS_NAME", className));
    replacements.insert(std::make_pair("ORIG_CLASS_NAME", common::nameToClassCopy(name())));
    replacements.insert(std::make_pair("PROT_NAMESPACE", generator().mainNamespace()));
    replacements.insert(std::make_pair("FIELD_BASE_PARAMS", getFieldBaseParams()));
    replacements.insert(std::make_pair("FIELD_OPTS", getFieldOpts(scope)));
    replacements.insert(std::make_pair("NAME", getNameCommonWrapFunc(adjustScopeWithNamespace(scope))));
    replacements.insert(std::make_pair("READ", getCustomRead()));
    replacements.insert(std::make_pair("WRITE", getCustomWrite()));
    replacements.insert(std::make_pair("LENGTH", getCustomLength()));
    replacements.insert(std::make_pair("VALID", getCustomValid()));
    replacements.insert(std::make_pair("REFRESH", getCustomRefresh()));
    replacements.insert(std::make_pair("MEMBERS_STRUCT_DEF", getMembersDef(scope)));
    replacements.insert(std::make_pair("ACCESS", getAccess()));
    replacements.insert(std::make_pair("PUBLIC", getExtraPublic()));
    replacements.insert(std::make_pair("PROTECTED", getFullProtected()));
    replacements.insert(std::make_pair("PRIVATE", getFullPrivate()));
    if (!replacements["FIELD_OPTS"].empty()) {
        replacements["COMMA"] = ',';
    }

    if (!externalRef().empty()) {
        replacements.insert(std::make_pair("MEMBERS_OPT", "<TOpt>"));
    }

    return common::processTemplate(ClassTemplate, replacements);
}

std::string BitfieldField::getExtraDefaultOptionsImpl(const std::string& scope) const
{
    return getExtraOptions(scope, &Field::getDefaultOptions, std::string());
}

std::string BitfieldField::getExtraBareMetalDefaultOptionsImpl(const std::string& base, const std::string& scope) const
{
    return getExtraOptions(scope, &Field::getBareMetalDefaultOptions, base);
}

std::string BitfieldField::getExtraDataViewDefaultOptionsImpl(const std::string& base, const std::string& scope) const
{
    return getExtraOptions(scope, &Field::getDataViewDefaultOptions, base);
}

std::string BitfieldField::getPluginAnonNamespaceImpl(
    const std::string& scope,
    bool forcedSerialisedHidden,
    bool serHiddenParam) const
{
    static_cast<void>(forcedSerialisedHidden);
    auto fullScope = scope + common::nameToClassCopy(name()) + common::membersSuffixStr();
    if (!externalRef().empty()) {
        fullScope += "<>";
    }
    fullScope += "::";

    common::StringsList props;
    for (auto& f : m_members) {
        props.push_back(f->getPluginCreatePropsFunc(fullScope, true, serHiddenParam));
    }

    static const std::string Templ =
        "struct #^#CLASS_NAME#$#Members\n"
        "{\n"
        "    #^#PROPS#$#\n"
        "};\n";

    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
    replacements.insert(std::make_pair("PROPS", common::listToString(props, "\n", common::emptyString())));
    return common::processTemplate(Templ, replacements);
}

std::string BitfieldField::getPluginPropertiesImpl(bool serHiddenParam) const
{
    common::StringsList props;
    props.reserve(m_members.size());
    auto prefix =
        common::nameToClassCopy(name()) + common::membersSuffixStr() +
        "::createProps_";
    for (auto& f : m_members) {
        auto str = ".add(" + prefix + common::nameToAccessCopy(f->name()) + "(";
        if (serHiddenParam) {
            str += common::serHiddenStr();
        }
        str += "))";
        props.push_back(std::move(str));
    }

    return common::listToString(props, "\n", common::emptyString());
}

void BitfieldField::setForcedPseudoImpl()
{
    for (auto& m : m_members) {
        m->setForcedPseudo();
    }
}

void BitfieldField::setForcedNoOptionsConfigImpl()
{
    for (auto& m : m_members) {
        m->setForcedNoOptionsConfig();
    }
}

bool BitfieldField::isVersionDependentImpl() const
{
    assert(
        std::none_of(
            m_members.begin(), m_members.end(),
            [](auto& m)
            {
                return m->isVersionDependent();
            }));
    return Base::isVersionDependentImpl();
}

std::string BitfieldField::getCommonDefinitionImpl(const std::string& fullScope) const
{
    common::StringsList defs;
    auto updatedScope =
        fullScope + common::membersSuffixStr() + "::";
    for (auto& m : m_members) {
        auto str = m->getCommonDefinition(updatedScope);
        if (!str.empty()) {
            defs.emplace_back(std::move(str));
        }
    }

    std::string membersCommon;
    if (!defs.empty()) {
        static const std::string Templ =
            "/// @brief Scope for all the common definitions of the member fields of\n"
            "///     @ref #^#SCOPE#$# field.\n"
            "struct #^#CLASS_NAME#$#MembersCommon\n"
            "{\n"
            "    #^#DEFS#$#\n"
            "};\n";

        common::ReplacementMap repl;
        repl.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
        repl.insert(std::make_pair("SCOPE", fullScope));
        repl.insert(std::make_pair("DEFS", common::listToString(defs, "\n", common::emptyString())));
        membersCommon = common::processTemplate(Templ, repl);
    }

    static const std::string Templ =
        "#^#COMMON#$#\n"
        "/// @brief Scope for all the common definitions of the\n"
        "///     @ref #^#SCOPE#$# field.\n"
        "struct #^#CLASS_NAME#$#Common\n"
        "{\n"
        "    #^#NAME_FUNC#$#\n"
        "};\n\n";

    common::ReplacementMap repl;
    repl.insert(std::make_pair("COMMON", std::move(membersCommon)));
    repl.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
    repl.insert(std::make_pair("SCOPE", fullScope));
    repl.insert(std::make_pair("NAME_FUNC", getCommonNameFunc(fullScope)));
    return common::processTemplate(Templ, repl);
}

std::string BitfieldField::getExtraRefToCommonDefinitionImpl(const std::string& fullScope) const
{
    static const std::string Templ =
        "/// @brief Common types and functions for members of\n"
        "///     @ref #^#SCOPE#$# field.\n"
        "using #^#CLASS_NAME#$#MembersCommon = #^#COMMON_SCOPE#$#MembersCommon;\n\n";

    auto commonScope = scopeForCommon(generator().scopeForField(externalRef(), true, true));
    std::string className = classNameFromFullScope(fullScope);

    common::ReplacementMap repl;
    repl.insert(std::make_pair("SCOPE", fullScope));
    repl.insert(std::make_pair("CLASS_NAME", std::move(className)));
    repl.insert(std::make_pair("COMMON_SCOPE", std::move(commonScope)));

    return common::processTemplate(Templ, repl);
}

bool BitfieldField::verifyAliasImpl(const std::string& fieldName) const
{
    assert(!fieldName.empty());
    auto dotPos = fieldName.find('.');
    std::string firstFieldName(fieldName, 0, dotPos);
    auto iter =
        std::find_if(
            m_members.begin(), m_members.end(),
            [&firstFieldName](auto& f)
            {
                return firstFieldName == f->name();
            });

    if (iter == m_members.end()) {
        return false;
    }

    if (dotPos == std::string::npos) {
        return true;
    }

    std::string restFieldName(fieldName, dotPos + 1);
    return (*iter)->verifyAlias(restFieldName);
}

std::string BitfieldField::getFieldBaseParams() const
{
    auto obj = bitfieldFieldDslObj();
    auto endian = obj.endian();
    return getCommonFieldBaseParams(endian);
}

std::string BitfieldField::getFieldOpts(const std::string& scope) const
{
    StringsList options;

    updateExtraOptions(scope, options);

    return common::listToString(options, ",\n", common::emptyString());
}

std::string BitfieldField::getMembersDef(
    const std::string& scope) const
{
    auto className = common::nameToClassCopy(name());
    std::string memberScope;
    if (!scope.empty()) {
        memberScope = scope + className + common::membersSuffixStr() + "::";
    }

    StringsList membersDefs;
    StringsList membersNames;

    membersDefs.reserve(m_members.size());
    membersNames.reserve(m_members.size());
    for (auto& m : m_members) {
        membersDefs.push_back(m->getClassDefinition(memberScope));
        membersNames.push_back(common::nameToClassCopy(m->name()));
    }

    std::string prefix;
    if (!externalRef().empty()) {
        prefix += "/// @tparam TOpt Protocol options.\n";
        prefix += "template <typename TOpt = " + generator().scopeForOptions(common::defaultOptionsStr(), true, true) + ">";
    }

    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("CLASS_NAME", className));
    replacements.insert(std::make_pair("EXTRA_PREFIX", std::move(prefix)));
    replacements.insert(std::make_pair("MEMBERS_DEFS", common::listToString(membersDefs, "\n", common::emptyString())));
    replacements.insert(std::make_pair("MEMBERS", common::listToString(membersNames, ",\n", common::emptyString())));
    return common::processTemplate(MembersDefTemplate, replacements);

}

std::string BitfieldField::getAccess() const
{
    static const std::string Templ =
        "/// @brief Allow access to internal fields.\n"
        "/// @details See definition of @b COMMS_FIELD_MEMBERS_NAMES macro\n"
        "///     related to @b comms::field::Bitfield class from COMMS library\n"
        "///     for details.\n"
        "///\n"
        "///     The generated types and access functions are:\n"
        "#^#ACCESS_DOC#$#\n"
        "COMMS_FIELD_MEMBERS_NAMES(\n"
        "    #^#NAMES#$#\n"
        ");\n";

    StringsList accessDocList;
    StringsList namesList;
    accessDocList.reserve(m_members.size());
    namesList.reserve(m_members.size());

    auto scope = common::nameToClassCopy(name()) + common::membersSuffixStr() + "::";
    for (auto& m : m_members) {
        namesList.push_back(common::nameToAccessCopy(m->name()));
        std::string accessStr =
            "///     @li @b Field_" + namesList.back() +
            " type and @b field_" + namesList.back() +
            "() access function -\n"
            "///         for " + scope +
            common::nameToClassCopy(m->name()) + " member field.";
        accessDocList.push_back(std::move(accessStr));

    }

    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("ACCESS_DOC", common::listToString(accessDocList, "\n", common::emptyString())));
    replacements.insert(std::make_pair("NAMES", common::listToString(namesList, ",\n", common::emptyString())));
    return common::processTemplate(Templ, replacements);
}

std::string BitfieldField::getExtraOptions(
    const std::string& scope,
    GetExtraOptionsFunc func,
    const std::string& base) const
{
    std::string nextBase;
    std::string ext;
    if (!base.empty()) {
        nextBase = base + "::" + common::nameToClassCopy(name()) + common::membersSuffixStr();
        ext = " : public " + nextBase;
    }

    std::string memberScope = scope + common::nameToClassCopy(name()) + common::membersSuffixStr() + "::";
    StringsList options;
    options.reserve(m_members.size());
    for (auto& m : m_members) {
        assert(m);
        auto opt = (m.get()->*func)(nextBase, memberScope);
        if (!opt.empty()) {
            options.push_back(std::move(opt));
        }
    }

    if (options.empty()) {
        return common::emptyString();
    }

    common::ReplacementMap replacements;
    replacements.insert(std::make_pair("CLASS_NAME", common::nameToClassCopy(name())));
    replacements.insert(std::make_pair("SCOPE", scope));
    replacements.insert(std::make_pair("EXT", std::move(ext)));
    replacements.insert(std::make_pair("OPTIONS", common::listToString(options, "\n", common::emptyString())));
    return common::processTemplate(MembersOptionsTemplate, replacements);
}

} // namespace commsdsl2comms

max_stars_repo_name: Haititi/commsdsl

max_issues_repo_name: Haititi/commsdsl

max_forks_repo_name: Haititi/commsdsl


text:
//
//  axWebApp.cpp
//  HttpServer
//
//  Created by Alexandre Arsenault on 2015-04-08.
//  Copyright (c) 2015 Alexandre Arsenault. All rights reserved.
//

#include "axWebApp.h"
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
//#include "mime_types.h"
//#include "reply.h"
//#include "request.h"
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>

#include "axHtml.h"

axWebApp::axWebApp(const std::string& doc_root) :
http::server::request_handler(doc_root)
{

}

void axWebApp::RequestCallback(const std::string& url,
                               const http::server::request& req,
                               http::server::reply& rep)
{
    std::string r_keyword = url;

    //$(url);

    size_t pos = r_keyword.find_first_of("?");

    if(pos != std::string::npos)
    {
        r_keyword = r_keyword.substr(0, pos);
    }

    axWevEvtMap::iterator it = _eventMap.find(r_keyword);

    if(it != _eventMap.end())
    {
        it->second(req, rep);
    }
    else
    {
        std::string request_path = req.uri;

        std::cout << "res : " << request_path << std::endl;

        // Determine the file extension.
        std::string extension = GetFileExtension(request_path);

        // Open the file to send back.
        std::string full_path = doc_root_ + request_path;

        std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);

        if (!is)
        {
            rep = http::server::reply::stock_reply(http::server::reply::not_found);
            return;
        }

        // Fill out the reply to be sent to the client.
        rep.status = http::server::reply::ok;

        char buf[512];

        while (is.read(buf, sizeof(buf)).gcount() > 0)
        {
            rep.content.append(buf, is.gcount());
        }

        rep.headers.resize(2);
        rep.headers[0].name = "Content-Length";
        rep.headers[0].value = std::to_string(rep.content.size());
        rep.headers[1].name = "Content-Type";
        rep.headers[1].value = http::server::mime_types::extension_to_type(extension);
    }
}

void axWebApp::AddEventFunction(const std::string& name,
                                const axWebEvtFunction& fct)
{
    std::cout << "Add : " << name << " to event map." << std::endl;
    _eventMap.insert(std::pair<std::string, axWebEvtFunction>(name, fct));
}

axVectorPairString axWebApp::GetParameterListFromUrl(const std::string& url) const
{
    axVectorPairString vec;
    std::string tmp = url, name, value;
    vec.clear();

    // Decode form parameter.
    size_t pos = url.find_first_of("?");

    if(pos != std::string::npos)
    {
        tmp = url.substr(pos + 1, tmp.length());
    }

    std::string param;
    while((pos = tmp.find_first_of("&")) != std::string::npos)
    {
        param = tmp.substr(0, pos);
        size_t pos_left = param.find_first_of("=");
        name = param.substr(0, pos_left);
        value = param.substr(pos_left+1, pos);
        vec.push_back(std::pair<std::string, std::string>(name, value));
        tmp = tmp.substr(pos + 1, tmp.length());
    }

    if((pos = tmp.find_first_of("=")) != std::string::npos)
    {
        name = tmp.substr(0, pos);
        value = tmp.substr(pos + 1, tmp.length());
        vec.push_back(axPairString(name, value));
    }

    return vec;
}

max_stars_repo_name: alxarsenault/axServer

max_issues_repo_name: alxarsenault/axServer

max_forks_repo_name: alxarsenault/axServer


text:
/*
 * simple_file_open_close_test.cpp
 *
 *  Created on: 4 Apr 2017
 *      Author: gnx91527
 */
#include <sys/time.h>
#include <boost/program_options.hpp>
#include <iostream>

#include "hdf5_file_operations.h"

namespace opt = boost::program_options;

int main(int argc, char** argv)
{
	int iterations = 0;
	hsize_t dsetSize = 0;
	int dataset = 0;
	int fnum = 1;
	int flush = 0;

	// Declare a group of options that will allowed only on the command line
	opt::options_description options("Performance test options");
	options.add_options()
			("help,h", "Print this help message")
			("fnum,n", opt::value<unsigned int>()->default_value(1), "File number")
			("gpfs,g", opt::value<unsigned int>()->default_value(0), "Use local(0), GPFS0(1) or gpfs0(2)")
			("dataset,d", opt::value<unsigned int>()->default_value(0), "1 - Create Dataset")
			("iterations,i", opt::value<unsigned int>()->default_value(10), "Number of iterations of the test");

	// Parse the command line options
	opt::variables_map vm;
	opt::store(opt::parse_command_line(argc, argv, options), vm);
	opt::notify(vm);

	// If the command-line help option was given, print help and exit
	if (vm.count("help")){
	    std::cout << "usage: simple_writing_performance_test [options]" << std::endl << std::endl;
		std::cout << options << std::endl;
		return 1;
	}

	if (vm.count("fnum")){
		fnum = vm["fnum"].as<unsigned int>();
	}

	if (vm.count("dataset")){
		dataset = vm["dataset"].as<unsigned int>();
	}

	if (vm.count("iterations")){
		iterations = vm["iterations"].as<unsigned int>();
	}

	double times[iterations];

	for (int loop=0; loop < iterations; loop++){
		std::stringstream fname;
		if (vm.count("gpfs")){
			if (vm["gpfs"].as<unsigned int>() == 0){
				fname << "/scratch/gnx91527/latrd/latrd_" << fnum << ".h5";
			}
			if (vm["gpfs"].as<unsigned int>() == 1){
				fname << "/mnt/GPFS01/tmp/gnx91527/latrd/latrd_" << fnum << ".h5";
			}
			if (vm["gpfs"].as<unsigned int>() == 2){
				fname << "/mnt/gpfs02/testdir/gnx91527/latrd/latrd_" << fnum << ".h5";
			}
		} else {
			fname << "/scratch/gnx91527/latrd/latrd_" << fnum << ".h5";
		}

		timeval curTime;
		gettimeofday(&curTime, NULL);
		unsigned long micro = curTime.tv_sec*(u_int64_t)1000000+curTime.tv_usec;
		// Create the file with 4MB alignment
		hid_t fileID = createFile(fname.str(), (4*1024*1024));
		gettimeofday(&curTime, NULL);
		micro = curTime.tv_sec*(u_int64_t)1000000+curTime.tv_usec - micro;
		double tTime = (double)micro / 1000000.0;
		times[loop] = tTime;
		//printf("File creation time: %f\n", tTime);

		if (dataset ==1){
			gettimeofday(&curTime, NULL);
			micro = curTime.tv_sec*(u_int64_t)1000000+curTime.tv_usec;
			// Create the dataset (chunk size is dimension so supply buffSize)
			hid_t dsetID = createDataset(fileID, "uint32", H5T_NATIVE_UINT32, (4*1024*1024), iterations);
			gettimeofday(&curTime, NULL);
			micro = curTime.tv_sec*(u_int64_t)1000000+curTime.tv_usec - micro;
			tTime = (double)micro / 1000000.0;
			//printf("Dataset creation time: %f\n", tTime);
			closeDataset(dsetID);
		}

		gettimeofday(&curTime, NULL);
		micro = curTime.tv_sec*(u_int64_t)1000000+curTime.tv_usec;
		closeFile(fileID);
		gettimeofday(&curTime, NULL);
		micro = curTime.tv_sec*(u_int64_t)1000000+curTime.tv_usec - micro;
		tTime = (double)micro / 1000000.0;
		//printf("File close time: %f\n", tTime);
	}

	FILE *f = fopen("/home/gnx91527/performance.log", "w");
	for (int loop=0; loop < iterations; loop++){
		fprintf(f, "%d %f\n", loop, times[loop]);
	}
	fclose(f);

	return 0;
}

max_stars_repo_name: dls-controls/LATRD

max_issues_repo_name: dls-controls/LATRD

max_forks_repo_name: dls-controls/LATRD


text:
// Copyright (C) 2008-2018 Lorenzo Caminiti
// Distributed under the Boost Software License, Version 1.0 (see accompanying
// file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt).
// See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html

//[mitchell02_push_button
#ifndef PUSH_BUTTON_HPP_
#define PUSH_BUTTON_HPP_

#include <boost/contract.hpp>
#include <cassert>

class push_button {
public:
    // No inv and no bases so contracts optional if no pre, post, and override.

    /* Creation */

    // Create an enabled button.
    push_button() : enabled_(true) {
        boost::contract::check c = boost::contract::constructor(this)
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(enabled()); // Enabled.
            })
        ;
    }

    // Destroy button.
    virtual ~push_button() {
        // Could have omitted contracts here (nothing to check).
        boost::contract::check c = boost::contract::destructor(this);
    }

    /* Queries */

    // If button is enabled.
    bool enabled() const {
        // Could have omitted contracts here (nothing to check).
        boost::contract::check c = boost::contract::public_function(this);
        return enabled_;
    }

    /* Commands */

    // Enable button.
    void enable() {
        boost::contract::check c = boost::contract::public_function(this)
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(enabled()); // Enabled.
            })
        ;

        enabled_ = true;
    }

    // Disable button.
    void disable() {
        boost::contract::check c = boost::contract::public_function(this)
            .postcondition([&] {
                BOOST_CONTRACT_ASSERT(!enabled()); // Disabled.
            })
        ;

        enabled_ = false;
    }

    // Invoke externally when button clicked.
    virtual void on_bn_clicked(boost::contract::virtual_* v = 0) = 0;

private:
    bool enabled_;
};

void push_button::on_bn_clicked(boost::contract::virtual_* v) {
    boost::contract::check c = boost::contract::public_function(v, this)
        .precondition([&] {
            BOOST_CONTRACT_ASSERT(enabled()); // Enabled.
        })
    ;
    assert(false);
}

#endif // #include guard
//]


text: #include <boost/container/pmr/unsynchronized_pool_resource.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#pragma once

#include "dict.hpp"
#include "function_ref.hpp"
#include <iosfwd>
#include <memory>
#include <string>
#include <boost/container/small_vector.hpp>

using boost::container::small_vector;

namespace document { namespace impl {

class shared_keys_t;

class path_t
{
public:

    class element_t
    {
    public:
        element_t(slice_t property);
        element_t(int32_t array_index);
        element_t(const element_t &e);
        bool operator== (const element_t &e) const;
        element_t &operator=(element_t &&other);
        bool is_key() const;
        dict_t::key_t& key() const;
        slice_t key_str() const;
        int32_t index() const;

        const value_t* eval(const value_t* NONNULL) const noexcept;
        static const value_t* eval(char token, slice_t property, int32_t index, const value_t *item NONNULL) noexcept;

    private:
        static const value_t* get_from_array(const value_t* NONNULL, int32_t index) noexcept;

        alloc_slice_t _key_buf;
        std::unique_ptr<dict_t::key_t> _key {nullptr};
        int32_t _index {0};
    };

    path_t(slice_t specifier);
    path_t() = default;

    void add_property(slice_t key);
    void add_index(int index);
    void add_components(slice_t components);

    bool operator== (const path_t& other) const;
    bool operator!= (const path_t& other) const;
    path_t& operator += (const path_t& other);

    void drop(size_t num_to_drop_from_start);

    const small_vector<element_t, 4>& path() const;
    small_vector<element_t, 4>& path();
    bool empty() const;
    size_t size() const;

    const element_t& operator[] (size_t i) const;
    element_t& operator[] (size_t i);

    const value_t* eval(const value_t *root) const noexcept;
    static const value_t* eval(slice_t specifier, const value_t *root NONNULL);
    static const value_t* eval_json_pointer(slice_t specifier, const value_t* root NONNULL);

    explicit operator std::string();

    void write_to(std::ostream &out) const;
    static void write_property(std::ostream &out, slice_t key, bool first = false);
    static void write_index(std::ostream &out, int array_index);

private:
    using each_component_callback = function_ref<bool(char, slice_t, int32_t)>;
    static void for_each_component(slice_t in, bool at_start, each_component_callback);

    small_vector<element_t, 4> _path;
};

} }

max_stars_repo_name: cyberduckninja/RocketJoe

max_issues_repo_name: cyberduckninja/RocketJoe

max_forks_repo_name: cyberduckninja/RocketJoe


text:
//
// Created by Michael Smith on 12/8/15.
//

#include <boost/algorithm/string/join.hpp>
#include "package.hpp"

namespace Puppet {
    using namespace std;

    Package::Package(string name, State ensure, Version version, string source)
            : Resource(name, ensure), version_(move(version)), source_(move(source)) {}

    Package::Version const& Package::version() const
    {
        return version_;
    }

    string const& Package::source() const
    {
        return source_;
    }

    static string print_version(Package::Version const& version)
    {
        return to_string(get<0>(version)) + "." + to_string(get<1>(version)) + "." + to_string(get<2>(version));
    }

    string Package::print() const
    {
        return "package { '" + name() + "':\n\tensure => " + print_ensure(ensure()) + ",\n\tversion => '" + print_version(version()) + "',\n\tsource => '" + source() + "'\n}";
    }

}

ext: cc

max_stars_repo_name: puppetlabs/cppbestpractices

max_issues_repo_name: puppetlabs/cppbestpractices

max_forks_repo_name: puppetlabs/cppbestpractices


text:
/* boost uuid/detail/random_provider_wincrypt implementation
*
* Copyright Jens Maurer 2000
* Copyright 2007 Andy Tompkins.
* Copyright Steven Watanabe 2010-2011
* Copyright 2017 James E. King III
*
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* https://www.boost.org/LICENSE_1_0.txt)
*
* $Id$
*/

#include <cstddef>
#include <boost/config.hpp>
#include <boost/core/ignore_unused.hpp>
#include <boost/move/core.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/winapi/crypt.hpp>
#include <boost/winapi/get_last_error.hpp>
#include <boost/throw_exception.hpp>

#if defined(BOOST_UUID_FORCE_AUTO_LINK) || (!defined(BOOST_ALL_NO_LIB) && !defined(BOOST_UUID_RANDOM_PROVIDER_NO_LIB))
#   if defined(_WIN32_WCE)
#      define BOOST_LIB_NAME "coredll"
#   else
#      define BOOST_LIB_NAME "advapi32"
#   endif
#   if defined(BOOST_AUTO_LINK_NOMANGLE)
#      include <boost/config/auto_link.hpp>
#   else
#      define BOOST_AUTO_LINK_NOMANGLE
#      include <boost/config/auto_link.hpp>
#      undef BOOST_AUTO_LINK_NOMANGLE
#   endif
#endif

namespace boost {
namespace uuids {
namespace detail {

class random_provider_base
{
    BOOST_MOVABLE_BUT_NOT_COPYABLE(random_provider_base)

public:
    random_provider_base()
        : hProv_(0)
    {
        boost::winapi::BOOL_ res = boost::winapi::CryptAcquireContextW(
            &hProv_,
            NULL,
            NULL,
            boost::winapi::PROV_RSA_FULL_,
            boost::winapi::CRYPT_VERIFYCONTEXT_ | boost::winapi::CRYPT_SILENT_);
        if (BOOST_UNLIKELY(!res))
        {
            boost::winapi::DWORD_ err = boost::winapi::GetLastError();
            BOOST_THROW_EXCEPTION(entropy_error(err, "CryptAcquireContext"));
        }
    }

    random_provider_base(BOOST_RV_REF(random_provider_base) that) BOOST_NOEXCEPT : hProv_(that.hProv_)
    {
        that.hProv_ = 0;
    }

    random_provider_base& operator= (BOOST_RV_REF(random_provider_base) that) BOOST_NOEXCEPT
    {
        destroy();
        hProv_ = that.hProv_;
        that.hProv_ = 0;
        return *this;
    }

    ~random_provider_base() BOOST_NOEXCEPT
    {
        destroy();
    }

    //! Obtain entropy and place it into a memory location
    //! \param[in]  buf  the location to write entropy
    //! \param[in]  siz  the number of bytes to acquire
    void get_random_bytes(void *buf, std::size_t siz)
    {
        boost::winapi::BOOL_ res = boost::winapi::CryptGenRandom(
            hProv_,
            boost::numeric_cast<boost::winapi::DWORD_>(siz),
            static_cast<boost::winapi::BYTE_ *>(buf));
        if (BOOST_UNLIKELY(!res))
        {
            boost::winapi::DWORD_ err = boost::winapi::GetLastError();
            BOOST_THROW_EXCEPTION(entropy_error(err, "CryptGenRandom"));
        }
    }

private:
    void destroy() BOOST_NOEXCEPT
    {
        if (hProv_)
        {
            boost::ignore_unused(boost::winapi::CryptReleaseContext(hProv_, 0));
        }
    }

private:
    boost::winapi::HCRYPTPROV_ hProv_;
};

} // detail
} // uuids
} // boost

ext: ipp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
//
// Created by cerussite on 19/06/15.
//

#ifndef MAKE_RULE_HPP
#define MAKE_RULE_HPP

#include <boost/algorithm/string.hpp>
#include <forward_list>
#include <iostream>
#include <regex>
#include <string>
#include <vector>

#include "../variables.hpp"

namespace make {
    namespace detail {
        inline std::regex getPatternRegex(std::string pattern) {
            boost::algorithm::replace_all(pattern, "\\", "\\\\");
            boost::algorithm::replace_all(pattern, ".", "\\.");
            boost::algorithm::replace_all(pattern, "+", "\\+");
            boost::algorithm::replace_all(pattern, "*", "\\*");
            boost::algorithm::replace_all(pattern, "^", "\\^");
            boost::algorithm::replace_all(pattern, "|", "\\|");
            boost::algorithm::replace_all(pattern, "$", "\\$");
            boost::algorithm::replace_all(pattern, "%", "(.+)");
            pattern = "^" + pattern + "$";

            return std::regex(pattern);
        }
        inline bool isMatchToPattern(const std::string &target, std::string pattern) {
            return std::regex_match(target, getPatternRegex(std::move(pattern)));
        }
    } // namespace detail

    class Command {
    private:
        bool _errorIgnored;
        bool _noEchoCommand;
        std::string _command;

    public:
        Command(bool errorIgnored, bool noEchoCommand, std::string command)
            : _errorIgnored(errorIgnored)
            , _noEchoCommand(noEchoCommand)
            , _command(std::move(command)) {}

    public:
        void assignVariables(
            const std::unordered_map<std::string, std::vector<std::string>> &variableMap) {
            _command = make::assignVariables(_command, variableMap);
        }

    public:
        bool isErrorIgnored() const noexcept { return _errorIgnored; }
        bool isNoEchoCommand() const noexcept { return _noEchoCommand; }
        const std::string &command() const { return _command; }

        std::string &command() { return _command; }
    };

    class Rule {
    private:
        std::vector<std::string> _targets, _dependencies;
        std::forward_list<Command> _commands;

    public:
        Rule()
            : Rule({}, {}, {}) {}
        Rule(std::vector<std::string> targets, std::vector<std::string> dependencies,
             std::forward_list<Command> commands)
            : _targets(std::move(targets))
            , _dependencies(std::move(dependencies))
            , _commands(std::move(commands)) {}

        Rule(const Rule &) = default;
        Rule(Rule &&) = default;
        Rule &operator=(const Rule &) = default;
        Rule &operator=(Rule &&) = default;

    public:
        void assignVariablesToCommand(
            const std::unordered_map<std::string, std::vector<std::string>> &variableMap) {
            for (auto &command : _commands) {
                command.assignVariables(variableMap);
            }
            for (auto &target : _targets) {
                target = make::assignVariables(target, variableMap);
            }
            for (auto &dependency : _dependencies) {
                dependency = make::assignVariables(dependency, variableMap);
            }
        }

    public:
        bool isPatternRule() const {
            for (const auto &target : targets()) {
                if (boost::contains(target, "%"))
                    return true;
            }
            for (const auto &dependency : dependencies()) {
                if (boost::contains(dependency, "%"))
                    return true;
            }
            return false;
        }

        bool isPatternRuleMatchTo(const std::string &target) const {
            if (!isPatternRule())
                return false;
            for (const auto &ruleTarget : targets()) {
                if (detail::isMatchToPattern(target, ruleTarget)) {
                    return true;
                }
            }
            return false;
        }

        std::string targetToPlaceholder(const std::string &target) const {
            for (const auto &ruleTarget : targets()) {
                if (boost::contains(ruleTarget, "%")) {
                    const auto regex = detail::getPatternRegex(ruleTarget);
                    std::smatch sm;
                    if (std::regex_match(target, sm, regex)) {
                        return sm[1].str();
                    }
                }
            }
            throw std::runtime_error("dmake bug: targetToPlaceholder(target) must be "
                                     "isPatternRuleMatchTo(target) == true");
        }

    public:
        Rule setPlaceholder(const std::string &placeholder) const {
            std::vector<std::string> targets(std::size(_targets)),
                dependencies(std::size(_dependencies));

            const auto converter = [&placeholder](const std::string &file) {
                return boost::algorithm::replace_all_copy(file, "%", placeholder);
            };

            std::transform(std::begin(_targets), std::end(_targets), std::begin(targets),
                           converter);
            std::transform(std::begin(_dependencies), std::end(_dependencies),
                           std::begin(dependencies), converter);

            return Rule(targets, dependencies, _commands);
        }

    public:
        const std::vector<std::string> &targets() const { return _targets; }

        const std::vector<std::string> &dependencies() const { return _dependencies; }

        const std::forward_list<Command> commands() const { return _commands; }
    };

} // namespace make

#endif // MAKE_RULE_HPP

max_stars_repo_name: SiLeader/dmake

max_issues_repo_name: SiLeader/dmake

max_forks_repo_name: SiLeader/dmake


text:
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/JointState.h>
#include <iostream>
#include <iomanip>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <math.h>

using namespace std;
using namespace boost::asio;

static std::string Base_Port = "";
static std::string cmd_topic = "";
unsigned char startByte = 0xff;
unsigned char endByte = 0xfe;

union Max_Value{
    unsigned char buf[8];
    struct _Float_{
        float _float_vX;
        float _float_vTh;
    }Float_RAM;
}Send_Data;

io_service iosev;
serial_port sp(iosev);

void cmd_velCallback(const geometry_msgs::Twist &twist_aux)
{
    Send_Data.Float_RAM._float_vX = twist_aux.linear.x;
    Send_Data.Float_RAM._float_vTh = twist_aux.angular.z;

    ROS_INFO("cmd_vel linear.x  is %f", twist_aux.linear.x);
    ROS_INFO("cmd_vel angular.z is %f\n", twist_aux.angular.z);

    write(sp, buffer(&startByte, 1));
    write(sp, buffer(Send_Data.buf, 8));
    write(sp, buffer(&endByte, 1));
}

int main(int argc, char** argv){
    ros::init(argc, argv, "velocity_publisher");
    ros::NodeHandle nh_private("~");
    ros::NodeHandle nh;

    if(!nh_private.getParam("cmd_topic", cmd_topic)){
        cmd_topic = "cmd_vel";
    }

    if(!nh_private.getParam("Base_Port", Base_Port)){
        Base_Port = "/dev/ttyUSB1";
    }

    std::cout<<"cmd_vel: "<<cmd_topic<< "\tPort: "<< Base_Port<<std::endl;
    ros::Subscriber cmd_vel_sub = nh.subscribe(cmd_topic, 10, cmd_velCallback);

    sp.open(Base_Port);
    sp.set_option(serial_port::baud_rate(9600));
    sp.set_option(serial_port::flow_control(serial_port::flow_control::none));
    sp.set_option(serial_port::parity(serial_port::parity::none));
    sp.set_option(serial_port::stop_bits(serial_port::stop_bits::one));
    sp.set_option(serial_port::character_size(8));

    ros::spin();                    // check for incoming messages
}


text:
//  Copyright (c)      2013 Thomas Heller
//  Copyright (c) 2007-2012 Hartmut Kaiser
//
//  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)

#if !defined(HPX_PARCELSET_IBVERBS_ACCEPTOR_HPP)
#define HPX_PARCELSET_IBVERBS_ACCEPTOR_HPP

#include <hpx/hpx_fwd.hpp>
#include <hpx/runtime/parcelset/ibverbs/ibverbs_errors.hpp>
#include <hpx/runtime/parcelset/ibverbs/context.hpp>
#include <hpx/runtime/parcelset/ibverbs/helper.hpp>
#include <hpx/util/io_service_pool.hpp>

#include <boost/asio/basic_io_object.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <boost/static_assert.hpp>
#include <boost/system/system_error.hpp>
#include <boost/thread/thread_time.hpp>
#include <boost/scope_exit.hpp>
#include <boost/atomic.hpp>

#include <netdb.h>
#include <rdma/rdma_cma.h>

///////////////////////////////////////////////////////////////////////////////
namespace hpx { namespace parcelset { namespace ibverbs
{
    ///////////////////////////////////////////////////////////////////////////
    //
    struct basic_acceptor_options
    {
        template <typename T>
        struct option
        {
            /*
            option(T const& num) : val_(num) {}
            T val_;
            */
        };

        /*
        typedef option<std::size_t> msg_num;
        typedef option<bool> manage;
        */
    };

    ///////////////////////////////////////////////////////////////////////////
    template <typename Service>
    class basic_acceptor
      : public boost::asio::basic_io_object<Service>,
        public basic_acceptor_options
    {
    public:
        explicit basic_acceptor(boost::asio::io_service &io_service)
          : boost::asio::basic_io_object<Service>(io_service)
        {
        }

        void open(boost::system::error_code &ec = boost::system::throws)
        {
            this->service.open(this->implementation, ec);
        }

        void close(boost::system::error_code &ec = boost::system::throws)
        {
            this->service.close(this->implementation, ec);
        }

        void bind(
            boost::asio::ip::tcp::endpoint const & ep,
            boost::system::error_code &ec = boost::system::throws)
        {
            this->service.bind(this->implementation, ep, ec);
        }

        // synchronous and asynchronous accept
        template <typename Service_>
        void accept(basic_context<Service_> & conn,
            boost::system::error_code &ec = boost::system::throws)
        {
            return this->service.accept(this->implementation, conn, ec);
        }

        template <typename Service_, typename Handler>
        void async_accept(basic_context<Service_> & conn, Handler handler)
        {
            this->service.async_accept(this->implementation, conn, handler);
        }
    };

    ///////////////////////////////////////////////////////////////////////////
    namespace detail
    {
        ///////////////////////////////////////////////////////////////////////
        template <typename Handler, typename Implementation, typename Service>
        class accept_operation
          : public boost::enable_shared_from_this<
                accept_operation<Handler, Implementation, Service> >
        {
            typedef boost::shared_ptr<Implementation> implementation_type;

        public:
            accept_operation(implementation_type &impl,
                  boost::asio::io_service &io_service,
                  basic_context<Service> & conn, Handler handler)
              : impl_(impl),
                io_service_(io_service),
                conn_(conn),
                handler_(handler)
            {}

            void call() const
            {
                implementation_type impl = impl_.lock();
                if (impl)
                {
                    boost::system::error_code ec;
                    if (!impl->get_connect_request(conn_, ec) && !ec) {
                        // repost this function
                        io_service_.post(boost::bind(
                            &accept_operation::call, this->shared_from_this()));
                    }
                    else {
                        io_service_.post(boost::bind(
                            &accept_operation::try_accept, this->shared_from_this()));
                    }
                }
                else
                {
                    io_service_.post(
                        boost::asio::detail::bind_handler(handler_,
                            boost::asio::error::operation_aborted));
                }
            }

        private:
            void try_accept() const
            {
                implementation_type impl = impl_.lock();
                if (impl)
                {
                    boost::system::error_code ec;
                    if (!impl->try_accept(conn_, ec) && !ec) {
                        // repost this function
                        io_service_.post(boost::bind(
                            &accept_operation::try_accept, this->shared_from_this()));
                    }
                    else {
                        io_service_.post(
                            boost::asio::detail::bind_handler(handler_, ec));
                    }
                }
                else
                {
                    io_service_.post(
                        boost::asio::detail::bind_handler(handler_,
                            boost::asio::error::operation_aborted));
                }
            }

            boost::weak_ptr<Implementation> impl_;
            boost::asio::io_service &io_service_;
            basic_context<Service> & conn_;
            Handler handler_;
        };
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Implementation>
    class basic_acceptor_service
      : public boost::asio::io_service::service
    {
    public:
        static boost::asio::io_service::id id;

        explicit basic_acceptor_service(boost::asio::io_service &io_service)
          : boost::asio::io_service::service(io_service)
        {}

        ~basic_acceptor_service()
        {}

        typedef boost::shared_ptr<Implementation> implementation_type;

        void construct(implementation_type &impl)
        {
            impl.reset(new Implementation());
        }

        void destroy(implementation_type &impl)
        {
            impl->destroy();
            impl.reset();
        }

        void open(implementation_type &impl, boost::system::error_code &ec)
        {
            impl->open(ec);
            boost::asio::detail::throw_error(ec);
        }

        void close(implementation_type &impl, boost::system::error_code &ec)
        {
            impl->close(ec);
            boost::asio::detail::throw_error(ec);
        }

        void bind(implementation_type &impl,
            boost::asio::ip::tcp::endpoint const & ep,
            boost::system::error_code &ec)
        {
            impl->bind(ep, ec);
            boost::asio::detail::throw_error(ec);
        }

        // synchronous and asynchronous accept
        template <typename Service>
        void accept(implementation_type &impl,
            basic_context<Service> & conn, boost::system::error_code &ec)
        {
            while (!impl->try_get_connect_request(conn, ec) && !ec)
                /* just wait for operation to succeed */;
            while (!impl->try_accept(conn, ec) && !ec)
                /* just wait for operation to succeed */;
            boost::asio::detail::throw_error(ec);
        }

        template <typename Service, typename Handler>
        void async_accept(implementation_type &impl,
            basic_context<Service> & conn, Handler handler)
        {
            typedef detail::accept_operation<Handler, Implementation, Service>
                operation_type;

            boost::shared_ptr<operation_type> op(
                boost::make_shared<operation_type>(
                    impl, this->get_io_service(), conn, handler));

            this->get_io_service().post(boost::bind(&operation_type::call, op));
        }

    private:
        void shutdown_service()
        {}
    };

    template <typename Implementation>
    boost::asio::io_service::id basic_acceptor_service<Implementation>::id;

    ///////////////////////////////////////////////////////////////////////////
    class acceptor_impl
    {
    public:
        acceptor_impl()
          : event_channel_(0),
            listener_(0),
            executing_operation_(0),
            aborted_(false),
            close_operation_(false)
        {}

        ~acceptor_impl()
        {
            boost::system::error_code ec;
            close(ec);
        }

        void open(boost::system::error_code &ec)
        {
        }

        void bind(
            boost::asio::ip::tcp::endpoint const & ep
          , boost::system::error_code &ec)
        {
            if(event_channel_)
            {
                HPX_IBVERBS_THROWS_IF(ec, boost::asio::error::already_connected);
            }
            else
            {
                event_channel_ = rdma_create_event_channel();
                if(!event_channel_)
                {
                    int verrno = errno;
                    close(ec);
                    boost::system::error_code err(verrno, boost::system::system_category());
                    HPX_IBVERBS_THROWS_IF(
                        ec
                      , err
                    );
                    return;
                }
                set_nonblocking(event_channel_->fd, ec);
                if(ec)
                {
                    close(ec);
                    return;
                }

                int ret = 0;
                ret = rdma_create_id(event_channel_, &listener_, NULL, RDMA_PS_TCP);

                if(ret)
                {
                    int verrno = errno;
                    close(ec);
                    boost::system::error_code err(verrno, boost::system::system_category());
                    HPX_IBVERBS_THROWS_IF(
                        ec
                      , err
                    );
                    return;
                }

                std::string host = ep.address().to_v4().to_string();
                std::string port = boost::lexical_cast<std::string>(ep.port());

                addrinfo *addr;

                getaddrinfo(host.c_str(), port.c_str(), NULL, &addr);

                ret = rdma_bind_addr(listener_, addr->ai_addr);

                freeaddrinfo(addr);
                if(ret)
                {
                    int verrno = errno;
                    close(ec);
                    boost::system::error_code err(verrno, boost::system::system_category());
                    HPX_IBVERBS_THROWS_IF(
                        ec
                      , err
                    );
                    return;
                }
                ret = rdma_listen(listener_, 10); /* backlog = 10 is arbitrary */
                if(ret)
                {
                    int verrno = errno;
                    close(ec);
                    boost::system::error_code err(verrno, boost::system::system_category());
                    HPX_IBVERBS_THROWS_IF(
                        ec
                      , err
                    );
                    return;
                }
                HPX_IBVERBS_RESET_EC(ec);
            }
        }

        void close(boost::system::error_code &ec)
        {
            if(!event_channel_)
            {
                HPX_IBVERBS_RESET_EC(ec);
                return;
            }

            close_operation_.store(true);

            BOOST_SCOPE_EXIT(&close_operation_) {
                close_operation_.store(false);
            } BOOST_SCOPE_EXIT_END

            // wait for pending operations to return
            while (executing_operation_.load())
                ;

            if(event_channel_)
            {
                rdma_destroy_event_channel(event_channel_);
                event_channel_ = 0;
            }
            else {
                HPX_IBVERBS_THROWS_IF(ec, boost::asio::error::not_connected);
            }

            if(listener_)
            {
                rdma_destroy_id(listener_);
                listener_ = 0;
            }

            HPX_IBVERBS_RESET_EC(ec);
        }

        void destroy()
        {
            aborted_.store(true);
            BOOST_SCOPE_EXIT(&aborted_) {
                aborted_.store(false);
            } BOOST_SCOPE_EXIT_END

            // cancel operation
            while (executing_operation_.load())
                ;
        }

        bool get_next_rdma_event(rdma_cm_event & event, boost::system::error_code &ec)
        {
            ++executing_operation_;
            BOOST_SCOPE_EXIT(&executing_operation_) {
                --executing_operation_;
            } BOOST_SCOPE_EXIT_END

            if (close_operation_.load() || !event_channel_) {
                HPX_IBVERBS_THROWS_IF(ec, boost::asio::error::not_connected);
                return false;
            }

            if (aborted_.load()) {
                aborted_.store(false);
                HPX_IBVERBS_THROWS_IF(ec, boost::asio::error::connection_aborted);
                return false;
            }

            return get_next_event(event_channel_, event, this, ec);
        }

        template <typename Service>
        bool get_connect_request(basic_context<Service> & conn, boost::system::error_code &ec)
        {
            if (close_operation_.load() || !event_channel_) {
                HPX_IBVERBS_THROWS_IF(ec, boost::asio::error::not_connected);
                return false;
            }

            rdma_cm_event event;
            if(!get_next_rdma_event(event, ec))
            {
                return false;
            }

            if(event.event == RDMA_CM_EVENT_CONNECT_REQUEST)
            {
                rdma_conn_param cm_params;
                std::memset(&cm_params, 0, sizeof(rdma_conn_param));
                cm_params.initiator_depth = cm_params.responder_resources = 1;
                cm_params.rnr_retry_count = 7; // infinite retry

                conn.build_connection(event.id, ec);
                if(ec)
                {
                    return false;
                }

                conn.on_preconnect(event.id, ec);
                if(ec)
                {
                    return false;
                }

                rdma_accept(event.id, &cm_params);
                return true;
            }
            return false;
        }

        template <typename Service>
        bool try_accept(basic_context<Service> & conn, boost::system::error_code &ec)
        {
            if (close_operation_.load() || !event_channel_) {
                HPX_IBVERBS_THROWS_IF(ec, boost::asio::error::not_connected);
                return false;
            }

            rdma_cm_event event;
            if(!get_next_rdma_event(event, ec))
            {
                return false;
            }
            if(ec)
            {
                return false;
            }
            if(event.event == RDMA_CM_EVENT_ESTABLISHED)
            {
                conn.on_connection(event.id, ec);
                if(ec)
                {
                    return false;
                }
                HPX_IBVERBS_RESET_EC(ec);
                return true;
            }

            return false;
        }

        void on_disconnect(rdma_cm_id * id)
        {
        }

    private:
        rdma_event_channel *event_channel_;
        rdma_cm_id *listener_;

        boost::atomic<boost::uint16_t> executing_operation_;
        boost::atomic<bool> aborted_;
        boost::atomic<bool> close_operation_;
    };

    ///////////////////////////////////////////////////////////////////////////
    typedef basic_acceptor<
        basic_acceptor_service<acceptor_impl>
    > acceptor;
}}}

#endif

max_stars_repo_name: andreasbuhr/hpx

max_issues_repo_name: andreasbuhr/hpx

max_forks_repo_name: andreasbuhr/hpx