text:
#include <stdio.h>
#include <stdlib.h>

#include <Eigen/Geometry>
#include <chrono>
#include <functional>
#include <iostream>
#include <map>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>

#ifndef SIMPLE_KMEANS_CLUSTERING_HPP
#define SIMPLE_KMEANS_CLUSTERING_HPP

namespace simple_kmeans_clustering {
class SimpleKMeansClustering {
 private:
  SimpleKMeansClustering() {}

  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static uint32_t GetClosestCluster(const Datatype& datapoint,
                                    const std::function<double(const Datatype&, const Datatype&)>& distance_fn,
                                    const std::vector<Datatype, Allocator>& cluster_centers) {
    int64_t best_label = -1;
    double best_distance = INFINITY;
    for (size_t cluster = 0; cluster < cluster_centers.size(); cluster++) {
      const Datatype& cluster_center = cluster_centers[cluster];
      const double distance = distance_fn(cluster_center, datapoint);
      if (distance < best_distance) {
        best_distance = distance;
        best_label = (int64_t)cluster;
      }
    }
    assert(best_label >= 0);
    return (uint32_t)best_label;
  }

  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static std::vector<uint32_t> PerformSingleClusteringIteration(
      const std::vector<Datatype, Allocator>& data,
      const std::function<double(const Datatype&, const Datatype&)>& distance_fn,
      const std::vector<Datatype, Allocator>& cluster_centers) {
    std::vector<uint32_t> cluster_labels(data.size());
    for (size_t idx = 0; idx < data.size(); idx++) {
      const Datatype& datapoint = data[idx];
      const uint32_t label = GetClosestCluster(datapoint, distance_fn, cluster_centers);
      cluster_labels[idx] = label;
    }
    return cluster_labels;
  }

  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static std::vector<Datatype, Allocator> ComputeClusterCenters(
      const std::vector<Datatype, Allocator>& data, const std::vector<uint32_t>& cluster_labels,
      const std::function<Datatype(const std::vector<Datatype, Allocator>&)>& average_fn, const uint32_t num_clusters) {
    assert(data.size() == cluster_labels.size());
    // Separate the datapoints into their clusters
    std::vector<std::vector<Datatype, Allocator>> clustered_data(num_clusters);
    for (size_t idx = 0; idx < data.size(); idx++) {
      const Datatype& datapoint = data[idx];
      const uint32_t label = cluster_labels[idx];
      clustered_data[label].push_back(datapoint);
    }
    // Compute the center of each cluster
    std::vector<Datatype, Allocator> cluster_centers(num_clusters);
    for (uint32_t cluster = 0; cluster < num_clusters; cluster++) {
      const std::vector<Datatype, Allocator>& cluster_data = clustered_data[cluster];
      cluster_centers[cluster] = average_fn(cluster_data);
    }
    return cluster_centers;
  }

  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static std::vector<Datatype, Allocator> ComputeClusterCentersWeighted(
      const std::vector<Datatype, Allocator>& data, const std::vector<double>& weights,
      const std::vector<uint32_t>& cluster_labels,
      const std::function<Datatype(const std::vector<Datatype, Allocator>&, const std::vector<double>&)>& average_fn,
      const uint32_t num_clusters) {
    assert(data.size() == cluster_labels.size());

    // Separate the datapoints into their clusters
    std::vector<std::vector<Datatype, Allocator>> clustered_data(num_clusters);
    std::vector<std::vector<double>> clustered_weights(num_clusters);
    for (size_t idx = 0; idx < data.size(); idx++) {
      const Datatype& datapoint = data[idx];
      const double weight = weights[idx];
      const uint32_t label = cluster_labels[idx];

      clustered_data[label].push_back(datapoint);
      clustered_weights[label].push_back(weight);
    }

    // Compute the center of each cluster
    std::vector<Datatype, Allocator> cluster_centers(num_clusters);
    for (uint32_t cluster = 0; cluster < num_clusters; cluster++) {
      const std::vector<Datatype, Allocator>& cluster_data = clustered_data[cluster];
      const std::vector<double>& cluster_weights = clustered_weights[cluster];
      cluster_centers[cluster] = average_fn(cluster_data, cluster_weights);
    }
    return cluster_centers;
  }

  static bool CheckForConvergence(const std::vector<uint32_t>& old_labels, const std::vector<uint32_t>& new_labels) {
    assert(old_labels.size() == new_labels.size());
    for (size_t idx = 0; idx < old_labels.size(); idx++) {
      const uint32_t old_label = old_labels[idx];
      const uint32_t new_label = new_labels[idx];
      if (old_label != new_label) {
        return false;
      }
    }
    return true;
  }

 public:
  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static std::pair<std::vector<uint32_t>, std::vector<Datatype, Allocator>> Cluster(
      const std::vector<Datatype, Allocator>& data,
      const std::function<double(const Datatype&, const Datatype&)>& distance_fn,
      const std::function<Datatype(const std::vector<Datatype, Allocator>&)>& average_fn,
      std::vector<Datatype, Allocator> cluster_centers) {
    const uint32_t num_clusters = cluster_centers.size();
    assert(num_clusters < std::numeric_limits<uint32_t>::max());

    // Run the first iteration of clustering
    std::vector<uint32_t> cluster_labels = PerformSingleClusteringIteration(data, distance_fn, cluster_centers);

    // Itterate until converged
    bool converged = false;
    uint32_t iteration = 1u;
    while (!converged) {
      // Update cluster centers
      cluster_centers = ComputeClusterCenters(data, cluster_labels, average_fn, num_clusters);
      // Cluster with the new centers
      std::vector<uint32_t> new_cluster_labels = PerformSingleClusteringIteration(data, distance_fn, cluster_centers);
      // Check for convergence
      converged = CheckForConvergence(cluster_labels, new_cluster_labels);
      cluster_labels = new_cluster_labels;
      iteration++;
    }
    std::cerr << "[K-means clustering] Clustering converged after " << iteration << " iterations" << std::endl;
    return std::make_pair(cluster_labels, cluster_centers);
  }

  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static std::vector<uint32_t> Cluster(
      const std::vector<Datatype, Allocator>& data,
      const std::function<double(const Datatype&, const Datatype&)>& distance_fn,
      const std::function<Datatype(const std::vector<Datatype, Allocator>&)>& average_fn, const uint32_t num_clusters,
      const bool do_preliminary_clustering = false) {
    assert(data.size() > 0);
    assert(num_clusters > 0);
    if (num_clusters == 1) {
      std::cerr << "[K-means clustering] Provided num_clusters = 1, returning default labels for cluster 0"
                << std::endl;
      return std::vector<uint32_t>(data.size(), 0u);
    }
    // Prepare an RNG for cluster initialization
    auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::mt19937_64 prng(seed);
    std::uniform_int_distribution<size_t> initialization_distribution(0u, data.size() - 1);
    // Initialize cluster centers
    std::vector<Datatype, Allocator> cluster_centers;
    // Make sure we have enough datapoints to do meaningful preliminary clustering
    bool enable_preliminary_clustering = do_preliminary_clustering;
    if (enable_preliminary_clustering) {
      const size_t subset_size = (size_t)ceil((double)data.size() * 0.1);
      if (subset_size >= (num_clusters * 5)) {
        enable_preliminary_clustering = true;
        std::cerr << "[K-means clustering] Preliminary clustering enabled, using subset of " << subset_size
                  << " datapoints from " << data.size() << " total" << std::endl;
      } else {
        enable_preliminary_clustering = false;
        std::cerr << "[K-means clustering] Preliminary clustering disabled as input data is too small w.r.t. number of "
                     "clusters"
                  << std::endl;
      }
    }
    if (enable_preliminary_clustering) {
      // Select a random 10% of the input data
      const size_t subset_size = (size_t)ceil((double)data.size() * 0.1);
      // This makes sure we don't get duplicates
      std::map<size_t, uint8_t> index_map;
      while (index_map.size() < subset_size) {
        const size_t random_index = initialization_distribution(prng);
        index_map[random_index] = 1u;
      }
      std::vector<Datatype, Allocator> random_subset;
      random_subset.reserve(subset_size);
      for (auto itr = index_map.begin(); itr != index_map.end(); ++itr) {
        if (itr->second == 1u) {
          const size_t random_index = itr->first;
          const Datatype& random_element = data[random_index];
          random_subset.push_back(random_element);
        }
      }
      assert(random_subset.size() == subset_size);
      // Run clustering on the subset
      std::vector<uint32_t> random_subset_labels = Cluster(random_subset, distance_fn, average_fn, num_clusters, false);
      // Now we use the centers of the clusters to form the cluster centers
      cluster_centers = ComputeClusterCenters(random_subset, random_subset_labels, average_fn, num_clusters);
    } else {
      // This makes sure we don't get duplicates
      std::map<size_t, uint8_t> index_map;
      while (index_map.size() < num_clusters) {
        const size_t random_index = initialization_distribution(prng);
        index_map[random_index] = 1u;
      }
      cluster_centers.reserve(num_clusters);
      for (auto itr = index_map.begin(); itr != index_map.end(); ++itr) {
        if (itr->second == 1u) {
          const size_t random_index = itr->first;
          const Datatype& random_element = data[random_index];
          cluster_centers.push_back(random_element);
        }
      }
    }
    assert(cluster_centers.size() == num_clusters);
    return Cluster(data, distance_fn, average_fn, cluster_centers).first;
  }

  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static std::pair<std::vector<uint32_t>, std::vector<Datatype, Allocator>> ClusterWeighted(
      const std::vector<Datatype, Allocator>& data, const std::vector<double>& weights,
      const std::function<double(const Datatype&, const Datatype&)>& distance_fn,
      const std::function<Datatype(const std::vector<Datatype, Allocator>&, const std::vector<double>&)>& average_fn,
      std::vector<Datatype, Allocator> cluster_centers) {
    const uint32_t num_clusters = cluster_centers.size();
    assert(num_clusters < std::numeric_limits<uint32_t>::max());

    // Run the first iteration of clustering
    std::vector<uint32_t> cluster_labels = PerformSingleClusteringIteration(data, distance_fn, cluster_centers);
    // Itterate until converged
    bool converged = false;
    uint32_t iteration = 1u;
    while (!converged) {
      // Update cluster centers
      cluster_centers = ComputeClusterCentersWeighted(data, weights, cluster_labels, average_fn, num_clusters);
      // Cluster with the new centers
      std::vector<uint32_t> new_cluster_labels = PerformSingleClusteringIteration(data, distance_fn, cluster_centers);
      // Check for convergence
      converged = CheckForConvergence(cluster_labels, new_cluster_labels);
      cluster_labels = new_cluster_labels;
      iteration++;
    }
    std::cerr << "[K-means clustering] Clustering converged after " << iteration << " iterations" << std::endl;
    return std::make_pair(cluster_labels, cluster_centers);
  }

