text:
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/*
    此文件是Rippled的一部分：https://github.com/ripple/rippled
    版权所有（c）2012，2013 Ripple Labs Inc.

    使用、复制、修改和/或分发本软件的权限
    特此授予免费或不收费的目的，前提是
    版权声明和本许可声明出现在所有副本中。

    本软件按“原样”提供，作者不作任何保证。
    关于本软件，包括
    适销性和适用性。在任何情况下，作者都不对
    任何特殊、直接、间接或后果性损害或任何损害
    因使用、数据或利润损失而导致的任何情况，无论是在
    合同行为、疏忽或其他侵权行为
    或与本软件的使用或性能有关。
**/

//==============================================================

#include <ripple/basics/Log.h>
#include <test/jtx.h>
#include <ripple/json/to_string.h>
#include <ripple/protocol/Feature.h>
#include <ripple/protocol/JsonFields.h>
#include <ripple/protocol/TxFlags.h>
#include <ripple/beast/hash/uhash.h>
#include <ripple/beast/unit_test.h>
#include <boost/lexical_cast.hpp>
#include <boost/optional.hpp>
#include <utility>

namespace ripple {
namespace test {

class Env_test : public beast::unit_test::suite
{
public:
    template <class T>
    static
    std::string
    to_string (T const& t)
    {
        return boost::lexical_cast<
            std::string>(t);
    }

//帐户H中的声明
    void
    testAccount()
    {
        using namespace jtx;
        {
            Account a;
            Account b(a);
            a = b;
            a = std::move(b);
            Account c(std::move(a));
        }
        Account("alice");
        Account("alice", KeyType::secp256k1);
        Account("alice", KeyType::ed25519);
        auto const gw = Account("gw");
        [](AccountID){}(gw);
        auto const USD = gw["USD"];
        void(Account("alice") < gw);
        std::set<Account>().emplace(gw);
        std::unordered_set<Account,
            beast::uhash<>>().emplace("alice");
    }

//金额申报.h
    void
    testAmount()
    {
        using namespace jtx;

        PrettyAmount(0);
        PrettyAmount(1);
        PrettyAmount(0u);
        PrettyAmount(1u);
        PrettyAmount(-1);
        static_assert(! std::is_constructible<
            PrettyAmount, char>::value, "");
        static_assert(! std::is_constructible<
            PrettyAmount, unsigned char>::value, "");
        static_assert(! std::is_constructible<
            PrettyAmount, short>::value, "");
        static_assert(! std::is_constructible<
            PrettyAmount, unsigned short>::value, "");

        try
        {
            XRP(0.0000001);
            fail("missing exception");
        }
        catch(std::domain_error const&)
        {
            pass();
        }
        XRP(-0.000001);
        try
        {
            XRP(-0.0000009);
            fail("missing exception");
        }
        catch(std::domain_error const&)
        {
            pass();
        }

        BEAST_EXPECT(to_string(XRP(5)) == "5 XRP");
        BEAST_EXPECT(to_string(XRP(.80)) == "0.8 XRP");
        BEAST_EXPECT(to_string(XRP(.005)) == "5000 drops");
        BEAST_EXPECT(to_string(XRP(0.1)) == "0.1 XRP");
        BEAST_EXPECT(to_string(XRP(10000)) == "10000 XRP");
        BEAST_EXPECT(to_string(drops(10)) == "10 drops");
        BEAST_EXPECT(to_string(drops(123400000)) == "123.4 XRP");
        BEAST_EXPECT(to_string(XRP(-5)) == "-5 XRP");
        BEAST_EXPECT(to_string(XRP(-.99)) == "-0.99 XRP");
        BEAST_EXPECT(to_string(XRP(-.005)) == "-5000 drops");
        BEAST_EXPECT(to_string(XRP(-0.1)) == "-0.1 XRP");
        BEAST_EXPECT(to_string(drops(-10)) == "-10 drops");
        BEAST_EXPECT(to_string(drops(-123400000)) == "-123.4 XRP");

        BEAST_EXPECT(XRP(1) == drops(1000000));
        BEAST_EXPECT(XRP(1) == STAmount(1000000));
        BEAST_EXPECT(STAmount(1000000) == XRP(1));

        auto const gw = Account("gw");
        auto const USD = gw["USD"];
        BEAST_EXPECT(to_string(USD(0)) == "0/USD(gw)");
        BEAST_EXPECT(to_string(USD(10)) == "10/USD(gw)");
        BEAST_EXPECT(to_string(USD(-10)) == "-10/USD(gw)");
        BEAST_EXPECT(USD(0) == STAmount(USD, 0));
        BEAST_EXPECT(USD(1) == STAmount(USD, 1));
        BEAST_EXPECT(USD(-1) == STAmount(USD, -1));

        auto const get = [](AnyAmount a){ return a; };
        BEAST_EXPECT(! get(USD(10)).is_any);
        BEAST_EXPECT(get(any(USD(10))).is_any);
    }

//测试环境
    void
    testEnv()
    {
        using namespace jtx;
        auto const n = XRP(10000);
        auto const gw = Account("gw");
        auto const USD = gw["USD"];
        auto const alice = Account("alice");

//无资金的
        {
            Env env(*this);
            env(pay("alice", "bob", XRP(1000)), seq(1), fee(10), sig("alice"), ter(terNO_ACCOUNT));
        }

//基金
        {
            Env env(*this);

//变差函数
            env.fund(n, "alice");
            env.fund(n, "bob", "carol");
            env.fund(n, "dave", noripple("eric"));
            env.fund(n, "fred", noripple("gary", "hank"));
            env.fund(n, noripple("irene"));
            env.fund(n, noripple("jim"), "karen");
            env.fund(n, noripple("lisa", "mary"));

//旗帜
            env.fund(n, noripple("xavier"));
            env.require(nflags("xavier", asfDefaultRipple));
            env.fund(n, "yana");
            env.require(flags("yana", asfDefaultRipple));
        }

//信任
        {
            Env env(*this);
            env.fund(n, "alice", "bob", gw);
            env(trust("alice", USD(100)), require(lines("alice", 1)));
        }

//平衡
        {
            Env env(*this);
            BEAST_EXPECT(env.balance(alice) == 0);
            BEAST_EXPECT(env.balance(alice, USD) != 0);
            BEAST_EXPECT(env.balance(alice, USD) == USD(0));
            env.fund(n, alice, gw);
            BEAST_EXPECT(env.balance(alice) == n);
            BEAST_EXPECT(env.balance(gw) == n);
            env.trust(USD(1000), alice);
            env(pay(gw, alice, USD(10)));
            BEAST_EXPECT(to_string(env.balance("alice", USD)) == "10/USD(gw)");
            BEAST_EXPECT(to_string(env.balance(gw, alice["USD"])) == "-10/USD(alice)");
        }

//SEQ
        {
            Env env(*this);
            env.fund(n, noripple("alice", gw));
            BEAST_EXPECT(env.seq("alice") == 1);
            BEAST_EXPECT(env.seq(gw) == 1);
        }

//自动填充
        {
            Env env(*this);
            env.fund(n, "alice");
            env.require(balance("alice", n));
            env(noop("alice"), fee(1),                  ter(telINSUF_FEE_P));
            env(noop("alice"), seq(none),               ter(temMALFORMED));
            env(noop("alice"), seq(none), fee(10),      ter(temMALFORMED));
            env(noop("alice"), fee(none),               ter(temMALFORMED));
            env(noop("alice"), sig(none),               ter(temMALFORMED));
            env(noop("alice"), fee(autofill));
            env(noop("alice"), fee(autofill), seq(autofill));
            env(noop("alice"), fee(autofill), seq(autofill), sig(autofill));
        }
    }

//要求：要求
    void
    testRequire()
    {
        using namespace jtx;
        Env env(*this);
        auto const gw = Account("gw");
        auto const USD = gw["USD"];
        env.require(balance("alice", none));
        env.require(balance("alice", XRP(none)));
        env.fund(XRP(10000), "alice", gw);
        env.require(balance("alice", USD(none)));
        env.trust(USD(100), "alice");
env.require(balance("alice", XRP(10000))); //费用退还
        env.require(balance("alice", USD(0)));
        env(pay(gw, "alice", USD(10)), require(balance("alice", USD(10))));

        env.require(nflags("alice", asfRequireDest));
        env(fset("alice", asfRequireDest), require(flags("alice", asfRequireDest)));
        env(fclear("alice", asfRequireDest), require(nflags("alice", asfRequireDest)));
    }

//使用secp256k1和ed25519密钥签名
    void
    testKeyType()
    {
        using namespace jtx;

        Env env(*this);
        Account const alice("alice", KeyType::ed25519);
        Account const bob("bob", KeyType::secp256k1);
        Account const carol("carol");
        env.fund(XRP(10000), alice, bob);

//仅主密钥
        env(noop(alice));
        env(noop(bob));
        env(noop(alice), sig("alice"),                          ter(tefBAD_AUTH_MASTER));
        env(noop(alice), sig(Account("alice",
            KeyType::secp256k1)),                               ter(tefBAD_AUTH_MASTER));
        env(noop(bob), sig(Account("bob",
            KeyType::ed25519)),                                 ter(tefBAD_AUTH_MASTER));
        env(noop(alice), sig(carol),                            ter(tefBAD_AUTH_MASTER));

//万能钥匙和普通钥匙
        env(regkey(alice, bob));
        env(noop(alice));
        env(noop(alice), sig(bob));
        env(noop(alice), sig(alice));

//仅限普通钥匙
        env(fset(alice, asfDisableMaster), sig(alice));
        env(noop(alice));
        env(noop(alice), sig(bob));
        env(noop(alice), sig(alice),                            ter(tefMASTER_DISABLED));
        env(fclear(alice, asfDisableMaster), sig(alice),        ter(tefMASTER_DISABLED));
        env(fclear(alice, asfDisableMaster), sig(bob));
        env(noop(alice), sig(alice));
    }

//支付基础
    void
    testPayments()
    {
        using namespace jtx;
        Env env(*this);
        auto const gw = Account("gateway");
        auto const USD = gw["USD"];

        env.fund(XRP(10000), "alice", "bob", "carol", gw);
        env.require(balance("alice", XRP(10000)));
        env.require(balance("bob", XRP(10000)));
        env.require(balance("carol", XRP(10000)));
        env.require(balance(gw, XRP(10000)));

        env(pay(env.master, "alice", XRP(1000)), fee(none),     ter(temMALFORMED));
        env(pay(env.master, "alice", XRP(1000)), fee(1),        ter(telINSUF_FEE_P));
        env(pay(env.master, "alice", XRP(1000)), seq(none),     ter(temMALFORMED));
        env(pay(env.master, "alice", XRP(1000)), seq(20),       ter(terPRE_SEQ));
        env(pay(env.master, "alice", XRP(1000)), sig(none),     ter(temMALFORMED));
        env(pay(env.master, "alice", XRP(1000)), sig("bob"),    ter(tefBAD_AUTH_MASTER));

        env(pay(env.master, "dilbert", XRP(1000)), sig(env.master));

        env.trust(USD(100), "alice", "bob", "carol");
        env.require(owners("alice", 1), lines("alice", 1));
        env(rate(gw, 1.05));

        env(pay(gw, "carol", USD(50)));
        env.require(balance("carol", USD(50)));
        env.require(balance(gw, Account("carol")["USD"](-50)));

        env(offer("carol", XRP(50), USD(50)), require(owners("carol", 2)));
        env(pay("alice", "bob", any(USD(10))),                  ter(tecPATH_DRY));
        env(pay("alice", "bob", any(USD(10))),
            paths(XRP), sendmax(XRP(10)),                       ter(tecPATH_PARTIAL));
        env(pay("alice", "bob", any(USD(10))), paths(XRP),
            sendmax(XRP(20)));
        env.require(balance("bob", USD(10)));
        env.require(balance("carol", USD(39.5)));

        env.memoize("eric");
        env(regkey("alice", "eric"));
        env(noop("alice"));
        env(noop("alice"), sig("alice"));
        env(noop("alice"), sig("eric"));
        env(noop("alice"), sig("bob"),                          ter(tefBAD_AUTH));
        env(fset("alice", asfDisableMaster),                    ter(tecNEED_MASTER_KEY));
        env(fset("alice", asfDisableMaster), sig("eric"),       ter(tecNEED_MASTER_KEY));
        env.require(nflags("alice", asfDisableMaster));
        env(fset("alice", asfDisableMaster), sig("alice"));
        env.require(flags("alice", asfDisableMaster));
        env(regkey("alice", disabled),                          ter(tecNO_ALTERNATIVE_KEY));
        env(noop("alice"));
        env(noop("alice"), sig("alice"),                        ter(tefMASTER_DISABLED));
        env(noop("alice"), sig("eric"));
        env(noop("alice"), sig("bob"),                          ter(tefBAD_AUTH));
        env(fclear("alice", asfDisableMaster), sig("bob"),      ter(tefBAD_AUTH));
        env(fclear("alice", asfDisableMaster), sig("alice"),    ter(tefMASTER_DISABLED));
        env(fclear("alice", asfDisableMaster));
        env.require(nflags("alice", asfDisableMaster));
        env(regkey("alice", disabled));
        env(noop("alice"), sig("eric"),                         ter(tefBAD_AUTH_MASTER));
        env(noop("alice"));
    }

//多符号基础
    void
    testMultiSign()
    {
        using namespace jtx;

        Env env(*this);
        env.fund(XRP(10000), "alice");
        env(signers("alice", 1,
            { { "alice", 1 }, { "bob", 2 } }),                  ter(temBAD_SIGNER));
        env(signers("alice", 1,
            { { "bob", 1 }, { "carol", 2 } }));
        env(noop("alice"));

        auto const baseFee = env.current()->fees().base;
        env(noop("alice"), msig("bob"), fee(2 * baseFee));
        env(noop("alice"), msig("carol"), fee(2 * baseFee));
        env(noop("alice"), msig("bob", "carol"), fee(3 * baseFee));
        env(noop("alice"), msig("bob", "carol", "dilbert"),
            fee(4 * baseFee),                                   ter(tefBAD_SIGNATURE));

        env(signers("alice", none));
    }

    void
    testTicket()
    {
        using namespace jtx;
//创建语法
        ticket::create("alice", "bob");
        ticket::create("alice", 60);
        ticket::create("alice", "bob", 60);
        ticket::create("alice", 60, "bob");

        {
            Env env(*this, supported_amendments().set(featureTickets));
            env.fund(XRP(10000), "alice");
            env(noop("alice"),                  require(owners("alice", 0), tickets("alice", 0)));
            env(ticket::create("alice"),        require(owners("alice", 1), tickets("alice", 1)));
            env(ticket::create("alice"),        require(owners("alice", 2), tickets("alice", 2)));
        }
    }

    struct UDT
    {
    };

    void testJTxProperties()
    {
        struct T { };
        using namespace jtx;
        JTx jt1;
//直接测试
//财产
        BEAST_EXPECT(!jt1.get<int>());
        jt1.set<int>(7);
        BEAST_EXPECT(jt1.get<int>());
        BEAST_EXPECT(*jt1.get<int>() == 7);
        BEAST_EXPECT(!jt1.get<UDT>());

//测试属性是否为
//如果存在，则更换。
        jt1.set<int>(17);
        BEAST_EXPECT(jt1.get<int>());
        BEAST_EXPECT(*jt1.get<int>() == 17);
        BEAST_EXPECT(!jt1.get<UDT>());

//测试修改
//返回的道具已保存
        *jt1.get<int>() = 42;
        BEAST_EXPECT(jt1.get<int>());
        BEAST_EXPECT(*jt1.get<int>() == 42);
        BEAST_EXPECT(!jt1.get<UDT>());

//test get（）常量
        auto const& jt2 = jt1;
        BEAST_EXPECT(jt2.get<int>());
        BEAST_EXPECT(*jt2.get<int>() == 42);
        BEAST_EXPECT(!jt2.get<UDT>());
    }

    void testProp()
    {
        using namespace jtx;
        Env env(*this);
        env.fund(XRP(100000), "alice");
        auto jt1 = env.jt(noop("alice"));
        BEAST_EXPECT(!jt1.get<std::uint16_t>());
        auto jt2 = env.jt(noop("alice"),
            prop<std::uint16_t>(-1));
        BEAST_EXPECT(jt2.get<std::uint16_t>());
        BEAST_EXPECT(*jt2.get<std::uint16_t>() ==
            65535);
        auto jt3 = env.jt(noop("alice"),
            prop<std::string>(
                "Hello, world!"),
                    prop<bool>(false));
        BEAST_EXPECT(jt3.get<std::string>());
        BEAST_EXPECT(*jt3.get<std::string>() ==
            "Hello, world!");
        BEAST_EXPECT(jt3.get<bool>());
        BEAST_EXPECT(!*jt3.get<bool>());
    }

    void testJTxCopy()
    {
        struct T { };
        using namespace jtx;
        JTx jt1;
        jt1.set<int>(7);
        BEAST_EXPECT(jt1.get<int>());
        BEAST_EXPECT(*jt1.get<int>() == 7);
        BEAST_EXPECT(!jt1.get<UDT>());
        JTx jt2(jt1);
        BEAST_EXPECT(jt2.get<int>());
        BEAST_EXPECT(*jt2.get<int>() == 7);
        BEAST_EXPECT(!jt2.get<UDT>());
        JTx jt3;
        jt3 = jt1;
        BEAST_EXPECT(jt3.get<int>());
        BEAST_EXPECT(*jt3.get<int>() == 7);
        BEAST_EXPECT(!jt3.get<UDT>());
    }

    void testJTxMove()
    {
        struct T { };
        using namespace jtx;
        JTx jt1;
        jt1.set<int>(7);
        BEAST_EXPECT(jt1.get<int>());
        BEAST_EXPECT(*jt1.get<int>() == 7);
        BEAST_EXPECT(!jt1.get<UDT>());
        JTx jt2(std::move(jt1));
        BEAST_EXPECT(!jt1.get<int>());
        BEAST_EXPECT(!jt1.get<UDT>());
        BEAST_EXPECT(jt2.get<int>());
        BEAST_EXPECT(*jt2.get<int>() == 7);
        BEAST_EXPECT(!jt2.get<UDT>());
        jt1 = std::move(jt2);
        BEAST_EXPECT(!jt2.get<int>());
        BEAST_EXPECT(!jt2.get<UDT>());
        BEAST_EXPECT(jt1.get<int>());
        BEAST_EXPECT(*jt1.get<int>() == 7);
        BEAST_EXPECT(!jt1.get<UDT>());
    }

    void
    testMemo()
    {
        using namespace jtx;
        Env env(*this);
        env.fund(XRP(10000), "alice");
        env(noop("alice"), memodata("data"));
        env(noop("alice"), memoformat("format"));
        env(noop("alice"), memotype("type"));
        env(noop("alice"), memondata("format", "type"));
        env(noop("alice"), memonformat("data", "type"));
        env(noop("alice"), memontype("data", "format"));
        env(noop("alice"), memo("data", "format", "type"));
        env(noop("alice"), memo("data1", "format1", "type1"), memo("data2", "format2", "type2"));
    }

    void
    testAdvance()
    {
        using namespace jtx;
        Env env(*this);
        auto seq = env.current()->seq();
        BEAST_EXPECT(seq == env.closed()->seq() + 1);
        env.close();
        BEAST_EXPECT(env.closed()->seq() == seq);
        BEAST_EXPECT(env.current()->seq() == seq + 1);
        env.close();
        BEAST_EXPECT(env.closed()->seq() == seq + 1);
        BEAST_EXPECT(env.current()->seq() == seq + 2);
    }

    void
    testClose()
    {
        using namespace jtx;
        Env env(*this);
        env.close();
        env.close();
        env.fund(XRP(100000), "alice", "bob");
        env.close();
        env(pay("alice", "bob", XRP(100)));
        env.close();
        env(noop("alice"));
        env.close();
        env(noop("bob"));
    }

    void
    testPath()
    {
        using namespace jtx;
        Env env(*this);
        auto const gw = Account("gw");
        auto const USD = gw["USD"];
        env.fund(XRP(10000), "alice", "bob");
        env.json(
            pay("alice", "bob", USD(10)),
                path(Account("alice")),
                path("bob"),
                path(USD),
                path(~XRP),
                path(~USD),
                path("bob", USD, ~XRP, ~USD)
                );
    }

//测试JTX是否可以重新签署已经签署的事务。
    void testResignSigned()
    {
        using namespace jtx;
        Env env(*this);

        env.fund(XRP(10000), "alice");
        auto const baseFee = env.current()->fees().base;
        std::uint32_t const aliceSeq = env.seq ("alice");

//签署JSONNOP。
        Json::Value jsonNoop = env.json (
            noop ("alice"), fee(baseFee), seq(aliceSeq), sig("alice"));
//重新签署jsonnoop。
        JTx jt = env.jt (jsonNoop);
        env (jt);
    }

    void testSignAndSubmit()
    {
        using namespace jtx;
        Env env(*this);
        Env_ss envs(env);

        auto const alice = Account("alice");
        env.fund(XRP(10000), alice);

        {
            envs(noop(alice), fee(none), seq(none))();

//确保我们取回正确的帐户。
            auto tx = env.tx();
            if (BEAST_EXPECT(tx))
            {
                BEAST_EXPECT(tx->getAccountID(sfAccount) == alice.id());
                BEAST_EXPECT(tx->getTxnType() == ttACCOUNT_SET);
            }
        }

        {
            auto params = Json::Value(Json::nullValue);
            envs(noop(alice), fee(none), seq(none))(params);

//确保我们取回正确的帐户。
            auto tx = env.tx();
            if (BEAST_EXPECT(tx))
            {
                BEAST_EXPECT(tx->getAccountID(sfAccount) == alice.id());
                BEAST_EXPECT(tx->getTxnType() == ttACCOUNT_SET);
            }
        }

        {
            auto params = Json::Value(Json::objectValue);
//将系数降低到足以使其失效。
            params[jss::fee_mult_max] = 1;
            params[jss::fee_div_max] = 2;
//RPC错误导致temInvalid
            envs(noop(alice), fee(none),
                seq(none), ter(temINVALID))(params);

            auto tx = env.tx();
            BEAST_EXPECT(!tx);
        }
    }

