text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/*                                                                           */
/*  This file is part of the library KASKADE 7                               */
/*    see http://www.zib.de/projects/kaskade7-finite-element-toolbox         */
/*                                                                           */
/*  Copyright (C) 2002-2011 Zuse Institute Berlin                            */
/*                                                                           */
/*  KASKADE 7 is distributed under the terms of the ZIB Academic License.    */
/*    see $KASKADE/academic.txt                                              */
/*                                                                           */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

#include <iostream>

#include <boost/timer/timer.hpp>

#include "dune/grid/config.h"
#include "dune/grid/uggrid.hh"

#include "fem/gridmanager.hh"
#include "fem/lagrangespace.hh"
#include "timestepping/limexWithoutJens.hh"
#include "utilities/gridGeneration.hh" //  createUnitSquare

using namespace Kaskade;

#include "mygrid.hh"
#include "integrate.hh"
#include "movingsource.hh"

struct InitialValue
{
  using Scalar = double;
  static int const components = 1;
  using ValueType = Dune::FieldVector<Scalar,components>;

  InitialValue(int c): component(c) {}

  template <class Cell> int order(Cell const&) const { return std::numeric_limits<int>::max(); }
  template <class Cell>
  ValueType value(Cell const& cell,
                  Dune::FieldVector<typename Cell::ctype,Cell::dimension> const& localCoordinate) const
  {
    Dune::FieldVector<typename Cell::ctype,Cell::dimensionworld> x = cell.geometry().global(localCoordinate);
    x -= 0.5;
    return 0.0;
  }

private:
  int component;
};

int main(int argc, char *argv[])
  {
    int const dim = 2;
    int refinements = 5, order = 2, extrapolOrder = 2, maxSteps = 100,
      verbosity=1;
    double dt = 0.1, maxDT = 1.0, T = 1.0, rTolT = 1.0e-3, aTolT = 1.0e-3, rTolX = 2.0e-5, aTolX = 2.0e-5, writeInterval = 1.0;

    std::cout << "Start moving source tutorial program" << std::endl;

    using Grid = Dune::UGGrid<dim>;
    using H1Space = FEFunctionSpace<ContinuousLagrangeMapper<double,Grid::LeafGridView> >;
    using Spaces = boost::fusion::vector<H1Space const*>;
    using VariableDescriptions = boost::fusion::vector<VariableDescription<0,1,0> >;
    using VariableSet = VariableSetDescription<Spaces,VariableDescriptions>;
    using Equation = MovingSourceEquation<double,VariableSet>;

    GridManager<Grid> gridManager(RefineGrid<Grid>(refinements));
    std::cout << "Grid: " << gridManager.grid().size(0) << " " << gridManager.grid().size(1) << " "
              << gridManager.grid().size(2) << std::endl;

// construct involved spaces.

  H1Space temperatureSpace(gridManager,gridManager.grid().leafView(),order);

    Spaces spaces(&temperatureSpace);

    std::string varNames[1] = { "u" };

    VariableSet variableSet(spaces,varNames);

    Equation Eq;

  std::vector<VariableSet::VariableSet> solutions;
  // std::vector<VariableSet::VariableSet> devnull;

  Eq.time(0);
  VariableSet::VariableSet x(variableSet);
  Eq.scaleInitialValue<0>(InitialValue(0),x);

  x = integrate(gridManager,Eq,variableSet,spaces,
          dt,maxDT,T,maxSteps,rTolT,aTolT,rTolX,aTolX,extrapolOrder,
          std::back_inserter(solutions),writeInterval,x,DirectType::SUPERLU,verbosity);

    std::cout << "End moving source tutorial program" << std::endl;

  }

max_stars_repo_name: chenzongxiong/streambox

max_issues_repo_name: chenzongxiong/streambox

max_forks_repo_name: chenzongxiong/streambox


text:
/*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  DynamoBI 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 "fennel/common/CommonPreamble.h"
#include "fennel/exec/MockProducerExecStream.h"
#include "fennel/tuple/TupleAccessor.h"
#include "fennel/tuple/TuplePrinter.h"
#include "fennel/tuple/StandardTypeDescriptor.h"
#include "fennel/exec/ExecStreamBufAccessor.h"
#include <boost/scoped_array.hpp>

FENNEL_BEGIN_CPPFILE("$Id$");

MockProducerExecStream::MockProducerExecStream()
{
    cbTuple = 0;
    nRowsProduced = nRowsMax = 0;
    saveTuples = false;
    echoTuples = 0;
}

void MockProducerExecStream::prepare(MockProducerExecStreamParams const &params)
{
    SingleOutputExecStream::prepare(params);
    pGenerator = params.pGenerator;
    pBatchGenerator = params.pBatchGenerator;
    for (uint i = 0; i < params.outputTupleDesc.size(); i++) {
        assert(!params.outputTupleDesc[i].isNullable);
        StandardTypeDescriptorOrdinal ordinal =
            StandardTypeDescriptorOrdinal(
                params.outputTupleDesc[i].pTypeDescriptor->getOrdinal());
        assert(StandardTypeDescriptor::isIntegralNative(ordinal));
        if (pGenerator) {
            assert(ordinal == STANDARD_TYPE_INT_64);
        }
    }
    outputData.compute(params.outputTupleDesc);
    TupleAccessor &tupleAccessor = pOutAccessor->getScratchTupleAccessor();
    assert(tupleAccessor.isFixedWidth());
    cbTuple = tupleAccessor.getMaxByteCount();
    nRowsMax = params.nRows;
    saveTuples = params.saveTuples;
    echoTuples = params.echoTuples;
    if (saveTuples || echoTuples) {
        assert(pGenerator);
    }
}

void MockProducerExecStream::open(bool restart)
{
    SingleOutputExecStream::open(restart);
    nRowsProduced = 0;
    savedTuples.clear();
    if (saveTuples) {
        // assume it's not too big
        savedTuples.reserve(nRowsMax);
    }
}

ExecStreamResult MockProducerExecStream::execute(
    ExecStreamQuantum const &quantum)
{
    if (pGenerator) {
        TuplePrinter tuplePrinter;
        uint nTuples = 0;
        boost::scoped_array<int64_t> values(new int64_t[outputData.size()]);
        for (int col = 0; col < outputData.size(); ++col) {
            outputData[col].pData = reinterpret_cast<PConstBuffer>(
                &(values.get()[col]));
        }
        while (nRowsProduced < nRowsMax) {
            if (pOutAccessor->getProductionAvailable() < cbTuple) {
                return EXECRC_BUF_OVERFLOW;
            }

            if (pBatchGenerator) {
                int64_t newBatch = pBatchGenerator->next();
                if (newBatch == 0) {
                    return EXECRC_QUANTUM_EXPIRED;
                }
            }

            for (int col = 0; col < outputData.size(); ++col) {
                values.get()[col] =
                    pGenerator->generateValue(nRowsProduced, col);
            }

            bool rc = pOutAccessor->produceTuple(outputData);
            assert(rc);
            ++nTuples;
            ++nRowsProduced;
            if (echoTuples) {
                tuplePrinter.print(
                    *echoTuples,
                    pOutAccessor->getTupleDesc(), outputData);
            }
            if (saveTuples) {
                std::ostringstream oss;
                tuplePrinter.print(
                    oss, pOutAccessor->getTupleDesc(), outputData);
                savedTuples.push_back(oss.str());
            }
            if (nTuples >= quantum.nTuplesMax) {
                return EXECRC_QUANTUM_EXPIRED;
            }
        }
        pOutAccessor->markEOS();
        return EXECRC_EOS;
    }

    // NOTE: implementation below is kept lean and mean
    // intentionally so that it can be used to drive other streams with minimal
    // overhead during profiling

    uint cb = pOutAccessor->getProductionAvailable();
    uint nRows = std::min<uint64_t>(nRowsMax - nRowsProduced, cb / cbTuple);
    uint cbBatch = nRows * cbTuple;

    // TODO:  pOutAccessor->validateTupleSize(?);
    if (cbBatch) {
        cb -= cbBatch;
        nRowsProduced += nRows;
        PBuffer pBuffer = pOutAccessor->getProductionStart();
        memset(pBuffer, 0, cbBatch);
        pOutAccessor->produceData(pBuffer + cbBatch);
        pOutAccessor->requestConsumption();
    }
    if (nRowsProduced == nRowsMax) {
        pOutAccessor->markEOS();
        return EXECRC_EOS;
    } else {
        return EXECRC_BUF_OVERFLOW;
    }
}

uint64_t MockProducerExecStream::getProducedRowCount()
{
    uint waitingRowCount = pOutAccessor->getConsumptionTuplesAvailable();
    return nRowsProduced - waitingRowCount;
}

MockProducerExecStreamGenerator::~MockProducerExecStreamGenerator()
{
}

FENNEL_END_CPPFILE("$Id$");

// End MockProducerExecStream.cpp

ext: cpp


text:
#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <iostream>
#include <random>

BOOST_DATA_TEST_CASE(
    test1,
    boost::unit_test::data::xrange(2) * boost::unit_test::data::xrange(3),
    xr1, xr2)
{
    std::cout << "test 1: " << xr1 << ", " << xr2 << std::endl;
    BOOST_TEST((xr1 <= 2 && xr2 <= 3));
}

BOOST_DATA_TEST_CASE(
    test2,
    boost::unit_test::data::xrange(3) * (boost::unit_test::data::random(
                                            boost::unit_test::data::distribution =
                                              std::uniform_real_distribution<float>
                                                ( 1, 2))
                                         ^
                                         boost::unit_test::data::xrange(2)),
    xr,
    random_sample,
    index)
{
    std::cout << "test 2: " << xr << " / " << random_sample << ", " << index
              << std::endl;
    BOOST_TEST(random_sample < 2);
}

max_stars_repo_name: ordinary-developer/education

max_issues_repo_name: ordinary-developer/education

max_forks_repo_name: ordinary-developer/education


text:
/** zookeeper_configuration_service.cc
    Jeremy Barnes, 26 September 2012
    Copyright (c) 2012 Datacratic Inc.  All rights reserved.

    Configuration service using Zookeeper.
*/

#include "zookeeper_configuration_service.h"
#include "soa/service/zookeeper.h"
#include "jml/utils/exc_assert.h"
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace ML;

namespace Datacratic {

std::string printZookeeperEventType(int type)
{

    if (type == ZOO_CREATED_EVENT)
        return "CREATED";
    if (type == ZOO_DELETED_EVENT)
        return "DELETED";
    if (type == ZOO_CHANGED_EVENT)
        return "CHANGED";
    if (type == ZOO_CHILD_EVENT)
        return "CHILD";
    if (type == ZOO_SESSION_EVENT)
        return "SESSION";
    if (type == ZOO_NOTWATCHING_EVENT)
        return "NOTWATCHING";
    return ML::format("UNKNOWN(%d)", type);
}

std::string printZookeeperState(int state)
{
    if (state == ZOO_EXPIRED_SESSION_STATE)
        return "ZOO_EXPIRED_SESSION_STATE";
    if (state == ZOO_AUTH_FAILED_STATE)
        return "ZOO_AUTH_FAILED_STATE";
    if (state == ZOO_CONNECTING_STATE)
        return "ZOO_CONNECTING_STATE";
    if (state == ZOO_ASSOCIATING_STATE)
        return "ZOO_ASSOCIATING_STATE";
    if (state == ZOO_CONNECTED_STATE)
        return "ZOO_CONNECTED_STATE";
    return ML::format("ZOO_UNKNOWN_STATE(%d)", state);
}

void
watcherFn(int type, std::string const & path, void * watcherCtx)
{
    typedef std::shared_ptr<ConfigurationService::Watch::Data> SharedPtr;
    std::unique_ptr<SharedPtr> data(reinterpret_cast<SharedPtr *>(watcherCtx));
#if 0
    cerr << "type = " << printZookeeperEventType(type)
         << " state = " << printZookeeperState(state)
         << " path = " << path << " context "
         << watcherCtx << " data " << data->get() << endl;
#endif

    ConfigurationService::ChangeType change;
    if (type == ZOO_CREATED_EVENT)
        change = ConfigurationService::CREATED;
    if (type == ZOO_DELETED_EVENT)
        change = ConfigurationService::DELETED;
    if (type == ZOO_CHANGED_EVENT)
        change = ConfigurationService::VALUE_CHANGED;
    if (type == ZOO_CHILD_EVENT)
        change = ConfigurationService::NEW_CHILD;

    auto & item = *data;
    if (item->watchReferences > 0) {
        item->onChange(path, change);
    }
}

ZookeeperConnection::Callback::Type
getWatcherFn(const ConfigurationService::Watch & watch)
{
    if (!watch)
        return nullptr;
    return watcherFn;
}

/*****************************************************************************/
/* ZOOKEEPER CONFIGURATION SERVICE                                           */
/*****************************************************************************/

ZookeeperConfigurationService::
ZookeeperConfigurationService()
{
}

ZookeeperConfigurationService::
ZookeeperConfigurationService(const std::string & host,
                              const std::string & prefix,
                              int timeout)
{
    init(host, prefix, timeout);
}

ZookeeperConfigurationService::
~ZookeeperConfigurationService()
{
}

void
ZookeeperConfigurationService::
init(const std::string & host,
     const std::string & prefix,
     int timeout)
{
    zoo.reset(new ZookeeperConnection());
    zoo->connect(host, timeout);
    this->prefix = prefix;

    if (!this->prefix.empty()
        && this->prefix[this->prefix.size() - 1] != '/')
        this->prefix = this->prefix + "/";

    if (!this->prefix.empty()
        && this->prefix[0] != '/')
        this->prefix = "/" + this->prefix;

    zoo->createPath(this->prefix);

#if 0
    for (unsigned i = 1;  i < prefix.size();  ++i) {
        if (prefix[i] == '/') {
            zoo->createNode(string(prefix, 0, i),
                            "",
                            false,
                            false,
                            false /* must succeed */);
        }
    }
#endif
}

Json::Value
ZookeeperConfigurationService::
getJson(const std::string & key, Watch watch)
{
    ExcAssert(zoo);
    auto val = zoo->readNode(prefix + key, getWatcherFn(watch),
                             watch.get());
    try {
        if (val == "")
            return Json::Value();
        return Json::parse(val);
    } catch (...) {
        cerr << "error parsing JSON entry '" << val << "'" << endl;
        throw;
    }
}

void
ZookeeperConfigurationService::
set(const std::string & key,
    const Json::Value & value)
{
    //cerr << "setting " << key << " to " << value << endl;
    // TODO: race condition
    if (!zoo->createNode(prefix + key, boost::trim_copy(value.toString()),
                         false, false,
                         false /* must succeed */,
                         true /* create path */).second)
        zoo->writeNode(prefix + key, boost::trim_copy(value.toString()));
    ExcAssert(zoo);
}

std::string
ZookeeperConfigurationService::
setUnique(const std::string & key,
          const Json::Value & value)
{
    //cerr << "setting unique " << key << " to " << value << endl;
    ExcAssert(zoo);
    return zoo->createNode(prefix + key, boost::trim_copy(value.toString()),
                           true /* ephemeral */,
                           false /* sequential */,
                           true /* mustSucceed */,
                           true /* create path */)
        .first;
}

std::vector<std::string>
ZookeeperConfigurationService::
getChildren(const std::string & key,
            Watch watch)
{
    //cerr << "getChildren " << key << " watch " << watch << endl;
    return zoo->getChildren(prefix + key,
                            false /* fail if not there */,
                            getWatcherFn(watch),
                            watch.get());
}

bool
ZookeeperConfigurationService::
forEachEntry(const OnEntry & onEntry,
                      const std::string & startPrefix) const
{
    //cerr << "forEachEntry: startPrefix = " << startPrefix << endl;

    ExcAssert(zoo);

    std::function<bool (const std::string &)> doNode
        = [&] (const std::string & currentPrefix)
        {
            //cerr << "doNode " << currentPrefix << endl;

            string r = zoo->readNode(prefix + currentPrefix);

            //cerr << "r = " << r << endl;

            if (r != "") {
                if (!onEntry(currentPrefix, Json::parse(r)))
                    return false;
            }

            vector<string> children = zoo->getChildren(prefix + currentPrefix,
                                                       false);

            for (auto child: children) {
                //cerr << "child = " << child << endl;
                string newPrefix = currentPrefix + "/" + child;
                if (currentPrefix.empty())
                    newPrefix = child;

                if (!doNode(newPrefix))
                    return false;
            }

            return true;
        };

    if (!zoo->nodeExists(prefix + startPrefix)) {

        return true;
    }

    return doNode(startPrefix);
}

void
ZookeeperConfigurationService::
removePath(const std::string & path)
{
    ExcAssert(zoo);
    zoo->removePath(prefix + path);
}

} // namespace Datacratic

ext: cc

max_stars_repo_name: sharpyfox/soa

max_issues_repo_name: sharpyfox/soa

max_forks_repo_name: sharpyfox/soa


text:
#include <boost/test/unit_test.hpp>

#include "st_tree.h"
#include "ut_common.h"

#include <algorithm>

BOOST_AUTO_TEST_SUITE(ut_raw)

BOOST_AUTO_TEST_CASE(default_ctor) {
    tree<int> t1;
    BOOST_CHECK(t1.empty());
    BOOST_CHECK_EQUAL(t1.size(), 0);
    BOOST_CHECK_EQUAL(t1.depth(), 0);
    BOOST_CHECK_THROW(t1.root(), st_tree::exception);
}

BOOST_AUTO_TEST_CASE(insert_root) {
    tree<int> t1;
    t1.insert(7);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.size(), 1);
    BOOST_CHECK_EQUAL(t1.depth(), 1);
    BOOST_CHECK_EQUAL(t1.root().is_root(), true);
    BOOST_CHECK_EQUAL(t1.root().data(), 7);
    BOOST_CHECK_THROW(t1.root().parent(), st_tree::exception);
}

BOOST_AUTO_TEST_CASE(insert_subnodes) {
    tree<int> t1;

    t1.insert(7);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.size(), 1);
    BOOST_CHECK_EQUAL(t1.depth(), 1);
    BOOST_CHECK_EQUAL(t1.root().size(), 0);

    t1.root().insert(8);
    BOOST_CHECK_EQUAL(t1.size(), 2);
    BOOST_CHECK_EQUAL(t1.depth(), 2);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 1);

    t1.root().insert(9);
    BOOST_CHECK_EQUAL(t1.size(), 3);
    BOOST_CHECK_EQUAL(t1.depth(), 2);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 2);

    BOOST_CHECK_EQUAL(t1.root().data(), 7);
    BOOST_CHECK_EQUAL(t1.root()[0].data(), 8);
    BOOST_CHECK_EQUAL(t1.root()[1].data(), 9);
}

BOOST_AUTO_TEST_CASE(emplace_subnodes) {
    struct str1 {
        int i1;
        std::string s1;
        str1() {
            i1 = 0;
            s1 = "";
        }
        str1(int i, const std::string s) {
            i1 = i;
            s1 = s;
        }
    };

    tree<str1> t1;

    t1.emplace(7, "7");
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.size(), 1);
    BOOST_CHECK_EQUAL(t1.depth(), 1);
    BOOST_CHECK_EQUAL(t1.root().size(), 0);

    t1.root().emplace_back(8, "8");
    BOOST_CHECK_EQUAL(t1.size(), 2);
    BOOST_CHECK_EQUAL(t1.depth(), 2);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 1);

    t1.root().emplace_insert(9, "9");
    BOOST_CHECK_EQUAL(t1.size(), 3);
    BOOST_CHECK_EQUAL(t1.depth(), 2);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 2);

    BOOST_CHECK_EQUAL(t1.root().data().i1, 7);
    BOOST_CHECK_EQUAL(t1.root()[0].data().i1, 8);
    BOOST_CHECK_EQUAL(t1.root()[1].data().i1, 9);
    BOOST_CHECK_EQUAL(t1.root().data().s1, "7");
    BOOST_CHECK_EQUAL(t1.root()[0].data().s1, "8");
    BOOST_CHECK_EQUAL(t1.root()[1].data().s1, "9");
}

BOOST_AUTO_TEST_CASE(clear) {
    tree<int> t1;

    t1.insert(7);
    t1.root().insert(8);
    t1.root().insert(9);
    BOOST_CHECK_EQUAL(t1.size(), 3);
    BOOST_CHECK_EQUAL(t1.depth(), 2);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 2);

    t1.clear();
    BOOST_CHECK_EQUAL(t1.size(), 0);
    BOOST_CHECK_EQUAL(t1.depth(), 0);
    BOOST_CHECK_EQUAL(t1.empty(), true);
    BOOST_CHECK_THROW(t1.root(), st_tree::exception);
}

BOOST_AUTO_TEST_CASE(reinsert) {
    tree<int> t1;

    t1.insert(7);
    t1.root().insert(8);
    t1.root().insert(9);
    BOOST_CHECK_EQUAL(t1.size(), 3);
    BOOST_CHECK_EQUAL(t1.depth(), 2);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 2);

    t1.insert(3);
    BOOST_CHECK_EQUAL(t1.size(), 1);
    BOOST_CHECK_EQUAL(t1.depth(), 1);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 0);
    BOOST_CHECK_EQUAL(t1.root().data(), 3);
}

BOOST_AUTO_TEST_CASE(erase) {
    tree<int> t1;

    t1.insert(7);
    t1.root().insert(8);

    t1.root().erase(t1.root().begin());
    BOOST_CHECK_EQUAL(t1.size(), 1);
    BOOST_CHECK_EQUAL(t1.depth(), 1);
    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t1.root().size(), 0);
    BOOST_CHECK_EQUAL(t1.root().data(), 7);
}

BOOST_AUTO_TEST_CASE(erase_noarg) {
    tree<int> t1;

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t1.root()[0].insert(7);
    t1.root()[0].insert(11);
    t1.root()[1].insert(13);
    t1.root()[1].insert(17);

    CHECK_TREE(t1, data(), "2 3 5 7 11 13 17");
    t1.root()[1].erase();
    CHECK_TREE(t1, data(), "2 3 7 11");

    t1.root()[0][1].erase();
    CHECK_TREE(t1, data(), "2 3 7");

    t1.root().erase();
    BOOST_CHECK_EQUAL(t1.empty(), true);
    CHECK_TREE(t1, data(), "");
}

BOOST_AUTO_TEST_CASE(bf_iterator_empty) {
    tree<int> t1;
    BOOST_CHECK_EQUAL(t1.bf_begin() == t1.bf_end(), true);
    BOOST_CHECK_EQUAL(t1.bf_begin() != t1.bf_end(), false);
}

BOOST_AUTO_TEST_CASE(bf_iterator) {
    tree<int> t1;
    CHECK_TREE(t1, data(), "");

    t1.insert(2);
    CHECK_TREE(t1, data(), "2");

    t1.root().insert(3);
    t1.root().insert(5);
    CHECK_TREE(t1, data(), "2 3 5");

    t1.root()[0].insert(7);
    t1.root()[1].insert(13);
    t1.root()[0].insert(11);
    t1.root()[1].insert(17);
    CHECK_TREE(t1, data(), "2 3 5 7 11 13 17");
    CHECK_TREE(t1.root(), data(), "2 3 5 7 11 13 17");
    tree<int> const& ct1 = t1;
    CHECK_TREE(ct1, data(), "2 3 5 7 11 13 17");
    CHECK_TREE(ct1.root(), data(), "2 3 5 7 11 13 17");
}

BOOST_AUTO_TEST_CASE(df_post_iterator_empty) {
    tree<int> t1;
    BOOST_CHECK_EQUAL(t1.df_post_begin() == t1.df_post_end(), true);
    BOOST_CHECK_EQUAL(t1.df_post_begin() != t1.df_post_end(), false);
}

BOOST_AUTO_TEST_CASE(df_post_iterator) {
    tree<int> t1;
    CHECK_TREE_DF_POST(t1, data(), "");

    t1.insert(2);
    CHECK_TREE_DF_POST(t1, data(), "2");

    t1.root().insert(3);
    t1.root().insert(5);
    CHECK_TREE_DF_POST(t1, data(), "3 5 2");

    t1.root()[0].insert(7);
    t1.root()[1].insert(13);
    t1.root()[0].insert(11);
    t1.root()[1].insert(17);
    CHECK_TREE_DF_POST(t1, data(), "7 11 3 13 17 5 2");
    CHECK_TREE_DF_POST(t1.root(), data(), "7 11 3 13 17 5 2");
    tree<int> const& ct1 = t1;
    CHECK_TREE_DF_POST(ct1, data(), "7 11 3 13 17 5 2");
    CHECK_TREE_DF_POST(ct1.root(), data(), "7 11 3 13 17 5 2");
}

BOOST_AUTO_TEST_CASE(df_pre_iterator_empty) {
    tree<int> t1;
    BOOST_CHECK_EQUAL(t1.df_pre_begin() == t1.df_pre_end(), true);
    BOOST_CHECK_EQUAL(t1.df_pre_begin() != t1.df_pre_end(), false);
}

BOOST_AUTO_TEST_CASE(df_pre_iterator) {
    tree<int> t1;
    CHECK_TREE_DF_PRE(t1, data(), "");

    t1.insert(2);
    CHECK_TREE_DF_PRE(t1, data(), "2");

    t1.root().insert(3);
    t1.root().insert(5);
    CHECK_TREE_DF_PRE(t1, data(), "2 3 5");

    t1.root()[0].insert(7);
    t1.root()[1].insert(13);
    t1.root()[0].insert(11);
    t1.root()[1].insert(17);
    CHECK_TREE_DF_PRE(t1, data(), "2 3 7 11 5 13 17");
    CHECK_TREE_DF_PRE(t1.root(), data(), "2 3 7 11 5 13 17");
    tree<int> const& ct1 = t1;
    CHECK_TREE_DF_PRE(ct1, data(), "2 3 7 11 5 13 17");
    CHECK_TREE_DF_PRE(ct1.root(), data(), "2 3 7 11 5 13 17");
}

BOOST_AUTO_TEST_CASE(node_ply) {
    tree<int> t1;

    t1.insert(2);
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t1, ply(), "0");

    t1.root().insert(3);
    t1.root().insert(5);
    CHECK_TREE(t1, data(), "2 3 5");
    CHECK_TREE(t1, ply(), "0 1 1");

    t1.root()[0].insert(7);
    t1.root()[0].insert(11);
    t1.root()[1].insert(13);
    t1.root()[1].insert(17);
    CHECK_TREE(t1, data(), "2 3 5 7 11 13 17");
    CHECK_TREE(t1, ply(), "0 1 1 2 2 2 2");

    t1.root().insert(77);
    CHECK_TREE(t1, data(), "2 3 5 77 7 11 13 17");
    CHECK_TREE(t1, ply(), "0 1 1 1 2 2 2 2");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2 5 77 13 17");
    CHECK_TREE(t1, ply(), "0 1 1 2 2");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2 77");
    CHECK_TREE(t1, ply(), "0 1");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t1, ply(), "0");
}

BOOST_AUTO_TEST_CASE(node_depth) {
    tree<int> t1;

    t1.insert(2);
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t1, depth(), "1");
    CHECK_TREE(t1, ply(), "0");

    t1.root().insert(3);
    t1.root().insert(5);
    CHECK_TREE(t1, data(), "2 3 5");
    CHECK_TREE(t1, depth(), "2 1 1");
    CHECK_TREE(t1, ply(), "0 1 1");

    t1.root()[0].insert(7);
    t1.root()[0].insert(11);
    t1.root()[1].insert(13);
    t1.root()[1].insert(17);
    CHECK_TREE(t1, data(), "2 3 5 7 11 13 17");
    CHECK_TREE(t1, depth(), "3 2 2 1 1 1 1");
    CHECK_TREE(t1, ply(), "0 1 1 2 2 2 2");

    t1.root().insert(77);
    CHECK_TREE(t1, data(), "2 3 5 77 7 11 13 17");
    CHECK_TREE(t1, depth(), "3 2 2 1 1 1 1 1");
    CHECK_TREE(t1, ply(), "0 1 1 1 2 2 2 2");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2 5 77 13 17");
    CHECK_TREE(t1, depth(), "3 2 1 1 1");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2 77");
    CHECK_TREE(t1, depth(), "2 1");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t1, depth(), "1");
}

BOOST_AUTO_TEST_CASE(node_subtree_size) {
    tree<int> t1;

    t1.insert(2);
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t1, subtree_size(), "1");

    t1.root().insert(3);
    t1.root().insert(5);
    CHECK_TREE(t1, data(), "2 3 5");
    CHECK_TREE(t1, subtree_size(), "3 1 1");

    t1.root()[0].insert(7);
    t1.root()[0].insert(11);
    t1.root()[1].insert(13);
    t1.root()[1].insert(17);
    CHECK_TREE(t1, data(), "2 3 5 7 11 13 17");
    CHECK_TREE(t1, subtree_size(), "7 3 3 1 1 1 1");

    t1.root().insert(77);
    CHECK_TREE(t1, data(), "2 3 5 77 7 11 13 17");
    CHECK_TREE(t1, subtree_size(), "8 3 3 1 1 1 1 1");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2 5 77 13 17");
    CHECK_TREE(t1, subtree_size(), "5 3 1 1 1");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2 77");
    CHECK_TREE(t1, subtree_size(), "2 1");

    t1.root().erase(t1.root().begin());
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t1, subtree_size(), "1");
}

BOOST_AUTO_TEST_CASE(node_parent) {
    tree<int> t1;
    t1.insert(2);
    BOOST_CHECK_THROW(t1.root().parent(), st_tree::exception);
    t1.root().insert(3);
    BOOST_CHECK_EQUAL(t1.root()[0].parent().data(), 2);
    const tree<int>& t2 = t1;
    BOOST_CHECK_EQUAL(t2.root()[0].parent().data(), 2);
}

BOOST_AUTO_TEST_CASE(node_tree) {
    tree<int> t1;
    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    tree<int>& t2 = t1.root().tree();
    BOOST_CHECK_EQUAL(t1 == t2, true);
    t2 = t1.root()[0].tree();
    BOOST_CHECK_EQUAL(t1 == t2, true);
    const tree<int>& t3 = t1;
    const tree<int>& t4 = t3.root().tree();
    BOOST_CHECK_EQUAL(t1 == t4, true);
}

BOOST_AUTO_TEST_CASE(erase_node) {
    tree<int> t1;
    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t1.root()[0].insert(7);
    t1.root()[1].insert(13);
    t1.root()[0].insert(11);
    t1.root()[1].insert(17);
    BOOST_CHECK_EQUAL(t1.size(), 7);
    BOOST_CHECK_EQUAL(t1.depth(), 3);

    t1.root().erase(t1.root().begin());
    BOOST_CHECK_EQUAL(t1.size(), 4);
    BOOST_CHECK_EQUAL(t1.depth(), 3);

    CHECK_TREE(t1, data(), "2 5 13 17");
    CHECK_TREE(t1, ply(), "0 1 2 2");
    CHECK_TREE(t1, subtree_size(), "4 3 1 1");
}

BOOST_AUTO_TEST_CASE(clear_node) {
    tree<int> t1;
    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t1.root()[0].insert(7);
    t1.root()[1].insert(13);
    t1.root()[0].insert(11);
    t1.root()[1].insert(17);
    BOOST_CHECK_EQUAL(t1.size(), 7);
    BOOST_CHECK_EQUAL(t1.depth(), 3);

    t1.root().clear();
    BOOST_CHECK_EQUAL(t1.size(), 1);
    BOOST_CHECK_EQUAL(t1.depth(), 1);

    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t1, ply(), "0");
    CHECK_TREE(t1, subtree_size(), "1");
}

BOOST_AUTO_TEST_CASE(node_op_equal) {
    tree<int> t1;
    t1.insert(2);
    t1.root().insert(3);

    tree<int> t2;
    t2.insert(5);
    t2.root().insert(7);
    t2.root().insert(11);

    BOOST_CHECK_EQUAL(t1.root().data(), 2);

    t1.root()[0] = t2.root();
    BOOST_CHECK_EQUAL(t1.size(), 4);
    BOOST_CHECK_EQUAL(t1.depth(), 3);

    CHECK_TREE(t1, data(), "2 5 7 11");
    CHECK_TREE(t1, ply(), "0 1 2 2");
    CHECK_TREE(t1, subtree_size(), "4 3 1 1");

    CHECK_TREE(t2, data(), "5 7 11");
    CHECK_TREE(t2, ply(), "0 1 1");
    CHECK_TREE(t2, subtree_size(), "3 1 1");
}

BOOST_AUTO_TEST_CASE(node_op_equal_root) {
    tree<int> t1;
    t1.insert(2);
    t1.root().insert(3);

    tree<int> t2;
    t2.insert(5);
    t2.root().insert(7);
    t2.root().insert(11);

    t1.root() = t2.root();
    BOOST_CHECK_EQUAL(t1.size(), 3);
    BOOST_CHECK_EQUAL(t1.depth(), 2);

    CHECK_TREE(t1, data(), "5 7 11");
    CHECK_TREE(t1, ply(), "0 1 1");
    CHECK_TREE(t1, subtree_size(), "3 1 1");

    CHECK_TREE(t2, data(), "5 7 11");
    CHECK_TREE(t2, ply(), "0 1 1");
    CHECK_TREE(t1, subtree_size(), "3 1 1");
}

BOOST_AUTO_TEST_CASE(node_op_equal_subtree) {
    tree<int> t1;

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t1.root()[0].insert(7);
    t1.root()[0].insert(11);
    t1.root()[1].insert(13);
    t1.root()[1].insert(17);

    BOOST_CHECK_THROW(t1.root()[0] = t1.root(), st_tree::exception);

    t1.root() = t1.root()[0];
    CHECK_TREE(t1, data(), "3 7 11");
    BOOST_CHECK_EQUAL(t1.size(), 3);
    BOOST_CHECK_EQUAL(t1.depth(), 2);

    t1.root()[1].insert(13);
    t1.root()[1].insert(17);
    t1.root()[1] = t1.root()[1][1];
    CHECK_TREE(t1, data(), "3 7 17");
}

BOOST_AUTO_TEST_CASE(node_swap) {
    tree<int> t1;
    tree<int> t2;

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t1.root()[0].insert(7);
    t1.root()[0].insert(11);

    t2.insert(102);
    t2.root().insert(103);
    t2.root().insert(105);
    t2.root()[0].insert(107);
    t2.root()[0].insert(111);

    // swap a leaf
    swap(t1.root()[0][0], t2.root()[0][0]);
    BOOST_CHECK_EQUAL(t1.size(), 5);
    BOOST_CHECK_EQUAL(t1.depth(), 3);
    CHECK_TREE(t1, data(), "2 3 5 107 11");
    CHECK_TREE(t1, ply(), "0 1 1 2 2");
    CHECK_TREE(t1, depth(), "3 2 1 1 1");
    CHECK_TREE(t1, subtree_size(), "5 3 1 1 1");

    BOOST_CHECK_EQUAL(t2.size(), 5);
    BOOST_CHECK_EQUAL(t2.depth(), 3);
    CHECK_TREE(t2, data(), "102 103 105 7 111");
    CHECK_TREE(t2, ply(), "0 1 1 2 2");
    CHECK_TREE(t2, depth(), "3 2 1 1 1");
    CHECK_TREE(t2, subtree_size(), "5 3 1 1 1");

    // put it back
    swap(t1.root()[0][0], t2.root()[0][0]);

    // swap an internal
    swap(t1.root()[0], t2.root()[0]);
    BOOST_CHECK_EQUAL(t1.size(), 5);
    BOOST_CHECK_EQUAL(t1.depth(), 3);
    CHECK_TREE(t1, data(), "2 103 5 107 111");
    CHECK_TREE(t1, ply(), "0 1 1 2 2");
    CHECK_TREE(t1, depth(), "3 2 1 1 1");
    CHECK_TREE(t1, subtree_size(), "5 3 1 1 1");
    BOOST_CHECK_EQUAL(t2.size(), 5);
    BOOST_CHECK_EQUAL(t2.depth(), 3);
    CHECK_TREE(t2, data(), "102 3 105 7 11");
    CHECK_TREE(t2, ply(), "0 1 1 2 2");
    CHECK_TREE(t2, depth(), "3 2 1 1 1");
    CHECK_TREE(t2, subtree_size(), "5 3 1 1 1");

    // put it back
    swap(t1.root()[0], t2.root()[0]);

    // swap the root
    swap(t1.root(), t2.root());
    BOOST_CHECK_EQUAL(t1.size(), 5);
    BOOST_CHECK_EQUAL(t1.depth(), 3);
    CHECK_TREE(t1, data(), "102 103 105 107 111");
    CHECK_TREE(t1, ply(), "0 1 1 2 2");
    CHECK_TREE(t1, depth(), "3 2 1 1 1");
    CHECK_TREE(t1, subtree_size(), "5 3 1 1 1");
    BOOST_CHECK_EQUAL(t2.size(), 5);
    BOOST_CHECK_EQUAL(t2.depth(), 3);
    CHECK_TREE(t2, data(), "2 3 5 7 11");
    CHECK_TREE(t2, ply(), "0 1 1 2 2");
    CHECK_TREE(t2, depth(), "3 2 1 1 1");
    CHECK_TREE(t2, subtree_size(), "5 3 1 1 1");

    // put it back
    swap(t1.root(), t2.root());

    // swap different plies
    swap(t1.root(), t2.root()[0]);
    BOOST_CHECK_EQUAL(t1.size(), 3);
    BOOST_CHECK_EQUAL(t1.depth(), 2);
    CHECK_TREE(t1, data(), "103 107 111");
    CHECK_TREE(t1, ply(), "0 1 1");
    CHECK_TREE(t1, depth(), "2 1 1");
    CHECK_TREE(t1, subtree_size(), "3 1 1");
    BOOST_CHECK_EQUAL(t2.size(), 7);
    BOOST_CHECK_EQUAL(t2.depth(), 4);
    CHECK_TREE(t2, data(), "102 2 105 3 5 7 11");
    CHECK_TREE(t2, ply(), "0 1 1 2 2 3 3");
    CHECK_TREE(t2, depth(), "4 3 1 2 1 1 1");
    CHECK_TREE(t2, subtree_size(), "7 5 1 3 1 1 1");

    // put them back
    swap(t1.root(), t2.root()[0]);

    // on same tree
    swap(t1.root()[0], t1.root()[1]);
    BOOST_CHECK_EQUAL(t1.size(), 5);
    BOOST_CHECK_EQUAL(t1.depth(), 3);
    CHECK_TREE(t1, data(), "2 5 3 7 11");
    CHECK_TREE(t1, ply(), "0 1 1 2 2");
    CHECK_TREE(t1, depth(), "3 1 2 1 1");
    CHECK_TREE(t1, subtree_size(), "5 1 3 1 1");

    // put them back
    swap(t1.root()[0], t1.root()[1]);

    // no-no
    BOOST_CHECK_THROW(swap(t1.root(), t1.root()[0]), st_tree::exception);
    BOOST_CHECK_THROW(swap(t1.root()[1], t1.root()), st_tree::exception);
}

BOOST_AUTO_TEST_CASE(graft) {
    tree<int> t1;
    tree<int> t2;

    // start with the node/tree overloadings
    // graft node -> tree
    t1.insert(2);
    t2.insert(1);
    t2.graft(t1.root());
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "2");
    CHECK_TREE(t2, depth(), "1");
    CHECK_TREE(t2, ply(), "0");
    CHECK_TREE(t2, subtree_size(), "1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.graft(t1.root());
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "2 3 5");
    CHECK_TREE(t2, depth(), "2 1 1");
    CHECK_TREE(t2, ply(), "0 1 1");
    CHECK_TREE(t2, subtree_size(), "3 1 1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.graft(t1.root()[1]);
    CHECK_TREE(t1, data(), "2 3");
    CHECK_TREE(t1, depth(), "2 1");
    CHECK_TREE(t1, ply(), "0 1");
    CHECK_TREE(t1, subtree_size(), "2 1");
    CHECK_TREE(t2, data(), "5");
    CHECK_TREE(t2, depth(), "1");
    CHECK_TREE(t2, ply(), "0");
    CHECK_TREE(t2, subtree_size(), "1");

    // graft tree -> tree (empty)
    t1.clear();
    t2.graft(t1);
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "");

    // graft tree -> tree (non-empty)
    t1.insert(2);
    t2.graft(t1);
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "2");

    // graft tree -> node (empty)
    t2.root().graft(t1);
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "2");

    // graft tree -> node (non-empty)
    t1.insert(2);
    t2.insert(1);
    t2.root().graft(t1);
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "1 2");

    // node --> node
    t1.insert(2);
    t2.insert(1);
    t2.root().graft(t1.root());
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "1 2");
    CHECK_TREE(t2, depth(), "2 1");
    CHECK_TREE(t2, ply(), "0 1");
    CHECK_TREE(t2, subtree_size(), "2 1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.insert(1);
    t2.root().graft(t1.root());
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "1 2 3 5");
    CHECK_TREE(t2, depth(), "3 2 1 1");
    CHECK_TREE(t2, ply(), "0 1 2 2");
    CHECK_TREE(t2, subtree_size(), "4 3 1 1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.insert(1);
    t2.root().graft(t1.root()[1]);
    CHECK_TREE(t1, data(), "2 3");
    CHECK_TREE(t1, depth(), "2 1");
    CHECK_TREE(t1, ply(), "0 1");
    CHECK_TREE(t1, subtree_size(), "2 1");
    CHECK_TREE(t2, data(), "1 5");
    CHECK_TREE(t2, depth(), "2 1");
    CHECK_TREE(t2, ply(), "0 1");
    CHECK_TREE(t2, subtree_size(), "2 1");
}

