text:
#ifndef MUSYCL_MIDI_IN_HPP
#define MUSYCL_MIDI_IN_HPP

/** \file SYCL abstraction for a MIDI input pipe

    Based on RtMidi library.
*/

#include <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <thread>
#include <tuple>
#include <type_traits>
#include <variant>
#include <vector>

#include <boost/callable_traits/args.hpp>
#include <boost/fiber/buffered_channel.hpp>

#include "rtmidi/RtMidi.h"

#include <triSYCL/detail/overloaded.hpp>

#include "musycl/midi.hpp"

namespace musycl {

// To use time unit literals directly
using namespace std::chrono_literals;

/** A MIDI input interface exposed as a SYCL pipe.

    In SYCL the type is used to synthesize the connection between
    kernels, so there can be only 1 instance of a MIDI input
    interface. */
class midi_in {
  /// Capacity of the MIDI message pipe
  static auto constexpr pipe_min_capacity = 64;

  /// The buffered channel used on MIDI input with the right size by default
  struct pipe_channel : boost::fibers::buffered_channel<midi::msg> {
    pipe_channel()
        : boost::fibers::buffered_channel<midi::msg> { pipe_min_capacity } {}
  };

  /** The handlers to control the MIDI input interfaces

      Use a pointer because RtMidiIn is a broken type and is neither
      copyable nor movable */
  static inline std::vector<std::unique_ptr<RtMidiIn>> interfaces;

  /// FIFO used to implement the pipe of MIDI messages on each port
  static inline std::map<std::int8_t, pipe_channel> channels;

  /* FIFO used to postpone event dispatch at a time picked by the user
     to avoid race condition */
  static inline std::map<std::int8_t, pipe_channel> dispatch_channels;

  /// A key to dispatch MIDI messages from this index
  struct port_msg_header {
    std::int8_t port;
    midi::msg_header header;
    // Just use some lexicographic comparison by default
    auto operator<=>(const port_msg_header&) const = default;
  };

  /// Actions to run for each received CC message from each MIDI port
  static inline std::multimap<port_msg_header,
                              std::function<void(const midi::msg&)>>
      midi_actions;

  /// Check for RtMidi errors
  static auto constexpr check_error = [](auto&& function) {
    try {
      return function();
    } catch (const RtMidiError& error) {
      error.printMessage();
      std::exit(EXIT_FAILURE);
    }
  };

  /// Process the incomming MIDI messages
  static inline void process_midi_in(double time_stamp,
                                     std::vector<std::uint8_t>* p_midi_message,
                                     void* port) {
    auto& midi_message = *p_midi_message;
    auto n_bytes = midi_message.size();
    auto p = reinterpret_cast<std::intptr_t>(port);
    std::cout << "Received from port " << p << " at time stamp = " << time_stamp
              << std::endl
              << '\t';
    for (int i = 0; i < n_bytes; ++i)
      std::cout << "Byte " << i << " = 0x" << std::hex << std::setw(2)
                << std::setfill('0') << static_cast<int>(midi_message[i])
                << ", " << std::resetiosflags(std::cout.flags());
    std::cout << std::endl;

    auto m = musycl::midi::parse(midi_message);
    /* Enqueue the midi message for future event dispatch by
       dispatch_registered_actions(). If it is full, just drop the
       message */
    dispatch_channels[p].try_push(m);
    /* Also enqueue the midi event for explicit consumption. If it is
       full, just drop the message */
    channels[p].try_push(m);
  }

 public:
  void open(const std::string& application_name, const std::string& port_name,
            RtMidi::Api backend) {
    std::cout << "RtMidi version " << RtMidi::getVersion() << std::endl;
    // Create a throwable MIDI input just to get later the number of port
    auto midi_in = check_error([&] {
      return RtMidiIn { backend, "muSYCLtest" };
    });
    auto n_in_ports = midi_in.getPortCount();
    std::cout << "\nThere are " << n_in_ports
              << " MIDI input sources available.\n";

    for (auto i = 0; i < n_in_ports; ++i) {
      interfaces.push_back(check_error([&] {
        return std::make_unique<RtMidiIn>(backend, application_name);
      }));

      auto port_name = check_error([&] { return midi_in.getPortName(i); });
      std::cout << "  Input Port #" << i << ": " << port_name << std::endl;

      // Open the port and give it a fancy name
      check_error([&] { interfaces[i]->openPort(i, port_name); });

      // Don't ignore sysex, timing, or active sensing messages
      check_error([&] { interfaces[i]->ignoreTypes(false, false, false); });

      // Drain the message queue to avoid leftover MIDI messages
      std::vector<std::uint8_t> message;
      do {
        // There is a race condition in RtMidi where the messages are
        // not seen if these is not some sleep here
        std::this_thread::sleep_for(1ms);
        check_error([&] { interfaces[i]->getMessage(&message); });
      } while (!message.empty());

      // Handle MIDI messages with this callback function
      check_error([&] {
        interfaces[i]->setCallback(process_midi_in, reinterpret_cast<void*>(i));
      });
    }
  }

  /// The sycl::pipe::read-like interface to read a MIDI message
  static midi::msg read(std::int8_t port) { return channels[port].value_pop(); }

  /// The non-blocking sycl::pipe::read-like interface to read a MIDI message
  static bool try_read(std::int8_t port, midi::msg& m) {
    return channels[port].try_pop(m) ==
           boost::fibers::channel_op_status::success;
  }

  /// Insert a new MIDI message in the input flow
  static void insert(std::int8_t port, const midi::msg& m) {
    channels[port].push(m);
  }

  /** Dispatch the registered actions for a MIDI input event

      This is decoupled from the MIDI system call-back function to be
      called by the user at the right time, typically when this will
      not cause race condition, compared to asynchronous call back
      happening in a background thread.
   */
  static void dispatch_registered_actions() {
    for (auto&& [port, channel] : dispatch_channels) {
      midi::msg m;
      while (channel.try_pop(m) == boost::fibers::channel_op_status::success) {
        std::cout << m << std::endl;
        auto [first, last] = midi_actions.equal_range({ port, m });
        std::for_each(first, last, [&](auto&& action) { action.second(m); });
      }
    }
  }

  /** Associate an action to a MIDI message

      \param[in] port is the input MIDI port

      \param[in] header is the MIDI message header to dispatch

      \param[in] action is the action to call with the matching MIDI
      message
  */
  template <typename Callable>
  static void add_action(std::int8_t port, const midi::msg_header& header,
                         Callable&& action) {
    std::cout << "add_action on port " << int { port } << " for" << header
              << std::endl;
    midi_actions.emplace(port_msg_header { port, header }, action);
  }

  /** Associate an action to a channel controller (CC)

      \param[in] port is the input MIDI port

      \param[in] number is the CC number

      \param[in] action is the action to call with the value
      returned by the CC as a parameter.

      If the action parameter has a floating point type, the value is
      scaled to [0, 1] first.
  */
  template <typename Callable>
  static void cc_action(std::int8_t port, std::int8_t channel, std::int8_t number,
                        Callable&& action) {
    using arg0_t =
        std::tuple_element_t<0, boost::callable_traits::args_t<Callable>>;
    // Register an action producing the right value for the action
    if constexpr (std::is_floating_point_v<arg0_t>)
      // If we have a floating point type, scale the value in [0, 1]
      midi_actions.emplace(
          port_msg_header { port, midi::control_change_header { channel, number } },
          [action = std::forward<Callable>(action)](const midi::msg& m) {
            action(midi::control_change::get_value_as<arg0_t>(
                std::get<midi::control_change>(m).value));
          });
    else
      // Just provides the CC value directly to the action
      midi_actions.emplace(
          port_msg_header { port, midi::control_change_header { channel, number } },
          [action = std::forward<Callable>(action)](const midi::msg& m) {
            action(std::get<midi::control_change>(m).value);
          });
  }

  /** Associate an action to a channel controller (CC) on the first
      MIDI input port

      \param[in] number is the CC number

      \param[in] action is the action to call with the value
      returned by the CC as a parameter.

      If the action parameter has a floating point type, the value is
      scaled to [0, 1] first.
  */
  template <typename Callable>
  static void cc_action(std::int8_t number, Callable&& action) {
    cc_action(0, 0, number, std::forward<Callable>(action));
  }

  /** Associate an action to a channel controller (CC)

      \param[in] number is the CC number

      \param[in] action is the action to call with the value
      returned by the CC as a parameter.

      If the action parameter has a floating point type, the value is
      scaled to [0, 1] first.

      \todo Remove this templated API
  */
  template <std::int8_t number, typename Callable>
  static void cc_action(Callable&& action) {
    cc_action(number, std::forward<Callable>(action));
  }

  /** Associate a variable to a channel controller (CC)

      \param[in] number is the CC number

      \param[out] variable is the variable to set to the value
      returned by the CC. If the variable has a floating point type,
      the value is scaled to [0, 1] first.

      \todo Remove this templated API
  */
  template <std::int8_t number, typename T>
  static void cc_variable(T& variable) {
    cc_action<number>([&](T v) { variable = v; });
  }
};

} // namespace musycl

#endif // MUSYCL_MIDI_IN_HPP

max_stars_repo_name: keryell/muSYCL

max_issues_repo_name: keryell/muSYCL

max_forks_repo_name: keryell/muSYCL


text:
//  (C) Copyright Raffi Enficiaud 2018.
//  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)

//  See http://www.boost.org/libs/test for the library home page.
//
/// @file
/// Defines a lazy/delayed dataset store
// ***************************************************************************

#ifndef BOOST_TEST_DATA_MONOMORPHIC_DELAYED_HPP_062018GER
#define BOOST_TEST_DATA_MONOMORPHIC_DELAYED_HPP_062018GER

// Boost.Test
#include <boost/test/data/config.hpp>
#include <boost/test/data/monomorphic/fwd.hpp>
#include <boost/test/data/index_sequence.hpp>

#include <boost/core/ref.hpp>

#include <algorithm>
#include <memory>

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) && \
    !defined(BOOST_NO_CXX11_HDR_TUPLE)

namespace boost {
namespace unit_test {
namespace data {
namespace monomorphic {

// ************************************************************************** //
// **************               delayed_dataset                ************** //
// ************************************************************************** //

/// Delayed dataset
///
/// This dataset holds another dataset that is instanciated on demand. It is
/// constructed with the @c data::make_delayed<dataset_t>(arg1,....) instead of the
/// @c data::make.
template <class dataset_t, class ...Args>
class delayed_dataset
{
public:
    enum { arity = dataset_t::arity };
    using iterator = decltype(std::declval<dataset_t>().begin());

    delayed_dataset(Args... args)
    : m_args(std::make_tuple(std::forward<Args>(args)...))
    {}

    // Mostly for VS2013
    delayed_dataset(delayed_dataset&& b)
    : m_args(std::move(b.m_args))
    , m_dataset(std::move(b.m_dataset))
    {}

    boost::unit_test::data::size_t size() const {
        return this->get().size();
    }

    // iterator
    iterator begin() const {
        return this->get().begin();
    }

private:

  dataset_t& get() const {
      if(!m_dataset) {
          m_dataset = create(boost::unit_test::data::index_sequence_for<Args...>());
      }
      return *m_dataset;
  }

  template<std::size_t... I>
  std::unique_ptr<dataset_t>
  create(boost::unit_test::data::index_sequence<I...>) const
  {
      return std::unique_ptr<dataset_t>{new dataset_t(std::get<I>(m_args)...)};
  }

