text:
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef NBDL_BIND_VARIANT_HPP
#define NBDL_BIND_VARIANT_HPP

#include <nbdl/fwd/bind_variant.hpp>

#include <nbdl/concept/BindableVariant.hpp>
#include <nbdl/detail/filter_empties.hpp>

#include <boost/hana/core/tag_of.hpp>
#include <type_traits>
#include <utility>

namespace nbdl {
  template <BindableVariant BindableVariant, typename BindFn>
  constexpr auto bind_variant_fn::operator()(int const type_id,
                                             BindableVariant&& v,
                                             BindFn&& f) const {
    using Tag = hana::tag_of_t<BindableVariant>;
    using Impl = bind_variant_impl<Tag>;

    return Impl::apply(
      type_id,
      std::forward<BindableVariant>(v),
      detail::filter_empties_fn<std::decay_t<BindFn>>{std::forward<BindFn>(f)}
    );
  };

  template <BindableVariant BindableVariant, typename BindFn>
  constexpr auto bind_variant_fn::operator()(BindableVariant const& v,
                                             BindFn&& f) const {
    using Tag = hana::tag_of_t<BindableVariant>;
    using Impl = bind_variant_impl<Tag>;

    return Impl::apply(
      v,
      detail::filter_empties_fn<std::decay_t<BindFn>>{std::forward<BindFn>(f)}
    );
  };
}

#endif

ext: hpp

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


text:
/*
 * Copyright 2021 MusicScience37 (Kenta Kabashima)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*!
 * \file
 * \brief Test of blurred sine function.
 */
#include "num_prob_collect/regularization/blur_sine.h"

#include <cmath>
#include <random>

#include <Eigen/Core>
#include <celero/Celero.h>

#include "log_error_udm.h"
#include "log_param_udm.h"
#include "num_collect/regularization/explicit_gcv.h"
#include "num_collect/regularization/explicit_l_curve.h"
#include "num_collect/regularization/full_gen_tikhonov.h"
#include "num_collect/regularization/tikhonov.h"
#include "num_prob_collect/regularization/dense_diff_matrix.h"

// NOLINTNEXTLINE: external library
CELERO_MAIN

class blur_sine_fixture : public celero::TestFixture {
public:
    blur_sine_fixture() = default;

    [[nodiscard]] auto getExperimentValues() const
        -> std::vector<celero::TestFixture::ExperimentValue> override {
        std::vector<celero::TestFixture::ExperimentValue> problem_space;
        problem_space.emplace_back(-100);  // NOLINT
        problem_space.emplace_back(-4);    // NOLINT
        problem_space.emplace_back(-2);    // NOLINT
        problem_space.emplace_back(0);     // NOLINT
        return problem_space;
    }

    void setUp(
        const celero::TestFixture::ExperimentValue& experiment_value) override {
        error_rate_ = std::pow(10.0,  // NOLINT
            static_cast<int>(experiment_value.Value));
        std::mt19937 engine;  // NOLINT
        std::normal_distribution<double> dist{0.0,
            std::sqrt(prob_.data().squaredNorm() /
                static_cast<double>(prob_.data().size()) * error_rate_)};
        data_with_error_ = prob_.data();
        for (num_collect::index_type i = 0; i < data_with_error_.size(); ++i) {
            data_with_error_(i) += dist(engine);
        }
    }

    void set_error(const Eigen::VectorXd& solution) {
        log_error_->addValue(
            std::log10((solution - prob_.solution()).squaredNorm() /
                prob_.solution().squaredNorm()));
    }

    void set_param(double val) { log_param_->addValue(std::log10(val)); }

    [[nodiscard]] auto getUserDefinedMeasurements() const -> std::vector<
        std::shared_ptr<celero::UserDefinedMeasurement>> override {
        return {log_error_, log_param_};
    }

    [[nodiscard]] auto prob() const
        -> const num_prob_collect::regularization::blur_sine& {
        return prob_;
    }

    [[nodiscard]] auto data_with_error() const -> const Eigen::VectorXd& {
        return data_with_error_;
    }

    [[nodiscard]] auto dense_diff_matrix() const -> const Eigen::MatrixXd& {
        return dense_diff_matrix_;
    }

private:
    double error_rate_{};

#ifndef NDEBUG
    static constexpr num_collect::index_type solution_size = 30;
    static constexpr num_collect::index_type data_size = solution_size;
#else
    static constexpr num_collect::index_type solution_size = 60;
    static constexpr num_collect::index_type data_size = solution_size;
#endif
    const num_prob_collect::regularization::blur_sine prob_{
        data_size, solution_size};

    Eigen::VectorXd data_with_error_{};

    const Eigen::MatrixXd dense_diff_matrix_{
        num_prob_collect::regularization::dense_diff_matrix<Eigen::MatrixXd>(
            solution_size)};

    std::shared_ptr<log_error_udm> log_error_{
        std::make_shared<log_error_udm>()};
    std::shared_ptr<log_param_udm> log_param_{
        std::make_shared<log_param_udm>()};
};

constexpr std::int64_t samples = 30;
#ifndef NDEBUG
constexpr std::int64_t iterations = 1;
#else
constexpr std::int64_t iterations = 10;
#endif

using coeff_type =
    typename num_prob_collect::regularization::blur_sine::coeff_type;
using data_type =
    typename num_prob_collect::regularization::blur_sine::data_type;

// NOLINTNEXTLINE: external library
BASELINE_F(
    reg_blur_sine, tikhonov_l_curve, blur_sine_fixture, samples, iterations) {
    using solver_type =
        num_collect::regularization::tikhonov<coeff_type, data_type>;
    using searcher_type =
        num_collect::regularization::explicit_l_curve<solver_type>;

    solver_type solver;
    solver.compute(prob().coeff(), data_with_error());

    searcher_type searcher{solver};
    searcher.search();
    Eigen::VectorXd solution;
    searcher.solve(solution);

    set_error(solution);
    set_param(searcher.opt_param());
}

// NOLINTNEXTLINE: external library
BENCHMARK_F(
    reg_blur_sine, tikhonov_gcv, blur_sine_fixture, samples, iterations) {
    using solver_type =
        num_collect::regularization::tikhonov<coeff_type, data_type>;
    using searcher_type =
        num_collect::regularization::explicit_gcv<solver_type>;

    solver_type solver;
    solver.compute(prob().coeff(), data_with_error());

    searcher_type searcher{solver};
    searcher.search();
    Eigen::VectorXd solution;
    searcher.solve(solution);

    set_error(solution);
    set_param(searcher.opt_param());
}

// NOLINTNEXTLINE: external library
BENCHMARK_F(reg_blur_sine, full_gen_tik_l_curve, blur_sine_fixture, samples,
    iterations) {
    using solver_type =
        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>;
    using searcher_type =
        num_collect::regularization::explicit_l_curve<solver_type>;

    solver_type solver;
    solver.compute(prob().coeff(), data_with_error(), dense_diff_matrix());

    searcher_type searcher{solver};
    searcher.search();
    Eigen::VectorXd solution;
    searcher.solve(solution);

    set_error(solution);
    set_param(searcher.opt_param());
}

// NOLINTNEXTLINE: external library
BENCHMARK_F(
    reg_blur_sine, full_gen_tik_gcv, blur_sine_fixture, samples, iterations) {
    using solver_type =
        num_collect::regularization::full_gen_tikhonov<coeff_type, data_type>;
    using searcher_type =
        num_collect::regularization::explicit_gcv<solver_type>;

    solver_type solver;
    solver.compute(prob().coeff(), data_with_error(), dense_diff_matrix());

    searcher_type searcher{solver};
    searcher.search();
    Eigen::VectorXd solution;
    searcher.solve(solution);

    set_error(solution);
    set_param(searcher.opt_param());
}

ext: cpp


text:
/**
 * \file schat.cpp
 * \author Julien Kauffmann <julien.kauffmann@freelan.org>
 * \brief A simple chat client.
 */

#include <fscp/fscp.hpp>

#include <cryptoplus/cryptoplus.hpp>
#include <cryptoplus/error/error_strings.hpp>

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

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <csignal>

using boost::asio::buffer;
using boost::asio::buffer_cast;
using boost::asio::buffer_size;

static boost::mutex output_mutex;

using boost::mutex;

void signal_handler(const boost::system::error_code& error, int signal_number, boost::function<void ()> stop_function)
{
	if (!error)
	{
		{
			mutex::scoped_lock lock(output_mutex);
			std::cerr << "Signal caught (" << signal_number << "): exiting..." << std::endl;
		}

		stop_function();
	}
}

static void simple_handler(const std::string& msg, const boost::system::error_code& ec)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << msg << ": " << ec.message() << std::endl;
}

static bool on_hello(fscp::server& server, const fscp::server::ep_type& sender, bool default_accept)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << "Received HELLO request from " << sender << std::endl;

	server.async_introduce_to(sender, boost::bind(&simple_handler, "async_introduce_to()", _1));

	return default_accept;
}

static void on_hello_response(fscp::server& server, const fscp::server::ep_type& sender, const boost::system::error_code& ec, const boost::posix_time::time_duration& duration)
{
	mutex::scoped_lock lock(output_mutex);

	if (ec)
	{
		std::cout << "Received no HELLO response from " << sender << " after " << duration << ": " << ec.message() << std::endl;
	}
	else
	{
		std::cout << "Received HELLO response from " << sender << " after " << duration << ": " << ec.message() << std::endl;

		server.async_introduce_to(sender, boost::bind(&simple_handler, "async_introduce_to()", _1));

		std::cout << "Sending a presentation message to " << sender << std::endl;
	}
}

static bool on_presentation(fscp::server& server, const fscp::server::ep_type& sender, fscp::server::cert_type sig_cert, fscp::server::presentation_status_type status)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << "Received PRESENTATION from " << sender << " (" << sig_cert.subject() << ") - " << status << std::endl;

	server.async_request_session(sender, boost::bind(&simple_handler, "async_request_session()", _1));

	return true;
}

static bool on_session_request(const fscp::server::ep_type& sender, const fscp::cipher_suite_list_type&, const fscp::elliptic_curve_list_type&, bool default_accept)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << "Received SESSION_REQUEST from " << sender << std::endl;

	return default_accept;
}

static bool on_session(const fscp::server::ep_type& sender, fscp::cipher_suite_type cs, fscp::elliptic_curve_type ec, bool default_accept)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << "Received SESSION from " << sender << ": " << cs << ", " << ec << std::endl;

	return default_accept;
}

static void on_session_failed(const fscp::server::ep_type& host, bool is_new)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << "Session failed with " << host << std::endl;
	std::cout << "New session: " << is_new << std::endl;
}

static void on_session_established(const fscp::server::ep_type& host, bool is_new, const fscp::cipher_suite_type& cs, const fscp::elliptic_curve_type& ec)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << "Session established with " << host << std::endl;
	std::cout << "New session: " << is_new << std::endl;
	std::cout << "Cipher suite: " << cs << std::endl;
	std::cout << "Elliptic curve: " << ec << std::endl;
}

static void on_session_lost(const fscp::server::ep_type& host, fscp::server::session_loss_reason reason)
{
	mutex::scoped_lock lock(output_mutex);

	std::cout << "Session lost with " << host << " (" << reason << ")" << std::endl;
}

static void on_data(const fscp::server::ep_type& sender, fscp::channel_number_type channel_number, fscp::SharedBuffer, boost::asio::const_buffer data)
{
	try
	{
		mutex::scoped_lock lock(output_mutex);

		std::cout << sender << " (" << static_cast<int>(channel_number) << "): " << std::string(buffer_cast<const char*>(data), buffer_size(data)) << std::endl;
	}
	catch (std::exception&)
	{
	}
}

void handle_read_line(fscp::server& server, std::string line)
{
	if (line[0] == '!')
	{
		std::istringstream iss(line.substr(1));

		std::string command;

		if (iss >> command)
		{
			if (command == "connect")
			{
				std::string host, port;

				iss >> host >> port;

				boost::asio::ip::udp::resolver resolver(server.get_io_service());
				boost::asio::ip::udp::resolver::query query(host, port);

				try
				{
					boost::asio::ip::udp::endpoint ep = *resolver.resolve(query);

					server.async_greet(ep, boost::bind(&on_hello_response, boost::ref(server), ep, _1, _2));

					std::cout << "Contacting " << ep << "..." << std::endl;
				}
				catch (std::exception& ex)
				{
					std::cerr << "Unable to resolve the specified host/port: " << ex.what() << std::endl;
				}
			} else if (command == "quit" || command == "exit")
			{
				server.close();
			}
		}
	} else
	{
		fscp::SharedBuffer buf(line.size());
		std::memcpy(buffer_cast<char*>(buf), &line[0], line.size());

		server.async_send_data_to_all(fscp::CHANNEL_NUMBER_0, buffer(buf), [buf] (const std::map<fscp::server::ep_type, boost::system::error_code>& results) {
			mutex::scoped_lock lock(output_mutex);

			for (std::map<fscp::server::ep_type, boost::system::error_code>::const_iterator result = results.begin(); result != results.end(); ++result)
			{
				if (result->second)
				{
					std::cout << result->first << ": " << result->second.message() << std::endl;
				}
				else
				{
					std::cout << result->first << ": message sent successfully." << std::endl;
				}
			}
		});
	}
}

#ifdef BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR

void handle_read_input(fscp::server& server, boost::asio::posix::stream_descriptor& input, const boost::system::error_code& ec, boost::asio::streambuf& input_buffer, size_t length)
{
	if (!ec)
	{
		std::string line(length - 1, '\0');

		input_buffer.sgetn(&line[0], length - 1);
		input_buffer.consume(1);

		handle_read_line(server, line);

		boost::asio::async_read_until(input, input_buffer, '\n', boost::bind(&handle_read_input, boost::ref(server), boost::ref(input), boost::asio::placeholders::error, boost::ref(input_buffer), boost::asio::placeholders::bytes_transferred));
	} else
	{
		server.close();
	}
}

#endif

int main(int argc, char** argv)
{
	try
	{
		if (argc != 5)
		{
			std::cerr << "Usage: schat <certificate> <private_key> <listen_host> <listen_port>" << std::endl;

			return EXIT_FAILURE;
		}

		const std::string certificate_filename(argv[1]);
		const std::string private_key_filename(argv[2]);
		const std::string listen_host(argv[3]);
		const std::string listen_port(argv[4]);

		cryptoplus::crypto_initializer crypto_initializer;
		cryptoplus::algorithms_initializer algorithms_initializer;
		cryptoplus::error::error_strings_initializer error_strings_initializer;

		boost::asio::io_service io_service;
		boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
		fscp::logger _logger;

		boost::asio::ip::udp::resolver listen_resolver(io_service);
		boost::asio::ip::udp::resolver::query listen_query(listen_host, listen_port);
		boost::asio::ip::udp::endpoint listen_ep = *listen_resolver.resolve(listen_query);

		cryptoplus::x509::certificate certificate = cryptoplus::x509::certificate::from_certificate(cryptoplus::file::open(certificate_filename, "r"));
		cryptoplus::pkey::pkey private_key = cryptoplus::pkey::pkey::from_private_key(cryptoplus::file::open(private_key_filename, "r"));

		const std::string local_name = certificate.subject().find(NID_commonName)->data().str();

		fscp::server server(io_service, _logger, fscp::identity_store(certificate, private_key));

		server.open(listen_ep);

		server.set_hello_message_received_callback(boost::bind(&on_hello, boost::ref(server), _1, _2));
		server.set_presentation_message_received_callback(boost::bind(&on_presentation, boost::ref(server), _1, _2, _3));
		server.set_session_request_message_received_callback(&on_session_request);
		server.set_session_message_received_callback(&on_session);
		server.set_session_failed_callback(&on_session_failed);
		server.set_session_established_callback(&on_session_established);
		server.set_session_lost_callback(&on_session_lost);
		server.set_data_received_callback(&on_data);

		std::cout << "Chat started. Type !quit to exit." << std::endl;

#ifdef BOOST_ASIO_HAS_POSIX_STREAM_DESCRIPTOR
		boost::asio::streambuf input_buffer(512);
		boost::asio::posix::stream_descriptor input(io_service, ::dup(STDIN_FILENO));
		boost::asio::async_read_until(input, input_buffer, '\n', boost::bind(&handle_read_input, boost::ref(server), boost::ref(input), boost::asio::placeholders::error, boost::ref(input_buffer), boost::asio::placeholders::bytes_transferred));

		auto stop_function = [&](){
			input.close();
		};

#else

		auto stop_function = [&](){
			server.close();
		};

		std::cout << "No POSIX stream descriptors available. Press Ctrl+C twice to exit." << std::endl;

		char line[512] = {};

		while (std::cin.getline(line, sizeof(line)))
		{
			server.get_io_service().post(boost::bind(&handle_read_line, boost::ref(server), std::string(line)));
		}

#endif

		signals.async_wait(boost::bind(signal_handler, _1, _2, stop_function));
		boost::thread_group threads;

		const unsigned int THREAD_COUNT = boost::thread::hardware_concurrency();

		std::cout << "Starting client with " << THREAD_COUNT << " thread(s)." << std::endl;

		for (std::size_t i = 0; i < THREAD_COUNT; ++i)
		{
			threads.create_thread([&io_service, i, &stop_function, &signals] () {
				{
					mutex::scoped_lock lock(output_mutex);
					std::cout << "Thread #" << i << " started." << std::endl;
				}

				try
				{
					io_service.run();
				}
				catch (std::exception& ex)
				{
					mutex::scoped_lock lock(output_mutex);
					std::cout << "Fatal exception occurred in thread #" << i << ": " << ex.what() << std::endl;

					stop_function();
					signals.cancel();
				}

				{
					mutex::scoped_lock lock(output_mutex);
					std::cout << "Thread #" << i << " stopped." << std::endl;
				}
			});
		}

		threads.join_all();

		std::cout << "Chat closing..." << std::endl;
	}
	catch (std::exception& ex)
	{
		std::cerr << "Error: " << ex.what() << std::endl;

		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}

max_stars_repo_name: krattai/AEBL

max_issues_repo_name: krattai/AEBL

max_forks_repo_name: krattai/AEBL


text:
//
//  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
#include "test_locale.h"
#include "test_locale_tools.h"
#include <booster/locale/utf.h>

#include <string.h>

using namespace booster::locale::utf;

char *make2(unsigned v)
{
    static unsigned char buf[3] = {0};
    buf[0] = 0xC0 | (v >> 6);
    buf[1] = 0x80 | (v & 0x3F );
    return reinterpret_cast<char*>(buf);
}

char *make3(unsigned v)
{
    static unsigned char buf[4] = {0};
    buf[0] = 0xE0 | ((v >> 12) ) ;
    buf[1] = 0x80 | ((v >>  6) & 0x3F );
    buf[2] = 0x80 | ((v >>  0) & 0x3F );
    return reinterpret_cast<char*>(buf);
}

char *make4(unsigned v)
{
    static unsigned char buf[5] = {0};
    buf[0] = 0xF0 | ((v >> 18) ) ;
    buf[1] = 0x80 | ((v >> 12) & 0x3F );
    buf[2] = 0x80 | ((v >>  6) & 0x3F );
    buf[3] = 0x80 | ((v >>  0) & 0x3F );
    return reinterpret_cast<char*>(buf);
}

booster::uint32_t const *u32_seq(booster::uint32_t a)
{
    static booster::uint32_t buf[2];
    buf[0]=a;
    buf[1]=0;
    return buf;
}

booster::uint16_t const *u16_seq(booster::uint16_t a)
{
    static booster::uint16_t buf[2];
    buf[0]=a;
    buf[1]=0;
    return buf;
}

booster::uint16_t const *u16_seq(booster::uint16_t a,booster::uint16_t b)
{
    static booster::uint16_t buf[3];
    buf[0]=a;
    buf[1]=b;
    buf[2]=0;
    return buf;
}

template<typename CharType>
void test_to(CharType const *s,unsigned codepoint)
{
    CharType const *begin = s;
    CharType const *end = begin;

    while(*end)
        end++;

    typedef utf_traits<CharType> tr;

    TEST(tr::max_width == 4 / sizeof(CharType));

    TEST(tr::template decode<CharType const *>(begin,end) == codepoint);

    if(codepoint == incomplete || codepoint != illegal)
        TEST(end == begin);

    if(codepoint == incomplete) {
        TEST(*s== 0 || 0 < tr::trail_length(*s));
        TEST(tr::trail_length(*s) + 1 > end - s);
    }

    if(codepoint != incomplete && codepoint != illegal) {
        begin=s;
        TEST(tr::is_lead(*begin));
        TEST(!tr::is_trail(*begin));
        begin++;
        while(begin!=end) {
            TEST(tr::is_trail(*begin));
            TEST(!tr::is_lead(*begin));
            begin++;
        }
        TEST(tr::width(codepoint)==end - s);
        TEST(tr::trail_length(*s) == tr::width(codepoint) - 1);
        begin = s;
        TEST(tr::decode_valid(begin) == codepoint);
        TEST(begin == end);
    }
}

template<typename CharType>
void test_from(CharType const *str,unsigned codepoint)
{
    CharType buf[5] = {1,1,1,1,1};
    CharType *p=buf;
    p = utf_traits<CharType>::template encode<CharType *>(codepoint,p);
    CharType const *end = str;
    while(*end)
        end++;
    TEST(end - str == p-buf );
    TEST(*p);
    *p=0;
    TEST(memcmp(str,buf,sizeof(CharType) * (end-str))==0);
}

int main()
{
    try {

        std::cout << "Test UTF-8" << std::endl;
        std::cout << "- From UTF-8" << std::endl;

        std::cout << "-- Correct" << std::endl;

        test_to("\x7f",0x7f);
        test_to("\xc2\x80",0x80);
        test_to("\xdf\xbf",0x7ff);
        test_to("\xe0\xa0\x80",0x800);
        test_to("\xef\xbf\xbf",0xffff);
        test_to("\xf0\x90\x80\x80",0x10000);
        test_to("\xf4\x8f\xbf\xbf",0x10ffff);

        std::cout << "-- Too big" << std::endl;
        test_to("\xf4\x9f\x80\x80",illegal); //  11 0000
        test_to("\xfb\xbf\xbf\xbf",illegal); // 3ff ffff
        test_to("\xf8\x90\x80\x80\x80",illegal);  // 400 0000
        test_to("\xfd\xbf\xbf\xbf\xbf\xbf",illegal);  // 7fff ffff

        std::cout << "-- Invalid length" << std::endl;

        /// test that this actually works
        test_to(make2(0x80),0x80);
        test_to(make2(0x7ff),0x7ff);

        test_to(make3(0x800),0x800);
        test_to(make3(0xffff),0xffff);

        test_to(make4(0x10000),0x10000);
        test_to(make4(0x10ffff),0x10ffff);

        test_to(make4(0x110000),illegal);
        test_to(make4(0x1fffff),illegal);

        test_to(make2(0),illegal);
        test_to(make3(0),illegal);
        test_to(make4(0),illegal);
        test_to(make2(0x7f),illegal);
        test_to(make3(0x7f),illegal);
        test_to(make4(0x7f),illegal);

        test_to(make3(0x80),illegal);
        test_to(make4(0x80),illegal);
        test_to(make3(0x7ff),illegal);
        test_to(make4(0x7ff),illegal);

        test_to(make4(0x8000),illegal);
        test_to(make4(0xffff),illegal);

        std::cout << "-- Invalid surrogate" << std::endl;

        test_to(make3(0xd800),illegal);
        test_to(make3(0xdbff),illegal);
        test_to(make3(0xdc00),illegal);
        test_to(make3(0xdfff),illegal);

        test_to(make4(0xd800),illegal);
        test_to(make4(0xdbff),illegal);
        test_to(make4(0xdc00),illegal);
        test_to(make4(0xdfff),illegal);

        std::cout <<"-- Incomplete" << std::endl;

        test_to("",incomplete);

        test_to("\x80",illegal);
        test_to("\xc2",incomplete);

        test_to("\xdf",incomplete);

        test_to("\xe0",incomplete);
        test_to("\xe0\xa0",incomplete);

        test_to("\xef\xbf",incomplete);
        test_to("\xef",incomplete);

        test_to("\xf0\x90\x80",incomplete);
        test_to("\xf0\x90",incomplete);
        test_to("\xf0",incomplete);

        test_to("\xf4\x8f\xbf",incomplete);
        test_to("\xf4\x8f",incomplete);
        test_to("\xf4",incomplete);

        std::cout << "- To UTF-8" << std::endl;

        std::cout << "-- Test correct" << std::endl;

        test_from("\x7f",0x7f);
        test_from("\xc2\x80",0x80);
        test_from("\xdf\xbf",0x7ff);
        test_from("\xe0\xa0\x80",0x800);
        test_from("\xef\xbf\xbf",0xffff);
        test_from("\xf0\x90\x80\x80",0x10000);
        test_from("\xf4\x8f\xbf\xbf",0x10ffff);

        std::cout << "Test UTF-16" << std::endl;
        std::cout << "- From UTF-16" << std::endl;

        std::cout << "-- Correct" << std::endl;

        test_to(u16_seq(0x10),0x10);
        test_to(u16_seq(0xffff),0xffff);
        test_to(u16_seq(0xD800,0xDC00),0x10000);
        test_to(u16_seq(0xDBFF,0xDFFF),0x10FFFF);

        std::cout << "-- Invalid surrogate" << std::endl;

        test_to(u16_seq(0xDFFF),illegal);
        test_to(u16_seq(0xDC00),illegal);

        std::cout <<"-- Incomplete" << std::endl;

        test_to(u16_seq(0),incomplete);
        test_to(u16_seq(0xD800),incomplete);
        test_to(u16_seq(0xDBFF),incomplete);

        std::cout << "- To UTF-16" << std::endl;

        std::cout << "-- Test correct" << std::endl;

        test_to(u16_seq(0x10),0x10);
        test_to(u16_seq(0xffff),0xffff);
        test_to(u16_seq(0xD800,0xDC00),0x10000);
        test_to(u16_seq(0xDBFF,0xDFFF),0x10FFFF);

        std::cout << "Test UTF-32" << std::endl;
        std::cout << "- From UTF-32" << std::endl;

        std::cout << "-- Correct" << std::endl;

        test_to(u32_seq(0x10),0x10);
        test_to(u32_seq(0xffff),0xffff);
        test_to(u32_seq(0x10000),0x10000);
        test_to(u32_seq(0x10ffff),0x10ffff);

        std::cout << "-- Invalid surrogate" << std::endl;

        test_to(u32_seq(0xD800),illegal);
        test_to(u32_seq(0xDBFF),illegal);
        test_to(u32_seq(0xDFFF),illegal);
        test_to(u32_seq(0xDC00),illegal);
        test_to(u32_seq(0x110000),illegal);

        std::cout <<"-- Incomplete" << std::endl;

        test_to(u32_seq(0),incomplete);

        std::cout << "- To UTF-32" << std::endl;

        std::cout << "-- Test correct" << std::endl;

        test_to(u32_seq(0x10),0x10);
        test_to(u32_seq(0xffff),0xffff);
        test_to(u32_seq(0x10ffff),0x10ffff);

    }
    catch(std::exception const &e) {
        std::cerr << "Failed " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    FINALIZE();
}

// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
// boostinspect:noascii

max_stars_repo_name: gatehouse/cppcms

max_issues_repo_name: gatehouse/cppcms

max_forks_repo_name: gatehouse/cppcms


text:
#include <vector>
#include <iostream>
#include <boost/format.hpp>
#include "test_case.hpp"
#include "metro/SampleRange.hpp"
#include "metro/union_ranges.hpp"
#include "metro/regression/Design.hpp"

#define DEBUG 1

BOOST_AUTO_TEST_SUITE( test_regression_design )

AUTO_TEST_CASE( test_construction ) {
	using metro::SampleRange ;
	using metro::regression::Design ;
	typedef Design::Matrix Matrix ;
	typedef Design::Vector Vector ;

	for( int nSamples = 0; nSamples < 100; ++nSamples ) {
		Vector const outcome_nonmissingness = Vector::Constant( nSamples, 1.0 ) ;
		Vector outcome = Vector::Zero( nSamples ) ;
		for( int i = 1; i < nSamples; i += 2 ) {
			outcome(i) = 1 ;
		}

		std::vector< metro::SampleRange > all_samples ;
		all_samples.push_back( metro::SampleRange( 0, nSamples )) ;

		for( int nCovariates = 0; nCovariates < 10; ++nCovariates ) {
			Matrix const covariates = Matrix::Constant( nSamples, nCovariates, 1001.0 ) ;
			Matrix const covariate_nonmissingness = Matrix::Constant( nSamples, nCovariates, 1.0 ) ;
			for( int nPredictors = 0; nPredictors < 10; ++nPredictors ) {
				Matrix predictor_levels = Matrix::Constant( 1, nPredictors, 5.0 ) ;
				Matrix predictor_probabilities = Matrix::Constant( nSamples, 1, 1.0 ) ;

				Design design(
					outcome, all_samples, std::vector< std::string >( 1, "outcome" ),
					covariates, all_samples, std::vector< std::string >( nCovariates, "cov" ),
					std::vector< std::string >( nPredictors, "predictor" )
				) ;

				design.set_predictors( predictor_levels, predictor_probabilities, all_samples ) ;

				// check the outcome
				BOOST_CHECK_EQUAL( design.outcome().rows(), nSamples ) ;
				for( int i = 0; i < nSamples; ++i ) {
					BOOST_CHECK_EQUAL( design.outcome()(i,0), ( i % 2 ) ) ;
				}

				Matrix const& matrix = design.set_predictor_level( 0 ).matrix() ;
				BOOST_CHECK_EQUAL( matrix.rows(), nSamples ) ;
				BOOST_CHECK_EQUAL( matrix.cols(), nCovariates + nPredictors + 1 ) ;

				if( nSamples > 0 ) {
					// check the baseline column
					BOOST_CHECK_EQUAL( matrix.col(0).maxCoeff(), 1.0 ) ;
					BOOST_CHECK_EQUAL( matrix.col(0).minCoeff(), 1.0 ) ;

					// check the predictor columns
					for( int i = 0; i < nPredictors; ++i ) {
						BOOST_CHECK_EQUAL( matrix.col(i+1).maxCoeff(), 5.0 ) ;
						BOOST_CHECK_EQUAL( matrix.col(i+1).minCoeff(), 5.0 ) ;
					}

					// check the covariate columns
					for( int i = 0; i < nCovariates; ++i ) {
						BOOST_CHECK_EQUAL( matrix.col(i+1+nPredictors).maxCoeff(), 1001.0 ) ;
						BOOST_CHECK_EQUAL( matrix.col(i+1+nPredictors).minCoeff(), 1001.0 ) ;
					}
				}
			}
		}
	}
}

AUTO_TEST_CASE( test_predictor_levels ) {
	using metro::SampleRange ;
	using metro::regression::Design ;
	typedef Design::Matrix Matrix ;
	typedef Design::Vector Vector ;

	int nSamples = 10;
	int nCovariates = 0 ;

	typedef std::vector< metro::SampleRange > SampleRanges ;
	SampleRanges const all_samples( 1, metro::SampleRange( 0, nSamples )) ;

	Vector outcome = Vector::Zero( nSamples ) ;
	for( int i = 0; i < nSamples; i += 2 ) {
		outcome(i) = 1 ;
	}

	Matrix const covariates = Matrix::Constant( nSamples, nCovariates, 1001.0 ) ;

	for( int nPredictors = 0; nPredictors < 10; ++nPredictors ) {
		Design design(
			outcome, all_samples, std::vector< std::string >( 1, "outcome" ),
			covariates, all_samples, std::vector< std::string >( nCovariates, "cov" ),
			std::vector< std::string >( nPredictors, "predictor" )
		) ;

		for( int nPredictorLevels = 0; nPredictorLevels < 10; ++nPredictorLevels ) {
			Matrix predictor_levels = Matrix::Zero( nPredictorLevels, nPredictors ) ;
			for( int i = 0; i < nPredictorLevels; ++i ) {
				for( int j = 0; j < nPredictors; ++j ) {
					predictor_levels( i, j ) = double( (i+1)*(j+1) ) ;
				}
			}

			Matrix predictor_probabilities = Matrix::Constant( nSamples, nPredictorLevels, 1 / double( nPredictorLevels ) ) ;
			design.set_predictors( predictor_levels, predictor_probabilities, all_samples ) ;

			for( int iLevel = 0; iLevel < nPredictorLevels; ++iLevel ) {
				Matrix const& matrix = design.set_predictor_level( iLevel ).matrix() ;

				if( nSamples > 0 ) {
					for( int j = 0; j < nPredictors; ++j ) {
							BOOST_CHECK_EQUAL( matrix.col(j+1).maxCoeff(), double((iLevel+1)*(j+1)) ) ;
							BOOST_CHECK_EQUAL( matrix.col(j+1).minCoeff(), double((iLevel+1)*(j+1)) ) ;
					}
				}
			}
		}
	}
}

AUTO_TEST_CASE( test_names ) {
	using metro::SampleRange ;
	using metro::regression::Design ;

	typedef std::vector< metro::SampleRange > SampleRanges ;
	int const nSamples = 5 ;
	SampleRanges const all_samples( 1, metro::SampleRange( 0, nSamples )) ;

	for( int numberOfPredictors = 0; numberOfPredictors < 10; ++numberOfPredictors ) {
		std::vector< std::string > predictor_names( numberOfPredictors ) ;
		for( int i = 0; i < numberOfPredictors; ++i ) {
			predictor_names[i] = ( boost::format( "predictor%d" ) % (i+1) ).str() ;
		}

		for( int numberOfCovariates = 0; numberOfCovariates < 10; ++numberOfCovariates ) {
			Eigen::VectorXd outcome = Eigen::VectorXd::Zero( 5 ) ;
			Eigen::MatrixXd cov = Eigen::MatrixXd::Constant( 5, numberOfCovariates, 2 ) ;

			std::vector< std::string > cov_names( numberOfCovariates ) ;
			for( int i = 0; i < numberOfCovariates; ++i ) {
				cov_names[i] = ( boost::format( "cov%d" ) % (i+1)).str() ;
				cov.col(i).setConstant( i ) ;
			}

			Design design(
				outcome, all_samples, std::vector< std::string >( 1, "outcome" ),
				cov, all_samples, cov_names,
				predictor_names
			) ;
			std::vector< std::string > names = design.design_matrix_column_names() ;
			TEST_ASSERT( names.size() == 1 + numberOfPredictors + numberOfCovariates ) ;
			TEST_ASSERT( names[0] == "baseline" ) ;
			for( int i = 0; i < numberOfPredictors; ++i ) {
				TEST_ASSERT( names[1+i] == predictor_names[i] ) ;
			}
			for( int i = 0; i < numberOfCovariates; ++i ) {
				TEST_ASSERT( names[1+numberOfPredictors+i] == cov_names[i] ) ;
			}

#if DEBUG
			std::cerr << design.get_summary() << "\n" ;
#endif

		}
	}
}

AUTO_TEST_CASE( test_names_interaction ) {
	using metro::SampleRange ;
	using metro::regression::Design ;

	typedef std::vector< metro::SampleRange > SampleRanges ;
	int const nSamples = 5 ;
	SampleRanges const all_samples( 1, metro::SampleRange( 0, nSamples )) ;

	for( int numberOfPredictors = 0; numberOfPredictors < 10; ++numberOfPredictors ) {
		std::vector< std::string > predictor_names( numberOfPredictors ) ;
		for( int i = 0; i < numberOfPredictors; ++i ) {
			predictor_names[i] = ( boost::format( "predictor%d" ) % (i+1) ).str() ;
		}

		for( int numberOfCovariates = 0; numberOfCovariates < 10; ++numberOfCovariates ) {
			Eigen::VectorXd outcome = Eigen::VectorXd::Zero( 5 ) ;
			Eigen::MatrixXd cov = Eigen::MatrixXd::Constant( 5, numberOfCovariates, 2 ) ;

			std::vector< std::string > cov_names( numberOfCovariates ) ;
			for( int i = 0; i < numberOfCovariates; ++i ) {
				cov_names[i] = ( boost::format( "cov%d" ) % (i+1)).str() ;
				cov.col(i).setConstant( i ) ;
			}

			std::vector< int > interactions ;
			for( int interaction = 0; interaction < numberOfCovariates; interaction +=2 ) {
				interactions.push_back( interaction ) ;
			}

			Design design(
				outcome, all_samples, std::vector< std::string >( 1, "outcome" ),
				cov, all_samples, cov_names,
				predictor_names,
				Design::eIdentity,
				interactions
			) ;

#if DEBUG
			std::cerr << design.get_summary() << "\n" ;
#endif

			std::vector< std::string > names = design.design_matrix_column_names() ;
			BOOST_CHECK_EQUAL( names.size(), 1 + numberOfPredictors * ( 1 + interactions.size() ) + numberOfCovariates ) ;
			BOOST_CHECK_EQUAL( names[0], "baseline" ) ;
			for( int i = 0; i < numberOfPredictors; ++i ) {
				BOOST_CHECK_EQUAL( names[1+i], predictor_names[i] ) ;
			}
			for( int j = 0; j < interactions.size(); ++j ) {
				for( int i = 0; i < numberOfPredictors; ++i ) {
					BOOST_CHECK_EQUAL( names[1+((j+1)*numberOfPredictors)+i], predictor_names[i] + "x" + cov_names[interactions[j]] ) ;
				}
			}
			for( int i = 0; i < numberOfCovariates; ++i ) {
				BOOST_CHECK_EQUAL( names[1+(numberOfPredictors*(1+interactions.size()))+i], cov_names[i] ) ;
			}

		}
	}
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: gavinband/qctool

max_issues_repo_name: gavinband/qctool

max_forks_repo_name: gavinband/qctool


text:
/**
 * Copyright (c) 2011, 2012
 * Claudio Kopper <claudio.kopper@icecube.wisc.edu>
 * and the IceCube Collaboration <http://www.icecube.wisc.edu>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 *
 * $Id: I3PhotonToMCPEConverter.cxx 179373 2020-03-10 21:25:48Z jvansanten $
 *
 * @file I3PhotonToMCPEConverter.cxx
 * @version $Revision: 179373 $
 * @date $Date: 2020-03-10 15:25:48 -0600 (Tue, 10 Mar 2020) $
 * @author Claudio Kopper
 */

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>

#include <algorithm>
#include <cmath>

#include "clsim/dom/I3PhotonToMCPEConverter.h"

#include <boost/foreach.hpp>

#include "simclasses/I3Photon.h"
#include "simclasses/I3CompressedPhoton.h"

#include "phys-services/I3SummaryService.h"

#include "dataclasses/geometry/I3OMGeo.h"
#include "dataclasses/geometry/I3ModuleGeo.h"

#include "simclasses/I3MCPE.h"
#include "dataclasses/physics/I3ParticleID.h"
#include <sim-services/MCPEMCPulseTools.hpp>

#include "dataclasses/I3Constants.h"

// The module
I3_MODULE(I3PhotonToMCPEConverter);

I3PhotonToMCPEConverter::I3PhotonToMCPEConverter(const I3Context& context)
: I3ConditionalModule(context)
{
    AddParameter("MCPEGenerator",
                 "Instance of I3CLSimPhotonToMCPEConverter",
                 mcpeGenerator_);

    inputPhotonSeriesMapName_="PropagatedPhotons";
    AddParameter("InputPhotonSeriesMapName",
                 "Name of the input I3PhotonSeriesMap frame object.",
                 inputPhotonSeriesMapName_);

    outputMCPESeriesMapName_="MCPESeriesMap";
    AddParameter("OutputMCPESeriesMapName",
                 "Name of the output I3MCPESeries frame object.",
                 outputMCPESeriesMapName_);

    mergeHits_=false;
    AddParameter("MergeHits",
                 "Merge photoelectrons which are very close in time in the output.",
                 mergeHits_);

    // add an outbox
    AddOutBox("OutBox");

    numGeneratedHits_=0;

}

I3PhotonToMCPEConverter::~I3PhotonToMCPEConverter()
{
    log_trace("%s", __PRETTY_FUNCTION__);
}

void I3PhotonToMCPEConverter::Configure()
{
    log_trace("%s", __PRETTY_FUNCTION__);

    GetParameter("MCPEGenerator", mcpeGenerator_);
    if (!mcpeGenerator_)
        log_fatal("You must set an MCPEGenerator");

    GetParameter("InputPhotonSeriesMapName", inputPhotonSeriesMapName_);
    GetParameter("OutputMCPESeriesMapName", outputMCPESeriesMapName_);

    GetParameter("MergeHits",mergeHits_);
}

namespace {

    template <typename Photon>
    void CheckSanity(const Photon &photon)
    {}

    template <>
    void CheckSanity<I3Photon>(const I3Photon &photon) {
        // sanity check for unscattered photons: is their direction ok
        // w.r.t. the vector from emission to detection?
        if (photon.GetNumScattered()==0)
        {
            I3Position pp(photon.GetPos() - photon.GetStartPos());
            const double ppl = pp.Magnitude();
            const double cosang = (pp*photon.GetDir())/ppl;

            if ((cosang < 0.9) && (ppl>1.*I3Units::m)) {
                log_fatal("unscattered photon direction is inconsistent: cos(ang)==%f, d=(%f,%f,%f), pp=(%f,%f,%f) pp_l=%f",
                          cosang,
                          photon.GetDir().GetX(), photon.GetDir().GetY(), photon.GetDir().GetZ(),
                          pp.GetX(), pp.GetY(), pp.GetZ(),
                          ppl
                          );
            }
        }
    }
}

template <typename PhotonMapType>
std::pair<I3MCPESeriesMapPtr,I3ParticleIDMapPtr>
I3PhotonToMCPEConverter::Convert(I3FramePtr frame)
{
    boost::shared_ptr<const PhotonMapType> inputPhotonSeriesMap = frame->Get<boost::shared_ptr<const PhotonMapType> >(inputPhotonSeriesMapName_);

    // allocate the output hitSeriesMap
    I3MCPESeriesMapPtr outputMCPESeriesMap(new I3MCPESeriesMap());
    I3ParticleIDMapPtr outputParentInfo;
    typedef std::map<OMKey, MCHitMerging::MCPEStream> MCPEStreamMap;
    boost::optional<MCPEStreamMap> mcpeStreams;
    if (mergeHits_) //only create this if it is needed
        mcpeStreams.emplace(MCPEStreamMap());

    for (const auto &it : *inputPhotonSeriesMap)
    {
        const ModuleKey &module_key = it.first;
        const auto &photons = it.second;

        for (const auto &photon : photons)
        {
            CheckSanity(photon);

            auto hit = mcpeGenerator_->Convert(module_key, photon);
            if (!hit)
                continue;

            // add a new hit
            if (mergeHits_) {
                (*mcpeStreams)[std::get<0>(*hit)].insert(std::get<1>(*hit));
            } else {
                (*outputMCPESeriesMap)[std::get<0>(*hit)].push_back(std::get<1>(*hit));
            }
            numGeneratedHits_++;
        }
    }

    if (mergeHits_) {
        outputParentInfo.reset(new I3ParticleIDMap());
        for (auto &pair : *mcpeStreams) {
            std::tie(
                (*outputMCPESeriesMap)[pair.first],
                (*outputParentInfo)[pair.first]
            ) = pair.second.extractMCPEsWithPIDInfo();
        }
    } else {
        for (auto &pair : *outputMCPESeriesMap) {
            std::sort(
                pair.second.begin(),
                pair.second.end(),
                [](const I3MCPE &a, const I3MCPE &b) { return a.time < b.time; }
            );
        }
    }
    return std::make_pair(outputMCPESeriesMap,outputParentInfo);
}

void I3PhotonToMCPEConverter::DAQ(I3FramePtr frame)
{
    log_trace("%s", __PRETTY_FUNCTION__);

    I3MCPESeriesMapPtr outputMCPESeriesMap;
    I3ParticleIDMapPtr outputParentInfo;
    if (frame->Get<I3PhotonSeriesMapConstPtr>(inputPhotonSeriesMapName_)) {
        std::tie(outputMCPESeriesMap,outputParentInfo) = Convert<I3PhotonSeriesMap>(frame);
    } else if (frame->Get<I3CompressedPhotonSeriesMapConstPtr>(inputPhotonSeriesMapName_)) {
        std::tie(outputMCPESeriesMap,outputParentInfo) = Convert<I3CompressedPhotonSeriesMap>(frame);
    } else {
        log_debug("Frame does not contain an I3PhotonSeriesMap named \"%s\".",
                  inputPhotonSeriesMapName_.c_str());

        // do nothing if there is no input data
        PushFrame(frame);
        return;
    }

    // store the output I3MCPESeriesMap
    frame->Put(outputMCPESeriesMapName_, outputMCPESeriesMap);
    if (outputParentInfo) {
        frame->Put(outputMCPESeriesMapName_+"ParticleIDMap", outputParentInfo);
    }

    // that's it!
    PushFrame(frame);
}

void I3PhotonToMCPEConverter::Finish()
{
    // add some summary information to a potential I3SummaryService
    I3MapStringDoublePtr summary = context_.Get<I3MapStringDoublePtr>("I3SummaryService");
    if (summary) {
        const std::string prefix = "I3PhotonToMCPEConverter_" + GetName() + "_";

        (*summary)[prefix+"NumGeneratedHits"] = numGeneratedHits_;
    }

}

I3CLSimPhotonToMCPEConverter::~I3CLSimPhotonToMCPEConverter() {}

I3CLSimPhotonToMCPEConverterForDOMs::I3CLSimPhotonToMCPEConverterForDOMs(I3RandomServicePtr random,
    boost::shared_ptr<const std::map<OMKey, I3CLSimFunctionConstPtr>> wavelengthAcceptance, I3CLSimFunctionConstPtr angularAcceptance)
    : randomService_(random), wavelengthAcceptance_(wavelengthAcceptance), angularAcceptance_(angularAcceptance)
{}

I3CLSimPhotonToMCPEConverterForDOMs::~I3CLSimPhotonToMCPEConverterForDOMs() {}

boost::optional<std::tuple<OMKey,I3MCPE>>
I3CLSimPhotonToMCPEConverterForDOMs::Convert(const ModuleKey &mkey, const I3CompressedPhoton &photon) const
{
    boost::optional<std::tuple<OMKey,I3MCPE>> hit;
    double hitProbability = photon.GetWeight();
    if (hitProbability < 0.) log_fatal("Photon with negative weight found.");
    if (hitProbability == 0.) return hit;

    // Only treat DOM-sized DOMs for now
    const double domRadius = 165.1*I3Units::mm;
    const double distFromDOMCenter = photon.GetPos().Magnitude();
    if (std::abs(distFromDOMCenter - domRadius) > 3*I3Units::cm) {
        log_fatal("distance not %fmm.. it is %fmm (diff=%gmm) (OMKey=(%i,%u) (photon @ pos=(%g,%g,%g)mm))",
                  domRadius/I3Units::mm,
                  distFromDOMCenter/I3Units::mm,
                  (distFromDOMCenter-domRadius)/I3Units::mm,
                  mkey.GetString(), mkey.GetOM(),
                  photon.GetPos().GetX()/I3Units::mm,
                  photon.GetPos().GetY()/I3Units::mm,
                  photon.GetPos().GetZ()/I3Units::mm
                  );
    }

    double photonCosAngle = photon.GetDir().GetZ();
    photonCosAngle = std::max(-1., std::min(1., photonCosAngle));

    OMKey omkey(mkey.GetString(),mkey.GetOM());
    auto domAcceptance = wavelengthAcceptance_->find(omkey);
    if (domAcceptance == wavelengthAcceptance_->end()) {
        log_debug_stream("No wavelength acceptance configured for "<<omkey);
        return hit;
    }
    hitProbability *= domAcceptance->second->GetValue(photon.GetWavelength());
    log_trace("After wlen acceptance: prob=%g (wlen acceptance is %f)",
             hitProbability, domAcceptance->second->GetValue(photon.GetWavelength()));

    hitProbability *= angularAcceptance_->GetValue(photonCosAngle);
    log_trace("After wlen&angular acceptance: prob=%g (angular acceptance is %f)",
              hitProbability, angularAcceptance_->GetValue(photonCosAngle));

    if (hitProbability > 1.+1e-4) {
        log_warn("hitProbability==%f > 1: your hit weights are too high. (hitProbability-1=%g)", hitProbability, hitProbability-1.);

        double hitProbability = photon.GetWeight();

        const double photonAngle = std::acos(photonCosAngle);
        log_warn("Photon (lambda=%fnm, angle=%fdeg, dist=%fm, module=(%d,%d)) has weight %g, 1/weight %g",
                 photon.GetWavelength()/I3Units::nanometer,
                 photonAngle/I3Units::deg,
                 distFromDOMCenter/I3Units::m,
                 mkey.GetString(),
                 mkey.GetOM(),
                 hitProbability,
                 1./hitProbability);

        hitProbability *= domAcceptance->second->GetValue(photon.GetWavelength());
        log_warn("After wlen acceptance: prob=%g (wlen acceptance is %f)",
                 hitProbability, domAcceptance->second->GetValue(photon.GetWavelength()));

        hitProbability *= angularAcceptance_->GetValue(photonCosAngle);
        log_warn("After wlen&angular acceptance: prob=%g (angular acceptance is %f)",
                  hitProbability, angularAcceptance_->GetValue(photonCosAngle));

        log_fatal("cannot continue.");
    }

    // does it survive?
    if (hitProbability <= randomService_->Uniform()) return hit;

    // FIXME: roll arrival time correction into kernel
    hit.emplace(omkey,I3MCPE(photon.GetParticleID(), 1, photon.GetTime()));
    return hit;
}

ext: cxx


text:
/*
 * libexecuteplus - A portable execution library.
 * Copyright (C) 2010-2011 Julien KAUFFMANN <julien.kauffmann@freelan.org>
 *
 * This file is part of libexecuteplus.
 *
 * libexecuteplus is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * libexecuteplus is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program. If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations
 * including the two.
 * You must obey the GNU General Public License in all respects
 * for all of the code used other than OpenSSL.  If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so.  If you
 * do not wish to do so, delete this exception statement from your
 * version.  If you delete this exception statement from all source
 * files in the program, then also delete it here.
 *
 * If you intend to use libexecuteplus in a commercial software, please
 * contact me : we may arrange this for a small fee or no fee at all,
 * depending on the nature of your project.
 */

/**
 * \file windows_system.cpp
 * \author Julien KAUFFMANN <julien.kauffmann@freelan.org>
 * \brief Windows system primitives.
 */

#include "windows_system.hpp"

#ifdef WINDOWS

#include "error.hpp"

#include <iostream>
#include <sstream>
#include <locale>
#include <codecvt>
#include <algorithm>
#include <memory>

#include <boost/lexical_cast.hpp>

#include <shlobj.h>
#include <shellapi.h>

namespace executeplus
{
	namespace
	{
		template <typename CharType>
		struct argument_helper;

		template <>
		struct argument_helper<char>
		{
			static const char ESCAPE_CHARACTER = '\\';
			static const char QUOTE_CHARACTER = '"';
			static const char EQUAL_CHARACTER = '=';
			static const char NULL_CHARACTER = '\0';
		};

		template <>
		struct argument_helper<wchar_t>
		{
			static const wchar_t ESCAPE_CHARACTER = L'\\';
			static const wchar_t QUOTE_CHARACTER = L'"';
			static const wchar_t EQUAL_CHARACTER = L'=';
			static const wchar_t NULL_CHARACTER = L'\0';
		};

		struct EnvironmentStringsDeleter
		{
			void operator()(wchar_t* p)
			{
				::FreeEnvironmentStringsW(p);
			}

			void operator()(char* p)
			{
				::FreeEnvironmentStringsA(p);
			}
		};

		template <typename CharType>
		const std::unique_ptr<CharType, EnvironmentStringsDeleter> get_environment_strings();

		template <>
		const std::unique_ptr<wchar_t, EnvironmentStringsDeleter> get_environment_strings<wchar_t>()
		{
			return std::unique_ptr<wchar_t, EnvironmentStringsDeleter>(::GetEnvironmentStringsW());
		}

#ifndef UNICODE
		template <>
		const std::unique_ptr<char, EnvironmentStringsDeleter> get_environment_strings<char>()
		{
			return std::unique_ptr<char, EnvironmentStringsDeleter>(::GetEnvironmentStringsA());
		}
#endif

		template <typename CharType>
		std::map<std::basic_string<CharType>, std::basic_string<CharType>> get_current_environment()
		{
			typedef std::basic_string<CharType> string_type;

			std::map<string_type, string_type> result;

			const auto environment_strings = get_environment_strings<CharType>();
			auto ptr = environment_strings.get();

			if (ptr)
			{
				while (*ptr)
				{
					const string_type line(ptr);

					// Environment variables that start with an equal sign are private to the shell and should be ignored.
					if (*ptr != argument_helper<CharType>::EQUAL_CHARACTER)
					{
						const auto pos = line.find(argument_helper<CharType>::EQUAL_CHARACTER);

						if (pos == string_type::npos)
						{
							// Discard the result.
						}
						else
						{
							const string_type key = line.substr(0, pos);
							const string_type value = line.substr(pos + 1);
							result[key] = value;
						}
					}

					ptr += line.size() + 1;
				}
			}

			return result;
		}

		class handle_closer
		{
			public:
				handle_closer(HANDLE handle) : m_handle(handle) {}
				~handle_closer() { ::CloseHandle(m_handle); }

			private:
				HANDLE m_handle;
		};

		void output(const char* str)
		{
			std::cout << str << std::endl;
		}

		void output(const wchar_t* str)
		{
			std::wcout << str << std::endl;
		}

		bool has_escapable_characters(const std::string& str)
		{
			return (str.find_first_of(" \t\n\v\"") != std::string::npos);
		}

		bool has_escapable_characters(const std::wstring& str)
		{
			return (str.find_first_of(L" \t\n\v\"") != std::string::npos);
		}

		template <typename CharType>
		std::basic_string<CharType> escape_argument(const std::basic_string<CharType>& arg)
		{
			std::basic_string<CharType> result(1, argument_helper<CharType>::QUOTE_CHARACTER);

			for (auto it = arg.begin();; ++it)
			{
				unsigned int escapes_count = 0;

				while ((it != arg.end()) && (*it == argument_helper<CharType>::ESCAPE_CHARACTER))
				{
					++it;
					++escapes_count;
				}

				if (it == arg.end())
				{
					result.append(escapes_count * 2, argument_helper<CharType>::ESCAPE_CHARACTER);
					break;
				}
				else if (*it == argument_helper<CharType>::QUOTE_CHARACTER)
				{
					result.append(escapes_count * 2 + 1, argument_helper<CharType>::ESCAPE_CHARACTER);
					result.push_back(*it);
				}
				else
				{
					result.append(escapes_count, argument_helper<CharType>::ESCAPE_CHARACTER);
					result.push_back(*it);
				}
			}

			result.push_back(argument_helper<CharType>::QUOTE_CHARACTER);

			return result;
		}

		template <typename CharType>
		std::basic_string<CharType> escape_argument_if_needed(const std::basic_string<CharType>& arg)
		{
			if (!arg.empty() && !has_escapable_characters(arg))
			{
				return arg;
			}
			else
			{
				return escape_argument(arg);
			}
		}

		DWORD do_create_process(const char* application, char* command_line, char* env, STARTUPINFOA& si, PROCESS_INFORMATION& pi)
		{
			return ::CreateProcessA(application, command_line, NULL, NULL, FALSE, 0, env, NULL, &si, &pi);
		}

		DWORD do_create_process(const wchar_t* application, wchar_t* command_line, wchar_t* env, STARTUPINFOW& si, PROCESS_INFORMATION& pi)
		{
			return ::CreateProcessW(application, command_line, NULL, NULL, FALSE, CREATE_UNICODE_ENVIRONMENT, env, NULL, &si, &pi);
		}

		template <typename CharType>
		struct startupinfo;

		template <>
		struct startupinfo<char>
		{
			typedef STARTUPINFOA type;
		};

		template <>
		struct startupinfo<wchar_t>
		{
			typedef STARTUPINFOW type;
		};

		template <typename CharType>
		DWORD create_process(const CharType* application, CharType* command_line, CharType* env)
		{
			DWORD exit_status;

			typename startupinfo<CharType>::type si;
			si.cb = sizeof(si);
			si.lpReserved = NULL;
			si.lpDesktop = NULL;
			si.lpTitle = NULL;
			si.dwX = 0;
			si.dwY = 0;
			si.dwXSize = 0;
			si.dwYSize = 0;
			si.dwXCountChars = 0;
			si.dwYCountChars = 0;
			si.dwFillAttribute = 0;
			si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES; // Remove STARTF_USESTDHANDLES to show stdout
			si.wShowWindow = SW_HIDE;
			si.cbReserved2 = 0;
			si.lpReserved2 = NULL;
			si.hStdInput = INVALID_HANDLE_VALUE;
#if FREELAN_DEBUG
			si.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);
#else
			si.hStdOutput = INVALID_HANDLE_VALUE;
#endif
			si.hStdError = INVALID_HANDLE_VALUE;

			PROCESS_INFORMATION pi;

#if FREELAN_DEBUG
			output(command_line);
#endif

			if (!do_create_process(application, command_line, env, si, pi))
			{
				throw boost::system::system_error(::GetLastError(), boost::system::system_category());
			}

			handle_closer thread_closer(pi.hThread);
			handle_closer process_closer(pi.hProcess);

			DWORD wait_result = ::WaitForSingleObject(pi.hProcess, INFINITE);

			switch (wait_result)
			{
				case WAIT_OBJECT_0:
					{
						DWORD exit_code = 0;

						if (::GetExitCodeProcess(pi.hProcess, &exit_code))
						{
							exit_status = static_cast<int>(exit_code);
						}
						else
						{
							throw boost::system::system_error(::GetLastError(), boost::system::system_category());
						}

						break;
					}
				default:
					{
						throw boost::system::system_error(::GetLastError(), boost::system::system_category());
					}
			}

			return exit_status;
		}

		template <typename CharType>
		int do_execute(const std::vector<std::basic_string<CharType>>& args, const std::map<std::basic_string<CharType>, std::basic_string<CharType>>& env, boost::system::error_code& ec)
		{
			if (args.empty())
			{
				ec = make_error_code(executeplus_error::external_process_failed);

				return EXIT_FAILURE;
			}

			const std::basic_string<CharType> application = args.front();
			std::basic_ostringstream<CharType> command_line_buffer;
			std::basic_ostringstream<CharType> environment_string_buffer;

			for (auto it = args.begin(); it != args.end(); ++it)
			{
				if (it != args.begin())
				{
					command_line_buffer << " ";
				}

				command_line_buffer << escape_argument_if_needed(*it);
			}

			for (auto&& pair : env)
			{
				environment_string_buffer << pair.first << argument_helper<CharType>::EQUAL_CHARACTER << pair.second << argument_helper<CharType>::NULL_CHARACTER;
			}

			std::basic_string<CharType> command_line = command_line_buffer.str();
			std::basic_string<CharType> environment_string = environment_string_buffer.str();

			return create_process<CharType>(application.c_str(), command_line.empty() ? nullptr : &command_line[0], environment_string.empty() ? nullptr : &environment_string[0]);
		}

		template <typename CharType>
		int do_execute(const std::vector<std::basic_string<CharType>>& args, const std::map<std::basic_string<CharType>, std::basic_string<CharType>>& env)
		{
			boost::system::error_code ec;

			const auto result = do_execute(args, env, ec);

			if (result < 0)
			{
				throw boost::system::system_error(ec);
			}

			return result;
		}

		template <typename CharType>
		void do_checked_execute(const std::vector<std::basic_string<CharType>>& args, const std::map<std::basic_string<CharType>, std::basic_string<CharType>>& env)
		{
			if (do_execute(args, env) != 0)
			{
				throw boost::system::system_error(make_error_code(executeplus_error::external_process_failed));
			}
		}
	}

#ifdef UNICODE
	std::map<std::wstring, std::wstring> get_current_environment()
	{
		return get_current_environment<wchar_t>();
	}
#else
	std::map<std::string, std::string> get_current_environment()
	{
		return get_current_environment<char>();
	}
#endif

#ifdef UNICODE
	int execute(const std::vector<std::wstring>& args, const std::map<std::wstring, std::wstring>& env, boost::system::error_code& ec)
#else
	int execute(const std::vector<std::string>& args, const std::map<std::string, std::string>& env, boost::system::error_code& ec)
#endif
	{
		return do_execute(args, env, ec);
	}

#ifdef UNICODE
	int execute(const std::vector<std::wstring>& args, const std::map<std::wstring, std::wstring>& env)
#else
	int execute(const std::vector<std::string>& args, const std::map<std::string, std::string>& env)
#endif
	{
		return do_execute(args, env);
	}

#ifdef UNICODE
	void checked_execute(const std::vector<std::wstring>& args, const std::map<std::wstring, std::wstring>& env)
#else
	void checked_execute(const std::vector<std::string>& args, const std::map<std::string, std::string>& env)
#endif
	{
		do_checked_execute(args, env);
	}
}

#endif


text:
#include "parse_opening_hours.hpp"
#include "rules_evaluation.hpp"

#define BOOST_TEST_MODULE OpeningHoursIntegration

#include <algorithm>
#include <ctime>
#include <map>

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/test/included/unit_test.hpp>

namespace
{
template <typename T>
std::string ToString(T const & t)
{
  std::stringstream sstr;
  sstr << t;
  return sstr.str();
}

template <typename T>
bool HasPeriod(std::vector<T> const & v)
{
  auto const hasPeriod = [](T const & t) { return t.HasPeriod(); };
  return std::any_of(begin(v), end(v), hasPeriod);
}

template <typename T>
bool HasPlus(std::vector<T> const & v)
{
  auto const hasPlus = [](T const & t) { return t.HasPlus(); };
  return std::any_of(begin(v), end(v), hasPlus);
}

bool HasOffset(osmoh::TMonthdayRanges const & mr)
{
  auto const hasOffset = [](osmoh::MonthdayRange const & md) {
    return
        md.GetStart().HasOffset() ||
        md.GetEnd().HasOffset();
  };
  return std::any_of(begin(mr), end(mr), hasOffset);
}

bool HasOffset(osmoh::Weekdays const & wd)
{
  auto const hasOffset = [](osmoh::WeekdayRange const & w) { return w.HasOffset(); };
  return std::any_of(begin(wd.GetWeekdayRanges()), end(wd.GetWeekdayRanges()), hasOffset);
}

template <typename ParserResult>
bool CompareNormalized(std::string const & original, ParserResult const & pretendent)
{
  auto originalCopy = original;
  auto pretendentCopy = ToString(pretendent);

  boost::to_lower(originalCopy);
  boost::to_lower(pretendentCopy);

  boost::replace_all(originalCopy, "off", "closed");

  boost::replace_all(originalCopy, " ", "");
  boost::replace_all(pretendentCopy, " ", "");

  return pretendentCopy == originalCopy;
}

enum
{
  Parsed,
  Serialised,
  Period,
  Plus,
  Offset,
  Count_
};
using TRuleFeatures = std::array<bool, Count_>;

std::ostream & operator<<(std::ostream & ost, TRuleFeatures const & f)
{
 std::copy(begin(f), end(f), std::ostream_iterator<bool>(ost, "\t"));
 return ost;
}

TRuleFeatures DescribeRule(osmoh::TRuleSequences const & rule)
{
  TRuleFeatures features{};
  for (auto const & r : rule)
  {
    features[Period] |= HasPeriod(r.GetTimes());
    features[Period] |= HasPeriod(r.GetMonths());
    features[Period] |= HasPeriod(r.GetYears());
    features[Period] |= HasPeriod(r.GetWeeks());

    features[Plus] |= HasPlus(r.GetTimes());
    features[Plus] |= HasPlus(r.GetMonths());
    features[Plus] |= HasPlus(r.GetYears());

    features[Offset] |= HasOffset(r.GetMonths());
    features[Offset] |= HasOffset(r.GetWeekdays());
  }

  return features;
}
} // namespace

/// How to run:
/// 1. copy opening-count.lst to where the binary is
/// 2. run with --log_level=message
BOOST_AUTO_TEST_CASE(OpeningHours_CountFailed)
{
  std::ifstream datalist("opening-count.lst");
  BOOST_REQUIRE_MESSAGE(datalist.is_open(),
                        "Can't open ./opening-count.lst: " << std::strerror(errno));

  std::string line;

  size_t line_num = 0;
  size_t num_failed = 0;
  size_t num_total = 0;

  std::map<size_t, size_t> hist;
  std::map<TRuleFeatures, size_t> featuresDistrib;

  while (std::getline(datalist, line))
  {
    size_t count = 1;
    std::string datastr;

    auto d = line.find('|');
    if (d == std::string::npos)
    {
      BOOST_WARN_MESSAGE((d != std::string::npos),
                         "Incorrect line " << line_num << " format: " << line);
      datastr = line;
    }
    else
    {
      count = std::stol(line.substr(0, d));
      datastr = line.substr(d + 1);
    }

    line_num++;

    osmoh::TRuleSequences rule;
    auto const isParsed = Parse(datastr, rule);
    TRuleFeatures features{};

    if (isParsed)
      features = DescribeRule(rule);
    features[Parsed] = true;
    features[Serialised] = true;

    if (!isParsed)
    {
      num_failed += count;
      ++hist[count];
      features[Parsed] = false;
      features[Serialised] = false;
      BOOST_TEST_MESSAGE("-- " << count << " :[" << datastr << "]");
    }
    else if (!CompareNormalized(datastr, rule))
    {
      num_failed += count;
      ++hist[count];
      features[Serialised] = false;
      BOOST_TEST_MESSAGE("- " << count << " :[" << datastr << "]");
      BOOST_TEST_MESSAGE("+ " << count << " :[" << ToString(rule) << "]");
    }

    featuresDistrib[features] += count;
    num_total += count;
  }

  BOOST_CHECK_MESSAGE((num_failed == 0),
                      "Failed " << num_failed <<
                      " of " << num_total <<
                      " (" << double(num_failed)/(double(num_total)/100) << "%)");

  {
    std::stringstream message;
    for (auto const & e : hist)
      message << "Weight: " << e.first << " Count: " << e.second << std::endl;

    BOOST_TEST_MESSAGE(message.str());
  }
  {
    std::stringstream message;
    message << "Parsed\tSerialised\tPeriod\tPlus\tOffset\tCount" << std::endl;
    for (auto const & e : featuresDistrib)
      message << e.first  << '\t' << e.second << std::endl;

    BOOST_TEST_MESSAGE(message.str());
  }
}

max_stars_repo_name: Dushistov/omim

max_issues_repo_name: Dushistov/omim

max_forks_repo_name: Dushistov/omim


text:
/*=============================================================================
    Copyright (c) 2006 Tobias Schwinger
    http://spirit.sourceforge.net/

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

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

#include <boost/typeof/typeof.hpp>

#include <boost/spirit/home/classic/namespace.hpp>
#include <boost/spirit/home/classic/core/nil.hpp>
#include <boost/spirit/home/classic/core/primitives/numerics_fwd.hpp>
#include <boost/spirit/home/classic/core/scanner/scanner_fwd.hpp>
#include <boost/spirit/home/classic/core/scanner/skipper_fwd.hpp>
#include <boost/spirit/home/classic/core/non_terminal/subrule_fwd.hpp>

namespace boost { namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

    // parser.hpp
    template <typename IteratorT> struct parse_info;
    struct plain_parser_category;
    struct binary_parser_category;
    struct unary_parser_category;
    struct action_parser_category;

    // match.hpp
    template<typename T> class match;

    // primitives/primitives.hpp
    template<class ParserT> struct negated_char_parser;
    template<typename CharT> struct chlit;
    template<typename CharT> struct range;
    template<typename IteratorT> class chseq;
    template<typename IteratorT> class strlit;
    struct nothing_parser;
    struct anychar_parser;
    struct alnum_parser;
    struct alpha_parser;
    struct cntrl_parser;
    struct digit_parser;
    struct xdigit_parser;
    struct graph_parser;
    struct upper_parser;
    struct lower_parser;
    struct print_parser;
    struct punct_parser;
    struct blank_parser;
    struct space_parser;
    struct eol_parser;
    struct end_parser;

    // non_terminal/parser_context.hpp
    template<typename T> struct parser_context;

    // non_terminal/parser_id.hpp
    class parser_id;
    template<int N> struct parser_tag;
    class dynamic_parser_tag;
    struct parser_address_tag;

    // non_terminal/rule.hpp
    template<typename T0, typename T1, typename T2> class rule;

    // non_terminal/grammar.hpp
    template<class DerivedT, typename ContextT> struct grammar;

    // composite.hpp
    template<class ParserT, typename ActionT> class action;
    template<class A, class B> struct alternative;
    template<class A, class B> struct difference;
    template<class A, class B> struct exclusive_or;
    template<class A, class B> struct intersection;
    template<class a, class b> struct sequence;
    template<class A, class B> struct sequential_or;
    template<class S> struct kleene_star;
    template<class S> struct positive;
    template<class S> struct optional;
    // composite/directives.hpp
    template<class ParserT> struct contiguous;
    template<class ParserT> struct inhibit_case;
    template<class BaseT> struct inhibit_case_iteration_policy;
    template<class A, class B> struct longest_alternative;
    template<class A, class B> struct shortest_alternative;
    template<class ParserT, typename BoundsT> struct min_bounded;
    template<class ParserT, typename BoundsT> struct max_bounded;
    template<class ParserT, typename BoundsT> struct bounded;
    // composite/no_actions.hpp
    template<class Parser> struct no_actions_parser;
    template<class Base> struct no_actions_action_policy;
    // composite/epsilon.hpp
    struct epsilon_parser;
    template<typename CondT, bool positive> struct condition_parser;
    template<typename SubjectT> struct empty_match_parser;
    template<typename SubjectT> struct negated_empty_match_parser;

    // deprecated assign/push_back actor -- they live somewhere else, now
    struct assign_action;
    struct push_back_action;
    template<typename T, typename ActionT> class ref_value_actor;
    template<typename T, typename ValueT, typename ActionT>
    class ref_const_ref_actor;

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

}} // namespace BOOST_SPIRIT_CLASSIC_NS

#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

// parser.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::parse_info,1)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::plain_parser_category)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::binary_parser_category)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::unary_parser_category)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::action_parser_category)

// nil.hpp (included directly)

#if !defined(BOOST_SPIRIT_NIL_T_TYPEOF_REGISTERED)
// registration guard to decouple the iterators from the core
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::nil_t)
#   define BOOST_SPIRIT_NIL_T_TYPEOF_REGISTERED
#endif

// match.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::match, 1)

BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::match<BOOST_SPIRIT_CLASSIC_NS::nil_t>)

// primitives/primitives.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::negated_char_parser, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::chlit, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::range, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::chseq, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::strlit, 1)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::nothing_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::anychar_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::alnum_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::alpha_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::cntrl_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::digit_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::xdigit_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::graph_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::upper_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::lower_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::print_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::punct_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::blank_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::space_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::eol_parser)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::end_parser)

BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::chlit<char>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::chlit<wchar_t>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::range<char>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::range<wchar_t>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::chseq<char const *>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::chseq<wchar_t const *>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::strlit<char const *>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::strlit<wchar_t const *>)

// primitives/numerics.hpp (has forward header)

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::int_parser, (class)(int)(unsigned)(int))
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::uint_parser, (class)(int)(unsigned)(int))
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::sign_parser)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::real_parser, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::real_parser_policies, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::ureal_parser_policies, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::strict_real_parser_policies, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::strict_ureal_parser_policies, 1)

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::int_parser, (class)(int))
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::uint_parser, (class)(int))
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::int_parser<boost::int32_t>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::uint_parser<boost::uint32_t>)
#if !defined(BOOST_NO_INT64_T)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::int_parser<boost::int64_t>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::uint_parser<boost::uint64_t>)
#endif
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::real_parser_policies<float>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::real_parser_policies<double>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::ureal_parser_policies<float>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::ureal_parser_policies<double>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::strict_real_parser_policies<float>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::strict_real_parser_policies<double>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::strict_ureal_parser_policies<float>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::strict_ureal_parser_policies<double>)

// scanner/scanner.hpp (has forward header)

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::scanner,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::scanner_policies,3)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::iteration_policy)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::action_policy)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::match_policy)

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::scanner,1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::scanner_policies,2)

// scanner/skipper.hpp (has forward header)

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::skipper_iteration_policy,1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::no_skipper_iteration_policy,1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::skip_parser_iteration_policy,2)

BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::skipper_iteration_policy<>)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::skip_parser_iteration_policy,1)

// non_terminal/parser_context.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::parser_context,1)

BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::parser_context<BOOST_SPIRIT_CLASSIC_NS::nil_t>)

// non_terminal/parser_id.hpp

BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::parser_id)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::parser_tag, (int))
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::dynamic_parser_tag)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::parser_address_tag)

// non_terminal/subrule.hpp (has forward header)

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::subrule,(int)(class))
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::subrule_parser,(int)(class)(class))
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::subrule_list,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::subrules_scanner,2)

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::subrule,(int))
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::subrule_parser,(int)(class))
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<0>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<1>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<2>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<3>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<4>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<5>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<6>)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::subrule<7>)

// non_terminal/rule.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::rule,3)
#if BOOST_SPIRIT_RULE_SCANNERTYPE_LIMIT > 1
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::scanner_list,1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::scanner_list,BOOST_SPIRIT_RULE_SCANNERTYPE_LIMIT)
#endif

// non_terminal/grammar.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::grammar,2)

// composite.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::action, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::alternative, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::difference, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::exclusive_or, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::intersection, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::sequence, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::sequential_or, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::kleene_star, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::positive, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::optional, 1)

// composite/directives.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::contiguous, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::inhibit_case, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::inhibit_case_iteration_policy,1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::longest_alternative, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::shortest_alternative, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::min_bounded, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::max_bounded, 2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::bounded, 2)

// composite/no_actions.hpp

BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::no_actions_parser, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::no_actions_action_policy, 1)

BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::no_actions_action_policy<BOOST_SPIRIT_CLASSIC_NS::action_policy>)

// composite/epsilon.hpp

BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::epsilon_parser)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::condition_parser, (class)(bool))
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::empty_match_parser, 1)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::negated_empty_match_parser, 1)

#if !defined(BOOST_SPIRIT_ACTOR_TYPEOF_HPP)
// deprecated assign/push_back actor -- they live somewhere else, now
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::ref_value_actor,2)
BOOST_TYPEOF_REGISTER_TEMPLATE(BOOST_SPIRIT_CLASSIC_NS::ref_const_ref_actor,3)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::assign_action)
BOOST_TYPEOF_REGISTER_TYPE(BOOST_SPIRIT_CLASSIC_NS::push_back_action)
#endif

#if BOOST_WORKAROUND(BOOST_MSVC,BOOST_TESTED_AT(1400)) && BOOST_MSVC >= 1400
namespace boost { namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

    nil_t & operator* (nil_t);
    nil_t & operator+ (nil_t);

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

} } // namespace ::BOOST_SPIRIT_CLASSIC_NS
#endif

#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include "../WeakCallback.h"

#define BOOST_TEST_MAIN
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif

#include <stdio.h>
#include <boost/noncopyable.hpp>

class String
{
 public:
  String(const char* str)
  {
    printf("String ctor this %p\n", this);
  }

  String(const String& rhs)
  {
    printf("String copy ctor this %p, rhs %p\n", this, &rhs);
  }

  String(String&& rhs)
  {
    printf("String move ctor this %p, rhs %p\n", this, &rhs);
  }
};

class Foo : boost::noncopyable
{
 public:
  void zero();
  void zeroc() const;
  void one(int);
  void oner(int&);
  void onec(int) const;
  void oneString(const String& str);
  void oneStringRR(String&& str);
};

void Foo::zero()
{
  printf("Foo::zero()\n");
}

void Foo::zeroc() const
{
  printf("Foo::zeroc()\n");
}

void Foo::one(int x)
{
  printf("Foo::one() x=%d\n", x);
}

void Foo::oner(int& x)
{
  printf("Foo::oner() x=%d\n", x);
  x = 1000;
}

void Foo::onec(int x) const
{
  printf("Foo::onec() x=%d\n", x);
}

void Foo::oneString(const String& str)
{
  printf("Foo::oneString\n");
}

void Foo::oneStringRR(String&& str)
{
  printf("Foo::oneStringRR\n");
}

String getString()
{
  return String("zz");
}

BOOST_AUTO_TEST_CASE(testMove)
{
  String s("xx");
  Foo f;
  f.oneString(s);
  f.oneString(String("yy"));
  // f.oneStringRR(s);
  f.oneStringRR(String("yy"));
  f.oneString(getString());
  f.oneStringRR(getString());
}

BOOST_AUTO_TEST_CASE(testWeakCallback)
{
  printf("======== testWeakCallback \n");
  std::shared_ptr<Foo> foo(new Foo);
  muduo::WeakCallback<Foo> cb0 = muduo::makeWeakCallback(foo, &Foo::zero);
  muduo::WeakCallback<Foo> cb0c = muduo::makeWeakCallback(foo, &Foo::zeroc);
  cb0();
  cb0c();

  muduo::WeakCallback<Foo, int> cb1 = muduo::makeWeakCallback(foo, &Foo::one);
  auto cb1c = muduo::makeWeakCallback(foo, &Foo::onec);
  auto cb1r = muduo::makeWeakCallback(foo, &Foo::oner);
  cb1(123);
  cb1c(234);
  int i = 345;
  cb1r(i);
  BOOST_CHECK_EQUAL(i, 1000);

  auto cb2 = muduo::makeWeakCallback(foo, &Foo::oneString);
  auto cb2r = muduo::makeWeakCallback(foo, &Foo::oneStringRR);
  printf("_Z%s\n", typeid(cb2).name());
  printf("_Z%s\n", typeid(cb2r).name());
  cb2(String("xx"));
  cb2r(String("yy"));

  muduo::WeakCallback<Foo> cb3(foo, std::bind(&Foo::oneString, std::placeholders::_1, "zz"));

  cb3();

  printf("======== reset \n");
  foo.reset();
  cb0();
  cb0c();
  cb1(123);
  cb1c(234);
  cb2(String("xx"));
  cb2r(String("yy"));
  cb3();
}

ext: cc

max_stars_repo_name: ririripley/recipes

max_issues_repo_name: ririripley/recipes

max_forks_repo_name: ririripley/recipes


text:
// The code could be easier and just call std::exit(), but the purpose here is
// to teach how to interrupt a task while the remaining tasks of the program
// continue to run and std::exit() wouldn't work in such case.

#include <boost/chrono.hpp>
#include <iostream>
#include <boost/thread/scoped_thread.hpp>
#include <vector>
#include <signal.h>
#include <cstdlib>

static int pfd[2];

void sighandler(int sig)
{
    if (write(pfd[1], ".", 1) == -1)
        std::exit(-1);
}

// Given pthread_cancel() behaviour under C++ mode[1], I assume the default
// expectation for thread programmers is that they can't call join() or any
// other possibly long-running function after the thread is interrupted. So,
// `interrupt_and_detach` is used instead `interrupt_and_join` here.
//
// [1] https://udrepper.livejournal.com/21541.html
struct interrupt_and_detach_if_joinable
{
    template <class Thread>
    void operator()(Thread& t)
    {
        t.interrupt();
        if (t.joinable()) {
            t.detach();
        }
    }
};

boost::thread sleepsort(const std::vector<int>& v)
{
    // The grouping thread to dispatch multiple interrupt requests
    return boost::thread{ [v]() {
        std::vector<
            boost::scoped_thread<interrupt_and_detach_if_joinable>
        > threads;
        threads.reserve(v.size());

        // The sleep-sort algo {{{
        for (auto e: v) {
            threads.emplace_back(
                [e]() {
                    boost::this_thread::sleep_for(boost::chrono::seconds(e));
                    std::cout << e << std::endl;
                }
            );
        }
        // }}}

        for (auto& t : threads) {
            t.join();
        }
    } };
}

int main(int argc, char* argv[]) {
    std::vector<int> v{8, 42, 38, 111, 2, 39, 1};

    if (pipe(pfd) == -1)
        std::exit(-1);

    if (signal(SIGUSR1, sighandler) == SIG_ERR)
        std::exit(-1);

    auto sleeper = sleepsort(v);

    auto sigwaiter = boost::thread([&]() {
        char ch;
        if (read(pfd[0], &ch, 1) == -1)
            std::exit(-1);
        sleeper.interrupt();
    });

    sleeper.join();

    // This piece is optional if you start `sigwaiter` thread detached, but it
    // is included anyway to show how to synchronize tasks so you can properly
    // manage resources in more complex code.
    //
    // For instance: were sigwaiter thread to keep running after we deallocated
    // the `sleeper` object, we'd have a bug. {{{
    if (raise(SIGUSR1) != 0)
        std::exit(-1);
    sigwaiter.join();
    // }}}
}

max_stars_repo_name: blinktrade/iofiber

max_issues_repo_name: blinktrade/iofiber

max_forks_repo_name: blinktrade/iofiber


text:
/**
 * @file bitstream.hpp
 * @author Robin Dietrich <me (at) invokr (dot) org>
 * @version 1.3
 *
 * @par License
 *    Alice Replay Parser
 *    Copyright 2014 Robin Dietrich
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 * @par Source
 *    You can find most of the things implemented in this bitstream in the public
 *    Source Engine SDK released by Valve.
 */

#ifndef _DOTA_BITSTREAM_HPP_
#define _DOTA_BITSTREAM_HPP_

#include <fstream>
#include <math.h>
#include <cstring>
#include <string>
#include <vector>
#include <boost/endian/conversion.hpp>

/// Defines the maximum possible size of a bitstream
///
/// This requirement is verly likely not defined in the source engine. In our case however this is helpful
/// towards mitigating problems from malicious replays by limiting the amount of data a single entity or
/// stringtable update can pass to a bitstream.
#define DOTA_BITSTREAM_MAX_SIZE 65536

/// Defines the underlying type used to represent the data
#if DOTA_64BIT
    #define DOTA_BITSTREAM_WORD_TYPE uint64_t
#else
    #define DOTA_BITSTREAM_WORD_TYPE uint32_t // slightly faster on 32 bit systems
#endif

/// Number of fraction bits in a normalized float
#define NORMAL_FRACTION_BITS 11
/// Normal denominator
#define NORMAL_DENOMINATOR ( (1<<(NORMAL_FRACTION_BITS)) - 1 )
/// Normal resolution
#define NORMAL_RESOLUTION (1.0/(NORMAL_DENOMINATOR))
/// Maximum number of bytes to read for a 32 bit varint (32/8 + 1)
#define VARINT32_MAX 5
/// Maximum number of bytes to read for a 64 bit varint (64/8 + 2)
#define VARINT64_MAX 10
/// Number of bits to read for the integer part of a coord
#define COORD_INTEGER_BITS 14
/// Number of bits to read for the fraction part of a coord
#define COORD_FRACTION_BITS 5
/// Coord demoniator
#define COORD_DENOMINATOR (1<<(COORD_FRACTION_BITS))
/// Coord resolution
#define COORD_RESOLUTION (1.0/(COORD_DENOMINATOR))
/// Bits to read for multiplayer optimized coordinates
#define COORD_INTEGER_BITS_MP 11
/// Fractional part of low-precision coords
#define COORD_FRACTION_BITS_MP_LOWPRECISION 3
/// Denominator for low-precision coords
#define COORD_DENOMINATOR_LOWPRECISION (1<<(COORD_FRACTION_BITS_MP_LOWPRECISION))
/// Resolution for low-precision coords
#define COORD_RESOLUTION_LOWPRECISION (1.0/(COORD_DENOMINATOR_LOWPRECISION))
/// Number of bits to read for the fraction part of a cell coord
#define CELL_COORD_FRACTION_BITS 5
/// Number of bits to read for a low-precision cell coord's fraction
#define CELL_COORD_FRACTION_BITS_LOWPRECISION 3

namespace dota {
    /// @defgroup CORE Core
    /// @{

    /**
     * Converts a string into a read-only bitstream.
     *
     * The string is converted into a vector of word_t. It keeps track of the data read
     * and adjusts its position accordingly. Size values are mostly measured in bits.
     *
     * Methods starting with "n" provide facilities to read network encoded data from the
     * bitstream.
     *
     * Thanks to edith for providing an initial implementation.
     */
    class bitstream {
        public:
            /** Underlying type used to represent a chunk of data */
            typedef DOTA_BITSTREAM_WORD_TYPE word_t;
            /** Type used to keep track of the stream position */
            typedef std::size_t size_type;

            /** Creates an empty bitstream */
            bitstream() : data{}, pos{0}, size{0} { }

            /** Creates a bitstream from a std::string */
            bitstream(const std::string &str) : data{}, pos{0}, size{str.size()*8} {
                // Reserve the memory in beforehand so we can just memcpy everything
                data.resize((str.size() + 3) / 4 + 1);
                memcpy(&data[0], str.c_str(), str.size());
            }

            /** Copy-Constructor */
            bitstream(const bitstream& b) : data(b.data), pos(b.pos), size(b.size) {}

            /** Move-Constructor */
            bitstream(bitstream&& b) : data(std::move(b.data)), pos(b.pos), size(b.size) {
                b.data.clear();
                b.pos = 0;
                b.size = 0;
            }

            /** Destructor */
            ~bitstream() = default;

            /** Assignment operator */
            bitstream& operator= (bitstream t) {
                swap(t);
                return *this;
            }

            /** Swap this bitstream with given one */
            void swap(bitstream& b) {
                std::swap(data, b.data);
                std::swap(pos, b.pos);
                std::swap(size, b.size);
            }

            /** Checkes whether there is still data left to be read. */
            inline bool good() const {
                return pos < size;
            }

            /** Returns the size of the stream in bits. */
            inline size_type end() const {
                return size;
            }

            /** Returns the current position of the stream in bits. */
            inline size_type position() const {
                return pos;
            }

            /**
             * Returns result of reading n bits into an uint32_t.
             *
             * This function can read a maximum of 32 bits at once. If the amount of data requested
             * exceeds the remaining size of the current chunk it wraps around to the next one.
             */
            uint32_t read(const size_type n);

            /**
             * Seek n bits forward.
             *
             * If the resulting position would overflow, it is set to the maximum one possible.
             */
            void seekForward(const size_type n) {
                pos += n;

                if (pos > size) {
                    pos = size;
                }
            }

            /**
             * Seek n bits backward.
             *
             * If the resulting position would underflow, it is set to 0.
             */
            void seekBackward(const size_type n) {
                if ((pos - n) > pos) {
                    pos = 0;
                } else {
                    pos -= n;
                }
            }

            /**
             * Read an unsigned integer from the stream.
             *
             * n corresponds to the number of bits in the sendprop.
             */
            uint32_t nReadUInt(const size_type n) {
                return read(n);
            }

            /**
             * Read a signed integer from the stream.
             *
             * n corresponds to the number of bits in the sendprop.
             */
            /*int32_t nReadSInt(const size_type n) {
                int32_t ret = read(n);
                const uint32_t sign = 1 << (n - 1);

                if (ret >= sign)
                    ret = ret - sign - sign;

                return ret;
            }*/

            /**
             * Read a normalized float from the stream.
             *
             * Reads one bit for the sign and NORMAL_FRACTION_BITS for the float.
             */
            float nReadNormal() {
                const bool sign = read(1);
                const float fraction = read( NORMAL_FRACTION_BITS );
                const float ret = fraction * NORMAL_RESOLUTION;

                if (sign)
                    return -ret;
                else
                    return ret;
            }

            /** Skips a normalized float in the stream. */
            void nSkipNormal() {
                // sign bit + fraction bits
                seekForward(NORMAL_FRACTION_BITS + 1);
            }

            /** Reads a bit angle */
            float nReadAngle(uint32_t n);

            /** Reads a normalized float vector */
            std::vector<float> nRead3BitNormal();

            /** Reads a normalized float */
            //float nReadNormal();

            /** Reads a little-endian uint16. */
            uint16_t nReadLeUInt16();

            /** Reads a little-endian uint32. */
            uint32_t nReadLeUInt32();

            /** Reads a little-endian uint64. */
            uint64_t nReadLeUInt64();

            /** Reads a big-endian uint16. */
            uint16_t nReadBeUInt16();

            /** Reads a big-endian uint32. */
            uint32_t nReadBeUInt32();

            /** Reads a big-endian uint64. */
            uint64_t nReadBeUInt64();

            /**
             * Reads a bit variable sized uint32_t from the stream.
             *
             * The header looks like this: [XY00001111222233333333333333333333] where everything > 0 is optional.
             * The first 2 bits (X and Y) tell us how much (if any) to read other than the 6 initial bits:
             * Y set -> read 4
             * X set -> read 8
             * X + Y set -> read 28
             */
            uint32_t nReadUBitVar();

            /** Another ubitvar variant, encoding in first 2 bits of 6 bit group */
            uint32_t nReadUBitVar2();

            /** Ubit variant used in the fieldpath */
            uint32_t nReadUBitVarFP();

            /**
             * Reads a variable sized uint32_t from the stream.
             *
             * A variable int is read in chunks of 8. The first 7 bits are added to return value
             * while the last bit is the indicator whether to continue reading.
             */
            uint32_t nReadVarUInt32();

            /** Reads a variable sized uint64_t from the stream. */
            uint64_t nReadVarUInt64();

            /**
             * Reads a variable sized int32_t from the stream.
             *
             * The signed version of the varint uses protobuf's zigzag encoding for
             * the sign part.
             */
            int32_t nReadVarSInt32() {
                const uint32_t value = nReadVarUInt32();
                return (value >> 1) ^ -static_cast<int32_t>(value & 1);
            }

            /** Reads a variable sized int64_t from the stream. */
            int64_t nReadVarSInt64() {
                const uint64_t value = nReadVarUInt64();
                return (value >> 1) ^ -static_cast<int64_t>(value & 1);
            }

            /**
             * Skips over a variable sized int.
             *
             * This function will skip 7 bits and read 1.
             */
            void nSkipVarInt() {
                do { seekForward(7); } while (read(1));
            }

            /** Reads networked coordinates from the bitstream. */
            float nReadCoord();

            /**
             * Skips coordinates in bitstream.
             *
             * This function reads 2 bits to determine the amount of skipped bits
             */
            void nSkipCoord() {
                switch( read(2) ) {
                    case 1:
                        seekForward( COORD_INTEGER_BITS + 1 );
                        break;
                    case 2:
                        seekForward( COORD_FRACTION_BITS + 1 );
                        break;
                    case 3:
                        seekForward( COORD_INTEGER_BITS + COORD_FRACTION_BITS + 1 );
                        break;
                }
            }

            /**
             * Reads coordinates, version optimized for multi player games.
             *
             * Float Encoding:   [ Inbound | IsInteger |  IsSigned  | [Int Part] | Float Part ]
             * Integer Encoding: [ Inbound | IsInteger | [IsSigned] | [Int part] ]
             */
            float nReadCoordMp(const bool integral, const bool lowPrecision);

            /**
             * Skips coordinates optimized towards multiplayer games.
             *
             * This function needs to read 2 - 3 bits in order to determine the amount required.
             */
            void nSkipCoordMp(const bool integral, const bool lowPrecision);

            /** Reads cell coordinate from their network representation. */
            float nReadCellCoord(size_type n, const bool integral, const bool lowPrecision);

            /**
             * Skips cell coordinate.
             *
             * Can fully skip the coord based on the sendprop flags.
             */
            void nSkipCellCoord(size_type n, const bool integral, const bool lowPrecision) {
                if (!integral)
                    lowPrecision ? seekForward( n + 3 ) : seekForward( n + 5 );
                else
                    seekForward(n);
            }

            /**
             * Reads a null-terminated string into the buffer, stops once it reaches \0 or n chars.
             *
             * n is treated as the number of bytes to be read.
             * n can be arbitrarily large in this context. The underlying read method throws in case an overflow
             * happens.
             */
            void nReadString(char *buffer, const size_type n);

            /**
             * Skips over a 0 terminated string.
             *
             * This function will always read the full 8 bits per character until the null
             * terminator occours.
             */
            void nSkipString(const size_type n) {
                for (std::size_t i = 0; i < n; ++i) {
                    if (static_cast<char>(read(8)) == '\0')
                        return;
                }
            }

            /**
             * Reads the exact number of bits into the buffer.
             *
             * The function reads in chunks of 8 bit until n is smaller than that
             * and appends the left over bits
             */
            void readBits(char *buffer, const size_type n);
        private:
            /** Data to read from */
            std::vector<word_t> data;
            /** Current position in the vector in bits */
            size_type pos;
            /** Overall size of the data in bits */
            size_type size;

            /** Bitmask for reading */
            static const uint64_t masks[64];
            /** Shift amount for reading */
            static const uint64_t shift[64];
    };

    /// @}
}

//uint32_t readVarUInt32(std::ifstream &stream);

uint32_t readVarUInt32(const char*, int &pos);

#endif /* _DOTA_BITSTREAM_HPP_ */

max_stars_repo_name: devilesk/dota-replay-parser

max_issues_repo_name: devilesk/dota-replay-parser

max_forks_repo_name: devilesk/dota-replay-parser