  template <typename Datatype, typename Allocator = std::allocator<Datatype>>
  static std::vector<uint32_t> ClusterWeighted(
      const std::vector<Datatype, Allocator>& data, const std::vector<double>& weights,
      const std::function<double(const Datatype&, const Datatype&)>& distance_fn,
      const std::function<Datatype(const std::vector<Datatype, Allocator>&, const std::vector<double>&)>& average_fn,
      const uint32_t num_clusters, const bool do_preliminary_clustering = false) {
    assert(data.size() > 0);
    assert(num_clusters > 0);

    if (num_clusters == 1) {
      std::cerr << "[K-means clustering] Provided num_clusters = 1, returning default labels for cluster 0"
                << std::endl;
      return std::vector<uint32_t>(data.size(), 0u);
    }

    // Prepare an RNG for cluster initialization
    auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count();
    std::mt19937_64 prng(seed);
    std::uniform_int_distribution<size_t> initialization_distribution(0u, data.size() - 1);
    // Initialize cluster centers
    std::vector<Datatype, Allocator> cluster_centers;

    // Make sure we have enough datapoints to do meaningful preliminary clustering
    bool enable_preliminary_clustering = do_preliminary_clustering;
    if (enable_preliminary_clustering) {
      const size_t subset_size = (size_t)ceil((double)data.size() * 0.1);
      if (subset_size >= (num_clusters * 5)) {
        enable_preliminary_clustering = true;
        std::cerr << "[K-means clustering] Preliminary clustering enabled, using subset of " << subset_size
                  << " datapoints from " << data.size() << " total" << std::endl;
      } else {
        enable_preliminary_clustering = false;
        std::cerr << "[K-means clustering] Preliminary clustering disabled as input data is too small w.r.t. number of "
                     "clusters"
                  << std::endl;
      }
    }

    if (enable_preliminary_clustering) {
      // Select a random 10% of the input data
      const size_t subset_size = (size_t)ceil((double)data.size() * 0.1);
      // This makes sure we don't get duplicates
      std::map<size_t, uint8_t> index_map;
      while (index_map.size() < subset_size) {
        const size_t random_index = initialization_distribution(prng);
        index_map[random_index] = 1u;
      }
      std::vector<Datatype, Allocator> random_subset;
      random_subset.reserve(subset_size);
      for (auto itr = index_map.begin(); itr != index_map.end(); ++itr) {
        if (itr->second == 1u) {
          const size_t random_index = itr->first;
          const Datatype& random_element = data[random_index];
          random_subset.push_back(random_element);
        }
      }
      assert(random_subset.size() == subset_size);
      // Run clustering on the subset
      std::vector<uint32_t> random_subset_labels =
          ClusterWeighted(random_subset, weights, distance_fn, average_fn, num_clusters, false);
      // Now we use the centers of the clusters to form the cluster centers
      cluster_centers =
          ComputeClusterCentersWeighted(random_subset, weights, random_subset_labels, average_fn, num_clusters);
    } else {
      // This makes sure we don't get duplicates
      std::map<size_t, uint8_t> index_map;
      while (index_map.size() < num_clusters) {
        const size_t random_index = initialization_distribution(prng);
        index_map[random_index] = 1u;
      }
      cluster_centers.reserve(num_clusters);
      for (auto itr = index_map.begin(); itr != index_map.end(); ++itr) {
        if (itr->second == 1u) {
          const size_t random_index = itr->first;
          const Datatype& random_element = data[random_index];
          cluster_centers.push_back(random_element);
        }
      }
    }

    assert(cluster_centers.size() == num_clusters);
    return ClusterWeighted(data, weights, distance_fn, average_fn, cluster_centers).first;
  }
};
}  // namespace simple_kmeans_clustering
#endif  // SIMPLE_KMEANS_CLUSTERING_HPP


text:
/**
   @author Shizuko Hattori
   @author Shin'ichiro Nakaoka
*/

#include "RTCItem.h"
#include "BridgeConf.h"
#include "OpenRTMUtil.h"
#include <cnoid/BodyItem>
#include <cnoid/Link>
#include <cnoid/Sensor>
#include <cnoid/ItemManager>
#include <cnoid/Archive>
#include <cnoid/FileUtil>
#include <cnoid/ExecutablePath>
#include <cnoid/MessageView>
#include <cnoid/Sleep>
#include <rtm/CorbaNaming.h>
#include <boost/bind.hpp>
#include <boost/regex.hpp>
#include "gettext.h"

using namespace boost;
using namespace cnoid;

namespace {
const bool TRACE_FUNCTIONS = false;
}

void RTCItem::initialize(ExtensionManager* ext)
{
    static bool initialized = false;
    if(!initialized){
        ext->itemManager().registerClass<RTCItem>(N_("RTCItem"));
        ext->itemManager().addCreationPanel<RTCItem>();
        initialized = true;
    }
}

RTCItem::RTCItem()
    : os(MessageView::instance()->cout()),
      periodicType(N_PERIODIC_TYPE, CNOID_GETTEXT_DOMAIN_NAME)
{
    rtcomp = 0;
    moduleName.clear();
    mv = MessageView::instance();

    periodicRate = 1000;
    periodicType.setSymbol(PERIODIC_EXECUTION_CONTEXT,  N_("PeriodicExecutionContext"));
    periodicType.setSymbol(SYNCH_EXT_TRIGGER,  N_("SynchExtTriggerEC"));
    periodicType.setSymbol(EXT_TRIG_EXECUTION_CONTEXT,  N_("ExtTrigExecutionContext"));
    periodicType.setSymbol(CHOREONOID_EXECUTION_CONTEXT,  N_("ChoreonoidExecutionContext"));
    periodicType.select(PERIODIC_EXECUTION_CONTEXT);
    oldType = PERIODIC_EXECUTION_CONTEXT;
    properties.clear();
    properties.insert(make_pair(string("exec_cxt.periodic.type"), periodicType.selectedSymbol()));
    stringstream ss;
    ss << periodicRate;
    properties.insert(make_pair(string("exec_cxt.periodic.rate"), ss.str()));
}

RTCItem::RTCItem(const RTCItem& org)
    : os(MessageView::instance()->cout()),
      Item(org),
      periodicType(org.periodicType)
{
    rtcomp = org.rtcomp;
    moduleName = org.moduleName;
    mv = MessageView::instance();
    periodicRate = org.periodicRate;
    oldType = org.oldType;
    properties = org.properties;
}

RTCItem::~RTCItem()
{

}

void RTCItem::onPositionChanged()
{
    if(!rtcomp){
        rtcomp = new RTComponent(moduleName, properties);
    }
}

void RTCItem::onDisconnectedFromRoot()
{
    if(rtcomp){
        rtcomp->deleteRTC(false);
        delete rtcomp;
        rtcomp = 0;
    }
}

ItemPtr RTCItem::doDuplicate() const
{
    return new RTCItem(*this);
}

void RTCItem::setModuleName(const std::string& name)
{
    if(moduleName!=name){
        moduleName = name;
        if(rtcomp){
            delete rtcomp;
        }
        rtcomp = new RTComponent(moduleName, properties);
    }
}

void RTCItem::setPeriodicType(int type)
{
    if(oldType != type){
        oldType = type;
        properties["exec_cxt.periodic.type"] = periodicType.symbol(type);
        if(rtcomp){
            delete rtcomp;
        }
        rtcomp = new RTComponent(moduleName, properties);
    }
}

void RTCItem::setPeriodicRate(int rate)
{
    if(periodicRate!=rate){
        periodicRate = rate;
        stringstream ss;
        ss << periodicRate;
        properties["exec_cxt.periodic.rate"] = ss.str();
        if(rtcomp){
            delete rtcomp;
        }
        rtcomp = new RTComponent(moduleName, properties);
    }
}

void RTCItem::doPutProperties(PutPropertyFunction& putProperty)
{
    Item::doPutProperties(putProperty);
    putProperty(_("RTC module Name"), moduleName,
                boost::bind(&RTCItem::setModuleName, this, _1), true);
    putProperty(_("Periodic type"), periodicType,
                boost::bind((bool(Selection::*)(int))&Selection::select, &periodicType, _1));
    setPeriodicType(periodicType.selectedIndex());
    putProperty(_("Periodic Rate"), periodicRate,
                boost::bind(&RTCItem::setPeriodicRate, this, _1), true);
}

bool RTCItem::store(Archive& archive)
{
    if(!Item::store(archive)){
        return false;
    }
    archive.writeRelocatablePath("moduleName", moduleName);
    archive.write("periodicType", periodicType.selectedSymbol());
    archive.write("periodicRate", periodicRate);
    return true;
}

bool RTCItem::restore(const Archive& archive)
{
    if(!Item::restore(archive)){
        return false;
    }
    string value;
    if(archive.read("moduleName", value)){
        moduleName = archive.expandPathVariables(value);
    }
    string symbol;
    if(archive.read("periodicType", symbol)){
        periodicType.select(symbol);
        oldType = periodicType.selectedIndex();
    }
    archive.read("periodicRate", periodicRate);
    return true;
}

RTComponent::RTComponent(string moduleName_)
{
    rtc_ = 0;
    rtcRef = 0;
    if(moduleName_.empty()){
        return;
    }
    PropertyMap prop;
    prop.clear();
    init(moduleName_, prop);
}

RTComponent::RTComponent(string moduleName_, PropertyMap& prop)
{
    rtc_ = 0;
    rtcRef = 0;
    if(moduleName_.empty()){
        return;
    }
    init(moduleName_, prop);
}

RTComponent::~RTComponent()
{
    deleteRTC(true);
}

void RTComponent::init(string moduleName_, PropertyMap& prop)
{
    mv = MessageView::instance();
    moduleName = moduleName_;
    createRTC(prop);
}

bool  RTComponent::createRTC(PropertyMap& prop)
{
    filesystem::path modulePath(moduleName);
    string moduleNameLeaf = modulePath.leaf().string();
    size_t i = moduleNameLeaf.rfind('.');
    if(i != string::npos){
        componentName = moduleNameLeaf.substr(0, i);
    } else {
        componentName = moduleNameLeaf;
    }

    if(!checkAbsolute(modulePath)){
        modulePath =
            filesystem::path(executableTopDirectory()) /
            CNOID_PLUGIN_SUBDIR / "rtc" / modulePath;
    }

    string actualFilename;

    if(filesystem::exists(modulePath)){
        actualFilename = getNativePathString(modulePath);
        if(modulePath.extension() == SUFFIX_SHARED_EXT){
            string initFunc(componentName + "Init");
            setupModules(actualFilename, initFunc, componentName, prop);
        } else {
            createProcess(actualFilename, prop);
        }
    } else {
        filesystem::path exePath(modulePath.string() + SUFFIX_EXE_EXT);
        if(filesystem::exists(exePath)){
            actualFilename = getNativePathString(exePath);
            createProcess(actualFilename, prop);
        } else {
            filesystem::path dllPath(modulePath.string() + SUFFIX_SHARED_EXT);
            if(filesystem::exists(dllPath)){
                actualFilename = getNativePathString(dllPath);
                string initFunc(componentName + "Init");
                setupModules(actualFilename, initFunc, componentName, prop);
            } else {
                mv->putln(fmt(_("A file of RTC \"%1%\" does not exist.")) % componentName);
            }
        }
    }

    bool created = isValid();

    if(created){
        mv->putln(fmt(_("RTC \"%1%\" has been created from \"%2%\".")) % componentName % actualFilename);
    } else {
        mv->putln(fmt(_("RTC \"%1%\" cannot be created.")) % componentName);
    }

    return created;
}

void RTComponent::setupModules(string& fileName, string& initFuncName, string& componentName, PropertyMap& prop)
{
    RTC::Manager& rtcManager = RTC::Manager::instance();

    rtcManager.load(fileName.c_str(), initFuncName.c_str());

    string option("?");
    for(PropertyMap::iterator it = prop.begin(); it != prop.end(); ){
        option += it->first + "=" + it->second;
        if(++it != prop.end()){
            option += "&";
        }
    }
    rtc_ = createManagedRTC((componentName + option).c_str());

    if(!rtc_){
        mv->putln(fmt(_("RTC \"%1%\" cannot be created by the RTC manager.\n"
                        " RTC module file: \"%2%\"\n"
                        " Init function: %3%\n"
                        " option: %4%"))
                  % componentName % fileName % initFuncName % option);
    }
}

void RTComponent::onReadyReadServerProcessOutput()
{
    mv->put(QString(rtcProcess.readAll()));
}

bool RTComponent::isValid() const
{
    return (rtc_ || rtcProcess.state() != QProcess::NotRunning);
}

void RTComponent::createProcess(string& command, PropertyMap& prop)
{
    QStringList argv;
    argv.push_back(QString("-o"));
    argv.push_back(QString("naming.formats: %n.rtc"));
    argv.push_back(QString("-o"));
    argv.push_back(QString("logger.enable: NO"));
    for(PropertyMap::iterator it = prop.begin(); it != prop.end(); it++){
        argv.push_back(QString("-o"));
        argv.push_back(QString(string(it->first+":"+it->second).c_str()));
    }
    if(rtcProcess.state() != QProcess::NotRunning){
        rtcProcess.kill();
        rtcProcess.waitForFinished(100);
    }
#ifdef _WIN32
    rtcProcess.start(QString("\"") + command.c_str() + "\"", argv );
#else
    rtcProcess.start(command.c_str(), argv);
#endif
    if(!rtcProcess.waitForStarted()){
        mv->putln(fmt(_("RT Component process \"%1%\" cannot be executed.")) % command);
    } else {
        mv->putln(fmt(_("RT Component process \"%1%\" has been executed.")) % command );
        rtcProcess.sigReadyReadStandardOutput().connect(
            boost::bind(&RTComponent::onReadyReadServerProcessOutput, this));
    }
}