  std::tuple<typename std::decay<Args>::type...> m_args;
  mutable std::unique_ptr<dataset_t> m_dataset;
};

//____________________________________________________________________________//

//! A lazy/delayed dataset is a dataset.
template <class dataset_t, class ...Args>
struct is_dataset< delayed_dataset<dataset_t, Args...> > : boost::mpl::true_ {};

//____________________________________________________________________________//

} // namespace monomorphic

//! Delayed dataset instanciation
template<class dataset_t, class ...Args>
inline typename std::enable_if<
  monomorphic::is_dataset< dataset_t >::value,
  monomorphic::delayed_dataset<dataset_t, Args...>
>::type
make_delayed(Args... args)
{
    return monomorphic::delayed_dataset<dataset_t, Args...>( std::forward<Args>(args)... );
}

} // namespace data
} // namespace unit_test
} // namespace boost

#endif

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_DATA_MONOMORPHIC_DELAYED_HPP_062018GER

ext: hpp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 *  @file DiscreteFactorGraph.cpp
 *  @date Feb 14, 2011
 *  @author Duy-Nguyen Ta
 *  @author Frank Dellaert
 */

//#define ENABLE_TIMING
#include <gtsam/discrete/DiscreteFactorGraph.h>
#include <gtsam/discrete/DiscreteConditional.h>
#include <gtsam/inference/EliminationTree-inl.h>
#include <boost/make_shared.hpp>

namespace gtsam {

	// Explicitly instantiate so we don't have to include everywhere
	template class FactorGraph<DiscreteFactor> ;
	template class EliminationTree<DiscreteFactor> ;

	/* ************************************************************************* */
	DiscreteFactorGraph::DiscreteFactorGraph() {
	}

	/* ************************************************************************* */
	DiscreteFactorGraph::DiscreteFactorGraph(
			const BayesNet<DiscreteConditional>& bayesNet) :
			FactorGraph<DiscreteFactor>(bayesNet) {
	}

	/* ************************************************************************* */
	FastSet<Index> DiscreteFactorGraph::keys() const {
		FastSet<Index> keys;
		BOOST_FOREACH(const sharedFactor& factor, *this)
		if (factor) keys.insert(factor->begin(), factor->end());
		return keys;
	}

	/* ************************************************************************* */
	DecisionTreeFactor DiscreteFactorGraph::product() const {
		DecisionTreeFactor result;
		BOOST_FOREACH(const sharedFactor& factor, *this)
			if (factor) result = (*factor) * result;
		return result;
	}

	/* ************************************************************************* */
	double DiscreteFactorGraph::operator()(
			const DiscreteFactor::Values &values) const {
		double product = 1.0;
		BOOST_FOREACH( const sharedFactor& factor, factors_ )
			product *= (*factor)(values);
		return product;
	}

	/* ************************************************************************* */
	void DiscreteFactorGraph::print(const std::string& s,
			const IndexFormatter& formatter) const {
		std::cout << s << std::endl;
		std::cout << "size: " << size() << std::endl;
		for (size_t i = 0; i < factors_.size(); i++) {
			std::stringstream ss;
			ss << "factor " << i << ": ";
			if (factors_[i] != NULL) factors_[i]->print(ss.str(), formatter);
		}
	}

	/* ************************************************************************* */
	std::pair<DiscreteConditional::shared_ptr, DecisionTreeFactor::shared_ptr>  //
	EliminateDiscrete(const FactorGraph<DiscreteFactor>& factors, size_t num) {

		// PRODUCT: multiply all factors
		tic(1, "product");
		DecisionTreeFactor product;
		BOOST_FOREACH(const DiscreteFactor::shared_ptr& factor, factors){
			product = (*factor) * product;
		}

		toc(1, "product");

		// sum out frontals, this is the factor on the separator
		tic(2, "sum");
		DecisionTreeFactor::shared_ptr sum = product.sum(num);
		toc(2, "sum");

		// now divide product/sum to get conditional
		tic(3, "divide");
		DiscreteConditional::shared_ptr cond(new DiscreteConditional(product, *sum));
		toc(3, "divide");
		tictoc_finishedIteration();

		return std::make_pair(cond, sum);
	}

/* ************************************************************************* */
} // namespace

ext: cpp


text:
// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "master/gc_strategy.h"

#include <gflags/gflags.h>
#include <boost/lexical_cast.hpp>

#include "db/filename.h"
#include "io/utils_leveldb.h"

DECLARE_string(tera_tabletnode_path_prefix);
DECLARE_string(tera_master_meta_table_name);
DECLARE_int32(tera_garbage_collect_debug_log);

