text:
// Boost.Geometry

// Copyright (c) 2018-2020 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle

// 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_STRATEGY_EXPAND_HPP
#define BOOST_GEOMETRY_STRATEGY_EXPAND_HPP

#include <boost/geometry/core/static_assert.hpp>

namespace boost { namespace geometry
{

namespace strategy { namespace expand { namespace services
{

/*!
\brief Traits class binding a default envelope strategy to a coordinate system
\ingroup util
\tparam Tag tag of geometry
\tparam CSTag tag of coordinate system
\tparam CalculationType \tparam_calculation
*/
template <typename Tag, typename CSTag, typename CalculationType = void>
struct default_strategy
{
    BOOST_GEOMETRY_STATIC_ASSERT_FALSE(
        "Not implemented for this type.",
        Tag, CSTag);
};

}}} // namespace strategy::expand::services

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGY_EXPAND_HPP


text:
#include <cstdio>
#include <iterator>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>

#include <boost/timer.hpp>
#include <boost/lexical_cast.hpp>

#include <CGAL/Simple_cartesian.h>
#include <CGAL/point_generators_2.h>
#include <CGAL/compiler_config.h>

int format_output(const char* lib, const char* generator, int n, float time) {
  return std::printf("| %s || %s || %d || %.4fM items/sec\n", lib, generator, n, time);
}

typedef CGAL::Simple_cartesian<double>         R;
typedef R::Point_2                             Point;
typedef CGAL::Creator_uniform_2<double,Point>  Creator;
typedef std::vector<Point>                     Vector;

int main(int argc, char* argv[]) {
  int n = 10000000;
  int repeats = 10;

  if(argc > 1)
    n = boost::lexical_cast<int>(argv[1]);

  if(argc > 2)
    repeats = boost::lexical_cast<int>(argv[2]);

  Vector points(n, Point());

  CGAL::Random_points_in_disc_2<Point,Creator> g( 1000.0);
  boost::timer timer;
  const char* generator = "Random_points_in_disc_2";
  float time;

  std::cout <<
    "{| \n"
    "! Library !! Generator !! #Elements !! items/sec \n"
    "|- \n";

  timer.restart();
  for (int i = 0; i < repeats; ++i) { CGAL::copy_n( g, n, points.begin()); }
  time = (double)n*repeats/timer.elapsed()/1.0E6;
  format_output("CGAL", generator , n, time);
  std::cout << "|- \n";

#ifndef CGAL_CFG_NO_CPP0X_COPY_N
  timer.restart();
  for (int i = 0; i < repeats; ++i) { std::copy_n( g, n, points.begin()); }
  time = (double)n*repeats/timer.elapsed()/1.0E6;
  format_output("stdlib", generator, n, time);
#endif

  //wiki markup footer
  std::cout << "|}" << std::endl;
}

ext: cpp

max_stars_repo_name: hlzz/dotfiles

max_issues_repo_name: hlzz/dotfiles

max_forks_repo_name: hlzz/dotfiles


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

using namespace Eigen;
using namespace std;

int main(int, char**)
{
  cout.precision(3);
  int array[24];
for(int i = 0; i < 24; ++i) array[i] = i;
cout << Map<MatrixXi, 0, Stride<Dynamic,2> >
         (array, 3, 3, Stride<Dynamic,2>(8, 2))
     << endl;

  return 0;
}

max_issues_repo_name: TANHAIYU/planecalib

max_forks_repo_name: TANHAIYU/planecalib


text:
#include <iostream>
#include <vector>

#include <algorithm>
#include <unordered_map>
#include <set>
#include <utility>
#include <stdexcept>
#include <cmath>
#include <chrono>
#include <exception>
#include <boost/filesystem.hpp>

#include "dynet/lstm.h"
#include "dynet/training.h"
#include "dynet/dynet.h"
#include "dynet/dict.h"

#include <boost/functional/hash.hpp>
#include <boost/program_options.hpp>
#include <boost/serialization/unordered_set.hpp>

#include "lemon_inc.h"
#include "serialization.h"
#include "nn/biaffine_parser.h"
#include "utils.h"

#include "dependency.h"
#include "spine_data.h"
#include "activation_function.h"

int main(int argc, char **argv)
{
    std::string train_path;
    std::string dev_path;
    std::string model_path;
    unsigned n_iteration;

    bool probabilistic;

    bool eval_on_dev;

    bool dropout;
    double dropout_p;

    std::string ignore_dynet_mem;
    std::string ignore_dynet_wd;

    unsigned n_stack;
    unsigned n_layer;
    int lstm_dim;
    int word_dim;
    int pos_dim;

    ActivationFunctionOption activation_function;
    bool best_head = false;

    namespace po = boost::program_options;
    po::options_description desc("Options");
    desc.add_options()
        ("train", po::value<std::string>(&train_path)->required(), "")
        ("model", po::value<std::string>(&model_path)->required(), "")
        ("iteration", po::value<unsigned>(&n_iteration)->default_value(20), "")
        ("eval-on-dev", po::value<bool>(&eval_on_dev)->default_value(false), "")
        ("dev-path", po::value<std::string>(&dev_path)->default_value(""), "")
        // dropout
        ("dropout", po::value<bool>(&dropout)->default_value(false), "")
        ("dropout-p", po::value<double>(&dropout_p)->default_value(0.5), "")
        // dynet
        ("dynet-mem", po::value<std::string>(&ignore_dynet_mem), "")
        ("dynet-weight-decay", po::value<std::string>(&ignore_dynet_wd), "")
        // nn options
        ("activation-function", po::value<ActivationFunctionOption>(&activation_function), "")
        ("lstm-dim", po::value<int>(&lstm_dim)->default_value(125))
        ("word-dim", po::value<int>(&word_dim)->default_value(100))
        ("pos-dim", po::value<int>(&pos_dim)->default_value(25))
        ("n-stack", po::value<unsigned>(&n_stack)->default_value(1u), "")
        ("n-layer", po::value<unsigned>(&n_layer)->default_value(1u), "")
        ("probabilistic", po::value<bool>(&probabilistic)->default_value(false), "")
        ("best-head", po::value<bool>(&best_head)->default_value(false))
    ;

    po::positional_options_description pod;
    pod.add("train", 1);
    pod.add("model", 1);

    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(desc).positional(pod).run(), vm);
    po::notify(vm);

    if (probabilistic && !best_head)
        throw std::runtime_error("Use --best-head=true in order to use probabilistic network");

    dynet::initialize(argc, argv);

    SpineSettings spine_settings;
    read_object(model_path + ".spine_settings.param", spine_settings);

    std::cerr << "Reading train data..." << std::endl << std::flush;
    SpineData spine_train(spine_settings);
    std::vector<IntSentence> train_data;
    spine_train.read(train_path);
    spine_train.as_int_sentence([&](const IntSentence& s) { train_data.push_back(s); });

    std::vector<IntSentence> dev_data;
    if (eval_on_dev)
    {
        SpineData spine_dev(spine_settings);
        spine_dev.read(dev_path);
        spine_dev.as_int_sentence([&](const IntSentence& s) { dev_data.push_back(s); });
    }

    // TODO: other trainer
    dynet::Model model;
    dynet::AdamTrainer trainer(model);
    trainer.sparse_updates_enabled = false;

    RNNSettings node_rnn_settings;
    node_rnn_settings.padding = true;
    node_rnn_settings.dim = lstm_dim;
    node_rnn_settings.n_stack = n_stack;
    node_rnn_settings.n_layer = n_layer;

    NeuralBiaffineParserSettings nn_settings;
    nn_settings.n_word = spine_settings.word_dict.size();
    nn_settings.n_pos = spine_settings.pos_dict.size();
    nn_settings.word_unknown = spine_settings.word_dict.convert("*UNKNOWN*");
    nn_settings.word_dim = word_dim;
    nn_settings.pos_dim = pos_dim;
    nn_settings.pos_input = true;
    nn_settings.activation_function = activation_function.value;

    NeuralBiaffineParser<dynet::LSTMBuilder> rnn(model, nn_settings, node_rnn_settings);

    for (auto const& sentence : train_data)
    {
        // Count word frequence (used for dropout)
        for (auto const& token : sentence)
            rnn.m_word_count[token.word] += 1;
    }

    double loss = 0.0;

    save_object(model_path + ".parser.nn_settings", nn_settings);
    save_object(model_path + ".parser.rnn_settings", node_rnn_settings);

    std::vector<unsigned> dev_uas;

