text:
#include "software/ai/hl/stp/stp.h"

#include <google/protobuf/map.h>
#include <munkres/munkres.h>

#include <algorithm>
#include <boost/bind.hpp>
#include <chrono>
#include <exception>
#include <random>

#include "proto/play_info_msg.pb.h"
#include "shared/parameter/cpp_dynamic_parameters.h"
#include "software/ai/hl/stp/play/halt_play.h"
#include "software/ai/hl/stp/play/play.h"
#include "software/ai/hl/stp/tactic/all_tactics.h"
#include "software/ai/hl/stp/tactic/tactic.h"
#include "software/ai/intent/stop_intent.h"
#include "software/ai/motion_constraint/motion_constraint_set_builder.h"
#include "software/logger/logger.h"
#include "software/util/generic_factory/generic_factory.h"
#include "software/util/typename/typename.h"

STP::STP(std::shared_ptr<const AiConfig> ai_config)
    : robot_tactic_assignment(),
      ai_config(ai_config),
      goalie_tactic(std::make_shared<GoalieTactic>(ai_config)),
      stop_tactics(),
      current_play(std::make_unique<HaltPlay>(ai_config)),
      fsm(std::make_unique<FSM<PlaySelectionFSM>>(PlaySelectionFSM{ai_config})),
      override_play(nullptr)
{
    ai_config->getAiControlConfig()->getCurrentAiPlay()->registerCallbackFunction(
        [this, ai_config](std::string new_override_play_name) {
            if (ai_config->getAiControlConfig()->getOverrideAiPlay()->value())
            {
                overridePlayFromName(new_override_play_name);
            }
        });

    ai_config->getAiControlConfig()->getOverrideAiPlay()->registerCallbackFunction(
        [this, ai_config](bool new_override_ai_play) {
            if (new_override_ai_play)
            {
                overridePlayFromName(
                    ai_config->getAiControlConfig()->getCurrentAiPlay()->value());
            }
        });

    for (unsigned int i = 0; i < MAX_ROBOT_IDS; i++)
    {
        stop_tactics.push_back(std::make_shared<StopTactic>(false));
    }
}

std::vector<std::unique_ptr<Intent>> STP::getIntentsFromCurrentPlay(const World& world)
{
    fsm->process_event(PlaySelectionFSM::Update(
        [this](std::unique_ptr<Play> play) { current_play = std::move(play); },
        world.gameState()));

    auto assignment_function = [this](const ConstPriorityTacticVector& tactics,
                                      const World& world,
                                      bool automatically_assign_goalie) {
        return assignRobotsToTactics(tactics, world, automatically_assign_goalie);
    };
    auto motion_constraint_function = [world](const Tactic& tactic) {
        return buildMotionConstraintSet(world.gameState(), tactic);
    };

    if (static_cast<bool>(override_play))
    {
        return override_play->get(assignment_function, motion_constraint_function, world,
                                  inter_play_communication,
                                  [this](InterPlayCommunication comm) {
                                      inter_play_communication = std::move(comm);
                                  });
    }
    else
    {
        return current_play->get(assignment_function, motion_constraint_function, world,
                                 inter_play_communication,
                                 [this](InterPlayCommunication comm) {
                                     inter_play_communication = std::move(comm);
                                 });
    }
}

std::vector<std::unique_ptr<Intent>> STP::getIntents(const World& world)
{
    auto intents = getIntentsFromCurrentPlay(world);

    auto all_tactics = stop_tactics;
    all_tactics.push_back(goalie_tactic);
    for (auto tactic : all_tactics)
    {
        auto iter = robot_tactic_assignment.find(tactic);
        if (iter != robot_tactic_assignment.end())
        {
            auto intent = tactic->get(iter->second, world);
            intent->setMotionConstraints(
                buildMotionConstraintSet(world.gameState(), *tactic));
            intents.push_back(std::move(intent));
        }
    }

    return intents;
}

TbotsProto::PlayInfo STP::getPlayInfo()
{
    std::string info_play_name = objectTypeName(*current_play);
    TbotsProto::PlayInfo info;
    info.mutable_play()->set_play_name(info_play_name);

    for (const auto& [tactic, robot] : robot_tactic_assignment)
    {
        TbotsProto::PlayInfo_Tactic tactic_msg;
        tactic_msg.set_tactic_name(objectTypeName(*tactic));
        tactic_msg.set_tactic_fsm_state(tactic->getFSMState());
        (*info.mutable_robot_tactic_assignment())[robot.id()] = tactic_msg;
    }

    return info;
}

std::map<std::shared_ptr<const Tactic>, Robot> STP::assignRobotsToTactics(
    ConstPriorityTacticVector tactics, const World& world,
    bool automatically_assign_goalie)
{
    robot_tactic_assignment.clear();

    std::optional<Robot> goalie_robot = world.friendlyTeam().goalie();
    std::vector<Robot> robots         = world.friendlyTeam().getAllRobots();

    if (goalie_robot && automatically_assign_goalie)
    {
        if (goalie_robot.has_value())
        {
            robot_tactic_assignment.emplace(goalie_tactic, goalie_robot.value());

            robots.erase(std::remove(robots.begin(), robots.end(), goalie_robot.value()),
                         robots.end());
        }
        else if (world.friendlyTeam().getGoalieId().has_value())
        {
            LOG(WARNING) << "Robot not found for goalie ID: "
                         << std::to_string(world.friendlyTeam().getGoalieId().value())
                         << std::endl;
        }
        else
        {
            LOG(WARNING) << "No goalie ID set!" << std::endl;
        }
    }

    // This functions optimizes the assignment of robots to tactics by minimizing
    // the total cost of assignment using the Hungarian algorithm
    // (also known as the Munkres algorithm)
    // https://en.wikipedia.org/wiki/Hungarian_algorithm
    //
    // https://github.com/saebyn/munkres-cpp is the implementation of the Hungarian
    // algorithm that we use here
    for (unsigned int i = 0; i < tactics.size(); i++)
    {
        auto tactic_vector = tactics[i];
        size_t num_tactics = tactic_vector.size();

        if (robots.size() < tactic_vector.size())
        {
            // We do not have enough robots to assign all the tactics to. We "drop"
            // (aka don't assign) the tactics at the end of the vector since they are
            // considered lower priority
            tactic_vector.resize(robots.size());
            num_tactics = tactic_vector.size();
        }
        else if (i == (tactics.size() - 1))
        {
            // If assigning the last tactic vector, then assign rest of robots with
            // StopTactics
            for (unsigned int i = 0; i < (robots.size() - num_tactics); i++)
            {
                tactic_vector.push_back(stop_tactics[i]);
            }
        }

        size_t num_rows = robots.size();
        size_t num_cols = tactic_vector.size();

        // The Matrix constructor will assert if the rows and columns of the matrix are
        // not >= 1, so we perform that check first and skip over this tactic_vector if
        // it is empty. This represents the cases where there are either no tactics or no
        // robots
        if (num_rows == 0 || num_cols == 0)
        {
            continue;
        }

        // The rows of the matrix are the "workers" (the robots) and the columns are the
        // "jobs" (the Tactics).
        Matrix<double> matrix(num_rows, num_cols);

        // Initialize the matrix with the cost of assigning each Robot to each Tactic
        for (size_t row = 0; row < num_rows; row++)
        {
            for (size_t col = 0; col < num_cols; col++)
            {
                Robot robot                           = robots.at(row);
                std::shared_ptr<const Tactic>& tactic = tactic_vector.at(col);
                double robot_cost_for_tactic = tactic->calculateRobotCost(robot, world);

                std::set<RobotCapability> required_capabilities =
                    tactic->robotCapabilityRequirements();
                std::set<RobotCapability> robot_capabilities =
                    robot.getAvailableCapabilities();
                std::set<RobotCapability> missing_capabilities;
                std::set_difference(
                    required_capabilities.begin(), required_capabilities.end(),
                    robot_capabilities.begin(), robot_capabilities.end(),
                    std::inserter(missing_capabilities, missing_capabilities.begin()));

                if (missing_capabilities.size() > 0)
                {
                    matrix(row, col) = robot_cost_for_tactic + 10.0f;
                }
                else
                {
                    // capability requirements are satisfied, use real cost
                    matrix(row, col) = robot_cost_for_tactic;
                }
            }
        }

        // Apply the Munkres/Hungarian algorithm to the matrix.
        Munkres<double> m;
        m.solve(matrix);

        // The Munkres matrix gets solved such that there will be exactly one 0 in every
        // row and exactly one 0 in every column. All other values will be -1. The 0's
        // indicate the "workers" and "jobs" (robots and tactics for us) that are most
        // optimally paired together
        //
        // Example matrices:
        //        -1, 0,-1,         and            0,-1,
        //         0,-1,-1,                       -1, 0,
        //        -1,-1, 0,
        auto remaining_robots = robots;

        for (size_t row = 0; row < num_rows; row++)
        {
            for (size_t col = 0; col < num_cols; col++)
            {
                auto val = matrix(row, col);
                if (val == 0)
                {
                    robot_tactic_assignment.emplace(tactic_vector.at(col),
                                                    robots.at(row));
                    remaining_robots.erase(
                        std::remove_if(remaining_robots.begin(), remaining_robots.end(),
                                       [robots, row](const Robot& robot) {
                                           return robot.id() == robots.at(row).id();
                                       }),
                        remaining_robots.end());
                    break;
                }
            }
        }

        robots = remaining_robots;
    }

    return robot_tactic_assignment;
}

void STP::overridePlay(std::unique_ptr<Play> play)
{
    override_play = std::move(play);
}

void STP::overridePlayFromName(std::string name)
{
    overridePlay(GenericFactory<std::string, Play, AiConfig>::create(name, ai_config));
}


text:
// Copyright (c) 2015-2018 Daniel Cooke
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#ifndef variational_bayes_mixture_model_hpp
#define variational_bayes_mixture_model_hpp

#include <array>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iterator>
#include <cstddef>
#include <utility>
#include <cassert>
#include <limits>

#include <boost/optional.hpp>
#include <boost/math/special_functions/digamma.hpp>

#include "utils/maths.hpp"
#include "core/models/haplotype_likelihood_cache.hpp"

/**
 *
 * This file contains an implementation of the Variational Bayes mixture model
 * used by some genotype models. The notation follows the documentation.
 *
 */

namespace octopus { namespace model {

// Types needed for Variational Bayes model

struct VariationalBayesParameters
{
    double epsilon;
    unsigned max_iterations;
};

using ProbabilityVector    = std::vector<double>;
using LogProbabilityVector = std::vector<double>;

template <std::size_t K>
using VBAlpha = std::array<double, K>;
template <std::size_t K>
using VBAlphaVector = std::vector<VBAlpha<K>>;

class VBReadLikelihoodArray
{
public:
    using BaseType = HaplotypeLikelihoodCache::LikelihoodVector;

    VBReadLikelihoodArray() = default;

    explicit VBReadLikelihoodArray(const BaseType&);

    VBReadLikelihoodArray(const VBReadLikelihoodArray&)            = default;
    VBReadLikelihoodArray& operator=(const VBReadLikelihoodArray&) = default;
    VBReadLikelihoodArray(VBReadLikelihoodArray&&)                 = default;
    VBReadLikelihoodArray& operator=(VBReadLikelihoodArray&&)      = default;

    ~VBReadLikelihoodArray() = default;

    void operator=(const BaseType&);
    void operator=(std::reference_wrapper<const BaseType>);
    std::size_t size() const noexcept;
    BaseType::const_iterator begin() const noexcept;
    BaseType::const_iterator end() const noexcept;
    double operator[](const std::size_t n) const noexcept;

private:
    const BaseType* likelihoods;
};

template <std::size_t K>
using VBGenotype = std::array<VBReadLikelihoodArray, K>; // One element per haplotype in genotype (i.e. K)
template <std::size_t K>
using VBGenotypeVector = std::vector<VBGenotype<K>>; // Per element per genotype
template <std::size_t K>
using VBReadLikelihoodMatrix = std::vector<VBGenotypeVector<K>>; // One element per sample

template <std::size_t K>
using VBTau = std::array<double, K>; // One element per haplotype in genotype (i.e. K)
template <std::size_t K>
using VBResponsabilityVector = std::vector<VBTau<K>>; // One element per genotype
template <std::size_t K>
using VBResponsabilityMatrix = std::vector<VBResponsabilityVector<K>>; // One element per sample

template <std::size_t K>
struct VBLatents
{
    ProbabilityVector genotype_posteriors;
    LogProbabilityVector genotype_log_posteriors;
    VBAlphaVector<K> alphas;
    VBResponsabilityMatrix<K> responsabilities;
};

// Main VB method

template <std::size_t K>
std::pair<VBLatents<K>, double>
run_variational_bayes(const VBAlphaVector<K>& prior_alphas,
                      const LogProbabilityVector& genotype_log_priors,
                      const VBReadLikelihoodMatrix<K>& log_likelihoods,
                      const VariationalBayesParameters& params,
                      std::vector<LogProbabilityVector> seeds);

namespace detail {

using VBInverseLikelihood = std::vector<double>; // One element per genotype
using VBInverseGenotype = std::vector<VBInverseLikelihood>; // One element per read
template <std::size_t K>
using VBInverseGenotypeVector = std::array<VBInverseGenotype, K>; // One element per haplotype in genotype
template <std::size_t K>
using VBInverseReadLikelihoodMatrix = std::vector<VBInverseGenotypeVector<K>>; // One element per sample

template <std::size_t K>
auto invert(const VBGenotypeVector<K>& likelihoods)
{
    static_assert(K > 0, "K == 0");
    const auto num_genotypes = likelihoods.size();
    assert(num_genotypes > 0);
    const auto num_reads = likelihoods.front().front().size();
    VBInverseGenotypeVector<K> result {};
    for (std::size_t k {0}; k < K; ++k) {
        result[k] = VBInverseGenotype(num_reads, VBInverseLikelihood(num_genotypes));
        for (std::size_t n {0}; n < num_reads; ++n) {
            for (std::size_t g {0}; g < num_genotypes; ++g) {
                result[k][n][g] = likelihoods[g][k][n];
            }
        }
    }
    return result;
}

template <std::size_t K>
auto invert(const VBReadLikelihoodMatrix<K>& matrix)
{
    VBInverseReadLikelihoodMatrix<K> result {};
    result.reserve(matrix.size());
    std::transform(std::cbegin(matrix), std::cend(matrix), std::back_inserter(result),
                   [] (const auto& v) { return invert(v); });
    return result;
}

inline ProbabilityVector& exp(const LogProbabilityVector& log_probabilities, ProbabilityVector& result) noexcept
{
    std::transform(std::cbegin(log_probabilities), std::cend(log_probabilities), std::begin(result),
                   [] (const auto lp) noexcept { return std::exp(lp); });
    return result;
}

inline ProbabilityVector exp(const LogProbabilityVector& log_probabilities)
{
    ProbabilityVector result(log_probabilities.size());
    return exp(log_probabilities, result);
}

inline auto sum(const VBAlpha<2>& alpha) noexcept
{
    return alpha[0] + alpha[1];
}

inline auto sum(const VBAlpha<3>& alpha) noexcept
{
    return alpha[0] + alpha[1] + alpha[2];
}

template <std::size_t K>
auto sum(const VBAlpha<K>& alpha) noexcept
{
    return std::accumulate(std::cbegin(alpha), std::cend(alpha), 0.0);
}

template <typename T>
inline auto digamma_diff(const T a, const T b)
{
    using boost::math::digamma;
    return digamma(a) - digamma(b);
}

template <typename T>
inline T log_sum_exp(const std::array<T, 1>& logs)
{
    return logs[0];
}

template <typename T>
inline T log_sum_exp(const std::array<T, 2>& logs)
{
    return maths::log_sum_exp(logs[0], logs[1]);
}

template <typename T>
inline T log_sum_exp(const std::array<T, 3>& logs)
{
    return maths::log_sum_exp(logs[0], logs[1], logs[2]);
}

template <typename T, std::size_t K>
T log_sum_exp(const std::array<T, K>& logs)
{
    return maths::log_sum_exp(logs);
}

template <std::size_t K>
auto count_reads(const VBGenotypeVector<K>& likelihoods) noexcept
{
    return likelihoods[0][0].size();
}

template <std::size_t K>
auto count_reads(const VBInverseGenotypeVector<K>& likelihoods) noexcept
{
    return likelihoods[0].size();
}

template <std::size_t K>
auto marginalise(const ProbabilityVector& distribution, const VBGenotypeVector<K>& likelihoods,
                 const unsigned k, const std::size_t n) noexcept
{
    return std::inner_product(std::cbegin(distribution), std::cend(distribution),
                              std::cbegin(likelihoods), 0.0, std::plus<> {},
                              [k, n] (const auto p, const auto& haplotype_likelihoods) noexcept {
                                  return p * haplotype_likelihoods[k][n];
                              });
}

template <std::size_t K>
auto marginalise(const ProbabilityVector& distribution, const VBInverseGenotypeVector<K>& likelihoods,
                 const unsigned k, const std::size_t n) noexcept
{
    return std::inner_product(std::cbegin(distribution), std::cend(distribution), std::cbegin(likelihoods[k][n]), 0.0);
}

template <std::size_t K, typename VBLikelihoodVector_>
VBResponsabilityVector<K>
init_responsabilities(const VBAlpha<K>& prior_alphas,
                      const ProbabilityVector& genotype_probabilities,
                      const VBLikelihoodVector_& read_likelihoods)
{
    using T = typename VBAlpha<K>::value_type;
    std::array<T, K> al; // no need to keep recomputing this
    const auto a0 = sum(prior_alphas);
    for (unsigned k {0}; k < K; ++k) {
        al[k] = digamma_diff(prior_alphas[k], a0);
    }
    const auto N = count_reads(read_likelihoods);
    VBResponsabilityVector<K> result(N);
    std::array<T, K> ln_rho;
    for (std::size_t n {0}; n < N; ++n) {
        for (unsigned k {0}; k < K; ++k) {
            ln_rho[k] = al[k] + marginalise(genotype_probabilities, read_likelihoods, k, n);
        }
        const auto ln_rho_norm = log_sum_exp(ln_rho);
        for (unsigned k {0}; k < K; ++k) {
            result[n][k] = std::exp(ln_rho[k] - ln_rho_norm);
        }
    }
    return result;
}

template <std::size_t K, typename VBLikelihoodMatrix>
VBResponsabilityMatrix<K>
init_responsabilities(const VBAlphaVector<K>& prior_alphas,
                      const ProbabilityVector& genotype_probabilities,
                      const VBLikelihoodMatrix& read_likelihoods)
{
    const auto S = read_likelihoods.size(); // num samples
    VBResponsabilityMatrix<K> result{};
    result.reserve(S);
    for (std::size_t s {0}; s < S; ++s) {
        result.push_back(init_responsabilities(prior_alphas[s], genotype_probabilities, read_likelihoods[s]));
    }
    return result;
}

template <std::size_t K, typename VBLikelihoodVector_>
void update_responsabilities(VBResponsabilityVector<K>& result,
                             const VBAlpha<K>& posterior_alphas,
                             const ProbabilityVector& genotype_probabilities,
                             const VBLikelihoodVector_& read_likelihoods)
{
    using T = typename VBAlpha<K>::value_type;
    std::array<T, K> al;
    const auto a0 = sum(posterior_alphas);
    for (unsigned k {0}; k < K; ++k) {
        al[k] = digamma_diff(posterior_alphas[k], a0);
    }
    const auto N = count_reads(read_likelihoods);
    std::array<T, K> ln_rho;
    for (std::size_t n {0}; n < N; ++n) {
        for (unsigned k {0}; k < K; ++k) {
            ln_rho[k] = al[k] + marginalise(genotype_probabilities, read_likelihoods, k, n);
        }
        const auto ln_rho_norm = log_sum_exp(ln_rho);
        for (unsigned k {0}; k < K; ++k) {
            result[n][k] = std::exp(ln_rho[k] - ln_rho_norm);
        }
    }
}

// same as init_responsabilities but in-place
template <std::size_t K, typename VBLikelihoodMatrix>
void update_responsabilities(VBResponsabilityMatrix<K>& result,
                             const VBAlphaVector<K>& posterior_alphas,
                             const ProbabilityVector& genotype_probabilities,
                             const VBLikelihoodMatrix& read_likelihoods)
{
    const auto S = read_likelihoods.size();
    for (std::size_t s {0}; s < S; ++s) {
        update_responsabilities(result[s], posterior_alphas[s], genotype_probabilities, read_likelihoods[s]);
    }
}

template <std::size_t K>
auto sum(const VBResponsabilityVector<K>& taus, const unsigned k) noexcept
{
    return std::accumulate(std::cbegin(taus), std::cend(taus), 0.0,
                           [k] (const auto curr, const auto& tau) noexcept {
                               return curr + tau[k];
                           });
}

template <std::size_t K>
void update_alpha(VBAlpha<K>& alpha, const VBAlpha<K>& prior_alpha,
                  const VBResponsabilityVector<K>& taus) noexcept
{
    for (unsigned k {0}; k < K; ++k) {
        alpha[k] = prior_alpha[k] + sum(taus, k);
    }
}

template <std::size_t K>
void update_alphas(VBAlphaVector<K>& alphas, const VBAlphaVector<K>& prior_alphas,
                   const VBResponsabilityMatrix<K>& responsabilities) noexcept
{
    const auto S = alphas.size();
    assert(S == prior_alphas.size() && S == responsabilities.size());
    for (std::size_t s {0}; s < S; ++s) {
        update_alpha(alphas[s], prior_alphas[s], responsabilities[s]);
    }
}

template <std::size_t K>
auto marginalise(const VBResponsabilityVector<K>& responsabilities,
                 const VBGenotypeVector<K>& read_likelihoods,
                 const std::size_t g) noexcept
{
    double result {0};
    const auto N = read_likelihoods[0][0].size(); // num reads in sample s
    assert(responsabilities.size() == N);
    assert(responsabilities[0].size() == K && read_likelihoods[g].size() == K);
    for (unsigned k {0}; k < K; ++k) {
        const auto& k_likelihoods = read_likelihoods[g][k];
        for (std::size_t n {0}; n < N; ++n) {
            result += responsabilities[n][k] * k_likelihoods[n];
        }
    }
    return result;
}

template <std::size_t K>
auto marginalise(const VBResponsabilityMatrix<K>& responsabilities,
                 const VBReadLikelihoodMatrix<K>& read_likelihoods,
                 const std::size_t g) noexcept
{
    double result {0};
    const auto S = read_likelihoods.size(); // num samples
    assert(S == responsabilities.size());
    for (std::size_t s {0}; s < S; ++s) {
        result += marginalise(responsabilities[s], read_likelihoods[s], g);
    }
    return result;
}

template <std::size_t K>
void update_genotype_log_posteriors(LogProbabilityVector& result,
                                    const LogProbabilityVector& genotype_log_priors,
                                    const VBResponsabilityMatrix<K>& responsabilities,
                                    const VBReadLikelihoodMatrix<K>& read_likelihoods)
{
    const auto G = result.size();
    for (std::size_t g {0}; g < G; ++g) {
        result[g] = genotype_log_priors[g] + marginalise(responsabilities, read_likelihoods, g);
    }
    maths::normalise_logs(result);
}

inline auto max_change(const VBAlpha<2>& lhs, const VBAlpha<2>& rhs) noexcept
{
    return std::max(std::abs(lhs.front() - rhs.front()), std::abs(lhs.back() - rhs.back()));
}

inline auto max_change(const VBAlpha<3>& lhs, const VBAlpha<3>& rhs) noexcept
{
    return std::max({std::abs(lhs[0] - rhs[0]), std::abs(lhs[1] - rhs[1]), std::abs(lhs[2] - rhs[2])});
}

template <std::size_t K>
auto max_change(const VBAlpha<K>& lhs, const VBAlpha<K>& rhs) noexcept
{
    double result {0};
    for (std::size_t k {0}; k < K; ++k) {
        const auto curr = std::abs(lhs[k] - rhs[k]);
        if (curr > result) result = curr;
    }
    return result;
}

template <std::size_t K>
auto max_change(const VBAlphaVector<K>& prior_alphas, const VBAlphaVector<K>& posterior_alphas) noexcept
{
    const auto S = prior_alphas.size();
    assert(S == posterior_alphas.size());
    double result {0};
    for (std::size_t s {0}; s < S; ++s) {
        const auto curr = max_change(prior_alphas[s], posterior_alphas[s]);
        if (curr > result) result = curr;
    }
    return result;
}

template <std::size_t K>
std::pair<bool, double> check_convergence(const VBAlphaVector<K>& prior_alphas,
                                          const VBAlphaVector<K>& posterior_alphas,
                                          const double prev_max_change,
                                          const double epsilon) noexcept
{
    const auto new_max_change = max_change(prior_alphas, posterior_alphas);
    return std::make_pair(std::abs(new_max_change - prev_max_change) < epsilon, new_max_change);
}

template <std::size_t K>
auto entropy(const VBTau<K>& tau) noexcept
{
    return -std::accumulate(std::cbegin(tau), std::cend(tau), 0.0,
                            [] (const auto curr, const auto t) noexcept { return curr + (t * std::log(t)); });
}

// E [ln q(Z_s)]
template <std::size_t K>
auto sum_entropies(const VBResponsabilityVector<K>& taus) noexcept
{
    return std::accumulate(std::cbegin(taus), std::cend(taus), 0.0,
                           [] (const auto curr, const auto& tau) noexcept { return curr + entropy(tau); });
}

template <std::size_t K>
auto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,
                                    const VBAlphaVector<K>& posterior_alphas,
                                    const LogProbabilityVector& genotype_log_priors,
                                    const ProbabilityVector& genotype_posteriors,
                                    const LogProbabilityVector& genotype_log_posteriors,
                                    const VBResponsabilityMatrix<K>& taus,
                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,
                                    const boost::optional<double> max_posterior_skip = boost::none)
{
    const auto G = genotype_log_priors.size();
    const auto S = log_likelihoods.size();
    double result {0};
    for (std::size_t g {0}; g < G; ++g) {
        if (!max_posterior_skip || genotype_posteriors[g] >= *max_posterior_skip) {
            auto w = genotype_log_priors[g] - genotype_log_posteriors[g];
            for (std::size_t s {0}; s < S; ++s) {
                const auto N_s = taus[s].size();
                for (std::size_t k {0}; k < K; ++k) {
                    for (std::size_t n {0}; n < N_s; ++n) {
                        w += taus[s][n][k] * log_likelihoods[s][g][k][n];
                    }
                }
            }
            result += genotype_posteriors[g] * w;
        }
    }
    for (std::size_t s {0}; s < S; ++s) {
        result += (maths::log_beta(posterior_alphas[s]) - maths::log_beta(prior_alphas[s]));
        result += sum_entropies(taus[s]);
    }
    return result;
}

// Main algorithm - single seed

// Starting iteration with given genotype_log_posteriors
template <std::size_t K, typename VBLikelihoodMatrix1, typename VBLikelihoodMatrix2>
VBLatents<K>
run_variational_bayes(const VBAlphaVector<K>& prior_alphas,
                      const LogProbabilityVector& genotype_log_priors,
                      const VBLikelihoodMatrix1& log_likelihoods1,
                      const VBLikelihoodMatrix2& log_likelihoods2,
                      LogProbabilityVector genotype_log_posteriors,
                      const VariationalBayesParameters& params)
{
    assert(!prior_alphas.empty());
    assert(!genotype_log_priors.empty());
    assert(!log_likelihoods1.empty());
    assert(log_likelihoods1.size() == log_likelihoods2.size());
    assert(prior_alphas.size() == log_likelihoods1.size()); // num samples
    assert(log_likelihoods1.front().size() == genotype_log_priors.size()); // num genotypes
    assert(params.max_iterations > 0);
    auto genotype_posteriors = exp(genotype_log_posteriors);
    auto posterior_alphas = prior_alphas;
    auto responsabilities = init_responsabilities<K>(posterior_alphas, genotype_posteriors, log_likelihoods2);
    assert(responsabilities.size() == log_likelihoods1.size()); // num samples
    auto prev_evidence = std::numeric_limits<double>::lowest();
    bool is_converged {};
    double max_change {};
    for (unsigned i {0}; i < params.max_iterations; ++i) {
        update_genotype_log_posteriors(genotype_log_posteriors, genotype_log_priors, responsabilities, log_likelihoods1);
        exp(genotype_log_posteriors, genotype_posteriors);
        update_alphas(posterior_alphas, prior_alphas, responsabilities);
        update_responsabilities(responsabilities, posterior_alphas, genotype_posteriors, log_likelihoods2);
        std::tie(is_converged, max_change) = check_convergence(prior_alphas, posterior_alphas, max_change, params.epsilon);
        if (is_converged) break;
        auto curr_evidence = calculate_evidence_lower_bound(prior_alphas, posterior_alphas, genotype_log_priors,
                                                            genotype_posteriors, genotype_log_posteriors, responsabilities,
                                                            log_likelihoods1, 1e-10);
        if (curr_evidence <= prev_evidence || (curr_evidence - prev_evidence) < params.epsilon) break;
        prev_evidence = curr_evidence;
    }
    return VBLatents<K> {
        std::move(genotype_posteriors), std::move(genotype_log_posteriors),
        std::move(posterior_alphas), std::move(responsabilities)
    };
}

// Not using inverted log likelihoods
template <std::size_t K>
VBLatents<K>
run_variational_bayes(const VBAlphaVector<K>& prior_alphas,
                      const LogProbabilityVector& genotype_log_priors,
                      const VBReadLikelihoodMatrix<K>& log_likelihoods,
                      LogProbabilityVector genotype_log_posteriors,
                      const VariationalBayesParameters& params)
{
    return run_variational_bayes(prior_alphas, genotype_log_posteriors, log_likelihoods,
                                 log_likelihoods, genotype_log_posteriors, params);
}

// Main algorithm - multiple seed

template <std::size_t K>
bool run_vb_with_matrix_inversion(const VBReadLikelihoodMatrix<K>& log_likelihoods,
                                  const VariationalBayesParameters& params,
                                  const std::vector<LogProbabilityVector>& seeds) noexcept
{
    return true;
}

template <std::size_t K>
std::vector<VBLatents<K>>
run_variational_bayes(const VBAlphaVector<K>& prior_alphas,
                      const LogProbabilityVector& genotype_log_priors,
                      const VBReadLikelihoodMatrix<K>& log_likelihoods,
                      const VariationalBayesParameters& params,
                      std::vector<LogProbabilityVector>&& seeds)
{
    std::vector<VBLatents<K>> result {};
    result.reserve(seeds.size());
    if (run_vb_with_matrix_inversion(log_likelihoods, params, seeds)) {
        const auto inverted_log_likelihoods = invert(log_likelihoods);
        for (auto& seed : seeds) {
            result.push_back(detail::run_variational_bayes(prior_alphas, genotype_log_priors,
                                                           log_likelihoods, inverted_log_likelihoods,
                                                           std::move(seed), params));
        }
    } else {
        for (auto& seed : seeds) {
            result.push_back(detail::run_variational_bayes(prior_alphas, genotype_log_priors,
                                                           log_likelihoods,
                                                           std::move(seed), params));
        }
    }
    return result;
}

// lower-bound calculation

template <std::size_t K>
auto calculate_evidence_lower_bound(const VBAlphaVector<K>& prior_alphas,
                                    const LogProbabilityVector& genotype_log_priors,
                                    const VBReadLikelihoodMatrix<K>& log_likelihoods,
                                    const VBLatents<K>& latents)
{
    return calculate_evidence_lower_bound(prior_alphas, latents.alphas, genotype_log_priors,
                                          latents.genotype_posteriors, latents.genotype_log_posteriors,
                                          latents.responsabilities, log_likelihoods);

}

template <std::size_t K>
std::pair<VBLatents<K>, double>
get_max_evidence_latents(const VBAlphaVector<K>& prior_alphas,
                         const LogProbabilityVector& genotype_log_priors,
                         const VBReadLikelihoodMatrix<K>& log_likelihoods,
                         std::vector<VBLatents<K>>&& latents)
{
    std::vector<double> seed_evidences(latents.size());
    std::transform(std::cbegin(latents), std::cend(latents), std::begin(seed_evidences),
                   [&] (const auto& seed_latents) {
                       return calculate_evidence_lower_bound(prior_alphas, genotype_log_priors, log_likelihoods, seed_latents);
                   });
    const auto max_itr = std::max_element(std::cbegin(seed_evidences), std::cend(seed_evidences));
    const auto max_idx = std::distance(std::cbegin(seed_evidences), max_itr);
    return std::make_pair(std::move(latents[max_idx]), *max_itr);
}

} // namespace detail

template <std::size_t K>
std::pair<VBLatents<K>, double>
run_variational_bayes(const VBAlphaVector<K>& prior_alphas,
                      const LogProbabilityVector& genotype_log_priors,
                      const VBReadLikelihoodMatrix<K>& log_likelihoods,
                      const VariationalBayesParameters& params,
                      std::vector<LogProbabilityVector> seeds)
{
    assert(!seeds.empty());
    auto latents = detail::run_variational_bayes(prior_alphas, genotype_log_priors, log_likelihoods, params, std::move(seeds));
    return detail::get_max_evidence_latents(prior_alphas, genotype_log_priors, log_likelihoods, std::move(latents));
}

inline VBReadLikelihoodArray::VBReadLikelihoodArray(const BaseType& underlying_likelihoods)
: likelihoods{std::addressof(underlying_likelihoods)} {}

inline void VBReadLikelihoodArray::operator=(const BaseType& other)
{
    likelihoods = std::addressof(other);
}

inline void VBReadLikelihoodArray::operator=(std::reference_wrapper<const BaseType> other)
{
    likelihoods = std::addressof(other.get());
}

inline std::size_t VBReadLikelihoodArray::size() const noexcept
{
    return likelihoods->size();
}

inline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::begin() const noexcept
{
    return likelihoods->begin();
}

inline VBReadLikelihoodArray::BaseType::const_iterator VBReadLikelihoodArray::end() const noexcept
{
    return likelihoods->end();
}

inline double VBReadLikelihoodArray::operator[](const std::size_t n) const noexcept
{
    return likelihoods->operator[](n);
}

} // namespace model
} // namespace octopus

#endif

ext: hpp

max_stars_repo_name: alimanfoo/octopus

max_issues_repo_name: alimanfoo/octopus

max_forks_repo_name: alimanfoo/octopus


text:
#include "Types.h"
#include <boost/asio/buffer.hpp>
#include <iostream>
#include <writer.hpp>
#include <fstream>
// #include <cfloat>

namespace asio = boost::asio;
using namespace detail;
using namespace std::chrono;
using namespace date;

template <typename T>
asio::mutable_buffer writeMessage(asio::mutable_buffer buf, const T& val,
                                  TestTypes::MsgType mType) {
    auto bufRest = buf + 10u;
    bufRest = write(bufRest, val);

    TestTypes::FixedHeader head;
    head.length = asio::buffer_size(bufRest) - asio::buffer_size(buf);
    head.msgType = mType;
    write(asio::buffer(buf), head);
    return bufRest;
}

int main(int argc, char* argv[]) {
    std::array<char, 1024> mainBuf;
    {
        std::ofstream serializedData;
        serializedData.open("data.bin", std::ios::out | std::ios::binary);

        auto req = TestTypes::DataRequest{"GOOGL", 1};

        auto tp = system_clock::now();
        sys_time<microseconds> currTimePoint =
            time_point_cast<microseconds>(tp);
        TestTypes::DataSeries data = {
            {2.5, -56.789, 5.56},
            {currTimePoint, currTimePoint + seconds{5},
             currTimePoint + seconds{7}}};

        for (auto i = 0u; i < data.dataPoints.size(); ++i) {
            std::cout << "Data value: " << data.dataPoints.at(i) << ", "
                << "Time point: " << data.timePoints.at(i) << '\n';
        }
        auto buf = writeMessage(asio::buffer(mainBuf), req,
                                TestTypes::MsgType::DataRequest);
        buf = writeMessage(buf, data, TestTypes::MsgType::DataSeries);

        auto sz = mainBuf.size()-asio::buffer_size(buf);
        std::cout<<"Write buffer size: " << sz <<'\n';
        serializedData.write(mainBuf.data(), sz);
        serializedData.close();
    }
    return 0;
}

ext: cpp

max_stars_repo_name: semirpuskarevic/serialization

max_issues_repo_name: semirpuskarevic/serialization

max_forks_repo_name: semirpuskarevic/serialization


text:
// Copyright 2020 Google LLC
//
// 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.

// [START functions_pubsub_system_test]
#include <google/cloud/pubsub/publisher.h>
#include <google/cloud/pubsub/topic_admin_client.h>
#include <boost/process.hpp>
#include <fmt/format.h>
#include <gmock/gmock.h>
#include <chrono>
#include <string>
#include <thread>

namespace {

namespace bp = ::boost::process;
namespace pubsub = ::google::cloud::pubsub;
using ::testing::AnyOf;
using ::testing::HasSubstr;

class PubsubSystemTest : public ::testing::Test {
 protected:
  void SetUp() override {
    // This test can only run if it is properly configured.
    auto const* project_id = std::getenv("GOOGLE_CLOUD_PROJECT");
    ASSERT_NE(project_id, nullptr);
    auto const* topic_id = std::getenv("TOPIC_ID");
    ASSERT_NE(topic_id, nullptr);
    auto const* service_id = std::getenv("SERVICE_ID");
    ASSERT_NE(service_id, nullptr);
    service_id_ = service_id;

    // Automatically setup the test environment, create the topic if it does
    // not exist.
    auto admin = pubsub::TopicAdminClient(pubsub::MakeTopicAdminConnection());
    topic_ = pubsub::Topic(project_id, topic_id);
    auto topic_metadata = admin.CreateTopic(pubsub::TopicBuilder(topic()));
    // If we get an error other than kAlreadyExists, abort the test.
    ASSERT_THAT(topic_metadata.status().code(),
                AnyOf(google::cloud::StatusCode::kOk,
                      google::cloud::StatusCode::kAlreadyExists));
  }

  void TearDown() override {}

  [[nodiscard]] pubsub::Topic const& topic() const { return topic_; }
  [[nodiscard]] std::string const& service_id() const { return service_id_; }

 private:
  pubsub::Topic topic_ = pubsub::Topic("--invalid--", "--invalid--");
  std::string service_id_;
};

TEST_F(PubsubSystemTest, Basic) {
  struct TestCases {
    std::string data;
    std::string expected;
  } cases[]{
      {"C++", "Hello C++"},
      {"World", "Hello World"},
  };

  auto publisher =
      pubsub::Publisher(pubsub::MakePublisherConnection(topic(), {}));

  for (auto const& test : cases) {
    SCOPED_TRACE("Testing for " + test.expected);
    auto id =
        publisher.Publish(pubsub::MessageBuilder().SetData(test.data).Build());
    publisher.Flush();
    EXPECT_TRUE(id.get().ok());

    std::vector<std::string> lines;
    // It may take a few seconds for the logs to propagate, so try a few times.
    using namespace std::chrono_literals;
    for (auto delay : {1s, 2s, 4s, 8s, 16s}) {
      bp::ipstream out;
      auto constexpr kProject = "--project={}";
      auto constexpr kLogFilter =
          "resource.type=cloud_run_revision AND "
          "resource.labels.service_name={} AND "
          "logName:stdout";
      auto reader = bp::child(bp::search_path("gcloud"), "logging", "read",
                              fmt::format(kProject, topic().project_id()),
                              fmt::format(kLogFilter, service_id()),
                              "--format=value(textPayload)", "--limit=1",
                              (bp::std_out & bp::std_err) > out);
      reader.wait();
      ASSERT_EQ(reader.exit_code(), 0);
      for (std::string l; std::getline(out, l);) lines.push_back(std::move(l));
      auto count = std::count_if(lines.begin(), lines.end(),
                                 [s = test.expected](auto l) {
                                   return l.find(s) != std::string::npos;
                                 });
      if (count != 0) break;
      std::this_thread::sleep_for(delay);
    }
    EXPECT_THAT(lines, Contains(HasSubstr(test.expected)));
  }
}

}  // namespace

// [END functions_pubsub_system_test]

ext: cc

max_issues_repo_name: devjgm/functions-framework-cpp

max_forks_repo_name: devjgm/functions-framework-cpp


text:
/**
 *  Copyright (C) 2015 Topology LP
 *
 *  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.
 */

#ifndef BONEFISH_WAMP_TRACE_HPP
#define BONEFISH_WAMP_TRACE_HPP

#include <boost/format.hpp>
#include <boost/preprocessor/comparison/greater.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/variadic/size.hpp>
#include <iostream>
#include <string.h>

namespace bonefish {
namespace trace {

extern bool _enabled;

inline bool is_enabled()
{
    return _enabled;
}

inline void set_enabled(bool is_enabled)
{
    _enabled = is_enabled;
}

inline const char* base_file_name(const char* file_path)
{
    const char* file_name = strrchr(file_path, '/');
    return file_name == nullptr ? file_path : file_name + 1;
}

} // namespace trace
} // namespace bonefish

// Macro for facilitating debug trace logging.
#define BONEFISH_TRACE(...) \
	BOOST_PP_IIF(BOOST_PP_GREATER(BOOST_PP_VARIADIC_SIZE(__VA_ARGS__), 1), BONEFISH_TRACE_ARGS(__VA_ARGS__), BONEFISH_TRACE_NOARGS(BOOST_PP_VARIADIC_ELEM(0, __VA_ARGS__)))

#define BONEFISH_TRACE_NOARGS(fmt) \
    if (bonefish::trace::is_enabled()) { \
        std::cerr << "[" << bonefish::trace::base_file_name(__FILE__) << ":" << __LINE__ << "][" << __FUNCTION__ << "] " \
                << boost::format(fmt) << std::endl; \
    }

#define BONEFISH_TRACE_ARGS(fmt, ...) \
    if (bonefish::trace::is_enabled()) { \
        std::cerr << "[" << bonefish::trace::base_file_name(__FILE__) << ":" << __LINE__ << "][" << __FUNCTION__ << "] " \
                << (boost::format(fmt) % __VA_ARGS__) << std::endl; \
    }

#endif // BONEFISH_WAMP_TRACE_HPP

max_stars_repo_name: aiwc/extlib-bonefish

max_issues_repo_name: aiwc/extlib-bonefish

max_forks_repo_name: aiwc/extlib-bonefish


text:
// Copyright (c) 2019 Graphcore Ltd. All rights reserved.
#define BOOST_TEST_MODULE Parallel0InplaceTest

#include <memory>
#include <vector>

#include <boost/test/unit_test.hpp>

#include <filereader.hpp>
#include <popart/builder.hpp>
#include <popart/dataflow.hpp>
#include <popart/inputshapeinfo.hpp>
#include <popart/ir.hpp>
#include <popart/op/identity.hpp>
#include <popart/op/l1.hpp>
#include <popart/sgd.hpp>
#include <popart/tensor.hpp>
#include <popart/tensorinfo.hpp>
#include <popart/tensornames.hpp>
#include <popart/tensors.hpp>
#include <popart/testdevice.hpp>

using namespace popart;

// confirm that when the Pattern is not enabled, nothing is made inplace
BOOST_AUTO_TEST_CASE(Inplace_basic0) {

  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset9();

  TensorInfo shape{"FLOAT", std::vector<int64_t>{1}};
  auto in0 = builder->addInputTensor(shape);
  auto h0  = aiOnnx.relu({in0});
  builder->setInplacePreferences(h0, {{"ReluInplace", 1e8}});
  auto h1  = aiOnnx.relu({h0});
  auto out = aiOnnx.relu({h1});
  auto l1  = builder->aiGraphcoreOpset1().l1loss({out}, 0.1);

  auto proto      = builder->getModelProto();
  auto modelProto = io::getModelFromString(proto);

  // Create the IR
  auto dataFlow  = DataFlow(1, {{out, AnchorReturnType("All")}});
  auto optimizer = ConstSGD(0.01);
  auto device    = createTestDevice(TEST_TARGET);

  Ir ir;
  ir.prepare({modelProto,
              InputShapeInfo(),
              dataFlow,
              l1,
              &optimizer,
              *device,
              {},
              Patterns(PatternsLevel::NoPatterns)
                  .enableRuntimeAsserts(false)
                  .enableInPlace(false)});

  // Check the ir
  auto opsOfTypeRelu = ir.opsOfType(Onnx::AiOnnx::OpSet9::Relu);
  BOOST_CHECK(opsOfTypeRelu.size() == 3);
  auto opsOfTypeReluInplace = ir.opsOfType(Onnx::CustomOperators::ReluInplace);
  BOOST_CHECK(opsOfTypeReluInplace.size() == 0);
}

// confirm that properties are transferred to the inplace Op
BOOST_AUTO_TEST_CASE(Inplace_basic1) {

  auto builder = Builder::create();
  auto aiOnnx  = builder->aiOnnxOpset9();

  TensorInfo shape{"FLOAT", std::vector<int64_t>{1}};
  auto in0 = builder->addInputTensor(shape);

  std::string relu0name = "allymacky";
  auto h0               = aiOnnx.relu({in0}, relu0name);
  int64_t relu0vGraph   = 16;
  builder->setInplacePreferences(h0, {{"ReluInplace", 1e8}});
  builder->virtualGraph(h0, relu0vGraph);

  std::string relu1name = "zipperzoo";
  auto h1               = aiOnnx.relu({h0}, relu1name);
  int64_t relu1vGraph   = 127;
  builder->setInplacePreferences(h1, {{"ReluInplace", 1e7}});
  builder->virtualGraph(h1, relu1vGraph);

  auto out = aiOnnx.relu({h1});
  builder->virtualGraph(out, 4);
  auto l1 = builder->aiGraphcoreOpset1().l1loss({out}, 0.1);
  builder->virtualGraph(l1, 4);

  auto proto      = builder->getModelProto();
  auto modelProto = io::getModelFromString(proto);

  // Create the IR
  auto dataFlow  = DataFlow(1, {{out, AnchorReturnType("All")}});
  auto optimizer = ConstSGD(0.01);
  auto device    = createTestDevice(TEST_TARGET);

  Ir ir;

  SessionOptions opts;
  opts.virtualGraphMode = VirtualGraphMode::Manual;
  ir.prepare({modelProto,
              InputShapeInfo(),
              dataFlow,
              l1,
              &optimizer,
              *device,
              opts,
              Patterns(PatternsLevel::NoPatterns)
                  .enableRuntimeAsserts(false)
                  .enableInPlace(true)});

  // Check the ir
  // first check that all 3 relus have been inplaced
  auto opsOfTypeRelu = ir.opsOfType(Onnx::AiOnnx::OpSet9::Relu);
  BOOST_CHECK(opsOfTypeRelu.size() == 0);
  auto opsOfTypeReluInplace = ir.opsOfType(Onnx::CustomOperators::ReluInplace);
  BOOST_CHECK(opsOfTypeReluInplace.size() == 3);

  auto inplaceOps = ir.opsOfType(Onnx::CustomOperators::ReluInplace);
  // we have already confirmed that there are 2 inplace ops:
  if (inplaceOps.size() == 2) {
    if (inplaceOps[0]->output->id(0) == h1) {
      std::swap(inplaceOps[0], inplaceOps[1]);
    }

    // confirm the output names are h0 and h1
    BOOST_CHECK(inplaceOps[0]->output->id(0) == h0);
    BOOST_CHECK(inplaceOps[1]->output->id(0) == h1);

    // confirm the virtualGraph numbers are relu0vGraph and relu1vGraph
    BOOST_CHECK(inplaceOps[0]->settings.vgraphId == relu0vGraph);
    BOOST_CHECK(inplaceOps[1]->settings.vgraphId == relu1vGraph);

    // confirm the names contain relu0name and relu1name in them
    BOOST_CHECK(inplaceOps[0]->settings.name.find(relu0name) !=
                std::string::npos);
    BOOST_CHECK(inplaceOps[1]->settings.name.find(relu1name) !=
                std::string::npos);

    // as for the recompute flag, i suspect that
    // this doesn't make sense for inplace ops
  }
}


text:
/*==============================================================================
  Copyright (c) 2017, 2018 Matt Calabrese

  Distributed under the Boost Software License, Version 1.0. (See accompanying
  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/

#ifndef ARGOT_GEN_CONCEPT_BODY_DETAIL_IS_PARENTHESIZED_COMMA_HPP_
#define ARGOT_GEN_CONCEPT_BODY_DETAIL_IS_PARENTHESIZED_COMMA_HPP_

#include <boost/preprocessor/control/iif.hpp>

// TODO(mattcalabrese) Define
#define ARGOT_GEN_DETAIL_IS_PARENTHESIZED_COMMA( ... )                         \

#endif  // ARGOT_GEN_CONCEPT_BODY_DETAIL_IS_PARENTHESIZED_COMMA_HPP_

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
// xml.hpp
//
// Copyright (c) 2010 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanyiong file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef XML_HPP_INCLUDED
#define XML_HPP_INCLUDED

#include <string>
#include <vector>
#include <iosfwd>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <boost/property_tree/detail/rapidxml.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>

#include "html_writer.hpp"

namespace boost {
namespace regression {

class xml_error : public std::exception {
public:
    explicit xml_error(const std::string& m) : message(m) {}
    virtual ~xml_error() throw() {}
    virtual const char * what() const throw() { return message.c_str(); }
private:
    std::string message;
};

typedef boost::property_tree::detail::rapidxml::xml_node<> node_type;
typedef boost::property_tree::detail::rapidxml::xml_attribute<> attr_type;
typedef boost::property_tree::detail::rapidxml::xml_document<> document_type;
typedef node_type* node_ptr;
typedef attr_type* attr_ptr;
typedef document_type* document_ptr;

struct test_case_t {
    std::string toolset_name;
    std::string library;
    std::string test_name;
};

std::size_t hash_value(const test_case_t& test_case);
bool operator==(const test_case_t& lhs, const test_case_t& rhs);

struct expected_results_t {
    typedef boost::unordered_map<test_case_t, bool> tests_t;
    typedef boost::unordered_map<std::string, std::string> toolset_aliases_t;
    tests_t tests;
    toolset_aliases_t toolset_aliases;
};
void load_expected_results(node_ptr root, expected_results_t& expected_results);

struct test_structure_t {
    struct target_t {
        std::string type;
        std::string timestamp;
        bool result;
        node_ptr contents;
    };
    typedef boost::variant<std::string, node_ptr> note_t;
    struct test_log_t {
        std::string library;
        std::string test_program;
        bool show_run_output;
        std::string toolset;
        std::string test_type;
        std::string test_name;
        std::string target_directory;
        bool result;
        bool expected_result;
        std::string expected_reason;
        bool status;
        bool is_new;
        std::string category;
        boost::unordered_map<std::string, target_t> targets;
        std::vector<note_t> notes;
    };
    typedef std::vector<test_log_t> test_case_t;
    typedef std::map<std::string, test_case_t> library_t;
    typedef std::map<std::string, library_t> toolset_t;
    typedef std::map<std::string, toolset_t> toolset_group_t;
    struct run_t {
        std::string runner;
        std::string platform;
        std::string run_type;
        std::string source;
        std::string revision;
        std::string comment;
        boost::posix_time::ptime timestamp;
        toolset_group_t toolsets;
        toolset_group_t non_test_case_targets;
    };
    typedef std::vector<run_t> platform_t;
    typedef std::map<std::string, platform_t> platform_group_t;
    platform_group_t platforms;
};
void load_test_structure(node_ptr root, test_structure_t& structure, std::vector<test_structure_t::run_t*>& runs);

struct failures_markup_t {
    boost::unordered_map<std::string, node_ptr> libraries;
    boost::unordered_set<std::string> required_toolsets;
    boost::unordered_map<std::string, node_ptr> notes;
};
void load_failures_markup(node_ptr root, failures_markup_t& failures_markup);

#define FOR_EACH_ELEMENT(name, node)\
    for(::boost::regression::node_ptr name = (node)->first_node(); name != 0; name = name->next_sibling())

attr_ptr lookup_attr(node_ptr element, const std::string& name);
bool lookup_attr(node_ptr element, const std::string& name, std::string& result);
bool check_attr(node_ptr element, const std::string& name, const std::string& expected);
bool check_name(node_ptr element, const std::string& name);
bool check_attr(node_ptr element, const std::string& element1, const std::string& attr, const std::string& expected);
node_ptr lookup_element(node_ptr element, const std::string& name);
int count_element(node_ptr element, const std::string& name);
std::string value_of(node_ptr element);

std::string escape_xml(const std::string& s);
void write_to_stream(html_writer& os, node_ptr node, bool trim=false);
void write_contents(html_writer& document, node_ptr node, bool trim=false);
boost::shared_ptr<document_type> read_xml_file(const char* filename);

}
}

#endif

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
///////////////////////////////////////////////////////////////////////////////
//
// http://protoc.sourceforge.net/
//
// Copyright (C) 2013 Bjorn Reese <breese@users.sourceforge.net>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
// CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
//
///////////////////////////////////////////////////////////////////////////////

#include <boost/test/unit_test.hpp>

#include <protoc/ubjson/decoder.hpp>

using namespace protoc;

BOOST_AUTO_TEST_SUITE(ubjson_decoder_suite)

//-----------------------------------------------------------------------------
// Basic types
//-----------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_empty)
{
    const char input[] = "";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_junk)
{
    const char input[] = "\t";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_error);
}

BOOST_AUTO_TEST_CASE(test_noop)
{
    const char input[] = "NNN";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_null)
{
    const char input[] = "Z";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_null);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_true)
{
    const char input[] = "T";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_true);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_false)
{
    const char input[] = "F";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_false);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

//-----------------------------------------------------------------------------
// Integers
//-----------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_int8_missing_one)
{
    const char input[] = "B";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int8_zero)
{
    const char input[] = "B\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int8);
    BOOST_REQUIRE_EQUAL(decoder.get_int8(), 0x00);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int8_one)
{
    const char input[] = "B\x01";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int8);
    BOOST_REQUIRE_EQUAL(decoder.get_int8(), 0x01);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int8_7F)
{
    const char input[] = "B\x7F";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int8);
    BOOST_REQUIRE_EQUAL(decoder.get_int8(), 0x7F);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int8_80)
{
    const char input[] = "B\x80";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int8);
    BOOST_REQUIRE_EQUAL(decoder.get_int8(), -0x80);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int8_81)
{
    // Integers as signed (two's complement)
    const char input[] = "B\x81";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int8);
    BOOST_REQUIRE_EQUAL(decoder.get_int8(), -0x7F);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int8_FF)
{
    const char input[] = "B\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int8);
    BOOST_REQUIRE_EQUAL(decoder.get_int8(), -1);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_missing_one)
{
    const char input[] = "i\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_missing_two)
{
    const char input[] = "i";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_zero)
{
    const char input[] = "i\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int16);
    BOOST_REQUIRE_EQUAL(decoder.get_int16(), 0x0000);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_one)
{
    const char input[] = "i\x00\x01";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int16);
    BOOST_REQUIRE_EQUAL(decoder.get_int16(), 0x0001);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_minus_one)
{
    const char input[] = "i\xFF\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int16);
    BOOST_REQUIRE_EQUAL(decoder.get_int16(), -0x0001);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_FF)
{
    const char input[] = "i\x00\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int16);
    BOOST_REQUIRE_EQUAL(decoder.get_int16(), 0x00FF);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_7FFF)
{
    const char input[] = "i\x7F\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int16);
    BOOST_REQUIRE_EQUAL(decoder.get_int16(), 0x7FFF);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_minus_7FFF)
{
    const char input[] = "i\x80\x01";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int16);
    BOOST_REQUIRE_EQUAL(decoder.get_int16(), -0x7FFF);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int16_minus_8000)
{
    const char input[] = "i\x80\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int16);
    BOOST_REQUIRE_EQUAL(decoder.get_int16(), -0x8000);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_missing_one)
{
    const char input[] = "I\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_missing_two)
{
    const char input[] = "I\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_missing_three)
{
    const char input[] = "I\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_missing_four)
{
    const char input[] = "I";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_zero)
{
    const char input[] = "I\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int32);
    BOOST_REQUIRE_EQUAL(decoder.get_int32(), 0x00000000);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_one)
{
    const char input[] = "I\x00\x00\x00\x01";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int32);
    BOOST_REQUIRE_EQUAL(decoder.get_int32(), 0x00000001);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_minus_one)
{
    const char input[] = "I\xFF\xFF\xFF\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int32);
    BOOST_REQUIRE_EQUAL(decoder.get_int32(), -0x00000001);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_two)
{
    const char input[] = "I\x00\x00\x00\x02";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int32);
    BOOST_REQUIRE_EQUAL(decoder.get_int32(), 0x00000002);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_minus_two)
{
    const char input[] = "I\xFF\xFF\xFF\xFE";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int32);
    BOOST_REQUIRE_EQUAL(decoder.get_int32(), -0x00000002);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_7FFFFFFF)
{
    const char input[] = "I\x7F\xFF\xFF\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int32);
    BOOST_REQUIRE_EQUAL(decoder.get_int32(), 0x7FFFFFFF);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int32_minus_7FFFFFFF)
{
    const char input[] = "I\x80\x00\x00\x01";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int32);
    BOOST_REQUIRE_EQUAL(decoder.get_int32(), -0x7FFFFFFF);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_one)
{
    const char input[] = "L\x00\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_two)
{
    const char input[] = "L\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_three)
{
    const char input[] = "L\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_four)
{
    const char input[] = "L\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_five)
{
    const char input[] = "L\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_six)
{
    const char input[] = "L\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_seven)
{
    const char input[] = "L\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_missing_eight)
{
    const char input[] = "L";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_zero)
{
    const char input[] = "L\x00\x00\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int64);
    BOOST_REQUIRE_EQUAL(decoder.get_int64(), 0x0000000000000000L);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_one)
{
    const char input[] = "L\x00\x00\x00\x00\x00\x00\x00\x01";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int64);
    BOOST_REQUIRE_EQUAL(decoder.get_int64(), 0x0000000000000001L);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_minus_one)
{
    const char input[] = "L\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int64);
    BOOST_REQUIRE_EQUAL(decoder.get_int64(), -0x0000000000000001L);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_int64_7FFFFFFFFFFFFFFF)
{
    const char input[] = "L\x7F\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_int64);
    BOOST_REQUIRE_EQUAL(decoder.get_int64(), 0x7FFFFFFFFFFFFFFF);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

//-----------------------------------------------------------------------------
// Floating-point
//-----------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_float32_zero)
{
    const char input[] = "d" "\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float32);
    BOOST_REQUIRE_EQUAL(decoder.get_float32(), 0.0f);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_one)
{
    const char input[] = "d" "\x3F\x80\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float32);
    BOOST_REQUIRE_EQUAL(decoder.get_float32(), 1.0f);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_minus_one)
{
    const char input[] = "d" "\xBF\x80\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float32);
    BOOST_REQUIRE_EQUAL(decoder.get_float32(), -1.0f);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_two)
{
    const char input[] = "d" "\x40\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float32);
    BOOST_REQUIRE_EQUAL(decoder.get_float32(), 2.0f);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_minus_two)
{
    const char input[] = "d" "\xC0\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float32);
    BOOST_REQUIRE_EQUAL(decoder.get_float32(), -2.0f);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

#if 0
BOOST_AUTO_TEST_CASE(test_float32_e14)
{
    const char input[] = "d" "\x56\xB5\xE6\x21"; // FIXME: Find exact number
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float32);
    BOOST_REQUIRE_EQUAL(decoder.get_float32(), 1e14);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_em14)
{
    const char input[] = "d" "\x28\x34\x24\xDC"; // FIXME: Find exact number
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float32);
    BOOST_REQUIRE_EQUAL(decoder.get_float32(), 1e-14);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}
#endif

BOOST_AUTO_TEST_CASE(test_float32_missing_one)
{
    const char input[] = "d" "\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_missing_two)
{
    const char input[] = "d" "\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_missing_three)
{
    const char input[] = "d" "\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float32_missing_four)
{
    const char input[] = "d";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_zero)
{
    const char input[] = "D" "\x00\x00\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float64);
    BOOST_REQUIRE_EQUAL(decoder.get_float64(), 0.0);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_one)
{
    const char input[] = "D" "\x3F\xF0\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float64);
    BOOST_REQUIRE_EQUAL(decoder.get_float64(), 1.0);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_minus_one)
{
    const char input[] = "D" "\xBF\xF0\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float64);
    BOOST_REQUIRE_EQUAL(decoder.get_float64(), -1.0);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_two)
{
    const char input[] = "D" "\x40\x00\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float64);
    BOOST_REQUIRE_EQUAL(decoder.get_float64(), 2.0);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_minus_two)
{
    const char input[] = "D" "\xC0\x00\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_float64);
    BOOST_REQUIRE_EQUAL(decoder.get_float64(), -2.0);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_one)
{
    const char input[] = "D" "\x00\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_two)
{
    const char input[] = "D" "\x00\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_three)
{
    const char input[] = "D" "\x00\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_four)
{
    const char input[] = "D" "\x00\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_five)
{
    const char input[] = "D" "\x00\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_six)
{
    const char input[] = "D" "\x00\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_seven)
{
    const char input[] = "D" "\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_float64_missing_eight)
{
    const char input[] = "D";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

//-----------------------------------------------------------------------------
// Strings
//-----------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_string_empty)
{
    const char input[] = "s" "B\x00";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_string);
    BOOST_REQUIRE_EQUAL(decoder.get_string(), "");
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_string_one)
{
    const char input[] = "s" "B\x01" "A";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_string);
    BOOST_REQUIRE_EQUAL(decoder.get_string(), "A");
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_string_two)
{
    const char input[] = "s" "B\x02" "AB";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_string);
    BOOST_REQUIRE_EQUAL(decoder.get_string(), "AB");
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_string_missing_length_indicator)
{
    const char input[] = "s";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_string_invalid)
{
    const char input[] = "s" "s";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_error);
}

BOOST_AUTO_TEST_CASE(test_string_missing_length)
{
    const char input[] = "s" "B";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_string_missing_data)
{
    const char input[] = "s" "B\x01";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_string_length_too_big)
{
    const char input[] = "s" "B\x02" "A";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_string_negative_length_FF)
{
    const char input[] = "s" "B\xFF" "A";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_error);
}

BOOST_AUTO_TEST_CASE(test_string_negative_length_80)
{
    const char input[] = "s" "B\x80" "A";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_error);
}

//-----------------------------------------------------------------------------
// Containers
//-----------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_object_begin)
{
    const char input[] = "{";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_object_end)
{
    const char input[] = "}";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_object_empty)
{
    const char input[] = "{}";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_object_nested_empty)
{
    const char input[] = "{{}}";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_object_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_array_begin)
{
    const char input[] = "[";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_array_end)
{
    const char input[] = "]";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_array_empty)
{
    const char input[] = "[]";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_CASE(test_array_nested_empty)
{
    const char input[] = "[[]]";
    ubjson::decoder decoder(input, input + sizeof(input) - 1);
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_begin);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_array_end);
    BOOST_REQUIRE_NO_THROW(decoder.next());
    BOOST_REQUIRE_EQUAL(decoder.type(), ubjson::token_eof);
}

BOOST_AUTO_TEST_SUITE_END()


text:
//          Copyright Camille Gillot 2012 - 2015.
// 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)

//[po_wildcard
/*`
  [po_wildcard_policy]
  [po_wildcard_decl]
  [po_wildcard_use]
 */
//]

#include "./classes.hpp"

#include <boost/test/unit_test.hpp>

using namespace rtti;

namespace {

//[po_wildcard_policy
/*`
  In this example, we want to be able to flag any found ambiguity,
  both at generation time and at call time.

  To remember the ambiguities found
  we will use the following global flags:
 */
// set by ambiguity_handler
int found_ambiguous  = 0;
// set by bad_dispatch
int called_ambiguous = 0;

/*`
  We can now define our policy class.
 */
struct wildcard_policy
: public mmethod::default_policy
{
  static bool ambiguity_handler(std::size_t /*n*/,
                                rtti_hierarchy const /*types*/ []);
  static int bad_dispatch(foo& /*arg1*/, foo& /*arg2*/);
};

/*`
  The function `ambiguity_handler` is responsible for the handling of
  ambiguities at table generation time.
  It is called whenever the table generation algorithm
  runs into an ambiguous case.
  The passed parameters are:

  * the arity of the __multimethod__,
  * a C array of __rtti__ type ids.
 */
bool
wildcard_policy::ambiguity_handler(std::size_t n, rtti_hierarchy const types[])
{
  BOOST_CHECK_EQUAL(n, 2u);
  BOOST_CHECK_EQUAL(types[0], static_node<bar>());
  BOOST_CHECK_EQUAL(types[1], static_node<bar>());

  ++found_ambiguous;
  //=std::cout << "Ambiguity found of arity " << n << ": "
  //=          << types[0] << " and " << types[1] << std::endl;

  return false;
}

/*`
  The function `bad_dispatch` will be called whenever the user
  tries to invoke an ambiguous overload.
  Its job is to provide a default behaviour,
  when a suitable implementation cannot be found.
  It is called with the arguments passed to the __multimethod__.
 */
int
wildcard_policy::bad_dispatch(foo& arg1, foo& arg2)
{
  ++called_ambiguous;
  /*<-*/(void)arg1; (void)arg2;/*->*/
  //=std::cout << "Bad dispatch called with arguments: "
  //=          << &arg1 << " and " << &arg2 << std::endl;

  return 42;
}
//]

//[po_wildcard_decl
/*`
  After a policy class has been defined,
  we can declare a __multimethod__ using it.
  We only have to replace `DECLARE_MMETHOD`
  by `DECLARE_MMETHOD_POLICY` and add the policy
  as fourth argument.
 */
using tags::_v;
DECLARE_MMETHOD_POLICY(wild, int, (_v<foo&>, _v<foo&>), wildcard_policy);

/*`
  Then, the implementations of the __multimethod__ need
  not care about the policy.
  The policy is perfectly transparent to the user
  providing the overloads.
 */
IMPLEMENT_MMETHOD(wild, int, (foo&, foo&)) { return 0; }
IMPLEMENT_MMETHOD(wild, int, (bar&, foo&)) { return 13; }
IMPLEMENT_MMETHOD(wild, int, (foo&, bar&)) { return 8; }

// bar-bar is ambiguous : bar-foo and foo-bar are equally good matches
//]

} // namespace

BOOST_AUTO_TEST_CASE(test_wildcard) {
  foo a; bar b;
  foo x; bar y;

  //[po_wildcard_use
  /*`
    The runtime behaviour is then the expected one :
   */
  // force generation
  wild.generate();

  // ambiguity_handler has been called
  BOOST_CHECK_EQUAL( found_ambiguous, 1 );

  // regular calls
  BOOST_CHECK_EQUAL( wild(a, x),  0 ); // (1-1 case)
  BOOST_CHECK_EQUAL( wild(a, y),  8 ); // (1-2 case)
  BOOST_CHECK_EQUAL( wild(b, x), 13 ); // (2-1 case)
  BOOST_CHECK_EQUAL( called_ambiguous, 0 );

  // ambiguous call
  BOOST_CHECK_EQUAL( wild(b, y), 42 ); // (2-2 case : ambiguous)
  BOOST_CHECK_EQUAL( called_ambiguous, 1 );
  //]
}

max_stars_repo_name: cjgillot/rtti

max_issues_repo_name: cjgillot/rtti

max_forks_repo_name: cjgillot/rtti


text:
/***************************************************************************************************
LICENSE:
    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.

Author:liu.hao(33852613@163.com)

Time:2021-1

info:

***************************************************************************************************/

#include <mkheaders.h>
#include <boost/algorithm/hex.hpp>
#include <boost/uuid/detail/md5.hpp>
#include"mkMD5.h"

bool
mkMD5::Get(std::string &str_md5, const char* const buffer, size_t buffer_size)
{
	if (buffer == nullptr) {
		return false;
	}
	boost::uuids::detail::md5 boost_md5;
	boost::uuids::detail::md5::digest_type digest
    ;
    boost_md5.process_bytes(buffer, buffer_size);
	boost_md5.get_digest(digest);

    const char* char_digest = reinterpret_cast<const char*>(&digest);
	str_md5.clear();
	boost::algorithm::hex(char_digest,char_digest+sizeof(boost::uuids::detail::md5::digest_type), std::back_inserter(str_md5));
	return true;
}

max_stars_repo_name: unihykes/monk

max_issues_repo_name: six-th/monk

max_forks_repo_name: six-th/monk


text:
/** @file */

#include <boost/test/unit_test.hpp>

#include <YukariMSP/MSPParsers.h>

namespace Yukari
{
namespace MSP
{
  namespace Test
  {
    BOOST_AUTO_TEST_SUITE(MSPClientTest)

    BOOST_AUTO_TEST_CASE(MSPClient_Build_Payload)
    {
      MSPClient::Payload payload;
      MSPClient::Payload data = {0xff, 0xff, 0x03, 0x00, 0x70, 0x00};

      MSPClient::BuildCommandPayload(payload, MSPClient::ATTITUDE, data);

      MSPClient::Payload expected = {'$',  'M',  '<',  6,    0x6c, 0xff,
                                     0xff, 0x03, 0x00, 0x70, 0x00, 0x19};

      BOOST_CHECK_EQUAL(payload.size(), expected.size());
      BOOST_CHECK(payload == expected);
    }

    BOOST_AUTO_TEST_CASE(MSPClient_Build_Payload_2)
    {
      MSPClient::Payload payload;

      MSPClient::BuildCommandPayload(payload, MSPClient::RAW_IMU, {});

      MSPClient::Payload expected = {'$', 'M', '<', 0, 102, 102};

      BOOST_CHECK_EQUAL(payload.size(), expected.size());
      BOOST_CHECK(payload == expected);
    }

    BOOST_AUTO_TEST_CASE(MSPClient_Parse_Payload)
    {
      MSPClient::Payload payload = {'$',  'M',  '<',  6,    0x6c, 0xff,
                                    0xff, 0x03, 0x00, 0x70, 0x00, 0x19};
      MSPClient::MSPCommand command;
      MSPClient::Payload data;

      bool result = MSPClient::ParseResponsePayload(payload, command, data);
      BOOST_CHECK(result);

      MSPClient::Payload expected = {0xff, 0xff, 0x03, 0x00, 0x70, 0x00};

      BOOST_CHECK_EQUAL(command, MSPClient::ATTITUDE);
      BOOST_CHECK_EQUAL(data.size(), expected.size());
      BOOST_CHECK(data == expected);
    }

    BOOST_AUTO_TEST_CASE(MSPClient_Parse_Payload_Bad_Checksum)
    {
      MSPClient::Payload payload = {'$',  'M',  '<',  6,    0x6c, 0xff,
                                    0xff, 0x03, 0x00, 0x70, 0x00, 0x10};
      MSPClient::MSPCommand command;
      MSPClient::Payload data;

      bool result = MSPClient::ParseResponsePayload(payload, command, data);
      BOOST_CHECK(!result);

      BOOST_CHECK_EQUAL(command, MSPClient::NOP);
      BOOST_CHECK(data.empty());
    }

    BOOST_AUTO_TEST_SUITE_END()
  }
}
}

max_stars_repo_name: DanNixon/Yukari

max_issues_repo_name: DanNixon/Yukari

max_forks_repo_name: DanNixon/Yukari


text: #include <boost/spirit/include/support.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include "boost_asio_demo/deadline_timer.h"
#include <boost/thread/thread_time.hpp>
#include <boost/bind.hpp>

DeadlineTimer::DeadlineTimer(boost::asio::io_service& io, float sleepSeconds, finish_func_type callbackFinish)
  : io(io), sleepDuration(boost::posix_time::milliseconds(static_cast<unsigned int>(sleepSeconds * 1000))), callbackFinish(callbackFinish), timer(NULL), stopped(false)
{
}

DeadlineTimer::~DeadlineTimer()
{
  if (timer)
  {
    stopped = true;
    timer->cancel();
  }
}

void DeadlineTimer::init()
{
  timer = timer_type(new boost::asio::deadline_timer(io, sleepDuration));
  stopped = false;
  begin = end = boost::get_system_time();
  async_wait();
}

void DeadlineTimer::wakeUp()
{
  if (timer)
  {
    end = boost::get_system_time();
    timer->cancel();
  }
  else
  {
    print("recreate");
    init();
  }
}

void DeadlineTimer::async_wait()
{
  timer->async_wait(boost::bind(&DeadlineTimer::callback, this, boost::asio::placeholders::error));
}

void DeadlineTimer::callback(const boost::system::error_code &err)
{
  if (!stopped && isPaused(err))
  {
    pause();
    async_wait();
  }
  else
  {
    timer.reset();
    stopped = true;
    callbackFinish();
    print("finished");
  }
}

void DeadlineTimer::doPrint(const char* prefix)
{
  std::cout << prefix << (boost::get_system_time() - begin).total_milliseconds()/1000.0 << std::endl;
}


text:
//=======================================================================
// Copyright 2007 Aaron Windsor
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/properties.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/ref.hpp>
#include <vector>

#include <boost/graph/biconnected_components.hpp>
#include <boost/graph/make_biconnected_planar.hpp>
#include <boost/graph/boyer_myrvold_planar_test.hpp>

using namespace boost;

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

  typedef adjacency_list
    < vecS,
      vecS,
      undirectedS,
      property<vertex_index_t, int>,
      property<edge_index_t, int>
    >
    graph;

  graph g(11);
  add_edge(0,1,g);
  add_edge(2,3,g);
  add_edge(3,0,g);
  add_edge(3,4,g);
  add_edge(4,5,g);
  add_edge(5,3,g);
  add_edge(5,6,g);
  add_edge(6,7,g);
  add_edge(7,8,g);
  add_edge(8,5,g);
  add_edge(8,9,g);
  add_edge(0,10,g);

  //Initialize the interior edge index
  property_map<graph, edge_index_t>::type e_index = get(edge_index, g);
  graph_traits<graph>::edges_size_type edge_count = 0;
  graph_traits<graph>::edge_iterator ei, ei_end;
  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)
    put(e_index, *ei, edge_count++);

  //Test for planarity; compute the planar embedding as a side-effect
  typedef std::vector< graph_traits<graph>::edge_descriptor > vec_t;
  std::vector<vec_t> embedding(num_vertices(g));
  if (boyer_myrvold_planarity_test(boyer_myrvold_params::graph = g,
                                   boyer_myrvold_params::embedding =
                                     &embedding[0]
                                   )
      )
    std::cout << "Input graph is planar" << std::endl;
  else
    std::cout << "Input graph is not planar" << std::endl;

  typedef std::vector< graph_traits<graph>::edges_size_type >
    component_storage_t;
  typedef iterator_property_map
    < component_storage_t::iterator,
      property_map<graph, edge_index_t>::type
    >
    component_map_t;

  component_storage_t component_storage(num_edges(g));
  component_map_t component(component_storage.begin(), get(edge_index, g));

  std::cout << "Before calling make_biconnected_planar, the graph has "
            << biconnected_components(g, component)
            << " biconnected components" << std::endl;

  make_biconnected_planar(g, &embedding[0]);

  // Re-initialize the edge index, since we just added a few edges
  edge_count = 0;
  for(tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)
    put(e_index, *ei, edge_count++);

  // Re-size the storage for the biconnected components, since we
  // just added a few edges

  component_storage.resize(num_edges(g));
  component = component_map_t(component_storage.begin(), get(edge_index,g));

  std::cout << "After calling make_biconnected_planar, the graph has "
            << biconnected_components(g, component)
            << " biconnected components" << std::endl;

  if (boyer_myrvold_planarity_test(g))
    std::cout << "Also, the graph is still planar." << std::endl;
  else
    std::cout << "But the graph is not still planar." << std::endl;

  return 0;
}

max_issues_repo_name: boost-cmake/vintage

max_forks_repo_name: boost-cmake/vintage


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

#include <boost/simd/arithmetic/functions/fma.hpp>

namespace boost { namespace simd { namespace ext
{
  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::fma_, boost::simd::tag::fma4_,
                      (A0),
                      ((simd_<single_<A0>,boost::simd::tag::sse_>))
                      ((simd_<single_<A0>,boost::simd::tag::sse_>))
                      ((simd_<single_<A0>,boost::simd::tag::sse_>))
                     )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)
    {
      return _mm_macc_ps(a0, a1, a2);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::fma_, boost::simd::tag::fma4_,
                      (A0),
                      ((simd_<double_<A0>,boost::simd::tag::sse_>))
                      ((simd_<double_<A0>,boost::simd::tag::sse_>))
                      ((simd_<double_<A0>,boost::simd::tag::sse_>))
                     )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)
    {
      return _mm_macc_pd(a0, a1, a2);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::fma_, boost::simd::tag::fma4_,
                      (A0),
                      ((simd_<single_<A0>,boost::simd::tag::avx_>))
                      ((simd_<single_<A0>,boost::simd::tag::avx_>))
                      ((simd_<single_<A0>,boost::simd::tag::avx_>))
                     )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)
    {
      return _mm256_macc_ps(a0, a1, a2);
    }
  };

  BOOST_SIMD_FUNCTOR_IMPLEMENTATION(boost::simd::tag::fma_, boost::simd::tag::fma4_,
                      (A0),
                      ((simd_<double_<A0>,boost::simd::tag::avx_>))
                      ((simd_<double_<A0>,boost::simd::tag::avx_>))
                      ((simd_<double_<A0>,boost::simd::tag::avx_>))
                     )
  {
    typedef A0 result_type;
    BOOST_SIMD_FUNCTOR_CALL_REPEAT(3)
    {
      return _mm256_macc_pd(a0, a1, a2);
    }
  };
} } }

#endif
#endif