namespace tera {
namespace master {

BatchGcStrategy::BatchGcStrategy (boost::shared_ptr<TabletManager> tablet_manager)
    : tablet_manager_(tablet_manager),
      file_total_num_(0),
      file_delete_num_(0) {}

bool BatchGcStrategy::PreQuery () {
    int64_t start_ts = get_micros();
    gc_live_files_.clear();
    gc_tablets_.clear();

    std::vector<TablePtr> tables;

    tablet_manager_->ShowTable(&tables, NULL);
    for (size_t i = 0; i < tables.size(); ++i) {
        if (tables[i]->GetStatus() != kTableEnable ||
            tables[i]->GetTableName() == FLAGS_tera_master_meta_table_name) {
            // table not ready and skip metatable
            continue;
        }
        GcTabletSet& tablet_set = gc_tablets_[tables[i]->GetTableName()];
        if (!tables[i]->GetTabletsForGc(&tablet_set.first, &tablet_set.second)) {
            // tablet not ready or there is none dead tablets
            gc_tablets_.erase(tables[i]->GetTableName());
            continue;
        }
    }

    file_total_num_ = 0;
    CollectDeadTabletsFiles();

    LOG(INFO) << "[gc] DoTabletNodeGc: collect all files, total:" << file_total_num_
        << ", cost: " << (get_micros() - start_ts) / 1000 << "ms.";

    if (gc_tablets_.size() == 0) {
        LOG(INFO) << "[gc] do not need gc this time.";
        return false;
    }
    return true;
}

void BatchGcStrategy::PostQuery () {
    bool is_success = true;
    std::map<std::string, GcTabletSet>::iterator it = gc_tablets_.begin();
    for (; it != gc_tablets_.end(); ++it) {
        if (it->second.first.size() != 0) {
            VLOG(10) << "[gc] there are tablet not ready: " << it->first;
            is_success = false;
            break;
        }
    }
    if (!is_success) {
        LOG(INFO) << "[gc] gc not success, try next time.";
        return;
    }

    file_delete_num_ = 0;
    int64_t start_ts = get_micros();
    DeleteObsoleteFiles();
    LOG(INFO) << "[gc] DoTabletNodeGcPhase2 finished, total:" << file_delete_num_
        << ", cost:" << (get_micros() - start_ts) / 1000 << "ms. list_times " << list_count_.Get();
    list_count_.Clear();
}

void BatchGcStrategy::Clear(std::string tablename) {
    LOG(INFO) << "[gc] Clear do nothing (BatchGcStrategy) " << tablename;
}

void BatchGcStrategy::ProcessQueryCallbackForGc(QueryResponse* response) {
    MutexLock lock(&gc_mutex_);
    std::set<std::string> gc_table_set;
    for (int i = 0; i < response->inh_live_files_size(); ++i) {
        const InheritedLiveFiles& live = response->inh_live_files(i);
        gc_table_set.insert(live.table_name());
    }

    for (int i = 0; i < response->tabletmeta_list().meta_size(); ++i) {
        const TabletMeta& meta = response->tabletmeta_list().meta(i);
        VLOG(10) << "[gc] try erase live tablet: " << meta.path()
            << ", tablename: " << meta.table_name();
        if (gc_tablets_.find(meta.table_name()) != gc_tablets_.end() &&
            gc_table_set.find(meta.table_name()) != gc_table_set.end()) {
            // erase live tablet
            VLOG(10) << "[gc] erase live tablet: " << meta.path();
            uint64_t tabletnum = leveldb::GetTabletNumFromPath(meta.path());
            gc_tablets_[meta.table_name()].first.erase(tabletnum);
        }
    }

    // erase inherited live files
    for (int i = 0; i < response->inh_live_files_size(); ++i) {
        const InheritedLiveFiles& live = response->inh_live_files(i);
        if (gc_live_files_.find(live.table_name()) == gc_live_files_.end()) {
            VLOG(10) << "[gc] table: " << live.table_name() << " skip gc.";
            continue;
        }
        GcFileSet& file_set = gc_live_files_[live.table_name()];
        int lg_num = live.lg_live_files_size();
        CHECK(static_cast<size_t>(lg_num) == file_set.size())
            << "lg_num should eq " << file_set.size();
        for (int lg = 0; lg < lg_num; ++lg) {
            const LgInheritedLiveFiles& lg_live_files = live.lg_live_files(lg);
            for (int f = 0; f < lg_live_files.file_number_size(); ++f) {
                std::string file_path = leveldb::BuildTableFilePath(
                    live.table_name(), lg, lg_live_files.file_number(f));
                VLOG(10) << "[gc] " << " erase live file: " << file_path;
                file_set[lg].erase(lg_live_files.file_number(f));
            }
        }
    }
}

void BatchGcStrategy::CollectDeadTabletsFiles() {
    std::map<std::string, GcTabletSet>::iterator table_it = gc_tablets_.begin();
    for (; table_it != gc_tablets_.end(); ++table_it) {
        std::set<uint64_t>& dead_tablets = table_it->second.second;
        std::set<uint64_t>::iterator tablet_it = dead_tablets.begin();
        for (; tablet_it != dead_tablets.end(); ++tablet_it) {
            CollectSingleDeadTablet(table_it->first, *tablet_it);
        }
    }
}

void BatchGcStrategy::CollectSingleDeadTablet(const std::string& tablename, uint64_t tabletnum) {
    std::string tablepath = FLAGS_tera_tabletnode_path_prefix + tablename;
    std::string tablet_path = leveldb::GetTabletPathFromNum(tablepath, tabletnum);
    leveldb::Env* env = io::LeveldbBaseEnv();
    std::vector<std::string> children;
    env->GetChildren(tablet_path, &children);
    list_count_.Inc();
    if (children.size() == 0) {
        LOG(INFO) << "[gc] delete empty tablet dir: " << tablet_path;
        env->DeleteDir(tablet_path);
        return;
    }
    for (size_t lg = 0; lg < children.size(); ++lg) {
        std::string lg_path = tablet_path + "/" + children[lg];
        leveldb::FileType type = leveldb::kUnknown;
        uint64_t number = 0;
        if (ParseFileName(children[lg], &number, &type)) {
            LOG(INFO) << "[gc] delete: " << lg_path;
            env->DeleteFile(lg_path);
            continue;
        }

        leveldb::Slice rest(children[lg]);
        uint64_t lg_num = 0;
        if (!leveldb::ConsumeDecimalNumber(&rest, &lg_num)) {
            LOG(ERROR) << "[gc] skip unknown dir: " << lg_path;
            continue;
        }

        std::vector<std::string> files;
        env->GetChildren(lg_path, &files);
        list_count_.Inc();
        if (files.size() == 0) {
            LOG(INFO) << "[gc] delete empty lg dir: " << lg_path;
            env->DeleteDir(lg_path);
            continue;
        }
        file_total_num_ += files.size();
        for (size_t f = 0; f < files.size(); ++f) {
            std::string file_path = lg_path + "/" + files[f];
            type = leveldb::kUnknown;
            number = 0;
            if (!ParseFileName(files[f], &number, &type) ||
                type != leveldb::kTableFile) {
                // only keep sst, delete rest files
                io::DeleteEnvDir(file_path);
                continue;
            }

            uint64_t full_number = leveldb::BuildFullFileNumber(lg_path, number);
            GcFileSet& file_set = gc_live_files_[tablename];
            if (file_set.size() == 0) {
                TablePtr table;
                tablet_manager_->FindTable(tablename, &table);
                file_set.resize(table->GetSchema().locality_groups_size());
                VLOG(10) << "[gc] resize : " << tablename
                    << " fileset lg size: " << file_set.size();
            }
            VLOG(10) << "[gc] " << tablename << " insert live file: " << file_path;
            CHECK(lg_num < file_set.size());
            file_set[lg_num].insert(full_number);
        }
    }
}

void BatchGcStrategy::DeleteObsoleteFiles() {
    leveldb::Env* env = io::LeveldbBaseEnv();
    std::map<std::string, GcFileSet>::iterator table_it = gc_live_files_.begin();
    for (; table_it != gc_live_files_.end(); ++table_it) {
        std::string tablepath = FLAGS_tera_tabletnode_path_prefix + table_it->first;
        GcFileSet& file_set = table_it->second;
        for (size_t lg = 0; lg < file_set.size(); ++lg) {
            std::set<uint64_t>::iterator it = file_set[lg].begin();
            for (; it != file_set[lg].end(); ++it) {
                std::string file_path = leveldb::BuildTableFilePath(tablepath, lg, *it);
                LOG(INFO) << "[gc] delete: " << file_path;
                env->DeleteFile(file_path);
                file_delete_num_++;
            }
        }
    }
}

IncrementalGcStrategy::IncrementalGcStrategy(boost::shared_ptr<TabletManager> tablet_manager)
    :   tablet_manager_(tablet_manager),
        last_gc_time_(std::numeric_limits<int64_t>::max()),
        max_ts_(std::numeric_limits<int64_t>::max()) {}

bool IncrementalGcStrategy::PreQuery () {
    int64_t start_ts = get_micros();
    std::vector<TablePtr> tables;
    tablet_manager_->ShowTable(&tables, NULL);

    for (size_t i = 0; i < tables.size(); ++i) {
        TabletFiles tablet_files;
        std::string table_name = tables[i]->GetTableName();
        if (table_name == FLAGS_tera_master_meta_table_name) continue;
        dead_tablet_files_.insert(std::make_pair(table_name, tablet_files));
        live_tablet_files_.insert(std::make_pair(table_name, tablet_files));

        std::set<uint64_t> live_tablets, dead_tablets;
        tables[i]->GetTabletsForGc(&live_tablets, &dead_tablets);
        std::set<uint64_t>::iterator it;
        // update dead tablets
        for (it = dead_tablets.begin(); it != dead_tablets.end(); ++it) {
            TabletFiles& temp_tablet_files = dead_tablet_files_[table_name];
            TabletFileSet tablet_file_set(get_micros() / 1000000, 0);
            bool ret = temp_tablet_files.insert(std::make_pair(*it, tablet_file_set)).second;
            if (ret) {
                VLOG(12) << "[gc] newly dead talbet " << table_name << " " << *it;
                CollectSingleDeadTablet(table_name, *it);
            }
        }

        // erase newly dead tablets from live tablets
        for (TabletFiles::iterator it = live_tablet_files_[table_name].begin();
             it != live_tablet_files_[table_name].end(); ++it) {
            if (dead_tablet_files_[table_name].find(static_cast<uint64_t>(it->first)) != dead_tablet_files_[table_name].end()) {
                live_tablet_files_[table_name].erase(it);
            }
        }

        // add new live tablets
        for (it = live_tablets.begin(); it != live_tablets.end(); ++it) {
            TabletFiles& temp_tablet_files = live_tablet_files_[table_name];
            TabletFileSet tablet_file_set;
            temp_tablet_files.insert(std::make_pair(*it, tablet_file_set));
        }
    }
    if (FLAGS_tera_garbage_collect_debug_log) {
        DEBUG_print_files(true);
        DEBUG_print_files(false);
    }
    LOG(INFO) << "[gc] Gather dead tablets, cost: " << (get_micros() - start_ts) / 1000 << "ms.";

    // do not need gc if there is no new dead tablet
    if (dead_tablet_files_.size() == 0) {
        LOG(INFO) << "[gc] Do not need gc this time";
    }
    return dead_tablet_files_.size() != 0;
}

void IncrementalGcStrategy::ProcessQueryCallbackForGc(QueryResponse* response) {
    LOG(INFO) << "[gc] ProcessQueryCallbackForGc";
    MutexLock lock(&gc_mutex_);

    std::set<std::string> ready_tables;
    for (int table = 0; table < response->inh_live_files_size(); ++table) {
        ready_tables.insert(response->inh_live_files(table).table_name());
    }

    // update tablet ready time
    for (int i = 0; i < response->tabletmeta_list().meta_size(); ++i) {
        const TabletMeta& meta = response->tabletmeta_list().meta(i);
        std::string table_name = meta.table_name();
        if (table_name == FLAGS_tera_master_meta_table_name) continue;
        if (live_tablet_files_.find(table_name) == live_tablet_files_.end() ||
            ready_tables.find(table_name) == ready_tables.end()) {
            continue;
        }
        VLOG(12) << "[gc] see live table " << table_name;
        int64_t tablet_number = static_cast<int64_t>(leveldb::GetTabletNumFromPath(meta.path()));
        if (live_tablet_files_[table_name].find(tablet_number) == live_tablet_files_[table_name].end()) continue;
        live_tablet_files_[table_name][tablet_number].ready_time_ = get_micros() / 1000000;
    }

    // insert live files
    for (int table = 0; table < response->inh_live_files_size(); ++table) {
        InheritedLiveFiles live_files = response->inh_live_files(table);
        std::string table_name = live_files.table_name();
        if (table_name == FLAGS_tera_master_meta_table_name) continue;
        VLOG(12) << "[gc] inh pb: " << response->inh_live_files(table).ShortDebugString();
        if (live_tablet_files_.find(table_name) == live_tablet_files_.end()) continue;
        // collect live files
        TabletFiles temp_tablet_files;
        for (int lg = 0; lg < live_files.lg_live_files_size(); ++lg) {
            LgInheritedLiveFiles lg_live_files = live_files.lg_live_files(lg);
            uint32_t lg_no = lg_live_files.lg_no();
            for (int i = 0; i < lg_live_files.file_number_size(); ++i) {
                uint64_t tablet_number, file;
                uint64_t file_number = lg_live_files.file_number(i);
                leveldb::ParseFullFileNumber(file_number, &tablet_number, &file);
                if (dead_tablet_files_[table_name].find(tablet_number) ==
                    dead_tablet_files_[table_name].end()) {
                    VLOG(12) << "[gc] skip newly dead tablet " << tablet_number;
                    continue;
                }
                TabletFileSet tablet_file_set;
                temp_tablet_files.insert(std::make_pair(tablet_number, tablet_file_set));
                TabletFileSet& temp_tablet_file_set = temp_tablet_files[tablet_number];
                LgFileSet lg_files;
                temp_tablet_file_set.files_.insert(std::make_pair(lg_no, lg_files));
                temp_tablet_file_set.files_[lg_no].live_files_.insert(file_number);
                VLOG(12) << "[gc] insert live file " << tablet_number << "/" << lg_no << "/" << file;
                const LgFileSet& check = ((dead_tablet_files_[table_name][tablet_number]).files_)[lg_no];
                CHECK(check.storage_files_.find(file_number) != check.storage_files_.end()) << "[gc] insert error";
            }
        }
        // update live files in dead tablets
        TabletFiles::iterator tablet_it = temp_tablet_files.begin();
        TabletFiles& dead_tablets = dead_tablet_files_[table_name];
        for (; tablet_it != temp_tablet_files.end(); ++tablet_it) {
            uint64_t tablet_number = tablet_it->first;
            if (dead_tablets.find(tablet_number) == dead_tablets.end()) {
                VLOG(12) << "[gc] skip tablet " << table_name << "/" << tablet_number;
                continue;
            }
            std::map<int64_t, LgFileSet>& live_lg = (tablet_it->second).files_;
            std::map<int64_t, LgFileSet>& dead_lg = dead_tablets[tablet_number].files_;
            std::map<int64_t, LgFileSet>::iterator lg_it = live_lg.begin();
            for (; lg_it != live_lg.end(); ++lg_it) {
                uint32_t lg_no = lg_it->first;
                LgFileSet lg_file_set;
                dead_lg.insert(std::make_pair(lg_no, lg_file_set));
                for (std::set<uint64_t>::iterator it = live_lg[lg_no].live_files_.begin(); it != live_lg[lg_no].live_files_.end(); ++it) {
                    dead_lg[lg_no].live_files_.insert(*it);
                }
                VLOG(12) << "[gc] copy " << tablet_number << "-" << lg_no;
            }
        }
    }
    if (FLAGS_tera_garbage_collect_debug_log) {
        DEBUG_print_files(true);
    }
}

void IncrementalGcStrategy::PostQuery () {
    LOG(INFO) << "[gc] PostQuery";
    if (FLAGS_tera_garbage_collect_debug_log) {
        DEBUG_print_files(true);
        DEBUG_print_files(false);
    }
    int64_t start_ts = get_micros();
    TableFiles::iterator table_it = dead_tablet_files_.begin();
    for (; table_it != dead_tablet_files_.end(); ++table_it) {
        DeleteTableFiles(table_it->first);
    }
    if (FLAGS_tera_garbage_collect_debug_log) {
        DEBUG_print_files(true);
        DEBUG_print_files(false);
    }
    LOG(INFO) << "[gc] Delete useless sst, cost: " << (get_micros() - start_ts) / 1000 << "ms. list_times " << list_count_.Get();
    list_count_.Clear();
}

void IncrementalGcStrategy::Clear(std::string tablename) {
    LOG(INFO) << "[gc] Clear " << tablename;
    MutexLock lock(&gc_mutex_);
    dead_tablet_files_.erase(tablename);
    live_tablet_files_.erase(tablename);
}

void IncrementalGcStrategy::DeleteTableFiles(const std::string& table_name) {
    std::string table_path = FLAGS_tera_tabletnode_path_prefix + table_name;
    leveldb::Env* env = io::LeveldbBaseEnv();
    TabletFiles& dead_tablets = dead_tablet_files_[table_name];
    TabletFiles& live_tablets = live_tablet_files_[table_name];
    int64_t earliest_ready_time = max_ts_;
    TabletFiles::iterator tablet_it = live_tablets.begin();
    for (; tablet_it != live_tablets.end(); ++tablet_it) {
        if (tablet_it->second.ready_time_ < earliest_ready_time) {
            earliest_ready_time = tablet_it->second.ready_time_;
        }
    }

    VLOG(12) << "[gc] earliest ready time  " << earliest_ready_time;
    std::set<int64_t> gc_tablets;
    for (tablet_it = dead_tablets.begin(); tablet_it != dead_tablets.end(); ++tablet_it) {
        if (tablet_it->second.dead_time_ < earliest_ready_time) {
            gc_tablets.insert(tablet_it->first);
            VLOG(12) << "[gc] push back gc tablet " << tablet_it->first;
        }
    }

    std::set<int64_t>::iterator gc_it = gc_tablets.begin();
    for (; gc_it != gc_tablets.end();) {
        std::map<int64_t, LgFileSet>& lg_files = dead_tablets[*gc_it].files_;
        std::map<int64_t, LgFileSet>::iterator lg_it = lg_files.begin();
        std::string tablet_path = leveldb::GetTabletPathFromNum(table_path, *gc_it);
        for (; lg_it != lg_files.end();) {
            VLOG(12) << "[gc] entry lg gc lg=" << lg_it->first;
            LgFileSet& lg_file_set = lg_it->second;
            std::set<uint64_t>::iterator file_it = lg_file_set.storage_files_.begin();
            for (; file_it != lg_file_set.storage_files_.end();) {
                if (lg_file_set.live_files_.find(*file_it) == lg_file_set.live_files_.end()) {
                    std::string file_path =
                        leveldb::BuildTableFilePath(table_path, lg_it->first, *file_it);

                    std::string debug_str;
                    for (std::set<uint64_t>::iterator it = lg_file_set.live_files_.begin(); it != lg_file_set.live_files_.end(); ++it) {
                        uint64_t file_no;
                        leveldb::ParseFullFileNumber(*it, NULL, &file_no);
                        debug_str += " " + boost::lexical_cast<std::string>(file_no);
                    }
                    VLOG(12) << "[gc] live = " << debug_str;
                    LOG(INFO) << "[gc] delete: " << file_path;
                    env->DeleteFile(file_path);
                    lg_file_set.storage_files_.erase(file_it++);
                } else {
                    file_it++;
                }
            }
            if (lg_file_set.storage_files_.size() == 0) {
                if (lg_file_set.live_files_.size() != 0) {
                    uint64_t full_number = *(lg_file_set.live_files_.begin());
                    uint64_t tablet_number, file_number;
                    leveldb::ParseFullFileNumber(full_number, &tablet_number, &file_number);
                    LOG(ERROR) << "still has live files: " << tablet_number << "/" << lg_it->first << "/" << file_number;
                    assert(0);
                }
                std::string lg_str = boost::lexical_cast<std::string>(lg_it->first);
                std::string lg_path = tablet_path + "/" + lg_str;
                LOG(INFO) << "[gc] delete empty lg dir: " << lg_path;
                env->DeleteDir(lg_path);
                lg_files.erase(lg_it++);
            } else {
                lg_it++;
            }
        }

        if (lg_files.size() == 0) {
            LOG(INFO) << "[gc] delete empty tablet dir: " << tablet_path;
            env->DeleteDir(tablet_path);
            dead_tablets.erase(*gc_it);
        } else {
            // clear live_files_ in dead_tablets for next round of gc
            for (lg_it = lg_files.begin(); lg_it != lg_files.end(); ++lg_it) {
                VLOG(12) << "[gc] clear live_files_ " << *gc_it << "/" << lg_it->first;
                lg_it->second.live_files_.clear();
            }
            VLOG(12) << "[gc] update dead_time_ ";
            dead_tablets[*gc_it].dead_time_ = get_micros() / 1000000;
        }
        gc_it++;
    }
}

void IncrementalGcStrategy::CollectSingleDeadTablet(const std::string& tablename, uint64_t tabletnum) {
    std::string tablepath = FLAGS_tera_tabletnode_path_prefix + tablename;
    std::string tablet_path = leveldb::GetTabletPathFromNum(tablepath, tabletnum);
    leveldb::Env* env = io::LeveldbBaseEnv();
    std::vector<std::string> children;
    env->GetChildren(tablet_path, &children);
    list_count_.Inc();

    for (size_t lg = 0; lg < children.size(); ++lg) {
        std::string lg_path = tablet_path + "/" + children[lg];
        leveldb::FileType type = leveldb::kUnknown;
        uint64_t number = 0;
        if (ParseFileName(children[lg], &number, &type)) {
            LOG(INFO) << "[gc] delete: " << lg_path;
            env->DeleteFile(lg_path);
            continue;
        }

        leveldb::Slice rest(children[lg]);
        uint64_t lg_num = 0;
        if (!leveldb::ConsumeDecimalNumber(&rest, &lg_num)) {
            LOG(INFO) << "[gc] skip unknown dir: " << lg_path;
            continue;
        }

        std::vector<std::string> files;
        env->GetChildren(lg_path, &files);
        list_count_.Inc();

        int64_t lg_no = boost::lexical_cast<int64_t>(children[lg]);
        std::map<int64_t, LgFileSet>& tablet_files = dead_tablet_files_[tablename][tabletnum].files_;
        LgFileSet lg_file_set;
        tablet_files.insert(std::make_pair(lg_no, lg_file_set));
        LgFileSet& temp_lg_files_set = tablet_files[lg_no];
        for (size_t f = 0; f < files.size(); ++f) {
            std::string file_path = lg_path + "/" + files[f];
            type = leveldb::kUnknown;
            number = 0;
            if (!ParseFileName(files[f], &number, &type) ||
                type != leveldb::kTableFile) {
                // only keep sst, delete rest files
                io::DeleteEnvDir(file_path);
                continue;
            }

            uint64_t full_number = leveldb::BuildFullFileNumber(lg_path, number);
            temp_lg_files_set.storage_files_.insert(full_number);
        }
    }
}

void IncrementalGcStrategy::DEBUG_print_files(bool print_dead) {
    TableFiles all_tablet_files;
    if (print_dead == true) {
        LOG(INFO) << "----------------------------[gc] Test print DEAD";
        all_tablet_files = dead_tablet_files_;
    } else {
        LOG(INFO) << "----------------------------[gc] Test print LIVE";
        all_tablet_files = live_tablet_files_;
    }
    TableFiles::iterator table_it;
    for (table_it = all_tablet_files.begin(); table_it != all_tablet_files.end(); ++table_it) {
        LOG(INFO) << "[gc] table=" << table_it->first;
        TabletFiles& tablet_files = table_it->second;
        TabletFiles::iterator tablet_it;
        for (tablet_it = tablet_files.begin(); tablet_it != tablet_files.end(); ++tablet_it) {
            LOG(INFO) << "[gc]   tablet -- " << tablet_it->first;
            TabletFileSet tablet_file_set = tablet_it->second;
            LOG(INFO) << "[gc]   ready -- " << tablet_file_set.ready_time_;
            LOG(INFO) << "[gc]   dead  -- " << tablet_file_set.dead_time_;
            std::map<int64_t, LgFileSet>& files = tablet_file_set.files_;
            std::map<int64_t, LgFileSet>::iterator lg_it;
            for (lg_it = files.begin(); lg_it != files.end(); ++lg_it) {
                std::set<uint64_t>& f = (lg_it->second).storage_files_;
                std::string debug_str = "";
                for (std::set<uint64_t>::iterator it = f.begin(); it != f.end(); ++it) {
                    uint64_t file_no;
                    leveldb::ParseFullFileNumber(*it, NULL, &file_no);
                    debug_str += " " + boost::lexical_cast<std::string>(file_no);
                }
                LOG(INFO) << "[gc]     lg stor -- " << lg_it->first << "-" << (lg_it->second).storage_files_.size() << debug_str;
                f = (lg_it->second).live_files_;
                debug_str = "";
                for (std::set<uint64_t>::iterator it = f.begin(); it != f.end(); ++it) {
                    uint64_t file_no;
                    leveldb::ParseFullFileNumber(*it, NULL, &file_no);
                    debug_str += " " + boost::lexical_cast<std::string>(file_no);
                }
                LOG(INFO) << "[gc]     lg live -- " << lg_it->first << "-" << (lg_it->second).live_files_.size() << debug_str;
            }
        }
    }
    LOG(INFO) << "----------------------------[gc] Done Test print";
}

} // namespace master
} // namespace tera

ext: cc

max_stars_repo_name: abin-coding/baidu

max_issues_repo_name: abin-coding/baidu

max_forks_repo_name: abin-coding/baidu


text:
#include "planner_modules_pr2/module_param_cache.h"
#include <boost/foreach.hpp>
#define forEach BOOST_FOREACH
#include <sstream>

namespace planner_modules_pr2
{
using namespace std;
using namespace modules;
inline void writeKeyDouble(std::stringstream& ss, const string& name, double value, double precision = 0.01)
{
	ss << name;
	if (value < 0)
	{
		ss << "N";
	}
	ss << abs(lrint(1.0 / precision * value));
}

std::string createPoseParamString(const geometry_msgs::Pose& pose, double precPose, double precQuat)
{
	std::stringstream ss;
	ss.precision(0);
	ss << std::fixed;
	// the actual values don't matter as long as they are unique for this pose
	// cannot use doubles here, as param keys are not allowed to contain '.' or '-'
	writeKeyDouble(ss, "x", pose.position.x, precPose);
	writeKeyDouble(ss, "y", pose.position.y, precPose);
	writeKeyDouble(ss, "z", pose.position.z, precPose);
	writeKeyDouble(ss, "qx", pose.orientation.x, precQuat);
	writeKeyDouble(ss, "qy", pose.orientation.y, precQuat);
	writeKeyDouble(ss, "qz", pose.orientation.z, precQuat);
	writeKeyDouble(ss, "qw", pose.orientation.w, precQuat);

	return ss.str();
}

std::string createPoseParamString(const geometry_msgs::Pose2D& pose, double torso_position, double precPose, double precTheta)
{
	std::stringstream ss;
	ss.precision(0);
	ss << std::fixed;
	// the actual values don't matter as long as they are unique for this pose
	// cannot use doubles here, as param keys are not allowed to contain '.' or '-'
	writeKeyDouble(ss, "x", pose.x, precPose);
	writeKeyDouble(ss, "y", pose.y, precPose);
	writeKeyDouble(ss, "th", pose.theta, precTheta);
	writeKeyDouble(ss, "tp", torso_position, precPose);

	return ss.str();
}

bool splitNamedId(const string & namedId, string & name, int & id)
{
	string::size_type foundIdx = namedId.find_first_of("0123456789");
	if (foundIdx == string::npos)
		return false;

	name = namedId.substr(0, foundIdx);

	std::stringstream ss(namedId.substr(foundIdx));
	ss >> id;
	return true;
}

}


text:
#include <boost/test/unit_test.hpp>
#include <eosio/testing/tester.hpp>
#include <infinite/infinite.wast.hpp>

using namespace eosio;
using namespace eosio::chain;
using namespace eosio::chain::contracts;
using namespace eosio::testing;

BOOST_AUTO_TEST_SUITE(limits_tests)

BOOST_AUTO_TEST_CASE(infinite_loop) {
   try {
      // set up runtime limits
      tester t({fc::milliseconds(1), fc::milliseconds(1)});
      t.produce_block();

      t.create_account(N(infinite));
      t.set_code(N(infinite), infinite_wast);

      {
         action act;
         act.account = N(infinite);
         act.name = N(op);
         act.authorization = vector<permission_level>{{N(infinite), config::active_name}};

         signed_transaction trx;
         trx.actions.emplace_back(std::move(act));

         t.set_tapos(trx);
         trx.sign(t.get_private_key(N(infinite), "active"), chain_id_type());

         BOOST_REQUIRE_THROW(t.push_transaction(trx), checktime_exceeded);
      }
   } FC_LOG_AND_RETHROW();
}

BOOST_AUTO_TEST_SUITE_END()

max_issues_repo_name: ElementhFoundation/blockchain

max_forks_repo_name: ElementhFoundation/blockchain


text:
// C++ Command line parameters parser.
// http://clp-parser.sourceforge.net/
//
// Copyright (C) Denis Shevchenko, 2010.
// shev.denis @ gmail.com
//
// 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.
//
// See http://www.opensource.org/licenses/mit-license.php

#ifndef CLPP_DETAIL_VALUES_SEMANTIC_HPP
#define CLPP_DETAIL_VALUES_SEMANTIC_HPP

#include "common_checker.hpp"
#include "../parameter.hpp"
#include "../parameter_parts_extractor.hpp"
#include "../argument_caster.hpp"
#include "validators.hpp"

#include <boost/assign.hpp>

/// \namespace clpp
/// \brief Main namespace of library.
namespace clpp {

/// \namespace clpp::detail
/// \brief Details of realization.
namespace detail {

using namespace boost::assign;

typedef common_checker< parameters, parameter_parts_extractor, std::string > checker;

/// \class values_semantic_checker
/// \brief Parameter's values semantic checker.
///
/// Checks semantic of parameters that registered with function 'check_semantic()'.
class values_semantic_checker : public checker {
    typedef boost::function< void ( const std::string& /* arg */
                                    , const std::string& /* parameter name */ ) >
            check_func;

    typedef std::map
                <
                    const value_semantic
                    , const check_func
                >
            checkers;
public:
    values_semantic_checker( const parameters&                  registered_parameters
                             , const parameter_parts_extractor& extractor
                             , const std::string&               name_value_separator ) :
            checker( registered_parameters, extractor, name_value_separator ) {
        insert( semantic_checkers )( path,  check_path_existence )
                                   ( ipv4,  check_ipv4_validity )
                                   ( ipv6,  check_ipv6_validity )
                                   ( ip,    check_ip_validity )
                                   ( email, check_email_validity )
                                   ;
    }
private:
    checkers semantic_checkers;
    argument_caster caster;
public:
    void check( const str_storage& inputed_parameters ) const {
    	str_storage all_names = collect_names_of_all_registered_parameters();
        check_semantic_of_inputed_values( inputed_parameters, all_names );
        check_semantic_of_default_values( all_names );
    }
private:
    str_storage collect_names_of_all_registered_parameters() const {
        str_storage all_names;
    	BOOST_FOREACH ( const parameter& registered_parameter, registered_parameters ) {
    		all_names += registered_parameter.short_name;
    	}
        return all_names;
    }

    void check_semantic_of_inputed_values( const str_storage& inputed_parameters
                                           , str_storage& all_names ) const {
        BOOST_FOREACH ( const std::string& inputed_parameter, inputed_parameters ) {
    		if ( this_is_parameter_with_value( inputed_parameter ) ) {
    			const std::string name  = extractor.extract_name_from( inputed_parameter );
                const std::string value = extractor.extract_value_from( inputed_parameter );
    			parameter_const_it it = std::find( registered_parameters.begin()
                                                   , registered_parameters.end()
                                                   , name );
                if ( registered_parameters.end() != it ) {
                    check_semantic_of_inputed_value( *it, value );
                    delete_element( all_names, name );
                } else {}
    		} else {}
    	}
    }

    bool this_is_parameter_with_value( const std::string& inputed_parameter ) const {
        return boost::contains( inputed_parameter, name_value_separator );
    }

    void check_semantic_of_inputed_value( const parameter& registered_parameter
                                          , const std::string& value ) const {
        const value_semantic semantic = registered_parameter.semantic;
        if ( no_semantic != semantic ) {
            const std::string name = registered_parameter.short_name;
            semantic_checkers.at( semantic )( value, name );
		} else {}
    }
private:
    void check_semantic_of_default_values( const str_storage& all_names ) const {
        BOOST_FOREACH ( const parameter& registered_parameter, registered_parameters ) {
    		str_const_it it = std::find( all_names.begin()
                                         , all_names.end()
                                         , registered_parameter.short_name );
    		if ( all_names.end() != it ) {
                check_semantic_of_default_value( registered_parameter );
    		} else {}
    	}
    }

    void check_semantic_of_default_value( const parameter& registered_parameter ) const {
        const value_semantic semantic = registered_parameter.semantic;
        if ( need_to_check_semantic( registered_parameter, semantic ) ) {
			s_arg_p p = boost::any_cast< s_arg_p >( registered_parameter.for_arg );
			semantic_checkers.at( registered_parameter.semantic )( p->default_value, registered_parameter.short_name );
        } else {}
    }

    bool need_to_check_semantic( const parameter& registered_parameter
                                 , const value_semantic& semantic ) const {
        return registered_parameter.has_default_value()
               && ( no_semantic != semantic )
               && caster.argument_must_be_string( registered_parameter )
               ;
    }
};

} // namespace detail
} // namespace clpp

#endif // CLPP_DETAIL_VALUES_SEMANTIC_HPP

max_stars_repo_name: HydrArgs/clpp

max_issues_repo_name: HydrArgs/clpp

max_forks_repo_name: HydrArgs/clpp


text:
// Copyright (c) 2016
// Author: Chrono Law
#include <std.hpp>
//using namespace std;

#include <boost/type_traits.hpp>
using namespace boost;

#include "../meta/mp_utils.hpp"

///////////////////////////////////////

void case1()
{
    assert((integral_constant<int, 10>::value == 10));

    static_assert(integral_constant<char, 0x30>::value == '0', "");

    static_assert(integral_constant<short, 100>::value == 100, "");

    static_assert(true_type::value == true, "");

    static_assert(mp_eval(false_type) == false, "");

}

///////////////////////////////////////

int main()
{
    std::cout << "hello type implementation" << std::endl;

    case1();
    //case2();
    //case3();
    //case4();
}


text:
// Copyright 2005 The Trustees of Indiana University.

// 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)

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
#ifndef BOOST_GRAPH_PYTHON_DISTRIBUTED_EXPORTS_HPP
#define BOOST_GRAPH_PYTHON_DISTRIBUTED_EXPORTS_HPP

#include <string>
#include <boost/python.hpp>

namespace boost { namespace graph { namespace distributed { namespace python {

void export_mpi();

template<typename Graph>
void export_graph(const char* name, const char* directedness);

void export_boman_et_al_graph_coloring();
void export_breadth_first_search();
void export_connected_components();
void export_dijkstra_shortest_paths();
void export_dinic_max_flow();
void export_dehne_gotz_min_spanning_tree();
void export_fruchterman_reingold_force_directed_layout();
void export_page_rank();
void export_strong_components();

template<typename Graph>
boost::python::object
vertex_property_map(const Graph& g, const std::string type);

template<typename Graph>
boost::python::object
edge_property_map(const Graph& g, const std::string type);

template<typename Graph> void export_property_maps();

template<typename Graph> void export_generators(const std::string& directness);

template<typename Graph> void export_metis(const std::string& directedness);

template<typename Graph> void export_graphviz(const std::string& directedness);

} } } } // end namespace boost::graph::distributed::python

#endif // BOOST_GRAPH_PYTHON_DISTRIBUTED_EXPORTS_HPP

max_stars_repo_name: erwinvaneijk/bgl-python

max_issues_repo_name: erwinvaneijk/bgl-python

max_forks_repo_name: erwinvaneijk/bgl-python


text:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <map>
#include <Eigen/Geometry>
#include <arc_utilities/arc_helpers.hpp>
#include <arc_utilities/eigen_helpers.hpp>

#ifndef ABB_IRB1600_145_FK_FAST_HPP
#define ABB_IRB1600_145_FK_FAST_HPP

namespace ABB_IRB1600_145_FK_FAST
{
    const size_t ABB_IRB1600_145_NUM_ACTIVE_JOINTS = 6;
    const size_t ABB_IRB1600_145_NUM_LINKS = 8;

    const std::string ABB_IRB1600_145_ACTIVE_JOINT_1_NAME = "joint_1";
    const std::string ABB_IRB1600_145_ACTIVE_JOINT_2_NAME = "joint_2";
    const std::string ABB_IRB1600_145_ACTIVE_JOINT_3_NAME = "joint_3";
    const std::string ABB_IRB1600_145_ACTIVE_JOINT_4_NAME = "joint_4";
    const std::string ABB_IRB1600_145_ACTIVE_JOINT_5_NAME = "joint_5";
    const std::string ABB_IRB1600_145_ACTIVE_JOINT_6_NAME = "joint_6";

    const std::string ABB_IRB1600_145_LINK_1_NAME = "link_0";
    const std::string ABB_IRB1600_145_LINK_2_NAME = "link_1";
    const std::string ABB_IRB1600_145_LINK_3_NAME = "link_2";
    const std::string ABB_IRB1600_145_LINK_4_NAME = "link_3";
    const std::string ABB_IRB1600_145_LINK_5_NAME = "link_4";
    const std::string ABB_IRB1600_145_LINK_6_NAME = "link_5";
    const std::string ABB_IRB1600_145_LINK_7_NAME = "link_6";
    const std::string ABB_IRB1600_145_LINK_8_NAME = "link_7";

    typedef std::vector<Eigen::Isometry3d, Eigen::aligned_allocator<Eigen::Isometry3d>> VectorIsometry3d;

    inline Eigen::Isometry3d Get_base_joint1_LinkJointTransform(const double joint_val)
    {
        Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.1245);
        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);
        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;
        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);
        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitZ()));
        Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;
        return (pre_joint_transform * joint_transform);
    }

    inline Eigen::Isometry3d Get_link_1_joint_2_LinkJointTransform(const double joint_val)
    {
        Eigen::Translation3d pre_joint_translation(0.15, -0.1395, 0.362);
        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);
        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;
        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);
        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));
        Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;
        return (pre_joint_transform * joint_transform);
    }

    inline Eigen::Isometry3d Get_link_2_joint_3_LinkJointTransform(const double joint_val)
    {
        Eigen::Translation3d pre_joint_translation(0.0, 0.028, 0.7);
        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);
        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;
        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);
        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));
        Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;
        return (pre_joint_transform * joint_transform);
    }

    inline Eigen::Isometry3d Get_link_3_joint_4_LinkJointTransform(const double joint_val)
    {
        Eigen::Translation3d pre_joint_translation(0.314, 0.107, 0.0);
        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);
        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;
        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);
        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitX()));
        Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;
        return (pre_joint_transform * joint_transform);
    }

    inline Eigen::Isometry3d Get_link_4_joint_5_LinkJointTransform(const double joint_val)
    {
        Eigen::Translation3d pre_joint_translation(0.286, 0.0, 0.0);
        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);
        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;
        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);
        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitY()));
        Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;
        return (pre_joint_transform * joint_transform);
    }

    inline Eigen::Isometry3d Get_link_5_joint_6_LinkJointTransform(const double joint_val)
    {
        Eigen::Translation3d pre_joint_translation(0.0, 0.0, 0.0);
        Eigen::Quaterniond pre_joint_rotation(1.0, 0.0, 0.0, 0.0);
        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;
        Eigen::Translation3d joint_translation(0.0, 0.0, 0.0);
        Eigen::Quaterniond joint_rotation(Eigen::AngleAxisd(joint_val, Eigen::Vector3d::UnitX()));
        Eigen::Isometry3d joint_transform = joint_translation * joint_rotation;
        return (pre_joint_transform * joint_transform);
    }

    inline Eigen::Isometry3d Get_Fixed_link_6_joint_tool_LinkJointTransform(void)
    {
        Eigen::Translation3d pre_joint_translation(0.065, 0.0, 0.0);
        Eigen::Quaterniond pre_joint_rotation(0.7071067811865476, 0.0, 0.7071067811865476, 0.0);
        Eigen::Isometry3d pre_joint_transform = pre_joint_translation * pre_joint_rotation;
        return pre_joint_transform;
    }

    inline VectorIsometry3d GetLinkTransforms(const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())
    {
        assert(configuration.size() == ABB_IRB1600_145_NUM_ACTIVE_JOINTS);
        VectorIsometry3d link_transforms(ABB_IRB1600_145_NUM_LINKS);
        link_transforms[0] = base_transform;
        link_transforms[1] = link_transforms[0] * Get_base_joint1_LinkJointTransform(configuration[0]);
        link_transforms[2] = link_transforms[1] * Get_link_1_joint_2_LinkJointTransform(configuration[1]);
        link_transforms[3] = link_transforms[2] * Get_link_2_joint_3_LinkJointTransform(configuration[2]);
        link_transforms[4] = link_transforms[3] * Get_link_3_joint_4_LinkJointTransform(configuration[3]);
        link_transforms[5] = link_transforms[4] * Get_link_4_joint_5_LinkJointTransform(configuration[4]);
        link_transforms[6] = link_transforms[5] * Get_link_5_joint_6_LinkJointTransform(configuration[5]);
        link_transforms[7] = link_transforms[6] * Get_Fixed_link_6_joint_tool_LinkJointTransform();
        return link_transforms;
    }

    inline VectorIsometry3d GetLinkTransforms(std::map<std::string, double> configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())
    {
        std::vector<double> configuration_vector(ABB_IRB1600_145_NUM_ACTIVE_JOINTS);
        configuration_vector[0] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_1_NAME];
        configuration_vector[1] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_2_NAME];
        configuration_vector[2] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_3_NAME];
        configuration_vector[3] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_4_NAME];
        configuration_vector[4] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_5_NAME];
        configuration_vector[5] = configuration[ABB_IRB1600_145_ACTIVE_JOINT_6_NAME];
        return GetLinkTransforms(configuration_vector, base_transform);
    }

    inline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(const std::vector<double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())
    {
        const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);
        EigenHelpers::MapStringIsometry3d link_transforms_map;
        link_transforms_map[ABB_IRB1600_145_LINK_1_NAME] = link_transforms[0];
        link_transforms_map[ABB_IRB1600_145_LINK_2_NAME] = link_transforms[1];
        link_transforms_map[ABB_IRB1600_145_LINK_3_NAME] = link_transforms[2];
        link_transforms_map[ABB_IRB1600_145_LINK_4_NAME] = link_transforms[3];
        link_transforms_map[ABB_IRB1600_145_LINK_5_NAME] = link_transforms[4];
        link_transforms_map[ABB_IRB1600_145_LINK_6_NAME] = link_transforms[5];
        link_transforms_map[ABB_IRB1600_145_LINK_7_NAME] = link_transforms[6];
        link_transforms_map[ABB_IRB1600_145_LINK_8_NAME] = link_transforms[7];
        return link_transforms_map;
    }

    inline EigenHelpers::MapStringIsometry3d GetLinkTransformsMap(const std::map<std::string, double>& configuration, const Eigen::Isometry3d& base_transform=Eigen::Isometry3d::Identity())
    {
        const EigenHelpers::VectorIsometry3d link_transforms = GetLinkTransforms(configuration, base_transform);
        EigenHelpers::MapStringIsometry3d link_transforms_map;
        link_transforms_map[ABB_IRB1600_145_LINK_1_NAME] = link_transforms[0];
        link_transforms_map[ABB_IRB1600_145_LINK_2_NAME] = link_transforms[1];
        link_transforms_map[ABB_IRB1600_145_LINK_3_NAME] = link_transforms[2];
        link_transforms_map[ABB_IRB1600_145_LINK_4_NAME] = link_transforms[3];
        link_transforms_map[ABB_IRB1600_145_LINK_5_NAME] = link_transforms[4];
        link_transforms_map[ABB_IRB1600_145_LINK_6_NAME] = link_transforms[5];
        link_transforms_map[ABB_IRB1600_145_LINK_7_NAME] = link_transforms[6];
        link_transforms_map[ABB_IRB1600_145_LINK_8_NAME] = link_transforms[7];
        return link_transforms_map;
    }
}

#endif // ABB_IRB1600_145_FK_FAST_HPP


text:
#include <boost/algorithm/string.hpp>
#include <string>
#include <iostream>

using namespace boost::algorithm;

int main()
{
  std::string s = "Boost C++ Libraries";
  boost::iterator_range<std::string::iterator> r = find_first(s, "C++");
  std::cout << r << '\n';
  r = find_first(s, "xyz");
  std::cout << r << '\n';
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/**
 * Copyright (c) 2011-2015  Regents of the University of California.
 *
 * This file is part of ndnSIM. See AUTHORS for complete list of ndnSIM authors and
 * contributors.
 *
 * ndnSIM is free software: you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * ndnSIM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * ndnSIM, e.g., in COPYING.md file.  If not, see <http://www.gnu.org/licenses/>.
 **/

#include "ndn-block-header.hpp"

#include <iosfwd>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>

#include <ndn-cxx/encoding/tlv.hpp>
#include <ndn-cxx/interest.hpp>
#include <ndn-cxx/data.hpp>
#include <ndn-cxx/lp/packet.hpp>

namespace io = boost::iostreams;
namespace nfdFace = nfd::face;

namespace ns3 {
namespace ndn {

ns3::TypeId
BlockHeader::GetTypeId()
{
  static ns3::TypeId tid =
    ns3::TypeId("ns3::ndn::Packet")
    .SetGroupName("Ndn")
    .SetParent<Header>()
    .AddConstructor<BlockHeader>()
    ;
  return tid;
}

TypeId
BlockHeader::GetInstanceTypeId(void) const
{
  return GetTypeId();
}

BlockHeader::BlockHeader()
{
}

BlockHeader::BlockHeader(const nfdFace::Transport::Packet& packet)
  : m_block(packet.packet)
{
}

uint32_t
BlockHeader::GetSerializedSize(void) const
{
  return m_block.size();
}

void
BlockHeader::Serialize(ns3::Buffer::Iterator start) const
{
  start.Write(m_block.wire(), m_block.size());
}

class Ns3BufferIteratorSource : public io::source {
public:
  Ns3BufferIteratorSource(ns3::Buffer::Iterator& is)
    : m_is(is)
  {
  }

  std::streamsize
  read(char* buf, std::streamsize nMaxRead)
  {
    std::streamsize i = 0;
    for (; i < nMaxRead && !m_is.IsEnd(); ++i) {
      buf[i] = m_is.ReadU8();
    }
    if (i == 0) {
      return -1;
    }
    else {
      return i;
    }
  }

private:
  ns3::Buffer::Iterator& m_is;
};

uint32_t
BlockHeader::Deserialize(ns3::Buffer::Iterator start)
{
  io::stream<Ns3BufferIteratorSource> is(start);
  m_block = ::ndn::Block::fromStream(is);
  return m_block.size();
}

void
BlockHeader::Print(std::ostream& os) const
{
  namespace tlv = ::ndn::tlv;
  namespace lp = ::ndn::lp;

  std::function<void(const Block& block)> decodeAndPrint = [&os, &decodeAndPrint] (const Block& block) {
    switch (block.type()) {
      case tlv::Interest: {
        Interest i(block);
        os << "Interest: " << i;
        break;
      }
      case tlv::Data: {
        Data d(block);
        os << "Data: " << d.getName();
        break;
      }
      case lp::tlv::LpPacket: {
        os << "NDNLP(";
        lp::Packet p(block);
        if (p.has<lp::FragCountField>() && p.get<lp::FragCountField>() != 1) {
          os << "fragment " << (p.get<lp::FragIndexField>() + 1) << " out of " << p.get<lp::FragCountField>();
        }
        else {
          if (p.has<lp::NackField>()) {
            lp::NackHeader nack = p.get<lp::NackField>();
            os << "NACK(" << nack.getReason() << ") for ";
          }

          ::ndn::Buffer::const_iterator first, last;
          std::tie(first, last) = p.get<lp::FragmentField>(0);
          Block fragmentBlock(&*first, std::distance(first, last));
          decodeAndPrint(fragmentBlock);
        }
        os << ")";
        break;
      }
      default: {
        os << "Unrecognized";
        break;
      }
    }
  };

  decodeAndPrint(m_block);
}

Block&
BlockHeader::getBlock()
{
  return m_block;
}

const Block&
BlockHeader::getBlock() const
{
  return m_block;
}

} // namespace ndn
} // namespace ns3

max_stars_repo_name: NDNLink/NDN-Chord

max_issues_repo_name: NDNLink/NDN-Chord

max_forks_repo_name: NDNLink/NDN-Chord


text:
#include <ros/ros.h>

// PCL specific includes
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/io/pcd_io.h>
#include <vtkRenderWindow.h>
#include <pcl/common/transforms.h>
#include <stdlib.h>
#include <sstream>
#include <stdio.h>
#include <time.h>
#include <Eigen/Eigen>
#include <Eigen/Geometry>
#include <tf/tf.h>
#include <pcl_ros/transforms.h>
#include <pcl/registration/icp.h>
#include <pcl/registration/icp_nl.h>
#include <pcl/keypoints/uniform_sampling.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/fpfh.h>
#include <pcl/registration/ia_ransac.h>
#include <pcl/surface/convex_hull.h>
#include <pcl/filters/crop_hull.h>
#include <pcl/registration/sample_consensus_prerejective.h>
#include <pcl/common/time.h>
#include <sensor_msgs/PointCloud.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>

typedef pcl::PointXYZRGBNormal PointT;
typedef pcl::visualization::PointCloudColorHandlerCustom<PointT> ColorHandlerT;
using namespace std;

boost::shared_ptr<pcl::visualization::PCLVisualizer> pclViewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
//boost::shared_ptr<pcl::visualization::PCLVisualizer> pclViewer2 (new pcl::visualization::PCLVisualizer ("Tests"));

pcl::PointCloud<PointT>::Ptr in1(new pcl::PointCloud<PointT>);
pcl::PointCloud<PointT>::Ptr in2(new pcl::PointCloud<PointT>);
pcl::PointCloud<PointT>::Ptr in2_transformed(new pcl::PointCloud<PointT>);
pcl::PointCloud<PointT>::Ptr out(new pcl::PointCloud<PointT>);

pcl::PointCloud<PointT>::Ptr container_model(new pcl::PointCloud<PointT>);
pcl::PointCloud<PointT>::Ptr icp_aligned_cloud(new pcl::PointCloud<PointT>);

int l_count = 0;
bool sData = true;
bool tData = true;
bool mData = false;
bool rData = false;

void keyboardEventOccurred (const pcl::visualization::KeyboardEvent &event, void* viewer_void);

time_t timer_beginning;
time_t timer_end;

void initPCLViewer(){
    //PCL Viewer
    pclViewer->registerKeyboardCallback (keyboardEventOccurred, (void*)&pclViewer);
    pclViewer->setBackgroundColor (0, 0, 0);
    pclViewer->initCameraParameters ();
    pclViewer->setCameraPosition(0,0,0,0,0,1,0,-1,0);
    vtkSmartPointer<vtkRenderWindow> renderWindow = pclViewer->getRenderWindow();
    renderWindow->SetSize(800,450);
    renderWindow->Render();

//    //PCL Viewer 2 (for testing)
//    pclViewer2->registerKeyboardCallback (keyboardEventOccurred, (void*)&pclViewer2);
//    pclViewer2->setBackgroundColor (0, 0, 0);
//    pclViewer2->initCameraParameters ();
//    pclViewer2->setCameraPosition(0,0,0,0,0,1,0,-1,0);
//    vtkSmartPointer<vtkRenderWindow> renderWindow2 = pclViewer2->getRenderWindow();
//    renderWindow2->SetSize(800,450);
//    renderWindow2->Render();
}

void keyboardEventOccurred (const pcl::visualization::KeyboardEvent &event, void* viewer_void)
{
    l_count = l_count + 1;
    if(l_count < 2){
        boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer = *static_cast<boost::shared_ptr<pcl::visualization::PCLVisualizer> *> (viewer_void);
        if (event.getKeySym () == "1" && tData){
            viewer->removePointCloud("in1");
            tData = false;
        }
        else if (event.getKeySym () == "1" && !tData){
            //viewer->removePointCloud("in1");
            pcl::visualization::PointCloudColorHandlerCustom<PointT> yellow(in1, 255, 255, 0);
            viewer->addPointCloud<PointT>(in1, yellow ,"in1");
            viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "in1");
            tData = true;
        }

        else if(event.getKeySym () == "2" && sData){
            viewer->removePointCloud("in2");
            sData = false;
        }
        else if(event.getKeySym () == "2" && !sData){
            //viewer->removePointCloud("in2");
            pclViewer->addPointCloud (in2_transformed, ColorHandlerT(in2_transformed, 255.0, 0.0, 0.0), "in2");
            pclViewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "in2");
            sData = true;
        }
        else if(event.getKeySym () == "3" && mData){
            viewer->removePointCloud("merged");
            mData = false;
        }
        else if(event.getKeySym () == "3" && !mData){
            // viewer->removePointCloud("merged");
            pcl::visualization::PointCloudColorHandlerCustom<PointT> green(out, 0.0, 255.0, 0.0);
            pclViewer->addPointCloud (out, green, "merged");
            pclViewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "merged");
            mData = true;
        }
        else if(event.getKeySym () == "4" && rData){
            viewer->removePointCloud("rgb");
            rData = false;
        }
        else if(event.getKeySym () == "4" && !rData){
            //viewer->removePointCloud("rgb");
            pcl::visualization::PointCloudColorHandlerRGBField<PointT> rgb(out);
            pclViewer->addPointCloud<PointT>(out, rgb, "rgb");
            pclViewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "rgb");
            rData = true;
        }

    }
    else{
        l_count = 0;
    }

}

