text:
#include <boost/test/unit_test.hpp>
#include "client/AsyncClient.hpp"
#include "../TestSocket.hpp"
#include "../TestSocketFactory.hpp"
#include "net/Net.hpp"
#include <chrono>
using namespace http;

BOOST_AUTO_TEST_SUITE(TestClient)

BOOST_AUTO_TEST_CASE(construct)
{
    TestSocketFactory socket_factory;
    socket_factory.recv_buffer =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/plain\r\n"
        "Content-Length: 10\r\n"
        "\r\n"
        "0123456789";

    AsyncClientParams params;
    params.host = "localhost";
    params.port = 80;
    params.tls = false;
    params.max_connections = 5;
    params.socket_factory = &socket_factory;

    AsyncClient client(params);

    client.exit();
    client.start();
    client.exit();
}

BOOST_AUTO_TEST_CASE(single)
{
    TestSocketFactory socket_factory;
    socket_factory.recv_buffer =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/plain\r\n"
        "Content-Length: 10\r\n"
        "\r\n"
        "0123456789";

    AsyncClientParams params;
    params.host = "localhost";
    params.port = 80;
    params.tls = false;
    params.max_connections = 5;
    params.socket_factory = &socket_factory;

    AsyncClient client(params);

    AsyncRequest req;
    req.method = GET;
    req.raw_url = "/index.html";

    auto response = client.queue(&req).get();
    BOOST_CHECK_EQUAL(200, response->status.code);
}

BOOST_AUTO_TEST_CASE(sequential)
{
    TestSocketFactory socket_factory;
    socket_factory.recv_buffer =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/plain\r\n"
        "Content-Length: 10\r\n"
        "\r\n"
        "0123456789";

    AsyncClientParams params;
    params.host = "localhost";
    params.port = 80;
    params.tls = false;
    params.max_connections = 5;
    params.socket_factory = &socket_factory;

    AsyncClient client(params);

    AsyncRequest req;
    req.method = GET;
    req.raw_url = "/index.html";

    auto response = client.queue(&req).get();
    BOOST_CHECK_EQUAL(200, response->status.code);

    req.reset();
    response = client.queue(&req).get();
    BOOST_CHECK_EQUAL(200, response->status.code);

    req.reset();
    response = client.queue(&req).get();
    BOOST_CHECK_EQUAL(200, response->status.code);
}

BOOST_AUTO_TEST_CASE(callback)
{
    std::atomic<bool> done(false);

    TestSocketFactory socket_factory;
    socket_factory.recv_buffer =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/plain\r\n"
        "Content-Length: 10\r\n"
        "\r\n"
        "0123456789";

    AsyncClientParams params;
    params.host = "localhost";
    params.port = 80;
    params.tls = false;
    params.max_connections = 5;
    params.socket_factory = &socket_factory;

    AsyncClient client(params);

    AsyncRequest req;
    req.method = GET;
    req.raw_url = "/index.html";
    req.on_completion = [&done](AsyncRequest *, Response &) -> void
    {
        done = true;
    };

    client.queue(&req);
    auto response = req.wait();
    BOOST_CHECK_EQUAL(200, response->status.code);
    BOOST_CHECK(done);
}

BOOST_AUTO_TEST_CASE(async_error)
{
    std::atomic<bool> done(false);

    class Factory : public SocketFactory
    {
    public:
        virtual std::unique_ptr<http::Socket> connect(const std::string &host, uint16_t port, bool)override
        {
            throw ConnectionError(host, port);
        }
    };
    Factory socket_factory;

    AsyncClientParams params;
    params.host = "localhost";
    params.port = 80;
    params.tls = false;
    params.max_connections = 5;
    params.socket_factory = &socket_factory;

    AsyncClient client(params);

    AsyncRequest req;
    req.method = GET;
    req.raw_url = "/index.html";
    req.on_exception = [&done](AsyncRequest*) -> void
    {
        try
        {
            throw;
        }
        catch (const ConnectionError &)
        {
            done = true;
        }
    };

    client.queue(&req);
    BOOST_CHECK_THROW(req.wait(), ConnectionError);
    BOOST_CHECK(done);
}

