text: #include <boost/spirit/include/karma_eps.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**
 *  Copyright (C) 2015-2019
 *  Author Alvin Ahmadov <alvin.dev.ahmadov@gmail.com>
 *
 *  This file is part of Dixter Project
 *  License-Identifier: MIT License
 *  See README.md for more information.
 */

#pragma once

#include <map>
#include <unordered_map>
#include <set>
#include <mutex>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
#include "Commons.hpp"

namespace Dixter
{
	struct TNode;
	class TNodeData;
	class TNodeEntry;
	struct IConfiguration;

	/**
	 * \author Alvin Ahmadov
	 * \namespace Dixter
	 * \struct ConfigurationInterface
	 * \brief Interface for Configuration readers/writers.
	 * */
	struct IConfiguration
	{
		using PropertyTree          = boost::property_tree::basic_ptree<TString, TUString>;
		using PropertyTreePtr       = std::unique_ptr<PropertyTree>;
		using NodeEntryPtr       	= std::shared_ptr<TNodeEntry>;
		using ConfigurationProperty = std::unordered_map<TString, std::shared_ptr<IConfiguration>>;

		/**
		 * \interface ConfigurationInterface
		 * \brief Abstract method for loading data
		 * from configuration file.
		 * */
		virtual void load() = 0;

		/**
		 * \interface ConfigurationInterface
		 * \brief Abstract method for writing data
		 * to configuration file.
		 * */
		virtual void save() = 0;

		virtual void set(const TString& key, const TUString& value) = 0;

		virtual void keys(std::list<TString>&) const = 0;

		virtual void get(const TString& key, std::vector<TUString>& values) const = 0;

		virtual TUString get(const TString& key, const TUString& byValue) const = 0;

		virtual TUString get(const TString& key) const = 0;

		virtual ~IConfiguration() = default;
	};

	/**
	 * \brief Enum that defines which configuration reader/writer to use.
	 * */
	enum class EConfiguration
	{
		None,
		INI,
		XML,
		JSON
	};

	/**
	 * @brief Class for reading and storing settings from ini file
	 * */
	class TConfigurationINI final : public IConfiguration,
									public TMoveOnly
	{
	public:
		explicit TConfigurationINI(const TString& file) noexcept;

		virtual ~TConfigurationINI() noexcept override = default;

		void load() override;

		void save() override;

		void set(const TString& key, const TUString& value) override;

		void keys(std::list<TString>&) const override;

		TUString get(const TString& key) const override;

		void get(const TString& key, std::vector<TUString>& values) const override;

		TUString get(const TString& key, const TUString& byValue) const override;

	private:
		TString m_file;
		PropertyTreePtr m_propertyTree;
		NodeEntryPtr m_entries;
	};

	/**
	 * \class XMLConfiguration
	 * \implements ConfigurationInterface
	 * \brief Class for reading and storing settings from xml file
	 * */
	class TConfigurationXML final : public IConfiguration,
									public TMoveOnly
	{
	public:
		/**
		 * \class XMLConfiguration
		 * \brief ctor.
		 * \param file Absolute path to XML configuration xml file.
		 * */
		explicit TConfigurationXML(const TString& file) noexcept;

		/**
		 * \class XMLConfiguration
		 * \brief dtor.
		 * */
		virtual ~TConfigurationXML() noexcept override = default;

		/**
		 * \class XMLConfiguration
		 * \brief Loads data from configuration file to memory.
		 * */
		void load() override;

		/**
		 * \class XMLConfiguration
		 * \brief Saves data to configuration file.
		 * \note Not implemented for now.
		 * \throws NotImplementedException
		 * */
		void save() override;

		void set(const TString& key, const TUString& value) override;

		void keys(std::list<TString>&) const override;

		void get(const TString& key, std::vector<TUString>& values) const override;

		TUString get(const TString& key) const override;

		TUString get(const TString& key, const TUString& byValue) const override;

	private:
		TString m_file;

		TString m_rootNode;

		NodeEntryPtr m_entries;

		PropertyTreePtr m_propertyTree;

		mutable std::mutex m_mutex;
	};

	class TConfigurationJSON : public IConfiguration,
							   public TMoveOnly
	{
	public:
		using PropertyTree = boost::property_tree::basic_ptree<TString, TString>;

	public:
		explicit TConfigurationJSON(const TString& file) noexcept ;

		virtual ~TConfigurationJSON() noexcept override = default;

		void load() override;

		void save() override;

		void set(const TString&, const TUString&) override {}

		void keys(std::list<TString>&) const override;

		void get(const TString& key, std::vector<TUString>& values) const override;

		TUString get(const TString& key) const override;

		TUString get(const TString& key, const TUString& byValue) const override;

	private:
		TString m_file;

		TString m_rootNode;

		NodeEntryPtr m_entries;

		std::unique_ptr<PropertyTree> m_propertyTree;
	};

	class TConfigurationFactory : public TMoveOnly
	{
	private:
		using IConfigurationPtr = std::shared_ptr<IConfiguration>;
	public:
		explicit TConfigurationFactory(const TString& configPath, EConfiguration type);

		~TConfigurationFactory() noexcept = default;

		void load();

		void save();

		void keys(std::list<TString>&) const;

		IConfigurationPtr
		getConfiguration();

		EConfiguration
		getType() const;

	private:
		EConfiguration m_type;

		IConfigurationPtr m_configuration;
	};

	/**
	 * \author Alvin Ahmadov
	 * \class ConfigurationManager
	 * \implements ConfigurationManagerInterface
	 * \namespace Dixter
	 * \brief Singleton class that manages configurations
	 * */
	class TConfigurationManager : public TNonCopyable
	{
		/**
		 * \author Alvin Ahmadov
		 * \class ConfigurationManager::Accessor
		 * \brief Class used as inner helper class to read data of ConfigurationManager.
		 *
		 * Provides easy access interfaces to data. Data is immutable.
		 * */
		class TAccessor : public TNonCopyable
		{
		public:
			/**
			 * \brief Constructs TAccessor with non-owning TConfigurationManager pointer,
			 * which means it doesn't delete passed pointer.
			 * */
			explicit TAccessor(TConfigurationManager* manager) noexcept;

			~TAccessor() noexcept override = default;

			/**
		 * \class ConfigurationManager
		 * \brief Get value of node using key.
		 * \param key Node name of value.
		 * \returns Found value.
		 * \throws NotFoundException.
		 * */
			TUString getValue(const TString& key,
							  const TString& root = TString()) const;

			/**
			 * \class XMLConfiguration
			 * \brief Get value of node with key and with sibling value.
			 * \param byValue Sibling value.
			 * \param key Node name of sibling value.
			 * \returns value
			 * \throws NotFoundException
			 * */
			TUString getValue(const TString& key, const TUString& byValue,
							  const TString& root = TString()) const;

			/**
			 * \brief Get all values of node with specified name.
			 * \tparam Container Container to which save data.
			 * */
			const TAccessor*
			getValues(const TString& key, std::vector<TUString>& values,
					  const TString& root = TString()) const;

		private:
			std::shared_ptr<IConfiguration>
			get(const TString& key, const TString& root = TString()) const;

		private:
			TConfigurationManager* m_manager;
		};

		/**
		 * \author Alvin Ahmadov
		 * \class ConfigurationManager::Mutator
		 * \brief Class used as inner helper class to write data of ConfigurationManager.
		 *
		 * Provides easy access interfaces to data. Data is mutable.
		 * */
		class TMutator : public TNonCopyable
		{
		public:
			/**
			 * \brief Constructs TMutator with non-owning TConfigurationManager pointer,
			 * which means it doesn't delete passed pointer.
			 * */
			explicit TMutator(TConfigurationManager* manager) noexcept;

			~TMutator() noexcept override = default;

			/**
		 * \class ConfigurationManager
		 * \brief Get value of node using key.
		 * \param key Node name of value.
		 * \returns Found value.
		 * \throws NotFoundException.
		 * */
			const TMutator*
			setValue(const TString& key, const TUString& value,
					 const TString& root = "");

		private:
			std::shared_ptr<IConfiguration>
			get(const TString& key, const TString& root = "");

		private:
			TConfigurationManager*  m_manager;

			mutable std::mutex m_mutex;
		};

	public:
		using TSelf 			= TConfigurationManager;
		using TInstancePtr 		= std::shared_ptr<TSelf>;
		using TAccessorPtr 		= std::unique_ptr<TAccessor>;
		using TMutatorPtr 		= std::unique_ptr<TMutator>;
		using TConstIterator	= IConfiguration::ConfigurationProperty::const_iterator;

		virtual ~TConfigurationManager() noexcept = default;

		/**
		 * \class ConfigurationManager
		 * \brief Get instance of manager.
		 * \param type Configuration type.
		 * \param paths List of paths to configuration files.
		 * \returns Manager instance.
		 *
		 * If there is an initialised instance and its type is different,
		 * then the first instance will be added to a set, and new instance
		 * is initialised and used. Depending on type it will return the correct instance.
		 * */
		static TInstancePtr&
		getManager(EConfiguration type, std::set<TString> paths = std::set<TString>());

		const TAccessorPtr&
		accessor() const;

		const TMutatorPtr&
		mutator();

		/**
		 * \class ConfigurationManager
		 * \brief Gets the type of current instance.
		 * \returns Instance's type.
		 * */
		EConfiguration
		getType() const;

		/**
		 * \class ConfigurationManager
		 * \brief Updates loaded configuration values.
		 * \returns True if values updated.
		 * */
		// bool update();

	private:
		/**
		 * \class ConfigurationManager
		 * \brief ctor. Loads configuration for every configuration file.
		 * \param type Type of configuration to initialise.
		 * \param paths List of paths to configuration files.
		 * */
		TConfigurationManager(EConfiguration type, const std::set<TString>& paths);

		void read(EConfiguration type, const TString& path);

		void write(EConfiguration type, const TString& path);

		void checkKey(const TConstIterator key, TString errorMsg = "") const;

	private:
		static TInstancePtr m_instance;

		EConfiguration m_type;

		std::set<TString> m_paths;

		IConfiguration::ConfigurationProperty m_properties;

		std::unique_ptr<TAccessor> m_accessor;

		std::unique_ptr<TMutator> m_mutator;
	};

	inline TConfigurationManager::TInstancePtr
	getManager(EConfiguration type, const std::set<TString>& path)
	{
		return TConfigurationManager::getManager(type, path);
	}

	inline TConfigurationManager::TInstancePtr
	getIniManager(const std::set<TString>& path)
	{
		return TConfigurationManager::getManager(EConfiguration::INI, path);
	}

	inline TConfigurationManager::TInstancePtr
	getXmlManager(const std::set<TString>& path = {})
	{
		return TConfigurationManager::getManager(EConfiguration::XML, path);
	}

	inline TConfigurationManager::TInstancePtr
	getJsonManager(const std::set<TString>& path = {})
	{
		return TConfigurationManager::getManager(EConfiguration::JSON, path);
	}
} // namespace Dixter

max_stars_repo_name: alvinahmadov/Dixter

max_issues_repo_name: alvinahmadov/Dixter

max_forks_repo_name: alvinahmadov/Dixter


text:
#pragma once
#include <boost/asio.hpp>

namespace boost {
	class thread;
}

class Asio {
public:
	static void startup();
	static boost::asio::io_service &getIoService();
	static void shutdown();
private:
	static boost::asio::io_service *ioService;
	static boost::asio::io_service::work *work;
	static boost::thread *butler;
};


text:
/*
Copyright Barrett Adair 2016-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http ://boost.org/LICENSE_1_0.txt)
*/

#include <type_traits>
#include <functional>
#include <tuple>
#include <boost/callable_traits/remove_member_reference.hpp>
#include "test.hpp"

#ifdef BOOST_CLBL_TRTS_DISABLE_REFERENCE_QUALIFIERS
int main(){ return 0; }
#else

struct foo{};

int main() {
    {
        using f   = void(foo::*)();
        using l   = void(foo::*)() &;
        using r   = void(foo::*)() &&;
        using c   = void(foo::*)() const;
        using cl  = void(foo::*)() const &;
        using cr  = void(foo::*)() const &&;
        using v   = void(foo::*)() volatile;
        using vl  = void(foo::*)() volatile &;
        using vr  = void(foo::*)() volatile &&;
        using cv  = void(foo::*)() const volatile;
        using cvl = void(foo::*)() const volatile &;
        using cvr = void(foo::*)() const volatile &&;

        CT_ASSERT(std::is_same<f,    TRAIT(remove_member_reference,  f)>{});
        CT_ASSERT(std::is_same<c,    TRAIT(remove_member_reference,  c)>{});
        CT_ASSERT(std::is_same<v,    TRAIT(remove_member_reference,  v)>{});
        CT_ASSERT(std::is_same<cv,   TRAIT(remove_member_reference,  cv)>{});
        CT_ASSERT(std::is_same<f,    TRAIT(remove_member_reference,  l)>{});
        CT_ASSERT(std::is_same<c,    TRAIT(remove_member_reference,  cl)>{});
        CT_ASSERT(std::is_same<v,    TRAIT(remove_member_reference,  vl)>{});
        CT_ASSERT(std::is_same<cv,   TRAIT(remove_member_reference,  cvl)>{});
        CT_ASSERT(std::is_same<f,    TRAIT(remove_member_reference,  r)>{});
        CT_ASSERT(std::is_same<c,    TRAIT(remove_member_reference,  cr)>{});
        CT_ASSERT(std::is_same<v,    TRAIT(remove_member_reference,  vr)>{});
        CT_ASSERT(std::is_same<cv,   TRAIT(remove_member_reference,  cvr)>{});
    }

    {
        using f   = void();
        using l   = void() &;
        using r   = void() &&;
        using c   = void() const;
        using cl  = void() const &;
        using cr  = void() const &&;
        using v   = void() volatile;
        using vl  = void() volatile &;
        using vr  = void() volatile &&;
        using cv  = void() const volatile;
        using cvl = void() const volatile &;
        using cvr = void() const volatile &&;

        CT_ASSERT(std::is_same<f,    TRAIT(remove_member_reference,  f)>{});
        CT_ASSERT(std::is_same<c,    TRAIT(remove_member_reference,  c)>{});
        CT_ASSERT(std::is_same<v,    TRAIT(remove_member_reference,  v)>{});
        CT_ASSERT(std::is_same<cv,   TRAIT(remove_member_reference,  cv)>{});
        CT_ASSERT(std::is_same<f,    TRAIT(remove_member_reference,  l)>{});
        CT_ASSERT(std::is_same<c,    TRAIT(remove_member_reference,  cl)>{});
        CT_ASSERT(std::is_same<v,    TRAIT(remove_member_reference,  vl)>{});
        CT_ASSERT(std::is_same<cv,   TRAIT(remove_member_reference,  cvl)>{});
        CT_ASSERT(std::is_same<f,    TRAIT(remove_member_reference,  r)>{});
        CT_ASSERT(std::is_same<c,    TRAIT(remove_member_reference,  cr)>{});
        CT_ASSERT(std::is_same<v,    TRAIT(remove_member_reference,  vr)>{});
        CT_ASSERT(std::is_same<cv,   TRAIT(remove_member_reference,  cvr)>{});
    }
}

#endif //#ifndef BOOST_CLBL_TRTS_DISABLE_REFERENCE_QUALIFIERS

ext: cpp


text:
//----------------------------------------------------------------------------
// Copyright (C) 2018-2020 Mikhail Komarov <nemo@nil.foundation>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the Server Side Public License, version 1,
// as published by the author.
//
// This program 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
// Server Side Public License for more details.
//
// You should have received a copy of the Server Side Public License
// along with this program. If not, see
// <https://github.com/NilFoundation/plugin/blob/master/LICENSE_1_0.txt>.
//----------------------------------------------------------------------------

#define BOOST_TEST_MODULE post_rational_compound_test

#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/unit_test.hpp>

#include <nil/filecoin/storage/proofs/core/sector.hpp>

#include <nil/filecoin/storage/proofs/post/rational/compound.hpp>

#include "../../core/merkle/generate_tree.hpp"

using namespace nil::filecoin;

BOOST_AUTO_TEST_SUITE(post_rational_compound_test_suite)

template<typename MerkleTreeType>
void rational_post_test_compound() {
    const auto rng = XorShiftRng::from_seed(crate::TEST_SEED);

    const auto leaves = 32 * get_base_tree_count::<Tree>();
    const auto sector_size = (leaves * NODE_SIZE) as u64;
    const auto challenges_count = 2;

    const auto setup_params = compound_proof::SetupParams {
        vanilla_params : rational::SetupParams {
            sector_size,
            challenges_count,
        },
        partitions : None,
        priority : true,
    };

    const auto pub_params = RationalPoStCompound::<Tree>::setup(&setup_params).expect("setup failed");

    // Construct and store an MT using a named DiskStore.
    const auto temp_dir = tempfile::tempdir();
    const auto temp_path = temp_dir.path();

    auto data1, data2, tree1, tree2;
    const std::tie(data1, tree1) = merkletree::generate_tree<Tree>(rng, leaves, Some(temp_path.to_path_buf()));
    const std::tie(data2, tree2) = merkletree::generate_tree<Tree>(rng, leaves, Some(temp_path.to_path_buf()));

    const auto faults = OrderedSectorSet();
    auto sectors = OrderedSectorSet();
    sectors.insert(0.into());
    sectors.insert(1.into());

    const auto seed = (0..leaves).map(| _ | rng.gen()).collect::<Vec<u8>>();
    const auto challenges = derive_challenges(challenges_count, sector_size, &sectors, &seed, &faults);

    const std::vector<auto> comm_r_lasts_raw = { tree1.root(), tree2.root() };
    const std::vector<_> comm_r_lasts = challenges.iter().map(| c | comm_r_lasts_raw[u64::from(c.sector) as usize]).collect();

    const std::vector <typename MerkleTreeType::hash_type::digest_type > comm_cs
        = challenges.iter().map(| _c | typename MerkleTreeType::hash_type::digest_type::random(rng)).collect();

    const std::vector<_> comm_rs = comm_cs.iter()
                       .zip(comm_r_lasts.iter())
                       .map(| (comm_c, comm_r_last) | {<typename MerkleTreeType::hash_type>::Function::hash2(comm_c, comm_r_last)})
                       .collect();

    const auto pub_inputs = rational::PublicInputs {
        challenges : &challenges,
        faults : &faults,
        comm_rs : &comm_rs,
    };

    auto trees = BTreeMap();
    trees.insert(0.into(), &tree1);
    trees.insert(1.into(), &tree2);

    const auto priv_inputs = rational::PrivateInputs::<Tree> {
        trees : &trees,
        comm_r_lasts : &comm_r_lasts,
        comm_cs : &comm_cs,
    };

    const auto gparams = RationalPoStCompound::<Tree>::groth_params(Some(rng), &pub_params.vanilla_params);

    const auto proof =
        RationalPoStCompound::<Tree>::prove(&pub_params, &pub_inputs, &priv_inputs, &gparams);

    const auto(circuit, inputs) =
        RationalPoStCompound::<Tree>::circuit_for_test(&pub_params, &pub_inputs, &priv_inputs);

    auto cs = TestConstraintSystem();

    circuit.synthesize(cs);

    BOOST_ASSERT (cs.is_satisfied());
    BOOST_ASSERT (cs.verify(&inputs));

    const auto verified = RationalPoStCompound::<Tree>::verify(&pub_params, &pub_inputs, &proof, &NoRequirements);

    BOOST_ASSERT (verified);
}

BOOST_AUTO_TEST_CASE(rational_post_test_compound_pedersen) {
    rational_post_test_compound<BinaryMerkleTree<PedersenHasher>>();
}

BOOST_AUTO_TEST_CASE(rational_post_test_compound_poseidon) {
    rational_post_test_compound<BinaryMerkleTree<PoseidonHasher>>();
}

BOOST_AUTO_TEST_SUITE_END()


text:
//  (C) Copyright Edward Diener 2011
//  Use, modification and distribution are 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).

#if !defined(TTI_DETAIL_MEM_DATA_HPP)
#define TTI_DETAIL_MEM_DATA_HPP

#include <boost/config.hpp>
#include <boost/function_types/components.hpp>
#include <boost/function_types/is_member_object_pointer.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/tti/detail/ddeftype.hpp>
#include <boost/tti/detail/dftclass.hpp>
#include <boost/tti/gen/namespace_gen.hpp>
#include <boost/type_traits/detail/yes_no_type.hpp>
#include <boost/type_traits/is_same.hpp>

#if defined(BOOST_MSVC)

#define BOOST_TTI_DETAIL_TRAIT_HAS_MEMBER_DATA(trait,name) \
  template<class T,class C> \
  struct BOOST_PP_CAT(trait,_detail_hmd) \
    { \
    template<class> \
    struct return_of; \
    \
    template<class R,class C> \
    struct return_of<R C::*> \
      { \
      typedef R type; \
      }; \
    \
    template<bool,typename U> \
    struct menable_if; \
    \
    template<typename U> \
    struct menable_if<true,U> \
      { \
      typedef U type; \
      }; \
    \
    template<typename U,typename V> \
    static ::boost::type_traits::yes_type check2(V U::*); \
    \
    template<typename U,typename V> \
    static ::boost::type_traits::no_type check2(U); \
    \
    template<typename U,typename V> \
    static typename \
      menable_if \
        < \
        sizeof(check2<U,V>(&U::name))==sizeof(::boost::type_traits::yes_type), \
        ::boost::type_traits::yes_type \
        > \
      ::type \
    has_matching_member(int); \
    \
    template<typename U,typename V> \
    static ::boost::type_traits::no_type has_matching_member(...); \
    \
    template<class U,class V> \
    struct ttc_md \
      { \
      typedef boost::mpl::bool_<sizeof(has_matching_member<V,typename return_of<U>::type>(0))==sizeof(::boost::type_traits::yes_type)> type; \
      }; \
    \
    typedef typename ttc_md<T,C>::type type; \
    \
    BOOST_STATIC_CONSTANT(bool,value=type::value); \
    \
    }; \
/**/

#else // !defined(BOOST_MSVC)

#include <boost/tti/detail/dmem_fun.hpp>

#define BOOST_TTI_DETAIL_TRAIT_HAS_MEMBER_DATA(trait,name) \
  BOOST_TTI_DETAIL_TRAIT_HAS_TYPES_MEMBER_FUNCTION(trait,name) \
  template<class T,class C> \
  struct BOOST_PP_CAT(trait,_detail_hmd) : \
    BOOST_PP_CAT(trait,_detail_types)<T,C> \
    { \
    }; \
/**/

#endif // defined(BOOST_MSVC)

namespace boost
  {
  namespace tti
    {
    namespace detail
      {

      template<class T,class R>
      struct ptmd
        {
        typedef R T::* type;
        };

      template<class T>
      struct dmem_check_ptmd :
        boost::mpl::identity<T>
        {
        BOOST_MPL_ASSERT((boost::function_types::is_member_object_pointer<T>));
        };

      template<class T>
      struct dmem_check_ptec :
        BOOST_TTI_NAMESPACE::detail::class_type<T>
        {
        BOOST_MPL_ASSERT((boost::function_types::is_member_object_pointer<T>));
        };

      template<class T,class T2>
      struct dmem_get_type :
        boost::mpl::eval_if
          <
          boost::is_same<T2,BOOST_TTI_NAMESPACE::detail::deftype>,
          BOOST_TTI_NAMESPACE::detail::dmem_check_ptmd<T>,
          BOOST_TTI_NAMESPACE::detail::ptmd<T,T2>
          >
        {
        };

      template<class T,class T2>
      struct dmem_get_enclosing :
        boost::mpl::eval_if
          <
          boost::is_same<T2,BOOST_TTI_NAMESPACE::detail::deftype>,
          BOOST_TTI_NAMESPACE::detail::dmem_check_ptec<T>,
          boost::mpl::identity<T>
          >
        {
        };

      }
    }
  }

#endif // TTI_DETAIL_MEM_DATA_HPP

max_stars_repo_name: juslee/boost-svn

max_issues_repo_name: juslee/boost-svn

max_forks_repo_name: juslee/boost-svn


text:
//=========================================================================
//  Copyright (c) Kitware, Inc.
//  All rights reserved.
//  See LICENSE.txt for details.
//
//  This software is distributed WITHOUT ANY WARRANTY; without even
//  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
//  PURPOSE.  See the above copyright notice for more information.
//=========================================================================

#include "smtk/common/CompilerInformation.h"

SMTK_THIRDPARTY_PRE_INCLUDE
#include <pybind11/embed.h>

//force to use filesystem version 3
#define BOOST_FILESYSTEM_VERSION 3
#include <boost/filesystem.hpp>

// We use either STL regex or Boost regex, depending on support. These flags
// correspond to the equivalent logic used to determine the inclusion of Boost's
// regex library.
#if defined(SMTK_CLANG) ||                                                                         \
  (defined(SMTK_GCC) && __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) ||                 \
  defined(SMTK_MSVC)
#include <regex>
using std::regex;
using std::sregex_token_iterator;
#else
#include <boost/regex.hpp>
using boost::regex;
using boost::regex_match;
using boost::regex_replace;
using boost::regex_search;
using boost::sregex_token_iterator;
#endif

#include <boost/dll.hpp>

#ifdef _WIN32
#include <Python.h>
extern __declspec(dllimport) int Py_NoSiteFlag;
#endif

#include <patchlevel.h>

SMTK_THIRDPARTY_POST_INCLUDE

// We include the header after the third party includes because Python.h warns
// if it is not included before the stl headers our header file includes.
#include "smtk/common/PythonInterpreter.h"

#include "smtk/common/Environment.h"
#include "smtk/common/Paths.h"

#include <cstdlib>
#include <sstream>

namespace
{

//PYTHON_MODULEDIR is defined by cmake
std::string python_moduledir = PYTHON_MODULEDIR;
} // namespace

namespace smtk
{
namespace common
{
PythonInterpreter PythonInterpreter::m_instance;

PythonInterpreter& PythonInterpreter::instance()
{
  return PythonInterpreter::m_instance;
}

PythonInterpreter::PythonInterpreter()
{
  this->initialize();
}

PythonInterpreter::~PythonInterpreter()
{
  this->finalize();
}

bool PythonInterpreter::isInitialized() const
{
  return Py_IsInitialized() != 0;
}

void PythonInterpreter::initialize()
{
  // If the interpreter is already initialized, then there's nothing to do.
  if (this->isInitialized())
  {
    return;
  }

  // We are initializing the embedded python.
  m_embedded = true;

#ifdef __APPLE__
  // On macOS, see if we are running inside a packaged bundle.
  // If so, set the python path appropriately
  smtk::common::Paths paths;
  auto bundleDir = paths.bundleDirectory();
  std::ostringstream bundlePythonPath;
  bundlePythonPath << bundleDir << "/Contents/Libraries/lib/python" << PY_MAJOR_VERSION << "."
                   << PY_MINOR_VERSION;
  if (paths.directoryExists(bundlePythonPath.str()))
  {
    std::vector<wchar_t> pythonPath;
    pythonPath.resize(bundlePythonPath.str().size() + 1);
    mbstowcs(
      &pythonPath[0], bundlePythonPath.str().c_str(), static_cast<size_t>(pythonPath.size()));
    Py_SetPath(&pythonPath[0]);
  }
#endif

  // Locate the directory containing the python library in use, and set
  // PYTHONHOME to this path.
  static std::string pythonLibraryLocation = Paths::pathToLibraryContainingFunction(Py_Initialize);
#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 3) || PY_MAJOR_VERSION > 3
  // Python 3.3 switched to wchar_t.
  static std::vector<wchar_t> loc;
  loc.resize(pythonLibraryLocation.size() + 1);
  mbstowcs(&loc[0], pythonLibraryLocation.c_str(), static_cast<size_t>(loc.size()));
  Py_SetProgramName(&loc[0]);
#else
  Py_SetProgramName(const_cast<char*>(pythonLibraryLocation.c_str()));
#endif

  // Initialize the embedded interpreter.
  Py_NoSiteFlag = 1;
  pybind11::initialize_interpreter();

  // Locate the directory containing the library that describes this
  // class.
  boost::filesystem::path smtkLibDir =
    boost::dll::symbol_location(PythonInterpreter::instance).parent_path();

  // Use it to ensure that the smtk module is in our embedded python instance's
  // module path. If we don't find it, we don't do anyting special. Consuming
  // projects (like CMB) may have packaged SMTK with logic that does not follow
  // SMTK's install or build pattern, and that's ok. In this case, it is up to
  // the consuming project to properly set the embedded python's PYTHONPATH to
  // find SMTK, and can use the public methods
  // pathToLibraryContainingFunction(), addToPythonPath() and canFindModule() to
  // do so.
  this->addPathToPluginModule("smtk", smtkLibDir.string());
}

void PythonInterpreter::finalize()
{
  if (this->isInitialized())
  {
    pybind11::finalize_interpreter();
    m_embedded = false;
  }
}

std::vector<std::string> PythonInterpreter::pythonPath()
{
  if (!this->isInitialized())
  {
    this->initialize();
  }

  // Access the embedded python's PYTHONPATH from the python instance itself,
  // and parse it into a vector of strings.
  pybind11::dict locals;
  std::stringstream testCmd;
  testCmd << "import sys\n"
          << "path = ','.join(sys.path)";
  pybind11::exec(testCmd.str().c_str(), pybind11::globals(), locals);

  std::string path_list = locals["path"].cast<std::string>();

  std::vector<std::string> paths;

  regex re(",");
  sregex_token_iterator it(path_list.begin(), path_list.end(), re, -1), last;
  for (; it != last; ++it)
  {
    paths.push_back(it->str());
  }

  return paths;
}

bool PythonInterpreter::addToPythonPath(const std::string& path_list, std::string separator)
{
  if (!this->isInitialized())
  {
    this->initialize();
  }

  // Iterate over <path_list> with breaks at <separator> and add each path to
  // the embedded python's PYTHONPATH.
  pybind11::module sys = pybind11::module::import("sys");
  regex re(separator);
  sregex_token_iterator it(path_list.begin(), path_list.end(), re, -1), last;
  for (; it != last; ++it)
  {
    sys.attr("path").attr("insert")(0, it->str().c_str());
  }

  return true;
}

bool PythonInterpreter::addPathToPluginModule(const std::string& module, const std::string& libdir)
{
  // If the executing process's environment has set PYTHONPATH to find the
  // module, then there's no need for us to look for it.
  if (canFindModule(module))
  {
    return true;
  }

  std::string dir = boost::filesystem::path(libdir).parent_path().string();

  // Otherwise, locate the directory containing a library in the plugin.
  // We first look for SMTK as run from the build tree.
  bool found = this->addPathToBuildTree(dir, module);

  // If we don't find it, then we look for the module as an installed project.
  if (!found)
  {
    found = this->addPathToInstalledModule(dir, module);
  }

  // If we don't find it, then we look for the module as a packaged project.
  if (!found)
  {
    found = this->addPathToPackagedModule(dir, module);
  }

  return found;
}

bool PythonInterpreter::canFindModule(const std::string& module) const
{
  // If the python interpreter is not initialized, then we cannot find any
  // modules.
  if (!this->isInitialized())
  {
    return false;
  }

  // Within the embedded python environment, attempt to import <module>. We
  // allow for the possibility of the module not being found, but we
  // deliberately do not catch additional exceptions in case <module> cannot be
  // loaded for other reasons.

  bool found = true;
  pybind11::dict locals;
  std::stringstream testCmd;
  testCmd << "found = True\n"
          << "try:\n"
          << "    import " << module << "\n";
  if (Environment::hasVariable("SMTK_PYTHON_MODULE_LOAD_VERBOSE"))
  {
    testCmd << "except ImportError as error:\n"
            << "    print(str(error))\n";
  }
  else
  {
    testCmd << "except ImportError:\n";
  }
  testCmd << "    found = False";
  pybind11::exec(testCmd.str().c_str(), pybind11::globals(), locals);

  found = locals["found"].cast<bool>();
  return found;
}

bool PythonInterpreter::addPathToPackagedModule(
  const std::string& packageDir,
  const std::string& module)
{
  // If <module> is run out of a package, we add its directory to the PYTHONPATH.
  // The path to the module is specific to each platform.

#ifdef __APPLE__
  boost::filesystem::path inputPath = boost::filesystem::path(packageDir);
  boost::filesystem::path absPath = boost::filesystem::canonical(inputPath);
  boost::filesystem::path pythonPath = absPath / "Python";
#endif

#ifdef __linux__
  boost::filesystem::path inputPath = boost::filesystem::path(packageDir);
  boost::filesystem::path absPath = boost::filesystem::canonical(inputPath);
  boost::filesystem::path pythonPath = absPath.parent_path().parent_path() / python_moduledir;
#endif

#ifdef _WIN32
  boost::filesystem::path pythonPath = boost::filesystem::path(packageDir) / python_moduledir;
#endif

  boost::filesystem::path bundledPyInit = pythonPath / module / "__init__.py";
  if (boost::filesystem::is_regular_file(bundledPyInit))
  {
    this->addToPythonPath(pythonPath.string());
    return true;
  }
  return false;
}

bool PythonInterpreter::addPathToInstalledModule(
  const std::string& installDir,
  const std::string& module)
{
  // If <module> is run out of the install tree, we expect that the directory
  // that contains its libraries also contains a directory called
  // "python<PY_MAJOR_VERSION>.<PY_MINOR_VERSION>"/site-packages/<module>", so
  // we attempt to add this directory to the PYTHONPATH.

  boost::filesystem::path pythonPath = boost::filesystem::path(installDir) / python_moduledir;
  boost::filesystem::path installedPyInit = pythonPath / module / "__init__.py";

  if (boost::filesystem::is_regular_file(installedPyInit))
  {
    this->addToPythonPath(pythonPath.string());
    return true;
  }
  return false;
}

bool PythonInterpreter::addPathToBuildTree(
  const std::string& buildTreePath,
  const std::string& module)
{
  // If <module> is run out of the build tree, we expect the directory that
  // contains its libraries to reside one level below the build directory,
  // so we attempt to add the build directory to the PYTHONPATH.

  boost::filesystem::path pythonPath = boost::filesystem::path(buildTreePath) / python_moduledir;
  boost::filesystem::path buildTreePyInit = pythonPath / module / "__init__.py";

  if (boost::filesystem::is_regular_file(buildTreePyInit))
  {
    this->addToPythonPath(pythonPath.string());
    return true;
  }
  return false;
}

void PythonInterpreter::dontWriteByteCode(bool choice)
{
  // Access the embedded python's sys.dont_write_byte_code from the python
  // instance itself.
  pybind11::dict locals;
  std::stringstream testCmd;
  testCmd << "import sys\n"
          << "sys.dont_write_bytecode = " << (choice ? "True" : "False");
  pybind11::exec(testCmd.str().c_str(), pybind11::globals(), locals);
}

bool PythonInterpreter::dontWriteByteCode()
{
  // Access the embedded python's sys.dont_write_byte_code from the python
  // instance itself.
  pybind11::dict locals;
  std::stringstream testCmd;
  testCmd << "import sys\n"
          << "choice = sys.dont_write_bytecode";
  pybind11::exec(testCmd.str().c_str(), pybind11::globals(), locals);

  bool choice = locals["choice"].cast<bool>();

  return choice;
}

bool PythonInterpreter::loadPythonSourceFile(const std::string& fileName)
{
  return this->loadPythonSourceFile(fileName, smtk::common::Paths::stem(fileName));
}

bool PythonInterpreter::loadPythonSourceFile(
  const std::string& fName,
  const std::string& moduleName)
{
  // Convert to boost's generic format to avoid complications with Windows slashes
  std::string fileName = boost::filesystem::path(fName).generic_string();

  // For user-submitted source files, disable the generation of byte code
  bool dontWriteByteCode = this->dontWriteByteCode();
  this->dontWriteByteCode(true);

  bool loaded = true;
  pybind11::dict locals;
  std::stringstream testCmd;

  testCmd << "loaded = True\n"
          << "try:\n"
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5
          << "    import sys, types, importlib.machinery\n"
          << "    loader = importlib.machinery.SourceFileLoader('" << moduleName << "', '"
          << fileName << "')\n"
          << "    mod = types.ModuleType(loader.name)\n"
          << "    loader.exec_module(mod)\n"
          << "    sys.modules['" << moduleName << "'] = mod\n"
#elif PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 3 && PY_MINOR_VERSION <= 4
          << "    from importlib.machinery import SourceFileLoader\n"
          << "    tmp = SourceFileLoader('" << moduleName << "', '" << fileName
          << "').load_module()\n"
#else /* PY_MAJOR_VERSION == 2 */
          << "    import imp\n"
          << "    tmp = imp.load_source('" << moduleName << "', '" << fileName << "')\n"
#endif
          << "except Exception as e:\n"
          << "    print(e)\n"
          << "    loaded = False";

  pybind11::exec(testCmd.str().c_str(), pybind11::globals(), locals);

  loaded = locals["loaded"].cast<bool>();

  this->dontWriteByteCode(dontWriteByteCode);

  return loaded;
}
} // namespace common
} // namespace smtk

ext: cxx

max_stars_repo_name: jcfr/SMTK

max_issues_repo_name: jcfr/SMTK

max_forks_repo_name: jcfr/SMTK


text:
//
// Created by limenghua on 18-3-12.
//

#include <iostream>
#include <boost/config.hpp>

#include "modulepp/module.h"
#include "modulepp/plugin/plugin_config.h"
#include "modulepp/plugin/plugin_module.h"
#include "core/service.h"

namespace core {

    using namespace modulepp;
    using modulepp::plugin::plugin_module;
    using modulepp::plugin::plugin_config;

    class core_service:public service{
    public:
		virtual int version() { return 1; };
        virtual std::string name(){return "core";}
        virtual std::string describe(){return "this is the core service";}
	};

    class core_module:public plugin_module
    {
    public:
        core_module():
                plugin_module("core"){
            register_service<service>("service",std::make_shared<core_service>());
            std::cout<<"demo module core construct"<<std::endl;
        }

        ~core_module(){
            std::cout<<"demo module core destroyed"<<std::endl;
        }

        virtual void start()override {
            module::start();
            std::cout<<"demo module core start..."<<std::endl;

        }

        virtual void stop()override {
            module::stop();
            std::cout<<"demo module core stop..."<<std::endl;
        }
    };

// Exporting `my_namespace::plugin` variable with alias name `plugin`
// (Has the same effect as `BOOST_DLL_ALIAS(my_namespace::plugin, plugin)`)
    extern "C" BOOST_SYMBOL_EXPORT core_module plugin_module;
    core_module plugin_module;

} // namespace my_namespace

max_stars_repo_name: limenghua/modulespp

max_issues_repo_name: limenghua/modulespp

max_forks_repo_name: limenghua/modulespp