void RTComponent::deleteRTC(bool waitToBeDeleted)
{
    if(TRACE_FUNCTIONS){
        cout << "BodyRTComponent::deleteRTC()" << endl;
    }

    if(rtc_){
        string rtcName(rtc_->getInstanceName());
        mv->putln(fmt(_("delete %1%")) % rtcName);
        if(!cnoid::deleteRTC(rtc_, true)){
            mv->putln(fmt(_("%1% cannot be deleted.")) % rtcName);
        }
        rtc_ = 0;

    } else if(rtcProcess.state() != QProcess::NotRunning){
        mv->putln(fmt(_("delete %1%")) % componentName);
        rtcProcess.kill();
        rtcProcess.waitForFinished(100);
    }

    if(TRACE_FUNCTIONS){
        cout << "End of BodyRTCItem::deleteModule()" << endl;
    }
}

ext: cpp

max_stars_repo_name: snozawa/choreonoid

max_issues_repo_name: snozawa/choreonoid

max_forks_repo_name: snozawa/choreonoid


text:
#ifndef LM_BUILDER_OUTPUT_H
#define LM_BUILDER_OUTPUT_H

#include "lm/builder/header_info.hh"
#include "util/file.hh"

#include <boost/ptr_container/ptr_vector.hpp>
#include <boost/utility.hpp>

#include <map>

namespace util { namespace stream { class Chains; class ChainPositions; } }

/* Outputs from lmplz: ARPA< sharded files, etc */
namespace lm { namespace builder {

// These are different types of hooks.  Values should be consecutive to enable a vector lookup.
enum HookType {
  COUNT_HOOK, // Raw N-gram counts, highest order only.
  PROB_PARALLEL_HOOK, // Probability and backoff (or just q).  Output must process the orders in parallel or there will be a deadlock.
  PROB_SEQUENTIAL_HOOK, // Probability and backoff (or just q).  Output can process orders any way it likes.  This requires writing the data to disk then reading.  Useful for ARPA files, which put unigrams first etc.
  NUMBER_OF_HOOKS // Keep this last so we know how many values there are.
};

class Output;

class OutputHook {
  public:
    explicit OutputHook(HookType hook_type) : type_(hook_type), master_(NULL) {}

    virtual ~OutputHook();

    virtual void Apply(util::stream::Chains &chains);

    virtual void Run(const util::stream::ChainPositions &positions) = 0;

  protected:
    const HeaderInfo &GetHeader() const;
    int GetVocabFD() const;

  private:
    friend class Output;
    const HookType type_;
    const Output *master_;
};

class Output : boost::noncopyable {
  public:
    Output() {}

    // Takes ownership.
    void Add(OutputHook *hook) {
      hook->master_ = this;
      outputs_[hook->type_].push_back(hook);
    }

    bool Have(HookType hook_type) const {
      return !outputs_[hook_type].empty();
    }

    void SetVocabFD(int to) { vocab_fd_ = to; }
    int GetVocabFD() const { return vocab_fd_; }

    void SetHeader(const HeaderInfo &header) { header_ = header; }
    const HeaderInfo &GetHeader() const { return header_; }

    void Apply(HookType hook_type, util::stream::Chains &chains) {
      for (boost::ptr_vector<OutputHook>::iterator entry = outputs_[hook_type].begin(); entry != outputs_[hook_type].end(); ++entry) {
        entry->Apply(chains);
      }
    }

  private:
    boost::ptr_vector<OutputHook> outputs_[NUMBER_OF_HOOKS];
    int vocab_fd_;
    HeaderInfo header_;
};

inline const HeaderInfo &OutputHook::GetHeader() const {
  return master_->GetHeader();
}

inline int OutputHook::GetVocabFD() const {
  return master_->GetVocabFD();
}

}} // namespaces

#endif // LM_BUILDER_OUTPUT_H

ext: hh

max_issues_repo_name: Kabongosalomon/AMMI-NLP

max_forks_repo_name: Kabongosalomon/AMMI-NLP


text:
// Copyright 2018, Intel Corporation

#include "tile/codegen/emitc.h"

#include <vector>

#include <boost/format.hpp>

namespace vertexai {
namespace tile {
namespace codegen {

using boost::format;
using namespace std::placeholders;  // NOLINT
using namespace stripe;             // NOLINT

namespace {

class CodeGenerator {
 public:
  CodeGenerator() {}

  std::string EmitProgram(const Block& program) {
    EmitLine("#include <stdint.h>");
    EmitLine("#include <stdlib.h>");
    EmitLine(R"(
int min(int x, int y) {
  return (x < y) ? x : y;
}

int max(int x, int y) {
  return (x < y) ? y : x;
}

float softmax(float x) {
  return x;
}
)");
    EmitLine("int main(int argc, char** argv) {");
    PushTab();
    EmitBlock(program);
    EmitLine("return 0;");
    PopTab();
    EmitLine("}");
    return oss_.str();
  }

 private:
  void EmitLoad(const Block& block, const Load& load) {
    auto ref = block.ref_by_into(load.from);
    EmitLine(format("%1% %2% = %3%[%4%];")      //
             % IntoC(ref->interior_shape.type)  //
             % ScalarName(load.into)            //
             % UniqueName(load.from)            //
             % UniqueResolve(ref->FlatAccess()));
  }

  void EmitStore(const Block& block, const Store& store) {
    auto ref = block.ref_by_into(store.into);
    auto into = UniqueName(ref->into());
    auto access = UniqueResolve(ref->FlatAccess());
    if (ref->agg_op == Intrinsic::SUM) {
      EmitLine(format("%1%[%2%] += %3%;") % into % access % ScalarName(store.from));
    } else if (ref->agg_op == Intrinsic::PROD) {
      EmitLine(format("%1%[%2%] *= %3%;") % into % access % ScalarName(store.from));
    } else if (ref->agg_op == Intrinsic::MIN) {
      EmitLine(format("%1%[%2%] = min(%1%[%2%], %3%);") % into % access % ScalarName(store.from));
    } else if (ref->agg_op == Intrinsic::MAX) {
      EmitLine(format("%1%[%2%] = max(%1%[%2%], %3%);") % into % access % ScalarName(store.from));
    } else {
      EmitLine(format("%1%[%2%] = %3%;") % into % access % ScalarName(store.from));
    }
  }

  void EmitLoadIndex(const Block& block, const LoadIndex& load_index) {
    EmitLine(format("%1% %2% = %3%;")                  //
             % IntoC(vertexai::tile::DataType::INT64)  //
             % ScalarName(load_index.into)             //
             % ParentResolve(load_index.from));
  }

  void EmitIntrinsic(const Block& block, const Intrinsic& intrinsic) {
    if (intrinsic.outputs.size() > 1) {
      throw std::runtime_error("Only a single output is supported for intrinsics");
    }
    auto output = ScalarName(intrinsic.outputs[0]);
    if (intrinsic.name == Intrinsic::MUL) {
      EmitLine(format("%1% %2% = %3% * %4%;")     //
               % IntoC(intrinsic.type)            //
               % output                           //
               % ScalarName(intrinsic.inputs[0])  //
               % ScalarName(intrinsic.inputs[1]));
    } else if (intrinsic.name == Intrinsic::ADD) {
      EmitLine(format("%1% %2% = %3% + %4%;")     //
               % IntoC(intrinsic.type)            //
               % output                           //
               % ScalarName(intrinsic.inputs[0])  //
               % ScalarName(intrinsic.inputs[1]));
    } else if (intrinsic.name == "bit_right") {
      EmitLine(format("%1% %2% = %3% >> %4%;")    //
               % IntoC(intrinsic.type)            //
               % output                           //
               % ScalarName(intrinsic.inputs[0])  //
               % ScalarName(intrinsic.inputs[1]));
    } else if (intrinsic.name == Intrinsic::ASSIGN) {
      EmitLine(format("%1% %2% = %3%;")  //
               % IntoC(intrinsic.type)   //
               % output                  //
               % ScalarName(intrinsic.inputs[0]));
    } else if (intrinsic.name == "zelu") {
      EmitLine(format("%1% %2% = %3% < 0 ? 0 : %3%;")  //
               % IntoC(intrinsic.type)                 //
               % output                                //
               % ScalarName(intrinsic.inputs[0]));
    } else {
      std::stringstream inputs;
      for (size_t i = 0; i < intrinsic.inputs.size(); i++) {
        if (i) {
          inputs << ", ";
        }
        inputs << ScalarName(intrinsic.inputs[i]);
      }
      EmitLine(format("%1% %2% = %3%(%4%);")  //
               % IntoC(intrinsic.type)        //
               % output                       //
               % intrinsic.name               //
               % inputs.str());
    }
  }

  void EmitConstant(const Constant& constant) {
    switch (constant.type) {
      case ConstType::Integer:
        EmitLine(format("int %1% = %2%;") % ScalarName(constant.name) % constant.iconst);
        break;
      case ConstType::Float:
        EmitLine(format("double %1% = %2%;") % ScalarName(constant.name) % constant.fconst);
        break;
    }
  }

  void EmitSpecial(const Special& special) {  //
    EmitLine(format("// TODO: %1%") % special);
  }

  void EmitBlock(const Block& block) {
    Push();

    EmitLine(format("{ // block: %1%") % block.name);
    std::stringstream ss(block.comments);
    std::string line;
    for (std::string line; std::getline(ss, line, '\n');) {
      EmitLine(format("// %1%") % line);
    }
    PushTab();

    for (const auto& idx : block.idxs) {
      auto idx_name = UniqueName(idx.name);
      if (idx.range == 1) {
        EmitLine(format("int %1% = %2%;") % idx_name % ParentResolve(idx.affine));
      } else {
        EmitLine(format("for (int %1% = 0; %1% < %2%; %1%++) {") % idx_name % idx.range);
        PushTab();
      }
    }

    for (const auto& constraint : block.constraints) {
      EmitLine(format("if ((%1%) < 0) {") % UniqueResolve(constraint));
      PushTab();
      EmitLine("continue;");
      PopTab();
      EmitLine("}");
    }

    for (const auto& ref : block.refs) {
      auto type = IntoC(ref.interior_shape.type);
      auto into = UniqueName(ref.into());
      if (ref.from.empty()) {
        EmitLine(format("%1%* %2% = malloc(%3% * sizeof(%1%));") % type % into % ref.interior_shape.elem_size());
      } else {
        EmitLine(format("%1%* %2% = %3% + %4%;") % type % into % ParentName(ref.from) %
                 UniqueResolve(ref.FlatAccess()));
      }
    }

    for (const auto& stmt : block.stmts) {
      switch (stmt->kind()) {
        case StmtKind::Load:
          EmitLoad(block, *Load::Downcast(stmt));
          break;
        case StmtKind::Store:
          EmitStore(block, *Store::Downcast(stmt));
          break;
        case StmtKind::LoadIndex:
          EmitLoadIndex(block, *LoadIndex::Downcast(stmt));
          break;
        case StmtKind::Intrinsic:
          EmitIntrinsic(block, *Intrinsic::Downcast(stmt));
          break;
        case StmtKind::Constant:
          EmitConstant(*Constant::Downcast(stmt));
          break;
        case StmtKind::Special:
          EmitSpecial(*Special::Downcast(stmt));
          break;
        case StmtKind::Block:
          EmitBlock(*Block::Downcast(stmt));
          break;
      }
    }
    for (const auto& ref : block.refs) {
      if (ref.from.empty()) {
        EmitLine(format("free(%1%);") % UniqueName(ref.into()));
      }
    }

    for (const auto& idx : block.idxs) {
      if (idx.range != 1) {
        PopTab();
        EmitLine("}");
      }
    }

    PopTab();
    EmitLine("}");

    Pop();
  }

  std::string IntoC(const DataType& type) {
    switch (type) {
      case DataType::BOOLEAN:
        return "bool";
      case DataType::INT8:
        return "int8_t";
      case DataType::INT16:
        return "int16_t";
      case DataType::INT32:
        return "int32_t";
      case DataType::INT64:
        return "int64_t";
      case DataType::INT128:
        return "int128_t";
      case DataType::UINT8:
        return "uint8_t";
      case DataType::UINT16:
        return "uint16_t";
      case DataType::UINT32:
        return "uint32_t";
      case DataType::UINT64:
        return "uint64_t";
      case DataType::FLOAT16:
        return "half";
      case DataType::FLOAT32:
        return "float";
      case DataType::FLOAT64:
        return "double";
      default:
        throw std::runtime_error("Invalid tile type");
    }
  }

  void EmitTab() { oss_ << std::string(indent_ << 1, ' '); }

  void EmitLine(const std::string& str) {
    EmitTab();
    oss_ << str << '\n';
  }

  void EmitLine(const format& fmt) {
    EmitTab();
    oss_ << fmt << '\n';
  }

  void Push() { depth_++; }
  void Pop() { depth_--; }

  void PushTab() { indent_++; }
  void PopTab() { indent_--; }

  std::string ScalarName(std::string str) {
    std::replace(str.begin(), str.end(), '$', '_');
    return UniqueName(str);
  }

  Affine Resolve(Affine affine, const std::function<std::string(const std::string&)>& resolver) {
    std::vector<std::string> names;
    for (const auto& kvp : affine.getMap()) {
      if (!kvp.first.empty()) {
        names.push_back(kvp.first);
      }
    }
    for (const auto& name : names) {
      affine.substitute(name, Affine{resolver(name)});
    }
    return affine;
  }

  std::string ParentName(const std::string& name) { return str(format("d%1%_%2%") % (depth_ - 1) % name); }
  std::string UniqueName(const std::string& name) { return str(format("d%1%_%2%") % depth_ % name); }

  Affine ParentResolve(const Affine& affine) {
    return Resolve(affine, std::bind(&CodeGenerator::ParentName, this, _1));
  }

  Affine UniqueResolve(const Affine& affine) {
    return Resolve(affine, std::bind(&CodeGenerator::UniqueName, this, _1));
  }

  std::ostringstream oss_;
  size_t indent_ = 0;
  size_t depth_ = 0;
};

}  // namespace

std::string EmitC(const Block& program) {
  CodeGenerator gen;
  return gen.EmitProgram(program);
}

}  // namespace codegen
}  // namespace tile
}  // namespace vertexai

ext: cc

max_stars_repo_name: redoclag/plaidml

max_issues_repo_name: HOZHENWAI/plaidml

max_forks_repo_name: HOZHENWAI/plaidml


text:
#include <gtest/gtest.h>

#include "converter/fixml2fix_converter.hxx"
#include "converter/xml_element_helper.hxx"
#include "converter/fix_helper.hxx"
#include "util/fix_env.hxx"
#include "tools/test_util.hxx"

#include <boost/log/trivial.hpp>

#include <quickfix/fix50sp2/MarketDataRequestReject.h>

#include <list>
#include <set>
#include <string>
#include <utility>

using namespace std;
using namespace fix2xml;

TEST ( MarketDataRequestReject, set_fields)
{

  fixml2fix_converter converter {"../spec/fix/FIX50SP2.xml", "../spec/xsd/fixml-main-5-0-SP2.xsd"};
  auto& fixml_dict = converter.fixml_dico();
  ASSERT_TRUE(converter.init());
  ASSERT_TRUE(converter.parse_fixt_dico("../spec/fix/FIXT11.xml"));
  FIX50SP2::MarketDataRequestReject msg;

  list<multiset<string>> all_values;
  multiset<string> all_compo_names;
  multiset<string> MarketDataRequestReject_0;
  set_field(msg, FIX::EncodedText{"DATA_877704865"}, MarketDataRequestReject_0);
  set_field(msg, FIX::EncodedTextLen{1916235360}, MarketDataRequestReject_0);
  set_field(msg, FIX::MDReqID{"STRING_1606313308"}, MarketDataRequestReject_0);
  set_field(msg, FIX::MDReqRejReason{'D'}, MarketDataRequestReject_0);
  set_field(msg, FIX::Text{"STRING_729216902"}, MarketDataRequestReject_0);
  all_values.push_back(MarketDataRequestReject_0);

  all_compo_names.insert("MarketDataRequestReject");

  // MDRjctGrp
  // Group MDRjctGrp.NoAltMDSource
  {
    FIX50SP2::MarketDataRequestReject::NoAltMDSource noAltMDSource_0_0;
    // MDRjctGrp.NoAltMDSource
    multiset<string> MDRjctGrp_NoAltMDSource_0;
    set_field(noAltMDSource_0_0, FIX::AltMDSourceID{"STRING_739076571"}, MDRjctGrp_NoAltMDSource_0);
    all_values.push_back(MDRjctGrp_NoAltMDSource_0);
    all_compo_names.insert("...NoAltMDSource");

    msg.addGroup(noAltMDSource_0_0);
  }
  // Parties
  // Group Parties.NoPartyIDs
  {
    FIX50SP2::MarketDataRequestReject::NoPartyIDs noPartyIDs_0_0;
    // Parties.NoPartyIDs
    multiset<string> Parties_NoPartyIDs_61;
    set_field(noPartyIDs_0_0, FIX::PartyID{"STRING_1533823668"}, Parties_NoPartyIDs_61);
    set_field(noPartyIDs_0_0, FIX::PartyIDSource{'B'}, Parties_NoPartyIDs_61);
    set_field(noPartyIDs_0_0, FIX::PartyRole{46}, Parties_NoPartyIDs_61);
    all_values.push_back(Parties_NoPartyIDs_61);
    all_compo_names.insert("...NoPartyIDs");

    // PtysSubGrp
    // Group PtysSubGrp.NoPartySubIDs
    {
      FIX50SP2::MarketDataRequestReject::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_0;
      // PtysSubGrp.NoPartySubIDs
      multiset<string> PtysSubGrp_NoPartySubIDs_128;
      set_field(noPartySubIDs_0_1_0, FIX::PartySubID{"STRING_1923194990"}, PtysSubGrp_NoPartySubIDs_128);
      set_field(noPartySubIDs_0_1_0, FIX::PartySubIDType{22}, PtysSubGrp_NoPartySubIDs_128);
      all_values.push_back(PtysSubGrp_NoPartySubIDs_128);
      all_compo_names.insert("...NoPartyIDs...NoPartySubIDs");

      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_0);
    }
    {
      FIX50SP2::MarketDataRequestReject::NoPartyIDs::NoPartySubIDs noPartySubIDs_0_1_1;
      // PtysSubGrp.NoPartySubIDs
      multiset<string> PtysSubGrp_NoPartySubIDs_129;
      set_field(noPartySubIDs_0_1_1, FIX::PartySubID{"STRING_1753801884"}, PtysSubGrp_NoPartySubIDs_129);
      set_field(noPartySubIDs_0_1_1, FIX::PartySubIDType{29}, PtysSubGrp_NoPartySubIDs_129);
      all_values.push_back(PtysSubGrp_NoPartySubIDs_129);
      all_compo_names.insert("...NoPartyIDs...NoPartySubIDs");

      noPartyIDs_0_0.addGroup(noPartySubIDs_0_1_1);
    }
    msg.addGroup(noPartyIDs_0_0);
  }
  {
    FIX50SP2::MarketDataRequestReject::NoPartyIDs noPartyIDs_0_1;
    // Parties.NoPartyIDs
    multiset<string> Parties_NoPartyIDs_62;
    set_field(noPartyIDs_0_1, FIX::PartyID{"STRING_903766107"}, Parties_NoPartyIDs_62);
    set_field(noPartyIDs_0_1, FIX::PartyIDSource{'E'}, Parties_NoPartyIDs_62);
    set_field(noPartyIDs_0_1, FIX::PartyRole{31}, Parties_NoPartyIDs_62);
    all_values.push_back(Parties_NoPartyIDs_62);
    all_compo_names.insert("...NoPartyIDs");

    // PtysSubGrp
    // Group PtysSubGrp.NoPartySubIDs
    {
      FIX50SP2::MarketDataRequestReject::NoPartyIDs::NoPartySubIDs noPartySubIDs_1_1_0;
      // PtysSubGrp.NoPartySubIDs
      multiset<string> PtysSubGrp_NoPartySubIDs_130;
      set_field(noPartySubIDs_1_1_0, FIX::PartySubID{"STRING_343450914"}, PtysSubGrp_NoPartySubIDs_130);
      set_field(noPartySubIDs_1_1_0, FIX::PartySubIDType{29}, PtysSubGrp_NoPartySubIDs_130);
      all_values.push_back(PtysSubGrp_NoPartySubIDs_130);
      all_compo_names.insert("...NoPartyIDs...NoPartySubIDs");

      noPartyIDs_0_1.addGroup(noPartySubIDs_1_1_0);
    }
    msg.addGroup(noPartyIDs_0_1);
  }
  // header
  multiset<string> header_41;
  set_header_field(msg.getHeader(), FIX::ApplVerID{"STRING_1"}, header_41);
  set_header_field(msg.getHeader(), FIX::BeginString{"STRING_1094579088"}, header_41);
  set_header_field(msg.getHeader(), FIX::BodyLength{1253092317}, header_41);
  set_header_field(msg.getHeader(), FIX::CstmApplVerID{"STRING_527763163"}, header_41);
  set_header_field(msg.getHeader(), FIX::DeliverToCompID{"STRING_909197963"}, header_41);
  set_header_field(msg.getHeader(), FIX::DeliverToLocationID{"STRING_484308063"}, header_41);
  set_header_field(msg.getHeader(), FIX::DeliverToSubID{"STRING_1703809741"}, header_41);
  set_header_field(msg.getHeader(), FIX::LastMsgSeqNumProcessed{569471891}, header_41);
  set_header_field(msg.getHeader(), FIX::MessageEncoding{"STRING_EUC-JP"}, header_41);
  set_header_field(msg.getHeader(), FIX::MsgSeqNum{434030959}, header_41);
  set_header_field(msg.getHeader(), FIX::OnBehalfOfCompID{"STRING_338223603"}, header_41);
  set_header_field(msg.getHeader(), FIX::OnBehalfOfLocationID{"STRING_1034835173"}, header_41);
  set_header_field(msg.getHeader(), FIX::OnBehalfOfSubID{"STRING_1927583592"}, header_41);
  set_header_field(msg.getHeader(), FIX::OrigSendingTime{FIX::UTCTIMESTAMP(9, 56, 5, 21, 8, 2007)}, header_41);
  set_header_field(msg.getHeader(), FIX::PossDupFlag{false}, header_41);
  set_header_field(msg.getHeader(), FIX::PossResend{false}, header_41);
  set_header_field(msg.getHeader(), FIX::SecureData{"DATA_1310620516"}, header_41);
  set_header_field(msg.getHeader(), FIX::SecureDataLen{1206661210}, header_41);
  set_header_field(msg.getHeader(), FIX::SenderCompID{"STRING_218106252"}, header_41);
  set_header_field(msg.getHeader(), FIX::SenderLocationID{"STRING_66902975"}, header_41);
  set_header_field(msg.getHeader(), FIX::SenderSubID{"STRING_1591681710"}, header_41);
  set_header_field(msg.getHeader(), FIX::SendingTime{FIX::UTCTIMESTAMP(23, 24, 21, 24, 6, 2016)}, header_41);
  set_header_field(msg.getHeader(), FIX::TargetCompID{"STRING_1615586092"}, header_41);
  set_header_field(msg.getHeader(), FIX::TargetLocationID{"STRING_1791426028"}, header_41);
  set_header_field(msg.getHeader(), FIX::TargetSubID{"STRING_679737013"}, header_41);
  set_header_field(msg.getHeader(), FIX::XmlData{"DATA_1171912185"}, header_41);
  set_header_field(msg.getHeader(), FIX::XmlDataLen{213414271}, header_41);
  all_values.push_back(header_41);
  all_compo_names.insert(".header");

  xml_element elt;
  converter.fix2fixml(msg, elt);
  BOOST_LOG_TRIVIAL(debug) << "The resulting XML is";
  cout << "////////////////////////////////////////////" << endl;
  cout << elt.to_string() << endl;
  cout << "////////////////////////////////////////////" << endl << endl;

  BOOST_LOG_TRIVIAL(debug) << "Quickfix XML representation is";
  cout << "////////////////////////////////////////////" << endl;
  cout << msg.toXML() << endl;
  cout << "////////////////////////////////////////////" << endl << endl;
  list<multiset<string>> elt_lists;
  elt.to_list(elt_lists);
  EXPECT_EQ(elt_lists.size(), all_values.size());

  if (elt_lists.size() != all_values.size())  {
    multiset<string> elt_compo_name;
    elt.all_components(elt_compo_name);
    BOOST_LOG_TRIVIAL(debug) << "XML Elements are:";
    cout << "	[";
    copy(elt_compo_name.begin(), elt_compo_name.end(), ostream_iterator<string>(cout, " "));    cout << "]" << endl;

    BOOST_LOG_TRIVIAL(debug) << "FIX Components are:";
    cout << "	[";
    copy(all_compo_names.begin(), all_compo_names.end(), ostream_iterator<string>(cout, " "));    cout << "]" << endl;

  }
  BOOST_LOG_TRIVIAL(debug) << "All FIX components";
  for (const auto& l : all_values) {
    cout << "	[";
    copy(l.begin(), l.end(), ostream_iterator<string>(cout, " "));
    cout << "]" << endl;
  }
  BOOST_LOG_TRIVIAL(debug) << "All XML components";
  for (const auto& l : elt_lists) {
    cout << "	[";
    copy(l.begin(), l.end(), ostream_iterator<string>(cout, " "));
    cout << "]" << endl;

  }

  for (const auto& xml_l : elt_lists) {
    bool found = false;
    for (const auto& l : all_values) {
      if (includes(l.begin(), l.end(), xml_l.begin(), xml_l.end())) {
        found = true;
        break;
      } // end if includes
    } // end for all_values
    EXPECT_TRUE(found);
    if ( ! found) {
      BOOST_LOG_TRIVIAL(debug) << "[TO CHECK] This XML component was not found in FIX message";
      cout << "	 ---> [";
      copy(xml_l.begin(), xml_l.end(), ostream_iterator<string>(cout, " "));      cout << "]" << endl << endl;
    } // end if ! found
  } // end for elt_lists
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2010-2012 Barend Gehrels, Amsterdam, the Netherlands.

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