BOOST_AUTO_TEST_CASE(parallel)
{
    class Factory : public TestSocketFactory
    {
    public:
        using TestSocketFactory::TestSocketFactory;
        std::mutex go;
        virtual std::unique_ptr<http::Socket> connect(const std::string &host, uint16_t port, bool tls)override
        {
            ++connect_count;
            std::unique_lock<std::mutex> lock(go);
            auto sock = std::unique_ptr<TestSocket>(new TestSocket());
            sock->host = host;
            sock->port = port;
            sock->tls = tls;
            sock->recv_buffer = recv_buffer;
            last = sock.get();
            return std::move(sock);
        }
    };
    Factory socket_factory;
    socket_factory.recv_buffer =
        "HTTP/1.1 200 OK\r\n"
        "Content-Type: text/plain\r\n"
        "Content-Length: 10\r\n"
        "Connection: keep-alive\r\n"
        "\r\n"
        "0123456789";

    std::unique_lock<std::mutex> lock(socket_factory.go);

    AsyncClientParams params;
    params.host = "localhost";
    params.port = 80;
    params.tls = false;
    params.max_connections = 4;
    params.socket_factory = &socket_factory;

    AsyncClient client(params);

    auto req = []() -> AsyncRequest
    {
        AsyncRequest req;
        req.method = GET;
        req.raw_url = "/index.html";
        return req;
    };

    auto a = req();
    auto b = req();
    auto c = req();
    auto d = req();
    auto e = req();
    auto f = req();

    client.queue(&a);
    client.queue(&b);
    client.queue(&c);
    client.queue(&d);
    client.queue(&e);
    client.queue(&f);

    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    BOOST_CHECK_EQUAL(4U, socket_factory.connect_count.load());
    lock.unlock();

    BOOST_CHECK_NO_THROW(a.wait());
    BOOST_CHECK_NO_THROW(b.wait());
    BOOST_CHECK_NO_THROW(c.wait());
    BOOST_CHECK_NO_THROW(d.wait());
    BOOST_CHECK_NO_THROW(e.wait());
    BOOST_CHECK_NO_THROW(f.wait());

    BOOST_CHECK_EQUAL(4U, socket_factory.connect_count.load());
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: wnewbery/cpphttp

max_issues_repo_name: wnewbery/cpphttp

max_forks_repo_name: wnewbery/cpphttp


text:
#pragma once

#include <iomanip>
#include <vector>
#include <cmath>

#include <Eigen/Core>
#include <opencv2/core/core.hpp>

#include "Bounds.hh"
#include "../Math/math.hh"
#include "../util/assert.hh"
#include "../util/Maybe.hh"

#include "LineSegment/linesegment.hh"

namespace bold
{
  /**
   * Line, specified using radius/distance-from-origin parameters (normal form.)
   *
   * Equations defining the line are:
   *
   *   r = x*sin(theta) + y*cos(theta)
   *
   *   x = (r - y*cos(theta))/sin(theta)
   *   y = (r - x*sin(theta))/cos(theta)
   */
  class Line
  {
  // TODO rename to NormalLine2d?
  public:
    Line(double const radius, double const theta, const ushort votes = 0)
    : d_radius(radius),
      d_theta(theta)
    {
      ASSERT(theta >= 0);
      ASSERT(theta <= M_PI);
      ASSERT(!std::isnan(theta) && !std::isnan(radius) && !std::isinf(theta) && !std::isinf(radius));
    };

    double radius() const { return d_radius; }
    double theta() const { return d_theta; }
    double thetaDegrees() const { return Math::radToDeg(d_theta); }

    double gradient() const { return tanh(d_theta); }
    double yIntersection() const { return d_radius / cos(d_theta); }

    void draw(cv::Mat& mat, cv::Scalar const& color) const
    {
      Maybe<LineSegment<int,2>> line(intersectWith(Bounds2i(Eigen::Vector2i::Zero(), Eigen::Vector2i(mat.cols, mat.rows))));

      if (line.hasValue())
      {
        Eigen::Vector2i const& p1 = line->p1();
        Eigen::Vector2i const& p2 = line->p2();
        cv::line(mat, cv::Point(p1.x(), p1.y()), cv::Point(p2.x(), p2.y()), color);
      }
    }

    template<typename T>
    Maybe<LineSegment<T,2>> intersectWith(Bounds<T,2> bounds) const
    {
      ASSERT(d_theta >= 0 && d_theta <= M_PI);

      double tsin = sin(d_theta);
      double tcos = cos(d_theta);

      int minX = bounds.min().x();
      int minY = bounds.min().y();
      int maxX = bounds.max().x();
      int maxY = bounds.max().y();

      // r = x*sin(theta) + y*cos(theta)
      // x = (r - y*cos(theta))/sin(theta)
      // y = (r - x*sin(theta))/cos(theta)

      double xWhenYMin = (d_radius-minY*tcos)/tsin;
      double yWhenXMin = (d_radius-minX*tsin)/tcos;

      double xWhenYMax = (d_radius-maxY*tcos)/tsin;
      double yWhenXMax = (d_radius-maxX*tsin)/tcos;

      std::vector<Eigen::Matrix<T,2,1>> edgeContactPoints;

      if (xWhenYMin >= minX && xWhenYMin <= maxX)
        edgeContactPoints.emplace_back(xWhenYMin, minY);

      if (xWhenYMax >= minX && xWhenYMax <= maxX)
        edgeContactPoints.emplace_back(xWhenYMax, maxY);

      if (yWhenXMin >= minY && yWhenXMin <= maxY)
        edgeContactPoints.emplace_back(minX, yWhenXMin);

      if (yWhenXMax >= minY && yWhenXMax <= maxY)
        edgeContactPoints.emplace_back(maxX, yWhenXMax);

      if (edgeContactPoints.size() == 0)
        return Maybe<LineSegment<T,2>>::empty();

      ASSERT(edgeContactPoints.size() == 2);

      if (edgeContactPoints.size() != 2)
        return Maybe<LineSegment<T,2>>::empty();

      return Maybe<LineSegment<T,2>>(LineSegment<T,2>(edgeContactPoints[0], edgeContactPoints[1]));
    }

    bool operator==(Line const& other) const
    {
      const double epsilon = 0.0000001;
      return fabs(d_radius - other.d_radius) < epsilon
          && fabs(d_theta - other.d_theta) < epsilon;
    }

    template<typename T>
    static Line fromSegment(LineSegment2<T> const& segment)
    {
      double theta = atan2(segment.p2().y() - segment.p1().y(),
                           segment.p1().x() - segment.p2().x());

      double radius = segment.p1().x() * std::sin(theta) +
        segment.p1().y() * std::cos(theta);

      while (theta < 0)
      {
        theta += M_PI;
        radius = -radius;
      }

      while (theta > M_PI)
      {
        theta -= M_PI;
        radius = -radius;
      }

      return Line(radius, theta);
    }

    friend std::ostream& operator<<(std::ostream& stream, Line const& line)
    {
      return stream << std::setprecision(13) << "Line (radius=" << line.radius() << " theta=" << line.theta() << ")";
    }

  private:
    double d_radius;
    double d_theta;
  };
}

ext: hh

max_stars_repo_name: drewnoakes/bold-humanoid

max_issues_repo_name: drewnoakes/bold-humanoid

max_forks_repo_name: drewnoakes/bold-humanoid


text:
//          Copyright Oliver Kowalke 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)

#include <cstdlib>
#include <exception>
#include <functional>
#include <iostream>
#include <memory>
#include <sstream>

#include <boost/context/execution_context.hpp>

/*
 * grammar:
 *   P ---> E '\0'
 *   E ---> T {('+'|'-') T}
 *   T ---> S {('*'|'/') S}
 *   S ---> digit | '(' E ')'
 */
class Parser{
   char next;
   std::istream& is;
   std::function<void(char)> cb;

   char pull(){
        return std::char_traits<char>::to_char_type(is.get());
   }

   void scan(){
       do{
           next=pull();
       }
       while(isspace(next));
   }

public:
   Parser(std::istream& is_,std::function<void(char)> cb_) :
      next(), is(is_), cb(cb_)
    {}

   void run() {
      scan();
      E();
   }

private:
   void E(){
      T();
      while (next=='+'||next=='-'){
         cb(next);
         scan();
         T();
      }
   }

   void T(){
      S();
      while (next=='*'||next=='/'){
         cb(next);
         scan();
         S();
      }
   }

   void S(){
      if (isdigit(next)){
         cb(next);
         scan();
      }
      else if(next=='('){
         cb(next);
         scan();
         E();
         if (next==')'){
             cb(next);
             scan();
         }else{
             throw std::runtime_error("parsing failed");
         }
      }
      else{
         throw std::runtime_error("parsing failed");
      }
   }
};

int main() {
    try {
        std::istringstream is("1+1");
        bool done=false;
        std::exception_ptr except;

        // create handle to main execution context
        auto sink(boost::context::execution_context::current());
        // execute parser in new execution context
        boost::context::execution_context source(
                [&sink,&is,&done,&except](void*){
                // create parser with callback function
                Parser p(is,
                         [&sink](char ch){
                                // resume main execution context
                                sink(&ch);
                        });
                    try {
                        // start recursive parsing
                        p.run();
                    } catch (...) {
                        // store other exceptions in exception-pointer
                        except = std::current_exception();
                    }
                    // set termination flag
                    done=true;
                    // resume main execution context
                    sink();
                });

        // user-code pulls parsed data from parser
        // invert control flow
        void* vp = source();
        if (except) {
            std::rethrow_exception(except);
        }
        while( ! done) {
            printf("Parsed: %c\n",* static_cast<char*>(vp));
            vp = source();
            if (except) {
                std::rethrow_exception(except);
            }
        }
        std::cout << "main: done" << std::endl;
        return EXIT_SUCCESS;
    } catch ( std::exception const& e) {
        std::cerr << "exception: " << e.what() << std::endl;
    }
    return EXIT_FAILURE;
}

ext: cpp

max_stars_repo_name: ZCube/boost-cmake

max_issues_repo_name: ZCube/boost-cmake

max_forks_repo_name: ZCube/boost-cmake


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

#include "EntityManager.hpp"

#include "Overlay.hpp"
#include "Utils.hpp"
#include "VariantVisitors.hpp"

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/range/iterator_range.hpp>
#include <nlohmann/json.hpp>
#include <sdbusplus/asio/connection.hpp>
#include <sdbusplus/asio/object_server.hpp>

#include <charconv>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <map>
#include <regex>
#include <variant>
constexpr const char* hostConfigurationDirectory = SYSCONF_DIR "configurations";
constexpr const char* configurationDirectory = PACKAGE_DIR "configurations";
constexpr const char* schemaDirectory = PACKAGE_DIR "configurations/schemas";
constexpr const char* tempConfigDir = "/tmp/configuration/";
constexpr const char* lastConfiguration = "/tmp/configuration/last.json";
constexpr const char* currentConfiguration = "/var/configuration/system.json";
constexpr const char* globalSchema = "global.json";
constexpr const bool debug = false;

const boost::container::flat_map<const char*, probe_type_codes, CmpStr>
    probeTypes{{{"FALSE", probe_type_codes::FALSE_T},
                {"TRUE", probe_type_codes::TRUE_T},
                {"AND", probe_type_codes::AND},
                {"OR", probe_type_codes::OR},
                {"FOUND", probe_type_codes::FOUND},
                {"MATCH_ONE", probe_type_codes::MATCH_ONE}}};

static constexpr std::array<const char*, 6> settableInterfaces = {
    "FanProfile", "Pid", "Pid.Zone", "Stepwise", "Thresholds", "Polling"};
using JsonVariantType =
    std::variant<std::vector<std::string>, std::vector<double>, std::string,
                 int64_t, uint64_t, double, int32_t, uint32_t, int16_t,
                 uint16_t, uint8_t, bool>;

using ManagedObjectType = boost::container::flat_map<
    sdbusplus::message::object_path,
    boost::container::flat_map<
        std::string,
        boost::container::flat_map<std::string, BasicVariantType>>>;

// store reference to all interfaces so we can destroy them later
boost::container::flat_map<
    std::string, std::vector<std::weak_ptr<sdbusplus::asio::dbus_interface>>>
    inventory;

// todo: pass this through nicer
std::shared_ptr<sdbusplus::asio::connection> systemBus;
nlohmann::json lastJson;

boost::asio::io_context io;

const std::regex illegalDbusPathRegex("[^A-Za-z0-9_.]");
const std::regex illegalDbusMemberRegex("[^A-Za-z0-9_]");

FoundProbeTypeT findProbeType(const std::string& probe)
{
    boost::container::flat_map<const char*, probe_type_codes,
                               CmpStr>::const_iterator probeType;
    for (probeType = probeTypes.begin(); probeType != probeTypes.end();
         ++probeType)
    {
        if (probe.find(probeType->first) != std::string::npos)
        {
            return probeType;
        }
    }

    return std::nullopt;
}

static std::shared_ptr<sdbusplus::asio::dbus_interface>
    createInterface(sdbusplus::asio::object_server& objServer,
                    const std::string& path, const std::string& interface,
                    const std::string& parent, bool checkNull = false)
{
    // on first add we have no reason to check for null before add, as there
    // won't be any. For dynamically added interfaces, we check for null so that
    // a constant delete/add will not create a memory leak

    auto ptr = objServer.add_interface(path, interface);
    auto& dataVector = inventory[parent];
    if (checkNull)
    {
        auto it = std::find_if(dataVector.begin(), dataVector.end(),
                               [](const auto& p) { return p.expired(); });
        if (it != dataVector.end())
        {
            *it = ptr;
            return ptr;
        }
    }
    dataVector.emplace_back(ptr);
    return ptr;
}

// writes output files to persist data
bool writeJsonFiles(const nlohmann::json& systemConfiguration)
{
    std::filesystem::create_directory(configurationOutDir);
    std::ofstream output(currentConfiguration);
    if (!output.good())
    {
        return false;
    }
    output << systemConfiguration.dump(4);
    output.close();
    return true;
}

template <typename JsonType>
bool setJsonFromPointer(const std::string& ptrStr, const JsonType& value,
                        nlohmann::json& systemConfiguration)
{
    try
    {
        nlohmann::json::json_pointer ptr(ptrStr);
        nlohmann::json& ref = systemConfiguration[ptr];
        ref = value;
        return true;
    }
    catch (const std::out_of_range&)
    {
        return false;
    }
}

// template function to add array as dbus property
template <typename PropertyType>
void addArrayToDbus(const std::string& name, const nlohmann::json& array,
                    sdbusplus::asio::dbus_interface* iface,
                    sdbusplus::asio::PropertyPermission permission,
                    nlohmann::json& systemConfiguration,
                    const std::string& jsonPointerString)
{
    std::vector<PropertyType> values;
    for (const auto& property : array)
    {
        auto ptr = property.get_ptr<const PropertyType*>();
        if (ptr != nullptr)
        {
            values.emplace_back(*ptr);
        }
    }

    if (permission == sdbusplus::asio::PropertyPermission::readOnly)
    {
        iface->register_property(name, values);
    }
    else
    {
        iface->register_property(
            name, values,
            [&systemConfiguration,
             jsonPointerString{std::string(jsonPointerString)}](
                const std::vector<PropertyType>& newVal,
                std::vector<PropertyType>& val) {
                val = newVal;
                if (!setJsonFromPointer(jsonPointerString, val,
                                        systemConfiguration))
                {
                    std::cerr << "error setting json field\n";
                    return -1;
                }
                if (!writeJsonFiles(systemConfiguration))
                {
                    std::cerr << "error setting json file\n";
                    return -1;
                }
                return 1;
            });
    }
}

template <typename PropertyType>
void addProperty(const std::string& propertyName, const PropertyType& value,
                 sdbusplus::asio::dbus_interface* iface,
                 nlohmann::json& systemConfiguration,
                 const std::string& jsonPointerString,
                 sdbusplus::asio::PropertyPermission permission)
{
    if (permission == sdbusplus::asio::PropertyPermission::readOnly)
    {
        iface->register_property(propertyName, value);
        return;
    }
    iface->register_property(
        propertyName, value,
        [&systemConfiguration,
         jsonPointerString{std::string(jsonPointerString)}](
            const PropertyType& newVal, PropertyType& val) {
            val = newVal;
            if (!setJsonFromPointer(jsonPointerString, val,
                                    systemConfiguration))
            {
                std::cerr << "error setting json field\n";
                return -1;
            }
            if (!writeJsonFiles(systemConfiguration))
            {
                std::cerr << "error setting json file\n";
                return -1;
            }
            return 1;
        });
}

void createDeleteObjectMethod(
    const std::string& jsonPointerPath,
    const std::shared_ptr<sdbusplus::asio::dbus_interface>& iface,
    sdbusplus::asio::object_server& objServer,
    nlohmann::json& systemConfiguration)
{
    std::weak_ptr<sdbusplus::asio::dbus_interface> interface = iface;
    iface->register_method(
        "Delete", [&objServer, &systemConfiguration, interface,
                   jsonPointerPath{std::string(jsonPointerPath)}]() {
            std::shared_ptr<sdbusplus::asio::dbus_interface> dbusInterface =
                interface.lock();
            if (!dbusInterface)
            {
                // this technically can't happen as the pointer is pointing to
                // us
                throw DBusInternalError();
            }
            nlohmann::json::json_pointer ptr(jsonPointerPath);
            systemConfiguration[ptr] = nullptr;

            // todo(james): dig through sdbusplus to find out why we can't
            // delete it in a method call
            io.post([&objServer, dbusInterface]() mutable {
                objServer.remove_interface(dbusInterface);
            });

            if (!writeJsonFiles(systemConfiguration))
            {
                std::cerr << "error setting json file\n";
                throw DBusInternalError();
            }
        });
}

// adds simple json types to interface's properties
void populateInterfaceFromJson(
    nlohmann::json& systemConfiguration, const std::string& jsonPointerPath,
    std::shared_ptr<sdbusplus::asio::dbus_interface>& iface,
    nlohmann::json& dict, sdbusplus::asio::object_server& objServer,
    sdbusplus::asio::PropertyPermission permission =
        sdbusplus::asio::PropertyPermission::readOnly)
{
    for (auto& dictPair : dict.items())
    {
        auto type = dictPair.value().type();
        bool array = false;
        if (dictPair.value().type() == nlohmann::json::value_t::array)
        {
            array = true;
            if (!dictPair.value().size())
            {
                continue;
            }
            type = dictPair.value()[0].type();
            bool isLegal = true;
            for (const auto& arrayItem : dictPair.value())
            {
                if (arrayItem.type() != type)
                {
                    isLegal = false;
                    break;
                }
            }
            if (!isLegal)
            {
                std::cerr << "dbus format error" << dictPair.value() << "\n";
                continue;
            }
        }
        if (type == nlohmann::json::value_t::object)
        {
            continue; // handled elsewhere
        }
        std::string key = jsonPointerPath + "/" + dictPair.key();
        if (permission == sdbusplus::asio::PropertyPermission::readWrite)
        {
            // all setable numbers are doubles as it is difficult to always
            // create a configuration file with all whole numbers as decimals
            // i.e. 1.0
            if (array)
            {
                if (dictPair.value()[0].is_number())
                {
                    type = nlohmann::json::value_t::number_float;
                }
            }
            else if (dictPair.value().is_number())
            {
                type = nlohmann::json::value_t::number_float;
            }
        }

        switch (type)
        {
            case (nlohmann::json::value_t::boolean):
            {
                if (array)
                {
                    // todo: array of bool isn't detected correctly by
                    // sdbusplus, change it to numbers
                    addArrayToDbus<uint64_t>(dictPair.key(), dictPair.value(),
                                             iface.get(), permission,
                                             systemConfiguration, key);
                }

                else
                {
                    addProperty(dictPair.key(), dictPair.value().get<bool>(),
                                iface.get(), systemConfiguration, key,
                                permission);
                }
                break;
            }
            case (nlohmann::json::value_t::number_integer):
            {
                if (array)
                {
                    addArrayToDbus<int64_t>(dictPair.key(), dictPair.value(),
                                            iface.get(), permission,
                                            systemConfiguration, key);
                }
                else
                {
                    addProperty(dictPair.key(), dictPair.value().get<int64_t>(),
                                iface.get(), systemConfiguration, key,
                                sdbusplus::asio::PropertyPermission::readOnly);
                }
                break;
            }
            case (nlohmann::json::value_t::number_unsigned):
            {
                if (array)
                {
                    addArrayToDbus<uint64_t>(dictPair.key(), dictPair.value(),
                                             iface.get(), permission,
                                             systemConfiguration, key);
                }
                else
                {
                    addProperty(dictPair.key(),
                                dictPair.value().get<uint64_t>(), iface.get(),
                                systemConfiguration, key,
                                sdbusplus::asio::PropertyPermission::readOnly);
                }
                break;
            }
            case (nlohmann::json::value_t::number_float):
            {
                if (array)
                {
                    addArrayToDbus<double>(dictPair.key(), dictPair.value(),
                                           iface.get(), permission,
                                           systemConfiguration, key);
                }

                else
                {
                    addProperty(dictPair.key(), dictPair.value().get<double>(),
                                iface.get(), systemConfiguration, key,
                                permission);
                }
                break;
            }
            case (nlohmann::json::value_t::string):
            {
                if (array)
                {
                    addArrayToDbus<std::string>(
                        dictPair.key(), dictPair.value(), iface.get(),
                        permission, systemConfiguration, key);
                }
                else
                {
                    addProperty(
                        dictPair.key(), dictPair.value().get<std::string>(),
                        iface.get(), systemConfiguration, key, permission);
                }
                break;
            }
            default:
            {
                std::cerr << "Unexpected json type in system configuration "
                          << dictPair.key() << ": "
                          << dictPair.value().type_name() << "\n";
                break;
            }
        }
    }
    if (permission == sdbusplus::asio::PropertyPermission::readWrite)
    {
        createDeleteObjectMethod(jsonPointerPath, iface, objServer,
                                 systemConfiguration);
    }
    iface->initialize();
}

sdbusplus::asio::PropertyPermission getPermission(const std::string& interface)
{
    return std::find(settableInterfaces.begin(), settableInterfaces.end(),
                     interface) != settableInterfaces.end()
               ? sdbusplus::asio::PropertyPermission::readWrite
               : sdbusplus::asio::PropertyPermission::readOnly;
}

void createAddObjectMethod(const std::string& jsonPointerPath,
                           const std::string& path,
                           nlohmann::json& systemConfiguration,
                           sdbusplus::asio::object_server& objServer,
                           const std::string& board)
{
    std::shared_ptr<sdbusplus::asio::dbus_interface> iface = createInterface(
        objServer, path, "xyz.openbmc_project.AddObject", board);

    iface->register_method(
        "AddObject",
        [&systemConfiguration, &objServer,
         jsonPointerPath{std::string(jsonPointerPath)}, path{std::string(path)},
         board](const boost::container::flat_map<std::string, JsonVariantType>&
                    data) {
            nlohmann::json::json_pointer ptr(jsonPointerPath);
            nlohmann::json& base = systemConfiguration[ptr];
            auto findExposes = base.find("Exposes");

            if (findExposes == base.end())
            {
                throw std::invalid_argument("Entity must have children.");
            }

            // this will throw invalid-argument to sdbusplus if invalid json
            nlohmann::json newData{};
            for (const auto& item : data)
            {
                nlohmann::json& newJson = newData[item.first];
                std::visit([&newJson](auto&& val) { newJson = std::move(val); },
                           item.second);
            }

            auto findName = newData.find("Name");
            auto findType = newData.find("Type");
            if (findName == newData.end() || findType == newData.end())
            {
                throw std::invalid_argument("AddObject missing Name or Type");
            }
            const std::string* type = findType->get_ptr<const std::string*>();
            const std::string* name = findName->get_ptr<const std::string*>();
            if (type == nullptr || name == nullptr)
            {
                throw std::invalid_argument("Type and Name must be a string.");
            }

            bool foundNull = false;
            size_t lastIndex = 0;
            // we add in the "exposes"
            for (const auto& expose : *findExposes)
            {
                if (expose.is_null())
                {
                    foundNull = true;
                    continue;
                }

                if (expose["Name"] == *name && expose["Type"] == *type)
                {
                    throw std::invalid_argument(
                        "Field already in JSON, not adding");
                }

                if (foundNull)
                {
                    continue;
                }

                lastIndex++;
            }

            std::ifstream schemaFile(std::string(schemaDirectory) + "/" +
                                     *type + ".json");
            // todo(james) we might want to also make a list of 'can add'
            // interfaces but for now I think the assumption if there is a
            // schema avaliable that it is allowed to update is fine
            if (!schemaFile.good())
            {
                throw std::invalid_argument(
                    "No schema avaliable, cannot validate.");
            }
            nlohmann::json schema =
                nlohmann::json::parse(schemaFile, nullptr, false);
            if (schema.is_discarded())
            {
                std::cerr << "Schema not legal" << *type << ".json\n";
                throw DBusInternalError();
            }
            if (!validateJson(schema, newData))
            {
                throw std::invalid_argument("Data does not match schema");
            }
            if (foundNull)
            {
                findExposes->at(lastIndex) = newData;
            }
            else
            {
                findExposes->push_back(newData);
            }
            if (!writeJsonFiles(systemConfiguration))
            {
                std::cerr << "Error writing json files\n";
                throw DBusInternalError();
            }
            std::string dbusName = *name;

            std::regex_replace(dbusName.begin(), dbusName.begin(),
                               dbusName.end(), illegalDbusMemberRegex, "_");

            std::shared_ptr<sdbusplus::asio::dbus_interface> interface =
                createInterface(objServer, path + "/" + dbusName,
                                "xyz.openbmc_project.Configuration." + *type,
                                board, true);
            // permission is read-write, as since we just created it, must be
            // runtime modifiable
            populateInterfaceFromJson(
                systemConfiguration,
                jsonPointerPath + "/Exposes/" + std::to_string(lastIndex),
                interface, newData, objServer,
                sdbusplus::asio::PropertyPermission::readWrite);
        });
    iface->initialize();
}

void postToDbus(const nlohmann::json& newConfiguration,
                nlohmann::json& systemConfiguration,
                sdbusplus::asio::object_server& objServer)

{
    // iterate through boards
    for (auto& boardPair : newConfiguration.items())
    {
        std::string boardKey = boardPair.value()["Name"];
        std::string boardKeyOrig = boardPair.value()["Name"];
        std::string jsonPointerPath = "/" + boardPair.key();
        // loop through newConfiguration, but use values from system
        // configuration to be able to modify via dbus later
        auto boardValues = systemConfiguration[boardPair.key()];
        auto findBoardType = boardValues.find("Type");
        std::string boardType;
        if (findBoardType != boardValues.end() &&
            findBoardType->type() == nlohmann::json::value_t::string)
        {
            boardType = findBoardType->get<std::string>();
            std::regex_replace(boardType.begin(), boardType.begin(),
                               boardType.end(), illegalDbusMemberRegex, "_");
        }
        else
        {
            std::cerr << "Unable to find type for " << boardKey
                      << " reverting to Chassis.\n";
            boardType = "Chassis";
        }
        std::string boardtypeLower = boost::algorithm::to_lower_copy(boardType);

        std::regex_replace(boardKey.begin(), boardKey.begin(), boardKey.end(),
                           illegalDbusMemberRegex, "_");
        std::string boardName = "/xyz/openbmc_project/inventory/system/";
        boardName += boardtypeLower;
        boardName += "/";
        boardName += boardKey;

        std::shared_ptr<sdbusplus::asio::dbus_interface> inventoryIface =
            createInterface(objServer, boardName,
                            "xyz.openbmc_project.Inventory.Item", boardKey);

        std::shared_ptr<sdbusplus::asio::dbus_interface> boardIface =
            createInterface(objServer, boardName,
                            "xyz.openbmc_project.Inventory.Item." + boardType,
                            boardKeyOrig);

        createAddObjectMethod(jsonPointerPath, boardName, systemConfiguration,
                              objServer, boardKeyOrig);

        populateInterfaceFromJson(systemConfiguration, jsonPointerPath,
                                  boardIface, boardValues, objServer);
        jsonPointerPath += "/";
        // iterate through board properties
        for (auto& boardField : boardValues.items())
        {
            if (boardField.value().type() == nlohmann::json::value_t::object)
            {
                std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
                    createInterface(objServer, boardName, boardField.key(),
                                    boardKeyOrig);

                populateInterfaceFromJson(systemConfiguration,
                                          jsonPointerPath + boardField.key(),
                                          iface, boardField.value(), objServer);
            }
        }

        auto exposes = boardValues.find("Exposes");
        if (exposes == boardValues.end())
        {
            continue;
        }
        // iterate through exposes
        jsonPointerPath += "Exposes/";

        // store the board level pointer so we can modify it on the way down
        std::string jsonPointerPathBoard = jsonPointerPath;
        size_t exposesIndex = -1;
        for (auto& item : *exposes)
        {
            exposesIndex++;
            jsonPointerPath = jsonPointerPathBoard;
            jsonPointerPath += std::to_string(exposesIndex);

            auto findName = item.find("Name");
            if (findName == item.end())
            {
                std::cerr << "cannot find name in field " << item << "\n";
                continue;
            }
            auto findStatus = item.find("Status");
            // if status is not found it is assumed to be status = 'okay'
            if (findStatus != item.end())
            {
                if (*findStatus == "disabled")
                {
                    continue;
                }
            }
            auto findType = item.find("Type");
            std::string itemType;
            if (findType != item.end())
            {
                itemType = findType->get<std::string>();
                std::regex_replace(itemType.begin(), itemType.begin(),
                                   itemType.end(), illegalDbusPathRegex, "_");
            }
            else
            {
                itemType = "unknown";
            }
            std::string itemName = findName->get<std::string>();
            std::regex_replace(itemName.begin(), itemName.begin(),
                               itemName.end(), illegalDbusMemberRegex, "_");
            std::string ifacePath = boardName;
            ifacePath += "/";
            ifacePath += itemName;

            std::shared_ptr<sdbusplus::asio::dbus_interface> itemIface =
                createInterface(objServer, ifacePath,
                                "xyz.openbmc_project.Configuration." + itemType,
                                boardKeyOrig);

            populateInterfaceFromJson(systemConfiguration, jsonPointerPath,
                                      itemIface, item, objServer,
                                      getPermission(itemType));

            for (auto& objectPair : item.items())
            {
                jsonPointerPath = jsonPointerPathBoard +
                                  std::to_string(exposesIndex) + "/" +
                                  objectPair.key();
                if (objectPair.value().type() ==
                    nlohmann::json::value_t::object)
                {
                    std::shared_ptr<sdbusplus::asio::dbus_interface>
                        objectIface = createInterface(
                            objServer, ifacePath,
                            "xyz.openbmc_project.Configuration." + itemType +
                                "." + objectPair.key(),
                            boardKeyOrig);

                    populateInterfaceFromJson(systemConfiguration,
                                              jsonPointerPath, objectIface,
                                              objectPair.value(), objServer,
                                              getPermission(objectPair.key()));
                }
                else if (objectPair.value().type() ==
                         nlohmann::json::value_t::array)
                {
                    size_t index = 0;
                    if (!objectPair.value().size())
                    {
                        continue;
                    }
                    bool isLegal = true;
                    auto type = objectPair.value()[0].type();
                    if (type != nlohmann::json::value_t::object)
                    {
                        continue;
                    }

                    // verify legal json
                    for (const auto& arrayItem : objectPair.value())
                    {
                        if (arrayItem.type() != type)
                        {
                            isLegal = false;
                            break;
                        }
                    }
                    if (!isLegal)
                    {
                        std::cerr << "dbus format error" << objectPair.value()
                                  << "\n";
                        break;
                    }

                    for (auto& arrayItem : objectPair.value())
                    {

                        std::shared_ptr<sdbusplus::asio::dbus_interface>
                            objectIface = createInterface(
                                objServer, ifacePath,
                                "xyz.openbmc_project.Configuration." +
                                    itemType + "." + objectPair.key() +
                                    std::to_string(index),
                                boardKeyOrig);

                        populateInterfaceFromJson(
                            systemConfiguration,
                            jsonPointerPath + "/" + std::to_string(index),
                            objectIface, arrayItem, objServer,
                            getPermission(objectPair.key()));
                        index++;
                    }
                }
            }
        }
    }
}

// reads json files out of the filesystem
bool findJsonFiles(std::list<nlohmann::json>& configurations)
{
    // find configuration files
    std::vector<std::filesystem::path> jsonPaths;
    if (!findFiles(
            std::vector<std::filesystem::path>{configurationDirectory,
                                               hostConfigurationDirectory},
            R"(.*\.json)", jsonPaths))
    {
        std::cerr << "Unable to find any configuration files in "
                  << configurationDirectory << "\n";
        return false;
    }

    std::ifstream schemaStream(std::string(schemaDirectory) + "/" +
                               globalSchema);
    if (!schemaStream.good())
    {
        std::cerr
            << "Cannot open schema file,  cannot validate JSON, exiting\n\n";
        std::exit(EXIT_FAILURE);
        return false;
    }
    nlohmann::json schema = nlohmann::json::parse(schemaStream, nullptr, false);
    if (schema.is_discarded())
    {
        std::cerr
            << "Illegal schema file detected, cannot validate JSON, exiting\n";
        std::exit(EXIT_FAILURE);
        return false;
    }

    for (auto& jsonPath : jsonPaths)
    {
        std::ifstream jsonStream(jsonPath.c_str());
        if (!jsonStream.good())
        {
            std::cerr << "unable to open " << jsonPath.string() << "\n";
            continue;
        }
        auto data = nlohmann::json::parse(jsonStream, nullptr, false);
        if (data.is_discarded())
        {
            std::cerr << "syntax error in " << jsonPath.string() << "\n";
            continue;
        }
        /*
         * todo(james): reenable this once less things are in flight
         *
        if (!validateJson(schema, data))
        {
            std::cerr << "Error validating " << jsonPath.string() << "\n";
            continue;
        }
        */

        if (data.type() == nlohmann::json::value_t::array)
        {
            for (auto& d : data)
            {
                configurations.emplace_back(d);
            }
        }
        else
        {
            configurations.emplace_back(data);
        }
    }
    return true;
}

void startRemovedTimer(boost::asio::steady_timer& timer,
                       nlohmann::json& systemConfiguration)
{
    static bool scannedPowerOff = false;
    static bool scannedPowerOn = false;

    if (systemConfiguration.empty() || lastJson.empty())
    {
        return; // not ready yet
    }
    if (scannedPowerOn)
    {
        return;
    }

    if (!isPowerOn() && scannedPowerOff)
    {
        return;
    }

    timer.expires_after(std::chrono::seconds(10));
    timer.async_wait(
        [&systemConfiguration](const boost::system::error_code& ec) {
            if (ec == boost::asio::error::operation_aborted)
            {
                // we were cancelled
                return;
            }

            bool powerOff = !isPowerOn();
            for (const auto& item : lastJson.items())
            {
                if (systemConfiguration.find(item.key()) ==
                    systemConfiguration.end())
                {
                    bool isDetectedPowerOn = false;
                    auto powerState = item.value().find("PowerState");
                    if (powerState != item.value().end())
                    {
                        auto ptr = powerState->get_ptr<const std::string*>();
                        if (ptr)
                        {
                            if (*ptr == "On" || *ptr == "BiosPost")
                            {
                                isDetectedPowerOn = true;
                            }
                        }
                    }
                    if (powerOff && isDetectedPowerOn)
                    {
                        // power not on yet, don't know if it's there or not
                        continue;
                    }
                    if (!powerOff && scannedPowerOff && isDetectedPowerOn)
                    {
                        // already logged it when power was off
                        continue;
                    }

                    logDeviceRemoved(item.value());
                }
            }
            scannedPowerOff = true;
            if (!powerOff)
            {
                scannedPowerOn = true;
            }
        });
}

// main properties changed entry
void propertiesChangedCallback(nlohmann::json& systemConfiguration,
                               sdbusplus::asio::object_server& objServer)
{
    static bool inProgress = false;
    static boost::asio::steady_timer timer(io);
    static size_t instance = 0;
    instance++;
    size_t count = instance;

    timer.expires_after(std::chrono::seconds(5));

    // setup an async wait as we normally get flooded with new requests
    timer.async_wait([&systemConfiguration, &objServer,
                      count](const boost::system::error_code& ec) {
        if (ec == boost::asio::error::operation_aborted)
        {
            // we were cancelled
            return;
        }
        if (ec)
        {
            std::cerr << "async wait error " << ec << "\n";
            return;
        }

        if (inProgress)
        {
            propertiesChangedCallback(systemConfiguration, objServer);
            return;
        }
        inProgress = true;

        nlohmann::json oldConfiguration = systemConfiguration;
        auto missingConfigurations = std::make_shared<nlohmann::json>();
        *missingConfigurations = systemConfiguration;

        std::list<nlohmann::json> configurations;
        if (!findJsonFiles(configurations))
        {
            std::cerr << "cannot find json files\n";
            inProgress = false;
            return;
        }

        auto perfScan = std::make_shared<PerformScan>(
            systemConfiguration, *missingConfigurations, configurations,
            objServer,
            [&systemConfiguration, &objServer, count, oldConfiguration,
             missingConfigurations]() {
                // this is something that since ac has been applied to the bmc
                // we saw, and we no longer see it
                bool powerOff = !isPowerOn();
                for (const auto& item : missingConfigurations->items())
                {
                    bool isDetectedPowerOn = false;
                    auto powerState = item.value().find("PowerState");
                    if (powerState != item.value().end())
                    {
                        auto ptr = powerState->get_ptr<const std::string*>();
                        if (ptr)
                        {
                            if (*ptr == "On" || *ptr == "BiosPost")
                            {
                                isDetectedPowerOn = true;
                            }
                        }
                    }
                    if (powerOff && isDetectedPowerOn)
                    {
                        // power not on yet, don't know if it's there or not
                        continue;
                    }
                    std::string name = item.value()["Name"].get<std::string>();
                    std::vector<std::weak_ptr<sdbusplus::asio::dbus_interface>>&
                        ifaces = inventory[name];
                    for (auto& iface : ifaces)
                    {
                        auto sharedPtr = iface.lock();
                        if (!sharedPtr)
                        {
                            continue; // was already deleted elsewhere
                        }
                        objServer.remove_interface(sharedPtr);
                    }
                    ifaces.clear();
                    systemConfiguration.erase(item.key());
                    logDeviceRemoved(item.value());
                }

                nlohmann::json newConfiguration = systemConfiguration;
                for (auto it = newConfiguration.begin();
                     it != newConfiguration.end();)
                {
                    auto findKey = oldConfiguration.find(it.key());
                    if (findKey != oldConfiguration.end())
                    {
                        it = newConfiguration.erase(it);
                    }
                    else
                    {
                        it++;
                    }
                }
                for (const auto& item : newConfiguration.items())
                {
                    logDeviceAdded(item.value());
                }

                inProgress = false;

                io.post([count, newConfiguration, &systemConfiguration,
                         &objServer]() {
                    loadOverlays(newConfiguration);

                    io.post([&systemConfiguration]() {
                        if (!writeJsonFiles(systemConfiguration))
                        {
                            std::cerr << "Error writing json files\n";
                        }
                    });
                    io.post([count, newConfiguration, &systemConfiguration,
                             &objServer]() {
                        postToDbus(newConfiguration, systemConfiguration,
                                   objServer);
                        if (count != instance)
                        {
                            return;
                        }
                        startRemovedTimer(timer, systemConfiguration);
                    });
                });
            });
        perfScan->run();
    });
}

int main()
{
    // setup connection to dbus
    systemBus = std::make_shared<sdbusplus::asio::connection>(io);
    systemBus->request_name("xyz.openbmc_project.EntityManager");

    sdbusplus::asio::object_server objServer(systemBus);

    std::shared_ptr<sdbusplus::asio::dbus_interface> entityIface =
        objServer.add_interface("/xyz/openbmc_project/EntityManager",
                                "xyz.openbmc_project.EntityManager");

    // to keep reference to the match / filter objects so they don't get
    // destroyed

    nlohmann::json systemConfiguration = nlohmann::json::object();

    // We need a poke from DBus for static providers that create all their
    // objects prior to claiming a well-known name, and thus don't emit any
    // org.freedesktop.DBus.Properties signals.  Similarly if a process exits
    // for any reason, expected or otherwise, we'll need a poke to remove
    // entities from DBus.
    sdbusplus::bus::match::match nameOwnerChangedMatch(
        static_cast<sdbusplus::bus::bus&>(*systemBus),
        sdbusplus::bus::match::rules::nameOwnerChanged(),
        [&](sdbusplus::message::message&) {
            propertiesChangedCallback(systemConfiguration, objServer);
        });
    // We also need a poke from DBus when new interfaces are created or
    // destroyed.
    sdbusplus::bus::match::match interfacesAddedMatch(
        static_cast<sdbusplus::bus::bus&>(*systemBus),
        sdbusplus::bus::match::rules::interfacesAdded(),
        [&](sdbusplus::message::message&) {
            propertiesChangedCallback(systemConfiguration, objServer);
        });
    sdbusplus::bus::match::match interfacesRemovedMatch(
        static_cast<sdbusplus::bus::bus&>(*systemBus),
        sdbusplus::bus::match::rules::interfacesRemoved(),
        [&](sdbusplus::message::message&) {
            propertiesChangedCallback(systemConfiguration, objServer);
        });

    io.post(
        [&]() { propertiesChangedCallback(systemConfiguration, objServer); });

    entityIface->register_method("ReScan", [&]() {
        propertiesChangedCallback(systemConfiguration, objServer);
    });
    entityIface->initialize();

    if (fwVersionIsSame())
    {
        if (std::filesystem::is_regular_file(currentConfiguration))
        {
            // this file could just be deleted, but it's nice for debug
            std::filesystem::create_directory(tempConfigDir);
            std::filesystem::remove(lastConfiguration);
            std::filesystem::copy(currentConfiguration, lastConfiguration);
            std::filesystem::remove(currentConfiguration);

            std::ifstream jsonStream(lastConfiguration);
            if (jsonStream.good())
            {
                auto data = nlohmann::json::parse(jsonStream, nullptr, false);
                if (data.is_discarded())
                {
                    std::cerr << "syntax error in " << lastConfiguration
                              << "\n";
                }
                else
                {
                    lastJson = std::move(data);
                }
            }
            else
            {
                std::cerr << "unable to open " << lastConfiguration << "\n";
            }
        }
    }
    else
    {
        // not an error, just logging at this level to make it in the journal
        std::cerr << "Clearing previous configuration\n";
        std::filesystem::remove(currentConfiguration);
    }

    // some boards only show up after power is on, we want to not say they are
    // removed until the same state happens
    setupPowerMatch(systemBus);

    io.run();

    return 0;
}

max_stars_repo_name: cjcain/entity-manager

max_issues_repo_name: cjcain/entity-manager

max_forks_repo_name: cjcain/entity-manager


text:
/*
 * 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)
 *
 * Copyright (c) 2009 Helge Bahmann
 * Copyright (c) 2014 Andrey Semashev
 */
/*!
 * \file   atomic/detail/platform.hpp
 *
 * This header defines macros for the target platform detection
 */

#ifndef BOOST_ATOMIC_DETAIL_PLATFORM_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_PLATFORM_HPP_INCLUDED_

#include <boost/atomic/detail/config.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#if defined(__GNUC__) && defined(__arm__)

// Newer gcc versions define __ARM_ARCH. Older ones don't, so we have to deduce ARM arch version from a bunch of version-specific macros.
#if defined(__ARM_ARCH)
#define BOOST_ATOMIC_DETAIL_ARM_ARCH __ARM_ARCH
#elif defined(__ARM_ARCH_8A__)
#define BOOST_ATOMIC_DETAIL_ARM_ARCH 8
#elif defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) ||\
    defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) ||\
    defined(__ARM_ARCH_7EM__) || defined(__ARM_ARCH_7S__)
#define BOOST_ATOMIC_DETAIL_ARM_ARCH 7
#elif defined(__ARM_ARCH_6__)  || defined(__ARM_ARCH_6J__) ||\
    defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) ||\
    defined(__ARM_ARCH_6ZK__)
#define BOOST_ATOMIC_DETAIL_ARM_ARCH 6
#else
// We are not interested in older versions - they don't support atomic ops
#define BOOST_ATOMIC_DETAIL_ARM_ARCH 0
#endif

#endif // defined(__GNUC__) && defined(__arm__)

#if !defined(BOOST_ATOMIC_FORCE_FALLBACK)

// Determine the target platform.
// The target platform describes the compiler and target architecture. It can be used by more generic backends, such as the ones
// based on compiler intrinsics, to implement specialized operations in a non-generic way.

#if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))

#define BOOST_ATOMIC_DETAIL_PLATFORM gcc_x86
#define BOOST_ATOMIC_DETAIL_EXTRA_BACKEND gcc_x86

#elif defined(__GNUC__) && (defined(__POWERPC__) || defined(__PPC__))

#define BOOST_ATOMIC_DETAIL_PLATFORM gcc_ppc
#define BOOST_ATOMIC_DETAIL_EXTRA_BACKEND gcc_ppc

#elif defined(__GNUC__) && defined(__arm__) && (BOOST_ATOMIC_DETAIL_ARM_ARCH+0) >= 6

#define BOOST_ATOMIC_DETAIL_PLATFORM gcc_arm
#define BOOST_ATOMIC_DETAIL_EXTRA_BACKEND gcc_arm

#elif (defined(__GNUC__) || defined(__SUNPRO_CC)) && (defined(__sparcv8plus) || defined(__sparc_v9__))

#define BOOST_ATOMIC_DETAIL_PLATFORM gcc_sparc

#elif defined(__GNUC__) && defined(__alpha__)

#define BOOST_ATOMIC_DETAIL_PLATFORM gcc_alpha

#elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))

#define BOOST_ATOMIC_DETAIL_PLATFORM msvc_x86

#elif defined(_MSC_VER) && _MSC_VER >= 1700 && (defined(_M_ARM) || defined(_M_ARM64))

#define BOOST_ATOMIC_DETAIL_PLATFORM msvc_arm

#endif

// Compiler-based backends

// IBM XL C++ Compiler has to be checked before GCC/Clang as it pretends to be one but does not support __atomic* intrinsics.
// It does support GCC inline assembler though.
#if !(defined(__ibmxl__) || defined(__IBMCPP__)) &&\
    ((defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 407)) ||\
        (defined(BOOST_CLANG) && ((__clang_major__ * 100 + __clang_minor__) >= 302))) &&\
    (\
        (__GCC_ATOMIC_BOOL_LOCK_FREE + 0) == 2 ||\
        (__GCC_ATOMIC_CHAR_LOCK_FREE + 0) == 2 ||\
        (__GCC_ATOMIC_SHORT_LOCK_FREE + 0) == 2 ||\
        (__GCC_ATOMIC_INT_LOCK_FREE + 0) == 2 ||\
        (__GCC_ATOMIC_LONG_LOCK_FREE + 0) == 2 ||\
        (__GCC_ATOMIC_LLONG_LOCK_FREE + 0) == 2\
    )