text:
//
// FILE NAME:       $HeadURL: svn+ssh://svn.cm.aol.com/advertising/adlearn/gen1/trunk/lib/cpp/DataProxy/private/ShellStreamTransformer.cpp $
//
// REVISION:        $Revision: 287491 $
//
// COPYRIGHT:       (c) 2008 Advertising.com All Rights Reserved.
//
// LAST UPDATED:    $Date: 2013-09-11 20:45:11 -0400 (Wed, 11 Sep 2013) $
// UPDATED BY:      $Author: sstrick $

#include "ShellStreamTransformer.hpp"
#include "ShellExecutor.hpp"
#include "TransformerUtilities.hpp"
#include "MVLogger.hpp"
#include "LargeStringStream.hpp"
#include <boost/lexical_cast.hpp>

namespace
{
	const std::string COMMAND( "command" );
	const std::string TIMEOUT( "timeout" );
}

ShellStreamTransformer::ShellStreamTransformer()
 :	ITransformFunction()
{
}

ShellStreamTransformer::~ShellStreamTransformer()
{
}

boost::shared_ptr< std::istream > ShellStreamTransformer::TransformInput( boost::shared_ptr< std::istream > i_pInputStream, const std::map< std::string, std::string >& i_rParameters )
{
	std::large_stringstream* pResult( new std::large_stringstream() );
	std::string command = TransformerUtilities::GetValue( COMMAND, i_rParameters );
	double timeout = TransformerUtilities::GetValueAs< double >( TIMEOUT, i_rParameters );

	std::large_stringstream standardError;
	ShellExecutor executor( command );
	MVLOGGER( "root.lib.DataProxy.DataProxyClient.StreamTransformers.Shell.TransformStream.ExecutingCommand", "Executing command: '" << command << "'" );
	int status = executor.Run( timeout, *i_pInputStream, *pResult, standardError );
	standardError.flush();
	if( status != 0 )
	{
		MV_THROW( ShellStreamTransformerException, "Command: '" << command << "' returned non-zero status: " << status << ". Standard error: " << standardError.rdbuf() );
	}
	if( !standardError.str().empty() )
	{
		MVLOGGER( "root.lib.DataProxy.DataProxyClient.StreamTransformers.Shell.TransformStream.StandardError",
			"Command: '" << command << "' generated standard error output: " << standardError.rdbuf() );
	}
	pResult->flush();
	return boost::shared_ptr< std::istream >( pResult );
}

max_stars_repo_name: aol/DataProxyLibrary

max_issues_repo_name: aol/DataProxyLibrary

max_forks_repo_name: aol/DataProxyLibrary


text:
//
// quick.cpp - a quick test for boost/bind/bind.hpp
//
// Copyright 2017 Peter Dimov
//
// 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
//

#include <boost/bind/bind.hpp>
#include <boost/core/lightweight_test.hpp>

using namespace boost::placeholders;

//

int f( int a, int b, int c )
{
    return a + 10 * b + 100 * c;
}

int main()
{
    int const i = 1;

    BOOST_TEST_EQ( boost::bind( f, _1, 2, 3 )( i ), 321 );

    return boost::report_errors();
}

max_issues_repo_name: qingkouwei/mediaones


text:
#ifndef __PARTICLE_FILTER_HPP
#define __PARTICLE_FILTER_HPP

#include <boost/random/discrete_distribution.hpp>

#include "particle_filter_base.hpp"

template <size_t Size>
ParticleFilter<Size>::ParticleFilter(const PredictionModel<Size> &pm,
				     const LikelihoodModel<Size> &lm,
				     unsigned int nParticles,
				     const double *initState):
  pm(pm),
  lm(lm),
  particles(std::vector<Particle<Size> >(nParticles)),
  epoch(0)
{
  if (initState)
  {
    pm.init(initState, particles);
  }
  else
  {
    double *_initState = new double[Size];
    std::fill(_initState, _initState+Size, 0);
    pm.init(initState, particles);
    delete []_initState;
  }
}

template <size_t Size>
const std::vector<Particle<Size> > &ParticleFilter<Size>::getParticles() const
{
  return particles;
}

template <size_t Size>
const Particle<Size> &ParticleFilter<Size>::getBestParticle() const
{

  double bestLikelihood = particles.at(0).likelihood;
  int bestID = 0;

  for (typename std::vector<Particle<Size> >::const_iterator it=particles.begin()+1;
       it!=particles.end(); ++it)
  {
    const Particle<Size> &p = *it;
    if (p.likelihood>bestLikelihood)
    {
      bestLikelihood = p.likelihood;
      bestID = it-particles.begin();
    }
  }

  return particles.at(bestID);
}

template <size_t Size>
void ParticleFilter<Size>::step(double deltaT)
{
  // Create a copy of the current particles
  std::vector<Particle<Size> > tempParticles(particles.size());
  std::copy(particles.begin(), particles.end(), tempParticles.begin());

  // Particle filter iteration
  // - update the particles state using the provided state-update model
  pm.update(tempParticles, deltaT);

  // - compute the importance weights using the provided likelihood model
  lm.eval(tempParticles);

  // Normalize the particles weight (and build the list of normalized weights
  // used in the next selection step)
  double wSum = 0.;
  for (typename std::vector<Particle<Size> >::iterator it=tempParticles.begin();
       it!=tempParticles.end(); ++it)
  {
    const Particle<Size> &p = *it;
    wSum += p.likelihood;
  }

  std::vector<double> normW;
  for (typename std::vector<Particle<Size> >::iterator it=tempParticles.begin();
       it!=tempParticles.end(); ++it)
  {
    Particle<Size> &p = *it;
    p.likelihood /= wSum;
    normW.push_back(p.likelihood);
  }

  // - selection step
  // TODO: parameterize at which epoch execute selection
  //if (!(epoch%10))
  if (true)
  {
    boost::random::discrete_distribution<> D(normW.begin(), normW.end());

    std::vector<int> idx;
    for (int i=0; i<tempParticles.size(); i++) idx.push_back(D(rng));

    // Copy back the selected particles
    for (int i=0; i<idx.size(); i++) particles.at(i) = tempParticles.at(idx.at(i));
  }
  else
  {
    std::copy(tempParticles.begin(), tempParticles.end(), particles.begin());
  }

  epoch++;

  // Done
}

#endif // __PARTICLE_FILTER_HPP


text:
#include <cctbx/boost_python/flex_fwd.h>

#include <cctbx/xray/gradients_direct.h>
#include <boost/python/class.hpp>

namespace cctbx { namespace xray { namespace structure_factors {
namespace boost_python {

namespace {

  struct gradients_direct_wrappers
  {
    typedef gradients_direct<> w_t;
    typedef w_t::scatterer_type scatterer_type;
    typedef w_t::float_type float_type;

    static void
    wrap()
    {
      using namespace boost::python;
      class_<w_t>("structure_factors_gradients_direct", no_init)
        .def(init<uctbx::unit_cell const&,
                  sgtbx::space_group const&,
                  af::const_ref<miller::index<> > const&,
                  af::const_ref<scatterer_type> const&,
                  af::const_ref<float_type> const&,
                  scattering_type_registry const&,
                  sgtbx::site_symmetry_table const&,
                  af::const_ref<std::complex<float_type> > const&,
                  std::size_t>())
        .def(init<math::cos_sin_table<double> const&,
                  uctbx::unit_cell const&,
                  sgtbx::space_group const&,
                  af::const_ref<miller::index<> > const&,
                  af::const_ref<scatterer_type> const&,
                  af::const_ref<float_type> const&,
                  scattering_type_registry const&,
                  sgtbx::site_symmetry_table const&,
                  af::const_ref<std::complex<float_type> > const&,
                  std::size_t>())
        .def("packed", &w_t::packed)
        .def("d_target_d_site_frac", &w_t::d_target_d_site_frac)
        .def("d_target_d_u_iso", &w_t::d_target_d_u_iso)
        .def("d_target_d_u_star", &w_t::d_target_d_u_star)
        .def("d_target_d_occupancy", &w_t::d_target_d_occupancy)
        .def("d_target_d_fp", &w_t::d_target_d_fp)
        .def("d_target_d_fdp", &w_t::d_target_d_fdp)
      ;
    }
  };

} // namespace <anoymous>

}} // namespace structure_factors::boost_python

namespace boost_python {

  void wrap_gradients_direct()
  {
    structure_factors::boost_python::gradients_direct_wrappers::wrap();
  }

}}} // namespace cctbx::xray::boost_python


text:
#include "ros/ros.h"
#include "tr3_msgs/ForwardIK.h"
#include <Eigen/Geometry>
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/robot_model/robot_model.h>
#include <moveit/robot_state/robot_state.h>

bool forward_ik(tr3_msgs::ForwardIK::Request &req, tr3_msgs::ForwardIK::Response &res)
{
	robot_model_loader::RobotModelLoader robot_model_loader("robot_description");
	robot_model::RobotModelPtr kinematic_model = robot_model_loader.getModel();
	ROS_INFO("Model frame: %s", kinematic_model->getModelFrame().c_str());

	robot_state::RobotStatePtr kinematic_state(new robot_state::RobotState(kinematic_model));
	kinematic_state->setToDefaultValues();
	const robot_state::JointModelGroup* joint_model_group = kinematic_model->getJointModelGroup("tr3_arm");

	const std::vector<std::string>& joint_names = joint_model_group->getVariableNames();

	std::vector<double> joint_values;
	kinematic_state->copyJointGroupPositions(joint_model_group, joint_values);
	for (std::size_t i = 0; i < joint_names.size(); ++i)
	{
		for (std::size_t j = 0; j < req.state.name.size(); j++)
		{
			if (joint_names[i] == req.state.name[j])
			{
				joint_values[i] = req.state.position[j];
			}
		}
	}

	kinematic_state->setJointGroupPositions(joint_model_group, joint_values);
	kinematic_state->enforceBounds();

	const Eigen::Affine3d& end_effector_state = kinematic_state->getGlobalLinkTransform("link_g0_fixed");

	res.pose.position.x = end_effector_state.translation().x();
	res.pose.position.y = end_effector_state.translation().y();
	res.pose.position.z = end_effector_state.translation().z();

	Eigen::Quaterniond q = (Eigen::Quaterniond)end_effector_state.rotation();
	res.pose.orientation.x = q.x();
	res.pose.orientation.y = q.y();
	res.pose.orientation.z = q.z();
	res.pose.orientation.w = q.w();

  ROS_INFO_STREAM("Found pose: \n" << res.pose << "\n");

	return true;
}

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

	ros::ServiceServer service = n.advertiseService("forward_ik", forward_ik);
	ROS_INFO("Ready.");
	ros::spin();

	return 0;
}