BOOST_AUTO_TEST_CASE(insert_node) {
    tree<int> t1;
    tree<int> t2;

    // start with the node/tree overloadings
    // insert node -> tree
    t1.insert(2);
    t2.insert(1);
    t2.insert(t1.root());
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t2, data(), "2");
    CHECK_TREE(t2, depth(), "1");
    CHECK_TREE(t2, ply(), "0");
    CHECK_TREE(t2, subtree_size(), "1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.insert(t1.root());
    CHECK_TREE(t1, data(), "2 3 5");
    CHECK_TREE(t2, data(), "2 3 5");
    CHECK_TREE(t2, depth(), "2 1 1");
    CHECK_TREE(t2, ply(), "0 1 1");
    CHECK_TREE(t2, subtree_size(), "3 1 1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.insert(t1.root()[1]);
    CHECK_TREE(t1, data(), "2 3 5");
    CHECK_TREE(t1, depth(), "2 1 1");
    CHECK_TREE(t1, ply(), "0 1 1");
    CHECK_TREE(t1, subtree_size(), "3 1 1");
    CHECK_TREE(t2, data(), "5");
    CHECK_TREE(t2, depth(), "1");
    CHECK_TREE(t2, ply(), "0");
    CHECK_TREE(t2, subtree_size(), "1");

    // insert tree -> tree (empty)
    t1.clear();
    t2.insert(t1);
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "");

    // insert tree -> tree (non-empty)
    t1.insert(2);
    t2.insert(t1);
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t2, data(), "2");

    // insert tree -> node (empty)
    t1.clear();
    t2.root().insert(t1);
    CHECK_TREE(t1, data(), "");
    CHECK_TREE(t2, data(), "2");

    // insert tree -> node (non-empty)
    t1.insert(2);
    t2.insert(1);
    t2.root().insert(t1);
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t2, data(), "1 2");

    // node --> node
    t1.insert(2);
    t2.insert(1);
    t2.root().insert(t1.root());
    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t2, data(), "1 2");
    CHECK_TREE(t2, depth(), "2 1");
    CHECK_TREE(t2, ply(), "0 1");
    CHECK_TREE(t2, subtree_size(), "2 1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.insert(1);
    t2.root().insert(t1.root());
    CHECK_TREE(t1, data(), "2 3 5");
    CHECK_TREE(t2, data(), "1 2 3 5");
    CHECK_TREE(t2, depth(), "3 2 1 1");
    CHECK_TREE(t2, ply(), "0 1 2 2");
    CHECK_TREE(t2, subtree_size(), "4 3 1 1");

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t2.insert(1);
    t2.root().insert(t1.root()[1]);
    CHECK_TREE(t1, data(), "2 3 5");
    CHECK_TREE(t1, depth(), "2 1 1");
    CHECK_TREE(t1, ply(), "0 1 1");
    CHECK_TREE(t1, subtree_size(), "3 1 1");
    CHECK_TREE(t2, data(), "1 5");
    CHECK_TREE(t2, depth(), "2 1");
    CHECK_TREE(t2, ply(), "0 1");
    CHECK_TREE(t2, subtree_size(), "2 1");
}

BOOST_AUTO_TEST_CASE(node_op_equality) {
    tree<int> t1;

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t1.root()[0].insert(7);
    t1.root()[1].insert(13);
    t1.root()[0].insert(11);
    t1.root()[1].insert(17);

    tree<int> t2;

    t2.insert(2);
    t2.root().insert(3);
    t2.root().insert(5);
    t2.root()[0].insert(7);
    t2.root()[1].insert(13);
    t2.root()[0].insert(11);
    t2.root()[1].insert(17);

    BOOST_CHECK_EQUAL(t1.root() == t1.root(), true);
    BOOST_CHECK_EQUAL(t1.root()[0] == t1.root()[0], true);
    BOOST_CHECK_EQUAL(t1.root()[0][0] == t1.root()[0][0], true);

    BOOST_CHECK_EQUAL(t1.root() == t2.root(), true);
    BOOST_CHECK_EQUAL(t1.root()[0] == t2.root()[0], true);
    BOOST_CHECK_EQUAL(t1.root()[0][0] == t2.root()[0][0], true);

    BOOST_CHECK_EQUAL(t1.root()[0] == t2.root()[1], false);
    BOOST_CHECK_EQUAL(t1.root()[0][0] == t2.root()[0][1], false);
}

BOOST_AUTO_TEST_CASE(node_op_lessthan) {
    tree<int> t1;
    tree<int> t2;

    t1.insert(2);
    t2.insert(2);

    BOOST_CHECK_EQUAL(t1.root() < t2.root(), false);

    t2.root().data() = 3;
    BOOST_CHECK_EQUAL(t1.root() < t2.root(), true);

    t2.root().data() = 2;
    t1.root().insert(3);
    t1.root().insert(5);
    t2.root().insert(3);
    t2.root().insert(5);

    BOOST_CHECK_EQUAL(t1.root() < t2.root(), false);

    t2.root()[1].data() = 7;
    BOOST_CHECK_EQUAL(t1.root() < t2.root(), true);
}

BOOST_AUTO_TEST_CASE(node_derived_comp_ops) {
    tree<int> t1;
    tree<int> t2;

    t1.insert(2);
    t2.insert(2);
    BOOST_CHECK_EQUAL(t1.root() != t2.root(), false);
    BOOST_CHECK_EQUAL(t2.root() != t1.root(), false);
    BOOST_CHECK_EQUAL(t1.root() >  t2.root(), false);
    BOOST_CHECK_EQUAL(t2.root() >  t1.root(), false);
    BOOST_CHECK_EQUAL(t1.root() <= t2.root(), true);
    BOOST_CHECK_EQUAL(t2.root() <= t1.root(), true);
    BOOST_CHECK_EQUAL(t1.root() >= t2.root(), true);
    BOOST_CHECK_EQUAL(t2.root() >= t1.root(), true);

    t2.root().data() = 3;
    BOOST_CHECK_EQUAL(t1.root() != t2.root(), true);
    BOOST_CHECK_EQUAL(t2.root() != t1.root(), true);
    BOOST_CHECK_EQUAL(t1.root() >  t2.root(), false);
    BOOST_CHECK_EQUAL(t2.root() >  t1.root(), true);
    BOOST_CHECK_EQUAL(t1.root() <= t2.root(), true);
    BOOST_CHECK_EQUAL(t2.root() <= t1.root(), false);
    BOOST_CHECK_EQUAL(t1.root() >= t2.root(), false);
    BOOST_CHECK_EQUAL(t2.root() >= t1.root(), true);
}

BOOST_AUTO_TEST_CASE(tree_op_equality) {
    tree<int> t1;
    tree<int> t2;

    BOOST_CHECK_EQUAL(t1 == t2, true);

    t2.insert(2);
    BOOST_CHECK_EQUAL(t1 == t2, false);

    t1.insert(2);
    BOOST_CHECK_EQUAL(t1 == t2, true);

    t2.root().data() = 3;
    BOOST_CHECK_EQUAL(t1 == t2, false);
}

BOOST_AUTO_TEST_CASE(tree_op_lessthan) {
    tree<int> t1;
    tree<int> t2;
    BOOST_CHECK_EQUAL(t1 < t2, false);

    t2.insert(2);
    BOOST_CHECK_EQUAL(t1 < t2, true);
    BOOST_CHECK_EQUAL(t2 < t1, false);

    t1.insert(2);
    BOOST_CHECK_EQUAL(t1 < t2, false);

    t2.root().data() = 3;
    BOOST_CHECK_EQUAL(t1 < t2, true);
    BOOST_CHECK_EQUAL(t2 < t1, false);

    BOOST_CHECK_EQUAL(t1 < t1, false);
}

BOOST_AUTO_TEST_CASE(tree_derived_comp_ops) {
    tree<int> t1;
    tree<int> t2;

    t1.insert(2);
    t2.insert(2);
    BOOST_CHECK_EQUAL(t1 != t2, false);
    BOOST_CHECK_EQUAL(t2 != t1, false);
    BOOST_CHECK_EQUAL(t1 >  t2, false);
    BOOST_CHECK_EQUAL(t2 >  t1, false);
    BOOST_CHECK_EQUAL(t1 <= t2, true);
    BOOST_CHECK_EQUAL(t2 <= t1, true);
    BOOST_CHECK_EQUAL(t1 >= t2, true);
    BOOST_CHECK_EQUAL(t2 >= t1, true);

    t2.root().data() = 3;
    BOOST_CHECK_EQUAL(t1 != t2, true);
    BOOST_CHECK_EQUAL(t2 != t1, true);
    BOOST_CHECK_EQUAL(t1 >  t2, false);
    BOOST_CHECK_EQUAL(t2 >  t1, true);
    BOOST_CHECK_EQUAL(t1 <= t2, true);
    BOOST_CHECK_EQUAL(t2 <= t1, false);
    BOOST_CHECK_EQUAL(t1 >= t2, false);
    BOOST_CHECK_EQUAL(t2 >= t1, true);
}

BOOST_AUTO_TEST_CASE(tree_op_equal_lhs_n_rhs_e) {
    tree<int> t1;
    t1.insert(2);
    t1.root().insert(3);

    tree<int> t2;

    t1 = t2;

    BOOST_CHECK_EQUAL(t1.empty(), true);
    BOOST_CHECK_EQUAL(t2.empty(), true);

    CHECK_TREE(t1, data(), "");
}

BOOST_AUTO_TEST_CASE(tree_op_equal_lhs_e_rhs_n) {
    tree<int> t1;

    tree<int> t2;
    t2.insert(2);
    t2.root().insert(3);

    t1 = t2;

    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t2.empty(), false);

    CHECK_TREE(t1, data(), "2 3");
    CHECK_TREE(t1, ply(), "0 1");
    CHECK_TREE(t1, subtree_size(), "2 1");
}

BOOST_AUTO_TEST_CASE(tree_op_equal_lhs_n_rhs_n) {
    tree<int> t1;
    t1.insert(31);
    t1.root().insert(41);

    tree<int> t2;
    t2.insert(2);
    t2.root().insert(3);

    t1 = t2;

    BOOST_CHECK_EQUAL(t1.empty(), false);
    BOOST_CHECK_EQUAL(t2.empty(), false);

    CHECK_TREE(t1, data(), "2 3");
    CHECK_TREE(t1, ply(), "0 1");
    CHECK_TREE(t1, subtree_size(), "2 1");
}

BOOST_AUTO_TEST_CASE(tree_swap) {
    tree<int> t1;
    tree<int> t2;

    t1.insert(2);
    t2.insert(3);

    // method version
    t1.swap(t2);

    CHECK_TREE(t1, data(), "3");
    CHECK_TREE(t2, data(), "2");

    // function version
    swap(t1, t2);

    CHECK_TREE(t1, data(), "2");
    CHECK_TREE(t2, data(), "3");
}

BOOST_AUTO_TEST_CASE(push_pop_back) {
    tree<int> t1;
    t1.insert(2);
    t1.root().push_back(3);
    BOOST_CHECK_EQUAL(t1.root().back().data(), 3);
    BOOST_CHECK_EQUAL(t1.root().front().data(), 3);
    t1.root().push_back(5);
    BOOST_CHECK_EQUAL(t1.root().back().data(), 5);
    BOOST_CHECK_EQUAL(t1.root().front().data(), 3);
    t1.root().push_back(7);
    BOOST_CHECK_EQUAL(t1.root().back().data(), 7);
    BOOST_CHECK_EQUAL(t1.root().front().data(), 3);
    t1.root().pop_back();
    BOOST_CHECK_EQUAL(t1.root().back().data(), 5);
    BOOST_CHECK_EQUAL(t1.root().front().data(), 3);
    t1.root().pop_back();
    BOOST_CHECK_EQUAL(t1.root().back().data(), 3);
    BOOST_CHECK_EQUAL(t1.root().front().data(), 3);
}

