text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2012, 2013 Ripple Labs Inc.

    Permission to use, copy, modify, and/or 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.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================

#include <ripple/app/misc/Transaction.h>
#include <ripple/app/tx/apply.h>
#include <ripple/basics/Log.h>
#include <ripple/core/DatabaseCon.h>
#include <ripple/app/ledger/LedgerMaster.h>
#include <ripple/app/main/Application.h>
#include <ripple/app/misc/HashRouter.h>
#include <ripple/protocol/Feature.h>
#include <ripple/protocol/JsonFields.h>
#include <boost/optional.hpp>

namespace ripple {

Transaction::Transaction (std::shared_ptr<STTx const> const& stx,
    std::string& reason, Application& app)
    noexcept
    : mTransaction (stx)
    , mApp (app)
    , j_ (app.journal ("Ledger"))
{
    try
    {
        mTransactionID  = mTransaction->getTransactionID ();
    }
    catch (std::exception& e)
    {
        reason = e.what();
        return;
    }

    mStatus = NEW;
}

//
// Misc.
//

void Transaction::setStatus (TransStatus ts, std::uint32_t lseq)
{
    mStatus     = ts;
    mInLedger   = lseq;
}

TransStatus Transaction::sqlTransactionStatus(
    boost::optional<std::string> const& status)
{
    char const c = (status) ? (*status)[0] : TXN_SQL_UNKNOWN;

    switch (c)
    {
    case TXN_SQL_NEW:       return NEW;
    case TXN_SQL_CONFLICT:  return CONFLICTED;
    case TXN_SQL_HELD:      return HELD;
    case TXN_SQL_VALIDATED: return COMMITTED;
    case TXN_SQL_INCLUDED:  return INCLUDED;
    }

    assert (c == TXN_SQL_UNKNOWN);
    return INVALID;
}

Transaction::pointer Transaction::transactionFromSQL (
    boost::optional<std::uint64_t> const& ledgerSeq,
    boost::optional<std::string> const& status,
    Blob const& rawTxn,
    Application& app)
{
    std::uint32_t const inLedger =
        rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or (0));

    SerialIter it (makeSlice(rawTxn));
    auto txn = std::make_shared<STTx const> (it);
    std::string reason;
    auto tr = std::make_shared<Transaction> (
        txn, reason, app);

    tr->setStatus (sqlTransactionStatus (status));
    tr->setLedger (inLedger);
    return tr;
}

Transaction::pointer Transaction::transactionFromSQLValidated(
    boost::optional<std::uint64_t> const& ledgerSeq,
    boost::optional<std::string> const& status,
    Blob const& rawTxn,
    Application& app)
{
    auto ret = transactionFromSQL(ledgerSeq, status, rawTxn, app);

    if (checkValidity(app.getHashRouter(),
            *ret->getSTransaction(), app.
                getLedgerMaster().getValidatedRules(),
                    app.config()).first !=
                        Validity::Valid)
        return {};

    return ret;
}

Transaction::pointer Transaction::load(uint256 const& id, Application& app)
{
    std::string sql = "SELECT LedgerSeq,Status,RawTxn "
            "FROM Transactions WHERE TransID='";
    sql.append (to_string (id));
    sql.append ("';");

    boost::optional<std::uint64_t> ledgerSeq;
    boost::optional<std::string> status;
    Blob rawTxn;
    {
        auto db = app.getTxnDB ().checkoutDb ();
        soci::blob sociRawTxnBlob (*db);
        soci::indicator rti;

        *db << sql, soci::into (ledgerSeq), soci::into (status),
                soci::into (sociRawTxnBlob, rti);
        if (!db->got_data () || rti != soci::i_ok)
            return {};

        convert(sociRawTxnBlob, rawTxn);
    }

    return Transaction::transactionFromSQLValidated (
        ledgerSeq, status, rawTxn, app);
}

// options 1 to include the date of the transaction
Json::Value Transaction::getJson (int options, bool binary) const
{
    Json::Value ret (mTransaction->getJson (0, binary));

    if (mInLedger)
    {
        ret[jss::inLedger] = mInLedger;        // Deprecated.
        ret[jss::ledger_index] = mInLedger;

        if (options == 1)
        {
            auto ct = mApp.getLedgerMaster().
                getCloseTimeBySeq (mInLedger);
            if (ct)
                ret[jss::date] = ct->time_since_epoch().count();
        }
    }

    return ret;
}

} // ripple

max_stars_repo_name: Alpha-Pay/AlphaPay

max_issues_repo_name: Alpha-Pay/AlphaPay

max_forks_repo_name: Alpha-Pay/AlphaPay


text:
// This file is part of the dune-gdt project:
//   https://github.com/dune-community/dune-gdt
// Copyright 2010-2017 dune-gdt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//      or  GPL-2.0+ (http://opensource.org/licenses/gpl-license)
//          with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
//   Felix Schindler (2014 - 2017)
//   Rene Milk       (2014, 2016 - 2017)
//   Tobias Leibner  (2014, 2016)

#ifndef DUNE_GDT_SPACES_CG_INTERFACE_HH
#define DUNE_GDT_SPACES_CG_INTERFACE_HH

#include <boost/numeric/conversion/cast.hpp>

#include <dune/common/dynvector.hh>
#include <dune/common/version.hh>
#include <dune/common/typetraits.hh>

#include <dune/geometry/referenceelements.hh>

#include <dune/xt/common/exceptions.hh>
#include <dune/xt/common/type_traits.hh>
#include <dune/xt/common/ranges.hh>
#include <dune/xt/grid/boundaryinfo.hh>

#include "../interface.hh"

namespace Dune {
namespace GDT {

static constexpr Backends default_cg_backend = default_space_backend;

template <class ImpTraits, size_t domainDim, size_t rangeDim, size_t rangeDimCols = 1>
class CgSpaceInterface : public SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols>
{
  typedef SpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> BaseType;
  typedef CgSpaceInterface<ImpTraits, domainDim, rangeDim, rangeDimCols> ThisType;

public:
  typedef ImpTraits Traits;

  using BaseType::polOrder;

  using typename BaseType::DomainFieldType;
  using BaseType::dimDomain;
  using typename BaseType::DomainType;

  using typename BaseType::RangeFieldType;
  using BaseType::dimRange;
  using BaseType::dimRangeCols;

  using typename BaseType::GridLayerType;
  using typename BaseType::EntityType;
  using typename BaseType::PatternType;

private:
  typedef Dune::XT::Common::FieldVector<DomainFieldType, dimDomain> StuffDomainType;
  static const constexpr RangeFieldType compare_tolerance_ = 1e-13;

public:
  /**
   * \defgroup interface ´´These methods have to be implemented!''
   * @{
   **/
  std::vector<DomainType> lagrange_points(const EntityType& entity) const
  {
    CHECK_CRTP(this->as_imp().lagrange_points(entity));
    return this->as_imp().lagrange_points(entity);
  }

  std::set<size_t> local_dirichlet_DoFs(
      const EntityType& entity,
      const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridLayerType>>& boundaryInfo) const
  {
    CHECK_CRTP(this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo));
    return this->as_imp().local_dirichlet_DoFs(entity, boundaryInfo);
  }
  /** @} */

  /**
   * \defgroup provided ´´These methods are provided by the interface for convenience.''
   * @{
   **/
  std::vector<DomainType> lagrange_points_order_1(const EntityType& entity) const
  {
    // check
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    assert(this->grid_layer().indexSet().contains(entity));
    // get the basis and reference element
    const auto basis = this->base_function_set(entity);
    typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
    std::vector<RangeType> tmp_basis_values(basis.size(), RangeType(0));
    const auto& reference_element = ReferenceElements<DomainFieldType, dimDomain>::general(entity.type());
    const auto num_vertices = reference_element.size(dimDomain);
    assert(num_vertices >= 0);
    assert(boost::numeric_cast<size_t>(num_vertices) == basis.size() && "This should not happen with polOrder 1!");
    // prepare return vector
    std::vector<DomainType> local_vertices(num_vertices, DomainType(0));
    // loop over all vertices
    for (auto ii : Dune::XT::Common::value_range(num_vertices)) {
      // get the local coordinate of the iith vertex
      const auto local_vertex = reference_element.position(ii, dimDomain);
      // evaluate the basefunctionset
      basis.evaluate(local_vertex, tmp_basis_values);
      // find the basis function that evaluates to one here (has to be only one!)
      size_t ones = 0;
      size_t zeros = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs((tmp_basis_values)[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          local_vertices[jj] = local_vertex;
          ++ones;
        } else if (std::abs((tmp_basis_values)[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      assert(ones == 1 && zeros == (basis.size() - 1) && failures == 0 && "This must not happen for polOrder 1!");
    }
    return local_vertices;
  } // ... lagrange_points_order_1(...)

  std::set<size_t> local_dirichlet_DoFs_order_1(
      const EntityType& entity,
      const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridLayerType>>& boundaryInfo) const
  {
    static_assert(polOrder == 1, "Not tested for higher polynomial orders!");
    static const XT::Grid::DirichletBoundary dirichlet{};
    if (dimRange != 1)
      DUNE_THROW(NotImplemented, "Does not work for higher dimensions");
    // check
    assert(this->grid_layer().indexSet().contains(entity));
    if (!entity.hasBoundaryIntersections())
      return std::set<size_t>();
    // prepare
    std::set<size_t> localDirichletDofs;
    std::vector<DomainType> dirichlet_vertices;
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_layer().iend(entity);
    for (auto intersection_it = this->grid_layer().ibegin(entity); intersection_it != intersection_it_end;
         ++intersection_it) {
      // only work on dirichlet ones
      const auto& intersection = *intersection_it;
      // actual dirichlet intersections + process boundaries for parallel runs
      if (boundaryInfo.type(intersection) == dirichlet || (!intersection.neighbor() && !intersection.boundary())) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (auto cc : Dune::XT::Common::value_range(geometry.corners()))
          dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
      } // only work on dirichlet ones
    } // loop over all intersections
    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
    std::vector<RangeType> tmp_basis_values(basis.size(), RangeType(0));
    for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
      // find the basis function that evaluates to one here (has to be only one!)
      basis.evaluate(dirichlet_vertices[cc], tmp_basis_values);
      size_t ones = 0;
      size_t zeros = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        if (std::abs(tmp_basis_values[jj][0] - RangeFieldType(1)) < compare_tolerance_) {
          localDirichletDofs.insert(jj);
          ++ones;
        } else if (std::abs(tmp_basis_values[jj][0]) < compare_tolerance_)
          ++zeros;
        else
          ++failures;
      }
      // asserts valid for polorder 1 only
      assert(ones == 1);
      assert(zeros == (basis.size() - 1));
      assert(failures == 0);
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs_order_1(...)

  std::set<size_t> local_dirichlet_DoFs_simplicial_lagrange_elements(
      const EntityType& entity,
      const XT::Grid::BoundaryInfo<XT::Grid::extract_intersection_t<GridLayerType>>& boundaryInfo) const
  {
    if (!entity.type().isSimplex())
      DUNE_THROW(NotImplemented, "Only implemented for simplex elements!");
    // check
    assert(this->grid_layer().indexSet().contains(entity));
    // prepare
    std::set<size_t> localDirichletDofs;
    std::vector<DomainType> dirichlet_vertices;
    // get all dirichlet vertices of this entity, therefore
    // * loop over all intersections
    const auto intersection_it_end = this->grid_layer().iend(entity);
    for (auto intersection_it = this->grid_layer().ibegin(entity); intersection_it != intersection_it_end;
         ++intersection_it) {
      const auto& intersection = *intersection_it;
      std::vector<StuffDomainType> dirichlet_vertices_intersection;
      // only work on dirichlet ones, actual dirichlet intersections + process boundaries for parallel runs
      if (boundaryInfo.dirichlet(intersection) || (!intersection.neighbor() && !intersection.boundary())) {
        // and get the vertices of the intersection
        const auto geometry = intersection.geometry();
        for (auto cc : Dune::XT::Common::value_range(geometry.corners())) {
          dirichlet_vertices_intersection.emplace_back(entity.geometry().local(geometry.corner(cc)));
          dirichlet_vertices.emplace_back(entity.geometry().local(geometry.corner(cc)));
        }
      } // only work on dirichlet ones
      // for higher polynomial orders, add points associated to DoFs within the intersection
      // calculate by using lagrange grid {x = \sum_{j=0}^d \lambda_j a_j | \sum_j lambda_j = 1}, where a_j are the
      // vertices of the entity and \lambda_j \in {\frac{m}{polOrder} | m = 0, ... , polOrder}
      std::vector<double> possible_coefficients(polOrder < 1 ? 0 : polOrder - 1);
      for (int m = 0; m < polOrder; ++m)
        possible_coefficients[m] = m / polOrder;
      std::set<std::vector<double>> possible_coefficient_vectors;
      possible_convex_combination_coefficients(
          possible_coefficient_vectors, possible_coefficients, dirichlet_vertices_intersection.size());
      for (const auto& coefficient_vector : possible_coefficient_vectors)
        dirichlet_vertices.emplace_back(std::inner_product(dirichlet_vertices_intersection.begin(),
                                                           dirichlet_vertices_intersection.end(),
                                                           coefficient_vector.begin(),
                                                           StuffDomainType(0)));
    } // loop over all intersections

    // find the corresponding basis functions
    const auto basis = this->base_function_set(entity);
    typedef typename BaseType::BaseFunctionSetType::RangeType RangeType;
    std::vector<RangeType> tmp_basis_values(basis.size(), RangeType(0));
    for (size_t cc = 0; cc < dirichlet_vertices.size(); ++cc) {
      // find the basis function that evaluates to one here (has to be only one per range dimension!)
      basis.evaluate(dirichlet_vertices[cc], tmp_basis_values);
      size_t ones = 0;
      size_t zeros = 0;
      size_t failures = 0;
      for (size_t jj = 0; jj < basis.size(); ++jj) {
        for (size_t rr = 0; rr < dimRange; ++rr) {
          if (std::abs(tmp_basis_values[jj][rr] - RangeFieldType(1)) < compare_tolerance_) {
            localDirichletDofs.insert(jj);
            ++ones;
          } else if (std::abs(tmp_basis_values[jj][rr]) < compare_tolerance_)
            ++zeros;
          else
            ++failures;
        }
      }
      assert(ones == dimRange && zeros == ((basis.size() - 1) * dimRange) && failures == 0 && "This must not happen!");
    }
    return localDirichletDofs;
  } // ... local_dirichlet_DoFs_simplicial_lagrange_elements(...)

  using BaseType::compute_pattern;

  template <class GL, class S, size_t d, size_t r, size_t rC>
  typename std::enable_if<XT::Grid::is_layer<GL>::value, PatternType>::type
  compute_pattern(const GL& grd_layr, const SpaceInterface<S, d, r, rC>& ansatz_space) const
  {
    return BaseType::compute_volume_pattern(grd_layr, ansatz_space);
  }

  using BaseType::local_constraints;

  template <class S, size_t d, size_t r, size_t rC, class ConstraintsType>
  void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/,
                         const EntityType& /*entity*/,
                         ConstraintsType& /*ret*/) const
  {
    static_assert(AlwaysFalse<S>::value, "Not implemented for these constraints!");
  }

  template <class S, size_t d, size_t r, size_t rC>
  void local_constraints(const SpaceInterface<S, d, r, rC>& /*other*/,
                         const EntityType& entity,
                         DirichletConstraints<XT::Grid::extract_intersection_t<GridLayerType>>& ret) const
  {
    const auto local_DoFs = this->local_dirichlet_DoFs(entity, ret.boundary_info());
    if (local_DoFs.size() > 0) {
      const auto global_indices = this->mapper().globalIndices(entity);
      for (const auto& local_DoF : local_DoFs) {
        ret.insert(global_indices[local_DoF]);
      }
    }
  } // ... local_constraints(..., Constraints::Dirichlet<...> ...)
  /** @} */

private:
  void possible_convex_combination_coefficients(std::set<std::vector<double>>& vectors_in,
                                                const std::vector<double>& possible_coefficients,
                                                const size_t final_size) const
  {
    if (vectors_in.empty()) {
      if (final_size != 0)
        for (const auto& coeff : possible_coefficients)
          vectors_in.insert(std::vector<double>(1, coeff));
    } else if (vectors_in.begin()->size() != final_size) {
      std::set<std::vector<double>> vectors_out;
      for (auto& vec : vectors_in) {
        for (const auto& coeff : possible_coefficients) {
          if ((vec.size() != final_size - 1
               && Dune::XT::Common::FloatCmp::le(std::accumulate(vec.begin(), vec.end(), 0.0) + coeff, 1.0))
              || (vec.size() == final_size - 1
                  && Dune::XT::Common::FloatCmp::eq(std::accumulate(vec.begin(), vec.end(), 0.0) + coeff, 1.0))) {
            std::vector<double> vec_copy = vec;
            vec_copy.push_back(coeff);
            vectors_out.insert(vec_copy);
          }
        }
      }
      vectors_in = vectors_out;
      possible_convex_combination_coefficients(vectors_in, possible_coefficients, final_size);
    } // if (...)
  } // ... possible_convex_combination_coefficients(...)
}; // class CgSpaceInterface

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_SPACES_CG_INTERFACE_HH

ext: hh

max_stars_repo_name: tobiasleibner/dune-gdt

max_issues_repo_name: tobiasleibner/dune-gdt

max_forks_repo_name: tobiasleibner/dune-gdt


text:
/*===========================================================================*\

Author: Matthias W. Smith
Email:  mwsmith2@uw.edu
Date:   11/02/14

Detail: This is a new test program for my Fid libraries

\*===========================================================================*/

//--- std includes ----------------------------------------------------------//
#include <iostream>
#include <fstream>
#include <vector>
#include <cmath>
using std::vector;
using std::cout;
using std::endl;

//--- other includes --------------------------------------------------------//
#include <armadillo>

//--- project includes ------------------------------------------------------//
#include "fid.h"
using namespace fid;

int main(int argc, char** argv)
{
  // set precision
  cout.precision(10);
  cout.setf(std::ios::fixed, std:: ios::floatfield);

  // declare variables
  int fid_length = 5000;
  double ti = -1.0;
  double dt = 0.001;
  double ftruth = 23.0;

  vector<double> wf_re;
  vector<double> tm;
  wf_re.reserve(fid_length);
  tm.reserve(fid_length);

  std::ofstream out;
  out.precision(10);

  for (int i = 0; i < fid_length; i++){
    tm.push_back(i * dt + ti);
  }

  for (int i = 0; i < fid_length; ++i) {
    wf_re.push_back(sin(40 * tm[i]));
  }

  auto wf_im = dsp::hilbert(wf_re);
  arma::cx_vec wf(wf_im.size());

  for (int i = 0; i < wf_re.size(); ++i) {
    wf[i] = arma::cx_double(wf_re[i], wf_im[i]);
  }

  auto wf_rc = dsp::rconvolve(wf, 4000);

  out.open("wvd_test_rc_real.txt");
  for (int i = 0; i < wf_rc.n_elem; ++i) {
    out << wf_rc[i].real() << ",";
  }
  out.close();

  out.open("wvd_test_rc_imag.txt");
  for (int i = 0; i < wf_rc.n_elem; ++i) {
    out << wf_rc[i].imag() << ",";
  }
  out.close();

  return 0;
}

ext: cxx


text:
/*
 * Created by Anton Zhigaylo <antoooon@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the MIT License
 */

#include <atomic>
#include <thread>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <iostream>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#include "common/slog.h"
#include "gateway/MqttGatewayImpl.hpp"

namespace
{
volatile std::sig_atomic_t is_interrupt;

void signalHandler(int sig)
{
    is_interrupt = sig;

    switch (sig)
    {
    case SIGTERM:
    case SIGINT:
    {
        printDebug("MqttGateway/%s: Application termination requested [Signal:%i]", __FUNCTION__, sig);
        break;
    }
    default:
    {
        printError("MqttGateway/%s: Fatal signal obtained: [Signal:%i], exit...", __FUNCTION__, sig);
        _exit(EXIT_FAILURE);
    }
    }
}

void configureSignalHandlers()
{
    struct sigaction sa;
    sa.sa_handler = signalHandler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;

    sigaction(SIGTERM, &sa, NULL);
    sigaction(SIGINT, &sa, NULL);
}

bool isQuit()
{
    return is_interrupt != 0;
}

} // namespace

int main(int argc, const char** argv)
{
    uint32_t debug_level;
    uint32_t debug_sink;
    boost::filesystem::path config_file;
    boost::filesystem::path gtw_table_file;

    boost::program_options::options_description desc("HomeBrain core <-> MQTT Gateway Component Options");
    desc.add_options()
        ("help,h", "produce help message")
        ("debug,d", boost::program_options::value<uint32_t>(&debug_level), "debug level 0-4(err/wr/info/dbg")
        ("sink,s",  boost::program_options::value<uint32_t>(&debug_sink), "debug sink 0-1(console/dlt")
        ("config,c",boost::program_options::value<boost::filesystem::path>(&config_file)->default_value("gtw_table.json"),
                    std::string("Specify gatway table path. By default: 'gtw_table.json'").c_str())
        ("table,t", boost::program_options::value<boost::filesystem::path>(&gtw_table_file)->default_value("gtw_config.json"),
                    std::string("Specify config path. By default: 'gtw_config.json'").c_str());

    boost::program_options::variables_map vm;
    try
    {
        boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);
        boost::program_options::notify(vm);
    }
    catch (const boost::program_options::error& e)
    {
        std::cerr << "Error while parsing: '" << e.what() << "'" << std::endl;
        return EXIT_FAILURE;
    }

    if (vm.count("help"))
    {
        std::cout << desc << std::endl;
        return EXIT_SUCCESS;
    }

    if (vm.count("debug"))
    {
        setDbgLevel(debug_level);
    }

    if (vm.count("sink"))
    {
        setDbgSink(debug_sink);
    }

    if (TRACE_SINK_DLT == getDbgSink())
    {
        initDlt();
        printDebug("MqttGateway/%s: Dlt inited...", __FUNCTION__);
    }

    printDebug("MqttGateway/%s: debug level = %i", __FUNCTION__, debug_level);
    printDebug("MqttGateway/%s: debug sink = %i", __FUNCTION__, debug_sink);
    printDebug("MqttGateway/%s: started with cfg = %s", __FUNCTION__, config_file.string().c_str());

    printDebug("MqttGateway/%s: HomeBrain core <-> MQTT Gateway Starting...", __FUNCTION__);

    try
    {
        std::unique_ptr<MqttGateway::CMqttGatewayImpl> core_gateway;
        core_gateway.reset(new MqttGateway::CMqttGatewayImpl(std::make_shared<Parsers::CConfigParser>(config_file.string()),
                                                             std::make_shared<Parsers::CGtwTableParser>(gtw_table_file.string())));

        core_gateway->performStart();

        // Setup signal handlers
        configureSignalHandlers();

        while(!isQuit())
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
        }

        printDebug("MqttGateway/%s: HomeBrain core <-> MQTT Gateway Stopping...", __FUNCTION__);

        // close all activity
        core_gateway->performStop();

        printDebug("MqttGateway/%s: HomeBrain core <-> MQTT Gateway Stopped...", __FUNCTION__);

        if (TRACE_SINK_DLT == getDbgSink())
        {
            deinitDlt();
            printDebug("MqttGateway/%s: Dlt deinited...", __FUNCTION__);
        }
    }
    catch (const std::exception& e)
    {
        printDebug("MqttGateway/%s: Error description: %s", __FUNCTION__, e.what());
        printDebug("MqttGateway/%s: Gateway is closings", __FUNCTION__);
        if (TRACE_SINK_DLT == getDbgSink())
        {
            deinitDlt();
            printDebug("MqttGateway/%s: Dlt deinited...", __FUNCTION__);
        }
        return 1;
    }

    return EXIT_SUCCESS;
}

ext: cpp

max_stars_repo_name: azhigaylo/mqttgateway

max_issues_repo_name: azhigaylo/mqttgateway

max_forks_repo_name: azhigaylo/mqttgateway


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

    StateIdMapping: function that maps original stateids to destination hg stateids, for either
   HypergraphCopy.hpp copy() or IMutableHypergraph restrict()

    used instead of sdl::function<StateId (StateID)> for metadata e.g. some transformations are
   stateAdding() and some aren't, and performance

    StateIdTranslation: caches StateIdMapping so we don't overgenerate states (in case StateIdMapping is lazy)

    design rationale - uses are:

    1. compress stateid space while deleting some states, e.g. those with no, or
   low-relative-to-best-probability, paths

    2. sort or partition states (no deletion)

    3. concatenate arcs for union or string concatenation, keeping stateid separate

    the mapping can be lazy or eager:

    A. lazy (allocating starting with max stateid+1 of HG you're copying to) - then we'd want a
   sdl::function or whatever, for anything beyond a simple "contiguous as needed" or "fixed offset" (status
   quo)

    B. eager (populate mapping in advance)

    and in-place or copy:

    x. copy: need to add states for range of translation.

    y. in-place: currently, in-place stores a list of all arcs, then clears the resulting HG's adjacencies,
   then transforms labels, start/final state. so, even though the mapping is populated, you need to add states

    and finally, for lazy+pass HG only: kCanonicalLex in resulting transducer - make concatenated share
   lexical states, etc.

    awkwardness:

    Ax (lazy+copy) - either before adding arc create all the states, or when generating the mapping, add the
   state (status quo)

    By (eager+in-place) - for in-place, we don't want states added at all - we haven't removed them yet.
   option: move initialization into post-clear (requires type-erased sdl::function etc for generating the
   mapping)

    kCanonicalLex : in-place: if you want same state for same labelpair, then build the original hg w/
   kCanonicalLex. copy: no problem.

*/

#ifndef STATEIDTRANSLATION_LW20111212_HPP
#define STATEIDTRANSLATION_LW20111212_HPP
#pragma once

#include <sdl/Hypergraph/FwdDecls.hpp>
#include <sdl/Hypergraph/Types.hpp>
#include <sdl/Util/LogHelper.hpp>
#include <sdl/Util/Unordered.hpp>
#include <boost/noncopyable.hpp>
#include <graehl/shared/os.hpp>

namespace sdl {
namespace Hypergraph {

// TODO: use vector? kNoState for unset

// map stateids from source to copy or compacted hg. this is either a lazy complete mapping or partial

// TODO: version of this that supports kCanonicalLex

// TODO: use dynamically expanded, or prealloced, vector w/ explicit kNoState mapping - more
// efficient except in very sparse cases

// note: for 2-best and worse, you don't have the same derivation for each instance of a vertex, necessarily.
// so this might not make sense

struct trivialTag {
  trivialTag() {}
};

namespace {
trivialTag const trivial;
}

struct StateIdMapping {
  virtual char const* name() const { return "StateIdMapping"; }
  virtual bool stateAdding() const { return false; }
  virtual bool identity() const { return false; }
  virtual bool partial() const { return false; }
  /// may return kNoState (partial mapping)
  virtual StateId remap(StateId s) = 0;
  /// may return kNoState; call only for lexical labelpairs (the ones that kCanonicalLex affects)
  virtual StateId remapForLabelPair(StateId s, LabelPair const& io) { return remap(s); }

  virtual ~StateIdMapping() {}
};

typedef shared_ptr<StateIdMapping> StateIdMappingPtr;

struct IdentityIdMapping : public StateIdMapping {
  virtual char const* name() const override { return "IdentityIdMapping"; }
  virtual bool identity() const override { return true; }

  virtual StateId remap(StateId s) override { return s; }
  //  static IdentityIdMapping canonical;
};

struct OffsetIdMapping : public StateIdMapping {
  virtual char const* name() const override { return "OffsetIdMapping"; }
  virtual bool identity() const override { return !offset; }

  virtual StateId remap(StateId s) override { return s + offset; }
  StateId offset;
  OffsetIdMapping(StateId offset) : offset(offset) {}
};

struct ConsecutiveIdMapping : public StateIdMapping {
  virtual char const* name() const override { return "ConsecutiveIdMapping"; }

  virtual StateId remap(StateId s) override { return next++; }
  StateId next;
  ConsecutiveIdMapping(StateId next = 0) : next(next) {}
};

// TODO: common base for IMutableHypergraph for non-arc parts? e.g. addState* methods
// NOTE: these add using the usual interface, so when used in-place we have to copy arcs/labels then clear.
template <class A>
struct StateAddMapping : public StateIdMapping {
  virtual char const* name() const override { return "StateAddMapping"; }
  virtual bool stateAdding() const override { return true; }

  IMutableHypergraph<A>* outHg;
  StateAddMapping(IMutableHypergraph<A>* outHg) : outHg(outHg) {}
  virtual StateId remap(StateId s) override {
    StateId r = outHg->addState();
    SDL_TRACE(Hypergraph.StateIdTranslation, "StateAddMapping remap outhg=" << outHg << " s=" << s << " -> r=" << r
                                                                            << " numStates=" << outHg->size());
    return r;
  }
  virtual StateId remapForLabelPair(StateId s, LabelPair const& io) override { return outHg->addState(io); }
};

template <class A>
struct StateAddIdentityMapping : public StateIdMapping {
  virtual char const* name() const override { return "StateAddMapping"; }
  virtual bool stateAdding() const override { return true; }

  IMutableHypergraph<A>* outHg;
  StateAddIdentityMapping(IMutableHypergraph<A>* outHg) : outHg(outHg) {}
  // we don't declare this as identity because we want to make sure remap is actually called
  virtual StateId remap(StateId s) override {
    StateId r = outHg->addStateId(s);
    SDL_TRACE(Hypergraph.StateIdTranslation, "StateAddMapping remap outhg=" << outHg << " s=" << s << " -> r=" << r
                                                                            << " numStates=" << outHg->size());
    assert(r == s);
    return s;
  }
  virtual StateId remapForLabelPair(StateId s, LabelPair const& io) override { return outHg->addState(io); }
};

template <class A>
struct SubsetStateAddMapping : public StateAddMapping<A> {
  virtual char const* name() const override { return "SubsetStateAddMapping"; }

  virtual bool partial() const override { return true; }

  StateSet const& subset;
  SubsetStateAddMapping(IMutableHypergraph<A>* outHg, StateSet const& subset)
      : StateAddMapping<A>(outHg), subset(subset) {}
  virtual StateId remap(StateId s) override { return remapImpl(s); }
  StateId remapImpl(StateId s) { return Util::contains(subset, s) ? this->outHg->addState() : kNoState; }
  virtual StateId remapForLabelPair(StateId s, LabelPair const& io) override {
    return Util::contains(subset, s) ? this->outHg->addState(io) : kNoState;
  }
};

struct SubsetIdentityMapping : public StateIdMapping {
  virtual char const* name() const override { return "SubsetIdentityMapping"; }

  virtual bool partial() const override { return true; }

  StateSet const& subset;
  SubsetIdentityMapping(StateSet const& subset) : subset(subset) {}
  virtual StateId remap(StateId s) override { return remapImpl(s); }
  StateId remapImpl(StateId s) { return Util::contains(subset, s) ? s : kNoState; }
};

struct StateIdTranslation : boost::noncopyable {
  StateIdMap cache;
  typedef StateIdTranslation self_type;

 private:
  StateIdMapping* map;
  StateIdMappingPtr impl;
  bool partialMap, identityMap, stateAddingMap;

 public:
  std::size_t size() const { return cache.size(); }
  bool partial() const { return partialMap; }
  bool identity() const { return identityMap; }
  bool stateAdding() const { return stateAddingMap; }
  StateIdTranslation(trivialTag) { setIdentity(); }
  /// pointer is from new! will be deleted
  StateIdTranslation(StateIdMapping* map_ = 0) { resetNew(map_); }
  /// reference: not deleted
  StateIdTranslation(StateIdMapping& map_) { reset(&map_); }
  /// 0 pointer gets Identity mapping
  StateIdTranslation(StateIdMappingPtr const& p) : impl(p) {
    if (!impl) impl.reset(new IdentityIdMapping());
    reset(impl.get());
  }
  operator bool() const { return map; }
  void reset(StateIdMapping* map_) {
    map = map_;
    if (map) {
      partialMap = map->partial();
      identityMap = map->identity();
      stateAddingMap = map->stateAdding();
    }
    cache.clear();
    frozenMap = false;  // if true, partial mapping and cache is authoratitive.
  }
  void resetNew(StateIdMapping* map_) {
    impl.reset(map_);
    reset(map_);
  }
  void clear() { resetNew(0); }

  /// adds states to o in order requested
  template <class A>
  StateIdTranslation(IMutableHypergraph<A>* o) {
    resetNew(new StateAddMapping<A>(o));
  }
  /// same, but for only source states in subset
  template <class A>
  StateIdTranslation(IMutableHypergraph<A>* o, StateSet const& subset) {
    resetNew(new SubsetStateAddMapping<A>(o, subset));
  }
  void setIdentity() { resetNew(new IdentityIdMapping()); }

 private:
  bool frozenMap;  // TODO: make hypergraphcopy use this instead of separate Subset methods
 public:
  void freeze() {
    frozenMap = true;
    partialMap = true;
  }
  bool frozen() const { return frozenMap; }
  StateId existingState(StateId s) const {
    return Util::getOrElse(cache, s, kNoState);
    //    if (s==kNoState) return s; // handled above already
  }

  /// be careful: make sure 'to' is a value obtained by stateFor or an existing state
  void add(StateId from, StateId to) { cache.insert(std::pair<StateId, StateId>(from, to)); }
  void setSameAs(StateId a, StateId b) { add(a, stateFor(b)); }

  /// this could be used to predict stateids for a previously empty hypergraph. usually the other version is
  /// used
  StateId stateForImpl(StateId s) {
    if (s == kNoState) return s;
    if (frozenMap) return existingState(s);
    StateId* r;
    if (Util::update(cache, s, r)) {
      return (*r = map->remap(s));
    } else
      return *r;
  }

  StateId stateFor(StateId s) {
    if (s == kNoState) return s;
    StateId r = stateForImpl(s);
    // SDL_TRACE(Hypergraph.StateIdTranslation, "stateFor(" << s<<")=" << r);
    return r;
  }

  StateId addState(StateId s, LabelPair const& io) {
    StateId r = addStateImpl(s, io);
    // SDL_TRACE(Hypergraph.StateIdTranslation, "addState(" << s<<"," << io << ")=" << r);
    return r;
  }

  // for axioms (lexical states w/ no arcs)
  StateId addStateImpl(StateId s, LabelPair const& io) {
    if (frozenMap) return existingState(s);
    StateId* r;
    if (Util::update(cache, s, r)) {
      return (*r = map->remapForLabelPair(s, io));
    } else
      return *r;
  }

  // modify arc in place, returning true if it's kept. you should pre-map the axioms first if you want
  // kCanonicalLex. but maybe some of the axioms aren't useful! hm. maybe detect axiom in here? would need the
  // hg or pre-computed state->axiom? bitvector.
  /// NOTE: this may add states that turn out to be useless, unless you prpopulate then freeze the state
  /// mapping
  template <class A>
  bool relabelArc(A& a) {
    if (identityMap && !stateAddingMap) return true;
    StateIdContainer& ts = a.tails();
    StateId head = stateFor(a.head());
    if (partialMap) {
      if (head == kNoState) return false;
      a.setHead(head);
      for (unsigned i = 0; i < ts.size(); ++i) {
        StateId s = stateFor(ts[i]);
        if (s == kNoState) return false;
        ts[i] = s;
      }
      return true;
    } else {
      a.setHead(head);
      for (unsigned i = 0; i < ts.size(); ++i) ts[i] = stateFor(ts[i]);
      return true;
    }
  }

  template <class A>
  A* copyArc(A const& a) {
    if (identityMap) return new A(a);
    assert(stateAddingMap);
    if (partialMap) {
      StateIdContainer const& ts = a.tails();
      StateId head = stateFor(a.head());
      if (head == kNoState) return 0;
      TailId N = (TailId)ts.size();
      StateIdContainer tails(N);
      for (TailId i = 0; i < N; ++i) {
        StateId ti = stateFor(ts[i]);
        if (ti == kNoState) return 0;
        tails[i] = ti;
      }
      return new A(head, tails, a.weight());
    } else {
      return copyArcWithMappedStates(*this, a);
    }
  }

  template <class A>
  void transferLabelsPartial(IHypergraph<A> const& ihg, IMutableHypergraph<A>& ohg) {
    for (StateIdMap::value_type const& io : cache) ohg.setLabelPair(io.second, ihg.labelPair(io.first));
  }

  template <class A>
  void transferLabels(IHypergraph<A> const& ihg, IMutableHypergraph<A>& ohg) {
    if (frozenMap) {
      transferLabelsPartial(ihg, ohg);
    } else {
      StateId s = 0, e = ihg.size();
      StateId onStates = ohg.size();  // lower bound on true number of states
      for (; s != e; ++s)
        if (ihg.hasLabel(s)) {
          StateId so = stateFor(s);
          if (!stateAddingMap && so >= onStates) {
            // TODO: test
            ohg.addStateId(so);
            onStates = ohg.size();
          }
          if (so != kNoState) ohg.setLabelPair(so, ihg.labelPair(s));
        }
    }
  }

  template <class Out>
  void print(Out& o) const {
    o << map->name();
    if (identityMap) {
      o << "=Identity";
    } else {
      if (frozenMap) o << "(frozen)";
      o << "= {" << printer(cache, Util::multiLine()) << "}";
    }
  }

  template <class C, class T>
  friend std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& o, StateIdTranslation const& self) {
    self.print(o);
    return o;
  }
  template <class C, class T>
  friend std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& o, StateIdTranslation const* selfp) {
    o << "StateIdTranslation@0x" << (void*)selfp << ": ";
    if (selfp) selfp->print(o);
    return o;
  }
};

}}

#endif

ext: hpp

max_stars_repo_name: sdl-research/hyp

max_issues_repo_name: hypergraphs/hyp

max_forks_repo_name: hypergraphs/hyp


text:
/*
 * Copyright (c) 2016-2018 Nicholas Corgan (n.corgan@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#ifndef PKMN_POKEMON_BOX_IMPL_HPP
#define PKMN_POKEMON_BOX_IMPL_HPP

#include "utils/misc.hpp"

#include "pokemon_impl.hpp"

#include <pkmn/pokedex.hpp>
#include <pkmn/pokemon_box.hpp>

#include <boost/thread/lockable_adapter.hpp>
#include <boost/thread/recursive_mutex.hpp>

#include <string>

namespace pkmn {

    class pokemon_box_impl: public pokemon_box,
                            public boost::basic_lockable_adapter<boost::recursive_mutex>
    {
        public:
            pokemon_box_impl() {}
            explicit pokemon_box_impl(
                int game_id
            );

            virtual ~pokemon_box_impl() {}

            pkmn::e_game get_game() final;

            const pkmn::pokemon::sptr& get_pokemon(
                int index
            ) final;

            const pkmn::pokemon_list_t& as_vector() final;

            void* get_native() final;

            // For internal use

            inline void set_pokedex(
                pkmn::pokedex::sptr pokedex
            )
            {
                _pokedex = pokedex;
            }

        protected:
            pkmn::pokemon_list_t _pokemon_list;
            std::string _box_name;

            pkmn::pokedex::sptr _pokedex;

            void* _p_native;

            int _game_id, _generation;

            virtual void _from_native() = 0;
            virtual void _to_native() = 0;
    };

}

#endif /* PKMN_POKEMON_BOX_IMPL_HPP */

max_stars_repo_name: ncorgan/libpkmn

max_issues_repo_name: PMArkive/libpkmn

max_forks_repo_name: PMArkive/libpkmn


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

#include <boost/vmd/is_general_identifier.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/preprocessor/list/at.hpp>
#include <boost/preprocessor/seq/elem.hpp>
#include <boost/preprocessor/tuple/elem.hpp>

int main()
      {

#if BOOST_PP_VARIADICS

    #define A_TUPLE (*,#,zzz)
    #define JDATA somevalue
    #define A_SEQ (num)(%)(#)
    #define A_LIST (eeb,(grist,(&,BOOST_PP_NIL)))

    BOOST_TEST(BOOST_VMD_IS_GENERAL_IDENTIFIER(BOOST_PP_TUPLE_ELEM(2,A_TUPLE)));
    BOOST_TEST(BOOST_VMD_IS_GENERAL_IDENTIFIER(JDATA));
    BOOST_TEST(BOOST_VMD_IS_GENERAL_IDENTIFIER(BOOST_PP_SEQ_ELEM(0,A_SEQ)));
    BOOST_TEST(BOOST_VMD_IS_GENERAL_IDENTIFIER(BOOST_PP_LIST_AT(A_LIST,0)));
    BOOST_TEST(BOOST_VMD_IS_GENERAL_IDENTIFIER(BOOST_PP_LIST_AT(A_LIST,1)));
    BOOST_TEST(!BOOST_VMD_IS_GENERAL_IDENTIFIER());
    BOOST_TEST(!BOOST_VMD_IS_GENERAL_IDENTIFIER(A_TUPLE));
    BOOST_TEST(!BOOST_VMD_IS_GENERAL_IDENTIFIER(A_SEQ));
    BOOST_TEST(!BOOST_VMD_IS_GENERAL_IDENTIFIER(A_LIST));

#else

BOOST_ERROR("No variadic macro support");

#endif

      return boost::report_errors();

      }


text:
//
// Created by Andrew Bailey on 2019-07-19.
//

#ifndef EMBED_FAST5_SRC_FULLSAEVENT_HPP_
#define EMBED_FAST5_SRC_FULLSAEVENT_HPP_

#include <boost/coroutine2/all.hpp>

using namespace std;
using namespace boost::coroutines2;

class FullSaEvent {
 public:
  string contig;
  uint64_t reference_index;
  string reference_kmer;
  string read_file;
  string strand;
  uint64_t event_index;
  double event_mean;
  double event_noise;
  double event_duration;
  string aligned_kmer;
  double scaled_mean_current;
  double scaled_noise;
  double posterior_probability;
  double descaled_event_mean;
  double ont_model_mean;
  string path_kmer;
  ~FullSaEvent();
  FullSaEvent(string contig, uint64_t reference_index, string reference_kmer, string read_file, string strand,
              uint64_t event_index, double event_mean, double event_noise, double event_duration, string aligned_kmer,
              double scaled_mean_current, double scaled_noise, double posterior_probability, double descaled_event_mean,
              double ont_model_mean, string path_kmer);
};

typedef coroutine<FullSaEvent> full_sa_coro;

#endif //EMBED_FAST5_SRC_FULLSAEVENT_HPP_


text:
// -----------------------------------------------------------------------------
// Fern © Geoneric
//
// This file is part of Geoneric Fern which is available under the terms of
// the GNU General Public License (GPL), version 2. If you do not want to
// be bound by the terms of the GPL, you may purchase a proprietary license
// from Geoneric (http://www.geoneric.eu/contact).
// -----------------------------------------------------------------------------
#define BOOST_TEST_MODULE fern ast
#include <boost/test/unit_test.hpp>
#include "fern/language/script/algebra_parser.h"
#include "fern/language/ast/core/vertices.h"
#include "fern/language/ast/xml/xml_parser.h"
#include "fern/language/ast/visitor/io_visitor.h"

namespace fl = fern::language;

class Support
{

public:

    Support()
        : _algebra_parser(),
          _xml_parser(),
          _visitor()
    {
    }

protected:

    fl::AlgebraParser _algebra_parser;

    fl::XmlParser _xml_parser;

    fl::IOVisitor _visitor;

};

BOOST_FIXTURE_TEST_SUITE(module_visitor, Support)

BOOST_AUTO_TEST_CASE(visit_inputs)
{
    std::string xml;
    std::shared_ptr<fl::ModuleVertex> tree;

    // The tree contains four inputs: b, c, a, d.
    tree = _xml_parser.parse_string(_algebra_parser.parse_string(u8R"(
a = foo(b, c, a, d, b)
)"));

    fl::IOVisitor visitor;
    tree->Accept(visitor);

    BOOST_CHECK_EQUAL(tree->scope()->statements().size(), 1u);

    auto inputs = visitor.inputs();
    BOOST_REQUIRE_EQUAL(inputs.size(), 4u);

    BOOST_CHECK_EQUAL(inputs[0], "b");
    BOOST_CHECK_EQUAL(inputs[1], "c");
    BOOST_CHECK_EQUAL(inputs[2], "a");
    BOOST_CHECK_EQUAL(inputs[3], "d");
}

BOOST_AUTO_TEST_CASE(visit_outputs)
{
    std::string xml;
    std::shared_ptr<fl::ModuleVertex> tree;

    // The tree contains five statements. There are four outputs: a, b, c, d.
    // a is overwritten, and only the last a counts as an output. Verify that
    // the last one is indeed reported, instead of the first one.
    tree = _xml_parser.parse_string(_algebra_parser.parse_string(u8R"(
a = 5
b = 6
c = 7
a = 8
d = 9
)"));

    fl::IOVisitor visitor;
    tree->Accept(visitor);

    BOOST_CHECK_EQUAL(tree->scope()->statements().size(), 5u);

    fl::AssignmentVertex const* assignment;
    fl::NameVertex const* a_1 = nullptr;
    fl::NameVertex const* a_2 = nullptr;
    fl::NameVertex const* b = nullptr;
    fl::NameVertex const* c = nullptr;
    fl::NameVertex const* d = nullptr;

    assignment = dynamic_cast<fl::AssignmentVertex const*>(
        &(*tree->scope()->statements()[0]));
    a_1 = dynamic_cast<fl::NameVertex const*>(&(*assignment->target()));
    BOOST_REQUIRE(a_1);

    assignment = dynamic_cast<fl::AssignmentVertex const*>(
        &(*tree->scope()->statements()[1]));
    b = dynamic_cast<fl::NameVertex const*>(&(*assignment->target()));
    BOOST_REQUIRE(b);

    assignment = dynamic_cast<fl::AssignmentVertex const*>(
        &(*tree->scope()->statements()[2]));
    c = dynamic_cast<fl::NameVertex const*>(&(*assignment->target()));
    BOOST_REQUIRE(c);

    assignment = dynamic_cast<fl::AssignmentVertex const*>(
        &(*tree->scope()->statements()[3]));
    a_2 = dynamic_cast<fl::NameVertex const*>(&(*assignment->target()));
    BOOST_REQUIRE(a_2);

    assignment = dynamic_cast<fl::AssignmentVertex const*>(
        &(*tree->scope()->statements()[4]));
    d = dynamic_cast<fl::NameVertex const*>(&(*assignment->target()));
    BOOST_REQUIRE(d);

    auto outputs = visitor.outputs();
    BOOST_REQUIRE_EQUAL(outputs.size(), 4u);

    BOOST_CHECK_EQUAL(outputs[0], b);
    BOOST_CHECK_EQUAL(outputs[1], c);
    BOOST_CHECK_EQUAL(outputs[2], a_2);
    BOOST_CHECK_EQUAL(outputs[3], d);
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
/********************************************************************************

Copyright (c) 2017 Bob Perry / asw204k_AT_yahoo.com
All rights reserved.

Please see license in the project root directory fro more details

*/

#include <boost/chrono.hpp>
#include <cstdlib>
#include <cassert>
#include <string>
#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include "oxmem.h"
#include "oxbluebus.h"
#include "oxBlueDevice.h"
#include "named_store.h"

#include "trivial_log.h"

using namespace std;

class TestBlueDevice : public OxBlueDevice {

public:
  TestBlueDevice( const string &name ) : OxBlueDevice( name ) {}
  void rw_device() {
    string msg("This is a test.\n");
    bus->write(msg);
  }
  ~TestBlueDevice(){}
};

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

  init_log();

  string remote_device = "00:06:66:73:E6:0D";

  OxBluebus bus( remote_device ,1 );
  TestBlueDevice test_device( "Test Device" );

  bus.add_device( &test_device );
  bus.run();

  b::this_thread::sleep(b::posix_time::milliseconds(100));

  bus.stop();

  cerr << endl << "complete" << endl;;

  return 0;
}

max_stars_repo_name: perryrob/oxcart

max_issues_repo_name: perryrob/oxcart

max_forks_repo_name: perryrob/oxcart


text:
//
// Copyright (c) 2018-2019 Christian Mazakas (christian dot mazakas at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/LeonineKing1199/foxy
//

#include <foxy/utility.hpp>
#include <foxy/test/helpers/ssl_ctx.hpp>
#include <boost/asio/buffer.hpp>

namespace ssl  = boost::asio::ssl;
namespace asio = boost::asio;

auto
foxy::test::make_server_ssl_ctx() -> boost::asio::ssl::context
{
  auto ctx = ssl::context(ssl::context::method::tlsv12_server);

  auto const cert = boost::string_view(
    "-----BEGIN CERTIFICATE-----\n"
    "MIIDWzCCAkMCFEkgH0LSdOVvLn/i+NRjXLmhgXjGMA0GCSqGSIb3DQEBCwUAMHsx\n"
    "CzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRMwEQYDVQQHDApTYWNy\n"
    "YW1lbnRvMSAwHgYDVQQKDBdDb2RlciBpbiBhIENhdmUgU3R1ZGlvczEgMB4GA1UE\n"
    "AwwXQ29kZXIgaW4gYSBDYXZlIFN0dWRpb3MwHhcNMTkwOTE1MjM0MjQzWhcNMjQw\n"
    "OTEzMjM0MjQzWjBZMQswCQYDVQQGEwJVUzETMBEGA1UECAwKU29tZS1TdGF0ZTEh\n"
    "MB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMRIwEAYDVQQDDAkxMjcu\n"
    "MC4wLjEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDhXSGTS78ZuAJN\n"
    "ou764hvCOP9yY02sgCcZJ0Ykni8SK/cE0USCe1VEiWgwcedLAJgRvkEhtvinsSFk\n"
    "mUGkmaOy+dwg0lgjmuIlhsi3rA2ngprjcLVqPriwNfVBhkKb+cztwjnrNomxq/Ab\n"
    "/sX2lDAb6VbfVTNnmMT5QbOljzYf82gWc6pYcm5pixooQBD+W52ehq/jpPMYvoqY\n"
    "Vqnz/XKT8NvO3bMhbG2hgKxlocpznog61ih9N39OISbdLDbNXNrkpFfs/ST3I2mK\n"
    "5juVyQuBoJftJOHc+xtlPRcJfRMWSigGrXc4Nv61GJgBv+PwqpJpwjHe/bEc2h8D\n"
    "JJpZ1tuZAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAJWIJoWb035YgXRrW8Qd0TWy\n"
    "n3DmFdN0AEaS7JVrA8zqpGNwZmShvLV4YEEasO/NHXU0qpxuoiKhAAB+e/QEutBP\n"
    "o5gopns4T3irRJYb++RDaVbJwpl1VmenSRDkg5wQT6ZoH3l4coxrD8nbF2mOz3jP\n"
    "VGuG0JhT80rGuOyHVgRz2ilRMgsBc0svPcIo9oNHFQnDCp4uArBhRp+LEK72nZ3J\n"
    "X75SCLwET3fg5QCsfvGQp9cvBqgMWYL9NhXD68xkLlzoWVoGZeM4Pe/QS9A/Eyqu\n"
    "m48CeYe3QQpC395iTjgn0eW6Y/Qaicu7znwIfaVPS+049Lp/HdKL4jFjiv2Kt/A=\n"
    "-----END CERTIFICATE-----\n");

  auto const key = boost::string_view(
    "-----BEGIN RSA PRIVATE KEY-----\n"
    "MIIEpQIBAAKCAQEA4V0hk0u/GbgCTaLu+uIbwjj/cmNNrIAnGSdGJJ4vEiv3BNFE\n"
    "gntVRIloMHHnSwCYEb5BIbb4p7EhZJlBpJmjsvncINJYI5riJYbIt6wNp4Ka43C1\n"
    "aj64sDX1QYZCm/nM7cI56zaJsavwG/7F9pQwG+lW31UzZ5jE+UGzpY82H/NoFnOq\n"
    "WHJuaYsaKEAQ/ludnoav46TzGL6KmFap8/1yk/Dbzt2zIWxtoYCsZaHKc56IOtYo\n"
    "fTd/TiEm3Sw2zVza5KRX7P0k9yNpiuY7lckLgaCX7STh3PsbZT0XCX0TFkooBq13\n"
    "ODb+tRiYAb/j8KqSacIx3v2xHNofAySaWdbbmQIDAQABAoIBAQDJ7AgJUfUHtjda\n"
    "GILHh5AXlbpLY25VAP4HK4lNhe3m+j15s4cO4jKkFfmkbmouaXnXbAAvlSF2Ht8s\n"
    "o6SNNpvV4Mm7HryaKkw2E24EI8SYMg1Ve8cQSuJv/+ifrQxBdLCI113Nwi/dYZDh\n"
    "hIUbSetRFuEfedd1GwxhyNyNmqOEO4R6dnt1rTmFhtXqHaUWbrCuTp5t3JrnQQO+\n"
    "jPgLd35G9A1hjXQ0CFUzkd1JuVJdx/U6nN4JKWc2qimQ8t1YpPQ0v8I6Q2DrPmIe\n"
    "pY7bh7wheZ2JwsJ0spgtTfUwCP3LZfQ/UW5BdjHtxnwlyuoHWLB8dgD8XfJHvwd4\n"
    "+p1HN7YBAoGBAPiIMOUk3rU2hOklLU3TvpD4/GtzhO08KR9T4XrPG4lMJ2/fx4OG\n"
    "XqYFWA1hkY7f1Lc9L1LxeOUAfNEagC7K9nz8ESVa8ink4X2F1IwIyDAU19aTvYK4\n"
    "9e4LrM9C9td6BQF0r3jemmN1qjV1naRWj4z8MlW3O2hBRo9RijOVMrQ1AoGBAOgi\n"
    "uI9v8mJXtrDeTAjVbSqnfw0Ra3WXi1ONfOXvPjldnCHCmwsv7PRpET/jvPZrWvaB\n"
    "96RpiEMcClDCaJX62zhEtCk/2Or2xvSureCnRavzmFmKF2Ehjom0ova6rImlmdWh\n"
    "u2NpfxXb/nR9mBClrElG47diW4qucHpiNo4aEa5VAoGAdAjx+yoZqLWJnGi1HC8O\n"
    "PBVjlK9ckn6SHIRHM9VaX+HkT8FFH00vB4hbMfQpx3ENmXfBjpIbBaASpnYe/rnY\n"
    "F0aAotYxVgn8lWRUdgTrojc5Bn/37P56I+fjiOkU4kmf6KwX+PDFWEZpb4g4T6/y\n"
    "WbqtrYNdAzHmxacmRSsVfzkCgYEA3cAVSEhrZdBen9SrE6E1+JIqx0QFwD51BOrb\n"
    "Dhed/FTVClcJnwU4OT6JENwvrcJeEa+T7oY1ec42eHFOUT9i3Pycke8A+2ukIScg\n"
    "yMNhxeIcfiRxMwNIU3mwVzt6CL+eFbq69DtaAHq4N3WmpvhsfU9vxsX5pp/+qJpb\n"
    "fSGgFEUCgYEA6iyrZxQ5QDIZMqzJYXsB6FW4TnAB5sEUTWzoOfsvs3iRMB/y/yhp\n"
    "pG1N/bFkTnAmwU8/Hp9ZozFXMUxb3AHnWMeg6YPhTYvUj5X1NzsCvSR3KX+V/crC\n"
    "84+kQvgny42OaKjwmvTbRCqv7/iOZzSqCSwMytcFVx11NO4+FMFSUp4=\n"
    "-----END RSA PRIVATE KEY-----\n");

  ctx.set_options(ssl::context::default_workarounds | ssl::context::no_sslv2 |
                  ssl::context::single_dh_use);

  ctx.use_certificate_chain(asio::buffer(cert.data(), cert.size()));
  ctx.use_private_key(asio::buffer(key.data(), key.size()), ssl::context::file_format::pem);

  return ctx;
}

auto
foxy::test::make_client_ssl_ctx() -> boost::asio::ssl::context
{
  auto ctx = ssl::context(ssl::context::method::tlsv12_client);

  foxy::certify::enable_https_verification(ctx);
  ctx.set_verify_mode(ssl::context::verify_peer | ssl::context::verify_fail_if_no_peer_cert);

  ctx.load_verify_file("root-cas.pem");

  // This is our root CA that was used to sign the server's certificate
  //
  auto const root_ca = boost::string_view(
    "-----BEGIN CERTIFICATE-----\n"
    "MIID1zCCAr+gAwIBAgIUBzm5/pOjqdVMVfoTQgGf8RxiuAkwDQYJKoZIhvcNAQEL\n"
    "BQAwezELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExEzARBgNVBAcM\n"
    "ClNhY3JhbWVudG8xIDAeBgNVBAoMF0NvZGVyIGluIGEgQ2F2ZSBTdHVkaW9zMSAw\n"
    "HgYDVQQDDBdDb2RlciBpbiBhIENhdmUgU3R1ZGlvczAeFw0xOTA5MTUyMzI4MDha\n"
    "Fw0yNDA5MTMyMzI4MDhaMHsxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9y\n"
    "bmlhMRMwEQYDVQQHDApTYWNyYW1lbnRvMSAwHgYDVQQKDBdDb2RlciBpbiBhIENh\n"
    "dmUgU3R1ZGlvczEgMB4GA1UEAwwXQ29kZXIgaW4gYSBDYXZlIFN0dWRpb3MwggEi\n"
    "MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDDBUCUPopmLtS8Zpd9zMz0+9Br\n"
    "iP4DqRfciqe9ltRBJGvFVaXpyDjknQPcl+cfKiw/4DKRDUnb6EmGk3v8PcVtPIF7\n"
    "ko59URmMelgxdhQSW6oraUGp0xE9UVsRVJYNpnnqAg0rUwwTKAKJx+7aAx75eWEn\n"
    "seWFZK7plZwGFDkvEvAgKsXDSZGjTqgcsbpWaJQ1o3XRhNcIfakhe6pA4hVlIBqM\n"
    "NgeDqCwLgvnRwqNtfFPNCcjizIngX7Jc48MhtgcGKKYo1ddUwE9lj32kB5rpk5wt\n"
    "a6fPkvWYDFu2gWDgtxxEO0bJJkFxPRbppNHxQp00h8ojk+QFDePCd9EAGGPDAgMB\n"
    "AAGjUzBRMB0GA1UdDgQWBBQIo4VHujILmom1rPijIu1U8ndLZDAfBgNVHSMEGDAW\n"
    "gBQIo4VHujILmom1rPijIu1U8ndLZDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3\n"
    "DQEBCwUAA4IBAQBcnGgLMMRhLq0WuoedkxG/G6zuStoDiuGtKzg0TYvdgegOjpHl\n"
    "PsCQmCEUcPMFoo+ohqlZMwoLTZNv02JpRaiBGbOFFNvLQM/cyQ5neGb+o5zmoJAW\n"
    "jG5gzY1mQB3KGq+tP/IBvvdGkq7aqC3Qmnvqr5+3qO6sFzQlXGuH6Qwai8mZJhLB\n"
    "zV6lehqLWuFiWfmAe08V9jDSaMR4mQEYPdi4vkxu8L1/yI12tptdkYoTleQ+qJiy\n"
    "CGwuI6o0hcJWpOEJBkut35FagHqjL54ORLUYQ13kRIaHQkSQ8UgAEa/TbhGDqqjU\n"
    "bPbxZffpGVFTPP02ILYH3/cS6hN1vjltNk/4\n"
    "-----END CERTIFICATE-----\n");

  ctx.add_certificate_authority(asio::const_buffer(root_ca.data(), root_ca.size()));

  return ctx;
}

max_stars_repo_name: Olipro/foxy

max_issues_repo_name: Olipro/foxy

max_forks_repo_name: Olipro/foxy


text:
// HTTP credits: http://lcs.ios.ac.cn/~maxt/SPelton/reports/report-9aa0d3.html
// JSON credits: https://github.com/nlohmann/json
#include <fstream>
#include <iostream>
#include <string>
#include <set>
#include <ctime>
#include <chrono>
#include "./http_stuff.h"
#include "./json.hpp"
#include "gameState.h"
#include <pthread.h>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace nlohmann;

std::string moves[4] = {"up", "down", "left", "right"};
extern int move(Board &board, Game &game, Turn &turn, You &you, std::set<pair<int, int> > &obstacles);
extern void init_data(const json &data, Board &board, Game &game, Turn &turn,
                      You &you, std::set<pair<int, int> > &obstacles);
pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER;
extern int DEBUG_PRINT;

void test_main(void) {
  /* For testing only */
  auto data = R"(
    {"board":{"food":[{"x":8,"y":2},{"x":10,"y":10},{"x":10,"y":4},{"x":6,"y":8},{"x":0,"y":0},{"x":2,"y":8},{"x":0,"y":6},{"x":4,"y":2}],"hazards":[],"height":11,"snakes":[{"body":[{"x":9,"y":10},{"x":9,"y":9},{"x":9,"y":8}],"head":{"x":9,"y":10},"health":91,"id":"gs_kTKcxB9w99BfGqD3rSbjtPhM","latency":"58","length":3,"name":"testsnake","shout":""},{"body":[{"x":1,"y":10},{"x":1,"y":9},{"x":1,"y":8}],"head":{"x":1,"y":10},"health":91,"id":"gs_XrdgvBhQGD34j86TRgFwP3D3","latency":"61","length":3,"name":"testsnake","shout":""},{"body":[{"x":5,"y":10},{"x":5,"y":9},{"x":5,"y":8},{"x":5,"y":7}],"head":{"x":5,"y":10},"health":95,"id":"gs_p4RGYfGGkCfjqBhYqVBRjQKM","latency":"120","length":4,"name":"testsnake","shout":""}],"width":11},"game":{"id":"e437218a-ddd4-486c-a18f-cb0af1ae05bc","ruleset":{"name":"standard","version":"v1.0.17"},"timeout":500},"turn":9,"you":{"body":[{"x":9,"y":10},{"x":9,"y":9},{"x":9,"y":8}],"head":{"x":9,"y":10},"health":91,"id":"gs_kTKcxB9w99BfGqD3rSbjtPhM","latency":"58","length":3,"name":"testsnake","shout":""}}
  )"_json;

  Board board;
  Game game;
  Turn turn;
  You you;
  std::set<pair<int, int> > obstacles;
  init_data(data, board, game, turn, you, obstacles);
  //int index = move(board, game, turn, you, obstacles);
}

void run_program(void) {
  httplib::Server svr;
  svr.Get("/", [](const auto &, auto &res) {
    string head = "default";  // TODO: Change head
    string tail = "default";  // TODO: Change tail
    string author = "NaN";
    string color = "#888888";  // TODO: Change a hex color
    res.set_content("{\"apiversion\":\"1\", \"head\":\"" + head +
                        "\", \"tail\":\"" + tail + "\", \"color\":\"" + color +
                        "\", " + "\"author\":\"" + author + "\"}",
                    "text/json");
  });
  svr.Post("/end", [](const auto &, auto &res) {
    res.set_content("ok", "text/plain");
  });
  svr.Post("/start", [](const auto &, auto &res) {
    res.set_content("ok", "text/plain");
  });
  svr.Post("/move", [](auto &req, auto &res) {
    const json data = json::parse(req.body);
    const boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
    const boost::posix_time::time_duration td = now.time_of_day();
    const long hours        = td.hours();
    const long minutes      = td.minutes();
    const long seconds      = td.seconds();
    const long milliseconds = td.total_milliseconds() -
                              ((hours * 3600 + minutes * 60 + seconds) * 1000);

    if (DEBUG_PRINT) {
      cout << "====== new snake state " << milliseconds << " ============" << endl;
      pthread_mutex_lock(&print_mutex);
      cout << data;
      cout << "\n\n";
      pthread_mutex_unlock(&print_mutex);
    }

    Board board;
    Game game;
    Turn turn;
    You you;

    std::set<pair<int, int> > obstacles;

    init_data(data, board, game, turn, you, obstacles);
    int index = move(board, game, turn, you, obstacles);
    res.set_content("{\"move\": \"" + moves[index] + "\"}", "text/plain");
  });

  svr.listen("0.0.0.0", 8080);
  std::cout << "Server started";
}

int main(void) {
  // test_main();
  run_program();
  return 0;
}


text:
#ifndef ANALYSESYMBOLSTASK_HXX
#define ANALYSESYMBOLSTASK_HXX

#include "task.hxx"

#include <boost/program_options.hpp>

class Analyse_Task : public Task {
private:
  boost::program_options::variables_map vm;
  unsigned int mNumThreads = 1;

public:
  using Task::Task;
  boost::program_options::options_description options() override;
  void parse_args(const std::vector<std::string>& args) override;
  void execute(Database3& db) override;
};

#endif // ANALYSESYMBOLSTASK_HXX

ext: hxx

max_stars_repo_name: Sigill/Elfxplore

max_issues_repo_name: Sigill/Elfxplore

max_forks_repo_name: Sigill/Elfxplore


text:
// This file is part of LatNet Builder.
//
// Copyright (C) 2012-2021  The LatNet Builder author's, supervised by Pierre L'Ecuyer, Universite de Montreal.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "netbuilder/NetConstructionTraits.h"

#include "latbuilder/SeqCombiner.h"
#include "latbuilder/Traversal.h"

#include <boost/dynamic_bitset.hpp>
#include <vector>
#include <list>

#include "latbuilder/TextStream.h"

namespace NetBuilder {

    const std::string NetConstructionTraits<NetConstruction::SOBOL>::name = "Sobol";

    typedef typename NetConstructionTraits<NetConstruction::SOBOL>::GenValue GenValue;

    typedef typename NetConstructionTraits<NetConstruction::SOBOL>::SizeParameter SizeParameter;

    bool NetConstructionTraits<NetConstruction::SOBOL>::checkGenValue(const GenValue& genValue, const SizeParameter& sizeParameter)
    {
        auto dimension = genValue.first;

        if (dimension==0)
        {
            return (genValue.second.size()==1 && genValue.second.front()==0);
        }

        unsigned int degree = nthPrimitivePolynomialDegree(dimension);

        if (genValue.second.size() != degree){
            return false;
        }

        for(unsigned int j = 0; j < degree; ++j)
        {
              if (!(genValue.second[j] % 2 == 1)){ //each direction number is odd
                  return false;
              }
              if (!(genValue.second[j]< (unsigned int) (2<<j))){ // each direction number is small enough
                  return false;
              }
        }
        return true;
    }

    unsigned int NetConstructionTraits<NetConstruction::SOBOL>::nRows(const SizeParameter& param) { return (unsigned int) param; }

    unsigned int NetConstructionTraits<NetConstruction::SOBOL>::nCols(const SizeParameter& param) { return (unsigned int) param; }

    static const std::array<unsigned int,21200> degrees =
    {{
        #include "../data/primitive_polynomials_degrees.csv"
    }};

    static const std::array<unsigned long,21200> representations =
    {{
        #include "../data/primitive_polynomials_representations.csv"
    }};

    NetConstructionTraits<NetConstruction::SOBOL>::PrimitivePolynomial  NetConstructionTraits<NetConstruction::SOBOL>::nthPrimitivePolynomial(Dimension n)
    {
        // primitive polynomials are hard-coded because their computation is really complex.
        if (n>0 && n <= 21200)
        return std::pair<unsigned int,uInteger>(degrees[n-1],representations[n-1]);
        else{
            return std::pair<unsigned int,uInteger>(0,0);
        }
    }

    unsigned int  NetConstructionTraits<NetConstruction::SOBOL>::nthPrimitivePolynomialDegree(Dimension n)
    {
        // primitive polynomials are hard-coded because their computation is really complex.
        if (n>0 && n <= 21200)
        return degrees[n-1];
        else{
            return 0;
        }
    }

    void makeIteration(GeneratingMatrix& mat, std::list<boost::dynamic_bitset<>>& reg, const boost::dynamic_bitset<>& mask, unsigned int k)
    {
        assert(k <= mat.nCols() && k<= mat.nRows());
        boost::dynamic_bitset<> newDirNum = reg.front();
        newDirNum.resize(k);
        assert(reg.size()==mask.size());
        unsigned j = 0;
        for(boost::dynamic_bitset<> tmp : reg)
        {
            if (mask[j])
            {
                tmp.resize(k);
                tmp = tmp << (reg.size()-j);
                newDirNum ^= tmp;
            }
            ++j;
        }
        reg.pop_front();
        for(unsigned int i = 0; i < k; ++i)
        {
            mat(i, k-1) = newDirNum[k-i-1];
        }
        reg.push_back(std::move(newDirNum));
    }

    GeneratingMatrix*  NetConstructionTraits<NetConstruction::SOBOL>::createGeneratingMatrix(const GenValue& genValue, const SizeParameter& sizeParam, const Dimension& dimension_j, const unsigned int nRows)
    {
        unsigned int m  = nCols(sizeParam);
        unsigned int finalnRows = (nRows == 0)? m : nRows;
        Dimension coord = genValue.first;

        if (coord==0) // special case for the first dimension
        {
            GeneratingMatrix* tmp = new GeneratingMatrix(m,m);
            for(unsigned int k = 0; k<m; ++k){
            (*tmp)(k,k) = 1; // start with identity
            }
            return tmp;
        }

        // compute the vector defining the linear recurrence on the columns of the matrix
        PrimitivePolynomial p = nthPrimitivePolynomial(coord);
        auto degree = p.first;
        auto poly_rep = p.second;
        boost::dynamic_bitset<> mask(degree,(poly_rep << 1) + 1);
        unsigned int matrixSize = std::max(degree,m);
        GeneratingMatrix* tmp = new GeneratingMatrix(matrixSize, matrixSize);
        std::list<boost::dynamic_bitset<>> reg;
        unsigned int k = 1;
        for(auto dirNum : genValue.second)
        {
            reg.push_back(boost::dynamic_bitset<>(k,dirNum));
            for(unsigned int i = 0; i < k; ++i)
            {
                (*tmp)(i,k-1) = reg.back()[k-i-1];
            }
            ++k;
        }
        while (k<=matrixSize)
        {
            makeIteration(*tmp, reg, mask, k);
            ++k;
        }
        tmp->resize(finalnRows, m);
        return tmp;
    }

   NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::GenValueSpaceCoordSeq(Dimension coord):
    m_coord(coord),
    m_underlyingSeq(underlyingSeqs(coord))
    {};

    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::const_iterator(const GenValueSpaceCoordSeq& seq):
        m_coord(seq.coord()),
        m_underlyingIterator(seq.underlyingSeq().begin()),
        m_value(GenValue(m_coord, *m_underlyingIterator))
    {};

    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::const_iterator(const GenValueSpaceCoordSeq& seq, end_tag):
        m_coord(seq.coord()),
        m_underlyingIterator(seq.underlyingSeq().end())
    {};

    bool NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::equal(const const_iterator& other) const
    {
        return m_underlyingIterator == other.m_underlyingIterator;
    }

    const NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::value_type& NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::dereference() const
    {
        return m_value;
    }

    void NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator::increment()
    {
        if (m_underlyingIterator != m_underlyingIterator.seq().end())
        {
            ++m_underlyingIterator;
            m_value = GenValue(m_coord, *m_underlyingIterator);
        }
    }

    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::begin() const
    {
        return const_iterator(*this);
    }

    NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::const_iterator NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::end() const
    {
        return const_iterator(*this, typename const_iterator::end_tag{} );
    }

    Dimension NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::coord() const
    {
        return m_coord;
    }

    size_t  NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::size() const
    {
        return m_underlyingSeq.size();
    }

    const LatBuilder::SeqCombiner<std::vector<uInteger>,LatBuilder::CartesianProduct>& NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::underlyingSeq() const
    {
        return m_underlyingSeq;
    }

    std::vector<std::vector<uInteger>> NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq::underlyingSeqs(Dimension coord)
    {
        if (coord == 0)
        {
            return {{0}};
        }
        else
        {
            unsigned int size = nthPrimitivePolynomialDegree(coord);
            std::vector<uInteger> dirNums{1};
            dirNums.reserve( (1 << (size - 1))  - 1);

            std::vector<std::vector<uInteger>> seqs;
            seqs.reserve(size);
            seqs.push_back(dirNums);

            uInteger upperBound = 2;
            for(unsigned int i = 1; i < size; ++i)
            {
                upperBound = 2 * upperBound;
                for(uInteger k = dirNums.back() + 2; k < upperBound; k += 2)
                {
                    dirNums.push_back(k);
                }
                seqs.push_back(dirNums);
            }
            return seqs;
        }
    }

    typename NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceCoordSeq NetConstructionTraits<NetConstruction::SOBOL>::genValueSpaceCoord(Dimension coord, const SizeParameter& sizeParameter)
    {
        return GenValueSpaceCoordSeq(coord);
    }

    typename NetConstructionTraits<NetConstruction::SOBOL>::GenValueSpaceSeq NetConstructionTraits<NetConstruction::SOBOL>::genValueSpace(Dimension dimension, const SizeParameter& sizeParameter)
    {
        std::vector<GenValueSpaceCoordSeq> seqs;
        seqs.reserve(dimension);
        for(Dimension coord = 0; coord < dimension; ++coord)
        {
            seqs.push_back(genValueSpaceCoord(coord, sizeParameter));
        }
        return GenValueSpaceSeq(seqs);
    }

    std::string NetConstructionTraits<NetConstruction::SOBOL>::format(const std::vector<std::shared_ptr<GeneratingMatrix>>& genMatrices, const std::vector<std::shared_ptr<GenValue>>& genVals, const SizeParameter& sizeParameter, OutputStyle outputStyle, unsigned int interlacingFactor)
    {
        std::string res;
        std::string dimension = std::to_string(genVals.size()/interlacingFactor);
        unsigned int k = nCols(sizeParameter);

        if (outputStyle == OutputStyle::TERMINAL){
            res += "Sobol Digital Net - Direction numbers =\n";
            for (unsigned int coord = 0; coord < genVals.size(); coord++){
                res+="  ";
                for(const auto& dirNum : genVals[coord]->second)
                {
                    res+= std::to_string(dirNum);
                    res+= " ";
                }
                res.pop_back();
                res+="\n";
            }
        }

        else if (outputStyle == OutputStyle::SOBOLJK){
            res += "# Parameters for Sobol points, in JK format\n";
            res += dimension + "    # s = " + dimension + " dimensions\n";
            if (interlacingFactor > 1){
                res+= std::to_string(interlacingFactor) + "    # Interlacing factor" + "\n";
                res+= std::to_string(genVals.size()) + "    # Number of components = interlacing factor x dimension" + "\n";
            }
            res += std::to_string(k) + "    # k = " + std::to_string(k) + ",  n = 2^"+ std::to_string(k) + " = " + std::to_string((int)pow(2, k)) + " points\n";
            res +="#  d  a  m_{j,c}\n";
            for (unsigned int coord = 1; coord < genVals.size(); coord++){
                res+= std::to_string(coord +1) + "  ";
                PrimitivePolynomial p = nthPrimitivePolynomial(coord);
                auto degree = p.first;
                auto poly_rep = p.second;
                res+= std::to_string(degree) + "  ";
                res+= std::to_string(poly_rep) + "  ";
                for(const auto& dirNum : genVals[coord]->second)
                {
                    res+= std::to_string(dirNum);
                    res+= " ";
                }
                res.pop_back();
                res+="\n";

            }
            res.pop_back();
        }

        else if (outputStyle == OutputStyle::SOBOL){
            res += "# Initial direction numbers m_{j,c} for Sobol points\n";
            res += dimension + "    # s = " + dimension + " dimensions\n";
            if (interlacingFactor > 1){
                res+= std::to_string(interlacingFactor) + "    # Interlacing factor" + "\n";
                res+= std::to_string(genVals.size()) + "    # Number of components = interlacing factor x dimension" + "\n";
            }
            res += std::to_string(k) + "    # k = " + std::to_string(k) + ",  n = 2^"+ std::to_string(k) + " = " + std::to_string((int)pow(2, k)) + " points\n";
            res +="# m_{j,c}, starting from the second coordinate\n";
            for (unsigned int coord = 1; coord < genVals.size(); coord++){
                for(const auto& dirNum : genVals[coord]->second)
                {
                    res += std::to_string(dirNum);
                    res += " ";
                }
                res.pop_back();
                res+="\n";

            }
            res.pop_back();
        }
        return res;
    }
}

max_stars_repo_name: umontreal-simul/latnetbuilder

max_issues_repo_name: umontreal-simul/latbuilder

max_forks_repo_name: umontreal-simul/latbuilder


text:
// Copyright (c) 2018 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "chain.h"
#include "test/test_bitcoin.h"

#include <boost/test/unit_test.hpp>

#include <set>

namespace{ class blockstatus_tests_uid; } // only used as unique identifier

template <>
struct BlockStatus::UnitTestAccess<blockstatus_tests_uid>
{
    UnitTestAccess() = delete;

    static void CheckBlockStatus(const BlockStatus s, BlockValidity validity,
                                 bool hasData, bool hasUndo, bool hasFailed,
                                 bool hasFailedParent) {
        BOOST_CHECK(s.getValidity() == validity);
        BOOST_CHECK_EQUAL(s.hasData(), hasData);
        BOOST_CHECK_EQUAL(s.hasUndo(), hasUndo);
        BOOST_CHECK_EQUAL(s.hasFailed(), hasFailed);
        BOOST_CHECK_EQUAL(s.hasFailedParent(), hasFailedParent);
        BOOST_CHECK_EQUAL(s.isInvalid(), hasFailed || hasFailedParent);
    }

    static BlockStatus WithData(BlockStatus s, bool hasData)
    {
        return s.withData( hasData );
    }

    static BlockStatus WithUndo(BlockStatus s, bool hasUndo)
    {
        return s.withUndo( hasUndo );
    }
};
using TestBlockStatus = BlockStatus::UnitTestAccess<blockstatus_tests_uid>;

BOOST_FIXTURE_TEST_SUITE(blockstatus_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(sighash_construction_test) {
    // Check default values.
    TestBlockStatus::CheckBlockStatus(BlockStatus(), BlockValidity::UNKNOWN, false, false, false,
                     false);

    // Check all possible permutations.
    std::set<BlockValidity> baseValidities{
        BlockValidity::UNKNOWN, BlockValidity::HEADER,
        BlockValidity::TREE,    BlockValidity::TRANSACTIONS,
        BlockValidity::CHAIN,   BlockValidity::SCRIPTS};
    std::set<bool> hasDataValues{false, true};
    std::set<bool> hasUndoValues{false, true};
    std::set<bool> hasFailedValues{false, true};
    std::set<bool> hasFailedParentValues{false, true};

    for (BlockValidity validity : baseValidities) {
        for (bool hasData : hasDataValues) {
            for (bool hasUndo : hasUndoValues) {
                for (bool hasFailed : hasFailedValues) {
                    for (bool hasFailedParent : hasFailedParentValues) {
                        BlockStatus s =
                            BlockStatus()
                                .withValidity(validity)
                                .withFailed(hasFailed)
                                .withFailedParent(hasFailedParent);
                        s = TestBlockStatus::WithData(s, hasData);
                        s = TestBlockStatus::WithUndo(s, hasUndo);

                        TestBlockStatus::CheckBlockStatus(s, validity, hasData, hasUndo,
                                         hasFailed, hasFailedParent);

                        // Clears failure flags.
                        TestBlockStatus::CheckBlockStatus(s.withClearedFailureFlags(), validity,
                                         hasData, hasUndo, false, false);

                        // Also check all possible alterations.
                        TestBlockStatus::CheckBlockStatus(
                            TestBlockStatus::WithData(s, hasData),
                            validity,
                            hasData,
                            hasUndo,
                            hasFailed,
                            hasFailedParent);
                        TestBlockStatus::CheckBlockStatus(
                            TestBlockStatus::WithData(s, !hasData),
                            validity,
                            !hasData,
                            hasUndo,
                            hasFailed,
                            hasFailedParent);
                        TestBlockStatus::CheckBlockStatus(
                            TestBlockStatus::WithUndo(s, hasUndo),
                            validity,
                            hasData,
                            hasUndo,
                            hasFailed,
                            hasFailedParent);
                        TestBlockStatus::CheckBlockStatus(
                            TestBlockStatus::WithUndo(s, !hasUndo),
                            validity,
                            hasData,
                            !hasUndo,
                            hasFailed,
                            hasFailedParent);
                        TestBlockStatus::CheckBlockStatus(s.withFailed(hasFailed), validity,
                                         hasData, hasUndo, hasFailed,
                                         hasFailedParent);
                        TestBlockStatus::CheckBlockStatus(s.withFailed(!hasFailed), validity,
                                         hasData, hasUndo, !hasFailed,
                                         hasFailedParent);
                        TestBlockStatus::CheckBlockStatus(s.withFailedParent(hasFailedParent),
                                         validity, hasData, hasUndo, hasFailed,
                                         hasFailedParent);
                        TestBlockStatus::CheckBlockStatus(s.withFailedParent(!hasFailedParent),
                                         validity, hasData, hasUndo, hasFailed,
                                         !hasFailedParent);

                        for (BlockValidity newValidity : baseValidities) {
                            TestBlockStatus::CheckBlockStatus(s.withValidity(newValidity),
                                             newValidity, hasData, hasUndo,
                                             hasFailed, hasFailedParent);
                        }
                    }
                }
            }
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: AustEcon/bitcoin-sv

max_issues_repo_name: wjxee/bitcoin-sv

max_forks_repo_name: wjxee/bitcoin-sv


text:
//
// Copyright 2005-2007 Adobe Systems Incorporated
//
// 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 BOOST_GIL_CONCEPTS_COLOR_HPP
#define BOOST_GIL_CONCEPTS_COLOR_HPP

#include <boost/gil/concepts/concept_check.hpp>

#include <type_traits>

#if defined(BOOST_CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#pragma clang diagnostic ignored "-Wunused-local-typedefs"
#endif

#if defined(BOOST_GCC) && (BOOST_GCC >= 40900)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif

namespace boost { namespace gil {

/// \ingroup ColorSpaceAndLayoutConcept
/// \brief Color space type concept
/// \code
/// concept ColorSpaceConcept<MPLRandomAccessSequence CS>
/// {
///    // Boost.MP11-compatible list, whose elements are color tags.
/// };
/// \endcode
template <typename CS>
struct ColorSpaceConcept
{
    void constraints()
    {
        // Boost.MP11-compatible list, whose elements are color tags

        // TODO: Is this incomplete?
    }
};

// Models ColorSpaceConcept
template <typename CS1, typename CS2>
struct color_spaces_are_compatible : std::is_same<CS1, CS2> {};

/// \ingroup ColorSpaceAndLayoutConcept
/// \brief Two color spaces are compatible if they are the same
/// \code
/// concept ColorSpacesCompatibleConcept<ColorSpaceConcept CS1, ColorSpaceConcept CS2>
/// {
///     where SameType<CS1, CS2>;
/// };
/// \endcode
template <typename CS1, typename CS2>
struct ColorSpacesCompatibleConcept
{
    void constraints()
    {
        static_assert(color_spaces_are_compatible<CS1, CS2>::value, "");
    }
};

/// \ingroup ColorSpaceAndLayoutConcept
/// \brief Channel mapping concept
/// \code
/// concept ChannelMappingConcept<MPLRandomAccessSequence CM>
/// {
///     // Boost.MP11-compatible list, whose elements
///     // model MPLIntegralConstant representing a permutation
/// };
/// \endcode
template <typename CM>
struct ChannelMappingConcept
{
    void constraints()
    {
        // Boost.MP11-compatible list, whose elements model
        // MPLIntegralConstant representing a permutation.

        // TODO: Is this incomplete?
    }
};

}} // namespace boost::gil

#if defined(BOOST_CLANG)
#pragma clang diagnostic pop
#endif

#if defined(BOOST_GCC) && (BOOST_GCC >= 40900)
#pragma GCC diagnostic pop
#endif

#endif

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp