text:
#include <iostream>
#include <chrono>
#include <fstream>
#include <memory>
#include <boost/mpi.hpp>

#include "ga/Hipercube.h"
#include "functions/Rastrigin.h"
#include "selection/Tournament.h"
#include "operators/mutations/GaussianMutator.h"
#include "operators/xover/LinearXOver.h"
#include "ga/HAEA/AbstractHAEA.h"
#include "ga/HAEA/PosixHAEA.h"
#include "ga/HAEA/OpenMPHAEA.h"

using namespace std;
using ns = chrono::microseconds;
using get_time = chrono::steady_clock;

void test();
void test1();

int main() {
    return 0;
}

void test1() {
    Hipercube h(-5.12, 5.12, 10000);
    vector<double> a = h.getRandomIndividual();
    vector<double> b = h.getRandomIndividual();
    vector<vector<double>> inds;
    inds.push_back(a);
    inds.push_back(b);

    GaussianMutator gaussianMutator(0.0, 0.3, 0.1);
    LinearXOver linearXOver;
    auto start = get_time::now();
    for(int i = 0; i < 100; ++i) {
        h.repair(a);
    }
    auto end = get_time::now();
    auto diff = end - start;
    cout << std::chrono::duration_cast<ns>(diff).count() << " ";
}

void test() {
    size_t popSize[] = {50};
    for(int i = 0; i < 1; ++i) {
        cout << "population size: " << popSize[i] << endl;
        for(size_t j = 1; j <= 5; j += 7) {

            ofstream file;
            file.open(to_string(popSize[i]) + "_" + to_string(j) + ".txt");

            cout << "threads: " << j << endl;
            size_t ITERS = 500;
            size_t POP = popSize[i];
            size_t DIM = 1000;
            size_t THREADS = j;
            int sampling = 3;

            Hipercube space(-5.12, 5.12, DIM);
            Rastrigin optimizationFunction;
            Tournament selection(optimizationFunction, 4);

            cout << optimizationFunction.apply(space.getRandomIndividual()) << endl;

            vector< shared_ptr<Operator<vector<double> > > > opers;
            opers.push_back(make_shared<GaussianMutator>(0.0, 0.3, 0.1));
            opers.push_back(make_shared<LinearXOver>());

            PosixHAEA<vector<double>> search(selection, opers, POP, ITERS);
            search.setThreads(THREADS);

            double rmean = 0.0;

            for(int k = 0; k < sampling; ++k) {
                cout << "iter: " << k << endl;
                auto start = get_time::now();
                vector<vector<double>> pop = search.solve(&space, &optimizationFunction);
                double bestInd = 10e8;
                for(size_t z = 0; z < pop.size(); ++z) {
                    double elem = optimizationFunction.apply(pop[z]);
                    if(elem < bestInd) {
                        bestInd = elem;
                    }
                }

                cout << bestInd << endl;
                auto end = get_time::now();
                auto diff = end - start;
                file  << chrono::duration_cast<ns>(diff).count() << " ";
                /*vector<vector<double> > result = search.solve(&space, &optimizationFunction, THREADS);
                double mean = 0.0;

                for(size_t i = 0; i < result.size(); ++i) {
                    for(size_t j = 0; j < result[0].size(); ++j) {
                        cout << result[i][j] << " ";
                    }
                    mean += optimizationFunction.apply(result[i]);
                }

                mean /= result.size();
                rmean += mean;*/
            }
            file.close();
        }
    }
}


text:
/*
 * Copyright 2020 Adobe. All rights reserved.
 * This file is licensed 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 REPRESENTATIONS
 * OF ANY KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
#include <cmath>
#include <iostream>

#include <lagrange/testing/common.h>

#include <Eigen/Geometry>

#include <lagrange/common.h>
#include <lagrange/compute_mesh_covariance.h>
#include <lagrange/create_mesh.h>
#include <lagrange/utils/safe_cast.h>

TEST_CASE("ComputeMeshCovariance", "[mesh][covariance]")
{
    using namespace lagrange;

    Vertices3D ref_vertices(6 + 3, 3);
    Triangles facets(4 + 1, 3);

    const double a = 0.5;
    const double b = 2.0;
    const double large_number = 1000;

    ref_vertices.row(0) << -a / 2., -b / 2., 0;
    ref_vertices.row(1) << +a / 2., -b / 2., 0;
    ref_vertices.row(2) << +a / 2., 0, 0;
    ref_vertices.row(3) << +a / 2., b / 4., 0;
    ref_vertices.row(4) << +a / 2., b / 2., 0;
    ref_vertices.row(5) << -a / 2., b / 2., 0;
    // Don't include in computation
    ref_vertices.row(6) << large_number, large_number, large_number;
    ref_vertices.row(7) << -large_number, -large_number, -large_number;
    ref_vertices.row(8) << 2 * large_number, 2 * large_number, 2 * large_number;

    facets.row(0) << 0, 1, 2;
    // Don't include in computation
    facets.row(1) << 6, 7, 8;
    //
    facets.row(2) << 0, 2, 3;
    facets.row(3) << 0, 3, 4;
    facets.row(4) << 0, 4, 5;

    // Reference values without transformations
    const double ref_area = a * b;
    Eigen::Vector3d ref_center(0, 0, 0);
    Eigen::Matrix3d ref_covariance = Eigen::Matrix3d::Zero();
    ref_covariance(0, 0) = b * a * a * a / 12.;
    ref_covariance(1, 1) = a * b * b * b / 12.;

    // Translate
    // Eigen::Vector3d tr(0,0,0);
    Eigen::Vector3d tr(-1, 3, 4);

    // Rotate
    // Eigen::Matrix3d rot = Eigen::Matrix3d::Identity();
    Eigen::Matrix3d rot =
        Eigen::AngleAxisd(1.2365, Eigen::Vector3d(-1, 2, 5.1).normalized()).toRotationMatrix();
    Eigen::Matrix3d rot_covariance = rot * ref_covariance * rot.transpose();
    Eigen::Matrix3d rot_covariance_tr = rot_covariance + ref_area * tr * tr.transpose();

    // Create the vertices
    Vertices3D vertices = (ref_vertices * rot.transpose()).rowwise() + tr.transpose();

    auto mesh_unique = lagrange::create_mesh(vertices, facets);
    auto out_covariance_at_zero =
        compute_mesh_covariance(*mesh_unique, Eigen::RowVector3d::Zero(), {0, 2, 3, 4});
    auto out_covariance_at_centroid =
        compute_mesh_covariance(*mesh_unique, tr.transpose(), {0, 2, 3, 4});

    CHECK((out_covariance_at_zero - rot_covariance_tr).norm() == Approx(0.).margin(1e-10));
    CHECK((out_covariance_at_centroid - rot_covariance).norm() == Approx(0.).margin(1e-10));

    // std::cout << out_covariance_at_zero.covariance << std::endl;
    // std::cout << rot_covariance_tr << std::endl;

} // end of TEST

ext: cpp


text:
#include <ripple/beast/asio/io_latency_probe.h>
#include <ripple/beast/unit_test.h>
#include <beast/test/yield_to.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <chrono>

using namespace std::chrono_literals;

class io_latency_probe_test :
    public beast::unit_test::suite, public beast::test::enable_yield_to
{
    using MyTimer = boost::asio::basic_waitable_timer<std::chrono::steady_clock>;

    struct test_sampler
    {
        beast::io_latency_probe <std::chrono::steady_clock> probe_;
        std::vector<std::chrono::steady_clock::duration> durations_;

        test_sampler (
            std::chrono::milliseconds interval,
            boost::asio::io_service& ios)
            : probe_ (interval, ios)
        {
        }

        void
        start()
        {
            probe_.sample (std::ref(*this));
        }

        void
        start_one()
        {
            probe_.sample_one (std::ref(*this));
        }

        void operator() (std::chrono::steady_clock::duration const& elapsed)
        {
            durations_.push_back(elapsed);
        }
    };

    void
    testSampleOne(boost::asio::yield_context& yield)
    {
        testcase << "sample one";
        boost::system::error_code ec;
        test_sampler io_probe {100ms, get_io_service()};
        io_probe.start_one();
        MyTimer timer {get_io_service(), 1s};
        timer.async_wait(yield[ec]);
        if(! BEAST_EXPECTS(! ec, ec.message()))
            return;
        BEAST_EXPECT(io_probe.durations_.size() == 1);
        io_probe.probe_.cancel_async();
    }

    void
    testSampleOngoing(boost::asio::yield_context& yield)
    {
        testcase << "sample ongoing";
        boost::system::error_code ec;
        test_sampler io_probe {99ms, get_io_service()};
        io_probe.start();
        MyTimer timer {get_io_service(), 1s};
        timer.async_wait(yield[ec]);
        if(! BEAST_EXPECTS(! ec, ec.message()))
            return;
        auto probes_seen = io_probe.durations_.size();
        BEAST_EXPECTS(probes_seen >=9 && probes_seen <= 11,
            std::string("probe count is ") + std::to_string(probes_seen));
        io_probe.probe_.cancel_async();
        timer.expires_from_now(1s);
        timer.async_wait(yield[ec]);
    }

    void
    testCanceled(boost::asio::yield_context& yield)
    {
        testcase << "canceled";
        test_sampler io_probe {100ms, get_io_service()};
        io_probe.probe_.cancel_async();
        except<std::logic_error>( [&io_probe](){ io_probe.start_one(); });
        except<std::logic_error>( [&io_probe](){ io_probe.start(); });
    }

public:
    void run () override
    {
        yield_to([&](boost::asio::yield_context& yield)
        {
            testSampleOne (yield);
            testSampleOngoing (yield);
            testCanceled (yield);
        });
    }
};

BEAST_DEFINE_TESTSUITE(io_latency_probe, asio, beast);


text:
#ifndef NVMB_NODE_HPP
#define NVMB_NODE_HPP

#include <string>
#include <vector>
#include <functional>
#include <armadillo>
using namespace std;
using namespace arma;

vector<string> tvcf(string);

class Vuln
{
public:

    string identifier;
    float quality;
    float span;
    function<vector<string>(string)> vcf; // patch function; return, (args)
    Vuln(string idf, float q, float s, vector<string> (*f)(string));

    // TODO: delete after finish, test method for Armadillo
    void CalculatePlans();

};

#endif

ext: hpp


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

#include "amount.h"
#include "chainparams.h"
#include "core_io.h"
#include "db.h"
#include "init.h"
#include "kernel.h"
#include "miner.h"
#include "rpcserver.h"
#include "txdb.h"
#include "util.h"

#include <boost/assign/list_of.hpp>

#include "univalue/univalue.h"

using namespace std;
using namespace boost::assign;

UniValue getsubsidy(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "getsubsidy [nTarget]\n"
            "Returns proof-of-work subsidy value for the specified value of target.");

    CAmount nReward = GetProofOfWorkReward(0);

    return (CAmount)nReward;
}

UniValue getstakesubsidy(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "getstakesubsidy <hex string>\n"
            "Returns proof-of-stake subsidy value for the specified coinstake.");

    RPCTypeCheck(params, list_of(UniValue::VSTR));

    vector<unsigned char> txData(ParseHex(params[0].get_str()));
    CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
    CTransaction tx;
    try {
        ssData >> tx;
    } catch (std::exception& e) {
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
    }

    uint64_t nCoinAge;
    CCoinsViewCache view(pcoinsTip);
    CValidationState state;
    if (!GetCoinAge(tx, state, view, nCoinAge, chainActive.Height()))
        throw JSONRPCError(RPC_MISC_ERROR, "GetCoinAge failed");

    CAmount nStakeReward = GetProofOfStakeReward(nCoinAge, 0, chainActive.Height());

    return (CAmount)nStakeReward;
}

UniValue getmininginfo(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getmininginfo\n"
            "Returns an object containing mining-related information.");

    uint64_t nWeight = 0;
    if (pwalletMain)
        nWeight = pwalletMain->GetStakeWeight();

    UniValue obj(UniValue::VOBJ);
    UniValue diff(UniValue::VOBJ);
    UniValue weight(UniValue::VOBJ);
    obj.push_back(Pair("blocks", (int)chainActive.Height()));
    obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
    obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));

    diff.push_back(Pair("proof-of-work", GetDifficulty()));
    diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(chainActive.Tip(), true))));
    diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
    obj.push_back(Pair("difficulty", diff));
    obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(0)));

    obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
    obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
    obj.push_back(Pair("errors", GetWarnings("statusbar")));
    obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
    obj.push_back(Pair("chain", Params().NetworkIDString()));

    weight.push_back(Pair("minimum", (uint64_t)nWeight));
    weight.push_back(Pair("maximum", (uint64_t)0));
    weight.push_back(Pair("combined", (uint64_t)nWeight));
    obj.push_back(Pair("stakeweight", weight));

    obj.push_back(Pair("testnet", Params().TestnetToBeDeprecatedFieldRPC()));
    return obj;
}

UniValue getstakinginfo(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getstakinginfo\n"
            "Returns an object containing staking-related information.");

    uint64_t nWeight = 0;
    if (pwalletMain)
        nWeight = pwalletMain->GetStakeWeight();

    uint64_t nNetworkWeight = GetPoSKernelPS();
    bool staking = nLastCoinStakeSearchInterval && nWeight && (GetAdjustedTime() - nLastCoinStakeSearchTime < 60);
    uint64_t nExpectedTime = staking ? (Params().TargetSpacing() * nNetworkWeight / nWeight) : 0;

    UniValue obj(UniValue::VOBJ);

    obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
    obj.push_back(Pair("staking", staking));
    obj.push_back(Pair("errors", GetWarnings("statusbar")));

    obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
    obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
    obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));

    obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(chainActive.Tip(), true))));
    obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
    obj.push_back(Pair("last-search-time", (int)nLastCoinStakeSearchTime));

    obj.push_back(Pair("weight", (uint64_t)nWeight));
    obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));

    obj.push_back(Pair("expectedtime", nExpectedTime));

    return obj;
}

UniValue checkkernel(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "checkkernel [{\"txid\":txid,\"vout\":n},...] [createblocktemplate=false]\n"
            "Check if one of given inputs is a kernel input at the moment.\n");

    RPCTypeCheck(params, list_of(UniValue::VARR)(UniValue::VBOOL));

    UniValue inputs = params[0].get_array();
    bool fCreateBlockTemplate = params.size() > 1 ? params[1].get_bool() : false;

    if (vNodes.empty())
        throw JSONRPCError(-9, "Metrix is not connected!");

    if (IsInitialBlockDownload())
        throw JSONRPCError(-10, "Metrix is downloading blocks...");

    COutPoint kernel;
    CBlockIndex* pindexPrev = chainActive.Tip();
    unsigned int nBits = GetNextTargetRequired(pindexPrev, true);
    int64_t nTime = GetAdjustedTime();
    nTime &= ~STAKE_TIMESTAMP_MASK;

    for (unsigned int idx = 0; idx < inputs.size(); idx++) {
        const UniValue& input = inputs[idx];
        const UniValue& o = input.get_obj();

        const UniValue& txid_v = find_value(o, "txid");
        if (!txid_v.isStr())
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
        string txid = txid_v.get_str();
        if (!IsHex(txid))
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");

        const UniValue& vout_v = find_value(o, "vout");
        if (!vout_v.isNum())
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
        int nOutput = vout_v.get_int();
        if (nOutput < 0)
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");

        COutPoint cInput(uint256(txid), nOutput);
        if (CheckKernel(pindexPrev, nBits, nTime, cInput)) {
            kernel = cInput;
            break;
        }
    }

    UniValue result(UniValue::VOBJ);
    result.push_back(Pair("found", !kernel.IsNull()));

    if (kernel.IsNull())
        return result;

    UniValue oKernel(UniValue::VOBJ);;
    oKernel.push_back(Pair("txid", kernel.hash.GetHex()));
    oKernel.push_back(Pair("vout", (int64_t)kernel.n));
    oKernel.push_back(Pair("time", nTime));
    result.push_back(Pair("kernel", oKernel));

    if (!fCreateBlockTemplate)
        return result;
    CReserveKey reservekey(pwalletMain);
    CAmount nFees;
    auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey, pwalletMain, true));
    CBlock* pblock = &pblocktemplate->block; //! pointer for convenience
    pblock->nTime = pblock->vtx[0].nTime = nTime;

    CDataStream ss(SER_DISK, PROTOCOL_VERSION);
    ss << *pblock;

    result.push_back(Pair("blocktemplate", HexStr(ss.begin(), ss.end())));
    result.push_back(Pair("blocktemplatefees", nFees));

    CPubKey pubkey;
    result.push_back(Pair("blocktemplatesignkey", HexStr(pubkey)));

    return result;
}

// NOTE: Unlike wallet RPC (which use BTC values), mining RPCs follow GBT (BIP 22) in using satoshi amounts
UniValue prioritisetransaction(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() != 3)
        throw runtime_error(
            "prioritisetransaction <txid> <priority delta> <fee delta>\n"
            "Accepts the transaction into mined blocks at a higher (or lower) priority\n"
            "\nArguments:\n"
            "1. \"txid\"       (string, required) The transaction id.\n"
            "2. priority delta (numeric, required) The priority to add or subtract.\n"
            "                  The transaction selection algorithm considers the tx as it would have a higher priority.\n"
            "                  (priority of a transaction is calculated: coinage * value_in_satoshis / txsize) \n"
            "3. fee delta      (numeric, required) The fee value (in satoshis) to add (or subtract, if negative).\n"
            "                  The fee is not actually paid, only the algorithm for selecting transactions into a block\n"
            "                  considers the transaction as it would have paid a higher (or lower) fee.\n"
            "\nResult\n"
            "true              (boolean) Returns true\n"
            "\nExamples:\n"
            + HelpExampleCli("prioritisetransaction", "\"txid\" 0.0 10000")
            + HelpExampleRpc("prioritisetransaction", "\"txid\", 0.0, 10000")
        );

    uint256 hash = ParseHashStr(params[0].get_str(), "txid");
    CAmount nAmount = params[2].get_int64();

    mempool.PrioritiseTransaction(hash, params[0].get_str(), params[1].get_real(), nAmount);
    return true;
}

UniValue getblocktemplate(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() > 1)
        throw runtime_error(
            "getblocktemplate [params]\n"
            "Returns data needed to construct a block to work on:\n"
            "  \"version\" : block version\n"
            "  \"previousblockhash\" : hash of current highest block\n"
            "  \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
            "  \"coinbaseaux\" : data that should be included in coinbase\n"
            "  \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
            "  \"target\" : hash target\n"
            "  \"mintime\" : minimum timestamp appropriate for next block\n"
            "  \"curtime\" : current timestamp\n"
            "  \"mutable\" : list of ways the block template may be changed\n"
            "  \"noncerange\" : range of valid nonces\n"
            "  \"sigoplimit\" : limit of sigops in blocks\n"
            "  \"sizelimit\" : limit of block size\n"
            "  \"bits\" : compressed target of next block\n"
            "  \"height\" : height of the next block\n"
            "See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");

    std::string strMode = "template";
    UniValue lpval = NullUniValue;
    if (params.size() > 0) {
        const UniValue& oparam = params[0].get_obj();
        const UniValue& modeval = find_value(oparam, "mode");
        if (modeval.isStr())
            strMode = modeval.get_str();
        else if (modeval.isNull())
        {
            /* Do nothing */
        }
        else
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
        lpval = find_value(oparam, "longpollid");
    }

    if (strMode != "template")
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");

    if (vNodes.empty())
        throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Metrix is not connected!");

    //! if (IsInitialBlockDownload())
    //!     throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Metrix is downloading blocks...");

    if (chainActive.Height() >= Params().LastPOWBlock())
        throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");

    static unsigned int nTransactionsUpdatedLast;
    if (!lpval.isNull())
    {
        //! Wait to respond until either the best block changes, OR a minute has passed and there are more transactions
        uint256 hashWatchedChain;
        boost::system_time checktxtime;
        unsigned int nTransactionsUpdatedLastLP;

        if (lpval.isStr())
        {
            //! Format: <hashBestChain><nTransactionsUpdatedLast>
            std::string lpstr = lpval.get_str();
            hashWatchedChain.SetHex(lpstr.substr(0, 64));
            nTransactionsUpdatedLastLP = atoi64(lpstr.substr(64));
        } else {
            //! NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier
            hashWatchedChain = chainActive.Tip()->GetBlockHash();
            nTransactionsUpdatedLastLP = nTransactionsUpdatedLast;
        }

        //! Release the wallet and main lock while waiting
#ifdef ENABLE_WALLET
        if (pwalletMain)
            LEAVE_CRITICAL_SECTION(pwalletMain->cs_wallet);
#endif
        LEAVE_CRITICAL_SECTION(cs_main);
        {
            checktxtime = boost::get_system_time() + boost::posix_time::minutes(1);

            boost::unique_lock<boost::mutex> lock(csBestBlock);
            while (chainActive.Tip()->GetBlockHash() == hashWatchedChain && IsRPCRunning()) {
                if (!cvBlockChange.timed_wait(lock, checktxtime)) {
                    //! Timeout: Check transactions for update
                    if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLastLP)
                        break;
                    checktxtime += boost::posix_time::seconds(10);
                }
            }
        }
        ENTER_CRITICAL_SECTION(cs_main);
#ifdef ENABLE_WALLET
        if (pwalletMain)
            ENTER_CRITICAL_SECTION(pwalletMain->cs_wallet);
#endif

        if (!IsRPCRunning())
            throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Shutting down");
        //! TODO: Maybe recheck connections/IBD and (if something wrong) send an expires-immediately template to stop miners?
    }

    //! Update block
    static CBlockIndex* pindexPrev;
    static int64_t nStart;
    static CBlockTemplate* pblocktemplate;
    if (pindexPrev != chainActive.Tip() ||
        (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) {
        //! Clear pindexPrev so future calls make a new block, despite any failures from here on
        pindexPrev = NULL;

        //! Store the chainActive.Tip() used before CreateNewBlock, to avoid races
        nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
        CBlockIndex* pindexPrevNew = chainActive.Tip();
        nStart = GetTime();

        //! Create new block
        if (pblocktemplate) {
            delete pblocktemplate;
            pblocktemplate = NULL;
        }
        CScript scriptDummy = CScript() << OP_TRUE;
        pblocktemplate = CreateNewBlock(scriptDummy, pwalletMain, false);
        if (!pblocktemplate)
            throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");

        //! Need to update only after we know CreateNewBlock succeeded
        pindexPrev = pindexPrevNew;
    }
    CBlock* pblock = &pblocktemplate->block; //! pointer for convenience

    //! Update nTime
    UpdateTime(*pblock, pindexPrev);
    pblock->nNonce = 0;

    UniValue transactions(UniValue::VARR);
    map<uint256, int64_t> setTxIndex;
    int i = 0;

    BOOST_FOREACH (CTransaction& tx, pblock->vtx) {
        uint256 txHash = tx.GetHash();
        setTxIndex[txHash] = i++;

        if (tx.IsCoinBase() || tx.IsCoinStake())
            continue;

        UniValue entry(UniValue::VOBJ);

        entry.push_back(Pair("data", EncodeHexTx(tx)));

        entry.push_back(Pair("hash", txHash.GetHex()));

        UniValue deps(UniValue::VARR);
        BOOST_FOREACH (const CTxIn& in, tx.vin) {
            if (setTxIndex.count(in.prevout.hash))
                deps.push_back(setTxIndex[in.prevout.hash]);
        }
        entry.push_back(Pair("depends", deps));
        int index_in_template = i - 1;
        entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template]));
        entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template]));
        transactions.push_back(entry);
    }

    UniValue aux(UniValue::VOBJ);
    aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));

    uint256 hashTarget = uint256().SetCompact(pblock->nBits);

    static UniValue aMutable(UniValue::VARR);
    if (aMutable.empty()) {
        aMutable.push_back("time");
        aMutable.push_back("transactions");
        aMutable.push_back("prevblock");
    }

    UniValue result(UniValue::VOBJ);
    result.push_back(Pair("version", pblock->nVersion));
    result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
    result.push_back(Pair("transactions", transactions));
    result.push_back(Pair("coinbaseaux", aux));
    result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
    result.push_back(Pair("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)));
    result.push_back(Pair("target", hashTarget.GetHex()));
    result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit() + 1));
    result.push_back(Pair("mutable", aMutable));
    result.push_back(Pair("noncerange", "00000000ffffffff"));
    result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
    result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
    result.push_back(Pair("curtime", pblock->GetBlockTime()));
    result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
    result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight + 1)));

    return result;
}

UniValue estimatefee(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "estimatefee nblocks\n"
            "\nEstimates the approximate fee per kilobyte\n"
            "needed for a transaction to begin confirmation\n"
            "within nblocks blocks.\n"
            "\nArguments:\n"
            "1. nblocks     (numeric)\n"
            "\nResult:\n"
            "n :    (numeric) estimated fee-per-kilobyte\n"
            "\n"
            "-1.0 is returned if not enough transactions and\n"
            "blocks have been observed to make an estimate.\n"
            "\nExample:\n" +
            HelpExampleCli("estimatefee", "6"));

    RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));

    int nBlocks = params[0].get_int();
    if (nBlocks < 1)
        nBlocks = 1;

    CFeeRate feeRate = mempool.estimateFee(nBlocks);
    if (feeRate == CFeeRate(0))
        return -1.0;

    return ValueFromAmount(feeRate.GetFeePerK());
}

UniValue estimatepriority(const UniValue& params, bool fHelp)
{
    if (fHelp || params.size() != 1)
        throw runtime_error(
            "estimatepriority nblocks\n"
            "\nEstimates the approximate priority\n"
            "a zero-fee transaction needs to begin confirmation\n"
            "within nblocks blocks.\n"
            "\nArguments:\n"
            "1. nblocks     (numeric)\n"
            "\nResult:\n"
            "n :    (numeric) estimated priority\n"
            "\n"
            "-1.0 is returned if not enough transactions and\n"
            "blocks have been observed to make an estimate.\n"
            "\nExample:\n" +
            HelpExampleCli("estimatepriority", "6"));

    RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));

    int nBlocks = params[0].get_int();
    if (nBlocks < 1)
        nBlocks = 1;

    return mempool.estimatePriority(nBlocks);
}


text:
#ifndef ALEPH_PERSISTENT_HOMOLOGY_EXTENDED_PERSISTENCE_HIERARCHY__
#define ALEPH_PERSISTENT_HOMOLOGY_EXTENDED_PERSISTENCE_HIERARCHY__

#include <algorithm>
#include <map>
#include <stdexcept>
#include <set>
#include <vector>

#include <boost/bimap.hpp>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/breadth_first_search.hpp>

#include <aleph/persistentHomology/PersistencePairing.hh>

#include <aleph/topology/SimplicialComplex.hh>
#include <aleph/topology/UnionFind.hh>

namespace aleph
{

namespace detail
{

using AdjacencyGraph = boost::adjacency_list<
  boost::vecS,
  boost::vecS,
  boost::undirectedS,
  boost::no_property,
  boost::no_property>;

using SizeType = std::size_t;

/** Extracts the adjacency graph of a simplicial complex */
template <class Simplex>
std::pair<boost::bimap<typename Simplex::VertexType, SizeType>, AdjacencyGraph> extractZeroDimensionalAdjacencyGraph( const topology::SimplicialComplex<Simplex>& S )
{
  AdjacencyGraph adjacencyGraph;

  using Vertex           = typename Simplex::VertexType;
  using VertexDescriptor = boost::graph_traits<AdjacencyGraph>::vertex_descriptor;
  using bimap_type       = boost::bimap<Vertex, SizeType>;

  bimap_type indices;
  std::map<Vertex, VertexDescriptor> vdm;

  SizeType vertexIndex = 0;

  for( auto it = S.begin_dimension(); it != S.end_dimension(); ++it )
  {
    // Vertices
    if( it->dimension() == 0 )
    {
      indices.insert( typename bimap_type::value_type( *it->begin(), vertexIndex++ ) );

      auto vertex         = boost::add_vertex( adjacencyGraph );
      vdm[ *it->begin() ] = vertex;
    }

    // Edges
    else if( it->dimension() == 1 )
    {
      auto&& edge = *it;

      auto u = *( edge.begin()     );
      auto v = *( edge.begin() + 1 );

      // It is possible that the simplicial complex, being a _part_ of
      // a larger filtration, contains edges for which no vertices are
      // available.
      if( S.contains(u) && S.contains(v) )
      {
        boost::add_edge( vdm.at(u),
                         vdm.at(v),
                         adjacencyGraph );
      }
    }
  }

  return std::make_pair( indices, adjacencyGraph );
}

} // namespace detail

/**
  @class ExtendedPersistenceHierarchy
  @brief Functor for calculating the extended persistence hierarchy

  This class is a functor that calculates the extended persistence
  hierarchy of a given simplicial complex. The complex is supposed
  to be in filtration order. Currently, only features in dimension
  zero are supported by this functor.

  For more information, please refer to the paper

    Hierarchies and Ranks for Persistence Pairs
    Bastian Rieck, Heike Leitte, and Filip Sadlo
    Proceedings of TopoInVis 2017, Japan
*/

template <class Simplex> class ExtendedPersistenceHierarchy
{
public:
  using SimplicialComplex = topology::SimplicialComplex<Simplex>;
  using Vertex            = typename Simplex::VertexType;
  using SimplexPairing    = PersistencePairing<Vertex>;

  using EdgeType          = std::pair<Vertex, Vertex>;
  using Edges             = std::vector<EdgeType>;

private:

  /**
    Helper function for 'tagging' all edges in the simplicial complex
    with the next critical point. This is a very slow---but simple---
    way of decomposing the domain.
  */

  std::map<Simplex, Vertex> tagEdges( const SimplicialComplex& S )
  {
    std::set<Vertex> vertices;
    S.vertices( std::inserter( vertices, vertices.begin() ) );

    std::map<Vertex, Vertex>  criticalPointMapVertices;  // critical point map kept along with Union--Find structure
    std::map<Simplex, Vertex> criticalPointMapSimplices; // critical point map on edge (simplex) basis (return value)

    for( auto&& vertex : vertices )
      criticalPointMapVertices[vertex] = vertex;

    for( auto&& simplex : S )
    {
      if( simplex.dimension() != 1 )
        continue;

      Vertex u = *( simplex.begin() );
      Vertex v = *( simplex.begin() + 1 );

      auto youngerComponent = u;
      auto olderComponent   = v;

      if( youngerComponent != olderComponent )
      {
        auto index1 = S.index( Simplex(youngerComponent) );
        auto index2 = S.index( Simplex(olderComponent)   );

        if( index1 < index2 )
          std::swap( youngerComponent, olderComponent );

        Simplex creator = *( S.find( Simplex( youngerComponent ) ) );

        if( creator.data() == simplex.data() )
          criticalPointMapVertices[ youngerComponent ] = criticalPointMapVertices[ olderComponent ];
      }

      criticalPointMapSimplices[ simplex ] = criticalPointMapVertices[ olderComponent ];
    }

    return criticalPointMapSimplices;
  }

  /**
    Calculates the interlevel set of a given simplicial complex. This
    means extracting a subset in which the assigned weight of  _each_
    simplex lies between the upper and lower value.

    The function will return the interlevel set as a simplicial complex,
    as well as a Union--Find data structure for connectivity queries.
  */

  std::pair< SimplicialComplex, topology::UnionFind<Vertex> >
    makeInterlevelSet( typename Simplex::DataType lower, typename Simplex::DataType upper,
                       const SimplicialComplex& S )
  {
    if( lower > upper )
      std::swap( lower, upper );

    std::vector<Simplex> simplices;

    std::copy_if( S.begin(), S.end(),
                  std::back_inserter( simplices ),
                  [&lower, &upper] ( const Simplex& s )
                  {
                    return s.data() >= lower && s.data() <= upper && s.dimension() <= 1;
                  } );

    SimplicialComplex K = SimplicialComplex( simplices.begin(),
                                             simplices.end() );

    // -----------------------------------------------------------------
    //
    // Find all 'proper' vertices in the simplicial complex. It is
    // possible that not all of them exist as 0-simplices, though.

    std::set<Vertex> vertices;

    for( auto&& simplex : simplices )
    {
      if( simplex.dimension() == 0 )
        vertices.insert( *simplex.begin() );
    }

    // Traversal -------------------------------------------------------

    topology::UnionFind<Vertex> uf( vertices.begin(), vertices.end()  );

    for( auto&& simplex : K )
    {
      if( simplex.dimension() == 1 )
      {
        Vertex u = *( simplex.begin() );
        Vertex v = *( simplex.begin() + 1 );

        if( !uf.contains( u ) || !uf.contains( v ) )
          continue;

        auto youngerComponent = uf.find( u );
        auto olderComponent   = uf.find( v );

        if( youngerComponent == olderComponent )
          continue;

        auto index1 = S.index( Simplex( youngerComponent ) );
        auto index2 = S.index( Simplex( olderComponent ) );

        if( index1 < index2 )
          std::swap( youngerComponent, olderComponent );

        uf.merge( youngerComponent, olderComponent );
      }
    }

    return std::make_pair( K, uf );
  }

public:

  /**
    Given a simplicial complex, calculates its 0-dimensional persistent
    homology and the corresponding extended persistence hierarchy. As a
    result, this will return a simplex pairing and all the edges of the
    pairing. Edges refer to indices in the original simplicial complex.
  */

  std::pair<SimplexPairing, Edges> operator()( const SimplicialComplex& simplicialComplex )
  {
    using namespace detail;

    // Extract {0,1}-simplices -----------------------------------------

    // Note that there is a range predicate for the simplicial complex class
    // that does essentially the same. However, the predicate is not stable
    // with respect to the filtration of the simplicial complex. Thus, to
    // extract the desired simplices, the internal function cannot be used.

    std::vector<Simplex> simplices;

    std::copy_if( simplicialComplex.begin(), simplicialComplex.end(),
                  std::back_inserter( simplices ),
                  [] ( const Simplex& s ) { return s.dimension() <= 1; } );

    SimplicialComplex S = SimplicialComplex( simplices.begin(),
                                             simplices.end() );

    // Persistence calculation -----------------------------------------

    std::set<Vertex> vertices;
    S.vertices( std::inserter( vertices,
                               vertices.begin() ) );

    Edges edges;

    // Pairs indices of critical vertices. This may be used later on to
    // obtain a persistence diagram. Using a pairing is advantageous as
    // it does not operate on weights but on indices, which are unique.
    SimplexPairing pairing;

    // This map contains a simple decomposition of the domain in terms
    // of the 'next' critical point.
    //
    // In a proper---and faster---implementation, Morse--Smale complex
    // calculations could be used.
    auto edgeToCriticalPoint = tagEdges( S );

    // Keeps track of the critical points that are created along with
    // hierarchy. This is the key difference to the regular hierarchy
    // and permits the hierarchy to distinguish data sets even though
    // their persistence diagram coincides.
    std::map<Vertex, Vertex> vertexToCriticalPoint;
    for( auto&& vertex : vertices )
      vertexToCriticalPoint[vertex] = vertex;

    // Required in order to obtain persistence pairs along with the
    // edges of the persistence hierarchy.
    topology::UnionFind<Vertex> uf( vertices.begin(), vertices.end() );

    for( auto&& simplex : S )
    {
      // Only edges can destroy a component
      if( simplex.dimension() != 1 )
        continue;

      auto u = *( simplex.begin() );
      auto v = *( simplex.begin() + 1 );

      // ---------------------------------------------------------------
      //
      // Ensure that the younger component is _always_ the first
      // component. A component is younger if its representative
      // vertex precedes the other vertex in the filtration.
      auto youngerComponent = uf.find( u );
      auto olderComponent   = uf.find( v );

      // If the component has already been merged by some other edge, we are
      // not interested in it any longer.
      if( youngerComponent == olderComponent )
        continue;

      {
        auto index1 = S.index( Simplex(youngerComponent) );
        auto index2 = S.index( Simplex(olderComponent)   );

        // The younger component has the _larger_ index as it is born _later_
        // in the filtration.
        if( index1 < index2 )
          std::swap( youngerComponent, olderComponent );
      }

      // Prepare information about creators ----------------------------
      //
      // Creator simplex for the simplex pairing below. I know that this
      // simplex must exist in the complex so I don't check for iterator
      // validity here.
      auto youngerCreator         = *( S.find( Simplex( youngerComponent ) ) );
      auto olderCreator           = *( S.find( Simplex( olderComponent ) ) );
      auto youngerCriticalSimplex = *( S.find( Simplex( vertexToCriticalPoint[youngerComponent] ) ) );
      auto olderCriticalSimplex   = *( S.find( Simplex( vertexToCriticalPoint[olderComponent]   ) ) );

      // Zero-persistence information; assign critical point of the
      // older component directly. This ensures that we are able to
      // obtain a proper decomposition.
      if( youngerCreator.data() == simplex.data() )
        vertexToCriticalPoint[youngerComponent] = olderComponent;
      else
      {
        // Ensures that the oldest, highest/lowest critical simplex is
        // being used to calculate the interlevel set. Else, it may be
        // impossible for a critical point to be reached.
        if( S.index( youngerCriticalSimplex ) < S.index( olderCriticalSimplex ) )
          std::swap( youngerCriticalSimplex, olderCriticalSimplex );

        auto clsPair
          = makeInterlevelSet(
              olderCriticalSimplex.data(), simplex.data(),
              S );

        bool inSameComponent
          =   ( clsPair.second.contains( *olderCriticalSimplex.begin() ) && clsPair.second.contains( *youngerCriticalSimplex.begin() ) )
           && ( clsPair.second.find( *olderCriticalSimplex.begin() ) == clsPair.second.find( *youngerCriticalSimplex.begin() ) );

        if( inSameComponent )
        {
          using V = boost::graph_traits<AdjacencyGraph>::vertex_descriptor;

          boost::bimap<Vertex, SizeType> vim;
          AdjacencyGraph G;

          std::tie( vim, G )
            = extractZeroDimensionalAdjacencyGraph( clsPair.first );

          std::vector<V> p( boost::num_vertices( G ) );

          auto u = vim.left.at( *olderCriticalSimplex.begin() );
          auto v = vim.left.at( *youngerCriticalSimplex.begin() );
          p[u]   = u;

          boost::breadth_first_search( G,
                                       boost::vertex( u, G ),
                                       boost::visitor(
                                        boost::make_bfs_visitor(
                                          boost::record_predecessors( &p[0], boost::on_tree_edge() ) ) ) );

          std::set<Vertex> criticalPoints;

          while( true )
          {
            auto parent = p.at( v );
            auto s      = *S.find( Simplex( {vim.right.at(v),vim.right.at(parent)} ) );

            if( parent == v )
              break;

            v = parent;

            // Find out which critical point the identified edge
            // belongs to.
            criticalPoints.insert( edgeToCriticalPoint.at( s ) );
          }

          // Exactly two critical points (i.e. the ones we were
          // looking for); hence, insert younger component as a
          // child of the youngest critical point.
          if( criticalPoints.size() == 2 )
          {
            edges.push_back( std::make_pair(
              vertexToCriticalPoint[olderComponent],
              youngerComponent )
            );
          }

          // More critical points; connect the critical points
          // according to the usual persistence hierarchy.
          else
          {
            edges.push_back( std::make_pair(
              olderComponent,
              youngerComponent )
            );
          }
        }

        // Not in the same component; connect the critical points
        // according to the usual persistence hierarchy.
        else
        {
          edges.push_back( std::make_pair(
            olderComponent,
            youngerComponent )
          );
        }

        // The youngest critical point along the current connected
        // component has been changed.
        vertexToCriticalPoint[olderComponent] = youngerComponent;
      }

      pairing.add( Vertex( S.index( Simplex( youngerCreator ) ) ),
                   Vertex( S.index( simplex ) ) );

      uf.merge( youngerComponent,
                olderComponent );
    }

    // Add features of infinite persistence to the pairing -------------

    std::set<Vertex> roots;
    uf.roots( std::inserter( roots, roots.begin() ) );

    for( auto&& root : roots )
      pairing.add( Vertex( S.index( root ) ) );

    return std::make_pair( pairing, edges );
  }
};

} // namespace aleph

#endif

ext: hh

max_stars_repo_name: eudoxos/Aleph

max_issues_repo_name: eudoxos/Aleph

max_forks_repo_name: eudoxos/Aleph


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

#include <boost/hana/accessors.hpp>
#include <boost/hana/adapt_struct.hpp>
#include <boost/hana/assert.hpp>
#include <boost/hana/core/to.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/find.hpp>
#include <boost/hana/first.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/not_equal.hpp>
#include <boost/hana/optional.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/string.hpp>
#include <boost/hana/transform.hpp>
#include <boost/hana/tuple.hpp>

#include <string>
namespace hana = boost::hana;

namespace ns {
    struct Person {
        std::string name;
        int age;
    };
}

BOOST_HANA_ADAPT_STRUCT(ns::Person,
    name,
    age
);

// The member names are hana::strings:
auto names = hana::transform(hana::accessors<ns::Person>(), hana::first);
BOOST_HANA_CONSTANT_CHECK(
    names == hana::make_tuple(BOOST_HANA_STRING("name"), BOOST_HANA_STRING("age"))
);

int main() {
    ns::Person john{"John", 30}, bob{"Bob", 40};
    BOOST_HANA_RUNTIME_CHECK(hana::equal(john, john));
    BOOST_HANA_RUNTIME_CHECK(hana::not_equal(john, bob));

    BOOST_HANA_RUNTIME_CHECK(hana::find(john, BOOST_HANA_STRING("name")) == hana::just("John"));
    BOOST_HANA_RUNTIME_CHECK(hana::find(john, BOOST_HANA_STRING("age")) == hana::just(30));
    BOOST_HANA_CONSTANT_CHECK(hana::find(john, BOOST_HANA_STRING("foo")) == hana::nothing);

    BOOST_HANA_RUNTIME_CHECK(hana::to_tuple(john) == hana::make_tuple(
        hana::make_pair(BOOST_HANA_STRING("name"), "John"),
        hana::make_pair(BOOST_HANA_STRING("age"), 30)
    ));

    BOOST_HANA_RUNTIME_CHECK(hana::to_map(john) == hana::make_map(
        hana::make_pair(BOOST_HANA_STRING("name"), "John"),
        hana::make_pair(BOOST_HANA_STRING("age"), 30)
    ));
}


text:
// Copyright (C) 2015, Pawel Tomulik <ptomulik@meil.pw.edu.pl>
//
// 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)
#define BOOST_TEST_MODULE test_txpl_vm_eval_binary_neq

#include <txpl/test_config.hpp>
#include <boost/test/unit_test.hpp>

#ifndef TXPL_TEST_SKIP_VM_EVAL_BINARY_NEQ

#include <txpl/vm/eval_binary_op.hpp>
#include <txpl/vm/basic_types.hpp>
#include <txpl/vm/value.hpp>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/get.hpp>

#include <type_traits>

using namespace txpl::vm;
typedef basic_types<>::char_type   char_type;
typedef basic_types<>::int_type    int_type;
typedef basic_types<>::bool_type   bool_type;
typedef basic_types<>::real_type   real_type;
typedef basic_types<>::string_type string_type;
typedef basic_types<>::regex_type  regex_type;
typedef basic_types<>::blank_type  blank_type;
typedef array<value<> >            array_type;
typedef object<value<> >           object_type;

BOOST_AUTO_TEST_CASE(char__neq__char)
{
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'\0'};
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (char_type{'\0'} != char_type{'\0'}));
  }
}
BOOST_AUTO_TEST_CASE(char__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'\0'};
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (char_type{'\0'} != int_type{0}));
  }
}
BOOST_AUTO_TEST_CASE(char__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'\0'};
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (char_type{'\0'} != bool_type{false}));
  }
}
BOOST_AUTO_TEST_CASE(char__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'\0'};
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (char_type{'\0'} != real_type{0.0}));
  }
}
BOOST_AUTO_TEST_CASE(char__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'a'};
    const value<> v2 = string_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(char__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'a'};
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(char__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'a'};
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(char__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = char_type{'a'};
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

BOOST_AUTO_TEST_CASE(int__neq__char)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (int_type{0} != char_type{'\0'}));
  }
}
BOOST_AUTO_TEST_CASE(int__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (int_type{0} != int_type{0}));
  }
}
BOOST_AUTO_TEST_CASE(int__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (int_type{0} != bool_type{false}));
  }
}
BOOST_AUTO_TEST_CASE(int__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (int_type{0} != real_type{0.0}));
  }
}
BOOST_AUTO_TEST_CASE(int__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = string_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(int__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(int__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(int__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = int_type{0};
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

BOOST_AUTO_TEST_CASE(bool__neq__char)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (char_type{false} != bool_type{'\0'}));
  }
}
BOOST_AUTO_TEST_CASE(bool__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (bool_type{false} != int_type{0}));
  }
}
BOOST_AUTO_TEST_CASE(bool__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (bool_type{false} != bool_type{false}));
  }
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = bool_type{true};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{false};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (bool_type{false} != bool_type{true}));
  }
  {
    const value<> v1 = bool_type{true};
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{false};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (bool_type{true} != bool_type{false}));
  }
  {
    const value<> v1 = bool_type{true};
    const value<> v2 = bool_type{true};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{false};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (bool_type{true} != bool_type{true}));
  }
}
BOOST_AUTO_TEST_CASE(bool__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (bool_type{false} != bool_type{0.0}));
  }
}
BOOST_AUTO_TEST_CASE(bool__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = string_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(bool__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(bool__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(bool__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = bool_type{false};
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

BOOST_AUTO_TEST_CASE(real__neq__char)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (real_type{0.0} != char_type{'\0'}));
  }
}
BOOST_AUTO_TEST_CASE(real__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (real_type{0.0} != int_type{0}));
  }
}
BOOST_AUTO_TEST_CASE(real__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (real_type{0.0} != bool_type{false}));
  }
}
BOOST_AUTO_TEST_CASE(real__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{true};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (real_type{0.0} != real_type{0.0}));
  }
}
BOOST_AUTO_TEST_CASE(real__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = string_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(real__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(real__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(real__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = real_type{0.0};
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

BOOST_AUTO_TEST_CASE(string__neq__char)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type();
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(string__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type();
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(string__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type();
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(string__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type();
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(string__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type("asd");
    const value<> v2 = string_type("asd");
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{false};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (string_type("asd") != string_type("asd")));
  }
  {
    const value<> v1 = string_type("asd");
    const value<> v2 = string_type("qwe");
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    bool_type x = bool_type{false};
    BOOST_CHECK_NO_THROW(x = boost::get<bool_type>(r));
    BOOST_CHECK(x == (string_type("asd") != string_type("qwe")));
  }
}
BOOST_AUTO_TEST_CASE(string__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type();
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(string__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type();
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(string__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = string_type();
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

BOOST_AUTO_TEST_CASE(regex__neq__char)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(regex__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(regex__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(regex__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(regex__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = string_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(regex__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(regex__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(regex__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = regex_type();
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

BOOST_AUTO_TEST_CASE(array__neq__char)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(array__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(array__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(array__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(array__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = string_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(array__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(array__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    array_type x;
    BOOST_CHECK_NO_THROW(x = boost::get<array_type>(r));
    BOOST_CHECK_EQUAL(x.size(), 0);
  }
  {
    array_type a1(3);
    array_type a2(3);
    a2[0] = a1[0] = char_type{'a'};
    a2[1] = a1[1] = int_type{100};
    a2[2] = real_type{321.0}; a1[2] = real_type{.123};
    const value<> v1 = a1;
    const value<> v2 = a2;
    r = blank_type();
    BOOST_CHECK(boost::apply_visitor(op, v1, v2));
    array_type x;
    BOOST_CHECK_NO_THROW(x = boost::get<array_type>(r));
    BOOST_CHECK_EQUAL(x.size(), 3);
    BOOST_CHECK(!boost::get<bool_type>(x[0]));
    BOOST_CHECK(!boost::get<bool_type>(x[1]));
    BOOST_CHECK(boost::get<bool_type>(x[2]));
  }
  {
    array_type a1(3);
    array_type a2(2);
    a2[0] = a1[0] = char_type{'a'};
    a2[1] = a1[1] = int_type{100};
    a1[2] = real_type{.123};
    const value<> v1 = a1;
    const value<> v2 = a2;
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(array__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = array_type();
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

BOOST_AUTO_TEST_CASE(object__neq__char)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = char_type{'\0'};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(object__neq__int)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = int_type{0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(object__neq__bool)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = bool_type{false};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(object__neq__real)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = real_type{0.0};
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(object__neq__string)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = string_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(object__neq__regex)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = regex_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(object__neq__array)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = array_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}
BOOST_AUTO_TEST_CASE(object__neq__object)
{
  using namespace txpl::vm;
  value<> r;
  auto op = eval_binary_op<op_t::neq_>(r);
  {
    const value<> v1 = object_type();
    const value<> v2 = object_type();
    r = blank_type();
    BOOST_CHECK(!boost::apply_visitor(op, v1, v2));
    BOOST_CHECK_NO_THROW(boost::get<blank_type>(r));
  }
}

#else
BOOST_AUTO_TEST_CASE(dummy)
{
  BOOST_CHECK(true);
}
#endif

max_stars_repo_name: ptomulik/txpl

max_issues_repo_name: ptomulik/txpl

max_forks_repo_name: ptomulik/txpl


text:
#ifndef TCPV4SERVER_HPP
#define TCPV4SERVER_HPP

#include "utils.hpp"
#include "wireformat.hpp"
#include <boost/noncopyable.hpp>

namespace tcpv4
{
    struct ServerParameters {
        std::string mAddress;
        uint16_t    mPort;
    };

    class Connection : boost::noncopyable
    {
    private:
        int mTCPSocket;

    public:
        Connection( int s )
	    : mTCPSocket( s )
        {
        }
        ~Connection();

        PacketData receive( int size );

        ssize_t send( const PacketData & );
        ssize_t send( const uint8_t *begin, const uint8_t *end );
        ssize_t send( const uint8_t *data, int size );
        ssize_t send( const WireFormat & );

        void shutdownSend();
        void shutdownReceive();
    };

    typedef std::shared_ptr<Connection> ConnectionPtr;

    class Server
    {
    private:
        int mTCPSocket;

    public:
        Server( const ServerParameters &p );
        ~Server();

        ConnectionPtr acceptConnection();
    };
}

#endif


text:
/****************************************************************************
*
*    Copyright (c) 2019 Vivante Corporation
*
*    Permission is hereby granted, free of charge, to any person obtaining a
*    copy of this software and associated documentation files (the "Software"),
*    to deal in the Software without restriction, including without limitation
*    the rights to use, copy, modify, merge, publish, distribute, sublicense,
*    and/or sell copies of the Software, and to permit persons to whom the
*    Software is furnished to do so, subject to the following conditions:
*
*    The above copyright notice and this permission notice shall be included in
*    all copies or substantial portions of the Software.
*
*    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
*    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
*    DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/

#include "NpuTensorHandler.hpp"

#include <string>
#include <armnn/TypesUtils.hpp>

#include <boost/log/trivial.hpp>

namespace armnn
{
// VSI NPU TensorHandler
void NpuTensorHandler::SetOperandId(unsigned int id)
{
    m_OperandId = id;
}

void NpuTensorHandler::Allocate()
{
}

TensorShape NpuTensorHandler::GetStrides() const
{
    TensorShape shape(m_TensorInfo.GetShape());
    auto size = GetDataTypeSize(m_TensorInfo.GetDataType());
    auto runningSize = size;
    std::vector<unsigned int> strides(shape.GetNumDimensions());
    auto lastIdx = shape.GetNumDimensions()-1;
    for (unsigned int i=0; i < lastIdx ; i++)
    {
        strides[lastIdx-i] = runningSize;
        runningSize *= shape[lastIdx-i];
    }
    strides[0] = runningSize;
    return TensorShape(shape.GetNumDimensions(), strides.data());
}

void NpuTensorHandler::CopyOutTo(void* memory) const {
    getMemoryReady();
    if (m_ExternalMem) {
        std::memcpy(memory, m_ExternalMem, m_TensorInfo.GetNumBytes());
    } else {
        std::memcpy(memory, m_Memory.get(), m_TensorInfo.GetNumBytes());
    }
}

void NpuTensorHandler::CopyInFrom(const void* memory) {
    getMemoryReady();
    if (m_ExternalMem) {
        std::memcpy(m_ExternalMem, memory, m_TensorInfo.GetNumBytes());
    } else {
        std::memcpy(m_Memory.get(), memory, m_TensorInfo.GetNumBytes());
    }
}

TensorShape NpuTensorHandler::GetShape() const
{
    return m_TensorInfo.GetShape();
}

void* NpuTensorHandler::Map(bool blocking)
{
    getMemoryReady();
    return m_ExternalMem ? m_ExternalMem : static_cast<void*>(m_Memory.get());
}

const void* NpuTensorHandler::Map(bool blocking) const
{
    getMemoryReady();
    return m_ExternalMem ? m_ExternalMem : static_cast<const void*>(m_Memory.get());
}

void* NpuTensorHandler::GetMemArea()
{
    return m_Memory.get();
}

void NpuTensorHandler::Unmap() const
{}

void NpuTensorHandler::Unmap()
{}

void NpuTensorHandler::getMemoryReady() const {
    bool IsInputTensor = m_ModelStack.empty();
    // TODO: InputHandle can be already allocated memory
    // If InputHandle already allocated memory: means it allocated by previous sub-graph allocated on our backend.
    // In this case, we should not be here because we didn't ask memory allocation internally.
    if (IsInputTensor) {
        if (nullptr == m_ExternalMem) {
            m_Memory.reset(new uint8_t[m_TensorInfo.GetNumBytes()]);
            // Keep this track random caculation error issue
            BOOST_LOG_TRIVIAL(info) << "allocated memory at" << m_Memory.get()
                                    << ", size = " << m_TensorInfo.GetNumBytes();
        }
        return;
    }

    // For middle tensor handler
    if (m_Memory) {
        // "Warn-Start NN execution"
        if (!m_ModelShell) {
            assert(false);
            BOOST_LOG_TRIVIAL(debug) << "Model prepare failed: check previous log for error log";
            return;
        }
        BOOST_LOG_TRIVIAL(info) << "Warn-Start NN execution" ;
        m_ModelShell->Execute();
        return;
    }

    // Rest code for output handler
    if (m_ExternalMem) {
        // "Warn-Start NN execution"
        if (!m_ModelShell) {
            auto mergedModel = adaption::utils::MergeModels(m_ModelStack);
            m_ModelShell.reset(new ModelShell(std::move(mergedModel)));
            if (!m_ModelShell) {
                assert(false);
                BOOST_LOG_TRIVIAL(debug)
                    << "Model prepare failed: check previous log for error log";
                return;
            }
        }

        BOOST_LOG_TRIVIAL(info) << "Warn-Start NN execution" ;

        m_ModelShell->Execute();
        return;
    }

    m_Memory.reset(new uint8_t[m_TensorInfo.GetNumBytes()]);

    auto mergedModel = adaption::utils::MergeModels(m_ModelStack);

    // IAmLastHope means: I must construct ModelShell object and execute the model for other output
    // usually, the last accessed output is the "last hope"
    bool IAmLastHope = true;
    for (auto& outputHandle : mergedModel->second.second) {
        if (outputHandle != this && !outputHandle->m_Memory) {
            outputHandle->Map(true); // recursive call for all output
            IAmLastHope = false;
        }
    }

    if (IAmLastHope){ // Only execute model while access last output tensor
        m_ModelShell.reset(new ModelShell(std::move(mergedModel)));
        // finalModel ready to run
        m_ModelShell->Execute();
    } else { // find model shell object created by "Last Hope"
        for (auto& OutputHandle: mergedModel->second.second) {
            auto sharedModelShell = OutputHandle->shareModelShell();
            if (sharedModelShell) {
                m_ModelShell = sharedModelShell;
            }
        }
    }
}

MemorySourceFlags NpuTensorHandler::GetImportFlags() const {
    // only support malloc
    return static_cast<MemorySourceFlags>(MemorySource::Malloc);
}

bool NpuTensorHandler::Import(void* memory, MemorySource source) {
    if ((static_cast<MemorySourceFlags>(source) &
        static_cast<MemorySourceFlags>(MemorySource::Malloc)) != 0) {
        m_ExternalMem = memory;
        return true;
    } else {
        return false;
    }
}
}

max_stars_repo_name: phytec-mirrors/nn-imx

max_issues_repo_name: phytec-mirrors/nn-imx

max_forks_repo_name: phytec-mirrors/nn-imx


text:
#include "algorithm.h"

#include <boost/heap/binomial_heap.hpp>

using namespace HybridAStar;

float aStar(Node2D& start, Node2D& goal, Node2D* nodes2D, int width, int height, CollisionDetection& configurationSpace);
void updateH(Node3D& start, const Node3D& goal, Node2D* nodes2D, int width, int height, CollisionDetection& configurationSpace);
Node3D* dubinsShot(Node3D& start, const Node3D& goal, CollisionDetection& configurationSpace);

//###################################################
//                                    NODE COMPARISON
//###################################################
/*!
   \brief A structure to sort nodes in a heap structure
*/
struct CompareNodes {
  /// Sorting 3D nodes by increasing C value - the total estimated cost
  bool operator()(const Node3D* lhs, const Node3D* rhs) const {
    return lhs->getC() > rhs->getC();
  }
  /// Sorting 2D nodes by increasing C value - the total estimated cost
  bool operator()(const Node2D* lhs, const Node2D* rhs) const {
    return lhs->getC() > rhs->getC();
  }
};

//###################################################
//                                        3D A*
//###################################################
Node3D* Algorithm::hybridAStar(Node3D& start,
                               const Node3D& goal,
                               Node3D* nodes3D,
                               Node2D* nodes2D,
                               int width,
                               int height,
                               CollisionDetection& configurationSpace) {

  // PREDECESSOR AND SUCCESSOR INDEX
  int iPred, iSucc;
  float newG;
  // Number of possible directions, 3 for forward driving and an additional 3 for reversing
  int dir = Constants::reverse ? 6 : 3;
  // Number of iterations the algorithm has run for stopping based on Constants::iterations
  int iterations = 0;

  // OPEN LIST AS BOOST IMPLEMENTATION
  typedef boost::heap::binomial_heap<Node3D*, boost::heap::compare<CompareNodes>> priorityQueue;
  priorityQueue O;

  // update h value
  updateH(start, goal, nodes2D, width, height, configurationSpace);
  // mark start as open
  start.open();
  // push on priority queue aka open list
  O.push(&start);
  iPred = start.setIdx(width, height);
  nodes3D[iPred] = start;

  // NODE POINTER
  Node3D* nPred;
  Node3D* nSucc;

  // float max = 0.f;

  // continue until O empty
  while (!O.empty()) {
    // pop node with lowest cost from priority queue
    nPred = O.top();
    // set index
    iPred = nPred->setIdx(width, height);
    iterations++;

    // _____________________________
    // LAZY DELETION of rewired node
    // if there exists a pointer this node has already been expanded
    if (nodes3D[iPred].isClosed()) {
      // pop node from the open list and start with a fresh node
      O.pop();
      continue;
    }
    // _________________
    // EXPANSION OF NODE
    else if (nodes3D[iPred].isOpen()) {
      // add node to closed list
      nodes3D[iPred].close();
      // remove node from open list
      O.pop();

      // _________
      // GOAL TEST
      if (*nPred == goal || iterations > Constants::iterations) {
        // DEBUG
        return nPred;
      }

      // ____________________
      // CONTINUE WITH SEARCH
      else {
        // _______________________
        // SEARCH WITH DUBINS SHOT
        if (Constants::dubinsShot && nPred->isInRange(goal) && nPred->getPrim() < 3) {
          nSucc = dubinsShot(*nPred, goal, configurationSpace);

          if (nSucc != nullptr && *nSucc == goal) {
            //DEBUG
            // std::cout << "max diff " << max << std::endl;
            return nSucc;
          }
        }

        // ______________________________
        // SEARCH WITH FORWARD SIMULATION
        for (int i = 0; i < dir; i++) {
          // create possible successor
          nSucc = nPred->createSuccessor(i);
          // set index of the successor
          iSucc = nSucc->setIdx(width, height);

          // ensure successor is on grid and traversable
          if (nSucc->isOnGrid(width, height) && configurationSpace.isTraversable(nSucc)) {

            // ensure successor is not on closed list or it has the same index as the predecessor
            if (!nodes3D[iSucc].isClosed() || iPred == iSucc) {

              // calculate new G value
              nSucc->updateG();
              newG = nSucc->getG();

              // if successor not on open list or found a shorter way to the cell
              if (!nodes3D[iSucc].isOpen() || newG < nodes3D[iSucc].getG() || iPred == iSucc) {

                // calculate H value
                updateH(*nSucc, goal, nodes2D, width, height, configurationSpace);

                // if the successor is in the same cell but the C value is larger
                if (iPred == iSucc && nSucc->getC() > nPred->getC() + Constants::tieBreaker) {
                  delete nSucc;
                  continue;
                }
                // if successor is in the same cell and the C value is lower, set predecessor to predecessor of predecessor
                else if (iPred == iSucc && nSucc->getC() <= nPred->getC() + Constants::tieBreaker) {
                  nSucc->setPred(nPred->getPred());
                }

                if (nSucc->getPred() == nSucc) {
                  std::cout << "looping";
                }

                // put successor on open list
                nSucc->open();
                nodes3D[iSucc] = *nSucc;
                O.push(&nodes3D[iSucc]);
                delete nSucc;
              } else { delete nSucc; }
            } else { delete nSucc; }
          } else { delete nSucc; }
        }
      }
    }
  }

  if (O.empty()) {
    return nullptr;
  }

  return nullptr;
}

//###################################################
//                                        DUBINS SHOT
//###################################################

Node3D* dubinsShot(Node3D& start, const Node3D& goal, CollisionDetection& configurationSpace) {
  // start
  double q0[] = { start.getX(), start.getY(), start.getT() };
  // goal
  double q1[] = { goal.getX(), goal.getY(), goal.getT() };
  // initialize the path
  DubinsPath path;
  // calculate the path
  dubins_init(q0, q1, Constants::r, &path);

  int i = 0;
  float x = 0.f;
  float length = dubins_path_length(&path);

  Node3D* dubinsNodes = new Node3D [(int)(length / Constants::dubinsStepSize) + 1];

  while (x <  length) {
    double q[3];
    dubins_path_sample(&path, x, q);
    dubinsNodes[i].setX(q[0]);
    dubinsNodes[i].setY(q[1]);
    dubinsNodes[i].setT(Constants::normalizeHeadingRad(q[2]));

    // collision check
    if (configurationSpace.isTraversable(&dubinsNodes[i])) {

      // set the predecessor to the previous step
      if (i > 0) {
        dubinsNodes[i].setPred(&dubinsNodes[i - 1]);
      } else {
        dubinsNodes[i].setPred(&start);
      }

      if (&dubinsNodes[i] == dubinsNodes[i].getPred()) {
        std::cout << "looping shot";
      }

      x += Constants::dubinsStepSize;
      i++;
    } else {
      //      std::cout << "Dubins shot collided, discarding the path" << "\n";
      // delete all nodes
      delete [] dubinsNodes;
      return nullptr;
    }
  }

  //  std::cout << "Dubins shot connected, returning the path" << "\n";
  return &dubinsNodes[i - 1];
}

//###################################################
//                                         COST TO GO
//###################################################
void updateH(Node3D& start, const Node3D& goal, Node2D* nodes2D, int width, int height, CollisionDetection& configurationSpace) {
  float dubinsCost = 0;
  float reedsSheppCost = 0;
  float twoDCost = 0;
  float twoDoffset = 0;

  // if dubins heuristic is activated calculate the shortest path
  // constrained without obstacles
  if (Constants::dubins) {
    ompl::base::DubinsStateSpace dubinsPath(Constants::r);
    State* dbStart = (State*)dubinsPath.allocState();
    State* dbEnd = (State*)dubinsPath.allocState();
    dbStart->setXY(start.getX(), start.getY());
    dbStart->setYaw(start.getT());
    dbEnd->setXY(goal.getX(), goal.getY());
    dbEnd->setYaw(goal.getT());
    dubinsCost = dubinsPath.distance(dbStart, dbEnd);
  }

  // if reversing is active use a
  if (Constants::reverse && !Constants::dubins) {
    //    ros::Time t0 = ros::Time::now();
    ompl::base::ReedsSheppStateSpace reedsSheppPath(Constants::r);
    State* rsStart = (State*)reedsSheppPath.allocState();
    State* rsEnd = (State*)reedsSheppPath.allocState();
    rsStart->setXY(start.getX(), start.getY());
    rsStart->setYaw(start.getT());
    rsEnd->setXY(goal.getX(), goal.getY());
    rsEnd->setYaw(goal.getT());
    reedsSheppCost = reedsSheppPath.distance(rsStart, rsEnd);
  }

  // if twoD heuristic is activated determine shortest path unconstrained with obstacles
  if (Constants::twoD && !nodes2D[(int)start.getY() * width + (int)start.getX()].isDiscovered()) {
    //    ros::Time t0 = ros::Time::now();
    // create a 2d start node
    Node2D start2d(start.getX(), start.getY(), 0, 0, nullptr);
    // create a 2d goal node
    Node2D goal2d(goal.getX(), goal.getY(), 0, 0, nullptr);
    // run 2d astar and return the cost of the cheapest path for that node
    nodes2D[(int)start.getY() * width + (int)start.getX()].setG(aStar(goal2d, start2d, nodes2D, width, height, configurationSpace));
    //    ros::Time t1 = ros::Time::now();
    //    ros::Duration d(t1 - t0);
    //    std::cout << "calculated 2D Heuristic in ms: " << d * 1000 << std::endl;
  }

  if (Constants::twoD) {
    // offset for same node in cell
    twoDoffset = sqrt(((start.getX() - (long)start.getX()) - (goal.getX() - (long)goal.getX())) * ((start.getX() - (long)start.getX()) - (goal.getX() - (long)goal.getX())) +
                      ((start.getY() - (long)start.getY()) - (goal.getY() - (long)goal.getY())) * ((start.getY() - (long)start.getY()) - (goal.getY() - (long)goal.getY())));
    twoDCost = nodes2D[(int)start.getY() * width + (int)start.getX()].getG() - twoDoffset;

  }

  // return the maximum of the heuristics, making the heuristic admissable
  start.setH(std::max(reedsSheppCost, std::max(dubinsCost, twoDCost)));
}

//###################################################
//                                        2D A*
//###################################################
float aStar(Node2D& start,
            Node2D& goal,
            Node2D* nodes2D,
            int width,
            int height,
            CollisionDetection& configurationSpace) {

  // PREDECESSOR AND SUCCESSOR INDEX
  int iPred, iSucc;
  float newG;

  // reset the open and closed list
  for (int i = 0; i < width * height; ++i) {
    nodes2D[i].reset();
  }

  boost::heap::binomial_heap<Node2D*, boost::heap::compare<CompareNodes>> O;
  // update h value
  start.updateH(goal);
  // mark start as open
  start.open();
  // push on priority queue
  O.push(&start);
  iPred = start.setIdx(width);
  nodes2D[iPred] = start;

  // NODE POINTER
  Node2D* nPred;
  Node2D* nSucc;

  // continue until O empty
  while (!O.empty()) {
    // pop node with lowest cost from priority queue
    nPred = O.top();
    // set index
    iPred = nPred->setIdx(width);

    // _____________________________
    // LAZY DELETION of rewired node
    // if there exists a pointer this node has already been expanded
    if (nodes2D[iPred].isClosed()) {
      // pop node from the open list and start with a fresh node
      O.pop();
      continue;
    }
    // _________________
    // EXPANSION OF NODE
    else if (nodes2D[iPred].isOpen()) {
      // add node to closed list
      nodes2D[iPred].close();
      nodes2D[iPred].discover();

      // remove node from open list
      O.pop();

      // GOAL TEST
      if (*nPred == goal) {
        return nPred->getG();
      }
      // ____________________
      // CONTINUE WITH SEARCH
      else {
        // _______________________________
        // CREATE POSSIBLE SUCCESSOR NODES
        for (int i = 0; i < Node2D::dir; i++) {
          // create possible successor
          nSucc = nPred->createSuccessor(i);
          // set index of the successor
          iSucc = nSucc->setIdx(width);

          // ensure successor is on grid ROW MAJOR
          // ensure successor is not blocked by obstacle
          // ensure successor is not on closed list
          if (nSucc->isOnGrid(width, height) &&  configurationSpace.isTraversable(nSucc) && !nodes2D[iSucc].isClosed()) {
            // calculate new G value
            nSucc->updateG();
            newG = nSucc->getG();

            // if successor not on open list or g value lower than before put it on open list
            if (!nodes2D[iSucc].isOpen() || newG < nodes2D[iSucc].getG()) {
              // calculate the H value
              nSucc->updateH(goal);
              // put successor on open list
              nSucc->open();
              nodes2D[iSucc] = *nSucc;
              O.push(&nodes2D[iSucc]);
              delete nSucc;
            } else { delete nSucc; }
          } else { delete nSucc; }
        }
      }
    }
  }

  // return large number to guide search away
  return 1000;
}


text:
#define BOOST_TEST_MODULE MatlabV5ParserImpl
#define BOOST_TEST_DYN_LINK

#include <boost/test/included/unit_test.hpp>

#include "CobraModelParser/MatlabV5/ParserImpl.hpp"

BOOST_AUTO_TEST_SUITE(MatlabV5ParserImpl_suite)

    BOOST_AUTO_TEST_CASE(MatlabV5ParserImpl_throwsIfMatlabFileIsNotV5) {
        CobraModelParser::MatlabV5::ParserImpl parser;

        BOOST_CHECK_THROW(parser.parseModelFromFile("unparsableFile.mat"),
                          CobraModelParser::UnexpectedFileTypeException);
    }

    BOOST_AUTO_TEST_CASE(MatlabV5ParserImpl_parsesModel_iJO1366) {
        CobraModelParser::MatlabV5::ParserImpl parser;
        CobraModelParser::Model model = parser.parseModelFromFile("iJO1366.mat");
        BOOST_CHECK(model.getOrigin() == "iJO1366.mat");
    }

    BOOST_AUTO_TEST_CASE(MatlabV5ParserImpl_parsesModel_iJO1366_2) {
        CobraModelParser::MatlabV5::ParserImpl parser;
        CobraModelParser::Model model = parser.parseModelFromFile("iJO1366_2.mat");
        BOOST_CHECK(model.getOrigin() == "iJO1366_2.mat");
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: qacwnfq/CobraModelParser

max_issues_repo_name: qacwnfq/CobraModelParser

max_forks_repo_name: qacwnfq/CobraModelParser


text:
#include "stdafx.h"

#include <boost\test\unit_test.hpp>

#include <geometry\geometry.hpp>

#include <boost\gil\extension\io_new\png_all.hpp>

using namespace boost;
using namespace gil;
//using namespace boost::gil::opencv;

template< typename Geometry, typename View >
struct draw {};

template< typename View, typename Point >
struct draw< geometry::box< Point >, View > { static void d() {} };

BOOST_AUTO_TEST_CASE( test_geometry )
{
	typedef geometry::point_xy<double> P;

	geometry::box< P > b( P( 10, 10 )
	                    , P( 35, 70 )
	                    );

    rgb8_image_t img;
    int i;
    //draw( i, view( img ) );

    draw< geometry::box< P >, double >::d();

    //write_view( "..\\out\\geometry.png", view( dst ), png_tag() );
}

max_stars_repo_name: boost-gil/gil-contributions

max_issues_repo_name: boost-gil/gil-contributions-archive

max_forks_repo_name: boost-gil/gil-contributions-archive