BOOST_AUTO_TEST_CASE(random_access) {
    tree<int> t1;
    typedef tree<int>::node_type::iterator iterator;

    t1.insert(2);
    t1.root().insert(3);
    t1.root().insert(5);
    t1.root().insert(7);

    CHECK_TREE(t1, data(), "2 3 5 7");

    iterator j = t1.root().begin();
    BOOST_CHECK_EQUAL(j->data(), 3);
    j++;
    BOOST_CHECK_EQUAL(j->data(), 5);
    j--;
    BOOST_CHECK_EQUAL(j->data(), 3);

    j += 2;
    BOOST_CHECK_EQUAL(j->data(), 7);
    j -= 1;
    BOOST_CHECK_EQUAL(j->data(), 5);

    BOOST_CHECK_EQUAL((j+1)->data(), 7);
    BOOST_CHECK_EQUAL((j-1)->data(), 3);

    BOOST_CHECK_EQUAL((1+j)->data(), 7);
    BOOST_CHECK_EQUAL((-1+j)->data(), 3);

    BOOST_CHECK_EQUAL((j+1)-(j-1), 2);

    BOOST_CHECK_EQUAL(j[1].data(), 7);
    BOOST_CHECK_EQUAL(j[-1].data(), 3);

    BOOST_CHECK_EQUAL(j < j, false);
    BOOST_CHECK_EQUAL(j < j+1, true);

    BOOST_CHECK_EQUAL(j <= j, true);
    BOOST_CHECK_EQUAL(j <= j+1, true);

    BOOST_CHECK_EQUAL(j > j, false);
    BOOST_CHECK_EQUAL(j > j-1, true);

    BOOST_CHECK_EQUAL(j >= j, true);
    BOOST_CHECK_EQUAL(j >= j-1, true);
}

BOOST_AUTO_TEST_CASE(sort_children) {
    tree<int> t1;
    typedef tree<int>::node_type::iterator iterator;

    t1.insert(2);
    t1.root().push_back(3);
    t1.root().push_back(7);
    t1.root().push_back(5);
    t1.root().push_back(13);
    t1.root().push_back(11);

    CHECK_TREE(t1, data(), "2 3 7 5 13 11");

    std::sort(t1.root().begin(), t1.root().end());

    CHECK_TREE(t1, data(), "2 3 5 7 11 13");
}

BOOST_AUTO_TEST_SUITE_END()


text:
/**
 * #brief Assimpを使ったモデルローダ
 */

#include "VK/Model.h"

#include <assimp/Importer.hpp>
#include <assimp/cimport.h>
#include <assimp/scene.h>

#include <algorithm>
#include <boost/assert.hpp>
#include <iostream>

#include "VK/Common.h"
#include "VK/Device.h"

static constexpr uint32_t defaultFlags =
    aiProcess_FlipWindingOrder | aiProcess_Triangulate |
    aiProcess_PreTransformVertices | aiProcess_CalcTangentSpace |
    aiProcess_GenSmoothNormals;

bool Model::LoadFromFile(const Device &device, const std::string &filepath,
                         VkQueue copyQueue, const VertexLayout &vertexLayout,
                         const ModelCreateInfo &modelCreateInfo) {
  Assimp::Importer importer;
  const aiScene *scene = importer.ReadFile(filepath, defaultFlags);
  if (scene == nullptr) {
    std::cerr << importer.GetErrorString() << std::endl;
    BOOST_ASSERT_MSG(scene != nullptr, "Filed to load model!");
    return false;
  }

  const glm::vec3 center = modelCreateInfo.center;
  const glm::vec3 scale = modelCreateInfo.scale;
  const glm::vec2 uvscale = modelCreateInfo.uvscale;

  meshes.clear();
  meshes.resize(scene->mNumMeshes);

  std::vector<float> vertexBuffer;
  vertexCount = 0;
  std::vector<uint32_t> indexBuffer;
  indexCount = 0;
  for (uint32_t i = 0; i < scene->mNumMeshes; i++) {
    const aiMesh *mesh = scene->mMeshes[i];

    meshes[i] = {};
    meshes[i].vertexBase = vertexCount;
    meshes[i].indexBase = indexCount;

    vertexCount += mesh->mNumVertices;

    aiColor3D color(0.0f, 0.0f, 0.0f);
    if (modelCreateInfo.color.has_value()) {
      color.r = modelCreateInfo.color->r;
      color.g = modelCreateInfo.color->g;
      color.b = modelCreateInfo.color->b;
    } else {
      scene->mMaterials[mesh->mMaterialIndex]->Get(AI_MATKEY_COLOR_DIFFUSE,
                                                   color);
    }
    const aiVector3D zero3D(0.0f, 0.0f, 0.0f);
    for (uint32_t j = 0; j < mesh->mNumVertices; j++) {

      const aiVector3D &pos = mesh->mVertices[j];
      const aiVector3D &norm = mesh->mNormals[j];
      const aiVector3D &uv =
          (mesh->HasTextureCoords(0)) ? mesh->mTextureCoords[0][j] : zero3D;
      const aiVector3D &tang =
          (mesh->HasTangentsAndBitangents()) ? mesh->mTangents[j] : zero3D;
      const aiVector3D &bitang =
          (mesh->HasTangentsAndBitangents()) ? mesh->mBitangents[j] : zero3D;

      for (const auto &component : vertexLayout.components) {
        switch (component) {
        case VertexLayoutComponent::Position:
          vertexBuffer.emplace_back(pos.x * scale.x + center.x);
          vertexBuffer.emplace_back(pos.y * scale.y + center.y);
          vertexBuffer.emplace_back(pos.z * scale.z + center.z);
          break;
        case VertexLayoutComponent::Normal:
          vertexBuffer.emplace_back(norm.x);
          vertexBuffer.emplace_back(norm.y);
          vertexBuffer.emplace_back(norm.z);
          break;
        case VertexLayoutComponent::UV:
          vertexBuffer.emplace_back(uv.x * uvscale.s);
          vertexBuffer.emplace_back(uv.y * uvscale.t);
          break;
        case VertexLayoutComponent::Color:
          vertexBuffer.emplace_back(color.r);
          vertexBuffer.emplace_back(color.g);
          vertexBuffer.emplace_back(color.b);
          break;
        case VertexLayoutComponent::Tangent:
          vertexBuffer.emplace_back(tang.x);
          vertexBuffer.emplace_back(tang.y);
          vertexBuffer.emplace_back(tang.z);
          break;
        case VertexLayoutComponent::Bitangent:
          vertexBuffer.emplace_back(bitang.x);
          vertexBuffer.emplace_back(bitang.y);
          vertexBuffer.emplace_back(bitang.z);
          break;
        case VertexLayoutComponent::DummyFloat:
          vertexBuffer.emplace_back(0.0f);
          break;
        case VertexLayoutComponent::DummyVec4:
          vertexBuffer.emplace_back(0.0f);
          vertexBuffer.emplace_back(0.0f);
          vertexBuffer.emplace_back(0.0f);
          vertexBuffer.emplace_back(0.0f);
          break;
        }
      }
      dim.min.x = std::min(pos.x, dim.min.x);
      dim.min.y = std::min(pos.y, dim.min.y);
      dim.min.z = std::min(pos.z, dim.min.z);

      dim.max.x = std::max(pos.x, dim.max.x);
      dim.max.y = std::max(pos.y, dim.max.y);
      dim.max.z = std::max(pos.z, dim.max.z);
    }
    meshes[i].vertexCount = mesh->mNumVertices;

    const auto indexBase = static_cast<uint32_t>(indexBuffer.size());
    for (uint32_t j = 0; j < mesh->mNumFaces; j++) {
      const aiFace &face = mesh->mFaces[j];
      if (face.mNumIndices != 3) {
        continue;
      }
      indexBuffer.emplace_back(indexBase + face.mIndices[0]);
      indexBuffer.emplace_back(indexBase + face.mIndices[1]);
      indexBuffer.emplace_back(indexBase + face.mIndices[2]);
      meshes[i].indexCount += 3;
      indexCount += 3;
    }
  }

  const auto vtxBufSize =
      static_cast<uint32_t>(vertexBuffer.size()) * sizeof(float);
  const auto idxBufSize =
      static_cast<uint32_t>(indexBuffer.size()) * sizeof(uint32_t);

  // ステージングバッファを使用して、頂点バッファとインデックスバッファをデバイスのローカルメモリに移動します。
  Buffer vertexStaging;
  VK_CHECK_RESULT(vertexStaging.Create(device, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
                                       VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
                                           VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
                                       vtxBufSize, vertexBuffer.data()));
  Buffer indexStaging;
  VK_CHECK_RESULT(indexStaging.Create(device, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
                                      VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
                                          VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
                                      idxBufSize, indexBuffer.data()));

  // デバイスのローカルターゲットバッファを生成します。
  VK_CHECK_RESULT(vertices.Create(
      device,
      VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
      VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | modelCreateInfo.memoryPropertyFlags,
      vtxBufSize));
  VK_CHECK_RESULT(indices.Create(
      device,
      VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT,
      VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT | modelCreateInfo.memoryPropertyFlags,
      idxBufSize));

  // ステージングバッファからコピーします。
  VkCommandBuffer copyCmd = device.CreateCommandBuffer();
  VkBufferCopy copyRegion{};

  copyRegion.size = vtxBufSize;
  vkCmdCopyBuffer(copyCmd, vertexStaging.buffer, vertices.buffer, 1,
                  &copyRegion);

  copyRegion.size = idxBufSize;
  vkCmdCopyBuffer(copyCmd, indexStaging.buffer, indices.buffer, 1, &copyRegion);

  device.FlushCommandBuffer(copyCmd, copyQueue);

  // ステージングリソースを解放します。
  indexStaging.Destroy(device);
  vertexStaging.Destroy(device);

  return true;
}

void Model::Destroy(const Device &device) const {
  indices.Destroy(device);
  vertices.Destroy(device);
}

max_stars_repo_name: mnrn/ReVK

max_issues_repo_name: mnrn/ReVK

max_forks_repo_name: mnrn/ReVK


text:
// Boost.Range library
//
//  Copyright Neil Groves 2009. 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)
//
//
// For more information, see http://www.boost.org/libs/range/
//
//[indirected_example
#include <boost/range/adaptor/indirected.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/shared_ptr.hpp>
#include <iterator>
#include <iostream>
#include <vector>

//<-
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>

#include <boost/range/algorithm_ext/push_back.hpp>

namespace
{
void indirected_example_test()
//->
//=int main(int argc, const char* argv[])
{
    using namespace boost::adaptors;

    std::vector<boost::shared_ptr<int> > input;

    for (int i = 0; i < 10; ++i)
        input.push_back(boost::shared_ptr<int>(new int(i)));

    boost::copy(
        input | indirected,
        std::ostream_iterator<int>(std::cout, ","));

//=    return 0;
//=}
//]
    std::vector<int> reference;
    for (int i = 0; i < 10; ++i)
        reference.push_back(i);

    std::vector<int> test;
    boost::push_back(test, input | indirected);

    BOOST_CHECK_EQUAL_COLLECTIONS( reference.begin(), reference.end(),
        test.begin(), test.end() );
}
}

boost::unit_test::test_suite*
init_unit_test_suite(int argc, char* argv[])
{
    boost::unit_test::test_suite* test
        = BOOST_TEST_SUITE( "RangeTestSuite.adaptor.indirected_example" );

    test->add( BOOST_TEST_CASE( &indirected_example_test ) );

    return test;
}


text:
#ifndef __VSIM_PHYSICS_MODEL_HPP__
#define __VSIM_PHYSICS_MODEL_HPP__

#include <string>
#include <vector>
#include <memory>
#include <map>
#include <Eigen/Core>

#include <vsim/env/scene_fwd.hpp>
#include <vsim/env/pose.hpp>
#include <vsim/env/base_element.hpp>

namespace vsim {

// a physics model contains bodies and their constraints

struct PhysicsModel: public BaseElement {
public:

    PhysicsModel() = default ;

    std::vector<RigidBodyPtr> bodies_ ;
    std::vector<RigidBodyConstraintPtr> constraints_ ;
};

}
#endif

ext: hpp

max_stars_repo_name: malasiot/vsim

max_issues_repo_name: malasiot/vsim

max_forks_repo_name: malasiot/vsim


text:
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <rapidcheck/gtest.h>

#include <crest/geometry/indexed_mesh.hpp>
#include <crest/geometry/refinement.hpp>
#include <crest/basis/lagrange_basis2d.hpp>
#include <crest/basis/homogenized_basis.hpp>
#include <crest/basis/schur_corrector_solver.hpp>
#include <crest/basis/homogenized_basis_dense_fallback.hpp>
#include <crest/basis/amg_corrector_solver.hpp>

#include <crest/util/algorithms.hpp>

#include <util/eigen_matchers.hpp>
#include <util/test_generators.hpp>

#include <Eigen/Sparse>
#include <Eigen/Dense>

using ::testing::ElementsAreArray;
using ::testing::Pointwise;
using ::testing::Eq;
using ::testing::DoubleEq;
using ::testing::Lt;
using ::testing::Each;

using crest::IndexedMesh;
using crest::LagrangeBasis2d;

typedef IndexedMesh<double, int>::Vertex Vertex;
typedef IndexedMesh<double, int>::Element Element;

constexpr static double TOL = 1e-14;