    for (unsigned iteration = 0 ; iteration <= n_iteration ; ++iteration)
    {
        std::cerr << "Iteration: " << iteration << std::endl;
        std::cerr << std::flush;

        unsigned n_correct = 0;
        unsigned n_total = 0;

        std::random_shuffle(std::begin(train_data), std::end(train_data));

        for (const IntSentence& sentence : train_data)
        {
            dynet::ComputationGraph cg;

            // loss output
            std::vector<Expression> errs;

            if (best_head)
            {
                std::vector<unsigned> correct_indices(sentence.size());
                std::vector<std::vector<Expression>> head_exprs(sentence.size());

                std::vector<std::vector<double>> scores(sentence.size());

                rnn.compute(
                    cg,
                    sentence,
                    [&] (unsigned head, unsigned modifier, double score, dynet::expr::Expression& expr) -> void
                    {
                        if ((int) head == sentence[modifier].head)
                            correct_indices.at(modifier-1) = head_exprs.at(modifier-1).size();
                        head_exprs.at(modifier-1).push_back(expr);

                        if (!probabilistic)
                        {
                            // loss augmented
                            if ((int) head == sentence[modifier].head)
                                score += 1.0;

                            scores.at(modifier-1).push_back(score);
                        }
                    },
                    true, // word dropout
                    dropout,
                    dropout_p
                );

                if (probabilistic)
                {
                    for (unsigned i = 0u ; i < correct_indices.size() ; ++i)
                    {
                        // loss
                        dynet::expr::Expression heads = dynet::expr::concatenate(head_exprs.at(i));
                        errs.push_back(pickneglogsoftmax(heads, correct_indices.at(i)));

                        auto vec = dynet::as_vector(heads.value());
                        int predicted = std::distance(std::begin(vec), std::max_element(std::begin(vec), std::end(vec)));
                        if (predicted == (int) correct_indices.at(i))
                            n_correct += 1;
                    }
                }
                else
                {
                    for (unsigned i = 0u ; i < correct_indices.size() ; ++i)
                    {
                        // loss
                        dynet::expr::Expression heads = dynet::expr::concatenate(head_exprs.at(i));

                        auto vec = dynet::as_vector(heads.value());
                        int predicted = std::distance(std::begin(vec), std::max_element(std::begin(vec), std::end(vec)));
                        if (predicted == (int) correct_indices.at(i))
                        {
                            n_correct += 1;
                        }
                        else
                        {
                            errs.push_back(dynet::expr::pick(heads, predicted) - pick(heads, correct_indices.at(i)));
                        }
                    }
                }
            }
            else
            {
                // MSA decoding
                assert(!probabilistic);
                // TODO
                throw std::runtime_error("unimplemented");
            }
            n_total += sentence.size();

            // backprop
            if (errs.size() > 0)
            {
                Expression sum_errs = dynet::expr::sum(errs);
                loss += as_scalar(cg.get_value(sum_errs.i));
                cg.backward(sum_errs.i);
                trainer.update(1.0);
            }
        }

        trainer.update_epoch();
        trainer.status();

        std::cerr << "E = " << (loss / (double) n_total) << " ppl=" << exp(loss / (double) n_total) << " (acc=" << n_correct / (double) n_total << ")" << std::endl;
        std::cerr << std::flush;

        save_object(model_path + ".parser.param." + std::to_string(iteration), model);

        // Evaluate on dev set
        if (eval_on_dev)
        {
            unsigned n_good_head = 0u;
            unsigned n_total_head = 0u;

            std::cerr << "Evaluating on dev..." << std::endl << std::flush;

            for (auto const& sentence : dev_data)
            {
                dynet::ComputationGraph cg;

                LDigraph lemon_graph;
                LArcMap lemon_weights(lemon_graph);

                for (unsigned i = 0 ; i <= sentence.size() ; ++i)
                {
                    LNode node = lemon_graph.addNode();
                    assert(lemon_graph.id(node) == (int) i);
                }

                rnn.compute(
                    cg,
                    sentence,
                    [&] (unsigned head, unsigned modifier, double score, dynet::expr::Expression& expr) -> void
                    {
                        unused_parameter(expr);
                        LArc lemon_arc = lemon_graph.addArc(
                            lemon_graph.nodeFromId(head),
                            lemon_graph.nodeFromId(modifier)
                        );
                        lemon_weights[lemon_arc] = -score;
                    }
                );

                MSA msa(lemon_graph, lemon_weights);
                msa.run(lemon_graph.nodeFromId(0));

                for (unsigned modifier = 1 ; modifier <= sentence.size() ; ++modifier)
                {
                    auto msa_pred = msa.pred(lemon_graph.nodeFromId(modifier));
                    assert(msa_pred != lemon::INVALID);

                    int predicted = lemon_graph.id(lemon_graph.source(msa_pred));
                    if (predicted == sentence[modifier].head)
                        ++ n_good_head;
                }

                n_total_head += sentence.size();
            }

            std::cerr << " -> UAS: " << n_good_head / (double) n_total_head << std::endl;
            dev_uas.push_back(n_good_head);
        }
        std::cerr << "------" << std::endl;
    }

    if (eval_on_dev)
    {
        unsigned max = std::distance(std::begin(dev_uas), std::max_element(std::begin(dev_uas), std::end(dev_uas)));
        boost::filesystem::copy_file(
                model_path + ".parser.param." + std::to_string(max),
                model_path + ".parser.param",
                boost::filesystem::copy_option::overwrite_if_exists
        );

    }
    else
    {
        // juste resave the last model
        save_object(model_path + ".parser.param", model);
    }
}


text:
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>

#include <boost/ref.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>

static void interpolateJoints(const std::vector<double>& start,
                              const std::vector<double>& stop,
                              double ratio,
                              std::vector<double>& out)
{
  for (std::size_t i = 0; i < start.size(); ++i) {
    out[i] = start[i] + (stop[i] - start[i]) * ratio;
  }
}

class RobotSimulator
{
public:
  RobotSimulator(double rate, const std::vector<std::string>& names)
    : target_position_(names.size(), 0.0)
    , joint_velocities_(names.size(), 1.0)
    , joint_names_(names)
    , pub_rate_(rate)
    , active_flag_(false)
  {
  }

  ~RobotSimulator()
  {
    stop();
  }

  void start()
  {
    boost::unique_lock<boost::mutex> lock(mutex_);
    if (active_flag_) throw std::runtime_error("Don't call start twice");
    active_flag_ = true;

    worker_ = boost::thread(&RobotSimulator::worker_main, this);
  }

  void stop()
  {
    boost::unique_lock<boost::mutex> lock(mutex_);
    active_flag_ = false;
  }

  void update(const sensor_msgs::JointState& state) {
    boost::unique_lock<boost::mutex> lock(mutex_);
    target_position_ = state.position;
  }

private:
  void worker_main()
  {
    ros::NodeHandle nh;
    ros::Publisher pub = nh.advertise<sensor_msgs::JointState>("joint_states", 1);

    // State
    std::vector<double> current_position (joint_names_.size(), 0.0);
    ros::Rate rate (pub_rate_);

    // Prep message
    sensor_msgs::JointState state;
    state.header.frame_id = "world";
    state.header.stamp = ros::Time::now();
    state.name = joint_names_;

    // Main
    while (true)
    {
      // Fetch target
      std::vector<double> target;
      {
        boost::unique_lock<boost::mutex> lock(mutex_);
        if (!active_flag_) break;
        target = target_position_;
      }

      // Calculate maximum step
      interpolateJoints(current_position, target_position_, 0.03, current_position);

      // update message and publish
      state.position = current_position;
      state.header.stamp = ros::Time::now();
      pub.publish(state);

      // sleep
      rate.sleep();
    }
  }

  // State data
  std::vector<double> target_position_;
  const std::vector<double> joint_velocities_;
  const std::vector<std::string> joint_names_;
  double pub_rate_;

  // Thread stuff
  boost::thread worker_;
  boost::mutex mutex_;
  bool active_flag_;
};

void handleCommand(const sensor_msgs::JointStateConstPtr& states,
                   RobotSimulator& sim)
{
  sim.update(*states);
}

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

  // Load parameters
  double publish_rate;
  if (!nh.getParam("pub_rate", publish_rate)) {
    ROS_FATAL("Param 'pub_rate' must be set.");
    return -1;
  }

  std::vector<std::string> joint_names;
  if (!nh.getParam("controller_joint_names", joint_names)) {
    ROS_FATAL("Param 'controller_joint_names' must be set.");
    return -1;
  }

  RobotSimulator sim (publish_rate, joint_names);

  ros::Subscriber command_sub =
      nh.subscribe<sensor_msgs::JointState>("target", 1,
                                            boost::bind(handleCommand, _1, boost::ref(sim)));

  ROS_INFO("Starting teleop robot simulator.");
  sim.start();
  ros::spin();

  return 0;
}

max_stars_repo_name: swri-robotics/delaunay

max_issues_repo_name: swri-robotics/delaunay

max_forks_repo_name: swri-robotics/delaunay