text:
#ifndef LAYERED_HARDWARE_GAZEBO_OPERATION_MODE_BASE_HPP
#define LAYERED_HARDWARE_GAZEBO_OPERATION_MODE_BASE_HPP

#include <string>

#include <layered_hardware_gazebo/common_namespaces.hpp>
#include <ros/duration.h>
#include <ros/node_handle.h>
#include <ros/time.h>
#include <transmission_interface/transmission_interface_loader.h> // for RawJointData

#include <gazebo/physics/physics.hh>

#include <boost/shared_ptr.hpp>

namespace layered_hardware_gazebo {

class OperationModeBase {
public:
  OperationModeBase(const std::string &name, const gzp::JointPtr joint)
      : name_(name), joint_(joint) {}

  virtual ~OperationModeBase() {}

  std::string getName() const { return name_; }

  virtual bool init(const ros::NodeHandle &param_nh) = 0;

  virtual void starting(ti::RawJointData *const data) = 0;

  virtual void read(ti::RawJointData *const data) = 0;

  virtual void write(const ti::RawJointData &data) = 0;

  virtual void update(const ros::Time &time, const ros::Duration &period) = 0;

  virtual void stopping() = 0;

protected:
  const std::string name_;
  const gzp::JointPtr joint_;
};

typedef boost::shared_ptr< OperationModeBase > OperationModePtr;
typedef boost::shared_ptr< const OperationModeBase > OperationModeConstPtr;
} // namespace layered_hardware_gazebo

#endif


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

#ifndef FM_LAST_MOOST_PROCESS_SERVICE_H_
#define FM_LAST_MOOST_PROCESS_SERVICE_H_

/**
 * \file service.hpp
 *
 * The moost::process::service class hides most of the process of setting up a system
 * service within an easy to use, yet customisable template. It takes care of:
 *
 *   - daemonisation
 *   - pid file creation
 *   - setting up signal handlers
 *   - setting up a local and/or remote command shell
 *   - setting up a moost::standard_console
 *   - starting the service
 *   - shutting down the service
 *
 * For this to work, a (usually very small) service class must be provided that implements
 * the following methods:

\code
class MyService
{
public:
   typedef MyServiceHandler HandlerType;   // a typedef for the service handler

   const std::string& name() const;        // returns the name of the service

   boost::shared_ptr<HandlerType> handler();
                                 // returns a shared pointer to the service handler object,
                                 //    which must implement the necessary methods to be used
                                 //    with moost::service::remote_shell
                                 // guaranteed not to be called before start() or after stop()

   void start();                 // performs all operations necessary to create and start the
                                 //    service handler

   void stop();                  // performs all operations necessary to stop the service
                                 //    handler
};
\endcode

 * The service handler defined by \c HandlerType must be compatible with
 * moost::service::remote_shell, i.e. it must implement the get_prompt(), show_help()
 * and handler_command() methods. It can be, but doesn't neccessarily have to be derived
 * from moost::fm303_cmd_shell.
 *
 * With the above class, a simple service can be implemented in a couple of lines of code:

\code
int main()
{
   MLOG_INIT();

   moost::process::service<MyService> service(new MyService);

   service.set_pidfile(pidfile);       // optional: override pid file name
   service.set_shell_port(shell_port); // optional: to enable the remote shell, set the shell port

   service.run(in_daemon_mode);        // run the service in daemon/non-daemon mode

   return 0;
}
\endcode

 * Nothing important happens inside the \c service object until its run() method is
 * called. The run method will do the following:
 *
 * - When \c in_daemon_mode is \c true, it will first fork a child process using
 *   moost::process::daemon.
 *
 * - The parent process will create a pid file and exit.
 *
 * - If \c in_daemon_mode is \c true or a remote shell port has been set (i.e.
 *   if there is no local shell), it will set up a signal handler using
 *   moost::process::quit_handler.
 *
 * - It will then call the start() method of service class defined above.
 *   The start() method must return with the created service handler running
 *   in its own thread.
 *
 * - If a shell port has been set or if \c in_daemon_mode is \c false, it will
 *   now set up a shell using moost::service::remote_shell. Otherwise, it will
 *   just set up an interruptible sleeper using moost::process::sleeper.
 *
 * - Whenever either shell exits or a terminating signal is received, the
 *   stop() method of the service class will be called.
 *
 * - Finally, the run() method returns.
 *
 * - The pid file will be deleted by the moost::process::service destructor.
 *
 * The service class must ensure that its handler() method returns a valid
 * handler object after the start() method has been called until the stop()
 * method is called.
 *
 * Here are some examples for more advanced usage:
 *
 * - You can use the set_child_init_func() method to set a boost::function
 *   object that will be passed on to moost::process::daemon and that will
 *   be called just after the child process has been forked. If the service
 *   is not daemonised, the function object will be called just after the
 *   run() method has been entered. The return value is ignored in that case.
 *   Note that the child init function is called just in time to allow
 *   further configuration of the moost::process::service instance, i.e.
 *   you can still configure all options relevant for the child process
 *   from within the child init function.
 *
 * - You can also override the exit behaviour of the parent process using
 *   set_parent_exit_func(). The function object is called with the child's
 *   process id as its only argument. The default implementation just calls
 *   exit(0). If you don't call exit() from the function object, run() will
 *   just return in the parent process and as a side effect, the pid file
 *   will be deleted as soon as the parent's instance of moost::process::service
 *   is destroyed.
 *
 * - You can override the creation of a console logger by passing a console
 *   logger policy as a template argument to moost::process::service. The default
 *   \c MoostStandardConsoleLoggerPolicy will create a moost::logging::standard_console
 *   instance. Use NoConsoleLoggerPolicy if you don't want a console logger.
 *   Note that the remote shell doesn't require a console logger to support logging.
 *
 * If you think that your service code is too long even with moost::process::service,
 * have a look at moost::service::skeleton.
 */

#include <stdexcept>
#include <cassert>

#include <boost/filesystem/path.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/noncopyable.hpp>
#include <boost/function.hpp>

#include "daemon.hpp"
#include "sleeper.hpp"
#include "pidfile.hpp"
#include "quit_handler.hpp"
#include "../logging/class_logger.hpp"
#include "../logging/standard_console.hpp"
#include "../service/remote_shell.h"
#include "../service/appender.h"

// XXX: This is just a workaround until hopefully some day show_help() and get_prompt() are const...
// #define MPS_FM303_SHELL_CONST const
#define MPS_FM303_SHELL_CONST

namespace moost { namespace process {

class NoConsoleLoggerPolicy
{
public:
   void create()
   {
   }

   bool set_log_level(const std::string&)
   {
      return false;
   }

   std::string show_help() const
   {
      return "";
   }

   bool handle_command(std::string&, const std::string&, const std::string&)
   {
      return false;
   }

   void enable()
   {
   }

   void disable()
   {
   }

   void log(const std::string&)
   {
   }
};

class MoostStandardConsoleLoggerPolicy
{
public:
   MoostStandardConsoleLoggerPolicy()
     : m_disabled(false)
     , m_invalid_log_level(new log4cxx::Level(-1, LOG4CXX_STR("INVALID"), 7 ))
   {
   }

   void create()
   {
      if (!m_console)
      {
         m_console.reset(new moost::logging::standard_console);
         set_log_level(m_log_level);
      }
   }

   bool set_log_level(const std::string& level)
   {
      if (m_console)
      {
         if (level.empty())
         {
            // default to 'info' level
            return m_console->setThreshold(log4cxx::Level::getInfo());
         }

         return m_console->setThreshold(level);
      }

      // this shouldn't be here; but we're safe as long as
      // this code and the logging framework are both in moost

      log4cxx::LevelPtr new_level = log4cxx::Level::toLevel(level, m_invalid_log_level);

      if (new_level == m_invalid_log_level)
      {
         return false;
      }

      m_log_level = level;

      return true;
   }

   std::string show_help() const
   {
      if (m_console && !m_disabled)
      {
         return "- level [off|fatal|error|warn|info|debug|trace|all]\n"
                "      set console log level [default: info]\n";
      }

      return "";
   }

   bool handle_command(std::string& rv, const std::string& cmd, const std::string& args)
   {
      if (m_console && !m_disabled)
      {
         if (cmd == "level")
         {
            if (set_log_level(args))
            {
               std::string level;
               m_console->getThreshold(level);
               rv = "log level set to [" + level + "]\n";
            }
            else
            {
               rv = "unknown log level " + args + "\n";
            }

            return true;
         }
      }

      return false;
   }

   void enable()
   {
      if (m_console && m_disabled)
      {
         m_console->enable();
         m_disabled = false;
      }
   }

   void disable()
   {
      if (m_console && !m_disabled)
      {
         m_console->disable();
         m_disabled = true;
      }
   }

   void log(const std::string& msg)
   {
      MLOG_NAMED_INFO("moost::process::service", msg);
   }

private:
   bool m_disabled;
   boost::scoped_ptr<moost::logging::standard_console> m_console;
   std::string m_log_level;
   log4cxx::LevelPtr m_invalid_log_level;
};

template<class ServiceT, class ConsoleLoggerPolicy = MoostStandardConsoleLoggerPolicy>
class service : public boost::noncopyable
{
private:
   struct noop_child_init_func
   {
      bool operator()()
      {
         return false;
      }
   };

   struct default_parent_exit_func
   {
      void operator()(pid_t)
      {
         exit(0);
      }
   };

   class service_wrapper : public boost::noncopyable
   {
   private:
      boost::shared_ptr<typename ServiceT::HandlerType> checked_handler()
      {
         boost::shared_ptr<typename ServiceT::HandlerType> hdl(m_service->handler());

         if (!hdl)
         {
            throw std::runtime_error("got null pointer for service handler");
         }

         return hdl;
      }

      boost::shared_ptr<const typename ServiceT::HandlerType> checked_handler() const
      {
         boost::shared_ptr<const typename ServiceT::HandlerType> hdl(m_service->handler());

         if (!hdl)
         {
            throw std::runtime_error("got null pointer for service handler");
         }

         return hdl;
      }

   public:
      service_wrapper(boost::shared_ptr<ServiceT> service)
        : m_service(service)
      {
      }

      bool set_log_level(const std::string& level)
      {
         return m_logger.set_log_level(level);
      }

      std::string get_prompt() MPS_FM303_SHELL_CONST
      {
         return checked_handler()->get_prompt();
      }

      std::string show_help() MPS_FM303_SHELL_CONST
      {
         std::string help;

         help += m_logger.show_help();
         help += checked_handler()->show_help();

         return help;
      }

      bool handle_command(std::string& rv, const std::string& cmd, const std::string& args)
      {
         if (m_logger.handle_command(rv, cmd, args))
         {
            return true;
         }

         return checked_handler()->handle_command(rv, cmd, args);
      }

      std::string name() const
      {
         return m_service->name();
      }

      void start()
      {
         m_logger.create();

         m_service->start();
      }

      void disable_logger()
      {
         m_logger.disable();
      }

      void enable_logger()
      {
         m_logger.enable();
      }

      void stop()
      {
         m_service->stop();
      }

      boost::shared_ptr<ServiceT> get_service()
      {
         return m_service;
      }

      void log(const std::string& msg)
      {
         m_logger.log(msg);
      }

   private:
      boost::shared_ptr<ServiceT> m_service;
      ConsoleLoggerPolicy m_logger;
   };

   struct enable_logger_func
   {
   public:
      enable_logger_func(service_wrapper& svc)
        : m_svc(svc)
      {
      }

      void operator()()
      {
         m_svc.enable_logger();
      }

   private:
      service_wrapper& m_svc;
   };

public:
   service(boost::shared_ptr<ServiceT> service)
     : m_svc(service)
     , m_started(false)
     , m_daemonised(false)
     , m_shell_port(0)
     , m_default_stdout_state(true)
     , m_default_stderr_state(true)
     , m_child_init_func(noop_child_init_func())
     , m_parent_exit_func(default_parent_exit_func())
   {
   }

   ~service()
   {
      if (m_pidfile)
      {
         m_pidfile->remove();
         m_pidfile.reset();
      }
   }

   bool set_log_level(const std::string& log_level)
   {
      return m_svc.set_log_level(log_level);
   }

   std::string name() const
   {
      return m_svc.name();
   }

   void set_shell_port(unsigned short shell_port)
   {
      m_shell_port = shell_port;
   }

   void set_appender_factory(moost::service::appender_factory_ptr factory)
   {
      m_app_factory = factory;
   }

   void set_default_stdout_state(bool enabled)
   {
      m_default_stdout_state = enabled;
   }

   void set_default_stderr_state(bool enabled)
   {
      m_default_stderr_state = enabled;
   }

   void set_child_init_func(boost::function0<bool> child_init_func)
   {
      m_child_init_func = child_init_func;
   }

   void set_parent_exit_func(boost::function1<void, pid_t> parent_exit_func)
   {
      m_parent_exit_func = parent_exit_func;
   }

   void run(bool daemonise = false)
   {
      if (daemonise)
      {
         moost::process::daemon d(false, m_child_init_func);

         m_pidfile.reset(m_pidfile_name.empty() ? new moost::process::pidfile(m_svc.name(), moost::process::pidfile::get_default_rundir().string())
                                                : new moost::process::pidfile(m_pidfile_name));

         if (d.is_parent())
         {
            pid_t child_pid = d.get_pid();

            if (!m_pidfile->create(child_pid))
            {
               throw std::runtime_error("failed to create pid file");
            }

            m_parent_exit_func(child_pid);

            return;
         }

         m_daemonised = true;
      }
      else
      {
         m_child_init_func();
      }

      moost::process::quit_handler::set(boost::bind(&moost::process::service<ServiceT, ConsoleLoggerPolicy>::quit_handler, this));

      m_svc.start();

      m_started = true;

      if (daemonise && !m_shell_port)
      {
         m_svc.disable_logger();
         m_sleeper.sleep();
      }
      else
      {
         // Create our io_service object and preload it with a function
         // object that will disable the standard_console logger. This
         // will be executed as soon as the io_service starts its main
         // event loop, i.e. when the local shell has taken over control.

         boost::shared_ptr<boost::asio::io_service> ios(new boost::asio::io_service);

         ios->post(boost::bind(&service_wrapper::disable_logger, &m_svc));

         m_remote_shell.reset(new remote_shell_t(m_svc, ios));

         if (m_app_factory)
         {
            m_remote_shell->set_appender_factory(m_app_factory);
         }

         m_remote_shell->set_default_stdout_state(m_default_stdout_state);
         m_remote_shell->set_default_stderr_state(m_default_stderr_state);

         if (m_shell_port)
         {
            m_remote_shell->set_listen_port(m_shell_port);
         }

         if (!daemonise)
         {
            // Enable a local shell if we're not daemonising. The pre shutdown
            // function object ensures that the standard_console has taken over
            // logging from the local shell before the local shell quits.

            m_remote_shell->enable_local_shell();
            m_remote_shell->set_pre_shutdown_function(enable_logger_func(m_svc));
         }

         m_remote_shell->run();
      }

      m_started = false;

      m_svc.stop();
   }

   void quit(const std::string& msg = "")
   {
      if (m_started)
      {
         if (m_remote_shell)
         {
            m_remote_shell->stop(msg);
         }

         m_sleeper.awaken();

         m_started = false;
      }
   }

   void set_pidfile(const std::string& pidfile)
   {
      boost::filesystem::path p(pidfile);

      if (!p.has_root_directory())
      {
         throw std::runtime_error("require absolute path for pid file");
      }

      m_pidfile_name = pidfile;
   }

   boost::shared_ptr<ServiceT> get_service()
   {
      return m_svc.get_service();
   }

private:
   void quit_handler()
   {
      m_svc.log("Received quit signal, shutting down.");
      quit("quit signal received, shutting down");
   }

   typedef moost::service::remote_shell<service_wrapper> remote_shell_t;

   service_wrapper m_svc;
   std::string m_pidfile_name;
   bool m_started;
   bool m_daemonised;
   boost::scoped_ptr<moost::process::pidfile> m_pidfile;
   unsigned short m_shell_port;
   boost::scoped_ptr<remote_shell_t> m_remote_shell;
   moost::service::appender_factory_ptr m_app_factory;
   moost::process::sleeper m_sleeper;
   bool m_default_stdout_state;
   bool m_default_stderr_state;
   boost::function0<bool> m_child_init_func;
   boost::function1<void, pid_t> m_parent_exit_func;
};

} }

#endif

max_stars_repo_name: lastfm/libmoost

max_issues_repo_name: lastfm/libmoost

max_forks_repo_name: lastfm/libmoost


text:
//  (C) Copyright Daniel James 2005.
//  Use, modification and distribution are 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)

#include <boost/functional/hash/pair.hpp>
#include <boost/functional/hash/vector.hpp>
#include <boost/functional/hash/list.hpp>
#include <boost/functional/hash/deque.hpp>
#include <boost/functional/hash/set.hpp>
#include <boost/functional/hash/map.hpp>
#include <boost/functional/hash/hash.hpp>
#include <boost/functional/hash.hpp>
#include <boost/functional/hash.hpp>

extern int f();
int main() { return f(); }

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM


text:
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#ifndef BOOST_HANA_TEST_AUTO_SORT_HPP
#define BOOST_HANA_TEST_AUTO_SORT_HPP

#include <boost/hana/all_of.hpp>
#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/less.hpp>
#include <boost/hana/permutations.hpp>
#include <boost/hana/sort.hpp>
#include <boost/hana/transform.hpp>

#include "test_case.hpp"
#include <laws/base.hpp>
#include <support/equivalence_class.hpp>

