text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2013-2018 Regents of the University of California.
 *
 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
 *
 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 *
 * You should have received copies of the GNU General Public License and GNU Lesser
 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 */

#include "ndn-cxx/delegation-list.hpp"

#include "tests/boost-test.hpp"
#include <boost/lexical_cast.hpp>

namespace ndn {
namespace tests {

BOOST_AUTO_TEST_SUITE(TestDelegationList)

const uint8_t DEL1A[] = {
  0x1f, 0x08, // Delegation
        0x1e, 0x01, 0x01, // Preference=1
        0x07, 0x03, 0x08, 0x01, 0x41 // Name=/A
};
const uint8_t DEL1B[] = {
  0x1f, 0x08, // Delegation
        0x1e, 0x01, 0x01, // Preference=1
        0x07, 0x03, 0x08, 0x01, 0x42 // Name=/B
};
const uint8_t DEL2A[] = {
  0x1f, 0x08, // Delegation
        0x1e, 0x01, 0x02, // Preference=2
        0x07, 0x03, 0x08, 0x01, 0x41 // Name=/A
};
const uint8_t DEL2B[] = {
  0x1f, 0x08, // Delegation
        0x1e, 0x01, 0x02, // Preference=2
        0x07, 0x03, 0x08, 0x01, 0x42 // Name=/B
};

Block
makeDelegationListBlock(uint32_t type, std::initializer_list<const uint8_t*> dels)
{
  Block block(type);
  for (const uint8_t* del : dels) {
    block.push_back(Block(del, 2 + del[1]));
  }
  block.encode();
  return block;
}

BOOST_AUTO_TEST_SUITE(Decode)

BOOST_AUTO_TEST_CASE(DecodeUnsorted)
{
  DelegationList dl(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A, DEL2B, DEL1A}), false);
  BOOST_CHECK_EQUAL(dl.size(), 3);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 2);
  BOOST_CHECK_EQUAL(dl.at(0).name, "/A");
  BOOST_CHECK_EQUAL(dl.at(1).preference, 2);
  BOOST_CHECK_EQUAL(dl.at(1).name, "/B");
  BOOST_CHECK_EQUAL(dl.at(2).preference, 1);
  BOOST_CHECK_EQUAL(dl.at(2).name, "/A");
}

BOOST_AUTO_TEST_CASE(DecodeSorted)
{
  DelegationList dl(makeDelegationListBlock(tlv::Content, {DEL2A, DEL2B, DEL1A}));
  BOOST_CHECK_EQUAL(dl.size(), 3);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 1);
  BOOST_CHECK_EQUAL(dl.at(0).name, "/A");
  BOOST_CHECK_EQUAL(dl.at(1).preference, 2);
  BOOST_CHECK_EQUAL(dl.at(1).name, "/A");
  BOOST_CHECK_EQUAL(dl.at(2).preference, 2);
  BOOST_CHECK_EQUAL(dl.at(2).name, "/B");
}

BOOST_AUTO_TEST_CASE(DecodeEmpty)
{
  DelegationList dl;
  Block block = makeDelegationListBlock(tlv::ForwardingHint, {});
  BOOST_CHECK_THROW(dl.wireDecode(block), DelegationList::Error);
}

BOOST_AUTO_TEST_CASE(DecodeBadType)
{
  DelegationList dl;
  Block block = makeDelegationListBlock(tlv::Selectors, {DEL1A, DEL2B});
  BOOST_CHECK_THROW(dl.wireDecode(block), DelegationList::Error);
}

BOOST_AUTO_TEST_CASE(DecodeNotDelegation)
{
  const uint8_t BAD_DEL[] = {
    0x09, 0x00 // Selectors
  };

  DelegationList dl;
  Block block = makeDelegationListBlock(tlv::ForwardingHint, {DEL1A, BAD_DEL});
  BOOST_CHECK_THROW(dl.wireDecode(block), DelegationList::Error);
}

BOOST_AUTO_TEST_CASE(DecodeMissingPreference)
{
  const uint8_t BAD_DEL[] = {
    0x1f, 0x05, // Delegation
          0x07, 0x03, 0x08, 0x01, 0x42 // Name=/B
  };

  DelegationList dl;
  Block block = makeDelegationListBlock(tlv::ForwardingHint, {DEL1A, BAD_DEL});
  BOOST_CHECK_THROW(dl.wireDecode(block), DelegationList::Error);
}

BOOST_AUTO_TEST_CASE(DecodeMissingName)
{
  const uint8_t BAD_DEL[] = {
    0x1f, 0x03, // Delegation
          0x1e, 0x01, 0x02, // Preference=2
  };

  DelegationList dl;
  Block block = makeDelegationListBlock(tlv::ForwardingHint, {DEL1A, BAD_DEL});
  BOOST_CHECK_THROW(dl.wireDecode(block), DelegationList::Error);
}

BOOST_AUTO_TEST_CASE(DecodeUnknownField)
{
  const uint8_t BAD_DEL[] = {
    0x1f, 0x0a, // Delegation
          0x1e, 0x01, 0x02, // Preference=2
          0x09, 0x00, // Selectors
          0x07, 0x03, 0x08, 0x01, 0x42 // Name=/B
  };

  DelegationList dl;
  Block block = makeDelegationListBlock(tlv::ForwardingHint, {DEL1A, BAD_DEL});
  BOOST_CHECK_THROW(dl.wireDecode(block), DelegationList::Error);
}

BOOST_AUTO_TEST_CASE(DecodeWrongOrder)
{
  const uint8_t BAD_DEL[] = {
    0x1f, 0x08, // Delegation
          0x07, 0x03, 0x08, 0x01, 0x42, // Name=/B
          0x1e, 0x01, 0x02 // Preference=2
  };

  DelegationList dl;
  Block block = makeDelegationListBlock(tlv::ForwardingHint, {DEL1A, BAD_DEL});
  BOOST_CHECK_THROW(dl.wireDecode(block), DelegationList::Error);
}

BOOST_AUTO_TEST_SUITE_END() // Decode

BOOST_AUTO_TEST_SUITE(InsertEncode)

BOOST_AUTO_TEST_CASE(InsertSimple)
{
  DelegationList dl;
  BOOST_CHECK_EQUAL(dl.empty(), true);
  dl.insert(2, "/A");
  BOOST_CHECK_EQUAL(dl.empty(), false);
  dl.insert(1, "/B");
  BOOST_CHECK_EQUAL(dl.size(), 2);

  EncodingBuffer encoder;
  dl.wireEncode(encoder);
  BOOST_CHECK_EQUAL(encoder.block(), makeDelegationListBlock(tlv::ForwardingHint, {DEL1B, DEL2A}));
}

BOOST_AUTO_TEST_CASE(InsertReplace)
{
  DelegationList dl({{2, "/A"}});
  dl.insert(Delegation{1, "/A"}, DelegationList::INS_REPLACE);
  BOOST_CHECK_EQUAL(dl.size(), 1);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 1);
  BOOST_CHECK_EQUAL(dl[0].name, "/A");

  EncodingBuffer encoder;
  dl.wireEncode(encoder);
  BOOST_CHECK_EQUAL(encoder.block(), makeDelegationListBlock(tlv::ForwardingHint, {DEL1A}));
}

BOOST_AUTO_TEST_CASE(InsertAppend)
{
  DelegationList dl({{2, "/A"}});
  dl.insert(Delegation{1, "/A"}, DelegationList::INS_APPEND);
  BOOST_CHECK_EQUAL(dl.size(), 2);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 1);
  BOOST_CHECK_EQUAL(dl.at(1).preference, 2);

  EncodingBuffer encoder;
  dl.wireEncode(encoder);
  BOOST_CHECK_EQUAL(encoder.block(), makeDelegationListBlock(tlv::ForwardingHint, {DEL1A, DEL2A}));
}

BOOST_AUTO_TEST_CASE(InsertSkip)
{
  DelegationList dl({{2, "/A"}});
  dl.insert(Delegation{1, "/A"}, DelegationList::INS_SKIP);
  BOOST_CHECK_EQUAL(dl.size(), 1);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 2);

  EncodingBuffer encoder;
  dl.wireEncode(encoder);
  BOOST_CHECK_EQUAL(encoder.block(), makeDelegationListBlock(tlv::ForwardingHint, {DEL2A}));
}

BOOST_AUTO_TEST_CASE(Unsorted)
{
  DelegationList dl(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A}), false);
  dl.insert(1, "/B");
  BOOST_CHECK_EQUAL(dl.size(), 2);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 2);
  BOOST_CHECK_EQUAL(dl.at(0).name, "/A");
  BOOST_CHECK_EQUAL(dl.at(1).preference, 1);
  BOOST_CHECK_EQUAL(dl.at(1).name, "/B");

  EncodingBuffer encoder;
  dl.wireEncode(encoder, tlv::Content);
  BOOST_CHECK_EQUAL(encoder.block(), makeDelegationListBlock(tlv::Content, {DEL2A, DEL1B}));
}

BOOST_AUTO_TEST_CASE(EncodeBadType)
{
  DelegationList dl(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A}));
  EncodingBuffer encoder;
  BOOST_CHECK_THROW(dl.wireEncode(encoder, tlv::Selectors), std::invalid_argument);
}

BOOST_AUTO_TEST_CASE(EncodeEmpty)
{
  DelegationList dl;
  EncodingBuffer encoder;
  BOOST_CHECK_THROW(dl.wireEncode(encoder), DelegationList::Error);
}

BOOST_AUTO_TEST_SUITE_END() // InsertEncode

BOOST_AUTO_TEST_SUITE(Erase)

BOOST_AUTO_TEST_CASE(EraseNoop)
{
  DelegationList dl;
  dl.insert(1, "/A");
  BOOST_CHECK_EQUAL(dl.erase(2, "/A"), 0);
  BOOST_CHECK_EQUAL(dl.erase(Delegation{1, "/B"}), 0);
  BOOST_CHECK_EQUAL(dl.size(), 1);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 1);
  BOOST_CHECK_EQUAL(dl.at(0).name, "/A");
}

BOOST_AUTO_TEST_CASE(EraseOne)
{
  DelegationList dl;
  dl.insert(1, "/A");
  BOOST_CHECK_EQUAL(dl.erase(1, "/A"), 1);
  BOOST_CHECK_EQUAL(dl.size(), 0);
}

BOOST_AUTO_TEST_CASE(EraseByName)
{
  DelegationList dl;
  dl.insert(1, "/A");
  dl.insert(2, "/A", DelegationList::INS_APPEND);
  BOOST_CHECK_EQUAL(dl.size(), 2);
  BOOST_CHECK_EQUAL(dl.erase("/A"), 2);
  BOOST_CHECK_EQUAL(dl.size(), 0);
}

BOOST_AUTO_TEST_SUITE_END() // Erase

BOOST_AUTO_TEST_SUITE(Sort)

BOOST_AUTO_TEST_CASE(Noop)
{
  DelegationList dl(makeDelegationListBlock(tlv::ForwardingHint, {DEL1A}));
  BOOST_CHECK_EQUAL(dl.isSorted(), true);
  dl.sort();
  BOOST_CHECK_EQUAL(dl.isSorted(), true);
}

BOOST_AUTO_TEST_CASE(Sort)
{
  DelegationList dl(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A, DEL2B, DEL1A}), false);
  BOOST_CHECK_EQUAL(dl.isSorted(), false);
  dl.sort();
  BOOST_CHECK_EQUAL(dl.isSorted(), true);
  BOOST_CHECK_EQUAL(dl.size(), 3);
  BOOST_CHECK_EQUAL(dl.at(0).preference, 1);
  BOOST_CHECK_EQUAL(dl.at(0).name, "/A");
  BOOST_CHECK_EQUAL(dl.at(1).preference, 2);
  BOOST_CHECK_EQUAL(dl.at(1).name, "/A");
  BOOST_CHECK_EQUAL(dl.at(2).preference, 2);
  BOOST_CHECK_EQUAL(dl.at(2).name, "/B");
}

BOOST_AUTO_TEST_SUITE_END() // Sort

BOOST_AUTO_TEST_SUITE(Compare)

BOOST_AUTO_TEST_CASE(Empty)
{
  DelegationList dl1, dl2;
  BOOST_CHECK_EQUAL(dl1, dl2);
}

BOOST_AUTO_TEST_CASE(SortedEqual)
{
  DelegationList dl1(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A, DEL1B})),
                 dl2(makeDelegationListBlock(tlv::Content, {DEL1B, DEL2A}));
  BOOST_CHECK_EQUAL(dl1, dl2);
}

BOOST_AUTO_TEST_CASE(SortedUnequal)
{
  DelegationList dl1(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A, DEL1B})),
                 dl2(makeDelegationListBlock(tlv::Content, {DEL1A, DEL2B}));
  BOOST_CHECK_NE(dl1, dl2);
}

BOOST_AUTO_TEST_CASE(UnsortedSameOrder)
{
  DelegationList dl1(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A, DEL1B}), false),
                 dl2(makeDelegationListBlock(tlv::Content, {DEL2A, DEL1B}), false);
  BOOST_CHECK_EQUAL(dl1, dl2);
}

BOOST_AUTO_TEST_CASE(UnsortedDifferentOrder)
{
  DelegationList dl1(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A, DEL1B}), false),
                 dl2(makeDelegationListBlock(tlv::Content, {DEL1B, DEL2A}), false);
  BOOST_CHECK_NE(dl1, dl2);
}

BOOST_AUTO_TEST_SUITE_END() // Compare

BOOST_AUTO_TEST_SUITE(Print)

BOOST_AUTO_TEST_CASE(PrintEmpty)
{
  DelegationList dl;
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(dl), "[]");
}

BOOST_AUTO_TEST_CASE(PrintNormal)
{
  DelegationList dl(makeDelegationListBlock(tlv::ForwardingHint, {DEL2A, DEL1B}));
  BOOST_CHECK_EQUAL(boost::lexical_cast<std::string>(dl), "[/B(1),/A(2)]");
}

BOOST_AUTO_TEST_SUITE_END() // Print

BOOST_AUTO_TEST_SUITE_END() // TestDelegationList

} // namespace tests
} // namespace ndn


text:
//===---------------------------------------------------------------------------------*- C++-*-===//
//                         _____                        _
//                        / ____|                      (_)
//                       | (___   ___  __ _ _   _  ___  _  __ _
//                        \___ \ / _ \/ _` | | | |/ _ \| |/ _` |
//                        ____) |  __/ (_| | |_| | (_) | | (_| |
//                       |_____/ \___|\__, |\__,_|\___/|_|\__,_| - Game Engine
//                                       | |
//                                       |_|
//
// This file is distributed under the MIT License (MIT).
// See LICENSE.txt for details.
//
//===------------------------------------------------------------------------------------------===//

#include "sequoia-engine/Game/SceneNode.h"
#include "sequoia-engine/Core/Format.h"
#include "sequoia-engine/Core/Logging.h"
#include "sequoia-engine/Core/StringRef.h"
#include "sequoia-engine/Core/StringUtil.h"
#include "sequoia-engine/Math/CoordinateSystem.h"
#include <boost/lexical_cast.hpp>
#include <numeric>

namespace sequoia {

namespace game {

SceneNode::SceneNode(const std::string& name, SceneNode::SceneNodeKind kind)
    : std::enable_shared_from_this<SceneNode>(), kind_(kind), position_(math::vec3()),
      orientation_(math::quat()), scale_(1.0f), modelMatrix_(), modelMatrixIsDirty_(true),
      parent_(), name_(name) {
  for(int i = 0; i < capabilities_.size(); ++i)
    capabilities_[i] = nullptr;
}

SceneNode::SceneNode(const SceneNode& other)
    : std::enable_shared_from_this<SceneNode>(), kind_(other.kind_), position_(other.position_),
      orientation_(other.orientation_), scale_(other.scale_), modelMatrix_(other.modelMatrix_),
      modelMatrixIsDirty_(other.modelMatrixIsDirty_), parent_(other.parent_) {

  // Adjust the name, we append a `_copy_X` where `X` is the version of the copy
  StringRef nameRef(other.name_);
  std::size_t copyPos = nameRef.find("_copy_");

  if(copyPos != StringRef::npos) {
    StringRef versionStr = nameRef.substr(copyPos + sizeof("_copy_") - 1);
    int version = boost::lexical_cast<int>(versionStr.data(), versionStr.size()) + 1;
    name_ = nameRef.substr(0, copyPos).str() + "_copy_" + std::to_string(version);
  } else {
    name_ = other.name_ + "_copy_1";
  }

  // Clone children
  for(const auto& child : other.children_)
    children_.emplace_back(child->clone());

  // Clone capabilites
  for(int i = 0; i < capabilities_.size(); ++i)
    capabilities_[i] = other.capabilities_[i] ? other.capabilities_[i]->clone(this) : nullptr;
}

SceneNode::~SceneNode() {}

void SceneNode::resetOrientation() { setOrientation(math::quat()); }

math::mat3 SceneNode::getLocalAxes() const {
  math::vec3 axisX = getOrientation() * math::CoordinateSystem::X();
  math::vec3 axisY = getOrientation() * math::CoordinateSystem::Y();
  math::vec3 axisZ = getOrientation() * math::CoordinateSystem::Z();
  return math::mat3(axisX, axisY, axisZ);
}

void SceneNode::applyImpl(const std::function<void(SceneNode*)>& functor) {
  functor(this);
  for(const auto& child : getChildren())
    child->applyImpl(functor);
}

void SceneNode::applyNoexceptImpl(
    const std::function<void(SceneNode*) noexcept>& functor) noexcept {
  functor(this);
  for(const auto& child : getChildren())
    child->applyNoexceptImpl(functor);
}

void SceneNode::update(const UpdateEvent& event) {
  for(int i = 0; i < capabilities_.size(); ++i)
    if(capabilities_[i])
      capabilities_[i]->update(event);
}

void SceneNode::translate(const math::vec3& d, TransformSpace relativeTo) {
  setPosition(getPosition() + d);
}

void SceneNode::rotate(const math::quat& q, TransformSpace relativeTo) {
  math::quat newOrientation = q * getOrientation();

  // Normalize quaternion to avoid drift
  newOrientation = math::normalize(newOrientation);
  setOrientation(newOrientation);
}

void SceneNode::rotate(const math::vec3& axis, const math::Radian& angle,
                       SceneNode::TransformSpace relativeTo) {
  rotate(math::angleAxis(angle.inRadians(), axis), relativeTo);
}

void SceneNode::roll(const math::Radian& angle, TransformSpace relativeTo) {
  rotate(math::CoordinateSystem::Z(), angle, relativeTo);
}

void SceneNode::pitch(const math::Radian& angle, TransformSpace relativeTo) {
  rotate(math::CoordinateSystem::X(), angle, relativeTo);
}

void SceneNode::yaw(const math::Radian& angle, TransformSpace relativeTo) {
  rotate(math::CoordinateSystem::Y(), angle, relativeTo);
}

std::shared_ptr<SceneNode> SceneNode::clone() { return SceneNode::allocate<SceneNode>(*this); }

std::string SceneNode::toString() const {
  auto stringPair = toStringImpl();
  return core::format("{}[\n  {}]", stringPair.first, core::indent(stringPair.second));
}

std::pair<std::string, std::string> SceneNode::toStringImpl() const {
  return std::make_pair(
      "SceneNode",
      core::format(
          "name = {},\n"
          "position = {},\n"
          "orientation = {},\n"
          "scale = {},\n"
          "parent = {},\n"
          "capabilities = {},\n"
          "children = {},\n",
          name_, position_, orientation_, scale_, hasParent() ? getParent()->getName() : "null",

          // Capabilities
          std::accumulate(
              capabilities_.begin(), capabilities_.end(), true,
              [](bool isNull, const auto& capability) { return isNull && capability == nullptr; })
              ? "null"
              : core::toStringRange(capabilities_,
                                    [](const auto& capability) {
                                      return core::indent(capability ? capability->toString()
                                                                     : "null");
                                    }),

          // Children
          hasChildren()
              ? core::toStringRange(children_,
                                    [](const auto& node) { return core::indent(node->toString()); })
              : "null"));
}

void SceneNode::computeModelMatrix() {
  // ModelMatrix = TranslationMatrix * RotatationMatrix * ScaleMatrix
  modelMatrix_ = math::translate(math::mat4(1.0f), position_);
  modelMatrix_ = modelMatrix_ * math::mat4_cast(orientation_);
  modelMatrix_ = math::scale(modelMatrix_, glm::vec3(scale_));

  modelMatrixIsDirty_ = false;
}

} // namespace game

} // namespace sequoia

ext: cpp

max_stars_repo_name: thfabian/sequoia

max_issues_repo_name: thfabian/sequoia

max_forks_repo_name: thfabian/sequoia


text:
/**
 * @file commclient.cpp
 * @brief
 * Implements the client side of an application. CommClient inherits the functionality
 * of CommCore and just adds a connect operation to it.
 *
 * @author Johan Vanslembrouck (johan.vanslembrouck@altran.com, johan.vanslembrouck@gmail.com)
 */

#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio.hpp>

#include "async_operation.h"
#include "commservice.h"
#include "commcore.h"

#include "commclient.h"

using boost::asio::steady_timer;
using boost::asio::ip::tcp;

namespace corolib
{

CommClient::CommClient(boost::asio::io_context& io_context,
    boost::asio::ip::tcp::endpoint ep)
    : CommCore(io_context)
    , m_ep(ep)
{
    print(PRI2, "%p: CommClient::CommClient()\n", this);
}

// Called by the user of the CommClient class to initiate the connection process.
void CommClient::start()
{
    print(PRI2, "%p: CommClient::start()\n", this);
    index = (index + 1) & (NROPERATIONS - 1);
    assert(m_async_operations[index] == nullptr);
    start_connect(index);

    // Start the deadline actor. You will note that we're not setting any
    // particular deadline here. Instead, the connect and input actors will
    // update the deadline prior to each asynchronous operation.
    m_deadline.async_wait(std::bind(&CommClient::check_deadline, this));
}

async_operation<void> CommClient::start_connecting()
{
    print(PRI2, "%p: CommClient::start_connecting()\n", this);
    index = (index + 1) & (NROPERATIONS - 1);
    assert(m_async_operations[index] == nullptr);
    async_operation<void> ret{ this, index };
    start_connect(index);
    return ret;
}

void CommClient::start_connect(const int idx)
{
    print(PRI2, "%p: CommClient::start_connect()\n", this);

    m_stopped = false;

    std::vector<boost::asio::ip::tcp::endpoint> eps;
    eps.push_back(m_ep);

    tcp::resolver::results_type::iterator endpoint_iter;

    // Set a deadline for the connect operation.
    m_deadline.expires_after(std::chrono::seconds(5));

    // Start the asynchronous connect operation.
    boost::asio::async_connect(
        m_socket,
        eps,
        [this, idx](const boost::system::error_code& error,
                    const tcp::endpoint& result_endpoint)
        {
            (void)result_endpoint;

            print(PRI2, "%p: CommClient::handle_connect(): idx = %d, entry\n", this, idx);
            async_operation_base* om_async_operation = m_async_operations[idx];

            if (m_stopped)
                return;

            // The async_operation function automatically opens the socket at the start
            // of the asynchronous operation. If the socket is closed at this time then
            // the timeout handler must have run first.
            if (!m_socket.is_open())
            {
                print(PRI2, "%p: CommClient::handle_connect(): idx = %d, Connect timed out\n", this, idx);

                // Try the next available endpoint.
                start_connect(idx);
            }
            // Check if the connect operation failed before the deadline expired.
            else if (error)
            {
                print(PRI2, "%p: CommClient::handle_connect(): idx = %d, Connect error: %d\n", this, idx, error);

                // We need to close the socket used in the previous connection attempt
                // before starting a new one.
                m_socket.close();

                // Try the next available endpoint.
                start_connect(idx);
            }
            // Otherwise we have successfully established a connection.
            else
            {
                print(PRI2, "%p: CommClient::handle_connect(): idx = %d, Connection successfully established\n", this, idx);

                print(PRI2, "%p: CommClient::handle_connect(): idx = %d, om_async_operation = %p\n", this, idx, om_async_operation);
                //assert(om_async_operation != nullptr);
                if (om_async_operation)
                {
                    om_async_operation->completed();
                }
                else
                {
                    // This can occur when the async_operation_base has gone out of scope.
                    print(PRI1, "%p: CommCore::handle_connect(): idx = %d, Warning: om_async_operation == nullptr\n", this, idx);
                }
            }
            print(PRI2, "%p: CommClient::CommClient(): idx = %d, exit\n\n", this, idx);
        });
}

}

max_stars_repo_name: JohanVanslembrouck/corolib

max_issues_repo_name: JohanVanslembrouck/corolib

max_forks_repo_name: JohanVanslembrouck/corolib


text:
/*
Copyright 2009-2021 Nicolas Colombe

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 <core/random.hpp>

#include <core/string.hpp>
#include <boost/random.hpp>
#include <sstream>

namespace eXl
{
  class BoostRNG : public Random
  {
  public:
    BoostRNG(unsigned int iSeed) : m_Gen(iSeed) {}

    unsigned int Generate() override
    {
      return m_Gen();
    }

    String Save() override
    {
      std::stringstream outStr;
      outStr << m_Gen;

      return StringUtil::FromASCII(outStr.str().c_str());
    }

    void Restore(String const& iStr)
    {
      std::stringstream inStr(StringUtil::ToASCII(iStr).c_str());
      inStr >> m_Gen;
    }

  protected:
    boost::random::mt19937 m_Gen;
  };

  Random* Random::CreateDefaultRNG(unsigned int iSeed)
  {
    return new BoostRNG(iSeed);
  }
}

max_stars_repo_name: eXl-Nic/eXl

max_issues_repo_name: eXl-Nic/eXl

max_forks_repo_name: eXl-Nic/eXl


text:
/* Author: Zachary Kingston */

#include <boost/date_time.hpp>

#include <robowflex_library/log.h>
#include <robowflex_library/util.h>

#include <robowflex_movegroup/services.h>

using namespace robowflex;

/* \file tapedeck.cpp
 * An example script that shows how to use MoveGroupHelper. Here, a callback is
 * installed so that every motion plan issued to MoveGroup is saved to disk as a
 * YAML file. This is useful for collecting and replaying motion planning
 * requests that are done over the course of an experiment.
 */

// Output a captured action to a YAML file.
void callback(movegroup::MoveGroupHelper::Action &action)
{
    ros::Time time = ros::Time::now();

    // Save the requests to a folder in the home directory.
    const std::string filename = "~/robowflex_tapedeck/" + to_iso_string(time.toBoost()) + ".yml";
    action.toYAMLFile(filename);

    RBX_INFO("Wrote YAML for Request ID `%s` to file `%s`", action.id, filename);
}

int main(int argc, char **argv)
{
    // Startup ROS
    ROS ros(argc, argv);

    // Create helper
    movegroup::MoveGroupHelper helper;

    // Setup callback function
    helper.setResultCallback(callback);

    // Wait until killed
    ros.wait();
}

max_stars_repo_name: servetb/robowflex

max_issues_repo_name: servetb/robowflex

max_forks_repo_name: servetb/robowflex


text:
#pragma once
#include <type_traits>

#include <boost/hana/core/when.hpp>
#include <boost/hana/tuple.hpp>

#include <cppjni/concepts/is_java_class_definition.hpp>
#include <cppjni/jni_wrappers/generate_jni_signature_string.hpp>
#include <cppjni/mpl/condition.hpp>
#include <cppjni/mpl/list.hpp>
#include <cppjni/types/object.fwd.hpp>
#include <cppjni/types/object_converter.hpp>

namespace cppjni
{
namespace metadeclaration
{
    template<typename T>
    struct replace_java_declaration_with_converter
    {
        using type = T;
    };

    template<template <typename> class T>
    struct replace_java_declaration_with_converter<cppjni::types::Object<T>>
    {
        using type = types::ObjectConverter<cppjni::types::Object<T>>;
    };

    template<typename function_signature_t>
    struct signature_info;

    template<typename function_return_t, typename ...args_t>
    struct signature_info<function_return_t(args_t...)>
    {
        using original_signature_t = function_return_t(args_t...);
        using arguments_t = mpl::list<
                                typename replace_java_declaration_with_converter<args_t>::type...
                            >;
        using return_t = typename replace_java_declaration_with_converter<function_return_t>::type;

        using final_signature_t = return_t(typename replace_java_declaration_with_converter<args_t>::type...);
        using jni_type_string_t = typename ::cppjni::jniwrappers::generate_jni_signature_string<final_signature_t>::type;
    };
}
}

ext: hpp

max_stars_repo_name: CMakeezer/cppJNI

max_issues_repo_name: CMakeezer/cppJNI

max_forks_repo_name: CMakeezer/cppJNI


text:
#pragma once

#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <vector>
#include <utility>

#include <Eigen/Core>

#include <pcl/common/transforms.h>
#include <pcl/io/pcd_io.h>
#include <pcl/common/common.h>
#include <pcl/point_cloud.h>

class PointCloudDim2D;
struct TransformXYTheta;

typedef Eigen::Matrix<std::uint8_t, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> RMatrixXui8;

void writeBGM(const std::string& kSavePath, const RMatrixXui8& kMat);

void writeScanInfo(const std::string& KInfofilename, const std::vector<std::string>& kVelonames,
                   const std::vector<TransformXYTheta>& kTFs,
                   const std::pair<std::uint32_t, std::uint32_t>& kMapImgSize,
                   const float kResolution);

inline
std::array<int, 2> computePixelLoc(
    int imgHeight,
    int imgWidth,
    float x,
    float y,
    float resolution)
{
    assert(imgHeight > 0 && imgWidth > 0);
    assert(x >= 0.f && y >= 0.f);
    assert(resolution > 0.f);

    return std::array<int, 2>{
        std::min(imgHeight - static_cast<int>(floor(x / resolution)), imgHeight - 1),
        std::min( imgWidth - static_cast<int>(floor(y / resolution)),  imgWidth - 1)
    };
}

template<typename T>
inline T eucddist(const T& x0, const T& y0, const T& x1, const T& y1)
{
    return std::sqrt(std::pow(x0 - x1, 2) + std::pow(y0 - y1, 2));
}

template <typename PointT>
void aggregatePointClouds(
    const std::vector<pcl::PointCloud<PointT>>& kIndivClouds,
    pcl::PointCloud<PointT>& aggCloud)
{
    for (auto it = kIndivClouds.begin(); it != kIndivClouds.end(); ++it)
        aggCloud += *it;
}

template<typename PointT>
RMatrixXui8 buildBEVFromCloud(
    const pcl::PointCloud<PointT>& kCloud,
    const float kXdiff,
    const float kYdiff,
    const float outRes,
    bool useZvals = false,
    float minZ = 0.f)
{
    // Sanity checks.
    assert(kXdiff > 0.f && kYdiff > 0.f && outRes > 0.f);

    // Compute the image size.
    auto imgHeight = static_cast<int>(ceil(kXdiff / outRes));
    auto imgWidth = static_cast<int>(ceil(kYdiff / outRes));

    // Create the bird's eye matrix (image) and iteratively fill the matrix.
    RMatrixXui8 bev = RMatrixXui8::Zero(imgHeight, imgWidth);
    for (std::size_t i = 0; i < kCloud.size(); i++)
    {
        const PointT& pt = kCloud[i];
        float pixelValue = 0.0f;
        // max / min from zlen
        if (useZvals)
        {
            //pixelValue = (pt.z - kMinPt.z) / (kMaxPt.z - kMinPt.z);
            pixelValue = (pt.z + minZ) / (minZ * 2);
        }
        else
        {
            pixelValue = pt.intensity;
        }
        pixelValue = std::min(std::max(pixelValue * 255.0f, 0.0f), 255.0f);

        auto pxLoc = computePixelLoc(imgHeight, imgWidth, pt.x, pt.y, outRes);
        auto row = pxLoc[0];
        auto col = pxLoc[1];

        bev(row, col) = std::max(static_cast<std::uint8_t>(pixelValue), bev(row, col));
    }
    return bev;
}

template<typename PointT>
void extractPointCloudROI(
    const pcl::PointCloud<PointT>& kOriginalPC,
    const float kXlen,
    const float kYlen,
    pcl::PointCloud<PointT>& extractedPC)
{
    // Sanity checks.
    assert(kOriginalPC.size() > 0);
    assert(kXlen > 0.f && kYlen > 0.f);

    float x = 0.f, y = 0.f;
    for (auto pt_it = kOriginalPC.points.begin(); pt_it != kOriginalPC.points.end(); ++pt_it)
    {
        x = pt_it->x;
        y = pt_it->y;
        if (-kXlen < x && x < kXlen && -kYlen < y && y < kYlen)
            extractedPC.push_back(*pt_it);
    }
}

template<typename PointT>
void extractPointCloudROI(
    const pcl::PointCloud<PointT>& kOriginalPC,
    const float kRadius,
    pcl::PointCloud<PointT>& extractedPC)
{
    // Sanity checks.
    assert(kOriginalPC.size() > 0);
    assert(kRadius > 0.f);

    float d = 0.f;
    for (auto pt_it = kOriginalPC.points.begin(); pt_it != kOriginalPC.points.end(); ++pt_it)
    {
        d = std::sqrt(std::pow(pt_it->x, 2) + std::pow(pt_it->y, 2));
        if (d < kRadius)
            extractedPC.push_back(*pt_it);
    }
}

template<typename PointT>
void translateDataXY(
    pcl::PointCloud<PointT>& cloud,
    const Eigen::Vector2f& kShift)
{
    // Sanity check.
    assert(cloud.size() > 0);

    const float dx = -kShift[0], dy = -kShift[1];
    for (auto it = cloud.points.begin(); it != cloud.points.end(); ++it)
    {
        it->x += dx;
        it->y += dy;
    }
}

template<typename T>
void translateDataXY(
    std::vector<T>& data,
    const Eigen::Vector2f& kShift)
{
    // Sanity check.
    assert(data.size() > 0);

    const float dx = -kShift[0], dy = -kShift[1];
    for (auto it = data.begin(); it != data.end(); ++it)
    {
        it->x += dx;
        it->y += dy;
    }
}


text:
// Copyright 2020 Dow, Inc.
//
// 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 "ReceptorVisitor.h"
#include "core/Error.h"
#include "core/Projection.h"
#include "core/Scenario.h"
#include "core/Validation.h"

#include <algorithm>
#include <filesystem>

#include <boost/log/trivial.hpp>
#include <boost/log/attributes/scoped_attribute.hpp>
#include <fmt/format.h>

// ERRORS LIST:
// FluxProfileDialog.cpp
//     BOOST_LOG_TRIVIAL(error) << "Failed to acquire write lock";
//     BOOST_LOG_TRIVIAL(error) << "Failed to acquire read lock";
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Import");
//         BOOST_LOG_TRIVIAL(error) << e.what();
// GenericDistribution.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Distribution");
//         BOOST_LOG_TRIVIAL(warning) << e.what();
// GenericDistributionDialog.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Distribution");
//         BOOST_LOG_TRIVIAL(warning) << e.what();
// GeometryOp.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Geometry");
//         BOOST_LOG_TRIVIAL(warning) << message;
//         BOOST_LOG_TRIVIAL(error) << e.what();
// GeosOp.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Geometry");
//         BOOST_LOG_TRIVIAL(info) << "geos: " << buf;
//         BOOST_LOG_TRIVIAL(error) << "geos: " << buf;
// IPCServer.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Model");
//         BOOST_LOG_TRIVIAL(error) << "Unable to start the IPC server: "
//         BOOST_LOG_TRIVIAL(error) << "Unable to stop the IPC server: "
// RunstreamParser.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Import");
//         *Many*
// Scenario.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Model");
//         BOOST_LOG_TRIVIAL(error) << "Invalid time range";
//         BOOST_LOG_TRIVIAL(error) << "Missing flux profile for source " << s.srcid;
//         BOOST_LOG_TRIVIAL(error) << "Failed to acquire read lock";
// ShapefileParser.cpp
//     BOOST_LOG_SCOPED_THREAD_TAG("Source", "Import");
//         *Many*
// UDUnitsInterface.cpp
//     BOOST_LOG_TRIVIAL(error) << "udunits2: " << buf;

namespace Validation {

ValidateScenario::ValidateScenario(const Scenario& s)
    : s_(s)
{
    BOOST_LOG_SCOPED_THREAD_TAG("Source", s.name)

    // Warn is projection is "Local"
    // Check projection validity
    // Check that domain intersects projection area

    validateMeteorology();
    validateFluxProfiles();
    validateReceptors();
    validateSourceGroups();
}

void ValidateScenario::validateMeteorology()
{
    /*
    namespace fs = std::filesystem;

    if (s_.surfaceFile.empty()) {
        BOOST_LOG_TRIVIAL(error) << "Surface file is missing";
    }
    else {
        fs::path path(s_.surfaceFile);
        try {
            if (!fs::exists(path) || !fs::is_regular_file(path)) {
                BOOST_LOG_TRIVIAL(error) << "Surface file does not exist; check path";
            }
        }
        catch (fs::filesystem_error& e) {
            BOOST_LOG_TRIVIAL(error) << "Surface file error: " << e.what();
        }
    }

    if (s_.upperAirFile.empty()) {
        BOOST_LOG_TRIVIAL(error) << "Upper air file is missing";
    }
    else {
        try {
            fs::path path(s_.upperAirFile);
            if (!fs::exists(path) || !fs::is_regular_file(path)) {
                BOOST_LOG_TRIVIAL(error) << "Upper air file does not exist; check path";
            }
        }
        catch (fs::filesystem_error& e) {
            BOOST_LOG_TRIVIAL(error) << "Upper air file error: " << e.what();
        }
    }

    // Try to parse file
    // Check for calm/missing hours exceed 10% threshold
    // Check for matching records in upper air file
    // Check for PROFBASE (anemometer elevation) below source or receptor elevations
    */
}

void ValidateScenario::validateFluxProfiles()
{
    if (s_.fluxProfiles.empty()) {
        BOOST_LOG_TRIVIAL(error) << "No flux profiles have been defined";
        return;
    }

    for (std::shared_ptr<FluxProfile> fp : s_.fluxProfiles) {
        if (!fp)
            continue;

        if (fp->refAppRate < 0)
            BOOST_LOG_TRIVIAL(error) << "Reference application rate for flux profile '" << fp->name << "' is negative";

        if (fp->refAppRate == 0)
            BOOST_LOG_TRIVIAL(warning) << "Reference application rate for flux profile '" << fp->name << "' is zero; reference flux profile will not be scaled by source application rate";

        if (fp->refFlux.empty())
            BOOST_LOG_TRIVIAL(error) << "Flux profile '" << fp->name << "' has no reference flux data; flux will be zero for all hours";

        if (fp->dsMethod != FluxProfile::DSMethod::Disabled && fp->refVL == fp->maxVL)
            BOOST_LOG_TRIVIAL(warning) << "Depth scaling enabled for flux profile '" << fp->name << "' and reference volatilization loss equals maximum volatilization loss; depth scaling will not be used";
    }
}

void ValidateScenario::validateReceptors()
{
    if (s_.receptors.empty()) {
        BOOST_LOG_TRIVIAL(error) << "No receptors have been defined";
        return;
    }

    double zElevMin = 0;
    double zElevMax = 0;

    for (const auto& rg : s_.receptors) {
        std::string name = boost::apply_visitor(ReceptorGroupNameVisitor(), rg);
        std::size_t n = boost::apply_visitor(ReceptorNodeCountVisitor(), rg);
        if (n == 0)
            BOOST_LOG_TRIVIAL(warning) << "Receptor group '" << name << "' contains no receptors";

        for (std::size_t i = 0; i < n; ++i) {
            ReceptorNode node = boost::apply_visitor(ReceptorGroupNodeVisitor(i), rg);
            zElevMin = std::min(zElevMin, node.zElev);
            zElevMax = std::max(zElevMax, node.zElev);
        }
    }

    if (!s_.aermodFlat && zElevMin == zElevMax) {
        BOOST_LOG_TRIVIAL(warning) << "ELEV is enabled, but all receptors have equal elevation";
    }

    // Receptor group 'G' contains receptors outside of modeling domain
}

void ValidateScenario::validateSourceGroups()
{
    if (s_.sourceGroups.empty()) {
        BOOST_LOG_TRIVIAL(error) << "No source groups have been defined";
    }

    for (const std::shared_ptr<SourceGroup>& sg : s_.sourceGroups) {
        if (!sg)
            continue;

        if (sg->sources.empty())
            BOOST_LOG_TRIVIAL(error) << "No sources have been defined for source group '" << sg->grpid << "'";

        if (sg->fluxProfile.data.empty())
            BOOST_LOG_TRIVIAL(error) << "Flux profile probabilities have not been set for source group '" << sg->grpid << "'";
    }

    // Sources 'A', 'B', 'C' ... have overlapping geometry within the same emission period
    // Receptor ring 'R' not updated after source geometry changed
    // Receptor ring 'R' references a missing source group
    // Missing flux profile for source 'S'
    // Emission period for Source 'S' overlaps met file start
    // Emission period for Source 'S' overlaps met file end
    // Emission period for source 'S' is outside of met file range; flux will be zero for all hours
    // Application rate for source 'S' is zero; flux will be zero for all hours (only if reference flux application rate is non-zero)
    // Buffer zone could not be assigned to source 'S': [area, application rate] exceeds threshold
    // Monte Carlo parameter [name] generated values outside of acceptable limits for source 'S'
}

} // namespace Validation

