text:
#include "tcp_server.h"
#include "utility.h"
#include <thread>
#include <atomic>
#include <boost/function.hpp>
#include <boost/exception/diagnostic_information.hpp>

namespace Akumuli {

//                       //
//     Telnet Session    //
//                       //

std::string make_unique_session_name() {
    static std::atomic<int> counter = {0};
    std::stringstream str;
    str << "tcp-session-" << counter.fetch_add(1);
    return str.str();
}

/** Server session that handles RESP messages.
 *  Must be created in the heap.
  */
template<class ProtocolT>
class TelnetSession : public ProtocolSession, public std::enable_shared_from_this<TelnetSession<ProtocolT>> {
    // TODO: Unique session ID
    enum {
        BUFFER_SIZE = ProtocolT::RDBUF_SIZE,  //< Buffer size
    };
    const bool                      parallel_;
    IOServiceT*                     io_;
    SocketT                         socket_;
    StrandT                         strand_;
    std::shared_ptr<DbSession>      spout_;
    ProtocolT                       parser_;
    Logger                          logger_;

public:
    typedef Byte* BufferT;

    TelnetSession(IOServiceT *io, std::shared_ptr<DbSession> spout, bool parallel)
        : parallel_(parallel)
        , io_(io)
        , socket_(*io)
        , strand_(*io)
        , spout_(spout)
        , parser_(spout)
    , logger_(make_unique_session_name())
    {
        logger_.info() << "Session created";
        parser_.start();
    }

    ~TelnetSession() {
        logger_.info() << "Session destroyed";
    }

    virtual SocketT& socket() {
        return socket_;
    }

    virtual void start() {
        BufferT buf;
        size_t buf_size;
        std::tie(buf, buf_size) = get_next_buffer();
        if (parallel_) {
            socket_.async_read_some(
                    boost::asio::buffer(buf, buf_size),
                    strand_.wrap(
                        boost::bind(&TelnetSession<ProtocolT>::handle_read,
                                    this->shared_from_this(),
                                    buf,
                                    boost::asio::placeholders::error,
                                    boost::asio::placeholders::bytes_transferred)));
        } else {
            // Strand is not used here
            socket_.async_read_some(
                    boost::asio::buffer(buf, buf_size),
                    boost::bind(&TelnetSession<ProtocolT>::handle_read,
                                this->shared_from_this(),
                                buf,
                                boost::asio::placeholders::error,
                                boost::asio::placeholders::bytes_transferred));
        }
    }

    virtual ErrorCallback get_error_cb() {
        logger_.info() << "Creating error handler for session";
        auto self = this->shared_from_this();
        auto weak = std::weak_ptr<TelnetSession>(self);
        auto fn = [weak](aku_Status status, u64) {
            auto session = weak.lock();
            if (session) {
                const char* msg = aku_error_message(status);
                session->logger_.trace() << msg;
                boost::asio::streambuf stream;
                std::ostream os(&stream);
                os << session->parser_.error_repr(ProtocolT::DB, msg);
                boost::asio::async_write(session->socket_,
                                         stream,
                                         boost::bind(&TelnetSession<ProtocolT>::handle_write_error,
                                                     session,
                                                     boost::asio::placeholders::error));
            }
        };
        return ErrorCallback(fn);
    }

private:
    /** Allocate new buffer.
      */
    std::tuple<BufferT, size_t> get_next_buffer() {
        Byte *buffer = parser_.get_next_buffer();
        return std::make_tuple(buffer, BUFFER_SIZE);
    }

    void handle_read(BufferT buffer,
                     boost::system::error_code error,
                     size_t nbytes)
    {
        if (error) {
            logger_.error() << error.message();
            parser_.close();
        } else {
            try {
                auto response = parser_.parse_next(buffer, static_cast<u32>(nbytes));
                if(response.is_available()) {
                    boost::asio::streambuf stream;
                    std::ostream os(&stream);
                    os << ProtocolT::PARSE, response.get_body();
                    boost::asio::async_write(socket_, stream,
                                             boost::bind(&TelnetSession::handle_write,
                                                         this->shared_from_this(),
                                                         boost::asio::placeholders::error)
                                             );
                }
                start();
            } catch (StreamError const& stream_error) {
                // This error is related to client so we need to send it back
                logger_.error() << stream_error.what();
                boost::asio::streambuf stream;
                std::ostream os(&stream);
                os << parser_.error_repr(ProtocolT::PARSE, stream_error.what());
                boost::asio::async_write(socket_, stream,
                                         boost::bind(&TelnetSession::handle_write_error,
                                                     this->shared_from_this(),
                                                     boost::asio::placeholders::error)
                                         );
            } catch (DatabaseError const& dberr) {
                // Database error
                logger_.error() << boost::current_exception_diagnostic_information();
                boost::asio::streambuf stream;
                std::ostream os(&stream);
                os << parser_.error_repr(ProtocolT::DB, dberr.what());
                boost::asio::async_write(socket_, stream,
                                         boost::bind(&TelnetSession::handle_write_error,
                                                     this->shared_from_this(),
                                                     boost::asio::placeholders::error)
                                         );
            } catch (...) {
                // Unexpected error
                logger_.error() << boost::current_exception_diagnostic_information();
                boost::asio::streambuf stream;
                std::ostream os(&stream);
                os << parser_.error_repr(ProtocolT::ERR, boost::current_exception_diagnostic_information());
                boost::asio::async_write(socket_, stream,
                                         boost::bind(&TelnetSession::handle_write_error,
                                                     this->shared_from_this(),
                                                     boost::asio::placeholders::error)
                                         );
            }
        }
    }

    void handle_write(boost::system::error_code error) {
        if (error) {
            logger_.error() << "Error sending error message to client";
            logger_.error() << error.message();
            parser_.close();
        }
    }

    void handle_write_error(boost::system::error_code error) {
        if (!error) {
            logger_.info() << "Clean shutdown";
            boost::system::error_code shutdownerr;
            socket_.shutdown(SocketT::shutdown_both, shutdownerr);
            if (shutdownerr) {
                logger_.error() << "Shutdown error: " << shutdownerr.message();
            }
        } else {
            logger_.error() << "Error sending error message to client";
            logger_.error() << error.message();
            parser_.close();
        }
    }
};

typedef TelnetSession<RESPProtocolParser> RESPSession;
typedef TelnetSession<OpenTSDBProtocolParser> OpenTSDBSession;

//                           //
//     Protocol builders     //
//                           //

struct RESPSessionBuilder : ProtocolSessionBuilder {
    bool parallel_;

    RESPSessionBuilder(bool parallel=true)
        : parallel_(parallel)
    {
    }

    virtual std::shared_ptr<ProtocolSession> create(IOServiceT *io, std::shared_ptr<DbSession> session) {
        std::shared_ptr<ProtocolSession> result;
        result.reset(new RESPSession(io, session, parallel_));
        return result;
    }

    virtual std::string name() const {
        return "RESP";
    }
};

struct OpenTSDBSessionBuilder : ProtocolSessionBuilder {
    bool parallel_;

    OpenTSDBSessionBuilder(bool parallel=true)
        : parallel_(parallel)
    {
    }

    virtual std::shared_ptr<ProtocolSession> create(IOServiceT *io, std::shared_ptr<DbSession> session) {
        std::shared_ptr<ProtocolSession> result;
        result.reset(new OpenTSDBSession(io, session, parallel_));
        return result;
    }

    virtual std::string name() const {
        return "OpenTSDB";
    }
};

std::unique_ptr<ProtocolSessionBuilder> ProtocolSessionBuilder::create_resp_builder(bool parallel) {
    std::unique_ptr<ProtocolSessionBuilder> res;
    res.reset(new RESPSessionBuilder(parallel));
    return res;
}

std::unique_ptr<ProtocolSessionBuilder> ProtocolSessionBuilder::create_opentsdb_builder(bool parallel) {
    std::unique_ptr<ProtocolSessionBuilder> res;
    res.reset(new OpenTSDBSessionBuilder(parallel));
    return res;
}

//                      //
//     Tcp Acceptor     //
//                      //

TcpAcceptor::TcpAcceptor(// Server parameters
                        std::vector<IOServiceT *> io, EndpointT endpoint,
                        // Storage & pipeline
                        std::shared_ptr<DbConnection> connection ,
                        bool parallel)
    //: parallel_(parallel)
    : acceptor_(own_io_, endpoint)
    , protocol_(ProtocolSessionBuilder::create_resp_builder(true))
    , sessions_io_(io)
    , connection_(connection)
    , io_index_{0}
    , start_barrier_(2)
    , stop_barrier_(2)
    , logger_("tcp-acceptor")
    , iothread_started_(false)
{
    logger_.info() << "Server created!";
    logger_.info() << "Endpoint: " << endpoint;

    // Blocking I/O services
    for (auto io: sessions_io_) {
        sessions_work_.emplace_back(*io);
    }
}

TcpAcceptor::TcpAcceptor(
        std::vector<IOServiceT*> io,
        EndpointT endpoint,
        std::unique_ptr<ProtocolSessionBuilder> protocol,
        std::shared_ptr<DbConnection> connection,
        bool parallel)
    //: parallel_(parallel)
    : acceptor_(own_io_, endpoint)
    , protocol_(std::move(protocol))
    , sessions_io_(io)
    , connection_(connection)
    , io_index_{0}
    , start_barrier_(2)
    , stop_barrier_(2)
    , logger_("tcp-acceptor")
    , iothread_started_(false)
{
    logger_.info() << "Server created!";
    logger_.info() << "Endpoint: " << endpoint;

    // Blocking I/O services
    for (auto io: sessions_io_) {
        sessions_work_.emplace_back(*io);
    }
}

TcpAcceptor::~TcpAcceptor() {
    logger_.info() << "TCP acceptor destroyed";
}

void TcpAcceptor::start() {
    WorkT work(own_io_);

    // Run detached thread for accepts
    auto self = shared_from_this();
    std::thread accept_thread([self]() {
#ifdef __gnu_linux__
        // Name the thread
        std::string thread_name = "TCP-accept-" + self->protocol_->name();
        auto thread = pthread_self();
        pthread_setname_np(thread, thread_name.c_str());
#endif
        self->logger_.info() << "Starting acceptor worker thread";
        self->start_barrier_.wait();
        self->logger_.info() << "Acceptor worker thread have started";

        try {
            self->own_io_.run();
        } catch (...) {
            self->logger_.error() << "Error in acceptor worker thread: " << boost::current_exception_diagnostic_information();
            throw;
        }

        self->logger_.info() << "Stopping acceptor worker thread";
        self->stop_barrier_.wait();
        self->logger_.info() << "Acceptor worker thread have stopped";
    });
    accept_thread.detach();

    start_barrier_.wait();
    iothread_started_ = true;

    logger_.info() << "Start listening";
    _start();
}

void TcpAcceptor::_run_one() {
    own_io_.run_one();
}

void TcpAcceptor::_start() {
    std::shared_ptr<ProtocolSession> session;
    auto con = connection_.lock();
    if (con) {
        std::shared_ptr<DbSession> spout = con->create_session();
        IOServiceT* io = sessions_io_.at(static_cast<size_t>(io_index_++) % sessions_io_.size());
        session = protocol_->create(io, spout);
    } else {
        logger_.error() << "Database was already closed";
    }
    // attach session to spout
    // run session
    acceptor_.async_accept(
                session->socket(),
                boost::bind(&TcpAcceptor::handle_accept,
                            this,
                            session,
                            boost::asio::placeholders::error)
                );
}

void TcpAcceptor::stop() {
    logger_.info() << "Stopping acceptor";
    acceptor_.close();
    own_io_.stop();
    sessions_work_.clear();
    logger_.info() << "Trying to stop acceptor";
    stop_barrier_.wait();
    logger_.info() << "Acceptor successfully stopped";
}

void TcpAcceptor::_stop() {
    logger_.info() << "Stopping acceptor (test runner)";
    acceptor_.close();
    if (!iothread_started_) {
        // If I/O thread wasn't started we have to spin the loop
        // to run pending I/O handlers to prevent memory leak.
        // This code path should only work in unit-tests.
        own_io_.poll();
    }
    own_io_.stop();
    sessions_work_.clear();
}

std::string TcpAcceptor::name() const {
    return protocol_->name();
}

void TcpAcceptor::handle_accept(std::shared_ptr<ProtocolSession> session, boost::system::error_code err) {
    if (AKU_LIKELY(!err)) {
        session->start();
        _start();
    } else {
        logger_.error() << "Acceptor error " << err.message();
    }
}

//                    //
//     Tcp Server     //
//                    //

TcpServer::TcpServer(std::shared_ptr<DbConnection> connection, int concurrency, EndpointT ep, TcpServer::Mode mode)
    : connection_(connection)
    , barrier(static_cast<u32>(concurrency) + 1)
    , stopped{0}
    , logger_("tcp-server")
{
    logger_.info() << "TCP server created, concurrency: " << concurrency;
    if (mode == Mode::EVENT_LOOP_PER_THREAD) {
        for(int i = 0; i < concurrency; i++) {
            IOPtr ptr = IOPtr(new IOServiceT(1));
            iovec.push_back(ptr.get());
            ios_.push_back(std::move(ptr));
        }
    } else {
        IOPtr ptr = IOPtr(new IOServiceT(static_cast<size_t>(concurrency)));
        iovec.push_back(ptr.get());
        ios_.push_back(std::move(ptr));
    }
    bool parallel = mode == Mode::SHARED_EVENT_LOOP;
    auto con = connection_.lock();
    if (con) {
        auto serv = std::make_shared<TcpAcceptor>(iovec, ep, con, parallel);
        serv->start();
        acceptors_.push_back(serv);
    } else {
        logger_.error() << "Can't start TCP server, database closed";
        std::runtime_error err("DB connection closed");
        BOOST_THROW_EXCEPTION(err);
    }
}

TcpServer::TcpServer(std::shared_ptr<DbConnection> connection,
                     int concurrency,
                     std::map<EndpointT, std::unique_ptr<ProtocolSessionBuilder> > protocol_map,
                     TcpServer::Mode mode)
    : connection_(connection)
    , barrier(static_cast<u32>(concurrency) + 1)
    , stopped{0}
    , logger_("tcp-server")
{
    logger_.info() << "TCP server created, concurrency: " << concurrency;
    if (mode == Mode::EVENT_LOOP_PER_THREAD) {
        for(int i = 0; i < concurrency; i++) {
            IOPtr ptr = IOPtr(new IOServiceT(1));
            iovec.push_back(ptr.get());
            ios_.push_back(std::move(ptr));
        }
    } else {
        IOPtr ptr = IOPtr(new IOServiceT(static_cast<size_t>(concurrency)));
        iovec.push_back(ptr.get());
        ios_.push_back(std::move(ptr));
    }
    bool parallel = mode == Mode::SHARED_EVENT_LOOP;
    auto con = connection_.lock();
    for (auto& kv: protocol_map) {
        EndpointT endpoint = kv.first;
        auto protocol = std::move(kv.second);
        logger_.info() << "Create acceptor for " << protocol->name() << ", endpoint: " << endpoint;
        if (con) {
            auto serv = std::make_shared<TcpAcceptor>(iovec, endpoint, std::move(protocol), con, parallel);
            serv->start();
            acceptors_.push_back(serv);
        } else {
            logger_.error() << "Can't start TCP server, database closed";
            std::runtime_error err("DB connection closed");
            BOOST_THROW_EXCEPTION(err);
        }
    }
}

TcpServer::~TcpServer() {
    logger_.info() << "TCP server destroyed";
}

void TcpServer::start(SignalHandler* sig, int id) {

    auto self = shared_from_this();
    sig->add_handler(boost::bind(&TcpServer::stop, self), id);

    auto iorun = [self](IOServiceT& io, int cnt) {
        auto fn = [self, &io, cnt]() {
#ifdef __gnu_linux__
            // Name the thread
            auto thread = pthread_self();
            pthread_setname_np(thread, "TCP-worker");
#endif
            Logger logger("tcp-server-worker");
            try {
                logger.info() << "Event loop " << cnt << " started";
                io.run();
                logger.info() << "Event loop " << cnt << " stopped";
                self->barrier.wait();
            } catch (RESPError const& e) {
                logger.error() << e.what();
                throw;
            } catch (...) {
                logger.error() << "Error in event loop " << cnt << ": " << boost::current_exception_diagnostic_information();
                throw;
            }
            logger.info() << "Worker thread " << cnt << " stopped";
        };
        return fn;
    };

    int cnt = 0;
    for (auto io: iovec) {
        std::thread iothread(iorun(*io, cnt++));
        iothread.detach();
    }
}

void TcpServer::stop() {
    if (stopped++ == 0) {
        for (auto serv: acceptors_) {
            serv->stop();
            logger_.info() << "TcpServer " << serv->name() << " stopped";
        }

        for(auto& svc: ios_) {
            svc->stop();
            logger_.info() << "I/O service stopped";
        }

        barrier.wait();
        logger_.info() << "I/O threads stopped";
    }
}

static Logger s_logger_("tcp-server");

struct TcpServerBuilder {

    TcpServerBuilder() {
        ServerFactory::instance().register_type("TCP", *this);
    }

    std::shared_ptr<Server> operator () (std::shared_ptr<DbConnection> con,
                                         std::shared_ptr<ReadOperationBuilder>,
                                         const ServerSettings& settings) {
        auto nworkers = settings.nworkers;
        auto ncpus = std::thread::hardware_concurrency();
        if (ncpus <= 4) {
            nworkers = 1;
        } else if (ncpus <= 8) {
            nworkers = static_cast<int>(ncpus - 2);
        } else {
            nworkers = static_cast<int>(ncpus - 4);
        }
        if (nworkers >= AKU_MAX_THREADS) {
            nworkers = AKU_MAX_THREADS - 4;
        }
        std::map<EndpointT, std::unique_ptr<ProtocolSessionBuilder>> protocol_map;
        for (const auto& protocol: settings.protocols) {
            std::unique_ptr<ProtocolSessionBuilder> inst;
            if (protocol.name == "RESP") {
                inst = ProtocolSessionBuilder::create_resp_builder(true);
            } else if (protocol.name == "OpenTSDB") {
                inst = ProtocolSessionBuilder::create_opentsdb_builder(true);
            } else {
                s_logger_.error() << "Unknown protocol " << protocol.name;
            }
            protocol_map[protocol.endpoint] = std::move(inst);
        }
        return std::make_shared<TcpServer>(con, nworkers, std::move(protocol_map));
    }
};

static TcpServerBuilder reg_type;

}

max_stars_repo_name: webfolderio/akumuli

max_issues_repo_name: webfolderio/akumuli

max_forks_repo_name: webfolderio/akumuli


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

#include <Eigen/Core>
#include <catch2/catch_test_macros.hpp>
#include <catch2/matchers/catch_matchers_floating.hpp>

#include "num_collect/interp/kernel/euclidean_distance.h"
#include "num_collect/interp/kernel/gaussian_rbf.h"
#include "num_collect/interp/kernel/rbf_kernel.h"

TEST_CASE("num_collect::interp::kernel::calc_kernel_mat") {
    using num_collect::interp::kernel::calc_kernel_mat;
    using num_collect::interp::kernel::euclidean_distance;
    using num_collect::interp::kernel::gaussian_rbf;
    using num_collect::interp::kernel::rbf_kernel;

    SECTION("calculate") {
        const auto kernel = rbf_kernel<euclidean_distance<Eigen::Vector3d>,
            gaussian_rbf<double>>();
        const auto list = std::vector<Eigen::Vector3d,
            Eigen::aligned_allocator<Eigen::Vector3d>>{
            Eigen::Vector3d(1.234, 2.345, 3.456),
            Eigen::Vector3d(1.357, 2.468, 3.579)};

        const Eigen::MatrixXd mat = calc_kernel_mat(kernel, list);

        REQUIRE(mat.rows() == 2);
        REQUIRE(mat.cols() == 2);

        const double non_diagonal_elem =
            std::exp(-(list[0] - list[1]).squaredNorm());
        REQUIRE_THAT(mat(0, 0), Catch::Matchers::WithinRel(1.0));
        REQUIRE_THAT(mat(0, 1), Catch::Matchers::WithinRel(non_diagonal_elem));
        REQUIRE_THAT(mat(1, 0), Catch::Matchers::WithinRel(non_diagonal_elem));
        REQUIRE_THAT(mat(1, 1), Catch::Matchers::WithinRel(1.0));
    }
}

ext: cpp


text:
#include "BotPCH.h"
#include "Config.h"
#ifdef _MSC_VER
#  pragma warning (push)
#  pragma warning (disable: 4127 4701 4819)
#endif
#include <boost/lexical_cast.hpp>
#ifdef _MSC_VER
#  pragma warning (pop)
#endif
#include <iostream>

namespace gideon { namespace bot {

namespace
{

template <typename T>
inline T toInteger(const std::string& s)
{
    try {
        return boost::lexical_cast<T>(s.c_str());
    }
    catch(const boost::bad_lexical_cast &) {}
    return 0;
}

void parseAddress(std::string& ip, uint16_t& port,
    const std::string& address)
{
    ip.clear();
    port = 0;

    const size_t pos = address.find_first_of(':');
    if (pos != std::string::npos) {
        ip = address.substr(0, pos);
        port = toInteger<uint16_t>(address.substr(pos + 1));
    }
}

} // namespace

// = Config

Config::Config() :
    startAccountId_(1),
    numberOfClients_(1),
    serverPort_(0),
    shouldRetry_(false),
    verbose_(false)
{
}

bool Config::parseArgs(int argc, char* argv[])
{
    if (argc < 2) {
        return false;
    }

    bool isOk = true;
    for (int i = 1; i < argc; ++i) {
        const std::string arg(argv[i]);
        if (arg == "-?") {
            isOk = false;
            break;
        }

        if (arg == "-v") {
            verbose_ = true;
        }
        else if (arg == "-r") {
            shouldRetry_ = true;
        }
        else if (arg.compare(0, 3, "-s=") == 0) {
            parseAddress(serverAddress_, serverPort_, arg.substr(3));
        }
        else if (arg.compare(0, 3, "-a=") == 0) {
            startAccountId_ = toInteger<AccountId>(arg.substr(3));
        }
        else if (arg.compare(0, 3, "-c=") == 0) {
            numberOfClients_ = toInteger<uint16_t>(arg.substr(3));
        }
        else {
            std::cerr << "Unknown option '" << arg.c_str() << "', ignoring it.\n";
        }
    }

    if (serverAddress_.empty() || (serverPort_ == 0)) {
        isOk = false;
    }
    else if (numberOfClients_ <= 0) {
        isOk = false;
    }

    return isOk;
}

void Config::printUsage()
{
    std::cout << "== Gideon Bot ==\n" <<
        "USAGE: Bot [options]\n" <<
        "  -s=<address:port> server address\n" <<
        "  -a=<account-id> start AccountId(default: 1)\n" <<
        "  -c=<count> the number of clients(default: 1)\n" <<
        "  -r retry if failed(default: off)\n" <<
        "  -v verbose (default: off)\n" <<
        " ex)\n" <<
        "   Bot -s=127.0.0.1:10000 -a=1 -c=100 -v\n";
}

}} // namespace gideon { namespace bot {

max_stars_repo_name: mark-online/server

max_issues_repo_name: mark-online/server

max_forks_repo_name: mark-online/server


text:
// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

// Includes ====================================================================
#include <AxInit.h>

// Using =======================================================================
using namespace boost::python;

// Module ======================================================================
void Export_pyste_src_AxInit()
{
    class_< AxInit >("AxInit", init<  >())
        .def(init< const AxInit& >())
        .def(init< const char* >())
    ;

}

max_issues_repo_name: DIT-Tools/pyaaf


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2010.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#include <mpllibs/metamonad/letrec.hpp>
#include <mpllibs/metamonad/lambda_c.hpp>
#include <mpllibs/metamonad/eval_syntax.hpp>
#include <mpllibs/metamonad/lazy.hpp>
#include <mpllibs/metamonad/if_.hpp>
#include <mpllibs/metamonad/apply.hpp>
#include <mpllibs/metamonad/syntax.hpp>

#include <boost/test/unit_test.hpp>

#include "common.hpp"

#include <boost/mpl/minus.hpp>
#include <boost/mpl/assert.hpp>

BOOST_AUTO_TEST_CASE(test_letrec)
{
  using boost::mpl::equal_to;
  using boost::mpl::minus;

  using mpllibs::metamonad::letrec;
  using mpllibs::metamonad::if_;
  using mpllibs::metamonad::lambda_c;
  using mpllibs::metamonad::lazy;
  using mpllibs::metamonad::syntax;
  using mpllibs::metamonad::eval_syntax;
  using mpllibs::metamonad::apply;

  // name is replaced with a nullary metafunction evaluating to the
  // substituted expression
  // test_letrec_name
  BOOST_MPL_ASSERT((
    equal_to<int13, eval_syntax<letrec<x, syntax<int13>, syntax<x> > >::type>
  ));

  // test_letrec_not_name
  BOOST_MPL_ASSERT((
    equal_to<
      int11,
      eval_syntax<letrec<x, syntax<int13>, syntax<int11> > >::type
    >
  ));

  // test_template
  BOOST_MPL_ASSERT((
    equal_to<
      int26,
      eval_syntax<
        letrec<x, syntax<int13>, syntax<lazy_double_value<x> > >
      >::type
    >
  ));

  // test_recursion
  BOOST_MPL_ASSERT((
    equal_to<
      int24,
      eval_syntax<
        letrec<
          x,
          syntax<
            lambda_c<
              y,
              if_<
                lazy_equal_to<y, int0>,
                int1,
                lazy_times<apply<x, minus<y, int1> >, y>
              >
            >
          >,
          syntax<apply<x, int4> >
        >
      >::type
    >
  ));

  // test_letrec_lazy
  BOOST_MPL_ASSERT((
    equal_to<
      int11,
      eval_syntax<
        letrec<x, syntax<int2>, syntax<lazy<minus<int13, x> > > >
      >::type
    >
  ));
}


text:
//   GUM: GAMBIT Universal Model Machine
//   ************************************
///  \file
///
///  Definitions of Feynrules class
///
///  **********************************
///
///  \author Sanjay Bloor
///          (sanjay.bloor12@imperial.ac.uk)
///  \date 2018, 2019, 2020
///
///  \author Tomas Gonzalo
///          (tomas.gonzalo@monash.edu)
///  \date 2019 July
///
///  ***********************************

#include <set>
#include <algorithm>
#include <cstring>
#include <fstream>

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

#include "feynrules.hpp"

namespace GUM
{

  // Feynrules constructor, loads Feynrules and model
  FeynRules::FeynRules(std::string model, std::string base_model) : Math_Package(model)
  {
    // Math_Package constructor already creates the WSTP link

    try
    {
      // Load Feynrules
      load_feynrules();

      // Load model
      load_model(model, base_model);
    }
    catch(...) { throw; }
  }

  // Load Feynrules
  void FeynRules::load_feynrules()
  {

    std::cout << "Loading FeynRules... ";
    std::cout.flush();

    std::string input = "$FeynRulesPath = SetDirectory[\"" + std::string(FEYNRULES_PATH) + "\"]";

    send_to_math(input);

    const char* out;
    if (!WSGetString(link, &out))
    {
        throw std::runtime_error("Error loading FeynRules. Please check that Mathematica\n"
                                 "is working and that FeynRules actually lives where CMake put it, in:\n"
                                 "  " + std::string(FEYNRULES_PATH) + "\n"
                                 "Please try rebuilding.");
    }
    else
    {
        std::cout << "FeynRules loaded from " << out << "." << std::endl;
    }

    // Need to run FR serially, as it bugs out in parallel
    input = "FR$Parallel=False;";
    send_to_math(input);

    input = "<<FeynRules`";
    send_to_math(input);

  }

  void FeynRules::load_model(std::string model, std::string base_model)
  {

    std::cout << "Loading model " + model + " in FeynRules";
    std::cout.flush();
    if (not base_model.empty()) { std::cout << ", piggybacking off of " << base_model; }
    std::cout << "... " << std::endl;

    std::string modelpath;

    // Check to see if the model is in the FeynRules directory
    modelpath = std::string(FEYNRULES_PATH) + "/Models/" + model + "/" + model + ".fr";
    std::ifstream modelpath1(modelpath.c_str());

    // If it's not in the FeynRules directory, try the gum Models dir...
    if (!modelpath1.good())
    {
        modelpath = std::string(GUM_DIR) + "/Models/" + model + "/" + model + ".fr";
        std::ifstream modelpath2(modelpath.c_str());
        if (!modelpath2.good())
        {
            throw std::runtime_error("GUM Error: Unable to find the model " + model + " in either the "
                                     "FeynRules model directory, or the GUM model directory!");
        }
    }

    // Same process for the base_model
    if (!base_model.empty())
    {
        std::string basepath = std::string(FEYNRULES_PATH) + "/Models/" + base_model + "/" + base_model + ".fr";

        std::ifstream basepath1(basepath.c_str());
        if (!basepath1.good())
        {
            basepath = std::string(GUM_DIR) + "/Models/" + base_model + "/" + base_model + ".fr";
            std::ifstream basepath2(basepath.c_str());
            if (!basepath2.good())
            {
            throw std::runtime_error("GUM Error: Unable to find the base model " + base_model + " in either"
                                     " the FeynRules model directory, or the GUM model directory!");
            }
        }
        // Fire off the LoadModel command with the model and the base model.
        std::string command = "LoadModel[\"" + basepath + "\",\"" + modelpath + "\"]";
        send_to_math(command);
    }
    else
    {
        // Fire off the LoadModel command with just the model.
        std::string command = "LoadModel[\"" + modelpath + "\"]";
        send_to_math(command);
    }

    // Check the model has been loaded by querying the model name. If it has changed from the default then we're set.
    // TODO: need to check for duplicate definitions of gauge groups, field contents etc - this makes gum freeze
    std::string modelname = get_modelname();

    std::string tomatch = "Models" + model + model;
    if (modelname == tomatch)
        throw std::runtime_error("FeynRules Error: Could not load model " + model + ". Please check your FeynRules file.");
    else if ((modelname == "Standard Model") and (base_model.empty()))
        throw std::runtime_error("FeynRules Error: GUM is for BSM physics, yo!");
    else if ((modelname == "Standard Model") and (not base_model.empty()))
        throw std::runtime_error("FeynRules Error: GUM tried to import something on top of the Standard Model, but your model file did not import properly. Please check it.");
    else if ((modelname == "M$ModelName"))
        throw std::runtime_error("FeynRules Error: models not loaded correctly, given as 'M$ModelName'. Please check your FeynRules files.");
    // All good. else {
    std::cout << "Model " + model + " loaded successfully, with model name " << modelname << "." << std::endl;
    //}
  }

  // The model may have a different "internal" name than what's on the package.
  // Need this info for output files, etc.
  std::string FeynRules::get_modelname()
  {
    std::string command = "M$ModelName";
    send_to_math(command);

    std::string modelname;
    get_from_math(modelname);
    return modelname;
  }

  /// Load a restriction file up. Firstly tries to find it in the model directory,
  /// then the base_model directory.
  void FeynRules::load_restriction(std::string model, std::string base_model, std::string rst)
  {

    std::cout << "Attempting to load restriction " + rst + "... " << std::endl;

    std::string respath;
    respath = std::string(FEYNRULES_PATH) + "/Models/" + model + "/" + rst + ".rst";
    std::ifstream path1(respath.c_str());

    // If it's not in the FeynRules directory, try the gum Models dir...
    if (!path1.good())
    {
        respath = std::string(GUM_DIR) + "/Models/" + model + "/" + rst + ".rst";
        std::ifstream path2(respath.c_str());

        // If it's not in the model directory, try the base_model...
        if (!path2.good())
        {
            if (!base_model.empty())
            {
                respath = std::string(FEYNRULES_PATH) + "/Models/" + base_model + "/" + rst + ".rst";

                std::ifstream path3(respath.c_str());
                if (!path3.good())
                {
                    respath = std::string(GUM_DIR) + "/Models/" + base_model + "/" + rst + ".rst";
                    std::ifstream path4(respath.c_str());
                    if (!path4.good())
                    {
                    throw std::runtime_error("GUM Error: Unable to find the restriction " + rst + " in either\n"
                                             "the FeynRules model directory, or the GUM model directory,"
                                             "for both the model *and* the base_model!");
                    }
                }
            }
            else
            {
                throw std::runtime_error("GUM Error: Unable to find the restriction " + rst + " in either\n"
                                         "the FeynRules model directory, or the GUM model directory!");
            }
        }
    }

    std::cout << "Found restriction file at " << respath << std::endl;

    // LoadRestriction command.
    std::string command = "LoadRestriction[\"" + respath + "\"]";
    send_to_math(command);

    // Check restrictions are ok
    command = "Length[M$Restrictions]";
    send_to_math(command);

    int out;
    get_from_math(out);
    if (out == 0)
        throw std::runtime_error("FeynRules Error: No restrictions loaded. Please check "
                                 "your .gum file and \nthat your .rst files are in the "
                                 "correct place.");

    std::cout << "Restriction " + rst + " loaded successfully." << std::endl;
  }

  // Check to see the Lagrangian returns something sensible
  void FeynRules::check_lagrangian(std::string LTot)
  {
    std::cout << "Checking the Lagrangian... you have specified the following: ";
    std::cout << LTot << std::endl;

    std::string command = "Head@("+LTot+") // ToString";
    send_to_math(command);

    std::string entry;
    get_from_math(entry);
    if (entry == "Symbol")
    {
        command = LTot + "// ToString";
        send_to_math(command);
        get_from_math(entry);
        if (entry == LTot)
        {
            std::stringstream ss;
            ss << "Lagrangian has not been loaded successfully." << std::endl;
            ss << "Please check your .gum file and .fr file(s)." << std::endl;
            throw std::runtime_error(ss.str());
        }
    }

    std::cout << "Lagrangian seems OK..." << std::endl;
  }

  // Check a model is Hermitian (it should be...)
  // Also check for correct normalisation
  void FeynRules::check_herm(std::string LTot)
  {

    std::cout << "Checking the model is Hermitian... ";
    std::cout.flush();

    std::string command = "ch = CheckHermiticity[" + LTot + "]";
    send_to_math(command);

    command = "Length[ch]";
    send_to_math(command);

    int lench;
    get_from_math(lench);

    if (lench == 0)
    {
        std::cout << "Your Lagrangian is Hermitian." << std::endl;
    }
    else
    {
        std::stringstream ss;
        ss << "Your Lagrangian is not Hermitian." << std::endl;
        ss << "FeynRules found " + std::to_string(lench) + " vertices in L-HC[L]." << std::endl;
        ss << "Please check your FeynRules file." << std::endl;
        throw std::runtime_error(ss.str());
    }

    std::cout << "Checking kinetic and mass terms are properly diagonalised..." << std::endl;

    // Check for kinetic term diagonalisation...
    std::string isnorm;
    command = "CheckDiagonalKineticTerms[" + LTot + "]";
    send_to_math(command);

    get_from_math(isnorm);
    if (isnorm != "True")
    {
        std::stringstream ss;
        ss << "Your Lagrangian has kinetic terms that are not correctly diagonalised!" << std::endl;
        ss << "Please check your FeynRules file and the FeynRules manual." << std::endl;
        throw std::runtime_error(ss.str());
    }

    std::cout << "Kinetic terms are diagonal... ";
    std::cout.flush();

    // Check for mass term diagonalisation...
    command = "CheckDiagonalMassTerms[" + LTot + "]";
    send_to_math(command);

    get_from_math(isnorm);
    if (isnorm != "True")
    {
        std::stringstream ss;
        ss << "Your Lagrangian has mass terms that are not correctly diagonalised!" << std::endl;
        ss << "Please check your FeynRules file and the FeynRules manual." << std::endl;
        throw std::runtime_error(ss.str());
    }

    std::cout << "Mass terms are diagonal... ";
    std::cout.flush();

    // Kinetic term normalisation.
    // We ignore the SM neutrinos because they don't have a kinetic term under the SM.
    command = "CheckKineticTermNormalisation[" + LTot + ", Free -> {ve,vm,vt}] == Null // ToString";
    send_to_math(command);

    get_from_math(isnorm);
    if (isnorm == "True")
    {
        std::stringstream ss;
        ss << "Your Lagrangian is not correctly normalised!" << std::endl;
        ss << "Please check your FeynRules file and the FeynRules manual." << std::endl;
        throw std::runtime_error(ss.str());
    }

    std::cout << "All good." << std::endl;

  }

  // Gets the 'PartList' -- this contains all particles in the model.
  void FeynRules::get_partlist(std::vector<Particle> &partlist)
  {

    std::cout << "Extracting particles from FeynRules model." << std::endl;

    // Command to get a list of lists of lists of lists(!) with particle info.
    std::string command = "pl = PartList;";
    send_to_math(command);

    // Find out how many particles we have to get.
    command = "Length[pl]";
    send_to_math(command);

    std::stringstream ss;

    int lenpl;
    get_from_math(lenpl);
    std::cout << "Found " << lenpl << " particle sets." << std::endl;

    // Get to parsing this monster.
    for (int i=0; i<lenpl; i++)
    {

        // First things first, check to see if we are dealing with multiplets.
        // e.g., l = (e, mu, tau).
        int numelements;
        command = "Length[pl[[" + std::to_string(i+1) + ",2]]]";
        send_to_math(command);
        get_from_math(numelements);

        for (int j=0; j<numelements; j++)
        {

            // Initialise all properties we wish to find out about a particle.
            std::string name;
            std::string antiname;
            std::string spin;
            std::string fullname;
            std::string eaten;
            std::string mass;
            // Needs to initialise these to suppress compiler warnings.
            int color = 1;
            int chargeX3 = 0;
            int spinX2 = 0;
            int pdg;
            bool SM;

            // Firstly, find the name
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",1]]";
            send_to_math(command);
            get_from_math(name);

            // Then, the antiparticle name
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",2]]";
            send_to_math(command);
            get_from_math(antiname);

            // Next, find out the spin.
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",3]]";
            send_to_math(command);
            get_from_math(spin);
            if (spin == "V")
            {
                spinX2 = 2;
            }
            else if (spin == "F")
            {
                spinX2 = 1;
            }
            else if (spin == "S")
            {
                spinX2 = 0;
            }
            else if (spin == "T")
            {
                spinX2 = 4;
            }
            // Don't try and parse ghosts; it'll give us an error. We also
            // don't care about them from a pheno (GUM) standpoint.
            else if (spin == "U")
            {
                continue;
            }

            // PDG code.
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",9]]";
            send_to_math(command);
            get_from_math(pdg);

            // "Full name"
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",10]]";
            send_to_math(command);
            get_from_math(fullname);

            // Name of the mass parameter.
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",5]]";
            send_to_math(command);
            get_from_math(mass);

            // Check it doesn't get eaten - this isn't a physical particle.
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",13]]";
            send_to_math(command);
            get_from_math(eaten);
            if (eaten != "NoGS")
            {
                continue;
            }

            // Color representation
            command = "pl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",7]]";
            send_to_math(command);

            std::string colorstr;
            get_from_math(colorstr);
            if (colorstr == "S")
            {
                color = 1;
            }
            else if (colorstr == "T")
            {
                color = 3;
            }
            else if (colorstr == "O")
            {
                color = 8;
            }

            // Charge

            // Firsly, need to get the name of the Class in FeynRules (in case there's
            // multiple entries -- they will all have the same QNUMBERS.)
            std::string classname;
            command = "pl[[" + std::to_string(i+1) + ",1,2]]";
            send_to_math(command);
            get_from_math(classname);

            // Now see if there is a charge entry
            float charge = 0.;

            command = "N[Q[" + classname + "]]";
            send_to_math(command);
            get_from_math(charge);

            chargeX3 = int(round(charge * 3));

            // If we've got this far, our particle is physical.
            // One last thing... check if it's a SM particle or not.
            std::set<int> SM_pdgs = {1, 2, 3, 4, 5, 6, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24};
            if (SM_pdgs.count(abs(pdg)))
            {
                SM = true;
            }
            else
            {
                SM = false;
            }

            // Add the particle to the list.
            Particle particle(pdg, std::string(name), spinX2, chargeX3, color, SM, mass, std::string(antiname), std::string(fullname));
            partlist.push_back(particle);
        }

     }

  }

  // Gets the 'ParamList' -- this contains all particles in the model.
  void FeynRules::get_paramlist(std::vector<Parameter> &paramlist)
  {
    std::cout << "Extracting external parameters from FeynRules model." << std::endl;

    std::string command = "epl = EParamList;";
    send_to_math(command);

    // Find out how many parameters we have to get.
    command = "Length[epl]";
    send_to_math(command);

    std::stringstream ss;

    int lenepl;
    get_from_math(lenepl);

    std::cout << "Found " << lenepl << " parameter blocks." << std::endl;

    std::string block;

    for (int i=0; i<lenepl; i++)
    {
        command = "epl[[" + std::to_string(i+1) + ",1]]";
        send_to_math(command);
        get_from_math(block);

        // First things first, check how many elements are in each block.
        // e.g., SMINPUTS = (aEWM1, Gf, alphaS).
        int numelements;
        command = "Length[epl[[" + std::to_string(i+1) + ",2]]]";
        send_to_math(command);
        get_from_math(numelements);

        for (int j=0; j<numelements; j++)
        {

            std::string paramname;

            command = "epl[[" + std::to_string(i+1) + ",2," + std::to_string(j+1) + ",2,1]]";
            send_to_math(command);
            get_from_math(paramname);

            Parameter parameter(paramname, block, int(j+1));
            paramlist.push_back(parameter);
        }
    }
  }

  // Set the gauge -- accepts either 'feynman' or 'unitary'
  void FeynRules::set_gauge(std::string gauge)
  {
    if ((gauge != "feynman") && (gauge != "unitary"))
    {
        std::stringstream ss;
        ss << "set_gauge() called with an incorrect option, "
                  << gauge << ".\n Allowed options: 'feynman' or 'unitary'."
                  << std::endl;
        throw std::runtime_error(ss.str());
    }
    std::string command;
    if (gauge == "feynman")
    {
        command = "FeynmanGauge = True;";
        std::cout << "Setting Feynman Gauge." << std::endl;
    }
    else if (gauge == "unitary")
    {
        command = "FeynmanGauge = False;";
        std::cout << "Setting Unitary Gauge." << std::endl;
    }
    send_to_math(command);
  }

  // Write CalcHEP output.
  void FeynRules::write_ch_output(std::string LTot)
  {
    std::cout << "Writing CalcHEP output." << std::endl;

    // CalcHEP is faster in Feynman Gauge.
    std::string gauge = "feynman";
    set_gauge(gauge);

    // Check to see if FR catches any 4-fermion vertices.
    bool fourF = false;
    int nfourF = 0;

    // Redirect output to catch them after writing CH files
    send_to_math("streams = AppendTo[$Output, OpenWrite[]];");

    // Write output.
    std::string command = "WriteCHOutput[" + LTot + ", CHAutoWidths -> False];";
    send_to_math(command);

    // Close the output stream and restore to stdout
    command = "Close@Last@streams; $Output = Most@streams; output = ReadList@First@Last@streams;";
    send_to_math(command);

    // Process the output to find out if there are any 4-fermion interactions.
    int noutput;
    send_to_math("Length[output]");
    get_from_math(noutput);

    for(int i=1; i<=noutput; i++)
    {
      std::string output;
      send_to_math("ToString[output[[" + std::to_string(i) + "]]]");
      get_from_math(output);

      // If we find a 4-fermion vertex, take a note of it
      size_t pos = output.find("4 fermion");
      if(pos != std::string::npos)
      {
        fourF = true;
        nfourF++;
      }
    }

    // 4-fermion vertices result in a fatal error in GUM v1.
    if(fourF)
    {
      std::stringstream ss;
      ss << "GUM caught " + std::to_string(nfourF) + " 4-fermion vertices in your Lagrangian." << std::endl;
      ss << "This is a fatal error in the current release of GUM." << std::endl;
      ss << "Dealing with 4-fermion vertices is planned for future releases." << std::endl;
      throw std::runtime_error(ss.str());
    }
    std::cout << "CalcHEP files written." << std::endl;

  }

  // Write MadGraph output.
  void FeynRules::write_mg_output(std::string LTot)
  {
    std::cout << "Writing MadGraph (UFO) output for Pythia/MadDM." << std::endl;

    // Write output.
    std::string command = "WriteUFO[" + LTot + "];";
    send_to_math(command);

    std::cout << "MadGraph files written." << std::endl;
  }

  // Performs all FeynRules output.
  void all_feynrules(Options opts, std::vector<Particle> &partlist, std::vector<Parameter> &paramlist,
                     Outputs &outputs, std::vector<std::string> &backends, Error &error)
  {
    try
    {
      std::cout << "Calling FeynRules with model " << opts.model() << "..." << std::endl;

      // Create FeynRules object, open link to Mathematica, load Feynrules and the model
      FeynRules model(opts.model(), opts.base_model());

      // Load restrictions - if there are any.
      if (not opts.restriction().empty())
      {
        model.load_restriction(opts.model(), opts.base_model(), opts.restriction());
      }

      // Check the Lagrangian seems to exist.
      model.check_lagrangian(opts.lagrangian());

      // Diagnositics -- check it is hermitian
      model.check_herm(opts.lagrangian());

      // Get all of the particles
      model.get_partlist(partlist);

      // And all parameters
      model.get_paramlist(paramlist);

      // Get the "actual" model name
      std::string fr_model_name = model.get_modelname();

      // Output directory
      std::string output = std::string(FEYNRULES_PATH) + "/" + fr_model_name;

      /// Write CalcHEP output
      if (std::find(backends.begin(), backends.end(), "calchep") != backends.end() ||
          std::find(backends.begin(), backends.end(), "micromegas") != backends.end() )
      {
        model.write_ch_output(opts.lagrangian());

        // Location of CalcHEP files
        std::string chdir = output + "-CH";
        std::replace(chdir.begin(), chdir.end(), ' ', '-');
        outputs.set_ch(chdir);
      }

      /// Same for MadGraph->Pythia
      if (std::find(backends.begin(), backends.end(), "pythia") != backends.end() ||
          std::find(backends.begin(), backends.end(), "ufo") != backends.end() )
      {
        model.write_mg_output(opts.lagrangian());

        // Location of MadGraph (UFO) files
        std::string mgdir = output + "_UFO";
        std::replace(mgdir.begin(), mgdir.end(), ' ', '_');
        outputs.set_mg(mgdir);
      }
    }
    catch(std::exception &e)
    {
      error.raise("FeynRules Error: " + std::string(e.what()));
    }
  }

} // namespace GUM

// Now all the grizzly stuff, so Python can call C++ (which can call Mathematica...)
BOOST_PYTHON_MODULE(libfr)
{
  using namespace boost::python;

  class_<Particle>("FRParticle", init<int, std::string, int, int, int, bool, std::string, std::string, std::string>())
    .def("pdg",      &Particle::pdg)
    .def("name",     &Particle::name)
    .def("SM",       &Particle::SM)
    .def("spinX2",   &Particle::spinX2)
    .def("chargeX3", &Particle::chargeX3)
    .def("color",    &Particle::color)
    .def("mass",     &Particle::mass)
    .def("SC",       &Particle::SC)
    .def("antiname", &Particle::antiname)
    ;

  class_<Parameter>("FRParameter", init<std::string, std::string, int>())
    .def("name",  &Parameter::name)
    .def("block", &Parameter::block)
    .def("index", &Parameter::index)
    ;

  class_<Options>("FROptions", init<std::string, std::string, std::string, std::string, std::string>())
    .def("package",     &Options::package)
    .def("model",       &Options::model)
    .def("base_model",  &Options::base_model)
    .def("restriction", &Options::restriction)
    .def("lagrangian",  &Options::lagrangian)
    ;

  class_<Outputs>("FROutputs", init<>())
    .def("get_ch",  &Outputs::get_ch)
    .def("get_mg",  &Outputs::get_mg)
    .def("set_ch",  &Outputs::set_ch)
    .def("set_mg",  &Outputs::set_mg)
    ;

  class_<Error>("FRError", init<>())
    .def("is_error", &Error::is_error)
    .def("what", &Error::what)
    ;

  class_< std::vector<Particle> >("FRVectorOfParticles")
    .def(vector_indexing_suite< std::vector<Particle> >() )
    ;

  class_< std::vector<Parameter> >("FRVectorOfParameters")
    .def(vector_indexing_suite< std::vector<Parameter> >() )
    ;

  class_< std::vector<std::string> >("FRBackends")
    .def(vector_indexing_suite< std::vector<std::string> >() )
    ;

  def("all_feynrules", GUM::all_feynrules);

}


text:
//
// 	Copyright (c) 2018  Cem Bassoy, cem.bassoy@gmail.com
// 	Copyright (c) 2019, Amit Singh, amitsingh19975@gmail.com
//
//  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)
//
//  The authors gratefully acknowledge the support of
//  Google and Fraunhofer IOSB, Ettlingen, Germany
//

#include <boost/test/unit_test.hpp>
#include <boost/numeric/ublas/tensor/extents.hpp>

BOOST_AUTO_TEST_SUITE ( test_extents_dynamic )

struct fixture
{
  using extents = boost::numeric::ublas::extents<>;

//  static inline auto n     = extents{};
  static inline auto n1    = extents{1};
  static inline auto n2    = extents{2};
  static inline auto n11   = extents{1,1};
  static inline auto n12   = extents{1,2};
  static inline auto n21   = extents{2,1};
  static inline auto n22   = extents{2,2};
  static inline auto n32   = extents{3,2};
  static inline auto n111  = extents{1,1,1};
  static inline auto n211  = extents{2,1,1};
  static inline auto n121  = extents{1,2,1};
  static inline auto n112  = extents{1,1,2};
  static inline auto n123  = extents{1,2,3};
  static inline auto n321  = extents{3,2,1};
  static inline auto n213  = extents{2,1,3};
  static inline auto n432  = extents{4,3,2};
};

BOOST_FIXTURE_TEST_CASE(test_extents_dynamic_empty,
                        fixture,
                        *boost::unit_test::label("dynamic_extents") *boost::unit_test::label("empty"))
{
  namespace ublas = boost::numeric::ublas;

//  BOOST_CHECK( ublas::empty(n   ));
  BOOST_CHECK(!ublas::empty(n1  ));
  BOOST_CHECK(!ublas::empty(n2  ));
  BOOST_CHECK(!ublas::empty(n11 ));
  BOOST_CHECK(!ublas::empty(n12 ));
  BOOST_CHECK(!ublas::empty(n21 ));
  BOOST_CHECK(!ublas::empty(n22 ));
  BOOST_CHECK(!ublas::empty(n32 ));
  BOOST_CHECK(!ublas::empty(n111));
  BOOST_CHECK(!ublas::empty(n211));
  BOOST_CHECK(!ublas::empty(n121));
  BOOST_CHECK(!ublas::empty(n112));
  BOOST_CHECK(!ublas::empty(n123));
  BOOST_CHECK(!ublas::empty(n321));
  BOOST_CHECK(!ublas::empty(n213));
  BOOST_CHECK(!ublas::empty(n432));

  BOOST_CHECK_THROW( extents({1,1,0}), std::invalid_argument);
  BOOST_CHECK_THROW( extents({1,0})  , std::invalid_argument);
  BOOST_CHECK_THROW( extents({0}  )  , std::invalid_argument);
  BOOST_CHECK_THROW( extents({0,1})  , std::invalid_argument);
}

BOOST_FIXTURE_TEST_CASE(test_extents_dynamic_size,
                        fixture,
                        *boost::unit_test::label("dynamic_extents") *boost::unit_test::label("size"))
{
  namespace ublas = boost::numeric::ublas;

//  BOOST_CHECK_EQUAL(ublas::size(n   ),0);
  BOOST_CHECK_EQUAL(ublas::size(n1  ),1);
  BOOST_CHECK_EQUAL(ublas::size(n2  ),1);
  BOOST_CHECK_EQUAL(ublas::size(n11 ),2);
  BOOST_CHECK_EQUAL(ublas::size(n12 ),2);
  BOOST_CHECK_EQUAL(ublas::size(n21 ),2);
  BOOST_CHECK_EQUAL(ublas::size(n22 ),2);
  BOOST_CHECK_EQUAL(ublas::size(n32 ),2);
  BOOST_CHECK_EQUAL(ublas::size(n111),3);
  BOOST_CHECK_EQUAL(ublas::size(n211),3);
  BOOST_CHECK_EQUAL(ublas::size(n121),3);
  BOOST_CHECK_EQUAL(ublas::size(n112),3);
  BOOST_CHECK_EQUAL(ublas::size(n123),3);
  BOOST_CHECK_EQUAL(ublas::size(n321),3);
  BOOST_CHECK_EQUAL(ublas::size(n213),3);
  BOOST_CHECK_EQUAL(ublas::size(n432),3);
}

BOOST_FIXTURE_TEST_CASE(test_extents_dynamic_at_read,
                       fixture,
                       *boost::unit_test::label("dynamic_extents") *boost::unit_test::label("at_read"))
{
  BOOST_CHECK_EQUAL(n1  .at(0),1);
  BOOST_CHECK_EQUAL(n2  .at(0),2);

  BOOST_CHECK_EQUAL(n11 .at(0),1);
  BOOST_CHECK_EQUAL(n11 .at(1),1);

  BOOST_CHECK_EQUAL(n12 .at(0),1);
  BOOST_CHECK_EQUAL(n12 .at(1),2);

  BOOST_CHECK_EQUAL(n21 .at(0),2);
  BOOST_CHECK_EQUAL(n21 .at(1),1);

  BOOST_CHECK_EQUAL(n22 .at(0),2);
  BOOST_CHECK_EQUAL(n22 .at(1),2);

  BOOST_CHECK_EQUAL(n32 .at(0),3);
  BOOST_CHECK_EQUAL(n32 .at(1),2);

  BOOST_CHECK_EQUAL(n432.at(0),4);
  BOOST_CHECK_EQUAL(n432.at(1),3);
  BOOST_CHECK_EQUAL(n432.at(2),2);

//  BOOST_CHECK_THROW( (void)n  .at(0), std::out_of_range);
  BOOST_CHECK_THROW( (void)n32.at(2), std::out_of_range);
  BOOST_CHECK_THROW( (void)n32.at(5), std::out_of_range);
}

BOOST_FIXTURE_TEST_CASE(test_extents_dynamic_at_write,
                        fixture,
                        *boost::unit_test::label("dynamic_extents") *boost::unit_test::label("at_write"))
{
  auto n3 = extents{1};
  n3 = extents{3};
  BOOST_CHECK_EQUAL(n3.at(0),3);

  auto n34 = extents{1,1};
  n34 = extents{3,4};
  BOOST_CHECK_EQUAL(n34.at(0),3);
  BOOST_CHECK_EQUAL(n34.at(1),4);

  auto n345 = extents{1,1,1};
  n345 = extents{3,4,5};
  BOOST_CHECK_EQUAL(n345.at(0),3);
  BOOST_CHECK_EQUAL(n345.at(1),4);
  BOOST_CHECK_EQUAL(n345.at(2),5);

  auto n5432 = extents{1,1,1,1};
  n5432 = extents{5,4,3,2};
  BOOST_CHECK_EQUAL(n5432.at(0),5);
  BOOST_CHECK_EQUAL(n5432.at(1),4);
  BOOST_CHECK_EQUAL(n5432.at(2),3);
  BOOST_CHECK_EQUAL(n5432.at(3),2);
}

BOOST_FIXTURE_TEST_CASE(test_extents_dynamic_operator_access_read,
                        fixture,
                        *boost::unit_test::label("dynamic_extents") *boost::unit_test::label("operator_access_read"))
{
  BOOST_CHECK_EQUAL(n1  [0],1);
  BOOST_CHECK_EQUAL(n2  [0],2);

  BOOST_CHECK_EQUAL(n11 [0],1);
  BOOST_CHECK_EQUAL(n11 [1],1);

  BOOST_CHECK_EQUAL(n12 [0],1);
  BOOST_CHECK_EQUAL(n12 [1],2);

  BOOST_CHECK_EQUAL(n21 [0],2);
  BOOST_CHECK_EQUAL(n21 [1],1);

  BOOST_CHECK_EQUAL(n22 [0],2);
  BOOST_CHECK_EQUAL(n22 [1],2);

  BOOST_CHECK_EQUAL(n32 [0],3);
  BOOST_CHECK_EQUAL(n32 [1],2);

  BOOST_CHECK_EQUAL(n432[0],4);
  BOOST_CHECK_EQUAL(n432[1],3);
  BOOST_CHECK_EQUAL(n432[2],2);
}

BOOST_AUTO_TEST_SUITE_END()


text:
//
// Copyright (c) 2018 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//

#ifndef BOOST_BEAST_CORE_IMPL_TIMEOUT_SERVICE_HPP
#define BOOST_BEAST_CORE_IMPL_TIMEOUT_SERVICE_HPP

#include <boost/beast/_experimental/core/detail/timeout_service.hpp>
#include <boost/asio/execution_context.hpp>
#include <boost/assert.hpp>

namespace boost {
namespace beast {

timeout_handle::
timeout_handle(net::io_context& ioc)
    : timeout_handle(
        net::use_service<
            detail::timeout_service>(
                ioc).make_handle())
{
}

void
timeout_handle::
destroy()
{
    BOOST_ASSERT(svc_ != nullptr);
    svc_->destroy(*this);
    id_ = 0;
    svc_ = nullptr;
}

template<class Executor, class CancelHandler>
void
timeout_handle::
set_callback(
    Executor const& ex, CancelHandler&& handler)
{
    svc_->set_callback(*this, ex,
        std::forward<CancelHandler>(handler));
}

//------------------------------------------------------------------------------

void
set_timeout_service_options(
    net::io_context& ioc,
    std::chrono::seconds interval)
{
    net::use_service<
        detail::timeout_service>(
            ioc).set_option(interval);
}

} // beast
} // boost

#endif

ext: hpp

max_stars_repo_name: octobanana/beast

max_issues_repo_name: octobanana/beast

max_forks_repo_name: octobanana/beast


text:
/* simd.cc
   Jeremy Barnes, 21 February 2007
   Copyright (c) 2007 Jeremy Barnes.  All rights reserved.

   Implementation of SIMD code.
*/

#include "simd.h"
#include <boost/tuple/tuple.hpp>
#include "jml/arch/exception.h"
#include <iostream>
#include <iomanip>

using namespace std;

namespace ML {

#if defined __i686__ || defined __amd64__

namespace {

enum {
    CPUID_VENDOR_ID = 0,
    CPUID_LEVEL = 0,
    CPUID_FEATURES = 1,
    CPUID_CACHE_INFO = 2,
    CPUID_SERIAL_NUMBER = 3,
    CPUID_EXT_CACHE_INFO = 4,
    CPUID_MONITOR_MWAIT = 5,
    CPUID_THERMAL_POWER = 6,
    CPUID_DCA_ACCESS = 7,
    CPUID_EXT_LEVEL =      0x80000000,
    CPUID_EXT_FEATURES =   0x80000001,
    CPUID_EXT_BRAND1 =     0x80000002,
    CPUID_EXT_BRAND2 =     0x80000003,
    CPUID_EXT_BRAND3 =     0x80000004,
    CPUID_EXT_L1CACHE =    0x80000005,
    CPUID_EXT_L2CACHE =    0x80000006,
    CPUID_EXT_APM_INFO =   0x80000007,
    CPUID_EXT_ADDR_SIZES = 0x80000008,
    CPUID_EXT_SVM_INFO =   0x8000000A
};

struct Regs {
    uint32_t eax, ebx, ecx, edx;
};

Regs
cpuid(uint32_t request, uint32_t ecx = 0)
{
    Regs result = {0, 0, 0, 0};
    asm volatile
        (
#if defined(__i686__)
         "sub  $0x40,  %%esp\n\t"
         "push %%ebx\n\t"
         "push %%edx\n\t"
#else
         "sub  $0x40,  %%rsp\n\t"
         "push %%rbx\n\t"
         "push %%rdx\n\t"
#endif
         "cpuid\n\t"

         "mov  %%eax,  0(%[addr])\n\t"
         "mov  %%ebx,  4(%[addr])\n\t"
         "mov  %%ecx,  8(%[addr])\n\t"
         "mov  %%edx, 12(%[addr])\n\t"
#if defined(__i686__)
         "pop  %%edx\n\t"
         "pop  %%ebx\n\t"
         "add  $0x40,   %%esp\n\t"
#else
         "pop  %%rdx\n\t"
         "pop  %%rbx\n\t"
         "add  $0x40,   %%rsp\n\t"
#endif
         : "+a" (request), "+c" (ecx)
         : [addr] "S" (&result)
         : "cc", "memory"
         );
    return result;
}

} // file scope

uint32_t cpuid_flags()
{
    return cpuid(1).edx;
}

namespace {

std::string to_ascii(uint32_t x)
{
    std::string result(4, ' ');
    for (unsigned i = 0;  i < 4;  ++i)
        result[i] = x >> (i * 8);
    return result;
}

} // file scope

std::string vendor_id()
{
    Regs r = cpuid(CPUID_VENDOR_ID);
    return to_ascii(r.ebx) + to_ascii(r.edx) + to_ascii(r.ecx);
}

std::string model_id()
{
    uint32_t cpuid_extlevel = cpuid(CPUID_EXT_LEVEL).eax;

    cerr << "cpuid_extlevel = " << setw(16) << cpuid_extlevel << endl;

    if (cpuid_extlevel < 0x80000000 || cpuid_extlevel > 0x8000ffff)
        return "";  // no model if no extended CPUID

    std::string result;
    for (unsigned i = 0;  i < 3;  ++i) {
        Regs r = cpuid(CPUID_EXT_BRAND1 + i);
        result
            +=  to_ascii(r.eax) + to_ascii(r.ebx)
              + to_ascii(r.ecx) + to_ascii(r.edx);
    }

    //cerr << "model_id = " << result << endl;

    if (result.size() != 48)
        throw Exception("model_id(): invalid model ID");

    if (result[47] != 0)
        throw Exception("model_id(): invalid model ID terminator");

    return result.c_str();  // truncate to null terminator
}

CPU_Info::CPU_Info()
{
    cpuid_level = cpuid_extlevel = standard1 = standard2 = extended = amd = 0;

    cpuid_level = cpuid(CPUID_LEVEL).eax;
    cpuid_extlevel = cpuid(CPUID_EXT_LEVEL).eax;

    //cerr << "cpuid level = " << cpuid_level << endl;
    //cerr << "cpuid ext level = " << cpuid_extlevel - 0x80000000 << endl;

    if (cpuid_extlevel < 0x80000000 || cpuid_extlevel > 0x8000ffff)
        cpuid_extlevel = 0;

    vendor = vendor_id();
    model = model_id();

    Regs r = cpuid(CPUID_FEATURES);
    standard1 = r.edx;
    standard2 = r.ecx;

    if (cpuid_extlevel >= CPUID_EXT_FEATURES) {
        r = cpuid(CPUID_EXT_FEATURES);
        extended = r.edx;
        amd = r.ecx;
    }

#if 0
    if (fpu) cerr << "fpu ";

    if (vme) cerr << "vme ";
    if (de) cerr << "de ";
    if (pse) cerr << "pse ";
    if (tsc) cerr << "tsc ";
    if (msr) cerr << "msr ";
    if (pae) cerr << "pae ";
    if (mce) cerr << "mce ";
    if (cx8) cerr << "cx8 ";
    if (apic) cerr << "apic ";
    if (sep) cerr << "sep ";
    if (mtrr) cerr << "mtrr ";
    if (pge) cerr << "pge ";
    if (mca) cerr << "mca ";
    if (cmov) cerr << "cmov ";
    if (pat) cerr << "pat ";
    if (pse36) cerr << "pse36 ";
    if (psn) cerr << "psn ";
    if (clflush) cerr << "clflush ";
    if (dts) cerr << "dts ";
    if (acpi) cerr << "acpi ";
    if (mmx) cerr << "mmx ";
    if (fxsr) cerr << "fxsr ";
    if (sse) cerr << "sse ";
    if (sse2) cerr << "sse2 ";
    if (ss) cerr << "ss ";
    if (ht) cerr << "ht ";
    if (tm) cerr << "tm ";
    if (ia64) cerr << "ia64 ";
    if (pbe) cerr << "pbe ";

    if (sse3) cerr << "sse3 ";
    if (monitor) cerr << "monitor ";
    if (ds_cpl) cerr << "ds_cpl ";
    if (vmx) cerr << "vmx ";
    if (est) cerr << "est ";
    if (tm2) cerr << "tm2 ";
    if (pni) cerr << "pni ";
    if (cid) cerr << "cid ";
    if (cx16) cerr << "cx16 ";
    if (xtpr) cerr << "xtpr ";
    if (dca) cerr << "dca ";

    if (syscall) cerr << "syscall ";
    if (nx) cerr << "nx ";       // 20
    if (mmxext) cerr << "mmxext ";
    if (ffxsr) cerr << "ffxsr ";
    if (rdtscp) cerr << "rdtscp ";
    if (lm) cerr << "lm ";
    if (threednowext) cerr << "3nowext ";
    if (threednow) cerr << "3dnow ";

    if (lahfsahf) cerr << "lahfsahf ";
    if (svm) cerr << "svm ";
    if (cmplegacy) cerr << "cmplegacy ";
    if (altmovcr8) cerr << "altmovcr8 ";

    cerr << endl;
#endif
}

#if 0
std::string
CPU_Info::
print_flags()
{
    //static const char * STANDARD1_NAMES = { };
    return "";
}
#endif

CPU_Info * static_cpu_info = 0;

#endif // __i686__

} // namespace ML

ext: cc

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: TuanTranEngineer/rtbkit

max_forks_repo_name: TuanTranEngineer/rtbkit


text:
/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/localization/msf/local_gnss/gnss_positioning.h"
#include <Eigen/Eigen>
#include <vector>
#include "modules/localization/msf/local_gnss/atmosphere.h"
#include "modules/localization/msf/local_gnss/gnss_utility.hpp"

namespace apollo {
namespace localization {
namespace local_gnss {

// this file contains lots of quality control strategies learned from field
// datas to be conservative for a safety-critical vehicle.

bool GnssPntSolver::IsSafeStandardPointPos(const double std_rover,
                                            const double pdop) {
  if (fabs(std_rover) >= 10.0 || std_rover < 0.0) {
    return false;
  }
  if (fabs(pdop) > 10.0) {
    return false;
  }
  return true;
}

bool GnssPntSolver::IsSafeCodeDiffPos(const double dis, const double std_dif,
                                       const bool valid_delta_pos) {
  if (fabs(std_dif) > 2.0 || fabs(std_dif) < 0.2) {
    return false;
  }
  if (dis > 10.0) {
    return false;
  }
  if (valid_delta_pos) {
    return false;
  }
  return true;
}

bool GnssPntSolver::IsSafeFixedSolution(const unsigned int gnss_type_size,
                                        const unsigned int num_fixed_phase) {
  if (!b_rtkfixed_) {
    return false;
  }
  if (num_fixed_phase <= 5 * gnss_type_size) {
    std::string excute_info = "";
    if (num_fixed_phase <= 4 * gnss_type_size) {
      ResetFixedRtk();
      excute_info = "reset";
    }
    EncodeDetails(
        "fixed_phase_num not enough for safe solution = %3d with num_sys = %3d "
        "%s",
        num_fixed_phase, gnss_type_size, excute_info.c_str());
    return false;
  }
  double leve_dop = sqrt(rtk_dop_phase_.x * rtk_dop_phase_.x +
                         rtk_dop_phase_.y * rtk_dop_phase_.y);
  std::string save_temp = gnss_utility::FormatString(
      " Safe_fixed_phase(3d_dop, level_dop, num, new) = %6.3f%6.3f%3d%3d",
      rtk_dop_phase_.Norm3D(), leve_dop, num_fixed_phase,
      new_fixed_phase_num_);

  if (rtk_dop_phase_.Norm3D() < 4.0 || leve_dop < 2.5) {
    invalid_rtk_sub_infor_ = invalid_rtk_sub_infor_ + save_temp;
    return true;
  }

  std::string rist_temp = gnss_utility::FormatString(
      " Risky_fixed_phase(3d_dop, level_dop, num, new) = %6.3f%6.3f%3d%3d",
      rtk_dop_phase_.Norm3D(), leve_dop, num_fixed_phase,
      new_fixed_phase_num_);

  invalid_rtk_sub_infor_ = invalid_rtk_sub_infor_ + rist_temp;
  if (++_continuous_risky_num >= 5) {
    _continuous_risky_num = 0;
    ResetFixedRtk();
  }

  return false;
}

void GnssPntSolver::WeightOnPostResidual(
    const double std_v,
    const std::vector<unsigned int>& range_type,
    const Eigen::MatrixXd& post_res,
    Eigen::MatrixXd* px_temp) {
  Eigen::MatrixXd px = *px_temp;
  for (unsigned int i = 0; i < range_type.size(); ++i) {
    if (range_type[i] == 0) {
      if (fabs(post_res(i, 0)) > 20 * std_v) {
        px(i, i) *= 0.01;
      } else if (fabs(post_res(i, 0)) > 15 * std_v) {
        px(i, i) *= 0.3;
      } else if (fabs(post_res(i, 0)) > 10 * std_v) {
        px(i, i) *= 0.7;
      }
    } else {
      if (fabs(post_res(i, 0)) > 4 * std_v) {
        px(i, i) *= 0.1;
      } else if (fabs(post_res(i, 0)) > 3 * std_v) {
        px(i, i) *= 0.3;
      } else if (fabs(post_res(i, 0)) > 2 * std_v) {
        px(i, i) *= 0.7;
      }
    }
  }
  *px_temp = px;
}

void GnssPntSolver::RemoveAmbWithAbnormalRes(
    const std::vector<ObsKey>& phase_recorder,
    const double& std_v,
    const std::vector<unsigned int>& range_type,
    const Eigen::MatrixXd& post_res,
    const double band_res_sum[apollo::drivers::gnss::GLO_G3]) {
  bool phase_slip_exist = false;
  unsigned int ind_phase = 0;
  for (unsigned int i = 0; i < range_type.size(); ++i) {
    if (range_type[i] == 0) {
      continue;
    }
    if (fabs(post_res(i, 0)) > 5 * std_v || fabs(post_res(i, 0)) >= 0.10) {
      phase_slip_exist = true;
      amb_tracker_.DeleteSlipAmb(phase_recorder[ind_phase].band_id,
                                 phase_recorder[ind_phase].sat_prn);
    }
    ++ind_phase;
  }
  if (!phase_slip_exist) {
    amb_tracker_.ReupdateReferenceAmb(band_res_sum);
  }
}

void GnssPntSolver::BoundRangePrecision(const double std_dif) {
  if (std_dif > range_precision_) {
    range_precision_ = std_dif;
  }
}

PointThreeDim GnssPntSolver::BoundedRtkStd() {
  PointThreeDim phase_std = std_rtk_.SquareRoot();
  if (std_rtk_thres_of_phase_dop_.Norm3D() > std_rtk_.Norm3D()) {
    phase_std = std_rtk_thres_of_phase_dop_.SquareRoot();
  }
  return phase_std;
}

bool GnssPntSolver::CheckSatObsForSPP(const SatelliteObservation& sat_obs) {
  if (sat_obs.band_obs_num() <= 0) {
    return false;
  }
  // 20804163.233 = 69 ms
  // 36804163.233 = 122.7 ms
  double time_duration = sat_obs.band_obs(0).pseudo_range() / C_MPS;
  if (time_duration < 0.030) {
    return false;
  }
  if (time_duration > 0.200) {
    return false;
  }
  return true;
}

int GnssPntSolver::IsValidBandObs(const BandObservation& band_obs1,
                                  const BandObservation& band_obs2) {
  if (band_obs1.band_id() != band_obs2.band_id()) {
    return -1;
  }
  if (gnss_utility::GetIndexInVector(band_obs1.band_id(), band_to_solve_) ==
      -1) {
    return -1;
  }
  return 0;
}

bool GnssPntSolver::CheckBaserObs(double std, double distance) {
  if (fabs(std) > 30.0 || std < 0.0) {
    return false;
  }
  if (fabs(distance) > 100.0) {
    return false;
  }
  return true;
}

int GnssPntSolver::EnableGlonassIfbEstimated() {
  // return 1 && b_rtkfixed_;
  return 0;
}

double GnssPntSolver::WeightScaleOnGnssSystem(
    const GnssType& type) {
  double scale = 25.0;
  switch (type) {
    case apollo::drivers::gnss::GPS_SYS:
      scale = 1.0;
      break;
    case apollo::drivers::gnss::BDS_SYS:
      scale = 1.0;
      break;
    case apollo::drivers::gnss::GLO_SYS:
      scale = 2.25;
      break;
    default:
      scale = 25.0;
  }
  return scale;
}

void GnssPntSolver::CheckConsecutiveTimeOffset(unsigned int week_num,
                                                  double week_sec) {
  double sec_per_week = SECOND_PER_WEEK;
  double t1 = week_num * sec_per_week + week_sec;
  double t2 = gnss_weeknum_ * sec_per_week + gnss_week_second_s_;
  if (fabs(t1 - t2) > 5.0) {
    ResetFixedRtk();
  }
  gnss_week_second_s_ = week_sec;
  gnss_weeknum_ = week_num;
}

bool GnssPntSolver::IsEnabledCodeDiff(const double& data_outage,
                                     const double& dis_rover2baser) {
  if (fabs(data_outage) > 60.0) {
    return false;
  }
  const double dis_tolerance = 50000;
  if (dis_rover2baser > dis_tolerance) {
    return false;
  }
  return true;
}

bool GnssPntSolver::IsEnabledPhaseDiff(const double& data_outage,
                                      const double& dis_rover2baser) {
  if (fabs(data_outage) > 15.0) {
    return false;
  }
  const double dis_tolerance = 25000;
  if (dis_rover2baser > dis_tolerance) {
    return false;
  }
  return true;
}

bool GnssPntSolver::CheckLambda(const double ratio, const double adop) {
  if (ratio < 0.0) {
    return false;
  }
  if (adop > 30.0) {
    return false;
  }
  return true;
}

bool GnssPntSolver::IsAbnormalFixedSolutionWithNewPhase(
    const bool& is_fixed, const double std_fixed,
    const unsigned int unknown_phase_num) {
  if (unknown_phase_num <= 0) {
    return false;
  }
  if (!is_fixed) {
    return false;
  }
  if (fabs(std_fixed) < 0.3) {
    return false;
  }
  return true;
}

bool GnssPntSolver::IsNeedRecursion(const bool& is_fixed,
                                    const double std_fixed,
                                    const unsigned int unknown_phase_num,
                                    const unsigned int common_phase_num) {
  if (unknown_phase_num > common_phase_num) {
    EncodeDetails("More unknown phase: %d > %d", unknown_phase_num,
                   common_phase_num);
    return true;
  }
  if (IsAbnormalFixedSolutionWithNewPhase(is_fixed, std_fixed,
                                             unknown_phase_num)) {
    EncodeDetails("abnormal_fixed_solution %6.3f", _std_v);
    SeedToughSatGroup(1.0);
    return true;
  }
  return false;
}

double GnssPntSolver::BoundRatio(const double& ratio) {
  if (ratio > 999.9) {
    return 1000.0;
  }
  return ratio;
}

double GnssPntSolver::GetStdThresForNewSat(const double new_ratio,
                                                const double std_v) {
  double thres_hold = 0.05;
  if (new_ratio < 3) {
    thres_hold = 0.002;
  } else if (new_ratio < 5) {
    thres_hold = 0.010;
  } else if (new_ratio < 8) {
    thres_hold = 0.020;
  } else if (new_ratio < 15) {
    thres_hold = 0.025;
  }
  if (std_v < 0.03) {
    thres_hold *= 2.0;
  }
  return thres_hold;
}

bool GnssPntSolver::CheckNewsatSolution(const PointThreeDim& denu,
                                          const double& thres,
                                          const double& dis_time_diff) {
  if (fabs(denu.z) > thres * 2) {
    return false;
  }
  if (fabs(denu.y) > thres) {
    return false;
  }
  if (fabs(denu.x) > thres) {
    return false;
  }
  if (fabs(dis_time_diff) > 0.05) {
    return false;
  }
  return true;
}

}  // namespace local_gnss
}  // namespace localization
}  // namespace apollo

max_stars_repo_name: renlancai/apollo

max_issues_repo_name: renlancai/apollo

max_forks_repo_name: renlancai/apollo


text:
#include <cstdio>
#include <iomanip>
#include <iostream>
#include <limits>
#include <stdexcept>

#include <Eigen/Dense>

#include <spii/spii.h>
#include <spii/solver.h>

#include "sgdsolver.hpp"

namespace spii {

void SGDSolver::solve(const Function& function, SolverResults* results) const {
  // Get the dimensionality of the problem.
  size_t dimension = function.get_number_of_scalars();
  std::cout << "Dimension is " << dimension << std::endl;

  if (dimension == 0) {
    results->exit_condition = SolverResults::FUNCTION_TOLERANCE;
    return;
  }

  Eigen::VectorXd current_point, gradient;
  Eigen::VectorXd next_point, next_point_gradient;

  function.copy_user_to_global(&current_point);
  Eigen::VectorXd stepdirection(dimension);

  results->exit_condition = SolverResults::INTERNAL_ERROR;
  int iteration = 0;

  double function_value = std::numeric_limits<double>::quiet_NaN();
  double gradient_norm = std::numeric_limits<double>::quiet_NaN();

  double previous_function_value = 0;
  double gain = 1.0;

  double exponentially_weighed_average_gain = gain;

  while (iteration < 500) {
    function_value = function.evaluate(current_point, &gradient);
    gradient_norm = std::max(gradient.maxCoeff(), -gradient.minCoeff());
    stepdirection = -gradient;

    gain = previous_function_value - function_value;

    printf("[%d:] Loss is %+.17e, norm is %+.17e, gain is %+.17e\n",
      iteration, function_value, gradient_norm, gain);

    double stepsize = (1.0 / gradient_norm) * (1.0/(iteration+1));

    // Evaluate the function at the next point and see if we are making
    // progress.
    double next_function_value;
    while (stepsize > 1.0e-10) {
      next_point = current_point + (10*stepsize) * stepdirection;
      next_function_value = function.evaluate(next_point,
        &next_point_gradient);
      // In order to make progress, the next_function_value needs to be smaller
      // than the current_function_value, so the gain needs to be positive.
      gain = function_value - next_function_value;
      if ((gain <= 0) || std::isnan(gain)) {
        printf("[%d:] gain is %+.17e, reducing stepsize * norm from %+.17e\n",
          iteration, gain, stepsize * gradient_norm);
        stepsize = stepsize / 100.0;
      } else {
        printf("[%d:] gain is %+.17e reducing loss to %+.17e\n", iteration,
          gain, next_function_value);
        current_point = next_point;
        gradient = next_point_gradient;
        break;
      }
    }

    if (stepsize <= 1.0e-100) {
      exponentially_weighed_average_gain = gain + (0.001 *
        exponentially_weighed_average_gain);
    } else {
      exponentially_weighed_average_gain = gain +
        (0.5 * exponentially_weighed_average_gain);
    }

    printf("[%d:] Exponentially weighed avg gain: %+.17e\n", iteration,
      exponentially_weighed_average_gain);

    if (exponentially_weighed_average_gain < 1.0e-20) {
      printf("[%d:] Exponentially weighed avg gain too small, aborting\n", iteration);
      if (exponentially_weighed_average_gain < 0.0) {
        printf("[%d:] Can't be negative, exiting.\n", iteration);
        exit(-1);
      }
      break;
    }

    if (function_value < 1.0) {
      printf("[%d:] Loss less than 1, aborting\n", iteration);
      break;
    }
    ++iteration;
    previous_function_value = function_value;
  }

  function.copy_global_to_user(current_point);
}

} // namespace spii

max_stars_repo_name: johannespitz/functionsimsearch

max_issues_repo_name: johannespitz/functionsimsearch

max_forks_repo_name: johannespitz/functionsimsearch


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

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/******************************************************************************\
* Author: Matthew Beauregard Smith                                             *
* Affiliation: The University of Texas at Austin                               *
* Department: Oden Institute and Institute for Cellular and Molecular Biology  *
* PI: Edward Marcotte                                                          *
* Project: Protein Fluorosequencing                                            *
\******************************************************************************/

// Boost unit test framework (recommended to be the first include):
#include <boost/test/unit_test.hpp>

// File under test:
#include "leaf-node.h"

// Standard C++ library headers:
#include <vector>

// External headers:
#include "fakeit.hpp"

// Local project headers:
#include "test-util/fakeit.h"  // in test directory

namespace whatprot {
namespace kd_tree {

namespace {
using boost::unit_test::tolerance;
using fakeit::_;
using fakeit::Fake;
using fakeit::Mock;
using fakeit::Verify;
using fakeit::VerifyNoOtherInvocations;
using std::vector;
using whatprot::test_util::Close;
using whatprot::test_util::Ptr;
const double TOL = 0.000000001;
}  // namespace

// Class we can use as a template parameter for E.
class Vec {
public:
    Vec(vector<double> v) : v(v), hits(1) {}
    Vec(vector<double> v, int hits) : v(v), hits(hits) {}
    double& operator[](int d) {
        return v[d];
    }
    double operator[](int d) const {
        return v[d];
    }
    // Needed to check arguments with FakeIt.
    bool operator==(const Vec& other) const {
        return (v == other.v) && (hits == other.hits);
    }
    vector<double> v;
    int hits;
};

BOOST_AUTO_TEST_SUITE(kd_tree_suite)
BOOST_AUTO_TEST_SUITE(leaf_node_suite)

BOOST_AUTO_TEST_CASE(constructor_test, *tolerance(TOL)) {
    int d = 3;
    vector<Vec> vecs(2, Vec(vector<double>(3, 0)));
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    BOOST_TEST(leaf.d == d);
    BOOST_TEST(leaf.begin == &vecs[0]);
    BOOST_TEST(leaf.end == &vecs[2]);
}

BOOST_AUTO_TEST_CASE(consider_success_test, *tolerance(TOL)) {
    int d = 3;
    vector<Vec> vecs(2, Vec(vector<double>(3, 0)));
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    vector<double> query(3, 0);
    query[0] = 1.0;
    query[1] = 1.1;
    query[2] = 1.2;
    Vec entry(vector<double>(3, 0));
    entry[0] = 2.00;
    entry[1] = 2.11;
    entry[2] = 2.22;
    Mock<KBest<Vec>> k_best_mock;
    Fake(Method(k_best_mock, insert));
    KBest<Vec>* k_best = &k_best_mock.get();
    k_best->kth_dist_sq = 1e9;
    leaf.consider(query, &entry, k_best);
    double dist_sq = 1.0 * 1.0 + 1.01 * 1.01 + 1.02 * 1.02;
    Verify(Method(k_best_mock, insert).Using(Close(dist_sq, TOL), Ptr(entry)));
    VerifyNoOtherInvocations(k_best_mock);
}

BOOST_AUTO_TEST_CASE(consider_failure_test, *tolerance(TOL)) {
    int d = 3;
    vector<Vec> vecs(2, Vec(vector<double>(3, 0)));
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    vector<double> query(3, 0);
    query[0] = 1.0;
    query[1] = 1.1;
    query[2] = 1.2;
    Vec entry(vector<double>(3, 0));
    entry[0] = 2.00;
    entry[1] = 2.11;
    entry[2] = 2.22;
    Mock<KBest<Vec>> k_best_mock;
    Fake(Method(k_best_mock, insert));
    KBest<Vec>* k_best = &k_best_mock.get();
    k_best->kth_dist_sq = 1e-2;
    leaf.consider(query, &entry, k_best);
    VerifyNoOtherInvocations(k_best_mock);
}

BOOST_AUTO_TEST_CASE(consider_success_big_d_test, *tolerance(TOL)) {
    int d = 6;
    vector<Vec> vecs(2, Vec(vector<double>(6, 0)));
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    vector<double> query(6, 0);
    query[0] = 1.0;
    query[1] = 1.1;
    query[2] = 1.2;
    query[3] = 1.3;
    query[4] = 1.4;
    query[5] = 1.5;
    Vec entry(vector<double>(6, 0));
    entry[0] = 2.00;
    entry[1] = 2.11;
    entry[2] = 2.22;
    entry[3] = 2.33;
    entry[4] = 2.44;
    entry[5] = 2.55;
    Mock<KBest<Vec>> k_best_mock;
    Fake(Method(k_best_mock, insert));
    KBest<Vec>* k_best = &k_best_mock.get();
    k_best->kth_dist_sq = 1e9;
    leaf.consider(query, &entry, k_best);
    double dist_sq = 1.0 * 1.0 + 1.01 * 1.01 + 1.02 * 1.02 + 1.03 * 1.03
                     + 1.04 * 1.04 + 1.05 * 1.05;
    Verify(Method(k_best_mock, insert).Using(Close(dist_sq, TOL), Ptr(entry)));
    VerifyNoOtherInvocations(k_best_mock);
}

BOOST_AUTO_TEST_CASE(consider_failure_big_d_test, *tolerance(TOL)) {
    int d = 6;
    vector<Vec> vecs(2, Vec(vector<double>(6, 0)));
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    vector<double> query(6, 0);
    query[0] = 1.0;
    query[1] = 1.1;
    query[2] = 1.2;
    query[3] = 1.3;
    query[4] = 1.4;
    query[5] = 1.5;
    Vec entry(vector<double>(6, 0));
    entry[0] = 2.00;
    entry[1] = 2.11;
    entry[2] = 2.22;
    entry[3] = 2.33;
    entry[4] = 2.44;
    entry[5] = 2.55;
    Mock<KBest<Vec>> k_best_mock;
    Fake(Method(k_best_mock, insert));
    KBest<Vec>* k_best = &k_best_mock.get();
    k_best->kth_dist_sq = 1e-2;
    leaf.consider(query, &entry, k_best);
    VerifyNoOtherInvocations(k_best_mock);
}

BOOST_AUTO_TEST_CASE(consider_barely_failure_big_d_test, *tolerance(TOL)) {
    int d = 6;
    vector<Vec> vecs(2, Vec(vector<double>(6, 0)));
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    vector<double> query(6, 0);
    query[0] = 1.0;
    query[1] = 1.1;
    query[2] = 1.2;
    query[3] = 1.3;
    query[4] = 1.4;
    query[5] = 1.5;
    Vec entry(vector<double>(6, 0));
    entry[0] = 2.00;
    entry[1] = 2.11;
    entry[2] = 2.22;
    entry[3] = 2.33;
    entry[4] = 2.44;
    entry[5] = 2.55;
    Mock<KBest<Vec>> k_best_mock;
    Fake(Method(k_best_mock, insert));
    KBest<Vec>* k_best = &k_best_mock.get();
    k_best->kth_dist_sq =
            1.0 * 1.0 + 1.01 * 1.01 + 1.02 * 1.02 + 1.03 * 1.03 - 1e-7;
    leaf.consider(query, &entry, k_best);
    VerifyNoOtherInvocations(k_best_mock);
}

BOOST_AUTO_TEST_CASE(search_success_test, *tolerance(TOL)) {
    int d = 3;
    vector<Vec> vecs(2, Vec(vector<double>(3, 0)));
    vecs[0][0] = 0.0;
    vecs[0][1] = 0.1;
    vecs[0][2] = 0.2;
    vecs[1][0] = 1.0;
    vecs[1][1] = 1.1;
    vecs[1][2] = 1.2;
    vector<double> query(3, 0);
    query[0] = 0.2;
    query[1] = 0.3;
    query[2] = 0.5;
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    Mock<KBest<Vec>> k_best_mock;
    Fake(Method(k_best_mock, insert));
    KBest<Vec>* k_best = &k_best_mock.get();
    k_best->kth_dist_sq = 1e9;
    leaf.search(query, k_best);
    double dst1 = 0.0;
    dst1 += (0.2 - 0.0) * (0.2 - 0.0);
    dst1 += (0.3 - 0.1) * (0.3 - 0.1);
    dst1 += (0.5 - 0.2) * (0.5 - 0.2);
    Vec v1(vector<double>(3, 0));
    v1[0] = 0.0;
    v1[1] = 0.1;
    v1[2] = 0.2;
    Verify(Method(k_best_mock, insert).Using(Close(dst1, TOL), Ptr(v1)))
            .Exactly(1);
    double dst2 = 0.0;
    dst2 += (0.2 - 1.0) * (0.2 - 1.0);
    dst2 += (0.3 - 1.1) * (0.3 - 1.1);
    dst2 += (0.5 - 1.2) * (0.5 - 1.2);
    Vec v2(vector<double>(3, 0));
    v2[0] = 1.0;
    v2[1] = 1.1;
    v2[2] = 1.2;
    Verify(Method(k_best_mock, insert).Using(Close(dst2, TOL), Ptr(v2)))
            .Exactly(1);
    VerifyNoOtherInvocations(k_best_mock);
}

BOOST_AUTO_TEST_CASE(search_failure_test, *tolerance(TOL)) {
    int d = 3;
    vector<Vec> vecs(2, Vec(vector<double>(3, 0)));
    vecs[0][0] = 0.0;
    vecs[0][1] = 0.1;
    vecs[0][2] = 0.2;
    vecs[1][0] = 1.0;
    vecs[1][1] = 1.1;
    vecs[1][2] = 1.2;
    vector<double> query(3, 0);
    query[0] = 0.2;
    query[1] = 0.3;
    query[2] = 0.5;
    LeafNode<Vec, vector<double>> leaf(d, &vecs[0], &vecs[2]);
    Mock<KBest<Vec>> k_best_mock;
    Fake(Method(k_best_mock, insert));
    KBest<Vec>* k_best = &k_best_mock.get();
    k_best->kth_dist_sq = 1e-2;
    leaf.search(query, k_best);
    VerifyNoOtherInvocations(k_best_mock);
}

BOOST_AUTO_TEST_SUITE_END()  // leaf_node_suite
BOOST_AUTO_TEST_SUITE_END()  // kd_tree_suite

}  // namespace kd_tree
}  // namespace whatprot

max_stars_repo_name: erisyon/whatprot

max_issues_repo_name: erisyon/whatprot

max_forks_repo_name: erisyon/whatprot


text:
/*
    This file is part of beautiful-bullet.

    Copyright (c) 2021, 2022 Bernardo Fichera <bernardo.fichera@gmail.com>

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
*/

#include <iostream>

#include <Eigen/Core>

#include <pinocchio/algorithm/frames.hpp>
#include <pinocchio/algorithm/jacobian.hpp>
#include <pinocchio/algorithm/joint-configuration.hpp>
#include <pinocchio/algorithm/kinematics.hpp>
#include <pinocchio/algorithm/rnea.hpp>
#include <pinocchio/parsers/urdf.hpp>

int main(int argc, char const* argv[])
{
    // Model
    pinocchio::Model model;
    pinocchio::urdf::buildModel("models/iiwa_bullet/model.urdf", model);
    pinocchio::Data data(model);

    // Frame ID
    const std::string name = "lbr_iiwa_link_7";
    const int id = model.getFrameId(name);

    // Random joint position and velocity
    Eigen::Matrix<double, 7, 1> q = Eigen::VectorXd::Random(7),
                                v = Eigen::VectorXd::Random(7);

    // Forward Kinematics
    pinocchio::forwardKinematics(model, data, q, v);
    pinocchio::framesForwardKinematics(model, data, q);

    // Jacobian
    pinocchio::Data::Matrix6x J(6, model.nv);
    J.setZero();
    pinocchio::computeFrameJacobian(model, data, q, id, J);

    // Pose
    pinocchio::SE3 pose = data.oMf[id];
    Eigen::Vector3d trans = pose.translation();
    Eigen::Matrix3d rot = pose.rotation();

    // Compare
    std::cout << "Jacobian derivation" << std::endl;
    std::cout << (J * v).transpose() << std::endl;

    std::cout << "Lie Algebra derivation" << std::endl;
    std::cout << pinocchio::log6(pose).toVector().transpose() << std::endl;

    return 0;
}


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <iostream>
#include <cmath>
#include <boost/detail/lightweight_test.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_bind.hpp>

using namespace boost::phoenix;
using namespace boost::phoenix::arg_names;
using namespace std;

    struct test
    {
        typedef void result_type;
        void operator()() const
        {
            cout << "Test lazy functions...\n";
        }
    };

    struct sqr
    {
        template <typename Arg>
        struct result
        {
            typedef Arg type;
        };

        template <typename Arg>
        Arg operator()(Arg n) const
        {
            return n * n;
        }
    };

    struct fact
    {
        template <typename Arg>
        struct result
        {
            typedef Arg type;
        };

        template <typename Arg>
        Arg operator()(Arg n) const
        {
            return (n <= 0) ? 1 : n * (*this)(n-1);
        }
    };

    struct power
    {
        template <typename Arg1, typename Arg2>
        struct result
        {
            typedef Arg1 type;
        };

        template <typename Arg1, typename Arg2>
        Arg1 operator()(Arg1 a, Arg2 b) const
        {
            return pow(a, b);
        }
    };

    struct add
    {
        template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
        struct result
        {
            typedef Arg1 type;
        };

        template <typename Arg1, typename Arg2, typename Arg3, typename Arg4>
        Arg1 operator()(Arg1 a, Arg2 b, Arg3 c, Arg4 d) const
        {
            return a + b + c + d;
        }
    };

int
main()
{
    int i5 = 5;
    double d5 = 5, d3 = 3;

    test()();
    BOOST_TEST(bind(sqr(), arg1)(i5) == (i5*i5));
    BOOST_TEST(bind(fact(), 4)() == 24);
    BOOST_TEST(bind(fact(), arg1)(i5) == 120);
    BOOST_TEST((int)bind(power(), arg1, arg2)(d5, d3) == (int)pow(d5, d3));
    BOOST_TEST((bind(sqr(), arg1) + 5)(i5) == ((i5*i5)+5));
    BOOST_TEST(bind(add(), arg1, arg1, arg1, arg1)(i5) == (5+5+5+5));

    int const ic5 = 5;
    // testing consts
    BOOST_TEST(bind(sqr(), arg1)(ic5) == (ic5*ic5));

    // From Steven Watanabe
    sqr s;
    int x = 2;
    int result = bind(ref(s), _1)(x);
    BOOST_TEST(result == 4);

    return boost::report_errors();
}


text:
// Copyright (C) 2006 Douglas Gregor <doug.gregor@gmail.com>

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

// An example using Boost.MPI's reduce() to concatenate strings.
#include <boost/mpicxx.hpp>
#include <iostream>
#include <string>
#include <boost/serialization/string.hpp> // Important for sending strings!
namespace mpi = boost::mpicxx;

/* Defining STRING_CONCAT_COMMUTATIVE lies to Boost.MPI by forcing it
 * to assume that string concatenation is commutative, which it is
 * not. However, doing so illustrates how the results of a reduction
 * can change when a non-commutative operator is assumed to be
 * commutative.
 */
#ifdef STRING_CONCAT_COMMUTATIVE
namespace boost { namespace mpicxx {

template<>
struct is_commutative<std::plus<std::string>, std::string> : mpl::true_ { };

} } // end namespace boost::mpicxx
#endif

int main(int argc, char* argv[])
{
  mpi::environment env(argc, argv);
  mpi::communicator world;

  std::string names[10] = { "zero ", "one ", "two ", "three ", "four ",
                            "five ", "six ", "seven ", "eight ", "nine " };

  std::string result;
  reduce(world,
         world.rank() < 10? names[world.rank()] : std::string("many "),
         result, std::plus<std::string>(), 0);

  if (world.rank() == 0)
    std::cout << "The result is " << result << std::endl;

  return 0;
}

max_stars_repo_name: aminiussi/mpicxx

max_issues_repo_name: aminiussi/mpicxx

max_forks_repo_name: aminiussi/mpicxx


text:
//---------------------------------------------------------------------------//
//  MIT License
//
//  Copyright (c) 2020-2021 Mikhail Komarov <nemo@nil.foundation>
//  Copyright (c) 2020-2021 Nikita Kaskov <nemo@nil.foundation>

//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.
//---------------------------------------------------------------------------//

#include <boost/filesystem/path.hpp>

#include <nil/crypto3/zk/snark/schemes/ppzksnark/r1cs_gg_ppzksnark.hpp>

namespace nil {
    namespace filecoin {
        template<typename SchemeType>
        struct scheme_params {
            typedef SchemeType scheme_type;
        };

        template<typename CurveType>
        struct scheme_params<crypto3::zk::snark::r1cs_gg_ppzksnark<CurveType>> {
            typedef CurveType curve_type;
            typedef typename curve_type::template g1_type<> g1_type;

            typedef crypto3::zk::snark::r1cs_gg_ppzksnark<CurveType> scheme_type;
            typedef typename scheme_type::verifying_key_type verifying_key_type;

            verifying_key_type vk;

            // Elements of the form ((tau^i * t(tau)) / delta) for i between 0 and
            // m-2 inclusive. Never contains points at infinity.
            std::vector<typename g1_type::value_type> h;

            // Elements of the form (beta * u_i(tau) + alpha v_i(tau) + w_i(tau)) / delta
            // for all auxiliary inputs. Variables can never be unconstrained, so this
            // never contains points at infinity.
            std::vector<typename g1_type::value_type> l;

            // QAP "A" polynomials evaluated at tau in the Lagrange basis. Never contains
            // points at infinity: polynomials that evaluate to zero are omitted from
            // the CRS and the prover can deterministically skip their evaluation.
            std::vector<typename g1_type::value_type> a;

            // QAP "B" polynomials evaluated at tau in the Lagrange basis. Needed
            // in G1 and G2 for C/B queries, respectively. Never contains points at
            // infinity for the same reason as the "A" polynomials.
            std::vector<typename g1_type::value_type> b_g1;
            std::vector<typename g1_type::value_type> b_g2;
        };
    }    // namespace filecoin
}    // namespace nil


text:
// Autogenerated from KST: please remove this line if doing any edits by hand!

#include <boost/test/unit_test.hpp>
#include "bits_simple.h"
#include <iostream>
#include <fstream>
#include <vector>

BOOST_AUTO_TEST_CASE(test_bits_simple) {
    std::ifstream ifs("src/fixed_struct.bin", std::ifstream::binary);
    kaitai::kstream ks(&ifs);
    bits_simple_t* r = new bits_simple_t(&ks);

    BOOST_CHECK_EQUAL(r->byte_1(), 80);
    BOOST_CHECK_EQUAL(r->byte_2(), 65);
    BOOST_CHECK_EQUAL(r->bits_a(), false);
    BOOST_CHECK_EQUAL(r->bits_b(), 4);
    BOOST_CHECK_EQUAL(r->bits_c(), 3);
    BOOST_CHECK_EQUAL(r->large_bits_1(), 300);
    BOOST_CHECK_EQUAL(r->spacer(), 5);
    BOOST_CHECK_EQUAL(r->large_bits_2(), 1329);
    BOOST_CHECK_EQUAL(r->normal_s2(), -1);
    BOOST_CHECK_EQUAL(r->byte_8_9_10(), 5259587);
    BOOST_CHECK_EQUAL(r->byte_11_to_14(), 1261262125);
    BOOST_CHECK_EQUAL(r->byte_15_to_19(), 293220057087LL);
    BOOST_CHECK_EQUAL(r->byte_20_to_27(), 18446744073709551615ULL);
    BOOST_CHECK_EQUAL(r->test_if_b1(), 123);

    delete r;
}