TEST(homogenized_basis_test, correctors_are_in_interpolator_kernel_for_threshold_fine_mesh)
{
    // Recall that by definition, I_H c = 0, for any corrector with weights c.
    const std::vector<Vertex> coarse_vertices {
            Vertex(0.0, 0.0),
            Vertex(1.0, 0.0),
            Vertex(1.0, 1.0),
            Vertex(0.0, 1.0)
    };

    const std::vector<Element> coarse_elements {
            Element({3, 0, 1}),
            Element({1, 2, 3})
    };

    const auto initial_mesh = IndexedMesh<double, int>(coarse_vertices, coarse_elements);

    const auto mesh = crest::threshold(initial_mesh, 0.5, { crest::ReentrantCorner<double, int>(0, 2.35)});
    const auto correctors = crest::SparseLuCorrectorSolver<double>().compute_correctors(mesh, 4);

    ASSERT_THAT(correctors.rows(), Eq(mesh.coarse_mesh().num_vertices()));
    ASSERT_THAT(correctors.cols(), Eq(mesh.fine_mesh().num_vertices()));

    const auto coarse_interior = mesh.coarse_mesh().compute_interior_vertices();
    const auto fine_dof = crest::algo::integer_range<int>(0, mesh.fine_mesh().num_vertices());

    const auto I_H = crest::quasi_interpolator(mesh);
    // We need to test with the coarse interior, because the matrix returned by quasi_interpolator
    // does not impose that I_H x = 0 on the boundary.
    const auto I_H_interior = sparse_submatrix(I_H, coarse_interior, fine_dof);

    // Recall that each row of 'basis' corresponds to weights in the fine space, so by transposing it and
    // left-multiplying by I_H, we effectively compute I_H x_i for each basis function i.
    // Since x_i is in the kernel of I_H, we expect the result to be zero.
    const Eigen::SparseMatrix<double> Z = I_H_interior * correctors.transpose();
    const Eigen::MatrixXd Z_dense = Z;

    EXPECT_TRUE(Z_dense.isZero(TOL));
}

TEST(construct_saddle_point_problem_test, blockwise_correct)
{
    MatrixX<double> A(5, 5);
    A.setZero();
    A(0, 0) = 1.0;
    A(1, 1) = 2.0;
    A(2, 2) = 3.0;
    A(3, 3) = 4.0;
    A(4, 4) = 5.0;

    MatrixX<double> I_H(3, 5);
    I_H.setZero();
    I_H(0, 0) = 6.0;
    I_H(1, 1) = 7.0;
    I_H(2, 2) = 8.0;

    const Eigen::SparseMatrix<double> A_sparse = A.sparseView();
    const Eigen::SparseMatrix<double> I_H_sparse = I_H.sparseView();

    const MatrixX<double> C = crest::detail::construct_saddle_point_problem(A_sparse, I_H_sparse);

    ASSERT_THAT(C.rows(), 8);
    ASSERT_THAT(C.cols(), 8);

    const MatrixX<double> bottomRightCorner = C.bottomRightCorner(3, 3);
    const auto bottomRightCornerElements = std::vector<double>(bottomRightCorner.data(), bottomRightCorner.data() + 9);

    EXPECT_TRUE(C.topLeftCorner(5, 5).isApprox(A));
    EXPECT_TRUE(C.bottomLeftCorner(3, 5).isApprox(I_H));
    EXPECT_TRUE(C.topRightCorner(5, 3).isApprox(I_H.transpose()));
    EXPECT_THAT(bottomRightCornerElements, Each(DoubleEq(0.0)));
}

template <typename CorrectorSolver>
void check_correctors_are_in_interpolator_kernel()
{
    const auto oversampling = *rc::gen::arbitrary<unsigned int>();
    const auto coarse_mesh = *crest::gen::arbitrary_unit_square_mesh(4);

    // Make sure the fine mesh does not coincide with the coarse mesh
    const auto fine_mesh = *rc::gen::suchThat(crest::gen::arbitrary_refinement(coarse_mesh, 1, 4),
                                              [coarse_mesh] (auto mesh)
                                              {
                                                  return mesh.num_elements() != coarse_mesh.num_elements();
                                              });

    const auto biscale = crest::BiscaleMesh<double, int>(coarse_mesh, fine_mesh);

    const auto correctors = CorrectorSolver().compute_correctors(biscale, oversampling);

    ASSERT_THAT(correctors.rows(), Eq(coarse_mesh.num_vertices()));
    ASSERT_THAT(correctors.cols(), Eq(fine_mesh.num_vertices()));

    const auto coarse_interior = coarse_mesh.compute_interior_vertices();
    const auto fine_dof = crest::algo::integer_range<int>(0, fine_mesh.num_vertices());

    const auto I_H = crest::quasi_interpolator(biscale);

    // We need to test with the coarse interior, because the matrix returned by quasi_interpolator
    // does not impose that I_H x = 0 on the boundary.
    const auto I_H_interior = sparse_submatrix(I_H, coarse_interior, fine_dof);

    // Recall that each row of 'basis' corresponds to weights in the fine space, so by transposing it and
    // left-multiplying by I_H, we effectively compute I_H x_i for each basis function i.
    // Since x_i is in the kernel of I_H, we expect the result to be zero.
    const Eigen::SparseMatrix<double> Z = I_H_interior * correctors.transpose();
    const Eigen::MatrixXd Z_dense = Z;

    RC_ASSERT(Z_dense.isZero(TOL));
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_in_interpolator_kernel_sparselu, ())
{
    check_correctors_are_in_interpolator_kernel<crest::SparseLuCorrectorSolver<double>>();
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_in_interpolator_kernel_schur, ())
{
    check_correctors_are_in_interpolator_kernel<crest::SchurCorrectorSolver<double>>();
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_in_interpolator_kernel_sparselu_dense_fallback, ())
{
    typedef crest::DenseFallbackCorrectorSolverWrapper<double, crest::SparseLuCorrectorSolver<double>> Wrapper;
    check_correctors_are_in_interpolator_kernel<Wrapper>();
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_in_interpolator_kernel_amg, ())
{
    check_correctors_are_in_interpolator_kernel<crest::AmgCorrectorSolver<double>>();
}

template <typename CorrectorSolver>
void check_correctors_are_zero_with_no_refinement()
{
    const auto oversampling = static_cast<unsigned int>(*rc::gen::inRange(0, 6));
    const auto mesh = *crest::gen::arbitrary_unit_square_mesh();
    const auto biscale = crest::BiscaleMesh<double, int>(mesh, mesh);
    const auto correctors = CorrectorSolver().compute_correctors(biscale, oversampling);
    ASSERT_THAT(correctors.rows(), Eq(mesh.num_vertices()));
    ASSERT_THAT(correctors.cols(), Eq(mesh.num_vertices()));

    double max_abs = 0.0;
    for (int o = 0; o < correctors.outerSize(); ++o)
    {
        for (Eigen::SparseMatrix<double>::InnerIterator it(correctors, o); it; ++it)
        {
            max_abs = std::max(max_abs, std::abs(it.value()));
        }
    }

    RC_ASSERT(max_abs < TOL);
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_zero_with_no_refinement_sparselu, ())
{
    check_correctors_are_zero_with_no_refinement<crest::SparseLuCorrectorSolver<double>>();
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_zero_with_no_refinement_schur, ())
{
    check_correctors_are_zero_with_no_refinement<crest::SchurCorrectorSolver<double>>();
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_zero_with_no_refinement_sparselu_dense_fallback, ())
{
    typedef crest::DenseFallbackCorrectorSolverWrapper<double, crest::SparseLuCorrectorSolver<double>> Wrapper;
    check_correctors_are_zero_with_no_refinement<Wrapper>();
}

RC_GTEST_PROP(homogenized_basis_test, correctors_are_zero_with_no_refinement_amg, ())
{
    check_correctors_are_zero_with_no_refinement<crest::AmgCorrectorSolver<double>>();
}

template <typename CorrectorSolver>
void check_corrected_basis_is_orthogonal_to_fine_space()
{
    // Let W be such that W_ij corrected basis function i is defined by
    //
    // lambda_i = sum_j W_ij phi_j
    //
    // where phi_j denotes the fine-scale basis functions. Then the a-orthogonality of the corrected space V_H and
    // the fine-scale finite element space implies that
    //
    // W A N = 0
    //
    // where A is the fine-scale stiffness matrix (interior nodes) and N is a basis for W_H = ker(I_H).
    // In real applications, obtaining a basis for W_H is normally infeasible due to sparsity requirements.
    // However, since we only do small-scale tests here, we have the luxury of just simply building a dense
    // basis through the SVD.
    //
    // Our corrected basis is constructed by a localized approximation, so the above property does not hold exactly.
    // We can, however, choose an oversampling parameter so large that each corrector problem is a global problem.
    // In this case, the above property must still hold.

    // Make sure interior is not empty, because Eigen's SVD fails on empty matrices
    const auto coarse = *rc::gen::suchThat(crest::gen::arbitrary_unit_square_mesh(),
                                           [] (const auto & mesh) {
                                               return !mesh.compute_interior_vertices().empty();
                                           }).as("coarse mesh");
    const auto fine = *crest::gen::arbitrary_refinement(coarse).as("fine mesh");
    const auto biscale = crest::BiscaleMesh<double, int>(coarse, fine);

    const auto fine_interior = fine.compute_interior_vertices();
    const auto coarse_interior = coarse.compute_interior_vertices();
    const auto fine_basis = LagrangeBasis2d<double>(fine);

    const auto oversampling = static_cast<unsigned int>(coarse.num_vertices());
    const auto basis_weights = CorrectorSolver()
            .compute_basis(biscale, oversampling).basis_weights();
    const auto basis_interior_weights = sparse_submatrix(basis_weights, coarse_interior, fine_interior);

    // Construct a basis for W_H, the kernel of I_H.
    const Eigen::MatrixXd I_H = sparse_submatrix(crest::quasi_interpolator(biscale), coarse_interior, fine_interior);
    const Eigen::JacobiSVD<Eigen::MatrixXd> svd(I_H, Eigen::ComputeFullV);
    const auto r = svd.rank();
    const auto n = I_H.cols();
    const Eigen::MatrixXd W_H_kernel_basis = svd.matrixV().rightCols(n - r);

    const Eigen::MatrixXd W = basis_interior_weights;
    const Eigen::MatrixXd A = sparse_submatrix(fine_basis.assemble().stiffness, fine_interior, fine_interior);
    const auto & N = W_H_kernel_basis;

    const Eigen::MatrixXd product = W * A * N;

    RC_LOG() << "W:   " << std::endl << W << std::endl << std::endl;
    RC_LOG() << "A:   " << std::endl << A << std::endl << std::endl;
    RC_LOG() << "N:   " << std::endl << N << std::endl << std::endl;
    RC_LOG() << "WAN: " << std::endl << product << std::endl << std::endl;

    RC_ASSERT(product.isZero(TOL));
}

RC_GTEST_PROP(homogenized_basis_test, corrected_basis_is_orthogonal_to_fine_space_sparselu, ())
{
    check_corrected_basis_is_orthogonal_to_fine_space<crest::SparseLuCorrectorSolver<double>>();
}

RC_GTEST_PROP(homogenized_basis_test, corrected_basis_is_orthogonal_to_fine_space_schur, ())
{
    check_corrected_basis_is_orthogonal_to_fine_space<crest::SchurCorrectorSolver<double>>();
}

RC_GTEST_PROP(homogenized_basis_test, corrected_basis_is_orthogonal_to_fine_space_sparselu_dense_fallback, ())
{
    typedef crest::DenseFallbackCorrectorSolverWrapper<double, crest::SparseLuCorrectorSolver<double>> Wrapper;
    check_corrected_basis_is_orthogonal_to_fine_space<Wrapper>();
}

RC_GTEST_PROP(homogenized_basis_test, corrected_basis_is_orthogonal_to_fine_space_amg, ())
{
    check_corrected_basis_is_orthogonal_to_fine_space<crest::AmgCorrectorSolver<double>>();
}

TEST(standard_coarse_basis_in_fine_space, basic_mesh)
{
    const std::vector<Vertex> coarse_vertices{
            Vertex(0.0, 0.0),
            Vertex(1.0, 0.0),
            Vertex(1.0, 1.0),
            Vertex(0.0, 1.0)
    };

    const std::vector<Element> coarse_elements {
            Element({3, 0, 1}),
            Element({1, 2, 3})
    };

    const std::vector<Vertex> fine_vertices {
            Vertex(0.0, 0.0),
            Vertex(1.0, 0.0),
            Vertex(1.0, 1.0),
            Vertex(0.0, 1.0),
            Vertex(0.5, 0.5)
    };

    const std::vector<Element> fine_elements {
            Element({0, 4, 3}),
            Element({2, 4, 1}),
            Element({1, 4, 0}),
            Element({2, 4, 3})
    };

    const std::vector<int> fine_ancestry { 0, 1, 0, 1 };

    const auto coarse_mesh = IndexedMesh<double, int>(coarse_vertices, coarse_elements);
    const auto fine_mesh = IndexedMesh<double, int>(fine_vertices, fine_elements, fine_ancestry);
    const auto biscale = crest::BiscaleMesh<double, int>(coarse_mesh, fine_mesh);

    const Eigen::Matrix<double, 4, 5> coarse_basis_in_fine =
            crest::detail::standard_coarse_basis_in_fine_space(biscale);

    Eigen::Matrix<double, 4, 5> expected;
    expected <<
             1.0, 0.0, 0.0, 0.0, 0.0,
            0.0, 1.0, 0.0, 0.0, 0.5,
            0.0, 0.0, 1.0, 0.0, 0.0,
            0.0, 0.0, 0.0, 1.0, 0.5;

    ASSERT_TRUE(coarse_basis_in_fine.isApprox(expected));
}

RC_GTEST_PROP(standard_coarse_basis_in_fine_space, quasi_interpolation_recovers_coarse_basis, ())
{
    // Let v_H be the weights of a function in the coarse space. Then v_H is also a function in the fine space,
    // and since I_H is a quasi interpolation, we have that I_H v_h = v_H, where v_h are the fine weights of
    // the coarse function.
    // We can verify that this property holds for all basis functions as represented in the fine space.

    const auto coarse = *crest::gen::arbitrary_unit_square_mesh().as("Coarse mesh");
    const auto fine = *crest::gen::arbitrary_refinement(coarse, 0, 5).as("Fine mesh");
    const auto biscale = crest::BiscaleMesh<double, int>(coarse, fine);

    const auto basis = crest::detail::standard_coarse_basis_in_fine_space(biscale);
    const auto I_H = crest::quasi_interpolator(biscale);

    const Eigen::SparseMatrix<double> interpolated = I_H * basis.transpose();
    const Eigen::MatrixXd interpolated_dense = interpolated;

    RC_LOG() << interpolated_dense << std::endl;

    // We could have had a shaper tolerance here, but it appears Eigen does not do an elementwise comparison
    // for isIdentity (which is very annoying, by the way), as it can spuriously fail even when all non-diagonal
    // elements are smaller than 3e-16.
    RC_ASSERT(interpolated_dense.isIdentity(TOL));
}

max_stars_repo_name: Andlon/crest

max_issues_repo_name: Andlon/crest

max_forks_repo_name: Andlon/crest


text:
/*
 Copyright (C) GridGain Systems. All Rights Reserved.

 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 GRID_CLIENT_VARIANT_HPP_INCLUDED
#define GRID_CLIENT_VARIANT_HPP_INCLUDED

#include <string>
#include <vector>
#include <cstdint>

#include <gridgain/gridconf.hpp>
#include <gridgain/gridclientuuid.hpp>

#include <boost/variant.hpp>

/** Forward declaration of class. */
class GridClientVariantVisitor;

/**
 * Class that replaces java.lang.Object holder for primitive types and string. It can hold boolean, int_*, float, double,
 * string and byte array values.
 */
class GRIDGAIN_API GridClientVariant {

public:
    /** No-value type. */
    class NullType {
    public:
        /**
         * Comparison operator with another null value.
         *
         * @param other Another null value.
         * @return Always returns <tt>true</tt>.
         */
        bool operator==(const NullType& other) const {
            return true;
        }
    };

private:
    class Impl {
    public:
        /** Boost typedef for holding multiple types. */
        typedef boost::variant<GridClientVariant::NullType, bool, int16_t, int32_t, int64_t, double,
                float, std::string, std::wstring, std::vector<int8_t>, std::vector<GridClientVariant>, GridClientUuid> TVariantType;

        /** Boost variable. */
        TVariantType var;

        /** Enum for possible types of values. */
        enum TypeEnum {
            BOOL_TYPE = 1,
            SHORT_TYPE,
            INT_TYPE,
            LONG_TYPE,
            DOUBLE_TYPE,
            FLOAT_TYPE,
            STRING_TYPE,
            WIDE_STRING_TYPE,
            BYTE_ARRAY_TYPE,
            VARIANT_VECTOR_TYPE,
            UUID_TYPE
        };
    };

public:

    /** No-arg constructor - variant with null value is created. */
    GridClientVariant();

    /** Destructor. */
    virtual ~GridClientVariant();

    /**
     * Constructor with boolean argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(bool val);

    /**
     * Constructor with int16_t argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(int16_t val);

    /**
     * Constructor with int32_t argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(int32_t val);

    /**
     * Constructor with int64_t argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(int64_t val);

    /**
     * Constructor with double argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(double val);

    /**
     * Constructor with float argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(float val);

    /**
     * Constructor with string argument. Added const char* explicitly because otherwise it boolean constructor
     * was called.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(const char * val);

    /**
     * Constructor with string argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(const std::string& val);

    /**
     * Constructor with wide string argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(const std::wstring& val);

    /**
     * Constructor with byte array argument.
     *
     * @param val Value for the variant.
     */
    GridClientVariant(const std::vector<int8_t>& val);

    /**
     * Constructor with variant vector argument.
     */
    GridClientVariant(const std::vector<GridClientVariant>& val);

    /**
     * Constructor with UUID argument.
     */
    GridClientVariant(const GridClientUuid& val);

    /**
     * Copy constructor.
     *
     * @param other Variant to take value from.
     */
    GridClientVariant(const GridClientVariant& other);

    /**
     * Assignment operator.
     *
     * @param other Variant to take value from.
     */
    GridClientVariant& operator=(const GridClientVariant& other);

    /**
     * Converts value contained in variant, to string.
     *
     * @return String representation of the value held.
     */
    std::string toString() const;

    /**
     * Returns debug string that contains type information and value.
     *
     * @return Type and value information.
     */
    std::string debugString() const;

    /**
     * Assigns this variant a boolean value.
     *
     * @param val New value for the variant.
     */
    void set(bool val);

    /**
     * Checks if this variant holds a boolean value.
     *
     * @return <tt>true</tt> if value is of boolean type, <tt>false</tt> otherwise.
     */
    bool hasBool() const;

    /**
     * Returns a boolean value from this variant.
     *
     * @return Value held in the variant.
     */
    bool getBool() const;

    /**
     * Assigns this variant an int16_t value.
     *
     * @param val New value for the variant.
     */
    void set(int16_t val);

    /**
     * Checks if this variant holds an int16_t value.
     *
     * @return <tt>true</tt> if value is of int16_t type, <tt>false</tt> otherwise.
     */
    bool hasShort() const;

    /**
     * Returns an int16_t value from this variant.
     *
     * @return Value held in the variant.
     */
    int16_t getShort() const;

    /**
     * Assigns this variant an int32_t value.
     *
     * @param val New value for the variant.
     */
    void set(int32_t val);

    /**
     * Checks if this variant holds an int32_t value.
     *
     * @return <tt>true</tt> if value is of int32_t type, <tt>false</tt> otherwise.
     */
    bool hasInt() const;

    /**
     * Returns an int16_t value from this variant.
     *
     * @return Value held in the variant.
     */
    int32_t getInt() const;

    /**
     * Assigns this variant an int64_t value.
     *
     * @param val New value for the variant.
     */
    void set(int64_t val);

    /**
     * Checks if this variant holds an int64_t value.
     *
     * @return <tt>true</tt> if value is of int64_t type, <tt>false</tt> otherwise.
     */
    bool hasLong() const;

    /**
     * Returns an int64_t value from this variant.
     *
     * @return Value held in the variant.
     */
    int64_t getLong() const;

    /**
     * Assigns this variant a double value.
     *
     * @param val New value for the variant.
     */
    void set(double val);

    /**
     * Checks if this variant holds a double value.
     *
     * @return <tt>true</tt> if value is of double type, <tt>false</tt> otherwise.
     */
    bool hasDouble() const;

    /**
     * Returns a double value from this variant.
     *
     * @return Value held in the variant.
     */
    double getDouble() const;

    /**
     * Assigns this variant a float value.
     *
     * @param val New value for the variant.
     */
    void set(float val);

    /**
     * Checks if this variant holds a float value.
     *
     * @return <tt>true</tt> if value is of float type, <tt>false</tt> otherwise.
     */
    bool hasFloat() const;

    /**
     * Returns a float value from this variant.
     *
     * @return Value held in the variant.
     */
    float getFloat() const;

    /**
     * Assigns this variant a string value.
     *
     * @param val New value for the variant.
     */
    void set(const std::string& val);

    /**
     * Assigns this variant a string value.
     *
     * @param val New value for the variant.
     */
    void set(const char* val);

    /**
     * Checks if this variant holds a string value.
     *
     * @return <tt>true</tt> if value is of string type, <tt>false</tt> otherwise.
     */
    bool hasString() const;

    /**
     * Returns a string value from this variant.
     *
     * @return Value held in the variant.
     */
    std::string getString() const;

    /**
     * Checks if this variant holds a wide string value.
     *
     * @return <tt>true</tt> if value is of wide string type, <tt>false</tt> otherwise.
     */
    bool hasWideString() const;

    /**
     * Returns a wide string value from this variant.
     *
     * @return Value held in the variant.
     */
    std::wstring getWideString() const;

    /**
     * Assigns this variant a byte array value.
     *
     * @param val New value for the variant.
     */
    void set(const std::vector<int8_t>& val);

    /**
     * Checks if this variant holds a byte array value.
     *
     * @return <tt>true</tt> if value is of byte array type, <tt>false</tt> otherwise.
     */
    bool hasByteArray() const;

    /**
     * Returns a byte array value from this variant.
     *
     * @return Value held in the variant.
     */
    std::vector<int8_t> getByteArray() const;

    /**
     * Checks if this variant holds a variant vector value.
     *
     * @return <tt>true</tt> if value is of variant vector type, <tt>false</tt> otherwise.
     */
    bool hasVariantVector() const;

    /**
     * Returns a variant vector value from this variant.
     *
     * @return Value held in the variant.
     */
    std::vector<GridClientVariant> getVariantVector() const;

    /**
     * Assigns this variant a UUID value.
     *
     * @param val New value for the variant.
     */
    void set(const GridClientUuid& val);

    /**
     * Checks if this variant holds a UUID value.
     *
     * @return <tt>true</tt> if value is of UUID type, <tt>false</tt> otherwise.
     */
    bool hasUuid() const;

    /**
     * Returns a UUID value from this variant.
     *
     * @return Value held in the variant.
     */
    GridClientUuid getUuid() const;

    /**
     * Method for visitors.
     *
     * @param visitor Visitor to accept.
     */
    void accept(const GridClientVariantVisitor& visitor) const;

    /**
     * Comparison operator for variant.
     *
     * @param other Variant to compare this variant to.
     * @return <tt>true</tt> if this variant is less than other, <tt>false</tt> otherwise.
     */
    bool operator<(const GridClientVariant& other) const;

    /**
     * Comparison operator for variant.
     *
     * @param other Variant to compare this variant to.
     * @return <tt>true</tt> if this variant equals to the other, <tt>false</tt> otherwise.
     */
    bool operator==(const GridClientVariant& other) const;

    /**
     * Clears value held (becomes null).
     */
    void clear();

    /**
     * Method to check if this variant holds any value.
     *
     * @return <tt>true</tt> if it has a value set, <tt>false</tt> otherwise.
     */
    bool hasAnyValue() const;

private:
    Impl pimpl;
};

/**
 * Print 'null' value to output stream.
 *
 * @param out Stream to print value to.
 * @param src Value to print (ignored).
 */
inline std::ostream& operator <<(std::ostream& out, const GridClientVariant::NullType& src) {
    return out;
}

/**
 * Prints variant to stream
 *
 * @param out Stream to output variant to.
 * @param m Variant.
 */
inline std::ostream& operator<<(std::ostream &out, const GridClientVariant &m) {
    return out << m.toString();
}

/** Base class for variant visitors. */
class GridClientVariantVisitor {
public:
    /** Virtual destructor. */
    virtual ~GridClientVariantVisitor() {};

    /** */
    virtual void visit(const bool val) const = 0;

    /** */
    virtual void visit(const int16_t) const = 0;

    /** */
    virtual void visit(const int32_t) const = 0;

    /** */
    virtual void visit(const int64_t) const = 0;

    /** */
    virtual void visit(const double) const = 0;

    /** */
    virtual void visit(const float) const = 0;

    /** */
    virtual void visit(const std::string&) const = 0;

    /** */
    virtual void visit(const std::wstring&) const = 0;

    /** */
    virtual void visit(const std::vector<int8_t>&) const = 0;

    /** */
    virtual void visit(const std::vector<GridClientVariant>&) const = 0;

    /** */
    virtual void visit(const GridClientUuid&) const = 0;
};

#endif //GRID_CLIENT_VARIANT_HPP_INCLUDED

max_stars_repo_name: cybernetics/gridgain

max_issues_repo_name: cybernetics/gridgain

max_forks_repo_name: cybernetics/gridgain


text:
// Compile me:  g++ -std=c++11 main.cpp -o test -ldl -Wno-main
#include <iostream>
#include <vector>
#include <string>

#include <boost/format.hpp>

#include <dlfcn.h>

using namespace std;

typedef int libc_start_main_f(...);

extern "C" int __libc_start_main(int (*main)(int, char **, char **), long argc, char** ubp_av,
                                 void *init, void *fini, void *rtld_fini, void *stack_end)
{
    static vector<string> args(ubp_av, ubp_av + argc);
    auto libc_start_main_symbol = dlsym(RTLD_NEXT, "__libc_start_main");
    auto real_libc_start_main = reinterpret_cast<libc_start_main_f*>(libc_start_main_symbol);
    return real_libc_start_main(main, (long)&args, ubp_av, init, fini, rtld_fini, stack_end);
}

int main(const vector<string>& args)
{
    cout << "argc = " << args.size() << endl;
    for (size_t i = 0, e = args.size(); i < e; ++i)
        cout << boost::format("arg #%1% = %2%\n") % i % args[i];

    return 0;
}

max_stars_repo_name: cvlabmiet/interview-tasks

max_issues_repo_name: cvlabmiet/interview-tasks

max_forks_repo_name: cvlabmiet/interview-tasks


text:
///////////////////////////////////////////////////////////////////////////////
// moving_average.hpp                                                        //
//                                                                           //
//  Copyright 2008 Erwann Rogard. Distributed under the Boost                //
//  Software License, Version 1.0. (See accompanying file                    //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         //
///////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_ACCUMULATORS_RANDOM_MOVING_AVERAGE_HPP_ER_2008_04
#define BOOST_ACCUMULATORS_RANDOM_MOVING_AVERAGE_HPP_ER_2008_04

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/fir.hpp>
#include <boost/range/iterator_range.hpp>
namespace boost{namespace random
{

// Simulates a Moving average process
template<typename T>
class moving_average{
public:
    typedef T               input_type;
    typedef T               result_type ;
    template<typename R>
    moving_average(const R& coeffs)
        :acc(
            accumulators::tag::fir::coefficients=coeffs,
            accumulators::tag::delay<>::cache_size=coeffs.size()){}
    moving_average(const moving_average& that)
        :acc(that.acc){}
    moving_average& operator=(const moving_average& that){
        if(&that!=this){
            acc = that.acc;
        }
        return *this;
    }
    template<typename G>//G models NumberGenerator
    result_type operator()(G& gen){
        T x = gen();
        acc(x);
        return accumulators::extract::fir(acc);
    }
private:
    typedef accumulators::accumulator_set<
        T,
        accumulators::stats<
            accumulators::tag::fir,
            accumulators::tag::delay<>
        >
    > acc_type;
    acc_type acc;
};

}}
#endif


text:
#ifndef SOLVERTOOLS_H
#define SOLVERTOOLS_H

#include <opengv/types.hpp>
#include <Eigen/Dense>
#include <opengv/optimization_tools/objective_function_tools/ObjectiveFunctionInfo.hpp>

class ObjectiveFunctionInfo;

class SolverTools{
 public:

  virtual Eigen::Matrix3d exp_R( Eigen::Matrix3d & X ) = 0;

  virtual opengv::rotation_t rotation_solver(opengv::rotation_t & state_rotation, const opengv::translation_t & translation,
					     double &tol, ObjectiveFunctionInfo * info_function, int & k) = 0;

  virtual opengv::translation_t translation_solver(const opengv::rotation_t & rotation,
						   opengv::translation_t & translation, double &tol, ObjectiveFunctionInfo * info_function, double &step, int & k) = 0;

};

#endif


text:
/* Copyright (c) 2017, United States Government, as represented by the
 * Administrator of the National Aeronautics and Space Administration.
 *
 * All rights reserved.
 *
 * The Astrobee platform is licensed under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with the
 * License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

#include <localization_analysis/bag_imu_filterer.h>
#include <localization_common/logger.h>
#include <localization_common/utilities.h>

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

namespace po = boost::program_options;
namespace lc = localization_common;

int main(int argc, char** argv) {
  std::string output_bagfile;
  std::string filter_name;
  po::options_description desc(
    "Reads through a bag file and filters imu measurements, replacing the old imu measurements with new filtered "
    "ones.  Saves output to a new bagfile.");
  desc.add_options()("help,h", "produce help message")("bagfile", po::value<std::string>()->required(),
                                                       "Input bagfile")(
    "output-bagfile,o", po::value<std::string>(&output_bagfile)->default_value("filtered_imu.bag"), "Output bagfile")(
    "filter-name,f", po::value<std::string>(&filter_name)->default_value("none"), "Imu filter name");
  po::positional_options_description p;
  p.add("bagfile", 1);
  po::variables_map vm;
  try {
    po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
    if (vm.count("help") || (argc <= 1)) {
      std::cout << desc << "\n";
      return 1;
    }
    po::notify(vm);
  } catch (std::exception& e) {
    std::cerr << "Error: " << e.what() << "\n";
    return 1;
  }

  const std::string input_bag = vm["bagfile"].as<std::string>();

  if (!boost::filesystem::exists(input_bag)) {
    LogFatal("Bagfile " << input_bag << " not found.");
  }

  if (vm["output-bagfile"].defaulted()) {
    const auto current_path = boost::filesystem::current_path();
    boost::filesystem::path output_bagfile_path(output_bagfile);
    const auto output_bagfile_full_path = current_path / output_bagfile_path;
    output_bagfile = output_bagfile_full_path.string();
  }

  localization_analysis::BagImuFilterer bag_imu_filterer(input_bag, output_bagfile, filter_name);
  bag_imu_filterer.Convert();
}

max_stars_repo_name: flowarko/astrobee

max_issues_repo_name: flowarko/astrobee

max_forks_repo_name: flowarko/astrobee


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

#ifndef BOOST_TR1_CMATH_HPP_INCLUDED
#  define BOOST_TR1_CMATH_HPP_INCLUDED
#  include <boost/tr1/detail/config.hpp>

#ifdef BOOST_HAS_TR1_CMATH

#  if defined(BOOST_HAS_INCLUDE_NEXT) && !defined(BOOST_TR1_DISABLE_INCLUDE_NEXT)
#     include_next BOOST_TR1_HEADER(cmath)
#  else
#     include <boost/tr1/detail/config_all.hpp>
#     include BOOST_TR1_HEADER(cmath)
#  endif

#else

#include <boost/math/tr1.hpp>

namespace std{ namespace tr1{

using boost::math::tr1::assoc_laguerre;
using boost::math::tr1::assoc_laguerref;
using boost::math::tr1::assoc_laguerrel;
// [5.2.1.2] associated Legendre functions:
using boost::math::tr1::assoc_legendre;
using boost::math::tr1::assoc_legendref;
using boost::math::tr1::assoc_legendrel;
// [5.2.1.3] beta function:
using boost::math::tr1::beta;
using boost::math::tr1::betaf;
using boost::math::tr1::betal;
// [5.2.1.4] (complete) elliptic integral of the first kind:
using boost::math::tr1::comp_ellint_1;
using boost::math::tr1::comp_ellint_1f;
using boost::math::tr1::comp_ellint_1l;
// [5.2.1.5] (complete) elliptic integral of the second kind:
using boost::math::tr1::comp_ellint_2;
using boost::math::tr1::comp_ellint_2f;
using boost::math::tr1::comp_ellint_2l;
// [5.2.1.6] (complete) elliptic integral of the third kind:
using boost::math::tr1::comp_ellint_3;
using boost::math::tr1::comp_ellint_3f;
using boost::math::tr1::comp_ellint_3l;
#if 0
// [5.2.1.7] confluent hypergeometric functions:
using boost::math::tr1::conf_hyperg;
using boost::math::tr1::conf_hypergf;
using boost::math::tr1::conf_hypergl;
#endif
// [5.2.1.8] regular modified cylindrical Bessel functions:
using boost::math::tr1::cyl_bessel_i;
using boost::math::tr1::cyl_bessel_if;
using boost::math::tr1::cyl_bessel_il;
// [5.2.1.9] cylindrical Bessel functions (of the first kind):
using boost::math::tr1::cyl_bessel_j;
using boost::math::tr1::cyl_bessel_jf;
using boost::math::tr1::cyl_bessel_jl;
// [5.2.1.10] irregular modified cylindrical Bessel functions:
using boost::math::tr1::cyl_bessel_k;
using boost::math::tr1::cyl_bessel_kf;
using boost::math::tr1::cyl_bessel_kl;
// [5.2.1.11] cylindrical Neumann functions;
// cylindrical Bessel functions (of the second kind):
using boost::math::tr1::cyl_neumann;
using boost::math::tr1::cyl_neumannf;
using boost::math::tr1::cyl_neumannl;
// [5.2.1.12] (incomplete) elliptic integral of the first kind:
using boost::math::tr1::ellint_1;
using boost::math::tr1::ellint_1f;
using boost::math::tr1::ellint_1l;
// [5.2.1.13] (incomplete) elliptic integral of the second kind:
using boost::math::tr1::ellint_2;
using boost::math::tr1::ellint_2f;
using boost::math::tr1::ellint_2l;
// [5.2.1.14] (incomplete) elliptic integral of the third kind:
using boost::math::tr1::ellint_3;
using boost::math::tr1::ellint_3f;
using boost::math::tr1::ellint_3l;
// [5.2.1.15] exponential integral:
using boost::math::tr1::expint;
using boost::math::tr1::expintf;
using boost::math::tr1::expintl;
// [5.2.1.16] Hermite polynomials:
using boost::math::tr1::hermite;
using boost::math::tr1::hermitef;
using boost::math::tr1::hermitel;
#if 0
// [5.2.1.17] hypergeometric functions:
using boost::math::tr1::hyperg;
using boost::math::tr1::hypergf;
using boost::math::tr1::hypergl;
#endif
// [5.2.1.18] Laguerre polynomials:
using boost::math::tr1::laguerre;
using boost::math::tr1::laguerref;
using boost::math::tr1::laguerrel;
// [5.2.1.19] Legendre polynomials:
using boost::math::tr1::legendre;
using boost::math::tr1::legendref;
using boost::math::tr1::legendrel;
// [5.2.1.20] Riemann zeta function:
using boost::math::tr1::riemann_zeta;
using boost::math::tr1::riemann_zetaf;
using boost::math::tr1::riemann_zetal;
// [5.2.1.21] spherical Bessel functions (of the first kind):
using boost::math::tr1::sph_bessel;
using boost::math::tr1::sph_besself;
using boost::math::tr1::sph_bessell;
// [5.2.1.22] spherical associated Legendre functions:
using boost::math::tr1::sph_legendre;
using boost::math::tr1::sph_legendref;
using boost::math::tr1::sph_legendrel;
// [5.2.1.23] spherical Neumann functions;
// spherical Bessel functions (of the second kind):
using boost::math::tr1::sph_neumann;
using boost::math::tr1::sph_neumannf;
using boost::math::tr1::sph_neumannl;

// types
using boost::math::tr1::double_t;
using boost::math::tr1::float_t;
// functions
using boost::math::tr1::acosh;
using boost::math::tr1::acoshf;
using boost::math::tr1::acoshl;
using boost::math::tr1::asinh;
using boost::math::tr1::asinhf;
using boost::math::tr1::asinhl;
using boost::math::tr1::atanh;
using boost::math::tr1::atanhf;
using boost::math::tr1::atanhl;
using boost::math::tr1::cbrt;
using boost::math::tr1::cbrtf;
using boost::math::tr1::cbrtl;
using boost::math::tr1::copysign;
using boost::math::tr1::copysignf;
using boost::math::tr1::copysignl;
using boost::math::tr1::erf;
using boost::math::tr1::erff;
using boost::math::tr1::erfl;
using boost::math::tr1::erfc;
using boost::math::tr1::erfcf;
using boost::math::tr1::erfcl;
#if 0
using boost::math::tr1::exp2;
using boost::math::tr1::exp2f;
using boost::math::tr1::exp2l;
#endif
using boost::math::tr1::expm1;
using boost::math::tr1::expm1f;
using boost::math::tr1::expm1l;
#if 0
using boost::math::tr1::fdim;
using boost::math::tr1::fdimf;
using boost::math::tr1::fdiml;
using boost::math::tr1::fma;
using boost::math::tr1::fmaf;
using boost::math::tr1::fmal;
#endif
using boost::math::tr1::fmax;
using boost::math::tr1::fmaxf;
using boost::math::tr1::fmaxl;
using boost::math::tr1::fmin;
using boost::math::tr1::fminf;
using boost::math::tr1::fminl;
using boost::math::tr1::hypot;
using boost::math::tr1::hypotf;
using boost::math::tr1::hypotl;
#if 0
using boost::math::tr1::ilogb;
using boost::math::tr1::ilogbf;
using boost::math::tr1::ilogbl;
#endif
using boost::math::tr1::lgamma;
using boost::math::tr1::lgammaf;
using boost::math::tr1::lgammal;
#if 0
using boost::math::tr1::llrint;
using boost::math::tr1::llrintf;
using boost::math::tr1::llrintl;
#endif
using boost::math::tr1::llround;
using boost::math::tr1::llroundf;
using boost::math::tr1::llroundl;
using boost::math::tr1::log1p;
using boost::math::tr1::log1pf;
using boost::math::tr1::log1pl;
#if 0
using boost::math::tr1::log2;
using boost::math::tr1::log2f;
using boost::math::tr1::log2l;
using boost::math::tr1::logb;
using boost::math::tr1::logbf;
using boost::math::tr1::logbl;
using boost::math::tr1::lrint;
using boost::math::tr1::lrintf;
using boost::math::tr1::lrintl;
#endif
using boost::math::tr1::lround;
using boost::math::tr1::lroundf;
using boost::math::tr1::lroundl;
#if 0
using boost::math::tr1::nan;
using boost::math::tr1::nanf;
using boost::math::tr1::nanl;
using boost::math::tr1::nearbyint;
using boost::math::tr1::nearbyintf;
using boost::math::tr1::nearbyintl;
#endif
using boost::math::tr1::nextafter;
using boost::math::tr1::nextafterf;
using boost::math::tr1::nextafterl;
using boost::math::tr1::nexttoward;
using boost::math::tr1::nexttowardf;
using boost::math::tr1::nexttowardl;
#if 0
using boost::math::tr1::remainder;
using boost::math::tr1::remainderf;
using boost::math::tr1::remainderl;
using boost::math::tr1::remquo;
using boost::math::tr1::remquof;
using boost::math::tr1::remquol;
using boost::math::tr1::rint;
using boost::math::tr1::rintf;
using boost::math::tr1::rintl;
#endif
using boost::math::tr1::round;
using boost::math::tr1::roundf;
using boost::math::tr1::roundl;
#if 0
using boost::math::tr1::scalbln;
using boost::math::tr1::scalblnf;
using boost::math::tr1::scalblnl;
using boost::math::tr1::scalbn;
using boost::math::tr1::scalbnf;
using boost::math::tr1::scalbnl;
#endif
using boost::math::tr1::tgamma;
using boost::math::tr1::tgammaf;
using boost::math::tr1::tgammal;
using boost::math::tr1::trunc;
using boost::math::tr1::truncf;
using boost::math::tr1::truncl;
// C99 macros defined as C++ templates
using boost::math::tr1::signbit;
using boost::math::tr1::fpclassify;
using boost::math::tr1::isfinite;
using boost::math::tr1::isinf;
using boost::math::tr1::isnan;
using boost::math::tr1::isnormal;
#if 0
using boost::math::tr1::isgreater;
using boost::math::tr1::isgreaterequal;
using boost::math::tr1::isless;
using boost::math::tr1::islessequal;
using boost::math::tr1::islessgreater;
using boost::math::tr1::isunordered;
#endif
} } // namespaces

#endif // BOOST_HAS_TR1_CMATH

#endif // BOOST_TR1_CMATH_HPP_INCLUDED

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema