text:
#include "client.hpp"
#include "tools.hpp"

#include "base/bytes.hpp"
#include "base/log.hpp"

#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>

#include <cstring>

namespace websocket
{

WebSocketClient::WebSocketClient(boost::asio::io_context& ioc,
                                 ReceiveMessageCallback receiveData,
                                 CloseCallback socketClosed)
  : _resolver(boost::asio::make_strand(ioc))
  , _websocket(boost::asio::make_strand(ioc))
  , _ready{ false }
  , _receiveCallback{ std::move(receiveData) }
  , _closeCallback{ std::move(socketClosed) }
  , _lastGivenQueryId{ 0 }
{}

WebSocketClient::~WebSocketClient() noexcept
{
    disconnect();
}

bool WebSocketClient::connect(const std::string& host)
{
    if (_ready) {
        LOG_ERROR << "socket already connected to address[ip_v4]: " << _websocket.next_layer().remote_endpoint();
        return false;
    }

    boost::asio::ip::tcp::endpoint targetEndpoint;
    try {
        targetEndpoint = createEndpoint(host);
    }
    catch (const base::InvalidArgument& er) {
        LOG_ERROR << "target host ip decoding error: " << er.what();
        return _ready;
    }

    boost::system::error_code ec;
    auto const results = _resolver.resolve(targetEndpoint, ec);
    if (ec) {
        LOG_ERROR << "resolving error: " << ec.message();
        return _ready;
    }

    auto ep = boost::asio::connect(_websocket.next_layer(), results, ec);
    if (ec) {
        LOG_ERROR << "connection error: " << ec.message();
        return _ready;
    }

    _websocket.set_option(boost::beast::websocket::stream_base::timeout::suggested(boost::beast::role_type::client));
    static const std::string userAgentName{ std::string(BOOST_BEAST_VERSION_STRING) +
                                            std::string(" websocket-client") };
    _websocket.set_option(
      boost::beast::websocket::stream_base::decorator([](boost::beast::websocket::request_type& req) {
          req.set(boost::beast::http::field::user_agent, userAgentName);
      }));

    auto resolvedHost = host + ':' + std::to_string(ep.port());
    _websocket.handshake(resolvedHost, "/", ec);
    if (ec) {
        LOG_ERROR << "handshake failed: " << ec.message();
        close(boost::beast::websocket::close_code::internal_error);
        return _ready;
    }

    doRead();

    _ready = true;
    _websocket.control_callback(
      std::bind(&WebSocketClient::frameControl, this, std::placeholders::_1, std::placeholders::_2));

    return _ready;
}

void WebSocketClient::frameControl(boost::beast::websocket::frame_type kind,
                                   [[maybe_unused]] boost::string_view payload) noexcept
{
    if (kind == boost::beast::websocket::frame_type::close) {
        disconnect();
    }
}

void WebSocketClient::send(Command::Id commandId, const base::PropertyTree& args)
{
    if (!_ready) {
        RAISE_ERROR(base::LogicError, "client is not ready");
    }
    base::PropertyTree query;
    query.add("type", serializeCommandType(commandId));
    query.add("name", serializeCommandName(commandId));
    query.add("api", base::config::RPC_PUBLIC_API_VERSION);
    query.add("id", registerNewQuery(commandId));
    query.add("args", args);

    boost::beast::error_code ec;
    _websocket.write(boost::asio::buffer(query.toString()), ec);
    if (ec) {
        LOG_ERROR << "write failed: " << ec.message();
        close(boost::beast::websocket::close_code::internal_error);
    }
}

void WebSocketClient::disconnect() noexcept
{
    close(boost::beast::websocket::close_code::normal);
}

void WebSocketClient::close(boost::beast::websocket::close_code reason) noexcept
{
    if (_websocket.is_open()) {
        boost::beast::error_code ec;
        _websocket.close(reason, ec);

        if (ec) {
            LOG_ERROR << "closing failed: " << ec.message();
            return;
        }

        _ready = false;
        if (_closeCallback) {
            try {
                _closeCallback();
            }
            catch (const std::exception& ex) {
                LOG_DEBUG << "exception at close callback " << ex.what();
            }
            catch (...) {
                LOG_DEBUG << "unexpected exception at close callback";
            }
        }
    }
}

void WebSocketClient::doRead()
{
    _websocket.async_read(_readBuffer, boost::beast::bind_front_handler(&WebSocketClient::onRead, this));
}

void WebSocketClient::onRead(boost::beast::error_code ec, std::size_t bytesTransferred)
{
    if (ec == boost::beast::websocket::error::closed) {
        LOG_DEBUG << "Connection closed";
        close(boost::beast::websocket::close_code::bad_payload);
        return;
    }

    if (ec) {
        LOG_WARNING << "read failed: " << ec.message();
        return;
    }

    base::Bytes receivedData(bytesTransferred);
    std::memcpy(receivedData.getData(), _readBuffer.data().data(), bytesTransferred);
    _readBuffer.clear();

    doRead();

    base::PropertyTree receivedQuery;
    try {
        receivedQuery = base::parseJson(receivedData.toString());
    }
    catch (const base::Error& error) {
        LOG_ERROR << "client json parsing fail: " << error.what();
    }

    QueryId queryId{ 0 };
    std::string type;
    std::string status;
    base::PropertyTree commandArgs;
    try {
        queryId = receivedQuery.get<QueryId>("id");
        status = receivedQuery.get<std::string>("status");
        type = receivedQuery.get<std::string>("type");
        commandArgs = receivedQuery.getSubTree("result");
    }
    catch (const base::Error& e) {
        LOG_ERROR << "deserialization error " << e.what();
        LOG_DEBUG << "received_json: " << receivedQuery.toString();
        return;
    }

    if (type != "answer") {
        LOG_DEBUG << "wrong answer type";
        return;
    }

    try {
        auto commandId = _currentQueries.find(queryId);
        if (commandId == _currentQueries.end()) {
            LOG_DEBUG << "received unregistered answer id";
            return;
        }
        auto currentCommandId = Command::Id(commandId->second);
        if (!static_cast<bool>(currentCommandId & Command::Id(Command::Type::SUBSCRIBE))) {
            _currentQueries.erase(commandId);
        }
        _receiveCallback(currentCommandId, std::move(commandArgs));
    }
    catch (const base::Error& error) {
        LOG_ERROR << "receive callback execution error" << error.what();
    }
}

QueryId WebSocketClient::registerNewQuery(Command::Id commandId)
{
    auto currentId = ++_lastGivenQueryId;
    _currentQueries.insert({ currentId, commandId });
    return currentId;
}

}

max_stars_repo_name: heshu-by/likelib-ws

max_issues_repo_name: heshu-by/likelib-ws

max_forks_repo_name: heshu-by/likelib-ws


text:
#include <boost/python.hpp>
#include <lightspeed/tensor.hpp>

using namespace lightspeed;
using namespace boost::python;

/**
 * Compute the UED or X-Ray elastic scattering intensity for a molecule,
 * averaging over a molecular orientation quadrature grid, and accounting for
 * anisotropy and/or modifications to the scattering intensity definition. Uses
 * the independent atom model.
 *
 * First, the scattering angles theta are computed according to the elastic
 * scattering formula,
 *
 * s = 4 pi / lambda * sin(theta / 2) => theta = 2 arcsin(s * lambda / (4 * pi))
 *
 * This will throw if s * lambda / (4 * pi) is outside [+1, -1]
 *
 * Next, the scattering vectors are computed according to,
 *
 * \vec s = {sx, sy, sz} = s { cos(theta/2)sin(eta), sin(theta/2), cos(theta/2)cos(eta) }
 *
 * Next the (isotropic) atomic scattering intensity is computed according to,
 *
 * D(s) = \sum_{A} | f_A (s) |^2
 *
 * Next, the scattering intensity is computed for each point in the molecular
 * orientation quadrature { R, w_R }, and summed up, including the possible
 * anisotropy weighting factor a(R).
 *
 * I(s, eta) = \sum_{R} w_{R} a(R) I_R (s, eta)
 *
 * Here the raw scattering intensity for a given molecular orientation is computed as,
 *
 * I_R (s, eta) = | \sum_{A} exp(i \vec s * (R^\dagger r_{A})) |^2
 *
 * e.g., the diffraction pattern of the rotated molecular geometry.
 *
 * If the "anisotropy" option is set to true, the factor a(R) will be computed as
 * the square of the projection of the rotated z axis on the original z axis
 * (cos^2 zeta perpendicular one-photon pump-probe anisotropy)
 *
 * If the "mod" option is set to true, the modified scattering intensity will
 * replace the raw scattering intensity in the result:
 *
 * M_R (s, eta) = [I_R (s, eta) - D(s)] / D(s)
 *
 * @param lambda (double) - probe wavelength (e.g., deBroglie wavelength) [Angstrom].
 * @param ss (Tensor of shape (ns,)) - s values to collocate to [Angstrom^-1]
 * @param etas (Tensor of shape (neta,)) - eta values to collocate to [Radian]
 * @param xyzs (Tensor of shape (natom, 3)) - x, y, z centers of atoms [Anstrom]
 * @param fs (Tensor of shape (natom, ns)) - atomic form factors f_A (s)
 *  computed for the above atoms and s values. Specialization to UED or X-Ray
 *  can be made outside of the present code by computing these factors
 *  appropriately. E.g., f_A^UED (s) = 1 / s^2 (Z_A - f_A^XRAY (s)).
 * @param Rs (Tensor of shape (nrot, 3, 3)) - rotation matrices in the
 *  molecular orientation quadrature grid.
 * @param ws (Tensor of shape (nrot,)) - weights of rotation matrices in the
 *  molecular orientation quadrature grid.
 * @param anisotropy (bool) - a(R) will be computed as R_zz'^2 if true
 *  (perpendicular one-photon anisotropy), else a(R) will be set to 1 if false
 *  (parallel arrangement or isotropic pump-probe experiment).
 * @param mod (bool) - compute M(s,eta) if true, else compute I(s,eta) if false.
 *
 * @return I (Tensor of shape (ns, neta)) - molecular scattering intensity I(s, eta)
 *  or M(s, eta)
 **/
lightspeed::shared_ptr<Tensor> compute_diffraction(
    double lambda,
    const lightspeed::shared_ptr<Tensor>& ss,
    const lightspeed::shared_ptr<Tensor>& etas,
    const lightspeed::shared_ptr<Tensor>& xyzs,
    const lightspeed::shared_ptr<Tensor>& fs,
    const lightspeed::shared_ptr<Tensor>& Rs,
    const lightspeed::shared_ptr<Tensor>& ws,
    bool anisotropy,
    bool mod
    )
{
    // Validity checks
    ss->ndim_error(1);
    etas->ndim_error(1);
    xyzs->ndim_error(2);
    xyzs->shape_error({xyzs->shape()[0], 3});
    fs->shape_error({xyzs->shape()[0], ss->shape()[0]});
    Rs->ndim_error(3);
    Rs->shape_error({Rs->shape()[0], 3, 3});
    ws->shape_error({Rs->shape()[0]});

    // Sizes
    size_t ns = ss->shape()[0];
    size_t neta = etas->shape()[0];
    size_t nA = xyzs->shape()[0];
    size_t nR = Rs->shape()[0];

    // Pointers
    const double* sp = ss->data().data();
    const double* etap = etas->data().data();
    const double* xyzp = xyzs->data().data();
    const double* fp = fs->data().data();
    const double* Rp = Rs->data().data();
    const double* wp = ws->data().data();

    // Scattering vectors
    lightspeed::shared_ptr<Tensor> sxyz(new Tensor({ns, neta, 3}));
    double* sxyzp = sxyz->data().data();
    for (size_t sind = 0; sind < ns; sind++) {
        double arg = lambda * sp[sind] / (4.0 * M_PI);
        if (arg > 1.0 or arg < -1.0) throw std::runtime_error("Invalid s:" + std::to_string(sp[sind]));
        double theta = 2.0 * asin(arg);
        for (size_t eind = 0; eind < neta; eind++) {
            sxyzp[3 * (sind * neta + eind) + 0] = sp[sind] * cos(theta / 2.0) * sin(etap[eind]);
            sxyzp[3 * (sind * neta + eind) + 1] = sp[sind] * sin(theta / 2.0);
            sxyzp[3 * (sind * neta + eind) + 2] = sp[sind] * cos(theta / 2.0) * cos(etap[eind]);
        }
    }

    // Atomic scattering intensity
    lightspeed::shared_ptr<Tensor> Ds(new Tensor({ns}));
    double* Dp = Ds->data().data();
    for (size_t sind = 0; sind < ns; sind++) {
        for (size_t A = 0; A < nA; A++) {
            Dp[sind] += pow(fp[A * ns + sind], 2);
        }
    }

    // Target
    lightspeed::shared_ptr<Tensor> Is(new Tensor({ns, neta}));
    double* Ip = Is->data().data();

    // #pragma omp parallel for schedule(static, 16)
    #pragma omp parallel for schedule(static)
    for (size_t P = 0; P < ns * neta; P++) {
        size_t sind = P / neta;
        size_t eind = P % neta;
        double sx = sxyzp[3*P + 0];
        double sy = sxyzp[3*P + 1];
        double sz = sxyzp[3*P + 2];
        double D = Dp[sind];
        double I = 0.0;
        for (size_t Rind = 0; Rind < Rs->shape()[0]; Rind++) {
            // Rotation quadrature
            const double* R2p = Rp + Rind * 9;
            double w = wp[Rind];
            // Anisotropy weight
            if (anisotropy) {
                w *= pow(R2p[8], 2);
            }
            // Diffraction cross section
            double NR = 0.0;
            double NI = 0.0;
            for (size_t A = 0; A < xyzs->shape()[0]; A++) {
                // Rotate coordinates to frame
                double x = R2p[0] * xyzp[3*A + 0] + R2p[1] * xyzp[3*A + 1] + R2p[2] * xyzp[3*A + 2];
                double y = R2p[3] * xyzp[3*A + 0] + R2p[4] * xyzp[3*A + 1] + R2p[5] * xyzp[3*A + 2];
                double z = R2p[6] * xyzp[3*A + 0] + R2p[7] * xyzp[3*A + 1] + R2p[8] * xyzp[3*A + 2];
                double theta = sx * x + sy * y + sz * z;
                double fA = fp[A * ns + sind];
                NR += fA * cos(theta);
                NI += fA * sin(theta);
            }
            double F = NR * NR + NI * NI;
            if (mod) {
                F = (F - D) / D;
            }
            I += w * F;
        }
        Ip[P] = I;
    }

    return Is;
}

BOOST_PYTHON_MODULE(pyplugin)
{
    def("compute_diffraction", compute_diffraction);
}

ext: cpp

max_stars_repo_name: cbannwarth/aimsprop

max_issues_repo_name: cbannwarth/aimsprop

max_forks_repo_name: cbannwarth/aimsprop


text:
//
// msgpack::rpc::session - MessagePack-RPC for C++
//
// Copyright (C) 2009-2010 FURUHASHI Sadayuki
//
//    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 "session.h"

#include "atomic_ops.h"
#include "exception_impl.h"
#include "future_impl.h"
#include "request_impl.h"
#include "session_impl.h"

#include <boost/log/trivial.hpp>

namespace msgpack {
namespace rpc {

session_impl::session_impl(const address& addr, loop lo) :
    m_addr(addr),
    m_loop(lo),
    m_msgid_rr(1),
    m_timeout(30),
    m_step_timer(m_loop->io_service())
{
    // TODO: We can improve performance here by only arming the
    //       the step timer when there are actually any requests
    //       to process. However, it will require some refactoring
    //       of the request table and session impl code to avoid
    //       race conditions.
    arm_step_timer();
}

session_impl::~session_impl()
{
    disarm_step_timer();
}

void session_impl::build(const builder& b)
{
    m_tran = b.build(this, m_addr);
    m_timeout = b.get_timeout();
}

shared_session
session_impl::create(const builder& b, const address addr, loop lo)
{
    shared_session s(new session_impl(addr, lo));
    s->build(b);
    return s;
}

future session_impl::send_request_impl(msgid_t msgid, std::string method,
    sbuffer* sbuf)
{
    BOOST_LOG_TRIVIAL(debug) << "sending... msgid=" << msgid;
    shared_future f(new future_impl(msgid, shared_from_this(), m_loop));
    m_reqtable.insert(msgid, f);

    m_tran->send_data(sbuf);
    return future(method, f);
}

future session_impl::send_request_impl(msgid_t msgid, std::string method,
    std::unique_ptr<with_shared_zone<vrefbuffer> > vbuf)
{
    BOOST_LOG_TRIVIAL(debug) << "sending... msgid=" <<  msgid;

    shared_future f(new future_impl(msgid, shared_from_this(), m_loop));
    m_reqtable.insert(msgid, f);

    m_tran->send_data(std::move(vbuf));
    return future(method, f);
}

void session_impl::send_notify_impl(sbuffer* sbuf)
{
    m_tran->send_data(sbuf);
}

void session_impl::send_notify_impl(auto_vreflife vbuf)
{
    m_tran->send_data(std::move(vbuf));
}

msgid_t session_impl::next_msgid()
{
    return atomic_increment(&m_msgid_rr);
}

void session_impl::arm_step_timer()
{
    m_step_timer.expires_from_now(boost::posix_time::seconds(1));
    m_step_timer.async_wait(std::bind(
            &session_impl::step_timer_handler, this, std::placeholders::_1));
}

void session_impl::disarm_step_timer()
{
    m_step_timer.cancel();
}

void session_impl::step_timer_handler(const boost::system::error_code& err)
{
    if (err == boost::asio::error::operation_aborted) {
        return;
    }

    std::vector<shared_future> timedout;
    m_reqtable.step_timeout(&timedout);
    if (!timedout.empty()) {
        for (std::vector<shared_future>::iterator it = timedout.begin();
                it != timedout.end(); ++it) {
            shared_future& f = *it;
            f->set_result(object(), TIMEOUT_ERROR, auto_zone());
#ifndef NDEBUG
            BOOST_LOG_TRIVIAL(warning) << "timeout " << f->msgid();
#endif
        }
    }

    arm_step_timer();
}

void session_impl::step_timeout(std::vector<shared_future>* timedout)
{
    m_reqtable.step_timeout(timedout);
}

void session_impl::on_connect_failed()
{
    std::vector<shared_future> all;
    m_reqtable.take_all(&all);
    for (std::vector<shared_future>::iterator it = all.begin();
            it != all.end(); ++it) {
        shared_future& f = *it;
        f->set_result(object(), CONNECT_ERROR, auto_zone());
    }
}

void session_impl::on_system_error(const boost::system::error_code& err)
{
    std::vector<shared_future> all;
    m_reqtable.take_all(&all);
    for (std::vector<shared_future>::iterator it = all.begin();
            it != all.end(); ++it) {
        shared_future& f = *it;
        // FIXME
        f->set_result(object(), CONNECT_ERROR, auto_zone());
    }
}

void session_impl::on_response(msgid_t msgid,
                               object result, object error, auto_zone z)
{
    BOOST_LOG_TRIVIAL(debug) << "response msgid=" << msgid;
    shared_future f = m_reqtable.take(msgid);
    if (!f) {
        BOOST_LOG_TRIVIAL(error) << "no entry on request table for msgid=" << msgid;
        return;
    }
    f->set_result(result, error, std::move(z));
}

void session_impl::on_notify(object method, object params, auto_zone z)
{
    // TODO
}

const address& session::get_address() const
{
    return m_pimpl->get_address();
}

loop session::get_loop()
{
    return m_pimpl->get_loop();
}

void session::set_timeout(unsigned int sec)
{
    m_pimpl->set_timeout(sec);
}

unsigned int session::get_timeout() const
{
    return m_pimpl->get_timeout();
}

future session::send_request_impl(msgid_t msgid, std::string method,
    std::unique_ptr<with_shared_zone<vrefbuffer> > vbuf)
{
    return m_pimpl->send_request_impl(msgid, method, std::move(vbuf));
}

future session::send_request_impl(msgid_t msgid, std::string method,
    sbuffer* sbuf)
{
    return m_pimpl->send_request_impl(msgid, method, sbuf);
}

void session::send_notify_impl(sbuffer* sbuf)
{
    return m_pimpl->send_notify_impl(sbuf);
}

void session::send_notify_impl(std::unique_ptr<with_shared_zone<vrefbuffer> > vbuf)
{
    return m_pimpl->send_notify_impl(std::move(vbuf));
}

msgid_t session::next_msgid()
{
    return m_pimpl->next_msgid();
}

}  // namespace rpc
}  // namespace msgpack

ext: cc

max_stars_repo_name: moldyreed/msgpack-rpc-boost

max_issues_repo_name: moldyreed/msgpack-rpc-boost

max_forks_repo_name: moldyreed/msgpack-rpc-boost


text:
#pragma once

#include "../linesegment.hh"
#include "../../../util/Maybe.hh"

#include <Eigen/Core>

namespace bold
{
  template<typename T>
  class LineSegment2 : public LineSegment<T, 2>
  {
  public:
    typedef Eigen::Matrix<T,2,1> Point;

    LineSegment2(Point const& p1, Point const& p2)
    : LineSegment<T, 2>::LineSegment(p1, p2)
    {}

    LineSegment2(T x1, T y1, T x2, T y2)
    : LineSegment<T, 2>::LineSegment(Point(x1, y1), Point(x2, y2))
    {}

    using LineSegment<T, 2>::LineSegment;
    using LineSegment<T, 2>::operator=;

    Maybe<Point> tryIntersect(LineSegment2<T> const& other) const
    {
      double t;
      double u;
      return tryIntersect(other, t, u);
    }

    /**
    * Attempt to intersect two line segments.
    * Note that even if the line segments do not intersect, the t and u values will be set.
    * @param other the line to attempt intersection of this line with
    * @param t (output) the distance along this line at which intersection would occur, or NaN if lines are collinear/parallel
    * @param u (output) the distance along the other line at which intersection would occur, or NaN if lines are collinear/parallel
    * @return The point of intersection if within the line segments, or empty.
    */
    Maybe<Point> tryIntersect(LineSegment2<T> const& other, double& t, double& u) const
    {
      // http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect

      Eigen::Vector2d pos1 = this->p1().template cast<double>();    // p
      Eigen::Vector2d pos2 = other.p1().template cast<double>();    // q
      Eigen::Vector2d dir1 = this->delta().template cast<double>(); // r
      Eigen::Vector2d dir2 = other.delta().template cast<double>(); // s

      // t = (q − p) × s / (r × s)
      // u = (q − p) × r / (r × s)

      double denom = fake2dCross(dir1, dir2);

      if (denom == 0)
      {
        // lines are collinear or parallel
        t = std::numeric_limits<double>::quiet_NaN();
        u = std::numeric_limits<double>::quiet_NaN();
        return Maybe<Point>::empty();
      }

      double t_numer = fake2dCross(pos2 - pos1, dir2);
      double u_numer = fake2dCross(pos2 - pos1, dir1);

      t = t_numer / denom;
      u = u_numer / denom;

      if (t < 0 || t > 1 || u < 0 || u > 1)
      {
        // line segments do not intersect within their ranges
        return Maybe<Point>::empty();
      }

      Eigen::Vector2d intersectionPoint = pos1 + dir1 * t;

      // If we are using integers, be sure to round the result before casting
      if (std::is_same<T,int>())
      {
        Eigen::Vector2d rounded = intersectionPoint.unaryExpr([](double v) { return round(v); });
        return Maybe<Point>(rounded.cast<T>());
      }

      return Maybe<Point>(intersectionPoint.cast<T>());
    }

  private:
    /**
     * Returns the magnitude of the vector that would result from a regular
     * 3D cross product of the input vectors, taking their Z values implicitly
     * as 0 (i.e. treating the 2D space as a plane in the 3D space)
     */
    inline static double fake2dCross(Eigen::Vector2d const& a, Eigen::Vector2d const& b)
    {
      return a.x()*b.y() - a.y()*b.x();
    }
  };

  typedef LineSegment2<double> LineSegment2d;
  typedef LineSegment2<float> LineSegment2f;
}

ext: hh

max_stars_repo_name: drewnoakes/bold-humanoid

max_issues_repo_name: drewnoakes/bold-humanoid

max_forks_repo_name: drewnoakes/bold-humanoid


text:
#include <test/test_bitcoin.h>
#include <tradelayer/createpayload.h>
#include <util/strencodings.h>

#include <boost/test/unit_test.hpp>
#include <stdint.h>
#include <string>
#include <vector>

BOOST_FIXTURE_TEST_SUITE(tradelayer_create_payload_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(payload_simple_send)
{
    // Simple send [type 0, version 0]
    std::vector<unsigned char> vch = CreatePayload_SimpleSend(
        static_cast<uint32_t>(1),          // property: MSC
        static_cast<int64_t>(100000000));  // amount to transfer: 1.0 MSC (in willets)

    BOOST_CHECK_EQUAL(HexStr(vch), "00000180c2d72f");
}

BOOST_AUTO_TEST_CASE(payload_send_all)
{
    // Send to owners [type 4, version 0]
    std::vector<unsigned char> vch = CreatePayload_SendAll();

    BOOST_CHECK_EQUAL(HexStr(vch), "0004");
}

BOOST_AUTO_TEST_CASE(payload_dex_offer)
{
    // Sell tokens for bitcoins [type 20, version 1]
    std::vector<unsigned char> vch = CreatePayload_DExSell(
        static_cast<uint32_t>(1),         // property: MSC
        static_cast<int64_t>(100000000),  // amount to transfer: 1.0 MSC (in willets)
        static_cast<int64_t>(20000000),   // amount desired: 0.2 BTC (in satoshis)
        static_cast<uint8_t>(10),         // payment window in blocks
        static_cast<int64_t>(10000),      // commitment fee in satoshis
        static_cast<uint8_t>(1));         // sub-action: new offer

    BOOST_CHECK_EQUAL(HexStr(vch),
        "01140180c2d72f80dac4090a904e01");
}

BOOST_AUTO_TEST_CASE(payload_meta_dex_new_trade)
{
    // Trade tokens for tokens [type 25, version 0]
    std::vector<unsigned char> vch = CreatePayload_MetaDExTrade(
        static_cast<uint32_t>(1),          // property: MSC
        static_cast<int64_t>(250000000),   // amount for sale: 2.5 MSC
        static_cast<uint32_t>(31),         // property desired: TetherUS
        static_cast<int64_t>(5000000000)); // amount desired: 50.0 TetherUS

    BOOST_CHECK_EQUAL(HexStr(vch),
        "00190180e59a771f80e497d012");
}

BOOST_AUTO_TEST_CASE(payload_contractdex_cancel_all)
{

    std::vector<unsigned char> vch = CreatePayload_ContractDexCancelAll(
        static_cast<uint8_t>(7)     // contractId
        );

    BOOST_CHECK_EQUAL(HexStr(vch),
        "002007");
}

BOOST_AUTO_TEST_CASE(payload_accept_dex_offer)
{
    // Purchase tokens with bitcoins [type 22, version 0]
    std::vector<unsigned char> vch = CreatePayload_DExAccept(
        static_cast<uint32_t>(1),          // property: MSC
        static_cast<int64_t>(130000000));  // amount to transfer: 1.3 MSC (in willets)

    BOOST_CHECK_EQUAL(HexStr(vch), "00160180c9fe3d");
}

BOOST_AUTO_TEST_CASE(payload_create_property)
{
    // Create property [type 50, version 0]
    std::vector<int> numbers;
    numbers.push_back(0);
    std::string name = "Lihki Coin";
    std::string url = "www.parcero.col";
    std::string data = "";

    std::vector<unsigned char> vch = CreatePayload_IssuanceFixed(
        static_cast<uint16_t>(1),            // property type: indivisible tokens
        static_cast<uint32_t>(0),            // previous property: none
        name,                                // name
        url,                                 // url
        data,                                // data
        static_cast<int64_t>(1000000),       // number of units to create
        numbers);

    BOOST_CHECK_EQUAL(HexStr(vch),
        "003201004c69686b6920436f696e007777772e7061726365726f2e636f6c0000c0843d00");
}

BOOST_AUTO_TEST_CASE(payload_create_property_empty)
{
    // Create property [type 50, version 0]
    std::vector<int> numbers;
    numbers.push_back(0);
    std::string name = "";
    std::string url = "";
    std::string data = "";

    std::vector<unsigned char> vch = CreatePayload_IssuanceFixed(
        static_cast<uint16_t>(1),        // property type: indivisible tokens
        static_cast<uint32_t>(0),        // previous property: none
        name,                 // name
        url,                 // url
        data,                 // data
        static_cast<int64_t>(1000000),  // number of units to create
        numbers);

    BOOST_CHECK_EQUAL(vch.size(), 11);
}

BOOST_AUTO_TEST_CASE(payload_create_property_full)
{
    // Create property [type 50, version 0]
    std::vector<int> numbers;
    numbers.push_back(0);
    std::string name = std::string(700, 'x');
    std::string url = std::string(700, 'x');
    std::string data = std::string(700, 'x');

    std::vector<unsigned char> vch = CreatePayload_IssuanceFixed(
        static_cast<uint16_t>(1),        // property type: indivisible tokens
        static_cast<uint32_t>(0),        // previous property: none
        name,           // name
        url,           // url
        data,           // data
        static_cast<int64_t>(1000000),  // number of units to create
        numbers);

    BOOST_CHECK_EQUAL(vch.size(), 776);
}

BOOST_AUTO_TEST_CASE(payload_create_managed_property)
{
    // create managed property [type 54, version 0]
    std::vector<int> numbers;
    numbers.push_back(0);
    std::string name = "Name";
    std::string url = "www.website.com";
    std::string data = "some data";

    std::vector<unsigned char> vch = CreatePayload_IssuanceManaged(
        static_cast<uint16_t>(1),            // property type: indivisible tokens
        static_cast<uint32_t>(0),            // previous property: none
        name,                                // name
        url,                                 // url
        data,                                // data
        numbers);

    BOOST_CHECK_EQUAL(HexStr(vch),"003601004e616d65007777772e776562736974652e636f6d00736f6d6520646174610000");
}

BOOST_AUTO_TEST_CASE(payload_create_managed_property_empty)
{
    // create managed property [type 54, version 0]
    std::vector<int> numbers;
    numbers.push_back(0);
    std::string name = "";
    std::string url = "";
    std::string data = "";
    std::vector<unsigned char> vch = CreatePayload_IssuanceManaged(
        static_cast<uint16_t>(1),   // property type: indivisible tokens
        static_cast<uint32_t>(0),   // previous property: none
        name,                       // name
        url,                        // url
        data,                       // data
        numbers);

    BOOST_CHECK_EQUAL(vch.size(), 8);

}

BOOST_AUTO_TEST_CASE(payload_create_managed_property_full)
{
    // create managed property [type 54, version 0]
    std::vector<int> numbers;
    numbers.push_back(0);
    numbers.push_back(1);
    std::string name = std::string(700, 'x');
    std::string url = std::string(700, 'x');
    std::string data = std::string(700, 'x');
    std::vector<unsigned char> vch = CreatePayload_IssuanceManaged(
        static_cast<uint16_t>(1),   // property type: indivisible tokens
        static_cast<uint32_t>(0),   // previous property: none
        name,                       // name
        url,                        // url
        data,                       // data
        numbers);
    BOOST_CHECK_EQUAL(vch.size(), 774);

}

BOOST_AUTO_TEST_CASE(payload_grant_tokens)
{
    // Grant tokens [type 55, version 0]
    std::vector<unsigned char> vch = CreatePayload_Grant(
        static_cast<uint32_t>(8),                  // property: SP #8
        static_cast<int64_t>(1000)                // number of units to issue
    );

    BOOST_CHECK_EQUAL(HexStr(vch),"003708e807");
}

BOOST_AUTO_TEST_CASE(payload_revoke_tokens)
{
    // Revoke tokens [type 56, version 0]
    std::vector<unsigned char> vch = CreatePayload_Revoke(
        static_cast<uint32_t>(8),                                   // property: SP #8
        static_cast<int64_t>(1000)                                  // number of units to revoke
    );

    BOOST_CHECK_EQUAL(HexStr(vch),
        "003808e807");
}

BOOST_AUTO_TEST_CASE(payload_revoke_tokens_empty)
{
    // Revoke tokens [type 56, version 0]
    std::vector<unsigned char> vch = CreatePayload_Revoke(
        static_cast<uint32_t>(8),    // property: SP #8
        static_cast<int64_t>(1000)  // number of units to revoke
    );
    BOOST_CHECK_EQUAL(vch.size(), 5);
}

BOOST_AUTO_TEST_CASE(payload_revoke_tokens_full)
{
    // Revoke tokens [type 56, version 0]
    std::vector<unsigned char> vch = CreatePayload_Revoke(
        static_cast<uint32_t>(8),    // property: SP #8
        static_cast<int64_t>(1000)  // number of units to revoke
    );
    BOOST_CHECK_EQUAL(vch.size(), 5);
}

BOOST_AUTO_TEST_CASE(payload_change_property_manager)
{
    // Change property manager [type 70, version 0]
    std::vector<unsigned char> vch = CreatePayload_ChangeIssuer(
        static_cast<uint32_t>(13));  // property: SP #13

    BOOST_CHECK_EQUAL(HexStr(vch), "00460d");
}

// BOOST_AUTO_TEST_CASE(payload_create_contract)
// {
//     std::vector<unsigned char> vch = CreatePayload_CreateContract(
//         static_cast<uint32_t>(1),            // denomType: 1 (dUSD)
//         std::string("ALL/dUSD"),             // name
//         static_cast<uint32_t>(3000),         // blocks until expiration
//         static_cast<uint32_t>(2),            // notional size
//         static_cast<uint32_t>(3),            // collateral currency
//         static_cast<uint64_t>(3)             // margin rpcrequirements
//     );
//     BOOST_CHECK_EQUAL(HexStr(vch),"00280101414c4c2f6455534400b81702030300");
// }

// BOOST_AUTO_TEST_CASE(payload_trade_contract)
// {
//     std::vector<unsigned char> vch = CreatePayload_ContractDexTrade(
//         static_cast<uint32_t>(7),            // contractId
//         static_cast<uint64_t>(1000),         // amount for sale
//         static_cast<uint64_t>(644),          // effective price
//         static_cast<uint8_t>(2)              // trading action
//     );
//         BOOST_CHECK_EQUAL(HexStr(vch),"001d07e807840502");
// }

BOOST_AUTO_TEST_CASE(payload_cancel_orders_by_address)
{
    std::vector<unsigned char> vch = CreatePayload_ContractDexCancelAll(
        static_cast<uint64_t>(7)         // contractId
    );
    BOOST_CHECK_EQUAL(HexStr(vch),"002007");
}

BOOST_AUTO_TEST_CASE(payload_cancel_orders_by_block)
{
    std::vector<unsigned char> vch = CreatePayload_ContractDexCancelOrderByTxId(
        static_cast<int>(1),                  // block
        static_cast<unsigned int>(7)         // idx
    );
    BOOST_CHECK_EQUAL(HexStr(vch),"00220107");}

BOOST_AUTO_TEST_CASE(payload_issuance_pegged)
{
  std::string name = "dUSD";
    std::vector<unsigned char> vch = CreatePayload_IssuancePegged(
        static_cast<uint16_t>(1),            // property type
        static_cast<uint32_t>(0),            // previous propertyId
        name,                                // name
        static_cast<uint32_t>(2),            // propertyId
        static_cast<uint32_t>(3),            // contractId
        static_cast<uint32_t>(78563)         // amount
    );
        BOOST_CHECK_EQUAL(HexStr(vch),"0064010064555344000203e3e504");
}

BOOST_AUTO_TEST_CASE(payload_send_pegged)
{

  std::vector<unsigned char> vch = CreatePayload_SendPeggedCurrency(static_cast<uint32_t>(0),              // propertyId
								    static_cast<uint32_t>(78563));         // amount
  BOOST_CHECK_EQUAL(HexStr(vch),"006600e3e504");
  BOOST_CHECK_EQUAL(vch.size(), 6);
}

BOOST_AUTO_TEST_CASE(payload_redemption_pegged)
{
    std::vector<unsigned char> vch = CreatePayload_RedemptionPegged(
        static_cast<uint32_t>(6),        // propertyId
        static_cast<uint32_t>(5),        // contractId
        static_cast<uint64_t>(0)         // amount
    );

    BOOST_CHECK_EQUAL(HexStr(vch),"0065060500");
    BOOST_CHECK_EQUAL(vch.size(), 5);
}

BOOST_AUTO_TEST_CASE(payload_close_position)
{

    std::vector<unsigned char> vch = CreatePayload_ContractDexClosePosition(
        static_cast<uint32_t>(5)        // contractId
    );

    BOOST_CHECK_EQUAL(HexStr(vch),"002105");
    BOOST_CHECK_EQUAL(vch.size(), 3);
}

BOOST_AUTO_TEST_CASE(payload_send_trade)
{
    std::vector<unsigned char> vch = CreatePayload_MetaDExTrade(
        static_cast<uint32_t>(1),         //propertyId for sale
        static_cast<uint64_t>(1000),      // amount for sale
        static_cast<uint32_t>(4),         // propertyId desired
        static_cast<uint64_t>(200)         // amount desired
    );

    BOOST_CHECK_EQUAL(HexStr(vch),"001901e80704c801");
    BOOST_CHECK_EQUAL(vch.size(), 8);
}

BOOST_AUTO_TEST_CASE(payload_send_dex_offer)
{
    std::vector<unsigned char> vch = CreatePayload_DExSell(
        static_cast<uint32_t>(1),         //propertyId
        static_cast<uint64_t>(600),       // amount for sale
        static_cast<uint64_t>(4),         // amount desired
        static_cast<uint8_t>(2000),       // time limit
        static_cast<uint64_t>(3),         // min fee
        static_cast<uint32_t>(1)          // sub action
    );

    BOOST_CHECK_EQUAL(HexStr(vch),"011401d80404d0010301");
    BOOST_CHECK_EQUAL(vch.size(), 10);
}

BOOST_AUTO_TEST_CASE(payload_send_dex_accept)
{
    std::vector<unsigned char> vch = CreatePayload_DExAccept(
        static_cast<uint32_t>(1),         //propertyId
        static_cast<uint64_t>(600)       // amount accepted
    );

    BOOST_CHECK_EQUAL(HexStr(vch),"001601d804");
    BOOST_CHECK_EQUAL(vch.size(), 5);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: patrickdugan/BlockPo-to-Tradelayer

max_issues_repo_name: patrickdugan/BlockPo-to-Tradelayer

max_forks_repo_name: patrickdugan/BlockPo-to-Tradelayer


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

#include "osrm/partitioner.hpp"
#include "osrm/partitioner_config.hpp"

#include <tbb/task_scheduler_init.h> // default_num_threads

BOOST_AUTO_TEST_SUITE(library_partition)

BOOST_AUTO_TEST_CASE(test_partition_with_invalid_config)
{
    using namespace osrm;

    osrm::PartitionerConfig config;
    config.requested_num_threads = tbb::task_scheduler_init::default_num_threads();
    BOOST_CHECK_THROW(osrm::partition(config),
                      std::exception); // including osrm::util::exception, etc.
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: asaveljevs/osrm-backend

max_issues_repo_name: serarca/osrm-backend

max_forks_repo_name: serarca/osrm-backend


text:
//
// Created by kevin on 2/19/17.
//
//

#ifndef CAFFE_STORE_HPP
#define CAFFE_STORE_HPP

#include <string>
#include <vector>
#include <boost/ptr_container/ptr_vector.hpp>
using namespace std;

class ImagePair {
public:
	ImagePair(const string &img1, const string &img2, const string &flow1, const string &flow2) : img1(img1),
																								  img2(img2),
																								  flow1(flow1),
																								  flow2(flow2) {}

	string img1;
	string img2;
	string flow1;
	string flow2;
};
#endif //CAFFE_STORE_HPP

ext: hpp

max_forks_repo_name: ParrtZhang/Optical-Flow-Guided-Feature


text:
// Part of the Jade Engine -- Copyright (c) Christian Neumüller 2012--2013
// This file is subject to the terms of the BSD 2-Clause License.
// See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause

#ifndef SOUNDMANAGER_HPP_INCLUDED
#define SOUNDMANAGER_HPP_INCLUDED SOUNDMANAGER_HPP_INCLUDED

#include "ressys/AutoResource.hpp"
#include "ressys/AutoSoundBuffer.hpp"
#include "ressys/VFileMusic.hpp"

#include <boost/ptr_container/ptr_vector.hpp>

#include <memory>
#include <string>

typedef AutoResource<sf::Sound, sf::SoundBuffer> AutoSound;

class SoundManager {
public:
    SoundManager();
    ~SoundManager();

    void playSound(std::string const& name);
    void playSound(ResourceTraits<sf::SoundBuffer>::Ptr const& buf);
    void playSound(AutoSound& sound);

    void setBackgroundMusic(std::string const& name, sf::Time fadeDuration = sf::Time::Zero);
    void setBackgroundMusic(VFileMusic& music, sf::Time fadeDuration = sf::Time::Zero);

    void fade(sf::Time elapsedTime);
    void tidy();

private:
    struct FadedMusic {
        FadedMusic(): target(0), increment(0) { }
        FadedMusic(VFileMusic& music, float target, sf::Time fadeDuration);

        FadedMusic& operator= (FadedMusic&& rhs);
        bool fade(sf::Time elapsedTime);

        float target;
        std::unique_ptr<VFileMusic> music;
        float increment;
    };

    FadedMusic m_previousMusic;
    FadedMusic m_currentMusic;
    boost::ptr_vector<AutoSound> m_playingSounds;
};

#endif


text:
// Boost.TypeErasure library
//
// Copyright 2011 Steven Watanabe
//
// 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)
//
// $Id$

#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/builtin.hpp>
#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/mpl/vector.hpp>

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

using namespace boost::type_erasure;

template<class T = _self>
struct common : ::boost::mpl::vector<
    copy_constructible<T>,
    typeid_<T>
> {};

typedef any<boost::mpl::vector<common<> > > any1_type;

struct test_class
{
    int i;
};

test_class operator+(const test_class& lhs, const any1_type& rhs)
{
    test_class result = { lhs.i + any_cast<int>(rhs) };
    return result;
}

BOOST_AUTO_TEST_CASE(test_basic)
{
    typedef boost::mpl::vector<common<>, addable<_self, any1_type> > test_concept;
    any1_type a1(1);
    test_class v = { 2 };
    any<test_concept> x(v);
    any<test_concept> y(x + a1);
    BOOST_CHECK_EQUAL(any_cast<test_class>(y).i, 3);
}

BOOST_AUTO_TEST_CASE(test_relaxed)
{
    typedef boost::mpl::vector<common<_a>, addable<_a, any1_type>, relaxed> test_concept;
    typedef boost::mpl::vector<common<_b>, addable<_b, any1_type>, relaxed> dest_concept;
    any1_type a1(1);
    test_class v = { 2 };
    any<test_concept, _a> x(v);
    any<test_concept, _a> y(x + a1);
    BOOST_CHECK_EQUAL(any_cast<test_class>(y).i, 3);

    any<dest_concept, _b> z(x);
}


text:
#include "DefaultWordDescriptionDownloader.h"

#include "gtest/gtest.h"

#include "ApiResponseFetcherMock.h"
#include "WordDescriptionResponseDeserializerMock.h"

#include "exceptions/InvalidApiKey.h"
#include "webConnection/exceptions/ConnectionFailed.h"
#include <boost/optional/optional_io.hpp>

using namespace ::testing;
using namespace glossary;
using namespace wordDescriptionDownloader;
using namespace wordDescriptionRepository;

namespace
{
const std::string apiKey{"topSecretKey"};
const EnglishWord englishWord{"englishWord"};
const webConnection::Response okResponse{200, "content"};
const webConnection::Response errorResponse{400, ""};
const Definitions definitions{"definition1", "definition2"};
const Examples examples{"example1", "example2"};
const Synonyms synonyms{"synonym1"};
const WordDescription wordDescription{englishWord, definitions, examples, synonyms};
const Definitions emptyDefinitions{};
const Examples emptyExamples{};
const Synonyms emptySynonyms{};
}

class DefaultWordDescriptionDownloaderTest : public Test
{
public:
    void expectDownloadedDefinitions() const
    {
        EXPECT_CALL(*apiResponseFetcher, tryGetWordDefinitionsResponse(englishWord, apiKey))
            .WillOnce(Return(okResponse));
        EXPECT_CALL(*responseDeserializer, deserializeDefinitions(okResponse.content))
            .WillOnce(Return(definitions));
    }

    void expectDownloadedExamples() const
    {
        EXPECT_CALL(*apiResponseFetcher, tryGetWordExamplesResponse(englishWord, apiKey))
            .WillOnce(Return(okResponse));
        EXPECT_CALL(*responseDeserializer, deserializeExamples(okResponse.content))
            .WillOnce(Return(examples));
    }

    void expectDownloadedSynonyms() const
    {
        EXPECT_CALL(*apiResponseFetcher, tryGetWordSynonymsResponse(englishWord, apiKey))
            .WillOnce(Return(okResponse));
        EXPECT_CALL(*responseDeserializer, deserializeSynonyms(okResponse.content))
            .WillOnce(Return(synonyms));
    }

    void expectDownloadedEmptyDefinitions() const
    {
        EXPECT_CALL(*apiResponseFetcher, tryGetWordDefinitionsResponse(englishWord, apiKey))
            .WillOnce(Return(okResponse));
        EXPECT_CALL(*responseDeserializer, deserializeDefinitions(okResponse.content))
            .WillOnce(Return(emptyDefinitions));
    }

    void expectDownloadedEmptyExamples() const
    {
        EXPECT_CALL(*apiResponseFetcher, tryGetWordExamplesResponse(englishWord, apiKey))
            .WillOnce(Return(okResponse));
        EXPECT_CALL(*responseDeserializer, deserializeExamples(okResponse.content))
            .WillOnce(Return(emptyExamples));
    }

    void expectDownloadedEmptySynonyms() const
    {
        EXPECT_CALL(*apiResponseFetcher, tryGetWordSynonymsResponse(englishWord, apiKey))
            .WillOnce(Return(okResponse));
        EXPECT_CALL(*responseDeserializer, deserializeSynonyms(okResponse.content))
            .WillOnce(Return(emptySynonyms));
    }

    std::unique_ptr<ApiResponseFetcherMock> apiResponseFetcherInit =
        std::make_unique<StrictMock<ApiResponseFetcherMock>>();
    ApiResponseFetcherMock* apiResponseFetcher = apiResponseFetcherInit.get();
    std::unique_ptr<WordDescriptionResponseDeserializerMock> responseDeserializerInit =
        std::make_unique<StrictMock<WordDescriptionResponseDeserializerMock>>();
    WordDescriptionResponseDeserializerMock* responseDeserializer = responseDeserializerInit.get();
    DefaultWordDescriptionDownloader downloader{std::move(apiResponseFetcherInit),
                                                std::move(responseDeserializerInit)};
};

TEST_F(DefaultWordDescriptionDownloaderTest, getDefinitions_throwConnectionFailed_shouldThrowConnectionFailed)
{
    EXPECT_CALL(*apiResponseFetcher, tryGetWordDefinitionsResponse(englishWord, apiKey))
        .WillOnce(Throw(webConnection::exceptions::ConnectionFailed{""}));

    ASSERT_THROW(downloader.tryDownloadWordDescription(englishWord, apiKey),
                 webConnection::exceptions::ConnectionFailed);
}

TEST_F(DefaultWordDescriptionDownloaderTest, getDefinitions_throwInvalidApiKey_shouldThrowInvalidApiKey)
{
    EXPECT_CALL(*apiResponseFetcher, tryGetWordDefinitionsResponse(englishWord, apiKey))
        .WillOnce(Throw(exceptions::InvalidApiKey{""}));

    ASSERT_THROW(downloader.tryDownloadWordDescription(englishWord, apiKey), exceptions::InvalidApiKey);
}

TEST_F(DefaultWordDescriptionDownloaderTest,
       getDefinitions_ReturnsNotOkResponseCode_shouldReturnEmptyWordDescription)
{
    EXPECT_CALL(*apiResponseFetcher, tryGetWordDefinitionsResponse(englishWord, apiKey))
        .WillOnce(Return(errorResponse));
    expectDownloadedEmptyExamples();
    expectDownloadedEmptySynonyms();

    const auto actualWordDescription = downloader.tryDownloadWordDescription(englishWord, apiKey);

    ASSERT_TRUE(actualWordDescription.empty());
}

TEST_F(DefaultWordDescriptionDownloaderTest, getExamples_throwConnectionFailed_shouldThrowConnectionFailed)
{
    expectDownloadedDefinitions();
    EXPECT_CALL(*apiResponseFetcher, tryGetWordExamplesResponse(englishWord, apiKey))
        .WillOnce(Throw(webConnection::exceptions::ConnectionFailed{""}));

    ASSERT_THROW(downloader.tryDownloadWordDescription(englishWord, apiKey),
                 webConnection::exceptions::ConnectionFailed);
}

TEST_F(DefaultWordDescriptionDownloaderTest, getExamples_throwInvalidApiKey_shouldThrowInvalidApiKey)
{
    expectDownloadedDefinitions();
    EXPECT_CALL(*apiResponseFetcher, tryGetWordExamplesResponse(englishWord, apiKey))
        .WillOnce(Throw(exceptions::InvalidApiKey{""}));

    ASSERT_THROW(downloader.tryDownloadWordDescription(englishWord, apiKey), exceptions::InvalidApiKey);
}

TEST_F(DefaultWordDescriptionDownloaderTest,
       getExamples_ReturnsNotOkResponseCode_shouldReturnEmptyWordDescription)
{
    expectDownloadedEmptyDefinitions();
    EXPECT_CALL(*apiResponseFetcher, tryGetWordExamplesResponse(englishWord, apiKey))
        .WillOnce(Return(errorResponse));
    expectDownloadedEmptySynonyms();

    const auto actualWordDescription = downloader.tryDownloadWordDescription(englishWord, apiKey);

    ASSERT_TRUE(actualWordDescription.empty());
}

TEST_F(DefaultWordDescriptionDownloaderTest, getSynonyms_throwConnectionFailed_shouldThrowConnectionFailed)
{
    expectDownloadedDefinitions();
    expectDownloadedExamples();
    EXPECT_CALL(*apiResponseFetcher, tryGetWordSynonymsResponse(englishWord, apiKey))
        .WillOnce(Throw(webConnection::exceptions::ConnectionFailed{""}));

    ASSERT_THROW(downloader.tryDownloadWordDescription(englishWord, apiKey),
                 webConnection::exceptions::ConnectionFailed);
}

TEST_F(DefaultWordDescriptionDownloaderTest, getSynonyms_throwInvalidApiKey_shouldReturnThrowInvalidApiKey)
{
    expectDownloadedDefinitions();
    expectDownloadedExamples();
    EXPECT_CALL(*apiResponseFetcher, tryGetWordSynonymsResponse(englishWord, apiKey))
        .WillOnce(Throw(exceptions::InvalidApiKey{""}));

    ASSERT_THROW(downloader.tryDownloadWordDescription(englishWord, apiKey), exceptions::InvalidApiKey);
}

TEST_F(DefaultWordDescriptionDownloaderTest,
       getSynonyms_ReturnsNotOkResponseCode_shouldReturnEmptyWordDescription)
{
    expectDownloadedEmptyDefinitions();
    expectDownloadedEmptyExamples();
    EXPECT_CALL(*apiResponseFetcher, tryGetWordSynonymsResponse(englishWord, apiKey))
        .WillOnce(Return(errorResponse));

    const auto actualWordDescription = downloader.tryDownloadWordDescription(englishWord, apiKey);

    ASSERT_TRUE(actualWordDescription.empty());
}

TEST_F(DefaultWordDescriptionDownloaderTest,
       fetchedDefinitionsExamplesAndSynonyms_shouldReturnWordDescription)
{
    expectDownloadedDefinitions();
    expectDownloadedExamples();
    expectDownloadedSynonyms();

    const auto actualWordDescription = downloader.tryDownloadWordDescription(englishWord, apiKey);

    ASSERT_EQ(actualWordDescription, wordDescription);
}

max_stars_repo_name: michalovsky/Glossary

max_issues_repo_name: michalovsky/Glossary

max_forks_repo_name: michalovsky/Glossary


text:
#define CATCH_CONFIG_MAIN
#include "../../vendor/catch/catch.hpp"

#include "filesystem.hpp"
#include "manipulator/details/basic.hpp"
#include "manipulator/details/types.hpp"
#include <boost/optional/optional_io.hpp>

namespace {
krbn::modifier_flag_manager::active_modifier_flag left_command_1(krbn::modifier_flag_manager::active_modifier_flag::type::increase,
                                                                 krbn::modifier_flag::left_command,
                                                                 krbn::device_id(1));
krbn::modifier_flag_manager::active_modifier_flag left_control_1(krbn::modifier_flag_manager::active_modifier_flag::type::increase,
                                                                 krbn::modifier_flag::left_control,
                                                                 krbn::device_id(1));
krbn::modifier_flag_manager::active_modifier_flag left_option_1(krbn::modifier_flag_manager::active_modifier_flag::type::increase,
                                                                krbn::modifier_flag::left_option,
                                                                krbn::device_id(1));
krbn::modifier_flag_manager::active_modifier_flag left_shift_1(krbn::modifier_flag_manager::active_modifier_flag::type::increase,
                                                               krbn::modifier_flag::left_shift,
                                                               krbn::device_id(1));
krbn::modifier_flag_manager::active_modifier_flag right_shift_1(krbn::modifier_flag_manager::active_modifier_flag::type::increase,
                                                                krbn::modifier_flag::right_shift,
                                                                krbn::device_id(1));

void set_file_logger(const std::string& file_path) {
  unlink(file_path.c_str());
  auto l = spdlog::rotating_logger_mt(file_path, file_path, 256 * 1024, 3);
  l->set_pattern("[%l] %v");
  krbn::logger::set_logger(l);
}

void set_null_logger(void) {
  static auto l = spdlog::stdout_logger_mt("null");
  l->flush_on(spdlog::level::off);
  krbn::logger::set_logger(l);
}
} // namespace

TEST_CASE("modifier_definition.make_modifiers") {
  using krbn::manipulator::details::event_definition;
  using krbn::manipulator::details::modifier_definition;

  {
    nlohmann::json json({"left_command", "left_shift", "fn", "any"});
    auto actual = modifier_definition::make_modifiers(json);
    auto expected = std::unordered_set<modifier_definition::modifier>({
        modifier_definition::modifier::left_command,
        modifier_definition::modifier::left_shift,
        modifier_definition::modifier::fn,
        modifier_definition::modifier::any,
    });
    REQUIRE(actual == expected);
  }

  {
    nlohmann::json json("left_command");
    auto actual = modifier_definition::make_modifiers(json);
    auto expected = std::unordered_set<modifier_definition::modifier>({
        modifier_definition::modifier::left_command,
    });
    REQUIRE(actual == expected);
  }

  {
    nlohmann::json json("unknown");
    auto actual = modifier_definition::make_modifiers(json);
    auto expected = std::unordered_set<modifier_definition::modifier>({});
    REQUIRE(actual == expected);
  }

  {
    nlohmann::json json(nullptr);
    auto actual = modifier_definition::make_modifiers(json);
    auto expected = std::unordered_set<modifier_definition::modifier>({});
    REQUIRE(actual == expected);
  }
}

TEST_CASE("modifier_definition.get_modifier") {
  using krbn::manipulator::details::modifier_definition;

  REQUIRE(modifier_definition::get_modifier(krbn::modifier_flag::zero) == modifier_definition::modifier::end_);
  REQUIRE(modifier_definition::get_modifier(krbn::modifier_flag::left_shift) == modifier_definition::modifier::left_shift);
}

TEST_CASE("manipulator.details.to_event_definition") {
  {
    nlohmann::json json;
    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_event_definition().get_type() == krbn::manipulator::details::event_definition::type::none);
    REQUIRE(event_definition.get_modifiers().size() == 0);
    REQUIRE(event_definition.get_lazy() == false);
    REQUIRE(event_definition.get_repeat() == true);
    REQUIRE(!(event_definition.get_event_definition().to_event()));
    REQUIRE(event_definition.make_modifier_events() == std::vector<krbn::event_queue::event>());
  }
  {
    nlohmann::json json({
        {"key_code", "spacebar"},
        {"modifiers", {
                          "shift",
                          "left_command",
                      }},
    });
    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_event_definition().get_type() == krbn::manipulator::details::event_definition::type::key_code);
    REQUIRE(event_definition.get_event_definition().get_key_code() == krbn::key_code::spacebar);
    REQUIRE(event_definition.get_event_definition().get_pointing_button() == boost::none);
    REQUIRE(event_definition.get_modifiers() == std::unordered_set<krbn::manipulator::details::modifier_definition::modifier>({
                                                    krbn::manipulator::details::modifier_definition::modifier::shift,
                                                    krbn::manipulator::details::modifier_definition::modifier::left_command,
                                                }));
    REQUIRE(event_definition.get_event_definition().to_event() == krbn::event_queue::event(krbn::key_code::spacebar));
    REQUIRE(event_definition.make_modifier_events() == std::vector<krbn::event_queue::event>({
                                                           krbn::event_queue::event(krbn::key_code::left_command),
                                                           krbn::event_queue::event(krbn::key_code::left_shift),
                                                       }));
  }
  {
    nlohmann::json json({
        {"key_code", "right_option"},
        {"modifiers", {
                          "shift",
                          "left_command",
                          // duplicated
                          "shift",
                          "left_command",
                      }},
    });
    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_event_definition().get_type() == krbn::manipulator::details::event_definition::type::key_code);
    REQUIRE(event_definition.get_event_definition().get_key_code() == krbn::key_code::right_option);
    REQUIRE(event_definition.get_event_definition().get_pointing_button() == boost::none);
    REQUIRE(event_definition.get_modifiers() == std::unordered_set<krbn::manipulator::details::modifier_definition::modifier>({
                                                    krbn::manipulator::details::modifier_definition::modifier::shift,
                                                    krbn::manipulator::details::modifier_definition::modifier::left_command,
                                                }));
    REQUIRE(event_definition.make_modifier_events() == std::vector<krbn::event_queue::event>({
                                                           krbn::event_queue::event(krbn::key_code::left_command),
                                                           krbn::event_queue::event(krbn::key_code::left_shift),
                                                       }));
  }
  {
    nlohmann::json json({
        {"key_code", nlohmann::json::array()},
        {"modifiers", {
                          "dummy",
                      }},
    });
    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_event_definition().get_type() == krbn::manipulator::details::event_definition::type::none);
    REQUIRE(event_definition.get_event_definition().get_key_code() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_pointing_button() == boost::none);
    REQUIRE(event_definition.get_modifiers().size() == 0);
    REQUIRE(event_definition.make_modifier_events() == std::vector<krbn::event_queue::event>({}));
  }
  {
    std::string shell_command = "open /Applications/Safari.app";
    nlohmann::json json({
        {"shell_command", shell_command},
    });
    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_event_definition().get_type() == krbn::manipulator::details::event_definition::type::shell_command);
    REQUIRE(event_definition.get_event_definition().get_key_code() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_pointing_button() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_shell_command() == shell_command);
    REQUIRE(event_definition.get_event_definition().get_input_source_selectors() == boost::none);
  }
  // select_input_source
  {
    krbn::input_source_selector input_source_selector(boost::none,
                                                      std::string("com.apple.keylayout.US"),
                                                      boost::none);

    nlohmann::json json;
    json["select_input_source"]["input_source_id"] = "com.apple.keylayout.US";

    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_event_definition().get_type() == krbn::manipulator::details::event_definition::type::select_input_source);
    REQUIRE(event_definition.get_event_definition().get_key_code() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_pointing_button() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_shell_command() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_input_source_selectors() == std::vector<krbn::input_source_selector>({input_source_selector}));
  }
  // select_input_source (array)
  {
    krbn::input_source_selector input_source_selector1(boost::none,
                                                       std::string("com.apple.keylayout.US"),
                                                       boost::none);
    krbn::input_source_selector input_source_selector2(std::string("en"),
                                                       boost::none,
                                                       boost::none);

    nlohmann::json json;
    json["select_input_source"] = nlohmann::json::array();
    json["select_input_source"].push_back(nlohmann::json::object());
    json["select_input_source"].back()["input_source_id"] = "com.apple.keylayout.US";
    json["select_input_source"].push_back(nlohmann::json::object());
    json["select_input_source"].back()["language"] = "en";

    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_event_definition().get_type() == krbn::manipulator::details::event_definition::type::select_input_source);
    REQUIRE(event_definition.get_event_definition().get_key_code() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_pointing_button() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_shell_command() == boost::none);
    REQUIRE(event_definition.get_event_definition().get_input_source_selectors() == std::vector<krbn::input_source_selector>({input_source_selector1,
                                                                                input_source_selector2}));
  }
  // lazy
  {
    nlohmann::json json;
    json["lazy"] = true;

    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_lazy() == true);
  }
  // lazy
  {
    nlohmann::json json;
    json["repeat"] = false;

    krbn::manipulator::details::to_event_definition event_definition(json);
    REQUIRE(event_definition.get_repeat() == false);
  }
}

TEST_CASE("event_definition.error_messages") {
  set_file_logger("tmp/error_messages.log");

  {
    std::ifstream json_file("json/error_messages.json");
    auto json = nlohmann::json::parse(json_file);
    for (const auto& j : json["to_event_definition"]) {
      krbn::manipulator::details::to_event_definition to_event_definition(j);
    }
  }

  set_null_logger();
}

max_stars_repo_name: cyrusccy/Karabiner-Elements

max_issues_repo_name: cyrusccy/Karabiner-Elements

max_forks_repo_name: cyrusccy/Karabiner-Elements


text: #include <boost/qvm/gen/vec_assign3.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/* =========================================================================
   Copyright (c) 2010-2012, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.
   Portions of this software are copyright by UChicago Argonne, LLC.

                            -----------------
                  ViennaCL - The Vienna Computing Library
                            -----------------

   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at

   (A list of authors and contributors can be found in the PDF manual)

   License:         MIT (X11), see file LICENSE in the base directory
============================================================================= */

/*
*
*   Tutorial:  Use of the iterative solvers in ViennaCL with Eigen (http://eigen.tuxfamily.org/)
*
*/

//
// include necessary system headers
//
#include <iostream>

#ifndef NDEBUG
 #define NDEBUG
#endif

//
// Include Eigen headers
//
#include <Eigen/Core>
#include <Eigen/Sparse>

// Must be set prior to any ViennaCL includes if you want to use ViennaCL algorithms on Eigen objects
#define VIENNACL_WITH_EIGEN 1

//
// ViennaCL includes
//
#include "viennacl/linalg/ilu.hpp"
#include "viennacl/linalg/cg.hpp"
#include "viennacl/linalg/bicgstab.hpp"
#include "viennacl/linalg/gmres.hpp"
#include "viennacl/io/matrix_market.hpp"

// Some helper functions for this tutorial:
#include "Random.hpp"
#include "vector-io.hpp"
#include "../benchmarks/benchmark-utils.hpp"

int main(int, char *[])
{
  typedef float ScalarType;

  Eigen::SparseMatrix<ScalarType, Eigen::RowMajor> eigen_matrix(65025, 65025);
  Eigen::VectorXf eigen_rhs;
  Eigen::VectorXf eigen_result;
  Eigen::VectorXf ref_result;
  Eigen::VectorXf residual;

  //
  // Read system from file
  //
  std::cout << "Reading matrix..." << std::endl;
  eigen_matrix.reserve(65025 * 7);
  if (!viennacl::io::read_matrix_market_file(eigen_matrix, "../examples/testdata/mat65k.mtx"))
  {
    std::cout << "Error reading Matrix file" << std::endl;
    return 0;
  }
  //eigen_matrix.endFill();
  std::cout << "Done: reading matrix" << std::endl;

  if (!readVectorFromFile("../examples/testdata/rhs65025.txt", eigen_rhs))
  {
    std::cout << "Error reading RHS file" << std::endl;
    return 0;
  }

  if (!readVectorFromFile("../examples/testdata/result65025.txt", ref_result))
  {
    std::cout << "Error reading Result file" << std::endl;
    return 0;
  }

  //CG solver:
  std::cout << "----- Running CG -----" << std::endl;
  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::cg_tag());

  residual = eigen_matrix * eigen_result - eigen_rhs;
  std::cout << "Relative residual: " << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;

  //BiCGStab solver:
  std::cout << "----- Running BiCGStab -----" << std::endl;
  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::bicgstab_tag());

  residual = eigen_matrix * eigen_result - eigen_rhs;
  std::cout << "Relative residual: " << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;

  //GMRES solver:
  std::cout << "----- Running GMRES -----" << std::endl;
  eigen_result = viennacl::linalg::solve(eigen_matrix, eigen_rhs, viennacl::linalg::gmres_tag());

  residual = eigen_matrix * eigen_result - eigen_rhs;
  std::cout << "Relative residual: " << viennacl::linalg::norm_2(residual) / viennacl::linalg::norm_2(eigen_rhs) << std::endl;

}

max_stars_repo_name: bollig/viennacl

max_issues_repo_name: bollig/viennacl

max_forks_repo_name: bollig/viennacl


text:
#include <Eigen/Dense>
#include <vector>
#include <algorithm>
#include "geometryUtil.hpp"
#include "privdef.hpp"

std::vector<Eigen::Vector3f> cornersWorkspaceAll(const Eigen::Vector3f& corner0, const Eigen::Vector3f& corner1) {
	std::vector<Eigen::Vector3f> corners;
	int index[3];
	for (int i = 0; i < 8; i++) { // for the number of the corners
		int res = i;
		for (int j = 0; j < 3; j++) { // for x, y, z
			index[j] = res % 2;
			res /= 2;
		}
		float x = (index[0] == 0 ? corner0.x() : corner1.x());
		float y = (index[1] == 0 ? corner0.y() : corner1.y());
		float z = (index[2] == 0 ? corner0.z() : corner1.z());
		corners.push_back(Eigen::Vector3f(x, y, z));
	}
	return corners;
}

std::vector<float> range2Points(const Eigen::Vector3f& pos_self, const Eigen::Quaternionf& quo_self, std::vector<Eigen::Vector3f> const& points) {
	std::vector<float> ranges;
	std::for_each(points.begin(), points.end(), [&ranges, &pos_self, &quo_self](Eigen::Vector3f point) {
		ranges.push_back((point - pos_self).dot(quo_self * Eigen::Vector3f::UnitZ()));
		});
	return ranges;
}

namespace dynaman {
	bool isInsideWorkspace(const Eigen::Vector3f& pos, const Eigen::Vector3f& lowerbound, const Eigen::Vector3f& upperbound) {
		Eigen::Vector3f v0 = pos - lowerbound;
		Eigen::Vector3f v1 = pos - upperbound;
		return (v0.x() * v1.x() <= 0) && (v0.y() * v1.y() <= 0) && (v0.z() * v1.z() <= 0);
	}

	Eigen::Matrix3f RotForDeviceId(int device_id, autd::GeometryPtr geo) {
		Eigen::Vector3f pos_origin = geo->position(device_id * NUM_TRANS_IN_UNIT);
		Eigen::Vector3f pos_trans_on_xaxis = geo->position(device_id * NUM_TRANS_IN_UNIT + NUM_TRANS_X - 1);
		Eigen::Vector3f pos_trans_on_yaxis = geo->position((device_id + 1) * NUM_TRANS_IN_UNIT - NUM_TRANS_X);
		Eigen::Vector3f unitX_device = (pos_trans_on_xaxis - pos_origin).normalized();
		Eigen::Vector3f unitY_device = (pos_trans_on_yaxis - pos_origin).normalized();
		Eigen::Vector3f unitZ_device = geo->direction(device_id * NUM_TRANS_IN_UNIT);
		Eigen::Matrix3f rot;
		rot << unitX_device, unitY_device, unitZ_device;
		return rot;
	}

	std::vector<Eigen::Matrix3f> RotsAutd(autd::GeometryPtr geo) {
		std::vector<Eigen::Matrix3f> rots(geo->numDevices());
		for (auto itr_device = rots.begin(); itr_device != rots.end(); itr_device++) {
			*itr_device = RotForDeviceId(std::distance(rots.begin(), itr_device), geo);
		}
		return rots;
	}

	std::vector<Eigen::Matrix3f> RotsAutd(std::shared_ptr<autd::Controller> pAupa) {
		return RotsAutd(pAupa->geometry());
	}

	Eigen::Vector3f CenterForDeviceId(int deviceId, autd::GeometryPtr geo) {
		Eigen::Vector3f center_local(TRANS_SIZE_MM * (NUM_TRANS_X / 2 - 0.5f), TRANS_SIZE_MM * (NUM_TRANS_Y / 2 - 0.5f), 0.f);
		return  RotForDeviceId(deviceId, geo) * center_local + geo->position(NUM_TRANS_IN_UNIT * deviceId);
	}

	Eigen::Matrix3Xf CentersAutd(autd::GeometryPtr geo) {
		Eigen::Matrix3Xf centers(3, geo->numDevices());
		for (int i_autd = 0; i_autd < geo->numDevices(); i_autd++) {
			centers.col(i_autd) = CenterForDeviceId(i_autd, geo);
		}
		return centers;
	}

	Eigen::Matrix3Xf DirectionsAutd(autd::GeometryPtr geo) {
		Eigen::Matrix3Xf directions;
		directions.resize(3, geo->numDevices());
		for (int i_col = 0; i_col < directions.cols(); i_col++) {
			directions.col(i_col) = geo->direction(i_col * NUM_TRANS_IN_UNIT);
		}
		return directions;
	}
}

max_stars_repo_name: shinolab/dynamic-manipulation

max_issues_repo_name: shinolab/dynamic-manipulation

max_forks_repo_name: shinolab/dynamic-manipulation


text:
// -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2009-2013 Illumina, Inc.
//
// This software is provided under the terms and conditions of the
// Illumina Open Source Software License 1.
//
// You should have received a copy of the Illumina Open Source
// Software License 1 along with this program. If not, see
// <https://github.com/sequencing/licenses/>
//

/// \file

/// variation on the original strowman snv caller -- implements a
/// compile-time specified grid in allele frequency space and requires
/// similar frequency as definition of non-somatic.
///

/// \author Chris Saunders
///
#ifndef __POSITION_SOMATIC_SNV_GRID_HH
#define __POSITION_SOMATIC_SNV_GRID_HH

#if 0

#include "blt_common/snp_pos_info.hh"
#include "blt_common/position_snp_call_pprob_digt.hh"
#include "strelka/strelka_shared.hh"

#include "position_somatic_snv_grid_shared.hh"

#include "blt_util/qscore.hh"

#include <boost/utility.hpp>

#include <iosfwd>

//#define SOMATIC_DEBUG

namespace DIGT_GRID {

// HET_RES is the number of points sampled between 0 and 0.5 on
// the continuous frequency scale. Thus a fully sampled axis will
// be sampled HET_RES*2+3 times.
//
enum constants { HET_RES = 4,
                 HET_COUNT = HET_RES*2+1,
                 HET_SIZE = DIGT::SIZE-N_BASE
               };

enum index_t { SIZE = N_BASE+HET_SIZE*HET_COUNT };

inline
unsigned
get_digt_state (const unsigned state) {
    if (state<N_BASE) return state;
    return N_BASE+((state-N_BASE)%HET_SIZE);
}

inline
unsigned
get_het_count(const unsigned state) {
    if (state<N_BASE) return 0;
    return (state-N_BASE)/HET_SIZE;
}
}

namespace DDIGT_GRID {

enum index_t { SIZE = DIGT_GRID::SIZE*DIGT_GRID::SIZE };

inline
unsigned
get_state(const unsigned normal_gt,
          const unsigned tumor_gt) {
    return normal_gt+DIGT_GRID::SIZE*tumor_gt;
}

inline
void
get_digt_grid_states(const unsigned dgt,
                     unsigned& normal_gt,
                     unsigned& tumor_gt) {
    normal_gt = (dgt%DIGT_GRID::SIZE);
    tumor_gt = (dgt/DIGT_GRID::SIZE);
}

struct is_nonsom_maker_t {
    is_nonsom_maker_t();

    std::vector<bool> val;
};
}

std::ostream& operator<<(std::ostream& os,const DDIGT_GRID::index_t dgt);

// object used to pre-compute priors:
struct somatic_snv_caller_grid {

    somatic_snv_caller_grid(const strelka_options& opt,
                            const pprob_digt_caller& pd_caller);

    //
    void
    position_somatic_snv_call(const extended_pos_info& normal_epi,
                              const extended_pos_info& tumor_epi,
                              const extended_pos_info* normal_epi_t2_ptr,
                              const extended_pos_info* tumor_epi_t2_ptr,
                              somatic_snv_genotype_grid& sgt) const;

private:
    const std::vector<blt_float_t>&
    lnprior_genomic(const unsigned ref_id) const {
        return _lnprior[ref_id].normal;
    }

    const std::vector<blt_float_t>&
    lnprior_polymorphic(const unsigned ref_id) const {
        return _lnprior[ref_id].normal_poly;
    }

    struct prior_set {
        prior_set()
            : normal(DIGT_GRID::SIZE)
            , normal_poly(DIGT_GRID::SIZE) {}

        std::vector<blt_float_t> normal;
        std::vector<blt_float_t> normal_poly;
    };

    const strelka_options& _opt;
    const pprob_digt_caller& _pd_caller;
    prior_set _lnprior[N_BASE+1];
    blt_float_t _ln_som_match;
    blt_float_t _ln_som_mismatch;
};

// snv call output:
//
void
write_somatic_snv_genotype_grid(const strelka_options& opt,
                                const somatic_snv_genotype_grid& sgt,
                                const snp_pos_info& normal_pi,
                                const snp_pos_info& tumor_pi,
                                std::ostream& os);

#endif

#endif


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2011 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2011 Mateusz Loskot, London, UK.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// 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)

#ifndef BOOST_GEOMETRY_UTIL_MATH_HPP
#define BOOST_GEOMETRY_UTIL_MATH_HPP

#include <cmath>
#include <limits>

#include <boost/math/constants/constants.hpp>

#include <boost/geometry/util/select_most_precise.hpp>

namespace boost { namespace geometry
{

namespace math
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail
{

template <typename Type, bool IsFloatingPoint>
struct equals
{
    static inline bool apply(Type const& a, Type const& b)
    {
        return a == b;
    }
};

template <typename Type>
struct equals<Type, true>
{
    static inline bool apply(Type const& a, Type const& b)
    {
        // See http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17,
        // FUTURE: replace by some boost tool or boost::test::close_at_tolerance
        return std::abs(a - b) <= std::numeric_limits<Type>::epsilon() * std::abs(a);
    }
};

template <typename Type, bool IsFloatingPoint>
struct equals_with_epsilon : public equals<Type, IsFloatingPoint> {};

/*!
\brief Short construct to enable partial specialization for PI, currently not possible in Math.
*/
template <typename T>
struct define_pi
{
    static inline T apply()
    {
        // Default calls Boost.Math
        return boost::math::constants::pi<T>();
    }
};

} // namespace detail
#endif

template <typename T>
inline T pi() { return detail::define_pi<T>::apply(); }

// Maybe replace this by boost equals or boost ublas numeric equals or so

/*!
    \brief returns true if both arguments are equal.
    \ingroup utility
    \param a first argument
    \param b second argument
    \return true if a == b
    \note If both a and b are of an integral type, comparison is done by ==.
    If one of the types is floating point, comparison is done by abs and
    comparing with epsilon. If one of the types is non-fundamental, it might
    be a high-precision number and comparison is done using the == operator
    of that class.
*/

template <typename T1, typename T2>
inline bool equals(T1 const& a, T2 const& b)
{
    typedef typename select_most_precise<T1, T2>::type select_type;
    return detail::equals
        <
            select_type,
            boost::is_floating_point<select_type>::type::value
        >::apply(a, b);
}

template <typename T1, typename T2>
inline bool equals_with_epsilon(T1 const& a, T2 const& b)
{
    typedef typename select_most_precise<T1, T2>::type select_type;
    return detail::equals_with_epsilon
        <
            select_type,
            boost::is_floating_point<select_type>::type::value
        >::apply(a, b);
}

double const d2r = geometry::math::pi<double>() / 180.0;
double const r2d = 1.0 / d2r;

/*!
    \brief Calculates the haversine of an angle
    \ingroup utility
    \note See http://en.wikipedia.org/wiki/Haversine_formula
    haversin(alpha) = sin2(alpha/2)
*/
template <typename T>
inline T hav(T const& theta)
{
    T const half = T(0.5);
    T const sn = sin(half * theta);
    return sn * sn;
}

/*!
\brief Short utility to return the square
\ingroup utility
\param value Value to calculate the square from
\return The squared value
*/
template <typename T>
inline T sqr(T const& value)
{
    return value * value;
}

/*!
\brief Short utility to workaround gcc/clang problem that abs is converting to integer
\ingroup utility
*/
template<typename T>
inline T abs(const T& t)
{
    using std::abs;
    return abs(t);
}

} // namespace math

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_UTIL_MATH_HPP

max_stars_repo_name: zigaosolin/Raytracer

max_issues_repo_name: zigaosolin/Raytracer

max_forks_repo_name: zigaosolin/Raytracer


text:
#include <kspp/utils/env.h>
#include <experimental/filesystem>
#include <boost/asio/ip/host_name.hpp>
#include <glog/logging.h>

namespace kspp {
  std::string get_env_and_log(const char *env, std::string default_value) {
    const char *env_p = std::getenv(env);
    if (env_p) {
      LOG(INFO) << "env: " << env << " -> " << env_p;
      return std::string(env_p);
    } else {
      if (default_value.size())
        LOG(INFO) << "env: " << env << " - not defined, using default: " << default_value;
      else
        LOG(INFO) << "env: " << env << " - not defined";
      return default_value;
    }
  }

  std::string get_env_and_log_hidden(const char *env, std::string default_value) {
    const char *env_p = std::getenv(env);
    if (env_p) {
      LOG(INFO) << "env: " << env << " -> [hidden]";
      return std::string(env_p);
    } else {
      LOG(INFO) << "env: " << env << " - not defined, using default: [hidden]";
      return default_value;
    }
  }

  std::string default_kafka_broker_uri() {
    return get_env_and_log("KSPP_KAFKA_BROKER_URL", "plaintext://localhost:9092");
  }

  std::string default_kafka_rest_uri() {
    return get_env_and_log("KSPP_KAFKA_REST_URL", "http://localhost:8082");
  }

  std::string default_schema_registry_uri() {
    return get_env_and_log("KSPP_SCHEMA_REGISTRY_URL", "http://localhost:8081");
  }

  std::string default_statestore_root() {
    return get_env_and_log("KSPP_STATE_STORE_ROOT", std::experimental::filesystem::temp_directory_path().generic_string() + "/kspp");
  }

#ifdef _WIN32
  std::string default_ca_cert_path() {
    return get_env_and_log("KSPP_CA_CERT", "");
  }

  std::string default_client_cert_path() {
    return get_env_and_log("KSPP_CLIENT_CERT", "");
  }

  std::string default_client_key_path() {
    return get_env_and_log("KSPP_CLIENT_KEY", "");
  }

  std::string default_client_key_passphrase() {
    return get_env_and_log_hidden("KSPP_CLIENT_KEY_PASSPHRASE", "");
  }
#else

  std::string default_pushgateway_uri() {
    return get_env_and_log("KSPP_PUSHGATEWAY_URL", "http://localhost:9091");
  }

  std::string default_ca_cert_path() {
    return get_env_and_log("KSPP_CA_CERT", "/etc/kspp/credentials/cacert.pem");
  }

  std::string default_client_cert_path() {
    return get_env_and_log("KSPP_CLIENT_CERT", "/etc/kspp/credentials/client.pem");
  }

  std::string default_client_key_path() {
    return get_env_and_log("KSPP_CLIENT_KEY", "/etc/kspp/credentials/client.key");
  }

  std::string default_client_key_passphrase() {
    return get_env_and_log_hidden("KSPP_CLIENT_KEY_PASSPHRASE", "");
  }

#endif

  /*
   * std::string default_hostname() {
#ifdef _WIN32
    if (const char* env_p = std::getenv("COMPUTERNAME"))
      return std::string(env_p);
    else
      return "unknown";
#else
    char buf[256];
    sprintf(buf, "unknown");
    gethostname(buf, 256);
    std::string hostname = buf;
    return hostname;
#endif
  }
  */
  std::string default_hostname() {
    auto host_name = boost::asio::ip::host_name();
    return host_name;
  }
}


text:
#include "SctpTestClientPch.h"

#include <fstream>
#include <sstream>
#include <string>
#include <boost/exception/all.hpp>
#include <boost/program_options.hpp>
#include <cpputil/Conversion.h>
#include <rtp++/application/ApplicationContext.h>
#include <rtp++/application/ApplicationUtil.h>
#include "../SctpTestServer/SctpAssociation.h"

using namespace std;
using namespace rtp_plus_plus;

namespace po = boost::program_options;

int g_uiMessages = 0;
int g_uiRecvMessages = 0;

void onSctpRecv(uint32_t uiChannelId, const NetworkPacket& networkPacket)
{
  VLOG(2) << "Received SCTP from server on channel " << uiChannelId
          << " Size: " << networkPacket.getSize()
          << " Message: " << networkPacket.data();
  ++g_uiRecvMessages;
}

int main(int argc, char** argv)
{
  if (argc != 5)
  {
    LOG(WARNING) << "Usage: " << argv[1] << " <<host>> <<sctp_port>> <<local_udp_encaps_port>> <<remote_udp_encaps_port>>";
    return -1;
  }

  if (!app::ApplicationContext::initialiseApplication(argv[0]))
  {
    LOG(WARNING) << "Failed to initialise application";
    return -1;
  }

  bool bOk = false;
  const char* szHost = argv[1];
  uint16_t uiSctpPort = convert<uint16_t>(argv[2], bOk);
  if (!bOk)
  {
    LOG(WARNING) << "Invalid SCTP port: " << argv[2];
    return -1;
  }
  uint16_t uiLocalUdpPort = convert<uint16_t>(argv[3], bOk);
  if (!bOk)
  {
    LOG(WARNING) << "Invalid local UDP port: " << argv[3];
    return -1;
  }
  uint16_t uiRemoteUdpPort = convert<uint16_t>(argv[4], bOk);
  if (!bOk)
  {
    LOG(WARNING) << "Invalid remote UDP port: " << argv[4];
    return -1;
  }

  sctp::SctpAssociation* pSctpAssociation = new sctp::SctpAssociation(uiSctpPort, uiLocalUdpPort, uiRemoteUdpPort);
  pSctpAssociation->setRecvCallback(boost::bind(&onSctpRecv, _1, _2));

  pSctpAssociation->bind();

  // BLOCKING?
  EndPoint endPoint(szHost, uiRemoteUdpPort);
  if (!pSctpAssociation->connect(endPoint))
  {
    LOG(WARNING) << "Failed to connect to " << endPoint;
  }
  else
  {
#if 1
    sctp::channel* pChannel = pSctpAssociation->openChannel(true, sctp::SCTP_PR_POLICY_SCTP_NONE, 0);
    VLOG(2) << "Opening channel " << pChannel->id;
#endif
  }

  if (!pSctpAssociation->setNonBlocking())
  {
    LOG(WARNING) << "Failed to set non-blocking";
  }
  else
  {
    VLOG(5) << "SCTP socket set to non-blocking";
  }

  g_uiMessages = 0;
  while (true)
  {
    if (g_uiMessages < 100)
    // if (g_uiMessages == 0)
    {
      if (g_uiMessages == 25)
      {
        int res = 1;
        int uiMessage = 0;
        while (res)
        {
          std::ostringstream ostr;
          ostr << "Client " << g_uiMessages << " " << uiMessage++;
          std::string sMessage = ostr.str();
          const int uiBufSize = 10000;
          char pLargeMessage[uiBufSize];
          memset(pLargeMessage, 0, uiBufSize);
          memcpy(pLargeMessage, sMessage.c_str(), sMessage.length());
          res = pSctpAssociation->sendUserMessage(0, pLargeMessage, uiBufSize);
          VLOG(5) << "Sending message " << g_uiMessages << " Message: " << sMessage
                  << " Result of send: " << res;
        }
      }
      else
      {
        std::ostringstream ostr;
        ostr << "Client " << g_uiMessages;
        std::string sMessage = ostr.str();
        int res = pSctpAssociation->sendUserMessage(0, sMessage.c_str(), sMessage.length());
        LOG(INFO) << "Sending message " << g_uiMessages << " Message: " << sMessage
                  << " Result of send: " << res;
      }
    }

    if (g_uiRecvMessages == 100)
      break;

#if 0
    sleep(1);
#else
    usleep(10000);
#endif
    // LOG(INFO) << "Done Sleeping";
    ++g_uiMessages;
  }

  // without this sleep, the server doesn't seem to get the shutdown signal
  sleep(1);
  // close all associations
  if (!pSctpAssociation->shutdown())
  {
    LOG(WARNING) << "Failed to shutdown socket";
  }
  else
  {
    VLOG(5) << "Shutdown SCTP socket";
  }

  delete pSctpAssociation;

  if (!app::ApplicationContext::cleanupApplication())
  {
    LOG(WARNING) << "Failed to cleanup application cleanly";
  }

  return 0;
}


text:
#pragma once

#include <string>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/export.hpp>

#include "../Utility/Vector3D.hpp"

namespace CraftWorld::Actions {
	/**
	 * Represents changes in the game state.
	 */
	class Action {
			friend boost::serialization::access;

			/**
			 * Serializes the Action.
			 * @tparam ArchiveType The type of archive used for serialization.
			 * @param archive The archive used for serialization.
			 * @param version The version of the serialization algorithm.
			 */
			template<typename ArchiveType>
			void serialize(ArchiveType& archive, const unsigned int& version) {
				archive & BOOST_SERIALIZATION_NVP(name);
				archive & BOOST_SERIALIZATION_NVP(source);
			}

		public:
			/**
			 * The name of the action.
			 */
			std::string name;

			/**
			 * The source of the action.
			 */
			int source;

			/**
			 * Creates a new Action.
			 */
			Action() = default;

			/**
			 * Creates a new Action.
			 * @param name The name.
			 * @param source The source.
			 */
			Action(const std::string& name, const int& source);

			/**
			 * Declares the class as polymorphic.
			 */
			virtual ~Action() = default;
	};
}

max_stars_repo_name: Adeelala/craftworld

max_issues_repo_name: Adeelala/craftworld

max_forks_repo_name: Adeelala/craftworld


text:
/*=============================================================================
    Copyright (c) 2001-2003 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 <vector>
#include <algorithm>
#include <iostream>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/function.hpp>

struct factorial_impl
{
    template <typename Sig>
    struct result;

    template <typename This, typename Arg>
    struct result<This(Arg)>
        : result<This(Arg const &)>
    {};

    template <typename This, typename Arg>
    struct result<This(Arg &)>
    {
        typedef Arg type;
    };

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

int
main()
{
    using boost::phoenix::arg_names::arg1;
    boost::phoenix::function<factorial_impl> factorial;
    int i = 4;
    std::cout << factorial(i)() << std::endl;
    std::cout << factorial(arg1)(i) << std::endl;
    return 0;
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#include <iostream>
#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/itl/itl.hpp>
#include <boost/numeric/itl/pc/ilut.hpp>

template <typename Matrix>
double test_factorization(const Matrix& A, unsigned p, double tau)
{
    itl::pc::ilut<Matrix>  P(A, p, tau);
    //itl::pc::ilu_0<Matrix>  P(A);
    Matrix L(P.get_L()), U(P.get_U()), I(num_rows(A), num_cols(A));
    I= 1.0;
    L+= I;
    invert_diagonal(U);
    //std::cout << "L is\n" << L << '\n';
    //std::cout << "U is\n" << U << '\n';
    Matrix LU(L*U);
    //std::cout << "LU is\n" << LU << '\n';
    LU-= A;
    //std::cout << "LU-A is\n" << LU << '\n';
    double diff_norm= frobenius_norm(LU);
    std::cout << "|A-LU|_1 with p = " << p << ", tau = " << tau << " is " << diff_norm << '\n';
    return diff_norm;
}

int main()
{
#ifndef __PGI
    // For a more realistic example set sz to 1000 or larger
    const unsigned size = 4, N = size * size;

    mtl::compressed2D<double>          A(N, N);
    laplacian_setup(A, size, size);

    std::cout << "A is\n" << A << '\n';
    MTL_THROW_IF(test_factorization(A, 3, 0.001) > 0.24, mtl::logic_error("ILUT(3, 0.001) too bad"));

#if 0
    for(unsigned i= 2; i <= size; i++)
	for (double f= 0.5; f > 0.000001; f/= 2)
	    test_factorization(A, i, f);

    itl::pc::ic_0<matrix_type, float>  P(A);
    mtl::dense_vector<double>          x(N), y, yc(N);
    iota(x);
    yc= 1.03194,1.60198,1.45357,2.5258,3.55386,3.16,2.91787,4.09338,3.81335;

    std::cout << x << '\n';
    y= solve(P, x);
    std::cout << y << '\n';

    MTL_THROW_IF(two_norm(mtl::dense_vector<double>(y - yc)) > 0.001,
		 mtl::logic_error("IC(0) doesn't yield expected result"));
#endif

#endif
    return 0;
}


text:
#ifndef SQL_PARSER_AST_IDENTIFIER_HPP
#define SQL_PARSER_AST_IDENTIFIER_HPP

#include "sql/ast/common.hpp"

#include <boost/optional.hpp>
#include <boost/spirit/home/x3/support/ast/position_tagged.hpp>
#include <boost/spirit/home/x3/support/ast/variant.hpp>

#include <vector>

namespace sql { namespace ast
{
        namespace x3 = boost::spirit::x3;

        struct identifier : x3::position_tagged {
            std::string identifier;
            quot quotation;
        };

        typedef std::vector<identifier> identifier_list;

        struct simple_table_identifier
        {
            identifier table;
        };

        struct schema_table_identifier
        {
            identifier schema;
            identifier table;
        };

        struct table_identifier : x3::variant<
                schema_table_identifier
                , simple_table_identifier
        >
        {
            using base_type::base_type;
            using base_type::operator=;
        };

        struct aliased_table_identifier
        {
            table_identifier table;
            boost::optional<identifier> alias;
        };
}}

#endif //SQL_PARSER_AST_IDENTIFIER_HPP

max_stars_repo_name: cviebig/lib-sql

max_issues_repo_name: cviebig/lib-sql

max_forks_repo_name: cviebig/lib-sql