max_stars_repo_name: sofea-model/sofea

max_issues_repo_name: sofea-model/sofea

max_forks_repo_name: sofea-model/sofea


text:
//
//  HansoftSDK_ResourceAllocation.cpp
//  Application Entry point
//
//  Created by Sitael S.p.A. on 20/02/2015.
//

#include "./hansoftSdk/HPMSdkCpp.h"

#ifdef _MSC_VER
#include <tchar.h>
#include <conio.h>
#include <windows.h>
#else
#include <sys/time.h>
#include <sys/select.h>
#include <termios.h>
#ifdef __APPLE__
#include <errno.h>
#include <pthread.h>
#endif
#endif
#include <iostream>
#include <string>
#include <map>
#include "WorkDoneUpdatedTask.h"
#include "xlslib.h"
#include <boost/date_time.hpp>
#include "DateTimeHelper.h"
#include "XlsConstants.h"
#include "HansoftConnectionService.h"
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <stdio.h>
#include <stdlib.h>
#include "HansoftLinkHelper.h"

using namespace std;
using namespace HPMSdk;
using namespace xlslib_core;
using namespace boost;

class HansoftSDK_ResourceAllocation
{
public:

	HansoftConnectionService hansoftService;
	HPMSdkSession *sdkSession;
	container::flat_map<string, int> mapActiveResource;
	container::flat_map <string, container::flat_map<unsigned long long, vector<WorkDoneUpdatedTask>>> mapTask;

	/**
	* Constructor
	*
	*
	*/
	HansoftSDK_ResourceAllocation()
	{
		sdkSession = NULL;
	}

	/**
	* Distructor
	*
	*
	*/
	~HansoftSDK_ResourceAllocation()
	{
		if (sdkSession)
		{
			hansoftService.disconnect();
		}
	}
	/**
	* Execute method.
	* Parse projects and output excel based on config.ini file
	*
	*/
	void Execute()
	{

		if (hansoftService.connectToHansoftServer())
		{
			try
			{
				sdkSession = hansoftService.m_pSession;
				printInputParameters();
				string projToAnalyze = ConfigHelper::getParamStringForSection(loginSection, projectNameToSearch);
				HPMProjectEnum projects = sdkSession->ProjectEnum();
				HPMResourceEnum resMemb = sdkSession->ResourceEnum();

				for (HPMUInt32 o = 0; o < resMemb.m_Resources.size(); ++o)
				{
					HPMUniqueID idRisorsa = resMemb.m_Resources[o];
					HPMResourceProperties propRes = sdkSession->ResourceGetProperties(idRisorsa);
					if (propRes.m_ResourceType != EHPMResourceType::EHPMResourceType_QAAccount )
					{
						string resourceName = string(propRes.m_Name.begin(), propRes.m_Name.end());
						EHPMResourceLockFlag flag = sdkSession->ResourceGetLockFlags(idRisorsa);
						if (flag == EHPMResourceLockFlag::EHPMResourceLockFlag_None)
						{
							mapActiveResource[resourceName] = 1;
						}

					}
				}

				for (HPMUInt32 i = 0; i < projects.m_Projects.size(); ++i)
				{
					HPMUniqueID projectUid = projects.m_Projects[i];
					HPMTaskEnum tasks = sdkSession->TaskEnum(projectUid);
					HPMProjectProperties projectProp = sdkSession->ProjectGetProperties(projectUid);
					HPMProjectCustomColumns columns = sdkSession->ProjectCustomColumnsGet(projectUid);
					HPMUniqueID customColumnDataHash;
					HPMProjectCustomColumnsColumn columnJob;
					string proj = string(projectProp.m_Name.begin(), projectProp.m_Name.end());

					if (!projectProp.m_bArchivedStatus && (projToAnalyze == "" || proj == projToAnalyze)){
						OutputLogger::logToConsole("Analyzing project:");
						OutputLogger::logToConsole(proj);
						for (HPMUInt32 k = 0; k < columns.m_ShowingColumns.size(); ++k)
						{
							HPMProjectCustomColumnsColumn info = columns.m_ShowingColumns[k];
							if (string(info.m_Name.begin(), info.m_Name.end()) == ConfigHelper::getParamStringForSection(customColumnSection, customColumnName)){
								customColumnDataHash = info.m_Hash;
							}
							else if (string(info.m_Name.begin(), info.m_Name.end()) == ConfigHelper::getParamStringForSection(customColumnSection, customColumnNameJobId)) {
								columnJob = info;
							}

						}
						for (HPMUInt32 j = 0; j < tasks.m_Tasks.size(); ++j)
						{
							string customColumnJobId = "";
							HPMUniqueID taskId = tasks.m_Tasks[j];
							HPMUniqueID clientId = sdkSession->TaskGetID(taskId);
							string taskDescriptionContainer = getContainerDescription(taskId);
							string taskHyperlinkContFinal = getContainerHyperlink(taskId);

							customColumnJobId = getCustomColumnValue(taskId, columnJob);

							parseHistoryForTask(taskId, customColumnDataHash, projectUid, projectProp, taskDescriptionContainer, taskHyperlinkContFinal, customColumnJobId);
						}
					}
				}
				writeResultsToExcel();

			}
			catch (HPMSdkException &_Error)
			{
				HPMString SdkError = _Error.GetAsString();
				OutputLogger::logToConsole("Exception in processing loop: " + string(SdkError.begin(), SdkError.end()));
			}
			catch (HPMSdkCppException _Error)
			{
				string SdkCppError = _Error.what();
				OutputLogger::logToConsole("Exception in processing loop: " + SdkCppError);
			}
		}
	}

	string getContainerDescription(HPMUniqueID idTask)
	{
		string desc = "";
		HPMTaskEnum tasksEn = sdkSession->TaskEnumReferences(idTask);
		for (HPMUInt32 j = 0; j < tasksEn.m_Tasks.size(); ++j)
		{
			HPMUniqueID taskRefId = tasksEn.m_Tasks[j];
			HPMUniqueID idParent = sdkSession->TaskRefUtilGetParent(taskRefId);

			if (sdkSession->UtilIsIDTaskRef(idParent))
			{
				HPMUniqueID taskId = sdkSession->TaskRefGetTask(idParent);
				if (taskId != idTask)
				{
					HPMString descHpm = sdkSession->TaskGetDescription(taskId);
					desc = string(descHpm.begin(), descHpm.end());
					break;
				}
			}

		}
		return desc;
	}

	string getContainerHyperlink(HPMUniqueID idTask)
	{
		string taskHyperlinkContFinal = "";
		HPMTaskEnum tasksEn = sdkSession->TaskEnumReferences(idTask);
		for (HPMUInt32 j = 0; j < tasksEn.m_Tasks.size(); ++j)
		{
			HPMUniqueID taskRefId = tasksEn.m_Tasks[j];
			HPMUniqueID idParent = sdkSession->TaskRefUtilGetParent(taskRefId);

			if (sdkSession->UtilIsIDTaskRef(idParent))
			{
				HPMUniqueID taskId = sdkSession->TaskRefGetTask(idParent);
				if (taskId != idTask)
				{
					taskHyperlinkContFinal = HansoftLinkHelper::getHansoftTaskLink(taskId, ConfigHelper::getParamStringForSection(loginSection, hansoftAddress), ConfigHelper::getParamStringForSection(loginSection, hansoftDatabase));
					break;
				}
			}

		}
		return taskHyperlinkContFinal;
	}

	string getCustomColumnValue(HPMUniqueID idTask, HPMProjectCustomColumnsColumn customColumn) {
		string ret = "";
		HPMString value = sdkSession->TaskGetCustomColumnData(idTask, customColumn.m_Hash);
		string valueStr = string(value.begin(), value.end());
		if (valueStr != "") {
			int index = -1;
			HPMString valueCol;
			switch (customColumn.m_Type)
			{
			case EHPMProjectCustomColumnsColumnType_DropList:
				index = atoi(valueStr.c_str());
				ret = getDropListItemValue(index, customColumn.m_DropListItems);
				break;
			default:
				ret = "TODO";
			}
		}

		return ret;
	}

	string getDropListItemValue(int id, vector<HPMProjectCustomColumnsColumnDropListItem> itemList) {
		string ret = "";
		for (vector<HPMProjectCustomColumnsColumnDropListItem>::iterator it = itemList.begin(); it != itemList.end(); ++it) {
			HPMProjectCustomColumnsColumnDropListItem item = *it;
			if (item.m_Id == id)
				ret = string(item.m_Name.begin(), item.m_Name.end());
		}

		return ret;
	}

	/**
	* Execute method
	*
	*
	*/
	int Run()
	{
		Execute();
		return 0;

	}

	/**
	* Print on console input parameters on config.ini
	*
	*
	*/
	void printInputParameters(){

		OutputLogger::logToConsole("Input parameter");
		OutputLogger::logToConsole("Selected Project");
		OutputLogger::logToConsole(ConfigHelper::getParamStringForSection(loginSection, projectNameToSearch));
		OutputLogger::logToConsole("Name Custom Column Work Done");
		OutputLogger::logToConsole(ConfigHelper::getParamStringForSection(customColumnSection, customColumnName));
		OutputLogger::logToConsole("Name Custom Column Job ");
		OutputLogger::logToConsole(ConfigHelper::getParamStringForSection(customColumnSection, customColumnNameJobId));
		OutputLogger::logToConsole("Date Start");
		OutputLogger::logToConsole(ConfigHelper::getParamStringForSection(reportSection, reportFromTime));
		OutputLogger::logToConsole("Date End");
		OutputLogger::logToConsole(ConfigHelper::getParamStringForSection(reportSection, reportToTime));
	};

	/**
	* Get history entries for task by querying hansoft sdk
	* @param HPMUniqueId taskId
	* @return HPMDataHistory historyObject
	*/
	HPMDataHistory getHistoryForTask(HPMUniqueID taskId){
		HPMDataHistoryGetHistoryParameters params;
		params.m_DataID = taskId;
		params.m_FieldID = EHPMStatisticsField_NoStatistics;
		params.m_FieldData = 0;
		params.m_DataIdent0 = EHPMStatisticsScope_NoStatisticsScope;
		params.m_DataIdent1 = 0;
		bool error;
		HPMDataHistory historyTask;
		historyTask = sdkSession->DataHistoryGetHistory(params, error);
		while (error){
			historyTask = sdkSession->DataHistoryGetHistory(params, error);
		}
		return historyTask;
	}

	/**
	* Write results to excel
	*
	*
	*/
	void writeResultsToExcel(){
		OutputLogger::logToConsole("Writing excel file");

		workbook wb;
		worksheet* sh = wb.sheet(xlsSheetName);

		sh->defaultColwidth(xlsColWidth);

		int startingRow = xlsStartingRow;

		sh->label(0, xlsResourceColumnNumber, xlsResourceColumnHeader);
		sh->label(0, xlsProjectNameColumnNumber, xlsProjectNameColumnHeader);
		sh->label(0, xlsTaskIdColumnNumber, xlsTaskIdColumnHeader);
		sh->label(0, xlsTaskContainerDescriptionColumnNumber, xlsTaskContainerDescriptionColumnHeader);
		sh->label(0, xlsTaskDescriptionColumnNumber, xlsTaskDescriptionColumnHeader);
		sh->label(0, xlsWorkDoneIncrementColumnNumber, xlsWorkDoneIncrementColumnHeader);
		sh->label(0, xlsTimeModificationColumnNumber, xlsTimeModificationColumnHeader);
		sh->label(0, xlsJobIdColumnNumber, xlsJobIdColumnHeader);
		for (container::flat_map<string, container::flat_map<unsigned long long, vector<WorkDoneUpdatedTask>>>::iterator it = mapTask.begin(); it != mapTask.end(); ++it)
		{
			container::flat_map<unsigned long long, vector<WorkDoneUpdatedTask>> mapForDateUser = it->second;
			startingRow = startingRow + xlsRowInterval;
			checkForMissingDays(mapForDateUser,it->first);
			//check sulla data mapForDateUser chiave giorno valore vettore task
			bool firstTimeForUser = true;
			for (container::flat_map<unsigned long long, vector<WorkDoneUpdatedTask>>::iterator it2 = mapForDateUser.begin(); it2 != mapForDateUser.end(); ++it2){
				double counterDailyWork = 0;

				vector<WorkDoneUpdatedTask> resourceList = it2->second;
				startingRow = !firstTimeForUser ? startingRow + xlsSecondRowInterval : startingRow;
				firstTimeForUser = false;
				format_t *myFormat = wb.format("#0.00");
				xf_t *x_myFormat = wb.xformat(myFormat);

				for (int l = 0; l < resourceList.size(); ++l)
				{
					WorkDoneUpdatedTask task = resourceList[l];
					sh->label(startingRow, xlsResourceColumnNumber, it->first);
					sh->label(startingRow, xlsProjectNameColumnNumber, task.m_projectName);
					sh->number(startingRow, xlsTaskIdColumnNumber, task.m_taskId);
					cell_t *cellHyper = sh->label(startingRow, xlsTaskDescriptionColumnNumber, task.m_taskDescription);
					sh->hyperLink(cellHyper, task.m_taskHyperlink);
					sh->number(startingRow, xlsWorkDoneIncrementColumnNumber, task.m_workDoneIncrement, x_myFormat);
					string completeDate = DateTimeHelper::getDateStringWithHoursFromUnixTimeStampMicroSeconds(task.m_time);
					sh->label(startingRow, xlsTimeModificationColumnNumber, completeDate.substr(0, 11));
					sh->label(startingRow, xlsHourModificationColumnNumber, completeDate.substr(12));
					cell_t *cellHyperCont = sh->label(startingRow, xlsTaskContainerDescriptionColumnNumber, task.m_taskContainerDescription);
					sh->hyperLink(cellHyperCont, task.m_taskContainerHyperlink);
					sh->label(startingRow, xlsJobIdColumnNumber, task.m_jobId);
					++startingRow;
					counterDailyWork += task.m_workDoneIncrement;
				}
				sh->label(startingRow, xlsResourceColumnNumber, it->first);
				string dateString = DateTimeHelper::getDateStringFromUnixTimeStampMicroSeconds((it2->first * 1000000ull));
				string dailyHourLabel = xlsDailyWorkColumnLabel;
				cell_t *cellDailyLabel = sh->label(startingRow, xlsDailyWorkColumnNumberLabel, dailyHourLabel);
				cell_t *cellDaily = sh->number(startingRow, xlsDailyWorkColumnNumber, counterDailyWork, x_myFormat);
				sh->label(startingRow, xlsTimeModificationColumnNumber, dateString);
				if (counterDailyWork < xlsMinHours){
					cellDaily->fillstyle(FILL_SOLID);
					cellDailyLabel->fillstyle(FILL_SOLID);
					cellDaily->fillfgcolor(CLR_RED);
					cellDailyLabel->fillfgcolor(CLR_RED);
				}
				++startingRow;
			}
		}
		string filenamePrefix = xlsFileNamePrefix;
		string fromDateMod = ConfigHelper::getParamStringForSection(reportSection, reportFromTime);
		boost::erase_all(fromDateMod, "/");
		string toDateMod = ConfigHelper::getParamStringForSection(reportSection, reportToTime);
		boost::erase_all(toDateMod, "/");
		string finalFilename = filenamePrefix + fromDateMod + "-" + toDateMod + xlsFileNameExtension;
		wb.Dump(finalFilename);
		OutputLogger::logToConsole("File saved: " + finalFilename);
	};

	void checkForMissingDays(container::flat_map<unsigned long long, vector<WorkDoneUpdatedTask>> &mapForDateUser, string nomeRisorsa)
	{
		if (mapActiveResource.find(nomeRisorsa) != mapActiveResource.end())
		{
			string fromDateConf = ConfigHelper::getParamStringForSection(reportSection, reportFromTime);
			unsigned long long startTimeStamp = DateTimeHelper::getUnixTimeFromString(fromDateConf);
			string toDateConf = ConfigHelper::getParamStringForSection(reportSection, reportToTime);
			unsigned long long endTimeStamp = DateTimeHelper::getUnixTimeFromString(toDateConf);
			unsigned long long currentTimestamp = startTimeStamp;
			while (currentTimestamp <= endTimeStamp)
			{
				if (!(DateTimeHelper::getIsSaturdayOrSunday(currentTimestamp)))
				{
					if ((mapForDateUser.find(currentTimestamp) == mapForDateUser.end()))
					{
						vector<WorkDoneUpdatedTask> emptyVectorUpdate;
						mapForDateUser[currentTimestamp] = emptyVectorUpdate;
					}
				}

				currentTimestamp += 86400ull;
			}
		}

	}

	/**
	* Parse history entries for task
	* @param HPMUniqueId taskId
	* @param HPMUniqueId hash for Work done column
	* @param HPMUniqueId projectId
	* @param HPMProjectProperties project properties
	*
	*/
	void parseHistoryForTask(HPMUniqueID taskId, HPMUniqueID customColumnDataHash, HPMUniqueID projectId, HPMProjectProperties prop,
		string taskContainerDescription, string taskContainerHyperlink, string customColumnJobId){
		string fromDate = ConfigHelper::getParamStringForSection(reportSection, reportFromTime);
		string toDate = ConfigHelper::getParamStringForSection(reportSection, reportToTime);
		HPMDataHistory history = getHistoryForTask(taskId);
		HPMString taskDescriptionW = sdkSession->TaskGetDescription(taskId);
		string taskDescription = string(taskDescriptionW.begin(), taskDescriptionW.end());
		int clientId = sdkSession->TaskGetID(taskId);
		std::vector<HPMDataHistoryEntry> sortedEntries = history.m_HistoryEntries;
		double incrementHistory = 0;
		for (HPMUInt32 m = 0; m < sortedEntries.size(); ++m)
		{
			HPMDataHistoryEntry entry = sortedEntries[m];
			if (entry.m_FieldData == customColumnDataHash){
				HPMVariantData dataForColumn = sdkSession->DataHistoryGetEntryData(history, m);
				if ((mapTask.find(string(entry.m_Resource.begin(), entry.m_Resource.end())) == mapTask.end())){
					container::flat_map<unsigned long long, vector<WorkDoneUpdatedTask>> emptyTaskMap;
					mapTask[string(entry.m_Resource.begin(), entry.m_Resource.end())] = emptyTaskMap;

				}
				double workDone = sdkSession->VariantDecode_HPMFP32(dataForColumn);
				workDone = round(workDone * 100) / 100.00;
				container::flat_map<unsigned long long, vector<WorkDoneUpdatedTask>> dateMapForUser = mapTask[string(entry.m_Resource.begin(), entry.m_Resource.end())];
				gregorian::date dateForUpdate = DateTimeHelper::getDateFromUnixTimeStampMicroSeconds(entry.m_Time);
				string dateForUpdateString = DateTimeHelper::getDateStringFromUnixTimeStampMicroSeconds(entry.m_Time);
				unsigned long long uxTimestamp = DateTimeHelper::getUnixTimeFromString(dateForUpdateString);
				if (dateMapForUser.find(uxTimestamp) == dateMapForUser.end()){
					vector<WorkDoneUpdatedTask> emptyVectorUpdate;
					dateMapForUser[uxTimestamp] = emptyVectorUpdate;
				}
				vector<WorkDoneUpdatedTask> vectorUpdate = dateMapForUser[uxTimestamp];
				double increment = incrementHistory == 0 ? workDone : workDone - incrementHistory;
				increment = round(increment * 100) / 100.00;
				if ((entry.m_Time >= (DateTimeHelper::getUnixTimeFromString(fromDate) * 1000000ull)) && (entry.m_Time <= (DateTimeHelper::getUnixTimeFromString(toDate) * 1000000ull) + (86400ull * 1000000))){
					WorkDoneUpdatedTask task;
					task.m_taskId = clientId;
					task.m_taskDescription = taskDescription;
					task.m_workDoneIncrement = increment;
					task.m_workDone = workDone;
					task.m_projectId = projectId;
					task.m_projectName = string(prop.m_Name.begin(), prop.m_Name.end());
					task.m_time = entry.m_Time;
					task.m_dateUpdate = dateForUpdate;
					string taskHyperlinkFinal;
					taskHyperlinkFinal = HansoftLinkHelper::getHansoftTaskLink(taskId, ConfigHelper::getParamStringForSection(loginSection, hansoftAddress), ConfigHelper::getParamStringForSection(loginSection, hansoftDatabase));
					task.m_taskHyperlink = taskHyperlinkFinal;
					task.m_taskContainerDescription = taskContainerDescription;
					task.m_taskContainerHyperlink = taskContainerHyperlink;
					task.m_jobId = customColumnJobId;
					vectorUpdate.push_back(task);
					dateMapForUser[uxTimestamp] = vectorUpdate;
					mapTask[string(entry.m_Resource.begin(), entry.m_Resource.end())] = dateMapForUser;
				}
				incrementHistory = workDone;
			}

		}
	};

};

#ifdef _MSC_VER
int _tmain(int argc, _TCHAR* argv[])
#else
int main(int argc, const char * argv[])
#endif
{
	HansoftSDK_ResourceAllocation resourceAllocation;

	return resourceAllocation.Run();
}

max_stars_repo_name: Hansoft/resourceallocation

max_issues_repo_name: Hansoft/resourceallocation

max_forks_repo_name: Hansoft/resourceallocation


text:
#pragma once

/* inclusions =============================================================== */

#include <boost/pending/disjoint_sets.hpp>

#include "../libraries/cxxopts/include/cxxopts.hpp"

#include "logic.hh"

/* uses ===================================================================== */

using cxxopts::value;

/* consts =================================================================== */

const string CLUSTER_VAR_OPTION = "cv";
const string CLUSTERING_HEURISTIC_OPTION = "ch";

/* classes ================================================================== */

class JoinComponent { // for projected model counting
public:
  Int varOrderHeuristic = MIN_INT;
  string clusteringHeuristic;
  vector<JoinNode*> subtrees; // R
  Set<Int> keptVars; // F

  Set<Int> projectableVars; // Z
  vector<Set<Int>> projectableVarSets; // Z_1..Z_m is a partition of Z
  vector<vector<JoinNode*>> nodeClusters; // kappa_0..kappa_m: kappa_0 is nodeClusters.back()

  JoinNonterminal* getComponentRoot();
  Set<Int> getNodeVars(const vector<JoinNode*>& nodes) const;
  vector<Int> getRestrictedVarOrder() const;

  JoinComponent(
    Int varOrderHeuristic,
    string clusteringHeuristic,
    const vector<JoinNode*>& subtrees,
    const Set<Int>& keptVars
  );
};

class JoinRootBuilder {
public:
  Set<Int> disjunctiveVars;
  vector<Set<Int>> disjunctiveVarSets; // clause index |-> vars
  vector<vector<Int>> clauseGroups; // group |-> clause indices

  void printDisjunctiveVarSets() const;
  void printClauseGroups() const;

  void setDisjunctiveVarSets(); // also sets disjunctiveVars
  void setClauseGroups();

  JoinNonterminal* buildRoot(Int varOrderHeuristic, string clusteringHeuristic) const;

  JoinRootBuilder();
};

class Planner { // abstract
public:
  JoinNonterminal* joinRoot = nullptr;

  bool usingTreeClustering; // as opposed to list clustering
  Int clusterVarOrderHeuristic;

  void printJoinTree() const;
  void outputJoinTree();

  virtual void setJoinTree() = 0;
};

class BucketPlanner : public Planner { // bucket elimination
public:
  void setJoinTree() override;

  BucketPlanner(bool usingTreeClustering, Int clusterVarOrderHeuristic);
};

class BouquetPlanner : public Planner { // Bouquet's Method
public:
  void setJoinTree() override;

  BouquetPlanner(bool usingTreeClustering, Int clusterVarOrderHeuristic);
};

class OptionDict {
public:
  string cnfFilePath;
  Int clusterVarOrderHeuristic;
  string clusteringHeuristic;

  static string helpClusteringHeuristic();
  void runCommand() const;

  OptionDict(int argc, char** argv);
};

/* global functions ========================================================= */

int main(int argc, char** argv);

ext: hh

max_stars_repo_name: vardigroup/DPMC

max_issues_repo_name: vardigroup/DPMC

max_forks_repo_name: vardigroup/DPMC


text:
//  (C) Copyright 2005 Daniel Egloff, Eric Niebler
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/variance.hpp>

using namespace boost;
using namespace unit_test;
using namespace accumulators;

///////////////////////////////////////////////////////////////////////////////
// test_stat
//
void test_stat()
{
    // matlab
    // >> samples = [1:5];
    // >> mean(samples)
    // ans = 3
    // >> sum(samples .* samples) / length(samples)
    // ans = 11
    // >> sum(samples .* samples) / length(samples) - mean(samples)^2
    // ans = 2

    // lazy variance, now lazy with syntactic sugar, thanks to Eric
    accumulator_set<int, stats<tag::variance(lazy)> > acc1;

    acc1(1);
    acc1(2);
    acc1(3);
    acc1(4);
    acc1(5);

    BOOST_CHECK_EQUAL(5u, count(acc1));
    BOOST_CHECK_CLOSE(3., mean(acc1), 1e-5);
    BOOST_CHECK_CLOSE(11., moment<2>(acc1), 1e-5);
    BOOST_CHECK_CLOSE(2., variance(acc1), 1e-5);

    // immediate variance
    accumulator_set<int, stats<tag::variance> > acc2;

    acc2(1);
    acc2(2);
    acc2(3);
    acc2(4);
    acc2(5);

    BOOST_CHECK_EQUAL(5u, count(acc2));
    BOOST_CHECK_CLOSE(3., mean(acc2), 1e-5);
    BOOST_CHECK_CLOSE(2., variance(acc2), 1e-5);
}

///////////////////////////////////////////////////////////////////////////////
// init_unit_test_suite
//
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    test_suite *test = BOOST_TEST_SUITE("variance test");

    test->add(BOOST_TEST_CASE(&test_stat));

    return test;
}


text:
// Created by Lina Felsner on Thu Aug 18th 2016

#ifndef __model_fdct_calibration_correction_hxx
#define __model_fdct_calibration_correction_hxx

#include <Eigen/Core>
#include <Eigen/Geometry>
#include <LibProjectiveGeometry/ProjectionMatrix.h>
#include "Model.hxx"

#include <Utils/Projtable.hxx>

namespace Geometry {

	struct ModelFDCTCalibrationCorrection : public Model<7>
	{

		double pp_u;
		double pp_v;
		double spacing;
		double sid;
		double sdd;

		static std::vector<std::string> ParameterNames()
		{
			std::vector<std::string> names;
			// Set parameter names
			names.resize(size());
			names[0] = "Translation u";
			names[1] = "Translation v";
			names[2] = "Yaw";
			names[3] = "Pitch";
			names[4] = "Roll";
			names[5] = "Source Isocenter Distance";
			names[6] = "Source Detector Distance";
			return names;
		}

		enum ParameterSet { Identity, DetectorShifts, DetectorRigid2D, DetectorRotations, SDDandSID, All };
		static std::vector<std::string> ParameterSets()
		{
			std::vector<std::string> sets;
			sets[0] = "Identity";
			sets[1] = "DetectorShifts";
			sets[2] = "DetectorRigid2D";
			sets[4] = "DetectorRotations";
			sets[5] = "Source Detector and Iso-Center Distances";
			sets[6] = "All";
			return sets;
		}

		void computeMeanPPandSIDandSDD(const std::vector<Geometry::ProjectionMatrix> Ps)
		{
			std::vector<double> sids, sdds;
			ProjTable::ctCircularTrajectoryToParameters(Ps, spacing, 0x0, 0x0, 0x0, &sids, &sdds);

			// calculate mean
			double sumSID = std::accumulate(sids.begin(), sids.end(), 0.0);
			sid = sumSID / sids.size();
			double sumSDD = std::accumulate(sdds.begin(), sdds.end(), 0.0);
			sdd = sumSDD / sdds.size();

			std::cout << "Mean sid and sdd: " << sid << " " << sdd << std::endl;

			Geometry::RP2Point ppmean(0,0,0);
			for (int i = 0; i < (int)Ps.size(); i++)
			{
				Geometry::RP2Point pp=Ps[i].block<3, 3>(0, 0)*Ps[i].block<1, 3>(2, 0).transpose();
				pp = pp / pp(2);
				ppmean+=pp;
			}
			pp_u = ppmean[0] / ppmean(2);
			pp_v = ppmean[1] / ppmean(2);
			std::cout << "Mean principal point: " << pp_u << " " << pp_v << std::endl;
		}

		ModelFDCTCalibrationCorrection(int _nu, int _nv, double  _spacing, double sid, double sdd, ParameterSet active = Identity)
			: Model<7>(ParameterNames())
			, pp_u(0.5*_nu)
			, pp_v(0.5*_nv)
			, spacing(_spacing)
		{
			// Set parameter names
			names = ModelFDCTCalibrationCorrection::ParameterNames();
			// Set active parameters
			setActiveParameters(active);
		}

		ModelFDCTCalibrationCorrection(double  _spacing, const std::vector<Geometry::ProjectionMatrix>& Ps, ParameterSet active = Identity)
			: Model<7>(ParameterNames())
			, spacing(_spacing)
		{
			// Set parameter names
			names = ModelFDCTCalibrationCorrection::ParameterNames();
			// Set active parameters
			setActiveParameters(active);
			// Analyze geometry
			computeMeanPPandSIDandSDD(Ps);
		}

		/// Several common sets of active parameters
		void setActiveParameters(ParameterSet set)
		{
			for (int i = 0; i<size(); i++) active[i] = (set==All);

			switch (set)
			{
				default:
				case Identity:
				case All:
					break;
				case DetectorShifts:
					active[0] = active[1] = true;
				break;
				case SDDandSID:
					active[5] = active[6] = true;
				break;
				case DetectorRotations:
					active[2]=active[3]=active[4]=true;
				break;
				case DetectorRigid2D:
					active[0] =active[1] = active[4] = true;
				break;
			}
		}

		// Transform the Projection Matrix via: H*H_init*P*T
		void transform(std::vector<Geometry::ProjectionMatrix> &Ps, Eigen::Matrix3d H_init = Eigen::Matrix3d::Identity()) const
		{

			//TODO
			std::pair<Eigen::Matrix3d, Eigen::Matrix4d> HT = getTransforms(Ps);
			Eigen::Matrix3d H = HT.first;
			Eigen::Matrix4d T = HT.second;

			for (int i = 0; i < Ps.size(); i++)
			{
				Ps[i] = H*H_init*Ps[i]*T;
				Geometry::normalizeProjectionMatrix(Ps[i]);
			}
		}

		// Compose a homography from Parametrization
		std::pair<Eigen::Matrix3d, Eigen::Matrix4d> getTransforms(std::vector<Geometry::ProjectionMatrix> Ps) const
		{
			const double *x(param); //parameter vector

			Eigen::Matrix3d H = Eigen::Matrix3d::Identity();
			Eigen::Matrix4d T = Eigen::Matrix4d::Identity();

			Geometry::RP2Point ppmean(pp_u, pp_v, 1.0);

			double sid_scale = (sid + x[5]) / sid;
			double sdd_scale = (sdd + x[6]) / sdd;

//// H = Matrix 3x3
			Eigen::Matrix3d H_roll, H_shift, H_scale;
			H_roll = H_shift = H_scale = H;

			// using the principal point / center of the image
			auto Hpp = H, Hppinv = H;
			Hpp.block<3, 1>(0, 2) = ppmean;
			Hppinv(0, 2) = -ppmean[0];
			Hppinv(1, 2) = -ppmean[1];

			//Roll -> Rotation
			if (x[4] != 0)
			{
				H_roll <<
					+cos(x[4]), -sin(x[4]), 0,
					+sin(x[4]), +cos(x[4]), 0,
					0,			0,			1;
			}

			// Translation u and Yaw
			H_shift(0, 2) += x[0];
			H_shift(0, 2) += tan(x[2])*sdd;

			// Translation v and Pitch
			H_shift(1, 2) += x[1];
			H_shift(1, 2) += tan(x[3])*sdd;

			//SDD
			H_scale.block<2, 2>(0, 0) *= sdd_scale;

			H = H_shift * Hpp * H_roll * H_scale * Hppinv;

//// T = Matrix 4x4
			//SID
			T.block<3, 3>(0, 0) *= sid_scale;

//// HT
			std::pair<Eigen::Matrix3d, Eigen::Matrix4d> HT = { H, T };
			return HT;
		}

	};

}

#endif // __model_fdct_calibration_correction_hxx

ext: hxx

max_stars_repo_name: mareikethies/EpipolarConsistency

max_issues_repo_name: mareikethies/EpipolarConsistency

max_forks_repo_name: mareikethies/EpipolarConsistency


text:
// Copyright Eric Crampton, 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef meridian__network__socket__hpp
#define meridian__network__socket__hpp

#include "meridian/core/event_source.hpp"
#include "meridian/network/ip_address.hpp"
#include "meridian/network/socket_address.hpp"

#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <unistd.h>

namespace meridian {
namespace network {

class socket : public core::event_source {
public:
    typedef boost::posix_time::time_duration time_duration;
    static int const INVALID_SOCKET_FD = -1;

    void close();
    void close_noexcept() noexcept;

    void set_socket_option(int level, int option, int value);
    int get_int_socket_option(int level, int option) const;

    void set_socket_option(int level, int option, unsigned value);
    unsigned get_unsigned_socket_option(int level, int option) const;

    void set_socket_option(int level, int option, unsigned char value);
    unsigned char get_unsigned_char_socket_option(int level, int option) const;

    void set_socket_option(int level, int option, ip_address const & value);
    ip_address get_ip_address_socket_option(int level, int option) const;

    void set_socket_option(int level, int option, time_duration const & value);
    boost::posix_time::time_duration get_time_duration_socket_option(int level, int option) const;

    void set_raw_socket_option(int level, int option, void const * value, size_t length);
    void get_raw_socket_option(int level, int option, void * value, socklen_t & length) const;

    //! \brief Sets the socket's send buffer size (@c SO_SNDBUF).
    //!
    //! \param size - the size, in bytes; this is a signed integer to match the match the system call's use of @c int

    void set_send_buffer_size(int size);
    int get_send_buffer_size() const;
    void set_receive_buffer_size(int size);
    int get_receive_buffer_size() const;
    void set_send_timeout(time_duration const & timeout);
    time_duration get_send_timeout() const;

    void set_receive_timeout(time_duration const & timeout);
    time_duration get_receive_timeout() const;

    void set_linger(bool on, int seconds);
    std::pair<bool, int /* seconds */> get_linger() const;

    void set_no_delay(bool flag);
    bool get_no_delay() const;

    void set_keep_alive(bool flag);
    bool get_keep_alive() const;

    void set_reuse_address(bool flag);
    bool get_reuse_address() const;

    void set_reuse_port(bool flag);
    bool get_reuse_port() const;

    void set_oob_inline(bool flag);
    bool get_oob_inline() const;

    void set_broadcast(bool flag);
    bool get_broadcast() const;

    //! \brief Returns the number of bytes which can be read without blocking.
    //!
    //! \return number of bytes available; 0 if no data is available

    int available();

    socket_address address() const;
    socket_address peer_address() const;

protected:
    socket();
    socket(int fd);

    void init(socket_domain domain, int type, int proto = 0);

    //! \brief Receive bytes on this socket.
    ssize_t receive(void * buffer, size_t length, int flags);
    ssize_t send(void const * buffer, size_t length, int flags);
    ssize_t receive_from(void * buffer, size_t length, int flags, socket_address & address);
    ssize_t send_to(void const * buffer, size_t length, int flags, socket_address const & address);

    void bind(socket_address const & address);
    void listen(int backlog);
    void shutdown_receive();
    void shutdown_send();
    void shutdown();
    void shutdown(int how);

    inline int fd();

private:
    int fd_;
};

#include "meridian/network/socket.ipp"

} // namespace network
} // namespace meridian

#endif /* meridian__network__socket__hpp */

max_stars_repo_name: yggchan/meridian

max_issues_repo_name: yggchan/meridian

max_forks_repo_name: yggchan/meridian


text:
#include <eosio/chain/webassembly/eos-vm.hpp>
#include <eosio/chain/webassembly/interface.hpp>
#include <eosio/chain/apply_context.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/wasm_eosio_constraints.hpp>
//eos-vm includes
#include <eosio/vm/backend.hpp>
#include <eosio/chain/webassembly/preconditions.hpp>
#ifdef EOSIO_EOS_VM_OC_RUNTIME_ENABLED
#include <eosio/chain/webassembly/eos-vm-oc.hpp>
#endif
#include <boost/hana/string.hpp>
#include <boost/hana/equal.hpp>

namespace eosio { namespace chain { namespace webassembly { namespace eos_vm_runtime {

using namespace eosio::vm;

namespace wasm_constraints = eosio::chain::wasm_constraints;

namespace {

  struct checktime_watchdog {
     checktime_watchdog(transaction_checktime_timer& timer) : _timer(timer) {}
     template<typename F>
     struct guard {
        guard(transaction_checktime_timer& timer, F&& func)
           : _timer(timer), _func(static_cast<F&&>(func)) {
           _timer.set_expiration_callback(&callback, this);
           if(_timer.expired) {
              _func(); // it's harmless if _func is invoked twice
           }
        }
        ~guard() {
           _timer.set_expiration_callback(nullptr, nullptr);
        }
        static void callback(void* data) {
           guard* self = static_cast<guard*>(data);
           self->_func();
        }
        transaction_checktime_timer& _timer;
        F _func;
     };
     template<typename F>
     guard<F> scoped_run(F&& func) {
        return guard{_timer, static_cast<F&&>(func)};
     }
     transaction_checktime_timer& _timer;
  };
}

// Used on setcode.  Must not reject anything that WAVM accepts
// For the moment, this runs after WAVM validation, as I am not
// sure that eos-vm will replicate WAVM's parsing exactly.
struct setcode_options {
   static constexpr bool forbid_export_mutable_globals = false;
   static constexpr bool allow_code_after_function_end = true;
   static constexpr bool allow_u32_limits_flags = true;
   static constexpr bool allow_invalid_empty_local_set = true;
   static constexpr bool allow_zero_blocktype = true;
};

void validate(const bytes& code, const whitelisted_intrinsics_type& intrinsics) {
   wasm_code_ptr code_ptr((uint8_t*)code.data(), code.size());
   try {
      eos_vm_null_backend_t<setcode_options> bkend(code_ptr, code.size(), nullptr);
      // check import signatures
       eos_vm_host_functions_t::resolve(bkend.get_module());
      // check that the imports are all currently enabled
      const auto& imports = bkend.get_module().imports;
      for(std::uint32_t i = 0; i < imports.size(); ++i) {
         EOS_ASSERT(std::string_view((char*)imports[i].module_str.raw(), imports[i].module_str.size()) == "env" &&
                    is_intrinsic_whitelisted(intrinsics, std::string_view((char*)imports[i].field_str.raw(), imports[i].field_str.size())),
                    wasm_serialization_error, "${module}.${fn} unresolveable",
                    ("module", std::string((char*)imports[i].module_str.raw(), imports[i].module_str.size()))
                    ("fn", std::string((char*)imports[i].field_str.raw(), imports[i].field_str.size())));
      }
   } catch(vm::exception& e) {
      EOS_THROW(wasm_serialization_error, e.detail());
   }
}

void validate( const bytes& code, const wasm_config& cfg, const whitelisted_intrinsics_type& intrinsics ) {
   EOS_ASSERT(code.size() <= cfg.max_module_bytes, wasm_serialization_error, "Code too large");
   wasm_code_ptr code_ptr((uint8_t*)code.data(), code.size());
   try {
      eos_vm_null_backend_t<wasm_config> bkend(code_ptr, code.size(), nullptr, cfg);
      // check import signatures
      eos_vm_host_functions_t::resolve(bkend.get_module());
      // check that the imports are all currently enabled
      const auto& imports = bkend.get_module().imports;
      for(std::uint32_t i = 0; i < imports.size(); ++i) {
         EOS_ASSERT(std::string_view((char*)imports[i].module_str.raw(), imports[i].module_str.size()) == "env" &&
                    is_intrinsic_whitelisted(intrinsics, std::string_view((char*)imports[i].field_str.raw(), imports[i].field_str.size())),
                    wasm_serialization_error, "${module}.${fn} unresolveable",
                    ("module", std::string((char*)imports[i].module_str.raw(), imports[i].module_str.size()))
                    ("fn", std::string((char*)imports[i].field_str.raw(), imports[i].field_str.size())));
      }
      // check apply
      uint32_t apply_idx = bkend.get_module().get_exported_function("apply");
      EOS_ASSERT(apply_idx < std::numeric_limits<uint32_t>::max(), wasm_serialization_error, "apply not exported");
      const vm::func_type& apply_type = bkend.get_module().get_function_type(apply_idx);
      EOS_ASSERT((apply_type == vm::host_function{{vm::i64, vm::i64, vm::i64}, {}}), wasm_serialization_error, "apply has wrong type");
   } catch(vm::exception& e) {
      EOS_THROW(wasm_serialization_error, e.detail());
   }
}

// Be permissive on apply.
struct apply_options {
   std::uint32_t max_pages = wasm_constraints::maximum_linear_memory/wasm_constraints::wasm_page_size;
   std::uint32_t max_call_depth = wasm_constraints::maximum_call_depth+1;
   static constexpr bool forbid_export_mutable_globals = false;
   static constexpr bool allow_code_after_function_end = false;
   static constexpr bool allow_u32_limits_flags = true;
   static constexpr bool allow_invalid_empty_local_set = true;
   static constexpr bool allow_zero_blocktype = true;
};

template<typename Impl>
class eos_vm_instantiated_module : public wasm_instantiated_module_interface {
   using backend_t = eos_vm_backend_t<Impl>;
   public:

      eos_vm_instantiated_module(eos_vm_runtime<Impl>* runtime, std::unique_ptr<backend_t> mod) :
         _runtime(runtime),
         _instantiated_module(std::move(mod)) {}

      void apply(apply_context& context) override {
         _instantiated_module->set_wasm_allocator(&context.control.get_wasm_allocator());
         _runtime->_bkend = _instantiated_module.get();
         apply_options opts;
         if(context.control.is_builtin_activated(builtin_protocol_feature_t::configurable_wasm_limits)) {
            const wasm_config& config = context.control.get_global_properties().wasm_configuration;
            opts = {config.max_pages, config.max_call_depth};
         }
         auto fn = [&]() {
            eosio::chain::webassembly::interface iface(context);
            _runtime->_bkend->initialize(&iface, opts);
            _runtime->_bkend->call(
                iface, "env", "apply",
                context.get_receiver().to_uint64_t(),
                context.get_action().account.to_uint64_t(),
                context.get_action().name.to_uint64_t());
         };
         try {
            checktime_watchdog wd(context.trx_context.transaction_timer);
            _runtime->_bkend->timed_run(wd, fn);
         } catch(eosio::vm::timeout_exception&) {
            context.trx_context.checktime();
         } catch(eosio::vm::wasm_memory_exception& e) {
            FC_THROW_EXCEPTION(wasm_execution_error, "access violation");
         } catch(eosio::vm::exception& e) {
            FC_THROW_EXCEPTION(wasm_execution_error, "eos-vm system failure");
         }
         _runtime->_bkend = nullptr;
      }

   private:
      eos_vm_runtime<Impl>*            _runtime;
      std::unique_ptr<backend_t> _instantiated_module;
};

template<typename Impl>
eos_vm_runtime<Impl>::eos_vm_runtime() {}

template<typename Impl>
void eos_vm_runtime<Impl>::immediately_exit_currently_running_module() {
   throw wasm_exit{};
}

template<typename Impl>
bool eos_vm_runtime<Impl>::inject_module(IR::Module& module) {
   return false;
}

template<typename Impl>
std::unique_ptr<wasm_instantiated_module_interface> eos_vm_runtime<Impl>::instantiate_module(const char* code_bytes, size_t code_size, std::vector<uint8_t>,
                                                                                const digest_type&, const uint8_t&, const uint8_t&) {

   using backend_t = eos_vm_backend_t<Impl>;
   try {
      wasm_code_ptr code((uint8_t*)code_bytes, code_size);
      apply_options options = { .max_pages = 65536,
                                .max_call_depth = 0 };
      std::unique_ptr<backend_t> bkend = std::make_unique<backend_t>(code, code_size, nullptr, options);
      eos_vm_host_functions_t::resolve(bkend->get_module());
      return std::make_unique<eos_vm_instantiated_module<Impl>>(this, std::move(bkend));
   } catch(eosio::vm::exception& e) {
      FC_THROW_EXCEPTION(wasm_execution_error, "Error building eos-vm interp: ${e}", ("e", e.what()));
   }
}

template class eos_vm_runtime<eosio::vm::interpreter>;
template class eos_vm_runtime<eosio::vm::jit>;

}

template <auto HostFunction, typename... Preconditions>
struct host_function_registrator {
   template <typename Mod, typename Name>
   constexpr host_function_registrator(Mod mod_name, Name fn_name) {
      using rhf_t = eos_vm_host_functions_t;
      rhf_t::add<HostFunction, Preconditions...>(mod_name.c_str(), fn_name.c_str());
#ifdef EOSIO_EOS_VM_OC_RUNTIME_ENABLED
      constexpr bool is_injected = (Mod() == BOOST_HANA_STRING(EOSIO_INJECTED_MODULE_NAME));
      eosvmoc::register_eosvm_oc<HostFunction, is_injected, std::tuple<Preconditions...>>(
          mod_name + BOOST_HANA_STRING(".") + fn_name);
#endif
   }
};

#define REGISTER_INJECTED_HOST_FUNCTION(NAME, ...)                                                                     \
   static host_function_registrator<&interface::NAME, ##__VA_ARGS__> NAME##_registrator_impl() {                       \
      return {BOOST_HANA_STRING(EOSIO_INJECTED_MODULE_NAME), BOOST_HANA_STRING(#NAME)};                                \
   }                                                                                \
   inline static auto NAME##_registrator = NAME##_registrator_impl();

#define REGISTER_HOST_FUNCTION(NAME, ...)                                                                              \
   static host_function_registrator<&interface::NAME, core_precondition, context_aware_check, ##__VA_ARGS__>           \
       NAME##_registrator_impl() {                                                                                \
      return {BOOST_HANA_STRING("env"), BOOST_HANA_STRING(#NAME)};                                                     \
   }                                                                                \
   inline static auto NAME##_registrator = NAME##_registrator_impl();

#define REGISTER_CF_HOST_FUNCTION(NAME, ...)                                                                           \
   static host_function_registrator<&interface::NAME, core_precondition, ##__VA_ARGS__> NAME##_registrator_impl() {    \
      return {BOOST_HANA_STRING("env"), BOOST_HANA_STRING(#NAME)};                                                     \
   }                                                                                \
   inline static auto NAME##_registrator = NAME##_registrator_impl();

#define REGISTER_LEGACY_HOST_FUNCTION(NAME, ...)                                                                       \
   static host_function_registrator<&interface::NAME, legacy_static_check_wl_args, context_aware_check, ##__VA_ARGS__> \
       NAME##_registrator_impl() {                                                                                \
      return {BOOST_HANA_STRING("env"), BOOST_HANA_STRING(#NAME)};                                                     \
   }                                                                                \
   inline static auto NAME##_registrator = NAME##_registrator_impl();

#define REGISTER_LEGACY_CF_HOST_FUNCTION(NAME, ...)                                                                    \
   static host_function_registrator<&interface::NAME, legacy_static_check_wl_args, ##__VA_ARGS__>                      \
       NAME##_registrator_impl() {                                                                                \
      return {BOOST_HANA_STRING("env"), BOOST_HANA_STRING(#NAME)};                                                     \
   }                                                                                \
   inline static auto NAME##_registrator = NAME##_registrator_impl();

#define REGISTER_LEGACY_CF_ONLY_HOST_FUNCTION(NAME, ...)                                                               \
   static host_function_registrator<&interface::NAME, legacy_static_check_wl_args, context_free_check, ##__VA_ARGS__>  \
       NAME##_registrator_impl() {                                                                                \
      return {BOOST_HANA_STRING("env"), BOOST_HANA_STRING(#NAME)};                                                     \
   }                                                                                \
   inline static auto NAME##_registrator = NAME##_registrator_impl();

// context free api
REGISTER_LEGACY_CF_ONLY_HOST_FUNCTION(get_context_free_data)

// privileged api
REGISTER_HOST_FUNCTION(is_feature_active, privileged_check);
REGISTER_HOST_FUNCTION(activate_feature, privileged_check);
REGISTER_LEGACY_HOST_FUNCTION(preactivate_feature, privileged_check);
REGISTER_HOST_FUNCTION(set_resource_limits, privileged_check);
REGISTER_LEGACY_HOST_FUNCTION(get_resource_limits, privileged_check);
REGISTER_HOST_FUNCTION(set_resource_limit, privileged_check);
REGISTER_HOST_FUNCTION(get_resource_limit, privileged_check);
REGISTER_HOST_FUNCTION(get_wasm_parameters_packed, privileged_check);
REGISTER_HOST_FUNCTION(set_wasm_parameters_packed, privileged_check);
REGISTER_LEGACY_HOST_FUNCTION(set_proposed_producers, privileged_check);
REGISTER_LEGACY_HOST_FUNCTION(set_proposed_producers_ex, privileged_check);
REGISTER_LEGACY_HOST_FUNCTION(get_blockchain_parameters_packed, privileged_check);
REGISTER_LEGACY_HOST_FUNCTION(set_blockchain_parameters_packed, privileged_check);
REGISTER_HOST_FUNCTION(get_parameters_packed, privileged_check);
REGISTER_HOST_FUNCTION(set_parameters_packed, privileged_check);
REGISTER_HOST_FUNCTION(get_kv_parameters_packed, privileged_check);
REGISTER_HOST_FUNCTION(set_kv_parameters_packed, privileged_check);
REGISTER_HOST_FUNCTION(is_privileged, privileged_check);
REGISTER_HOST_FUNCTION(set_privileged, privileged_check);

// softfloat api
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_add);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_sub);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_div);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_mul);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_min);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_max);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_copysign);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_abs);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_neg);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_sqrt);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_ceil);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_floor);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_trunc);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_nearest);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_eq);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_ne);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_lt);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_le);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_gt);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_ge);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_add);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_sub);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_div);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_mul);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_min);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_max);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_copysign);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_abs);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_neg);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_sqrt);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_ceil);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_floor);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_trunc);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_nearest);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_eq);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_ne);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_lt);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_le);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_gt);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_ge);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_promote);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_demote);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_trunc_i32s);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_trunc_i32s);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_trunc_i32u);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_trunc_i32u);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_trunc_i64s);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_trunc_i64s);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f32_trunc_i64u);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_f64_trunc_i64u);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_i32_to_f32);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_i64_to_f32);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_ui32_to_f32);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_ui64_to_f32);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_i32_to_f64);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_i64_to_f64);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_ui32_to_f64);
REGISTER_INJECTED_HOST_FUNCTION(_eosio_ui64_to_f64);

// producer api
REGISTER_LEGACY_HOST_FUNCTION(get_active_producers);

// crypto api
REGISTER_LEGACY_CF_HOST_FUNCTION(assert_recover_key);
REGISTER_LEGACY_CF_HOST_FUNCTION(recover_key);
REGISTER_LEGACY_CF_HOST_FUNCTION(assert_sha256);
REGISTER_LEGACY_CF_HOST_FUNCTION(assert_sha1);
REGISTER_LEGACY_CF_HOST_FUNCTION(assert_sha512);
REGISTER_LEGACY_CF_HOST_FUNCTION(assert_ripemd160);
REGISTER_LEGACY_CF_HOST_FUNCTION(sha256);
REGISTER_LEGACY_CF_HOST_FUNCTION(sha1);
REGISTER_LEGACY_CF_HOST_FUNCTION(sha512);
REGISTER_LEGACY_CF_HOST_FUNCTION(ripemd160);

// permission api
REGISTER_LEGACY_HOST_FUNCTION(check_transaction_authorization);
REGISTER_LEGACY_HOST_FUNCTION(check_permission_authorization);
REGISTER_HOST_FUNCTION(get_permission_last_used);
REGISTER_HOST_FUNCTION(get_account_creation_time);

// authorization api
REGISTER_HOST_FUNCTION(require_auth);
REGISTER_HOST_FUNCTION(require_auth2);
REGISTER_HOST_FUNCTION(has_auth);
REGISTER_HOST_FUNCTION(require_recipient);
REGISTER_HOST_FUNCTION(is_account);

// system api
REGISTER_HOST_FUNCTION(current_time);
REGISTER_HOST_FUNCTION(publication_time);
REGISTER_LEGACY_HOST_FUNCTION(is_feature_activated);
REGISTER_HOST_FUNCTION(get_sender);

// context-free system api
REGISTER_CF_HOST_FUNCTION(abort)
REGISTER_LEGACY_CF_HOST_FUNCTION(eosio_assert)
REGISTER_LEGACY_CF_HOST_FUNCTION(eosio_assert_message)
REGISTER_CF_HOST_FUNCTION(eosio_assert_code)
REGISTER_CF_HOST_FUNCTION(eosio_exit)

// action api
REGISTER_LEGACY_CF_HOST_FUNCTION(read_action_data);
REGISTER_CF_HOST_FUNCTION(action_data_size);
REGISTER_CF_HOST_FUNCTION(current_receiver);
REGISTER_HOST_FUNCTION(set_action_return_value);

// console api
REGISTER_LEGACY_CF_HOST_FUNCTION(prints);
REGISTER_LEGACY_CF_HOST_FUNCTION(prints_l);
REGISTER_CF_HOST_FUNCTION(printi);
REGISTER_CF_HOST_FUNCTION(printui);
REGISTER_LEGACY_CF_HOST_FUNCTION(printi128);
REGISTER_LEGACY_CF_HOST_FUNCTION(printui128);
REGISTER_CF_HOST_FUNCTION(printsf);
REGISTER_CF_HOST_FUNCTION(printdf);
REGISTER_LEGACY_CF_HOST_FUNCTION(printqf);
REGISTER_CF_HOST_FUNCTION(printn);
REGISTER_LEGACY_CF_HOST_FUNCTION(printhex);

// database api
// primary index api
REGISTER_LEGACY_HOST_FUNCTION(db_store_i64);
REGISTER_LEGACY_HOST_FUNCTION(db_update_i64);
REGISTER_HOST_FUNCTION(db_remove_i64);
REGISTER_LEGACY_HOST_FUNCTION(db_get_i64);
REGISTER_LEGACY_HOST_FUNCTION(db_next_i64);
REGISTER_LEGACY_HOST_FUNCTION(db_previous_i64);
REGISTER_HOST_FUNCTION(db_find_i64);
REGISTER_HOST_FUNCTION(db_lowerbound_i64);
REGISTER_HOST_FUNCTION(db_upperbound_i64);
REGISTER_HOST_FUNCTION(db_end_i64);

// uint64_t secondary index api
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_store);
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_update);
REGISTER_HOST_FUNCTION(db_idx64_remove);
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_find_secondary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_find_primary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_lowerbound);
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_upperbound);
REGISTER_HOST_FUNCTION(db_idx64_end);
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_next);
REGISTER_LEGACY_HOST_FUNCTION(db_idx64_previous);

// uint128_t secondary index api
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_store);
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_update);
REGISTER_HOST_FUNCTION(db_idx128_remove);
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_find_secondary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_find_primary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_lowerbound);
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_upperbound);
REGISTER_HOST_FUNCTION(db_idx128_end);
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_next);
REGISTER_LEGACY_HOST_FUNCTION(db_idx128_previous);

// 256-bit secondary index api
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_store);
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_update);
REGISTER_HOST_FUNCTION(db_idx256_remove);
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_find_secondary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_find_primary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_lowerbound);
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_upperbound);
REGISTER_HOST_FUNCTION(db_idx256_end);
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_next);
REGISTER_LEGACY_HOST_FUNCTION(db_idx256_previous);

// double secondary index api
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_store, is_nan_check);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_update, is_nan_check);
REGISTER_HOST_FUNCTION(db_idx_double_remove);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_find_secondary, is_nan_check);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_find_primary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_lowerbound, is_nan_check);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_upperbound, is_nan_check);
REGISTER_HOST_FUNCTION(db_idx_double_end);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_next);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_double_previous);

// long double secondary index api
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_store, is_nan_check);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_update, is_nan_check);
REGISTER_HOST_FUNCTION(db_idx_long_double_remove);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_find_secondary, is_nan_check);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_find_primary);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_lowerbound, is_nan_check);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_upperbound, is_nan_check);
REGISTER_HOST_FUNCTION(db_idx_long_double_end);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_next);
REGISTER_LEGACY_HOST_FUNCTION(db_idx_long_double_previous);

// kv database api
REGISTER_HOST_FUNCTION(kv_erase);
REGISTER_HOST_FUNCTION(kv_set);
REGISTER_HOST_FUNCTION(kv_get);
REGISTER_HOST_FUNCTION(kv_get_data);
REGISTER_HOST_FUNCTION(kv_it_create);
REGISTER_HOST_FUNCTION(kv_it_destroy);
REGISTER_HOST_FUNCTION(kv_it_status);
REGISTER_HOST_FUNCTION(kv_it_compare);
REGISTER_HOST_FUNCTION(kv_it_key_compare);
REGISTER_HOST_FUNCTION(kv_it_move_to_end);
REGISTER_HOST_FUNCTION(kv_it_next);
REGISTER_HOST_FUNCTION(kv_it_prev);
REGISTER_HOST_FUNCTION(kv_it_lower_bound);
REGISTER_HOST_FUNCTION(kv_it_key);
REGISTER_HOST_FUNCTION(kv_it_value);

// memory api
REGISTER_LEGACY_CF_HOST_FUNCTION(memcpy);
REGISTER_LEGACY_CF_HOST_FUNCTION(memmove);
REGISTER_LEGACY_CF_HOST_FUNCTION(memcmp);
REGISTER_LEGACY_CF_HOST_FUNCTION(memset);

// transaction api
REGISTER_LEGACY_HOST_FUNCTION(send_inline);
REGISTER_LEGACY_HOST_FUNCTION(send_context_free_inline);
REGISTER_LEGACY_HOST_FUNCTION(send_deferred);
REGISTER_LEGACY_HOST_FUNCTION(cancel_deferred);

// context-free transaction api
REGISTER_LEGACY_CF_HOST_FUNCTION(read_transaction);
REGISTER_CF_HOST_FUNCTION(transaction_size);
REGISTER_CF_HOST_FUNCTION(expiration);
REGISTER_CF_HOST_FUNCTION(tapos_block_num);
REGISTER_CF_HOST_FUNCTION(tapos_block_prefix);
REGISTER_LEGACY_CF_HOST_FUNCTION(get_action);

// InfraBlockchain standard token api
REGISTER_HOST_FUNCTION(get_token_symbol);
REGISTER_HOST_FUNCTION(get_token_total_supply);
REGISTER_HOST_FUNCTION(get_token_balance);
REGISTER_HOST_FUNCTION(issue_token);
REGISTER_HOST_FUNCTION(transfer_token);
REGISTER_HOST_FUNCTION(redeem_token);

// InfraBlockchain system token api
REGISTER_HOST_FUNCTION(get_system_token_count);
REGISTER_LEGACY_HOST_FUNCTION(get_system_token_list_packed);
REGISTER_LEGACY_HOST_FUNCTION(set_system_token_list_packed, privileged_check);

// InfraBlockchain transaction fee management api
REGISTER_HOST_FUNCTION(set_trx_fee_for_action, privileged_check);
REGISTER_HOST_FUNCTION(unset_trx_fee_for_action, privileged_check);
REGISTER_LEGACY_HOST_FUNCTION(get_trx_fee_for_action_packed);
REGISTER_HOST_FUNCTION(trx_fee_payer);

// InfraBlockchain proof-of-transaction api
REGISTER_LEGACY_HOST_FUNCTION(get_top_transaction_vote_receivers_packed);
REGISTER_HOST_FUNCTION(get_total_weighted_transaction_votes);

// compiler builtins api
REGISTER_LEGACY_CF_HOST_FUNCTION(__ashlti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__ashrti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__lshlti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__lshrti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__divti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__udivti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__multi3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__modti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__umodti3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__addtf3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__subtf3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__multf3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__divtf3);
REGISTER_LEGACY_CF_HOST_FUNCTION(__negtf2);
REGISTER_LEGACY_CF_HOST_FUNCTION(__extendsftf2);
REGISTER_LEGACY_CF_HOST_FUNCTION(__extenddftf2);
REGISTER_CF_HOST_FUNCTION(__trunctfdf2);
REGISTER_CF_HOST_FUNCTION(__trunctfsf2);
REGISTER_CF_HOST_FUNCTION(__fixtfsi);
REGISTER_CF_HOST_FUNCTION(__fixtfdi);
REGISTER_LEGACY_CF_HOST_FUNCTION(__fixtfti);
REGISTER_CF_HOST_FUNCTION(__fixunstfsi);
REGISTER_CF_HOST_FUNCTION(__fixunstfdi);
REGISTER_LEGACY_CF_HOST_FUNCTION(__fixunstfti);
REGISTER_LEGACY_CF_HOST_FUNCTION(__fixsfti);
REGISTER_LEGACY_CF_HOST_FUNCTION(__fixdfti);
REGISTER_LEGACY_CF_HOST_FUNCTION(__fixunssfti);
REGISTER_LEGACY_CF_HOST_FUNCTION(__fixunsdfti);
REGISTER_CF_HOST_FUNCTION(__floatsidf);
REGISTER_LEGACY_CF_HOST_FUNCTION(__floatsitf);
REGISTER_LEGACY_CF_HOST_FUNCTION(__floatditf);
REGISTER_LEGACY_CF_HOST_FUNCTION(__floatunsitf);
REGISTER_LEGACY_CF_HOST_FUNCTION(__floatunditf);
REGISTER_CF_HOST_FUNCTION(__floattidf);
REGISTER_CF_HOST_FUNCTION(__floatuntidf);
REGISTER_CF_HOST_FUNCTION(__cmptf2);
REGISTER_CF_HOST_FUNCTION(__eqtf2);
REGISTER_CF_HOST_FUNCTION(__netf2);
REGISTER_CF_HOST_FUNCTION(__getf2);
REGISTER_CF_HOST_FUNCTION(__gttf2);
REGISTER_CF_HOST_FUNCTION(__letf2);
REGISTER_CF_HOST_FUNCTION(__lttf2);
REGISTER_CF_HOST_FUNCTION(__unordtf2);

} // namespace webassembly
} // namespace chain
} // namespace eosio

max_stars_repo_name: YosemiteLabs/infrablockchain

max_issues_repo_name: YosemiteLabs/infrablockchain

max_forks_repo_name: YosemiteLabs/infrablockchain


text:
#pragma once

#include <boost/bimap.hpp>
#include <vector>

namespace opossum {

/*
 * boost::bimap does not support initializer_lists.
 * Instead we use this helper function to have an initializer_list-friendly interface.
 */
template <typename L, typename R>
boost::bimap<L, R> make_bimap(std::initializer_list<typename boost::bimap<L, R>::value_type> list) {
  return boost::bimap<L, R>(list.begin(), list.end());
}

}  // namespace opossum

max_stars_repo_name: nilsthamm/hyrise

max_issues_repo_name: nilsthamm/hyrise

max_forks_repo_name: nilsthamm/hyrise