#ifndef BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_HOLE_ITERATOR_HPP
#define BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_HOLE_ITERATOR_HPP

// Adapts Geometries from Boost.Polygon for usage in Boost.Geometry
// boost::polygon::polygon_with_holes_data -> boost::geometry::polygon
//   hole_iterator  -> returning ring_proxy's instead of normal polygon_data

#include <boost/polygon/polygon.hpp>

#include <boost/iterator/iterator_facade.hpp>

namespace boost { namespace geometry
{

namespace adapt { namespace bp
{

template <typename Polygon, typename RingProxy>
class hole_iterator
    : public ::boost::iterator_facade
        <
            hole_iterator<Polygon, RingProxy>,
            RingProxy, // value type
            boost::forward_traversal_tag,
            RingProxy // reference type
        >
{
public :
    typedef typename boost::polygon::polygon_with_holes_traits
        <
            Polygon
        >::iterator_holes_type ith_type;

    explicit inline hole_iterator(Polygon& polygon, ith_type const it)
        : m_polygon(polygon)
        , m_base(it)
    {
    }

    typedef std::ptrdiff_t difference_type;

private:
    friend class boost::iterator_core_access;

    inline RingProxy dereference() const
    {
        return RingProxy(m_polygon, this->m_base);
    }

    inline void increment() { ++m_base; }
    inline void decrement() { --m_base; }
    inline void advance(difference_type n)
    {
        for (int i = 0; i < n; i++)
        {
            ++m_base;
        }
    }

    inline bool equal(hole_iterator<Polygon, RingProxy> const& other) const
    {
        return this->m_base == other.m_base;
    }

    Polygon& m_polygon;
    ith_type m_base;
};

}}}}

#endif // BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_HOLE_ITERATOR_HPP

ext: hpp


text:
#pragma once

/*	jsch is a stack-based scheduler based on Emil Fresk's crect library
 *	We do not provide any garantee as of yet.
 *
 *	The goal is to create a reactive RTOS which can be configured to
 *	run on different hardware, with Raspberry Pi Pico's RP2040 chip based
 *	on Cortex M0+ as the first "client".
 *
 */
#include <type_traits>
#include <utility> // For pair

#include <boost/callable_traits/args.hpp>
#include <boost/heap/priority_queue.hpp>
#include <boost/tuple/tuple.hpp>

#include <type_expr.hpp> // Compile-time composition

template<typename ... Jobs>
class jsch
{
	template<typename T>
	using get_args = boost::callable_traits::args_t<T,te::ts_>;
public :
	using res_list = te::eval_pipe_<te::ts_<Jobs...>,
			te::transform_<te::wraptype_<std::decay>,te::wrap_<get_args>>>;
	using job_list = te::eval_pipe_<te::ts_<Jobs...>,
			te::transform_<te::wraptype_<std::decay_t>>,
			te::wrap_<boost::tuple>>;
private :
	job_list tup_job;

public:
	jsch(Jobs& ... js) : tup_job{js...}
	{

	}
	jsch(Jobs&& ... js) : tup_job{std::forward<Jobs>(js)...}
	{

	}

};

template<typename ... Jobs>
auto make_jsch(Jobs ... js) -> jsch<Jobs...>
{
	return jsch<Jobs...>(js...);
}


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

#pragma once
#ifndef SE3313_MSG_ERROR_HPP
#define SE3313_MSG_ERROR_HPP

#include <boost/property_tree/ptree.hpp>

#include <cstddef>
#include <string>

#include "instance.hpp"

namespace se3313
{

namespace msg
{

/*!
 * \brief Describes error codes passed back to a client when there is an error within the server.
 */
enum class ErrorCode: uint16_t {
    NONE                    = 0,

    /**
     * Valid request, but invalid timing.
     */
    INVALID_REQUEST_FROM_CLIENT = 50,

    /*!
     * The Username already exists on the server at this time.
     */
    USER_NAME_IN_USE        = 1,

    /*!
     * The User Name was invalid (e.g. empty).
     */
    INVALID_USER_NAME       = 2,

    MALFORMED_REQUEST_UNKNWN    = 200,

    MALFORMED_REQUEST_NO_TYPE       = 201,
    MALFORMED_REQUEST_UNKNOWN_TYPE  = 202,
    MALFORMED_REQUEST_BAD_OBJECT_DEF= 203,
    MALFORMED_REQUEST_NO_OBJ    = 210
};

namespace response {

/**
 * Describes an error from the server to a client.
 */
class error: public abstract_instance<error> {

public:

    /// Java-land type
    constexpr static const char TYPE[] = "ca.uwo.eng.se3313.lab4.network.response.ServerError";

    /// The error code
    constexpr static const char PROPERTY_CODE[] = "code";
    /// A nice-ish description of the error
    constexpr static const char PROPERTY_MESSAGE[] = "message";
    /// Who sent the error originally
    constexpr static const char PROPERTY_ORIGINATOR[] = "originator";

    /**
     * Converts a json tree to an instance.
     */
    static
    std::shared_ptr<error> fromJson(boost::property_tree::ptree& json);

    /**
     * Delegate constructor defaulting time to now and sender to the server.
     */
    error(const std::string& originator,
          const ErrorCode errorCode,
          const std::string& message)
        : error(clock_t::now(), instance::SERVER_SENDER, originator, errorCode, message)
        {}

    /**
     * Creates an error.
     * @param dateTime When the error occured
     * @param sender Who sent the error (usually server)
     * @param originator Who found the error (usually server again)
     * @param errorCode The code of the error
     * @param message Human readable message
     */
    error(const time_point_t dateTime,
          const std::string& sender,
          const std::string& originator,
          const ErrorCode errorCode,
          const std::string& message)
        : abstract_instance(dateTime, sender)
        , _originator(originator)
        , _errorCode(errorCode)
        , _message(message)
        {}

    /// default destructor
    virtual ~error() = default;

    /// Get the original creator
    const std::string originator() const { return _originator; }

    /// Get the human-readable message
    const std::string message() const { return _message; }

    /// Get the error code
    const ErrorCode code() const { return _errorCode; }

protected:

    /// Get the subtree for the error
    virtual
    boost::property_tree::ptree subToJson() const;

private:

    const std::string _originator;

    const ErrorCode _errorCode;

    const std::string _message;

};

/**
 * Returns `true` if the message is an error, `false` if `nullptr` or otherwise.
 *
 * @param instance @c instance to check against.
 * @return `true` if @p instance is an @c error instance.
 */
const bool is_error_msg(const std::shared_ptr<msg::instance> instance);

} // end namespace response

} // end namespace msg

} // end namespace se3313

#endif // SE3313_MSG_ERROR_HPP


text:
// Copyright Dean Michael Berris 2009.
// 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)

//[ uri_main
/*`
  This is a simple program that validates a URI.
 */
#include <boost/network/uri.hpp>
#include <string>
#include <iostream>

int main(int argc, char * argv[]) {
    std::string input;
    std::cout << "Please enter a URI to parse: ";
    std::cin >> input;

    /*<< Create a `boost::network::uri::uri` object from the input.  >>*/
    boost::network::uri::uri uri_(input);
    /*<< Check if it's a valid URI. >>*/
    std::cout << "You've entered "
              << (boost::network::uri::is_valid(uri_)?
                  std::string("a valid") : std::string("an invalid"))
              << " URI!" << std::endl;

    ///*<< Create a `boost::network::http::uri` object from the input. >>*/
    //boost::network::uri::http::uri http_uri_(input);
    ///*<< Check if it's a valid HTTP URI. >>*/
    //std::cout << "It's also "
    //          << (boost::network::uri::is_valid(http_uri_)?
    //              std::string("a valid HTTP URI") : std::string("an invalid HTTP URI."))
    //          << "!" << std::endl;

    return EXIT_SUCCESS;
}
//]

max_stars_repo_name: antoinelefloch/cpp-netlib

max_issues_repo_name: antoinelefloch/cpp-netlib

max_forks_repo_name: antoinelefloch/cpp-netlib


text:
/**
 * Copyright Soramitsu Co., Ltd. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

#include "backend/protobuf/query_responses/proto_roles_response.hpp"

#include <boost/range/iterator_range_core.hpp>

namespace shared_model {
  namespace proto {

    RolesResponse::RolesResponse(iroha::protocol::QueryResponse &query_response)
        : roles_response_{query_response.roles_response()},
          roles_{boost::copy_range<RolesIdType>(roles_response_.roles())} {}

    const RolesResponse::RolesIdType &RolesResponse::roles() const {
      return roles_;
    }

  }  // namespace proto
}  // namespace shared_model

max_stars_repo_name: akshatkarani/iroha

max_issues_repo_name: akshatkarani/iroha

max_forks_repo_name: akshatkarani/iroha


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

/**
 * @file lut_graph.hpp
 *
 * @brief LUT Graph
 *
 * @author Mathias Soeken
 * @since  2.2
 */

#ifndef LUT_GRAPH_HPP
#define LUT_GRAPH_HPP

#include <iostream>
#include <unordered_map>

#include <core/utils/dirty.hpp>
#include <core/utils/graph_utils.hpp>

#include <boost/dynamic_bitset.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/properties.hpp>
#include <range/v3/iterator_range.hpp>

namespace boost
{

enum vertex_lut_type_t { vertex_lut_type };
BOOST_INSTALL_PROPERTY(vertex, lut_type);

enum vertex_lut_t { vertex_lut };
BOOST_INSTALL_PROPERTY(vertex, lut);

}

namespace cirkit
{
using boost::adjacency_list;
using boost::default_color_type;
using boost::directedS;
using boost::edge_name_t;
using boost::property;
using boost::vecS;
using boost::vertex_color_t;
using boost::vertex_name_t;
using boost::vertex_lut_t;
using boost::vertex_lut_type_t;

enum class lut_type_t { pi, po, gnd, vdd, internal };

/******************************************************************************
 * LUT graph                                                                  *
 ******************************************************************************/

using lut_graph_vertex_properties_t = property<vertex_name_t, std::string,
                                      property<vertex_lut_t, std::string,
                                      property<vertex_lut_type_t, lut_type_t>>>;
using lut_graph_t  = digraph_t<lut_graph_vertex_properties_t>;
using lut_vertex_t = vertex_t<lut_graph_t>;
using lut_edge_t   = edge_t<lut_graph_t>;

unsigned lut_graph_lut_count( const lut_graph_t& g );

class lut_graph
{
public:
  using graph_t = lut_graph_t;
  using node_t = vertex_t<graph_t>;

  using input_vec_t  = std::vector<std::pair<node_t, std::string>>;
  using output_vec_t = std::vector<std::pair<node_t, std::string>>;

  using vertex_range_t = ranges::iterator_range<boost::graph_traits<lut_graph_t>::vertex_iterator>;
  using edge_range_t   = ranges::iterator_range<boost::graph_traits<lut_graph_t>::edge_iterator>;

  using name_property_map_t      = boost::property_map<graph_t, boost::vertex_name_t>::type;
  using lut_property_map_t       = boost::property_map<graph_t, boost::vertex_lut_t>::type;
  using gate_type_property_map_t = boost::property_map<graph_t, boost::vertex_lut_type_t>::type;

  lut_graph( const std::string& name = std::string() );

  lut_graph& operator=( const lut_graph& other )
  {
    g = other.g;
    gnd = other.gnd;
    vdd = other.vdd;

    _name = other._name;
    _inputs = other._inputs;
    _outputs = other._outputs;
    _input_to_id = other._input_to_id;

    _names = boost::get( boost::vertex_name, g );
    _types = boost::get( boost::vertex_lut_type, g );
    _luts = boost::get( boost::vertex_lut, g );
    for ( const auto& v : boost::make_iterator_range( boost::vertices( g ) ) )
    {
      _names[ v ] = other._names[ v ];
      _types[ v ] = other._types[ v ];
      _luts[ v ] = other._luts[ v ];
    }

    // fanout = other.fanout;
    // parentss = other.parentss;
    // levels = other.levels;

    _num_lut = other._num_lut;

    // ref_count = other.ref_count;
    // marks = other.marks;

    return *this;
  }
  void compute_fanout() const;
  void compute_parents() const;
  void compute_levels() const;
  void compute_sections() const;

  node_t get_constant( bool value ) const;
  node_t create_pi( const std::string& name );
  void create_po( const node_t& n, const std::string& name );
  void delete_po( unsigned index );
  node_t create_lut( const std::string& lut, const std::vector<node_t>& ops, const std::string& name = std::string() );

  unsigned fanin_count( const node_t& n ) const;
  unsigned fanout_count( const node_t& n ) const;
  const std::vector<node_t>& parents( const node_t& n ) const;
  const boost::dynamic_bitset<>& section( const node_t& n ) const;
  unsigned level( const node_t& n ) const;

  bool is_input( const node_t& n ) const;
  bool is_lut( const node_t& n ) const;

  const std::string& name() const;
  void set_name( const std::string& name );
  std::size_t size() const;
  unsigned num_gates() const;
  const graph_t& graph() const;
  graph_t& graph();
  const input_vec_t& inputs() const;
  const output_vec_t& outputs() const;
  input_vec_t& inputs();
  output_vec_t& outputs();
  const std::string& input_name( const node_t& n ) const;
  const unsigned input_index( const node_t& n ) const;
  std::vector<node_t> children( const node_t& n ) const;
  vertex_range_t nodes() const;
  edge_range_t edges() const;
  std::vector<node_t> topological_nodes() const;

  inline const name_property_map_t& names() { return _names; }
  inline const name_property_map_t& names() const { return _names; }
  inline const lut_property_map_t& luts() { return _luts; }
  inline const lut_property_map_t& luts() const { return _luts; }
  inline const gate_type_property_map_t& types() { return _types; }
  inline const gate_type_property_map_t& types() const { return _types; }

  inline unsigned num_luts() const { return _num_lut; }

  /* ref counting */
  void init_refs() const;
  unsigned get_ref( const lut_vertex_t& n ) const;
  unsigned inc_ref( const lut_vertex_t& n ) const;
  unsigned dec_ref( const lut_vertex_t& n ) const;
  void inc_output_refs() const;

  /* marking */
  void init_marks() const;
  bool is_marked( const lut_vertex_t& n ) const;
  void mark( const lut_vertex_t& n ) const;

  void mark_as_modified() const;

private:
  graph_t g;
  node_t gnd;
  node_t vdd;

  std::string  _name;
  input_vec_t  _inputs;
  output_vec_t _outputs;
  std::unordered_map<node_t, unsigned> _input_to_id;

  name_property_map_t      _names;
  gate_type_property_map_t _types;
  lut_property_map_t       _luts;

  /* additional network information */
  mutable dirty<std::vector<unsigned>>                fanout;
  mutable dirty<std::vector<std::vector<node_t>>>     parentss;
  mutable dirty<std::vector<unsigned>>                levels;
  mutable dirty<std::vector<boost::dynamic_bitset<>>> sections;

  /* network settings and stats */
  unsigned                                _num_lut = 0u;

  /* utilities */
  mutable std::vector<unsigned>                   ref_count;
  mutable boost::dynamic_bitset<>                 marks;
};

}

#endif

// Local Variables:
// c-basic-offset: 2
// eval: (c-set-offset 'substatement-open 0)
// eval: (c-set-offset 'innamespace 0)
// End:

max_stars_repo_name: eletesta/cirkit

max_issues_repo_name: eletesta/cirkit

max_forks_repo_name: eletesta/cirkit


text:
/*
 * Copyright (c) 2016 Spotify AB
 *
 * 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 <cstdlib>

#include <boost/mpl/list.hpp>
#include <boost/test/unit_test.hpp>

#include <spotify/json/detail/skip_chars.hpp>

BOOST_AUTO_TEST_SUITE(spotify)
BOOST_AUTO_TEST_SUITE(json)
BOOST_AUTO_TEST_SUITE(detail)

namespace {

std::string generate(const std::string &tpl, const std::size_t count) {
  std::string ws;
  ws.reserve(count);
  for (std::size_t i = 0; i < count; i++) {
    ws += tpl[i % tpl.size()];
  }
  return ws;
}

template <void (*function)(decode_context &)>
void verify_skip_any(
    const bool use_sse,
    const std::string &json,
    const std::size_t prefix = 0,
    const std::size_t suffix = 0) {
  auto context = decode_context(json.data() + prefix, json.data() + json.size());
  *const_cast<bool *>(&context.has_sse42) &= use_sse;
  const auto original_context = context;
  function(context);
  BOOST_CHECK_EQUAL(
      reinterpret_cast<intptr_t>(context.position),
      reinterpret_cast<intptr_t>(original_context.end - suffix));
  BOOST_CHECK_EQUAL(
      reinterpret_cast<intptr_t>(context.end),
      reinterpret_cast<intptr_t>(original_context.end));
}

template <void (*function)(decode_context &)>
void verify_skip_empty_nullptr(const bool use_sse) {
  auto context = decode_context(nullptr, nullptr);
  *const_cast<bool *>(&context.has_sse42) &= use_sse;
  function(context);
  BOOST_CHECK(context.position == nullptr);
  BOOST_CHECK(context.end == nullptr);
}

using true_false = boost::mpl::list<boost::true_type, boost::false_type>;

}  // namespace

/*
 * skip_any_simple_characters
 */

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_simple_characters, use_sse, true_false) {
  for (auto n = 0; n < 1024; n++) {
    const auto ws = generate("abcdefghIJKLMNOP:-,;'^¨´`xyz", n);
    const auto with_prefix = "\\" + ws;
    const auto with_suffix = ws + "\"abcde";
    verify_skip_any<skip_any_simple_characters>(use_sse::value, ws);
    verify_skip_any<skip_any_simple_characters>(use_sse::value, with_prefix, 1);
    verify_skip_any<skip_any_simple_characters>(use_sse::value, with_suffix, 0, 6);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_simple_characters_null_byte_in_string,
                              use_sse,
                              true_false) {
  alignas(16) char input_data[17] = "a\0\"\"\"\"\"\"\"\"\"\"\"\"\"\"";
  auto context = decode_context(input_data, input_data + 16);
  *const_cast<bool *>(&context.has_sse42) &= use_sse::value;
  skip_any_simple_characters(context);
  BOOST_CHECK_EQUAL(context.position - input_data, 2);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_simple_characters_with_empty_string,
                              use_sse,
                              true_false) {
  verify_skip_empty_nullptr<skip_any_simple_characters>(use_sse::value);
}

/*
 * skip_any_whitespace
 */

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_space, use_sse, true_false) {
  for (auto n = 0; n < 1024; n++) {
    const auto ws = generate(" ", n);
    const auto with_prefix = "}" + ws;
    const auto with_suffix = ws + "{ ";
    verify_skip_any<skip_any_whitespace>(use_sse::value, ws);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_prefix, 1);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_suffix, 0, 2);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_tabs, use_sse, true_false) {
  for (auto n = 0; n < 1024; n++) {
    const auto ws = generate("\t", n);
    const auto with_prefix = "}" + ws;
    const auto with_suffix = ws + "{ ";
    verify_skip_any<skip_any_whitespace>(use_sse::value, ws);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_prefix, 1);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_suffix, 0, 2);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_carriage_return, use_sse, true_false) {
  for (auto n = 0; n < 1024; n++) {
    const auto ws = generate("\r", n);
    const auto with_prefix = "}" + ws;
    const auto with_suffix = ws + "{ ";
    verify_skip_any<skip_any_whitespace>(use_sse::value, ws);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_prefix, 1);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_suffix, 0, 2);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_line_feed, use_sse, true_false) {
  for (auto n = 0; n < 1024; n++) {
    const auto ws = generate("\n", n);
    const auto with_prefix = "}" + ws;
    const auto with_suffix = ws + "{ ";
    verify_skip_any<skip_any_whitespace>(use_sse::value, ws);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_prefix, 1);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_suffix, 0, 2);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_whitespace, use_sse, true_false) {
  for (auto n = 0; n < 1024; n++) {
    const auto ws = generate("\n\t\r\n", n);
    const auto with_prefix = "}" + ws;
    const auto with_suffix = ws + "{ ";
    verify_skip_any<skip_any_whitespace>(use_sse::value, ws);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_prefix, 1);
    verify_skip_any<skip_any_whitespace>(use_sse::value, with_suffix, 0, 2);
  }
}

BOOST_AUTO_TEST_CASE_TEMPLATE(json_skip_any_whitespace_with_empty_string, use_sse, true_false) {
  verify_skip_empty_nullptr<skip_any_whitespace>(use_sse::value);
}

BOOST_AUTO_TEST_SUITE_END()  // detail
BOOST_AUTO_TEST_SUITE_END()  // json
BOOST_AUTO_TEST_SUITE_END()  // spotify

max_stars_repo_name: ivangalkin/spotify-json

max_issues_repo_name: ivangalkin/spotify-json

max_forks_repo_name: ivangalkin/spotify-json


text:
/*
FTX Zorro Plugin
https://github.com/vitakot/ftx_zorro_plugin

Licensed under the MIT License <http://opensource.org/licenses/MIT>.
SPDX-License-Identifier: MIT
Copyright (c) 2022 Vitezslav Kot <vitezslav.kot@gmail.com>.
*/

#include <ftx_api/ftx_ws_client.h>
#include <openssl/hmac.h>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/callable_traits.hpp>
#include <variant>
#include <iostream>
#include <openssl/sha.h>

namespace ftx {

#define STRINGIZE_I(x) #x
#define STRINGIZE(x) STRINGIZE_I(x)

#define MAKE_FILELINE \
    __FILE__ "(" STRINGIZE(__LINE__) ")"

const char *FTX_FUTURES_WS_HOST = "ftx.com";
const char *FTX_FUTURES_WS_PORT = "443";

struct WebSocketClient::P {
    boost::asio::io_context m_ioContext;
    std::string m_host = {FTX_FUTURES_WS_HOST};
    std::string m_port = {FTX_FUTURES_WS_PORT};
    onMessageReceivedCB m_onMessageCallback;
    std::map<WebSocket::handle, std::weak_ptr<WebSocket>> m_map;
    std::thread m_ioThread;
    std::atomic<bool> m_isRunning = false;
    onLogMessage m_logMessageCB;
    std::string m_apiKey;
    std::string m_apiSecret;
    std::string m_subAccountName;
    const EVP_MD *m_evp_md;

    P() : m_evp_md(EVP_sha256()) {
        m_onMessageCallback = {};
    }

    static bool isApiError(const nlohmann::json &json) {
        return json.contains("error") && json.contains("code") && json.contains("msg");
    }

    static std::pair<int, std::string> constructError(const nlohmann::json &json) {

        int ec;
        std::string msg;
        readValue<int>(json, "code", ec);
        readValue<std::string>(json, "msg", msg);

        return std::make_pair(ec, std::move(msg));
    }

    static nlohmann::json createRequest(const std::string &pair, Channel channel) {

        if (channel == +Channel::pingpong) {
            Ping request;
            return request.toJson();
        } else {
            ChannelSubscriptionRequest request;
            request.m_op = Operation::subscribe;
            request.m_channel = channel;
            request.m_market = pair;
            return request.toJson();
        }
    }

    nlohmann::json createAuthenticationRequest() const {
        AuthenticationRequest request;
        request.m_key = m_apiKey;
        request.m_subAccount = m_subAccountName;
        request.m_time = getMsTimestamp(currentTime()).count();

        std::string authString(std::to_string(request.m_time));
        authString.append("websocket_login");

        unsigned char digest[SHA256_DIGEST_LENGTH];
        unsigned int digestLength = 32;

        HMAC(m_evp_md, m_apiSecret.data(), m_apiSecret.size(),
             reinterpret_cast<const unsigned char *>(authString.data()),
             authString.length(), digest, &digestLength);

        request.m_sign = stringToHex(digest, sizeof(digest));

        return request.toJson();
    }

    template<typename F>
    WebSocket::handle startChannel(const std::string &pair, Channel channel, F cb) {
        using argsTuple = typename boost::callable_traits::args<decltype(cb)>::type;
        using messageType = typename std::tuple_element<3, argsTuple>::type;

        auto ws = std::make_shared<WebSocket>(m_ioContext);
        auto *h = ws.get();
        std::weak_ptr<WebSocket> wp{ws};

        std::string streamName = composeStreamName(pair, channel);
        std::vector<nlohmann::json> requests;

        requests.push_back(createRequest(pair, channel));

        if (channel == +Channel::orders || channel == +Channel::fills || channel == +Channel::ftxpay) {
            requests.push_back(createAuthenticationRequest());
        }

        ws->setStreamName(streamName);

        auto wsCallback = [this, streamName, requests, cb = std::move(cb)]
                (const char *fl, int ec, std::string errmsg, const char *ptr, std::size_t size) -> bool {
            if (ec) {
                try {
                    cb(fl, ec, std::move(errmsg), messageType{});
                } catch (const std::exception &ex) {

                    if (m_logMessageCB) {
                        m_logMessageCB(LogSeverity::Error, std::format("{}: {}\n", MAKE_FILELINE, ex.what()));
                    }
                }

                return false;
            }

            const nlohmann::json json = nlohmann::json::parse(ptr);

            if (json.is_object() && isApiError(json)) {
                auto error = constructError(json);
                auto errorCode = error.first;
                auto errorMsg = std::move(error.second);

                try {
                    messageType message{};
                    return cb(MAKE_FILELINE, errorCode, std::move(errorMsg), std::move(message));
                } catch (const std::exception &ex) {

                    if (m_logMessageCB) {
                        m_logMessageCB(LogSeverity::Error, std::format("{}: {}\n", MAKE_FILELINE, ex.what()));
                    }
                }
            }

            try {
                if (m_onMessageCallback) { m_onMessageCallback(streamName.c_str(), ptr, size); }
            } catch (const std::exception &ex) {
                if (m_logMessageCB) {
                    m_logMessageCB(LogSeverity::Error, std::format("{}: {}\n", MAKE_FILELINE, ex.what()));
                }
            }

            try {
                messageType message;
                message.fromJson(json);
                return cb(fl, ec, std::move(errmsg), std::move(message));
            } catch (const std::exception &ex) {
                if (m_logMessageCB) {
                    m_logMessageCB(LogSeverity::Error, std::format("{}: {}\n", MAKE_FILELINE, ex.what()));
                }
            }

            return false;
        };

        h->start(
                m_host, m_port, requests, std::move(wsCallback), std::move(ws)
        );

        removeDeadWebsockets();

        m_map.emplace(h, std::move(wp));

        return h;
    }

    template<typename F>
    void stopChannelImpl(WebSocket::handle h, F f) {
        auto it = m_map.find(h);
        if (it == m_map.end()) { return; }

        if (auto s = it->second.lock()) {
            f(s);
        }

        m_map.erase(it);

        removeDeadWebsockets();
    }

    void stopChannel(WebSocket::handle h) {
        return stopChannelImpl(h, [](const auto &sp) { sp->stop(); });
    }

    template<typename F>
    void unsubscribe_all_impl(F f) {
        for (auto it = m_map.begin(); it != m_map.end();) {
            if (auto s = it->second.lock()) {
                f(s);
            }

            it = m_map.erase(it);
        }
    }

    void unsubscribeAll() {
        return unsubscribe_all_impl([](const auto &sp) { sp->stop(); });
    }

    void removeDeadWebsockets() {
        for (auto it = m_map.begin(); it != m_map.end();) {
            if (!it->second.lock()) {
                it = m_map.erase(it);
            } else {
                ++it;
            }
        }
    }

    template<typename F>
    void pingAllImpl(F f) {
        for (auto it = m_map.begin(); it != m_map.end();) {
            if (auto s = it->second.lock()) {
                f(s);
            }
            ++it;
        }
    }

    void pingAll() {
        return pingAllImpl([](const auto &sp) {
            sp->ping();
        });
    }
};

WebSocketClient::WebSocketClient(const std::string &apiKey, const std::string &apiSecret,
                                 const std::string &subAccountName) : m_p(spimpl::make_unique_impl<P>()) {
    m_p->m_apiKey = apiKey;
    m_p->m_apiSecret = apiSecret;
    m_p->m_subAccountName = subAccountName;
}

WebSocketClient::~WebSocketClient() {
    if (m_p->m_ioThread.joinable()) {
        m_p->m_ioThread.join();
    }
}

std::string WebSocketClient::composeStreamName(const std::string &pair, Channel channel) {
    std::string res;
    if (!pair.empty()) {
        res += pair;
        if (pair != "!") {
            boost::algorithm::to_lower(res);
        }

        res += '@';
    }

    res += channel._to_string();

    return res;
}

bool WebSocketClient::isRunning() const {
    return m_p->m_isRunning;
}

void WebSocketClient::run() {

    if (m_p->m_ioThread.joinable()) {
        m_p->m_ioThread.join();
    }

    m_p->m_ioThread = std::thread([&] {
        for (;;) {
            try {
                m_p->m_isRunning = true;
                m_p->m_ioContext.run();
                m_p->m_isRunning = false;
                break;
            }
            catch (std::exception &e) {
                m_p->m_ioContext.restart();

                if (m_p->m_logMessageCB) {
                    m_p->m_logMessageCB(LogSeverity::Error, std::format("{}: {}\n", MAKE_FILELINE, e.what()));
                }
            }
        }
    });
}

void WebSocketClient::runBlocking() {

    for (;;) {
        try {
            m_p->m_isRunning = true;
            m_p->m_ioContext.run();
            m_p->m_isRunning = false;
            break;
        }
        catch (std::exception &e) {
            m_p->m_ioContext.restart();

            if (m_p->m_logMessageCB) {
                m_p->m_logMessageCB(LogSeverity::Error, std::format("{}: {}\n", MAKE_FILELINE, e.what()));
            }
        }
    }
}

void WebSocketClient::unsubscribe(WebSocket::handle h) {
    return m_p->stopChannel(h);
}

void WebSocketClient::unsubscribeAll() {
    return m_p->unsubscribeAll();
}

void WebSocketClient::setLoggerCallback(const onLogMessage &onLogMessageCB) {
    m_p->m_logMessageCB = onLogMessageCB;
}

WebSocket::handle WebSocketClient::findStream(const std::string &streamName) {

    m_p->removeDeadWebsockets();

    for (const auto &el: m_p->m_map) {
        if (auto s = el.second.lock()) {
            if (streamName == s->streamName()) {
                return el.first;
            }
        }
    }

    return nullptr;
}

void WebSocketClient::runFor(int seconds) {

    if (m_p->m_ioThread.joinable()) {
        m_p->m_ioThread.join();
    }

    m_p->m_ioThread = std::thread([&] {

        boost::asio::steady_timer unsubscribe_timer{m_p->m_ioContext};
        unsubscribe_timer.expires_after(std::chrono::seconds{seconds});
        unsubscribe_timer.async_wait(
                [this](const boost::system::error_code &) {
                    unsubscribeAll();
                }
        );
        m_p->m_isRunning = true;
        m_p->m_ioContext.run();
        m_p->m_isRunning = false;
    });
}

void WebSocketClient::runBlockingFor(int seconds) {

    boost::asio::steady_timer unsubscribe_timer{m_p->m_ioContext};
    unsubscribe_timer.expires_after(std::chrono::seconds{seconds});
    unsubscribe_timer.async_wait(
            [this](const boost::system::error_code &) {
                unsubscribeAll();
            }
    );
    m_p->m_isRunning = true;
    m_p->m_ioContext.run();
    m_p->m_isRunning = false;
}

WebSocket::handle WebSocketClient::ticker(const std::string &pair, onEventCB cb) {
    return m_p->startChannel(pair, Channel::ticker, std::move(cb));
}

WebSocket::handle WebSocketClient::markets(const std::string &pair, onEventCB cb) {
    return m_p->startChannel(pair, Channel::markets, std::move(cb));
}

void WebSocketClient::pingAll() {
    m_p->pingAll();
}

WebSocket::handle WebSocketClient::orders(onEventCB cb) {
    return m_p->startChannel("", Channel::orders, std::move(cb));
}

WebSocket::handle WebSocketClient::fills(onEventCB cb) {
    return m_p->startChannel("", Channel::fills, std::move(cb));
}
}


text:
/*
 * This file belongs to the Galois project, a C++ library for exploiting parallelism.
 * The code is being released under the terms of the 3-Clause BSD License (a
 * copy is located in LICENSE.txt at the top-level directory).
 *
 * Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
 * UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
 * SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
 * PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
 * DEALING OR USAGE OF TRADE.  NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
 * RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
 * shall University be liable for incidental, special, indirect, direct or
 * consequential damages or loss of profits, interruption of business, or
 * related expenses which may arise from use of Software or Documentation,
 * including but not limited to those resulting from defects in Software and/or
 * Documentation, or loss or inaccuracy of data of any kind.
 */

#include "galois/Galois.h"
#include "galois/Reduction.h"
#include "galois/Bag.h"
#include "galois/Timer.h"
#include "galois/graphs/LCGraph.h"
#include "galois/ParallelSTL.h"
#include "llvm/Support/CommandLine.h"
#include "Lonestar/BoilerPlate.h"
#include "galois/runtime/Profile.h"
#include <boost/iterator/transform_iterator.hpp>
#define CHUNK_SIZE 256

const char* name = "TC";
const char* desc = "Counts the triangles in a graph (inputs do NOT need to be symmetrized)";
const char* url  = 0;

namespace cll = llvm::cl;
static cll::opt<std::string> filetype(cll::Positional, cll::desc("<filetype: txt,adj,mtx,gr>"), cll::Required);
static cll::opt<std::string> filename(cll::Positional, cll::desc("<filename: unsymmetrized graph>"), cll::Required);
typedef galois::graphs::LC_CSR_Graph<uint32_t, void>::with_numa_alloc<true>::type ::with_no_lockable<true>::type Graph;
typedef Graph::GraphNode GNode;

#include "Mining/util.h"

void TcSolver(Graph& graph) {
	galois::GAccumulator<unsigned> total_num;
	total_num.reset();
	galois::for_each(
		galois::iterate(graph.begin(), graph.end()),
		[&](const GNode& src, auto& ctx) {
			for (auto e1 : graph.edges(src)) {
				GNode dst = graph.getEdgeDst(e1);
				for (auto e2 : graph.edges(dst)) {
					GNode dst_dst = graph.getEdgeDst(e2);
					for (auto e3 : graph.edges(src)) {
						GNode dst2 = graph.getEdgeDst(e3);
						if (dst_dst == dst2) {
							total_num += 1;
							break;
						}
					}
				}
			}
		},
		galois::chunk_size<CHUNK_SIZE>(), galois::steal(),
		galois::loopname("Couting")
	);
	galois::gPrint("\ttotal_num_triangles = ", total_num.reduce(), "\n\n");
}

int main(int argc, char** argv) {
	galois::SharedMemSys G;
	LonestarStart(argc, argv, name, desc, url);
	Graph graph;
	galois::StatTimer Tinitial("GraphReadingTime");
	Tinitial.start();
	read_graph(graph, filetype, filename, true);
	Tinitial.stop();
	galois::gPrint("num_vertices ", graph.size(), " num_edges ", graph.sizeEdges(), "\n\n");

	galois::StatTimer Tcomp("Compute");
	Tcomp.start();
	TcSolver(graph);
	Tcomp.stop();
	return 0;
}


text:
// Autogenerated from KST: please remove this line if doing any edits by hand!

#include <boost/test/unit_test.hpp>
#include "term_strz.h"
#include <iostream>
#include <fstream>
#include <vector>

BOOST_AUTO_TEST_CASE(test_term_strz) {
    std::ifstream ifs("src/term_strz.bin", std::ifstream::binary);
    kaitai::kstream ks(&ifs);
    term_strz_t* r = new term_strz_t(&ks);

    BOOST_CHECK_EQUAL(r->s1(), std::string("foo"));
    BOOST_CHECK_EQUAL(r->s2(), std::string("bar"));
    BOOST_CHECK_EQUAL(r->s3(), std::string("|baz@"));

    delete r;
}


text:
#include "ros/ros.h"
#include "ros/console.h"
#include <stdio.h>

#include <numeric>
#include <vector>
#include <Eigen/Eigen>

#include "ros/publisher.h"
#include "ros/subscriber.h"
#include "nav_msgs/Odometry.h"
#include <tf/transform_broadcaster.h>
#include <sensor_msgs/LaserScan.h>

using namespace std;
using namespace Eigen;

// structure of the nearest neighbor
typedef struct{
    std::vector<float> distances;
    std::vector<int> src_indices;
    std::vector<int> tar_indices;
} NeighBor;

class icp{

public:

    icp(ros::NodeHandle &n);
    ~icp();
    ros::NodeHandle& n;

    // robot init states
    double robot_x;
    double robot_y;
    double robot_theta;
    // sensor states = robot_x_y_theta
    Vector3d sensor_sta;

    // max iterations
    int max_iter;
    // distance threshold for filter the matching points
    double dis_th;
    // tolerance to stop icp
    double tolerance;
    // if is the first scan, set as the map/target
    bool isFirstScan;
    // src point cloud matrix
    MatrixXd src_pc;
    // target point cloud matrix
    MatrixXd tar_pc;

    // ICP process function
    void process(sensor_msgs::LaserScan input);
    // transform the ros msg to Eigen Matrix
    Eigen::MatrixXd rosmsgToEigen(const sensor_msgs::LaserScan input);
    // fint the nearest points & filter
    NeighBor findNearest(const Eigen::MatrixXd &src, const Eigen::MatrixXd &tar);
    // get the transform from two point sets in one iteration
    Eigen::Matrix3d getTransform(const Eigen::MatrixXd &A, const Eigen::MatrixXd &B);
    // calc 2D Euclidean distance
    float calc_dist(const Eigen::Vector2d &pta, const Eigen::Vector2d &ptb);
    // transform vector states to matrix form
    Eigen::Matrix3d staToMatrix(const Vector3d sta);

    // ros-related subscribers, publishers and broadcasters
    ros::Subscriber laser_sub;
    void publishResult(Matrix3d T);
 	tf::TransformBroadcaster odom_broadcaster;
 	ros::Publisher odom_pub;
};

icp::~icp()
{}

icp::icp(ros::NodeHandle& n):
    n(n)
{

	// get the params
	n.getParam("/icp/robot_x", robot_x);
	n.getParam("/icp/robot_y", robot_y);
	n.getParam("/icp/robot_theta", robot_theta);
	sensor_sta << robot_x, robot_y, robot_theta;

	n.getParam("/icp/max_iter", max_iter);
	n.getParam("/icp/tolerance", tolerance);
	n.getParam("/icp/dis_th", dis_th);

    isFirstScan = true;
    laser_sub = n.subscribe("/scan", 1, &icp::process, this);
    odom_pub = n.advertise<nav_msgs::Odometry>("icp_odom", 1);
}

void icp::process(sensor_msgs::LaserScan input)
{
    cout<<"------seq:  "<<input.header.seq<<endl;

    // set the inital
    if(isFirstScan)
    {
        tar_pc = this->rosmsgToEigen(input);
        isFirstScan =false;
        return;
    }

	double time_0 = (double)ros::Time::now().toSec();

    // init some variables
    NeighBor neigh_;
    src_pc = this->rosmsgToEigen(input);
    cout<<"input cnt:  "<<src_pc.cols()<<endl;

    Eigen::MatrixXd src_pc_xy;
    Eigen::MatrixXd tar_chorder;

    Eigen::Matrix3d Transform;
    Eigen::Matrix3d Transform_acc = Eigen::MatrixXd::Identity(3,3);
    double prev_error = 0;
    double mean_error;
    int iter_cnt = 0;

    int match_cnt = 0;

    // main LOOP
    for(int i=0; i<max_iter; i++)
    {
    	// cout<<"---iter: "<<i<<endl;
        neigh_ = this->findNearest(src_pc.transpose(), tar_pc.transpose());

    	src_pc_xy = Eigen::MatrixXd::Ones(2, neigh_.src_indices.size());
    	tar_chorder = Eigen::MatrixXd::Ones(2, neigh_.src_indices.size());

        // filter ...
        for(int j=0; j<neigh_.src_indices.size(); j++)
        {
        		src_pc_xy.block<2,1>(0,j) = src_pc.block<2,1>(0, neigh_.src_indices[j]);
	            tar_chorder.block<2,1>(0,j) = tar_pc.block<2,1>(0, neigh_.tar_indices[j]);
        }
        // filter finished ...

        Transform = this->getTransform(src_pc_xy.transpose(), tar_chorder.transpose());

        Transform_acc = Transform * Transform_acc;

        src_pc = Transform * src_pc;

        mean_error = std::accumulate(neigh_.distances.begin(),neigh_.distances.end(),0.0)/neigh_.distances.size();

        if (abs(prev_error - mean_error) < tolerance)
            break;

        prev_error = mean_error;
    	iter_cnt ++;
    }
    cout<<"total_iter: "<<iter_cnt<<endl;

    tar_pc = this->rosmsgToEigen(input);

    this->publishResult(Transform_acc);

	double time_1 = (double)ros::Time::now().toSec();
	cout<<"time_cost:  "<<time_1-time_0<<endl;
}

Eigen::MatrixXd icp::rosmsgToEigen(const sensor_msgs::LaserScan input)
{
    int total_num = (input.angle_max - input.angle_min) / input.angle_increment + 1;

    Eigen::MatrixXd pc = Eigen::MatrixXd::Ones(3,total_num);

    float angle;
    for(int i=0; i<total_num; i++)
    {
        angle = input.angle_min + i * input.angle_increment;

        pc(0,i) = input.ranges[i] * std::cos(angle);
        pc(1,i) = input.ranges[i] * std::sin(angle);
    }
    return pc;
}

NeighBor icp::findNearest(const Eigen::MatrixXd &src, const Eigen::MatrixXd &tar)
{
    // temp cpy
    int row_src = src.rows();
    int row_tar = tar.rows();
    Eigen::Vector2d vec_src;
    Eigen::Vector2d vec_tar;

    NeighBor neigh;
    float min = 100;
    int index = 0;
    float dist_temp = 0;

    for(int ii=0; ii < row_src; ii++){
        vec_src = src.block<1,2>(ii,0).transpose();
        min = 100;
        index = 0;
        dist_temp = 0;
        for(int jj=0; jj < row_tar; jj++){
            vec_tar = tar.block<1,2>(jj,0).transpose();
            dist_temp = calc_dist(vec_src,vec_tar);
            if (dist_temp < min){
                min = dist_temp;
                index = jj;
            }
        }

        //filter added
        if(min < dis_th)
        {
        	neigh.distances.push_back(min);
        	neigh.src_indices.push_back(ii);
        	neigh.tar_indices.push_back(index);
        }
    }
    return neigh;
}

Eigen::Matrix3d icp::getTransform(const Eigen::MatrixXd &src, const Eigen::MatrixXd &tar)
{
    Eigen::Matrix3d T = Eigen::MatrixXd::Identity(3, 3);
    Eigen::Vector2d centroid_src(0,0);
    Eigen::Vector2d centroid_tar(0,0);
    Eigen::MatrixXd src_ = src;
    Eigen::MatrixXd tar_ = tar;
    int num = src.rows();

    for(int i=0; i<num; i++){
        centroid_src += src.block<1,2>(i,0).transpose();
        centroid_tar += tar.block<1,2>(i,0).transpose();
    }
    centroid_src /= num;
    centroid_tar /= num;

    for(int i=0; i<num; i++){
        src_.block<1,2>(i,0) = src.block<1,2>(i,0) - centroid_src.transpose();
        tar_.block<1,2>(i,0) = tar.block<1,2>(i,0) - centroid_tar.transpose();
    }

    Eigen::MatrixXd H = src_.transpose()*tar_;
    Eigen::MatrixXd U;
    Eigen::VectorXd S;
    Eigen::MatrixXd V;
    Eigen::MatrixXd Vt;
    Eigen::Matrix2d R;
    Eigen::Vector2d t;

    JacobiSVD<Eigen::MatrixXd> svd(H, ComputeFullU | ComputeFullV);
    U = svd.matrixU();
    S = svd.singularValues();
    V = svd.matrixV();
    Vt = V.transpose();

    R = Vt.transpose()*U.transpose();

    t = centroid_tar - R*centroid_src;

    T.block<2,2>(0,0) = R;
    T.block<2,1>(0,2) = t;
    return T;
}

float icp::calc_dist(const Eigen::Vector2d &pta, const Eigen::Vector2d &ptb)
{
    return std::sqrt((pta[0]-ptb[0])*(pta[0]-ptb[0]) + (pta[1]-ptb[1])*(pta[1]-ptb[1]));
}

Eigen::Matrix3d icp::staToMatrix(Eigen::Vector3d sta)
{
	Matrix3d RT;
    RT << cos(sta(2)), -sin(sta(2)), sta(0),
          sin(sta(2)), cos(sta(2)),sta(1),
          0, 0, 1;
    return RT;
}

void icp::publishResult(Eigen::Matrix3d T)
{
    float delta_yaw = atan2(T(1,0), T(0,0));
    cout<<"sensor-delta-xyt: "<<T(0,2)<<" "<<T(1,2)<<" "<<delta_yaw<<endl;

    sensor_sta(0) = sensor_sta(0) + cos(sensor_sta(2))*T(0,2) - sin(sensor_sta(2))*T(1,2);
    sensor_sta(1) = sensor_sta(1) + sin(sensor_sta(2))*T(0,2) + cos(sensor_sta(2))*T(1,2);
    sensor_sta(2) = sensor_sta(2) + delta_yaw;

    cout<<"sensor-global: "<<sensor_sta.transpose()<<endl;

    // tf
    geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(sensor_sta(2));

    geometry_msgs::TransformStamped odom_trans;
    odom_trans.header.stamp = ros::Time::now();
    odom_trans.header.frame_id = "world_base";
    odom_trans.child_frame_id = "icp_odom";

    odom_trans.transform.translation.x = sensor_sta(0);
    odom_trans.transform.translation.y = sensor_sta(1);
    odom_trans.transform.translation.z = 0.0;
    odom_trans.transform.rotation = odom_quat;

    odom_broadcaster.sendTransform(odom_trans);

    // odom
    nav_msgs::Odometry odom;
    odom.header.stamp = ros::Time::now();
    odom.header.frame_id = "world_base";

    odom.pose.pose.position.x = sensor_sta(0);
    odom.pose.pose.position.y = sensor_sta(1);
    odom.pose.pose.position.z = 0.0;
    odom.pose.pose.orientation = odom_quat;

    odom_pub.publish(odom);
}

int main(int argc, char **argv)
{
    ros::init(argc, argv, "icp");
    ros::NodeHandle n;

    icp icp_(n);

    ros::MultiThreadedSpinner spinner(1);
    spinner.spin();

    return 0;
}

max_stars_repo_name: MJYINMC/Wheeled-Robot

max_issues_repo_name: MJYINMC/Wheeled-Robot

max_forks_repo_name: MJYINMC/Wheeled-Robot