TestCase test_sort{[]{
    namespace hana = boost::hana;
    using hana::test::ct_eq;
    using hana::test::ct_ord;

    // Test without a custom predicate
    {
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE()),
            MAKE_TUPLE()
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(ct_ord<0>{})),
            MAKE_TUPLE(ct_ord<0>{})
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(ct_ord<0>{}, ct_ord<1>{})),
            MAKE_TUPLE(ct_ord<0>{}, ct_ord<1>{})
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(ct_ord<1>{}, ct_ord<0>{})),
            MAKE_TUPLE(ct_ord<0>{}, ct_ord<1>{})
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(ct_ord<1>{}, ct_ord<0>{}, ct_ord<4>{}, ct_ord<2>{})),
            MAKE_TUPLE(ct_ord<0>{}, ct_ord<1>{}, ct_ord<2>{}, ct_ord<4>{})
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(ct_ord<1>{}, ct_ord<0>{}, ct_ord<-4>{}, ct_ord<2>{})),
            MAKE_TUPLE(ct_ord<-4>{}, ct_ord<0>{}, ct_ord<1>{}, ct_ord<2>{})
        ));
    }

    // Test with a custom predicate
    {
        auto pred = [](auto x, auto y) {
            return hana::less(x.unwrap, y.unwrap);
        };
        auto a = [](auto z) { return ::equivalence_class(ct_eq<999>{}, z); };
        auto b = [](auto z) { return ::equivalence_class(ct_eq<888>{}, z); };

        auto check = [=](auto ...sorted) {
            auto perms = hana::transform(
                hana::permutations(MAKE_TUPLE(a(sorted)...)),
                hana::sort.by(pred)
            );
            BOOST_HANA_CONSTANT_CHECK(hana::all_of(perms, [=](auto xs) {
                return hana::equal(xs, MAKE_TUPLE(a(sorted)...));
            }));
        };

        check();
        check(ct_ord<1>{});
        check(ct_ord<1>{}, ct_ord<2>{});
        check(ct_ord<1>{}, ct_ord<2>{}, ct_ord<3>{});

        // check stability
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(a(ct_ord<1>{}), b(ct_ord<1>{})), pred),
            MAKE_TUPLE(a(ct_ord<1>{}), b(ct_ord<1>{}))
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(b(ct_ord<1>{}), a(ct_ord<1>{})), pred),
            MAKE_TUPLE(b(ct_ord<1>{}), a(ct_ord<1>{}))
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(a(ct_ord<1>{}), b(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<2>{})), pred),
            MAKE_TUPLE(a(ct_ord<1>{}), b(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<2>{}))
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(a(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<1>{}), b(ct_ord<2>{})), pred),
            MAKE_TUPLE(a(ct_ord<1>{}), b(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<2>{}))
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(b(ct_ord<1>{}), a(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<2>{})), pred),
            MAKE_TUPLE(b(ct_ord<1>{}), a(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<2>{}))
        ));
        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(a(ct_ord<2>{}), b(ct_ord<1>{}), b(ct_ord<2>{}), a(ct_ord<1>{})), pred),
            MAKE_TUPLE(b(ct_ord<1>{}), a(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<2>{}))
        ));

        BOOST_HANA_CONSTANT_CHECK(hana::equal(
            hana::sort(MAKE_TUPLE(a(ct_ord<1>{}), a(ct_ord<3>{}), b(ct_ord<1>{}), a(ct_ord<2>{}), b(ct_ord<3>{})), pred),
            MAKE_TUPLE(a(ct_ord<1>{}), b(ct_ord<1>{}), a(ct_ord<2>{}), a(ct_ord<3>{}), b(ct_ord<3>{}))
        ));
    }
}};

#endif // !BOOST_HANA_TEST_AUTO_SORT_HPP


text:
#include <asio_uring/eventfd_queue.hpp>

#include <atomic>
#include <stdexcept>
#include <thread>
#include <vector>
#include <asio_uring/eventfd.hpp>
#include <asio_uring/liburing.hpp>
#include <asio_uring/uring.hpp>
#include <asio_uring/test/allocator.hpp>
#include <boost/core/noncopyable.hpp>
#include <poll.h>
#include <sys/uio.h>

#include <iostream>

#include <catch2/catch.hpp>

namespace asio_uring::tests {
namespace {

TEST_CASE("eventfd_queue emplace & consume_all",
          "[eventfd_queue][eventfd]")
{
  std::vector<int> consumed;
  eventfd_queue<int> queue;
  queue.emplace(1);
  queue.emplace(2);
  queue.consume_all([&](auto i) { consumed.push_back(i); });
  auto iter = consumed.begin();
  REQUIRE_FALSE(iter == consumed.end());
  CHECK(*iter == 1);
  ++iter;
  REQUIRE_FALSE(iter == consumed.end());
  CHECK(*iter == 2);
  ++iter;
  CHECK(iter == consumed.end());
  queue.emplace(3);
  queue.emplace(4);
  queue.emplace(5);
  queue.consume_all([&](auto i) { consumed.push_back(i); });
  iter = consumed.begin();
  REQUIRE_FALSE(iter == consumed.end());
  CHECK(*iter == 1);
  ++iter;
  REQUIRE_FALSE(iter == consumed.end());
  CHECK(*iter == 2);
  ++iter;
  REQUIRE_FALSE(iter == consumed.end());
  CHECK(*iter == 3);
  ++iter;
  REQUIRE_FALSE(iter == consumed.end());
  CHECK(*iter == 4);
  ++iter;
  REQUIRE_FALSE(iter == consumed.end());
  CHECK(*iter == 5);
  ++iter;
  CHECK(iter == consumed.end());
}

TEST_CASE("eventfd_queue push & consume_all",
          "[eventfd_queue][eventfd]")
{
  using allocator_type = test::allocator<int>;
  allocator_type::state_type s;
  allocator_type a(s);
  std::vector<int> consumed;
  {
    eventfd_queue<int,
                  allocator_type> queue(a);
    queue.push(1);
    CHECK(s.allocate == 1);
    CHECK(s.construct == 1);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    queue.push(2);
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    queue.consume_all([&](auto i) { consumed.push_back(i); });
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    auto iter = consumed.begin();
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 1);
    ++iter;
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 2);
    ++iter;
    CHECK(iter == consumed.end());
  }
  CHECK(s.allocate == 2);
  CHECK(s.construct == 2);
  CHECK(s.deallocate == 2);
  CHECK(s.destroy == 2);
}

TEST_CASE("eventfd_queue pending",
          "[eventfd_queue][eventfd]")
{
  using allocator_type = test::allocator<int>;
  allocator_type::state_type s;
  allocator_type a(s);
  std::vector<int> consumed;
  {
    eventfd_queue<int,
                  allocator_type> queue(a);
    queue.emplace(1);
    CHECK(s.allocate == 1);
    CHECK(s.construct == 1);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    queue.emplace(2);
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    auto pending = queue.pending();
    REQUIRE(pending == 2);
    queue.consume(1,
                  [&](auto i) { consumed.push_back(i); });
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    auto iter = consumed.begin();
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 1);
    ++iter;
    CHECK(iter == consumed.end());
    queue.consume(1,
                  [&](auto i) { consumed.push_back(i); });
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    iter = consumed.begin();
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 1);
    ++iter;
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 2);
    ++iter;
    CHECK(iter == consumed.end());
  }
  CHECK(s.allocate == 2);
  CHECK(s.construct == 2);
  CHECK(s.deallocate == 2);
  CHECK(s.destroy == 2);
}

TEST_CASE("eventfd_queue exception",
          "[eventfd_queue][eventfd]")
{
  using allocator_type = test::allocator<int>;
  allocator_type::state_type s;
  allocator_type a(s);
  std::vector<int> consumed;
  {
    eventfd_queue<int,
                  allocator_type> queue(a);
    queue.emplace(1);
    CHECK(s.allocate == 1);
    CHECK(s.construct == 1);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    queue.emplace(2);
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    auto pending = queue.pending();
    REQUIRE(pending == 2);
    auto func = [&](auto i) {
      consumed.push_back(i);
      throw std::runtime_error("foo");
    };
    CHECK_THROWS_AS(queue.consume(1,
                                  func),
                    std::runtime_error);
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    auto iter = consumed.begin();
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 1);
    ++iter;
    CHECK(iter == consumed.end());
    queue.consume(1,
                  [&](auto i) { consumed.push_back(i); });
    CHECK(s.allocate == 2);
    CHECK(s.construct == 2);
    CHECK(s.deallocate == 0);
    CHECK(s.destroy == 0);
    iter = consumed.begin();
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 1);
    ++iter;
    REQUIRE_FALSE(iter == consumed.end());
    CHECK(*iter == 2);
    ++iter;
    CHECK(iter == consumed.end());
  }
  CHECK(s.allocate == 2);
  CHECK(s.construct == 2);
  CHECK(s.deallocate == 2);
  CHECK(s.destroy == 2);
}

TEST_CASE("eventfd & uring polling",
          "[eventfd_queue][eventfd]")
{
  uring u(2);
  eventfd e;
  using allocator_type = test::allocator<int>;
  allocator_type::state_type s;
  allocator_type a(s);
  {
    eventfd_queue<int,
                  allocator_type> queue(a);
    std::atomic<std::size_t> produced(0);
    std::atomic<std::size_t> consumed(0);
    std::thread t([&]() {
      ::io_uring_sqe* sqe = ::io_uring_get_sqe(u.native_handle());
      CHECK(sqe);
      if (!sqe) {
        return;
      }
      ::io_uring_prep_poll_add(sqe,
                               e.native_handle(),
                               POLLIN);
      for (;;) {
        ::io_uring_sqe* sqe = ::io_uring_get_sqe(u.native_handle());
        CHECK(sqe);
        if (!sqe) {
          return;
        }
        ::io_uring_prep_poll_add(sqe,
                                 queue.native_handle(),
                                 POLLIN);
        ::io_uring_submit(u.native_handle());
        ::io_uring_cqe* cqe;
        int result = ::io_uring_wait_cqe(u.native_handle(),
                                         &cqe);
        CHECK(result >= 0);
        if (result < 0) {
          return;
        }
        if (!cqe->user_data) {
          return;
        }
        consumed += queue.consume_all([&](auto&&) {});
        if (consumed == produced) {
          return;
        }
        ::io_uring_cqe_seen(u.native_handle(),
                            cqe);
      }
    });
    class guard : private boost::noncopyable {
    public:
      guard(std::thread& t,
            eventfd& done) noexcept
        : t_   (t),
          done_(done)
      {}
      ~guard() noexcept {
        done_.write(1);
        t_.join();
      }
    private:
      std::thread& t_;
      eventfd&     done_;
    };
    guard g(t,
            e);
    for (std::size_t i = 0; i < 100000; ++i) {
      queue.emplace(1);
    }
    while (produced != consumed);
  }
  CHECK(s.allocate != 0);
  CHECK(s.construct == s.allocate);
  CHECK(s.deallocate == s.allocate);
  CHECK(s.destroy == s.construct);
}

}
}

max_stars_repo_name: soumy/AsioUring

max_issues_repo_name: soumy/AsioUring

max_forks_repo_name: soumy/AsioUring