text:
#define BOOST_TEST_MODULE pcraster old_calc mask_compressor
#include <boost/test/unit_test.hpp>
#include "com_algorithm.h"
#include "com_csfcell.h"
#include "com_exception.h"
#include "com_new.h"
#include "geo_csfmap.h"
#include "geo_filecreatetester.h"
#include "calc_maskcompressor.h"
#include "calc_nullcompressor.h"
#include "calc_compressioninput.h"
#include "calc_spatial.h"
#include "calc_decompresseddata.h"
#include "calc_modelbuilder.h"

BOOST_AUTO_TEST_CASE(compressor)
{
  using namespace calc;

 {
  geo::RasterSpace rs(2,3);
  UINT1 mask[6]= { 1, 1, 1, 1, 1, 1 };
  MaskCompressor mc(rs,mask);
  NullCompressor nc(rs);
  Compressor *cs[2] = { &mc, &nc };

  for (size_t i=0; i < 2; i++) {
    REAL4 *values = new REAL4[6];
    std::generate_n(values,6,com::SeqInc<REAL4>(1));
    // 1,2,3,4,5,6

    BOOST_CHECK(cs[i]->nrCellsCompressed()    == 6);
    BOOST_CHECK(cs[i]->toDecompressedIndex(0) == 0);
    BOOST_CHECK(cs[i]->toDecompressedIndex(2) == 2);
    BOOST_CHECK(cs[i]->toDecompressedIndex(5) == 5);

    CompressionInput ci(VS_S, values, *(cs[i]));
    Spatial *s=cs[i]->createSpatial(ci);
    BOOST_CHECK(s->nrValues() == cs[i]->nrCellsCompressed());
    ci.detachData(); // do not call [] delete => stack data
    REAL4 *compressed= (REAL4 *)const_cast<void*>(s->srcValue());
    BOOST_CHECK(compressed[0]==1);
    BOOST_CHECK(compressed[2]==3);
    BOOST_CHECK(compressed[5]==6);

    DecompressedData dd(VS_S);
    cs[i]->decompress(dd,s->srcValue());
    REAL4 *dCopy = (REAL4 *)const_cast<void*>(dd.decompressed());
    BOOST_CHECK(dCopy[0]==1);
    BOOST_CHECK(dCopy[2]==3);
    BOOST_CHECK(dCopy[4]==5);
    BOOST_CHECK(dCopy[5]==6);

    delete s;
  }
 }
 {
  geo::RasterSpace rs(2,3);
  UINT1 mask[6]= { 1, 1, MV_UINT1, 1, 0, 1 };
  REAL4 values[6] = { 1,2,3,4,5,6 };
  MaskCompressor mc(rs,mask);

  BOOST_CHECK(mc.nrCellsCompressed() == 4);
  BOOST_CHECK(mc.toDecompressedIndex(0) == 0);
  BOOST_CHECK(mc.toDecompressedIndex(2) == 3);
  BOOST_CHECK(mc.toDecompressedIndex(3) == 5);

  CompressionInput ci(VS_S, values, mc);
  Spatial *s=mc.createSpatial(ci);
  BOOST_CHECK(s->nrValues() == mc.nrCellsCompressed());
  ci.detachData(); // do not call [] delete => stack data
  REAL4 *compressed= (REAL4 *)const_cast<void*>(s->srcValue());
  BOOST_CHECK(compressed[0]==1);
  BOOST_CHECK(compressed[2]==4);
  BOOST_CHECK(compressed[3]==6);

  DecompressedData dd(VS_S);
  mc.decompress(dd,s->srcValue());
  REAL4 *dCopy = (REAL4 *)const_cast<void*>(dd.decompressed());
  BOOST_CHECK(dCopy[0]==1);
  BOOST_CHECK(pcr::isMV(dCopy[2]));
  BOOST_CHECK(pcr::isMV(dCopy[4]));
  BOOST_CHECK(dCopy[5]==6);

  delete s;
 }
}

BOOST_AUTO_TEST_CASE(script)
{
  using namespace calc;

  geo::RasterSpace rs(80,50);
  /* make boolean mask with:
   *  - triangle of 1, where mask is defined
   *  - triangle of MV
   *  - lower part if 1
   * - set boolean mask als areamap
   * TODO fill assumes all equal on non-spatial need
   *       for masking?
   */
  UINT1 **mask   = com::new2d<UINT1>(rs.nrRows(),rs.nrCols());
  REAL4 **result = com::new2d<REAL4>(rs.nrRows(),rs.nrCols());
  REAL4 **area   = com::new2d<REAL4>(rs.nrRows(),rs.nrCols());
  REAL4 count=1;
  for(size_t r=0; r< rs.nrRows(); r++)
   for(size_t c=0; c< rs.nrCols(); c++) {
     mask[r][c] = (r < c ) ? MV_UINT1 : (r < rs.nrCols());
     pcr::setMV(result[r][c]);
     if (mask[r][c]==1)
       result[r][c]=count++;
   }
   std::fill_n(area[0],rs.nrCells(), count-1);

  {
   geo::CSFMap mFile(std::string("mvComprMask.map"),rs,VS_BOOLEAN);
   mFile.putCells(mask[0]);
  }
  {
   geo::CSFMap mFile(std::string("mvComprResult.map"),rs,VS_SCALAR);
   mFile.putCells(result[0]);
  }
  {
   geo::CSFMap mFile(std::string("mvComprArea.map"),rs,VS_SCALAR);
   mFile.putCells(area[0]);
  }

  bool succes=true;
  try {

    geo::FileCreateTester mt("resultMvComprScript.map");
    geo::FileCreateTester ma("areaMvComprScript.map");

    ModelBuilder mb;
    mb.setClone("mvComprMask.map");
    mb.setMVCompression(true);
    mb.addStatement("resultMvComprScript.map = order((-ycoordinate(1))+10)");
    mb.addStatement("areaMvComprScript.map = maparea(resultMvComprScript.map)");

    mb.execute();

    BOOST_CHECK(mt.equalTo("mvComprResult.map",false));
    BOOST_CHECK(ma.equalTo("mvComprArea.map",false));

  } catch (const com::Exception& e) {
    std::cerr << e.messages();
    succes=false;
  }
  BOOST_CHECK(succes);

  com::delete2d<UINT1>(mask);
  com::delete2d<REAL4>(result);
  com::delete2d<REAL4>(area);

}

BOOST_AUTO_TEST_CASE(_0_option)
{
  using namespace calc;

  geo::RasterSpace rs(8,8);
  UINT1 **mask   = com::new2d<UINT1>(rs.nrRows(),rs.nrCols());
  REAL4 **result = com::new2d<REAL4>(rs.nrRows(),rs.nrCols());

  for(size_t r=0; r< rs.nrRows(); r++)
   for(size_t c=0; c< rs.nrCols(); c++) {
     mask[r][c] = (r < c ) ? MV_UINT1 : (r < rs.nrCols());
     pcr::setMV(result[r][c]);
     if (mask[r][c]==1)
       result[r][c]=1;
   }

  {
   geo::CSFMap mFile(std::string("zeroComprMask.map"),rs,VS_BOOLEAN);
   mFile.putCells(mask[0]);
   com::delete2d<UINT1>(mask);
  }
  {
   geo::CSFMap mFile(std::string("zeroComprResult.map"),rs,VS_SCALAR);
   mFile.putCells(result[0]);
   com::delete2d<REAL4>(result);
  }

  bool succes=true;
  try {

    geo::FileCreateTester mt("zeroCompr.map");

    ModelBuilder mb;
    mb.setClone("zeroComprMask.map");
    mb.setMVCompression(true);
    mb.set0Compression(true);
    mb.addStatement("X = scalar(0)");
    mb.addStatement("zeroCompr.map = X + spatial(1)");

    mb.execute();

    BOOST_CHECK(mt.equalTo("zeroComprResult.map",true));

  } catch (const com::Exception& e) {
    std::cerr << e.messages();
    succes=false;
  }
  BOOST_CHECK(succes);
}

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
/// \file
/// \brief Unit tests for dfe::poly

#include <array>
#include <valarray>
#include <vector>

#include <boost/test/unit_test.hpp>

#include "dfe/dfe_poly.hpp"

// make std::pair printable to allow direct comparision w/ boost::test

namespace std {
template<typename T>
inline ostream&
operator<<(ostream& os, const pair<T, T>& x)
{
  os << "{" << x.first << ", " << x.second << "}";
  return os;
};
} // namespace std

// test different input container types

#define COEFFS \
  { \
    1.0, 2.0, 0.25, 0.025 \
  }
constexpr double X0 = 0.5;
constexpr double Y0 = 2.065625;
constexpr double D0 = 2.2687500000000003;
constexpr std::pair<double, double> YD0 = {Y0, D0};

BOOST_AUTO_TEST_CASE(poly_initializerlist)
{
  BOOST_TEST(dfe::polynomial_val(X0, COEFFS) == Y0);
  BOOST_TEST(dfe::polynomial_der(X0, COEFFS) == D0);
  BOOST_TEST(dfe::polynomial_valder(X0, COEFFS) == YD0);
}

BOOST_AUTO_TEST_CASE(poly_array)
{
  double coeffs[] = COEFFS;
  BOOST_TEST(dfe::polynomial_val(X0, coeffs) == Y0);
  BOOST_TEST(dfe::polynomial_der(X0, coeffs) == D0);
  BOOST_TEST(dfe::polynomial_valder(X0, coeffs) == YD0);
}

BOOST_AUTO_TEST_CASE(poly_stdarray)
{
  std::array<double, 4> coeffs = COEFFS;
  BOOST_TEST(dfe::polynomial_val(X0, coeffs) == Y0);
  BOOST_TEST(dfe::polynomial_der(X0, coeffs) == D0);
  BOOST_TEST(dfe::polynomial_valder(X0, coeffs) == YD0);
}

BOOST_AUTO_TEST_CASE(poly_stdvector)
{
  std::vector<double> coeffs = COEFFS;
  BOOST_TEST(dfe::polynomial_val(X0, coeffs) == Y0);
  BOOST_TEST(dfe::polynomial_der(X0, coeffs) == D0);
  BOOST_TEST(dfe::polynomial_valder(X0, coeffs) == YD0);
}

// use std::valarray to calculate polynomial for multiple x values at once

BOOST_AUTO_TEST_CASE(poly_valarray)
{
  std::valarray<float> x(1024);
  for (std::size_t i = 0; i < x.size(); ++i) {
    x[i] = -1.0 + (2.0 / x.size()) * i;
  }
  auto linear = dfe::polynomial_val(x, {0.0, 1.0});
  auto quadratic = dfe::polynomial_val(x, {0.5, 0.0, 1.0});

  BOOST_TEST(x.size() == linear.size());
  BOOST_TEST(x.size() == quadratic.size());
  BOOST_TEST((x - linear).sum() == 0.0);
  BOOST_TEST((0.5 + x * x - quadratic).sum() == 0.0);
}

// special case of empty coefficients

BOOST_AUTO_TEST_CASE(poly_empty)
{
  BOOST_TEST(dfe::polynomial_val(-1.0, std::array<double, 0>{}) == 0.0);
  BOOST_TEST(dfe::polynomial_val(+0.0, std::array<double, 0>{}) == 0.0);
  BOOST_TEST(dfe::polynomial_val(+1.0, std::array<double, 0>{}) == 0.0);
}

// test different fixed polynomial orders

BOOST_AUTO_TEST_CASE(poly_const)
{
  BOOST_TEST(dfe::polynomial_val(-1.0, {42.0}) == 42.0);
  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0}) == 42.0);
  BOOST_TEST(dfe::polynomial_val(+1.0, {42.0}) == 42.0);
}

