text:
#include <cstdint>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <thread>
#include <boost/format.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>

#define ELPP_CUSTOM_COUT std::cerr
#define ELPP_THREAD_SAFE 1
#include "easylogging++.h"
#include "tclap/CmdLine.h"
#include "ProgramOpts.hpp"
#include "Alignment.hpp"
#include "AlnGraphBoost.hpp"
#include "DazAlnProvider.hpp"
#include "BoundedBuffer.hpp"

INITIALIZE_NULL_EASYLOGGINGPP

ProgramOpts popts;

typedef std::vector<dagcon::Alignment> AlnVec;

struct TargetData {
    std::string targSeq;
    AlnVec alns;
};

typedef BoundedBuffer<TargetData> TrgBuf;
typedef BoundedBuffer<std::string> CnsBuf;

void Reader(TrgBuf& trgBuf, AlnProvider* ap) {
    try {
        TargetData td;
        bool hasNext = true;
        do {
            hasNext = ap->nextTarget(td.targSeq, td.alns);
            //for (auto& aln : td.alns)
            //    std::cerr << aln;
            if (! td.alns.empty())
                trgBuf.push(td);
        } while (hasNext);
    }
    catch (PacBio::DagCon::IOException& e) {
        std::cerr << e.what();
        exit(1);
    }

    // write out sentinals, one per consensus thread
    TargetData sentinel;
    for (int i=0; i < popts.threads; i++)
        trgBuf.push(sentinel);
}

void Consensus(int id, TrgBuf& trgBuf, CnsBuf& cnsBuf) {
    int fake_well_counter; // just to avoid too many reads in the same bin
    TargetData td;
    trgBuf.pop(&td);
    std::vector<CnsResult> seqs;
    el::Loggers::getLogger("Consensus");

    while (td.alns.size() > 0) {
        if (td.alns.size() < popts.minCov) {
            trgBuf.pop(&td);
            continue;
        }
        boost::format msg("(%d) calling: %s Alignments: %d");
        CLOG(INFO, "Consensus") << msg % id % td.alns[0].id % td.alns.size();

        AlnGraphBoost ag(td.targSeq);
        AlnVec alns = td.alns;
        for (auto it = alns.begin(); it != alns.end(); ++it) {
            if (it->qstr.length() < popts.minLen) continue;
            dagcon::Alignment aln = normalizeGaps(*it);
            // XXX: Shouldn't be needed for dazcon, but causes some infinite
            // loops in the current consensus code.
            trimAln(aln, popts.trim);
            ag.addAln(aln);
        }
        CVLOG(3, "Consensus") << "Merging nodes";
        ag.mergeNodes();
        CVLOG(3, "Consensus") << "Generating consensus";
        ag.consensus(seqs, popts.minCov, popts.minLen);
        for (auto it = seqs.begin(); it != seqs.end(); ++it) {
            CnsResult result = *it;
            boost::format fasta(">%s/%d/%d_%d\n%s\n");
            fasta % alns[0].id
                  % fake_well_counter
                  % result.range[0]
                  % result.range[1]
                  % result.seq;
            cnsBuf.push(fasta.str());
            ++fake_well_counter;
        }
        trgBuf.pop(&td);
    }
    boost::format msg("(%d) ending ...");
    CLOG(INFO, "Consensus") << msg % id;
    // write out a sentinal
    cnsBuf.push("");
}

void Writer(CnsBuf& cnsBuf) {
    std::string cns;
    cnsBuf.pop(&cns);
    int sentinelCount = 0;
    while (true) {
        std::cout << cns;
        if (cns == "" && ++sentinelCount == popts.threads)
            break;

        cnsBuf.pop(&cns);
    }
}

void parseArgs(int argc, char **argv) {

    try {
        TCLAP::CmdLine cmd("PBI consensus module", ' ', "0.3");
        TCLAP::ValueArg<int> threadArg(
            "j","threads",                 // short, long name
            "Number of consensus threads", // description
             false, 4,                     // required, default
             "int", cmd);

        TCLAP::ValueArg<unsigned int> minCovArg(
            "c","min-coverage",
            "Minimum coverage for correction",
            false, 6, "uint", cmd);

        TCLAP::ValueArg<unsigned int> minLenArg(
            "l","min-len",
            "Minimum length for correction",
            false, 500, "uint", cmd);

        TCLAP::ValueArg<unsigned int> trimArg(
            "t","trim",
            "Trim alignments on either size",
            false, 10, "uint", cmd);

        TCLAP::ValueArg<std::string> alnFileArg(
            "a","align-file",
            "Path to the alignments file",
            true,"","string", cmd);

        TCLAP::ValueArg<std::string> seqFileArg(
            "s","seq-file",
            "Path to the sequences file",
            true,"","string", cmd);

        TCLAP::ValueArg<unsigned int> maxHitArg(
            "m","max-hit",
            "Maximum number of hits to pass to consensus",
            false,85,"uint", cmd);

        TCLAP::SwitchArg sortCovArg("x","coverage-sort",
            "Sort hits by coverage", cmd, false);

        TCLAP::SwitchArg properOvlArg("o","only-proper-overlaps",
            "Use only 'proper overlaps', i.e., align to the ends", cmd, false);

        TCLAP::SwitchArg verboseArg("v","verbose",
            "Turns on verbose logging", cmd, false);

        TCLAP::UnlabeledMultiArg<int> targetArgs(
            "targets", "Limit consensus to list of target ids",
            false, "list of ints", cmd);

        cmd.parse(argc, argv);

        popts.minCov     = minCovArg.getValue();
        popts.minLen     = minLenArg.getValue();
        popts.trim       = trimArg.getValue();
        popts.alnFile    = alnFileArg.getValue();
        popts.seqFile    = seqFileArg.getValue();
        popts.threads    = threadArg.getValue();
        popts.maxHits    = maxHitArg.getValue();
        popts.sortCov    = sortCovArg.getValue();
        popts.properOvls = properOvlArg.getValue();
        std::vector<int> tgs = targetArgs.getValue();
        popts.targets.insert(tgs.begin(), tgs.end());
    } catch (TCLAP::ArgException& e) {
        std::cerr << "Error " << e.argId() << ": " << e.error() << std::endl;
        exit(1);
    }
}

int main(int argc, char* argv[]) {
    parseArgs(argc, argv);
#if ELPP_ASYNC_LOGGING
    el::base::elStorage.reset(
       new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()),
                                               new el::base::AsyncDispatchWorker())
    );
#else
    el::base::elStorage.reset(
       new el::base::Storage(el::LogBuilderPtr(new el::base::DefaultLogBuilder()))
    );
#endif  // ELPP_ASYNC_LOGGING
    START_EASYLOGGINGPP(argc, argv);

    LOG(INFO) << "Initializing alignment provider";
    DazAlnProvider* ap;
    ap = new DazAlnProvider(popts);
    TrgBuf trgBuf(20);
    CnsBuf cnsBuf(10);

    std::thread writerThread(Writer, std::ref(cnsBuf));

    std::vector<std::thread> cnsThreads;
    for (int i=0; i < popts.threads; i++) {
        std::thread ct(Consensus, i, std::ref(trgBuf), std::ref(cnsBuf));
        cnsThreads.push_back(std::move(ct));
    }

    std::thread readerThread(Reader, std::ref(trgBuf), ap);

    writerThread.join();

    std::vector<std::thread>::iterator it;
    for (it = cnsThreads.begin(); it != cnsThreads.end(); ++it)
        it->join();

    readerThread.join();

    delete ap;

    return 0;
}


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//

#include "pxr/pxr.h"

#include "pxr/base/tf/pyErrorInternal.h"

#include <boost/python/object.hpp>
#include <boost/python/extract.hpp>

using namespace boost::python;
using std::string;

PXR_NAMESPACE_OPEN_SCOPE

string
TfPyExceptionState::GetExceptionString() const
{
    TfPyLock lock;
    string s;
    // Save the exception state so we can restore it -- getting the exception
    // string should not affect the exception state.
    TfPyExceptionStateScope exceptionStateScope;
    try {
        object tbModule(handle<>(PyImport_ImportModule("traceback")));
        object exception = tbModule.attr("format_exception")(_type, _value,
                                                                    _trace);
        boost::python::ssize_t size = len(exception);
        for (boost::python::ssize_t i = 0; i < size; ++i) {
            s += extract<string>(exception[i]);
        }
    } catch (boost::python::error_already_set const &) {
        // Just ignore the exception.
    }
    return s;
}

PXR_NAMESPACE_CLOSE_SCOPE

ext: cpp

max_stars_repo_name: DougRogers-DigitalFish/USD

max_issues_repo_name: DougRogers-DigitalFish/USD

max_forks_repo_name: DougRogers-DigitalFish/USD


text:
#include <geometry.h>
#include <tiny.h>

#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>

#include <vector>

typedef tiny::MathTypes<float> MT;
typedef MT::vector3_type       V;
typedef MT::quaternion_type    Q;
typedef MT::real_type          T;

class ContactInfo
{
public:

  V m_point;
  V m_normal;
  T m_distance;

};

class MyCallback
  : public geometry::ContactsCallback<V>
{
public:

  std::vector<ContactInfo> m_contacts;

public:

  void operator()(
                  V const & point
                  , V const & normal
                  , typename V::real_type const & distance
                  )
  {
    ContactInfo info;

    info.m_point = point;
    info.m_normal = normal;
    info.m_distance = distance;

    m_contacts.push_back(info);
  }

};

BOOST_AUTO_TEST_SUITE(geometry);

BOOST_AUTO_TEST_CASE(contacts_sphere_tetrahedron_test)
{
  // Separation in vertex regions
  {
    V const center = V::make(2.1, 0.0, 0.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make(0.0, 2.1, 0.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make(0.0, 0.0, 2.1);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make(-1.0, -1.0, -1.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  // Separation in edge regions
  {
    V const center = V::make(0.5, -1.0, -0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make(-1.0, 0.5, -0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make(-1.0, -1.0, 0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make( 1.0, 1.0, -1.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make( 1.0, -1.0, 1.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make(-1.0, 1.0, 1.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  // Separation in face regions
  {
    V const center = V::make( 0.2, 0.2, -2.1);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make( 0.2, -2.1,  0.2);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make( -2.1, 0.2,  0.2);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  {
    V const center = V::make( 2.0, 2.0, 2.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(!test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 0u);
  }
  // Contacts in vertex regions
  {
    V const center = V::make(1.9, 0.0, 0.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 1.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0),-1.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);
  }
  {
    V const center = V::make(1.9, 0.0, 0.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, true);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 1.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 1.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);
  }

  {
    V const center = V::make(0.0, 1.9, 0.0);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make(0.0, 0.0, 1.9);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make(-0.5, -0.5, -0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  // Contact in edge regions
  {
    V const center = V::make(0.5, -0.5, -0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.5, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.707106769, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 0.707106769, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.292893231, 0.01);

  }
  {
    V const center = V::make(0.5, -0.5, -0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, true);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.5, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), -0.707106769, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), -0.707106769, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.292893231, 0.01);

  }
  {
    V const center = V::make(-0.5, 0.5, -0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make(-0.5, -0.5, 0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron,  callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make( 0.5, 0.5, -0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make( 0.5, -0.5, 0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make(-0.5, 0.5, 0.5);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  // Contact in face regions
  {
    V const center = V::make( 0.2, 0.2, -0.9);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.2, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.2, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2), 1.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);
  }
  {
    V const center = V::make( 0.2, 0.2, -0.9);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, true);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(0), 0.2, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(1), 0.2, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_point(2), 0.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(0), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(1), 0.0, 0.01);
    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_normal(2),-1.0, 0.01);

    BOOST_CHECK_CLOSE(callback.m_contacts[0].m_distance, -0.1, 0.01);
  }
  {
    V const center = V::make( 0.2, -0.9,  0.2);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make( -0.9, 0.2,  0.2);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }
  {
    V const center = V::make( 0.7, 0.7, 0.7);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }

  // sphere inside
  {
    V const center = V::make( 0.3, 0.2, 0.1);
    T const radius = 1.0;

    V const p0 = V::make(0.0, 0.0, 0.0);
    V const p1 = V::make(1.0, 0.0, 0.0);
    V const p2 = V::make(0.0, 1.0, 0.0);
    V const p3 = V::make(0.0, 0.0, 1.0);

    geometry::Sphere<V>      const sphere      = geometry::make_sphere(center, radius);
    geometry::Tetrahedron<V> const tetrahedron = geometry::make_tetrahedron(p0, p1, p2 ,p3);

    MyCallback callback;

    bool const test = geometry::contacts_sphere_tetrahedron(sphere, tetrahedron, callback, false);

    BOOST_CHECK(test);

    BOOST_CHECK_EQUAL(callback.m_contacts.size(), 1u);
  }

}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: diku-dk/PROX

max_forks_repo_name: diku-dk/PROX


text:
//          Copyright Gavin Band 2008 - 2012.
// 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 SQLITEHAPLOTYPESSNPDATASINK_HPP
#define SQLITEHAPLOTYPESSNPDATASINK_HPP

#include <iostream>
#include <string>
#include <Eigen/Core>
#include "genfile/snp_data_utils.hpp"
#include "genfile/gen.hpp"
#include "genfile/GenLikeSNPDataSink.hpp"
#include "qcdb/DBOutputter.hpp"

	// This class represents a SNPDataSink which writes its data
	// to a plain GEN file.
	class SQLiteHaplotypesSNPDataSink: public genfile::SNPDataSink
	{
	public:
		SQLiteHaplotypesSNPDataSink(
			qcdb::DBOutputter::UniquePtr outputter,
			genfile::CohortIndividualSource const& samples
		) ;

		operator bool() const { return true ; }
		std::string get_spec() const ;

        void set_genotype_field( std::string field ) ;

	private:
		std::string m_genotype_field ;
		qcdb::DBOutputter::UniquePtr m_outputter ;
		genfile::CohortIndividualSource const& m_samples ;
		db::Connection::StatementPtr m_insert_data_stmnt ;

		std::vector< genfile::VariantIdentifyingData > m_snps ;
		std::vector< std::vector< uint8_t > > m_data ;
		std::size_t m_data_i ;

	private:
		void set_sample_names_impl( std::size_t number_of_samples, SampleNameGetter getter ) ;

		void write_variant_data_impl(
			genfile::VariantIdentifyingData const& id_data,
			genfile::VariantDataReader& data_reader,
			Info const& info = Info()
		) ;

		void finalise_impl() ;

		void flush_data( std::size_t const data_count ) ;
	} ;

#endif

ext: hpp

max_stars_repo_name: CreRecombinase/qctool

max_issues_repo_name: CreRecombinase/qctool

max_forks_repo_name: CreRecombinase/qctool


text:
//
// Copyright (c) 2012-2020 Kris Jusiak (kris at jusiak dot net)
//
// 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)
//
//<-
// clang-format off
#include <initializer_list>  // has to be before, due to the bug in clang < 3.7
// clang-format on
#include <boost/di.hpp>
#include <cassert>
#include <memory>
#include <set>
#include <vector>

namespace di = boost::di;

struct i1 {
  virtual ~i1() noexcept = default;
  virtual void dummy1() = 0;
};
struct impl : i1 {
  void dummy1() override {}
};
struct impl1 : i1 {
  void dummy1() override {}
};
//->

int main() {
  // clang-format off
  auto il = {1, 2, 3};
  auto injector = di::make_injector(
    di::bind<int[]>().to(il) // or di::bind<int*[]>.to(il)
  );
  // clang-format on

  auto v = injector.create<std::vector<int>>();
  assert(3 == v.size());
  assert(1 == v[0]);
  assert(2 == v[1]);
  assert(3 == v[2]);
}

max_stars_repo_name: szigetics/di

max_issues_repo_name: szigetics/di

max_forks_repo_name: szigetics/di


text:
/*-----------------------------------------------------------------------
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agceements.  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 agceed 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 "MyOwnStoreProtocolHandlers.h"

#include <boost/log/trivial.hpp>

#include <fetpapi/etp/AbstractSession.h>
#include <fetpapi/etp/fesapi/FesapiHelpers.h>
#include <fetpapi/etp/EtpException.h>
#include <fetpapi/etp/EtpHelpers.h>

#include "MyDataObjectRepository.h"

MyOwnStoreProtocolHandlers::MyOwnStoreProtocolHandlers(ETP_NS::AbstractSession* mySession, MyDataObjectRepository* repo_) :
	ETP_NS::StoreHandlers(mySession), repo(repo_) {}

void MyOwnStoreProtocolHandlers::on_GetDataObjects(const Energistics::Etp::v12::Protocol::Store::GetDataObjects & msg, int64_t correlationId)
{
	Energistics::Etp::v12::Protocol::Store::GetDataObjectsResponse objResponse;

	Energistics::Etp::v12::Protocol::Core::ProtocolException pe;
	for (const auto & pair : msg.uris) {
		BOOST_LOG_TRIVIAL(trace) << "Store received URI : " << pair.second;

		try
		{
			COMMON_NS::AbstractObject* obj = repo->getObjectFromUri(pair.second);

			if (obj->isPartial()) {
				obj = repo->resolvePartial(obj);
			}

			Energistics::Etp::v12::Datatypes::Object::DataObject dataObject = ETP_NS::FesapiHelpers::buildEtpDataObjectFromEnergisticsObject(obj);
			objResponse.dataObjects[pair.first] = dataObject;
		}
		catch (ETP_NS::EtpException& ex)
		{
			pe.errors[pair.first].message = ex.what();
			pe.errors[pair.first].code = ex.getErrorCode();
		}
	}

	if (!pe.errors.empty()) {
		session->send(objResponse, correlationId);
		session->send(pe, correlationId, 0x02);
	}
	else {
		session->send(objResponse, correlationId, 0x02);
	}
}

void MyOwnStoreProtocolHandlers::on_PutDataObjects(const Energistics::Etp::v12::Protocol::Store::PutDataObjects & msg, int64_t correlationId)
{
	Energistics::Etp::v12::Protocol::Store::PutDataObjectsResponse objResponse;

	Energistics::Etp::v12::Protocol::Core::ProtocolException pe;
	for (const auto& pair : msg.dataObjects) {
		BOOST_LOG_TRIVIAL(trace) << "Store received data object : " << pair.second.resource.uri;

		const std::string dataObjectType = ETP_NS::EtpHelpers::getDataObjectType(pair.second.resource.uri);

		COMMON_NS::AbstractObject* importedObj = repo->addOrReplaceGsoapProxy(pair.second.data, dataObjectType);
		if (importedObj == nullptr) {
			pe.errors[pair.first].message = "Could not put the dataobject with content type " + dataObjectType;
			pe.errors[pair.first].code = 4001;
			continue;
		}

		importedObj->loadTargetRelationships();

		objResponse.success[pair.first] = Energistics::Etp::v12::Datatypes::Object::PutResponse();
	}

	if (!pe.errors.empty()) {
		session->send(objResponse, correlationId);
		session->send(pe, correlationId, 0x02);
	}
	else
	{
		session->send(objResponse, correlationId, 0x02);
	}
}

void MyOwnStoreProtocolHandlers::on_DeleteDataObjects(const Energistics::Etp::v12::Protocol::Store::DeleteDataObjects & msg, int64_t correlationId)
{
	Energistics::Etp::v12::Datatypes::ErrorInfo error;
	error.code = 7;
	error.message = "The operation is not supported by the agent.";
	Energistics::Etp::v12::Protocol::Core::ProtocolException pe;
	pe.error.emplace(error);

	session->send(pe, correlationId, 0x02);
}


text:
#pragma once
#include <string>
#include <vector>
#include <eosio/eosio.hpp>
#include <eosio/crypto.hpp>
#include <eosio/action.hpp>
#include <eosio/singleton.hpp>
#include "./multi_index.hpp"
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/list/for_each.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/seq/push_back.hpp>

#ifndef VACCOUNTS_DELAYED_CLEANUP
#define VACCOUNTS_DELAYED_CLEANUP 0
#endif

#ifndef VACCOUNTS_SHARD_PINNING
#define VACCOUNTS_SHARD_PINNING false
#endif

#define VACCOUNTS_DAPPSERVICE_SKIP_HELPER true
#define VACCOUNTS_DAPPSERVICE_SERVICE_MORE \
  void execute_vaccounts_action(action act){\
      print("should never get here");\
  }

void verify_signature(std::vector<char> payload, const eosio::signature& sig, const eosio::public_key& pubkey){
    auto digest = sha256( payload.data(), payload.size() );
    eosio::assert_recover_key( digest, sig, pubkey);
}

template<typename T>
struct dummy_wrapper {
      T payload;
};

#define VACCOUNTS_DAPPSERVICE_ACTIONS_MORE() \
eosio::public_key _pubkey;\
uint64_t _nonce;\
bool _verified = false; \
eosio::public_key get_current_public_key(){ \
    return _pubkey; \
} \
void required_key(const eosio::public_key& pubkey){ \
    eosio::check(_pubkey == pubkey, "wrong public key"); \
} \
struct unpacked_payload { \
  uint64_t expiry; \
  uint64_t nonce; \
  eosio::checksum256 chainid; \
  eosio::action action; \
}; \
unpacked_payload unpack_payload(std::vector<char> payload) { \
  eosio::check(payload.size() > 48, "header is required");\
  auto unpacked = eosio::unpack<unpacked_payload>( payload.data(), payload.size() ); \
  return unpacked; \
} \
void verify_chain(eosio::checksum256 chainid, uint64_t expiry) { \
  eosio::check(chainid == getChain(),"invalid chain id"); \
  eosio::check(current_time_point().sec_since_epoch() <= expiry, "transaction has expired"); \
} \
void unpack_exec_action(eosio::action res){ \
    switch(res.name.value){ \
      case name("regaccount").value: \
        regaccount(res.data_as<regaccount_action>()); \
        break; \
      default: \
        execute_vaccounts_action(res);  \
        break; \
    } \
} \
SVC_RESP_VACCOUNTS(vexec)(std::vector<char> payload, eosio::signature sig, eosio::public_key pubkey, name current_provider){ \
    verify_signature(payload, sig, pubkey); \
    auto unpacked = unpack_payload(payload); \
    verify_chain(unpacked.chainid, unpacked.expiry); \
    _nonce = unpacked.nonce; \
    _pubkey = pubkey;\
    unpack_exec_action(unpacked.action); \
} \
TABLE vchain { \
  eosio::checksum256 chainid; \
}; \
TABLE vkey { \
  eosio::public_key pubkey; \
  name vaccount; \
  uint64_t nonce; \
  uint64_t primary_key() const {return vaccount.value;} \
}; \
typedef eosio::singleton<"vchain"_n, vchain> vchain_t; \
typedef dapp::multi_index<"vkey"_n, vkey> vkeys_t; \
typedef eosio::multi_index<".vkey"_n,vkey> vkeys_t_v_abi;\
TABLE shardbucket_t {\
        std::vector<char> shard_uri;\
        uint64_t shard;\
        uint64_t primary_key() const { return shard; }\
};\
typedef eosio::multi_index<"vkey"_n, shardbucket_t> vkeys_t_abi;\
struct regaccount_action { \
  name vaccount; \
  EOSLIB_SERIALIZE( regaccount_action, (vaccount) ) \
}; \
[[eosio::action]] void regaccount(regaccount_action payload) { \
    print("setting key for:");\
    print(payload.vaccount);\
    print("\n");\
   setKey(payload.vaccount, get_current_public_key()); \
} \
[[eosio::action]] void xvinit(eosio::checksum256 chainid) { \
    require_auth(_self); \
    print("setting chainid:");\
    print(chainid);\
    print("\n");\
   setChain(chainid); \
} \
void require_vaccount(name vaccount){ \
    auto pkey = handleNonce(vaccount); \
    required_key(pkey); \
} \
void setKey(name vaccount, eosio::public_key pubkey){ \
    vkeys_t vkeys_table(_self, _self.value, 1024, 64, VACCOUNTS_SHARD_PINNING, false, VACCOUNTS_DELAYED_CLEANUP); \
    auto existing = vkeys_table.find(vaccount.value); \
    eosio::check(existing == vkeys_table.end(),"vaccount already exists"); \
    vkeys_table.emplace(_self,[&]( auto& new_key ){ \
      new_key.pubkey = pubkey; \
      new_key.vaccount = vaccount;\
    }); \
} \
void setChain(eosio::checksum256 chainid){ \
    vchain_t vchain_table(_self, _self.value); \
    eosio::check(!vchain_table.exists(),"chain id has already been set"); \
    auto vchain = vchain_table.get_or_default(); \
    vchain.chainid = chainid; \
    vchain_table.set(vchain, _self); \
} \
eosio::public_key getKey(name vaccount){ \
    vkeys_t vkeys_table(_self, _self.value, 1024, 64, VACCOUNTS_SHARD_PINNING, false, VACCOUNTS_DELAYED_CLEANUP); \
    auto existing = vkeys_table.find(vaccount.value); \
    eosio::check(existing != vkeys_table.end(),"vaccount not found"); \
    return existing->pubkey; \
} \
eosio::public_key handleNonce(name vaccount){ \
    if(_verified) { return getKey(vaccount); } \
    vkeys_t vkeys_table(_self, _self.value, 1024, 64, VACCOUNTS_SHARD_PINNING, false, VACCOUNTS_DELAYED_CLEANUP); \
    auto existing = vkeys_table.find(vaccount.value); \
    eosio::check(existing != vkeys_table.end(),"vaccount not found"); \
    eosio::check(existing->nonce == _nonce,"invalid nonce"); \
    vkeys_table.modify(existing,_self,[&]( auto& v ){ \
      v.nonce++; \
    }); \
    _verified = true;\
    return existing->pubkey; \
} \
eosio::checksum256 getChain(){ \
    vchain_t vchain_table(_self, _self.value); \
    auto existing = vchain_table.get(); \
    return existing.chainid; \
}\

#define POPULATE_VACTION(r, dummy, field)                                           \
  case TONAME(BOOST_PP_SEQ_ELEM(1, field)).value: \
    { \
        auto payload_data = act.data_as<BOOST_PP_SEQ_ELEM(0, field)>(); \
        BOOST_PP_SEQ_ELEM(1, field)(payload_data); \
    } while(0); \
    break;

//hello(wrapper.payload[0]);

#define POPULATE_VACTION2(r, dummy, field) \
  BOOST_PP_SEQ_ELEM(1, field)

#define CONTRACT_ACTION_V_APPLY(VACTIONS) \
    BOOST_PP_SEQ_FOR_EACH(POPULATE_VACTION2, DUMMY_MACRO, VACTIONS)

#define VACCOUNTS_APPLY(VACTIONS) \
  void execute_vaccounts_action(action act){ \
    switch(act.name.value){ \
      BOOST_PP_SEQ_FOR_EACH(POPULATE_VACTION, DUMMY_MACRO, VACTIONS)\
      default: \
        break; \
    } \
  }


text:
#ifndef SDM_UTILS_HPP_
#define SDM_UTILS_HPP_

#include "fmath.hpp"
#include "alias.hpp"

#include <Eigen/Core>
#include <Eigen/SparseCore>

#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <cstdarg>
#include <cstddef>
#include <fstream>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <numeric>
#include <random>
#include <sstream>
#include <string>
#include <vector>

namespace sdm {

static inline void
get_cross_validation_index(const int num_fold, const int num_ins,
                           std::vector<std::vector<int>> &train_indexs,
                           std::vector<std::vector<int>> &valid_indexs,
                           const bool random_flag = false,
                           const bool seed_flag = false) {
  train_indexs.clear();
  train_indexs.resize(num_fold);
  valid_indexs.clear();
  valid_indexs.resize(num_fold);
  std::vector<int> whole_index(num_ins);
  std::iota(std::begin(whole_index), std::end(whole_index), 0);

  if (random_flag) {
    std::mt19937 engine;
    if (seed_flag) {
      std::random_device rnd;
      std::vector<std::uint_least32_t> v(10);
      std::generate(std::begin(v), std::end(v), std::ref(rnd));
      std::seed_seq seed(std::begin(v), std::end(v));
      engine.seed(seed);
    }
    std::shuffle(std::begin(whole_index), std::end(whole_index), engine);
  }

  int each_fold_num_ins = num_ins / num_fold;
  std::vector<int> each_fold_num_ins_vec(num_fold, each_fold_num_ins);
  int rest = num_ins % num_fold;
  for (int i = 0; i < rest; ++i)
    ++each_fold_num_ins_vec[i];

  auto start_it = std::begin(whole_index);
  auto end_it = std::end(whole_index);
  for (int i = 0; i < num_fold; ++i) {
    valid_indexs[i].reserve(each_fold_num_ins_vec[i]);
    end_it = start_it + each_fold_num_ins_vec[i];
    valid_indexs[i].insert(std::end(valid_indexs[i]), start_it, end_it);
    start_it = end_it;
  }

  for (int i = 0; i < num_fold; ++i) {
    std::sort(std::begin(valid_indexs[i]), std::end(valid_indexs[i]));
    train_indexs[i].reserve(num_ins - each_fold_num_ins_vec[i]);
  }

  for (int i = 0; i < num_fold; ++i)
    for (int j = 0; j < num_fold; ++j)
      if (i != j)
        train_indexs[j].insert(std::end(train_indexs[j]),
                               std::begin(valid_indexs[i]),
                               std::end(valid_indexs[i]));

  for (int i = 0; i < num_fold; ++i)
    std::sort(std::begin(train_indexs[i]), std::end(train_indexs[i]));
}

// misc
static inline std::vector<std::string> split_string(const std::string &str,
                                                    const std::string &delim) {
  std::vector<std::string> res;
  std::string::size_type current = 0, found, delimlen = delim.size();
  while ((found = str.find(delim, current)) != std::string::npos) {
    res.push_back(std::string(str, current, found - current));
    current = found + delimlen;
  }
  res.push_back(std::string(str, current, str.size() - current));
  return res;
}

static inline int count_lines(const std::string file_name) {
  int num_lines = 0;
  std::ifstream data_file;
  std::string line;
  data_file.open(file_name);
  if (data_file.fail()) {
    std::cerr << "Unable to open " << file_name << '\n';
    exit(8);
  }
  while (std::getline(data_file, line))
    ++num_lines;
  data_file.close();

  return num_lines;
}

// for cygwin(GCC) can't use std::stoi
static inline int str2int(const std::string &s) {
  int r = 0;
  bool neg = false;
  int index = 0;
  while (s[index] == ' ')
    ++index;
  if (s[index] == '-') {
    neg = true;
    ++index;
  } else if (s[index] == '+') {
    ++index;
  }
  while (s[index] >= '0' && s[index] <= '9') {
    r = (r * 10.0) + (s[index] - '0');
    ++index;
  }
  if (neg) {
    r = -r;
  }
  return r;
}

template <typename ValueType> ValueType naive_atot(const char *p) {
  ValueType r = 0.0;
  bool neg = false;
  while (*p == ' ')
    ++p;
  if (*p == '-') {
    neg = true;
    ++p;
  } else if (*p == '+') {
    ++p;
  }
  while (*p >= '0' && *p <= '9') {
    r = (r * 10.0) + (*p - '0');
    ++p;
  }
  if (*p == '.') {
    ValueType f = 0.0;
    int n = 0;
    ++p;
    while (*p >= '0' && *p <= '9') {
      f = (f * 10.0) + (*p - '0');
      ++p;
      ++n;
    }
    r += f / std::pow(10.0, n);
  }
  if (neg) {
    r = -r;
  }
  return r;
}

template <typename ValueType> ValueType naive_atot(const std::string &s) {
  ValueType r = 0.0;
  bool neg = false;
  auto it = s.begin();
  while (*it == ' ')
    ++it;
  if (*it == '-') {
    neg = true;
    ++it;
  } else if (*it == '-') {
    ++it;
  }
  while (*it >= '0' && *it <= '9') {
    r = (r * 10.0) + (*it - '0');
    ++it;
  }
  if (*it == '.') {
    ++it;
    ValueType f = 0.0;
    int n = 0;
    while (*it >= '0' && *it <= '9') {
      f = (f * 10.0) + (*it - '0');
      ++it;
      ++n;
    }
    r += f / std::pow(10.0, n);
  }
  if (neg)
    r = -r;
  return r;
}

template <typename RealType1, typename RealType2>
inline bool lessPair(const std::pair<RealType1, RealType2> &l,
                     const std::pair<RealType1, RealType2> &r) {
  return l.second < r.second;
}

template <typename RealType1, typename RealType2>
inline bool greaterPair(const std::pair<RealType1, RealType2> &l,
                        const std::pair<RealType1, RealType2> &r) {
  return l.second > r.second;
}

template <typename RealType> inline double norm_cdf(const RealType x) {
  constexpr double a1 = 0.254829592;
  constexpr double a2 = -0.284496736;
  constexpr double a3 = 1.421413741;
  constexpr double a4 = -1.453152027;
  constexpr double a5 = 1.061405429;
  constexpr double p = 0.3275911;

  int sign = 1;
  if (x < static_cast<RealType>(0.0))
    sign = -1;
  double tmp = fabs(x) / sqrt(2.0);

  // A&S formula 7.1.26
  double t = 1.0 / (1.0 + p * tmp);
  double y = 1.0 -
             (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t *
                 fmath::exp(-tmp * tmp);

  return 0.5 * (1.0 + sign * y);
}

template <typename RealType> inline double normsinv(const RealType pos) {

  constexpr double A1 = (-3.969683028665376e+01);
  constexpr double A2 = 2.209460984245205e+02;
  constexpr double A3 = (-2.759285104469687e+02);
  constexpr double A4 = 1.383577518672690e+02;
  constexpr double A5 = (-3.066479806614716e+01);
  constexpr double A6 = 2.506628277459239e+00;

  constexpr double B1 = (-5.447609879822406e+01);
  constexpr double B2 = 1.615858368580409e+02;
  constexpr double B3 = (-1.556989798598866e+02);
  constexpr double B4 = 6.680131188771972e+01;
  constexpr double B5 = (-1.328068155288572e+01);

  constexpr double C1 = (-7.784894002430293e-03);
  constexpr double C2 = (-3.223964580411365e-01);
  constexpr double C3 = (-2.400758277161838e+00);
  constexpr double C4 = (-2.549732539343734e+00);
  constexpr double C5 = 4.374664141464968e+00;
  constexpr double C6 = 2.938163982698783e+00;

  constexpr double D1 = 7.784695709041462e-03;
  constexpr double D2 = 3.224671290700398e-01;
  constexpr double D3 = 2.445134137142996e+00;
  constexpr double D4 = 3.754408661907416e+00;

  constexpr double P_LOW = 0.02425;
  /* P_high = 1 - p_low*/
  constexpr double P_HIGH = 0.97575;

  double x = 0.0;
  double q, r;
  if ((0 < pos) && (pos < P_LOW)) {
    q = sqrt(-2 * fmath::log(pos));
    x = (((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) /
        ((((D1 * q + D2) * q + D3) * q + D4) * q + 1);
  } else {
    if ((P_LOW <= pos) && (pos <= P_HIGH)) {
      q = pos - 0.5;
      r = q * q;
      x = (((((A1 * r + A2) * r + A3) * r + A4) * r + A5) * r + A6) * q /
          (((((B1 * r + B2) * r + B3) * r + B4) * r + B5) * r + 1);
    } else {
      if ((P_HIGH < pos) && (pos < 1)) {
        q = sqrt(-2 * fmath::log(1 - pos));
        x = -(((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) /
            ((((D1 * q + D2) * q + D3) * q + D4) * q + 1);
      } else {
        std::cout << "CDF position > 1 : " << pos << std::endl;
        x = 1.0;
      }
    }
  }

  /*
  // If you are composiling this under UNIX OR LINUX, you may uncomment this
  // block for better accuracy.
  if(( 0 < pos)&&(pos < 1)){
    e = 0.5 * erfc(-x/sqrt(2)) - pos;
    u = e * sqrt(2*M_PI) * exp(x*x/2);
    x = x - u/(1 + x*u/2);
  }
  */

  return x;
}

template <typename ValueType>
bool compare(const ValueType &lhs, const ValueType &rhs,
             const ValueType eps = 1e-12) {
  return (std::abs(lhs - rhs) <= std::max(lhs, rhs) * eps ||
          std::abs(lhs - rhs) <= eps);
}

template <typename ValueType, int _Rows, int _Cols, int _Option>
ValueType compare(const Eigen::Matrix<ValueType, _Rows, _Cols, _Option> &mat,
                  const ValueType value, const ValueType eps = 1e-12) {
  ValueType v;
  int num_eq = 0;
  if (_Option == Eigen::RowMajor) {
    for (int i = 0; i < mat.rows(); ++i) {
      for (int j = 0; j < mat.cols(); ++j) {
        v = mat.coeffRef(i, j);
        if (compare(v, value, eps))
          ++num_eq;
      }
    }
  } else {
    for (int j = 0; j < mat.cols(); ++j) {
      for (int i = 0; i < mat.rows(); ++i) {
        v = mat.coeffRef(i, j);
        if (compare(v, value, eps))
          ++num_eq;
      }
    }
  }
  return num_eq;
}

} // namespace sdm

#endif


text:
#ifndef _VINECOPULACPP_HEADER_HPP_
#define _VINECOPULACPP_HEADER_HPP_

// headers
#include <iostream>
#include <string>
#define _USE_MATH_DEFINES
#include <cmath>
#include <vector>
#include <nlopt.hpp>
#include <algorithm>
#include <utility>
#include <omp.h>

#include <stdlib.h>
#include <stdio.h>

#include<fstream>
#include<time.h>

// headers from the boost library
#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/students_t.hpp>
//#include <boost/math/special_functions/detail/t_distribution_inv.hpp>
#include <boost/math/tools/roots.hpp>
#include <boost/random.hpp>

// gsl library
//#include <stdio.h>
//#include <gsl/gsl_cdf.h>

#ifndef DBL_MAX
#define DBL_MAX 1.79769e+308
#endif

// User written headers
#include "VineCopulaCPP_helper.hpp"
#include "VineCopulaCPP_PC.hpp"
#include "VineCopulaCPP_PathToBoundsAndSeed.hpp"

#endif


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

#ifndef LANE_CHANGE_PLANNER__UTILITIES_HPP_
#define LANE_CHANGE_PLANNER__UTILITIES_HPP_

#include "lane_change_planner/route_handler.hpp"

#include <rclcpp/rclcpp.hpp>

#include <autoware_perception_msgs/msg/dynamic_object_array.hpp>
#include <autoware_planning_msgs/msg/path.hpp>
#include <autoware_planning_msgs/msg/path_with_lane_id.hpp>
#include <geometry_msgs/msg/point.hpp>
#include <geometry_msgs/msg/pose.hpp>
#include <geometry_msgs/msg/pose_array.hpp>

#include <boost/geometry/geometries/box.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>
#include <boost/geometry/geometry.hpp>

#include <lanelet2_core/geometry/Lanelet.h>
#include <lanelet2_routing/Route.h>
#include <lanelet2_routing/RoutingGraph.h>
#include <lanelet2_routing/RoutingGraphContainer.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>

#include <limits>
#include <string>
#include <vector>

namespace lane_change_planner
{
namespace util
{
using Point = boost::geometry::model::d2::point_xy<double>;
using Polygon = boost::geometry::model::polygon<Point>;
using LineString = boost::geometry::model::linestring<Point>;
struct FrenetCoordinate3d
{
  double length;
  double distance;
  FrenetCoordinate3d() : length(0), distance(0) {}
};

double normalizeRadian(const double radian);
double l2Norm(const geometry_msgs::msg::Vector3 vector);

Eigen::Vector3d convertToEigenPt(const geometry_msgs::msg::Point geom_pt);
std::vector<geometry_msgs::msg::Point> convertToGeometryPointArray(
  const autoware_planning_msgs::msg::PathWithLaneId & path);
geometry_msgs::msg::PoseArray convertToGeometryPoseArray(
  const autoware_planning_msgs::msg::PathWithLaneId & path);

autoware_perception_msgs::msg::PredictedPath convertToPredictedPath(
  const autoware_planning_msgs::msg::PathWithLaneId & path,
  const geometry_msgs::msg::Twist & vehicle_twist, const geometry_msgs::msg::Pose & vehicle_pose,
  const double duration, const double resolution, const double acceleration,
  const rclcpp::Logger & logger, const rclcpp::Clock::SharedPtr & clock);
autoware_perception_msgs::msg::PredictedPath resamplePredictedPath(
  const autoware_perception_msgs::msg::PredictedPath & input_path, const double resolution,
  const double duration, const rclcpp::Logger & logger, const rclcpp::Clock::SharedPtr & clock);

bool convertToFrenetCoordinate3d(
  const std::vector<geometry_msgs::msg::Point> & linestring,
  const geometry_msgs::msg::Point search_point_geom, FrenetCoordinate3d * frenet_coordinate);

geometry_msgs::msg::Pose lerpByPose(
  const geometry_msgs::msg::Pose & p1, const geometry_msgs::msg::Pose & p2, const double t);

geometry_msgs::msg::Point lerpByLength(
  const std::vector<geometry_msgs::msg::Point> & array, const double length);
bool lerpByTimeStamp(
  const autoware_perception_msgs::msg::PredictedPath & path, const rclcpp::Time & t,
  geometry_msgs::msg::Pose * lerped_pt, const rclcpp::Logger & logger,
  const rclcpp::Clock::SharedPtr & clock);

double getDistance3d(const geometry_msgs::msg::Point & p1, const geometry_msgs::msg::Point & p2);
double getDistanceBetweenPredictedPaths(
  const autoware_perception_msgs::msg::PredictedPath & path1,
  const autoware_perception_msgs::msg::PredictedPath & path2, const double start_time,
  const double end_time, const double resolution, const rclcpp::Logger & logger,
  const rclcpp::Clock::SharedPtr & clock);

double getDistanceBetweenPredictedPathAndObject(
  const autoware_perception_msgs::msg::DynamicObject & object,
  const autoware_perception_msgs::msg::PredictedPath & path, const double start_time,
  const double end_time, const double resolution, const rclcpp::Logger & logger,
  const rclcpp::Clock::SharedPtr & clock);

std::vector<size_t> filterObjectsByLanelets(
  const autoware_perception_msgs::msg::DynamicObjectArray & objects,
  const lanelet::ConstLanelets & lanelets, const double start_arc_length,
  const double end_arc_length, const rclcpp::Logger & logger);

std::vector<size_t> filterObjectsByLanelets(
  const autoware_perception_msgs::msg::DynamicObjectArray & objects,
  const lanelet::ConstLanelets & target_lanelets, const rclcpp::Logger & logger);

bool calcObjectPolygon(
  const autoware_perception_msgs::msg::DynamicObject & object, Polygon * object_polygon,
  const rclcpp::Logger & logger);

std::vector<size_t> filterObjectsByPath(
  const autoware_perception_msgs::msg::DynamicObjectArray & objects,
  const std::vector<size_t> & object_indices,
  const autoware_planning_msgs::msg::PathWithLaneId & ego_path, const double vehicle_width,
  const rclcpp::Logger & logger);

const geometry_msgs::msg::Pose refineGoal(
  const geometry_msgs::msg::Pose & goal, const lanelet::ConstLanelet & goal_lanelet);

autoware_planning_msgs::msg::PathWithLaneId refinePath(
  const double search_radius_range, const double search_rad_range,
  const autoware_planning_msgs::msg::PathWithLaneId & input, const geometry_msgs::msg::Pose & goal,
  const int64_t goal_lane_id, const rclcpp::Logger & logger);
autoware_planning_msgs::msg::PathWithLaneId removeOverlappingPoints(
  const autoware_planning_msgs::msg::PathWithLaneId & input_path);

bool containsGoal(const lanelet::ConstLanelets & lanes, const lanelet::Id & goal_id);

nav_msgs::msg::OccupancyGrid generateDrivableArea(
  const lanelet::ConstLanelets & lanes, const geometry_msgs::msg::PoseStamped & current_pose,
  const double width, const double height, const double resolution, const double vehicle_length,
  const RouteHandler & route_handler);

double getDistanceToEndOfLane(
  const geometry_msgs::msg::Pose & current_pose, const lanelet::ConstLanelets & lanelets);

double getDistanceToNextIntersection(
  const geometry_msgs::msg::Pose & current_pose, const lanelet::ConstLanelets & lanelets);
double getDistanceToCrosswalk(
  const geometry_msgs::msg::Pose & current_pose, const lanelet::ConstLanelets & lanelets,
  const lanelet::routing::RoutingGraphContainer & overall_graphs);
double getSignedDistance(
  const geometry_msgs::msg::Pose & current_pose, const geometry_msgs::msg::Pose & goal_pose,
  const lanelet::ConstLanelets & lanelets);

std::vector<uint64_t> getIds(const lanelet::ConstLanelets & lanelets);

autoware_planning_msgs::msg::Path convertToPathFromPathWithLaneId(
  const autoware_planning_msgs::msg::PathWithLaneId & path_with_lane_id);

lanelet::Polygon3d getVehiclePolygon(
  const geometry_msgs::msg::Pose & vehicle_pose, const double vehicle_width,
  const double base_link2front);

autoware_planning_msgs::msg::PathPointWithLaneId insertStopPoint(
  double length, autoware_planning_msgs::msg::PathWithLaneId * path);

double getArcLengthToTargetLanelet(
  const lanelet::ConstLanelets & current_lanes, const lanelet::ConstLanelet & target_lane,
  const geometry_msgs::msg::Pose & pose);

std::vector<Polygon> getTargetLaneletPolygons(
  const lanelet::ConstLanelets & lanelets, const geometry_msgs::msg::Pose & pose,
  const double check_length, const std::string & target_type);

std::vector<Polygon> filterObstaclePolygons(
  const std::vector<Polygon> & obstacle_polygons,
  const autoware_perception_msgs::msg::DynamicObjectArray & objects,
  const double static_obstacle_velocity_thresh);

double getDistanceToNearestObstaclePolygon(
  const std::vector<Polygon> & obstacle_polygons, const geometry_msgs::msg::Pose & pose);

class SplineInterpolate
{
  bool initialized_ = false;
  std::vector<double> a_;
  std::vector<double> b_;
  std::vector<double> c_;
  std::vector<double> d_;
  std::vector<double> h_;
  rclcpp::Logger logger_;

public:
  explicit SplineInterpolate(const rclcpp::Logger & logger);
  bool interpolate(
    const std::vector<double> & base_index, const std::vector<double> & base_value,
    const std::vector<double> & return_index, std::vector<double> & return_value);

private:
  double getValue(const double & query, const std::vector<double> & base_index) const;
  void generateSpline(
    const std::vector<double> & base_index, const std::vector<double> & base_value);
  bool isIncrease(const std::vector<double> & x) const;
  bool isValidInput(
    const std::vector<double> & base_index, const std::vector<double> & base_value,
    const std::vector<double> & return_index, std::vector<double> & return_value) const;
  std::vector<double> solveLinearSystem(const double omega, const size_t max_iter) const;
  bool isConvergeL1(
    const std::vector<double> & r1, const std::vector<double> & r2,
    const double converge_range) const;
};

}  // namespace util
}  // namespace lane_change_planner

#endif  // LANE_CHANGE_PLANNER__UTILITIES_HPP_


text:
#include "fakeit.hpp"
#include "mocks/Wire.h"
#include "test_utils.h"
#include <boost/endian/conversion.hpp>
#include <boost/test/unit_test.hpp>

// File being tested:
#include "sensor_mcp_9808.h"

using namespace scottz0r::temperature;
using namespace fakeit;

/// @brief Configure the given mock with a happy path i2c setup sequence for the MCP 9808 sensor.
/// @param mock Mock object to configure.
void configure_mock_begin_happy(Mock<TwoWireImpl> &mock)
{
    // Two 2-byte available reads for device info
    When(Method(mock, available)).Return(2, 2);

    Fake(Method(mock, begin));
    Fake(Method(mock, beginTransmission));

    // Three "good" calls to endTransmission. Two for reading device info, one for writing config.
    When(Method(mock, endTransmission)).Return(0, 0, 0);

    // Four bytes read for Manufacture id 84 and device id 1024 (big endian).
    When(Method(mock, read)).Return(0x00, 0x54, 0x04, 0x00);

    Fake(Method(mock, requestFrom));

    // Always return that byte was written.
    When(Method(mock, write)).AlwaysReturn(1);
}

BOOST_AUTO_TEST_SUITE(sensor_mcp_9808)

BOOST_AUTO_TEST_CASE(it_should_construct_default_state)
{
    SensorMcp9808 sensor;

    BOOST_TEST(sensor.bad());
    BOOST_TEST(!sensor.good());
}

BOOST_AUTO_TEST_CASE(it_should_begin_good_address)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    // Setup mock to get information from I2C device successfully.
    Mock<TwoWireImpl> mock;
    configure_mock_begin_happy(mock);
    wire_impl = &mock.get();

    SensorMcp9808 sensor;
    bool rc = false;

    rc = sensor.begin(0x18);
    BOOST_TEST(rc);
    BOOST_TEST(sensor.good());
    BOOST_TEST(!sensor.bad());
}

BOOST_AUTO_TEST_CASE(it_should_not_begin_setup_i2c_failure)
{
    // This test is for code coverage in read16() function to test bad transmit status and unexpected available().

    auto always = make_always([&]() { wire_impl = nullptr; });

    // Setup mock to fail on I2C register transmission.
    Mock<TwoWireImpl> mock;
    Fake(Method(mock, beginTransmission));
    Fake(Method(mock, write));
    When(Method(mock, endTransmission)).Return(1);
    When(Method(mock, requestFrom)).Return(2);
    When(Method(mock, available)).Return(2);
    When(Method(mock, read)).Return(0x00, 0x54, 0x04, 0x00);
    wire_impl = &mock.get();

    SensorMcp9808 sensor;
    bool rc = false;

    rc = sensor.begin(0x18);
    BOOST_TEST(!rc);
    BOOST_TEST(!sensor.good());
    BOOST_TEST(sensor.bad());

    // Similar test, but setup mock to return an incorrect number of bytes for 16 bit register read.
    mock.Reset();
    Fake(Method(mock, beginTransmission));
    Fake(Method(mock, write));
    When(Method(mock, endTransmission)).Return(0);
    When(Method(mock, requestFrom)).Return(1);
    When(Method(mock, available)).Return(1);
    When(Method(mock, read)).Return(0x00, 0x00);
    wire_impl = &mock.get();

    rc = sensor.begin(0x18);
    BOOST_TEST(!rc);
    BOOST_TEST(!sensor.good());
    BOOST_TEST(sensor.bad());
}

BOOST_AUTO_TEST_CASE(it_should_not_begin_bad_address)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    SensorMcp9808 sensor;
    bool rc = false;

    // Setup mock to get information from I2C device successfully.
    Mock<TwoWireImpl> mock;
    configure_mock_begin_happy(mock);
    wire_impl = &mock.get();

    // Address too small.
    rc = sensor.begin(0x17);
    BOOST_TEST(!rc);
    BOOST_TEST(!sensor.good());
    BOOST_TEST(sensor.bad());

    // Address too large.
    rc = sensor.begin(0x20);
    BOOST_TEST(!rc);
    BOOST_TEST(!sensor.good());
    BOOST_TEST(sensor.bad());
}

BOOST_AUTO_TEST_CASE(it_should_not_allow_begin_multiple_calls)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    SensorMcp9808 sensor;

    // Setup mock to get information from I2C device successfully.
    Mock<TwoWireImpl> mock;
    configure_mock_begin_happy(mock);
    wire_impl = &mock.get();

    bool rc = false;

    rc = sensor.begin(0x18);
    BOOST_TEST(rc);

    // Reset mock into a state that would start successfully, again.
    mock.Reset();
    configure_mock_begin_happy(mock);

    rc = sensor.begin(0x18);
    BOOST_TEST(!rc);
}

BOOST_AUTO_TEST_CASE(it_should_not_begin_bad_manuf_id)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    SensorMcp9808 sensor;

    // Setup a setup happy path, except the read() return values from the i2c device.
    Mock<TwoWireImpl> mock;
    When(Method(mock, available)).Return(2, 2);
    Fake(Method(mock, begin));
    Fake(Method(mock, beginTransmission));
    When(Method(mock, endTransmission)).Return(0, 0, 0);
    Fake(Method(mock, requestFrom));
    When(Method(mock, write)).AlwaysReturn(1);

    // Return bad manufacture id, but good device id.
    When(Method(mock, read)).Return(0xC3, 0x70, 0x04, 0x00);

    wire_impl = &mock.get();

    bool rc = sensor.begin(0x18);
    BOOST_TEST(!rc);
    BOOST_TEST(!sensor.good());
    BOOST_TEST(sensor.bad());
}

BOOST_AUTO_TEST_CASE(it_should_not_begin_bad_device_id)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    SensorMcp9808 sensor;

    // Setup a setup happy path, except the read() return values from the i2c device.
    Mock<TwoWireImpl> mock;
    When(Method(mock, available)).Return(2, 2);
    Fake(Method(mock, begin));
    Fake(Method(mock, beginTransmission));
    When(Method(mock, endTransmission)).Return(0, 0, 0);
    Fake(Method(mock, requestFrom));
    When(Method(mock, write)).AlwaysReturn(1);

    // Return good manufacture id, but bad device id.
    When(Method(mock, read)).Return(0x00, 0x54, 0x14, 0xAA);

    wire_impl = &mock.get();

    bool rc = sensor.begin(0x18);
    BOOST_TEST(!rc);
    BOOST_TEST(!sensor.good());
    BOOST_TEST(sensor.bad());
}

BOOST_AUTO_TEST_CASE(it_should_not_begin_bad_config)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    SensorMcp9808 sensor;

    // Setup a setup happy path, except the endTransmission() return value.
    Mock<TwoWireImpl> mock;
    When(Method(mock, available)).Return(2, 2);
    Fake(Method(mock, begin));
    Fake(Method(mock, beginTransmission));
    Fake(Method(mock, requestFrom));
    When(Method(mock, read)).Return(0x00, 0x54, 0x04, 0x00);
    When(Method(mock, write)).AlwaysReturn(1);

    // Make 3rd call to end transmission fail, which will fail the device configuration step.
    When(Method(mock, endTransmission)).Return(0, 0, 2);

    wire_impl = &mock.get();

    bool rc = sensor.begin(0x18);
    BOOST_TEST(!rc);
    BOOST_TEST(!sensor.good());
    BOOST_TEST(sensor.bad());
}

BOOST_AUTO_TEST_CASE(it_should_read_good_state_positive_temp)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    // Setup mock to get setup information from I2C device successfully.
    Mock<TwoWireImpl> mock;
    configure_mock_begin_happy(mock);
    wire_impl = &mock.get();

    SensorMcp9808 sensor;
    bool rc = false;

    rc = sensor.begin(0x18);
    BOOST_TEST(rc);

    // Setup mock to return 13.37 degrees, which is 214 in the device's max resolution.
    // Device returns big endian two's complement in 13 bits.
    mock.Reset();
    Fake(Method(mock, beginTransmission));
    Fake(Method(mock, write));
    When(Method(mock, endTransmission)).Return(0);
    When(Method(mock, requestFrom)).Return(2);
    When(Method(mock, available)).Return(2);
    When(Method(mock, read)).Return(0x00, 0xD6);

    int16_t temp = 0;
    rc = sensor.read_temp(temp);

    BOOST_TEST(rc);
    BOOST_TEST(temp == 1337);
}

BOOST_AUTO_TEST_CASE(it_should_read_good_state_negative_temp)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    // Setup mock to get setup information from I2C device successfully.
    Mock<TwoWireImpl> mock;
    configure_mock_begin_happy(mock);
    wire_impl = &mock.get();

    SensorMcp9808 sensor;
    bool rc = false;

    rc = sensor.begin(0x18);
    BOOST_TEST(rc);

    // Setup mock to return -35.00 degrees. Device returns big endian two's complement in 13 bits.
    mock.Reset();
    Fake(Method(mock, beginTransmission));
    Fake(Method(mock, write));
    When(Method(mock, endTransmission)).Return(0);
    When(Method(mock, requestFrom)).Return(2);
    When(Method(mock, available)).Return(2);
    When(Method(mock, read)).Return(0x1D, 0xD0);

    int16_t temp = 0;
    rc = sensor.read_temp(temp);

    BOOST_TEST(rc);
    BOOST_TEST(temp == -3500);
}

BOOST_AUTO_TEST_CASE(it_should_read_good_state_failure)
{
    auto always = make_always([&]() { wire_impl = nullptr; });

    // Setup mock to get setup information from I2C device successfully.
    Mock<TwoWireImpl> mock;
    configure_mock_begin_happy(mock);
    wire_impl = &mock.get();

    SensorMcp9808 sensor;
    bool rc = false;

    rc = sensor.begin(0x18);
    BOOST_TEST(rc);

    // Setup mock to make next read a failure.
    mock.Reset();
    Fake(Method(mock, beginTransmission));
    Fake(Method(mock, write));
    When(Method(mock, endTransmission)).Return(1); // Failure transmission.

    int16_t temp = 0;
    rc = sensor.read_temp(temp);

    BOOST_TEST(!rc);
}

BOOST_AUTO_TEST_CASE(it_should_return_false_read_bad_state)
{
    SensorMcp9808 sensor;

    // Don't call begin(), which means sensor is in a bad or not configured state.
    int16_t sensor_reading = 123;
    bool rc = sensor.read_temp(sensor_reading);

    BOOST_TEST(sensor.bad());
    BOOST_TEST(!sensor.good());
    BOOST_TEST(!rc);
    BOOST_TEST(sensor_reading == 0);
}

BOOST_AUTO_TEST_SUITE_END()


text:
// Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/ext/boost/mpl/list.hpp>
#include <boost/hana/find.hpp>
#include <boost/hana/find_if.hpp>
#include <boost/hana/optional.hpp>
#include <boost/hana/type.hpp>

#include <boost/mpl/list.hpp>
namespace hana = boost::hana;
namespace mpl = boost::mpl;

BOOST_HANA_CONSTANT_CHECK(
    hana::find_if(mpl::list<int, float, char const*>{}, hana::equal.to(hana::type_c<float>))
    ==
    hana::just(hana::type_c<float>)
);

BOOST_HANA_CONSTANT_CHECK(
    hana::find(mpl::list<int, float, char const*>{}, hana::type_c<void>)
    ==
    hana::nothing
);

int main() { }

max_issues_repo_name: lipper/arangodb

max_forks_repo_name: lipper/arangodb