Eigen::Matrix4f computeMatrixFromTransform(double x, double y, double z, double rx, double ry, double rz, double rw){

    Eigen::Vector3f vec(x, y, z);
    Eigen::Quaternionf quat(rw, rx, ry, rz);
    Eigen::Matrix3f rot = quat.toRotationMatrix();

    Eigen::Matrix4f mat;
    mat.setZero();
    mat.block(0, 0, 3, 3) = rot;
    mat.block(0, 3, 3, 1) = vec;
    mat(3,3) = 1;

    return mat;
}

pcl::PointCloud<PointT>::Ptr computeUniformSampling(pcl::PointCloud<PointT>::Ptr p_cloudIn, double radius)
{

    pcl::ScopeTime t("Uniform Sampling");

    std::cout << "US computation begin" << std::endl;

    pcl::UniformSampling<PointT> uniformSampling;
    pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>);
    boost::shared_ptr<std::vector<int> > point_cloud_indice (new std::vector<int> ());
    pcl::PointCloud<int> point_cloud_out;
    uniformSampling.setInputCloud(p_cloudIn);
    uniformSampling.setSearchMethod(tree);
    uniformSampling.setRadiusSearch(radius);
    uniformSampling.compute(point_cloud_out);

    for(int i = 0; i < point_cloud_out.size(); i++)
    {
        point_cloud_indice->push_back(point_cloud_out.at(i));
    }

    pcl::PointCloud<PointT>::Ptr sampled_cloud (new pcl::PointCloud<PointT>);

    pcl::ExtractIndices<PointT> extract;
    extract.setInputCloud(p_cloudIn);
    extract.setIndices(point_cloud_indice);
    extract.setNegative(false);
    extract.filter(*sampled_cloud);

    std::cout << "Pointcloud input size = " << p_cloudIn->size() << std::endl;
    std::cout << "Point cloud out size = " << point_cloud_out.size() << std::endl;
    std::cout << "Keypoints Size = " << sampled_cloud->size() << std::endl;

    return sampled_cloud;
}

pcl::PointCloud<PointT>::Ptr computeSurfaceNormals(pcl::PointCloud<PointT>::Ptr cloud)
{
    pcl::ScopeTime t("Normals");

    std::vector<int> indices;
    pcl::removeNaNFromPointCloud(*cloud, *cloud, indices);

    // Estimate the normals.
    pcl::NormalEstimation<PointT, pcl::Normal> normalEstimation;
    pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>);
    pcl::search::KdTree<PointT>::Ptr kdtree(new pcl::search::KdTree<PointT>);

    normalEstimation.setInputCloud(cloud);
    normalEstimation.setKSearch(10);
    normalEstimation.setSearchMethod(kdtree);
    normalEstimation.compute(*normals);

    pcl::PointCloud<PointT>::Ptr merged_cloud (new pcl::PointCloud<PointT>);
    pcl::concatenateFields(*cloud, *normals, *merged_cloud);

    return merged_cloud;

}

pcl::PointCloud<pcl::FPFHSignature33>::Ptr computeFPFH (pcl::PointCloud<PointT>::Ptr cloud){

    pcl::ScopeTime t("FPFH");

    pcl::PointCloud<pcl::FPFHSignature33>::Ptr features(new pcl::PointCloud<pcl::FPFHSignature33>);
    pcl::search::KdTree<PointT>::Ptr tree;
    double feature_radius = 0.02;

    pcl::FPFHEstimation<PointT, PointT, pcl::FPFHSignature33> fpfh_est;
    fpfh_est.setInputCloud (cloud);
    fpfh_est.setInputNormals (cloud);
    fpfh_est.setSearchMethod (tree);
    //fpfh_est.setKSearch(10);
    fpfh_est.setRadiusSearch (0.025);
    fpfh_est.compute (*features);

    return features;
}

Eigen::Matrix4f coarseAlignment(pcl::PointCloud<PointT>::Ptr src_cloud, pcl::PointCloud<pcl::FPFHSignature33>::Ptr src_features, pcl::PointCloud<PointT>::Ptr target_cloud, pcl::PointCloud<pcl::FPFHSignature33>::Ptr target_features){

    pcl::ScopeTime t("SAC-IA");

    pcl::SampleConsensusInitialAlignment<PointT, PointT, pcl::FPFHSignature33> sac_ia;
    float min_sample_distance = 0.1;
    float max_correspondence_distance = 1;
    int nr_iterations = 500;

    sac_ia.setMinSampleDistance (min_sample_distance);
    sac_ia.setMaxCorrespondenceDistance (max_correspondence_distance);
    sac_ia.setMaximumIterations (nr_iterations);

    sac_ia.setInputTarget (target_cloud);
    sac_ia.setTargetFeatures (target_features);

    sac_ia.setInputSource(src_cloud);
    sac_ia.setSourceFeatures (src_features);

    pcl::PointCloud<PointT>::Ptr registration_output(new pcl::PointCloud<PointT>);
    sac_ia.align (*registration_output);

    double fitness_score = (float) sac_ia.getFitnessScore(max_correspondence_distance);
    cout << "SAC-IA Transformation Score = " << fitness_score << endl;
    Eigen::Matrix4f transformation = sac_ia.getFinalTransformation ();

    return transformation;
}

Eigen::Matrix4f ransac_prerejective(pcl::PointCloud<PointT>::Ptr src_cloud, pcl::PointCloud<pcl::FPFHSignature33>::Ptr src_features, pcl::PointCloud<PointT>::Ptr target_cloud, pcl::PointCloud<pcl::FPFHSignature33>::Ptr target_features){

    pcl::ScopeTime t("RANSAC Prerejective");

    // Object for pose estimation.
    pcl::SampleConsensusPrerejective<PointT, PointT, pcl::FPFHSignature33> pose;
    pose.setInputSource(src_cloud);
    pose.setInputTarget(target_cloud);
    pose.setSourceFeatures(src_features);
    pose.setTargetFeatures(target_features);

    // Instead of matching a descriptor with its nearest neighbor, choose randomly between
    // the N closest ones, making it more robust to outliers, but increasing time.
    pose.setCorrespondenceRandomness(10);

    // Set the fraction (0-1) of inlier points required for accepting a transformation.
    // At least this number of points will need to be aligned to accept a pose.
    pose.setInlierFraction(0.95f);

    // Set the number of samples to use during each iteration (minimum for 6 DoF is 3).
    pose.setNumberOfSamples(3);

    // Set the similarity threshold (0-1) between edge lengths of the polygons. The
    // closer to 1, the more strict the rejector will be, probably discarding acceptable poses.
    pose.setSimilarityThreshold(0.75f);

    // Set the maximum distance threshold between two correspondent points in source and target.
    // If the distance is larger, the points will be ignored in the alignment process.
    pose.setMaxCorrespondenceDistance(0.04f);

    pose.setMaximumIterations(100);

    pcl::PointCloud<PointT>::Ptr alignedModel(new pcl::PointCloud<PointT>);
    pose.align(*alignedModel);
    Eigen::Matrix4f transformation = pose.getFinalTransformation();

    std::cout << "Converged : " << pose.hasConverged() << std::endl;
    std::cout << "Transformation Matrix : " << std::endl << transformation << std::endl;
    pcl::console::print_info ("Inliers: %i/%i\n", pose.getInliers().size (), src_cloud->size ());

    return transformation;

}

Eigen::Matrix4f align_icp(pcl::PointCloud<PointT>::Ptr src_cloud, pcl::PointCloud<PointT>::Ptr target_cloud, Eigen::Matrix4f initial_transform, double maxCorrespondanceDistance){

    pcl::ScopeTime t("ICP");

    pcl::IterativeClosestPoint<PointT, PointT> icp;
    icp.setInputSource(src_cloud);
    icp.setInputTarget(target_cloud);
    icp.setMaxCorrespondenceDistance(maxCorrespondanceDistance);
    icp.setMaximumIterations(40);
    pcl::PointCloud<PointT>::Ptr Final(new pcl::PointCloud<PointT>());
    icp.align(*Final,initial_transform);
    Eigen::Matrix4f icp_transform = icp.getFinalTransformation();

    return icp_transform;
}

void filterScenePointsFromAlignedModel(pcl::PointCloud<PointT>::Ptr aligned_model, pcl::PointCloud<PointT>::Ptr scene){

    pcl::PointCloud<PointT>::Ptr convexHull(new pcl::PointCloud<PointT>);
    pcl::ConvexHull<PointT> hull;
    std::vector<pcl::Vertices> polygons;
    hull.setInputCloud(aligned_model);
    hull.reconstruct(*convexHull, polygons);

    pcl::PointCloud<PointT>::Ptr objects (new pcl::PointCloud<PointT>);
    pcl::CropHull<PointT> bb_filter;

    bb_filter.setDim(3);
    bb_filter.setInputCloud(scene);
    bb_filter.setHullIndices(polygons);
    bb_filter.setHullCloud(convexHull);
    bb_filter.filter(*objects);
}

pcl::PointCloud<PointT>::Ptr downsample(pcl::PointCloud<PointT>::Ptr cloud){
    pcl::PointCloud<PointT>::Ptr returnCloud(new pcl::PointCloud<PointT>);
    pcl::VoxelGrid<PointT> grid;
    const float leaf = 0.008f;
    grid.setLeafSize (leaf, leaf, leaf);
    grid.setInputCloud (cloud);
    grid.filter (*returnCloud);

    return returnCloud;
}