BOOST_AUTO_TEST_CASE(poly_linear)
{
  BOOST_TEST(dfe::polynomial_val(-0.5, {42.0, 1.0}) == 41.5);
  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0, 1.0}) == 42.0);
  BOOST_TEST(dfe::polynomial_val(+0.5, {42.0, 1.0}) == 42.5);
}

BOOST_AUTO_TEST_CASE(poly_quadratic)
{
  BOOST_TEST(dfe::polynomial_val(-0.5, {42.0, 1.0, 0.5}) == 41.625);
  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0, 1.0, 0.5}) == 42.0);
  BOOST_TEST(dfe::polynomial_val(+0.5, {42.0, 1.0, 0.5}) == 42.625);
}

BOOST_AUTO_TEST_CASE(poly_cubic)
{
  BOOST_TEST(dfe::polynomial_val(-0.5, {42.0, 1.0, 0.5, -1.0}) == 41.75);
  BOOST_TEST(dfe::polynomial_val(+0.0, {42.0, 1.0, 0.5, -1.0}) == 42.0);
  BOOST_TEST(dfe::polynomial_val(+0.5, {42.0, 1.0, 0.5, -1.0}) == 42.5);
}

ext: cpp

max_stars_repo_name: pinkenburg/dfelibs

max_issues_repo_name: pinkenburg/dfelibs

max_forks_repo_name: pinkenburg/dfelibs


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

#include "Logging.h"
#include "Metrics.h"
#include "BookieCodecV2.h"
#include "RateLimiter.h"

#include <algorithm>
#include <iostream>

#include <wangle/bootstrap/ClientBootstrap.h>
#include <wangle/channel/AsyncSocketHandler.h>
#include <wangle/codec/LengthFieldBasedFrameDecoder.h>
#include <wangle/codec/LengthFieldPrepender.h>
#include <wangle/channel/EventBaseHandler.h>

#include <boost/program_options.hpp>
namespace po = boost::program_options;

DECLARE_LOG_OBJECT();

struct Arguments {
    std::string bookieAddress;
    double rate;
    int msgSize;
    int numberOfConnections;
    int statsReportingRateSeconds;
    bool formatStatsJson;
};

typedef Pipeline<IOBufQueue&, Request> BookieClientPipeline;
typedef ClientBootstrap<BookieClientPipeline> Client;

class AddEntryTask: public HandlerAdapter<Response, Request> {
public:
    AddEntryTask(BookieClientPipeline::Ptr pipeline, double rate, int msgSize, MetricPtr addEntryMetric) :
            pipeline_(pipeline),
            rateLimiter_(rate),
            msgSize_(msgSize),
            addEntryMetric_(addEntryMetric),
            thread_() {
    }

    void start() {
        LOG_INFO("Started add entry task " << bookieAddress_);
        int64_t ledgerId = ledgerIdGenerator_++;
        int64_t entryIdGenerator = 0;

        std::string payload;
        payload.resize(msgSize_, 'X');

        auto pipeline = pipeline_.get();
        EventBase* eventBase = pipeline_->getTransport()->getEventBase();

        while (true) {
            rateLimiter_.aquire();

            int64_t entryId = entryIdGenerator++;

            eventBase->runInEventBaseThread([entryId, &ledgerId, &payload, &pipeline, this]() {
                Request request {2, BookieOperation::AddEntry, ledgerId, entryId, 0, IOBuf::wrapBuffer(payload.c_str(),
                            payload.length())};
                LOG_DEBUG("Sending request " << request);
                pipeline->write(std::move(request));

                pendingRequests_.insert( {entryId, std::move(addEntryMetric_->startTimer())});
            });
        }
    }

    virtual void transportActive(Context* ctx) override {
        ctx->fireTransportActive();
        ctx->getTransport()->getPeerAddress(&bookieAddress_);
        thread_ = std::make_unique<std::thread>(std::bind(&AddEntryTask::start, this));
    }

    virtual void read(Context* ctx, Response response) override {
        LOG_DEBUG("Received response: " << response);
        if (UNLIKELY(response.errorCode != BookieError::OK)) {
            LOG_ERROR("Received error response: " << response.errorCode);
            std::exit(-1);
        }

        auto it = pendingRequests_.find(response.entryId);
        it->second.completed();
        pendingRequests_.erase(it);
    }

    virtual void readEOF(Context* ctx) override {
        std::cout << "EOF received" << std::endl;
        close(ctx);
    }

private:
    BookieClientPipeline::Ptr pipeline_;
    SocketAddress bookieAddress_;
    RateLimiter rateLimiter_;
    int msgSize_;
    MetricPtr addEntryMetric_;
    std::unique_ptr<std::thread> thread_;

    std::unordered_map<int64_t, Timer> pendingRequests_;

    static std::atomic<int64_t> ledgerIdGenerator_;
};

std::atomic<int64_t> AddEntryTask::ledgerIdGenerator_;

class BookieClientPipelineFactory: public PipelineFactory<BookieClientPipeline> {
    double perConnectionRate_;
    int msgSize_;
    MetricPtr addEntryMetric_;

public:

    BookieClientPipelineFactory(double rate, int msgSize, MetricPtr addEntryMetric) :
            perConnectionRate_(rate),
            msgSize_(msgSize),
            addEntryMetric_(addEntryMetric) {
    }

    BookieClientPipeline::Ptr newPipeline(std::shared_ptr<AsyncTransportWrapper> sock) {
        auto pipeline = BookieClientPipeline::create();
        pipeline->addBack(AsyncSocketHandler(sock));
        pipeline->addBack(LengthFieldBasedFrameDecoder(4, BookieConstant::MaxFrameSize));
        pipeline->addBack(BookieClientCodecV2());
        pipeline->addBack(std::make_shared<AddEntryTask>(pipeline, perConnectionRate_, msgSize_, addEntryMetric_));
        pipeline->finalize();
        return pipeline;
    }
};

int main(int argc, char** argv) {
    Logging::init();

    Arguments args;

    po::options_description options;
    options.add_options() //
    ("help,h", "This help message") //
    ("bookieAddress,a", po::value<std::string>(&args.bookieAddress)->default_value("localhost:3181"),
            "Boookie hostname and port") //
    ("rate,r", po::value<double>(&args.rate)->default_value(100), "Add entry rate") //
    ("msg-size,s", po::value<int>(&args.msgSize)->default_value(1024), "Message size") //
    ("num-connections,c", po::value<int>(&args.numberOfConnections)->default_value(16), "Number of connections") //
    ("format-stats", po::value<bool>(&args.formatStatsJson)->default_value(true), "Format stats JSON output") //
    ("stats-reporting", po::value<int>(&args.statsReportingRateSeconds)->default_value(10),
            "Interval to report latency stats in seconds") //
            ;

    po::variables_map map;
    try {
        po::store(po::command_line_parser(argc, argv).options(options).run(), map);
        po::notify(map);

        if (map.count("help")) {
            std::cerr << options << std::endl;
            exit(1);
        }
    }
    catch (const std::exception& e) {
        std::cerr << "Error parsing parameters -- " << e.what() << std::endl << std::endl;
        std::cerr << options << std::endl;
        return -1;
    }

    seconds statsReportingPeriod(args.statsReportingRateSeconds);

    MetricsManager metricsManager(statsReportingPeriod);
    MetricPtr addEntryMetric = metricsManager.createMetric("add-entry-metric");

    SocketAddress bookieAddress;
    bookieAddress.setFromHostPort(args.bookieAddress);
    LOG_INFO("Bookie address: " << bookieAddress);

    double perConnectionRate = args.rate / args.numberOfConnections;

    ClientBootstrap<BookieClientPipeline> client;
    client.group(std::make_shared<wangle::IOThreadPoolExecutor>(std::thread::hardware_concurrency()));
    client.pipelineFactory(
            std::make_shared<BookieClientPipelineFactory>(perConnectionRate, args.msgSize, addEntryMetric));

    std::vector<Future<BookieClientPipeline*>> connectFutures;
    for (int i = 0; i < args.numberOfConnections; i++) {
        auto future = client.connect(bookieAddress);
        connectFutures.push_back(std::move(future));
    }

    for (auto& future : connectFutures) {
        future.get();
    }

    while (true) {
        std::this_thread::sleep_for(statsReportingPeriod);
//        LOG_INFO("Stats : " << metricsManager.getJsonStats(args.formatStatsJson));
    }
}

max_stars_repo_name: merlimat/bookie-cpp

max_issues_repo_name: merlimat/bookie-cpp

max_forks_repo_name: merlimat/bookie-cpp


text: #include <boost/flyweight/refcounted.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <iostream>

#pragma GCC diagnostic ignored "-Wparentheses"
#pragma GCC optimize ("rtti")

#include <boost/units/systems/si.hpp>
#include <boost/units/systems/cgs/length.hpp>
#include <boost/units/io.hpp>

const auto meter = 1.0 * boost::units::si::meter;
const auto s     = 1.0 * boost::units::si::second;

void print( decltype( meter / s ) v ){
    std::cout << "velocity = " << v << "\n";
}

int main(){

   auto gravity = 10.0 * meter / ( s * s );
   auto duration = 2.0 * s;

   print( gravity * duration );

}


text:
/******************************************************************************
 * Copyright (C) 2014 by Jerome Maye                                          *
 * jerome.maye@gmail.com                                                      *
 ******************************************************************************/

/** \file ErrorTermPoseTest.cpp
    \brief This file tests the ErrorTermPose class.
  */

#include <cmath>

#include <boost/make_shared.hpp>

#include <gtest/gtest.h>

#include <sm/kinematics/EulerAnglesYawPitchRoll.hpp>

#include <aslam/backend/test/ErrorTermTestHarness.hpp>
#include <aslam/backend/EuclideanPoint.hpp>
#include <aslam/backend/RotationQuaternion.hpp>

#include <aslam/calibration/statistics/NormalDistribution.h>

#include "aslam/calibration/car/error-terms/ErrorTermPose.h"

using namespace aslam::backend;
using namespace aslam::calibration;
using namespace sm::kinematics;

TEST(AslamCalibrationTestSuite, testErrorTermPose) {

  // estimated pose, angles: yaw-pitch-roll
  const ErrorTermPose::Input xe((ErrorTermPose::Input() << 100, 200, 300,
    M_PI / 2.0, M_PI / 4.0, M_PI / 8.0).finished());

  // covariance matrix of the measurement
  ErrorTermPose::Covariance Q = ErrorTermPose::Covariance::Zero();
  Q(0, 0) = 1e-4;
  Q(1, 1) = 1e-4;
  Q(2, 2) = 1e-4;
  Q(3, 3) = 4e-4;
  Q(4, 4) = 4e-4;
  Q(5, 5) = 4e-4;

  // measured pose
  const ErrorTermPose::Input xm(NormalDistribution<6>(xe, Q).getSample());

  // encapsulate the estimated pose into a transformation expression
  auto translation = boost::make_shared<EuclideanPoint>(xe.head<3>());
  EulerAnglesYawPitchRoll conv;
  auto rotation = boost::make_shared<RotationQuaternion>(
    conv.parametersToRotationMatrix(xe.tail<3>()));
  TransformationExpression T(RotationExpression(rotation.get()),
    EuclideanExpression(translation.get()));

  // build the error term
  ErrorTermPose e1(T, xm, Q);

  // test the error term
  try {
    ErrorTermTestHarness<6> harness(&e1);
    harness.testAll();
  }
  catch (const std::exception& e) {
    FAIL() << e.what();
  }

  // accessors test
  e1.setInput(xm);
  e1.setCovariance(Q);
  ASSERT_EQ(e1.getInput(), xm);
  ASSERT_EQ(e1.getCovariance(), Q);
}


text:
// Copyright  (C)  2007  Ruben Smits <ruben dot smits at mech dot kuleuven dot be>

#ifndef KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP
#define KDL_CHAIN_IKSOLVERVEL_PINV_GIVENS_HPP

#include "chainiksolver.hpp"
#include "chainjnttojacsolver.hpp"

#include <Eigen/Core>

using namespace Eigen;

namespace KDL
{
    /**
     * Implementation of a inverse velocity kinematics algorithm based
     * on the generalize pseudo inverse to calculate the velocity
     * transformation from Cartesian to joint space of a general
     * KDL::Chain. It uses a svd-calculation based on householders
     * rotations.
     *
     * @ingroup KinematicFamily
     */
    class ChainIkSolverVel_pinv_givens : public ChainIkSolverVel
    {
    public:

        /**
         * Constructor of the solver
         *
         * @param chain the chain to calculate the inverse velocity
         * kinematics for
         *
         */
        explicit ChainIkSolverVel_pinv_givens(const Chain& chain);
        ~ChainIkSolverVel_pinv_givens();

        virtual int CartToJnt(const JntArray& q_in, const Twist& v_in, JntArray& qdot_out);
        /**
         * not (yet) implemented.
         *
         */
        virtual int CartToJnt(const JntArray& /*q_init*/, const FrameVel& /*v_in*/, JntArrayVel& /*q_out*/){return (error = E_NOT_IMPLEMENTED);};

        /// @copydoc KDL::SolverI::updateInternalDataStructures
        virtual void updateInternalDataStructures();

    private:
        const Chain& chain;
        unsigned int nj;
        ChainJntToJacSolver jnt2jac;
        Jacobian jac;
        bool transpose,toggle;
        unsigned int m,n;
        MatrixXd jac_eigen,U,V,B;
        VectorXd S,tempi,UY,SUY,qdot_eigen,v_in_eigen;
    };
}
#endif


text:
#if !defined(CXXPLGR_SECONDARY_GRAMMAR_HPP)
#define CXXPLGR_SECONDARY_GRAMMAR_HPP

#include <string>
#include <vector>

#include <boost/spirit/home/x3.hpp>
#include <boost/spirit/home/x3/support/ast/position_tagged.hpp>
#include <boost/spirit/home/x3/support/utility/error_reporting.hpp>
#include <boost/spirit/home/x3/support/utility/annotate_on_success.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

#include "cxxplgr/secondary/action.hpp"

namespace cxxplgr { namespace secondary
{
    namespace x3 = boost::spirit::x3;

    x3::rule<class grammar, std::vector<std::string>> grammar = "grammar";
    x3::rule<class word, std::string> word = "word";

    auto const large_alpha
        = x3::string("Α")[action_add_asis_string()]
        | x3::string("ᾼ")[action_add_asis_string()]
        | x3::string("Ά")[action_add_asis_string()]
        | x3::string("Ὰ")[action_add_asis_string()]
        | x3::string("Ἁ")[action_add_asis_string()]
        | x3::string("ᾉ")[action_add_asis_string()]
        | x3::string("Ἅ")[action_add_asis_string()]
        | x3::string("ᾍ")[action_add_asis_string()]
        | x3::string("Ἃ")[action_add_asis_string()]
        | x3::string("ᾋ")[action_add_asis_string()]
        | x3::string("Ἇ")[action_add_asis_string()]
        | x3::string("ᾏ")[action_add_asis_string()]
        | x3::string("Ἀ")[action_add_asis_string()]
        | x3::string("ᾈ")[action_add_asis_string()]
        | x3::string("Ἄ")[action_add_asis_string()]
        | x3::string("ᾌ")[action_add_asis_string()]
        | x3::string("Ἂ")[action_add_asis_string()]
        | x3::string("ᾊ")[action_add_asis_string()]
        | x3::string("Ἆ")[action_add_asis_string()]
        | x3::string("ᾎ")[action_add_asis_string()]
        ;

    auto const large_epsilon
        = x3::string("Ε")[action_add_asis_string()]
        | x3::string("Έ")[action_add_asis_string()]
        | x3::string("Ὲ")[action_add_asis_string()]
        | x3::string("Ἑ")[action_add_asis_string()]
        | x3::string("Ἕ")[action_add_asis_string()]
        | x3::string("Ἓ")[action_add_asis_string()]
        | x3::string("Ἐ")[action_add_asis_string()]
        | x3::string("Ἔ")[action_add_asis_string()]
        | x3::string("Ἒ")[action_add_asis_string()]
        ;

    auto const large_eta
        = x3::string("Η")[action_add_asis_string()]
        | x3::string("ῌ")[action_add_asis_string()]
        | x3::string("Ή")[action_add_asis_string()]
        | x3::string("Ὴ")[action_add_asis_string()]
        | x3::string("Ἡ")[action_add_asis_string()]
        | x3::string("ᾙ")[action_add_asis_string()]
        | x3::string("Ἥ")[action_add_asis_string()]
        | x3::string("ᾝ")[action_add_asis_string()]
        | x3::string("Ἣ")[action_add_asis_string()]
        | x3::string("ᾛ")[action_add_asis_string()]
        | x3::string("Ἧ")[action_add_asis_string()]
        | x3::string("ᾟ")[action_add_asis_string()]
        | x3::string("Ἠ")[action_add_asis_string()]
        | x3::string("ᾘ")[action_add_asis_string()]
        | x3::string("Ἤ")[action_add_asis_string()]
        | x3::string("ᾜ")[action_add_asis_string()]
        | x3::string("Ἢ")[action_add_asis_string()]
        | x3::string("ᾚ")[action_add_asis_string()]
        | x3::string("Ἦ")[action_add_asis_string()]
        | x3::string("ᾞ")[action_add_asis_string()]
        ;

    auto const large_iota
        = x3::string("Ι")[action_add_asis_string()]
        | x3::string("Ί")[action_add_asis_string()]
        | x3::string("Ὶ")[action_add_asis_string()]
        | x3::string("Ἱ")[action_add_asis_string()]
        | x3::string("Ἵ")[action_add_asis_string()]
        | x3::string("Ἳ")[action_add_asis_string()]
        | x3::string("Ἷ")[action_add_asis_string()]
        | x3::string("Ἰ")[action_add_asis_string()]
        | x3::string("Ἴ")[action_add_asis_string()]
        | x3::string("Ἲ")[action_add_asis_string()]
        | x3::string("Ἶ")[action_add_asis_string()]
        | x3::string("Ϊ")[action_add_asis_string()]
        ;

    auto const large_omicron
        = x3::string("Ο")[action_add_asis_string()]
        | x3::string("Ό")[action_add_asis_string()]
        | x3::string("Ὸ")[action_add_asis_string()]
        | x3::string("Ὁ")[action_add_asis_string()]
        | x3::string("Ὅ")[action_add_asis_string()]
        | x3::string("Ὃ")[action_add_asis_string()]
        | x3::string("Ὀ")[action_add_asis_string()]
        | x3::string("Ὄ")[action_add_asis_string()]
        | x3::string("Ὂ")[action_add_asis_string()]
        ;

    auto const large_upsilon
        = x3::string("Υ")[action_add_asis_string()]
        | x3::string("Ύ")[action_add_asis_string()]
        | x3::string("Ὺ")[action_add_asis_string()]
        | x3::string("Ὑ")[action_add_asis_string()]
        | x3::string("Ὕ")[action_add_asis_string()]
        | x3::string("Ὓ")[action_add_asis_string()]
        | x3::string("Ὗ")[action_add_asis_string()]
        | x3::string("Ϋ")[action_add_asis_string()]
        ;

    auto const large_omega
        = x3::string("Ω")[action_add_asis_string()]
        | x3::string("ῼ")[action_add_asis_string()]
        | x3::string("Ώ")[action_add_asis_string()]
        | x3::string("Ὼ")[action_add_asis_string()]
        | x3::string("Ὡ")[action_add_asis_string()]
        | x3::string("ᾩ")[action_add_asis_string()]
        | x3::string("Ὥ")[action_add_asis_string()]
        | x3::string("ᾭ")[action_add_asis_string()]
        | x3::string("Ὣ")[action_add_asis_string()]
        | x3::string("ᾫ")[action_add_asis_string()]
        | x3::string("Ὧ")[action_add_asis_string()]
        | x3::string("ᾯ")[action_add_asis_string()]
        | x3::string("Ὠ")[action_add_asis_string()]
        | x3::string("ᾨ")[action_add_asis_string()]
        | x3::string("Ὤ")[action_add_asis_string()]
        | x3::string("ᾬ")[action_add_asis_string()]
        | x3::string("Ὢ")[action_add_asis_string()]
        | x3::string("ᾪ")[action_add_asis_string()]
        | x3::string("Ὦ")[action_add_asis_string()]
        | x3::string("ᾮ")[action_add_asis_string()]
        ;

    auto const large_rho
        = x3::string("Ρ")[action_add_asis_string()]
        | x3::string("Ῥ")[action_add_asis_string()]
        ;

    auto const small_alpha
        = x3::string("α")[action_add_asis_string()]
        | x3::string("ᾳ")[action_add_asis_string()]
        | x3::string("ά")[action_add_asis_string()]
        | x3::string("ᾴ")[action_add_asis_string()]
        | x3::string("ὰ")[action_add_asis_string()]
        | x3::string("ᾲ")[action_add_asis_string()]
        | x3::string("ᾶ")[action_add_asis_string()]
        | x3::string("ᾷ")[action_add_asis_string()]
        | x3::string("ἁ")[action_add_asis_string()]
        | x3::string("ᾁ")[action_add_asis_string()]
        | x3::string("ἅ")[action_add_asis_string()]
        | x3::string("ᾅ")[action_add_asis_string()]
        | x3::string("ἃ")[action_add_asis_string()]
        | x3::string("ᾃ")[action_add_asis_string()]
        | x3::string("ἇ")[action_add_asis_string()]
        | x3::string("ᾇ")[action_add_asis_string()]
        | x3::string("ἀ")[action_add_asis_string()]
        | x3::string("ᾀ")[action_add_asis_string()]
        | x3::string("ἄ")[action_add_asis_string()]
        | x3::string("ᾄ")[action_add_asis_string()]
        | x3::string("ἂ")[action_add_asis_string()]
        | x3::string("ᾂ")[action_add_asis_string()]
        | x3::string("ἆ")[action_add_asis_string()]
        | x3::string("ᾆ")[action_add_asis_string()]
        ;

    auto const small_epsilon
        = x3::string("ε")[action_add_asis_string()]
        | x3::string("έ")[action_add_asis_string()]
        | x3::string("ὲ")[action_add_asis_string()]
        | x3::string("ἑ")[action_add_asis_string()]
        | x3::string("ἕ")[action_add_asis_string()]
        | x3::string("ἓ")[action_add_asis_string()]
        | x3::string("ἐ")[action_add_asis_string()]
        | x3::string("ἔ")[action_add_asis_string()]
        | x3::string("ἒ")[action_add_asis_string()]
        ;

    auto const small_eta
        = x3::string("η")[action_add_asis_string()]
        | x3::string("ῃ")[action_add_asis_string()]
        | x3::string("ή")[action_add_asis_string()]
        | x3::string("ῄ")[action_add_asis_string()]
        | x3::string("ὴ")[action_add_asis_string()]
        | x3::string("ῂ")[action_add_asis_string()]
        | x3::string("ῆ")[action_add_asis_string()]
        | x3::string("ῇ")[action_add_asis_string()]
        | x3::string("ἡ")[action_add_asis_string()]
        | x3::string("ᾑ")[action_add_asis_string()]
        | x3::string("ἥ")[action_add_asis_string()]
        | x3::string("ᾕ")[action_add_asis_string()]
        | x3::string("ἣ")[action_add_asis_string()]
        | x3::string("ᾓ")[action_add_asis_string()]
        | x3::string("ἧ")[action_add_asis_string()]
        | x3::string("ᾗ")[action_add_asis_string()]
        | x3::string("ἠ")[action_add_asis_string()]
        | x3::string("ᾐ")[action_add_asis_string()]
        | x3::string("ἤ")[action_add_asis_string()]
        | x3::string("ᾔ")[action_add_asis_string()]
        | x3::string("ἢ")[action_add_asis_string()]
        | x3::string("ᾒ")[action_add_asis_string()]
        | x3::string("ἦ")[action_add_asis_string()]
        | x3::string("ᾖ")[action_add_asis_string()]
        ;

    auto const small_iota
        = x3::string("ι")[action_add_asis_string()]
        | x3::string("ί")[action_add_asis_string()]
        | x3::string("ὶ")[action_add_asis_string()]
        | x3::string("ῖ")[action_add_asis_string()]
        | x3::string("ἱ")[action_add_asis_string()]
        | x3::string("ἵ")[action_add_asis_string()]
        | x3::string("ἳ")[action_add_asis_string()]
        | x3::string("ἷ")[action_add_asis_string()]
        | x3::string("ἰ")[action_add_asis_string()]
        | x3::string("ἴ")[action_add_asis_string()]
        | x3::string("ἲ")[action_add_asis_string()]
        | x3::string("ἶ")[action_add_asis_string()]
        | x3::string("ϊ")[action_add_asis_string()]
        | x3::string("ΐ")[action_add_asis_string()]
        | x3::string("ῒ")[action_add_asis_string()]
        | x3::string("ῗ")[action_add_asis_string()]
        ;

    auto const small_omicron
        = x3::string("ο")[action_add_asis_string()]
        | x3::string("ό")[action_add_asis_string()]
        | x3::string("ὸ")[action_add_asis_string()]
        | x3::string("ὁ")[action_add_asis_string()]
        | x3::string("ὅ")[action_add_asis_string()]
        | x3::string("ὃ")[action_add_asis_string()]
        | x3::string("ὀ")[action_add_asis_string()]
        | x3::string("ὄ")[action_add_asis_string()]
        | x3::string("ὂ")[action_add_asis_string()]
        ;

    auto const small_upsilon
        = x3::string("υ")[action_add_asis_string()]
        | x3::string("ύ")[action_add_asis_string()]
        | x3::string("ὺ")[action_add_asis_string()]
        | x3::string("ῦ")[action_add_asis_string()]
        | x3::string("ὑ")[action_add_asis_string()]
        | x3::string("ὕ")[action_add_asis_string()]
        | x3::string("ὓ")[action_add_asis_string()]
        | x3::string("ὗ")[action_add_asis_string()]
        | x3::string("ὐ")[action_add_asis_string()]
        | x3::string("ὔ")[action_add_asis_string()]
        | x3::string("ὒ")[action_add_asis_string()]
        | x3::string("ὖ")[action_add_asis_string()]
        | x3::string("ϋ")[action_add_asis_string()]
        | x3::string("ΰ")[action_add_asis_string()]
        | x3::string("ῢ")[action_add_asis_string()]
        | x3::string("ῧ")[action_add_asis_string()]
        ;

    auto const small_omega
        = x3::string("ω")[action_add_asis_string()]
        | x3::string("ῳ")[action_add_asis_string()]
        | x3::string("ώ")[action_add_asis_string()]
        | x3::string("ῴ")[action_add_asis_string()]
        | x3::string("ὼ")[action_add_asis_string()]
        | x3::string("ῲ")[action_add_asis_string()]
        | x3::string("ῶ")[action_add_asis_string()]
        | x3::string("ῷ")[action_add_asis_string()]
        | x3::string("ὡ")[action_add_asis_string()]
        | x3::string("ᾡ")[action_add_asis_string()]
        | x3::string("ὥ")[action_add_asis_string()]
        | x3::string("ᾥ")[action_add_asis_string()]
        | x3::string("ὣ")[action_add_asis_string()]
        | x3::string("ᾣ")[action_add_asis_string()]
        | x3::string("ὧ")[action_add_asis_string()]
        | x3::string("ᾧ")[action_add_asis_string()]
        | x3::string("ὠ")[action_add_asis_string()]
        | x3::string("ᾠ")[action_add_asis_string()]
        | x3::string("ὤ")[action_add_asis_string()]
        | x3::string("ᾤ")[action_add_asis_string()]
        | x3::string("ὢ")[action_add_asis_string()]
        | x3::string("ᾢ")[action_add_asis_string()]
        | x3::string("ὦ")[action_add_asis_string()]
        | x3::string("ᾦ")[action_add_asis_string()]
        ;

    auto const small_rho
        = x3::string("ρ")[action_add_asis_string()]
        | x3::string("ῥ")[action_add_asis_string()]
        | x3::string("ῤ")[action_add_asis_string()]
        ;

    auto const large_consonant
        = x3::string("Β")[action_add_asis_string()]
        | x3::string("Γ")[action_add_asis_string()]
        | x3::string("Δ")[action_add_asis_string()]
        | x3::string("Ζ")[action_add_asis_string()]
        | x3::string("Θ")[action_add_asis_string()]
        | x3::string("Κ")[action_add_asis_string()]
        | x3::string("Λ")[action_add_asis_string()]
        | x3::string("Μ")[action_add_asis_string()]
        | x3::string("Ν")[action_add_asis_string()]
        | x3::string("Ξ")[action_add_asis_string()]
        | x3::string("Π")[action_add_asis_string()]
        | x3::string("Σ")[action_add_asis_string()]
        | x3::string("Τ")[action_add_asis_string()]
        | x3::string("Φ")[action_add_asis_string()]
        | x3::string("Χ")[action_add_asis_string()]
        | x3::string("Ψ")[action_add_asis_string()]
        ;

    auto const small_consonant
        = x3::string("β")[action_add_asis_string()]
        | x3::string("γ")[action_add_asis_string()]
        | x3::string("δ")[action_add_asis_string()]
        | x3::string("ζ")[action_add_asis_string()]
        | x3::string("θ")[action_add_asis_string()]
        | x3::string("κ")[action_add_asis_string()]
        | x3::string("λ")[action_add_asis_string()]
        | x3::string("μ")[action_add_asis_string()]
        | x3::string("ν")[action_add_asis_string()]
        | x3::string("ξ")[action_add_asis_string()]
        | x3::string("π")[action_add_asis_string()]
        | x3::string("σ")[action_add_asis_string()]
        | x3::string("ς")[action_add_asis_string()]
        | x3::string("τ")[action_add_asis_string()]
        | x3::string("φ")[action_add_asis_string()]
        | x3::string("χ")[action_add_asis_string()]
        | x3::string("ψ")[action_add_asis_string()]
        ;

    auto const alphabet
        = large_alpha
        | large_epsilon
        | large_eta
        | large_iota
        | large_omicron
        | large_upsilon
        | large_omega
        | large_rho
        | small_alpha
        | small_epsilon
        | small_eta
        | small_iota
        | small_omicron
        | small_upsilon
        | small_omega
        | small_rho
        | large_consonant
        | small_consonant
        ;

    auto const apostroph
        = x3::string("'")[action_add_asis_string()]
        ;

    auto const word_def
        = x3::eps[action_assign_string()]
        >> +(alphabet)
        >> -(apostroph >> *(alphabet))
        ;

    auto const grammar_def
        = x3::eps[action_assign_list()]
        >> *(
                word[action_add_element()]
                | x3::char_[action_ignore()]
            );

    BOOST_SPIRIT_DEFINE(
            grammar,
            word
            );
}}

#endif


text:
/*
Copyright (c) 2017-2019,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC.  See
the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#include "ctestFixtures.hpp"
#include "helics/shared_api_library/internal/api_objects.h"
#include <boost/test/unit_test.hpp>

#include <cctype>

static bool hasIndexCode (const std::string &type_name)
{
    if (std::isdigit (type_name.back ()) != 0)
    {
        if (*(type_name.end () - 2) == '_')
        {  // this setup ignores the setup mode
            return true;
        }
    }
    return false;
}

static auto StartBrokerImp (const std::string &core_type_name, std::string initialization_string)
{
    if (core_type_name.compare (0, 3, "tcp") == 0)
    {
        initialization_string += " --reuse_address";
    }
    else if (core_type_name.compare (0, 3, "ipc") == 0)
    {
        initialization_string += " --client";
    }
    if (hasIndexCode (core_type_name))
    {
        std::string new_type (core_type_name.begin (), core_type_name.end () - 2);
        return helicsCreateBroker (new_type.c_str (), NULL, initialization_string.c_str (), 0);
    }
    return helicsCreateBroker (core_type_name.c_str (), NULL, initialization_string.c_str (), 0);
}

bool FederateTestFixture::hasIndexCode (const std::string &type_name)
{
    if (std::isdigit (type_name.back ()) != 0)
    {
        if (*(type_name.end () - 2) == '_')
        {  // this setup ignores the setup mode
            return true;
        }
    }
    return false;
}

int FederateTestFixture::getIndexCode (const std::string &type_name)
{
    return static_cast<int> (type_name.back () - '0');
}

FederateTestFixture::FederateTestFixture () { helicsErrorClear (&err); }
FederateTestFixture::~FederateTestFixture ()
{
    for (auto &fed : federates)
    {
        if (fed)
        {
            helics_federate_state state = helicsFederateGetState (fed, nullptr);
            helics_core core = helicsFederateGetCoreObject (fed, nullptr);
            if (state != helics_state_finalize)
            {
                helicsFederateFinalize (fed, nullptr);
            }
            helicsFederateFree (fed);
            if (helicsCoreIsValid (core))
            {
                helicsCoreDisconnect (core, nullptr);
            }
            helicsCoreFree (core);
        }
    }
    federates.clear ();

    for (auto &broker : brokers)
    {
        if (helicsBrokerIsValid (broker) == helics_false)
        {
            continue;
        }
        helics_bool res;
        if (ctype.compare (0, 3, "tcp") == 0)
        {
            res = helicsBrokerWaitForDisconnect (broker, 2000, nullptr);
        }
        else
        {
            res = helicsBrokerWaitForDisconnect (broker, 200, nullptr);
        }

        if (res != helics_true)
        {
            printf ("forcing disconnect\n");
            helicsBrokerDisconnect (broker, nullptr);
        }

        helicsBrokerFree (broker);
    }
    brokers.clear ();
    helicsCleanupLibrary ();
}

helics_broker FederateTestFixture::AddBroker (const std::string &core_type_name, int count)
{
    return AddBroker (core_type_name, std::string ("-f") + std::to_string (count));
}

helics_broker
FederateTestFixture::AddBroker (const std::string &core_type_name, const std::string &initialization_string)
{
    helics_broker broker;
    if (extraBrokerArgs.empty ())
    {
        broker = StartBrokerImp (core_type_name, initialization_string);
    }
    else
    {
        broker = StartBrokerImp (core_type_name, initialization_string + " " + extraBrokerArgs);
    }
    BOOST_CHECK (helicsBrokerIsValid (broker) == helics_true);
    brokers.push_back (broker);
    return broker;
}

void FederateTestFixture::SetupTest (FedCreator ctor,
                                     const std::string &core_type_name,
                                     int count,
                                     helics_time time_delta,
                                     const std::string &name_prefix)
{
    ctype = core_type_name;
    helics_broker broker = AddBroker (core_type_name, count);
    BOOST_CHECK (nullptr != broker);
    AddFederates (ctor, core_type_name, count, broker, time_delta, name_prefix);
}

void FederateTestFixture::AddFederates (FedCreator ctor,
                                                                std::string core_type_name,
                                                                int count,
                                                                helics_broker broker,
                                                                helics_time time_delta,
                                                                const std::string &name_prefix)
{
    bool hasIndex = hasIndexCode (core_type_name);
    int setup = (hasIndex) ? getIndexCode (core_type_name) : 1;
    if (hasIndex)
    {
        core_type_name.pop_back ();
        core_type_name.pop_back ();
    }

    std::string initString = std::string ("--broker=");
    initString += helicsBrokerGetIdentifier (broker);
    initString += " --broker_address=";
    initString += helicsBrokerGetAddress (broker);

    if (!extraCoreArgs.empty ())
    {
        initString.push_back (' ');
        initString.append (extraCoreArgs);
    }

    helics_federate_info fi = helicsCreateFederateInfo ();
    CE (helicsFederateInfoSetCoreTypeFromString (fi, core_type_name.c_str (), &err));
    CE (helicsFederateInfoSetTimeProperty (fi, helics_property_time_delta, time_delta, &err));

    switch (setup)
    {
    case 1:
    default:
    {
        auto init = initString + " --federates " + std::to_string (count);
        auto core = helicsCreateCore (core_type_name.c_str (), NULL, init.c_str (), &err);
        BOOST_REQUIRE_EQUAL (err.error_code, 0);
        CE (helicsFederateInfoSetCoreName (fi, helicsCoreGetIdentifier (core), &err));
        size_t offset = federates.size ();
        federates.resize (count + offset);
        for (int ii = 0; ii < count; ++ii)
        {
            auto name = name_prefix + std::to_string (ii + offset);
            auto fed = ctor (name.c_str (), fi, &err);
            BOOST_CHECK_EQUAL (err.error_code, 0);
            federates[ii + offset] = fed;
        }
        helicsCoreFree (core);
    }
    break;
    case 2:
    {  // each federate has its own core
        size_t offset = federates.size ();
        federates.resize (count + offset);
        for (int ii = 0; ii < count; ++ii)
        {
            auto init = initString + " --federates 1";
            auto core = helicsCreateCore (core_type_name.c_str (), NULL, init.c_str (), &err);
            BOOST_REQUIRE_EQUAL (err.error_code, 0);
            CE (helicsFederateInfoSetCoreName (fi, helicsCoreGetIdentifier (core), &err));

            auto name = name_prefix + std::to_string (ii + offset);
            auto fed = ctor (name.c_str (), fi, &err);
            BOOST_CHECK_EQUAL (err.error_code, 0);
            federates[ii + offset] = fed;
            helicsCoreFree (core);
        }
    }
    break;
    case 3:
    {
        auto subbroker = AddBroker (core_type_name, initString + " --federates " + std::to_string (count));
        auto newTypeString = core_type_name;
        newTypeString.push_back ('_');
        newTypeString.push_back ('2');
        for (int ii = 0; ii < count; ++ii)
        {
            AddFederates (ctor, newTypeString, 1, subbroker, time_delta, name_prefix);
        }
    }
    break;
    case 4:
    {
        auto newTypeString = core_type_name;
        newTypeString.push_back ('_');
        newTypeString.push_back ('2');
        for (int ii = 0; ii < count; ++ii)
        {
            auto subbroker = AddBroker (core_type_name, initString + " --federates 1");
            AddFederates (ctor, newTypeString, 1, subbroker, time_delta, name_prefix);
        }
    }
    break;
    }
    helicsFederateInfoFree (fi);
}

helics_federate FederateTestFixture::GetFederateAt (int index)
{
    if (index < static_cast<int> (federates.size ()))
    {
        return federates.at (index);
    }
    return nullptr;
}


text:
#ifndef GUARD_MONGODB_FLUSSPFERD_CURSOR_HPP
#define GUARD_MONGODB_FLUSSPFERD_CURSOR_HPP

#include <flusspferd.hpp>
#include <boost/shared_ptr.hpp>
#include <mongo/client/dbclient.h>

namespace mongodb_flusspferd {

class mongo_client;

FLUSSPFERD_CLASS_DESCRIPTION(
    cursor,
    (constructible, false)
    (full_name, "MongoDB.Cursor")
    (constructor_name, "Cursor")
    (methods,
      ("next", bind, next)
      ("more", bind, more)
      ("explain", bind, explain)
      ("hint", bind, hint)
      ("min", bind, min)
      ("max", bind, max)
      ("snapshot", bind, snapshot)
      ("sort", bind, sort)
      ("where", bind, where)
    )
    (properties,
      ("id", getter, get_id)
    )
) {
public:

  cursor(flusspferd::object const &obj, mongo_client *db_,
    flusspferd::string ns_, mongo::BSONObj query,
    boost::optional<mongo::BSONObj> fields);

  ~cursor();

  // Properties
  int get_id();

  // Methods
  flusspferd::object next();
  bool more();
  flusspferd::object explain();
  flusspferd::object hint();
  flusspferd::object min(object key);
  flusspferd::object max(object key);
  flusspferd::object snapshot();
  void sort(flusspferd::call_context &x);
  flusspferd::object where();
protected:
  mongo_client &db_;
  flusspferd::string ns_;
  mongo::Query query_;
  boost::optional<mongo::BSONObj> fields_;
  int limit_, skip_;

  boost::shared_ptr<mongo::DBClientCursor> cursor_;

  // For the chain methods, assert cursor_ hasn't been generated yet
  void assert_no_cursor();
  boost::shared_ptr<mongo::DBClientCursor> mongo_cursor();

  void trace(flusspferd::tracer &trc);
};

}

#endif

max_stars_repo_name: ashb/mongodb-flusspferd

max_issues_repo_name: ashb/mongodb-flusspferd

max_forks_repo_name: ashb/mongodb-flusspferd


text:
#pragma once

#include <xul/util/log.hpp>
#include <xul/macro/fill_zero.hpp>
#include <boost/config.hpp>

#include <boost/algorithm/string/split.hpp>

#include <boost/algorithm/string/classification.hpp>
#include <stdint.h>
#include <string>

#include <vector>

#if defined(BOOST_WINDOWS)

#include <xul/mswin/process_object.hpp>

namespace xul {

class process : private boost::noncopyable
{
public:
    typedef HANDLE native_type;
    typedef DWORD pid_type;
    typedef DWORD tid_type;

    process()
    {
    }
    ~process()
    {
        this->close();
    }

    static DWORD current_process_id()
    {
        return ::GetCurrentProcessId();
    }
    static DWORD current_thread_id()
    {
        return ::GetCurrentThreadId();
    }

    bool join( uint32_t milliseconds )
    {
        return m_object.join(milliseconds);
    }

    bool join()
    {
        return m_object.join();
    }

    void close()
    {
        if (is_open())
        {
            if ( is_alive() )
            {
                bool success = this->kill(123);
                assert( success );
            }
        }
        m_object.close();
    }

    HANDLE native_handle() const { return m_object.native_handle(); }
    DWORD native_id() const { return m_object.native_id(); }

    xul::mswin::process_object& native_object() { return m_object; }

    bool is_open() const
    {
        return m_object.is_open();
    }

    bool is_alive() const
    {
        return m_object.is_alive();
    }

    ULONG get_exit_code() const
    {
        return m_object.get_exit_code();
    }

    bool kill(DWORD exitCode)
    {
        return m_object.kill(exitCode);
    }

    bool start( const std::string& cmdline, STARTUPINFO& si, bool inheritHandles = false, bool createNoWindow = false )
    {
        assert( false == is_open() );
        assert( false == is_alive() );
        this->close();
        std::string cmdlinestr = cmdline;
        PROCESS_INFORMATION pi = { 0 };
        DWORD creationFlags = NORMAL_PRIORITY_CLASS;
        if (createNoWindow)
        {
            creationFlags |= CREATE_NO_WINDOW;
        }
        if ( FALSE == ::CreateProcess( NULL, &cmdlinestr[0], NULL, NULL, inheritHandles ? TRUE : FALSE, creationFlags, NULL, NULL, &si, &pi) )
        {
            APP_ERROR("failed to create process " << cmdlinestr << " errcode=" << ::GetLastError());
            return false;
        }
        m_object.attach(pi.hProcess, pi.dwProcessId);
        CloseHandle(pi.hThread);
        return true;
    }

    bool start( const std::string& cmdline, int outhandle, int inhandle = -1, int errhandle = -1, bool inheritHandles = false, bool createNoWindow = false )
    {
        return this->start(cmdline, get_pipe_handle(outhandle), get_pipe_handle(inhandle), get_pipe_handle(errhandle), inheritHandles);
    }

    bool start(const std::string& cmdline, HANDLE outhandle = INVALID_HANDLE_VALUE, HANDLE inhandle = INVALID_HANDLE_VALUE, HANDLE errhandle = INVALID_HANDLE_VALUE, bool inheritHandles = false, bool createNoWindow = false)
    {
        STARTUPINFO si;
        XUL_FILL_ZERO( si );
        si.cb = sizeof( si );
        if (INVALID_HANDLE_VALUE != outhandle)
        {
            si.dwFlags = STARTF_USESTDHANDLES;
            si.hStdOutput = outhandle;
            inheritHandles = true;
        }
        else
        {
            //si.hStdOutput = ::GetStdHandle( STD_OUTPUT_HANDLE );
        }
        if (INVALID_HANDLE_VALUE != inhandle)
        {
            si.dwFlags = STARTF_USESTDHANDLES;
            si.hStdInput = inhandle;
            inheritHandles = true;
        }
        else
        {
            //si.hStdInput = ::GetStdHandle( STD_INPUT_HANDLE );
        }
        if (INVALID_HANDLE_VALUE != errhandle)
        {
            si.dwFlags = STARTF_USESTDHANDLES;
            si.hStdError = errhandle;
            inheritHandles = true;
        }
        else
        {
            //si.hStdError = ::GetStdHandle( STD_ERROR_HANDLE );
        }
        return this->start( cmdline, si, inheritHandles );
    }

    static HANDLE get_pipe_handle( int fd )
    {
        if (-1 == fd)
            return INVALID_HANDLE_VALUE;
        HANDLE h = reinterpret_cast<HANDLE>( _get_osfhandle( fd ) );
        SetHandleInformation( h, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT );
        //::DuplicateHandle( )
        return h;
    }

protected:

private:
    xul::mswin::process_object m_object;
};

}

#else

#include <sys/wait.h>
#include <sys/types.h>

namespace xul {

class process : private boost::noncopyable
{
public:
    process() : m_pid( 0 )
    {
    }
    ~process()
    {
        this->close();
    }

    bool is_open() const
    {
        return m_pid > 0;
    }

    bool is_alive() const
    {
        if ( false == is_open() )
            return false;
        int s;
        if (::waitpid(m_pid, &s, 0) == -1)
            return false;
        return WIFSTOPPED(s);
    }

    bool kill()
    {
        return 0 == ::kill( m_pid, 9 );
    }

    bool start( const std::string& cmdline, int outhandle = -1, int inhandle = -1, int errhandle = -1)
    {
        printf("fork ok, execute command %s\n", cmdline.c_str());
        std::vector<std::string> tokens;
        boost::split(tokens, cmdline, boost::is_space());
        std::vector<char*> args;
        assert(tokens.size() >= 1);
        args.resize(tokens.size() + 1);
        for (size_t index = 0; index < tokens.size(); ++index)
        {
            args[index] = const_cast<char*>(tokens[index].c_str());
        }
        args[tokens.size()] = NULL;

        this->close();
        pid_t pid = fork ();
        if ( pid < (pid_t) 0 )
        {
            // The fork failed.
            fprintf (stderr, "Fork failed.\n");
            return false;
        }
        if ( pid > (pid_t)0 )
        {
            // This is the parent process.Close other end first.
            return true;
        }
        // This is the child process.Close other end first.
        //set_pipe_handle( outhandle, 1 );
        //set_pipe_handle( inhandle, 0 );
        //set_pipe_handle( errhandle, 2 );
        int ret = execv( tokens[0].c_str(), &args[0]);
        printf("fork ok, execute complete %s %d %d\n", tokens[0].c_str(), ret, errno);
        return true;
    }

    bool join()
    {
        int s;
        if (::waitpid(m_pid, &s, 0) == -1)
            return false;
        return true;
    }

    void close()
    {
        if (is_open())
        {
            if ( is_alive() )
            {
                bool success = this->kill();
                assert( success );
            }
            m_pid = 0;
        }
    }

protected:
    static void set_pipe_handle( int fd, int dest )
    {
        if ( fd != -1 )
        {
            dup2( fd, dest );
        }
    }

private:
    pid_t m_pid;
};

}

#endif

max_stars_repo_name: hindsights/xul

max_issues_repo_name: hindsights/xul

max_forks_repo_name: hindsights/xul


text:
//| Copyright Inria May 2015
//| This project has received funding from the European Research Council (ERC) under
//| the European Union's Horizon 2020 research and innovation programme (grant
//| agreement No 637972) - see http://www.resibots.eu
//|
//| Contributor(s):
//|   - Jean-Baptiste Mouret (jean-baptiste.mouret@inria.fr)
//|   - Antoine Cully (antoinecully@gmail.com)
//|   - Konstantinos Chatzilygeroudis (konstantinos.chatzilygeroudis@inria.fr)
//|   - Federico Allocati (fede.allocati@gmail.com)
//|   - Vaios Papaspyros (b.papaspyros@gmail.com)
//|   - Roberto Rama (bertoski@gmail.com)
//|
//| This software is a computer library whose purpose is to optimize continuous,
//| black-box functions. It mainly implements Gaussian processes and Bayesian
//| optimization.
//| Main repository: http://github.com/resibots/limbo
//| Documentation: http://www.resibots.eu/limbo
//|
//| This software is governed by the CeCILL-C license under French law and
//| abiding by the rules of distribution of free software.  You can  use,
//| modify and/ or redistribute the software under the terms of the CeCILL-C
//| license as circulated by CEA, CNRS and INRIA at the following URL
//| "http://www.cecill.info".
//|
//| As a counterpart to the access to the source code and  rights to copy,
//| modify and redistribute granted by the license, users are provided only
//| with a limited warranty  and the software's author,  the holder of the
//| economic rights,  and the successive licensors  have only  limited
//| liability.
//|
//| In this respect, the user's attention is drawn to the risks associated
//| with loading,  using,  modifying and/or developing or reproducing the
//| software by the user in light of its specific status of free software,
//| that may mean  that it is complicated to manipulate,  and  that  also
//| therefore means  that it is reserved for developers  and  experienced
//| professionals having in-depth computer knowledge. Users are therefore
//| encouraged to load and test the software's suitability as regards their
//| requirements in conditions enabling the security of their systems and/or
//| data to be ensured and,  more generally, to use and operate it in the
//| same conditions as regards security.
//|
//| The fact that you are presently reading this means that you have had
//| knowledge of the CeCILL-C license and that you accept its terms.
//|
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE test_nlopt

#include <boost/test/unit_test.hpp>

#include <limbo/limbo.hpp>
#include <limbo/opt/nlopt_grad.hpp>
#include <limbo/opt/nlopt_no_grad.hpp>

using namespace limbo;

struct Params {
    struct opt_nloptgrad : public defaults::opt_nloptgrad {
        BO_PARAM(int, iterations, 200);
    };

    struct opt_nloptnograd : public defaults::opt_nloptnograd {
        BO_PARAM(int, iterations, 200);
    };
};

opt::eval_t my_function(const Eigen::VectorXd& params, bool eval_grad)
{
    double v = -params(0) * params(0) - params(1) * params(1);
    if (!eval_grad)
        return opt::no_grad(v);
    Eigen::VectorXd grad(2);
    grad(0) = -2 * params(0);
    grad(1) = -2 * params(1);
    return {v, grad};
}

opt::eval_t my_constraint(const Eigen::VectorXd& params, bool eval_grad)
{
    double v = params(0) + 3. * params(1) - 10.;
    if (!eval_grad)
        return opt::no_grad(v);
    Eigen::VectorXd grad(2);
    grad(0) = 1.;
    grad(1) = 3.;
    return {v, grad};
}

opt::eval_t my_inequality_constraint(const Eigen::VectorXd& params, bool eval_grad)
{
    double v = -params(0) - 3. * params(1) + 10.;
    if (!eval_grad)
        return opt::no_grad(v);
    Eigen::VectorXd grad(2);
    grad(0) = -1.;
    grad(1) = -3.;
    return {v, grad};
}

BOOST_AUTO_TEST_CASE(test_nlopt_grad_simple)
{
    opt::NLOptGrad<Params, nlopt::LD_MMA> optimizer;
    Eigen::VectorXd g = optimizer(my_function, tools::random_vector(2), false);

    BOOST_CHECK_SMALL(g(0), 0.00000001);
    BOOST_CHECK_SMALL(g(1), 0.00000001);
}

BOOST_AUTO_TEST_CASE(test_nlopt_no_grad_simple)
{
    opt::NLOptNoGrad<Params, nlopt::LN_COBYLA> optimizer;
    Eigen::VectorXd best(2);
    best << 1, 1;
    size_t N = 10;
    for (size_t i = 0; i < N; i++) {
        Eigen::VectorXd g = optimizer(my_function, tools::random_vector(2), false);
        if (g.norm() < best.norm()) {
            best = g;
        }
    }

    BOOST_CHECK_SMALL(best(0), 0.00000001);
    BOOST_CHECK_SMALL(best(1), 0.00000001);
}

BOOST_AUTO_TEST_CASE(test_nlopt_no_grad_constraint)
{
    opt::NLOptNoGrad<Params, nlopt::LN_COBYLA> optimizer;
    optimizer.initialize(2);
    optimizer.add_equality_constraint(my_constraint);

    Eigen::VectorXd best = tools::random_vector(2).array() * 50.; // some random big value
    Eigen::VectorXd target(2);
    target << 1., 3.;
    size_t N = 10;
    for (size_t i = 0; i < N; i++) {
        Eigen::VectorXd g = optimizer(my_function, tools::random_vector(2), false);
        if ((g - target).norm() < (best - target).norm()) {
            best = g;
        }
    }

    BOOST_CHECK_SMALL(std::abs(1. - best(0)), 0.000001);
    BOOST_CHECK_SMALL(std::abs(3. - best(1)), 0.000001);
}

BOOST_AUTO_TEST_CASE(test_nlopt_grad_constraint)
{
    opt::NLOptGrad<Params, nlopt::LD_AUGLAG_EQ> optimizer;
    optimizer.initialize(2);
    optimizer.add_inequality_constraint(my_inequality_constraint);

    Eigen::VectorXd best = tools::random_vector(2).array() * 50.; // some random big value
    Eigen::VectorXd target(2);
    target << 1., 3.;
    size_t N = 10;
    for (size_t i = 0; i < N; i++) {
        Eigen::VectorXd g = optimizer(my_function, tools::random_vector(2), false);
        if ((g - target).norm() < (best - target).norm()) {
            best = g;
        }
    }

    BOOST_CHECK_SMALL(std::abs(1. - best(0)), 0.0001);
    BOOST_CHECK_SMALL(std::abs(3. - best(1)), 0.0001);
}


text:
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/util/exit.h"

#include <boost/optional.hpp>
#include <functional>
#include <stack>

#include "mongo/logv2/log.h"
#include "mongo/platform/mutex.h"
#include "mongo/stdx/condition_variable.h"
#include "mongo/stdx/thread.h"
#include "mongo/util/quick_exit.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kControl

namespace mongo {

namespace {

Mutex shutdownMutex;
stdx::condition_variable shutdownTasksComplete;
boost::optional<ExitCode> shutdownExitCode;
bool shutdownTasksInProgress = false;
AtomicWord<unsigned> shutdownFlag;
std::stack<unique_function<void(const ShutdownTaskArgs&)>> shutdownTasks;
stdx::thread::id shutdownTasksThreadId;

void runTasks(decltype(shutdownTasks) tasks, const ShutdownTaskArgs& shutdownArgs) noexcept {
    while (!tasks.empty()) {
        const auto& task = tasks.top();
        task(shutdownArgs);
        tasks.pop();
    }
}

// The logAndQuickExit_inlock() function should be called while holding the 'shutdownMutex' to
// prevent multiple threads from attempting to log that they are exiting. The quickExit() function
// has its own 'quickExitMutex' to prohibit multiple threads from attempting to call _exit().
MONGO_COMPILER_NORETURN void logAndQuickExit_inlock() {
    ExitCode code = shutdownExitCode.get();
    LOGV2(23138, "Shutting down with code: {exitCode}", "Shutting down", "exitCode"_attr = code);
    quickExit(code);
}

void setShutdownFlag() {
    shutdownFlag.fetchAndAdd(1);
}

}  // namespace

bool globalInShutdownDeprecated() {
    return shutdownFlag.loadRelaxed() != 0;
}

ExitCode waitForShutdown() {
    stdx::unique_lock<Latch> lk(shutdownMutex);
    shutdownTasksComplete.wait(lk, [] {
        const auto shutdownStarted = static_cast<bool>(shutdownExitCode);
        return shutdownStarted && !shutdownTasksInProgress;
    });

    return shutdownExitCode.get();
}

void registerShutdownTask(unique_function<void(const ShutdownTaskArgs&)> task) {
    stdx::lock_guard<Latch> lock(shutdownMutex);
    invariant(!globalInShutdownDeprecated());
    shutdownTasks.emplace(std::move(task));
}

void shutdown(ExitCode code, const ShutdownTaskArgs& shutdownArgs) {
    decltype(shutdownTasks) localTasks;

    {
        stdx::unique_lock<Latch> lock(shutdownMutex);

        if (shutdownTasksInProgress) {
            // Someone better have called shutdown in some form already.
            invariant(globalInShutdownDeprecated());

            // Re-entrant calls to shutdown are not allowed.
            invariant(shutdownTasksThreadId != stdx::this_thread::get_id());

            ExitCode originallyRequestedCode = shutdownExitCode.get();
            if (code != originallyRequestedCode) {
                LOGV2(23139,
                      "While running shutdown tasks with the intent to exit with code "
                      "{originalExitCode}, an additional shutdown request arrived with "
                      "the intent to exit with a different exit code {newExitCode}; "
                      "ignoring the conflicting exit code",
                      "Conflicting exit code at shutdown",
                      "originalExitCode"_attr = originallyRequestedCode,
                      "newExitCode"_attr = code);
            }

            // Wait for the shutdown tasks to complete
            while (shutdownTasksInProgress)
                shutdownTasksComplete.wait(lock);

            logAndQuickExit_inlock();
        }

        setShutdownFlag();
        shutdownExitCode.emplace(code);
        shutdownTasksInProgress = true;
        shutdownTasksThreadId = stdx::this_thread::get_id();

        localTasks.swap(shutdownTasks);
    }

    runTasks(std::move(localTasks), shutdownArgs);

    {
        stdx::lock_guard<Latch> lock(shutdownMutex);
        shutdownTasksInProgress = false;

        shutdownTasksComplete.notify_all();

        logAndQuickExit_inlock();
    }
}

void shutdownNoTerminate(const ShutdownTaskArgs& shutdownArgs) {
    decltype(shutdownTasks) localTasks;

    {
        stdx::lock_guard<Latch> lock(shutdownMutex);

        if (globalInShutdownDeprecated())
            return;

        setShutdownFlag();
        shutdownTasksInProgress = true;
        shutdownTasksThreadId = stdx::this_thread::get_id();

        localTasks.swap(shutdownTasks);
    }

    runTasks(std::move(localTasks), shutdownArgs);

    {
        stdx::lock_guard<Latch> lock(shutdownMutex);
        shutdownTasksInProgress = false;
        shutdownExitCode.emplace(EXIT_CLEAN);
    }

    shutdownTasksComplete.notify_all();
}

}  // namespace mongo

max_stars_repo_name: benety/mongo

max_issues_repo_name: benety/mongo

max_forks_repo_name: benety/mongo


text:
// Copyright (C) 2006 The Trustees of Indiana University.

// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

//  Authors: Douglas Gregor
//           Jeremiah Willcock
//           Andrew Lumsdaine

// Distributed version of the two-bit color map
#ifndef BOOST_DISTRIBUTED_TWO_BIT_COLOR_MAP_HPP
#define BOOST_DISTRIBUTED_TWO_BIT_COLOR_MAP_HPP

#ifndef BOOST_GRAPH_USE_MPI
#error "Parallel BGL files should not be included unless <boost/graph/use_mpi.hpp> has been included"
#endif

#include <boost/graph/two_bit_color_map.hpp>
#include <boost/property_map/parallel/distributed_property_map.hpp>
#include <boost/property_map/parallel/local_property_map.hpp>

namespace boost {

template<typename ProcessGroup, typename GlobalMap, typename StorageMap>
class two_bit_color_map<local_property_map<ProcessGroup,GlobalMap,StorageMap> >
  : public parallel::distributed_property_map<ProcessGroup, GlobalMap,
                                              two_bit_color_map<StorageMap> >
{
  typedef two_bit_color_map<StorageMap> local_map;

  typedef parallel::distributed_property_map<ProcessGroup, GlobalMap,
                                             local_map >
    inherited;

  typedef local_property_map<ProcessGroup, GlobalMap, StorageMap>
    index_map_type;

public:
  two_bit_color_map(std::size_t inital_size,
                    const index_map_type& index = index_map_type())
    : inherited(index.process_group(),  index.global(),
                local_map(inital_size, index.base())) { }

  inherited&       base()       { return *this; }
  const inherited& base() const { return *this; }
};

template<typename ProcessGroup, typename GlobalMap, typename StorageMap>
inline two_bit_color_type
get(two_bit_color_map<local_property_map<ProcessGroup,GlobalMap,StorageMap> >
      const& pm,
    typename two_bit_color_map<GlobalMap>::key_type key)
{
  return get(pm.base(), key);
}

template<typename ProcessGroup, typename GlobalMap, typename StorageMap>
inline void
put(two_bit_color_map<local_property_map<ProcessGroup,GlobalMap,StorageMap> >
      const& pm,
    typename two_bit_color_map<GlobalMap>::key_type key,
    two_bit_color_type value)
{
  put(pm.base(), key, value);
}

template<typename ProcessGroup, typename GlobalMap, typename StorageMap>
class two_bit_color_map<parallel::distributed_property_map<
                          ProcessGroup, GlobalMap, StorageMap> >
  : public parallel::distributed_property_map<
             ProcessGroup, GlobalMap, two_bit_color_map<StorageMap> >
{
  typedef two_bit_color_map<StorageMap> local_map;

  typedef parallel::distributed_property_map<ProcessGroup,GlobalMap,local_map>
    inherited;

  typedef parallel::distributed_property_map<ProcessGroup, GlobalMap,
                                             StorageMap>
    index_map_type;

public:
  two_bit_color_map(std::size_t inital_size,
                    const index_map_type& index = index_map_type())
    : inherited(index.process_group(),  index.global(),
                local_map(inital_size, index.base())) { }

  inherited&       base()       { return *this; }
  const inherited& base() const { return *this; }
};

template<typename ProcessGroup, typename GlobalMap, typename StorageMap>
inline two_bit_color_type
get(two_bit_color_map<
      parallel::distributed_property_map<
        ProcessGroup, GlobalMap, two_bit_color_map<StorageMap> > > const& pm,
    typename two_bit_color_map<GlobalMap>::key_type key)
{
  return get(pm.base(), key);
}

template<typename ProcessGroup, typename GlobalMap, typename StorageMap>
inline void
put(two_bit_color_map<
      parallel::distributed_property_map<
        ProcessGroup, GlobalMap, two_bit_color_map<StorageMap> > > const& pm,
    typename two_bit_color_map<GlobalMap>::key_type key,
    two_bit_color_type value)
{
  put(pm.base(), key, value);
}

} // end namespace boost

#endif // BOOST_DISTRIBUTED_TWO_BIT_COLOR_MAP_HPP

max_stars_repo_name: EricBoittier/vina-carb-docker

max_issues_repo_name: EricBoittier/vina-carb-docker

max_forks_repo_name: EricBoittier/vina-carb-docker


text:
#pragma optimize( "", off )
#include "stdafx.h"
#include <dos.h>
#if defined _WIN32
#include <windows.h>
#endif

#include <stdarg.h>
#include <stdio.h>
#include <conio.h>
#include <string>
#include <iostream>
#include "thzcbs.h"
#include "cppfbp.h"

#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>

#include <boost/ptr_container/ptr_list.hpp>

#define FILE struct _iobuf

void disp_IP(IPh   * this_IP);
/* first param of thxbnet is subnet address; last is whole net address */
int thxbnet(label_ent * label_ptr, Process *mother,
	Network * network, label_ent *label_tab);
//int findmod(char * p);

int thxscan(FILE *fp, label_ent *label, char file_name[10]);

int thzsend(Process *pptr, void **ptr, port_ent *peptr, int elem_no);
int thzcrep(Process *pptr, void **ptr, long IPsize, char *type);
int thzdrop(Process *pptr, void **ptr);
void thziclos(Process * proc, Port * cpp, int i);

//void thzputs(Process * p, char * buffer);

//static void run(Process * proc);

bool deadlock_test_sw = TRUE;

void Network::go(label_ent * label_blk, bool dynam, FILE * fp, bool timereq, _anchor proc_anchor) {
	Process *this_proc;
	cnxt_ent *cnxt_tab;
	proc_ent *proc_tab;
	label_ent *label_tab;
	label_ent *label_curr;
	label_ent *label_new;

	char file_name[10];

	Port *cpp;
	time_t st_time, end_time;
	double secs;
	st_time = time(NULL);

	Process * mother = (Process *) proc_anchor.reserved;

	_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF | _CRTDBG_LEAK_CHECK_DF);

	label_tab = (label_ent *)malloc(sizeof(label_ent));
	label_curr = label_tab;
	label_ent * label_this = label_blk;
	if (!dynam) {
		for (;;) {
			strcpy(label_curr->label,
				label_this->label);
			strcpy(label_curr->file,
				label_this->file);
			label_curr->cnxt_ptr =
				label_this->cnxt_ptr;
			label_curr->proc_ptr =
				label_this->proc_ptr;
			label_curr->ent_type =
				label_this->ent_type;
			label_this = label_this->succ;
			if (label_this == 0) break;
			label_new = (label_ent *)malloc(sizeof(label_ent));  // handle subnets
			label_curr->succ = label_new;
			label_curr = label_new;
		}

		cnxt_tab = label_tab -> cnxt_ptr;
		proc_tab = label_tab -> proc_ptr;
	}
	else {
		label_tab->succ = 0;
		file_name[0] = '\0';

		//if (fp == 0) {
		//	printf("File does not exist: %s\n", fp);
		//	exit(4);
		//}
		if (thxscan(fp, label_tab, file_name) != 0) {

			printf("Scan error\n");
			exit(4);
		}
	}
	//network = new Appl;
	//network = this;
	if (proc_anchor.reserved == NULL)
		strcpy(name,"APPL");
	else
		strcpy(name,"SUBNET");
	//first_ready_proc = 0;
	first_child_proc = 0;
	first_child_comp = 0;
	first_cnxt = 0;
	dynam = dynam;
	active = FALSE;
	possibleDeadlock = FALSE;
	deadlock = FALSE;

	thxbnet(label_tab, mother, this, label_tab);  // first param is network/subnet, 2nd is "mother" process", 4th is network as a whole

	int thread_count = 0;

	this_proc = (Process*) first_child_proc;
	while (this_proc != 0)
	{
		thread_count ++;
		this_proc = this_proc -> next_proc;
	}

	/* Look for processes with no input ports */

	latch =  new Cdl(thread_count);

	Cnxt * cnxt_ptr = (Cnxt *) first_cnxt;
	while (cnxt_ptr != 0) {
		cnxt_ptr -> closed = FALSE;
		cnxt_ptr = cnxt_ptr -> succ;
	}

	this_proc = (Process*) first_child_proc;
	while (this_proc != 0)
	{
		this_proc -> network = this;
		this_proc-> self_starting = TRUE;
		cpp = this_proc -> in_ports;
		while (cpp != 0) {
			for (int i = 0; i < cpp -> elem_count; i++) {
				if (cpp -> elem_list[i].gen.connxn != 0 &&
					! cpp -> elem_list[i].is_IIP)
					this_proc->self_starting = FALSE;
			}
			cpp = cpp -> succ;
		}
		if (this_proc -> self_starting)
		{
			// add to ready chain
			//this_proc -> status = INITIATED;

			if (this_proc -> trace)
				printf("%s Initiated\n",this_proc -> procname);

			this_proc -> activate();
		}
		//thread_count ++;
		this_proc = this_proc -> next_proc;
	}

	active = TRUE;

	waitForAll();
	delete latch;

	//if (dynam) {                  -- check this out!
	//	free(cnxt_tab);
	//	free(proc_tab);
	//}

	//free (latch);
	thxfcbs();
	//free(label_tab);

	end_time = time(NULL);
	secs = difftime(end_time, st_time);
	if (timereq){
		printf("Elapsed time in seconds: %5.3f\n",secs);
	}

	if (strcmp(name, "SUBNET") != 0) {
	  //_CrtDumpMemoryLeaks();

	  printf("Press enter to terminate\n");
	  std::string line;
	  std::getline(std::cin, line);  // read a line from std::cin into line
	  //system("pause");  // to see console
	  exit(0);
	}
}

Cdl::Cdl(int ct)  {
	count = ct;
}

void Network::waitForAll() {
	//boost::chrono::milliseconds msec(500);

	for (;;) {
		//Cdl * l = latch;
		int res = latch -> wait() ;  // 1 means count hit zero; 0 means timeout interval expired
		if (res == 1)
			break;
		if (res == 0 && deadlock_test_sw && deadlock_test())
			break;
	}
}

/// Blocks until the latch has counted down to zero or hit no. of msecs, whichever comes first .
int Cdl::wait()
{
	boost::unique_lock<boost::mutex> lock( mutex );

	boost::chrono::milliseconds msec(500);
	boost::cv_status res;
	//while ( count > 0 )
	//{
	res = cond_var.wait_for(lock, msec);
	if (res == boost::cv_status::timeout)
		return 0;     //time expired

	else   if (count == 0)
		return 1;    //countdown hit zero

	else
		return -1;   // countdown did not hit zero, and interval not up!
	//}
	//return 1;  //countdown hit zero
}

/// Decrement the count and notify anyone waiting if we reach zero.
/// @note count must be greater than 0 or undefined behavior
void Cdl::count_down()
{
	//boost::lock_guard<boost::mutex> lock(mutex);
	boost::unique_lock<boost::mutex> lock(mutex );
	assert( count );
	if ( --count == 0 )
	{
		cond_var.notify_all();
	}
}

void Process::activate() {
	    HINSTANCE hDLL;
		char procname_in_dll[255];
		char dllname[255];
		char szBuf[80];
		//typedef int (__stdcall* LPFNDLLFUNC)(_anchor);
        //LPFNDLLFUNC lpfnDllFunc;

		if (status == NOT_STARTED) {
			status = ACTIVE;
			//printf("Activate %s", compname);
			if (faddr == NULL) {
				//if (!composite) {
				//	strcpy(szBuf, "No link but not marked composite: ");
				//			strcat(szBuf, compname);
				//			MessageBox(NULL, szBuf, "Subnet specification", MB_ICONHAND);
				//}

				/* Load the CppFBPComponents module. This logic assumes all components in one dll file */

					strcpy(dllname, "TestSubnets.dll");
					hDLL = LoadLibrary(dllname);
					if (hDLL == NULL) {
						strcpy(szBuf, "LoadLibrary failed: ");
						strcat(szBuf, dllname);
						MessageBox(NULL, szBuf, "Library Functions", MB_ICONHAND);
					}
					else {

						/* Retrieve the address of the actual function. */

						strcpy_s(procname_in_dll, compname);

						faddr = (LPFNDLLFUNC)	GetProcAddress(hDLL, procname_in_dll);

						if (faddr == NULL) {
							GetLastError();
							strcpy(szBuf, "GetProcAddress failed: ");
							strcat(szBuf, procname_in_dll);
							MessageBox(NULL, szBuf, "Library Functions", MB_ICONHAND);
						}
					}
			}
			//else {
			boost::thread thread(&Process::run, this);
			//}
		}
		else if (status == DORMANT) {
			canGo.notify_all();
		}
	}

void Process::run() {

	//proc -> status = ACTIVE;

	/*
	run_test() returns 0 if data waiting
	1 if no data waiting, but not all upstream connections are closed
	2 if no input ports or input ports are only IIP ports or all input ports closed
	*/

	for( ; ; ) {
		if (2 == run_test()  && ! must_run && ! self_starting)
			break;
		Port * cpp = in_ports;
		while (cpp != 0) {
			for (int i = 0; i < cpp -> elem_count; i++) {
				if (cpp -> elem_list[i].gen.connxn == 0)
					continue;
				if (! cpp -> elem_list[i].is_IIP)
					cpp -> elem_list[i].closed = FALSE;
			}
			cpp = cpp -> succ;
		}
		//
		// execute component code!
		//
		value =
			faddr (proc_anchor);
		//
		// component code returns
		//

		if (value > 0)
			printf ("Process %s returned with value %d\n",
			procname, value);
		if (owned_IPs > 0)
			printf("%s Deactivated with %d IPs not disposed of\n",
			procname, owned_IPs);

		cpp = in_ports;
		while (cpp != 0)
		{
			for (int i = 0; i < cpp -> elem_count; i++) {
				Cnxt * cnp = cpp -> elem_list[i].gen.connxn;
				if (cnp == 0)
					continue;
				if (cpp -> elem_list[i].is_IIP)
					cpp -> elem_list[i].closed = TRUE;
			}
			cpp = cpp -> succ;
		}
		if (trace)
			printf("%s Deactivated with retcode %d\n",
			procname, value);

		if (value > 4) {
			//proc -> terminating = TRUE;
			break;
		}

		int res;
		/* res =  0 if data in cnxt; 1 if upstream not closed;
		2 if upstream closed */

		res = run_test();

		if (res == 2) break;
		if (res == 0) continue;

		dormwait();
	}

	/*
	Process * lpProc;
	// This should only be done at termination time!
	if (lpProc -> end_port != 0) {
	lpProc -> value = thzcrep(lpProc,
	&lpProc -> int_ptr, 0, "\0");
	lpProc -> int_pe.cpptr = lpProc -> end_port;
	lpProc -> value = thzsend(lpProc,
	&lpProc -> int_ptr, &lpProc -> int_pe, 0);
	if (lpProc -> value > 0)
	lpProc -> value = thzdrop(lpProc,
	&lpProc -> int_ptr);
	//break;
	}

	*/
	//close_outputPorts(proc);

	Port * cpp = out_ports;
	while (cpp != 0)
	{
		for (int i = 0; i < cpp -> elem_count; i++) {
			if (cpp -> elem_list[i].gen.connxn == 0)
				continue;
			/*value = */ thziclos(this, cpp, i);
		}
		cpp = cpp -> succ;
	}

	//close_inputPorts(proc);
	cpp = in_ports;
	while (cpp != 0)
	{
		for (int i = 0; i < cpp -> elem_count; i++) {
			if (cpp -> elem_list[i].gen.connxn == 0)
				continue;
			if (! cpp -> elem_list[i].is_IIP)
				thziclos(this, cpp, i);
		}
		cpp = cpp -> succ;
	}
	//printf("Terminated %s\n", proc -> procname);
	status = TERMINATED;
	if (trace)
		printf("%s Terminated with retcode %d\n",
		procname, value);
	//proc -> thread.join();
	network -> latch -> count_down();
}

void inline Process::dormwait() {
	boost::unique_lock<boost::mutex> lock (mtx);
	status = DORMANT;
	canGo.wait(lock);
	status = ACTIVE;

}

int Process::run_test() {

	/*
	returns 0 if data waiting
	1 if no data waiting, but not all upstream connections are closed
	2 if no input ports or input ports are only IIP ports or all input ports closed
	*/
	int res  = 2;
	Cnxt * cnp;
	Port * cpp = in_ports;
	while (cpp != 0)
	{
		for (int i = 0; i < cpp -> elem_count; i++) {
			cnp = cpp -> elem_list[i].gen.connxn;

			if (cnp == 0)
				continue;
			if (cpp -> elem_list[i].is_IIP) {
				cpp -> elem_list[i].closed = FALSE;
				continue;
			}
			boost::unique_lock<boost::mutex>lock  (cnp ->mtx );
			if (cnp -> IPcount > 0){
				res  = 0;  // data in upstream connection
				lock.unlock();
				lock.~unique_lock();
				break;
			}

			if (cnp -> nonterm_upstream_proc_count == 0 )
				cnp -> closed = TRUE;
			else
				res  = 1;    // no data in connection, but upstream processes not all closed!
			lock.unlock();
			lock.~unique_lock();
		}
		if (res == 0)
			break;
		cpp = cpp -> succ;
	}
	return res;
}

bool Network::deadlock_test() {

	//testTimeouts(freq);
	if (active) {
		active = FALSE; // reset flag every 1/2 sec
	} else if (!possibleDeadlock) {
		possibleDeadlock = TRUE;
	} else {
		deadlock = TRUE; // well, maybe
		// so test state of components

		class ABC
		{
		public:
			char c [100];
		};
		boost::ptr_list<ABC> msgs;
		boost::ptr_list<ABC>::iterator iterMsg;

		ABC * s1 = new ABC;
		strcpy (s1 ->c, "Network has deadlocked\n");
		msgs.push_front(s1);  		// add in case msgs are printed

		bool deadlock = TRUE;
		Process * this_proc = (Process *) first_child_proc;
		//Cnxt * cnp;
		bool terminated = TRUE;
		while (this_proc != 0)
		{
			char  status [30];
			switch (this_proc -> status) {
			case NOT_STARTED:
				strcpy(status, "Not Started\n");
				terminated = FALSE;
				break;
			case ACTIVE:
				strcpy(status, "Active\n");
				terminated = FALSE;
				deadlock = FALSE;
				break;
			case DORMANT:
				strcpy(status, "Inactive\n");
				terminated = FALSE;
				break;
			case SUSPENDED_ON_SEND:
				terminated = FALSE;
				strcpy(status, "Suspended on Send\n");
				//cnp = (Cnxt *) this_proc -> waiting_cnxt;
				//if (cnp -> IPcount < cnp ->max_IPcount) {
				//	cnp->buffer_not_full.notify_all();
				//	deadlock = FALSE;
				//}
				break;
			case SUSPENDED_ON_RECV:
				terminated = FALSE;
				strcpy(status, "Suspended on Receive\n");
				break;
				//case INITIATED:
				//	printf (" Process %s Initiated\n", this_proc -> procname);
				//	break;
				//case READY_TO_RESUME:
				//	printf (" Process %s Ready to Resume\n", this_proc -> procname);
				//	break;
			case TERMINATED:
				strcpy(status, "Terminated\n");
				break;
			}
			char msg[100];
			strcpy (msg, "Process ");
			strcat (msg, this_proc -> procname);
			strcat (msg, " ");
			strcat (msg, status);
			ABC * s1 = new ABC;
			strcpy(s1 -> c, msg);
			msgs.push_front(s1);
			this_proc = this_proc -> next_proc;
		}

		//if (listCompStatus(msgs)) { // if TRUE, it is a deadlock
		//          interruptAll();
		if (deadlock && !terminated) {

			for (iterMsg = msgs.begin(); iterMsg != msgs.end(); iterMsg++)
			{
				printf(iterMsg -> c );
			}

			//char c; std::cin>>c;   // to see console

			//		kill everything!
			Process * this_proc = (Process *) first_child_proc;
			boost::thread::id nat =  boost::thread::id::id();   // Not a Thread
			while (this_proc != 0)
			{
				boost::thread::id id = this_proc -> thread.get_id();
				if (nat != id)
					this_proc -> thread.interrupt();
				this_proc = this_proc -> next_proc;
			}
			return TRUE;
		}
		// one or more components haven't started or
		// are in a long wait
		deadlock = FALSE;
		possibleDeadlock = FALSE;

	}
	return FALSE;
}

void Network::thxfcbs()
{
	Port *cpp, *oldPortp;
	Process *this_proc;
	Cnxt *this_cnxt;

		this_proc = first_child_proc;
	    while (this_proc != 0) {
		first_child_proc = this_proc -> next_proc;
		  cpp = this_proc -> out_ports;
		  while (cpp != 0) {
			oldPortp = cpp;
			cpp = cpp -> succ;
			free(oldPortp);
		  }
		  cpp = this_proc -> in_ports;
		  while (cpp != 0) {
			//for (i = 0; i < cpp -> elem_count; i++) {
				//Cnxt * cnp = (Cnxt *) cpp -> elem_list[i].gen.connxn;
				//if (cnp != 0) {
					//free(cnp);
				//}
			//}
			oldPortp = cpp;
			cpp = cpp -> succ;
			free(oldPortp);
		  }
		  //old_proc = this_proc;
		  //this_proc = this_proc -> next_proc;
		  this_proc -> mtx.~mutex();
		  this_proc -> canGo.~condition_variable_any();
		  delete this_proc;
		  this_proc = first_child_proc;
	}

	this_cnxt = first_cnxt;
	while (this_cnxt != 0) {
		first_cnxt = this_cnxt -> succ;
		delete this_cnxt;
		this_cnxt = first_cnxt;
	}

	//if (!deadsw) {
		//delete network;
		//printf("Done\n");
	//}
}

void disp_IP(IPh   * this_IP) {   // not currently used...
	char * dptr;
	IPh   * ip;
	int i;
	unsigned j;
	long size;
	char *type;

	dptr = (char *) ((IP *) this_IP) -> datapart;
	ip = this_IP;
	size = ip -> IP_size;
	type = ip -> type;
	printf ("IP not disposed of - Length: %ld, Type: %s, Data:",
		size,  type);
	for (i = 0; i < size; i++)  {
		j = (int) *(dptr + i);
		printf("%c",j);
	}
	printf("%c\n", (int) *(dptr + size));
}

max_stars_repo_name: nyue/cppfbp

max_issues_repo_name: nyue/cppfbp

max_forks_repo_name: nyue/cppfbp


text: #include <boost/thread/poly_lockable_adapter.hpp>


text:
#define BOOST_TEXT_DOXYGEN
#include <boost/text/transcode_iterator.hpp>

max_stars_repo_name: eightysquirrels/text

max_issues_repo_name: eightysquirrels/text

max_forks_repo_name: eightysquirrels/text