#define BOOST_ATOMIC_DETAIL_BACKEND gcc_atomic

#elif defined(BOOST_ATOMIC_DETAIL_PLATFORM)

#define BOOST_ATOMIC_DETAIL_BACKEND BOOST_ATOMIC_DETAIL_PLATFORM

#elif defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 401) &&\
    (\
        defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1) ||\
        defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2) ||\
        defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) ||\
        defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8) ||\
        defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)\
    )

#define BOOST_ATOMIC_DETAIL_BACKEND gcc_sync

#endif

// OS-based backends

#if !defined(BOOST_ATOMIC_DETAIL_BACKEND)

#if defined(__linux__) && defined(__arm__)

#define BOOST_ATOMIC_DETAIL_BACKEND linux_arm

#elif defined(BOOST_WINDOWS) || defined(_WIN32_CE)

#define BOOST_ATOMIC_DETAIL_BACKEND windows

#endif

#endif // !defined(BOOST_ATOMIC_DETAIL_BACKEND)

#endif // !defined(BOOST_ATOMIC_FORCE_FALLBACK)

#if !defined(BOOST_ATOMIC_DETAIL_BACKEND)
#define BOOST_ATOMIC_DETAIL_BACKEND emulated
#define BOOST_ATOMIC_EMULATED
#endif

#if !defined(BOOST_ATOMIC_DETAIL_EXTRA_BACKEND)
#define BOOST_ATOMIC_DETAIL_EXTRA_BACKEND generic
#define BOOST_ATOMIC_DETAIL_EXTRA_BACKEND_GENERIC
#endif

#define BOOST_ATOMIC_DETAIL_BACKEND_HEADER(prefix) <BOOST_JOIN(prefix, BOOST_ATOMIC_DETAIL_BACKEND).hpp>
#define BOOST_ATOMIC_DETAIL_EXTRA_BACKEND_HEADER(prefix) <BOOST_JOIN(prefix, BOOST_ATOMIC_DETAIL_EXTRA_BACKEND).hpp>

#endif // BOOST_ATOMIC_DETAIL_PLATFORM_HPP_INCLUDED_

ext: hpp


text: #include <boost/archive/basic_archive.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef _VCLCANVAS_CANVASFONT_HXX
#define _VCLCANVAS_CANVASFONT_HXX

#include <comphelper/implementationreference.hxx>

#include <cppuhelper/compbase2.hxx>
#include <comphelper/broadcasthelper.hxx>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/geometry/Matrix2D.hpp>
#include <com/sun/star/rendering/FontRequest.hpp>
#include <com/sun/star/rendering/XCanvasFont.hpp>
#include <com/sun/star/rendering/XGraphicDevice.hpp>

#include <vcl/font.hxx>

#include <canvas/vclwrapper.hxx>

#include "spritecanvas.hxx"
#include "impltools.hxx"

#include <boost/utility.hpp>

/* Definition of CanvasFont class */

namespace vclcanvas
{
    typedef ::cppu::WeakComponentImplHelper2< ::com::sun::star::rendering::XCanvasFont,
                         					  ::com::sun::star::lang::XServiceInfo > CanvasFont_Base;

    class CanvasFont : public ::comphelper::OBaseMutex,
                       public CanvasFont_Base,
        			   private ::boost::noncopyable
    {
    public:
        typedef ::comphelper::ImplementationReference<
            CanvasFont,
            ::com::sun::star::rendering::XCanvasFont > Reference;

        CanvasFont( const ::com::sun::star::rendering::FontRequest& 									fontRequest,
                    const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& 	extraFontProperties,
                    const ::com::sun::star::geometry::Matrix2D&											rFontMatrix,
                    ::com::sun::star::rendering::XGraphicDevice&                                        rDevice,
                    const OutDevProviderSharedPtr&                                                      rOutDevProvider );

        /// Dispose all internal references
        virtual void SAL_CALL disposing();

        // XCanvasFont
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XTextLayout > SAL_CALL createTextLayout( const ::com::sun::star::rendering::StringContext& aText, sal_Int8 nDirection, sal_Int64 nRandomSeed ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::rendering::FontRequest SAL_CALL getFontRequest(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::rendering::FontMetrics SAL_CALL getFontMetrics(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< double > SAL_CALL getAvailableSizes(  ) throw (::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getExtraFontProperties(  ) throw (::com::sun::star::uno::RuntimeException);

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
        virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames()  throw( ::com::sun::star::uno::RuntimeException );

        ::Font getVCLFont() const;

    private:
        ::canvas::vcltools::VCLObject<Font>                                            maFont;
        ::com::sun::star::rendering::FontRequest                                       maFontRequest;
        ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XGraphicDevice> mpRefDevice;
        OutDevProviderSharedPtr                                                        mpOutDevProvider;
    };

}

#endif /* _VCLCANVAS_CANVASFONT_HXX */

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
#ifndef __TYTI_RANGE_UNION_HPP__
#define __TYTI_RANGE_UNION_HPP__

#include <utility>
#include <iterator>
#include <numeric>
#include <algorithm>
#include <functional>
#include <numeric>

#include <vector>

//#include <boost/range/iterator_range.hpp> // compatible with

namespace tyti
{
    template<typename RangeT, typename ContainerT>
    class range_union;
}

template<typename T, template<class,class> class C>
tyti::range_union<T,C> operator+(tyti::range_union<T,C> lhs, const typename T& rhs)
{
    return lhs += rhs;
}
template<typename T, template<class, class> class C>
tyti::range_union<T,C> operator-(tyti::range_union<T,C> lhs, const typename T& rhs)
{
    return lhs -= rhs;
}

namespace tyti
{
    /** \brief Simple Example of a range
     shows the requirement of a range
     */
    template<typename T>
    class pair_range : public std::pair<T, T>
    {
    public:
        typedef T iterator; //forward iterator
        pair_range(){}
        pair_range(const iterator& begin, const iterator& end) :std::pair<T, T>(begin, end) {}
        const T& begin() const { return first; }
        const T& end() const { return second; }
    };

    /** \brief range_union class
    @param RangeT range type. Requirement are shown in pair_range
    @param ContainerT container which will be used. Use vector, if you want max performance for iteration.
        Use list, if you want max performance when you insert/delete a lot(+=/-= operators).
    */
    template<typename RangeT, class ContainerT = std::vector<RangeT, std::allocator<RangeT> > >
    class range_union
    {
        ///////////////////////////////////////////////////////////////////////////////
        // common types
        ///////////////////////////////////////////////////////////////////////////////
    public:
        typedef RangeT range_type;
        typedef ContainerT container_type;
        typedef typename container_type::iterator ranges_iterator;
        typedef typename container_type::const_iterator const_ranges_iterator;

    private:
        ///////////////////////////////////////////////////////////////////////////////
        // members
        ///////////////////////////////////////////////////////////////////////////////
        container_type m_ranges;

        ///////////////////////////////////////////////////////////////////////////////
        // private details
        ///////////////////////////////////////////////////////////////////////////////
        struct less_or_disjunct
        {
            bool operator()(const RangeT& lhs, const RangeT& rhs)
            {
                return lhs.end() < rhs.begin();
            }
        };

        // iterator
        template<typename tagT>
        class base_iteratorT : public base_iteratorT<std::bidirectional_iterator_tag>
        {
        public:
            base_iteratorT(const range_union<range_type>& interval, const const_ranges_iterator& currentRange) :
                base_iteratorT<std::bidirectional_iterator_tag>(interval, currentRange)
            {}
            base_iteratorT(const base_iteratorT<std::bidirectional_iterator_tag>& it) :
                base_iteratorT<std::bidirectional_iterator_tag>(it)
            {}
        };

        template<>
        class base_iteratorT<std::forward_iterator_tag>
        {
        protected:
            const range_union<range_type>& m_interval;
            const_ranges_iterator m_currentRange;
            typename range_type::iterator m_current;

            bool equal(const base_iteratorT& rhs) const { return m_current == rhs.m_current; }

        public:
            base_iteratorT(const range_union<range_type>& interval, const const_ranges_iterator& currentRange) :
                m_interval(interval),
                m_currentRange(currentRange),
                m_current((currentRange != interval.ranges_end()) ? currentRange->begin() : interval.ranges_back().end())
            {
            }

            base_iteratorT& operator++()
            {
                if (m_currentRange == m_interval.ranges_end())
                    return *this;

                const_ranges_iterator nextRange = m_currentRange;
                ++nextRange;
                ++m_current;
                if (m_current == m_currentRange->end() && nextRange != m_interval.ranges_end()) //skip endIter if current range is not the last range
                {
                    m_current = nextRange->begin();
                    m_currentRange = nextRange;
                }

                return *this;
            }
            base_iteratorT operator++(int)
            {
                base_iteratorT tmp(*this);
                ++(*this);
                return tmp;
            }

            bool operator==(const base_iteratorT& rhs) const { return equal(rhs); }
            bool operator!=(const base_iteratorT& rhs) const { return !equal(rhs); }
            const typename range_type::iterator& operator*() const { return m_current; }
        };

        template<>
        class base_iteratorT<std::bidirectional_iterator_tag> : public base_iteratorT<std::forward_iterator_tag>
        {
        public:
            base_iteratorT(const range_union<range_type>& interval, const const_ranges_iterator& currentRange) :
                base_iteratorT<std::forward_iterator_tag>(interval, currentRange)
            {}
            base_iteratorT& operator--()
            {
                if (m_currentRange == m_interval.ranges_end())
                    return *this;

                const_ranges_iterator prevRange = m_currentRange;
                --prevRange;
                if (m_current == m_currentRange->begin())
                {
                    m_current = m_currentRange->end();
                    if (prevRange != m_interval.ranges_begin()) // if its not the first range, continue
                    {
                        --m_current;
                        m_currentRange = prevRange;
                    }
                }
                else
                    --m_current;

                return *this;
            }
            base_iteratorT operator--(int)
            {
                base_iteratorT tmp(*this);
                --(*this);
                return tmp;
            }
        };

        template<typename iter, bool isSpecT>
        class iteratorT : public std::iterator<typename std::iterator_traits<iter>::iterator_category, iter>, public base_iteratorT<typename std::iterator_traits<iter>::iterator_category>
        {
        public:
            iteratorT(const range_union<range_type>& interval, const const_ranges_iterator& currentRange) :
                base_iteratorT<typename std::iterator_traits<iter>::iterator_category>(interval, currentRange) {}
            iteratorT(const base_iteratorT<typename std::iterator_traits<iter>::iterator_category>& it) :
                base_iteratorT<typename std::iterator_traits<iter>::iterator_category>(it) {}
        };

        //for plain types like int, unsigned int, etc.
        template<typename iter>
        class iteratorT<iter, true> : public std::iterator<std::bidirectional_iterator_tag, iter>, public base_iteratorT<std::bidirectional_iterator_tag>
        {
        public:
            iteratorT(const range_union<range_type>& interval, const const_ranges_iterator& currentRange) :
                base_iteratorT<std::bidirectional_iterator_tag>(interval, currentRange) {}
            iteratorT(const base_iteratorT<std::bidirectional_iterator_tag>& it) :
                base_iteratorT<std::bidirectional_iterator_tag>(it) {}
        };

    public:
        ///////////////////////////////////////////////////////////////////////////////
        // public interface
        ///////////////////////////////////////////////////////////////////////////////

        typedef iteratorT<
            typename range_type::iterator,
            std::numeric_limits<typename range_type::iterator>::is_specialized
        > iterator;

        /** adds a given range to the current union
        * e.g.:
        * [(0,5)] += (4,10) -> [(0,10)]
        * [(0,5)] += (9,10) -> [(0,5),(9,10)]
        */
        range_union& operator+=(const range_type& rhs)
        {
            ranges_iterator lw_it = std::lower_bound(m_ranges.begin(), m_ranges.end(), rhs, less_or_disjunct());
            if (lw_it == m_ranges.end() || lw_it->begin() > rhs.end()) //all are less |or| lw_it is greater than rhs _and_ disjunct
            {
                m_ranges.insert(lw_it, rhs);
                return *this;
            }
            //lw_it and rhs are not disjunct
            ranges_iterator up_it = std::upper_bound(std::next(lw_it), m_ranges.end(), rhs, less_or_disjunct());
            //overwrite first non disjunct range
            using namespace std; //use algorithm min/max or, if defined before, windows macros of min/max
            *lw_it = range_type(min(rhs.begin(), lw_it->begin()), max(rhs.end(), std::prev(up_it)->end()));
            //delete the rest
            m_ranges.erase(std::next(lw_it), up_it);
            return *this;
        }

        /** removes a given range to the current union
        * e.g.:
        * [(0,10)] -= (4,10) -> [(0,4)]
        * [(0,10)] -= (7,8) -> [(0,7),(8,10)]
        */
        range_union& operator-=(const range_type& rhs)
        {
            std::pair<ranges_iterator, ranges_iterator> contiguous = std::equal_range(m_ranges.begin(), m_ranges.end(), rhs, less_or_disjunct());
            if (contiguous.first != contiguous.second)
            {
                typename range_type::iterator first = contiguous.first->begin();
                typename range_type::iterator last = std::prev(contiguous.second)->end();

                //range to delete
                std::pair<ranges_iterator, ranges_iterator> deleteRange =
                    std::make_pair((first < rhs.begin()) ? std::next(contiguous.first) : contiguous.first, contiguous.second);

                if (first < rhs.begin())//reuse first block?
                    *contiguous.first = range_type(contiguous.first->begin(), rhs.begin());

                ranges_iterator it = m_ranges.erase(deleteRange.first, deleteRange.second);

                if (last > rhs.end())
                    m_ranges.insert(it, range_type(rhs.end(), last));//m_ranges.emplace(rhs.end(), last);
            }
            return *this;
        }
        /**
        * remove all ranges from the given range_union
        */
        const range_union& operator-=(const range_union& rhs)
        {
            for (const_ranges_iterator it = rhs.ranges_begin(); it != rhs.ranges_end(); ++it)
                *this -= *it;
            return *this;
        }

        /**
        * add all ranges from the given range_union
        */
        const range_union& operator+=(const range_union& rhs)
        {
            for (const_ranges_iterator it = rhs.ranges_begin(); it != rhs.ranges_end(); ++it)
                *this += *it;
            return *this;
        }

        /**
        * get the beginning of the iterator. Iterates over all elements speicified by the ranges
        */
        iterator begin() const { return iterator(*this, ranges_begin()); }
        iterator end() const { return iterator(*this, ranges_end()); }
        iterator cbegin() const { return const_iterator(*this, ranges_begin()); }
        iterator cend() const { return const_iterator(*this, ranges_end()); }

        /**
        * get the beginning of the range_iterator. Iterates over all ranges inside the union
        */
        const_ranges_iterator ranges_begin() const { return m_ranges.begin(); }
        const_ranges_iterator ranges_end() const { return m_ranges.end(); }
        range_type ranges_front() const { return *m_ranges.begin(); }
        range_type ranges_back() const { return *m_ranges.rbegin(); }

        size_t size() { return m_ranges.size(); }
        bool empty() { return m_ranges.empty(); }

        /**
        * return true, if the given range is disjunct with all the ranges saved in the union. otherwise false
        */
        bool disjunct(const range_type& rhs)
        {
            std::pair<ranges_iterator, ranges_iterator> ov = std::equal_range(m_ranges.begin(), m_ranges.end(), rhs, less_or_disjunct());
            if (ov.first == ov.second)
                return true;
            return ov.first->begin() >= rhs.end();

        }

    };
}

#endif //__TYTI_RANGE_UNION_HPP__

max_stars_repo_name: TinyTinni/RangeUnion

max_issues_repo_name: TinyTinni/RangeUnion

max_forks_repo_name: TinyTinni/RangeUnion


text:
#ifndef SENSORS_STEREO_HUD_HPP
#define SENSORS_STEREO_HUD_HPP

#include "opencv2/opencv.hpp"
#include <cv.h>
#include <iostream>
#include <string>
#include <bot_core/bot_core.h>
#include <Eigen/Core>

using namespace cv;

#define PI 3.14159265

class Hud {

    private:
        float airspeed_, airspeed_unchecked_, altitude_, q0_, q1_, q2_, q3_, gps_speed_, gps_heading_, battery_voltage_, x_accel_, y_accel_, z_accel_, throttle_, elevonL_, elevonR_;
        long timestamp_;
        int frame_number_, video_number_;
        int plane_number_, log_number_;
        int scale_factor_;
        Scalar hud_color_ ;
        int box_line_width_;
        int text_font_;
        double hud_font_scale_;
        double hud_font_scale_small_;
        float text_thickness_;
        float pitch_range_of_lens_;
        int is_autonomous_;
        int clutter_level_;
        int traj_number_;
        std::string state_machine_state_ = "State Unknown";
        double u0_left_elevon_ = 0;
        double u0_right_elevon_ = 0;
        double u0_throttle_ = 0;

        void PutHudText(Mat hud_img, string str_in, Point text_orgin);
        void PutHudTextSmall(Mat hud_img, string str_in, Point text_orgin);

        void DrawAirspeed(Mat hud_img);
        void DrawAltitude(Mat hud_img);
        void DrawLadder(Mat hud_img, float value, bool for_airspeed, int major_increment, int minor_increment);
        void DrawFrameNumber(Mat hud_img);
        void DrawGpsSpeed(Mat hud_img);
        void DrawArtificialHorizon(Mat hud_img);
        void DrawCompass(Mat hud_img);
        void DrawBatteryVoltage(Mat hud_img);
        void DrawStateMachineState(Mat hud_img);

        void DrawHashBoxFill(Mat hud_img, Point top_left, Point top_right, Point bottom_left, Point bottom_right);

        void DrawDateTime(Mat hud_img);

        void DrawElevon(Mat hud_img, float elevon_value, float elevon_u0_value, float roll, int center_delta, int width, int position_left, int position_right, bool is_left);

        void DrawAutonomous(Mat hud_img);

        void DrawCenterMark(Mat hud_img);
        void DrawThrottle(Mat hud_img);
        void DrawPlaneAndLogNumbers(Mat hud_img);

        void DrawAllAccelerationIndicators(Mat hud_img);
        void DrawGraphIndicator(Mat hud_img, int left, int top, string label, int min_value, int max_value, int mark_increment, string plus_format, string minus_format, float value, bool zero_in_center = false, bool reverse_graph_direction = false);

        void GetEulerAngles(float *yaw, float *pitch, float *roll);

        int GetLadderBoxTop(Mat hud_img) { return hud_img.rows * 0.394; }
        int GetLadderBoxWidth(Mat hud_img) { return hud_img.cols * 0.10; }
        int GetLadderBoxHeight(Mat hud_img) { return hud_img.rows * 0.072; }
        int GetLadderArrowWidth(Mat hud_img) { return hud_img.cols * 0.025; }
        int GetAirspeedLeft(Mat hud_img) { return hud_img.cols * .045; }
        int GetAltitudeLeft(Mat hud_img) { return hud_img.cols * .833; }

    public:
        Hud(Scalar hud_color = Scalar(0.45, 0.95, 0.48)); // default is green

        void SetAirspeed(float airspeed_in_mps) { airspeed_
            = 2.23694*airspeed_in_mps; }

        void SetAirspeedUnchecked(float airspeed_unchecked_in_mps) { airspeed_unchecked_
            = 2.23694*airspeed_unchecked_in_mps; }

        void SetAltitude(float altitude_in_meters) { altitude_ = 3.28084*altitude_in_meters; }

        void SetGpsSpeed(float gps_speed_in_mps) { gps_speed_ = gps_speed_in_mps * 2.23694; }

        void SetPlaneNumber(int num) { plane_number_ = num; }
        void SetLogNumber(int num) { log_number_ = num; }

        void SetOrientation(float q0, float q1, float q2, float q3) {
            q0_ = q0;
            q1_ = q1;
            q2_ = q2;
            q3_ = q3;
        }

        void SetAcceleration(float x, float y, float z) {
            x_accel_ = x/9.81;
            y_accel_ = y/9.81;
            z_accel_ = z/9.81 - 1; // minus one since normal G is 1.0
        }

        void SetAutonomous(int autonomous) { is_autonomous_ = autonomous; }

        void SetServoCommands(float throttle, float elevonL, float elevonR) {
            throttle_ = throttle;
            elevonL_ = elevonL;
            elevonR_ = 100-elevonR; // because the servos are mounted in opposite directions
        }

        int GetClutterLevel() { return clutter_level_; }
        void SetClutterLevel(int clutter_level) { clutter_level_ = clutter_level; }

        void SetVideoNumber(int video_number) { video_number_ = video_number; }

        void SetGpsHeading(float gps_heading) { gps_heading_ = gps_heading; }

        void SetBatteryVoltage(float voltage) { battery_voltage_ = voltage; }

        void SetPitchRangeOfLens(float pitch_range_of_lens) { pitch_range_of_lens_ = pitch_range_of_lens; }
        float GetPitchRangeOfLens() { return pitch_range_of_lens_; }

        void SetFrameNumber(int frame_number_in) { frame_number_ = frame_number_in; }

        void SetTimestamp(long timestamp) { timestamp_ = timestamp; }

        void SetTrajectoryNumber(int traj_number) { traj_number_ = traj_number; }

        void SetStateMachineState(std::string state) { state_machine_state_ = state; }

        void SetUCommand(double left_elevon, double right_elevon, double throttle) {
            u0_left_elevon_ = left_elevon;
            u0_right_elevon_ = right_elevon;
            u0_throttle_ = throttle;
        }

        void SetImageScaling(float scale_factor) { scale_factor_ = scale_factor; }
        int GetImageScaling() { return scale_factor_; }

        int GetVideoNumber() { return video_number_; }
        int GetFrameNumber() { return frame_number_; }

        void DrawHud(InputArray _input_image, OutputArray _output_image);

};

#endif

max_stars_repo_name: titanomachy/flight

max_issues_repo_name: qiuwenhui/flight

max_forks_repo_name: qiuwenhui/flight


text:
///////////////////////////////////
#include <boost/test/unit_test.hpp>
///////////////////////////
#include "distancefixture.h"
/////////////////////////
#include <indivcluster.h>
//////////////////////
using namespace std;
using namespace info;
/////////////////////////////
BOOST_FIXTURE_TEST_SUITE(IndivClusterTestSuite, DistanceFixture)
;
BOOST_AUTO_TEST_CASE(testIndivCluster) {
	IIndivProvider *pProvider = m_provider.get();
	BOOST_REQUIRE(pProvider != nullptr);
	IndivDistanceMap *pMap = m_odistances.get();
	BOOST_REQUIRE(pMap != nullptr);
	IntType aIndex1 = 100, aIndex2 = 200;
	IndivCluster oCluster1(pProvider, aIndex1);
	IndivCluster oCluster2(pProvider, aIndex2);
	size_t nc = 0;
	bool bRet = pProvider->indivs_count(nc);
	BOOST_REQUIRE(bRet);
	BOOST_REQUIRE(nc > 1);
	for (size_t i = 0; i < nc; i += 2) {
		Indiv oInd1;
		if (!pProvider->find_indiv_at(i, oInd1)) {
			break;
		}
		oCluster1.add(oInd1);
		Indiv oInd2;
		if (!pProvider->find_indiv_at(i + 1, oInd2)) {
			break;
		}
		oCluster2.add(oInd2);
	}// i
	oCluster1.update_center();
	oCluster2.update_center();
	//
	double fintra = 0, finter = 0;
	bRet = oCluster1.intra_inertia(fintra);
	BOOST_CHECK(bRet);
	BOOST_CHECK(fintra > 0);
	bRet = oCluster1.inter_inertia(oCluster2, finter);
	BOOST_CHECK(bRet);
	BOOST_CHECK(finter > 0);
	//
	double dd = 0;
	ClusterAppendMode mode = ClusterAppendMode::modeInvalid;
	bRet = oCluster1.min_distance(oCluster2,dd, mode);
	BOOST_CHECK(bRet);
	BOOST_CHECK(mode != ClusterAppendMode::modeInvalid);
	BOOST_CHECK(dd > 0);
	oCluster1.add(oCluster2, mode);
	oCluster1.update_center();
	//
	for (size_t i = 0; i < nc; i += 2) {
		Indiv oInd;
		if (!pProvider->find_indiv_at(i, oInd)) {
			break;
		}
		double d1 = oCluster1.distance(oInd);
		BOOST_CHECK(d1 > 0);
		double d2 = oCluster2.distance(oInd);
		BOOST_CHECK(d2 > 0);
	}// i
} //testStatInfo

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: boubad/CygProjects

max_issues_repo_name: boubad/CygProjects

max_forks_repo_name: boubad/CygProjects


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

/*
 Copyright (C) 2007 Ferdinando Ametrano

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

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

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

/*! \file volcube.hpp
    \brief Interest rate (optionlet/swaption) volatility cube
*/

#ifndef quantlib_volatility_cube_h
#define quantlib_volatility_cube_h

#include <ql/handle.hpp>
#include <boost/shared_ptr.hpp>
#include <vector>

namespace QuantLib {

    class Period;
    class AbcdAtmVolCurve;
    class InterestRateVolSurface;
    class InterestRateIndex;

    class VolatilityCube {
      public:
        VolatilityCube(const std::vector<Handle<InterestRateVolSurface> >&,
                       const std::vector<Handle<AbcdAtmVolCurve> >&);
        const Period& minIndexTenor() const;
        const Period& maxIndexTenor() const;
        const std::vector<Handle<InterestRateVolSurface> >& surfaces() const;
        const std::vector<Handle<AbcdAtmVolCurve> >& curves() const;
      protected:
        std::vector<Handle<InterestRateVolSurface> > surfaces_;
        std::vector<Handle<AbcdAtmVolCurve> > curves_;
    };

    // inline

    inline const std::vector<Handle<InterestRateVolSurface> >&
    VolatilityCube::surfaces() const {
        return surfaces_;
    }

    inline const std::vector<Handle<AbcdAtmVolCurve> >&
    VolatilityCube::curves() const {
        return curves_;
    }

}

#endif

max_stars_repo_name: sfondi/QuantLib

max_issues_repo_name: sfondi/QuantLib

max_forks_repo_name: sfondi/QuantLib


text:
#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 12/14/2019, 10:43:31 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
ll MOD{0};
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{x % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
istream &operator>>(istream &stream, Mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const Mint &a) { return stream << a.x; }

// ----- main() -----

// I wrote this code referring to yataka1999-san's solution
// https://atcoder.jp/contests/agc035/submissions/6380939

Mint solve_even(ll N, ll K);
Mint solve_odd(ll N, ll K);

Mint solve_even(ll N, ll K)
{
  Mint ans{1};
  for (auto t = 0LL; t < 2; t++)
  {
    auto L{(N - t + 1) / 2};
    vector<Mint> to(L + 1), from(L + 1);
    to[0] = 1;
    for (auto i = 0LL; i < L; i++)
    {
      swap(to, from);
      to = vector<Mint>(L + 1);
      for (auto j = 0LL; j <= i; j++)
      {
        to[j + 1] += from[j];
        to[0] += from[j];
      }
      for (auto j = K / 2 + 1; j <= i + 1; j++)
      {
        to[j] = 0;
      }
    }
    Mint sum{0};
    for (auto j = 0LL; j <= L; j++)
    {
      sum += to[j];
    }
    ans *= sum;
  }
  return ans;
}

Mint solve_odd(ll N, ll K)
{
  vector<vector<vector<Mint>>> from(N + 1, vector<vector<Mint>>(N + 1, vector<Mint>(N + 1)));
  vector<vector<vector<Mint>>> to(N + 1, vector<vector<Mint>>(N + 1, vector<Mint>(N + 1)));
  to[0][0][N] = 1;
  for (auto i = 0LL; i < N; i++)
  {
    swap(to, from);
    to = vector<vector<vector<Mint>>>(N + 1, vector<vector<Mint>>(N + 1, vector<Mint>(N + 1)));
    auto even{i / 2 + 1};
    auto odd{(i + 1) / 2};
    for (auto j = 0LL; j <= even; j++)
    {
      for (auto k = 0LL; k <= odd; k++)
      {
        for (auto t = i; t <= N; t++)
        {
          if (from[j][k][t] == 0)
          {
            continue;
          }
          auto dst{(t % 2 == i % 2) ? N : t};
          to[0][j][dst] += from[j][k][t];
          if (t != i)
          {
            dst = j >= K / 2 + 1 ? min(t, i - 2 * k + K) : t;
            to[k + 1][j][dst] += from[j][k][t];
          }
        }
      }
    }
  }
  Mint ans{0};
  for (auto j = 0LL; j <= N; j++)
  {
    for (auto k = 0LL; k <= N; k++)
    {
      ans += to[j][k][N];
    }
  }
  return ans;
}

int main()
{
  ll N, K;
  cin >> N >> K >> MOD;
  if (K % 2 == 0)
  {
    cout << solve_even(N, K) << endl;
  }
  else
  {
    cout << solve_odd(N, K) << endl;
  }
}

max_stars_repo_name: kazunetakahashi/atcoder

max_issues_repo_name: kazunetakahashi/atcoder

max_forks_repo_name: kazunetakahashi/atcoder