text:
//  Copyright (c) 2016 Marcin Copik
//  Copyright (c) 2016 Hartmut Kaiser
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// hpxinspect:nodeprecatedinclude:boost/ref.hpp
// hpxinspect:nodeprecatedname:boost::reference_wrapper

#if !defined(HPX_PARALLEL_EXECUTOR_PARAMETERS)
#define HPX_PARALLEL_EXECUTOR_PARAMETERS

#include <hpx/config.hpp>
#include <hpx/parallel/config/inline_namespace.hpp>
#include <hpx/parallel/executors/executor_parameter_traits.hpp>
#include <hpx/runtime/serialization/base_object.hpp>
#include <hpx/traits/is_executor_parameters.hpp>
#include <hpx/util/decay.hpp>
#include <hpx/util/detail/pack.hpp>

#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/ref.hpp>

#include <cstddef>
#include <functional>
#include <type_traits>
#include <utility>
#include <vector>

namespace hpx { namespace parallel { HPX_INLINE_NAMESPACE(v3)
{
    namespace detail
    {
        /// \cond NOINTERNAL
        template <bool ... Flags>
        struct parameters_type_counter;

        template <>
        struct parameters_type_counter<>
        {
            static HPX_CONSTEXPR_OR_CONST int value = 0;
        };

        /// Return the number of parameters which are true
        template <bool Flag1, bool ... Flags>
        struct parameters_type_counter<Flag1, Flags...>
        {
            static HPX_CONSTEXPR_OR_CONST int value =
                Flag1 + parameters_type_counter<Flags...>::value;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T>
        struct unwrapper : T
        {
            // default constructor is needed for serialization purposes
            unwrapper() : T() {}

            // generic poor-man's forwarding constructor
            template <typename U>
            unwrapper(U && u) : T(std::forward<U>(u)) {}
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T, typename Wrapper, typename Enable = void>
        struct maximal_number_of_chunks_call_helper
        {
            maximal_number_of_chunks_call_helper(Wrapper&) {}
        };

        template <typename T, typename Wrapper>
        struct maximal_number_of_chunks_call_helper<T, Wrapper,
            typename std::enable_if<
                has_maximal_number_of_chunks<T>::value
            >::type>
        {
            maximal_number_of_chunks_call_helper(Wrapper& wrap)
              : wrap_(wrap)
            {}

            template <typename Executor>
            HPX_FORCEINLINE std::size_t maximal_number_of_chunks(
                Executor && exec, std::size_t cores)
            {
                return wrap_.get().maximal_number_of_chunks(
                    std::forward<Executor>(exec), cores);
            }

        private:
            Wrapper& wrap_;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T, typename Wrapper, typename Enable = void>
        struct get_chunk_size_call_helper
        {
            get_chunk_size_call_helper(Wrapper&) {}
        };

        template <typename T, typename Wrapper>
        struct get_chunk_size_call_helper<T, Wrapper,
            typename std::enable_if<has_get_chunk_size<T>::value>::type>
        {
            get_chunk_size_call_helper(Wrapper& wrap)
              : wrap_(wrap)
            {}

            template <typename Executor, typename F>
            HPX_FORCEINLINE std::size_t get_chunk_size(Executor && exec, F && f,
                std::size_t num_tasks)
            {
                return wrap_.get().get_chunk_size(std::forward<Executor>(exec),
                    std::forward<F>(f), num_tasks);
            }

        private:
            Wrapper& wrap_;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T, typename Wrapper, typename Enable = void>
        struct mark_begin_execution_call_helper
        {
            mark_begin_execution_call_helper(Wrapper&) {}
        };

        template <typename T, typename Wrapper>
        struct mark_begin_execution_call_helper<T, Wrapper,
            typename std::enable_if<has_mark_begin_execution<T>::value>::type>
        {
            mark_begin_execution_call_helper(Wrapper& wrap)
              : wrap_(wrap)
            {}

            HPX_FORCEINLINE void mark_begin_execution()
            {
                wrap_.get().mark_begin_execution();
            }

        private:
            Wrapper& wrap_;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T, typename Wrapper, typename Enable = void>
        struct mark_end_execution_call_helper
        {
            mark_end_execution_call_helper(Wrapper&) {}
        };

        template <typename T, typename Wrapper>
        struct mark_end_execution_call_helper<T, Wrapper,
            typename std::enable_if<has_mark_begin_execution<T>::value>::type>
        {
            mark_end_execution_call_helper(Wrapper& wrap)
              : wrap_(wrap)
            {}

            HPX_FORCEINLINE void mark_end_execution()
            {
                wrap_.get().mark_end_execution();
            }

        private:
            Wrapper& wrap_;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T, typename Wrapper, typename Enable = void>
        struct processing_units_count_call_helper
        {
            processing_units_count_call_helper(Wrapper&) {}
        };

        template <typename T, typename Wrapper>
        struct processing_units_count_call_helper<T, Wrapper,
            typename std::enable_if<
                has_processing_units_count<T>::value
            >::type>
        {
            processing_units_count_call_helper(Wrapper& wrap)
              : wrap_(wrap)
            {}

            HPX_FORCEINLINE std::size_t processing_units_count()
            {
                return wrap_.get().processing_units_count();
            }

        private:
            Wrapper& wrap_;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T, typename Wrapper, typename Enable = void>
        struct reset_thread_distribution_call_helper
        {
            reset_thread_distribution_call_helper(Wrapper&) {}
        };

        template <typename T, typename Wrapper>
        struct reset_thread_distribution_call_helper<T, Wrapper,
            typename std::enable_if<
                has_reset_thread_distribution<T>::value
            >::type>
        {
            reset_thread_distribution_call_helper(Wrapper& wrap)
              : wrap_(wrap)
            {}

            template <typename Executor>
            HPX_FORCEINLINE void reset_thread_distribution(Executor && exec)
            {
                wrap_.get().reset_thread_distribution(
                    std::forward<Executor>(exec));
            }

        private:
            Wrapper& wrap_;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T>
        struct base_member_helper
        {
            base_member_helper(T && t)
              : member_(std::move(t))
            {}

            T member_;
        };

        ///////////////////////////////////////////////////////////////////////
        template <typename T>
        struct unwrapper< ::boost::reference_wrapper<T> >
          : base_member_helper<boost::reference_wrapper<T> >
          , maximal_number_of_chunks_call_helper<T, boost::reference_wrapper<T> >
          , get_chunk_size_call_helper<T, boost::reference_wrapper<T> >
          , mark_begin_execution_call_helper<T, boost::reference_wrapper<T> >
          , mark_end_execution_call_helper<T, boost::reference_wrapper<T> >
          , processing_units_count_call_helper<T, boost::reference_wrapper<T> >
          , reset_thread_distribution_call_helper<T, boost::reference_wrapper<T> >
        {
            typedef boost::reference_wrapper<T> wrapper_type;

            unwrapper(wrapper_type wrapped_param)
              : base_member_helper<wrapper_type>(std::move(wrapped_param))
              , maximal_number_of_chunks_call_helper<T, wrapper_type>(this->member_)
              , get_chunk_size_call_helper<T, wrapper_type>(this->member_)
              , mark_begin_execution_call_helper<T, wrapper_type>(this->member_)
              , mark_end_execution_call_helper<T, wrapper_type>(this->member_)
              , processing_units_count_call_helper<T, wrapper_type>(this->member_)
              , reset_thread_distribution_call_helper<T, wrapper_type>(this->member_)
            {}
        };

        template <typename T>
        struct unwrapper< ::std::reference_wrapper<T> >
          : base_member_helper<std::reference_wrapper<T> >
          , maximal_number_of_chunks_call_helper<T, std::reference_wrapper<T> >
          , get_chunk_size_call_helper<T, std::reference_wrapper<T> >
          , mark_begin_execution_call_helper<T, std::reference_wrapper<T> >
          , mark_end_execution_call_helper<T, std::reference_wrapper<T> >
          , processing_units_count_call_helper<T, std::reference_wrapper<T> >
          , reset_thread_distribution_call_helper<T, std::reference_wrapper<T> >
        {
            typedef std::reference_wrapper<T> wrapper_type;

            unwrapper(wrapper_type wrapped_param)
              : base_member_helper<wrapper_type>(std::move(wrapped_param))
              , maximal_number_of_chunks_call_helper<T, wrapper_type>(this->member_)
              , get_chunk_size_call_helper<T, wrapper_type>(this->member_)
              , mark_begin_execution_call_helper<T, wrapper_type>(this->member_)
              , mark_end_execution_call_helper<T, wrapper_type>(this->member_)
              , processing_units_count_call_helper<T, wrapper_type>(this->member_)
              , reset_thread_distribution_call_helper<T, wrapper_type>(this->member_)
            {}
        };

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

#define HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY(func)                       \
    static_assert(                                                            \
        parameters_type_counter<                                              \
            BOOST_PP_CAT(hpx::parallel::v3::detail::has_, func)<              \
                typename hpx::util::decay_unwrap<Params>::type>::value...     \
        >::value <= 1,                                                        \
        "Passing more than one executor parameters type exposing "            \
            BOOST_PP_STRINGIZE(func) " is not possible")                      \
    /**/

#if defined(HPX_MSVC) && HPX_MSVC < 1900
// for MSVC 12 disable: warning C4520: '...' : multiple default constructors specified
#pragma warning(push)
#pragma warning(disable: 4520)
#endif

        template <typename ... Params>
        struct executor_parameters : public unwrapper<Params>...
        {
            static_assert(
                hpx::util::detail::all_of<
                    hpx::traits::is_executor_parameters<Params>...
                >::value,
                "All passed parameters must be a proper executor parameters "
                "objects"
            );
            static_assert(sizeof...(Params) >= 2,
                "This type is meant to be used with at least 2 parameters "
                "objects");

            HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY(get_chunk_size);
            HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY(mark_begin_execution);
            HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY(mark_end_execution);
            HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY(processing_units_count);
            HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY(maximal_number_of_chunks);
            HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY(reset_thread_distribution);

            executor_parameters()
              : unwrapper<Params>()...
            {}

            template <typename ... Params_, typename T =
                typename std::enable_if<
                    hpx::util::detail::pack<Params...>::size ==
                        hpx::util::detail::pack<Params_...>::size
                >::type>
            executor_parameters(Params_ &&... params)
              : unwrapper<Params>(std::forward<Params_>(params))...
            {}

        private:
            friend class hpx::serialization::access;

            template <typename Archive>
            void serialize(Archive & ar, const unsigned int version)
            {
                int const sequencer[] = {
                    (ar & serialization::base_object<Params>(*this), 0)..., 0
                };
                (void)sequencer;
            }
        };

#undef HPX_STATIC_ASSERT_ON_PARAMETERS_AMBIGUITY

        /// \endcond
    }

#if defined(HPX_MSVC) && HPX_MSVC < 1900
#pragma warning(pop)
#endif

    ///////////////////////////////////////////////////////////////////////////
    template <typename ... Params>
    struct executor_parameters_join
    {
        typedef detail::executor_parameters<
                typename hpx::util::decay<Params>::type...
            > type;
    };

    template <typename ... Params>
    HPX_FORCEINLINE
    typename executor_parameters_join<Params...>::type
    join_executor_parameters(Params &&... params)
    {
        typedef
            typename executor_parameters_join<Params...>::type
            joined_params;
        return joined_params(std::forward<Params>(params)...);
    }

    ///////////////////////////////////////////////////////////////////////////
    template <typename Param>
    struct executor_parameters_join<Param>
    {
        typedef Param type;
    };

    template <typename Param>
    HPX_FORCEINLINE
    Param && join_executor_parameters(Param && param)
    {
        return std::forward<Param>(param);
    }
}}}

#endif

max_stars_repo_name: brycelelbach/hpx

max_issues_repo_name: brycelelbach/hpx

max_forks_repo_name: brycelelbach/hpx


text: #include <boost/compute/algorithm/equal.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
////////////////////////////////////////////////////////////////////////////////
//  Copyright (c) 2019 Prashant K. Jha
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////

#ifndef UTILS_RANDOM_DIST_H
#define UTILS_RANDOM_DIST_H

#include <boost/random.hpp>
#include <random>

#include "libmesh/parallel.h"

#include "utilIO.hpp"

// boost method
//typedef boost::mt19937 RandGen;
//typedef boost::lognormal_distribution<> LogNormalDist;
//typedef boost::uniform_real<> UniformDist;
//typedef boost::normal_distribution<> NormalDist;

typedef std::mt19937 RandGenerator;
typedef std::lognormal_distribution<> LogNormalDistribution;
typedef std::uniform_real_distribution<> UniformDistribution;
typedef std::normal_distribution<> NormalDistribution;

namespace util {

inline RandGenerator get_rd_gen(int &seed) {

  //return RandGenerator();

  if (seed < 0) {
    std::random_device rd;
    seed = rd();
  }

  return RandGenerator(seed);
}

inline std::default_random_engine get_rd_engine(int &seed) {

  //return std::default_random_engine();

  if (seed < 0) {
    std::random_device rd;
    seed = rd();
  }

  return std::default_random_engine(seed);
}

inline double transform_to_normal_dist(double mean, double std, double sample) {
  return std * sample + mean;
}

inline double transform_to_uniform_dist(double min, double max, double sample) {
  return min + sample * (max - min);
}

template<class T>
class DistributionSample {
public:
  DistributionSample(double arg1, double arg2, int seed = -1)
      : d_seed(seed), d_gen(get_rd_gen(seed)), d_dist(arg1, arg2){};

  DistributionSample() : d_seed(-1){};

  void init(double arg1, double arg2, int seed = -1) {

    d_seed = seed;
    d_gen = RandGenerator(get_rd_gen(seed));
    d_dist = T(arg1, arg2);
  }

  double operator()() {
    return d_dist(d_gen);
  }

  // not implemented for this
  void debug_out(const std::string &filename) {
    return;
  }

  int d_seed;
  RandGenerator d_gen;
  T d_dist;
};

template<class T>
class DistributionSampleParallel {
public:
  DistributionSampleParallel(double arg1, double arg2,
                             libMesh::Parallel::Communicator *comm,
                             int seed = -1,
                             unsigned int sample_size = 1000)
      : d_seed(seed), d_curSample(0), d_sampleSize(sample_size),
        d_gen(get_rd_gen(seed)), d_dist(arg1, arg2), d_procRank(0),
        d_procSize(0), d_comm_p(comm) {

    if (comm) {
      d_procRank = d_comm_p->rank();
      d_procSize = d_comm_p->size();
    }

    d_samples.reserve(d_sampleSize);
    if (d_procRank == 0)
      d_samples.resize(d_sampleSize);

    update();
  };

  DistributionSampleParallel()
      : d_seed(-1), d_curSample(0), d_sampleSize(0), d_procRank(0),
        d_procSize(0), d_comm_p(nullptr){};

  void init(double arg1, double arg2,
            libMesh::Parallel::Communicator *comm,
            int seed = -1,
            unsigned int sample_size = 1000) {

    d_seed = seed;
    d_curSample = 0;
    d_sampleSize = sample_size;
    d_gen = RandGenerator(get_rd_gen(seed));
    d_dist = T(arg1, arg2);
    d_comm_p = comm;

    if (comm) {
      d_procRank = d_comm_p->rank();
      d_procSize = d_comm_p->size();
    }

    d_samples.reserve(d_sampleSize);
    if (d_procRank == 0)
      d_samples.resize(d_sampleSize);

    update();
  }

  double operator()() {
    if (d_curSample < d_sampleSize) {
      return d_samples[d_curSample++];
    } else {
      update();
      return d_samples[d_curSample++];
    }
  }

  void update() {

    d_curSample = 0;
    if (d_procRank == 0) {
      for (unsigned int i = 0; i < d_sampleSize; i++)
        d_samples[i] = d_dist(d_gen);
    } else {
      d_samples.resize(0);
    }

    d_comm_p->allgather(d_samples);
    if (d_samples.size() != d_sampleSize)
      libmesh_error_msg("Error collecting samples");
  }

  void debug_out(const std::string &filename) {
    util::io::printFile(filename + "_" + std::to_string(d_procRank) + ".txt", d_samples, 0, " ");
  }

  int d_seed;
  unsigned int d_curSample;
  unsigned int d_sampleSize;
  RandGenerator d_gen;
  T d_dist;
  unsigned int d_procRank;
  unsigned int d_procSize;
  libMesh::Parallel::Communicator *d_comm_p;
  std::vector<double> d_samples;
};

} // namespace util

#endif // UTILS_RANDOM_DIST_H


text:
#pragma once

#include <polyfem/Problem.hpp>
#include <polyfem/ExpressionValue.hpp>

#include <vector>
#include <Eigen/Dense>

namespace polyfem
{
	class GenericTensorProblem: public Problem
	{
	public:
		GenericTensorProblem(const std::string &name);

		void rhs(const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;
		bool is_rhs_zero() const override { return fabs(rhs_.maxCoeff())<1e-10 && fabs(rhs_.minCoeff())<1e-10; }

		void bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;
		void neumann_bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;

		bool has_exact_sol() const override { return false; }
		bool is_scalar() const override { return false; }

		void set_parameters(const json &params) override;

		bool is_dimention_dirichet(const int tag, const int dim) const override;
		bool all_dimentions_dirichelt() const override { return all_dimentions_dirichelt_; }

		// bool is_mixed() const override { return is_mixed_; }
	private:
		bool all_dimentions_dirichelt_ = true;
		// bool is_mixed_ = false;

		std::vector<Eigen::Matrix<ExpressionValue, 1, 3, Eigen::RowMajor>> forces_;
		std::vector<Eigen::Matrix<ExpressionValue, 1, 3, Eigen::RowMajor>> displacements_;

		std::vector<Eigen::Matrix<bool, 1, 3, Eigen::RowMajor>> dirichelt_dimentions_;

		Eigen::Matrix<double, 1, 3, Eigen::RowMajor> rhs_;
		bool is_all_;
	};

	class GenericScalarProblem: public Problem
	{
	public:
		GenericScalarProblem(const std::string &name);

		void rhs(const std::string &formulation, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;
		bool is_rhs_zero() const override { return fabs(rhs_) < 1e-10; }

		void bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;
		void neumann_bc(const Mesh &mesh, const Eigen::MatrixXi &global_ids, const Eigen::MatrixXd &uv, const Eigen::MatrixXd &pts, const double t, Eigen::MatrixXd &val) const override;

		bool has_exact_sol() const override { return false; }
		bool is_scalar() const override { return true; }

		void set_parameters(const json &params) override;

	private:
		std::vector<Eigen::Matrix<ExpressionValue, 1, 1, Eigen::RowMajor>> neumann_;
		std::vector<Eigen::Matrix<ExpressionValue, 1, 1, Eigen::RowMajor>> dirichlet_;

		double rhs_;
		bool is_all_;
	};
}

max_stars_repo_name: ldXiao/polyfem

max_issues_repo_name: ldXiao/polyfem

max_forks_repo_name: ldXiao/polyfem


text:
#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>

#include <iostream>
#include <string>
#include <vector>

namespace client
{
    namespace x3 = boost::spirit::x3;
    namespace ascii = boost::spirit::x3::ascii;

    ///////////////////////////////////////////////////////////////////////////
    //  Our number list parser
    ///////////////////////////////////////////////////////////////////////////
    template <typename Iterator>
    int parse_number(Iterator first, Iterator last)
    {
        using x3::int_;
        using x3::char_;
        using x3::phrase_parse;
        using ascii::space;
        using x3::parse;

        int value;
        std::vector<int> values;
        phrase_parse(
            first,                          // Start Iterator
            last,                           // End Iterator
            int_,
            space,                          // The Skip-Parser
            value
        );

        auto identifier = +char_("a-zA-Z0-9_");
        std::string t = "aaoeu_123_123";
        std::string result;
        parse(t.begin(), t.end(), identifier, result);

        std::cout << "Result: " << result << std::endl;

        return value;
    }
}

////////////////////////////////////////////////////////////////////////////
//  Main program
////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::string str = "12345";
    if (client::parse_number(str.begin(), str.end()) == 12345)
    {
      return 0;
    }
    else
    {
      return -1;
    }
}

ext: cxx


text:
#pragma once

#include <nano/lib/numbers.hpp>
#include <nano/lib/utility.hpp>
#include <nano/secure/common.hpp>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index_container.hpp>

#include <memory>
#include <unordered_set>
#include <vector>

namespace nano
{
class ledger;
class node_config;
class transaction;

/** Track online representatives and trend online weight */
class online_reps final
{
public:
	online_reps (nano::ledger & ledger_a, nano::node_config const & config_a);
	/** Add voting account \p rep_account to the set of online representatives */
	void observe (nano::account const & rep_account);
	/** Called periodically to sample online weight */
	void sample ();
	/** Returns the trended online stake */
	nano::uint128_t trended () const;
	/** Returns the current online stake */
	nano::uint128_t online () const;
	/** Returns the quorum required for confirmation*/
	nano::uint128_t delta () const;
	/** List of online representatives, both the currently sampling ones and the ones observed in the previous sampling period */
	std::vector<nano::account> list ();
	void clear ();
	static unsigned constexpr online_weight_quorum = 67;

private:
	class rep_info
	{
	public:
		std::chrono::steady_clock::time_point time;
		nano::account account;
	};
	class tag_time
	{
	};
	class tag_account
	{
	};
	nano::uint128_t calculate_trend (nano::transaction &) const;
	nano::uint128_t calculate_online () const;
	mutable nano::mutex mutex;
	nano::ledger & ledger;
	nano::node_config const & config;
	boost::multi_index_container<rep_info,
	boost::multi_index::indexed_by<
	boost::multi_index::ordered_non_unique<boost::multi_index::tag<tag_time>,
	boost::multi_index::member<rep_info, std::chrono::steady_clock::time_point, &rep_info::time>>,
	boost::multi_index::hashed_unique<boost::multi_index::tag<tag_account>,
	boost::multi_index::member<rep_info, nano::account, &rep_info::account>>>>
	reps;
	nano::uint128_t trended_m;
	nano::uint128_t online_m;
	nano::uint128_t minimum;

	friend class election_DISABLED_quorum_minimum_update_weight_before_quorum_checks_Test;
	friend std::unique_ptr<container_info_component> collect_container_info (online_reps & online_reps, std::string const & name);
};

std::unique_ptr<container_info_component> collect_container_info (online_reps & online_reps, std::string const & name);
}

max_stars_repo_name: Sukhmai/nano-node

max_issues_repo_name: Sukhmai/nano-node

max_forks_repo_name: Sukhmai/nano-node


text:
#include <iostream>
#include <string>
#include <memory>
#include <type_traits>
#include <boost/asio.hpp>

struct BinaryOstream{
	//BinaryOstream():
	//	m_buffer(std::make_shared<boost::asio::streambuf>() ),
	//	m_stream(m_buffer.get()){
	//}

	template<class T> typename std::enable_if<std::is_arithmetic<T>::value>::type  put(T data) {
	   m_stream.write(reinterpret_cast<const char*>(&data), sizeof(data));
	}
	void put(const char* data) {
		m_stream << data;
	}
	void put(const std::string& data) {
		m_stream << data;
	}
	bool finalize(){
		m_stream.flush();
		return !(m_stream.fail());
	}

	std::shared_ptr<boost::asio::streambuf> get_buffer(){
		return m_buffer;
	}
	size_t get_size() const{
		return m_buffer->size();
	}
private:
	std::shared_ptr<boost::asio::streambuf> 	m_buffer{std::make_shared<boost::asio::streambuf>() };
	std::ostream 		 						m_stream{m_buffer.get()};
};

struct BinaryIstream{

	BinaryIstream():
		m_buffer(std::make_shared<boost::asio::streambuf>() ),
		m_stream(m_buffer.get()){
	}

	BinaryIstream(std::shared_ptr<boost::asio::streambuf> buffer):
			m_buffer(buffer ),
			m_stream(m_buffer.get()){
		}

	template<class T> typename std::enable_if<std::is_arithmetic<T>::value>::type  get(T &data) {
	   m_stream.read(reinterpret_cast<char*>(&data), sizeof(data));
	}
	void get(char* data) {
		m_stream >> data;
	}
	void get(std::string& data) {
		m_stream >> data;
	}
	bool finalize(){
		return m_stream.good();
	}
	std::shared_ptr<boost::asio::streambuf> get_buffer(){
			return m_buffer;
		}
	size_t get_size() const{
		return m_buffer->size();
	}
private:
	std::shared_ptr<boost::asio::streambuf> 		m_buffer;
	std::istream 		 							m_stream;
};

int main(int, char*[])
{
	BinaryOstream os;
	int i1 = 1;
	os.put(i1);
	float f1 = 2.4;
	os.put(f1);
	os.put("123456");

	bool status = os.finalize();

	BinaryIstream is(os.get_buffer());
	int i2 =0;
	is.get(i2);
	float f2 = 0.0;
	is.get(f2);
	std::string s;
	is.get(s);
	status = is.finalize();

	std::cout <<i2 <<":"<< f2 <<":"<<s<<std::endl;

    return 0;
}

ext: cpp


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_PhotonMaterial.hpp
//! \author Alex Robinson
//! \brief  Photon material class declaration
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_PHOTON_MATERIAL_HPP
#define MONTE_CARLO_PHOTON_MATERIAL_HPP

// Boost Includes
#include <boost/unordered_map.hpp>

// Trilinos Includes
#include "Teuchos_RCP.hpp"
#include "Teuchos_Array.hpp"

// FRENSIE Includes
#include "MonteCarlo_ModuleTraits.hpp"
#include "MonteCarlo_Photoatom.hpp"
#include "Utility_Tuple.hpp"

namespace MonteCarlo{

//! The photon material class
class PhotonMaterial
{

private:

  // Typedef for Teuchos ScalarTraits
  typedef Teuchos::ScalarTraits<double> ST;

public:

  //! Typedef for photoatom name map
  typedef boost::unordered_map<std::string,Teuchos::RCP<Photoatom> >
  PhotoatomNameMap;

  //! Constructor
  PhotonMaterial( const ModuleTraits::InternalMaterialHandle id,
		  const double density,
		  const PhotoatomNameMap& photoatom_name_map,
		  const Teuchos::Array<double>& photoatom_fractions,
		  const Teuchos::Array<std::string>& photoatom_names );

  //! Destructor
  ~PhotonMaterial()
  { /* ... */ }

  //! Return the material id
  ModuleTraits::InternalMaterialHandle getId() const;

  //! Return the number density (atom/b-cm)
  double getNumberDensity() const;

  //! Return the macroscopic total cross section (1/cm)
  double getMacroscopicTotalCrossSection( const double energy ) const;

  //! Return the macroscopic absorption cross section (1/cm)
  double getMacroscopicAbsorptionCrossSection( const double energy ) const;

  //! Return the survival probability
  double getSurvivalProbability( const double energy ) const;

  //! Return the macroscopic cross section (1/cm) for a specific reaction
  double getMacroscopicReactionCrossSection(
				const double energy,
				const PhotoatomicReactionType reaction ) const;

  //! Return the macroscopic cross section (1/cm) for a specific reaction
  double getMacroscopicReactionCrossSection(
			       const double energy,
			       const PhotonuclearReactionType reaction ) const;

  //! Collide with a photon
  void collideAnalogue( PhotonState& photon, ParticleBank& bank ) const;

  //! Collide with a photon and survival bias
  void collideSurvivalBias( PhotonState& photon, ParticleBank& bank ) const;

private:

  // Get the atomic weight from an atom pointer
  static double getAtomicWeight(
	    const Utility::Pair<double,Teuchos::RCP<const Photoatom> >& pair );

  // Sample the atom that is collided with
  unsigned sampleCollisionAtom( const double energy ) const;

  // The material id
  ModuleTraits::InternalMaterialHandle d_id;

  // The number density of the atoms of the material
  double d_number_density;

  // The atoms that make up the material
  Teuchos::Array<Utility::Pair<double,Teuchos::RCP<const Photoatom> > >
  d_atoms;
};

} // end MonteCarlo namespace

#endif // end MONTE_CARLO_PHOTON_MATERIAL_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_PhotonMaterial.hpp
//---------------------------------------------------------------------------//


text:
/* Boost interval/transc.hpp template implementation file
 *
 * Copyright 2000 Jens Maurer
 * Copyright 2002 Hervé Brönnimann, Guillaume Melquiond, Sylvain Pion
 *
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or
 * copy at http://www.boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_NUMERIC_INTERVAL_TRANSC_HPP
#define BOOST_NUMERIC_INTERVAL_TRANSC_HPP

#include <boost/config.hpp>
#include <boost/numeric/interval/detail/interval_prototype.hpp>
#include <boost/numeric/interval/detail/bugs.hpp>
#include <boost/numeric/interval/detail/test_input.hpp>
#include <boost/numeric/interval/rounding.hpp>
#include <boost/numeric/interval/constants.hpp>
#include <boost/numeric/interval/arith.hpp>
#include <boost/numeric/interval/arith2.hpp>
#include <algorithm>

namespace boost {
namespace numeric {

template<class T, class Policies> inline
interval<T, Policies> exp(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  return I(rnd.exp_down(x.lower()), rnd.exp_up(x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> log(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x) ||
      !interval_lib::user::is_pos(x.upper()))
    return I::empty();
  typename Policies::rounding rnd;
  typedef typename Policies::checking checking;
  T l = !interval_lib::user::is_pos(x.lower())
             ? checking::neg_inf() : rnd.log_down(x.lower());
  return I(l, rnd.log_up(x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> cos(const interval<T, Policies>& x)
{
  if (interval_lib::detail::test_input(x))
    return interval<T, Policies>::empty();
  typename Policies::rounding rnd;
  typedef interval<T, Policies> I;
  typedef typename interval_lib::unprotect<I>::type R;

  // get lower bound within [0, pi]
  const R pi2 = interval_lib::pi_twice<R>();
  R tmp = fmod((const R&)x, pi2);
  if (width(tmp) >= pi2.lower())
    return I(static_cast<T>(-1), static_cast<T>(1), true); // we are covering a full period
  if (tmp.lower() >= interval_lib::constants::pi_upper<T>())
    return -cos(tmp - interval_lib::pi<R>());
  T l = tmp.lower();
  T u = tmp.upper();

  BOOST_USING_STD_MIN();
  // separate into monotone subintervals
  if (u <= interval_lib::constants::pi_lower<T>())
    return I(rnd.cos_down(u), rnd.cos_up(l), true);
  else if (u <= pi2.lower())
    return I(static_cast<T>(-1), rnd.cos_up(min BOOST_PREVENT_MACRO_SUBSTITUTION(rnd.sub_down(pi2.lower(), u), l)), true);
  else
    return I(static_cast<T>(-1), static_cast<T>(1), true);
}

template<class T, class Policies> inline
interval<T, Policies> sin(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  typedef typename interval_lib::unprotect<I>::type R;
  I r = cos((const R&)x - interval_lib::pi_half<R>());
  (void)&rnd;
  return r;
}

template<class T, class Policies> inline
interval<T, Policies> tan(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  typedef typename interval_lib::unprotect<I>::type R;

  // get lower bound within [-pi/2, pi/2]
  const R pi = interval_lib::pi<R>();
  R tmp = fmod((const R&)x, pi);
  const T pi_half_d = interval_lib::constants::pi_half_lower<T>();
  if (tmp.lower() >= pi_half_d)
    tmp -= pi;
  if (tmp.lower() <= -pi_half_d || tmp.upper() >= pi_half_d)
    return I::whole();
  return I(rnd.tan_down(tmp.lower()), rnd.tan_up(tmp.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> asin(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x)
     || x.upper() < static_cast<T>(-1) || x.lower() > static_cast<T>(1))
    return I::empty();
  typename Policies::rounding rnd;
  T l = (x.lower() <= static_cast<T>(-1))
             ? -interval_lib::constants::pi_half_upper<T>()
             : rnd.asin_down(x.lower());
  T u = (x.upper() >= static_cast<T>(1) )
             ?  interval_lib::constants::pi_half_upper<T>()
             : rnd.asin_up  (x.upper());
  return I(l, u, true);
}

template<class T, class Policies> inline
interval<T, Policies> acos(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x)
     || x.upper() < static_cast<T>(-1) || x.lower() > static_cast<T>(1))
    return I::empty();
  typename Policies::rounding rnd;
  T l = (x.upper() >= static_cast<T>(1) )
          ? static_cast<T>(0)
          : rnd.acos_down(x.upper());
  T u = (x.lower() <= static_cast<T>(-1))
          ? interval_lib::constants::pi_upper<T>()
          : rnd.acos_up  (x.lower());
  return I(l, u, true);
}

template<class T, class Policies> inline
interval<T, Policies> atan(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  return I(rnd.atan_down(x.lower()), rnd.atan_up(x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> sinh(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  return I(rnd.sinh_down(x.lower()), rnd.sinh_up(x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> cosh(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  if (interval_lib::user::is_neg(x.upper()))
    return I(rnd.cosh_down(x.upper()), rnd.cosh_up(x.lower()), true);
  else if (!interval_lib::user::is_neg(x.lower()))
    return I(rnd.cosh_down(x.lower()), rnd.cosh_up(x.upper()), true);
  else
    return I(static_cast<T>(1), rnd.cosh_up(-x.lower() > x.upper() ? x.lower() : x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> tanh(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  return I(rnd.tanh_down(x.lower()), rnd.tanh_up(x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> asinh(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x))
    return I::empty();
  typename Policies::rounding rnd;
  return I(rnd.asinh_down(x.lower()), rnd.asinh_up(x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> acosh(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x) || x.upper() < static_cast<T>(1))
    return I::empty();
  typename Policies::rounding rnd;
  T l = x.lower() <= static_cast<T>(1) ? static_cast<T>(0) : rnd.acosh_down(x.lower());
  return I(l, rnd.acosh_up(x.upper()), true);
}

template<class T, class Policies> inline
interval<T, Policies> atanh(const interval<T, Policies>& x)
{
  typedef interval<T, Policies> I;
  if (interval_lib::detail::test_input(x)
      || x.upper() < static_cast<T>(-1) || x.lower() > static_cast<T>(1))
    return I::empty();
  typename Policies::rounding rnd;
  typedef typename Policies::checking checking;
  T l = (x.lower() <= static_cast<T>(-1))
             ? checking::neg_inf() : rnd.atanh_down(x.lower());
  T u = (x.upper() >= static_cast<T>(1) )
             ? checking::pos_inf() : rnd.atanh_up  (x.upper());
  return I(l, u, true);
}

} // namespace numeric
} // namespace boost

#endif // BOOST_NUMERIC_INTERVAL_TRANSC_HPP


text: #include <boost/geometry/strategies/default_length_result.hpp>


text:
#include <iostream>
#include <queue>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/thread.hpp>

#include "flag.hpp"

using namespace boost::asio;
using namespace std;

static const std::string s = "abcdefghijklmnopqrstuvwxyz"
        "ABCDEFGHIJKLMNOQPRSTUVWXYZ"
        "0123456789!@#$%^&*()-_+=\\|`~;:'\"<>,./?";

class Connection: public boost::enable_shared_from_this<Connection>,
                  private boost::noncopyable
{
public:
    Connection(io_service &ios): socket(ios), writtenMB(0), readMB(0) {}

    ~Connection()
    {
        std::cout << remoteIP << ":" << remotePort << " Written: "
                  << writtenMB << " Read: " << readMB << std::endl;
    }

    void start()
    {
        remoteIP = socket.remote_endpoint().address().to_string();
        remotePort = socket.remote_endpoint().port();

        startRead();
    }

    ip::tcp::socket &getSocket()
    {
        return socket;
    }

private:
    void startRead()
    {
        boost::asio::async_read(socket, buffer(read_buf, max_len),
                                boost::bind(&Connection::onRead,
                                            shared_from_this(),
                                            placeholders::error));
    }

    void onRead(const boost::system::error_code &ec)
    {
        if (ec)
        {
            std::cout << "onRead: " << ec.message() << std::endl;
            return;
        }

        readMB += 1;

        startRead();
    }

private:
    ip::tcp::socket socket;
    enum {max_len = 1024 * 64}; // 1MB
    char read_buf[max_len];

    size_t writtenMB;
    size_t readMB;

    std::string remoteIP;
    int remotePort;
};

class Server
{
public:
    typedef boost::shared_ptr<Connection> ConnectionPtr;

    Server(io_service &ios, const ip::tcp::endpoint &ep):
        ios_(ios), acceptor_(ios, ep)
    {
    }

    void startAccept()
    {
        new_connection.reset(new Connection(ios_));
        acceptor_.async_accept(new_connection->getSocket(),
                               boost::bind(&Server::onAccept, this,
                                           new_connection, placeholders::error));
    }

private:
    void onAccept(ConnectionPtr connection, const boost::system::error_code &ec)
    {
        if (!ec)
        {
            connection->start();
        }

        startAccept();
    }

private:
    ConnectionPtr new_connection;
    io_service &ios_;
    ip::tcp::acceptor acceptor_;
};

ip::tcp::endpoint makeEndpoint(const std::string& ip, int port)
{
    if (ip.empty())
        return ip::tcp::endpoint(ip::tcp::v4(), port);
    else
        return ip::tcp::endpoint(ip::address::from_string(ip), port);
}

int main(int argc, const char *argv[])
{
    Flag flag;
    flag.addOption("h", "", "listening ip");
    flag.addOption("p", "10001", "listening port");

    if (!flag.parse(argc, argv))
    {
        std::cout << flag.help() << std::endl;
        return -1;
    }

    std::string ip;
    int port;

    flag.getString("h", ip);
    flag.getInt("p", port);

    try
    {
        io_service ios;

        Server server(ios, makeEndpoint(ip, port));
        server.startAccept();

        ios.run();
    }
    catch (exception &e)
    {
        cerr << e.what() << endl;
    }

    return 0;
}


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <cerrno>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <memory>
#include <string>
#include <sstream>

#ifdef _WIN32
#include <process.h>
#include <windows.h>
#endif

#include <boost/program_options.hpp>

#include "flint/temporary-file.h"
#include "isd2csv.h"
#include "isdstrip.h"
#include "isdf/isdf.h"

namespace po = boost::program_options;

using namespace flint;

namespace {

bool ReadHeader(std::istream *is, char *header)
{
	is->read(header, sizeof(isdf::ISDFHeader));
	return is->good();
}

bool ReadDescriptions(std::uint32_t num_bytes_descs, std::istream *is, char *rest)
{
	is->read(rest, num_bytes_descs);
	return is->good();
}

bool CountColumns(const boost::filesystem::path &input, std::uint32_t *num_columns)
{
	boost::filesystem::ifstream ifs(input, std::ios::in|std::ios::binary);
	if (!ifs.is_open()) {
		std::cerr << "could not open input file: " << input << std::endl;
		return false;
	}
	std::unique_ptr<char[]> header(new char[sizeof(isdf::ISDFHeader)]);
	if (!ReadHeader(&ifs, header.get())) {
		std::cerr << "could not read header: " << input << std::endl;
		ifs.close();
		return false;
	}
	*num_columns = reinterpret_cast<isdf::ISDFHeader *>(header.get())->num_objs;
	ifs.close();
	return true;
}

int CallIsd2csv(const isd2csv::Option &option, const boost::filesystem::path &input, std::ostream *os)
{
	boost::filesystem::ifstream ifs(input, std::ios::in|std::ios::binary);
	if (!ifs) {
		std::cerr << "failed to open input file: " << input << std::endl;
		return EXIT_FAILURE;
	}
	int r = isd2csv::Convert(option, &ifs, os);
	ifs.close();
	return r;
}

template<typename TChar>
void PutQuotedPath(const TChar *path, std::ostringstream *bss)
{
	*bss << "\"";
	TChar c;
	while ( (c = *path++) ) {
		switch (c) {
		case '\\':
			*bss << "\\\\";
			break;
		default:
			*bss << c;
			break;
		}
	}
	*bss << "\"";
}

template<typename TChar>
void CreateScript(std::uint32_t num_columns,
				  const TChar *csv_path,
				  const char *output_path,
				  std::ostringstream *bss)
{
	unsigned int row = 1, col = 1;
	unsigned int w = 640, h = 480;

	num_columns -= 1; // excluding the first "time"
	if (num_columns >= 16) {
		row = col = 4;
		w *= 2;
		h *= 2;
	} else if (num_columns >= 9) {
		row = col = 3;
		w *= 2;
		h *= 2;
	} else if (num_columns >= 4) {
		row = col = 2;
	} else if (num_columns == 3) {
		row = 3;
		col = 1;
	} else if (num_columns == 2) {
		row = 2;
		col = 1;
	}

	*bss << "set datafile separator \",\"" << std::endl
		 << "set format y '%g'" << std::endl
		 << "set key autotitle columnhead" << std::endl
		 << "set terminal png size " << w << "," << h << std::endl;

	*bss << "set output ";
	PutQuotedPath(output_path, bss);
	*bss << std::endl;

	*bss << "set multiplot layout " << row << "," << col << " rowsfirst downwards" << std::endl;
	unsigned int n = row*col+1;
	for (unsigned int i=2;i<=n;i++) {
		*bss << "plot ";
		PutQuotedPath(csv_path, bss);
		*bss << " using 1:" << i << " axes x1y1 with lines" << std::endl;
	}
	*bss << "unset multiplot" << std::endl;
}

#ifdef _WIN32

// Windows

template<typename TChar>
int CallGnuplot(const char *gnuplot,
				std::uint32_t num_columns,
				const TChar *csv_path,
				const char *output_path)
{
	SECURITY_ATTRIBUTES saAttr;
	saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
	saAttr.bInheritHandle = TRUE;
	saAttr.lpSecurityDescriptor = nullptr;

	HANDLE hChildInRead, hChildInWrite;
	if (!CreatePipe(&hChildInRead, &hChildInWrite, &saAttr, 0)) {
		std::cerr << "could not create pipe" << std::endl;
		return EXIT_FAILURE;
	}
	if (!SetHandleInformation(hChildInWrite, HANDLE_FLAG_INHERIT, 0)) {
		std::cerr << "could not set handle information" << std::endl;
		CloseHandle(hChildInWrite);
		CloseHandle(hChildInRead);
		return EXIT_FAILURE;
	}

	STARTUPINFO siStartInfo;
	GetStartupInfo(&siStartInfo);
	siStartInfo.hStdInput = hChildInRead;
	siStartInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
	siStartInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
	siStartInfo.dwFlags |= STARTF_USESTDHANDLES;
	PROCESS_INFORMATION piProcInfo;
	ZeroMemory(&piProcInfo, sizeof(piProcInfo));
	bool b = CreateProcess(gnuplot,
						   nullptr,
						   nullptr,
						   nullptr,
						   TRUE,
						   0,
						   nullptr,
						   nullptr,
						   &siStartInfo,
						   &piProcInfo);
	if (!b) {
		std::cerr << "could not create process: " << GetLastError() << std::endl;
		// should follow GetLastError()
		CloseHandle(hChildInWrite);
		CloseHandle(hChildInRead);
		return EXIT_FAILURE;
	}
	CloseHandle(hChildInRead); // close unused read end

	std::ostringstream bss;
	CreateScript(num_columns, csv_path, output_path, &bss);
	const std::string &buf(bss.str());
	WriteFile(hChildInWrite, (LPCVOID)buf.c_str(), (DWORD)buf.size(), nullptr, nullptr);
	CloseHandle(hChildInWrite);

	WaitForSingleObject(piProcInfo.hProcess, INFINITE);
	DWORD s;
	bool r = GetExitCodeProcess(piProcInfo.hProcess, &s);
	CloseHandle(piProcInfo.hThread);
	CloseHandle(piProcInfo.hProcess);
	if (r) {
		if (s == STILL_ACTIVE) {
			return EXIT_FAILURE;
		} else if (s == 0) {
			return EXIT_SUCCESS;
		} else { // TODO
			return EXIT_FAILURE;
		}
	}
	return EXIT_FAILURE;
}

#elif defined(HAVE_POPEN)

// POSIX

template<typename TChar>
int CallGnuplot(const char *gnuplot,
				std::uint32_t num_columns,
				const TChar *csv_path,
				const char *output_path)
{
	FILE *fp = popen(gnuplot, "w");
	if (!fp) {
		std::cerr << "failed to popen: "  << gnuplot << std::endl;
		return EXIT_FAILURE;
	}
	std::ostringstream bss;
	CreateScript(num_columns, csv_path, output_path, &bss);
	auto buf = bss.str();
	int result = EXIT_SUCCESS;
	if (std::fwrite(buf.c_str(), buf.size(), 1, fp) <= 0) {
		std::cerr << "failed to write script into pipe" << std::endl;
		result = EXIT_FAILURE;
	}
	int r = pclose(fp);
	if (r == -1) {
		std::cerr << "failed to pclose: " << std::strerror(errno) << std::endl;
		result = EXIT_FAILURE;
	}
	return result;
}

#else
#error "unavailability of popen is fatal."
#endif

} // namespace

int main(int argc, char *argv[])
{
	po::options_description opts("options");
	po::positional_options_description popts;
	po::variables_map vm;
	std::string gnuplot, input_file, output_file;
	int print_help = 0;

	opts.add_options()
		("gnuplot", boost::program_options::value<std::string>(&gnuplot)->default_value("gnuplot"),
		 "Command for gnuplot")
		("ignore-prefixes,P", "Ignore variable prefixes")
		("ignore-units,U", "Ignore units")
		("help,h", "Show this message")
		("output,o", po::value<std::string>(&output_file), "Output file name")
		("input", po::value<std::string>(&input_file), "Input file name");
	popts.add("input", 1);

	try {
		po::store(po::command_line_parser(argc, argv).options(opts).positional(popts).run(), vm);
		po::notify(vm);
		if (vm.count("help")) print_help = 1;
		if (vm.count("output") == 0) print_help = 2;
		if (vm.count("input") == 0) print_help = 2;
	} catch (const po::error &) {
		print_help = 2;
	}
	if (print_help != 0) {
		std::cerr << "usage: isdplot [OPTIONS] PATH" << std::endl;
		std::cerr << opts << std::endl;
		return (print_help == 1) ? EXIT_SUCCESS : EXIT_FAILURE;
	}

	isd2csv::Option isd2csv_option;
	isd2csv_option.ignore_prefixes = (vm.count("ignore-prefixes") > 0);
	isd2csv_option.ignore_units = (vm.count("ignore-units") > 0);
	isd2csv_option.port = ""; // no progress report

	std::vector<std::uint32_t> cv;
	if (!isdstrip::ExtractConstantColumns(input_file.c_str(), nullptr, &cv))
		return EXIT_FAILURE;
	boost::filesystem::path input_path(input_file.c_str());
	std::unique_ptr<TemporaryFile> temp_file;
	if (!cv.empty()) { // create a stripped file
		temp_file.reset(new TemporaryFile);
		if (!temp_file->ofs()) {
			std::cerr << "failed to open temporary file: " << temp_file->path() << std::endl;
			return EXIT_FAILURE;
		}
		int r = isdstrip::Filter(input_file.c_str(), cv, &temp_file->ofs());
		temp_file->Close();
		if (r != EXIT_SUCCESS) {
			std::cerr << "failed to filter constant columns: " << r << std::endl;
			return r;
		}
		input_path = temp_file->path();
	}

	std::uint32_t num_columns = 0;
	if (!CountColumns(input_path, &num_columns)) {
		return EXIT_FAILURE;
	}
	if (num_columns == 0) {
		std::cerr << "there seems no variable columns in: " << input_file.c_str() << std::endl;
		return EXIT_FAILURE;
	}
	TemporaryFile csv_file;
	if (!csv_file.ofs()) {
		std::cerr << "could not create temporary path: " << csv_file.path() << std::endl;
		return EXIT_FAILURE;
	}
	int r = CallIsd2csv(isd2csv_option, input_path, &csv_file.ofs());
	csv_file.Close();
	if (r != EXIT_SUCCESS)
		return r;
	r = CallGnuplot(gnuplot.c_str(), num_columns, csv_file.path().c_str(), output_file.c_str());
	return r;
}

ext: cc

max_stars_repo_name: Abhisheknishant/Flint

max_issues_repo_name: Abhisheknishant/Flint

max_forks_repo_name: Abhisheknishant/Flint


text:
/**
 * @file   VolumeCubeRenderable.cpp
 * @author Sebastian Maisch <sebastian.maisch@uni-ulm.de>
 * @date   2015.08.19
 *
 * @brief  Implementation of a renderable used to determine starting and end positions for raycasting.
 */

#include "VolumeCubeRenderable.h"
#include "gfx/glrenderer/GPUProgram.h"
#include <boost/assign.hpp>

namespace cgu {

    /**
     *  Constructor.
     *  @param backProg the GPU program for rendering the back faces.
     *  @param drawProg the GPU program for drawing the volume
     */
    VolumeCubeRenderable::VolumeCubeRenderable(GPUProgram* backProg, GPUProgram* drawProg) :
        vBuffer(0),
        iBuffer(0),
        backProgram(backProg),
        backAttribBind(nullptr),
        drawProgram(drawProg),
        drawAttribBind(nullptr)
    {
        CreateVertexIndexBuffers();
    }

    /**
     *  Copy-Constructor.
     *  @param orig the original VolumeCubeRenderable
     */
    VolumeCubeRenderable::VolumeCubeRenderable(const VolumeCubeRenderable& orig) :
        vBuffer(0),
        iBuffer(0),
        backProgram(orig.backProgram),
        backAttribBind(nullptr),
        drawProgram(orig.drawProgram),
        drawAttribBind(nullptr)
    {
        CreateVertexIndexBuffers();
    }

    /**
     *  Move-Constructor.
     *  @param orig the original VolumeCubeRenderable
     */
    VolumeCubeRenderable::VolumeCubeRenderable(VolumeCubeRenderable&& orig) :
        vBuffer(orig.vBuffer),
        iBuffer(orig.iBuffer),
        backProgram(orig.backProgram),
        backAttribBind(std::move(orig.backAttribBind)),
        drawProgram(orig.drawProgram),
        drawAttribBind(std::move(orig.drawAttribBind))

    {
        orig.vBuffer = 0;
        orig.iBuffer = 0;
        orig.backProgram = nullptr;
        orig.drawProgram = nullptr;
    }

    /**
     *  Assignment operator.
     *  @param orig the original VolumeCubeRenderable
     *  @return the newly assigned VolumeCubeRenderable
     */
    VolumeCubeRenderable& VolumeCubeRenderable::operator=(const VolumeCubeRenderable& orig)
    {
        DeleteVertexIndexBuffers();
        backAttribBind = nullptr;
        drawAttribBind = nullptr;
        backProgram = orig.backProgram;
        drawProgram = orig.drawProgram;
        CreateVertexIndexBuffers();
        return *this;
    }

    /**
     *  Move-Assignment operator.
     *  @param orig the original VolumeCubeRenderable
     *  @return the newly assigned VolumeCubeRenderable
     */
    VolumeCubeRenderable& VolumeCubeRenderable::operator=(VolumeCubeRenderable&& orig)
    {
        DeleteVertexIndexBuffers();
        backAttribBind = orig.backAttribBind;
        orig.backAttribBind = nullptr;
        drawAttribBind = orig.drawAttribBind;
        orig.drawAttribBind = nullptr;
        backProgram = orig.backProgram;
        orig.backProgram = nullptr;
        drawProgram = orig.drawProgram;
        orig.drawProgram = nullptr;
        vBuffer = orig.vBuffer;
        orig.vBuffer = 0;
        iBuffer = orig.iBuffer;
        orig.iBuffer = 0;
        return *this;
    }

    /**
     *  Destructor.
     */
    VolumeCubeRenderable::~VolumeCubeRenderable()
    {
        DeleteVertexIndexBuffers();
    }

    /**
     *  Creates the vertex- and index-buffers and their vertex attribute bindings.
     */
    void VolumeCubeRenderable::CreateVertexIndexBuffers()
    {
        std::vector<VolumeCubeVertex> vertices;
        vertices.push_back(VolumeCubeVertex{ glm::vec4(0.0f, 0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 0.0f, 0.0f) });
        vertices.push_back(VolumeCubeVertex{ glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), glm::vec3(1.0f, 0.0f, 0.0f) });
        vertices.push_back(VolumeCubeVertex{ glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), glm::vec3(0.0f, 1.0f, 0.0f) });
        vertices.push_back(VolumeCubeVertex{ glm::vec4(1.0f, 1.0f, 0.0f, 1.0f), glm::vec3(1.0f, 1.0f, 0.0f) });
        vertices.push_back(VolumeCubeVertex{ glm::vec4(0.0f, 0.0f, 1.0f, 1.0f), glm::vec3(0.0f, 0.0f, 1.0f) });
        vertices.push_back(VolumeCubeVertex{ glm::vec4(1.0f, 0.0f, 1.0f, 1.0f), glm::vec3(1.0f, 0.0f, 1.0f) });
        vertices.push_back(VolumeCubeVertex{ glm::vec4(0.0f, 1.0f, 1.0f, 1.0f), glm::vec3(0.0f, 1.0f, 1.0f) });
        vertices.push_back(VolumeCubeVertex{ glm::vec4(1.0f, 1.0f, 1.0f, 1.0f), glm::vec3(1.0f, 1.0f, 1.0f) });

        OGL_CALL(glGenBuffers, 1, &vBuffer);
        OGL_CALL(glBindBuffer, GL_ARRAY_BUFFER, vBuffer);
        OGL_CALL(glBufferData, GL_ARRAY_BUFFER, 8 * sizeof(VolumeCubeVertex), vertices.data(), GL_STATIC_DRAW);

        unsigned int indexData[36] = {
            1, 0, 3, 3, 0, 2,
            4, 5, 6, 6, 5, 7,
            0, 1, 4, 4, 1, 5,
            3, 2, 7, 7, 2, 6,
            1, 3, 5, 5, 3, 7,
            0, 4, 2, 2, 4, 6
        };
        OGL_CALL(glGenBuffers, 1, &iBuffer);
        OGL_CALL(glBindBuffer, GL_ELEMENT_ARRAY_BUFFER, iBuffer);
        OGL_CALL(glBufferData, GL_ELEMENT_ARRAY_BUFFER, 36 * sizeof(unsigned int), indexData, GL_STATIC_DRAW);

        VertexAttributeBindings bindings;
        FillVertexAttributeBindings(*backProgram, bindings);
        backAttribBind = bindings[0];
        bindings.clear();
        FillVertexAttributeBindings(*drawProgram, bindings);
        drawAttribBind = bindings[0];
    }

    /**
     *  Deletes the vertex- and index-buffers.
     */
    void VolumeCubeRenderable::DeleteVertexIndexBuffers()
    {
        if (vBuffer != 0) {
            OGL_CALL(glDeleteBuffers, 1, &vBuffer);
            vBuffer = 0;
        }

        if (iBuffer != 0) {
            OGL_CALL(glDeleteBuffers, 1, &iBuffer);
            iBuffer = 0;
        }
    }

    /**
     *  Draws the volumes back faces.
     */
    void VolumeCubeRenderable::DrawBack() const
    {
        backProgram->UseProgram();
        Draw(backAttribBind);
    }

    /**
     *  Draws the volume.
     */
    void VolumeCubeRenderable::Draw() const
    {
        drawProgram->UseProgram();
        Draw(drawAttribBind);
    }

    /**
     *  Internal rendering method.
     *  @param attribBinding the vertex attribute bindings to use.
     */
    // ReSharper disable once CppMemberFunctionMayBeStatic
    void VolumeCubeRenderable::Draw(const GLVertexAttributeArray* attribBinding) const
    {
        attribBinding->EnableVertexAttributeArray();
        OGL_CALL(glDrawElements, GL_TRIANGLES, 36, GL_UNSIGNED_INT, static_cast<char*> (nullptr));
        attribBinding->DisableVertexAttributeArray();
    }

    /**
     *  Fills the vertex attribute bindings.
     *  @param prog the program to create bindings for.
     *  @param bindings the created bindings.
     */
    void VolumeCubeRenderable::FillVertexAttributeBindings(GPUProgram& prog, VertexAttributeBindings& bindings) const
    {
        assert(bindings.size() == 0);

        auto loc = prog.GetAttributeLocations(boost::assign::list_of<std::string>("position")("texPosition"));
        OGL_CALL(glBindBuffer, GL_ARRAY_BUFFER, vBuffer);
        bindings.push_back(prog.CreateVertexAttributeArray(vBuffer, iBuffer));
        bindings[0]->StartAttributeSetup();
        bindings[0]->AddVertexAttribute(loc[0], 4, GL_FLOAT, GL_FALSE, sizeof(VolumeCubeVertex), 0);
        bindings[0]->AddVertexAttribute(loc[1], 3, GL_FLOAT, GL_FALSE, sizeof(VolumeCubeVertex), sizeof(glm::vec4));
        bindings[0]->EndAttributeSetup();
        OGL_CALL(glBindBuffer, GL_ARRAY_BUFFER, 0);
    }
}


text:
// Copyright 2018, Beeri 15.  All rights reserved.
// Author: Roman Gershman (romange@gmail.com)
//
#include "util/rpc/rpc_test_utils.h"

#include <boost/fiber/operations.hpp>

#include "absl/strings/numbers.h"
#include "absl/strings/strip.h"
#include "base/logging.h"

#include "util/asio/accept_server.h"
#include "util/asio/fiber_socket.h"

using namespace std;
using namespace boost;
using namespace chrono;

DEFINE_uint32(rpc_test_io_pool, 0, "Number of IO loops");

namespace util {
namespace rpc {

TestBridge::~TestBridge() {
}

void TestBridge::Join() {
  this_fiber::sleep_for(milliseconds(10));
}

void TestBridge::HandleEnvelope(uint64_t rpc_id, Envelope* envelope, EnvelopeWriter writer) {
  VLOG(1) << "Got " << rpc_id << ", hs=" << envelope->header.size()
          << ", ls=" << envelope->letter.size();
  if (clear_) {
    envelope->Clear();
  }
  absl::string_view header(strings::charptr(envelope->header.data()), envelope->header.size());

  if (absl::ConsumePrefix(&header, "repeat")) {
    uint32_t repeat = 0;
    CHECK(absl::SimpleAtoi(header, &repeat));
    for (uint32_t i = 0; i < repeat; ++i) {
      Envelope tmp;
      Copy(envelope->letter, &tmp.letter);
      string h = string("cont:") + to_string(i + 1 < repeat);
      Copy(h, &tmp.header);
      writer(std::move(tmp));
    }
    return;
  }

  if (absl::ConsumePrefix(&header, "sleep")) {
    uint32_t msec = 0;
    CHECK(absl::SimpleAtoi(header, &msec));
    this_fiber::sleep_for(milliseconds(msec));
  }

  writer(std::move(*envelope));
}

ServerTest::ServerTest() {}

void ServerTest::SetUp() {
  pool_.reset(new IoContextPool(FLAGS_rpc_test_io_pool));
  pool_->Run();
  service_.reset(new TestInterface);
  server_.reset(new AcceptServer(pool_.get()));
  port_ = server_->AddListener(0, service_.get());

  server_->Run();

  sock2_ = std::make_unique<FiberSyncSocket>("localhost", std::to_string(port_),
                                             &pool_->GetNextContext());

  ec_ = sock2_->ClientWaitToConnect(1000);
  CHECK(!ec_) << ec_.message();
  VLOG(1) << "Sock2 created " << sock2_->native_handle();
}

void ServerTest::TearDown() {
  VLOG(1) << "ServerTest::TearDown Start";
  server_.reset();
  sock2_.reset();
  pool_->Stop();
  VLOG(1) << "ServerTest::TearDown End";
}

}  // namespace rpc
}  // namespace util

max_stars_repo_name: dendisuhubdy/gaia

max_issues_repo_name: dendisuhubdy/gaia

max_forks_repo_name: dendisuhubdy/gaia


text:
#include "DarkART/Wavefunctions_Initial.hpp"

#include <cmath>
#include <complex>
#include <fstream>
#include <stdlib.h>

#include <boost/math/quadrature/gauss_kronrod.hpp>

#include "libphysica/Integration.hpp"
#include "libphysica/Natural_Units.hpp"
#include "libphysica/Utilities.hpp"

#include "DarkART/Special_Functions.hpp"
#include "DarkART/version.hpp"

namespace DarkART
{
using namespace std::complex_literals;
using namespace libphysica::natural_units;
using namespace boost::math::quadrature;
using boost::math::factorial;

double a0 = Bohr_Radius;
double au = 27.211386245988 * eV;

// 1. Initial state: Roothaan-Hartree-Fock Ground-State Atomic Wave Functions

void Initial_Electron_State::Import_RHF_Coefficients()
{
	std::string filepath = TOP_LEVEL_DIR "data/" + Orbital_Name() + ".txt";
	if(libphysica::File_Exists(filepath) == false)
	{
		std::cerr << "Error in Initial_Electron_State::Import_RHF_Coefficients(): Coefficient table for " << Orbital_Name() << " does not exist." << std::endl;
		std::exit(EXIT_FAILURE);
	}

	std::ifstream f;
	f.open(filepath);
	if(f.is_open())
	{
		f >> binding_energy;
		binding_energy *= au;
		double C, Z;
		unsigned int nin;
		while(f >> nin >> Z >> C)
		{
			n_lj.push_back(nin);
			Z_lj.push_back(Z);
			C_nlj.push_back(C);
		}
		f.close();
	}
	Z_eff = sqrt(-2.0 * binding_energy / au) * n;
}

void Initial_Electron_State::Check_Normalization()
{
	double norm = Normalization();
	if(std::fabs(1.0 - norm) > 1.0e-4)
	{
		std::cout << "Error in Initial_Electron_State(): Normalization of " << element_name << " = " << norm << " != 1.0" << std::endl;
		std::exit(EXIT_FAILURE);
	}
}

Initial_Electron_State::Initial_Electron_State()
: element_name("none"), n(0), l(0), binding_energy(0.0), Z_eff(0.0)
{
}

Initial_Electron_State::Initial_Electron_State(const std::string& element, int N, int L)
: element_name(element), n(N), l(L)
{
	Import_RHF_Coefficients();
	Check_Normalization();
}

Initial_Electron_State::Initial_Electron_State(const std::string& element, std::string shell_name)
: element_name(element)
{
	n = shell_name[0] - '0';
	for(l = 0; l < l_orbital_names.size(); l++)
		if(shell_name[1] == l_orbital_names[l][0])
			break;
	Import_RHF_Coefficients();
	Check_Normalization();
}

std::string Initial_Electron_State::Orbital_Name() const
{
	return element_name + "_" + std::to_string(n) + l_orbital_names[l];
}

double Initial_Electron_State::Radial_Wavefunction(double r) const
{
	double R_nl = 0.0;
	for(unsigned int j = 0; j < C_nlj.size(); j++)
		R_nl += C_nlj[j] * std::pow(2.0 * Z_lj[j], n_lj[j] + 0.5) / sqrt(factorial<double>(2.0 * n_lj[j])) * std::pow(r / a0, n_lj[j] - 1.0) * std::exp(-Z_lj[j] * r / a0);

	return std::pow(a0, -1.5) * R_nl;
}

double Initial_Electron_State::Radial_Wavefunction_Derivative(double r) const
{
	double dR_dr = 0.0;
	for(unsigned int j = 0; j < C_nlj.size(); j++)
		dR_dr += C_nlj[j] * std::pow(2.0 * Z_lj[j], n_lj[j] + 0.5) / sqrt(factorial<double>(2.0 * n_lj[j])) * ((n_lj[j] - 1.0) / a0 * std::pow(r / a0, n_lj[j] - 2.0) - Z_lj[j] / a0 * std::pow(r / a0, n_lj[j] - 1.0)) * std::exp(-Z_lj[j] * r / a0);

	return std::pow(a0, -1.5) * dR_dr;
}

double Initial_Electron_State::Normalization() const
{
	std::function<double(double)> integrand = [this](double r) {
		double R = Radial_Wavefunction(r);
		return r * r * R * R;
	};
	// Integrate with Gauss Legendre
	return libphysica::Integrate_Gauss_Legendre(integrand, 0.0, 50.0 * Bohr_Radius, 1000);
}

double Initial_Electron_State::Radial_Integral(double r) const
{
	std::function<double(double)> integrand = [this](double rprime) {
		double R = Radial_Wavefunction(rprime);
		return rprime * rprime * R * R;
	};
	return gauss_kronrod<double, 31>::integrate(integrand, 0.0, r, 5, 1e-9);
}

void Initial_Electron_State::Print_Summary(unsigned int mpi_rank) const
{
	if(mpi_rank == 0)
	{
		std::cout << SEPARATOR
				  << Orbital_Name() << " - Summary" << std::endl
				  << std::endl
				  << "Binding energy [eV]:\t" << In_Units(binding_energy, eV) << std::endl
				  << "Z_effective:\t\t" << Z_eff << std::endl
				  << std::endl
				  << "n_lj\tZ_lj\tC_nlj" << std::endl;
		for(unsigned int i = 0; i < C_nlj.size(); i++)
			std::cout << n_lj[i] << "\t" << Z_lj[i] << "\t" << C_nlj[i] << std::endl;
	}
}

}	// namespace DarkART

max_stars_repo_name: temken/DarkART

max_issues_repo_name: temken/DarkART

max_forks_repo_name: temken/DarkART


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

using namespace boost::spirit;

int main()
{
  std::string s;
  std::getline(std::cin, s);
  auto it = s.begin();
  bool match = qi::phrase_parse(it, s.end(), ascii::digit >> ascii::digit,
    ascii::space);
  std::cout << std::boolalpha << match << '\n';
  if (it != s.end())
    std::cout << std::string{it, s.end()} << '\n';
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
/*
 * Copyright 2014-2017, Andrea Del Prete, Rohan Budhiraja LAAS-CNRS
 *
 * This file is part of sot-torque-control.
 * sot-dyninv is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * sot-torque-control 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 Lesser General Public License for more details.  You should
 * have received a copy of the GNU Lesser General Public License along
 * with sot-torque-control.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <Eigen/Dense>

#include <dynamic-graph/factory.h>
#include <sot/core/debug.hh>
#include <sot/torque_control/numerical-difference.hh>
#include <sot/torque_control/commands-helper.hh>
#include <sot/torque_control/motor-model.hh>

namespace dynamicgraph
{
  namespace sot
  {
    namespace torque_control
    {

#define ALL_INPUT_SIGNALS m_xSIN

#define ALL_OUTPUT_SIGNALS  m_x_filteredSOUT << m_dxSOUT  << m_ddxSOUT

      namespace dynamicgraph = ::dynamicgraph;
      using namespace dynamicgraph;
      using namespace dynamicgraph::command;
      using namespace Eigen;

      /// Define EntityClassName here rather than in the header file
      /// so that it can be used by the macros DEFINE_SIGNAL_**_FUNCTION.
      typedef NumericalDifference EntityClassName;

      /* --- DG FACTORY ------------------------------------------------------- */
      DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(NumericalDifference,"NumericalDifference");

      /* --- CONSTRUCTION ----------------------------------------------------- */
      /* --- CONSTRUCTION ----------------------------------------------------- */
      /* --- CONSTRUCTION ----------------------------------------------------- */
      NumericalDifference::
      NumericalDifference( const std::string & name )
        : Entity(name),
          CONSTRUCT_SIGNAL_IN(x,                dynamicgraph::Vector)
        ,CONSTRUCT_SIGNAL_OUT(x_filtered,       dynamicgraph::Vector, m_x_dx_ddxSINNER)
        ,CONSTRUCT_SIGNAL_OUT(dx,               dynamicgraph::Vector, m_x_dx_ddxSINNER)
        ,CONSTRUCT_SIGNAL_OUT(ddx,              dynamicgraph::Vector, m_x_dx_ddxSINNER)
        ,CONSTRUCT_SIGNAL_INNER(x_dx_ddx,       dynamicgraph::Vector, m_xSIN)
      {
        Entity::signalRegistration( ALL_INPUT_SIGNALS << ALL_OUTPUT_SIGNALS);

        /* Commands. */
        addCommand("getTimestep",
                   makeDirectGetter(*this,&m_dt,
                                    docDirectGetter("Control timestep [s ]","double")));
        addCommand("getDelay",
                   makeDirectGetter(*this,&m_delay,
                                    docDirectGetter("Delay in the estimation of signal x","double")));
        addCommand("getSize",
                   makeDirectGetter(*this,&x_size,
                                    docDirectGetter("Size of the x signal","int")));
        addCommand("init", makeCommandVoid4(*this, &NumericalDifference::init,
                              docCommandVoid4("Initialize the estimator.",
                                              "Control timestep [s].",
                                              "Size of the input signal x",
                                              "Estimation delay for signal x",
                                              "Polynomial order")));
      }

      /* --- COMMANDS ---------------------------------------------------------- */
      /* --- COMMANDS ---------------------------------------------------------- */
      /* --- COMMANDS ---------------------------------------------------------- */
      void NumericalDifference::init(const double &timestep, const int& xSize,
                                     const double& delay, const int& polyOrder)
      {
        assert(timestep>0.0 && "Timestep should be > 0");
        assert(delay>=1.5*timestep && "Estimation delay should be >= 1.5*timestep");
        m_dt = timestep;
        m_delay = delay;
        x_size = xSize;
        int winSizeEnc     = (int)(2*delay/m_dt);
        assert(winSizeEnc>=3 && "Estimation-window's length should be >= 3");

        if (polyOrder==1)
          m_filter       = new LinEstimator(winSizeEnc, x_size, m_dt);
        else if(polyOrder==2)
          m_filter       = new QuadEstimator(winSizeEnc, x_size, m_dt);
        else
          SEND_MSG("Only polynomial orders 1 and 2 allowed. Reinitialize the filter", MSG_TYPE_INFO);
        m_ddx_filter_std.resize(x_size);
        m_dx_filter_std.resize(x_size);
        m_x_filter_std.resize(x_size);
        m_x_std.resize(x_size);
      }

      /* --- SIGNALS ---------------------------------------------------------- */
      /* --- SIGNALS ---------------------------------------------------------- */
      /* --- SIGNALS ---------------------------------------------------------- */

      /** Signal Filtering and Differentiation. */
      DEFINE_SIGNAL_INNER_FUNCTION(x_dx_ddx, dynamicgraph::Vector)
      {
        sotDEBUG(15)<<"Compute x_dx_ddx inner signal "<<iter<<std::endl;

        // read encoders and copy in std vector
        const dynamicgraph::Vector& base_x = m_xSIN(iter);
        COPY_VECTOR_TO_ARRAY(base_x, m_x_std);

        // Signal Filters
        m_filter->estimate(m_x_filter_std, m_x_std);
        m_filter->getEstimateDerivative(m_dx_filter_std, 1);
        m_filter->getEstimateDerivative(m_ddx_filter_std, 2);

        // copy data in signal vector
        if(s.size()!=3*x_size)
          s.resize(3*x_size);
        for(int i=0; i<x_size; i++)
          s(i) = m_x_filter_std[i];
        for(int i=0; i<x_size; i++)
          s(i+x_size) = m_dx_filter_std[i];
        for(int i=0; i<x_size; i++)
          s(i+2*x_size) = m_ddx_filter_std[i];

        return s;
      }

      /// ************************************************************************* ///
      /// The following signals depend only on other inner signals, so they
      /// just need to copy the interested part of the inner signal they depend on.
      /// ************************************************************************* ///

      DEFINE_SIGNAL_OUT_FUNCTION(x_filtered, dynamicgraph::Vector)
      {
        sotDEBUG(15)<<"Compute x_filtered output signal "<<iter<<std::endl;

        const dynamicgraph::Vector &x_dx_ddx = m_x_dx_ddxSINNER(iter);
        if(s.size()!=x_size)
          s.resize(x_size);
	s = x_dx_ddx.head(x_size);
        return s;
      }

      DEFINE_SIGNAL_OUT_FUNCTION(dx, dynamicgraph::Vector)
      {
        sotDEBUG(15)<<"Compute dx output signal "<<iter<<std::endl;

        const dynamicgraph::Vector &x_dx_ddx = m_x_dx_ddxSINNER(iter);
        if(s.size()!=x_size)
	  s.resize(x_size);
	s = x_dx_ddx.segment(x_size,x_size);
        return s;
      }

      DEFINE_SIGNAL_OUT_FUNCTION(ddx, dynamicgraph::Vector)
      {
        sotDEBUG(15)<<"Compute ddx output signal "<<iter<<std::endl;

        const dynamicgraph::Vector &x_dx_ddx = m_x_dx_ddxSINNER(iter);
        if(s.size()!=x_size)
          s.resize(x_size);
	s = x_dx_ddx.segment(2*x_size, x_size);
        return s;
      }

      void NumericalDifference::display( std::ostream& os ) const
      {
        os << "NumericalDifference "<<getName()<<":\n";
        try
        {
          getProfiler().report_all(3, os);
        }
        catch (ExceptionSignal e) {}
      }

    } // namespace torque_control
  } // namespace sot
} // namespace dynamicgraph

max_stars_repo_name: NoelieRamuzat/sot-torque-control

max_issues_repo_name: NoelieRamuzat/sot-torque-control

max_forks_repo_name: NoelieRamuzat/sot-torque-control


text:
#ifndef PANACEA_PRIVATE_VECTOREIGEN_H
#define PANACEA_PRIVATE_VECTOREIGEN_H
#pragma once

// Local PANACEA includes
#include "vector.hpp"

#include "data_settings.hpp"

// Third party includes
#include <Eigen/Dense>

// Third party includes
#include <memory>

namespace panacea {

/**
 * Here the underlying vector is owned by the memory manager so we only have a
 * pointer here.
 */
class VectorEigen : public Vector {
private:
  Direction direction_ = Direction::AlongRows;
  std::unique_ptr<Eigen::VectorXd> vector_;
  virtual void direction(const Direction &direction) final {
    direction_ = direction;
  }

public:
  VectorEigen();
  virtual ~VectorEigen() final{};
  virtual const VectorType type() const final;
  virtual VectorEigen &operator=(const Vector &vec) final;
  virtual double &operator()(const int index) final;
  virtual double operator()(const int index) const final;
  virtual Direction direction() const final;
  virtual void resize(const int size) final;
  virtual void setZero() final;
  virtual int rows() const final;
  virtual int cols() const final;
  virtual void print() const final;
};
} // namespace panacea

#endif // PANACEA_PRIVATE_VECTOREIGEN_H

max_stars_repo_name: lanl/PANACEA

max_issues_repo_name: lanl/PANACEA

max_forks_repo_name: lanl/PANACEA


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

Copyright (c) 2017 Bob Perry / asw204k_AT_yahoo.com
All rights reserved.

Please see license in the project root directory fro more details

*/

#include "oxapp.h"
#include "constants.h"
#include "conversion.h"
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include "devices/KOBO.h"
#include "algo/checksum.h"
#include "trivial_log.h"
#include <string>
#include <sstream>

using namespace std;

void KOBO::rw_device() {

  if( (OxApp::get_time_ms() - last_run) < interval ) return;
  last_run = OxApp::get_time_ms();

  stringstream PGRMZ;
  stringstream PITV5;
  stringstream PITV3;
  stringstream PITV4;

  PGRMZ << "PGRMZ," << OxApp::algo_press->get_val(PRESSURE_ALTITUDE) << "," <<
    "m" <<
    "," << "2";
  Checksum PGRMZck(PGRMZ);

  PITV3 << "PITV3," <<
    Conv::rad2deg(OxApp::algo_mad_euler->get_val( ROLL )) << "," <<
    Conv::rad2deg(OxApp::algo_mad_euler->get_val( PITCH )) << "," <<
    Conv::rad2deg(OxApp::algo_mad_euler->get_val( YAW )) << "," <<
    OxApp::algo_press->get_val(AIRSPEED) << "," <<
    OxApp::algo_misc_rate->get_val(LOAD_FACTOR);
  Checksum PITV3ck(PITV3);

  PITV5.precision(3);

  PITV5 << "PITV5," <<
    fixed << OxApp::algo_wind->get_val( WIND_SPEED ) << "," <<
    fixed << Conv::rad2deg(OxApp::algo_wind->get_val( WIND_DIR )) << "," <<
    fixed << sqrt( OxApp::algo_press->get_val(LOCAL_RHO) / SI_RHO ) << "," <<
    fixed << 0.0 << "," <<
    0 << "," <<
    fixed << OxApp::manual_double_vals->get_val(MCREADY);
  Checksum PITV5ck(PITV5);

  PITV4 << "PITV4," << OxApp::algo_press_rate->get_val(PRESSURE_TE_ALTITUDE) <<
    "," << OxApp::algo_press_rate->get_val(PRESSURE_TE_ALTITUDE) -
    polar.sink_rate( OxApp::algo_press->get_val(AIRSPEED)) << "," <<
    OxApp::algo_press_rate->get_val(PRESSURE_TE_ALTITUDE) -
    polar.sink_rate( OxApp::algo_press->get_val(AIRSPEED)) << "," <<
    OxApp::algo_press->get_val(PRESSURE_ALTITUDE) << "," <<
    OxApp::algo_press->get_val(PRESSURE_TE_ALTITUDE) << "," <<
    OxApp::algo_press->get_val(PRESSURE_TE_ALTITUDE) ;
  Checksum PITV4ck(PITV4);

  string GPRMC( OxApp::GPRMC->get_str() );
  string GPGGA( OxApp::GPGGA->get_str() );

  if( bus->is_open() ) {
    bus->write( GPRMC );
    bus->write( PGRMZck.get_sentence() );
    bus->write( PITV3ck.get_sentence() );
    bus->write( GPGGA );
    bus->write( PITV4ck.get_sentence() );
    bus->write( PITV5ck.get_sentence() );

  }

  BOOST_LOG_TRIVIAL(debug) << GPRMC;
  BOOST_LOG_TRIVIAL(debug) << GPGGA;
  BOOST_LOG_TRIVIAL(debug) << PGRMZck.get_sentence();
  BOOST_LOG_TRIVIAL(debug) << PITV3ck.get_sentence();
  BOOST_LOG_TRIVIAL(debug) << PITV4ck.get_sentence();
  BOOST_LOG_TRIVIAL(debug) << PITV5ck.get_sentence();
}

max_stars_repo_name: perryrob/oxcart

max_issues_repo_name: perryrob/oxcart

max_forks_repo_name: perryrob/oxcart


text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2012, 2013 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

//==============================================================================
/*
    2017-06-30  ajochems        Refactored for casinocoin
*/
//==============================================================================

#include <BeastConfig.h>
#include <casinocoin/basics/contract.h>
#include <casinocoin/basics/Log.h>
#include <casinocoin/json/to_string.h>
#include <casinocoin/protocol/Indexes.h>
#include <casinocoin/protocol/JsonFields.h>
#include <casinocoin/protocol/STLedgerEntry.h>
#include <boost/format.hpp>

namespace casinocoin {

STLedgerEntry::STLedgerEntry (Keylet const& k)
    :  STObject(sfLedgerEntry)
    , key_ (k.key)
    , type_ (k.type)
{
    auto const format =
        LedgerFormats::getInstance().findByType (type_);

    if (format == nullptr)
        Throw<std::runtime_error> ("invalid ledger entry type");

    set (format->elements);

    setFieldU16 (sfLedgerEntryType,
        static_cast <std::uint16_t> (type_));
}

STLedgerEntry::STLedgerEntry (
        SerialIter& sit,
        uint256 const& index)
    : STObject (sfLedgerEntry)
    , key_ (index)
{
    set (sit);
    setSLEType ();
}

STLedgerEntry::STLedgerEntry (
        STObject const& object,
        uint256 const& index)
    : STObject (object)
    , key_ (index)
{
    setSLEType ();
}

void STLedgerEntry::setSLEType ()
{
    auto format = LedgerFormats::getInstance().findByType (
        static_cast <LedgerEntryType> (
            getFieldU16 (sfLedgerEntryType)));

    if (format == nullptr)
        Throw<std::runtime_error> ("invalid ledger entry type");

    type_ = format->getType ();

    if (!setType (format->elements))
    {
        if (auto j = debugLog().error())
        {
            j << "Ledger entry not valid for type " << format->getName ();
            j << "Object: " << getJson (0);
        }

        Throw<std::runtime_error> ("ledger entry not valid for type");
    }
}

std::string STLedgerEntry::getFullText () const
{
    auto const format =
        LedgerFormats::getInstance().findByType (type_);

    if (format == nullptr)
        Throw<std::runtime_error> ("invalid ledger entry type");

    std::string ret = "\"";
    ret += to_string (key_);
    ret += "\" = { ";
    ret += format->getName ();
    ret += ", ";
    ret += STObject::getFullText ();
    ret += "}";
    return ret;
}

std::string STLedgerEntry::getText () const
{
    return str (boost::format ("{ %s, %s }")
                % to_string (key_)
                % STObject::getText ());
}

Json::Value STLedgerEntry::getJson (int options) const
{
    Json::Value ret (STObject::getJson (options));

    ret[jss::index] = to_string (key_);

    return ret;
}

bool STLedgerEntry::isThreadedType () const
{
    return getFieldIndex (sfPreviousTxnID) != -1;
}

bool STLedgerEntry::thread (
    uint256 const& txID,
    std::uint32_t ledgerSeq,
    uint256& prevTxID,
    std::uint32_t& prevLedgerID)
{
    uint256 oldPrevTxID = getFieldH256 (sfPreviousTxnID);

    JLOG (debugLog().info())
        << "Thread Tx:" << txID << " prev:" << oldPrevTxID;

    if (oldPrevTxID == txID)
    {
        // this transaction is already threaded
        assert (getFieldU32 (sfPreviousTxnLgrSeq) == ledgerSeq);
        return false;
    }

    prevTxID = oldPrevTxID;
    prevLedgerID = getFieldU32 (sfPreviousTxnLgrSeq);
    setFieldH256 (sfPreviousTxnID, txID);
    setFieldU32 (sfPreviousTxnLgrSeq, ledgerSeq);
    return true;
}

} // casinocoin

max_stars_repo_name: MassICTBV/casinocoind

max_issues_repo_name: MassICTBV/casinocoind

max_forks_repo_name: MassICTBV/casinocoind


text:
#ifndef CVUTILS_HPP
#define CVUTILS_HPP

#include <vector>
#include <opencv2/opencv.hpp>
#include <boost/circular_buffer.hpp>

namespace cvk {

inline boost::circular_buffer<cv::Scalar> create_color_palette(int n, double scale = 255.0) {
  std::vector<cv::Vec3b> palette;
  palette.reserve(n);

  for(int i=0; i<n; i++) {
    palette.push_back(cv::Vec3b((180.0 / (n+1)) * i, 220, 220));
  }
  cv::cvtColor(palette, palette, CV_HSV2BGR);

  boost::circular_buffer<cv::Scalar> hsv(n);
  double s = scale / 255.0;
  for(const auto& col: palette) {
    hsv.push_back(cv::Scalar(col[0] * s, col[1] * s, col[2] * s));
  }
  return hsv;
}

inline cv::Rect clip_roi(const cv::Rect& rect, const cv::Size& size) {
  int top = std::max(0, rect.y);
  int left = std::max(0, rect.x);
  int bottom = std::min(size.height, rect.y + rect.height);
  int right = std::min(size.width, rect.x + rect.width);
  return cv::Rect(left, top, right - left, bottom - top);
}

inline cv::Rect enlarge_rect(const cv::Rect& rect, double scale) {
  double dsize = (scale - 1.0) / 2.0;
  return cv::Rect(rect.x - rect.width * dsize, rect.y - rect.height * dsize, rect.width * scale, rect.height * scale);
}

inline cv::Rect shift_rect(const cv::Rect& rect, const cv::Point& pt) {
  return cv::Rect(rect.tl() + pt, rect.size());
}

}

#endif // CVUTILS_HPP


text: #include <boost/mpl/aux_/preprocessed/dmc/quote.hpp>


text:
// -----------------------------------------------------------------------------
// Fern © Geoneric
//
// This file is part of Geoneric Fern which is available under the terms of
// the GNU General Public License (GPL), version 2. If you do not want to
// be bound by the terms of the GPL, you may purchase a proprietary license
// from Geoneric (http://www.geoneric.eu/contact).
// -----------------------------------------------------------------------------
#define BOOST_TEST_MODULE fern algorithm accumulator min
#include <boost/test/unit_test.hpp>
#include "fern/algorithm/accumulator/min.h"

namespace faa = fern::algorithm::accumulator;

BOOST_AUTO_TEST_CASE(default_construct)
{
    faa::Min<int> min;
    BOOST_CHECK_EQUAL(min(), std::numeric_limits<int>::max());
}

BOOST_AUTO_TEST_CASE(accumulate)
{
    faa::Min<int> min(5);
    BOOST_CHECK_EQUAL(min(), 5);

    min(2);
    BOOST_CHECK_EQUAL(min(), 2);

    min(7);
    BOOST_CHECK_EQUAL(min(), 2);

    min = 3;
    BOOST_CHECK_EQUAL(min(), 3);
}

BOOST_AUTO_TEST_CASE(merge)
{
    auto min(faa::Min<int>(5) | faa::Min<int>(3));
    BOOST_CHECK_EQUAL(min(), 3);
}

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
/* vim: set tabstop=4 : */
#ifndef __terark_io_is_primitive_h__
#define __terark_io_var_int_h__

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <boost/cstdint.hpp>

#include <string>

// should be the last #include
#include <boost/type_traits/detail/bool_trait_def.hpp>

namespace terark {

BOOST_TT_AUX_BOOL_TRAIT_DEF1(is_primitive,T,false)

BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, char, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, unsigned char, true)

BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, int, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, long, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, short, true)

BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, unsigned int, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, unsigned long, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, unsigned short, true)

#if defined(BOOST_HAS_LONG_LONG)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, long long, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, unsigned long long, true)
#elif defined(BOOST_HAS_MS_INT64)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, __int64, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, unsigned __int64, true)
#endif

BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, std::string, true)
BOOST_TT_AUX_BOOL_TRAIT_CV_SPEC1(is_primitive, std::wstring, true)

} // namespace terark

#include "boost/type_traits/detail/bool_trait_undef.hpp"

#endif // __terark_io_var_int_h__

max_stars_repo_name: rockeet/terark-zip

max_issues_repo_name: rockeet/terark-zip

max_forks_repo_name: rockeet/terark-zip