text:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <variant>
#include <tuple>
#include <boost/lexical_cast.hpp>
#include <boost/property_tree/ptree.hpp>
#include "rtfw/config.hpp"

namespace rtfw {
namespace detail {
namespace propertytree {

namespace boostpt = boost::property_tree;

template<class, class, class=void>
struct eq_comparable: std::false_type{};

template<class T, class U>
struct eq_comparable<T, U, std::void_t<decltype(std::declval<T>() == std::declval<U>())>>: std::true_type{};

template<class T, class U>
constexpr bool eq_comparable_v = eq_comparable<T, U>::value;

template<class Variant, class T>
struct variant_eq_comparable: std::false_type{};

template<class T, class... Ts>
struct variant_eq_comparable<std::variant<Ts...>, T>{
	static constexpr bool value = std::disjunction_v<eq_comparable<Ts, T>...>;
};

template<class, class, class=void>
struct lt_comparable: std::false_type{};

template<class T, class U>
struct lt_comparable<T, U, std::void_t<decltype(std::declval<T>() < std::declval<U>())>>: std::true_type{};

template<class T, class U>
constexpr bool lt_comparable_v = lt_comparable<T, U>::value;

template<class Variant, class T>
struct variant_lt_comparable: std::false_type{};

template<class T, class... Ts>
struct variant_lt_comparable<std::variant<Ts...>, T>{
	static constexpr bool value = std::disjunction_v<lt_comparable<Ts, T>...>;
};

template<class, class, class=void>
struct gt_comparable: std::false_type{};

template<class T, class U>
struct gt_comparable<T, U, std::void_t<decltype(std::declval<T>() < std::declval<U>())>>: std::true_type{};

template<class T, class U>
constexpr bool gt_comparable_v = gt_comparable<T, U>::value;

template<class Variant, class T>
struct variant_gt_comparable: std::false_type{};

template<class T, class... Ts>
struct variant_gt_comparable<std::variant<Ts...>, T>{
	static constexpr bool value = std::disjunction_v<gt_comparable<Ts, T>...>;
};

using ScalarBase = std::variant<int, double, std::string>;

class Scalar: public ScalarBase {
public:
	using ScalarBase::ScalarBase;

	template<class T, class=std::enable_if_t<!std::is_same_v<std::decay_t<T>, Scalar>>>
	bool operator==(T&& t) const noexcept {
		static_assert(variant_eq_comparable<std::variant<int, double, std::string>, T>::value,
				"No known comparison with any variant type");

		if constexpr (eq_comparable_v<int, T>){
			if(std::holds_alternative<int>(*this))
				return std::get<int>(*this) == t;
		}
		if constexpr (eq_comparable_v<double, T>){
			if(std::holds_alternative<double>(*this))
				return std::get<double>(*this) == t;
		}

		if constexpr (eq_comparable_v<std::string, T>){
			if(std::holds_alternative<std::string>(*this))
				return std::get<std::string>(*this) == t;
		}
		return false;
	}

	template<class T>
	bool operator!=(T&& t) const noexcept {
		return !((*this) == t);
	}

	template<class T, class=std::enable_if_t<!std::is_same_v<std::decay_t<T>, Scalar>>>
	bool operator<(T&& t) const noexcept {
		static_assert(variant_lt_comparable<std::variant<int, double, std::string>, T>::value,
				"No known comparison with any variant type");
		if constexpr (lt_comparable_v<int, T>){
			if(std::holds_alternative<int>(*this))
				return std::get<int>(*this) < t;
		}
		if constexpr (lt_comparable_v<double, T>){
			if(std::holds_alternative<double>(*this))
				return std::get<double>(*this) < t;
		}

		if constexpr (lt_comparable_v<std::string, T>){
			if(std::holds_alternative<std::string>(*this))
				return std::get<std::string>(*this) < t;
		}
		return false;
	}

	template<class T>
	bool operator>=(T&& t) const noexcept {
		return !((*this) < t);
	}

	template<class T, class=std::enable_if_t<!std::is_same_v<std::decay_t<T>, Scalar>>>
	bool operator>(T&& t) const noexcept {
		static_assert(variant_gt_comparable<std::variant<int, double, std::string>, T>::value,
				"No known comparison with any variant type");

		if constexpr (gt_comparable_v<int, T>){
			if(std::holds_alternative<int>(*this))
				return std::get<int>(*this) > t;
		}
		if constexpr (gt_comparable_v<double, T>){
			if(std::holds_alternative<double>(*this))
				return std::get<double>(*this) > t;
		}
		if constexpr (gt_comparable_v<std::string, T>){
			if(std::holds_alternative<std::string>(*this))
				return std::get<std::string>(*this) > t;
		}
		return false;
	}

	template<class T>
	bool operator<=(T&& t) const noexcept {
		return !((*this) > t);
	}

	template<class T>
	T& as(){
		return std::get<T>(*this);
	}

	template<class T>
	const T& as() const {
		return std::get<T>(*this);
	}

	template<class T>
	T cast() const {
		auto visitor = [](const auto& item){
			return boost::lexical_cast<T>(item);
		};
		return std::visit(visitor, *static_cast<const ScalarBase*>(this));
	}

	template<class T>
	bool is_current_type() const {
		return std::holds_alternative<T>(*this);
	}
};

bool operator<(std::string_view str, const Scalar& s);

class Node;

using List = std::vector<Node>;

// std::less<> for using count() and find with std::string_view
using DictBase = std::map<Scalar, Node, std::less<>>;

class Dict: public DictBase{
public:
	using DictBase::DictBase;

	template<class T>
	Node& operator[](T&& t){
		return (*static_cast<DictBase*>(this))[std::forward<T>(t)];
	}

	Node& operator[](std::string_view key);

	Dict& operator-=(const Dict& other);

	Dict& left_union(const Dict& other);
	Dict& right_union(const Dict& other);

	Dict& left_intersect(const Dict& other);
	Dict& right_intersect(const Dict& other);

	std::vector<Config> to_configs() const;

private:
};

using NodeBase = std::variant<Scalar, List, Dict>;

class Node: public NodeBase {
public:
	using NodeBase::NodeBase;

	enum class Type{
		Scalar,
		List,
		Dict,
	};

	Node(const Config& conf);
	Node(Config&& conf);

	Node(const boostpt::ptree& tree);

	Node(const Node&) = default;
	Node& operator=(const Node&) = default;

	Node(Node&&) = default;
	Node& operator=(Node&&) = default;

	template<class T, class=std::enable_if_t<!std::is_same_v<std::decay_t<T>, Node>>>
	bool operator==(const T& t) const {
		static_assert(variant_eq_comparable<NodeBase, T>::value, "No known comparison with variant types");
		if constexpr (eq_comparable_v<Scalar, T>)
			if(std::holds_alternative<Scalar>(*this))
				return std::get<Scalar>(*this) == t;
		if constexpr (eq_comparable_v<List, T>)
			if(std::holds_alternative<List>(*this))
				return std::get<List>(*this) == t;
		if constexpr (eq_comparable_v<Dict, T>)
			if(std::holds_alternative<Dict>(*this))
				return std::get<Dict>(*this) == t;
		return false;
	}

	Type type() const;

	bool is_scalar() const noexcept;

	bool is_list() const noexcept;

	bool is_dict() const noexcept;

	Scalar& as_scalar();

	const Scalar& as_scalar() const;

	List& as_list();

	const List& as_list() const;

	Dict& as_dict();

	const Dict& as_dict() const;

};

inline std::string indent_str(int indent){
	return std::string(indent*4, ' ');
}

inline void print(const Scalar& s, int indent){
	std::cerr << indent_str(indent) << s.cast<std::string>() << '\n';
}

inline void print(const Node& node, int indent=0){
	if(node.is_scalar()){
		print(node.as_scalar(), indent);
	}
	else if(node.is_list()){
		std::cerr << indent_str(indent) <<  "[\n";
		for(const auto& subnode: node.as_list()){
			print(subnode, indent+1);
		}
		std::cerr << indent_str(indent) << "]\n";
	}
	else if(node.is_dict()){
		std::cerr << indent_str(indent) << "{\n";
		for(const auto& [key, value] : node.as_dict()){
			std::cerr << indent_str(indent+1) << key.cast<std::string>() << ":\n";
			print(value, indent+2);
		}
		std::cerr << indent_str(indent) << "}\n";
	}
	else {
		throw std::runtime_error("oh no");
	}
}

}
}
}

max_stars_repo_name: tlammi/rtfw

max_issues_repo_name: tlammi/rtfw

max_forks_repo_name: tlammi/rtfw


text:
#include <boost/log/trivial.hpp>
#include <stack>

/* project includes */
#include <reaper.hxx>

/******************************************************************************
 * background_worker_shm_reaper & objects implementation start
 ******************************************************************************/

background_worker_shm_reaper::background_worker_shm_reaper()
  : background_reaper() {

  this->shm = nullptr;

}

background_worker_shm_reaper::~background_worker_shm_reaper() {

  /* nothing special to do here */

}

void background_worker_shm_reaper::set_shm_handle(WorkerSHM *shm) {

  this->shm = shm;

}

void background_worker_shm_reaper::reap() {

  /*
   * Nothing to do if we have no SHM pointer.
   */
  if (this->shm == nullptr)
    return;

  while(!this->dead_pids.empty()) {

    pid_t deadpid = this->dead_pids.top();
    this->dead_pids.pop();

#ifdef __DEBUG__
    BOOST_LOG_TRIVIAL(debug) << "WARN: reaping dead PID "
                             << deadpid
                             << " from shared memory";
#endif

    /*
     * Ugly, but we need to loop through the shared memory
     * area to find the PID we need to drop.
     *
     * NOTE: We do this without interlocking, since
     *       we believe to reset the PID to 0 atomically.
     *
     *       This might by racy, but in the worst case we'll
     *       miss this potential free slot and won't find a
     *       remaining one. In this case the worker will
     *       fail and exit.
     */
    for (unsigned int i = 0 ; i < this->shm->getMaxWorkers(); i++) {

      shm_worker_area *ptr = (shm_worker_area *) (this->shm->shm_mem_ptr + i);

      if (ptr != NULL && ptr->pid == deadpid) {

        ptr->pid = 0;

      }

    }
  }

}

ext: cxx


text:
#ifndef SQUEAL_UTIL_META_GRAMMAR_HPP
#define SQUEAL_UTIL_META_GRAMMAR_HPP

#include <tao/pegtl.hpp>
#include <tao/pegtl/contrib/icu/utf8.hpp>

#include <deque>
#include <map>
#include <set>
#include <variant>

#include <boost/format.hpp>

#ifndef SQUEAL_UTIL_UTF8_HPP
#include "squeal/util/utf8.hpp"
#endif

namespace squeal
{
    namespace meta_grammar
    {
        namespace pegtl = tao::pegtl;

        namespace detail
        {
            template <typename Separator, typename... Rules>
            struct interleaved;

            template <typename Separator, typename Rule0, typename... RulesRest>
            struct interleaved<Separator, Rule0, RulesRest...>
                : pegtl::seq<Separator, Rule0, interleaved<Separator, RulesRest...>> {};

            template <typename Separator, typename Rule0>
            struct interleaved<Separator, Rule0>
                : pegtl::seq<Separator, Rule0> {};

        }
        // namespace detail

        struct sep : pegtl::star<pegtl::ascii::space> {};

        template<typename... Rules>
        using seq = detail::interleaved<sep, Rules...>;

        template<typename... Rules>
        using star = pegtl::star<seq<Rules...>>;

        template<typename... Rules>
        using opt = pegtl::opt<seq<Rules...>>;

        //
        // Here's the actual grammar:
        //

        struct langle : pegtl::ascii::one<'<'> {};
        struct rangle : pegtl::ascii::one<'>'> {};

        struct lbrac : pegtl::ascii::one<'['> {};
        struct rbrac : pegtl::ascii::one<']'> {};

        struct lbrace : pegtl::ascii::one<'{'> {};
        struct rbrace : pegtl::ascii::one<'}'> {};

        struct lparen : pegtl::ascii::one<'('> {};
        struct rparen : pegtl::ascii::one<')'> {};

        struct bar : pegtl::ascii::one<'|'> {};
        struct dash : pegtl::ascii::one<'-'> {};
        struct colon : pegtl::ascii::one<':'> {};
        struct percent : pegtl::ascii::one<'%'> {};

        struct assigns : pegtl::ascii::string<':', ':', '='> {};

        struct dots : pegtl::ascii::string<'.', '.', '.'> {};

        struct word : pegtl::plus<pegtl::sor<pegtl::alnum, pegtl::ascii::one<'_', '-'>>> {};

        struct name_char : pegtl::seq<pegtl::not_at<rangle>, pegtl::ascii::any> {};

        struct name : pegtl::seq<langle, pegtl::plus<name_char>, rangle> {};

        struct single : pegtl::seq<
                            pegtl::sor<
                                pegtl::ascii::string<'|', '|'>,
                                pegtl::ascii::string<'-', '>'>,
                                pegtl::ascii::any>,
                            pegtl::eof> {};

        struct hexit : pegtl::utf8::ranges<'0', '9', 'a', 'f', 'A', 'F'> {};

        struct special : pegtl::seq<pegtl::ascii::string<'!', '!'>, pegtl::star<pegtl::ascii::any>, pegtl::eof> {};

        struct disj;

        struct brac : seq<lbrac, disj, rbrac> {};

        struct brace : seq<lbrace, disj, rbrace> {};

        struct simple_escape_sequence : pegtl::utf8::one<')', '\\', '-', ':'> {};

        struct unicode_quad : pegtl::seq<hexit, hexit, hexit, hexit> {};

        struct unicode_oct : pegtl::seq<hexit, hexit, hexit, hexit, hexit, hexit, hexit, hexit> {};

        struct escape_sequence
            : pegtl::sor<
                simple_escape_sequence,
                pegtl::seq<pegtl::utf8::one<'u'>, unicode_quad>,
                pegtl::seq<pegtl::utf8::one<'U'>, unicode_oct>
            >
        {};

        struct escaped_rchar : pegtl::if_must<pegtl::utf8::one<'\\'>, escape_sequence> {};

        struct unescaped_rchar : pegtl::utf8::not_one<'\\', ')', '-', ':'> {};

        struct rchar : pegtl::sor<escaped_rchar, unescaped_rchar> {};

        struct crang_range : pegtl::seq<dash, rchar> {};

        struct crang_single : rchar {};

        struct crangs_cont : pegtl::sor<crang_range, crang_single> {};

        struct crangs : pegtl::seq<rchar, pegtl::star<crangs_cont>> {};

        struct crang : pegtl::seq<lparen, crangs, rparen> {};

        struct cclass_name
            : pegtl::plus<
                pegtl::sor<pegtl::ascii::alnum, pegtl::ascii::one<'_'>>
            >
        {};

        struct cclass : pegtl::seq<lparen, colon, cclass_name, colon, rparen> {};

        struct atom : pegtl::sor<name, word, brac, brace, cclass, crang> {};

        struct conj_cont;

        struct dots_conj_cont : seq<dots, opt<conj_cont>> {};
        struct atom_conj_cont : seq<atom, opt<conj_cont>> {};

        struct conj_cont : pegtl::sor<dots_conj_cont, atom_conj_cont> {};

        struct conj : seq<atom, opt<conj_cont>> {};

        struct disj_part : seq<bar, conj> {};

        struct disj : seq<conj, pegtl::star<disj_part>> {};

        struct expression : pegtl::sor<disj, single, special> {};

        struct grammar_definition
            : seq<name, assigns, expression> {};

        struct meta_rule_name
            : pegtl::plus<pegtl::sor<pegtl::ascii::alnum, pegtl::ascii::one<'-', '_'>>> {};

        struct meta_rule_space : pegtl::star<pegtl::ascii::one<' ', '\t'>> {};

        struct meta_rule_value
            : pegtl::star<pegtl::seq<pegtl::not_at<pegtl::eol>, pegtl::ascii::any>> {};

        struct meta_rule : pegtl::seq<percent, meta_rule_space, meta_rule_name, meta_rule_space, meta_rule_value, pegtl::eolf> {};

        struct definition : pegtl::sor<meta_rule, grammar_definition> {};

        //
        // Syntax tree nodes and parser state
        //

        struct cpp
        {
            static std::string esc_name(const std::string& p_str)
            {
                std::string s(p_str.begin()+1, p_str.end()-1);
                std::replace(s.begin(), s.end(), ' ', '_');
                std::replace(s.begin(), s.end(), '-', '_');
                std::replace(s.begin(), s.end(), '/', '_');
                return s;
            }

            static std::string esc_char(char p_ch)
            {
                std::string s;
                switch (p_ch)
                {
                    case '\'':
                    case '\\':
                        s.push_back('\\');
                }
                s.push_back(p_ch);
                return s;
            }

            static std::string esc_word(const std::string& p_word)
            {
                std::string s(p_word);
                if (p_word == "TRUE" || p_word == "FALSE" || p_word == "NULL")
                {
                    s.push_back('_');
                }
                std::replace(s.begin(), s.end(), ' ', '_');
                std::replace(s.begin(), s.end(), '-', '_');
                return s;
            }

        };

        struct context
        {
            std::ostream& out;
            int ind;
            std::string ns;
            std::set<std::string> keywords;

            context(std::ostream& p_out)
                : out(p_out), ind(0), ns("tao::pegtl::")
            {}

            void indent()
            {
                for (int i = 0; i < ind; ++i)
                {
                    out << "    ";
                }
            }
        };

        struct scope
        {
            scope(context& p_ctxt)
                : ctxt(p_ctxt)
            {
                ctxt.ind += 1;
            }

            ~scope()
            {
                ctxt.ind -= 1;
            }

            context& ctxt;
        };

        struct node
        {
            virtual ~node() {}

            virtual void names(std::set<std::string>& p_names) const = 0;

            virtual void words(std::set<std::string>& p_words) const = 0;

            virtual void render(context& p_ctxt) const = 0;

            // For debugging
            //
            virtual std::string dump() const = 0;
        };
        using node_ptr = std::shared_ptr<node>;

        struct state
        {
            std::vector<node_ptr> nodes;

            std::map<std::string, std::string> meta;
            std::map<std::string, node_ptr> rules;

            void dump(std::ostream& p_out) const
            {
                int i = 0;
                for (auto itr = nodes.rbegin(); itr != nodes.rend(); ++itr, ++i)
                {
                    p_out << i << '\t' << (*itr)->dump() << std::endl;
                }
            }
        };

        template<typename Rule>
        struct build_ast : tao::pegtl::nothing<Rule> {};

        struct name_node : node
        {
            std::string name;

            name_node(const std::string& p_name)
                : name(p_name)
            {
            }

            virtual void names(std::set<std::string>& p_names) const
            {
                p_names.insert(name);
            }

            virtual void words(std::set<std::string>& p_words) const
            {
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << cpp::esc_name(name);
            }

            virtual std::string dump() const { return name; }
        };
        using name_node_ptr = std::shared_ptr<name_node>;

        struct word_node : node
        {
            std::string word;

            word_node(const std::string& p_word)
                : word(p_word)
            {
            }

            virtual void names(std::set<std::string>& p_names) const
            {
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                p_words.insert(word);
            }

            virtual void render(context& p_ctxt) const
            {
                if (p_ctxt.keywords.count(word))
                {
                    p_ctxt.indent();
                    p_ctxt.out << "keywords::" << cpp::esc_word(word);
                    return;
                }

                if (word.size() == 1)
                {
                    p_ctxt.indent();
                    p_ctxt.out << "tao::pegtl::utf8::one<'" << cpp::esc_char(word[0]) << "'>";
                    return;
                }

                p_ctxt.out << "tao::pegtl::utf8::string<";
                for (auto itr = word.begin(); itr != word.end(); ++itr)
                {
                    if (itr != word.begin())
                    {
                        p_ctxt.out << ",";
                    }
                    p_ctxt.out << "'" << cpp::esc_char(*itr) << "'";
                }
                p_ctxt.out << ">";
            }

            virtual std::string dump() const { return word; }
        };
        using word_node_ptr = std::shared_ptr<word_node>;

        struct special_node : node
        {
            std::string word;

            special_node(const std::string& p_word)
                : word(p_word)
            {
            }

            virtual void names(std::set<std::string>& p_names) const
            {
            }

            virtual void words(std::set<std::string>& p_words) const
            {
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << word;
            }

            virtual std::string dump() const { return word; }
        };
        using special_node_ptr = std::shared_ptr<special_node>;

        struct crang_node : node
        {
            using single = char32_t;
            using range = std::pair<char32_t,char32_t>;
            using single_or_range = std::variant<single,range>;

            std::deque<single_or_range> parts;

            virtual void names(std::set<std::string>& p_names) const
            {
            }

            virtual void words(std::set<std::string>& p_words) const
            {
            }

            virtual void render(context& p_ctxt) const
            {
                std::vector<char32_t> singles;
                std::vector<range> ranges;
                for (size_t i = 0; i < parts.size(); ++i)
                {
                    switch (parts[i].index())
                    {
                        case 0:
                        {
                            singles.push_back(std::get<0>(parts[i]));
                            break;
                        }
                        case 1:
                        {
                            ranges.push_back(std::get<1>(parts[i]));
                            break;
                        }
                    }
                }
                //std::sort(singles.begin(), singles.end());
                //std::sort(ranges.begin(), ranges.end());
                if (singles.size() > 0 && ranges.size() == 0)
                {
                    renderSingles(p_ctxt, singles);
                }
                else if (singles.size() == 0 && ranges.size() > 0)
                {
                    renderRanges(p_ctxt, ranges);
                }
                else
                {
                    p_ctxt.indent();
                    p_ctxt.out << "tao::pegtl::sor<\n";
                    {
                        scope S(p_ctxt);
                        renderSingles(p_ctxt, singles);
                        p_ctxt.out << ",\n";
                        renderRanges(p_ctxt, ranges);
                        p_ctxt.out << "\n";
                    }
                    p_ctxt.indent();
                    p_ctxt.out << ">";
                }
            }

            static void renderSingles(context& p_ctxt, const std::vector<char32_t>& p_singles)
            {
                using namespace boost;

                p_ctxt.indent();
                p_ctxt.out << "tao::pegtl::utf8::one<";
                for (size_t i = 0; i < p_singles.size(); ++i)
                {
                    if (i > 0)
                    {
                        p_ctxt.out << ", ";
                    }
                    p_ctxt.out << str(format("0x%04x") % p_singles[i]);
                }
                p_ctxt.out << ">";
            }

            static void renderRanges(context& p_ctxt, const std::vector<range>& p_ranges)
            {
                using namespace boost;

                p_ctxt.indent();
                p_ctxt.out << "tao::pegtl::utf8::ranges<";
                for (size_t i = 0; i < p_ranges.size(); ++i)
                {
                    if (i > 0)
                    {
                        p_ctxt.out << ", ";
                    }
                    p_ctxt.out << str(format("0x%04x, 0x%04x") % p_ranges[i].first % p_ranges[i].second);
                }
                p_ctxt.out << ">";
            }

            virtual std::string dump() const
            {
                std::string s;
                s += "(";
                for (size_t i = 0; i < parts.size(); ++i)
                {
                    switch (parts[i].index())
                    {
                        case 0:
                        {
                            s += std::get<0>(parts[i]);
                            break;
                        }
                        case 1:
                        {
                            s += std::get<1>(parts[i]).first;
                            s += "-";
                            s += std::get<1>(parts[i]).second;
                            break;
                        }
                    }
                }
                s += ")";
                return s;
            }
        };
        using crang_node_ptr = std::shared_ptr<crang_node>;

        struct crang_part_node : node
        {
            crang_node::single_or_range part;

            crang_part_node(char32_t p_ch)
                : part(p_ch)
            {}

            crang_part_node(char32_t p_fst, char32_t p_lst)
                : part(crang_node::range(p_fst, p_lst))
            {}

            virtual void names(std::set<std::string>& p_names) const
            {
                throw std::logic_error("cannot get names from partial character ranges");
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                throw std::logic_error("cannot get words from partial character ranges");
            }

            virtual void render(context& p_ctxt) const
            {
                throw std::logic_error("cannot render partial character ranges");
            }

            virtual std::string dump() const
            {
                std::string s;
                s += "<<";
                switch (part.index())
                {
                    case 0:
                    {
                        s += std::to_string(std::get<0>(part));
                        break;
                    }
                    case 1:
                    {
                        s += std::to_string(std::get<1>(part).first);
                        s += "-";
                        s += std::to_string(std::get<1>(part).second);
                        break;
                    }
                }
                s += ">>";
                return s;
            }
        };
        using crang_part_node_ptr = std::shared_ptr<crang_part_node>;

        struct cclass_node : node
        {
            std::string name;

            cclass_node(const std::string& p_name)
                : name(p_name)
            {}

            virtual void names(std::set<std::string>& p_names) const
            {
            }

            virtual void words(std::set<std::string>& p_words) const
            {
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << "tao::pegtl::utf8::icu::" << name;
            }

            virtual std::string dump() const
            {
                std::string s;
                s += "(:";
                s += name;
                s += ":)";
                return s;
            }
        };
        using cclass_node_ptr = std::shared_ptr<cclass_node>;

        struct opt_node : node
        {
            node_ptr child;

            opt_node(const node_ptr& p_child)
                : child(p_child)
            {}

            virtual void names(std::set<std::string>& p_names) const
            {
                child->names(p_names);
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                child->words(p_words);
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << p_ctxt.ns << "opt<\n";
                {
                    scope S(p_ctxt);
                    child->render(p_ctxt);
                }
                p_ctxt.out << ">";
            }

            virtual std::string dump() const { return std::string("(") + child->dump() + std::string(")?"); }
        };
        using opt_node_ptr = std::shared_ptr<opt_node>;

        struct plus_node : node
        {
            node_ptr child;

            plus_node(const node_ptr& p_child)
                : child(p_child)
            {}

            virtual void names(std::set<std::string>& p_names) const
            {
                child->names(p_names);
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                child->words(p_words);
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << p_ctxt.ns << "plus<\n";
                {
                    scope S(p_ctxt);
                    child->render(p_ctxt);
                }
                p_ctxt.out << ">";
            }

            virtual std::string dump() const { return std::string("(") + child->dump() + std::string(")+"); }
        };
        using plus_node_ptr = std::shared_ptr<plus_node>;

        struct star_node : node
        {
            node_ptr child;

            star_node(const node_ptr& p_child)
                : child(p_child)
            {}

            virtual void names(std::set<std::string>& p_names) const
            {
                child->names(p_names);
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                child->words(p_words);
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << p_ctxt.ns << "star<\n";
                {
                    scope S(p_ctxt);
                    child->render(p_ctxt);
                }
                p_ctxt.out << ">";
            }

            virtual std::string dump() const { return std::string("(") + child->dump() + std::string(")*"); }
        };
        using star_node_ptr = std::shared_ptr<star_node>;

        struct conj_node : node
        {
            std::deque<node_ptr> nodes;

            virtual void names(std::set<std::string>& p_names) const
            {
                for (auto itr = nodes.begin(); itr != nodes.end(); ++itr)
                {
                    (*itr)->names(p_names);
                }
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                for (auto itr = nodes.begin(); itr != nodes.end(); ++itr)
                {
                    (*itr)->words(p_words);
                }
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << p_ctxt.ns << "seq<\n";
                for (auto itr = nodes.begin(); itr != nodes.end(); ++itr)
                {
                    scope S(p_ctxt);
                    if (itr != nodes.begin())
                    {
                        p_ctxt.out << ",\n";
                    }
                    (*itr)->render(p_ctxt);
                }
                p_ctxt.out << "\n";
                p_ctxt.indent();
                p_ctxt.out << ">";
            }

            virtual std::string dump() const {
                std::string s;
                s += "(";
                for (size_t i = 0; i < nodes.size(); ++i)
                {
                    if (i > 0)
                    {
                        s += " ";
                    }
                    s += nodes[i]->dump();
                }
                s += ")";
                return s;
            }
        };
        using conj_node_ptr = std::shared_ptr<conj_node>;

        struct disj_node : node
        {
            std::vector<node_ptr> nodes;

            virtual void names(std::set<std::string>& p_names) const
            {
                for (auto itr = nodes.begin(); itr != nodes.end(); ++itr)
                {
                    (*itr)->names(p_names);
                }
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                for (auto itr = nodes.begin(); itr != nodes.end(); ++itr)
                {
                    (*itr)->words(p_words);
                }
            }

            virtual void render(context& p_ctxt) const
            {
                p_ctxt.indent();
                p_ctxt.out << p_ctxt.ns << "sor<\n";
                for (auto itr = nodes.begin(); itr != nodes.end(); ++itr)
                {
                    scope S(p_ctxt);
                    if (itr != nodes.begin())
                    {
                        p_ctxt.out << ",\n";
                    }
                    (*itr)->render(p_ctxt);
                }
                p_ctxt.out << "\n";
                p_ctxt.indent();
                p_ctxt.out << ">";
            }

            virtual std::string dump() const {
                std::string s;
                s += "{";
                for (size_t i = 0; i < nodes.size(); ++i)
                {
                    if (i > 0)
                    {
                        s += " | ";
                    }
                    s += nodes[i]->dump();
                }
                s += "}";
                return s;
            }
        };
        using disj_node_ptr = std::shared_ptr<disj_node>;

        struct defn_node : node
        {
            std::string name;
            node_ptr defn;

            defn_node(const std::string& p_name, node_ptr p_defn)
                : name(p_name), defn(p_defn)
            {
            }

            virtual void names(std::set<std::string>& p_names) const
            {
                defn->names(p_names);
            }

            virtual void words(std::set<std::string>& p_words) const
            {
                defn->words(p_words);
            }

            virtual void render(context& p_ctxt) const
            {
                special_node_ptr p = std::dynamic_pointer_cast<special_node>(defn);
                if (p)
                {
                    p_ctxt.out << "#if 0" << std::endl;
                }
                p_ctxt.indent();
                p_ctxt.out << "struct " << cpp::esc_name(name) << " :\n";
                {
                    scope S(p_ctxt);
                    defn->render(p_ctxt);
                }
                p_ctxt.out << "\n";
                p_ctxt.indent();
                p_ctxt.out << "{};\n";
                if (p)
                {
                    p_ctxt.out << "#endif" << std::endl;
                }
            }

            std::string dump() const
            {
                std::string s;
                s += name;
                s += " ::= ";
                s += defn->dump();
                return s;
            }

        };
        using defn_node_ptr = std::shared_ptr<defn_node>;

        template<>
        struct build_ast<name>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p(new name_node(p_in.string()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<word>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p(new word_node(p_in.string()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<single>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p(new word_node(p_in.string()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<special>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p(new special_node(p_in.string()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<brac>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p = p_state.nodes.back();
                p_state.nodes.pop_back();
                plus_node_ptr q = std::dynamic_pointer_cast<plus_node>(p);
                if (q)
                {
                    node_ptr r(new star_node(q->child));
                    p_state.nodes.push_back(r);
                }
                else
                {
                    node_ptr r(new opt_node(p));
                    p_state.nodes.push_back(r);
                }
            }
        };

        template<>
        struct build_ast<unescaped_rchar>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                std::vector<char32_t> cs;
                squeal::util::utf8::decoder::decode(p_in.string(), cs);
                if (cs.size() != 1)
                {
                    throw std::logic_error("bad escaped character");
                }
                node_ptr p(new crang_part_node(cs.front()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<simple_escape_sequence>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                std::vector<char32_t> cs;
                squeal::util::utf8::decoder::decode(p_in.string(), cs);
                if (cs.size() != 1)
                {
                    throw std::logic_error("bad escaped character");
                }
                node_ptr p(new crang_part_node(cs.front()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<unicode_quad>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                char32_t ch = 0;
                std::string x = p_in.string();
                for (size_t i = 0; i < x.size(); ++i)
                {
                    if ('0' <= x[i] && x[i] <= '9')
                    {
                        ch = (ch << 4) + (x[i] - '0');
                    }
                    else if ('a' <= x[i] && x[i] <= 'f')
                    {
                        ch = (ch << 4) + (x[i] - 'a' + 10);
                    }
                    else if ('A' <= x[i] && x[i] <= 'F')
                    {
                        ch = (ch << 4) + (x[i] - 'A' + 10);
                    }
                    else
                    {
                        throw std::logic_error("bad hexit character");
                    }
                }

                node_ptr p(new crang_part_node(ch));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<unicode_oct>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                char32_t ch = 0;
                std::string x = p_in.string();
                for (size_t i = 0; i < x.size(); ++i)
                {
                    if ('0' <= x[i] && x[i] <= '9')
                    {
                        ch = (ch << 4) + (x[i] - '0');
                    }
                    else if ('a' <= x[i] && x[i] <= 'f')
                    {
                        ch = (ch << 4) + (x[i] - 'a' + 10);
                    }
                    else if ('A' <= x[i] && x[i] <= 'F')
                    {
                        ch = (ch << 4) + (x[i] - 'A' + 10);
                    }
                    else
                    {
                        throw std::logic_error("bad hexit character");
                    }
                }

                node_ptr p(new crang_part_node(ch));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<crang_range>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr q0 = p_state.nodes.back();
                p_state.nodes.pop_back();
                crang_part_node_ptr q = std::dynamic_pointer_cast<crang_part_node>(q0);
                node_ptr p0 = p_state.nodes.back();
                p_state.nodes.pop_back();
                crang_part_node_ptr p = std::dynamic_pointer_cast<crang_part_node>(p0);

                node_ptr r(new crang_part_node(std::get<0>(p->part), std::get<0>(q->part)));
                p_state.nodes.push_back(r);
            }
        };

        template<>
        struct build_ast<crang>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                crang_node_ptr r(new crang_node);
                while (p_state.nodes.size()
                       && std::dynamic_pointer_cast<crang_part_node>(p_state.nodes.back()))
                {
                    node_ptr p0 = p_state.nodes.back();
                    p_state.nodes.pop_back();
                    crang_part_node_ptr p = std::dynamic_pointer_cast<crang_part_node>(p0);
                    r->parts.push_front(p->part);
                }
                p_state.nodes.push_back(std::static_pointer_cast<node>(r));
            }
        };

        template <>
        struct build_ast<cclass_name>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p(new cclass_node(p_in.string()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<dots_conj_cont>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p = p_state.nodes.back();
                p_state.nodes.pop_back();
                node_ptr q(new plus_node(p));
                p_state.nodes.push_back(q);
            }
        };

        template<>
        struct build_ast<atom_conj_cont>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p = p_state.nodes.back();
                p_state.nodes.pop_back();
                node_ptr q = p_state.nodes.back();
                p_state.nodes.pop_back();

                conj_node_ptr c = std::dynamic_pointer_cast<conj_node>(p);
                if (c)
                {
                    c->nodes.push_front(q);
                }
                else
                {
                    c = conj_node_ptr(new conj_node);
                    c->nodes.push_back(q);
                    c->nodes.push_back(p);
                }
                p_state.nodes.push_back(std::static_pointer_cast<node>(c));
            }
        };

        template<>
        struct build_ast<disj_part>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p = p_state.nodes.back();
                p_state.nodes.pop_back();
                node_ptr q = p_state.nodes.back();
                p_state.nodes.pop_back();

                disj_node_ptr c = std::dynamic_pointer_cast<disj_node>(q);
                if (c)
                {
                    c->nodes.push_back(p);
                }
                else
                {
                    c = disj_node_ptr(new disj_node);
                    c->nodes.push_back(q);
                    c->nodes.push_back(p);
                }
                p_state.nodes.push_back(std::static_pointer_cast<node>(c));
            }
        };

        template<>
        struct build_ast<grammar_definition>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p = p_state.nodes.back();
                p_state.nodes.pop_back();
                node_ptr q = p_state.nodes.back();
                p_state.nodes.pop_back();
                name_node_ptr n = std::dynamic_pointer_cast<name_node>(q);
                p_state.rules[n->name] = node_ptr(new defn_node(n->name, p));
            }
        };

        template<>
        struct build_ast<meta_rule_name>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p(new name_node(p_in.string()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<meta_rule_value>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p(new name_node(p_in.string()));
                p_state.nodes.push_back(p);
            }
        };

        template<>
        struct build_ast<meta_rule>
        {
            template<typename ActionInput>
            static void apply(const ActionInput& p_in, state& p_state)
            {
                node_ptr p = p_state.nodes.back();
                p_state.nodes.pop_back();
                node_ptr q = p_state.nodes.back();
                p_state.nodes.pop_back();
                name_node_ptr mn = std::dynamic_pointer_cast<name_node>(q);
                name_node_ptr dn = std::dynamic_pointer_cast<name_node>(p);
                p_state.meta[mn->name] = dn->name;
            }
        };

    }
    // namespace meta_grammar
}
// namespace squeal

#endif // SQUEAL_UTIL_META_GRAMMAR_HPP

ext: hpp

max_stars_repo_name: drtconway/squeal

max_issues_repo_name: drtconway/squeal

max_forks_repo_name: drtconway/squeal


text:
#include "drake/manipulation/schunk_wsg/schunk_wsg_lcm.h"

#include <vector>

#include <Eigen/Dense>

#include "drake/common/drake_assert.h"
#include "drake/common/eigen_types.h"
#include "drake/lcm/lcm_messages.h"
#include "drake/lcmt_schunk_wsg_command.hpp"
#include "drake/lcmt_schunk_wsg_status.hpp"

namespace drake {
namespace manipulation {
namespace schunk_wsg {

using systems::BasicVector;
using systems::Context;

SchunkWsgCommandReceiver::SchunkWsgCommandReceiver(double initial_position,
                                                   double initial_force)
    : initial_position_(initial_position), initial_force_(initial_force) {
  this->DeclareVectorOutputPort("position", BasicVector<double>(1),
                                &SchunkWsgCommandReceiver::CalcPositionOutput);
  this->DeclareVectorOutputPort(
      "force_limit", BasicVector<double>(1),
      &SchunkWsgCommandReceiver::CalcForceLimitOutput);

  lcmt_schunk_wsg_command uninitialized_message{};
  this->DeclareAbstractInputPort(
      "command_message",
      Value<lcmt_schunk_wsg_command>(uninitialized_message));
}

void SchunkWsgCommandReceiver::CalcPositionOutput(
    const Context<double>& context, BasicVector<double>* output) const {
  const auto& message =
      this->get_input_port(0).Eval<lcmt_schunk_wsg_command>(context);

  double target_position = initial_position_;
  // N.B. This works due to lcm::Serializer<>::CreateDefaultValue() using
  // value-initialization.
  if (!lcm::AreLcmMessagesEqual(message, lcmt_schunk_wsg_command{})) {
    target_position = message.target_position_mm / 1e3;
    if (std::isnan(target_position)) {
      target_position = 0;
    }
  }

  output->SetAtIndex(0, target_position);
}

void SchunkWsgCommandReceiver::CalcForceLimitOutput(
    const Context<double>& context, BasicVector<double>* output) const {
  const auto& message =
      this->get_input_port(0).Eval<lcmt_schunk_wsg_command>(context);

  double force_limit = initial_force_;
  // N.B. This works due to lcm::Serializer<>::CreateDefaultValue() using
  // value-initialization.
  if (!lcm::AreLcmMessagesEqual(message, lcmt_schunk_wsg_command{})) {
    force_limit = message.force;
  }

  output->SetAtIndex(0, force_limit);
}

SchunkWsgCommandSender::SchunkWsgCommandSender(double default_force_limit)
    : position_input_port_(this->DeclareVectorInputPort(
                                   "position", systems::BasicVector<double>(1))
                               .get_index()),
      force_limit_input_port_(
          this->DeclareVectorInputPort("force_limit",
                                       systems::BasicVector<double>(1))
              .get_index()),
      default_force_limit_(default_force_limit) {
  this->DeclareAbstractOutputPort("lcmt_schunk_wsg_command",
                                  &SchunkWsgCommandSender::CalcCommandOutput);
}

void SchunkWsgCommandSender::CalcCommandOutput(
    const drake::systems::Context<double>& context,
    drake::lcmt_schunk_wsg_command* output) const {
  lcmt_schunk_wsg_command& command = *output;

  command.utime = context.get_time() * 1e6;
  command.target_position_mm = get_position_input_port().Eval(context)[0] * 1e3;
  if (get_force_limit_input_port().HasValue(context)) {
    command.force = get_force_limit_input_port().Eval(context)[0];
  } else {
    command.force = default_force_limit_;
  }
}

SchunkWsgStatusReceiver::SchunkWsgStatusReceiver()
    : state_output_port_(this->DeclareVectorOutputPort(
                                 "state", systems::BasicVector<double>(2),
                                 &SchunkWsgStatusReceiver::CopyStateOut)
                             .get_index()),
      force_output_port_(this->DeclareVectorOutputPort(
                                 "force", systems::BasicVector<double>(1),
                                 &SchunkWsgStatusReceiver::CopyForceOut)
                             .get_index()) {
  this->DeclareAbstractInputPort("lcmt_schunk_wsg_status",
                                 Value<lcmt_schunk_wsg_status>());
}

void SchunkWsgStatusReceiver::CopyStateOut(
    const drake::systems::Context<double>& context,
    drake::systems::BasicVector<double>* output) const {
  const auto& status =
      get_status_input_port().Eval<lcmt_schunk_wsg_status>(context);
  output->SetAtIndex(0, status.actual_position_mm / 1e3);
  output->SetAtIndex(1, status.actual_speed_mm_per_s / 1e3);
}

void SchunkWsgStatusReceiver::CopyForceOut(
    const drake::systems::Context<double>& context,
    drake::systems::BasicVector<double>* output) const {
  const auto& status =
      get_status_input_port().Eval<lcmt_schunk_wsg_status>(context);
  output->SetAtIndex(0, status.actual_force);
}

SchunkWsgStatusSender::SchunkWsgStatusSender() {
  state_input_port_ =
      this->DeclareInputPort(systems::kVectorValued, 2).get_index();
  force_input_port_ =
      this->DeclareInputPort(systems::kVectorValued, 1).get_index();
  this->DeclareAbstractOutputPort(&SchunkWsgStatusSender::OutputStatus);
}

void SchunkWsgStatusSender::OutputStatus(const Context<double>& context,
                                         lcmt_schunk_wsg_status* output) const {
  lcmt_schunk_wsg_status& status = *output;
  status.utime = context.get_time() * 1e6;

  const auto& state = get_state_input_port().Eval(context);
  // The position and speed reported in this message are between the
  // two fingers rather than the position/speed of a single finger
  // (so effectively doubled).
  status.actual_position_mm = state[0] * 1e3;
  status.actual_speed_mm_per_s = state[1] * 1e3;

  if (get_force_input_port().HasValue(context)) {
    // In drake-schunk-driver, the driver attempts to apply a sign to the
    // force value based on the last reported direction of gripper movement
    // (the gripper always reports positive values).  This does not work very
    // well, and as a result the sign is almost always negative (when
    // non-zero) regardless of which direction the gripper was moving in when
    // motion was blocked.  As it's not a reliable source of information in
    // the driver (and should be removed there at some point), we don't try to
    // replicate it here and instead report positive forces.
    using std::abs;
    status.actual_force = abs(get_force_input_port().Eval(context)[0]);
  } else {
    status.actual_force = 0;
  }
}

}  // namespace schunk_wsg
}  // namespace manipulation
}  // namespace drake

ext: cc


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

using namespace boost;

void communicate(asio::ip::tcp::socket& sock) {
	// Allocating and filling the buffer with
	// binary data.
	const char request_buf[] = { 0x48, 0x65, 0x0, 0x6c, 0x6c, 0x6f };

	// Sending the request data.
	asio::write(sock, asio::buffer(request_buf));

	// Shutting down the socket to let the
	// server know that we've sent the whole
	// request.
	sock.shutdown(asio::socket_base::shutdown_send);

	// We use extensible buffer for response
	// because we don't know the size of the
	// response message.
	asio::streambuf response_buf;

	system::error_code ec;
	asio::read(sock, response_buf, ec);

	if (ec == asio::error::eof) {
		// Whole response message has been received.
		// Here we can handle it.
	}
	else {
		throw system::system_error(ec);
	}
}

int main()
{
	std::string raw_ip_address = "127.0.0.1";
	unsigned short port_num = 3333;

	try {
		asio::ip::tcp::endpoint
			ep(asio::ip::address::from_string(raw_ip_address),
			port_num);

		asio::io_service ios;

		asio::ip::tcp::socket sock(ios, ep.protocol());

		sock.connect(ep);

		communicate(sock);
	}
	catch (system::system_error &e) {
		std::cout << "Error occured! Error code = " << e.code()
			<< ". Message: " << e.what();

		return e.code().value();
	}

	return 0;
}

ext: cpp

max_stars_repo_name: sinomiko/project

max_issues_repo_name: sinomiko/project

max_forks_repo_name: sinomiko/project


text:
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有（c）2009-2010 Satoshi Nakamoto
//版权所有（c）2009-2018比特币核心开发者
//根据MIT软件许可证分发，请参见随附的
//文件复制或http://www.opensource.org/licenses/mit-license.php。

#if defined(HAVE_CONFIG_H)
#include <config/bitcoin-config.h>
#endif

#include <util/time.h>

#include <atomic>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread.hpp>
#include <ctime>
#include <tinyformat.h>

static std::atomic<int64_t> nMockTime(0); //！<用于单元测试

int64_t GetTime()
{
    int64_t mocktime = nMockTime.load(std::memory_order_relaxed);
    if (mocktime) return mocktime;

    time_t now = time(nullptr);
    assert(now > 0);
    return now;
}

void SetMockTime(int64_t nMockTimeIn)
{
    nMockTime.store(nMockTimeIn, std::memory_order_relaxed);
}

int64_t GetMockTime()
{
    return nMockTime.load(std::memory_order_relaxed);
}

int64_t GetTimeMillis()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds();
    assert(now > 0);
    return now;
}

int64_t GetTimeMicros()
{
    int64_t now = (boost::posix_time::microsec_clock::universal_time() -
                   boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds();
    assert(now > 0);
    return now;
}

int64_t GetSystemTimeInSeconds()
{
    return GetTimeMicros()/1000000;
}

void MilliSleep(int64_t n)
{

/*
 *Boost的睡眠模式在1.50纳米级别的支持下是不间断的。
 *直到在1.52中固定。对损坏的案例使用已弃用的sleep方法。
 *参见：https://svn.boost.org/trac/boost/ticket/7238
 **/

#if defined(HAVE_WORKING_BOOST_SLEEP_FOR)
    boost::this_thread::sleep_for(boost::chrono::milliseconds(n));
#elif defined(HAVE_WORKING_BOOST_SLEEP)
    boost::this_thread::sleep(boost::posix_time::milliseconds(n));
#else
//不应该到这里
#error missing boost sleep implementation
#endif
}

std::string FormatISO8601DateTime(int64_t nTime) {
    struct tm ts;
    time_t time_val = nTime;
#ifdef _MSC_VER
    gmtime_s(&ts, &time_val);
#else
    gmtime_r(&time_val, &ts);
#endif
    return strprintf("%04i-%02i-%02iT%02i:%02i:%02iZ", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday, ts.tm_hour, ts.tm_min, ts.tm_sec);
}

std::string FormatISO8601Date(int64_t nTime) {
    struct tm ts;
    time_t time_val = nTime;
#ifdef _MSC_VER
    gmtime_s(&ts, &time_val);
#else
    gmtime_r(&time_val, &ts);
#endif
    return strprintf("%04i-%02i-%02i", ts.tm_year + 1900, ts.tm_mon + 1, ts.tm_mday);
}

std::string FormatISO8601Time(int64_t nTime) {
    struct tm ts;
    time_t time_val = nTime;
#ifdef _MSC_VER
    gmtime_s(&ts, &time_val);
#else
    gmtime_r(&time_val, &ts);
#endif
    return strprintf("%02i:%02i:%02iZ", ts.tm_hour, ts.tm_min, ts.tm_sec);
}

max_stars_repo_name: yinchengtsinghua/BitCoinCppChinese

max_issues_repo_name: yinchengtsinghua/BitCoinCppChinese

max_forks_repo_name: yinchengtsinghua/BitCoinCppChinese


text:
#include <sophus/se3.h>
#include <string>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <Eigen/StdVector>
// need pangolin for plotting trajectory
#include <pangolin/pangolin.h>

using namespace std;

// path to trajectory file
string trajectory_file = "./compare.txt";

// function for plotting trajectory, don't edit this code
// start point is red and end point is blue

/*******************************************************************************************/
void DrawTrajectoryc(vector<Sophus::SE3> poses1, vector<Sophus::SE3> poses2)
{
    if (poses1.empty() || poses2.empty())
    {
        cerr << "Trajectory is empty!" << endl;
        return;
    }

    // create pangolin window and plot the trajectory
    pangolin::CreateWindowAndBind("Trajectory Viewer", 1024, 768);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    pangolin::OpenGlRenderState s_cam(
        pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),
        pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0));

    pangolin::View &d_cam = pangolin::CreateDisplay()
                                .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)
                                .SetHandler(new pangolin::Handler3D(s_cam));

    while (pangolin::ShouldQuit() == false)
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        d_cam.Activate(s_cam);
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        glLineWidth(2);
        for (size_t i = 0; i < poses1.size() - 1; i++)
        {
            glColor3f(1 - (float)i / poses1.size(), 0.0f, (float)i / poses1.size());
            glBegin(GL_LINES);
            auto p1 = poses1[i], p2 = poses1[i + 1];
            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);
            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);
            glEnd();
        }

        for (size_t i = 0; i < poses2.size() - 1; i++)
        {
            glColor3f(1 - (float)i / poses2.size(), 0.0f, (float)i / poses2.size());
            glBegin(GL_LINES);
            auto p1 = poses2[i], p2 = poses2[i + 1];
            glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);
            glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);
            glEnd();
        }

        pangolin::FinishFrame();
        usleep(5000); // sleep 5 ms
    }
}

Sophus::SE3 pose_estimation_3d3d(vector<Sophus::SE3> poses1, vector<Sophus::SE3> poses2)
{

    Eigen::Vector3d center1, center2;
    int Number = poses1.size();
    for (int i = 0; i < N; i++)
    {
        center1 += poses1[i].translation();
        center2 += poses2[i].translation();
    }
    center1 = center1 / Number;
    center2 = center2 / Number;

    vector<Eigen::Vector3d> p1(Number), p2(Number);
    for (int i = 0; i < N; i++)
    {
        p1[i] = poses1[i] - center1;
        p2[i] = poses2[i] - center2;
    }

    Eigen::Matrix3d error = Eigen::Matrix3d::Zero();
    for (int i = 0; i < N; i++)
    {
        error += p1[i] * p2[i].transpose();
    }

    Eigen::JacobiSVD<Eigen::Matrix3d> svd(error, Eigen::ComputeFullU | Eigen::ComputeFullV);
    Eigen::Matrix3d U = svd.matrixU();
    Eigen::Matrix3d V = svd.matrixV();
    cout << "U=" << U << endl;
    cout << "V=" << V << endl;

    Eigen::Matrix3d R = U * (V.transpose());
    Eigen::Vector3d t = p1 - R * p2;
    Sophus::SE3 T(R,t);
    return T;
}

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

    vector<Sophus::SE3> poses1;
    vector<Sophus::SE3> poses2;

    /// implement pose reading code
    // start your code here (5~10 lines)

    ifstream fin(trajectory_file);
    for (int i = 0; i < 620; i++)
    {
        double data[8] = {0};
        for (auto &d : data)
            fin >> d;
        Eigen::Vector3d track1_t(data[1], data[2], data[3]);
        Eigen::Quaterniond track1_q(data[7], data[4], data[5], data[6]);
        Eigen::Vector3d track2_t(data[9], data[10], data[11]);
        Eigen::Quaterniond track2_q(data[12], data[13], data[14], data[15]);
        Sophus::SE3 SE3_1_qt(track1_q, track1_t);
        Sophus::SE3 SE3_2_qt(track2_q, track2_t);

        poses1.push_back(SE3_1_qt);
        poses2.push_back(SE3_2_qt);
    }
    // end your code here

    Sophus::SE3 T = pose_estimation_3d3d(vector<Sophus::SE3> poses1, vector<Sophus::SE3> poses2);
    for (int k = 0 ;k <poses2.size();k++)
    {
        poses2[k]  = T*poses2[k];
    }

    // draw trajectory in pangolin
    DrawTrajectory(poses1, poses2);

    return 0;
}

max_stars_repo_name: Yvon-Shong/SLAM


text:
#include <cradle/geometry/grid_points.hpp>
#include <cradle/geometry/regular_grid.hpp>

#include <boost/assign/std/vector.hpp>

#include <cradle/test.hpp>

using namespace cradle;
using namespace boost::assign;

TEST_CASE("regular_grid_test")
{
    regular_grid<1, float> default_constructed;

    vector2d p0 = make_vector<double>(0, 0);
    vector2d spacing = make_vector<double>(1, 0.5);
    vector2u n_points = make_vector<unsigned>(2, 3);

    regular_grid<2, double> grid(p0, spacing, n_points);
    REQUIRE(grid.p0 == p0);
    REQUIRE(grid.spacing == spacing);
    REQUIRE(grid.n_points == n_points);

    std::vector<vector2d> correct_points;
    correct_points += make_vector<double>(0, 0), make_vector<double>(1, 0),
        make_vector<double>(0, 0.5), make_vector<double>(1, 0.5),
        make_vector<double>(0, 1), make_vector<double>(1, 1);
    CRADLE_CHECK_RANGES_ALMOST_EQUAL(
        make_grid_point_list(grid), correct_points);
}

TEST_CASE("grid_bounding_box_test")
{
    vector2d p0 = make_vector<double>(-1, 0);
    vector2d spacing = make_vector<double>(1, 0.5);
    vector2u n_points = make_vector<unsigned>(2, 3);

    regular_grid<2, double> grid(p0, spacing, n_points);

    REQUIRE(
        bounding_box(grid)
        == box2d(make_vector<double>(-1, 0), make_vector<double>(1, 1)));
}

vector3d
get_point_at_index(regular_grid<3, double> const& grid, size_t index)
{
    size_t x_index = index % grid.n_points[0];
    size_t y_index = (index / grid.n_points[0]) % grid.n_points[1];
    size_t z_index = (index / grid.n_points[0]) / grid.n_points[1];
    return make_vector(
        grid.p0[0] + x_index * grid.spacing[0],
        grid.p0[1] + y_index * grid.spacing[1],
        grid.p0[2] + z_index * grid.spacing[2]);
}

max_stars_repo_name: mghro/astroid-core

max_issues_repo_name: mghro/astroid-core

max_forks_repo_name: mghro/astroid-core


text:
#include <boost/test/unit_test.hpp>

#include "combinatoire.h"

BOOST_AUTO_TEST_SUITE(test_combinatoire)

    BOOST_AUTO_TEST_CASE(coefficient_binomial) {
        BOOST_CHECK_EQUAL(35, combinatoire::coefficient_binomial(7, 3));
        BOOST_CHECK_EQUAL(70, combinatoire::coefficient_binomial(8, 4));
        BOOST_CHECK_EQUAL(1, combinatoire::coefficient_binomial(40, 0));
    }

    BOOST_AUTO_TEST_CASE(catalan) {
        BOOST_CHECK_EQUAL(1, combinatoire::catalan(0));
        BOOST_CHECK_EQUAL(1, combinatoire::catalan(1));
        BOOST_CHECK_EQUAL(16796, combinatoire::catalan<unsigned long long>(10));
    }

    BOOST_AUTO_TEST_CASE(factorielle) {
        BOOST_CHECK_EQUAL(120, combinatoire::factorielle(5));
        BOOST_CHECK_EQUAL(720, combinatoire::factorielle(6));
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ZongoForSpeed/ProjectEuler

max_issues_repo_name: ZongoForSpeed/ProjectEuler

max_forks_repo_name: ZongoForSpeed/ProjectEuler


text:
#include "moses/StaticData.h"
#include "moses/FactorCollection.h"
#include <boost/functional/hash.hpp>
#include "NeuralLMWrapper.h"
#include "neuralLM.h"

using namespace std;

namespace Moses
{
NeuralLMWrapper::NeuralLMWrapper(const std::string &line)
  :LanguageModelSingleFactor(line)
{
  ReadParameters();
}

NeuralLMWrapper::~NeuralLMWrapper()
{
  delete m_neuralLM_shared;
}

void NeuralLMWrapper::Load(AllOptions::ptr const& opts)
{

  // Set parameters required by ancestor classes
  FactorCollection &factorCollection = FactorCollection::Instance();
  m_sentenceStart = factorCollection.AddFactor(Output, m_factorType, BOS_);
  m_sentenceStartWord[m_factorType] = m_sentenceStart;
  m_sentenceEnd		= factorCollection.AddFactor(Output, m_factorType, EOS_);
  m_sentenceEndWord[m_factorType] = m_sentenceEnd;

  m_neuralLM_shared = new nplm::neuralLM();
  m_neuralLM_shared->read(m_filePath);
  m_neuralLM_shared->premultiply();
  //TODO: config option?
  m_neuralLM_shared->set_cache(1000000);

  m_unk = m_neuralLM_shared->lookup_word("<unk>");

  UTIL_THROW_IF2(m_nGramOrder != m_neuralLM_shared->get_order(),
                 "Wrong order of neuralLM: LM has " << m_neuralLM_shared->get_order() << ", but Moses expects " << m_nGramOrder);

}

LMResult NeuralLMWrapper::GetValue(const vector<const Word*> &contextFactor, State* finalState) const
{

  if (!m_neuralLM.get()) {
    m_neuralLM.reset(new nplm::neuralLM(*m_neuralLM_shared));
    //TODO: config option?
    m_neuralLM->set_cache(1000000);
  }

  vector<int> words(contextFactor.size());
  const size_t n = contextFactor.size();
  for (size_t i=0; i<n; i++) {
    const Word* word = contextFactor[i];
    const Factor* factor = word->GetFactor(m_factorType);
    const std::string string = factor->GetString().as_string();
    int neuralLM_wordID = m_neuralLM->lookup_word(string);
    words[i] = neuralLM_wordID;
  }
  // Generate hashCode for only the last n-1 words, that represents the next LM
  // state
  size_t hashCode = 0;
  for (size_t i=1; i<n; ++i) {
    boost::hash_combine(hashCode, words[i]);
  }

  double value = m_neuralLM->lookup_ngram(words);

  // Create a new struct to hold the result
  LMResult ret;
  ret.score = FloorScore(value);
  ret.unknown = (words.back() == m_unk);

  (*finalState) = (State*) hashCode;

  return ret;
}

}


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

namespace UtilitiesTests
{
    using namespace ktl;
    using namespace Data::Utilities;

    class AsyncLockTest
    {
    public:
        Common::CommonConfig config; // load the config object as its needed for the tracing to work

        AsyncLockTest()
        {
            NTSTATUS status;
            status = KtlSystem::Initialize(FALSE, &ktlSystem_);
            CODING_ERROR_ASSERT(NT_SUCCESS(status));
            ktlSystem_->SetStrictAllocationChecks(TRUE);
        }

        ~AsyncLockTest()
        {
            ktlSystem_->Shutdown();
        }

        KAllocator& GetAllocator()
        {
            return ktlSystem_->PagedAllocator();
        }

        AsyncLock::SPtr CreateAsyncLock()
        {
            AsyncLock::SPtr lock;

            NTSTATUS status = AsyncLock::Create(
                GetAllocator(),
                'TEST',
                lock);

            ASSERT_IFNOT(
                NT_SUCCESS(status),
                "Failed to create async write lock with {0}",
                status);

            return lock;
        }

    public:
        KtlSystem* ktlSystem_;
    };

    BOOST_FIXTURE_TEST_SUITE(AsyncLockTestSuite, AsyncLockTest)

    BOOST_AUTO_TEST_CASE(NewLockMustAcquireImmediately)
    {
        AsyncLock::SPtr lock = CreateAsyncLock();

        bool result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::MaxValue));
        VERIFY_IS_TRUE(result, L"Lock acquistion should pass");
        lock->ReleaseLock();
    }

    BOOST_AUTO_TEST_CASE(SerialAcquire)
    {
        AsyncLock::SPtr lock = CreateAsyncLock();

        bool result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::FromMilliseconds(1)));
        VERIFY_IS_TRUE(result, L"Lock acquistion should pass");
        lock->ReleaseLock();

        result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::FromMilliseconds(1)));
        VERIFY_IS_TRUE(result, L"Lock acquistion should pass");
        lock->ReleaseLock();
    }

    BOOST_AUTO_TEST_CASE(LockTimeout)
    {
        AsyncLock::SPtr lock = CreateAsyncLock();

        bool result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::MaxValue));
        VERIFY_IS_TRUE(result, L"Lock acquistion should pass");

        result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::FromMilliseconds(1)));
        VERIFY_IS_FALSE(result, L"Lock acquistion should fail");

        lock->ReleaseLock();
        result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::FromMilliseconds(1)));
        VERIFY_IS_TRUE(result, L"Lock acquistion should pass");
        lock->ReleaseLock();
    }

    BOOST_AUTO_TEST_CASE(SingleEntrancyTest)
    {
        AsyncLock::SPtr lock = CreateAsyncLock();

        bool result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::MaxValue));
        VERIFY_IS_TRUE(result, L"Lock acquistion should pass");

        Common::atomic_long countOfAcquired(1);
        Common::atomic_long totalCount(0);

        Common::Random r;

        Common::Threadpool::Post([&]
        {
            long count = --countOfAcquired;
            VERIFY_IS_TRUE(count == 0, L"Count must be 0");
            lock->ReleaseLock();
        },
        Common::TimeSpan::FromMilliseconds(r.Next(10)));

        int threadCount = 200;

        // While the above is acquired, start many threads that wait on the same lock and ensure only 1 of them acquires it successfully each time
        for (int i = 0; i < threadCount; i++)
        {
            Common::Threadpool::Post([&]
            {
                bool result = SyncAwait(lock->AcquireAsync(Common::TimeSpan::MaxValue));
                VERIFY_IS_TRUE(result, L"Lock acqusition should pass");

                long count = ++countOfAcquired;
                VERIFY_IS_TRUE(count == 1, L"Count must be 1");
                Sleep(10);
                count = --countOfAcquired;
                VERIFY_IS_TRUE(count == 0, L"Count must be 0");

                lock->ReleaseLock();
                totalCount++;
            },
            Common::TimeSpan::FromMilliseconds(r.Next(10)));
        }

        while (totalCount.load() < threadCount)
        {
            Sleep(1000);
        }
    }

    BOOST_AUTO_TEST_SUITE_END()
}

max_stars_repo_name: AnthonyM/service-fabric

max_issues_repo_name: AnthonyM/service-fabric

max_forks_repo_name: AnthonyM/service-fabric


text:
#include <algorithm>
#include <iostream>
#include "tile_data.h"

#include <ciso646>
#include <boost/sort/sort.hpp>

using namespace std;

typedef std::pair<OutputObjectsConstIt,OutputObjectsConstIt> OutputObjectsConstItPair;

void TileDataSource::MergeTileCoordsAtZoom(uint zoom, uint baseZoom, const TileIndex &srcTiles, TileCoordinatesSet &dstCoords) {
	if (zoom==baseZoom) {
		// at z14, we can just use tileIndex
		for (auto it = srcTiles.begin(); it!= srcTiles.end(); ++it) {
			TileCoordinates index = it->first;
			dstCoords.insert(index);
		}
	} else {
		// otherwise, we need to run through the z14 list, and assign each way
		// to a tile at our zoom level
		for (auto it = srcTiles.begin(); it!= srcTiles.end(); ++it) {
			TileCoordinates index = it->first;
			TileCoordinate tilex = index.x / pow(2, baseZoom-zoom);
			TileCoordinate tiley = index.y / pow(2, baseZoom-zoom);
			TileCoordinates newIndex(tilex, tiley);
			dstCoords.insert(newIndex);
		}
	}
}

void TileDataSource::MergeSingleTileDataAtZoom(TileCoordinates dstIndex, uint zoom, uint baseZoom, const TileIndex &srcTiles, std::vector<OutputObjectRef> &dstTile) {
	if (zoom==baseZoom) {
		// at z14, we can just use tileIndex
		auto oosetIt = srcTiles.find(dstIndex);
		if(oosetIt == srcTiles.end()) return;
		dstTile.insert(dstTile.end(), oosetIt->second.begin(), oosetIt->second.end());
	} else {
		// otherwise, we need to run through the z14 list, and assign each way
		// to a tile at our zoom level
		int scale = pow(2, baseZoom-zoom);
		TileCoordinates srcIndex1(dstIndex.x*scale, dstIndex.y*scale);
		TileCoordinates srcIndex2((dstIndex.x+1)*scale, (dstIndex.y+1)*scale);

		for(int x=srcIndex1.x; x<srcIndex2.x; x++)
		{
			for(int y=srcIndex1.y; y<srcIndex2.y; y++)
			{
				TileCoordinates srcIndex(x, y);
				auto oosetIt = srcTiles.find(srcIndex);
				if(oosetIt == srcTiles.end()) continue;
				for (auto it = oosetIt->second.begin(); it != oosetIt->second.end(); ++it) {
					OutputObjectRef oo = *it;
					if (oo->minZoom > zoom) continue;
					dstTile.insert(dstTile.end(), oo);
				}
			}
		}
	}
}

TileCoordinatesSet GetTileCoordinates(std::vector<class TileDataSource *> const &sources, unsigned int zoom) {
	TileCoordinatesSet tileCoordinates;

	// Create list of tiles
	tileCoordinates.clear();
	for(size_t i=0; i<sources.size(); i++)
		sources[i]->MergeTileCoordsAtZoom(zoom, tileCoordinates);

	return tileCoordinates;
}

std::vector<OutputObjectRef> GetTileData(std::vector<class TileDataSource *> const &sources, TileCoordinates coordinates, unsigned int zoom)
{
	std::vector<OutputObjectRef> data;
	for(size_t i=0; i<sources.size(); i++)
		sources[i]->MergeSingleTileDataAtZoom(coordinates, zoom, data);

	boost::sort::pdqsort(data.begin(), data.end());
	data.erase(unique(data.begin(), data.end()), data.end());
	return data;
}

OutputObjectsConstItPair GetObjectsAtSubLayer(std::vector<OutputObjectRef> const &data, uint_least8_t layerNum) {
    struct layerComp
    {
        bool operator() ( const OutputObjectRef &x, uint_least8_t layer ) const { return x->layer < layer; }
        bool operator() ( uint_least8_t layer, const OutputObjectRef &x ) const { return layer < x->layer; }
    };

	// compare only by `layer`
	// We get the range within ooList, where the layer of each object is `layerNum`.
	// Note that ooList is sorted by a lexicographic order, `layer` being the most significant.
	return equal_range(data.begin(), data.end(), layerNum, layerComp());
}

max_stars_repo_name: typebrook/tilemaker

max_issues_repo_name: typebrook/tilemaker

max_forks_repo_name: typebrook/tilemaker


text:
//////////////////////////////////////////////////////////////////////////////
// random::students_t_distribution.hpp                                      //
//                                                                          //
//                                                                          //
//  (C) Copyright 2009 Erwann Rogard                                        //
//  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)        //
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_RANDOM_STUDENTS_T_HPP_ER_2009
#define BOOST_RANDOM_STUDENTS_T_HPP_ER_2009
#include <vector>
#include <algorithm>
#include <iterator>
#include <boost/range.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/chi_squared.hpp>

namespace boost{
namespace random{

    // Samples from a students_t distribution
    template<typename T>
    class students_t_distribution{
            typedef boost::normal_distribution<T>           nd_;
            typedef random::chi_squared_distribution<T>     cs_;
        public:
            typedef typename nd_::input_type input_type;
            typedef typename nd_::result_type result_type;

        students_t_distribution():df_(2){}
        students_t_distribution(unsigned df):df_(df){}

        template<typename U>
        result_type
        operator()(U& urng){
            static nd_ nd(0,1);
            static cs_ cs(df_);
            result_type z = nd(urng);
            result_type d = cs(urng);
            d /= static_cast<result_type>(df_);
            d = sqrt(d);
            return z / d;
        }

        unsigned df()const{ return df_; }

        private:
            unsigned df_;
    };

}// random
}// boost

#endif


text:
#include "StdAfx.h"

#include "CSAuthenticated.h"
#include "AssetClient.h"
#include "RequestError.h"
#include "Validator.h"
#include "AssetServer.h"

#include <boost/bind.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <sstream>

namespace pt = boost::posix_time;

/*whip::ObjectPool<ServerResponseMsg::ptr, ServerResponseMsgCreator> CSAuthenticated::s_ResponsePool
	= whip::ObjectPool<ServerResponseMsg::ptr, ServerResponseMsgCreator>(ServerResponseMsgCreator());*/

CSAuthenticated::CSAuthenticated(boost::asio::io_service& ioService, IAsyncStorageBackend::ptr storage,
								 iwintramesh::MeshStorageBackend::ptr meshStorage,
								 bool isMeshConnection)
: _ioService(ioService), _storage(storage), _meshStorage(meshStorage), _isMeshConnection(isMeshConnection),
	_isActive(false), _activeSince(pt::second_clock::local_time())
{
}

CSAuthenticated::~CSAuthenticated()
{
}

void CSAuthenticated::setClient(AssetClientPtr client)
{
	_client = client;
}

void CSAuthenticated::waitForRequest()
{
	_currentRequest.reset(new ClientRequestMsg());
	_isActive = false;

	AssetClient::ptr client;
	if (client = _client.lock()) {
		boost::asio::async_read(client->getConn(),
			boost::asio::buffer(_currentRequest->getHeaderData(), ClientRequestMsg::HEADER_SIZE),
			boost::bind(
			  &CSAuthenticated::handleClientRequestHeaderRead, shared_from_this(),
				boost::asio::placeholders::error));
	}
}

void CSAuthenticated::handleClientRequestHeaderRead(const boost::system::error_code& error)
{
	if (! error) {
		//we now have a complete header, read it and figure out what type of message we're dealing with
		try {
			//if were here we got a request. Update stats
			AssetClient::AddRequestToStats();

			_isActive = true;
			_activeSince = pt::second_clock::local_time();

			switch (_currentRequest->getType()) {
				case ClientRequestMsg::RT_GET:
					this->handleGetRequest(true);
					break;

				case ClientRequestMsg::RT_PURGE:
					this->handlePurgeRequest();
					break;

				case ClientRequestMsg::RT_PUT:
					this->handlePutRequest();
					break;

				case ClientRequestMsg::RT_TEST:
					this->handleTestRequest();
					break;

				case ClientRequestMsg::RT_MAINT_PURGELOCALS:
					this->handlePurgeLocals();
					break;

				case ClientRequestMsg::RT_STATUS_GET:
					this->handleStatusGet();
					break;

				case ClientRequestMsg::RT_STORED_ASSET_IDS_GET:
					this->handleStoredAssetIdsGet();
					break;

				case ClientRequestMsg::RT_GET_DONTCACHE:
					this->handleGetRequest(false);
					break;

				default:
					throw RequestError("Invalid request type sent to server");
			}

		} catch (const std::exception& e) {
			SAFELOG(AppLog::instance().out() << "handleClientRequestHeaderRead(): Error while processing header: "
				<< e.what() << std::endl);

			AssetClient::ptr client;
			if (client = _client.lock()) {
				client->disconnect();
			}
		}

	} else {
		this->handleIoFailure(__FUNCTION__, error);

	}
}

void CSAuthenticated::handleStatusGet()
{
	_statusStream.reset(new std::stringstream());
	(*_statusStream) << "WHIP Server Status" << std::endl << std::endl;

	if (AssetClient::ptr client = _client.lock()) {
		AssetServer& server(client->getParentServer());
		server.getStatus(_statusStream);

		_storage->getStatus(_statusStream, boost::bind(&CSAuthenticated::statusGetCompleted, this));
	}
}

void CSAuthenticated::statusGetCompleted()
{
	_meshStorage->getStatus(_statusStream);

	ServerResponseMsg::ptr currentResponse(
		new ServerResponseMsg(ServerResponseMsg::RC_OK, "00000000000000000000000000000000", _statusStream->str()));

	_statusStream.reset();

	this->sendResponse(currentResponse);
}

void CSAuthenticated::handleStoredAssetIdsGet()
{
	_assetIdStream.reset(new std::stringstream());

	if (AssetClient::ptr client = _client.lock()) {
		AssetServer& server(client->getParentServer());

		std::string uuidStr(_currentRequest->getUUID());
		std::string prefix(uuidStr.substr(0, 3));
		_storage->getStoredAssetIDsWithPrefix(prefix, _assetIdStream, boost::bind(&CSAuthenticated::storedAssetIdsGetCompleted, this));
	}
}

void CSAuthenticated::storedAssetIdsGetCompleted()
{
	ServerResponseMsg::ptr currentResponse(
		new ServerResponseMsg(ServerResponseMsg::RC_OK, "00000000000000000000000000000000", _assetIdStream->str()));

	_assetIdStream.reset();

	this->sendResponse(currentResponse);
}

void CSAuthenticated::handleIoFailure(const std::string& method, const boost::system::error_code& error)
{
	AssetClient::ptr client;
	if (client = _client.lock()) {
		client->disconnect();
		SAFELOG(AppLog::instance().out() << method << ": Connection failed " << error.message() << std::endl);
	} else {
		SAFELOG(AppLog::instance().error() << method << ": Client instance disappeared" << std::endl);
	}
}

void CSAuthenticated::handleGetRequest(bool cacheResult)
{
	try {
		//validate asset UUID
		if (! Validator::IsValidUUID(_currentRequest->getUUID())) {
			//invalid asset id
			throw std::runtime_error("Invalid asset UUID: " + _currentRequest->getUUID());
		}

		unsigned int flags = SF_NONE;
		if (! cacheResult) {
			flags = SF_DONTCACHE;
		}

		_storage->getAsset(_currentRequest->getUUID(), flags,
			boost::bind(&CSAuthenticated::handleStorageGetResponse, this, _1, _2, _3));

	} catch (const std::exception& e) {
		SAFELOG(AppLog::instance().out() << __FUNCTION__ << ":  Unable to fetch asset: " << e.what() << std::endl);

		//send the error to the client
		this->sendError(e.what());
	}
}

void CSAuthenticated::handleStorageGetResponse(Asset::ptr foundAsset, bool success, AssetStorageError::ptr error)
{
	if (success) {
		//start working with a new response message
		ServerResponseMsg::ptr currentResponse(new ServerResponseMsg(ServerResponseMsg::RC_FOUND, foundAsset->getUUID(), foundAsset->getData()));

		//set the response to the client
		this->sendResponse(currentResponse);

	} else {

		if (error && error->isCritical()) {
			SAFELOG(AppLog::instance().error() << __FUNCTION__ << ":  Asset read failed: " << error->what() << std::endl);
		}

		if (! _isMeshConnection) {
			//try intramesh
			_meshStorage->getAsset(_currentRequest->getUUID(), boost::bind(&CSAuthenticated::handleIntrameshGetResponse, this, _1, _2));

		} else {
			//if this is a mesh connection and lookup fails for any reason we do NOT retry intramesh
			ServerResponseMsg::ptr currentResponse(new ServerResponseMsg(ServerResponseMsg::RC_NOTFOUND, _currentRequest->getUUID()));

			//set the response to the client
			this->sendResponse(currentResponse);
		}
	}
}

void CSAuthenticated::handleIntrameshGetResponse(std::string uuid, Asset::ptr foundAsset)
{
	if (foundAsset) {
		//start working with a new response message
		ServerResponseMsg::ptr currentResponse(new ServerResponseMsg(ServerResponseMsg::RC_FOUND, foundAsset->getUUID(), foundAsset->getData()));

		//set the response to the client
		this->sendResponse(currentResponse);

	} else {
		//start working with a new response message
		ServerResponseMsg::ptr currentResponse(new ServerResponseMsg(ServerResponseMsg::RC_NOTFOUND, uuid));

		//set the response to the client
		this->sendResponse(currentResponse);
	}
}

void CSAuthenticated::sendError(const std::string& errorMsg)
{
	ServerResponseMsg::ptr response(new ServerResponseMsg(ServerResponseMsg::RC_ERROR, _currentRequest->getUUID(), errorMsg));

	//set the error to the client
	this->sendResponse(response);
}

void CSAuthenticated::sendResponse(ServerResponseMsg::ptr response)
{
	AssetClient::ptr client;
	if (client = _client.lock()) {
		//send the asset header
		boost::asio::async_write(client->getConn(),
			boost::asio::buffer(response->getHeader(), response->getHeader().size()),
			boost::bind(&CSAuthenticated::handleResponseHeaderWrite, shared_from_this(),
				  boost::asio::placeholders::error, response));

	}
}

void CSAuthenticated::handleResponseHeaderWrite(const boost::system::error_code& error,
												ServerResponseMsg::ptr response)
{
	if (! error) {
		//no error, we can write the packet data now, if any

		//any data?
		if (response->getData()) {

			AssetClient::ptr client;
			if (client = _client.lock()) {
				//yes, send the contents and update stats
				whip::byte_array_ptr data(response->getData());
				boost::asio::async_write(client->getConn(),
					boost::asio::buffer(*data, data->size()),
					boost::bind(&CSAuthenticated::handleResponseDataWrite, shared_from_this(),
						  boost::asio::placeholders::error, response));

				AssetClient::AddTransferToStats(boost::numeric_cast<int>(data->size()));

				if (_isMeshConnection) {
					AssetClient::AddMeshTransferToStats(boost::numeric_cast<int>(data->size()));
				}
			}

		} else {
			//no, start waiting for another request

			this->waitForRequest();

		}

	} else {
		this->handleIoFailure(__FUNCTION__, error);
	}
}

void CSAuthenticated::handleResponseDataWrite(const boost::system::error_code& error,
											  ServerResponseMsg::ptr response)
{
	if (! error) {
		//data write complete, clear the response and wait for next request
		this->waitForRequest();

	} else {
		//we had an error
		this->handleIoFailure(__FUNCTION__, error);

	}
}

void CSAuthenticated::handleStoragePurgeResponse(bool success, AssetStorageError::ptr error)
{
	if (success) {
		//start working with a new response message
		ServerResponseMsg::ptr response(new ServerResponseMsg(ServerResponseMsg::RC_OK, _currentRequest->getUUID()));

		//set the response to the client
		this->sendResponse(response);
	} else {
		//send the error to the client
		this->sendError(error->what());
	}
}

void CSAuthenticated::handlePurgeRequest()
{
	try {
		//validate asset UUID
		if (! Validator::IsValidUUID(_currentRequest->getUUID())) {
			//invalid asset id
			throw std::runtime_error("Invalid asset UUID: " + _currentRequest->getUUID());
		}

		//ask storage to purge the asset
		_storage->purgeAsset(_currentRequest->getUUID(),
			boost::bind(&CSAuthenticated::handleStoragePurgeResponse, this, _1, _2));

	} catch (const std::exception& e) {
		SAFELOG(AppLog::instance().out() << __FUNCTION__ << ":  Unable to purge asset: " << e.what() << std::endl);

		//send the error to the client
		this->sendError(e.what());
	}
}

void CSAuthenticated::handlePutRequest()
{
	//init the data section of our request
	_currentRequest->initDataStorageFromHeader();

	AssetClient::ptr client;
	if (client = _client.lock()) {
		//read the rest of the incoming data
		boost::asio::async_read(client->getConn(),
			boost::asio::buffer(*_currentRequest->getData(), _currentRequest->getDataSize()),
			boost::bind(
			  &CSAuthenticated::handleAssetDataRead, shared_from_this(),
				boost::asio::placeholders::error));
	}
}

void CSAuthenticated::handleStorageWriteResponse(bool success, AssetStorageError::ptr error)
{
	if (success) {
		//start working with a new response message
		ServerResponseMsg::ptr response(new ServerResponseMsg(ServerResponseMsg::RC_OK, _currentRequest->getUUID()));

		//set the response to the client
		this->sendResponse(response);

	} else {

		if (error && error->isCritical()) {
			SAFELOG(AppLog::instance().error() << __FUNCTION__ << ":  Asset write failed: " << error->what() << std::endl);
		}

		this->sendError(error->what());

	}

	//update asset stats
	AssetClient::AddTransferToStats(_currentRequest->getDataSize());
}

void CSAuthenticated::handleAssetDataRead(const boost::system::error_code& error)
{
	if (! error) {
		try {
			//create an asset from the data given
			Asset::ptr newAsset(new Asset(_currentRequest->getData()));

			//validate asset UUID
			if (! Validator::IsValidUUID(newAsset->getUUID())) {
				//invalid asset id
				throw std::runtime_error("Invalid asset UUID: " + _currentRequest->getUUID());
			}

			//ask storage to save the asset
			_storage->storeAsset(newAsset, boost::bind(&CSAuthenticated::handleStorageWriteResponse, this, _1, _2));

		} catch (const std::exception& e) {
			SAFELOG(AppLog::instance().out() << __FUNCTION__ << ":  Unable to store asset: " << e.what() << std::endl);

			//send the error to the client
			this->sendError(e.what());
		}

	} else {
		this->handleIoFailure(__FUNCTION__, error);
	}
}

void CSAuthenticated::handleTestRequest()
{
	try {
		//validate asset UUID
		if (! Validator::IsValidUUID(_currentRequest->getUUID())) {
			//invalid asset id
			throw std::runtime_error("Invalid asset UUID: " + _currentRequest->getUUID());
		}

		//ask storage if we have this asset
		bool haveAsset = _storage->assetExists(_currentRequest->getUUID());

		ServerResponseMsg::ResponseCode responseCode;
		if (haveAsset) responseCode = ServerResponseMsg::RC_FOUND;
		else responseCode = ServerResponseMsg::RC_NOTFOUND;

		//start working with a new response message
		ServerResponseMsg::ptr response(new ServerResponseMsg(responseCode, _currentRequest->getUUID()));

		//set the response to the client
		this->sendResponse(response);

	} catch (const std::exception& e) {
		SAFELOG(AppLog::instance().out() << __FUNCTION__ << ":  Unable to test for asset: " << e.what() << std::endl);

		//send the error to the client
		this->sendError(e.what());
	}
}

void CSAuthenticated::handlePurgeLocals()
{
	try {
		_storage->beginPurgeLocals();

		//start working with a new response message
		ServerResponseMsg::ptr response(new ServerResponseMsg(ServerResponseMsg::RC_OK, "00000000000000000000000000000000"));

		//set the response to the client
		this->sendResponse(response);

	} catch (const std::exception& e) {
		SAFELOG(AppLog::instance().out() << __FUNCTION__ << ":  Unable to test for asset: " << e.what() << std::endl);

		//send the error to the client
		this->sendError(e.what());
	}
}

void CSAuthenticated::start()
{
	AssetClient::ptr client;
	if (client = _client.lock()) {
		SAFELOG(AppLog::instance().out() << "Client authentication successful > " << client->getConn().remote_endpoint().address().to_string() << std::endl);

		this->waitForRequest();
	}
}

std::string CSAuthenticated::getStateDescription()
{
	if (_isActive) {
		std::string status;
		status = "ACTIVE " + pt::to_simple_string(pt::second_clock::local_time() - _activeSince);

		if (_currentRequest) {
			if (_currentRequest->getType() == ClientRequestMsg::RT_GET) {
				status += " [GET " + _currentRequest->getUUID() + "]";

			} else if (_currentRequest->getType() == ClientRequestMsg::RT_PUT) {
				status += " [PUT " + _currentRequest->getUUID() + "]";

			}
		}

		return status;

	} else {
		return "IDLE " + pt::to_simple_string(pt::second_clock::local_time() - _activeSince);
	}
}