int main (int argc, char** argv){

    // Initialize ROS
    ros::init (argc, argv, "multipleKinects");
    ros::NodeHandle nh;
    ros::NodeHandle n("~");

    pcl::io::loadPCDFile("/home/jp/devel/src/perception3d/src/tests/device1_1.pcd", *in1);
    pcl::io::loadPCDFile("/home/jp/devel/src/perception3d/src/tests/device2_1.pcd", *in2);
    pcl::io::loadPCDFile("/home/jp/devel/src/perception3d/src/tests/container_model.pcd", *container_model);

    initPCLViewer();

    // Find the coarse transformation between the two scans of the scene
    Eigen::Matrix4f tf1_matrix = computeMatrixFromTransform(-0.012687, 0.2937498, 1.0124953, -0.36378023, -0.32528895, -0.56674915, 0.663812041);
    Eigen::Matrix4f tf2_matrix = computeMatrixFromTransform(-0.1223497, 0.28168088, 1.1013584, -0.5120674, -0.0235908, -0.04915027, 0.85721325);
    Eigen::Matrix4f coord_transform = tf1_matrix * tf2_matrix.inverse();

    // Uniform Sampling
    pcl::PointCloud<PointT>::Ptr in_sampled1(new pcl::PointCloud<PointT>);
    pcl::PointCloud<PointT>::Ptr in_sampled2(new pcl::PointCloud<PointT>);
    in_sampled1 = computeUniformSampling(in1, 0.02);
    in_sampled2 = computeUniformSampling(in2, 0.02);
//    container_model = computeUniformSampling(container_model, 0.01);

    // Calculate Normals for every pointcloud
//    in1 = computeSurfaceNormals(in1);
//    in2 = computeSurfaceNormals(in2);
//    container_model = computeSurfaceNormals(container_model);

//    // downsample
    in1 = downsample(in1);
    in2 = downsample(in2);

    //    // Calculate FPFH Features for every pointcloud
    //    pcl::PointCloud<pcl::FPFHSignature33>::Ptr in1_fpfh = computeFPFH(in1);
    //    pcl::PointCloud<pcl::FPFHSignature33>::Ptr in2_fpfh = computeFPFH(in2);
    //    pcl::PointCloud<pcl::FPFHSignature33>::Ptr container_model_fpfh = computeFPFH(container_model);

    // Coarse Alignment

//    Eigen::Matrix4f model_to_scene_2 = coarseAlignment(container_model, container_model_fpfh, in2, in2_fpfh);
//    Eigen::Matrix4f model_to_scene_1 = ransac_prerejective(container_model, container_model_fpfh, in1, in1_fpfh);
   // Eigen::Matrix4f model_to_scene_2 = ransac_prerejective(container_model, container_model_fpfh, in2, in2_fpfh);

   // pcl::PointCloud<PointT>::Ptr container_scene2(new pcl::PointCloud<PointT>);

  //  pcl::transformPointCloud(*container_model, *container_scene2, model_to_scene_2);

//    Eigen::Matrix4f model_to_scene_1 = coarseAlignment(container_model, container_model_fpfh, in1, in1_fpfh);
//    pcl::PointCloud<PointT>::Ptr container_scene1(new pcl::PointCloud<PointT>);
//     pcl::transformPointCloud(*container_model, *container_scene1, model_to_scene_1);

//    pcl::visualization::PointCloudColorHandlerCustom<PointT> yellow2(container_scene1, 255.0, 255.0, 0.0);
//    pclViewer2->addPointCloud (container_scene1, yellow2, "model");
//    pclViewer2->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "model");

////    pcl::visualization::PointCloudColorHandlerCustom<PointT> yellow3(container_scene2, 255.0, 255.0, 0.0);
////    pclViewer2->addPointCloud (container_scene2, yellow3, "model2");
////    pclViewer2->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "model2");

//    pcl::visualization::PointCloudColorHandlerCustom<PointT> red2(in1, 255.0, 0.0, 0.0);
//    pclViewer2->addPointCloud (in1, red2, "scene");
//    pclViewer2->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "scene");

//    pcl::visualization::PointCloudColorHandlerCustom<PointT> blue(in2, 0.0, 0.0, 255.0);
//    pclViewer2->addPointCloud (in2, blue, "scene2");
//    pclViewer2->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "scene2");

    pcl::transformPointCloud(*in2, *in2_transformed, coord_transform);

    Eigen::Matrix4f icp_transform = align_icp(in_sampled2, in_sampled1, coord_transform, 0.02);
    pcl::transformPointCloud(*in2, *icp_aligned_cloud, icp_transform);

    *out = *in1 + *icp_aligned_cloud;
    out = downsample(out);

    pclViewer->addPointCloud (in1, ColorHandlerT(in1, 255.0, 255.0, 0.0), "in1");
    pclViewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "in1");

    pclViewer->addPointCloud (in2_transformed, ColorHandlerT(in2_transformed, 255.0, 0.0, 0.0), "in2");
    pclViewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 1, "in2");

    // pc to pc2
    pcl::PCLPointCloud2 pcl_cloud1, pcl_cloud2;
    pcl::toPCLPointCloud2(*in1,                 pcl_cloud1);
    pcl::toPCLPointCloud2(*in2_transformed,   pcl_cloud2);

    //From PCL pointclouds to ROS pointclouds (sensor_msgs)
    sensor_msgs::PointCloud2 ros_cloud1, ros_cloud2;
    pcl_conversions::fromPCL(pcl_cloud1, ros_cloud1);
    pcl_conversions::fromPCL(pcl_cloud2, ros_cloud2);

    // Publish point clouds
    ros::Publisher scan_publisher = n.advertise<sensor_msgs::PointCloud2> ("/multipleKinectsScan", 1);
    scan_publisher.publish(ros_cloud1);
    sleep(1);
    scan_publisher.publish(ros_cloud2);

    ros::Rate r(30);
    while (ros::ok() && !pclViewer->wasStopped()) {
        pclViewer->spinOnce (100);
        r.sleep();
    }
    return 0;
}


text:
/*
 *    Copyright 2021-Present Couchbase, Inc.
 *
 *   Use of this software is governed by the Business Source License included
 *   in the file licenses/BSL-Couchbase.txt.  As of the Change Date specified
 *   in that file, in accordance with the Business Source License, use of this
 *   software will be governed by the Apache License, Version 2.0, included in
 *   the file licenses/APL2.txt.
 */

#include <boost/filesystem.hpp>
#include <folly/portability/Unistd.h>
#include <getopt.h>
#include <platform/dirutils.h>
#include <programs/getpass.h>
#include <programs/hostname_utils.h>
#include <protocol/connection/client_connection.h>
#include <protocol/connection/client_mcbp_commands.h>
#include <protocol/connection/frameinfo.h>
#include <utilities/string_utilities.h>
#include <utilities/terminal_color.h>
#include <utilities/terminate_handler.h>
#include <iostream>

static void usage() {
    std::cerr << R"(Usage mcifconfig [options] <tls|list|define|delete>

Options:

  --host hostname[:port]   The host (with an optional port) to connect to
  --port port              The port number to connect to
  --user username          The name of the user to authenticate as
  --password password      The passord to use for authentication
                           (use '-' to read from standard input, or
                           set the environment variable CB_PASSWORD)
  --tls[=cert,key]         Use TLS and optionally try to authenticate
                           by using the provided certificate and
                           private key.
  --ipv4                   Connect over IPv4
  --ipv6                   Connect over IPv6
  --help                   This help text

Commands:

   list                    List the defined interfaces
   define <filename/JSON>  Define a new interface
   delete <UUID>           Delete the interface with the provided UUID
   tls [filename/JSON]     Get (no argument) or set TLS properties

)";

    exit(EXIT_FAILURE);
}

/**
 * Get the payload to use. If param is a filename then read the file, if not
 * it should be the actual value
 *
 * @param param the parameter passed to the program
 */
std::string getPayload(const std::string& param) {
    boost::filesystem::path nm(param);
    std::string value = param;
    if (exists(nm)) {
        value = cb::io::loadFile(nm.generic_string());
    }
    try {
        const auto parsed = nlohmann::json::parse(value);
    } catch (const std::exception& e) {
        std::cerr << TerminalColor::Red
                  << "Failed to parse provided JSON: " << e.what()
                  << TerminalColor::Reset << std::endl;
        std::exit(EXIT_FAILURE);
    }
    return value;
}

int main(int argc, char** argv) {
    // Make sure that we dump callstacks on the console
    install_backtrace_terminate_handler();
#ifndef WIN32
    setTerminalColorSupport(isatty(STDOUT_FILENO) && isatty(STDERR_FILENO));
#endif

    int cmd;
    std::string port;
    std::string host{"localhost"};
    std::string user{};
    std::string password{};
    std::string ssl_cert;
    std::string ssl_key;
    sa_family_t family = AF_UNSPEC;
    bool secure = false;

    cb::net::initialize();

    // we could have used an array, but then we need to keep track of the
    // size. easier to just use a vector
    const std::vector<option> options{
            {"ipv4", no_argument, nullptr, '4'},
            {"ipv6", no_argument, nullptr, '6'},
            {"host", required_argument, nullptr, 'h'},
            {"port", required_argument, nullptr, 'p'},
            {"password", required_argument, nullptr, 'P'},
            {"user", required_argument, nullptr, 'u'},
            {"tls=", optional_argument, nullptr, 't'},
            {"help", no_argument, nullptr, 0},
            {nullptr, 0, nullptr, 0}};

    while ((cmd = getopt_long(argc, argv, "", options.data(), nullptr)) !=
           EOF) {
        switch (cmd) {
        case '6':
            family = AF_INET6;
            break;
        case '4':
            family = AF_INET;
            break;
        case 'h':
            host.assign(optarg);
            break;
        case 'p':
            port.assign(optarg);
            break;
        case 'u':
            user.assign(optarg);
            break;
        case 'P':
            password.assign(optarg);
            break;
        case 't':
            secure = true;
            if (optarg) {
                auto parts = split_string(optarg, ",");
                if (parts.size() != 2) {
                    std::cerr << TerminalColor::Red
                              << "Incorrect format for --tls=certificate,key"
                              << TerminalColor::Reset << std::endl;
                    exit(EXIT_FAILURE);
                }
                ssl_cert = std::move(parts.front());
                ssl_key = std::move(parts.back());

                if (!cb::io::isFile(ssl_cert)) {
                    std::cerr << TerminalColor::Red << "Certificate file "
                              << ssl_cert << " does not exists"
                              << TerminalColor::Reset << std::endl;
                    exit(EXIT_FAILURE);
                }

                if (!cb::io::isFile(ssl_key)) {
                    std::cerr << TerminalColor::Red << "Private key file "
                              << ssl_key << " does not exists"
                              << TerminalColor::Reset << std::endl;
                    exit(EXIT_FAILURE);
                }
            }
            break;
        default:
            usage();
        }
    }

    if (password == "-") {
        password.assign(getpass());
    } else if (password.empty()) {
        const char* env_password = std::getenv("CB_PASSWORD");
        if (env_password) {
            password = env_password;
        }
    }

    if (optind == argc) {
        usage();
    }

    std::string key;
    std::string value;
    const std::string command{argv[optind++]};
    if (command == "list") {
        key = command;
        if (optind < argc) {
            std::cerr << TerminalColor::Red
                      << "Error: list don't take parameters"
                      << TerminalColor::Reset << std::endl;
            std::exit(EXIT_FAILURE);
        }
    } else if (command == "tls") {
        key = command;
        if (optind + 1 < argc) {
            std::cerr << TerminalColor::Red
                      << "Error: tls have 1 (optional) parameter"
                      << TerminalColor::Reset << std::endl;
            std::exit(EXIT_FAILURE);
        }
        if (optind < argc) {
            value = getPayload(argv[optind]);
        }
    } else if (command == "define") {
        key = command;
        if (optind == argc || optind + 1 < argc) {
            std::cerr << TerminalColor::Red << "Error: define have 1 parameter"
                      << TerminalColor::Reset << std::endl;
            std::exit(EXIT_FAILURE);
        }
        value = getPayload(argv[optind]);
    } else if (command == "delete") {
        key = command;
        if (optind == argc || optind + 1 < argc) {
            std::cerr << TerminalColor::Red
                      << "Error: delete must have 1 parameter"
                      << TerminalColor::Reset << std::endl;
            std::exit(EXIT_FAILURE);
        }
        value = argv[optind];
    } else {
        std::cerr << TerminalColor::Red << "Error: Unknown command \""
                  << command << "\"" << TerminalColor::Reset << std::endl;
        std::exit(EXIT_FAILURE);
    }

    try {
        if (port.empty()) {
            port = secure ? "11207" : "11210";
        }
        in_port_t in_port;
        sa_family_t fam;
        std::tie(host, in_port, fam) = cb::inet::parse_hostname(host, port);

        if (family == AF_UNSPEC) { // The user may have used -4 or -6
            family = fam;
        }

        MemcachedConnection connection(host, in_port, family, secure);
        connection.setSslCertFile(ssl_cert);
        connection.setSslKeyFile(ssl_key);
        connection.connect();

        if (!user.empty()) {
            connection.authenticate(
                    user, password, connection.getSaslMechanisms());
        }

        connection.setAgentName("mcifconfig " MEMCACHED_VERSION);
        connection.setFeatures({cb::mcbp::Feature::XERROR});

        auto rsp = connection.execute(BinprotGenericCommand{
                cb::mcbp::ClientOpcode::Ifconfig, key, value});
        if (rsp.isSuccess()) {
            std::cout << TerminalColor::Green << rsp.getDataString()
                      << TerminalColor::Reset << std::endl;
        } else {
            std::cerr << TerminalColor::Red
                      << "Failed: " << to_string(rsp.getStatus())
                      << rsp.getDataString() << TerminalColor::Reset
                      << std::endl;
            std::exit(EXIT_FAILURE);
        }
    } catch (const ConnectionError& ex) {
        std::cerr << TerminalColor::Red << ex.what() << TerminalColor::Reset
                  << std::endl;
        return EXIT_FAILURE;
    } catch (const std::runtime_error& ex) {
        std::cerr << TerminalColor::Red << ex.what() << TerminalColor::Reset
                  << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}