text:
/*=============================================================================
    Copyright (c) 2010 Christopher Schmidt

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

#ifndef BOOST_FUSION_ADAPTED_ARRAY_TAG_OF_HPP
#define BOOST_FUSION_ADAPTED_ARRAY_TAG_OF_HPP

#include <boost/fusion/support/config.hpp>
#include <boost/fusion/support/tag_of_fwd.hpp>
#include <cstddef>

namespace boost
{
    namespace fusion
    {
        struct po_array_tag;
        struct po_array_iterator_tag;
        struct random_access_traversal_tag;
        struct fusion_sequence_tag;

        namespace traits
        {
#ifdef BOOST_NO_PARTIAL_SPECIALIZATION_IMPLICIT_DEFAULT_ARGS
            template<typename T, std::size_t N>
            struct tag_of<T[N], void>
            {
                typedef po_array_tag type;
            };

            template<typename T, std::size_t N>
            struct tag_of<T const[N], void>
            {
                typedef po_array_tag type;
            };
#else
            template<typename T, std::size_t N>
            struct tag_of<T[N], void>
            {
                typedef po_array_tag type;
            };

            template<typename T, std::size_t N>
            struct tag_of<T const[N], void>
            {
                typedef po_array_tag type;
            };
#endif
        }
    }

    namespace mpl
    {
        template<typename>
        struct sequence_tag;

        template<typename T, std::size_t N>
        struct sequence_tag<T[N]>
        {
            typedef fusion::po_array_tag type;
        };

        template<typename T, std::size_t N>
        struct sequence_tag<T const[N] >
        {
            typedef fusion::po_array_tag type;
        };
    }
}

#endif

ext: hpp


text:
#include "ompu/game/gc.hpp"
#include "ompu/game/game_data.hpp"
#include "ompu/midi.hpp"

#include "ompu/util.hpp"

#include <boost/scope_exit.hpp>

#include <thread>
#include <chrono>

#include <ctime>

namespace ompu { namespace game {

GC::Profile::Profile()
    : last_run_at(std::chrono::system_clock::now())
{
}

GC::GC(GameData* const gd)
    : gd_(gd)
    , l_(gd->envs(), "GC")
    , is_running_{false}
{}

GC::~GC()
{
    l_.note()
        << "remaining objects: "
        << gd_->in_midi_store_.size() + gd_->in_midi_store_sub_.size()
        << std::endl
    ;
    l_.note() << "(remaining objects will be destructed by the runtime)" << std::endl;
    l_.info() << "terminating..." << std::endl;
}

void GC::start()
{
    l_.info() << "start" << std::endl;
    is_running_ = true;

    try {
        while (is_running_) {
            if (this->need_run()) {
                this->run();
            }

            std::this_thread::yield();
            std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        }

#if 0
        //
        // ensure everything is cleaned
        //

        // if (this->need_run()) {
            this->run();
        // }
#endif

    } catch (std::exception const& e) {
        l_.note() << e.what() << std::endl;
        l_.error() << "!!! [BUG] exception thrown in GC !!!" << std::endl;
        throw;

    } catch (...) {
        l_.error() << "!!! [BUG] unknown exception thrown in GC !!!" << std::endl;
        throw;
    }
}

void GC::stop()
{
    //l_.info() << "stopping..." << std::endl;
    is_running_ = false;
}

bool GC::need_run()
{
    if (
        !gd_->in_midi_gc_.empty()

#if 0
        || !gd_->in_midi_sysex_gc_.empty()
#endif

    ) {
        return true;
    }

    return false;
}

void GC::run()
{
    auto const curr_run_start = clock_type::now();
    auto const curr_run_at = std::chrono::system_clock::now();
    std::size_t cleaned_obj_count = 0;

    BOOST_SCOPE_EXIT_ALL(this, curr_run_at, curr_run_start) {
        this->prof_->last_run_at = curr_run_at;
        this->prof_->last_run_at_steady = curr_run_start;
    };

    {
        l_.note() << "this run: " << ompu::util::time_print{curr_run_at} << std::endl;

        if (prof_) {
            l_.note() << "last run: " << ompu::util::time_print{prof_->last_run_at} << std::endl;
            l_.note() << "last run was " << std::chrono::duration_cast<std::chrono::seconds>(curr_run_at - prof_->last_run_at).count() << " sec ago" << std::endl;

            prof_ = std::make_unique<Profile>(*prof_);

        } else {
            l_.note() << "last run: (none, this is the initial run)" << std::endl;
            prof_ = std::make_unique<Profile>();
        }

        l_.info() << "running..." << std::endl;
    }

    {
        // do the GC
        std::lock_guard<decltype(gd_->store_mtx_)>
        lock(gd_->store_mtx_);

        cleaned_obj_count += gd_->in_midi_gc_.consume_all([this] (auto const& p) {
            gd_->in_midi_store_.erase(p);
        });
    }

    auto const curr_run_end = clock_type::now();

    l_.note()
        << "cleaned objects count: "
        << cleaned_obj_count
        << std::endl
    ;
    l_.note()
        << "took: "
        << std::chrono::duration_cast<std::chrono::milliseconds>(
            curr_run_end - curr_run_start
           ).count()
        << " msec"
        << std::endl
    ;
    l_.info() << "done" << std::endl;
}

}} // ompu

max_stars_repo_name: ompu/ompu

max_issues_repo_name: ompu/ompu

max_forks_repo_name: ompu/ompu


text:
/*------------------------------------------------------------------------------
                Copyright Butterfly Energy Systems 2014-2015.
           Distributed under the Boost Software License, Version 1.0.
              (See accompanying file LICENSE_1_0.txt or copy at
                    http://www.boost.org/LICENSE_1_0.txt)
------------------------------------------------------------------------------*/

#ifndef CPPWAMP_ASIOTRANSPORT_HPP
#define CPPWAMP_ASIOTRANSPORT_HPP

#include <array>
#include <chrono>
#include <cstdint>
#include <functional>
#include <memory>
#include <queue>
#include <stdexcept>
#include <string>
#include <utility>
#include <boost/asio/buffer.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <boost/system/error_code.hpp>
#include "../asiodefs.hpp"
#include "../error.hpp"
#include "../rawsockoptions.hpp"
#include "config.hpp"
#include "rawsockheader.hpp"

namespace wamp
{

namespace internal
{

//------------------------------------------------------------------------------
class AsioBuffer
{
public:
    void write(const char* data, size_t length) {payload_.append(data, length);}

    const char* data() const {return payload_.data();}

    size_t length() const {return payload_.length();}

private:
    using Header = uint32_t;
    using GatherBufs = std::array<boost::asio::const_buffer, 2>;

    void clear() {header_ = 0; payload_.clear();}

    void resize(size_t length) {payload_.resize(length);}

    GatherBufs gatherBuffers()
    {
        return GatherBufs{{ {&header_, sizeof(header_)},
                            {payload_.data(), payload_.size()} }};
    }

    boost::asio::mutable_buffers_1 headerBuffer()
    {
        return boost::asio::buffer(&header_, sizeof(header_));
    }

    boost::asio::mutable_buffers_1 payloadBuffer()
    {
        return boost::asio::buffer(&payload_.front(), payload_.length());
    }

    RawsockHeader header() const {return RawsockHeader::fromBigEndian(header_);}

    void prepare(RawsockMsgType type)
    {
        header_ = RawsockHeader().setMsgType(type)
                                 .setLength(payload_.length())
                                 .toBigEndian();
    }

    Header header_;
    std::string payload_;

    template <typename> friend class AsioTransport;
    template <typename> friend class LegacyAsioTransport;
};

//------------------------------------------------------------------------------
template <typename TSocket>
class AsioTransport :
        public std::enable_shared_from_this<AsioTransport<TSocket>>
{
public:
    using Ptr         = std::shared_ptr<AsioTransport>;
    using Buffer      = std::shared_ptr<AsioBuffer>;
    using RxHandler   = std::function<void (Buffer)>;
    using FailHandler = std::function<void (std::error_code ec)>;
    using PingHandler = std::function<void (float)>;

    using Socket      = TSocket;
    using SocketPtr   = std::unique_ptr<Socket>;

    static Ptr create(SocketPtr&& socket, size_t maxTxLength,
                      size_t maxRxLength)
    {
        return Ptr(new AsioTransport(std::move(socket), maxTxLength,
                                     maxRxLength));
    }

    // Noncopyable
    AsioTransport(const AsioTransport&) = delete;
    AsioTransport& operator=(const AsioTransport&) = delete;

    virtual ~AsioTransport() {}

    size_t maxSendLength() const {return maxTxLength_;}

    size_t maxReceiveLength() const {return maxRxLength_;}

    bool isOpen() const {return socket_ && socket_->is_open();}

    bool isStarted() const {return started_;}

    void start(RxHandler rxHandler, FailHandler failHandler)
    {
        assert(!started_);
        rxHandler_ = rxHandler;
        failHandler_ = failHandler;
        receive();
        started_ = true;
    }

    // TODO: Re-use buffers somehow
    Buffer getBuffer() {return std::make_shared<AsioBuffer>();}

    void send(Buffer message)
    {
        assert(started_);
        sendMessage(RawsockMsgType::wamp, std::move(message));
    }

    void close()
    {
        txQueue_ = TransmitQueue();
        rxHandler_ = nullptr;
        if (socket_)
            socket_->close();
    }

    template <typename TFunctor>
    void post(TFunctor&& fn) {iosvc_.post(std::forward<TFunctor>(fn));}

    void ping(Buffer message, PingHandler handler)
    {
        assert(started_);
        pingHandler_ = std::move(handler);
        pingBuffer_ = std::move(message);
        sendMessage(RawsockMsgType::ping, pingBuffer_);
        pingStart_ = std::chrono::high_resolution_clock::now();
    }

protected:
    using IoService     = AsioService;
    using TransmitQueue = std::queue<Buffer>;
    using TimePoint     = std::chrono::high_resolution_clock::time_point;

    AsioTransport(SocketPtr&& socket, size_t maxTxLength, size_t maxRxLength)
        : socket_(std::move(socket)),
          iosvc_(socket_->get_io_service()),
          maxTxLength_(maxTxLength),
          maxRxLength_(maxRxLength)
    {}

    virtual void sendMessage(RawsockMsgType type, Buffer message)
    {
        assert(socket_ && "Attempting to send on bad transport");
        assert((message->length() <= maxTxLength_) &&
               "Outgoing message is longer than allowed by peer");

        message->prepare(type);
        txQueue_.push(std::move(message));
        transmit();
    }

private:
    void transmit()
    {
        if (isReadyToTransmit())
        {
            txBuffer_ = txQueue_.front();
            txQueue_.pop();

            auto self = this->shared_from_this();
            boost::asio::async_write(*socket_, txBuffer_->gatherBuffers(),
                [this, self](AsioErrorCode ec, size_t size)
                {
                    txBuffer_.reset();
                    if (ec)
                    {
                        txQueue_ = TransmitQueue();
                        socket_.reset();
                    }
                    else
                    {
                        transmit();
                    }
                });
        }
    }

    bool isReadyToTransmit() const
    {
        return socket_ &&           // Socket is still open
               !txBuffer_ &&        // No async_write is in progress
               !txQueue_.empty();   // One or more messages are enqueued
    }

    void receive()
    {
        if (socket_)
        {
            rxBuffer_ = getBuffer();
            auto self = this->shared_from_this();
            boost::asio::async_read(*socket_, rxBuffer_->headerBuffer(),
                [this, self](AsioErrorCode ec, size_t)
                {
                    if (check(ec))
                        processHeader();
                });
        }
    }

    virtual void processHeader()
    {
        auto hdr = rxBuffer_->header();
        auto length  = hdr.length();
        if ( check(length <= maxRxLength_, TransportErrc::badRxLength) &&
             check(hdr.msgTypeIsValid(), RawsockErrc::badMessageType) )
        {
            receivePayload(hdr.msgType(), length);
        }
    }

    void receivePayload(RawsockMsgType msgType, size_t length)
    {
        rxBuffer_->resize(length);
        auto self = this->shared_from_this();
        boost::asio::async_read(*socket_, rxBuffer_->payloadBuffer(),
            [this, self, msgType](AsioErrorCode ec, size_t)
            {
                if (ec)
                    rxBuffer_->clear();
                if (check(ec))
                    switch (msgType)
                    {
                    case RawsockMsgType::wamp:
                        if (rxHandler_)
                            iosvc_.post(std::bind(rxHandler_,
                                                  std::move(rxBuffer_)));
                        receive();
                        break;

                    case RawsockMsgType::ping:
                        sendPong();
                        break;

                    case RawsockMsgType::pong:
                        receivePong();
                        break;

                    default:
                        assert(false);
                    }
            });
    }

    void sendPong()
    {
        auto buf = getBuffer();
        buf->payload_.swap(rxBuffer_->payload_);
        sendMessage(RawsockMsgType::pong, std::move(buf));
        receive();
    }

    void receivePong()
    {
        if (pingHandler_ && (rxBuffer_->payload_ == pingBuffer_->payload_))
        {
            pingBuffer_.reset();
            namespace chrn = std::chrono;
            pingStop_ = chrn::high_resolution_clock::now();
            using Fms = chrn::duration<float, chrn::milliseconds::period>;
            float elapsed = Fms(pingStop_ - pingStart_).count();
            iosvc_.post(std::bind(pingHandler_, elapsed));
            pingHandler_ = nullptr;
        }
        receive();
    }

    bool check(AsioErrorCode asioEc)
    {
        if (asioEc)
        {
            if (failHandler_)
            {
                auto ec = make_error_code(
                            static_cast<std::errc>(asioEc.value()));
                iosvc_.post(std::bind(failHandler_, ec));
            }
            cleanup();
        }
        return !asioEc;
    }

    template <typename TErrc>
    bool check(bool condition, TErrc errc)
    {
        if (!condition)
        {
            if (failHandler_)
                iosvc_.post(std::bind(failHandler_, make_error_code(errc)));
            cleanup();
        }
        return condition;
    }

    void cleanup()
    {
        rxHandler_ = nullptr;
        pingHandler_ = nullptr;
        failHandler_ = nullptr;
        txQueue_ = TransmitQueue();
        socket_.reset();
        rxBuffer_.reset();
        pingBuffer_.reset();
    }

    std::unique_ptr<TSocket> socket_;
    AsioService& iosvc_;
    size_t maxTxLength_;
    size_t maxRxLength_;
    bool started_ = false;
    RxHandler rxHandler_;
    FailHandler failHandler_;
    PingHandler pingHandler_;
    Buffer rxBuffer_;
    Buffer pingBuffer_;
    TransmitQueue txQueue_;
    Buffer txBuffer_;
    TimePoint pingStart_;
    TimePoint pingStop_;
};

} // namespace internal

} // namespace wamp

#endif // CPPWAMP_ASIOTRANSPORT_HPP

max_stars_repo_name: ecorm/cppwamp

max_issues_repo_name: ecorm/cppwamp

max_forks_repo_name: ecorm/cppwamp


text:
#include <boost/program_options.hpp>
#include <cartographer/mapping/map_builder.h>
#include <cartographer/mapping/map_builder_interface.h>
#include <cartographer_ros/node.h>
#include <cartographer_ros/node_options.h>
#include <cartographer_ros/ros_log_sink.h>
#include <cartographer_ros/urdf_reader.h>
#include <ros/ros.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>
#include <urdf/model.h>

#include <memory>
#include <string>
#include <vector>

namespace po = boost::program_options;

namespace cartographer_ros
{

void testFindConstraint(const std::string& configuration_directory, const std::string& urdf_filename,
                        const std::string& pbstream_filename, const std::string& rosbag_filename)
{
    LOG(INFO) << "TestFindConstraint";

    cartographer_ros::NodeOptions node_options;
    TrajectoryOptions trajectory_options;
    std::tie(node_options, trajectory_options) = LoadOptions(configuration_directory, "cartographer.lua");

    LOG(INFO) << "Loading URDF";
    auto tf_buffer = std::make_shared<tf2_ros::Buffer>();
    tf_buffer->setUsingDedicatedThread(true);
    ReadStaticTransformsFromUrdf(urdf_filename, tf_buffer.get());

    LOG(INFO) << "Building MapBuilder";
    auto map_builder_bridge = std::make_unique<MapBuilderBridge>(node_options, tf_buffer);
    std::ifstream file(pbstream_filename);
    map_builder_bridge->LoadState(file, true);

    using SensorId = cartographer::mapping::TrajectoryBuilderInterface::SensorId;
    using SensorType = SensorId::SensorType;
//    SensorId odom{SensorType::ODOMETRY, "odom"};
    SensorId front_laser{SensorType::RANGE, "/sick_s300_front/scan"};
    SensorId back_laser{SensorType::RANGE, "/sick_s300_back/scan"};
    const std::set<cartographer::mapping::TrajectoryBuilderInterface::SensorId> expected_sensor_ids = {front_laser,
                                                                                back_laser};

    const int trajectory_id = map_builder_bridge->AddTrajectory(expected_sensor_ids, trajectory_options);

    rosbag::Bag bag(rosbag_filename, rosbag::bagmode::Read);

    rosbag::View view(bag);
    for (const auto info : view.getConnections())
        LOG(INFO) << "Topic: " << info->topic;

    rosbag::View front_laser_view(bag, rosbag::TopicQuery(front_laser.id));
    rosbag::View back_laser_view(bag, rosbag::TopicQuery(back_laser.id));
//    rosbag::View odom_view(bag, rosbag::TopicQuery(odom.id));

    LOG(INFO) << "Loading data...";

    auto front_laser_msgs = front_laser_view.begin();
    auto back_laser_msgs = back_laser_view.begin();
//    auto odom_msgs = odom_view.begin();

    if (front_laser_msgs == front_laser_view.end())
        ROS_FATAL("No front laser message");

    if (back_laser_msgs == back_laser_view.end())
        ROS_FATAL("No back laser message");

    map_builder_bridge->sensor_bridge(trajectory_id)
        ->HandleLaserScanMessage(front_laser.id, front_laser_msgs->instantiate<sensor_msgs::LaserScan>());
    map_builder_bridge->sensor_bridge(trajectory_id)
        ->HandleLaserScanMessage(back_laser.id, back_laser_msgs->instantiate<sensor_msgs::LaserScan>());

    map_builder_bridge->RunFinalOptimization();
}

}  // namespace cartographer_ros

int main(int argc, char** argv)
{
    //    google::InitGoogleLogging(argv[0]);

    std::string configuration_directory;
    std::string pbstream_filename;
    std::string urdf_filename;
    std::string rosbag_filename;

    po::options_description desc("Options");
    try
    {
        // clang-format off
        desc.add_options()
        ("help,h", "Help Screen")
        ("configuration_directory", po::value<std::string>(&configuration_directory)->required(), "Cartographer configuration directory")
        ("pbstream", po::value<std::string>(&pbstream_filename)->required(), "Pbstream map")
        ("urdf", po::value<std::string>(&urdf_filename)->required(), "URDF")
        ("rosbag", po::value<std::string>(&rosbag_filename)->required(), "Rosbag");
        // clang-format on

        po::variables_map vm;
        po::store(po::parse_command_line(argc, argv, desc), vm);

        if (vm.count("help"))
        {
            std::cout << "display_pattern: " << std::endl << desc << std::endl;
            return EXIT_SUCCESS;
        }

        po::notify(vm);
    }
    catch (const po::error& e)
    {
        std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
        std::cerr << desc << std::endl;
        return EXIT_FAILURE;
    }

    cartographer_ros::testFindConstraint(configuration_directory, urdf_filename, pbstream_filename, rosbag_filename);
}

ext: cc


text:
// -*- coding: utf-8 -*-
#pragma once

#include <cassert>
#include <cmath>
#include <tuple>

#include "cut_config.hpp"
#include "half_nonnegative.hpp"

/**
 * @brief Find a point in a convex set (defined through a cutting-plane oracle).
 *
 *     A function f(x) is *convex* if there always exist a g(x)
 *     such that f(z) >= f(x) + g(x)' * (z - x), forall z, x in dom f.
 *     Note that dom f does not need to be a convex set in our definition.
 *     The affine function g' (x - xc) + beta is called a cutting-plane,
 *     or a ``cut'' for short.
 *     This algorithm solves the following feasibility problem:
 *
 *             find x
 *             s.t. f(x) <= 0,
 *
 *     A *separation oracle* asserts that an evalution point x0 is feasible,
 *     or provide a cut that separates the feasible region and x0.
 *
 * @tparam Oracle
 * @tparam Space
 * @param[in,out] Omega perform assessment on x0
 * @param[in,out] S     search Space containing x*
 * @param[in] options   maximum iteration and error tolerance etc.
 * @return Information of Cutting-plane method
 */
template <typename Oracle, typename Space>
auto cutting_plane_feas(Oracle&& Omega, Space&& S, const Options& options = Options()) -> CInfo {
    auto feasible = false;
    auto status = CUTStatus::success;

    auto niter = 0U;
    while (++niter != options.max_it) {
        const auto cut = Omega(S.xc());  // query the oracle at S.xc()
        if (!cut) {                      // feasible sol'n obtained
            feasible = true;
            break;
        }
        const auto result = S.update(*cut);  // update S

        const auto& cutstatus = std::get<0>(result);
        const auto& tsq = std::get<1>(result);
        if (cutstatus != CUTStatus::success) {
            status = cutstatus;
            break;
        }
        if (tsq < options.tol) {  // no more
            status = CUTStatus::smallenough;
            break;
        }
    }
    return {feasible, niter, status};
}

/**
 * @brief Cutting-plane method for solving convex problem
 *
 * @tparam Oracle
 * @tparam Space
 * @tparam opt_type
 * @param[in,out] Omega perform assessment on x0
 * @param[in,out] S     search Space containing x*
 * @param[in,out] t     best-so-far optimal sol'n
 * @param[in] options   maximum iteration and error tolerance etc.
 * @return Information of Cutting-plane method
 */
template <typename Oracle, typename Space, typename opt_type>
auto cutting_plane_dc(Oracle&& Omega, Space&& S, opt_type&& t, const Options& options = Options()) {
    const auto t_orig = t;
    decltype(S.xc()) x_best;
    auto status = CUTStatus::success;

    auto niter = 0U;
    while (++niter != options.max_it) {
        const auto result1 = Omega(S.xc(), t);
        const auto& cut = std::get<0>(result1);
        const auto& shrunk = std::get<1>(result1);
        if (shrunk) {  // best t obtained
            x_best = S.xc();
        }
        const auto result2 = S.update(cut);

        const auto& cutstatus = std::get<0>(result2);
        const auto& tsq = std::get<1>(result2);
        if (cutstatus != CUTStatus::success)  // ???
        {
            status = cutstatus;
            break;
        }
        if (tsq < options.tol) {  // no more
            status = CUTStatus::smallenough;
            break;
        }
    }
    return std::make_tuple(std::move(x_best), CInfo{t != t_orig, niter, status});
}  // END

/**
    Cutting-plane method for solving convex discrete optimization problem
    input
             oracle        perform assessment on x0
             S(xc)         Search space containing x*
             t             best-so-far optimal sol'n
             max_it        maximum number of iterations
             tol           error tolerance
    output
             x             solution vector
             niter          number of iterations performed
**/
// #include <boost/numeric/ublas/symmetric.hpp>
// namespace bnu = boost::numeric::ublas;
// #include <xtensor-blas/xlinalg.hpp>
// #include <xtensor/xarray.hpp>

/**
 * @brief Cutting-plane method for solving convex discrete optimization problem
 *
 * @tparam Oracle
 * @tparam Space
 * @param[in,out] Omega perform assessment on x0
 * @param[in,out] S     search Space containing x*
 * @param[in,out] t     best-so-far optimal sol'n
 * @param[in] options   maximum iteration and error tolerance etc.
 * @return Information of Cutting-plane method
 */
template <typename Oracle, typename Space, typename opt_type>
auto cutting_plane_q(Oracle&& Omega, Space&& S, opt_type&& t, const Options& options = Options()) {
    const auto t_orig = t;
    decltype(S.xc()) x_best;
    auto status = CUTStatus::nosoln;  // note!!!
    auto retry = (status == CUTStatus::noeffect);

    auto niter = 0U;
    while (++niter != options.max_it) {
        // auto retry = (status == CUTStatus::noeffect);
        const auto result1 = Omega(S.xc(), t, retry);
        const auto& cut = std::get<0>(result1);
        const auto& shrunk = std::get<1>(result1);
        const auto& x0 = std::get<2>(result1);
        const auto& more_alt = std::get<3>(result1);
        if (shrunk) {  // best t obtained
            // t = t1;
            x_best = x0;  // x0
        }
        const auto result2 = S.update(cut);
        const auto& cutstatus = std::get<0>(result2);
        const auto& tsq = std::get<1>(result2);

        if (cutstatus == CUTStatus::noeffect) {
            if (!more_alt) {  // more alt?
                break;        // no more alternative cut
            }
            status = cutstatus;
            retry = true;
        }
        if (cutstatus == CUTStatus::nosoln) {
            status = cutstatus;
            break;
        }
        if (tsq < options.tol) {
            status = CUTStatus::smallenough;
            break;
        }
    }
    return std::make_tuple(std::move(x_best), CInfo{t != t_orig, niter, status});
}  // END

/**
 * @brief
 *
 * @tparam Oracle
 * @tparam Space
 * @param[in,out] Omega    perform assessment on x0
 * @param[in,out] I        interval containing x*
 * @param[in]     options  maximum iteration and error tolerance etc.
 * @return CInfo
 */
template <typename Oracle, typename Space>
auto bsearch(Oracle&& Omega, Space&& I, const Options& options = Options()) -> CInfo {
    // assume monotone
    // auto& [lower, upper] = I;
    auto& lower = I.first;
    auto& upper = I.second;
    assert(lower <= upper);
    const auto u_orig = upper;
    auto niter = 0U;
    auto status = CUTStatus::success;

    for (; niter != options.max_it; ++niter) {
        auto tau = algo::half_nonnegative(upper - lower);
        if (tau < options.tol) {
            status = CUTStatus::smallenough;
            break;
        }

        auto t = lower;  // l may be `int` or `Fraction`
        t += tau;
        if (Omega(t)) {  // feasible sol'n obtained
            upper = t;
        } else {
            lower = t;
        }
    }
    return {upper != u_orig, niter + 1, status};
}

/**
 * @brief
 *
 * @tparam Oracle
 * @tparam Space
 */
template <typename Oracle, typename Space>  //
class bsearch_adaptor {
  private:
    Oracle& _P;
    Space& _S;
    const Options _options;

  public:
    /**
     * @brief Construct a new bsearch adaptor object
     *
     * @param[in,out] P perform assessment on x0
     * @param[in,out] S search Space containing x*
     */
    bsearch_adaptor(Oracle& P, Space& S) : bsearch_adaptor{P, S, Options()} {}

    /**
     * @brief Construct a new bsearch adaptor object
     *
     * @param[in,out] P perform assessment on x0
     * @param[in,out] S search Space containing x*
     * @param[in] options maximum iteration and error tolerance etc.
     */
    bsearch_adaptor(Oracle& P, Space& S, const Options& options)
        : _P{P}, _S{S}, _options{options} {}

    /**
     * @brief get best x
     *
     * @return auto
     */
    auto x_best() const { return this->_S.xc(); }

    /**
     * @brief
     *
     * @param[in,out] t the best-so-far optimal value
     * @return bool
     */
    template <typename opt_type> auto operator()(const opt_type& t) -> bool {
        Space S = this->_S.copy();
        this->_P.update(t);
        const auto ell_info = cutting_plane_feas(this->_P, S, this->_options);
        if (ell_info.feasible) {
            this->_S.set_xc(S.xc());
        }
        return ell_info.feasible;
    }
};


text:
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <exception>
#include <string>
#include <cctype>
#include <boost/program_options.hpp>
#include <signal.h>

#include "midiprocess.hpp"

typedef std::map<KeyCode,char> KeyCodeMidiMap_t;

static void signal_handler(int sig);
KeyCodeMidiMap_t parse_config(const std::string& filename);
XkbDescPtr bind_keys(Display* display, int device, const KeyCodeMidiMap_t& keycodes, bool generateEvents);

int main (int argc, char ** argv)
{
	const std::string JACK_CLIENT_NAME("xkb2midi");

	/*sigaction sigact;
	sigact.sa_handler = signal_handler;
	sigemptyset(&sigact.sa_mask);
	sigact.sa_flags = 0;
	sigaction(SIGINT, &sigact, nullptr);*/

	std::string homepath = getenv("HOME");
	int device;
	std::string cfgFilename;

	namespace po = boost::program_options;
	po::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "produce help message")
		("config,c",
			po::value<std::string>(&cfgFilename)->default_value(homepath + "/.config/xkb2midi.cfg"),
			"Set configuration file for keycode to note mappings.")
		("device,d",
			po::value<int>(&device)->default_value(XkbUseCoreKbd),
			"Set xkb device index (c.f. `xinput list`). Default value is the core keyboard, which"
			" probably should be avoided.")
		("unmap,u", "Prevent mapped keys from generating key events as usual.")
	;

	po::variables_map vm;
	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	if(vm.count("help")) {
		std::cerr << desc << std::endl;
		std::cerr <<
			"This program reads keycodes and midi note numbers from a config file\n"
			"and reconfigures a specific keyboard using the XKeyboard Extension.\n"
			"\nThe program then listens for keyboard events on the mapped keys,\n"
			"translating keystrokes to midi key press/release events outputted over\n"
                        "a jack connection. The program doesn't have to be in focus to work.\n"
			"\nPlease be aware that this program can potentially lock up your input handling,\n"
			"so don't use it on your core keyboard(!)\n" << std::endl;
		return 1;
	}

	bool generateEvents = !vm.count("unmap");

        std::map<KeyCode,char> kcNoteMap;
        try{
            std::map<KeyCode,char> kcNoteMap = parse_config(cfgFilename);
        }catch(std::invalid_argument& e)
        {
            std::cerr << "Unable to parse config file: '" << cfgFilename << "' - File does not exist." << std::endl;
            return 1;
        }

	if(device == XkbUseCoreKbd)
	{
		std::cout << "Are you sure you want to use the Core keyboard? This might make your system inoperable. (y/N) " << std::flush;
		char c;
		std::cin >> std::noskipws >> c;
		if(c!='y' && c!='Y') {
			std::cout << "Exiting ..." << std::endl;
			exit(1);
		}
		std::cout << std::endl;
	}

	// connect to X and XKeyboard Extension
	int event_base, error_base, open_result;
	Display *display = XkbOpenDisplay(nullptr, &event_base, &error_base, nullptr, nullptr, &open_result);

	if ( !display ) {
		std::cerr << "Failed to open X display\n" << std::endl;
		exit(1);
	}

	XkbDescPtr kbd = XkbGetMap(display, XkbKeySymsMask|XkbKeyActionsMask, device);
	if(kbd == nullptr) {
		std::cerr << "Unable to get map for device #" << device << std::endl;
		return 1;
	}

	kbd = bind_keys(display, device, kcNoteMap, generateEvents);

	MidiProcess mp(JACK_CLIENT_NAME);
	mp.activate();

	XkbSelectEvents(
		display, device,
		XkbActionMessageMask|XkbMapNotifyMask|XkbNewKeyboardNotifyMask,
		XkbActionMessageMask|XkbMapNotifyMask|XkbNewKeyboardNotifyMask);

	XEvent ev;
	while(XNextEvent(display, &ev) == Success)
	{
		if(ev.type == (event_base+XkbEventCode))
		{
			XkbEvent& xkbEvent = reinterpret_cast<XkbEvent&>(ev);
			switch(xkbEvent.any.xkb_type)
			{
				case XkbNewKeyboardNotify:
					if(xkbEvent.new_kbd.device != xkbEvent.new_kbd.old_device)
						break;// otherwise run MapNotify code - should be refactored.
				case XkbMapNotify:
					XkbRefreshKeyboardMapping(&xkbEvent.map);
					XkbSelectEvents(display, device, XkbMapNotifyMask, 0);
					kbd = bind_keys(display, device, kcNoteMap, generateEvents);
					XkbSelectEvents(display, device, XkbMapNotifyMask, XkbMapNotifyMask);
					break;
				case XkbActionMessage:
					{
						std::cout << "Got action message." << std::endl;
						// remove repeated presses.
						auto it = kcNoteMap.find(xkbEvent.message.keycode);
						if(it != kcNoteMap.end())
							mp.enqueue_packet(midi_packet(xkbEvent.message.press, it->second, 100));
					}
					break;
				default:
					std::cout << "Unknown xkb event: " << std::hex << xkbEvent.any.xkb_type << std::endl;
					break;
			}
		}
	}

	XCloseDisplay( display );
	return 0;
}

KeyCodeMidiMap_t parse_config(const std::string& filename)
{
	KeyCodeMidiMap_t res;
	std::ifstream fstr(filename);
	if(!fstr)
		throw std::invalid_argument("File: '"+filename+"' does not exist.");
	std::string line;

	std::cerr << "Parsing: '" << filename << "'" << std::endl;

	auto is_only_whitespace =
		[](const std::string& str, size_t pos=0){
			return std::all_of(std::next(str.begin(),pos), str.end(), [](char c){ return std::isspace(c);} );
		};

	unsigned int lineno = 1;
	while(!fstr.eof()) {
		std::getline(fstr, line);

		size_t found = line.find(";"); // comment
		if(found!=std::string::npos)
			line = line.substr(0, found);

		found = line.find("=");
		if(found!=std::string::npos) {
			std::string kcStr		= line.substr(0, found);
			std::string midiNoteStr = line.substr(found+1, std::string::npos);

			size_t pos;
			unsigned long kc, midiNote;
			try{
				kc = std::stoul(kcStr, &pos);
				if(pos!=kcStr.size() && !is_only_whitespace(kcStr, pos))
					throw std::invalid_argument(kcStr);

				midiNote = std::stoul(midiNoteStr, &pos);
				if(pos!=midiNoteStr.size() && !is_only_whitespace(midiNoteStr, pos))
					throw std::invalid_argument(midiNoteStr);

				std::cout << "kc " << kc << " :> note #" << midiNote << std::endl;
				res.emplace(std::make_pair(static_cast<KeyCode>(kc), midiNote & 0x7F));

			}catch(std::invalid_argument e){
				std::cerr << "Unable to parse line " << lineno << ": '" << e.what() << "'" << std::endl;
			}
		}else if(!is_only_whitespace(line)){
			std::cerr << "Unable to parse line " << lineno << ": '" << line << "'" << std::endl;
		}

		lineno++;
	}

	return res;
}

XkbDescPtr bind_keys(Display* display, int device, const KeyCodeMidiMap_t& keycodes, bool generateEvents)
{
	XkbDescPtr kbd = XkbGetMap(display, XkbKeySymsMask|XkbKeyActionsMask, device);

	for(const auto& pkc : keycodes)
	{
		auto kc = pkc.first;
		int nSyms = XkbKeyNumSyms(kbd, kc);

		if(XkbKeyActionEntry(kbd, kc, 0, 0) == nullptr)
		{
			std::cout << "Adding Xkb action to keycode 0x"
				<< std::hex << static_cast<unsigned int>(kc) << std::endl;
			assert(nSyms > 0);
			if(XkbResizeKeyActions(kbd, kc, 1) == nullptr)
			{
				std::cerr << "Unable to resize action field for keycode 0x"
					<< std::hex << static_cast<unsigned int>(kc) << std::endl;
				continue;
			}
		}

		XkbMessageAction ma;
		memset(&ma, 0, sizeof(ma));
		ma.type = XkbSA_ActionMessage;
		ma.flags = XkbSA_MessageOnPress|XkbSA_MessageOnRelease;
		if(generateEvents)
			ma.flags |= XkbSA_MessageGenKeyEvent;
		strncpy(reinterpret_cast<char*>(ma.message), "!", XkbActionMessageLength);

		XkbAction* ka = XkbKeyActionEntry(kbd, kc, 0, 0);
		assert(ka != nullptr);
		ka->msg = ma; // copy by value

		XkbMapChangesRec changes;
		memset(&changes, 0, sizeof(changes));
		changes.changed |= XkbKeyActionsMask;
		changes.first_key_act = kc;
		changes.num_key_acts = 1;

		if(!XkbChangeMap(display, kbd, &changes))
		{
			std::cerr << "Unable to add action to keycode 0x" << std::hex << static_cast<unsigned int>(kc) << std::endl;
			continue;
		}
	}

	return kbd;
}

void signal_handler(int signo)
{
	if(signo==SIGINT) exit(1);
}


text: #include <boost/bimap/property_map/set_support.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "ompl/control/planners/ltl/ProductGraph.h"
#include "ompl/base/State.h"
#include "ompl/control/planners/ltl/Automaton.h"
#include "ompl/control/planners/ltl/PropositionalDecomposition.h"
#include "ompl/control/planners/ltl/World.h"
#include "ompl/util/ClassForward.h"
#include "ompl/util/Console.h"
#include <algorithm>
#include <boost/function.hpp>
#include <boost/functional/hash.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <map>
#include <ostream>
#include <queue>
#include <stack>
#include <vector>

bool ompl::control::ProductGraph::State::operator==(const State& s) const
{
    return decompRegion==s.decompRegion
        && cosafeState==s.cosafeState
        && safeState==s.safeState;
}

bool ompl::control::ProductGraph::State::isValid(void) const
{
    return cosafeState != -1 && safeState != -1;
}

namespace ompl
{
    namespace control
    {
        std::size_t hash_value(const ProductGraph::State& s)
        {
            std::size_t hash = 0;
            boost::hash_combine(hash, s.decompRegion);
            boost::hash_combine(hash, s.cosafeState);
            boost::hash_combine(hash, s.safeState);
            return hash;
        }

        std::ostream& operator<<(std::ostream& out, const ProductGraph::State& s)
        {
            out << "(" << s.decompRegion << "," << s.cosafeState << ",";
            out << s.safeState << ")";
            return out;
        }
    }
}

int ompl::control::ProductGraph::State::getDecompRegion(void) const
{
    return decompRegion;
}

int ompl::control::ProductGraph::State::getCosafeState(void) const
{
    return cosafeState;
}

int ompl::control::ProductGraph::State::getSafeState(void) const
{
    return safeState;
}

ompl::control::ProductGraph::ProductGraph(const PropositionalDecompositionPtr& decomp,
    const AutomatonPtr& cosafetyAut, const AutomatonPtr& safetyAut) :
    decomp_(decomp),
    cosafety_(cosafetyAut),
    safety_(safetyAut)
{
}

ompl::control::ProductGraph::ProductGraph(const PropositionalDecompositionPtr& decomp,
    const AutomatonPtr& cosafetyAut) :
    decomp_(decomp),
    cosafety_(cosafetyAut),
    safety_(Automaton::AcceptingAutomaton(decomp->getNumProps()))
{
}

ompl::control::ProductGraph::~ProductGraph()
{
    clear();
}

const ompl::control::PropositionalDecompositionPtr& ompl::control::ProductGraph::getDecomp() const
{
    return decomp_;
}

const ompl::control::AutomatonPtr& ompl::control::ProductGraph::getCosafetyAutom() const
{
    return cosafety_;
}

const ompl::control::AutomatonPtr& ompl::control::ProductGraph::getSafetyAutom() const
{
    return safety_;
}

std::vector<ompl::control::ProductGraph::State*>
ompl::control::ProductGraph::computeLead(
    ProductGraph::State* start,
    const boost::function<double(ProductGraph::State*, ProductGraph::State*)>& edgeWeight)
{
	std::vector<GraphType::vertex_descriptor> parents(boost::num_vertices(graph_));
	std::vector<double> distances(boost::num_vertices(graph_));
    EdgeIter ei, eend;
    //first build up the edge weights
    for (boost::tie(ei,eend) = boost::edges(graph_); ei != eend; ++ei)
    {
        GraphType::vertex_descriptor src = boost::source(*ei, graph_);
        GraphType::vertex_descriptor target = boost::target(*ei, graph_);
        graph_[*ei].cost = edgeWeight(graph_[src], graph_[target]);
    }
    int startIndex = stateToIndex_[start];
	boost::dijkstra_shortest_paths(graph_, boost::vertex(startIndex,graph_),
		boost::weight_map(get(&Edge::cost, graph_)).distance_map(
			boost::make_iterator_property_map(distances.begin(), get(boost::vertex_index, graph_)
		)).predecessor_map(
			boost::make_iterator_property_map(parents.begin(), get(boost::vertex_index, graph_))
		)
	);
	//pick state from solutionStates_ such that distance[state] is minimized
	State* bestSoln = *solutionStates_.begin();
	double cost = distances[boost::vertex(stateToIndex_[bestSoln], graph_)];
	for (std::vector<State*>::const_iterator s = solutionStates_.begin()+1; s != solutionStates_.end(); ++s)
	{
		if (distances[boost::vertex(stateToIndex_[*s], graph_)] < cost)
		{
			cost = distances[boost::vertex(stateToIndex_[*s], graph_)];
			bestSoln = *s;
		}
	}
	//build lead from bestSoln parents
	std::stack<State*> leadStack;
	while (!(bestSoln == start))
	{
		leadStack.push(bestSoln);
		bestSoln = graph_[parents[boost::vertex(stateToIndex_[bestSoln], graph_)]];
	}
	leadStack.push(bestSoln);

	std::vector<State*> lead;
	while (!leadStack.empty())
	{
		lead.push_back(leadStack.top());
		leadStack.pop();
        // Truncate the lead as early when it hits the desired automaton states
        // TODO: more elegant way to do this?
        if (lead.back()->cosafeState == solutionStates_.front()->cosafeState
            && lead.back()->safeState == solutionStates_.front()->safeState)
            break;
	}
	return lead;
}

void ompl::control::ProductGraph::clear()
{
    solutionStates_.clear();
    stateToIndex_.clear();
    startState_ = NULL;
    graph_.clear();
    boost::unordered_map<State,State*>::iterator i;
    for (i = stateToPtr_.begin(); i != stateToPtr_.end(); ++i)
        delete i->second;
    stateToPtr_.clear();
}

void ompl::control::ProductGraph::buildGraph(State* start, const boost::function<void(State*)>& initialize)
{
    graph_.clear();
    solutionStates_.clear();
    std::queue<State*> q;
    boost::unordered_set<State*> processed;
    std::vector<int> regNeighbors;
    VertexIndexMap index = get(boost::vertex_index, graph_);

    GraphType::vertex_descriptor next = boost::add_vertex(graph_);
    startState_ = start;
    graph_[boost::vertex(next,graph_)] = startState_;
    stateToIndex_[startState_] = index[next];
    q.push(startState_);
    processed.insert(startState_);

    OMPL_INFORM("Building graph from start state (%u,%u,%u) with index %d",
		startState_->decompRegion, startState_->cosafeState,
		startState_->safeState, stateToIndex_[startState_]);

    while (!q.empty())
    {
        State* current = q.front();
        //Initialize each state using the supplied state initializer function
        initialize(current);
        q.pop();

        if (safety_->isAccepting(current->safeState) && cosafety_->isAccepting(current->cosafeState))
        {
            solutionStates_.push_back(current);
        }

        GraphType::vertex_descriptor v = boost::vertex(stateToIndex_[current], graph_);

        //enqueue each neighbor of current
        decomp_->getNeighbors(current->decompRegion, regNeighbors);
        for (std::vector<int>::const_iterator r = regNeighbors.begin(); r != regNeighbors.end(); ++r)
        {
            State* nextState = getState(current, *r);
            if (!nextState->isValid())
                continue;
			//if this state is newly discovered,
			//then we can dynamically allocate a copy of it
            //and add the new pointer to the graph.
            //either way, we need the pointer
			if (processed.find(nextState) == processed.end())
			{
				const GraphType::vertex_descriptor next = boost::add_vertex(graph_);
                stateToIndex_[nextState] = index[next];
				graph_[boost::vertex(next,graph_)] = nextState;
				q.push(nextState);
                processed.insert(nextState);
			}

            //whether or not the neighbor is newly discovered,
            //we still need to add the edge to the graph
            GraphType::edge_descriptor edge;
            bool ignore;
            boost::tie(edge,ignore) = boost::add_edge(v, boost::vertex(stateToIndex_[nextState],graph_), graph_);
            //graph_[edge].src = index[v];
            //graph_[edge].dest = stateToIndex_[nextState];
        }
		regNeighbors.clear();
    }
    if (solutionStates_.empty())
    {
        OMPL_ERROR("No solution path found in product graph.");
    }

    OMPL_INFORM("Number of decomposition regions: %u", decomp_->getNumRegions());
    OMPL_INFORM("Number of cosafety automaton states: %u", cosafety_->numStates());
    OMPL_INFORM("Number of safety automaton states: %u", safety_->numStates());
    OMPL_INFORM("Number of high-level states in abstraction graph: %u", boost::num_vertices(graph_));
}

bool ompl::control::ProductGraph::isSolution(const State* s) const
{
    return std::find(solutionStates_.begin(), solutionStates_.end(), s)
        != solutionStates_.end();
}

ompl::control::ProductGraph::State* ompl::control::ProductGraph::getStartState(void) const
{
    return startState_;
}

double ompl::control::ProductGraph::getRegionVolume(const State* s)
{
    return decomp_->getRegionVolume(s->decompRegion);
}

int ompl::control::ProductGraph::getCosafeAutDistance(const State* s) const
{
    return cosafety_->distFromAccepting(s->cosafeState);
}

int ompl::control::ProductGraph::getSafeAutDistance(const State* s) const
{
    return safety_->distFromAccepting(s->safeState);
}

ompl::control::ProductGraph::State* ompl::control::ProductGraph::getState(const base::State* cs) const
{
    return getState(cs, cosafety_->getStartState(), safety_->getStartState());
}

ompl::control::ProductGraph::State* ompl::control::ProductGraph::getState(const base::State* cs, int cosafe, int safe) const
{
    State s;
    s.decompRegion = decomp_->locateRegion(cs);
    s.cosafeState = cosafe;
    s.safeState = safe;
	State*& ret = stateToPtr_[s];
	if (ret == NULL)
		ret = new State(s);
    return ret;
}

ompl::control::ProductGraph::State* ompl::control::ProductGraph::getState(const State* parent, int nextRegion) const
{
    State s;
    s.decompRegion = nextRegion;
    const World nextWorld = decomp_->worldAtRegion(nextRegion);
    s.cosafeState = cosafety_->step(parent->cosafeState, nextWorld);
    s.safeState = safety_->step(parent->safeState, nextWorld);
	State*& ret = stateToPtr_[s];
	if (ret == NULL)
		ret = new State(s);
    return ret;
}

ompl::control::ProductGraph::State* ompl::control::ProductGraph::getState(const State* parent, const base::State* cs) const
{
    return getState(parent, decomp_->locateRegion(cs));
}

max_stars_repo_name: jmainpri/ompl

max_issues_repo_name: jmainpri/ompl

max_forks_repo_name: jmainpri/ompl


text:
//==================================================================================================
/*
  Copyright 2017 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy_n at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#include <boost/simd/algorithm/copy_n.hpp>
#include <numeric>
#include <vector>
#include <simd_test.hpp>

using namespace boost::simd;
using namespace boost::alignment;

STF_CASE_TPL( "Check unary simd::copy_n", STF_NUMERIC_TYPES )
{
  static const int N = pack<T>::static_size;

  std::vector<T> values(2*N+1), ref(2*N+3), out(2*N+3);
  std::iota(values.begin(), values.end(),T(1));

  std::copy(values.begin(), values.begin()+N, ref.begin());

  // verify we stopped where we should
  STF_EQUAL ( (boost::simd::copy_n(values.data(), N, out.data()))
            , out.data()+N
            );

  // verify values
  STF_EQUAL( out, ref );
}


text:
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using namespace boost::multiprecision;
int main() {
    int n; cin >> n;
    cpp_int tmp; cin >> tmp;
    for (int i = 1; i < n; i++) {
        cpp_int next; cin >> next;
        if (next == tmp) cout << "stay" << endl;
        else if (next > tmp) cout << "up " << next - tmp << endl;
        else cout << "down " << tmp - next << endl;
        tmp = next;
    }
}


text:
//=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// This file is part of the Boost Graph Library
//
// You should have received a copy of the License Agreement for the
// Boost Graph Library along with the software; see the file LICENSE.
// If not, contact Office of Research, Indiana University,
// Bloomington, IN 47405.
//
// Permission to modify the code and to distribute the code is
// granted, provided the text of this NOTICE is retained, a notice if
// the code was modified is included with the above COPYRIGHT NOTICE
// and with the COPYRIGHT NOTICE in the LICENSE file, and that the
// LICENSE file is distributed with the modified code.
//
// LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.
// By way of example, but not limitation, Licensor MAKES NO
// REPRESENTATIONS OR WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY
// PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE COMPONENTS
// OR DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS, TRADEMARKS
// OR OTHER RIGHTS.
//=======================================================================
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/pending/integer_range.hpp>
#include <boost/pending/indirect_cmp.hpp>
#include <boost/graph/graphviz.hpp>

#include <iostream>
using namespace boost;
template < typename TimeMap > class dfs_time_visitor:public default_dfs_visitor {
  typedef typename property_traits < TimeMap >::value_type T;
public:
  dfs_time_visitor(TimeMap dmap, TimeMap fmap, T & t)
:  m_dtimemap(dmap), m_ftimemap(fmap), m_time(t) {
  }
  template < typename Vertex, typename Graph >
    void discover_vertex(Vertex u, const Graph & g) const
  {
    put(m_dtimemap, u, m_time++);
  }
  template < typename Vertex, typename Graph >
    void finish_vertex(Vertex u, const Graph & g) const
  {
    put(m_ftimemap, u, m_time++);
  }
  TimeMap m_dtimemap;
  TimeMap m_ftimemap;
  T & m_time;
};

int
main()
{
  // Select the graph type we wish to use
  typedef adjacency_list < vecS, vecS, directedS > graph_t;
  typedef graph_traits < graph_t >::vertices_size_type size_type;
  // Set up the vertex names
  enum
  { u, v, w, x, y, z, N };
  char name[] = { 'u', 'v', 'w', 'x', 'y', 'z' };
  // Specify the edges in the graph
  typedef std::pair < int, int >E;
  E edge_array[] = { E(u, v), E(u, x), E(x, v), E(y, x),
    E(v, y), E(w, y), E(w, z), E(z, z)
  };
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
  graph_t g(N);
  for (std::size_t j = 0; j < sizeof(edge_array) / sizeof(E); ++j)
    add_edge(edge_array[j].first, edge_array[j].second, g);
#else
  graph_t g(edge_array, edge_array + sizeof(edge_array) / sizeof(E), N);
#endif

  // Typedefs
  typedef boost::graph_traits < graph_t >::vertex_descriptor Vertex;
  typedef size_type* Iiter;

write_graphviz(std::cout, g);

  // discover time and finish time properties
  std::vector < size_type > dtime(num_vertices(g));
  std::vector < size_type > ftime(num_vertices(g));
  size_type t = 0;
  dfs_time_visitor < size_type * >vis(&dtime[0], &ftime[0], t);

  depth_first_search(g, visitor(vis));

  // use std::sort to order the vertices by their discover time
  std::vector < size_type > discover_order(N);
  integer_range < size_type > r(0, N);
  std::copy(r.begin(), r.end(), discover_order.begin());
  std::sort(discover_order.begin(), discover_order.end(),
            indirect_cmp < Iiter, std::less < size_type > >(&dtime[0]));
  std::cout << "order of discovery: ";
  int i;
  for (i = 0; i < N; ++i)
    std::cout << name[discover_order[i]] << " ";

  std::vector < size_type > finish_order(N);
  std::copy(r.begin(), r.end(), finish_order.begin());
  std::sort(finish_order.begin(), finish_order.end(),
            indirect_cmp < Iiter, std::less < size_type > >(&ftime[0]));
  std::cout << std::endl << "order of finish: ";
  for (i = 0; i < N; ++i)
    std::cout << name[finish_order[i]] << " ";
  std::cout << std::endl;

  return EXIT_SUCCESS;
}

max_stars_repo_name: HenrikBengtsson/RBGL

max_issues_repo_name: HenrikBengtsson/RBGL

max_forks_repo_name: HenrikBengtsson/RBGL