<commit_before>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/alert.hpp>
#include <libtorrent/alert_types.hpp>
#include <boost/python.hpp>

using namespace boost::python;
using namespace libtorrent;

extern char const* alert_doc;
extern char const* alert_msg_doc;
extern char const* alert_severity_doc;
extern char const* torrent_alert_doc;
extern char const* tracker_alert_doc;
extern char const* tracker_error_alert_doc;
extern char const* tracker_warning_alert_doc;
extern char const* tracker_reply_alert_doc;
extern char const* tracker_announce_alert_doc;
extern char const* hash_failed_alert_doc;
extern char const* peer_ban_alert_doc;
extern char const* peer_error_alert_doc;
extern char const* invalid_request_alert_doc;
extern char const* peer_request_doc;
extern char const* torrent_finished_alert_doc;
extern char const* piece_finished_alert_doc;
extern char const* block_finished_alert_doc;
extern char const* block_downloading_alert_doc;
extern char const* storage_moved_alert_doc;
extern char const* torrent_deleted_alert_doc;
extern char const* torrent_paused_alert_doc;
extern char const* torrent_checked_alert_doc;
extern char const* url_seed_alert_doc;
extern char const* file_error_alert_doc;
extern char const* metadata_failed_alert_doc;
extern char const* metadata_received_alert_doc;
extern char const* listen_failed_alert_doc;
extern char const* listen_succeeded_alert_doc;
extern char const* portmap_error_alert_doc;
extern char const* portmap_alert_doc;
extern char const* fastresume_rejected_alert_doc;
extern char const* peer_blocked_alert_doc;
extern char const* scrape_reply_alert_doc;
extern char const* scrape_failed_alert_doc;
extern char const* udp_error_alert_doc;
extern char const* external_ip_alert_doc;
extern char const* save_resume_data_alert_doc;

void bind_alert()
{
    using boost::noncopyable;

    {
        scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init)
            .def("message", &alert::message, alert_msg_doc)
            .def("what", &alert::what)
            .def("category", &alert::category)
            .def("severity", &alert::severity, alert_severity_doc)
            .def("__str__", &alert::message, alert_msg_doc)
            ;

        enum_<alert::severity_t>("severity_levels")
            .value("debug", alert::debug)
            .value("info", alert::info)
            .value("warning", alert::warning)
            .value("critical", alert::critical)
            .value("fatal", alert::fatal)
            .value("none", alert::none)
            ;

        enum_<alert::category_t>("category_t")
            .value("error_notification", alert::error_notification)
            .value("peer_notification", alert::peer_notification)
            .value("port_mapping_notification", alert::port_mapping_notification)
            .value("storage_notification", alert::storage_notification)
            .value("tracker_notification", alert::tracker_notification)
            .value("debug_notification", alert::debug_notification)
            .value("status_notification", alert::status_notification)
            .value("progress_notification", alert::progress_notification)
            .value("ip_block_notification", alert::ip_block_notification)
            .value("all_categories", alert::all_categories)
            ;
    }

    class_<torrent_alert, bases<alert>, noncopyable>(
        "torrent_alert", torrent_alert_doc, no_init
    )
        .def_readonly("handle", &torrent_alert::handle)
        ;

    class_<tracker_alert, bases<torrent_alert>, noncopyable>(
        "tracker_alert", tracker_alert_doc, no_init
    )
        .def_readonly("url", &tracker_alert::url)
        ;

    class_<peer_alert, bases<torrent_alert>, noncopyable>(
        "peer_alert", no_init
    )
        .def_readonly("ip", &peer_alert::ip)
        .def_readonly("pid", &peer_alert::pid)
    ;
    class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(
        "tracker_error_alert", tracker_error_alert_doc, no_init
    )
        .def_readonly("times_in_row", &tracker_error_alert::times_in_row)
        .def_readonly("status_code", &tracker_error_alert::status_code)
        ;

    class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(
        "tracker_warning_alert", tracker_warning_alert_doc, no_init
    );

    class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(
        "tracker_reply_alert", tracker_reply_alert_doc, no_init
    )
        .def_readonly("num_peers", &tracker_reply_alert::num_peers)
        ;

    class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(
        "tracker_announce_alert", tracker_announce_alert_doc, no_init
    );

    class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(
        "hash_failed_alert", hash_failed_alert_doc, no_init
    )
        .def_readonly("piece_index", &hash_failed_alert::piece_index)
        ;

    class_<peer_ban_alert, bases<peer_alert>, noncopyable>(
        "peer_ban_alert", peer_ban_alert_doc, no_init
    );

    class_<peer_error_alert, bases<peer_alert>, noncopyable>(
        "peer_error_alert", peer_error_alert_doc, no_init
    );

    class_<invalid_request_alert, bases<peer_alert>, noncopyable>(
        "invalid_request_alert", invalid_request_alert_doc, no_init
    )
        .def_readonly("request", &invalid_request_alert::request)
        ;

    class_<peer_request>("peer_request", peer_request_doc)
        .def_readonly("piece", &peer_request::piece)
        .def_readonly("start", &peer_request::start)
        .def_readonly("length", &peer_request::length)
        .def(self == self)
        ;

    class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(
        "torrent_finished_alert", torrent_finished_alert_doc, no_init
    );

    class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(
        "piece_finished_alert", piece_finished_alert_doc, no_init
    )
        .def_readonly("piece_index", &piece_finished_alert::piece_index)
        ;

    class_<block_finished_alert, bases<peer_alert>, noncopyable>(
        "block_finished_alert", block_finished_alert_doc, no_init
    )
        .def_readonly("block_index", &block_finished_alert::block_index)
        .def_readonly("piece_index", &block_finished_alert::piece_index)
        ;

    class_<block_downloading_alert, bases<peer_alert>, noncopyable>(
        "block_downloading_alert", block_downloading_alert_doc, no_init
    )
        .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg)
        .def_readonly("block_index", &block_downloading_alert::block_index)
        .def_readonly("piece_index", &block_downloading_alert::piece_index)
        ;

    class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(
        "storage_moved_alert", storage_moved_alert_doc, no_init
    );

    class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(
        "torrent_deleted_alert", torrent_deleted_alert_doc, no_init
    );

    class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(
        "torrent_paused_alert", torrent_paused_alert_doc, no_init
    );

    class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(
        "torrent_checked_alert", torrent_checked_alert_doc, no_init
    );

    class_<url_seed_alert, bases<torrent_alert>, noncopyable>(
        "url_seed_alert", url_seed_alert_doc, no_init
    )
        .def_readonly("url", &url_seed_alert::url)
        ;

    class_<file_error_alert, bases<torrent_alert>, noncopyable>(
        "file_error_alert", file_error_alert_doc, no_init
    )
        .def_readonly("file", &file_error_alert::file)
        ;

    class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(
        "metadata_failed_alert", metadata_failed_alert_doc, no_init
    );

    class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(
        "metadata_received_alert", metadata_received_alert_doc, no_init
    );

    class_<listen_failed_alert, bases<alert>, noncopyable>(
        "listen_failed_alert", listen_failed_alert_doc, no_init
    );

    class_<listen_succeeded_alert, bases<alert>, noncopyable>(
        "listen_succeeded_alert", listen_succeeded_alert_doc, no_init
    )
        .def_readonly("endpoint", &listen_succeeded_alert::endpoint)
        ;

    class_<portmap_error_alert, bases<alert>, noncopyable>(
        "portmap_error_alert", portmap_error_alert_doc, no_init
    )
        .def_readonly("mapping", &portmap_error_alert::mapping)
        .def_readonly("type", &portmap_error_alert::type)
        ;

    class_<portmap_alert, bases<alert>, noncopyable>(
        "portmap_alert", portmap_alert_doc, no_init
    )
        .def_readonly("mapping", &portmap_alert::mapping)
        .def_readonly("external_port", &portmap_alert::external_port)
        .def_readonly("type", &portmap_alert::type)
        ;

    class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(
        "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init
    );

    class_<peer_blocked_alert, bases<alert>, noncopyable>(
        "peer_blocked_alert", peer_blocked_alert_doc, no_init
    )
        .def_readonly("ip", &peer_blocked_alert::ip)
        ;

    class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(
        "scrape_reply_alert", scrape_reply_alert_doc, no_init
    )
        .def_readonly("incomplete", &scrape_reply_alert::incomplete)
        .def_readonly("complete", &scrape_reply_alert::complete)
        ;

    class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(
        "scrape_failed_alert", scrape_failed_alert_doc, no_init
    );

    class_<udp_error_alert, bases<alert>, noncopyable>(
        "udp_error_alert", udp_error_alert_doc, no_init
    )
        .def_readonly("endpoint", &udp_error_alert::endpoint)
        ;

    class_<external_ip_alert, bases<alert>, noncopyable>(
        "external_ip_alert", external_ip_alert_doc, no_init
    )
        .def_readonly("external_address", &external_ip_alert::external_address)
        ;

    class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(
        "save_resume_data_alert", save_resume_data_alert_doc, no_init
    )
        .def_readonly("resume_data", &save_resume_data_alert::resume_data)
        ;

    class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(
        "file_renamed_alert", no_init
    )
        .def_readonly("name", &file_renamed_alert::name)
        ;

    class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>(
        "file_rename_failed_alert", no_init
    )
        .def_readonly("index", &file_rename_failed_alert::index)
        ;

    class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(
        "torrent_resumed_alert", no_init
	);

	class_<state_changed_alert, bases<torrent_alert>, noncopyable>(
	    "state_changed_alert", no_init
	)
	    .def_readonly("state", &state_changed_alert::state)
	    ;

	class_<dht_reply_alert, bases<tracker_alert>, noncopyable>(
	    "dht_reply_alert", no_init
	)
	    .def_readonly("num_peers", &dht_reply_alert::num_peers)
	    ;

	class_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>(
	    "peer_unsnubbed_alert", no_init
	);

	class_<peer_snubbed_alert, bases<peer_alert>, noncopyable>(
	    "peer_snubbed_alert", no_init
	);

    class_<peer_connect_alert, bases<peer_alert>, noncopyable>(
        "peer_connect_alert", no_init
    );

    class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>(
        "peer_disconnected_alert", no_init
    );

    class_<request_dropped_alert, bases<peer_alert>, noncopyable>(
        "request_dropped_alert", no_init
    )
        .def_readonly("block_index", &request_dropped_alert::block_index)
        .def_readonly("piece_index", &request_dropped_alert::piece_index)
    ;

    class_<block_timeout_alert, bases<peer_alert>, noncopyable>(
        "block_timeout_alert", no_init
    )
        .def_readonly("block_index", &block_timeout_alert::block_index)
        .def_readonly("piece_index", &block_timeout_alert::piece_index)
    ;

    class_<unwanted_block_alert, bases<peer_alert>, noncopyable>(
        "unwanted_block_alert", no_init
    )
        .def_readonly("block_index", &unwanted_block_alert::block_index)
        .def_readonly("piece_index", &unwanted_block_alert::piece_index)
    ;

    class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>(
        "torrent_delete_failed_alert", no_init
    );

    class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>(
        "save_resume_data_failed_alert", no_init
    );

}
<commit_msg>add tracker_error_alert::msg to bindings<commit_after>// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <libtorrent/alert.hpp>
#include <libtorrent/alert_types.hpp>
#include <boost/python.hpp>

using namespace boost::python;
using namespace libtorrent;

extern char const* alert_doc;
extern char const* alert_msg_doc;
extern char const* alert_severity_doc;
extern char const* torrent_alert_doc;
extern char const* tracker_alert_doc;
extern char const* tracker_error_alert_doc;
extern char const* tracker_warning_alert_doc;
extern char const* tracker_reply_alert_doc;
extern char const* tracker_announce_alert_doc;
extern char const* hash_failed_alert_doc;
extern char const* peer_ban_alert_doc;
extern char const* peer_error_alert_doc;
extern char const* invalid_request_alert_doc;
extern char const* peer_request_doc;
extern char const* torrent_finished_alert_doc;
extern char const* piece_finished_alert_doc;
extern char const* block_finished_alert_doc;
extern char const* block_downloading_alert_doc;
extern char const* storage_moved_alert_doc;
extern char const* torrent_deleted_alert_doc;
extern char const* torrent_paused_alert_doc;
extern char const* torrent_checked_alert_doc;
extern char const* url_seed_alert_doc;
extern char const* file_error_alert_doc;
extern char const* metadata_failed_alert_doc;
extern char const* metadata_received_alert_doc;
extern char const* listen_failed_alert_doc;
extern char const* listen_succeeded_alert_doc;
extern char const* portmap_error_alert_doc;
extern char const* portmap_alert_doc;
extern char const* fastresume_rejected_alert_doc;
extern char const* peer_blocked_alert_doc;
extern char const* scrape_reply_alert_doc;
extern char const* scrape_failed_alert_doc;
extern char const* udp_error_alert_doc;
extern char const* external_ip_alert_doc;
extern char const* save_resume_data_alert_doc;

void bind_alert()
{
    using boost::noncopyable;

    {
        scope alert_scope = class_<alert, noncopyable>("alert", alert_doc, no_init)
            .def("message", &alert::message, alert_msg_doc)
            .def("what", &alert::what)
            .def("category", &alert::category)
            .def("severity", &alert::severity, alert_severity_doc)
            .def("__str__", &alert::message, alert_msg_doc)
            ;

        enum_<alert::severity_t>("severity_levels")
            .value("debug", alert::debug)
            .value("info", alert::info)
            .value("warning", alert::warning)
            .value("critical", alert::critical)
            .value("fatal", alert::fatal)
            .value("none", alert::none)
            ;

        enum_<alert::category_t>("category_t")
            .value("error_notification", alert::error_notification)
            .value("peer_notification", alert::peer_notification)
            .value("port_mapping_notification", alert::port_mapping_notification)
            .value("storage_notification", alert::storage_notification)
            .value("tracker_notification", alert::tracker_notification)
            .value("debug_notification", alert::debug_notification)
            .value("status_notification", alert::status_notification)
            .value("progress_notification", alert::progress_notification)
            .value("ip_block_notification", alert::ip_block_notification)
            .value("all_categories", alert::all_categories)
            ;
    }

    class_<torrent_alert, bases<alert>, noncopyable>(
        "torrent_alert", torrent_alert_doc, no_init
    )
        .def_readonly("handle", &torrent_alert::handle)
        ;

    class_<tracker_alert, bases<torrent_alert>, noncopyable>(
        "tracker_alert", tracker_alert_doc, no_init
    )
        .def_readonly("url", &tracker_alert::url)
        ;

    class_<peer_alert, bases<torrent_alert>, noncopyable>(
        "peer_alert", no_init
    )
        .def_readonly("ip", &peer_alert::ip)
        .def_readonly("pid", &peer_alert::pid)
    ;
    class_<tracker_error_alert, bases<tracker_alert>, noncopyable>(
        "tracker_error_alert", tracker_error_alert_doc, no_init
    )
        .def_readonly("msg", &tracker_error_alert::msg)
        .def_readonly("times_in_row", &tracker_error_alert::times_in_row)
        .def_readonly("status_code", &tracker_error_alert::status_code)
        ;

    class_<tracker_warning_alert, bases<tracker_alert>, noncopyable>(
        "tracker_warning_alert", tracker_warning_alert_doc, no_init
    );

    class_<tracker_reply_alert, bases<tracker_alert>, noncopyable>(
        "tracker_reply_alert", tracker_reply_alert_doc, no_init
    )
        .def_readonly("num_peers", &tracker_reply_alert::num_peers)
        ;

    class_<tracker_announce_alert, bases<tracker_alert>, noncopyable>(
        "tracker_announce_alert", tracker_announce_alert_doc, no_init
    );

    class_<hash_failed_alert, bases<torrent_alert>, noncopyable>(
        "hash_failed_alert", hash_failed_alert_doc, no_init
    )
        .def_readonly("piece_index", &hash_failed_alert::piece_index)
        ;

    class_<peer_ban_alert, bases<peer_alert>, noncopyable>(
        "peer_ban_alert", peer_ban_alert_doc, no_init
    );

    class_<peer_error_alert, bases<peer_alert>, noncopyable>(
        "peer_error_alert", peer_error_alert_doc, no_init
    );

    class_<invalid_request_alert, bases<peer_alert>, noncopyable>(
        "invalid_request_alert", invalid_request_alert_doc, no_init
    )
        .def_readonly("request", &invalid_request_alert::request)
        ;

    class_<peer_request>("peer_request", peer_request_doc)
        .def_readonly("piece", &peer_request::piece)
        .def_readonly("start", &peer_request::start)
        .def_readonly("length", &peer_request::length)
        .def(self == self)
        ;

    class_<torrent_finished_alert, bases<torrent_alert>, noncopyable>(
        "torrent_finished_alert", torrent_finished_alert_doc, no_init
    );

    class_<piece_finished_alert, bases<torrent_alert>, noncopyable>(
        "piece_finished_alert", piece_finished_alert_doc, no_init
    )
        .def_readonly("piece_index", &piece_finished_alert::piece_index)
        ;

    class_<block_finished_alert, bases<peer_alert>, noncopyable>(
        "block_finished_alert", block_finished_alert_doc, no_init
    )
        .def_readonly("block_index", &block_finished_alert::block_index)
        .def_readonly("piece_index", &block_finished_alert::piece_index)
        ;

    class_<block_downloading_alert, bases<peer_alert>, noncopyable>(
        "block_downloading_alert", block_downloading_alert_doc, no_init
    )
        .def_readonly("peer_speedmsg", &block_downloading_alert::peer_speedmsg)
        .def_readonly("block_index", &block_downloading_alert::block_index)
        .def_readonly("piece_index", &block_downloading_alert::piece_index)
        ;

    class_<storage_moved_alert, bases<torrent_alert>, noncopyable>(
        "storage_moved_alert", storage_moved_alert_doc, no_init
    );

    class_<torrent_deleted_alert, bases<torrent_alert>, noncopyable>(
        "torrent_deleted_alert", torrent_deleted_alert_doc, no_init
    );

    class_<torrent_paused_alert, bases<torrent_alert>, noncopyable>(
        "torrent_paused_alert", torrent_paused_alert_doc, no_init
    );

    class_<torrent_checked_alert, bases<torrent_alert>, noncopyable>(
        "torrent_checked_alert", torrent_checked_alert_doc, no_init
    );

    class_<url_seed_alert, bases<torrent_alert>, noncopyable>(
        "url_seed_alert", url_seed_alert_doc, no_init
    )
        .def_readonly("url", &url_seed_alert::url)
        ;

    class_<file_error_alert, bases<torrent_alert>, noncopyable>(
        "file_error_alert", file_error_alert_doc, no_init
    )
        .def_readonly("file", &file_error_alert::file)
        ;

    class_<metadata_failed_alert, bases<torrent_alert>, noncopyable>(
        "metadata_failed_alert", metadata_failed_alert_doc, no_init
    );

    class_<metadata_received_alert, bases<torrent_alert>, noncopyable>(
        "metadata_received_alert", metadata_received_alert_doc, no_init
    );

    class_<listen_failed_alert, bases<alert>, noncopyable>(
        "listen_failed_alert", listen_failed_alert_doc, no_init
    );

    class_<listen_succeeded_alert, bases<alert>, noncopyable>(
        "listen_succeeded_alert", listen_succeeded_alert_doc, no_init
    )
        .def_readonly("endpoint", &listen_succeeded_alert::endpoint)
        ;

    class_<portmap_error_alert, bases<alert>, noncopyable>(
        "portmap_error_alert", portmap_error_alert_doc, no_init
    )
        .def_readonly("mapping", &portmap_error_alert::mapping)
        .def_readonly("type", &portmap_error_alert::type)
        ;

    class_<portmap_alert, bases<alert>, noncopyable>(
        "portmap_alert", portmap_alert_doc, no_init
    )
        .def_readonly("mapping", &portmap_alert::mapping)
        .def_readonly("external_port", &portmap_alert::external_port)
        .def_readonly("type", &portmap_alert::type)
        ;

    class_<fastresume_rejected_alert, bases<torrent_alert>, noncopyable>(
        "fastresume_rejected_alert", fastresume_rejected_alert_doc, no_init
    );

    class_<peer_blocked_alert, bases<alert>, noncopyable>(
        "peer_blocked_alert", peer_blocked_alert_doc, no_init
    )
        .def_readonly("ip", &peer_blocked_alert::ip)
        ;

    class_<scrape_reply_alert, bases<tracker_alert>, noncopyable>(
        "scrape_reply_alert", scrape_reply_alert_doc, no_init
    )
        .def_readonly("incomplete", &scrape_reply_alert::incomplete)
        .def_readonly("complete", &scrape_reply_alert::complete)
        ;

    class_<scrape_failed_alert, bases<tracker_alert>, noncopyable>(
        "scrape_failed_alert", scrape_failed_alert_doc, no_init
    );

    class_<udp_error_alert, bases<alert>, noncopyable>(
        "udp_error_alert", udp_error_alert_doc, no_init
    )
        .def_readonly("endpoint", &udp_error_alert::endpoint)
        ;

    class_<external_ip_alert, bases<alert>, noncopyable>(
        "external_ip_alert", external_ip_alert_doc, no_init
    )
        .def_readonly("external_address", &external_ip_alert::external_address)
        ;

    class_<save_resume_data_alert, bases<torrent_alert>, noncopyable>(
        "save_resume_data_alert", save_resume_data_alert_doc, no_init
    )
        .def_readonly("resume_data", &save_resume_data_alert::resume_data)
        ;

    class_<file_renamed_alert, bases<torrent_alert>, noncopyable>(
        "file_renamed_alert", no_init
    )
        .def_readonly("name", &file_renamed_alert::name)
        ;

    class_<file_rename_failed_alert, bases<torrent_alert>, noncopyable>(
        "file_rename_failed_alert", no_init
    )
        .def_readonly("index", &file_rename_failed_alert::index)
        ;

    class_<torrent_resumed_alert, bases<torrent_alert>, noncopyable>(
        "torrent_resumed_alert", no_init
	);

	class_<state_changed_alert, bases<torrent_alert>, noncopyable>(
	    "state_changed_alert", no_init
	)
	    .def_readonly("state", &state_changed_alert::state)
	    ;

	class_<dht_reply_alert, bases<tracker_alert>, noncopyable>(
	    "dht_reply_alert", no_init
	)
	    .def_readonly("num_peers", &dht_reply_alert::num_peers)
	    ;

	class_<peer_unsnubbed_alert, bases<peer_alert>, noncopyable>(
	    "peer_unsnubbed_alert", no_init
	);

	class_<peer_snubbed_alert, bases<peer_alert>, noncopyable>(
	    "peer_snubbed_alert", no_init
	);

    class_<peer_connect_alert, bases<peer_alert>, noncopyable>(
        "peer_connect_alert", no_init
    );

    class_<peer_disconnected_alert, bases<peer_alert>, noncopyable>(
        "peer_disconnected_alert", no_init
    );

    class_<request_dropped_alert, bases<peer_alert>, noncopyable>(
        "request_dropped_alert", no_init
    )
        .def_readonly("block_index", &request_dropped_alert::block_index)
        .def_readonly("piece_index", &request_dropped_alert::piece_index)
    ;

    class_<block_timeout_alert, bases<peer_alert>, noncopyable>(
        "block_timeout_alert", no_init
    )
        .def_readonly("block_index", &block_timeout_alert::block_index)
        .def_readonly("piece_index", &block_timeout_alert::piece_index)
    ;

    class_<unwanted_block_alert, bases<peer_alert>, noncopyable>(
        "unwanted_block_alert", no_init
    )
        .def_readonly("block_index", &unwanted_block_alert::block_index)
        .def_readonly("piece_index", &unwanted_block_alert::piece_index)
    ;

    class_<torrent_delete_failed_alert, bases<torrent_alert>, noncopyable>(
        "torrent_delete_failed_alert", no_init
    );

    class_<save_resume_data_failed_alert, bases<torrent_alert>, noncopyable>(
        "save_resume_data_failed_alert", no_init
    );

}
<|endoftext|>


<commit_before>/*
 * cStructureUtils.cpp
 *
 *  Created on: 2-aug-2010
 *      Author: Stefan
 */

#include "../d2tmh.h"

cStructureUtils::cStructureUtils() {
}

cStructureUtils::~cStructureUtils() {
}

int cStructureUtils::getHeightOfStructureTypeInCells(int structureType) {
	assert(structureType >= 0);
	assert(structureType < MAX_STRUCTURETYPES);
	return structures[structureType].bmp_height / TILESIZE_HEIGHT_PIXELS;
}

int cStructureUtils::getWidthOfStructureTypeInCells(int structureType) {
	assert(structureType >= 0);
	assert(structureType < MAX_STRUCTURETYPES);
	return structures[structureType].bmp_height / TILESIZE_WIDTH_PIXELS;
}

/**
 * This is almost the same as the findStructureToDeployUnit
 *
 * However, whenever the player has not set any primary building. Try to find a structure that has some free cell around it.
 */
int cStructureUtils::findStarportToDeployUnit(cPlayer * player) {
	assert(player);
	int playerId = player->getId();

	// check primary building first if set
	int primaryBuildingOfStructureType = player->iPrimaryBuilding[STARPORT];

	if (primaryBuildingOfStructureType > -1) {
		cAbstractStructure * theStructure = structure[primaryBuildingOfStructureType];
		if (theStructure && theStructure->iFreeAround() > -1) {
			return primaryBuildingOfStructureType;
		}
	}

	// find a starport that has space around it.
	int starportId = -1;
	int firstFoundStarportId = -1;
	bool foundStarportWithFreeAround = false;
	for (int i=0; i < MAX_STRUCTURES; i++) {
		cAbstractStructure * theStructure = structure[i];
		if (theStructure && theStructure->getOwner() == playerId) {
			if (theStructure->getType() == STARPORT) {
				// when no id set, always set one id
				if (starportId < 0) {
					starportId = i;
				}

				if (firstFoundStarportId < 0) {
					firstFoundStarportId = i;
				}

				if (theStructure->iFreeAround() > -1) {
					// when free around structure, override id and break out of loop
					starportId = i;
					foundStarportWithFreeAround = true;
					break;
				}
			}
		}
	}

	if (!foundStarportWithFreeAround) {
		if (primaryBuildingOfStructureType > -1) {
			return primaryBuildingOfStructureType;
		}
		if (firstFoundStarportId > -1) {
			return firstFoundStarportId;
		}
	}
	return starportId;

}

/**
 * Finds a building to deploy a unit from. Returns the structure ID of the found structure.
 *
 * Will use primary building set by player first, before looking for alternatives.
 *
 */
int cStructureUtils::findStructureToDeployUnit(cPlayer * player, int structureType) {
	assert(player);
	assert(structureType > -1);

	int playerId = player->getId();

	if (DEBUGGING) {
		char msg[255];
		sprintf(msg, "Looking for primary building (type %d, name %s, player %d)", structureType, structures[structureType].name, playerId);
		logbook(msg);
	}

	// check primary building first if set
	int primaryBuildingOfStructureType = player->iPrimaryBuilding[structureType];

	if (primaryBuildingOfStructureType > -1) {
		cAbstractStructure * theStructure = structure[primaryBuildingOfStructureType];
		if (theStructure && theStructure->iFreeAround() > -1) {
			return primaryBuildingOfStructureType;
		}
	}

	// check other structures now
	for (int i=0; i < MAX_STRUCTURES; i++) {
		cAbstractStructure * theStructure = structure[i];
		if (theStructure && theStructure->getOwner() == playerId) {
			if (theStructure->getType() == structureType) {
				if (theStructure->iFreeAround() > -1) {
					return i; // return this structure
				}
			}
		}
	}

	return -1;
}

/**
 * Depending on list type, return a structure type.
 */
int cStructureUtils::findStructureTypeByTypeOfList(cBuildingList *list, cBuildingListItem *item) {
	assert(list);
	assert(item);
	assert(item->getBuildType() == UNIT);

	int listTypeId = list->getType();
	char msg[255];
	sprintf(msg, "going to find list with listTypeId [%d]", listTypeId);
	cLogger::getInstance()->logCommentLine(msg);
	switch (listTypeId) {
		case LIST_CONSTYARD:
			// a unit, and then built from a constyard list
			assert(false);
			return CONSTYARD;
		case LIST_HEAVYFC:
			return HEAVYFACTORY;
		case LIST_INFANTRY:
			if (item->getBuildId() == INFANTRY || item->getBuildId() == SOLDIER) {
				return BARRACKS;
			}
			return WOR;
		case LIST_LIGHTFC:
			return LIGHTFACTORY;
		case LIST_ORNI:
			return HIGHTECH;
		case LIST_PALACE:
			return PALACE;
		case LIST_NONE:
			assert(false);
			return -1;
		case LIST_STARPORT:
			return STARPORT;
		default:
			assert(false);
			return -1;
	}
	return -1;
}

int cStructureUtils::findClosestStructureTypeToCell(int cell, int structureType, cPlayer * player) {
	assert(player);
	assert(structureType > -1);
	assert(cell >= 0 || cell < MAX_CELLS);

	// We need cell calculation, so get a calculator:
	cCellCalculator cellCalculator;

	int foundStructureId=-1;		// found structure id
	long shortestDistance=9999; // max distance to search in

	int playerId = player->getId();

	for (int i=0; i < MAX_STRUCTURES; i++) {
		if (structure[i]) {												// exists (pointer)
			if (structure[i]->getOwner() == playerId) {     			// same player
				if (structure[i]->getType() == structureType) {   		// type equals parameter
					if (structure[i]->iUnitID < 0) {    				// no other unit is heading to this structure
						long distance = cellCalculator.distance(cell, structure[i]->getCell());

						// if distance is lower than last found distance, it is the closest for now.
						if (distance < shortestDistance) {
							foundStructureId=i;
							shortestDistance=distance;
						}
					}
				}
			}
		}
	}

	return foundStructureId;
}
<commit_msg>Fixed bug where the method getWidthOfStructureTypeInCells used the height property of a structure (instead of the... width property :))<commit_after>/*
 * cStructureUtils.cpp
 *
 *  Created on: 2-aug-2010
 *      Author: Stefan
 */

#include "../d2tmh.h"

cStructureUtils::cStructureUtils() {
}

cStructureUtils::~cStructureUtils() {
}

int cStructureUtils::getHeightOfStructureTypeInCells(int structureType) {
	assert(structureType >= 0);
	assert(structureType < MAX_STRUCTURETYPES);
	return structures[structureType].bmp_height / TILESIZE_HEIGHT_PIXELS;
}

int cStructureUtils::getWidthOfStructureTypeInCells(int structureType) {
	assert(structureType >= 0);
	assert(structureType < MAX_STRUCTURETYPES);
	return structures[structureType].bmp_width / TILESIZE_WIDTH_PIXELS;
}

/**
 * This is almost the same as the findStructureToDeployUnit
 *
 * However, whenever the player has not set any primary building. Try to find a structure that has some free cell around it.
 */
int cStructureUtils::findStarportToDeployUnit(cPlayer * player) {
	assert(player);
	int playerId = player->getId();

	// check primary building first if set
	int primaryBuildingOfStructureType = player->iPrimaryBuilding[STARPORT];

	if (primaryBuildingOfStructureType > -1) {
		cAbstractStructure * theStructure = structure[primaryBuildingOfStructureType];
		if (theStructure && theStructure->iFreeAround() > -1) {
			return primaryBuildingOfStructureType;
		}
	}

	// find a starport that has space around it.
	int starportId = -1;
	int firstFoundStarportId = -1;
	bool foundStarportWithFreeAround = false;
	for (int i=0; i < MAX_STRUCTURES; i++) {
		cAbstractStructure * theStructure = structure[i];
		if (theStructure && theStructure->getOwner() == playerId) {
			if (theStructure->getType() == STARPORT) {
				// when no id set, always set one id
				if (starportId < 0) {
					starportId = i;
				}

				if (firstFoundStarportId < 0) {
					firstFoundStarportId = i;
				}

				if (theStructure->iFreeAround() > -1) {
					// when free around structure, override id and break out of loop
					starportId = i;
					foundStarportWithFreeAround = true;
					break;
				}
			}
		}
	}

	if (!foundStarportWithFreeAround) {
		if (primaryBuildingOfStructureType > -1) {
			return primaryBuildingOfStructureType;
		}
		if (firstFoundStarportId > -1) {
			return firstFoundStarportId;
		}
	}
	return starportId;

}

/**
 * Finds a building to deploy a unit from. Returns the structure ID of the found structure.
 *
 * Will use primary building set by player first, before looking for alternatives.
 *
 */
int cStructureUtils::findStructureToDeployUnit(cPlayer * player, int structureType) {
	assert(player);
	assert(structureType > -1);

	int playerId = player->getId();

	if (DEBUGGING) {
		char msg[255];
		sprintf(msg, "Looking for primary building (type %d, name %s, player %d)", structureType, structures[structureType].name, playerId);
		logbook(msg);
	}

	// check primary building first if set
	int primaryBuildingOfStructureType = player->iPrimaryBuilding[structureType];

	if (primaryBuildingOfStructureType > -1) {
		cAbstractStructure * theStructure = structure[primaryBuildingOfStructureType];
		if (theStructure && theStructure->iFreeAround() > -1) {
			return primaryBuildingOfStructureType;
		}
	}

	// check other structures now
	for (int i=0; i < MAX_STRUCTURES; i++) {
		cAbstractStructure * theStructure = structure[i];
		if (theStructure && theStructure->getOwner() == playerId) {
			if (theStructure->getType() == structureType) {
				if (theStructure->iFreeAround() > -1) {
					return i; // return this structure
				}
			}
		}
	}

	return -1;
}

/**
 * Depending on list type, return a structure type.
 */
int cStructureUtils::findStructureTypeByTypeOfList(cBuildingList *list, cBuildingListItem *item) {
	assert(list);
	assert(item);
	assert(item->getBuildType() == UNIT);

	int listTypeId = list->getType();
	char msg[255];
	sprintf(msg, "going to find list with listTypeId [%d]", listTypeId);
	cLogger::getInstance()->logCommentLine(msg);
	switch (listTypeId) {
		case LIST_CONSTYARD:
			// a unit, and then built from a constyard list
			assert(false);
			return CONSTYARD;
		case LIST_HEAVYFC:
			return HEAVYFACTORY;
		case LIST_INFANTRY:
			if (item->getBuildId() == INFANTRY || item->getBuildId() == SOLDIER) {
				return BARRACKS;
			}
			return WOR;
		case LIST_LIGHTFC:
			return LIGHTFACTORY;
		case LIST_ORNI:
			return HIGHTECH;
		case LIST_PALACE:
			return PALACE;
		case LIST_NONE:
			assert(false);
			return -1;
		case LIST_STARPORT:
			return STARPORT;
		default:
			assert(false);
			return -1;
	}
	return -1;
}

int cStructureUtils::findClosestStructureTypeToCell(int cell, int structureType, cPlayer * player) {
	assert(player);
	assert(structureType > -1);
	assert(cell >= 0 || cell < MAX_CELLS);

	// We need cell calculation, so get a calculator:
	cCellCalculator cellCalculator;

	int foundStructureId=-1;		// found structure id
	long shortestDistance=9999; // max distance to search in

	int playerId = player->getId();

	for (int i=0; i < MAX_STRUCTURES; i++) {
		if (structure[i]) {												// exists (pointer)
			if (structure[i]->getOwner() == playerId) {     			// same player
				if (structure[i]->getType() == structureType) {   		// type equals parameter
					if (structure[i]->iUnitID < 0) {    				// no other unit is heading to this structure
						long distance = cellCalculator.distance(cell, structure[i]->getCell());

						// if distance is lower than last found distance, it is the closest for now.
						if (distance < shortestDistance) {
							foundStructureId=i;
							shortestDistance=distance;
						}
					}
				}
			}
		}
	}

	return foundStructureId;
}
<|endoftext|>


<commit_before>#ifndef GCN_INPUT_HPP
#define GCN_INPUT_HPP

namespace gcn
{
  /**
   *
   */
  enum InputType
  {
    EMPTY,
    KEY_DOWN,
    KEY_TYPE,
    KEY_RELEASE,
    MOUSE_DOWN,
    MOUSE_RELEASE,
    MOUSE_WHEEL_UP,
    MOUSE_WHEEL_DOWN

  }; // end InputType

  /**
   *
   */
  class Input
  {
  public:
    /**
     *
     */
    virtual ~Input();
    /**
     *
     */
    virtual int getMouseX() = 0;
    /**
     *
     */
    virtual int getMouseY() = 0;
    /**
     *
     */
    virtual void getMousePosition(int& x, int& y) = 0;
    /**
     *
     */
    virtual const InputType& pollKeyInput(Key& key) = 0;
    /**
     *
     */
    virtual const InputType& pollMouseInput(int& x, int& y, int& button) = 0;

  }; // end Input

} // end gcn

#endif // end GCN_INPUT_HPP
<commit_msg>Added new functions to check whether the key and mouse queue is empty and a function to check whether to mouse has moved since the last frame.<commit_after>#ifndef GCN_INPUT_HPP
#define GCN_INPUT_HPP

#include "guichan/keyinput.hpp"
#include "guichan/mouseinput.hpp"

namespace gcn
{
  /**
   *
   */
  class Input
  {
  public:
    /**
     *
     */
    virtual ~Input();
    /**
     *
     */
    virtual int getMouseX() = 0;
    /**
     *
     */
    virtual int getMouseY() = 0;
    /**
     *
     */
    virtual void getMousePosition(int& x, int& y) = 0;

    /**
     *
     */
    virtual bool isKeyQueueEmpty() = 0;

    /**
     *
     */
    virtual KeyInput dequeueKeyInput() = 0;

    /**
     *
     */
    virtual bool isMouseQueueEmpty() = 0;

    /**
     *
     */
    virtual MouseInput dequeueMouseInput() = 0;

    /**
     *
     */
    virtual bool isMouseMoved() = 0;

    /**
     *
     */
    virtual void pollInput() = 0;

  }; // end Input

} // end gcn

#endif // end GCN_INPUT_HPP
<|endoftext|>


<commit_before>#include "marian.h"

#include "training/graph_group_async.h"
#include "training/graph_group_multinode_sync.h"
#include "training/graph_group_singleton.h"
#include "training/graph_group_sync.h"
#include "training/training.h"

#ifdef CUDA_FOUND
#include "training/graph_group_async_drop.h"
#include "training/graph_group_multinode.h"
#endif

int main(int argc, char** argv) {
  using namespace marian;

  auto options = parseOptions(argc, argv);

  // selects MultiNodeGraphGroup family
  // Note: --sync-sgd without --multi-node also supports MPI now, using the SyncGraphGroup.
  // This means we have two redundant implementations of multi-node sync-sgd. Note that the
  // MultiNodeGraphGroup family is out of date. Therefore, the goal is to remove MultiNodeGraphGroupSync.
  if(options->get<bool>("multi-node")) {
    LOG(warn, "[experimental] Old multi-node training implementations. These are presently not up-to-date");

    if(options->get<bool>("sync-sgd")) {
      LOG(debug, "[training] Using MultiNodeGraphGroupSync trainer");
      New<Train<MultiNodeGraphGroupSync>>(options)->run();
    } else {
#ifdef CUDA_FOUND
      LOG(debug, "[training] Using MultiNodeGraphGroup trainer");
      New<Train<MultiNodeGraphGroup>>(options)->run();
#else
      ABORT("Asynchronous multi-node training requires CUDA");
#endif
    }
  }
  // --sync-sgd always selects SyncGraphGroup
  // If given, then this implementation is used for all combinations of
  // (single, multiple) MPI processes x (single, multiple) GPUs per MPI process.
  // This variant is presently up-to-date and best supported.
  else if (options->get<bool>("sync-sgd")) {
    LOG(debug, "[training] Using SyncGraphGroup trainer");
    New<Train<SyncGraphGroup>>(options)->run();
  }
  else {
    auto devices = Config::getDevices(options);
    if(devices.size() == 1) {
      LOG(debug, "[training] Using SingletonGraph trainer");
      New<Train<SingletonGraph>>(options)->run();
    } else {
      if(options->get<float>("grad-dropping-rate") > 0.0) {
#ifdef CUDA_FOUND
        LOG(debug, "[training] Using AsyncGraphGroupDrop trainer");
        New<Train<AsyncGraphGroupDrop>>(options)->run();
#else
        ABORT("Asynchronous training with gradient dropping requires CUDA");
#endif
      } else {
        New<Train<AsyncGraphGroup>>(options)->run();
      }
    }
  }

  return 0;
}
<commit_msg>Use 'info' logging level with more user-friendly messages<commit_after>#include "marian.h"

#include "training/graph_group_async.h"
#include "training/graph_group_multinode_sync.h"
#include "training/graph_group_singleton.h"
#include "training/graph_group_sync.h"
#include "training/training.h"

#ifdef CUDA_FOUND
#include "training/graph_group_async_drop.h"
#include "training/graph_group_multinode.h"
#endif

int main(int argc, char** argv) {
  using namespace marian;

  auto options = parseOptions(argc, argv);

  // selects MultiNodeGraphGroup family
  //
  // Note: --sync-sgd without --multi-node also supports MPI now, using the SyncGraphGroup.  This
  // means we have two redundant implementations of multi-node sync-sgd.  Note that the
  // MultiNodeGraphGroup family is out of date.  Therefore, the goal is to remove
  // MultiNodeGraphGroupSync.
  if(options->get<bool>("multi-node")) {
    LOG(warn, "[experimental] Using old multi-node training implementations that are not up-to-date");

    if(options->get<bool>("sync-sgd")) {
      LOG(info, "Using multi-node synchronous training");
      New<Train<MultiNodeGraphGroupSync>>(options)->run();
    } else {
#ifdef CUDA_FOUND
      LOG(info, "Using multi-node asynchronous training");
      New<Train<MultiNodeGraphGroup>>(options)->run();
#else
      ABORT("Asynchronous multi-node training requires CUDA");
#endif
    }
  }
  // --sync-sgd always selects SyncGraphGroup
  //
  // If given, then this implementation is used for all combinations of (single, multiple) MPI
  // processes x (single, multiple) GPUs per MPI process.  This variant is presently up-to-date and
  // best supported.
  else if (options->get<bool>("sync-sgd")) {
    LOG(info, "Using synchronous training");
    New<Train<SyncGraphGroup>>(options)->run();
  }
  else {
    auto devices = Config::getDevices(options);
    if(devices.size() == 1) {
      LOG(info, "Using single-device training");
      New<Train<SingletonGraph>>(options)->run();
    } else {
      if(options->get<float>("grad-dropping-rate") > 0.0) {
#ifdef CUDA_FOUND
        LOG(info, "Using asynchronous training with gradient dropping");
        New<Train<AsyncGraphGroupDrop>>(options)->run();
#else
        ABORT("Asynchronous training with gradient dropping requires CUDA");
#endif
      } else {
        LOG(info, "Using asynchronous training");
        New<Train<AsyncGraphGroup>>(options)->run();
      }
    }
  }

  return 0;
}
<|endoftext|>


<commit_before>/**
 ** \file  libport/escape.hh
 ** \brief Escape: escaping special characters for output.
 **/

#ifndef LIBPORT_ESCAPE_HH
# define LIBPORT_ESCAPE_HH

# include <iosfwd>
# include <string>

# include <libport/export.hh>

namespace libport
{

  class LIBPORT_API Escape
  {
  public:
    std::ostream& print(std::ostream& ostr) const;

  protected:
    template <class T>
      Escape(const T&, char delimiter);

    // I (Akim) don't know if this is a bug in G++, but if I don't
    // declare the optional argument here, the ("real") declaration
    // that follows with the default value is not honored: callers
    // with a single argument do not match the right function.
    //
    // So declare it twice with the right prototype, including the
    // default argument.
    template <class T>
      friend Escape escape(const T&, char delimiter = '"');

  protected:
    std::string  str_;

  private:
    std::ostream& escape_(std::ostream& o, const std::string& es) const;
    char delimiter_;
  };

  /// Wrap \a t so that once output non printable characters are
  /// converted in \-based escapes.
  template <class T>
  Escape escape(const T& t, char delimiter = '"');

  /// Helper function.
  std::ostream& operator<< (std::ostream& o, const Escape&);

  /// Process \-based escapes.
  std::string unescape(const std::string& s);
}

# include <libport/escape.hxx>

#endif // !LIBPORT_ESCAPE_HH
<commit_msg>Do not give the default parameter in friend declaration.<commit_after>/**
 ** \file  libport/escape.hh
 ** \brief Escape: escaping special characters for output.
 **/

#ifndef LIBPORT_ESCAPE_HH
# define LIBPORT_ESCAPE_HH

# include <iosfwd>
# include <string>

# include <libport/export.hh>

namespace libport
{

  class LIBPORT_API Escape
  {
  public:
    std::ostream& print(std::ostream& ostr) const;

  protected:
    template <class T>
      Escape(const T&, char delimiter);

    // I (Akim) don't know if this is a bug in G++, but if I don't
    // declare the optional argument here, the ("real") declaration
    // that follows with the default value is not honored: callers
    // with a single argument do not match the right function.
    //
    // So declare it twice with the right prototype, including the
    // default argument.
    template <class T>
      friend Escape escape(const T&, char delimiter);

  protected:
    std::string  str_;

  private:
    std::ostream& escape_(std::ostream& o, const std::string& es) const;
    char delimiter_;
  };

  /// Wrap \a t so that once output non printable characters are
  /// converted in \-based escapes.
  template <class T>
  Escape escape(const T& t, char delimiter = '"');

  /// Helper function.
  std::ostream& operator<< (std::ostream& o, const Escape&);

  /// Process \-based escapes.
  std::string unescape(const std::string& s);
}

# include <libport/escape.hxx>

#endif // !LIBPORT_ESCAPE_HH
<|endoftext|>


<commit_before>/*
 * Copyright 2017 deepstreamHub GmbH
 *
 * 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.
 */
#ifndef DEEPSTREAM_WEBSOCKETS_PSEUDO_HPP
#define DEEPSTREAM_WEBSOCKETS_PSEUDO_HPP

#include <memory>
#include <string>
#include <utility>

#include <time.hpp>

namespace deepstream
{
	struct Buffer;

	namespace websockets
	{
		enum class StatusCode;
		struct Frame;
		struct Client;

		namespace pseudo
		{
			struct Client : public ::deepstream::websockets::Client
			{
				typedef std::unique_ptr<Frame> FramePtr;

				explicit Client();

				virtual std::string uri_impl() const override;

				virtual time::Duration get_receive_timeout_impl() override;
				virtual void set_receive_timeout_impl(time::Duration) override;

				virtual void close_impl() override;

				time::Duration timeout_;
			};
		}
	}
}

#endif
<commit_msg>Src: remove unused typedef<commit_after>/*
 * Copyright 2017 deepstreamHub GmbH
 *
 * 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.
 */
#ifndef DEEPSTREAM_WEBSOCKETS_PSEUDO_HPP
#define DEEPSTREAM_WEBSOCKETS_PSEUDO_HPP

#include <memory>
#include <string>
#include <utility>

#include <time.hpp>

namespace deepstream
{
	struct Buffer;

	namespace websockets
	{
		enum class StatusCode;
		struct Frame;
		struct Client;

		namespace pseudo
		{
			struct Client : public ::deepstream::websockets::Client
			{
				explicit Client();

				virtual std::string uri_impl() const override;

				virtual time::Duration get_receive_timeout_impl() override;
				virtual void set_receive_timeout_impl(time::Duration) override;

				virtual void close_impl() override;

				time::Duration timeout_;
			};
		}
	}
}

#endif
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef _OCTREE_HPP_
#define _OCTREE_HPP_

// boost
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/utility.hpp>

// stl
#include <vector>
#include <iostream>
#include <deque>

namespace mapnik {

   typedef uint8_t byte ;
   struct rgb
   {
         byte r;
         byte g;
         byte b;
         rgb(byte r_, byte b_, byte g_)
            : r(r_), g(g_), b(b_) {}
   };

   struct RGBPolicy
   {
         const static unsigned MAX_LEVELS = 6;
         inline static unsigned index_from_level(unsigned level, rgb const& c)
         {
            unsigned shift = (MAX_LEVELS + 1) - level;
            return (((c.r >> shift) & 1) << 2)
               | (((c.g >> shift) & 1) << 1)
               | ((c.b >> shift) & 1);
         }
   };

   template <typename T, typename InsertPolicy = RGBPolicy >
   class octree : private boost::noncopyable
   {
         struct node
         {
               node ()
                  :  reds(0),
                     greens(0),
                     blues(0),
                     count(0),
                     count2(0),
                     index(0)
               {
                  memset(&children_[0],0,sizeof(children_));
               }

               ~node ()
               {
                  for (unsigned i = 0;i < 8; ++i) {
                     if (children_[i] != 0) delete children_[i],children_[i]=0;
                  }
               }

               bool is_leaf() const { return count == 0; }
               node * children_[8];
               unsigned reds;
               unsigned greens;
               unsigned blues;
               unsigned count;
               unsigned count2;
               uint8_t  index;
         };
         struct node_cmp
         {
               bool operator() ( const node * lhs,const node* rhs) const
               {
                  return lhs->count2 < rhs->count2;
               }
         };

         std::deque<node*> reducible_[InsertPolicy::MAX_LEVELS];
         unsigned max_colors_;
         unsigned colors_;
         unsigned leaf_level_;

      public:
         explicit octree(unsigned max_colors=256)
            : max_colors_(max_colors),
              colors_(0),
              leaf_level_(InsertPolicy::MAX_LEVELS),
              root_(new node())
         {}

         ~octree() { delete root_;}

         void insert(T const& data)
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (true) {
               cur_node->count2++;

               if ( cur_node->count > 0 || level == leaf_level_)
               {
                  cur_node->reds   += data.r;
                  cur_node->greens += data.g;
                  cur_node->blues  += data.b;
                  cur_node->count  += 1;
                  if (cur_node->count == 1) ++colors_;
                  //if (colors_ >= max_colors_ - 1)
                  //reduce();
                  break;
               }

               unsigned idx = InsertPolicy::index_from_level(level,data);
               if (cur_node->children_[idx] == 0) {
                  cur_node->children_[idx] = new node();
                  if (level < leaf_level_-1)
                  {
                     reducible_[level+1].push_back(cur_node->children_[idx]);
                  }
               }
               cur_node = cur_node->children_[idx];
               ++level;
            }
         }

         int quantize(rgb const& c) const
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (cur_node)
            {
               if (cur_node->count != 0) return cur_node->index;
               unsigned idx = InsertPolicy::index_from_level(level,c);
               cur_node = cur_node->children_[idx];
               ++level;
            }
            return -1;
         }

         void create_palette(std::vector<rgb> & palette)
         {
            reduce();
            palette.reserve(colors_);
            create_palette(palette, root_);
         }

         void reduce()
         {
            // sort reducible
            for (unsigned i=0;i<InsertPolicy::MAX_LEVELS;++i)
            {
               std::sort(reducible_[i].begin(), reducible_[i].end(),node_cmp());
            }

            while ( colors_ >= max_colors_ - 1)
            {
               while (leaf_level_ >0  && reducible_[leaf_level_-1].size() == 0)
               {
                  --leaf_level_;
               }

               if (leaf_level_ < 1) continue;

               if ( reducible_[leaf_level_-1].size() == 0) return;

               typename std::deque<node*>::iterator pos = reducible_[leaf_level_-1].begin();
               node * cur_node = *pos;
               unsigned num_children = 0;
               for (unsigned idx=0; idx < 8; ++idx)
               {
                  if (cur_node->children_[idx] != 0)
                  {
                     ++num_children;
                     cur_node->reds   += cur_node->children_[idx]->reds;
                     cur_node->greens += cur_node->children_[idx]->greens;
                     cur_node->blues  += cur_node->children_[idx]->blues;
                     cur_node->count  += cur_node->children_[idx]->count;
                     delete cur_node->children_[idx], cur_node->children_[idx]=0;
                  }
               }

               reducible_[leaf_level_-1].erase(pos);
               if (num_children > 0 )
               {
                  colors_ -= (num_children - 1);
               }
            }
         }

         void create_palette(std::vector<rgb> & palette, node * itr) const
         {
            if (itr->count != 0)
            {
               unsigned count = itr->count;
               palette.push_back(rgb(uint8_t(itr->reds/float(count)),
                                     uint8_t(itr->greens/float(count)),
                                     uint8_t(itr->blues/float(count))));
               itr->index = palette.size() - 1;
            }
            for (unsigned i=0; i < 8 ;++i)
            {
               if (itr->children_[i] != 0)
                  create_palette(palette, itr->children_[i]);
            }
         }
      private:
         node * root_;
   };
} // namespace mapnik

#endif /* _OCTREE_HPP_ */
<commit_msg>+ boost-qualify type<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#ifndef _OCTREE_HPP_
#define _OCTREE_HPP_

// boost
#include <boost/cstdint.hpp>
#include <boost/format.hpp>
#include <boost/utility.hpp>

// stl
#include <vector>
#include <iostream>
#include <deque>

namespace mapnik {

   typedef boost::uint8_t byte ;
   struct rgb
   {
         byte r;
         byte g;
         byte b;
         rgb(byte r_, byte b_, byte g_)
            : r(r_), g(g_), b(b_) {}
   };

   struct RGBPolicy
   {
         const static unsigned MAX_LEVELS = 6;
         inline static unsigned index_from_level(unsigned level, rgb const& c)
         {
            unsigned shift = (MAX_LEVELS + 1) - level;
            return (((c.r >> shift) & 1) << 2)
               | (((c.g >> shift) & 1) << 1)
               | ((c.b >> shift) & 1);
         }
   };

   template <typename T, typename InsertPolicy = RGBPolicy >
   class octree : private boost::noncopyable
   {
         struct node
         {
               node ()
                  :  reds(0),
                     greens(0),
                     blues(0),
                     count(0),
                     count2(0),
                     index(0)
               {
                  memset(&children_[0],0,sizeof(children_));
               }

               ~node ()
               {
                  for (unsigned i = 0;i < 8; ++i) {
                     if (children_[i] != 0) delete children_[i],children_[i]=0;
                  }
               }

               bool is_leaf() const { return count == 0; }
               node * children_[8];
               unsigned reds;
               unsigned greens;
               unsigned blues;
               unsigned count;
               unsigned count2;
               uint8_t  index;
         };
         struct node_cmp
         {
               bool operator() ( const node * lhs,const node* rhs) const
               {
                  return lhs->count2 < rhs->count2;
               }
         };

         std::deque<node*> reducible_[InsertPolicy::MAX_LEVELS];
         unsigned max_colors_;
         unsigned colors_;
         unsigned leaf_level_;

      public:
         explicit octree(unsigned max_colors=256)
            : max_colors_(max_colors),
              colors_(0),
              leaf_level_(InsertPolicy::MAX_LEVELS),
              root_(new node())
         {}

         ~octree() { delete root_;}

         void insert(T const& data)
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (true) {
               cur_node->count2++;

               if ( cur_node->count > 0 || level == leaf_level_)
               {
                  cur_node->reds   += data.r;
                  cur_node->greens += data.g;
                  cur_node->blues  += data.b;
                  cur_node->count  += 1;
                  if (cur_node->count == 1) ++colors_;
                  //if (colors_ >= max_colors_ - 1)
                  //reduce();
                  break;
               }

               unsigned idx = InsertPolicy::index_from_level(level,data);
               if (cur_node->children_[idx] == 0) {
                  cur_node->children_[idx] = new node();
                  if (level < leaf_level_-1)
                  {
                     reducible_[level+1].push_back(cur_node->children_[idx]);
                  }
               }
               cur_node = cur_node->children_[idx];
               ++level;
            }
         }

         int quantize(rgb const& c) const
         {
            unsigned level = 0;
            node * cur_node = root_;
            while (cur_node)
            {
               if (cur_node->count != 0) return cur_node->index;
               unsigned idx = InsertPolicy::index_from_level(level,c);
               cur_node = cur_node->children_[idx];
               ++level;
            }
            return -1;
         }

         void create_palette(std::vector<rgb> & palette)
         {
            reduce();
            palette.reserve(colors_);
            create_palette(palette, root_);
         }

         void reduce()
         {
            // sort reducible
            for (unsigned i=0;i<InsertPolicy::MAX_LEVELS;++i)
            {
               std::sort(reducible_[i].begin(), reducible_[i].end(),node_cmp());
            }

            while ( colors_ >= max_colors_ - 1)
            {
               while (leaf_level_ >0  && reducible_[leaf_level_-1].size() == 0)
               {
                  --leaf_level_;
               }

               if (leaf_level_ < 1) continue;

               if ( reducible_[leaf_level_-1].size() == 0) return;

               typename std::deque<node*>::iterator pos = reducible_[leaf_level_-1].begin();
               node * cur_node = *pos;
               unsigned num_children = 0;
               for (unsigned idx=0; idx < 8; ++idx)
               {
                  if (cur_node->children_[idx] != 0)
                  {
                     ++num_children;
                     cur_node->reds   += cur_node->children_[idx]->reds;
                     cur_node->greens += cur_node->children_[idx]->greens;
                     cur_node->blues  += cur_node->children_[idx]->blues;
                     cur_node->count  += cur_node->children_[idx]->count;
                     delete cur_node->children_[idx], cur_node->children_[idx]=0;
                  }
               }

               reducible_[leaf_level_-1].erase(pos);
               if (num_children > 0 )
               {
                  colors_ -= (num_children - 1);
               }
            }
         }

         void create_palette(std::vector<rgb> & palette, node * itr) const
         {
            if (itr->count != 0)
            {
               unsigned count = itr->count;
               palette.push_back(rgb(uint8_t(itr->reds/float(count)),
                                     uint8_t(itr->greens/float(count)),
                                     uint8_t(itr->blues/float(count))));
               itr->index = palette.size() - 1;
            }
            for (unsigned i=0; i < 8 ;++i)
            {
               if (itr->children_[i] != 0)
                  create_palette(palette, itr->children_[i]);
            }
         }
      private:
         node * root_;
   };
} // namespace mapnik

#endif /* _OCTREE_HPP_ */
<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef __MINIZINC_MODEL_HH__
#define __MINIZINC_MODEL_HH__

#include <vector>
#include <iterator>

#include <minizinc/gc.hh>
#include <minizinc/ast.hh>

namespace MiniZinc {

  class VarDeclIterator;
  class ConstraintIterator;

  /// A MiniZinc model
  class Model {
    friend class GC;
  protected:
    /// Previous model in root set list
    Model* _roots_prev;
    /// Next model in root set list
    Model* _roots_next;

    /// Type of map from identifiers to function declarations
    typedef ASTStringMap<std::vector<FunctionI*> >::t FnMap;
    /// Map from identifiers to function declarations
    FnMap fnmap;

    /// Filename of the model
    ASTString _filename;
    /// Path of the model
    ASTString _filepath;
    /// Parent model if model was included
    Model* _parent;
    /// Items in the model
    std::vector<Item*> _items;
    /// Pointer to the solve item
    SolveI* _solveItem;
    /// Pointer to the output item
    OutputI* _outputItem;
  public:

    /// Construct empty model
    Model(void);
    /// Destructor
    ~Model(void);

    /// Add \a i to the model
    void addItem(Item* i) {
      _items.push_back(i);
      if (i->isa<SolveI>()) {
        _solveItem = i->cast<SolveI>();
      } else if (i->isa<OutputI>()) {
        _outputItem = i->cast<OutputI>();
      }
    }

    /// Get parent model
    Model* parent(void) const { return _parent; }
    /// Set parent model to \a p
    void setParent(Model* p) { assert(_parent==NULL); _parent = p; }

    /// Get file name
    ASTString filename(void) const { return _filename; }
    /// Get file path
    ASTString filepath(void) const { return _filepath; }
    /// Set file name
    void setFilename(const std::string& f) {
      assert(_filename.size()==0);
      _filename = ASTString(f);
    }
    /// Set file path
    void setFilepath(const std::string& f) {
      assert(_filepath.size()==0);
      _filepath = ASTString(f);
    }

    /// Register a builtin function item
    void registerFn(FunctionI* fi);
    /// Sort functions by type
    void sortFn(void);
    /// Return function declaration for \a id matching \a args
    FunctionI* matchFn(const ASTString& id,
                       const std::vector<Expression*>& args) const;
    /// Return function declaration for \a id matching types \a t
    FunctionI* matchFn(const ASTString& id, const std::vector<Type>& t);
    /// Return function declaration matching call \a c
    FunctionI* matchFn(Call* c) const;

    /// Return item \a i
    Item*& operator[] (int i);
    /// Return item \a i
    const Item* operator[] (int i) const;
    /// Return number of items
    unsigned int size(void) const;

    typedef std::vector<Item*>::iterator iterator;
    typedef std::vector<Item*>::const_iterator const_iterator;

    /// Iterator for beginning of items
    iterator begin(void);
    /// Iterator for beginning of items
    const_iterator begin(void) const;
    /// Iterator for end of items
    iterator end(void);
    /// Iterator for end of items
    const_iterator end(void) const;

    ConstraintIterator begin_constraints(void);
    ConstraintIterator end_constraints(void);
    VarDeclIterator begin_vardecls(void);
    VarDeclIterator end_vardecls(void);

    SolveI* solveItem(void);

    OutputI* outputItem(void);

    /// Remove all items marked as removed
    void compact(void);
  };

  class VarDeclIterator {
    Model* _model;
    Model::iterator _it;
  public:
    typedef typename Model::iterator::difference_type difference_type;
    typedef typename Model::iterator::value_type value_type;
    typedef VarDeclI& reference;
    typedef VarDeclI* pointer;
    typedef std::forward_iterator_tag iterator_category;

    VarDeclIterator() {}
    VarDeclIterator(const VarDeclIterator& vi) : _it(vi._it) {}
    VarDeclIterator(Model* model, const Model::iterator& it) : _model(model), _it(it) {
      while (_it != _model->end() && !(*_it)->isa<VarDeclI>()) {
        ++_it;
      }
    }
    ~VarDeclIterator() {}

    VarDeclIterator& operator=(const VarDeclIterator& vi) {
      if (this != &vi) {
        _it = vi._it;
      }
      return *this;
    }
    bool operator==(const VarDeclIterator& vi) const { return _it == vi._it; }
    bool operator!=(const VarDeclIterator& vi) const { return _it != vi._it; }
    VarDeclIterator& operator++() {
      do {
        ++_it;
      } while (_it != _model->end() && !(*_it)->isa<VarDeclI>());
      return *this;
    }

    reference operator*() const { return *(*_it)->cast<VarDeclI>(); }
    pointer operator->() const { return (*_it)->cast<VarDeclI>(); }
  };

  class ConstraintIterator {
    Model* _model;
    Model::iterator _it;
  public:
    typedef typename Model::iterator::difference_type difference_type;
    typedef typename Model::iterator::value_type value_type;
    typedef ConstraintI& reference;
    typedef ConstraintI* pointer;
    typedef std::forward_iterator_tag iterator_category;

    ConstraintIterator() {}
    ConstraintIterator(const ConstraintIterator& vi) : _it(vi._it) {}
    ConstraintIterator(Model* model, const Model::iterator& it) : _model(model), _it(it) {
      while (_it != _model->end() && !(*_it)->isa<ConstraintI>()) {
        ++_it;
      }
    }
    ~ConstraintIterator() {}

    ConstraintIterator& operator=(const ConstraintIterator& vi) {
      if (this != &vi) {
        _it = vi._it;
      }
      return *this;
    }
    bool operator==(const ConstraintIterator& vi) const { return _it == vi._it; }
    bool operator!=(const ConstraintIterator& vi) const { return _it != vi._it; }
    ConstraintIterator& operator++() {
      do {
        ++_it;
      } while (_it != _model->end() && !(*_it)->isa<ConstraintI>());
      return *this;
    }

    reference operator*() const { return *(*_it)->cast<ConstraintI>(); }
    pointer operator->() const { return (*_it)->cast<ConstraintI>(); }
  };

  /// Visitor for model items
  class ItemVisitor {
  public:
    /// Visit variable declaration
    void vVarDeclI(VarDeclI*) {}
    /// Visit assign item
    void vAssignI(AssignI*) {}
    /// Visit constraint item
    void vConstraintI(ConstraintI*) {}
    /// Visit solve item
    void vSolveI(SolveI*) {}
    /// Visit output item
    void vOutputI(OutputI*) {}
    /// Visit function item
    void vFunctionI(FunctionI*) {}
  };

  /// Iterator over items in a model and all its included models
  template<class I>
  class ItemIter {
  protected:
    I& iter;
  public:
    ItemIter(I& iter0) : iter(iter0) {}
    void run(Model* m) {
      UNORDERED_NAMESPACE::unordered_set<Model*> seen;
      std::vector<Model*> models;
      models.push_back(m);
      seen.insert(m);
      while (!models.empty()) {
        Model* cm = models.back();
        models.pop_back();
        for (unsigned int i=0; i<cm->size(); i++) {
          if ((*cm)[i]->removed())
            continue;
          switch ((*cm)[i]->iid()) {
          case Item::II_INC:
            if (seen.find((*cm)[i]->cast<IncludeI>()->m()) == seen.end()) {
              models.push_back((*cm)[i]->cast<IncludeI>()->m());
              seen.insert((*cm)[i]->cast<IncludeI>()->m());
            }
            break;
          case Item::II_VD:
            iter.vVarDeclI((*cm)[i]->cast<VarDeclI>());
            break;
          case Item::II_ASN:
            iter.vAssignI((*cm)[i]->cast<AssignI>());
            break;
          case Item::II_CON:
            iter.vConstraintI((*cm)[i]->cast<ConstraintI>());
            break;
          case Item::II_SOL:
            iter.vSolveI((*cm)[i]->cast<SolveI>());
            break;
          case Item::II_OUT:
            iter.vOutputI((*cm)[i]->cast<OutputI>());
            break;
          case Item::II_FUN:
            iter.vFunctionI((*cm)[i]->cast<FunctionI>());
            break;
          }
        }
      }
    }
  };

  /// Run iterator \a i over all items of model \a m
  template<class I>
  void iterItems(I& i, Model* m) {
    ItemIter<I>(i).run(m);
  }

}

#endif
<commit_msg>Can't use typename here<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef __MINIZINC_MODEL_HH__
#define __MINIZINC_MODEL_HH__

#include <vector>
#include <iterator>

#include <minizinc/gc.hh>
#include <minizinc/ast.hh>

namespace MiniZinc {

  class VarDeclIterator;
  class ConstraintIterator;

  /// A MiniZinc model
  class Model {
    friend class GC;
  protected:
    /// Previous model in root set list
    Model* _roots_prev;
    /// Next model in root set list
    Model* _roots_next;

    /// Type of map from identifiers to function declarations
    typedef ASTStringMap<std::vector<FunctionI*> >::t FnMap;
    /// Map from identifiers to function declarations
    FnMap fnmap;

    /// Filename of the model
    ASTString _filename;
    /// Path of the model
    ASTString _filepath;
    /// Parent model if model was included
    Model* _parent;
    /// Items in the model
    std::vector<Item*> _items;
    /// Pointer to the solve item
    SolveI* _solveItem;
    /// Pointer to the output item
    OutputI* _outputItem;
  public:

    /// Construct empty model
    Model(void);
    /// Destructor
    ~Model(void);

    /// Add \a i to the model
    void addItem(Item* i) {
      _items.push_back(i);
      if (i->isa<SolveI>()) {
        _solveItem = i->cast<SolveI>();
      } else if (i->isa<OutputI>()) {
        _outputItem = i->cast<OutputI>();
      }
    }

    /// Get parent model
    Model* parent(void) const { return _parent; }
    /// Set parent model to \a p
    void setParent(Model* p) { assert(_parent==NULL); _parent = p; }

    /// Get file name
    ASTString filename(void) const { return _filename; }
    /// Get file path
    ASTString filepath(void) const { return _filepath; }
    /// Set file name
    void setFilename(const std::string& f) {
      assert(_filename.size()==0);
      _filename = ASTString(f);
    }
    /// Set file path
    void setFilepath(const std::string& f) {
      assert(_filepath.size()==0);
      _filepath = ASTString(f);
    }

    /// Register a builtin function item
    void registerFn(FunctionI* fi);
    /// Sort functions by type
    void sortFn(void);
    /// Return function declaration for \a id matching \a args
    FunctionI* matchFn(const ASTString& id,
                       const std::vector<Expression*>& args) const;
    /// Return function declaration for \a id matching types \a t
    FunctionI* matchFn(const ASTString& id, const std::vector<Type>& t);
    /// Return function declaration matching call \a c
    FunctionI* matchFn(Call* c) const;

    /// Return item \a i
    Item*& operator[] (int i);
    /// Return item \a i
    const Item* operator[] (int i) const;
    /// Return number of items
    unsigned int size(void) const;

    typedef std::vector<Item*>::iterator iterator;
    typedef std::vector<Item*>::const_iterator const_iterator;

    /// Iterator for beginning of items
    iterator begin(void);
    /// Iterator for beginning of items
    const_iterator begin(void) const;
    /// Iterator for end of items
    iterator end(void);
    /// Iterator for end of items
    const_iterator end(void) const;

    ConstraintIterator begin_constraints(void);
    ConstraintIterator end_constraints(void);
    VarDeclIterator begin_vardecls(void);
    VarDeclIterator end_vardecls(void);

    SolveI* solveItem(void);

    OutputI* outputItem(void);

    /// Remove all items marked as removed
    void compact(void);
  };

  class VarDeclIterator {
    Model* _model;
    Model::iterator _it;
  public:
    typedef Model::iterator::difference_type difference_type;
    typedef Model::iterator::value_type value_type;
    typedef VarDeclI& reference;
    typedef VarDeclI* pointer;
    typedef std::forward_iterator_tag iterator_category;

    VarDeclIterator() {}
    VarDeclIterator(const VarDeclIterator& vi) : _it(vi._it) {}
    VarDeclIterator(Model* model, const Model::iterator& it) : _model(model), _it(it) {
      while (_it != _model->end() && !(*_it)->isa<VarDeclI>()) {
        ++_it;
      }
    }
    ~VarDeclIterator() {}

    VarDeclIterator& operator=(const VarDeclIterator& vi) {
      if (this != &vi) {
        _it = vi._it;
      }
      return *this;
    }
    bool operator==(const VarDeclIterator& vi) const { return _it == vi._it; }
    bool operator!=(const VarDeclIterator& vi) const { return _it != vi._it; }
    VarDeclIterator& operator++() {
      do {
        ++_it;
      } while (_it != _model->end() && !(*_it)->isa<VarDeclI>());
      return *this;
    }

    reference operator*() const { return *(*_it)->cast<VarDeclI>(); }
    pointer operator->() const { return (*_it)->cast<VarDeclI>(); }
  };

  class ConstraintIterator {
    Model* _model;
    Model::iterator _it;
  public:
    typedef Model::iterator::difference_type difference_type;
    typedef Model::iterator::value_type value_type;
    typedef ConstraintI& reference;
    typedef ConstraintI* pointer;
    typedef std::forward_iterator_tag iterator_category;

    ConstraintIterator() {}
    ConstraintIterator(const ConstraintIterator& vi) : _it(vi._it) {}
    ConstraintIterator(Model* model, const Model::iterator& it) : _model(model), _it(it) {
      while (_it != _model->end() && !(*_it)->isa<ConstraintI>()) {
        ++_it;
      }
    }
    ~ConstraintIterator() {}

    ConstraintIterator& operator=(const ConstraintIterator& vi) {
      if (this != &vi) {
        _it = vi._it;
      }
      return *this;
    }
    bool operator==(const ConstraintIterator& vi) const { return _it == vi._it; }
    bool operator!=(const ConstraintIterator& vi) const { return _it != vi._it; }
    ConstraintIterator& operator++() {
      do {
        ++_it;
      } while (_it != _model->end() && !(*_it)->isa<ConstraintI>());
      return *this;
    }

    reference operator*() const { return *(*_it)->cast<ConstraintI>(); }
    pointer operator->() const { return (*_it)->cast<ConstraintI>(); }
  };

  /// Visitor for model items
  class ItemVisitor {
  public:
    /// Visit variable declaration
    void vVarDeclI(VarDeclI*) {}
    /// Visit assign item
    void vAssignI(AssignI*) {}
    /// Visit constraint item
    void vConstraintI(ConstraintI*) {}
    /// Visit solve item
    void vSolveI(SolveI*) {}
    /// Visit output item
    void vOutputI(OutputI*) {}
    /// Visit function item
    void vFunctionI(FunctionI*) {}
  };

  /// Iterator over items in a model and all its included models
  template<class I>
  class ItemIter {
  protected:
    I& iter;
  public:
    ItemIter(I& iter0) : iter(iter0) {}
    void run(Model* m) {
      UNORDERED_NAMESPACE::unordered_set<Model*> seen;
      std::vector<Model*> models;
      models.push_back(m);
      seen.insert(m);
      while (!models.empty()) {
        Model* cm = models.back();
        models.pop_back();
        for (unsigned int i=0; i<cm->size(); i++) {
          if ((*cm)[i]->removed())
            continue;
          switch ((*cm)[i]->iid()) {
          case Item::II_INC:
            if (seen.find((*cm)[i]->cast<IncludeI>()->m()) == seen.end()) {
              models.push_back((*cm)[i]->cast<IncludeI>()->m());
              seen.insert((*cm)[i]->cast<IncludeI>()->m());
            }
            break;
          case Item::II_VD:
            iter.vVarDeclI((*cm)[i]->cast<VarDeclI>());
            break;
          case Item::II_ASN:
            iter.vAssignI((*cm)[i]->cast<AssignI>());
            break;
          case Item::II_CON:
            iter.vConstraintI((*cm)[i]->cast<ConstraintI>());
            break;
          case Item::II_SOL:
            iter.vSolveI((*cm)[i]->cast<SolveI>());
            break;
          case Item::II_OUT:
            iter.vOutputI((*cm)[i]->cast<OutputI>());
            break;
          case Item::II_FUN:
            iter.vFunctionI((*cm)[i]->cast<FunctionI>());
            break;
          }
        }
      }
    }
  };

  /// Run iterator \a i over all items of model \a m
  template<class I>
  void iterItems(I& i, Model* m) {
    ItemIter<I>(i).run(m);
  }

}

#endif
<|endoftext|>


<commit_before>#pragma once

#ifndef RXQT_RUN_LOOP_HPP

#include <QSignalMapper>
#include <QThread>
#include <QTimer>
#include <rxcpp/rx.hpp>

namespace rxqt {

class run_loop : public QObject {
public:
    run_loop(QObject* parent = Q_NULLPTR)
        : QObject(parent)
        , threadId(QThread::currentThreadId())
    {
        timer = new QTimer(this);
        mapper = new QSignalMapper(this);
        // Give the RxCpp run loop a a function to let us schedule a wakeup in order to dispatch run loop events
        rxcpp_run_loop.set_notify_earlier_wakeup([this](auto const& when) { this->on_earlier_wakeup(this->ms_until(when).count()); });
        timer->setSingleShot(true);
        timer->setTimerType(Qt::PreciseTimer);
        // When the timer expires, we'll flush the run loop
        timer->connect(timer, &QTimer::timeout, this, &run_loop::on_event_scheduled);
        mapper->connect(mapper, static_cast<void (QSignalMapper::*)(int)>(&QSignalMapper::mapped), this, &run_loop::on_earlier_wakeup);
    }

    rxcpp::schedulers::scheduler get_scheduler() const
    {
        return rxcpp_run_loop.get_scheduler();
    }

    auto observe_on_run_loop() const
    {
        return rxcpp::observe_on_run_loop(rxcpp_run_loop);
    }

    bool empty() const
    {
        return rxcpp_run_loop.empty();
    }

private:
    void on_earlier_wakeup(int msec)
    {
        // Tell the timer to wake-up at `when` if its not already waking up earlier
        if (threadId == QThread::currentThreadId()) {
            const int remainingTime = timer->remainingTime();
            if (remainingTime < 0 || msec < remainingTime) {
                timer->start(msec);
            }
        } else {
            mapper->setMapping(this, msec);
            mapper->map(this);
            mapper->removeMappings(this);
        }
    }

    // Flush the RxCpp run loop
    void on_event_scheduled()
    {
        // Dispatch outstanding RxCpp events
        while (!rxcpp_run_loop.empty() && rxcpp_run_loop.peek().when < rxcpp_run_loop.now()) {
            rxcpp_run_loop.dispatch();
        }
        // If there are outstanding events, set the timer to wakeup for the first one
        if (!rxcpp_run_loop.empty()) {
            const auto time_till_next_event = ms_until(rxcpp_run_loop.peek().when);
            timer->start(static_cast<int>(time_till_next_event.count()));
        }
    }

    // Calculate milliseconds from now until `when`
    std::chrono::milliseconds ms_until(rxcpp::schedulers::run_loop::clock_type::time_point const& when) const
    {
        return (std::max)(ceil<std::chrono::milliseconds>(when - rxcpp_run_loop.now()), std::chrono::milliseconds::zero());
    }

    // Round the specified duration to the smallest number of `To` ticks that's not less than `duration`
    template <class To, class Rep, class Period>
    static inline To ceil(const std::chrono::duration<Rep, Period>& duration)
    {
        const auto as_To = std::chrono::duration_cast<To>(duration);
        return (as_To < duration) ? (as_To + To { 1 }) : as_To;
    }

    rxcpp::schedulers::run_loop rxcpp_run_loop;
    QTimer* timer;
    Qt::HANDLE threadId;
    QSignalMapper* mapper;
};

} // namespace rxqt

#endif // RXQT_RUN_LOOP_HPP
<commit_msg>Add explicit keyword<commit_after>#pragma once

#ifndef RXQT_RUN_LOOP_HPP

#include <QSignalMapper>
#include <QThread>
#include <QTimer>
#include <rxcpp/rx.hpp>

namespace rxqt {

class run_loop : public QObject {
public:
    explicit run_loop(QObject* parent = Q_NULLPTR)
        : QObject(parent)
        , threadId(QThread::currentThreadId())
    {
        timer = new QTimer(this);
        mapper = new QSignalMapper(this);
        // Give the RxCpp run loop a a function to let us schedule a wakeup in order to dispatch run loop events
        rxcpp_run_loop.set_notify_earlier_wakeup([this](auto const& when) { this->on_earlier_wakeup(this->ms_until(when).count()); });
        timer->setSingleShot(true);
        timer->setTimerType(Qt::PreciseTimer);
        // When the timer expires, we'll flush the run loop
        timer->connect(timer, &QTimer::timeout, this, &run_loop::on_event_scheduled);
        mapper->connect(mapper, static_cast<void (QSignalMapper::*)(int)>(&QSignalMapper::mapped), this, &run_loop::on_earlier_wakeup);
    }

    rxcpp::schedulers::scheduler get_scheduler() const
    {
        return rxcpp_run_loop.get_scheduler();
    }

    auto observe_on_run_loop() const
    {
        return rxcpp::observe_on_run_loop(rxcpp_run_loop);
    }

    bool empty() const
    {
        return rxcpp_run_loop.empty();
    }

private:
    void on_earlier_wakeup(int msec)
    {
        // Tell the timer to wake-up at `when` if its not already waking up earlier
        if (threadId == QThread::currentThreadId()) {
            const int remainingTime = timer->remainingTime();
            if (remainingTime < 0 || msec < remainingTime) {
                timer->start(msec);
            }
        } else {
            mapper->setMapping(this, msec);
            mapper->map(this);
            mapper->removeMappings(this);
        }
    }

    // Flush the RxCpp run loop
    void on_event_scheduled()
    {
        // Dispatch outstanding RxCpp events
        while (!rxcpp_run_loop.empty() && rxcpp_run_loop.peek().when < rxcpp_run_loop.now()) {
            rxcpp_run_loop.dispatch();
        }
        // If there are outstanding events, set the timer to wakeup for the first one
        if (!rxcpp_run_loop.empty()) {
            const auto time_till_next_event = ms_until(rxcpp_run_loop.peek().when);
            timer->start(static_cast<int>(time_till_next_event.count()));
        }
    }

    // Calculate milliseconds from now until `when`
    std::chrono::milliseconds ms_until(rxcpp::schedulers::run_loop::clock_type::time_point const& when) const
    {
        return (std::max)(ceil<std::chrono::milliseconds>(when - rxcpp_run_loop.now()), std::chrono::milliseconds::zero());
    }

    // Round the specified duration to the smallest number of `To` ticks that's not less than `duration`
    template <class To, class Rep, class Period>
    static inline To ceil(const std::chrono::duration<Rep, Period>& duration)
    {
        const auto as_To = std::chrono::duration_cast<To>(duration);
        return (as_To < duration) ? (as_To + To { 1 }) : as_To;
    }

    rxcpp::schedulers::run_loop rxcpp_run_loop;
    QTimer* timer;
    Qt::HANDLE threadId;
    QSignalMapper* mapper;
};

} // namespace rxqt

#endif // RXQT_RUN_LOOP_HPP
<|endoftext|>