    void testFeatures()
    {
        testcase("Env features");
        using namespace jtx;
        auto const supported = supported_amendments();

//这将找到一个不在
//支持的修订列表和测试
//显式启用

        auto const neverSupportedFeat = [&]() -> boost::optional<uint256>
        {
            auto const n = supported.size();
            for(size_t i = 0; i < n; ++i)
                if (!supported[i])
                    return bitsetIndexToFeature(i);

            return boost::none;
        }();

        if (!neverSupportedFeat)
        {
            log << "No unsupported features found - skipping test." << std::endl;
            pass();
            return;
        }

        auto hasFeature = [](Env& env, uint256 const& f)
        {
            return (env.app().config().features.find (f) !=
                    env.app().config().features.end());
        };

        {
//默认env具有所有支持的功能
            Env env{*this};
            BEAST_EXPECT(
                supported.count() == env.app().config().features.size());
            foreachFeature(supported, [&](uint256 const& f) {
                this->BEAST_EXPECT(hasFeature(env, f));
            });
        }

        {
//env featurebitset只有*这些功能
            Env env{*this, FeatureBitset(featureEscrow, featureFlow)};
            BEAST_EXPECT(env.app().config().features.size() == 2);
            foreachFeature(supported, [&](uint256 const& f) {
                bool const has = (f == featureEscrow || f == featureFlow);
                this->BEAST_EXPECT(has == hasFeature(env, f));
            });
        }

        auto const noFlowOrEscrow =
            supported_amendments() - featureEscrow - featureFlow;
        {
//一个env支持的\u功能\除了缺少*仅*那些功能
            Env env{*this, noFlowOrEscrow};
            BEAST_EXPECT(
                env.app().config().features.size() == (supported.count() - 2));
            foreachFeature(supported, [&](uint256 const& f) {
                bool hasnot = (f == featureEscrow || f == featureFlow);
                this->BEAST_EXPECT(hasnot != hasFeature(env, f));
            });
        }

        {
//添加不在支持的修订列表中的功能
//以及一份明确修订的清单
//不支持的功能应与
//两个支持的
            Env env{
                *this,
                FeatureBitset(featureEscrow, featureFlow, *neverSupportedFeat)};

//这个应用只有2个支持的修正和
//另一个从不支持的功能标志
            BEAST_EXPECT(env.app().config().features.size() == (2 + 1));
            BEAST_EXPECT(hasFeature(env, *neverSupportedFeat));

            foreachFeature(supported, [&](uint256 const& f) {
                bool has = (f == featureEscrow || f == featureFlow);
                this->BEAST_EXPECT(has == hasFeature(env, f));
            });
        }

        {
//添加不在支持的修订列表中的功能
//省略了一些标准修正案
//应启用不支持的功能
            Env env{*this,
                    noFlowOrEscrow | FeatureBitset{*neverSupportedFeat}};

//此应用程序将包含所有支持的修订减去2，然后
//另一个从不支持的功能标志
            BEAST_EXPECT(
                env.app().config().features.size() ==
                (supported.count() - 2 + 1));
            BEAST_EXPECT(hasFeature(env, *neverSupportedFeat));
            foreachFeature(supported, [&](uint256 const& f) {
                bool hasnot = (f == featureEscrow || f == featureFlow);
                this->BEAST_EXPECT(hasnot != hasFeature(env, f));
            });
        }

        {
//添加不在支持的修订列表中的功能
//以及所有支持的修正案
//应启用不支持的功能
            Env env{*this, supported_amendments().set(*neverSupportedFeat)};

//此应用程序将包含所有支持的修订，然后
//另一个从不支持的功能标志
            BEAST_EXPECT(
                env.app().config().features.size() == (supported.count() + 1));
            BEAST_EXPECT(hasFeature(env, *neverSupportedFeat));
            foreachFeature(supported, [&](uint256 const& f) {
                this->BEAST_EXPECT(hasFeature(env, f));
            });
        }
    }

    void
    run() override
    {
        testAccount();
        testAmount();
        testEnv();
        testRequire();
        testKeyType();
        testPayments();
        testMultiSign();
        testTicket();
        testJTxProperties();
        testProp();
        testJTxCopy();
        testJTxMove();
        testMemo();
        testAdvance();
        testClose();
        testPath();
        testResignSigned();
        testSignAndSubmit();
        testFeatures();
    }
};

BEAST_DEFINE_TESTSUITE(Env,app,ripple);

} //测试
} //涟漪

max_stars_repo_name: yinchengtsinghua/RippleCPPChinese

max_issues_repo_name: yinchengtsinghua/RippleCPPChinese

max_forks_repo_name: yinchengtsinghua/RippleCPPChinese


text:
// Exercise 5.1.5 - Statistical Functions
//
// by Scott Sidoli
//
// 5-30-19
//
// Main.cpp
//
// In this exercise, we modify the code in TestNormalDistribution.cpp to work with the exponential distribution instead of the
// normal distribution and the poisson distribution instead of the gamma distribution.

#include <boost/math/distributions/normal.hpp>
#include <boost/math/distributions/gamma.hpp>
#include <boost/math/distributions.hpp> // For non-member functions of distributions
#include <boost/math/distributions/exponential.hpp>
#include <boost/math/distributions/poisson.hpp>

#include <vector>
#include <iostream>
using namespace std;

int main()
{
	// Don't forget to tell compiler which namespace
	using namespace boost::math;

	//=============================== Normal Distribution ===============================

	normal_distribution<> myNormal(1.0, 10.0); // Default type is 'double'
	cout << "Mean: " << mean(myNormal) << ", standard deviation: " << standard_deviation(myNormal) << endl;

	// Distributional properties
	double x = 10.25;

	cout << "pdf: " << pdf(myNormal, x) << endl;
	cout << "cdf: " << cdf(myNormal, x) << endl;

	// Choose another data type and now a N(0,1) variate
	normal_distribution<float> myNormal2;
	cout << "Mean: " << mean(myNormal2) << ", standard deviation: " << standard_deviation(myNormal2) << endl;

	cout << "pdf: " << pdf(myNormal2, x) << endl;
	cout << "cdf: " << cdf(myNormal2, x) << endl;

	// Choose precision
	cout.precision(10); // Number of values behind the comma

	// Other properties
	cout << "\n***normal distribution: \n";
	cout << "mean: " << mean(myNormal) << endl;
	cout << "variance: " << variance(myNormal) << endl;
	cout << "median: " << median(myNormal) << endl;
	cout << "mode: " << mode(myNormal) << endl;
	cout << "kurtosis excess: " << kurtosis_excess(myNormal) << endl;
	cout << "kurtosis: " << kurtosis(myNormal) << endl;
	cout << "characteristic function: " << chf(myNormal, x) << endl;
	cout << "hazard: " << hazard(myNormal, x) << endl;

	//=============================== Exponential Distribution ===============================

	double scaleParameter = 0.5;

	// Default type is 'double'
	exponential_distribution<> myExponential(scaleParameter);

	cout << "Mean: " << mean(myExponential) << ", standard deviation: " << standard_deviation(myExponential) << endl;

	// PDF and CDF
	cout << "pdf: " << pdf(myExponential, x) << endl;
	cout << "cdf: " << cdf(myExponential, x) << endl;

	// Using another data type and a N(0,1) variate
	exponential_distribution<float> myExponential2(1.0);
	cout << "Mean: " << mean(myExponential2) << ", standard deviation: " << standard_deviation(myExponential2) << endl;

	// PDF and CDF
	cout << "pdf: " << pdf(myExponential2, x) << endl;
	cout << "cdf: " << cdf(myExponential2, x) << endl;

	// Other properties
	cout << "\n***exponential distribution: \n";
	cout << "mean: " << mean(myExponential) << endl;
	cout << "variance: " << variance(myExponential) << endl;
	cout << "median: " << median(myExponential) << endl;
	cout << "mode: " << mode(myExponential) << endl;
	cout << "kurtosis excess: " << kurtosis_excess(myExponential) << endl;
	cout << "kurtosis: " << kurtosis(myExponential) << endl;
	cout << "characteristic function: " << chf(myExponential, x) << endl;
	cout << "hazard: " << hazard(myExponential, x) << endl;

	//=============================== Gamma Distribution ===============================
	double alpha = 3.0; // Shape parameter, k
	double beta = 0.5;	// Scale parameter, theta
	gamma_distribution<double> myGamma(alpha, beta);
	cout << "everything that follows is for the gamma distribution" << endl;
	double val = 13.0;
	cout << endl << "pdf: " << pdf(myGamma, val) << endl;
	cout << "cdf: " << cdf(myGamma, val) << endl;

	vector<double> pdfList;
	vector<double> cdfList;

	double start = 0.0;
	double end = 10.0;
	long N = 30;		// Number of subdivisions

	val = 0.0;
	double h = (end - start) / double(N);

	for (long j = 1; j <= N; ++j)
	{
		pdfList.push_back(pdf(myGamma, val));
		cdfList.push_back(cdf(myGamma, val));

		val += h;
	}

	for (long j = 0; j < pdfList.size(); ++j)
	{
		cout << pdfList[j] << ", " << endl;

	}

	cout << "***" << endl;

	for (long j = 0; j < cdfList.size(); ++j)
	{
		cout << cdfList[j] << ", " << endl;

	}

	//=============================== Poisson Distribution ===============================
	cout << "everything that follows is for the Poisson distribution" << endl;
	double mean = 3.0;
	poisson_distribution<double> myPoisson(mean);

	val = 3.5;
	cout << "pdf: " << pdf(myPoisson, val) << endl;
	cout << "cdf: " << cdf(myPoisson, val) << endl;

	vector<double> pdfList2;
	vector<double> cdfList2;

	double start2 = 0.0;
	double end2 = 6.0;
	long N2 = 30;		// Number of subdivisions

	val = 0.0;
	double h2 = (end2 - start2) / double(N2);

	for (long j = 1; j <= N2; ++j)
	{
		pdfList2.push_back(pdf(myPoisson, val));
		cdfList2.push_back(cdf(myPoisson, val));

		val += h2;
	}

	for (long j = 0; j < pdfList2.size(); ++j)
	{
		cout << pdfList2[j] << ", "<< endl;

	}

	cout << "***" << endl;

	for (long j = 0; j < cdfList2.size(); ++j)
	{
		cout << cdfList[j] << ", " << endl;

	}
	return 0;
}

ext: cpp

max_stars_repo_path: Scott_Sidoli Level 8 HW Submission/Section 5.1/Exercise515/Exercise515/Main.cpp


text:
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <iterator>
#include <numeric>
#include <memory>
#include <chrono>

#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>

#include "TestSet.hpp"
#include "BVNS.hpp"
#include "VNS.hpp"
#include "Solution.hpp"
#include "Helper.hpp"

using namespace std;
namespace ublas = boost::numeric::ublas;

/*********************************************************************************/
/*                  CONSTRUCTOR AND MEMBER FUNCTIONS OF BVNS                     */
/*********************************************************************************/

// Init BVNS Heuristic
BVNS::BVNS(const string &directory,
	const unsigned int &kMin,
	const unsigned int &kMax,
	const unsigned int &tMax,
	const unsigned int &shaking_mode,
	const unsigned int &local_Search_mode,
	const unsigned int &update_xij_mode,
	const unsigned int &initial_mode,
	const unsigned int &time):
		VNS(directory, kMin, kMax, tMax, shaking_mode,
			local_Search_mode, update_xij_mode, initial_mode, time),
		m_local_solution(m_locationNumber, 1)
{
	chrono::steady_clock::time_point timeStart = chrono::high_resolution_clock::now();
	initialSolution(m_incumbent_solution, m_bi, m_fi, m_dj, m_cij, m_sum_dj, m_initial_mode);

	unsigned int counter = 0, t = 0;
	bool stop = false;

	for (size_t i = 0; i != tMax && !stop; ++i)
	{
		// For all N_k Structures
		m_k = m_kMin - 1;
		while (m_k < m_kMax && !stop)
		{
			// Shake incumbent Solution
			m_perturbed_solution = shaking(m_incumbent_solution,
				m_bi, m_dj, m_cij, m_k, m_fx, m_shaking_mode);
			// Update Neighborhood Structure N_k(S')
			updateNeighborhoods(m_neighborhood_k, m_perturbed_solution, m_bi,
				m_sum_dj, m_shaking_mode, m_k);
			// Generate Local Solution
			m_local_solution = localSearch(m_perturbed_solution,
				m_neighborhood_k, m_k, m_fx, m_local_search_mode);
			// Move or not
			neighborhoodChange(m_incumbent_solution, m_local_solution, m_k, m_fx, m_best_fx, m_kMin);

			// Check if maximum COmputation Time is exeeded
			chrono::steady_clock::time_point bvns_step = chrono::high_resolution_clock::now();
			double time_end = (double)chrono::duration_cast<chrono::microseconds>(bvns_step - timeStart).count();
			if (time_end >= m_timeMax * 1000000.0)
			{
				cout << "Time Limit:" << m_timeMax << " exceeded." << endl;
				stop = true;
			}
		}
	}

	chrono::steady_clock::time_point timeEnd = chrono::high_resolution_clock::now();

	// Compute Optimal MODI Value
	updateXij(m_cij, m_dj, m_bi, m_incumbent_solution, m_update_xij_mode, m_best_fx);

	// Save Solution and Timestamps to File
	printFinalSolution(m_incumbent_solution, m_best_fx, m_kMax, m_tMax, m_shaking_mode,
		m_local_search_mode, m_update_xij_mode, m_initial_mode, m_directory, timeStart, timeEnd);
}

vector<bool> BVNS::localSearch(
	const vector<bool> &perturbed_solution,
	const vector<vector<bool>> &neighborhood_k,
	const unsigned int &k,
	double &fx,
	const unsigned int &local_search_mode)
{
	if (local_search_mode == 0)
		return localSearchFirstImprovment(perturbed_solution, neighborhood_k, k, fx);
	else
		return localSearchBestImprovment(perturbed_solution, neighborhood_k, k, fx);
}


text:
// Copyright (c) 2020-2021 Franz Alt
// This code is licensed under MIT license (see LICENSE.txt for details).

#include <libcvpg/videoproc/processors/frame.hpp>

#include <exception>
#include <future>
#include <vector>

#include <boost/asynchronous/continuation_task.hpp>

#include <libcvpg/core/exception.hpp>
#include <libcvpg/videoproc/stage_data_handler.hpp>

namespace cvpg::videoproc::processors {

template<typename Image> struct frame<Image>::processing_context
{
    std::size_t frames_id = 0;

    bool prev_stage_finished = false;

    struct status_info
    {
        std::size_t next_waiting = 0;

        std::size_t packet_counter = 0;
    };

    status_info status;

    struct callback_info
    {
        std::function<void(std::size_t, std::map<std::string, std::any>)> params;
        std::function<void(std::size_t, videoproc::packet<videoproc::frame<Image> >)> deliver_packet;
        std::function<void(std::size_t, std::size_t)> next;
        std::function<void(std::size_t)> finished;
        std::function<void(std::size_t, std::string)> failed;
        std::function<void(std::size_t, videoproc::update_indicator)> update_indicator;
    };

    callback_info callbacks;

    std::shared_ptr<stage_data_handler<videoproc::frame<Image> > > sdh_out;
};

template<typename Image> frame<Image>::frame(boost::asynchronous::any_weak_scheduler<imageproc::scripting::diagnostics::servant_job> scheduler,
                                             std::size_t max_frames_output_buffer,
                                             imageproc::scripting::image_processor_proxy image_processor)
    : boost::asynchronous::trackable_servant<imageproc::scripting::diagnostics::servant_job, imageproc::scripting::diagnostics::servant_job>(scheduler)
    , m_max_frames_output_buffer(max_frames_output_buffer)
    , m_image_processor(std::make_shared<imageproc::scripting::image_processor_proxy>(image_processor))
    , m_contexts()
{}

template<typename Image> void frame<Image>::init(std::size_t context_id, std::string script, stage_callbacks<Image> callbacks)
{
    // create new processing context
    auto context = std::make_shared<processing_context>();
    context->callbacks.params = std::move(callbacks.parameters);
    context->callbacks.deliver_packet = std::move(callbacks.deliver);
    context->callbacks.next = std::move(callbacks.next);
    context->callbacks.finished = std::move(callbacks.finished);
    context->callbacks.failed = std::move(callbacks.failed);
    context->callbacks.update_indicator = std::move(callbacks.update);

    context->sdh_out = std::make_shared<stage_data_handler<videoproc::frame<Image> > >(
        "frame",
        m_max_frames_output_buffer,
        [context_id, context]()
        {
            const auto free = context->sdh_out->free();

            if (free != 0)
            {
                // inform previous stage that this stage is ready to receive new data
                context->callbacks.next(context_id, free);
            }
        },
        [context]()
        {
            return context->status.next_waiting;
        },
        [this, context_id, context](std::vector<videoproc::frame<Image> > frames, std::function<void()> deliver_done_callback)
        {
            if (!frames.empty())
            {
                context->status.next_waiting = 0;

                auto packet_number = context->status.packet_counter;

                videoproc::packet<videoproc::frame<Image> > packet(packet_number);

                for (auto & f : frames)
                {
                    packet.add_frame(std::move(f));
                }

                context->callbacks.deliver_packet(context_id, std::move(packet));
            }

            deliver_done_callback();
        }
    );

    m_contexts.insert({ context_id, context });

    // compiling script
    struct compile_result
    {
        std::size_t id = 0;
        std::string error;
    };

    auto promise_compile = std::make_shared<std::promise<compile_result> >();

    std::vector<std::future<compile_result> > futures_compile;
    futures_compile.reserve(1);
    futures_compile.push_back(promise_compile->get_future());

    // compile frame script
    m_image_processor->compile(
        script,
        [promise_compile, context_id](std::size_t compile_id)
        {
            promise_compile->set_value({ compile_id });
        },
        [promise_compile, context_id](std::size_t compile_id, std::string error)
        {
            promise_compile->set_value({ compile_id, std::move(error) });
        }
    );

    boost::asynchronous::create_continuation_job<imageproc::scripting::diagnostics::diag_type>(
        [image_processor = m_image_processor, context, context_id, init_done_callback = std::move(callbacks.initialized)](auto cont_res) mutable
        {
            try
            {
                auto result = std::move(cont_res.at(0).get());

                context->frames_id = result.id;

                if (result.error.empty())
                {
                    init_done_callback(context_id, 0);
                }
                else
                {
                    throw cvpg::exception(result.error);
                }
            }
            catch (std::exception const & e)
            {
                // TODO report error
            }
            catch (...)
            {
                // TODO report error
            }
        },
        std::move(futures_compile)
    );

    context->sdh_out->try_flush();
}

template<typename Image> void frame<Image>::params(std::size_t context_id, std::map<std::string, std::any> p)
{
    auto it = m_contexts.find(context_id);

    if (it != m_contexts.end())
    {
        auto & context = it->second;

        context->callbacks.params(context_id, std::move(p));
    }
}

template<typename Image> void frame<Image>::start(std::size_t context_id)
{
    auto it = m_contexts.find(context_id);

    if (it != m_contexts.end())
    {
        auto & context = it->second;

        if (!(context->prev_stage_finished))
        {
            context->callbacks.next(context_id, context->sdh_out->free());
        }
    }
}

template<typename Image> void frame<Image>::finish(std::size_t context_id)
{
    auto it = m_contexts.find(context_id);

    if (it != m_contexts.end())
    {
        auto & context = it->second;

        context->prev_stage_finished = true;
    }
}

template<typename Image> void frame<Image>::process(std::size_t context_id, videoproc::packet<videoproc::frame<Image> > && packet)
{
    auto it = m_contexts.find(context_id);

    if (it != m_contexts.end())
    {
        auto & context = it->second;

        process_next_frames(context_id, std::move(packet.move_frames()));
    }
}

template<typename Image> void frame<Image>::next(std::size_t context_id, std::size_t max_new_data)
{
    auto it = m_contexts.find(context_id);

    if (it != m_contexts.end())
    {
        auto & context = it->second;

        context->status.next_waiting = max_new_data;

        context->sdh_out->try_flush();
    }
}

template<typename Image> void frame<Image>::process_next_frames(std::size_t context_id, std::vector<videoproc::frame<Image> > && frames)
{
    auto it = m_contexts.find(context_id);

    if (it != m_contexts.end())
    {
        auto & context = it->second;

        // update packet counter
        context->status.packet_counter++;

        // calling the image processor for each frame
        bool flush_frame = false;
        std::size_t flush_number = 0;

        for (auto & frame : frames)
        {
            const auto frame_number = frame.number();

            if (frame.flush())
            {
                flush_frame = true;
                flush_number = frame_number;
                continue;
            }

            auto image = frame.move_image();

            m_image_processor->evaluate_convert_if(
                context->frames_id,
                std::move(image),
                make_safe_callback(
                    [context, context_id, frame_number](typename videoproc::frame<Image>::image_type image)
                    {
                        context->callbacks.update_indicator(context_id, videoproc::update_indicator("frame", 1, 0));

                        context->sdh_out->add(typename videoproc::frame<Image>(frame_number, std::move(image)));
                    },
                    "processors::frame::process_next_frames::callback::success",
                    1
                ),
                make_safe_callback(
                    [context](std::size_t context_id, std::string error)
                    {
                        context->callbacks.update_indicator(context_id, videoproc::update_indicator("frame", 0, 1));

                        context->callbacks.failed(context_id, std::move(error));
                    },
                    "processors::frame::process_next_frames::callback::failed",
                    1
                )
            );
        }

        if (flush_frame)
        {
            context->sdh_out->add(typename videoproc::frame<Image>(flush_number));
        }
    }
}

// manual instantiation of frame<> for some types
template class frame<cvpg::image_gray_8bit>;
template class frame<cvpg::image_rgb_8bit>;

} // namespace cvpg::videoproc::processors

max_stars_repo_name: franz-alt/cv-playground

max_issues_repo_name: franz-alt/cv-playground

max_forks_repo_name: franz-alt/cv-playground


text:
/*
Copyright 2017-2018 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CORE_POINTER_TRAITS_HPP
#define BOOST_CORE_POINTER_TRAITS_HPP

#include <boost/config.hpp>
#if !defined(BOOST_NO_CXX11_POINTER_TRAITS)
#include <memory>
#else
#include <boost/core/addressof.hpp>
#endif

namespace boost
{

#if !defined(BOOST_NO_CXX11_POINTER_TRAITS)
template <class T>
struct pointer_traits : std::pointer_traits<T>
{
    template <class U>
    struct rebind_to
    {
        typedef typename std::pointer_traits<T>::template rebind<U> type;
    };
};

template <class T>
struct pointer_traits<T*> : std::pointer_traits<T*>
{
    template <class U>
    struct rebind_to
    {
        typedef U* type;
    };
};
#else
namespace detail
{

template <class>
struct ptr_void
{
    typedef void type;
};

template <class T>
struct ptr_first;

#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <template <class, class...> class T, class U, class... Args>
struct ptr_first<T<U, Args...>>
{
    typedef U type;
};
#else
template <template <class> class T, class U>
struct ptr_first<T<U>>
{
    typedef U type;
};

template <template <class, class> class T, class U1, class U2>
struct ptr_first<T<U1, U2>>
{
    typedef U1 type;
};

template <template <class, class, class> class T, class U1, class U2, class U3>
struct ptr_first<T<U1, U2, U3>>
{
    typedef U1 type;
};
#endif

template <class T, class = void>
struct ptr_element
{
    typedef typename ptr_first<T>::type type;
};

template <class T>
struct ptr_element<T, typename ptr_void<typename T::element_type>::type>
{
    typedef typename T::element_type type;
};

template <class, class = void>
struct ptr_difference
{
    typedef std::ptrdiff_t type;
};

template <class T>
struct ptr_difference<T, typename ptr_void<typename T::difference_type>::type>
{
    typedef typename T::difference_type type;
};

template <class T, class V>
struct ptr_transform;

#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template <template <class, class...> class T, class U, class... Args, class V>
struct ptr_transform<T<U, Args...>, V>
{
    typedef T<V, Args...> type;
};
#else
template <template <class> class T, class U, class V>
struct ptr_transform<T<U>, V>
{
    typedef T<V> type;
};

template <template <class, class> class T, class U1, class U2, class V>
struct ptr_transform<T<U1, U2>, V>
{
    typedef T<V, U2> type;
};

template <template <class, class, class> class T, class U1, class U2, class U3,
          class V>
struct ptr_transform<T<U1, U2, U3>, V>
{
    typedef T<V, U2, U3> type;
};
#endif

template <class T, class U, class = void>
struct ptr_rebind
{
    typedef typename ptr_transform<T, U>::type type;
};

#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
template <class T, class U>
struct ptr_rebind<T, U, typename ptr_void<typename T::template rebind<U>>::type>
{
    typedef typename T::template rebind<U> type;
};
#endif

template <class T>
struct ptr_value
{
    typedef T type;
};

template <>
struct ptr_value<void>
{
    typedef struct
    {
    } type;
};

} // namespace detail

template <class T>
struct pointer_traits
{
    typedef T pointer;
    typedef typename detail::ptr_element<T>::type element_type;
    typedef typename detail::ptr_difference<T>::type difference_type;
    template <class U>
    struct rebind_to
    {
        typedef typename detail::ptr_rebind<T, U>::type type;
    };
#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
    template <class U>
    using rebind = typename detail::ptr_rebind<T, U>::type;
#endif
    static pointer pointer_to(typename detail::ptr_value<element_type>::type& v)
    {
        return pointer::pointer_to(v);
    }
};

template <class T>
struct pointer_traits<T*>
{
    typedef T* pointer;
    typedef T element_type;
    typedef std::ptrdiff_t difference_type;
    template <class U>
    struct rebind_to
    {
        typedef U* type;
    };
#if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES)
    template <class U>
    using rebind = U*;
#endif
    static T* pointer_to(typename detail::ptr_value<T>::type& v) BOOST_NOEXCEPT
    {
        return boost::addressof(v);
    }
};
#endif

template <class T>
BOOST_CONSTEXPR inline T* to_address(T* v) BOOST_NOEXCEPT
{
    return v;
}

#if !defined(BOOST_NO_CXX14_RETURN_TYPE_DEDUCTION)
namespace detail
{

template <class T>
inline T* ptr_address(T* v, int) BOOST_NOEXCEPT
{
    return v;
}

template <class T>
inline auto ptr_address(const T& v, int) BOOST_NOEXCEPT
    -> decltype(boost::pointer_traits<T>::to_address(v))
{
    return boost::pointer_traits<T>::to_address(v);
}

template <class T>
inline auto ptr_address(const T& v, long) BOOST_NOEXCEPT
{
    return boost::detail::ptr_address(v.operator->(), 0);
}

} // namespace detail

template <class T>
inline auto to_address(const T& v) BOOST_NOEXCEPT
{
    return boost::detail::ptr_address(v, 0);
}
#else
template <class T>
inline typename pointer_traits<T>::element_type*
    to_address(const T& v) BOOST_NOEXCEPT
{
    return boost::to_address(v.operator->());
}
#endif

} // namespace boost

#endif

ext: hpp

max_stars_repo_name: sotaoverride/backup

max_issues_repo_name: sotaoverride/backup

max_forks_repo_name: sotaoverride/backup


text:
//
// third_party_lib.cpp
// ~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <asio.hpp>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <iostream>

using asio::ip::tcp;

namespace third_party_lib {

// Simulation of a third party library that wants to perform read and write
// operations directly on a socket. It needs to be polled to determine whether
// it requires a read or write operation, and notified when the socket is ready
// for reading or writing.
class session
{
public:
  session(tcp::socket& socket)
    : socket_(socket),
      state_(reading)
  {
  }

  // Returns true if the third party library wants to be notified when the
  // socket is ready for reading.
  bool want_read() const
  {
    return state_ == reading;
  }

  // Notify that third party library that it should perform its read operation.
  void do_read(asio::error_code& ec)
  {
    if (std::size_t len = socket_.read_some(asio::buffer(data_), ec))
    {
      write_buffer_ = asio::buffer(data_, len);
      state_ = writing;
    }
  }

  // Returns true if the third party library wants to be notified when the
  // socket is ready for writing.
  bool want_write() const
  {
    return state_ == writing;
  }

  // Notify that third party library that it should perform its write operation.
  void do_write(asio::error_code& ec)
  {
    if (std::size_t len = socket_.write_some(
          asio::buffer(write_buffer_), ec))
    {
      write_buffer_ = write_buffer_ + len;
      state_ = asio::buffer_size(write_buffer_) > 0 ? writing : reading;
    }
  }

private:
  tcp::socket& socket_;
  enum { reading, writing } state_;
  boost::array<char, 128> data_;
  asio::const_buffer write_buffer_;
};

} // namespace third_party_lib

// The glue between asio's sockets and the third party library.
class connection
  : public boost::enable_shared_from_this<connection>
{
public:
  typedef boost::shared_ptr<connection> pointer;

  static pointer create(asio::io_context& io_context)
  {
    return pointer(new connection(io_context));
  }

  tcp::socket& socket()
  {
    return socket_;
  }

  void start()
  {
    // Put the socket into non-blocking mode.
    socket_.non_blocking(true);

    start_operations();
  }

private:
  connection(asio::io_context& io_context)
    : socket_(io_context),
      session_impl_(socket_),
      read_in_progress_(false),
      write_in_progress_(false)
  {
  }

  void start_operations()
  {
    // Start a read operation if the third party library wants one.
    if (session_impl_.want_read() && !read_in_progress_)
    {
      read_in_progress_ = true;
      socket_.async_wait(tcp::socket::wait_read,
          boost::bind(&connection::handle_read,
            shared_from_this(),
            asio::placeholders::error));
    }

    // Start a write operation if the third party library wants one.
    if (session_impl_.want_write() && !write_in_progress_)
    {
      write_in_progress_ = true;
      socket_.async_wait(tcp::socket::wait_write,
          boost::bind(&connection::handle_write,
            shared_from_this(),
            asio::placeholders::error));
    }
  }

  void handle_read(asio::error_code ec)
  {
    read_in_progress_ = false;

    // Notify third party library that it can perform a read.
    if (!ec)
      session_impl_.do_read(ec);

    // The third party library successfully performed a read on the socket.
    // Start new read or write operations based on what it now wants.
    if (!ec || ec == asio::error::would_block)
      start_operations();

    // Otherwise, an error occurred. Closing the socket cancels any outstanding
    // asynchronous read or write operations. The connection object will be
    // destroyed automatically once those outstanding operations complete.
    else
      socket_.close();
  }

  void handle_write(asio::error_code ec)
  {
    write_in_progress_ = false;

    // Notify third party library that it can perform a write.
    if (!ec)
      session_impl_.do_write(ec);

    // The third party library successfully performed a write on the socket.
    // Start new read or write operations based on what it now wants.
    if (!ec || ec == asio::error::would_block)
      start_operations();

    // Otherwise, an error occurred. Closing the socket cancels any outstanding
    // asynchronous read or write operations. The connection object will be
    // destroyed automatically once those outstanding operations complete.
    else
      socket_.close();
  }

private:
  tcp::socket socket_;
  third_party_lib::session session_impl_;
  bool read_in_progress_;
  bool write_in_progress_;
};

class server
{
public:
  server(asio::io_context& io_context, unsigned short port)
    : acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
  {
    start_accept();
  }

private:
  void start_accept()
  {
    connection::pointer new_connection =
      connection::create(acceptor_.get_executor().context());

    acceptor_.async_accept(new_connection->socket(),
        boost::bind(&server::handle_accept, this, new_connection,
          asio::placeholders::error));
  }

  void handle_accept(connection::pointer new_connection,
      const asio::error_code& error)
  {
    if (!error)
    {
      new_connection->start();
    }

    start_accept();
  }

  tcp::acceptor acceptor_;
};

int main(int argc, char* argv[])
{
  try
  {
    if (argc != 2)
    {
      std::cerr << "Usage: third_party_lib <port>\n";
      return 1;
    }

    asio::io_context io_context;

    using namespace std; // For atoi.
    server s(io_context, atoi(argv[1]));

    io_context.run();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}


text:
#define BOOST_TEST_MODULE ReduceByKey
#include <algorithm>
#include <numeric>
#include <boost/test/unit_test.hpp>
#include <vexcl/vector.hpp>
#include <vexcl/scan_by_key.hpp>
#include "context_setup.hpp"

bool nvidia_cl(const vex::Context &ctx) {
#if defined(VEXCL_BACKEND_CUDA) || defined(VEXCL_BACKEND_JIT)
    return false;
#else
    return vex::Filter::Platform("NVIDIA")(ctx.device(0));
#endif
}

BOOST_AUTO_TEST_CASE(sbk)
{
    // NVIDIA OpenCL compiler crashes on scan_by_key kernels.
    if (nvidia_cl(ctx)) return;

    const int n = 1000;

    std::vector<int> x = random_vector<int>(n);
    std::vector<int> y = random_vector<int>(n);

    std::sort(x.begin(), x.end());

    std::vector<vex::backend::command_queue> queue(1, ctx.queue(0));

    vex::vector<int> ikeys(queue, x);
    vex::vector<int> ivals(queue, y);
    vex::vector<int> ovals(queue, n);

    vex::inclusive_scan_by_key(ikeys, ivals, ovals);

    check_sample(ovals, [&](size_t i, int v) {
            if (i == 0)
                BOOST_CHECK_EQUAL(v, y[i]);
            else if (x[i-1] == x[i])
                BOOST_CHECK_EQUAL(
                    y[i],
                    static_cast<int>(ovals[i]) - static_cast<int>(ovals[i-1])
                    );
            else
                BOOST_CHECK_EQUAL(v, y[i]);
            });

    vex::exclusive_scan_by_key(ikeys, ivals, ovals);

    check_sample(ovals, [&](size_t i, int v) {
            if (i == 0)
                BOOST_CHECK_EQUAL(v, 0);
            else if (x[i-1] == x[i])
                BOOST_CHECK_EQUAL(
                    y[i-1],
                    static_cast<int>(ovals[i]) - static_cast<int>(ovals[i-1])
                    );
            else
                BOOST_CHECK_EQUAL(v, 0);
            });
}

BOOST_AUTO_TEST_CASE(sbk_tuple)
{
    // NVIDIA OpenCL compiler crashes on scan_by_key kernels.
    if (nvidia_cl(ctx)) return;

    const int n = 1000;

    std::vector<int> x1 = random_vector<int>(n);
    std::vector<int> x2 = random_vector<int>(n);
    std::vector<int> y  = random_vector<int>(n);

    std::sort(x1.begin(), x1.end());
    std::sort(x2.begin(), x2.end());

    std::vector<vex::backend::command_queue> queue(1, ctx.queue(0));

    vex::vector<int> ikey1(queue, x1);
    vex::vector<int> ikey2(queue, x2);
    vex::vector<int> ivals(queue, y);
    vex::vector<int> ovals(queue, n);

    VEX_FUNCTION(bool, equal, (int, a1)(int, a2)(int, b1)(int, b2),
            return a1 == b1 && a2 == b2;
            );

    VEX_FUNCTION(int, plus, (int, x)(int, y),
            return x + y;
            );

    vex::inclusive_scan_by_key(
            boost::fusion::vector_tie(ikey1, ikey2), ivals, ovals,
            equal, plus);

    check_sample(ovals, [&](size_t i, int v) {
            if (i == 0)
                BOOST_CHECK_EQUAL(v, y[i]);
            else if (std::make_tuple(x1[i-1], x2[i-1]) == std::make_tuple(x1[i], x2[i]))
                BOOST_CHECK_EQUAL(
                    y[i],
                    static_cast<int>(ovals[i]) - static_cast<int>(ovals[i-1])
                    );
            else
                BOOST_CHECK_EQUAL(v, y[i]);
            });

    vex::exclusive_scan_by_key(
            boost::fusion::vector_tie(ikey1, ikey2), ivals, ovals,
            equal, plus);

    check_sample(ovals, [&](size_t i, int v) {
            if (i == 0)
                BOOST_CHECK_EQUAL(v, 0);
            else if (std::make_tuple(x1[i-1], x2[i-1]) == std::make_tuple(x1[i], x2[i]))
                BOOST_CHECK_EQUAL(
                    y[i-1],
                    static_cast<int>(ovals[i]) - static_cast<int>(ovals[i-1])
                    );
            else
                BOOST_CHECK_EQUAL(v, 0);
            });
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: lkusch/Kratos

max_issues_repo_name: lkusch/Kratos

max_forks_repo_name: lkusch/Kratos


text:
//
// OpenTissue, A toolbox for physical based simulation and animation.
// Copyright (C) 2007 Department of Computer Science, University of Copenhagen
//
#include <OpenTissue/configuration.h>

#include <OpenTissue/core/math/math_basic_types.h>
#include <OpenTissue/core/math/math_eigen_system_decomposition.h>

#define BOOST_AUTO_TEST_MAIN
#include <OpenTissue/utility/utility_push_boost_filter.h>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/test_tools.hpp>
#include <OpenTissue/utility/utility_pop_boost_filter.h>

#include <cmath>

using namespace OpenTissue;

template<typename vector3_type,typename matrix3x3_type>
void eigen_value_decomposition_test(vector3_type d,matrix3x3_type R)
{
  using std::fabs;

  typedef typename vector3_type::value_type    real_type;
  typedef typename vector3_type::value_traits  value_traits;

  real_type tol = 0.0001;

  vector3_type r1 = vector3_type(R(0,0),R(1,0),R(2,0));
  vector3_type r2 = vector3_type(R(0,1),R(1,1),R(2,1));
  vector3_type r3 = vector3_type(R(0,2),R(1,2),R(2,2));
  real_type    d0 = d(0);
  real_type    d1 = d(1);
  real_type    d2 = d(2);

  matrix3x3_type D = diag(d);
  matrix3x3_type A = R*D*trans(R);
  BOOST_CHECK( is_symmetric(A,tol) );

  matrix3x3_type V;
  OpenTissue::math::eigen(A, V, d);

  vector3_type e1 = vector3_type(V(0,0),V(1,0),V(2,0));
  vector3_type e2 = vector3_type(V(0,1),V(1,1),V(2,1));
  vector3_type e3 = vector3_type(V(0,2),V(1,2),V(2,2));

  real_type determinant = det(V);
  BOOST_CHECK_CLOSE( fabs( determinant ), value_traits::one(), tol );

  real_type epsilon = 10e-7;

  matrix3x3_type Itest = trans(V)*V;

  BOOST_CHECK_CLOSE( Itest(0,0), value_traits::one() , tol );
  BOOST_CHECK_CLOSE( Itest(1,1), value_traits::one() , tol );
  BOOST_CHECK_CLOSE( Itest(2,2), value_traits::one() , tol );
  //--- The check close versin behaves strange when rhs is exactly
  //--- zero?, so I use the check-version instead...
  //BOOST_CHECK_CLOSE(      Itest(0,1) , value_traits::zero(), tol );
  //BOOST_CHECK_CLOSE(      Itest(0,2) , value_traits::zero(), tol );
  //BOOST_CHECK_CLOSE(      Itest(1,0) , value_traits::zero(), tol );
  //BOOST_CHECK_CLOSE(      Itest(1,2) , value_traits::zero(), tol );
  //BOOST_CHECK_CLOSE(      Itest(2,0) , value_traits::zero(), tol );
  //BOOST_CHECK_CLOSE(      Itest(2,1) , value_traits::zero(), tol );
  BOOST_CHECK( fabs(Itest(0,1))<epsilon );
  BOOST_CHECK( fabs(Itest(0,2))<epsilon );
  BOOST_CHECK( fabs(Itest(1,0))<epsilon );
  BOOST_CHECK( fabs(Itest(1,2))<epsilon );
  BOOST_CHECK( fabs(Itest(2,0))<epsilon );
  BOOST_CHECK( fabs(Itest(2,1))<epsilon );

  matrix3x3_type Atest = A - V*diag(d)*trans(V);

  BOOST_CHECK( fabs(Atest(0,0))<epsilon );
  BOOST_CHECK( fabs(Atest(0,1))<epsilon );
  BOOST_CHECK( fabs(Atest(0,2))<epsilon );
  BOOST_CHECK( fabs(Atest(1,0))<epsilon );
  BOOST_CHECK( fabs(Atest(1,1))<epsilon );
  BOOST_CHECK( fabs(Atest(1,2))<epsilon );
  BOOST_CHECK( fabs(Atest(2,0))<epsilon );
  BOOST_CHECK( fabs(Atest(2,1))<epsilon );
  BOOST_CHECK( fabs(Atest(2,2))<epsilon );

  bool match1 = fabs( d0 - d(0) ) < epsilon &&
                fabs( d1 - d(1) ) < epsilon &&
                fabs( d2 - d(2) ) < epsilon ;

  bool match2 = fabs( d0 - d(0) )< epsilon &&
                fabs( d1 - d(2) )< epsilon &&
                fabs( d2 - d(1) )< epsilon ;

  bool match3 = fabs( d0 - d(1) )< epsilon &&
                fabs( d1 - d(0) )< epsilon &&
                fabs( d2 - d(2) )< epsilon ;

  bool match4 = fabs( d0 - d(1) )< epsilon &&
                fabs( d1 - d(2) )< epsilon &&
                fabs( d2 - d(0) )< epsilon ;

  bool match5 = fabs( d0 - d(2) )< epsilon &&
                fabs( d1 - d(0) )< epsilon &&
                fabs( d2 - d(1) )< epsilon ;

  bool match6 = fabs( d0 - d(2) )< epsilon &&
                fabs( d1 - d(1) )< epsilon &&
                fabs( d2 - d(0) )< epsilon ;

  BOOST_CHECK( match1 || match2 || match3 || match4 || match5 || match6 );
}

BOOST_AUTO_TEST_SUITE(opentissue_math_eigen);

  BOOST_AUTO_TEST_CASE(random_testing)
  {
    typedef OpenTissue::math::BasicMathTypes<double, size_t> math_types;
    typedef math_types::vector3_type                         vector3_type;
    typedef math_types::matrix3x3_type                       matrix3x3_type;
    typedef math_types::real_type                            real_type;

    matrix3x3_type R;
    vector3_type d;

    for(int i= 0;i<100;++i)
    {
      //--- non-negative eigen-values
      random(d,0,1);
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- non-positive eigen-values
      random(d,-1,0);
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- one zero eigen-values
      random(d,0,1);
      d(0) = 0;
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- one zero eigen-values
      random(d,0,1);
      d(1) = 0;
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- one zero eigen-values
      random(d,0,1);
      d(2) = 0;
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- two zero eigen-values
      random(d,0,1);
      d(0) = 0;
      d(1) = 0;
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- two zero eigen-values
      random(d,0,1);
      d(0) = 0;
      d(2) = 0;
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- two zero eigen-values
      random(d,0,1);
      d(1) = 0;
      d(2) = 0;
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- three zero eigen-values
      d.clear();
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- multiplicity of 3
      random(d,0,1);
      d(1) = d(0);
      d(2) = d(0);
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- multiplicity of 2
      random(d,0,1);
      d(1) = d(0);
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- multiplicity of 2
      random(d,0,1);
      d(2) = d(0);
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);

      //--- multiplicity of 2
      random(d,0,1);
      d(2) = d(1);
      random(R);
      R = ortonormalize(R);
      eigen_value_decomposition_test(d,R);
    }
  }

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ricortiz/OpenTissue

max_issues_repo_name: ricortiz/OpenTissue

max_forks_repo_name: ricortiz/OpenTissue


text:
/*
 * Copyright (C) 2012-2015 Open Source Robotics Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
/* Desc: Base class for all physical entities
 * Author: Nate Koenig
 * Date: 03 Apr 2007
 */

#ifndef _ENTITY_HH_
#define _ENTITY_HH_

#include <string>
#include <vector>

#include <boost/function.hpp>
#include "gazebo/msgs/msgs.hh"

#include "gazebo/transport/TransportTypes.hh"
#include "gazebo/common/CommonTypes.hh"
#include "gazebo/common/UpdateInfo.hh"

#include "gazebo/math/MathTypes.hh"
#include "gazebo/math/Box.hh"
#include "gazebo/math/Pose.hh"

#include "gazebo/physics/PhysicsTypes.hh"
#include "gazebo/physics/Base.hh"
#include "gazebo/util/system.hh"

namespace boost
{
  class recursive_mutex;
}

namespace gazebo
{
  namespace physics
  {
    /// \addtogroup gazebo_physics
    /// \{

    /// \class Entity Entity.hh physics/physics.hh
    /// \brief Base class for all physics objects in Gazebo.
    class GZ_PHYSICS_VISIBLE Entity : public Base
    {
      /// \brief Constructor.
      /// \param[in] _parent Parent of the entity.
      public: explicit Entity(BasePtr _parent);

      /// \brief Destructor.
      public: virtual ~Entity();

      /// \brief Load the entity.
      /// \param[in] _sdf Pointer to an SDF element.
      public: virtual void Load(sdf::ElementPtr _sdf);

      /// \brief Finalize the entity.
      public: virtual void Fini();

      /// \brief Reset the entity.
      public: virtual void Reset();

      /// \brief Update the parameters using new sdf values.
      /// \param[in] _sdf SDF to update from.
      public: virtual void UpdateParameters(sdf::ElementPtr _sdf);

      /// \brief Set the name of the entity.
      /// \param[in] _name The new name.
      public: virtual void SetName(const std::string &_name);

      /// \brief Set whether this entity is static: immovable.
      /// \param[in] _static True = static.
      public: void SetStatic(const bool &_static);

      /// \brief Return whether this entity is static.
      /// \return True if static.
      public: bool IsStatic() const;

      /// \brief Set the initial pose.
      /// \param[in] _pose The initial pose.
      public: void SetInitialRelativePose(const math::Pose &_pose);

      /// \brief Get the initial relative pose.
      /// \return The initial relative pose.
      public: math::Pose GetInitialRelativePose() const;

      /// \brief Return the bounding box for the entity.
      /// \return The bounding box.
      public: virtual math::Box GetBoundingBox() const;

      /// \brief Get the absolute pose of the entity.
      /// \return The absolute pose of the entity.
      public: inline virtual const math::Pose &GetWorldPose() const
              {return this->worldPose;}

      /// \brief Get the pose of the entity relative to its parent.
      /// \return The pose of the entity relative to its parent.
      public: math::Pose GetRelativePose() const;

      /// \brief Set the pose of the entity relative to its parent.
      /// \param[in] _pose The new pose.
      /// \param[in] _notify True = tell children of the pose change.
      /// \param[in] _publish True to publish the pose.
      public: void SetRelativePose(const math::Pose &_pose,
                                   bool _notify = true,
                                   bool _publish = true);

      /// \brief Set the world pose of the entity.
      /// \param[in] _pose The new world pose.
      /// \param[in] _notify True = tell children of the pose change.
      /// \param[in] _publish True to publish the pose.
      public: void SetWorldPose(const math::Pose &_pose,
                                bool _notify = true,
                                bool _publish = true);

      /// \brief Get the linear velocity of the entity.
      /// \return A math::Vector3 for the linear velocity.
      public: virtual math::Vector3 GetRelativeLinearVel() const
              {return math::Vector3();}

      /// \brief Get the linear velocity of the entity in the world frame.
      /// \return A math::Vector3 for the linear velocity.
      public: virtual math::Vector3 GetWorldLinearVel() const
              {return math::Vector3();}

      /// \brief Get the angular velocity of the entity.
      /// \return A math::Vector3 for the velocity.
      public: virtual math::Vector3 GetRelativeAngularVel() const
              {return math::Vector3();}

      /// \brief Get the angular velocity of the entity in the world frame.
      /// \return A math::Vector3 for the velocity.
      public: virtual math::Vector3 GetWorldAngularVel() const
              {return math::Vector3();}

      /// \brief Get the linear acceleration of the entity.
      /// \return A math::Vector3 for the acceleration.
      public: virtual math::Vector3 GetRelativeLinearAccel() const
              {return math::Vector3();}

      /// \brief Get the linear acceleration of the entity in the world frame.
      /// \return A math::Vector3 for the acceleration.
      public: virtual math::Vector3 GetWorldLinearAccel() const
              {return math::Vector3();}

      /// \brief Get the angular acceleration of the entity.
      /// \return A math::Vector3 for the acceleration.
      public: virtual math::Vector3 GetRelativeAngularAccel() const
              {return math::Vector3();}

      /// \brief Get the angular acceleration of the entity in the world frame.
      /// \return A math::Vector3 for the acceleration.
      public: virtual math::Vector3 GetWorldAngularAccel() const
              {return math::Vector3();}

      /// \brief Set to true if this entity is a canonical link for a model.
      /// \param[in] _value True if the link is canonical.
      public: void SetCanonicalLink(bool _value);

      /// \brief A helper function that checks if this is a canonical body.
      /// \return True if the link is canonical.
      public: inline bool IsCanonicalLink() const
              {return this->isCanonicalLink;}

      /// \brief Set an animation for this entity.
      /// \param[in] _anim Pose animation.
      /// \param[in] _onComplete Callback for when the animation completes.
      public: void SetAnimation(const common::PoseAnimationPtr &_anim,
                                boost::function<void()> _onComplete);

      /// \brief Set an animation for this entity.
      /// \param[in] _anim Pose animation.
      public: void SetAnimation(common::PoseAnimationPtr _anim);

      /// \brief Stop the current animation, if any.
      public: virtual void StopAnimation();

      /// \brief Get the parent model, if one exists.
      /// \return Pointer to a model, or NULL if no parent model exists.
      public: ModelPtr GetParentModel();

      /// \brief Get a child collision entity, if one exists.
      /// \param[in] _name Name of the child collision object.
      /// \return Pointer to the Collision object, or NULL if not found.
      public: CollisionPtr GetChildCollision(const std::string &_name);

      /// \brief Get a child linke entity, if one exists.
      /// \param[in] _name Name of the child Link object.
      /// \return Pointer to the Link object, or NULL if not found.
      public: LinkPtr GetChildLink(const std::string &_name);

      /// \brief Get the distance to the nearest entity below
      /// (along the Z-axis) this entity.
      /// \param[out] _distBelow The distance to the nearest entity below.
      /// \param[out] _entityName The name of the nearest entity below.
      public: void GetNearestEntityBelow(double &_distBelow,
                                         std::string &_entityName);

      /// \brief Move this entity to be ontop of the nearest entity below.
      public: void PlaceOnNearestEntityBelow();

      /// \brief Move this entity to be ontop of another entity by name.
      /// \param[in] _entityName Name of the Entity this Entity should be
      /// ontop of.
      public: void PlaceOnEntity(const std::string &_entityName);

      /// \brief Returns collision bounding box.
      /// \return Collsiion boundin box.
      public: math::Box GetCollisionBoundingBox() const;

      /// \brief Set angular and linear rates of an physics::Entity.
      /// \param[in] _linear Linear twist.
      /// \param[in] _angular Angular twist.
      /// \param[in] _updateChildren True to pass this update to child
      /// entities.
      public: void SetWorldTwist(const math::Vector3 &_linear,
                                 const math::Vector3 &_angular,
                                 bool _updateChildren = true);

      /// \brief Returns Entity#dirtyPose.
      ///
      /// The dirty pose is the pose set by the physics engine before it's
      /// value is propagated to the rest of the simulator.
      /// \return The dirty pose of the entity.
      public: const math::Pose &GetDirtyPose() const;

      /// \brief This function is called when the entity's
      /// (or one of its parents) pose of the parent has changed.
      protected: virtual void OnPoseChange() = 0;

      /// \brief Publish the pose.
      private: void PublishPose();

      /// \brief Helper function to get the collision bounding box.
      /// \param[in] _base Object to calculated the bounding box for.
      /// \return The boundin box for the passed in object.
      private: math::Box GetCollisionBoundingBoxHelper(BasePtr _base) const;

      /// \brief Set the world pose for a model.
      /// \param[in] _pose New pose for the entity.
      /// \param[in] _notify True to notify children of the pose update.
      /// \param[in] _publish True to publish the pose.
      private: void SetWorldPoseModel(const math::Pose &_pose,
                                      bool _notify,
                                      bool _publish);

      /// \brief Set the world pose for a canonical Link.
      /// \param[in] _pose New pose for the entity.
      /// \param[in] _notify True to notify children of the pose update.
      /// \param[in] _publish True to publish the pose.
      private: void SetWorldPoseCanonicalLink(const math::Pose &_pose,
                                              bool _notify, bool _publish);

      /// \brief Set the world pose for a common entity.
      /// \param[in] _pose New pose for the entity.
      /// \param[in] _notify True to notify children of the pose update.
      /// \param[in] _publish True to publish the pose.
      private: void SetWorldPoseDefault(const math::Pose &_pose, bool _notify,
                                        bool _publish);

      /// \brief Called when a new pose message arrives.
      /// \param[in] _msg The message to set the pose from.
      private: void OnPoseMsg(ConstPosePtr &_msg);

      /// \brief Handle a change of pose
      /// \param[in] update_children if set to true, will call OnPoseChange
      ///            for all children (1 level, non-recursive).
      ///            But if the Object is static, we force children
      ///            OnPoseChange call
      private: void UpdatePhysicsPose(bool update_children = true);

      /// \brief Update an animation.
      /// \param[in] _info Update information.
      private: void UpdateAnimation(const common::UpdateInfo &_info);

      /// \brief A helper that prevents numerous dynamic_casts.
      protected: EntityPtr parentEntity;

      /// \brief World pose of the entity.
      protected: mutable math::Pose worldPose;

      /// \brief Communication node.
      protected: transport::NodePtr node;

      /// \brief Visual publisher.
      protected: transport::PublisherPtr visPub;

      /// \brief Request publisher.
      protected: transport::PublisherPtr requestPub;

      /// \brief Visual message container.
      protected: msgs::Visual *visualMsg;

      /// \brief Current pose animation
      protected: common::PoseAnimationPtr animation;

      /// \brief Previous time an animation was updated.
      protected: common::Time prevAnimationTime;

      /// \brief Start pose of an animation.
      protected: math::Pose animationStartPose;

      /// \brief All our event connections.
      protected: std::vector<event::ConnectionPtr> connections;

      /// \brief Connection used to update an animation.
      protected: event::ConnectionPtr animationConnection;

      /// \brief The pose set by a physics engine.
      protected: math::Pose dirtyPose;

      /// \brief Scale of the entity
      protected: math::Vector3 scale;

      /// \brief True if the object is static.
      private: bool isStatic;

      /// \brief Only used by Links. Included here for performance.
      private: bool isCanonicalLink;

      /// \brief The initial pose of the entity.
      private: math::Pose initialRelativePose;

      /// \brief Pose publisher.
      private: transport::PublisherPtr posePub;

      /// \brief Pose subscriber.
      private: transport::SubscriberPtr poseSub;

      /// \brief Callback for when an animation completes.
      private: boost::function<void()> onAnimationComplete;

      /// \brief The function used to to set the world pose.
      private: void (Entity::*setWorldPoseFunc)(const math::Pose &, bool, bool);
    };
    /// \}
  }
}
#endif

ext: hh

max_stars_repo_name: shyamalschandra/gazebo-official

max_issues_repo_name: shyamalschandra/gazebo-official

max_forks_repo_name: shyamalschandra/gazebo-official


text:
#ifndef DbTables_DbVersion_hh
#define DbTables_DbVersion_hh

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

namespace mu2e {

  class DbVersion {
  public:
    DbVersion():_purpose(std::string("none")),_major(-1),
	      _minor(-1),_extension(-1) {}
    DbVersion(std::string const& purpose, int major,
	    int minor, int extension):_purpose(purpose),
	     _major(major),_minor(minor),_extension(extension){}
    DbVersion(std::string const& purpose, std::string version):
    _purpose(purpose),_major(-1),_minor(-1),_extension(-1){
      if( version[0]=='v' || version[0]=='V' )
	version = version.substr(1,version.size()-1);
      std::vector<std::string> cont;
      boost::split(cont, version, boost::is_any_of("_-/: "));
      for(auto& s: cont) boost::algorithm::trim(s);

      if(cont.size()>0) {
	if(cont[0]=="*" || cont[0]=="") {
	  _major = -1;
	} else {
	  _major = std::stoi(cont[0]);
	}
      }
      if(cont.size()>1) {
	if(cont[1]=="*" || cont[1]=="") {
	  _minor = -1;
	} else {
	  _minor = std::stoi(cont[1]);
	}
      }
      if(cont.size()>2) {
	if(cont[2]=="*" || cont[2]=="") {
	  _extension = -1;
	} else {
	  _extension = std::stoi(cont[2]);
	}
      }
    }
    std::string const& purpose() const {return _purpose;}
    int major() const { return _major;}
    int minor() const { return _minor;}
    int extension() const { return _extension;}
    std::string to_string(std::string const& sep = std::string("/")) const {
      return _purpose+" "
	+std::to_string(_major)+sep
	+std::to_string(_minor)+sep
	+std::to_string(_extension);}
  private:
    std::string _purpose;
    int _major;
    int _minor;
    int _extension;
  };
}
#endif

max_stars_repo_name: bonventre/Offline

max_issues_repo_name: bonventre/Offline

max_forks_repo_name: bonventre/Offline


text:
// -*- mode: c++; tab-width: 4; indent-tabs-mode: t; eval: (progn (c-set-style "stroustrup") (c-set-offset 'innamespace 0)); -*-
// vi:set ts=4 sts=4 sw=4 noet :
// Copyright 2008, The TPIE development team
//
// This file is part of TPIE.
//
// TPIE is free software: you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// TPIE is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TPIE.  If not, see <http://www.gnu.org/licenses/>
#include "execution_time_predictor.h"
#include <boost/filesystem.hpp>
#include "serialization.h"
#include <map>
#include <algorithm>
#include <tpie/prime.h>
#include <iostream>
#include <iomanip>
#include <fcntl.h>
#include <tpie/tpie_log.h>
#include <tpie/tempname.h>
#include <tpie/util.h>
#ifdef WIN32
#include <windows.h>
#undef NO_ERROR
#include <Shlobj.h>
#else
#include <sys/types.h>
#include <pwd.h>
#endif

using namespace std;
using namespace tpie;

namespace {

typedef std::pair<stream_size_type, time_type> p_t;

struct cmp_t {
	bool operator()(const p_t & a, const p_t & b) const {return a.first < b.first;}
};

struct entry {
	static const size_t max_points=10;
	size_t count;
	p_t points[max_points];

	entry() : count(0) {}

	inline p_t * begin() {return points;}
	inline p_t * end() {return points+count;}

	void add_point(p_t p) {
		p_t * l = std::lower_bound(begin(), end(), p, cmp_t());
		if (l != end() && l->first == p.first) {
			l->second = (l->second + p.second) / 2;
			return;
		}
		p_t * replace=end();
		if (count == max_points) {
			stream_size_type best_dist=points[2].first - points[0].first;
			replace=begin()+1;
			for(p_t * i=begin()+1; i < end()-1; ++i) {
				stream_size_type dist=(i+1)->first - (i-1)->first;
				if (dist < best_dist) {replace=i; best_dist=dist;}
			}
		} else
			++count;
		if (l <= replace) {
			for (p_t * i=replace-1; i >= l; --i) *(i+1) = *i;
		} else {
			--l;
			for (p_t * i=replace; i < l; ++i) *i=*(i+1);
		}
		*l = p;
	}
};

class time_estimator_database {
public:
	typedef std::map<hash_type, entry> db_type;
	db_type db;
	std::string dir_name;
	std::string file_name;

	time_estimator_database() {
#ifdef WIN32
		//dir_name
		TCHAR p[MAX_PATH];
		if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA | CSIDL_FLAG_CREATE, NULL, 0, p))) {
			dir_name=p;
			file_name = "\\"; //path separator
		}
#else
		const char * p = getenv("HOME");
		if (p != 0) dir_name=p;
		if (dir_name == "") dir_name = getpwuid(getuid())->pw_dir;
		file_name = "/."; //make hidden, include path separator
#endif

		file_name += "tpie_time_estimation_db";
#ifndef TPIE_NDEBUG
		file_name += "_debug";
#endif
	}

	void load() {
		ifstream f;
		std::string full_name = dir_name+file_name;
		f.open(full_name.c_str(), ifstream::binary | ifstream::in);
		if (f.is_open()) {
			try {
				tpie::unserializer u(f);
				u << "TPIE time execution database";
				size_t c;
				u >> c;
				for(size_t i=0; i < c; ++i) {
					hash_type id;
					size_t cnt;
					u >> id >> cnt;
					entry & e=db[id];
					for (size_t j=0; j < cnt; ++j) {
						stream_size_type n;
						time_type time;
						u >> n >> time;
						e.add_point(p_t(n, time));
					}
				}
			} catch(tpie::serialization_error &) {
			}
		}
	}

	~time_estimator_database() {}

	void save() {
		std::string tmp=tpie::tempname::tpie_name("",dir_name);
		ofstream f;
		f.open(tmp.c_str(), ifstream::binary | ifstream::out);
		if (!f.is_open()) {
			log_error() << "Failed to store time estimation database: Could not create temporary file" << std::endl;
			return;
		}

		{
			tpie::serializer s(f);
			s << "TPIE time execution database";
			s << (size_t)db.size();
			for(db_type::iterator i=db.begin(); i != db.end(); ++i) {
				s << (hash_type)i->first << (size_t)i->second.count;
				for (p_t * j=i->second.begin(); j != i->second.end(); ++j)
					s << (stream_size_type)j->first << (time_type)j->second;
			}
		}
		f.close();
		try {
			atomic_rename(tmp, dir_name+file_name);
		} catch(std::runtime_error e) {
			log_error() << "Failed to store time estimation database: " << e.what() << std::endl;
		}
	}

	time_type estimate(hash_type id, stream_size_type n, double & confidence) {
		db_type::iterator i=db.find(id);
		if (i == db.end()) {
			confidence=0.0;
			return -1;
		}
		entry & e=i->second;

		p_t * l = std::lower_bound(e.begin(), e.end(), p_t(n, 0), cmp_t());

		if (l != e.end() && l->first == n) {
			confidence=1.0;
			return l->second;
		}

		if (l == e.end()) {
			--l;
			if (l->first == 0) {
				log_debug() << "In time estimation, first was 0." << std::endl;
				confidence=0.0;
				return -1;
			}
			confidence = std::min(1.3 / (1.0 + std::log(double(n / l->first))/std::log(2.0)), 1.0);
			return (l->second*n)/l->first;
		}

		p_t p0(0,0);
		if (l != e.begin()) p0 = *(l-1);
		stream_size_type w=(l->first-p0.first);
		stream_size_type x=(n - p0.first);
		confidence=1.0;
		return p0.second * (w - x) / w + l->second * (x/w);
	}
};

static time_estimator_database * db = 0;

} //annonymous namespace

namespace tpie {

void init_execution_time_db() {
	if (db) return;
	db = new time_estimator_database();
	db->load();
}

void finish_execution_time_db() {
	if (!db) return;
	db->save();
	delete db;
	db = 0;
}

execution_time_predictor::execution_time_predictor(const std::string & id):
	m_id(prime_hash(id)), m_start_time(boost::posix_time::not_a_date_time),
	m_estimate(-1), m_confidence(1), m_pause_time_at_start(0)
#ifndef TPIE_NDEBUG
	,m_name(id)
#endif //TPIE_NDEBUG
 {}

execution_time_predictor::~execution_time_predictor() {
}

time_type execution_time_predictor::estimate_execution_time(stream_size_type n, double & confidence) {
	if (m_id == prime_hash(std::string())) {
		confidence=0.0;
		return -1;
	}
	time_type v=db->estimate(m_id, n, confidence);
#ifndef TPIE_NDEBUG
	if (v == static_cast<memory_size_type>(-1))
		log_debug() << "No database entry for " << m_name << " (" << m_id << ")" << std::endl;
#endif
	return v;
}

void execution_time_predictor::start_execution(stream_size_type n) {
    m_n = n;
    m_estimate = estimate_execution_time(n, m_confidence);
    m_start_time = boost::posix_time::microsec_clock::local_time();
	m_pause_time_at_start = s_pause_time;
}

time_type execution_time_predictor::end_execution() {
	if (m_id == prime_hash(std::string()) || !s_store_times) return 0;
	time_type t = (boost::posix_time::microsec_clock::local_time() - m_start_time).total_milliseconds();
	t -= (s_pause_time - m_pause_time_at_start);
	entry & e = db->db[m_id];
	e.add_point( p_t(m_n, t) );
	m_start_time = boost::posix_time::not_a_date_time;
	return t;
}

std::string execution_time_predictor::estimate_remaining_time(double progress) {
    double time = static_cast<double>((boost::posix_time::microsec_clock::local_time()-m_start_time).total_milliseconds());
	time -= static_cast<double>(s_pause_time - m_pause_time_at_start);

	double a = m_confidence * (1.0 - progress);
	double b = (1.0-m_confidence) * (1.0 - progress) + progress;

	double t2 = (progress < 0.00001)?0:time/progress;
	if (m_confidence * a + progress * b < 0.2) return "Estimating";
	double estimate = static_cast<double>(m_estimate) * a  + t2 * b;

	double remaining = estimate * (1.0-progress);

    stringstream s;
	remaining /= 1000;
    if (remaining < 60*10) {
		s << (int)remaining << " sec";
		return s.str();
    }
    remaining /= 60;
    if (remaining < 60*10) {
		s << (int)remaining << " min";
		return s.str();
    }
    remaining /= 60;
    if (remaining < 24*10) {
		s << (int)remaining << " hrs";
		return s.str();
    }
    remaining /= 24;
    s << (int)remaining << " days";
    return s.str();
}

void execution_time_predictor::start_pause() {
	s_start_pause_time = boost::posix_time::microsec_clock::local_time();
}

void execution_time_predictor::end_pause() {
	s_pause_time += static_cast<memory_size_type>(
		(boost::posix_time::microsec_clock::local_time() - s_start_pause_time).total_milliseconds());
}

void execution_time_predictor::disable_time_storing() {
	s_store_times = false;
}

time_type execution_time_predictor::s_pause_time = 0;
boost::posix_time::ptime execution_time_predictor::s_start_pause_time;
bool execution_time_predictor::s_store_times = true;

};

max_stars_repo_name: remusao/keyvi

max_issues_repo_name: remusao/keyvi

max_forks_repo_name: remusao/keyvi


text: #include <boost/mpl/aux_/preprocessor/repeat.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino