text:
// Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan
// Licensed under the MIT License. See LICENSE for details.

#include <algorithm>
#include <iostream>
#include "network.hpp"

#if CRAB_IMPL_BOOST

#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/circular_buffer.hpp>

// This impl is currently outdated and contains some bugs
// TODO - trampoline counters, like in Windows impl
// TODO - SignalStop
// TODO - check TCPSocket state machine
// TODO - convert std::chrono time points into boost
// TODO - UDP

namespace crab {

CRAB_INLINE bool Address::parse(Address &address, const std::string &ip, uint16_t port) {
	boost::system::error_code ec;
	address.addr = boost::asio::ip::address::from_string(ip, ec);
	address.port = port;
	return !ec;
}

CRAB_INLINE std::string Address::get_address() const {
	boost::system::error_code ec;
	return addr.to_string(ec);
}

CRAB_INLINE uint16_t Address::get_port() const { return port; }

CRAB_INLINE bool Address::is_multicast() const { return addr.is_multicast(); }

struct RunLoopImpl {
	boost::asio::io_service io;
	// size_t pending_counter = 0; // TODO
	// size_t impl_counter    = 0; // TODO

	steady_clock::time_point now = steady_clock::now();
};

CRAB_INLINE RunLoop::RunLoop() : impl(new RunLoopImpl()) {
	if (CurrentLoop::instance)
		throw std::runtime_error("RunLoop::RunLoop Only single RunLoop per thread is allowed");
	CurrentLoop::instance = this;
}

CRAB_INLINE RunLoop::~RunLoop() { CurrentLoop::instance = this; }

CRAB_INLINE void RunLoop::run() {
	auto &io = impl->io;
	io.reset();
	impl->now = steady_clock::now();
	while (!io.stopped()) {
		// Nothing triggered and no timers here
		if (idle_handlers.empty()) {
			io.run_one();  // Just waiting
		} else {
			if (io.poll() == 0 && !idle_handlers.empty()) {
				// Nothing triggered during poll, time for idle handlers to run
				Idle &idle = idle_handlers.front();
				// Rotate round-robin
				idle.idle_node.unlink();
				idle_handlers.push_back(idle);
				idle.a_handler();
			}
		}
		impl->now = steady_clock::now();
		// Runloop optimizes # of calls to now() because those can be slow
	}
}

CRAB_INLINE void RunLoop::cancel() { impl->io.stop(); }

CRAB_INLINE steady_clock::time_point RunLoop::now() { return impl->now; }

struct WatcherImpl {
	explicit WatcherImpl(Watcher *owner) : owner(owner) {}
	Watcher *owner;
	std::atomic<size_t> pending_calls;

	void close() {
		if (pending_calls != 0) {
			owner->impl.release();
			owner = nullptr;
		}
	}
	void handle_event() {
		auto after = --pending_calls;
		if (owner)
			return owner->a_handler.handler();
		if (after == 0)
			delete this;
	}
	void post(RunLoop *loop) {
		if (++pending_calls == 1)
			loop->get_impl()->io.post([&]() { handle_event(); });
	}
};

CRAB_INLINE Watcher::Watcher(Handler &&a_handler) : loop(RunLoop::current()), a_handler(std::move(a_handler)) {
	impl.reset(new WatcherImpl(this));  // Cannot postpone this to call() because we need mutex
}

CRAB_INLINE Watcher::~Watcher() { cancel(); }

CRAB_INLINE void Watcher::call() { impl->post(loop); }

CRAB_INLINE void Watcher::cancel() {
	impl->close();
	if (!impl)
		impl.reset(new WatcherImpl(this));
}

struct TimerImpl {
	explicit TimerImpl(Timer *owner) : owner(owner), timer(RunLoop::current()->get_impl()->io) {}
	Timer *owner;
	bool pending_wait = false;
	boost::asio::deadline_timer timer;

	void close() {
		if (pending_wait) {
			owner->impl.release();
			owner = nullptr;
			boost::system::error_code ec;
			timer.cancel(ec);  // Prevent exceptions
		}
	}
	void handle_timeout(const boost::system::error_code &e) {
		pending_wait = false;
		if (!owner) {
			delete this;
		}
		if (!e) {
			owner->a_handler();
			return;
		}
		if (e != boost::asio::error::operation_aborted) {
		}
	}
	void start_timer(double after_seconds) {
		// assert(pending_wait == false);
		pending_wait = true;
		timer.expires_from_now(boost::posix_time::milliseconds(
		    static_cast<int>(after_seconds * 1000)));  // int because we do not know exact type
		timer.async_wait([&](boost::system::error_code e) { handle_timeout(e); });
	}
};

CRAB_INLINE Timer::Timer(Handler &&cb) : a_handler(std::move(cb)) {}

CRAB_INLINE Timer::~Timer() { cancel(); }

CRAB_INLINE void Timer::cancel() {
	if (impl)
		impl->close();
}

CRAB_INLINE bool Timer::is_set() const { return impl && impl->pending_wait; }

CRAB_INLINE void Timer::once(double after_seconds) {
	cancel();
	if (!impl)
		impl.reset(new TimerImpl(this));
	impl->start_timer(after_seconds);
}

CRAB_INLINE void Timer::once(steady_clock::duration delay) {
	throw std::logic_error("TODO - implement");  // How to convert std::chrono to boost?
}

CRAB_INLINE void Timer::once_at(steady_clock::time_point time_point) {
	throw std::logic_error("TODO - implement");  // How to convert std::chrono to boost?
}

CRAB_INLINE bool SignalStop::running_under_debugger() { return false; }

CRAB_INLINE SignalStop::SignalStop(Handler &&cb) : a_handler(std::move(cb)) {}

CRAB_INLINE SignalStop::~SignalStop() = default;

struct TCPSocketImpl {
	explicit TCPSocketImpl(TCPSocket *owner) : owner(owner), socket(RunLoop::current()->get_impl()->io) {}
	TCPSocket *owner;
	bool connected = false;  // TODO - simplify state machine

	boost::asio::ip::tcp::socket socket;
	Buffer incoming_buffer{8192};
	Buffer outgoing_buffer{8192};
	bool pending_connect = false;
	bool pending_read    = false;
	bool pending_write   = false;
	bool asked_shutdown  = false;

	void close(bool called_from_run_loop) {
		boost::system::error_code ec;
		socket.close(ec);  // Prevent exceptions
		connected       = false;
		asked_shutdown  = false;
		pending_connect = false;
		pending_read    = false;
		pending_write   = false;
		incoming_buffer.clear();
		outgoing_buffer.clear();
		TCPSocket *was_owner = owner;
		if (pending_write || pending_read || pending_connect) {
			owner->impl.release();
			owner = nullptr;
		}
		if (was_owner && called_from_run_loop)
			was_owner->rwd_handler.handler();
	}
	void write_shutdown() {
		boost::system::error_code ignored_ec;
		socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ignored_ec);
	}

	void start_connect(const Address &address) {
		pending_connect = true;
		boost::asio::ip::tcp::endpoint endpoint(address.get_addr(), address.get_port());
		socket.async_connect(endpoint, [&](boost::system::error_code e) { handle_connect(e); });
	}
	void handle_connect(const boost::system::error_code &e) {
		pending_connect = false;
		if (!e) {
			connected = true;
			start_read();
			start_write();
			if (owner)
				owner->rwd_handler.handler();
			return;
		}
		if (e != boost::asio::error::operation_aborted) {
			close(true);
		}
	}
	void start_read() {
		if (incoming_buffer.full() || pending_read || !connected || !owner)
			return;
		pending_read = true;
		boost::array<boost::asio::mutable_buffer, 2> bufs{
		    boost::asio::buffer(incoming_buffer.write_ptr(), incoming_buffer.write_count()),
		    boost::asio::buffer(incoming_buffer.write_ptr2(), incoming_buffer.write_count2())};
		socket.async_read_some(bufs, [&](boost::system::error_code e, std::size_t b) { handle_read(e, b); });
	}

	void handle_read(const boost::system::error_code &e, std::size_t bytes_transferred) {
		pending_read = false;
		if (!e) {
			incoming_buffer.did_write(bytes_transferred);
			start_read();
			if (owner)
				owner->rwd_handler.handler();
			return;
		}
		if (e != boost::asio::error::operation_aborted) {
			close(true);
		}
	}

	void start_write() {
		if (pending_write || !connected || !owner)
			return;
		if (outgoing_buffer.empty()) {
			if (asked_shutdown)
				write_shutdown();
			return;
		}
		pending_write = true;
		boost::array<boost::asio::const_buffer, 2> bufs{
		    boost::asio::buffer(outgoing_buffer.read_ptr(), outgoing_buffer.read_count()),
		    boost::asio::buffer(outgoing_buffer.read_ptr2(), outgoing_buffer.read_count2())};
		socket.async_write_some(bufs, [&](boost::system::error_code e, std::size_t b) { handle_write(e, b); });
	}

	void handle_write(const boost::system::error_code &e, std::size_t bytes_transferred) {
		pending_write = false;
		if (!e) {
			outgoing_buffer.did_read(bytes_transferred);
			start_write();
			if (owner)
				owner->rwd_handler.handler();
			return;
		}
		if (e != boost::asio::error::operation_aborted) {
			close(true);
		}
	}
};

CRAB_INLINE TCPSocket::TCPSocket(Handler &&cb) : rwd_handler(std::move(cb)) {}

CRAB_INLINE TCPSocket::~TCPSocket() { close(); }

CRAB_INLINE void TCPSocket::close() {
	if (impl)
		impl->close(false);
}

CRAB_INLINE bool TCPSocket::is_open() const { return impl && (impl->connected || impl->pending_connect); }

CRAB_INLINE bool TCPSocket::connect(const Address &address) {
	close();
	if (!impl)
		impl.reset(new TCPSocketImpl(this));
	impl->start_connect(address);
	return true;
}

CRAB_INLINE size_t TCPSocket::read_some(uint8_t *data, size_t size) {
	if (!impl)
		return 0;
	size_t rc = impl->incoming_buffer.read_some(data, size);
	impl->start_read();
	return rc;
}

CRAB_INLINE size_t TCPSocket::write_some(const uint8_t *data, size_t size) {
	if (!impl || impl->asked_shutdown)
		return 0;
	size_t wc = impl->outgoing_buffer.write_some(data, size);
	impl->start_write();
	return wc;
}

CRAB_INLINE bool TCPSocket::can_write() const { return impl && !impl->outgoing_buffer.full(); }

// CRAB_INLINE bool UDPTransmitter::can_write() const { return true; } // TODO

CRAB_INLINE void TCPSocket::write_shutdown() {
	if (impl->asked_shutdown)
		return;
	impl->asked_shutdown = true;
	if (impl->connected && !impl->pending_write)
		impl->write_shutdown();
}

struct TCPAcceptorImpl {
	TCPAcceptor *owner;
	explicit TCPAcceptorImpl(TCPAcceptor *owner)
	    : owner(owner)
	    , acceptor(RunLoop::current()->get_impl()->io)
	    , socket_being_accepted(RunLoop::current()->get_impl()->io) {}
	boost::asio::ip::tcp::acceptor acceptor;
	boost::asio::ip::tcp::socket socket_being_accepted;
	bool socket_ready   = false;
	bool pending_accept = false;

	void close() {
		boost::system::error_code ignored_ec;
		acceptor.close(ignored_ec);
		if (pending_accept) {
			owner->impl.release();
			owner = nullptr;
		}
	}
	void start_accept() {
		pending_accept = true;
		acceptor.async_accept(socket_being_accepted, [&](boost::system::error_code ec) { handle_accept(ec); });
	}
	void handle_accept(const boost::system::error_code &e) {
		pending_accept = false;
		if (!e) {
			socket_ready = true;
			if (owner)
				owner->a_handler.handler();
		}
		if (e != boost::asio::error::operation_aborted) {
			// some nasty problem with socket, say so to the client
		}
	}
};

CRAB_INLINE TCPAcceptor::TCPAcceptor(const Address &address, Handler &&cb)
    : a_handler(std::move(cb)), impl(new TCPAcceptorImpl(this)) {
	boost::asio::ip::tcp::resolver resolver(RunLoop::current()->get_impl()->io);
	boost::asio::ip::tcp::endpoint endpoint(address.get_addr(), address.get_port());
	impl->acceptor.open(endpoint.protocol());
	impl->acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
	impl->acceptor.bind(endpoint);
	impl->acceptor.listen();

	impl->start_accept();
}

CRAB_INLINE bool TCPAcceptor::can_accept() { return impl->socket_ready; }

CRAB_INLINE void TCPSocket::accept(TCPAcceptor &acceptor, Address *accepted_addr) {
	if (!acceptor.impl->socket_ready)
		throw std::logic_error("TCPAcceptor::accept error, forgot if(can_accept())?");
	acceptor.impl->socket_ready = false;
	close();
	if (!impl)
		impl.reset(new TCPSocketImpl(this));
	std::swap(impl->socket, acceptor.impl->socket_being_accepted);

	impl->connected = true;
	if (accepted_addr) {
		//        *accepted_addr = Address(impl->socket.remote_endpoint().address().to_string());
	}
	impl->start_read();
	acceptor.impl->start_accept();
}

CRAB_INLINE TCPAcceptor::~TCPAcceptor() { impl->close(); }

/*class DNSResolver::Impl {
public:
    DNSResolver *owner;
    explicit Impl(DNSResolver *owner) : owner(owner), resolver(RunLoop::current()->get_impl()->io) {}
    boost::asio::ip::tcp::resolver resolver;
    bool pending_resolve;

    void close() {
        resolver.cancel();
        DNSResolver *was_owner = owner;
        if (pending_resolve) {
            owner           = nullptr;
            was_owner->impl = std::make_shared<Impl>(was_owner);  // We do not reuse LA Sockets
        }
    }
    void handle_resolve(const boost::system::error_code &err,
        boost::asio::ip::tcp::resolver::iterator endpoint_iterator) {
        pending_resolve = false;
        if (!err) {
            if (owner) {
                std::vector<std::string> names;

                for (; endpoint_iterator != boost::asio::ip::tcp::resolver::iterator(); ++endpoint_iterator) {
                    names.push_back(endpoint_iterator->endpoint().address().to_string());
                }
                owner->dns_handler(names);
            }
        } else {
            std::cout << "Error: " << err.message() << "\n";
        }
    }
};

DNSResolver::DNSResolver(DNS_handler handler) : dns_handler(handler), impl(std::make_shared<Impl>(this)) {}

DNSResolver::~DNSResolver() { impl->close(); }

void DNSResolver::resolve(const std::string &host_name, bool ipv4, bool ipv6) {
    impl->close();
    boost::asio::ip::tcp::resolver::query query(host_name, "http");
    impl->pending_resolve = true;
    impl->resolver.async_resolve(query,
        boost::bind(
            &Impl::handle_resolve, impl, boost::asio::placeholders::error, boost::asio::placeholders::iterator));
}

void DNSResolver::cancel() { impl->close(); }

bdata DNSResolver::parse_ipaddress(const std::string &str) {
    if (str.empty())
        return bdata();
    try {
        boost::asio::ip::address address = boost::asio::ip::address::from_string(str);
        if (address.is_v4()) {
            auto bytes = address.to_v4().to_bytes();
            return bdata(bytes.begin(), bytes.end());
        }
        if (address.is_v6()) {
            auto bytes = address.to_v6().to_bytes();
            return bdata(bytes.begin(), bytes.end());
        }
    } catch (...) {
    }
    return bdata();
}
*/

CRAB_INLINE std::vector<Address> DNSResolver::sync_resolve(
    const std::string &host_name, uint16_t port, bool ipv4, bool ipv6) {
	boost::system::error_code ec;

	boost::asio::ip::tcp::resolver resolver(RunLoop::current()->get_impl()->io);
	auto service = std::to_string(port);

	boost::asio::ip::tcp::resolver::query query(host_name, service);
	boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query, ec);
	std::vector<Address> names;
	if (ec)
		return names;
	for (; endpoint_iterator != boost::asio::ip::tcp::resolver::iterator(); ++endpoint_iterator) {
		names.emplace_back(endpoint_iterator->endpoint().address(), endpoint_iterator->endpoint().port());
	}
	return names;
}

CRAB_INLINE UDPTransmitter::UDPTransmitter(const Address &address, Handler &&cb, const std::string &adapter)
    : w_handler(std::move(cb)) {
	throw std::runtime_error("UDPTransmitter not yet implemented on Windows");
}

CRAB_INLINE bool UDPTransmitter::write_datagram(const uint8_t *data, size_t count) { return 0; }

CRAB_INLINE UDPReceiver::UDPReceiver(const Address &address, Handler &&cb, const std::string &adapter)
    : r_handler(std::move(cb)) {
	throw std::runtime_error("UDPReceiver not yet implemented on Windows");
}

CRAB_INLINE optional<size_t> UDPReceiver::read_datagram(uint8_t *data, size_t count, Address *peer_addr) {
	return {};
}

}  // namespace crab

#endif

ext: hxx

max_stars_repo_name: hrissan/crablib

max_issues_repo_name: hrissan/crablib

max_forks_repo_name: hrissan/crablib


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2011 - 2012   MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_CORE_FUNCTIONS_COMMON_AGGREGATE_HPP_INCLUDED
#define NT2_CORE_FUNCTIONS_COMMON_AGGREGATE_HPP_INCLUDED

#include <nt2/core/functions/aggregate.hpp>
#include <nt2/sdk/parameters.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>

namespace nt2 { namespace ext
{
#define M0(z,n,t) (A##n)
#define M1(z,n,t) (unspecified_<A##n>)
#define M2(z,n,t) boost::cref(a##n)

#define M3(z,n,t)                                                             \
BOOST_DISPATCH_IMPLEMENT  ( aggregate_, tag::cpu_                   \
                          , BOOST_PP_REPEAT(n,M0,~)                           \
                          , BOOST_PP_REPEAT(n,M1,~)                           \
                          )                                                   \
{                                                                             \
  typedef typename  boost::proto::result_of::make_expr                        \
                    < nt2::tag::aggregate_, container::domain                 \
                    , BOOST_PP_ENUM_BINARY_PARAMS ( n                         \
                                                  , const A                   \
                                                  , & BOOST_PP_INTERCEPT)     \
                    >::type      result_type;                                 \
                                                                              \
  BOOST_FORCEINLINE result_type                                               \
  operator()(BOOST_PP_ENUM_BINARY_PARAMS(n,const A,& a) ) const               \
  {                                                                           \
    return boost::proto::make_expr<tag::aggregate_,container::domain>         \
                                  ( BOOST_PP_ENUM(n,M2,~) );                  \
  }                                                                           \
};                                                                            \
/**/

  BOOST_PP_REPEAT_FROM_TO(1,BOOST_DISPATCH_MAX_META_ARITY,M3,~)

#undef M0
#undef M1
#undef M2
#undef M3
} }

#endif

ext: hpp


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

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

namespace cctbx { namespace xray { namespace f_model_core_data { namespace boost_python {
  namespace {

    struct f_model_core_data_derivative_holder_wrappers
    {
      typedef f_model_core_data_derivative_holder<double> w_t;

      static void
      wrap()
      {
        using namespace boost::python;
        class_<w_t>("f_model_core_data_derivative_holder")//, no_init)
          .def("ksol",(double(w_t::*)())  &w_t::ksol )
          .def("ksol",(void (w_t::*)(double))  &w_t::ksol )

          .def("usol",(double(w_t::*)())  &w_t::usol )
          .def("usol",(void(w_t::*)(double))  &w_t::usol )

          .def("kpart",(double(w_t::*)()) &w_t::kpart )
          .def("kpart",(void(w_t::*)(double)) &w_t::kpart )

          .def("upart",(double(w_t::*)()) &w_t::upart )
          .def("upart",(void(w_t::*)(double)) &w_t::upart )

          .def("koverall", (double(w_t::*)()) &w_t::koverall )
          .def("koverall", (void(w_t::*)(double)) &w_t::koverall )

          .def("ustar", (scitbx::sym_mat3<double>(w_t::*)()) &w_t::ustar )
          .def("ustar", (void(w_t::*)(scitbx::sym_mat3<double>)) &w_t::ustar )

          .def("accumulate", &w_t::accumulate)
          ;
      }

    };

    struct f_model_core_data_wrappers
    {
      typedef f_model_core_data<double> w_t;

      static void
      wrap()
      {
        using namespace boost::python;

        class_<w_t>("f_model_core_data", no_init)
          .def(init<
               scitbx::af::const_ref< cctbx::miller::index<> > const&,  // 1 indices
               scitbx::af::const_ref< std::complex< double > > const&,  // 2 f_atmos
               scitbx::af::const_ref< std::complex< double > > const&,  // 3 f_mask
               cctbx::uctbx::unit_cell const&,                          // 4 unit cell
               double const&,                                           // 7 overall scale
               scitbx::sym_mat3< double > const&,                       // 8 u star
               double const&,                                           // 9 bs scale
               double const&,                                           // 0 bs u
               scitbx::af::const_ref< std::complex< double > > const&,  // 1 f_part
               double const&,                                           // 2 part scale
               double const&                                            // 3 part u
               >
               ((arg("hkl"),
                 arg("f_atoms"),
                 arg("f_mask"),
                 arg("unit_cell"),
                 arg("k_overall"),
                 arg("u_star"),
                 arg("k_sol"),
                 arg("u_sol"),
                 arg("f_part"),
                 arg("k_part"),
                 arg("u_part") )))

          .def(init<
               scitbx::af::const_ref< cctbx::miller::index<> > const&,  // 1 indices
               scitbx::af::const_ref< std::complex< double > > const&,  // 2 f_atmos
               scitbx::af::const_ref< std::complex< double > > const&,  // 3 f_mask
               cctbx::uctbx::unit_cell const&,                          // 4 unit cell
               double const&,                                           // 7 overall scale
               scitbx::sym_mat3< double > const&,                       // 8 u star
               double const&,                                           // 9 bs scale
               double const&,                                           // 0 bs b
               scitbx::af::const_ref< std::complex< double > > const&,  // 1 f_part
               double const&,                                           // 2 part scale
               double const&                                            // 3 part b
               >
               ((arg("hkl"),
                 arg("f_atoms"),
                 arg("f_mask"),
                 arg("d_star_sq"),
                 arg("k_overall"),
                 arg("u_star"),
                 arg("k_sol"),
                 arg("u_sol"),
                 arg("f_part"),
                 arg("k_part"),
                 arg("u_part") )))

          // derivatives using gradientflags
          .def("d_target_d_all",
               ( f_model_core_data_derivative_holder<double>(w_t::*)
                 (double const&,
                  double const&,
                  std::size_t const&,
                  scitbx::af::const_ref<bool> const& )
               ) &w_t::d_target_d_all)
          .def("d_target_d_all",
               ( f_model_core_data_derivative_holder<double>(w_t::*)
                 (scitbx::af::const_ref<double> const&,
                  scitbx::af::const_ref<double> const&,
                  scitbx::af::const_ref<bool> const&)
               ) &w_t::d_target_d_all)
          /*
          .def("d_target_d_all",
               ( f_model_core_data_derivative_holder<double>(w_t::*)
                 (scitbx::af::const_ref<std::complex<double> > const&,
                  scitbx::af::const_ref<bool> const&)
               ) &w_t::d_target_d_all)
          */
          .def("d_target_d_all",
               ( f_model_core_data_derivative_holder<double>(w_t::*)
                 (scitbx::af::const_ref<double> const&,
                  scitbx::af::const_ref<bool> const&)
                 ) &w_t::d_target_d_all)

          // updating variables
          .def("refresh", &w_t::refresh)
          .def("renew_fatoms", &w_t::renew_fatoms)
          .def("renew_fmask", &w_t::renew_fmask)
          .def("renew_fpart", &w_t::renew_fpart)
          .def("renew_overall_scale_parameters",
               &w_t::renew_overall_scale_parameters)
          .def("renew_bulk_solvent_scale_parameters",
               &w_t::renew_bulk_solvent_scale_parameters)
          .def("renew_partial_structure_scale_parameters",
               &w_t::renew_partial_structure_scale_parameters)
          // get individual scales and sf's
          .def("f_atoms", &w_t::f_atoms)
          .def("f_bulk", &w_t::f_bulk)
          .def("f_part", &w_t::f_part)
          .def("bulk_scale", &w_t::bulk_scale)
          .def("part_scale", &w_t::part_scale)
          .def("f_model", &w_t::get_f_model_core_data)
          .def("overall_scale", &w_t::overall_scale)
          .def("fu_star", &w_t::fu_star)
          .def("d_f_model_core_data_d_f_atoms", &w_t::d_f_model_core_data_d_f_atoms)

          .def("ustar", (scitbx::sym_mat3<double>(w_t::*)()) &w_t::ustar)
          .def("koverall",(double(w_t::*)()) &w_t::koverall)
          .def("ksol", (double(w_t::*)()) &w_t::ksol)
          .def("kpart",(double(w_t::*)()) &w_t::kpart)
          .def("usol", (double(w_t::*)()) &w_t::usol)
          .def("upart",(double(w_t::*)()) &w_t::upart)

          .def("ustar", (void(w_t::*)(scitbx::sym_mat3<double>)) &w_t::ustar)
          .def("koverall",(void(w_t::*)(double)) &w_t::koverall)
          .def("ksol", (void(w_t::*)(double)) &w_t::ksol)
          .def("kpart",(void(w_t::*)(double)) &w_t::kpart)
          .def("usol", (void(w_t::*)(double)) &w_t::usol)
          .def("upart",(void(w_t::*)(double)) &w_t::upart)

          .def("d_star_sq", &w_t::d_star_sq)
          // selection method
          .def("select", &w_t::select)
          ;
      }
    };

  }

}} // namespace cctbx::xray

  namespace boost_python {

    void wrap_f_model_core_data()
    {
      f_model_core_data::boost_python::f_model_core_data_wrappers::wrap();
      f_model_core_data::boost_python::f_model_core_data_derivative_holder_wrappers::wrap();
    }

  }

}}

ext: cpp


text:
#include <nano/secure/versioning.hpp>

#include <boost/endian/conversion.hpp>

#include <lmdb/libraries/liblmdb/lmdb.h>

nano::pending_info_v14::pending_info_v14 (nano::account const & source_a, nano::amount const & amount_a, nano::epoch epoch_a) :
    source (source_a),
    amount (amount_a),
    epoch (epoch_a)
{
}

bool nano::pending_info_v14::deserialize (nano::stream & stream_a)
{
	auto error (false);
	try
	{
		nano::read (stream_a, source.bytes);
		nano::read (stream_a, amount.bytes);
	}
	catch (std::runtime_error const &)
	{
		error = true;
	}

	return error;
}

size_t nano::pending_info_v14::db_size () const
{
	return sizeof (source) + sizeof (amount);
}

bool nano::pending_info_v14::operator== (nano::pending_info_v14 const & other_a) const
{
	return source == other_a.source && amount == other_a.amount && epoch == other_a.epoch;
}

nano::account_info_v14::account_info_v14 (nano::block_hash const & head_a, nano::block_hash const & rep_block_a, nano::block_hash const & open_block_a, nano::amount const & balance_a, uint64_t modified_a, uint64_t block_count_a, uint64_t confirmation_height_a, nano::epoch epoch_a) :
    head (head_a),
    rep_block (rep_block_a),
    open_block (open_block_a),
    balance (balance_a),
    modified (modified_a),
    block_count (block_count_a),
    confirmation_height (confirmation_height_a),
    epoch (epoch_a)
{
}

size_t nano::account_info_v14::db_size () const
{
	debug_assert (reinterpret_cast<const uint8_t *> (this) == reinterpret_cast<const uint8_t *> (&head));
	debug_assert (reinterpret_cast<const uint8_t *> (&head) + sizeof (head) == reinterpret_cast<const uint8_t *> (&rep_block));
	debug_assert (reinterpret_cast<const uint8_t *> (&rep_block) + sizeof (rep_block) == reinterpret_cast<const uint8_t *> (&open_block));
	debug_assert (reinterpret_cast<const uint8_t *> (&open_block) + sizeof (open_block) == reinterpret_cast<const uint8_t *> (&balance));
	debug_assert (reinterpret_cast<const uint8_t *> (&balance) + sizeof (balance) == reinterpret_cast<const uint8_t *> (&modified));
	debug_assert (reinterpret_cast<const uint8_t *> (&modified) + sizeof (modified) == reinterpret_cast<const uint8_t *> (&block_count));
	debug_assert (reinterpret_cast<const uint8_t *> (&block_count) + sizeof (block_count) == reinterpret_cast<const uint8_t *> (&confirmation_height));
	return sizeof (head) + sizeof (rep_block) + sizeof (open_block) + sizeof (balance) + sizeof (modified) + sizeof (block_count) + sizeof (confirmation_height);
}

nano::block_sideband_v14::block_sideband_v14 (nano::block_type type_a, nano::account const & account_a, nano::block_hash const & successor_a, nano::amount const & balance_a, uint64_t height_a, uint64_t timestamp_a) :
    type (type_a),
    successor (successor_a),
    account (account_a),
    balance (balance_a),
    height (height_a),
    timestamp (timestamp_a)
{
}

size_t nano::block_sideband_v14::size (nano::block_type type_a)
{
	size_t result (0);
	result += sizeof (successor);
	if (type_a != nano::block_type::state && type_a != nano::block_type::open)
	{
		result += sizeof (account);
	}
	if (type_a != nano::block_type::open)
	{
		result += sizeof (height);
	}
	if (type_a == nano::block_type::receive || type_a == nano::block_type::change || type_a == nano::block_type::open)
	{
		result += sizeof (balance);
	}
	result += sizeof (timestamp);
	return result;
}

void nano::block_sideband_v14::serialize (nano::stream & stream_a) const
{
	nano::write (stream_a, successor.bytes);
	if (type != nano::block_type::state && type != nano::block_type::open)
	{
		nano::write (stream_a, account.bytes);
	}
	if (type != nano::block_type::open)
	{
		nano::write (stream_a, boost::endian::native_to_big (height));
	}
	if (type == nano::block_type::receive || type == nano::block_type::change || type == nano::block_type::open)
	{
		nano::write (stream_a, balance.bytes);
	}
	nano::write (stream_a, boost::endian::native_to_big (timestamp));
}

bool nano::block_sideband_v14::deserialize (nano::stream & stream_a)
{
	bool result (false);
	try
	{
		nano::read (stream_a, successor.bytes);
		if (type != nano::block_type::state && type != nano::block_type::open)
		{
			nano::read (stream_a, account.bytes);
		}
		if (type != nano::block_type::open)
		{
			nano::read (stream_a, height);
			boost::endian::big_to_native_inplace (height);
		}
		else
		{
			height = 1;
		}
		if (type == nano::block_type::receive || type == nano::block_type::change || type == nano::block_type::open)
		{
			nano::read (stream_a, balance.bytes);
		}
		nano::read (stream_a, timestamp);
		boost::endian::big_to_native_inplace (timestamp);
	}
	catch (std::runtime_error &)
	{
		result = true;
	}

	return result;
}

nano::block_sideband_v18::block_sideband_v18 (nano::account const & account_a, nano::block_hash const & successor_a, nano::amount const & balance_a, uint64_t height_a, uint64_t timestamp_a, nano::block_details const & details_a) :
    successor (successor_a),
    account (account_a),
    balance (balance_a),
    height (height_a),
    timestamp (timestamp_a),
    details (details_a)
{
}

nano::block_sideband_v18::block_sideband_v18 (nano::account const & account_a, nano::block_hash const & successor_a, nano::amount const & balance_a, uint64_t height_a, uint64_t timestamp_a, nano::epoch epoch_a, bool is_send, bool is_receive, bool is_epoch) :
    successor (successor_a),
    account (account_a),
    balance (balance_a),
    height (height_a),
    timestamp (timestamp_a),
    details (epoch_a, is_send, is_receive, is_epoch)
{
}

size_t nano::block_sideband_v18::size (nano::block_type type_a)
{
	size_t result (0);
	result += sizeof (successor);
	if (type_a != nano::block_type::state && type_a != nano::block_type::open)
	{
		result += sizeof (account);
	}
	if (type_a != nano::block_type::open)
	{
		result += sizeof (height);
	}
	if (type_a == nano::block_type::receive || type_a == nano::block_type::change || type_a == nano::block_type::open)
	{
		result += sizeof (balance);
	}
	result += sizeof (timestamp);
	if (type_a == nano::block_type::state)
	{
		static_assert (sizeof (nano::epoch) == nano::block_details::size (), "block_details_v18 is larger than the epoch enum");
		result += nano::block_details::size ();
	}
	return result;
}

void nano::block_sideband_v18::serialize (nano::stream & stream_a, nano::block_type type_a) const
{
	nano::write (stream_a, successor.bytes);
	if (type_a != nano::block_type::state && type_a != nano::block_type::open)
	{
		nano::write (stream_a, account.bytes);
	}
	if (type_a != nano::block_type::open)
	{
		nano::write (stream_a, boost::endian::native_to_big (height));
	}
	if (type_a == nano::block_type::receive || type_a == nano::block_type::change || type_a == nano::block_type::open)
	{
		nano::write (stream_a, balance.bytes);
	}
	nano::write (stream_a, boost::endian::native_to_big (timestamp));
	if (type_a == nano::block_type::state)
	{
		details.serialize (stream_a);
	}
}

bool nano::block_sideband_v18::deserialize (nano::stream & stream_a, nano::block_type type_a)
{
	bool result (false);
	try
	{
		nano::read (stream_a, successor.bytes);
		if (type_a != nano::block_type::state && type_a != nano::block_type::open)
		{
			nano::read (stream_a, account.bytes);
		}
		if (type_a != nano::block_type::open)
		{
			nano::read (stream_a, height);
			boost::endian::big_to_native_inplace (height);
		}
		else
		{
			height = 1;
		}
		if (type_a == nano::block_type::receive || type_a == nano::block_type::change || type_a == nano::block_type::open)
		{
			nano::read (stream_a, balance.bytes);
		}
		nano::read (stream_a, timestamp);
		boost::endian::big_to_native_inplace (timestamp);
		if (type_a == nano::block_type::state)
		{
			result = details.deserialize (stream_a);
		}
	}
	catch (std::runtime_error &)
	{
		result = true;
	}

	return result;
}

max_stars_repo_name: marioortizmanero/nano-node

max_issues_repo_name: marioortizmanero/nano-node

max_forks_repo_name: marioortizmanero/nano-node


text: #include <boost/vmd/size.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#define CL_USE_DEPRECATED_OPENCL_1_1_APIS

#include "clew.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <boost/compute/system.hpp>
#include <boost/compute/interop/opencv/core.hpp>
#include <boost/compute/interop/opencv/highgui.hpp>
#include <boost/compute/utility/source.hpp>

#include <iostream>
#define FRAME_HEIGHT 720
#define FRAME_WIDTH 1280
#define FRAME_INTERVAL (1000/30)

namespace compute = boost::compute;
using namespace cv;

compute::image2d process_image(cv::Mat input, const char *source, compute::context &context, compute::command_queue &queue)
{

    // convert image to BGRA (OpenCL requires 16-byte aligned data)
    cv::cvtColor(input, input, CV_BGR2BGRA);

    // transfer image to gpu
    compute::image2d input_image =
        compute::opencv_create_image2d_with_mat(
            	input, compute::image2d::read_write, queue
        		);

    // create output image
    compute::image2d output_image(
        	context,
        	input_image.width(),
        	input_image.height(),
        	input_image.format(),
        	compute::image2d::write_only
    		);

    compute::program flip_program =
        compute::program::create_with_source(source, context);
    flip_program.build();

    // create flip kernel and set arguments
    compute::kernel flip_kernel(flip_program, "flip_kernel");
    flip_kernel.set_arg(0, input_image);
    flip_kernel.set_arg(1, output_image);

    // run flip kernel
    size_t origin[2] = { 0, 0 };
    size_t region[2] = { input_image.width(), input_image.height() };
    queue.enqueue_nd_range_kernel(flip_kernel, 2, origin, region, 0);

    return output_image;
}

int main(int argc, const char *argv[])
{
    bool clpresent = 0 == clewInit();
    if( !clpresent ) {
		std::cerr << "opencl library not found" << std::endl;
		return -1;
    }

    // check command line
    if(argc < 2){
        std::cerr << "usage: " << argv[0] << " FILENAME" << std::endl;
        return -1;
    }

    // read image with opencv
    cv::Mat cv_image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
    if(!cv_image.data){
        std::cerr << "failed to load image" << std::endl;
        return -1;
    }
    // get default device and setup context
    compute::device gpu = compute::system::default_device();
    std::cout << "OpenCL Device: " << gpu.name() << std::endl;
    std::cout << "OpenCL Profile: " << gpu.profile() << std::endl;
    std::cout << "OpenCL Version: " << gpu.version() << std::endl;
    compute::context context(gpu);
    compute::command_queue queue(context, gpu);

    // create flip program
    const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(
        	__kernel void flip_kernel(__read_only image2d_t input,
                __write_only image2d_t output)
        	{
            const sampler_t sampler = CLK_ADDRESS_NONE | CLK_FILTER_NEAREST;
            int height = get_image_height(input);
            int2 input_coord = { get_global_id(0), get_global_id(1) };
            int2 output_coord = { input_coord.x, height - input_coord.y - 1 };
            float4 value = read_imagef(input, sampler, input_coord);
            write_imagef(output, output_coord, value);
        	}
    		);

    VideoCapture cap(0); // Grab the camera
    if (!cap.isOpened()) {
		std::cerr << "OpenCV Failed to open camera";
        exit(1);
    }

	while(1) {
    	Mat frame, send;
    	cap >> frame;
    	if(frame.size().width==0)continue;//simple integrity check; skip erroneous data...
    	resize(frame, send, Size(FRAME_WIDTH, FRAME_HEIGHT), 0, 0, INTER_LINEAR);

		auto output_image = process_image(send, source, context, queue);

    	// show host image
    	//cv::imshow("opencv image", cv_image);

    	// show gpu image
    	compute::opencv_imshow("filtered image", output_image, queue);

    	// wait and return
		cv::waitKey(FRAME_INTERVAL);
	}

	return 0;
}


text:
/**
*    Copyright (C) 2010 10gen Inc.
*
*    This program is free software: you can redistribute it and/or  modify
*    it under the terms of the GNU Affero General Public License, version 3,
*    as published by the Free Software Foundation.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU Affero General Public License for more details.
*
*    You should have received a copy of the GNU Affero General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "mongo/db/commands/authentication_commands.h"

#include <boost/scoped_ptr.hpp>
#include <string>
#include <vector>

#include "mongo/base/status.h"
#include "mongo/client/sasl_client_authenticate.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_manager_global.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/mongo_authentication_session.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/client_basic.h"
#include "mongo/db/commands.h"
#include "mongo/db/jsobj.h"
#include "mongo/platform/random.h"
#include "mongo/util/concurrency/mutex.h"
#include "mongo/util/md5.hpp"
#include "mongo/util/net/ssl_manager.h"

namespace mongo {

    static bool _areNonceAuthenticateCommandsEnabled = true;
    static const char _nonceAuthenticateCommandsDisabledMessage[] =
        "Challenge-response authentication using getnonce and authenticate commands is disabled.";

    void CmdAuthenticate::disableCommand() { _areNonceAuthenticateCommandsEnabled = false; }

    /* authentication

       system.users contains
         { user : <username>, pwd : <pwd_digest>, ... }

       getnonce sends nonce to client

       client then sends { authenticate:1, nonce64:<nonce_str>, user:<username>, key:<key> }

       where <key> is md5(<nonce_str><username><pwd_digest_str>) as a string
    */

    class CmdGetNonce : public Command {
    public:
        CmdGetNonce() :
            Command("getnonce"),
            _randMutex("getnonce"),
            _random(SecureRandom::create()) {
        }

        virtual bool logTheOp() { return false; }
        virtual bool slaveOk() const {
            return true;
        }
        void help(stringstream& h) const { h << "internal"; }
        virtual LockType locktype() const { return NONE; }
        virtual void addRequiredPrivileges(const std::string& dbname,
                                           const BSONObj& cmdObj,
                                           std::vector<Privilege>* out) {} // No auth required
        bool run(const string&, BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
            nonce64 n = getNextNonce();
            stringstream ss;
            ss << hex << n;
            result.append("nonce", ss.str() );
            ClientBasic::getCurrent()->resetAuthenticationSession(
                    new MongoAuthenticationSession(n));
            return true;
        }

    private:
        nonce64 getNextNonce() {
            SimpleMutex::scoped_lock lk(_randMutex);
            return _random->nextInt64();
        }

        SimpleMutex _randMutex;  // Synchronizes accesses to _random.
        boost::scoped_ptr<SecureRandom> _random;
    } cmdGetNonce;

    bool CmdAuthenticate::run(const string& dbname , BSONObj& cmdObj, int, string& errmsg, BSONObjBuilder& result, bool fromRepl) {
        log() << " authenticate db: " << dbname << " " << cmdObj << endl;

        std::string mechanism = cmdObj.getStringField("mechanism");
        if (mechanism.empty() || mechanism == "MONGODB-CR") {
            return authenticateCR(dbname, cmdObj, errmsg, result);
        }
#ifdef MONGO_SSL
        if (mechanism == "MONGODB-X509") {
            return authenticateX509(dbname, cmdObj, errmsg, result);
        }
#endif
        errmsg = "Unsupported mechanism: " + mechanism;
        result.append(saslCommandCodeFieldName, ErrorCodes::BadValue);
        return false;
    }

    bool CmdAuthenticate::authenticateCR(const string& dbname,
                                         BSONObj& cmdObj,
                                         string& errmsg,
                                         BSONObjBuilder& result) {

        string user = cmdObj.getStringField("user");

        if (!_areNonceAuthenticateCommandsEnabled) {
            // SERVER-8461, MONGODB-CR must be enabled for authenticating the internal user, so that
            // cluster members may communicate with each other.
            if (dbname != StringData("local", StringData::LiteralTag()) ||
                user != internalSecurity.user) {
                errmsg = _nonceAuthenticateCommandsDisabledMessage;
                result.append(saslCommandCodeFieldName, ErrorCodes::AuthenticationFailed);
                return false;
            }
        }

        string key = cmdObj.getStringField("key");
        string received_nonce = cmdObj.getStringField("nonce");

        if( user.empty() || key.empty() || received_nonce.empty() ) {
            log() << "field missing/wrong type in received authenticate command "
                  << dbname
                  << endl;
            errmsg = "auth fails";
            sleepmillis(10);
            result.append(saslCommandCodeFieldName, ErrorCodes::AuthenticationFailed);
            return false;
        }

        stringstream digestBuilder;

        {
            bool reject = false;
            ClientBasic *client = ClientBasic::getCurrent();
            AuthenticationSession *session = client->getAuthenticationSession();
            if (!session || session->getType() != AuthenticationSession::SESSION_TYPE_MONGO) {
                reject = true;
                LOG(1) << "auth: No pending nonce" << endl;
            }
            else {
                nonce64 nonce = static_cast<MongoAuthenticationSession*>(session)->getNonce();
                digestBuilder << hex << nonce;
                reject = digestBuilder.str() != received_nonce;
                if ( reject ) {
                    LOG(1) << "auth: Authentication failed for " << dbname << '$' << user << endl;
                }
            }
            client->resetAuthenticationSession(NULL);

            if ( reject ) {
                log() << "auth: bad nonce received or getnonce not called. could be a driver bug or a security attack. db:" << dbname << endl;
                errmsg = "auth fails";
                sleepmillis(30);
                result.append(saslCommandCodeFieldName, ErrorCodes::AuthenticationFailed);
                return false;
            }
        }

        BSONObj userObj;
        string pwd;
        Status status = getGlobalAuthorizationManager()->getPrivilegeDocument(
                dbname, UserName(user, dbname), &userObj);
        if (!status.isOK()) {
            log() << status.reason() << std::endl;
            errmsg = "auth fails";
            result.append(saslCommandCodeFieldName, ErrorCodes::AuthenticationFailed);
            return false;
        }
        pwd = userObj["pwd"].String();

        md5digest d;
        {
            digestBuilder << user << pwd;
            string done = digestBuilder.str();

            md5_state_t st;
            md5_init(&st);
            md5_append(&st, (const md5_byte_t *) done.c_str(), done.size());
            md5_finish(&st, d);
        }

        string computed = digestToString( d );

        if ( key != computed ) {
            log() << "auth: key mismatch " << user << ", ns:" << dbname << endl;
            errmsg = "auth fails";
            result.append(saslCommandCodeFieldName, ErrorCodes::AuthenticationFailed);
            return false;
        }

        AuthorizationSession* authorizationSession =
            ClientBasic::getCurrent()->getAuthorizationSession();
        Principal* principal = new Principal(UserName(user, dbname));
        principal->setImplicitPrivilegeAcquisition(true);
        authorizationSession->addAuthorizedPrincipal(principal);

        result.append( "dbname" , dbname );
        result.append( "user" , user );
        return true;
    }

#ifdef MONGO_SSL
    bool CmdAuthenticate::authenticateX509(const string& dbname,
                                           BSONObj& cmdObj,
                                           string& errmsg,
                                           BSONObjBuilder& result) {
        if(dbname != "$external") {
            errmsg = "X.509 authentication must always use the $external database.";
            result.append(saslCommandCodeFieldName, ErrorCodes::AuthenticationFailed);
            return false;
        }

        std::string user = cmdObj.getStringField("user");
        ClientBasic *client = ClientBasic::getCurrent();
        AuthorizationSession* authorizationSession = client->getAuthorizationSession();
        StringData subjectName = client->port()->getX509SubjectName();

        if (user != subjectName) {
            errmsg = "There is no x.509 client certificate matching the user.";
            result.append(saslCommandCodeFieldName, ErrorCodes::AuthenticationFailed);
            return false;
        }
        else {
            StringData srvSubjectName = getSSLManager()->getSubjectName();
            StringData srvClusterId = srvSubjectName.substr(0, srvSubjectName.find("/CN")+1);
            StringData peerClusterId = subjectName.substr(0, subjectName.find("/CN")+1);

            // Handle internal cluster member
            if (srvClusterId == peerClusterId) {
                authorizationSession->grantInternalAuthorization(UserName(user, "$external"));
            }
            // Handle normal client authentication
            else {
                Principal* principal = new Principal(UserName(user, "$external"));
                principal->setImplicitPrivilegeAcquisition(true);
                authorizationSession->addAuthorizedPrincipal(principal);
            }
            result.append( "dbname" , dbname );
            result.append( "user" , user );
            return true;
        }
    }
#endif
    CmdAuthenticate cmdAuthenticate;

    class CmdLogout : public Command {
    public:
        virtual bool logTheOp() {
            return false;
        }
        virtual bool slaveOk() const {
            return true;
        }
        virtual void addRequiredPrivileges(const std::string& dbname,
                                           const BSONObj& cmdObj,
                                           std::vector<Privilege>* out) {} // No auth required
        void help(stringstream& h) const { h << "de-authenticate"; }
        virtual LockType locktype() const { return NONE; }
        CmdLogout() : Command("logout") {}
        bool run(const string& dbname,
                 BSONObj& cmdObj,
                 int options,
                 string& errmsg,
                 BSONObjBuilder& result,
                 bool fromRepl) {
            AuthorizationSession* authSession =
                    ClientBasic::getCurrent()->getAuthorizationSession();
            authSession->logoutDatabase(dbname);
            return true;
        }
    } cmdLogout;
}

max_stars_repo_name: nleite/mongo

max_issues_repo_name: nleite/mongo

max_forks_repo_name: nleite/mongo


text:
/**
 * @file kde_test.cpp
 * @author Roberto Hueso
 *
 * Test mlpackMain() of kde_main.cpp
 *
 * mlpack is free software; you may redistribute it and/or modify it under the
 * terms of the 3-clause BSD license.  You should have received a copy of the
 * 3-clause BSD license along with mlpack.  If not, see
 * http://www.opensource.org/licenses/BSD-3-Clause for more information.
 */
#include <string>

#define BINDING_TYPE BINDING_TYPE_TEST

static const std::string testName = "KDE";

#include <mlpack/core.hpp>
#include <mlpack/core/util/mlpack_main.hpp>
#include "test_helper.hpp"
#include <mlpack/methods/kde/kde_main.cpp>

#include <boost/test/unit_test.hpp>
#include "../test_tools.hpp"

using namespace mlpack;

struct KDETestFixture
{
 public:
  KDETestFixture()
  {
      // Cache in the options for this program.
      CLI::RestoreSettings(testName);
  }

  ~KDETestFixture()
  {
      // Clear the settings.
      CLI::ClearSettings();
  }
};

void ResetKDESettings()
{
  CLI::ClearSettings();
  CLI::RestoreSettings(testName);
}

BOOST_FIXTURE_TEST_SUITE(KDEMainTest, KDETestFixture);

/**
  * Ensure that the estimations we get for KDEMain, are the same as the ones we
  * get from the KDE class without any wrappers. Requires normalization.
 **/
BOOST_AUTO_TEST_CASE(KDEGaussianRTreeResultsMain)
{
  // Datasets.
  arma::mat reference = arma::randu(3, 500);
  arma::mat query = arma::randu(3, 100);
  arma::vec kdeEstimations, mainEstimations;
  double kernelBandwidth = 1.5;
  double relError = 0.05;

  kernel::GaussianKernel kernel(kernelBandwidth);
  metric::EuclideanDistance metric;
  KDE<kernel::GaussianKernel,
      metric::EuclideanDistance,
      arma::mat,
      tree::RTree>
      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);
  kde.Train(reference);
  kde.Evaluate(query, kdeEstimations);
  // Normalize estimations.
  kdeEstimations /= kernel.Normalizer(reference.n_rows);

  // Main estimations.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("gaussian"));
  SetInputParam("tree", std::string("r-tree"));
  SetInputParam("rel_error", relError);
  SetInputParam("bandwidth", kernelBandwidth);

  mlpackMain();

  mainEstimations = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Check whether results are equal.
  for (size_t i = 0; i < query.n_cols; ++i)
    BOOST_REQUIRE_CLOSE(kdeEstimations[i], mainEstimations[i], relError);
}

/**
  * Ensure that the estimations we get for KDEMain, are the same as the ones we
  * get from the KDE class without any wrappers. Doesn't require normalization.
 **/
BOOST_AUTO_TEST_CASE(KDETriangularBallTreeResultsMain)
{
  // Datasets.
  arma::mat reference = arma::randu(3, 300);
  arma::mat query = arma::randu(3, 100);
  arma::vec kdeEstimations, mainEstimations;
  double kernelBandwidth = 3.0;
  double relError = 0.06;

  kernel::TriangularKernel kernel(kernelBandwidth);
  metric::EuclideanDistance metric;
  KDE<kernel::TriangularKernel,
      metric::EuclideanDistance,
      arma::mat,
      tree::BallTree>
      kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);
  kde.Train(reference);
  kde.Evaluate(query, kdeEstimations);

  // Main estimations.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("triangular"));
  SetInputParam("tree", std::string("ball-tree"));
  SetInputParam("rel_error", relError);
  SetInputParam("bandwidth", kernelBandwidth);

  mlpackMain();

  mainEstimations = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Check whether results are equal.
  for (size_t i = 0; i < query.n_cols; ++i)
    BOOST_REQUIRE_CLOSE(kdeEstimations[i], mainEstimations[i], relError);
}

/**
  * Ensure that the estimations we get for KDEMain, are the same as the ones we
  * get from the KDE class without any wrappers in the monochromatic case.
 **/
BOOST_AUTO_TEST_CASE(KDEMonoResultsMain)
{
  // Datasets.
  arma::mat reference = arma::randu(2, 300);
  arma::vec kdeEstimations, mainEstimations;
  double kernelBandwidth = 2.3;
  double relError = 0.05;

  kernel::EpanechnikovKernel kernel(kernelBandwidth);
  metric::EuclideanDistance metric;
  KDE<kernel::EpanechnikovKernel,
      metric::EuclideanDistance,
      arma::mat,
      tree::StandardCoverTree>
    kde(relError, 0.0, kernel, KDEMode::DUAL_TREE_MODE, metric);
  kde.Train(reference);
  // Perform monochromatic KDE.
  kde.Evaluate(kdeEstimations);
  // Normalize.
  kdeEstimations /= kernel.Normalizer(reference.n_rows);

  // Main estimations.
  SetInputParam("reference", reference);
  SetInputParam("kernel", std::string("epanechnikov"));
  SetInputParam("tree", std::string("cover-tree"));
  SetInputParam("rel_error", relError);
  SetInputParam("bandwidth", kernelBandwidth);

  mlpackMain();

  mainEstimations = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Check whether results are equal.
  for (size_t i = 0; i < reference.n_cols; ++i)
    BOOST_REQUIRE_CLOSE(kdeEstimations[i], mainEstimations[i], relError);
}

/**
  * Ensuring that absence of input data is checked.
 **/
BOOST_AUTO_TEST_CASE(KDENoInputData)
{
  // No input data is not provided. Should throw a runtime error.
  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
  * Check result has as many densities as query points.
 **/
BOOST_AUTO_TEST_CASE(KDEOutputSize)
{
  const size_t dim = 3;
  const size_t samples = 110;
  arma::mat reference = arma::randu<arma::mat>(dim, 325);
  arma::mat query = arma::randu<arma::mat>(dim, samples);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);

  mlpackMain();
  // Check number of output elements.
  BOOST_REQUIRE_EQUAL(CLI::GetParam<arma::vec>("predictions").size(), samples);
}

/**
  * Check that saved model can be reused.
 **/
BOOST_AUTO_TEST_CASE(KDEModelReuse)
{
  const size_t dim = 3;
  const size_t samples = 100;
  const double relError = 0.05;
  arma::mat reference = arma::randu<arma::mat>(dim, 300);
  arma::mat query = arma::randu<arma::mat>(dim, samples);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("bandwidth", 2.4);
  SetInputParam("rel_error", 0.05);

  mlpackMain();

  arma::vec oldEstimations = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Change parameters and load model.
  CLI::GetSingleton().Parameters()["reference"].wasPassed = false;
  SetInputParam("query", query);
  SetInputParam("input_model",
      std::move(CLI::GetParam<KDEModel*>("output_model")));

  mlpackMain();

  arma::vec newEstimations = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Check estimations are the same.
  for (size_t i = 0; i < samples; ++i)
    BOOST_REQUIRE_CLOSE(oldEstimations[i], newEstimations[i], relError);
}

/**
  * Ensure that the estimations we get for KDEMain, are the same as the ones we
  * get from the KDE class without any wrappers using single-tree mode.
 **/
BOOST_AUTO_TEST_CASE(KDEGaussianSingleKDTreeResultsMain)
{
  // Datasets.
  arma::mat reference = arma::randu(3, 400);
  arma::mat query = arma::randu(3, 400);
  arma::vec kdeEstimations, mainEstimations;
  double kernelBandwidth = 3.0;
  double relError = 0.06;

  kernel::GaussianKernel kernel(kernelBandwidth);
  metric::EuclideanDistance metric;
  KDE<kernel::GaussianKernel,
      metric::EuclideanDistance,
      arma::mat,
      tree::BallTree>
      kde(relError, 0.0, kernel, KDEMode::SINGLE_TREE_MODE, metric);
  kde.Train(reference);
  kde.Evaluate(query, kdeEstimations);
  kdeEstimations /= kernel.Normalizer(reference.n_rows);

  // Main estimations.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("gaussian"));
  SetInputParam("tree", std::string("kd-tree"));
  SetInputParam("algorithm", std::string("single-tree"));
  SetInputParam("rel_error", relError);
  SetInputParam("bandwidth", kernelBandwidth);

  mlpackMain();

  mainEstimations = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Check whether results are equal.
  for (size_t i = 0; i < query.n_cols; ++i)
    BOOST_REQUIRE_CLOSE(kdeEstimations[i], mainEstimations[i], relError);
}

/**
  * Ensure we get an exception when an invalid kernel is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidKernel)
{
  arma::mat reference = arma::randu<arma::mat>(2, 10);
  arma::mat query = arma::randu<arma::mat>(2, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("linux"));

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid tree is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidTree)
{
  arma::mat reference = arma::randu<arma::mat>(2, 10);
  arma::mat query = arma::randu<arma::mat>(2, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("tree", std::string("olive"));

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid algorithm is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidAlgorithm)
{
  arma::mat reference = arma::randu<arma::mat>(2, 10);
  arma::mat query = arma::randu<arma::mat>(2, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("algorithm", std::string("bogosort"));

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when both reference and input_model are
  * specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainReferenceAndModel)
{
  arma::mat reference = arma::randu<arma::mat>(2, 10);
  arma::mat query = arma::randu<arma::mat>(2, 5);
  KDEModel* model = new KDEModel();

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("input_model", model);

  Log::Fatal.ignoreInput = true;
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid absolute error is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidAbsoluteError)
{
  arma::mat reference = arma::randu<arma::mat>(1, 10);
  arma::mat query = arma::randu<arma::mat>(1, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);

  Log::Fatal.ignoreInput = true;
  // Invalid value.
  SetInputParam("abs_error", -0.1);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Valid value.
  SetInputParam("abs_error", 5.8);
  BOOST_REQUIRE_NO_THROW(mlpackMain());
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid relative error is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidRelativeError)
{
  arma::mat reference = arma::randu<arma::mat>(1, 10);
  arma::mat query = arma::randu<arma::mat>(1, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);

  Log::Fatal.ignoreInput = true;
  // Invalid under 0.
  SetInputParam("rel_error", -0.1);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Invalid over 1.
  SetInputParam("rel_error", 1.1);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Valid value.
  SetInputParam("rel_error", 0.3);
  BOOST_REQUIRE_NO_THROW(mlpackMain());
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid Monte Carlo probability is
  * specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidMCProbability)
{
  arma::mat reference = arma::randu<arma::mat>(1, 10);
  arma::mat query = arma::randu<arma::mat>(1, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("gaussian"));
  SetInputParam("monte_carlo", true);

  Log::Fatal.ignoreInput = true;
  // Invalid under 0.
  SetInputParam("mc_probability", -0.1);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Invalid over 1.
  SetInputParam("mc_probability", 1.1);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Valid value.
  SetInputParam("mc_probability", 0.3);
  BOOST_REQUIRE_NO_THROW(mlpackMain());
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid Monte Carlo initial sample size
  * is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidMCInitialSampleSize)
{
  arma::mat reference = arma::randu<arma::mat>(1, 10);
  arma::mat query = arma::randu<arma::mat>(1, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("gaussian"));
  SetInputParam("monte_carlo", true);

  Log::Fatal.ignoreInput = true;
  // Invalid under 0.
  SetInputParam("initial_sample_size", -1);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Invalid 0.
  SetInputParam("initial_sample_size", 0);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Valid value.
  SetInputParam("initial_sample_size", 20);
  BOOST_REQUIRE_NO_THROW(mlpackMain());
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid Monte Carlo entry coefficient
  * is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidMCEntryCoef)
{
  arma::mat reference = arma::randu<arma::mat>(1, 10);
  arma::mat query = arma::randu<arma::mat>(1, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("gaussian"));
  SetInputParam("monte_carlo", true);

  Log::Fatal.ignoreInput = true;
  // Invalid under 1.
  SetInputParam("mc_entry_coef", 0.5);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Valid greater than 1.
  SetInputParam("mc_entry_coef", 1.1);
  BOOST_REQUIRE_NO_THROW(mlpackMain());
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure we get an exception when an invalid Monte Carlo break coefficient
  * is specified.
 **/
BOOST_AUTO_TEST_CASE(KDEMainInvalidMCBreakCoef)
{
  arma::mat reference = arma::randu<arma::mat>(1, 10);
  arma::mat query = arma::randu<arma::mat>(1, 5);

  // Main params.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  SetInputParam("kernel", std::string("gaussian"));
  SetInputParam("monte_carlo", true);

  Log::Fatal.ignoreInput = true;
  // Invalid under 0.
  SetInputParam("mc_break_coef", -0.5);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);

  // Valid between 0 and 1.
  SetInputParam("mc_break_coef", 0.3);
  BOOST_REQUIRE_NO_THROW(mlpackMain());

  // Invalid greater than 1.
  SetInputParam("mc_break_coef", 1.1);
  BOOST_REQUIRE_THROW(mlpackMain(), std::runtime_error);
  Log::Fatal.ignoreInput = false;
}

/**
  * Ensure when --monte_carlo flag is true, then KDEMain actually uses Monte
  * Carlo estimations. Since this test has a random component, it might fail
  * (although it's unlikely).
 **/
BOOST_AUTO_TEST_CASE(KDEMainMonteCarloFlag)
{
  // Datasets.
  arma::mat reference = arma::randu(1, 5000);
  arma::mat query = arma::randu(1, 300);
  arma::vec estimations1, estimations2, differences;
  double kernelBandwidth = 0.2;

  // Parameters for estimations.
  SetInputParam("reference", arma::mat(reference));
  SetInputParam("query", arma::mat(query));
  SetInputParam("kernel", std::string("gaussian"));
  SetInputParam("tree", std::string("kd-tree"));
  SetInputParam("bandwidth", kernelBandwidth);
  SetInputParam("monte_carlo", true);

  // Compute estimations 1.
  mlpackMain();
  estimations1 = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Compute estimations 2.
  SetInputParam("reference", reference);
  SetInputParam("query", query);
  mlpackMain();
  estimations2 = std::move(CLI::GetParam<arma::vec>("predictions"));

  // Check whether results are equal.
  differences = arma::abs(estimations1 - estimations2);
  const double sumDifferences = arma::accu(differences);
  BOOST_REQUIRE_GT(sumDifferences, 0);
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: AYESDIE/mlpack

max_issues_repo_name: AYESDIE/mlpack

max_forks_repo_name: AYESDIE/mlpack


text:
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com)
// (C) Copyright 2004-2007 Jonathan Turkanis
// 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.)

// See http://www.boost.org/libs/iostreams for documentation.

// Contains the definitions of several constants used by the test program.

#ifndef BOOST_IOSTREAMS_TEST_CONSTANTS_HPP_INCLUDED
#define BOOST_IOSTREAMS_TEST_CONSTANTS_HPP_INCLUDED

#include <string.h>
#include <boost/config.hpp>

namespace boost { namespace iostreams { namespace test {

// Note: openmode could be a class type, so this header must be included
// by just one TU.
const BOOST_IOS::openmode in_mode = BOOST_IOS::in | BOOST_IOS::binary;
const BOOST_IOS::openmode out_mode = BOOST_IOS::out | BOOST_IOS::binary;

// Chunk size for reading or writing in chunks.
const int chunk_size = 59;

// Chunk size for reading or writing in chunks.
const int small_buffer_size = 23;

// Number of times data is repeated in test files.
const int data_reps = 300;

namespace detail {

// Returns string which is used to generate test files.
inline const char* data(char*)
{
    static const char* c =
        "!\"#$%&'()*+,-./0123456879:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n";
    return c;
}

// Returns string which is used to generate test files.
inline const wchar_t* data(wchar_t*)
{
    static const wchar_t* c =
        L"!\"#$%&'()*+,-./0123456879:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        L"[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n";
    return c;
}

} // End namespace detail.

inline const char* narrow_data() { return detail::data((char*)0); }

inline const wchar_t* wide_data() { return detail::data((wchar_t*)0); }

// Length of string returned by data().
inline int data_length()
{
    static int len = (int) strlen(narrow_data());
    return len;
}

} } } // End namespaces detail, iostreams, boost.

#endif // #ifndef BOOST_IOSTREAMS_TEST_CONSTANTS_HPP_INCLUDED

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
/// Copyright (C) 2021 Alessandro Fornasier, Control of Networked Systems,
/// University of Klagenfurt, Austria.
///
/// All rights reserved.
///
/// This software is licensed under the terms of the BSD-2-Clause-License with
/// no commercial use allowed, the full terms of which are made available in the
/// LICENSE file. No license in patents is granted.
///
/// You can contact the author at alessandro.fornasier@ieee.org

#ifndef INPUTDATAPARSER_HPP
#define INPUTDATAPARSER_HPP

#include <cstdlib>
#include <cstring>
#include <fstream>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <sstream>
#include <Eigen/Eigen>
#include <algorithm>

/**
* @brief Input data parser for FlightGoggles.
*
* This class has a series of functions that allows to generate
* data starting from a trajectory file generated through the
* MultiCopter simulation framework.
*
*/
class InputDataParser {

public:

  /**
  * @brief Input struct to parse a single line of a .csv file
  *
  * timestamp (t)
  * position (p)
  * rotation - quaternion (q) [defined as: x = R(q)x_b]
  * angular velocity (w)
  * acceleration (a)
  */
  struct Input {
    double t;
    Eigen::Vector3d p;
    Eigen::Quaterniond q;
    Eigen::Vector3d w;
    Eigen::Vector3d a;
  };

  /**
  * @brief constructor
  */
  InputDataParser();

  /**
  * @brief Clear actual data, read a new .csv file and convert to a matrix (vector of vectors)
  *
  * @param filename
  */
  void readParseCsv(const std::string filename);

  /**
  * @brief Get Data red from .csv file
  */
  const std::vector<Input> &getData() const;

  /**
  * @brief Parse a single line of the .csv file
  *
  * overloaded function to parse a single line of a .csv
  * file with a comma as delimeter.
  * This function is overloaded to include either string values
  * (usually the case for headers) or numerical values
  */
  void parseLine(std::string &line, std::vector<std::string> &data);

  template <typename T>
  void parseLine(std::string &line, std::vector<T> &data) {

    // Create a stringstream of the current line
    std::stringstream ss(line);

    // Temporary value
    T tmp;

    // Extract each cell
    while (ss >> tmp) {
      data.push_back(tmp);

      // skip commas
      if(ss.peek() == ',') ss.ignore();
    }
  }

  /**
  * @brief Find association between input file and defined convention
  *
  * The defined convention of the Input structure is -- t,p,q,w,a --
  * This function find the indices of the columns of the input file based
  * on its header in order to correctly associate input data with the
  * Input structure allowing inpput files with shuffled columns or even
  * more columns than the onse that are necessary
  */
  void getIndices(const std::vector<std::string> &header, std::vector<int> &indices);

  /**
  * @brief Find the index of token within the given vector
  */
  template <typename T>
  void getIndex(const std::vector<T> &data, const T &token, int &index) {

    // Iterator
    auto it = find(data.begin(), data.end(), token);

    // Check if element was found
    if (it != data.end())
    {
      // Get the index
      index = it - data.begin();
    }
    else {
      throw std::runtime_error("Required data missing. Exit programm.");
    }
  }

private:

  /**
  * @brief Raw data from a .csv file converted to a matrix (vector of inputs)
  */
  std::vector<Input> data_;

  /**
  * @brief vector of strings in header ordered based on defined convention -- t,p,q,w,a -
  */
  std::vector<std::string> categories_ = {"Time", "x", "y", "z", "qx", "qy", "qz", "qw", "vroll", "vpitch", "vyaw", "ax", "ay", "az"};

};

#endif //INPUTDATAPARSER_HPP


text:
#pragma once

#include <logos/network/peer_manager.hpp>
#include <logos/lib/log.hpp>

#include <boost/asio.hpp>

#include <memory>
#include <set>

class PeerAcceptor : public std::enable_shared_from_this<PeerAcceptor>
{
    using Service  = boost::asio::io_service;
    using Socket   = boost::asio::ip::tcp::socket;
    using Acceptor = boost::asio::ip::tcp::acceptor;
    using Endpoint = boost::asio::ip::tcp::endpoint;
    using Address  = boost::asio::ip::address;

public:

    PeerAcceptor(Service & service,
                 const Endpoint & local_endpoint,
                 PeerManager & manager);
    ~PeerAcceptor() = default;

    void Start();

    void Accept();

    void OnAccept(boost::system::error_code const & ec, std::shared_ptr<Socket> socket);

private:

    Acceptor        _acceptor;
    Log             _log;
    Service &       _service;
    Endpoint        _local_endpoint;
    Endpoint        _accepted_endpoint;
    PeerManager &   _manager;
};

max_stars_repo_name: LogosNetwork/logos-core

max_issues_repo_name: LogosNetwork/logos-core

max_forks_repo_name: LogosNetwork/logos-core


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

using namespace std;
//#pragma warning(disable : 4996)

//3.1
namespace _nmsp1
{
	//TC的泛化版本
	//template <typename T,typename U>
	template <typename T=int, typename U=int>
	struct TC
	{
		TC()
		{
			cout << "TC泛化版本的构造函数" << endl;
		}
		void functest1()
		{
			cout << "functest1泛化版本" << endl;
		}
	};

	//TC的特化版本
	//template <typename T = char>
	template <typename T>
	struct TC<T, int>
	{

	};
}

//3.2
namespace _nmsp2
{
	template <typename T,typename U = T*>
	struct TC
	{
		//....
	};
}

//3.3
namespace _nmsp3
{
	//声明1，指定了V和W
	template <typename T,typename U, typename V = int,typename W = char>
	struct TC;

	//声明2，指定U
	template <typename T, typename U = char, typename V, typename W>
	struct TC;

	//定义泛化版本的TC
	template <typename T, typename U, typename V, typename W>
	struct TC
	{
		//...
	};

	//4
	typedef TC<int, float> IF_TC;
	using IF_TCU = TC<int, float>;
}

//5
namespace _nmsp4
{
	template <typename T , typename U ,size_t arrsize=8>
	//template <typename T, typename U, auto arrsize = 8>
	struct TC
	{
		T m_arr[arrsize]; //这个arrsize是在编译器期间，编译器就会传递进来arrsize的大小来确定数组m_arr的大小。
		void functest2();
	};

	template <typename T, typename U, size_t arrsize>
	//template <typename T, typename U, auto arrsize>
	void TC<T,U, arrsize >::functest2()
	{
		cout << "functest2泛化版本" << endl;
	}
}

namespace _nmsp5
{
	template <const char *p>
	struct TC2
	{
		TC2()
		{
			printf("TC2::TC2执行了,p= %s\n", p);
		}
	};
	//const char* g_s = "hello"; //全局指针
	const char g_s[] = "hello";
}

int main()
{

	/*****

	第二节 类模板、变量模板、别名模板

	三：缺省参数
	3.1 常规缺省参数
	类型模板参数缺省值的规矩：如果某个模板参数有缺省值，那么从这个有缺省值的模板参数开始，
	后面的所有模板参数都得有缺省值。
	类模板片特化版本中的类型模板参数不可以有缺省值。

	3.2 后面的模板参数依赖前面的模板参数
	3.3 在模板声明中指定缺省参数

	四：类型别名
	考虑到类型名比较长，所以 一般都用typedef ，或者using给这些类型名起一个额外的别名来简化书写。

	五：非类型模板参数
	数字是常量.类型一般也限制在整型、指针类型等等。
	(1)全局指针不能作为函数参数
	(2)字符串常量也无法作为模板参数
	c++标准委员会有些特殊考虑。
	TC2<"hello">
	为什么不允许浮点类型数字作为非类型模板参数,因为其保存的不是一个精确数字。
	TC3<2.1111111>和TC3<2.11111109>

	******/

	//_nmsp1::TC<> mytc5; //使用了缺省模板参数，所以<>中啥也不用提供
	//_nmsp1::TC<double> mytc6; //<>中第一个类型不使用缺省参数，第二个类型使用缺省参数

	/*_nmsp2::TC<double> mytc5;
	_nmsp2::TC<double,int> mytc6;*/

	//_nmsp3::TC<int> mytc;  //第二、三、四个模板参数采用缺省值，所以<>里只提供了一个类型模板实参

	//_nmsp3::IF_TC mytc10;  //IF_TC等价于TC<int, float> ,所以整个代码行等价于：_nmsp3::TC<int, float>   mytc10;
	//_nmsp3::IF_TCU mytc11; //IF_TCU等价于TC<int, float>

	/*
	_nmsp4::TC<double, double> mytc30; //缺省的第三个模板参数是8
	for (size_t i = 0; i < 8; ++i)
	{
		mytc30.m_arr[i] = static_cast<double>(i);
	}
	cout << mytc30.m_arr[7] << endl; //7

	_nmsp4::TC<double, double,18> mytc31;
	mytc31.m_arr[10] = 16.8;
	cout << mytc31.m_arr[10] << endl; //16.8
	*/

	_nmsp5::TC2<_nmsp5::g_s> mytc40;
	//_nmsp5::TC2<"hello"> mytc41;

	return 0;
}

max_stars_repo_name: mallius/CppPrimer

max_issues_repo_name: mallius/CppPrimer

max_forks_repo_name: mallius/CppPrimer


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2008 J. Erik Radmall

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

/*! \file commodity.hpp
    \brief commodity type
*/

#ifndef quantlib_commodity_type_hpp
#define quantlib_commodity_type_hpp

#include <ql/qldefines.hpp>
#include <boost/shared_ptr.hpp>
#include <map>
#include <iosfwd>
#include <string>

namespace QuantLib {

    //! commodity type
    class CommodityType {
      public:
        //! default constructor
        /*! Instances built via this constructor have undefined
          behavior. Such instances can only act as placeholders
          and must be reassigned to a valid currency before being
          used.
        */
        CommodityType() {}
        CommodityType(const std::string& code, const std::string& name);
        //! \name Inspectors
        //@{
        //! commodity code, e.g, "HO"
        const std::string& code() const;
        //! name, e.g, "Heating Oil"
        const std::string& name() const;
        // commodity code
        //@}
        //! \name Other information
        //@{
        //! is this a usable instance?
        bool empty() const;
        //@}

      protected:
        struct Data;
        boost::shared_ptr<Data> data_;

        struct Data {
            std::string name, code;

            Data(const std::string& name,
                 const std::string& code)
            : name(name), code(code) {}
        };

        static std::map<std::string, boost::shared_ptr<Data> > commodityTypes_;
    };

    /*! \relates CommodityType */
    bool operator==(const CommodityType&,
                    const CommodityType&);

    /*! \relates CommodityType */
    bool operator!=(const CommodityType&,
                    const CommodityType&);

    /*! \relates CommodityType */
    std::ostream& operator<<(std::ostream&,
                             const CommodityType&);

    class NullCommodityType : public CommodityType {
      public:
        NullCommodityType() :
        CommodityType("<NULL>", "<NULL>") {}
    };

    inline const std::string& CommodityType::code() const {
        return data_->code;
    }

    inline const std::string& CommodityType::name() const {
        return data_->name;
    }

    inline bool CommodityType::empty() const {
        return !data_;
    }

    inline bool operator==(const CommodityType& c1, const CommodityType& c2) {
        return c1.code() == c2.code();
    }

    inline bool operator!=(const CommodityType& c1, const CommodityType& c2) {
        return !(c1 == c2);
    }

}

#endif

max_stars_repo_name: sfondi/QuantLib

max_issues_repo_name: sfondi/QuantLib

max_forks_repo_name: sfondi/QuantLib


text:
// Copyright 2012 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"
#include "ICEWS/EventMention.h"
#include "Generic/common/UnicodeUtil.h"
#include "Generic/state/XMLTheoryElement.h"
#include "Generic/state/XMLStrings.h"
#include "Generic/theories/Mention.h"
#include "Generic/theories/SentenceTheory.h"
#include "Generic/theories/TokenSequence.h"
#include <xercesc/util/XMLString.hpp>
#include <boost/foreach.hpp>

namespace ICEWS {

Symbol ICEWSEventMention::NEUTRAL_TENSE = Symbol(L"neutral");
Symbol ICEWSEventMention::CURRENT_TENSE = Symbol(L"current");
Symbol ICEWSEventMention::HISTORICAL_TENSE = Symbol(L"historical");
Symbol ICEWSEventMention::ONGOING_TENSE = Symbol(L"ongoing");

ICEWSEventMention::ICEWSEventMention(ICEWSEventType_ptr eventType, const ParticipantMap& participants, Symbol patternId, Symbol tense)
: _eventType(eventType), _participants(participants), _patternId(patternId), _event_tense(tense)
{
}

ActorMention_ptr ICEWSEventMention::getParticipant(Symbol role) const {
	ParticipantMap::const_iterator it = _participants.find(role);
	if (it == _participants.end())
		return ActorMention_ptr();
	else
		return (*it).second;
}

ICEWSEventType_ptr ICEWSEventMention::getEventType() const {
	return _eventType;
}

void ICEWSEventMention::setEventType(ICEWSEventType_ptr newEventType) {
	if (!newEventType)
		throw InternalInconsistencyException("ICEWSEventMention::setEventType",
			"Attempt to set event type to NULL");
	_eventType = newEventType;
}

void ICEWSEventMention::setEventTense(Symbol tense) {
	_event_tense = tense;
}

Symbol ICEWSEventMention::getEventTense() const {
	return _event_tense;
}

bool ICEWSEventMention::isValidTense(Symbol sym) {
	return (sym ==  NEUTRAL_TENSE || sym ==  CURRENT_TENSE ||
		sym ==  HISTORICAL_TENSE || sym ==  ONGOING_TENSE);
}

Symbol ICEWSEventMention::getPatternId() const {
	return _patternId;
}

void ICEWSEventMention::updateObjectIDTable() const {
	throw InternalInconsistencyException("ICEWSEventMention::updateObjectIDTable",
		"ICEWSEventMention does not currently have state file support");
}
void ICEWSEventMention::saveState(StateSaver *stateSaver) const {
	throw InternalInconsistencyException("ICEWSEventMention::saveState",
		"ICEWSEventMention does not currently have state file support");
}
void ICEWSEventMention::resolvePointers(StateLoader * stateLoader) {
	throw InternalInconsistencyException("ICEWSEventMention::resolvePointers",
		"ICEWSEventMention does not currently have state file support");
}

ICEWSEventMention::ICEWSEventMention(SerifXML::XMLTheoryElement elem) {
	using namespace SerifXML;
	static const XMLCh* X_ICEWSEventParticipant = xercesc::XMLString::transcode("ICEWSEventParticipant");
	static const XMLCh* X_actor_id = xercesc::XMLString::transcode("actor_id");
	static const XMLCh* X_eventCode = xercesc::XMLString::transcode("event_code");
	static const XMLCh* X_patternId = xercesc::XMLString::transcode("pattern_id");
	static const XMLCh* X_eventTense = xercesc::XMLString::transcode("event_tense");
	Symbol eventCode = elem.getAttribute<Symbol>(X_eventCode);
	_eventType = ICEWSEventType::getEventTypeForCode(eventCode);
	_patternId = elem.getAttribute<Symbol>(X_patternId);
	_event_tense = elem.getAttribute<Symbol>(X_eventTense);
	std::vector<XMLTheoryElement> participantElems = elem.getChildElementsByTagName(X_ICEWSEventParticipant);
	BOOST_FOREACH(XMLTheoryElement pElem, participantElems) {
		Symbol role = pElem.getAttribute<Symbol>(X_role);
		if (_participants.find(role) != _participants.end()) {
			std::wostringstream err;
			err << L"Role " << role << " assigned multiple values";
			elem.reportLoadError(err.str().c_str());
		}
		// Load the actor, and use shared_from_this to get its shared pointer.
		ActorMention* participant = pElem.loadNonConstTheoryPointer<ActorMention>(X_actor_id);
		_participants[role] = participant->shared_from_this();
	}
}

void ICEWSEventMention::saveXML(SerifXML::XMLTheoryElement elem, const Theory *context) const {
	using namespace SerifXML;
	static const XMLCh* X_ICEWSEventParticipant = xercesc::XMLString::transcode("ICEWSEventParticipant");
	static const XMLCh* X_actor_id = xercesc::XMLString::transcode("actor_id");
	static const XMLCh* X_eventCode = xercesc::XMLString::transcode("event_code");
	static const XMLCh* X_patternId = xercesc::XMLString::transcode("pattern_id");
	static const XMLCh* X_eventTense = xercesc::XMLString::transcode("event_tense");
	elem.setAttribute(X_eventCode, _eventType->getEventCode());
	elem.setAttribute(X_patternId, _patternId);
	elem.setAttribute(X_eventTense, _event_tense);

	typedef std::pair<Symbol, ActorMention_ptr> SymbolActorPair;
	BOOST_FOREACH(SymbolActorPair pair, _participants) {
		ActorMention_ptr actor = pair.second;
		XMLTheoryElement childElem = elem.addChild(X_ICEWSEventParticipant);
		childElem.saveTheoryPointer(X_actor_id, actor.get());
		childElem.setAttribute(X_role, pair.first);
	}
}

bool ICEWSEventMention::isDatabaseWorthyEvent() const {
	typedef std::pair<Symbol, ActorMention_ptr> SymbolActorPair;
	BOOST_FOREACH(SymbolActorPair pair, _participants) {
		if (CompositeActorMention_ptr cam_actor = boost::dynamic_pointer_cast<CompositeActorMention>(pair.second)) {
			if (cam_actor->getPairedActorId().isNull())
				return false;
		}
	}
	return true;
}

size_t ICEWSEventMention::getIcewsSentNo(const DocTheory* docTheory) const {
	// Check which sentence each participant was in.  Hopefully, they'll
	// all be in the same ICEWS sentence, but there's no guarantee that
	// this will be true since we use our own sentence segmentation.
	std::map<size_t, size_t> sent_no_count; // maps sent_no -> num_participants
	typedef std::pair<Symbol, ActorMention_ptr> SymbolActorPair;
	BOOST_FOREACH(SymbolActorPair pair, _participants) {
		ActorMention_ptr actor = pair.second;
		++sent_no_count[actor->getIcewsSentNo(docTheory)];
	}
	// Return the sentence number for the ICEWS sentence that has the
	// largest number of event participants.  (In case of tie, take the
	// lowest sentence number.)
	typedef std::pair<size_t, size_t> SizeTPair;
	SizeTPair best(0,0);
	BOOST_FOREACH(SizeTPair pair, sent_no_count) {
		if (pair.second > best.second)
			best = pair;
	}
	return best.first;
}

void ICEWSEventMention::dump(std::wostream &stream, const char* indent) {
	stream << indent << "EVENT-" << getEventType()->getEventCode()
		<< " (" << getEventType()->getName() << ")";
	stream << "\n" << indent << "Tense: " << _event_tense;
	typedef std::pair<Symbol, ActorMention_ptr> ParticipantPair;
	BOOST_FOREACH(ParticipantPair participantPair, _participants) {
		stream << "\n" << indent << "  " << participantPair.first << ": "
			<< participantPair.second << "\n" << indent << "          \""
			<< participantPair.second->getEntityMention()->toCasedTextString() << "\"";
	}
}

std::wstring ICEWSEventMention::getEventText() const {
	// for now, just return the entire sentence.
	if (_participants.empty()) return L"???";
	const SentenceTheory* sentTheory = _participants.begin()->second->getSentence();
	return sentTheory->getTokenSequence()->toString();
}

} // end of ICEWS namespace

std::wostream & operator << ( std::wostream &stream, ICEWS::ICEWSEventMention_ptr eventMention ) {
	eventMention->dump(stream);
	return stream;
}

std::ostream & operator << ( std::ostream &stream, ICEWS::ICEWSEventMention_ptr eventMention ) {
	std::wostringstream s;
	eventMention->dump(s);
	stream << UnicodeUtil::toUTF8StdString(s.str());
	return stream;
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
#ifndef ENGINE_HPP
#define	ENGINE_HPP

#include <boost/thread/barrier.hpp>
#include "OpManager.hpp"
#include "Sio.hpp"
#include "threadpool.hpp"
#include "tasks/PTaskBlockMgr.hpp"
#include "tasks/PTaskBlockMgrWithScheduler.hpp"
#include "Dispatcher.hpp"
#include "io_task.h"
#include "tasks/task.h"
#include "Worker.hpp"

const size_t BUFF_SIZE = 2000000; //should can store one vertex at least
const size_t SIZE = 40;
const size_t TASK_SIZE = 2000;
const size_t OP_TASK_SIZE = 3000000;
const size_t worker_num = 1;

namespace graphzx {

    template<typename edge_t, typename vertex_val_t, typename op_val_t, typename Application>
    class Engine {
    private:
        unsigned int max_iter_num;

    private:
        GraphProperty *gp;
        boost::threadpool::pool *tp;

        //buffers
    private:
        PTaskBlockMgrWithScheduler< struct io_buffer <edge_t, BUFF_SIZE> > *in_iobuffer;
        PTaskBlockMgrWithScheduler< struct TaskBlock<struct graphzx::adjlst<edge_t> *, TASK_SIZE> > **vertex_buffers;
        PTaskBlockMgrWithScheduler<TaskBlock<AOP<op_val_t>, OP_TASK_SIZE> >** op_handle_buffers;
        PTaskBlockMgrWithScheduler<TaskBlock<AOP<op_val_t>, OP_TASK_SIZE> >* output_op_buffer;

        vertex_val_t *vals;

    private:
        graphzx::Sio<edge_t, BUFF_SIZE> *sio;
        graphzx::Dispatcher<edge_t, BUFF_SIZE, TASK_SIZE, worker_num> *dispatcher;
        Worker< edge_t, vertex_val_t, op_val_t, \
             TASK_SIZE, OP_TASK_SIZE, worker_num,\
            Application > **workers;

        OpManager<vertex_val_t, op_val_t, OP_TASK_SIZE,\
            Application > *opmgr;

    private:

    private:

        void check_malloc(void *p) {
            if (p == NULL) {
                cerr << "allocate memory error in Engine" << endl;
                exit(-1);
            }
        }

    public:

        Engine(unsigned int _max_iter_num, GraphProperty *_gp, unsigned int _worker_num) \
    : max_iter_num(_max_iter_num), gp(_gp) {
            //gp = new GraphProperty(string("/home/ubu/Downloads/com-lj.ungraph.txt"));
            in_iobuffer = new PTaskBlockMgrWithScheduler< struct io_buffer <edge_t, BUFF_SIZE> >(SIZE);
            vertex_buffers = new PTaskBlockMgrWithScheduler< struct TaskBlock<struct adjlst<edge_t> *, TASK_SIZE> > *[worker_num];
            op_handle_buffers = new PTaskBlockMgrWithScheduler<TaskBlock<AOP<op_val_t>, OP_TASK_SIZE> >*[worker_num];

            for (int i = 0; i < worker_num; i++) {
                vertex_buffers[i] = new PTaskBlockMgrWithScheduler< struct TaskBlock<struct adjlst<edge_t> *, TASK_SIZE> >(SIZE);
                op_handle_buffers[i] = new PTaskBlockMgrWithScheduler<TaskBlock<AOP<op_val_t>, OP_TASK_SIZE> >(SIZE);
            }
            output_op_buffer = new PTaskBlockMgrWithScheduler<TaskBlock<AOP<op_val_t>, OP_TASK_SIZE> >(SIZE);

            sio = new graphzx::Sio<edge_t, BUFF_SIZE> (gp, in_iobuffer);
            dispatcher = new graphzx::Dispatcher<edge_t, BUFF_SIZE, TASK_SIZE, worker_num>(in_iobuffer, vertex_buffers);

            vals = new vertex_val_t[gp->nvertices_per_partition];

            workers = new Worker< edge_t, vertex_val_t, op_val_t, \
             TASK_SIZE, OP_TASK_SIZE, worker_num,\
  Application > *[worker_num];

            Worker<edge_t, vertex_val_t, op_val_t, \
             TASK_SIZE, OP_TASK_SIZE, worker_num,\
  Application >\
::init_shared_objects(gp, vertex_buffers, op_handle_buffers, output_op_buffer);

            for (int i = 0; i < worker_num; i++) {
                workers[i] = new Worker<edge_t, vertex_val_t, op_val_t, \
             TASK_SIZE, OP_TASK_SIZE, worker_num,\
  Application > (vals);
            }

            Vertex_Tracker::init(gp, worker_num, TASK_SIZE);

            opmgr = new OpManager<vertex_val_t, op_val_t, OP_TASK_SIZE,\
    Application > (gp, vals, output_op_buffer, worker_num);

            tp = new boost::threadpool::pool(worker_num+10);
        }

        virtual ~Engine() {

            delete tp;

            delete in_iobuffer;

            for (int i = 0; i < worker_num; i++) {
                delete vertex_buffers[i];
            }
            delete vertex_buffers;

            for (int i = 0; i < worker_num; i++) {
                delete op_handle_buffers[i];
            }
            delete op_handle_buffers;
            delete output_op_buffer;

            delete vals;

            delete sio;
            delete dispatcher;
            for (int i = 0; i < worker_num; i++) {
                delete workers[i];
            }
            delete workers;
        }

        int start() {
            for (int iter = 0; iter < max_iter_num; iter++) {
                gp->converged = true;
                for (int nth = 0; nth < gp-> par_num; nth++) {
                    logstream(LOG_INFO) << "iter: " << iter << std::endl;
                    logstream(LOG_INFO) << "nth_par: " << nth << std::endl;

//                    Worker< edge_t, vertex_val_t, op_val_t, \
//                        TASK_SIZE, OP_TASK_SIZE, worker_num,\
//                        Application >::init_vals(nth);

                    //update stored messaged to those vertices' values
                    Vertex_Tracker::nth_par = nth;
                    Vertex_Tracker::tell_self();
                    //reload partitions

                    opmgr->set_partition(nth);

                    tp->schedule(boost::bind(graphzx::Sio<edge_t, BUFF_SIZE>::start_retrive, sio, iter, nth));
                    //tp->schedule(boost::bind(graphzx::Sio<edge_t, BUFF_SIZE>::start_wait, sio, iter, nth));
                    tp->schedule(boost::bind(graphzx::Dispatcher<edge_t, BUFF_SIZE, TASK_SIZE, worker_num>::run, dispatcher));

                    for (int i = 0; i < worker_num; i++) {
                        tp->schedule(boost::bind(Worker<edge_t, vertex_val_t, op_val_t, \
                            TASK_SIZE, OP_TASK_SIZE, worker_num,\
                                Application >::run, workers[i], iter, nth));
                    }

                    tp->schedule(boost::bind(OpManager<vertex_val_t, op_val_t, OP_TASK_SIZE,\
                        Application > ::run, opmgr, nth));

                    tp->wait();

//                logstream(LOG_DEBUG) << "updatec: " << Application::updatec << std::endl;
                }

                logstream(LOG_INFO) << "Sio times: " << std::endl;
                sio->timer.tellself();

                logstream(LOG_INFO) << "dispatcher times: "  << std::endl;
                dispatcher->timer.tellself();

                logstream(LOG_INFO) << "opmanager times: " << std::endl;
                opmgr->refresh_timer.tellself();
                opmgr->write_timer.tellself();

                if (iter != 0 && gp->converged)
                    return 0;
            }

        }

    };
}
#endif	/* ENGINE_HPP */

max_stars_repo_name: connorimes/GraphZ

max_issues_repo_name: connorimes/GraphZ

max_forks_repo_name: connorimes/GraphZ


text:
///////////////////////////////////////////////////////////////////////////////
//  Copyright 2012 John Maddock.
//  Copyright Christopher Kormanyos 2013. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_MP_DETAIL_DYNAMIC_ARRAY_HPP
  #define BOOST_MP_DETAIL_DYNAMIC_ARRAY_HPP

  #include <vector>
  #include <boost/multiprecision/detail/rebind.hpp>

  namespace boost { namespace multiprecision { namespace backends { namespace detail
  {
    template <class value_type, const boost::uint32_t elem_number, class my_allocator>
    struct dynamic_array : public std::vector<value_type, typename rebind<value_type, my_allocator>::type>
    {
       dynamic_array() :
         std::vector<value_type, typename rebind<value_type, my_allocator>::type>(static_cast<typename std::vector<value_type, typename rebind<value_type, my_allocator>::type>::size_type>(elem_number), static_cast<value_type>(0))
       {
       }

             value_type* data()       { return &(*(this->begin())); }
       const value_type* data() const { return &(*(this->begin())); }
    };
  } } } } // namespace boost::multiprecision::backends::detail

#endif // BOOST_MP_DETAIL_DYNAMIC_ARRAY_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo