text:
// Copyright (c) 2018 Slawek Mozdzonek
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <rpc/server.h>
#include <rpc/client.h>
#include <consensus/validation.h>
#include <validation.h>
#include <policy/policy.h>
#include <utilstrencodings.h>
#include <stdint.h>
#include <amount.h>
#include <hash.h>
#include <net.h>
#include <rpc/mining.h>
#include <utilmoneystr.h>
#include <wallet/coincontrol.h>
#include <wallet/fees.h>

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

#include <data/datautils.h>
#include <data/retrievedatatxs.h>

static constexpr size_t maxDataSize=MAX_OP_RETURN_RELAY-6;
static std::string changeAddress("");

template
<
        class T
>
struct char_traits { };

template<> struct char_traits
<
        char
>
{
        typedef char char_type;
};

template<> struct char_traits
<
        unsigned char
>
{
        typedef unsigned char char_type;
};

template <class T> class FileReader
{
public:
    typedef typename char_traits<T>::char_type char_type;
    FileReader(const std::string& fileName_) : file(fileName_.c_str(), std::ios::in|std::ios::binary|std::ios::ate)
    {
        if(!file.is_open())
        {
            throw std::runtime_error("Couldn't open the file");
        }
        size = file.tellg();
    }

    ~FileReader()
    {
        if(file.is_open())
        {
            file.close();
        }
    }

    void read(std::vector<char_type>& binaryData)
    {
        if(file.is_open())
        {
            binaryData.resize(size);
            file.seekg(0, std::ios::beg);
            file.read(reinterpret_cast<char*>(binaryData.data()), size);
        }
    }

private:
    std::ifstream file;
    std::streampos size;
};

class FileWriter
{
public:
    FileWriter(const std::string& fileName_) : file(fileName_.c_str(), std::ios::out|std::ios::binary|std::ios::trunc)
    {
        if(!file.is_open())
        {
            throw std::runtime_error("Couldn't open the file");
        }
    }

    ~FileWriter()
    {
        if(file.is_open())
        {
            file.close();
        }
    }

    void write(const std::vector<char>& binaryData)
    {
        if(file.is_open())
        {
            file.write(binaryData.data(), binaryData.size());
        }
    }

private:
    std::ofstream file;
};

static std::string computeHash(char* binaryData, size_t size)
{
    constexpr size_t hashSize=CSHA256::OUTPUT_SIZE;
    unsigned char fileHash[hashSize];

    CHash256 fileHasher;

    fileHasher.Write(reinterpret_cast<unsigned char*>(binaryData), size);
    fileHasher.Finalize(fileHash);

    return byte2str(&fileHash[0], static_cast<int>(hashSize));
}

static void computeHash(char* binaryData, size_t size, std::vector<unsigned char>& hash)
{
    constexpr size_t hashSize=CSHA256::OUTPUT_SIZE;
    unsigned char fileHash[hashSize];

    CHash256 fileHasher;

    fileHasher.Write(reinterpret_cast<unsigned char*>(binaryData), size);
    fileHasher.Finalize(fileHash);

    hash.insert(hash.end(), &fileHash[0], &fileHash[hashSize]);
}

static UniValue callRPC(std::string args)
{
    std::vector<std::string> vArgs;
    boost::split(vArgs, args, boost::is_any_of(" \t"));
    std::string strMethod = vArgs[0];
    vArgs.erase(vArgs.begin());
    JSONRPCRequest request;
    request.strMethod = strMethod;
    request.params = RPCConvertValues(strMethod, vArgs);
    request.fHelp = false;

    rpcfn_type method = tableRPC[strMethod]->actor;
    try {
        UniValue result = (*method)(request);
        return result;
    }
    catch (const UniValue& objError) {
        throw std::runtime_error(find_value(objError, "message").get_str());
    }
}

static std::vector<char> getOPreturnData(const std::string& txid)
{
    std::shared_ptr<CWallet> wallet = GetWallets()[0];
    CWallet* pwallet=nullptr;
    if(wallet!=nullptr)
    {
        pwallet=wallet.get();
    }

    RetrieveDataTxs retrieveDataTxs(txid, pwallet);
    return retrieveDataTxs.getTxData();
}

UniValue setOPreturnData(const std::vector<unsigned char>& data, CCoinControl& coin_control)
{
    UniValue res(UniValue::VARR);

    std::shared_ptr<CWallet> wallet = GetWallets()[0];
    if(wallet==nullptr)
    {
        throw std::runtime_error(std::string("No wallet found"));
    }
    CWallet* const pwallet=wallet.get();

    pwallet->BlockUntilSyncedToCurrentChain();

    LOCK2(cs_main, pwallet->cs_wallet);

    CAmount curBalance = pwallet->GetBalance();

    CRecipient recipient;
    recipient.scriptPubKey << OP_RETURN << data;
    recipient.nAmount=0;
    recipient.fSubtractFeeFromAmount=false;

    std::vector<CRecipient> vecSend;
    vecSend.push_back(recipient);

    CReserveKey reservekey(pwallet);
    CAmount nFeeRequired;
    int nChangePosInOut=1;
    std::string strFailReason;
    CTransactionRef tx;

    EnsureWalletIsUnlocked(pwallet);

    if(!pwallet->CreateTransaction(vecSend, nullptr, tx, reservekey, nFeeRequired, nChangePosInOut, strFailReason, coin_control))
    {
        if (nFeeRequired > curBalance)
        {
            strFailReason = strprintf("Error: This transaction requires a transaction fee of at least %s", FormatMoney(nFeeRequired));
        }
        throw std::runtime_error(std::string("CreateTransaction failed with reason: ")+strFailReason);
    }

    CValidationState state;
    if(!pwallet->CommitTransaction(tx, {}, {}, reservekey, g_connman.get(), state))
    {
        throw std::runtime_error(std::string("CommitTransaction failed with reason: ")+FormatStateMessage(state));
    }

    std::string txid=tx->GetHash().GetHex();
    return UniValue(UniValue::VSTR, txid);
}

UniValue retrievedata(const JSONRPCRequest& request)
{
    RPCTypeCheck(request.params, {UniValue::VSTR});

    if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
    throw std::runtime_error(
        "retrievedata \"txid\" \n"
        "\nRetrieves user data from a blockchain.\n"

        "\nArguments:\n"
        "1. \"txid\"                        (string, required) A hex-encoded transaction id string\n"
        "2. \"path to the file\"            (string, optional) A path to the file\n"

        "\nResult:\n"
        "\"string\"                         (string) A retrieved user data string\n"

        "\nExamples:\n"
        + HelpExampleCli("retrievedata", "\"txid\"")
        + HelpExampleRpc("retrievedata", "\"txid\"")
        + HelpExampleCli("retrievedata", "\"txid\" \"/home/myfile.bin\"")
        + HelpExampleRpc("retrievedata", "\"txid\" \"/home/myfile.bin\"")
    );

    std::string txid=request.params[0].get_str();
    std::vector<char> OPreturnData=getOPreturnData(txid);

    if(!request.params[1].isNull())
    {
        std::string filePath=request.params[1].get_str();
        FileWriter fileWriter(filePath);
        fileWriter.write(OPreturnData);

        return UniValue(UniValue::VSTR);
    }

    std::string retStr=byte2str(reinterpret_cast<unsigned char*>(OPreturnData.data()), OPreturnData.size());
    return UniValue(UniValue::VSTR, std::string("\"")+retStr+std::string("\""));
}

UniValue retrievemessage(const JSONRPCRequest& request)
{
    RPCTypeCheck(request.params, {UniValue::VSTR});

    if (request.fHelp || request.params.size() != 1)
    throw std::runtime_error(
        "retrievemessage \"txid\" \n"
        "\nRetrieves user data string from a blockchain.\n"

        "\nArguments:\n"
        "1. \"txid\"                        (string, required) A hex-encoded transaction id string\n"

        "\nResult:\n"
        "\"string\"                         (string) A retrieved user data string\n"

        "\nExamples:\n"
        + HelpExampleCli("retrievemessage", "\"txid\"")
        + HelpExampleRpc("retrievemessage", "\"txid\"")
    );

    std::string txid=request.params[0].get_str();
    std::vector<char> OPreturnData=getOPreturnData(txid);
    if(!OPreturnData.empty())
    {
        return UniValue(UniValue::VSTR, std::string("\"")+std::string(OPreturnData.begin(), OPreturnData.end())+std::string("\""));
    }

    return UniValue(UniValue::VSTR, std::string("\"\""));
}

UniValue storemessage(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
    throw std::runtime_error(
        "storemessage \"string\" \n"
        "\nStores a user data string in a blockchain.\n"
        "A transaction fee is computed as a (string length)*(fee rate). \n"
        "Before this command walletpassphrase is required. \n"

        "\nArguments:\n"
        "1. \"message\"                     (string, required) A user message string\n"
        "2. replaceable                     (boolean, optional) Allow this transaction to be replaced by a transaction with higher fees via BIP 125\n"
        "3. conf_target                     (numeric, optional) Confirmation target (in blocks)\n"
        "4. \"estimate_mode\"               (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
        "       \"UNSET\"\n"
        "       \"ECONOMICAL\"\n"
        "       \"CONSERVATIVE\"\n"

        "\nResult:\n"
        "\"txid\"                           (string) A hex-encoded transaction id\n"

        "\nExamples:\n"
        + HelpExampleCli("storemessage", "\"mystring\"")
        + HelpExampleRpc("storemessage", "\"mystring\"")
    );

    std::string msg=request.params[0].get_str();

    if(msg.length()>maxDataSize)
    {
        throw std::runtime_error(strprintf("data size is grater than %d bytes", maxDataSize));
    }

    CCoinControl coin_control;
    if (!request.params[1].isNull())
    {
        coin_control.m_signal_bip125_rbf = request.params[1].get_bool();
    }

    if (!request.params[2].isNull())
    {
        coin_control.m_confirm_target = ParseConfirmTarget(request.params[2]);
    }

    if (!request.params[3].isNull())
    {
        if (!FeeModeFromString(request.params[3].get_str(), coin_control.m_fee_mode)) {
            throw std::runtime_error("Invalid estimate_mode parameter");
        }
    }
    std::vector<unsigned char> data(msg.begin(), msg.end());
    return setOPreturnData(data, coin_control);
}

UniValue storesignature(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
    throw std::runtime_error(
        "storesignature \"string\" \n"
        "\nStores a hash of a user file into a blockchain.\n"
        "A transaction fee is computed as a (hash length)*(fee rate). \n"
        "Before this command walletpassphrase is required. \n"

        "\nArguments:\n"
        "1. \"path to the file\"            (string, required) A path to the file\n"
        "2. replaceable                     (boolean, optional) Allow this transaction to be replaced by a transaction with higher fees via BIP 125\n"
        "3. conf_target                     (numeric, optional) Confirmation target (in blocks)\n"
        "4. \"estimate_mode\"               (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
        "       \"UNSET\"\n"
        "       \"ECONOMICAL\"\n"
        "       \"CONSERVATIVE\"\n"

        "\nResult:\n"
        "\"txid\"                           (string) A hex-encoded transaction id\n"

        "\nExamples:\n"
        + HelpExampleCli("storesignature", "\"/home/myfile.txt\"")
        + HelpExampleRpc("storesignature", "\"/home/myfile.txt\"")
    );

    UniValue res(UniValue::VARR);

    std::string filePath=request.params[0].get_str();

    std::vector<char> binaryData;
    FileReader<char> fileReader(filePath);
    fileReader.read(binaryData);
    std::vector<unsigned char> data;
    computeHash(binaryData.data(), binaryData.size(), data);

    CCoinControl coin_control;
    if (!request.params[1].isNull())
    {
        coin_control.m_signal_bip125_rbf = request.params[1].get_bool();
    }

    if (!request.params[2].isNull())
    {
        coin_control.m_confirm_target = ParseConfirmTarget(request.params[2]);
    }

    if (!request.params[3].isNull())
    {
        if (!FeeModeFromString(request.params[3].get_str(), coin_control.m_fee_mode)) {
            throw std::runtime_error("Invalid estimate_mode parameter");
        }
    }
    return setOPreturnData(data, coin_control);
}

UniValue storedata(const JSONRPCRequest& request)
{
    if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
    throw std::runtime_error(
        "storedata \"string\" \n"
        "\nStores content of a user file into a blockchain.\n"
        "A transaction fee is computed as a (file size)*(fee rate). \n"
        "Before this command walletpassphrase is required. \n"

        "\nArguments:\n"
        "1. \"path to the file\"            (string, required) A path to the file\n"
        "2. replaceable                     (boolean, optional) Allow this transaction to be replaced by a transaction with higher fees via BIP 125\n"
        "3. conf_target                     (numeric, optional) Confirmation target (in blocks)\n"
        "4. \"estimate_mode\"               (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
        "       \"UNSET\"\n"
        "       \"ECONOMICAL\"\n"
        "       \"CONSERVATIVE\"\n"

        "\nResult:\n"
        "\"txid\"                           (string) A hex-encoded transaction id\n"

        "\nExamples:\n"
        + HelpExampleCli("storedata", "\"/home/myfile.txt\"")
        + HelpExampleRpc("storedata", "\"/home/myfile.txt\"")
    );

    UniValue res(UniValue::VARR);

    std::string filePath=request.params[0].get_str();

    std::vector<unsigned char> binaryData;

    FileReader<unsigned char> fileReader(filePath);
    fileReader.read(binaryData);

    if(binaryData.size()>maxDataSize)
    {
        throw std::runtime_error(strprintf("data size is grater than %d bytes", maxDataSize));
    }

    CCoinControl coin_control;
    if (!request.params[1].isNull())
    {
        coin_control.m_signal_bip125_rbf = request.params[1].get_bool();
    }

    if (!request.params[2].isNull())
    {
        coin_control.m_confirm_target = ParseConfirmTarget(request.params[2]);
    }

    if (!request.params[3].isNull())
    {
        if (!FeeModeFromString(request.params[3].get_str(), coin_control.m_fee_mode)) {
            throw std::runtime_error("Invalid estimate_mode parameter");
        }
    }
    return setOPreturnData(binaryData, coin_control);
}

UniValue checkmessage(const JSONRPCRequest& request)
{
    RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});

    if (request.fHelp || request.params.size() != 2)
    throw std::runtime_error(
        "checkmessage \"txid\" \"message\" \n"
        "\nChecks user data string against the message in a blockchain.\n"

        "\nArguments:\n"
        "1. \"txid\"                        (string, required) A hex-encoded transaction id string\n"
        "2. \"message\"                     (string, required) A user message string\n"

        "\nResult:\n"
        "\"string\"                         (string) PASS or FAIL\n"

        "\nExamples:\n"
        + HelpExampleCli("checkmessage", "\"txid\" \"message\"")
        + HelpExampleRpc("checkmessage", "\"txid\" \"message\"")
    );

    std::string txid=request.params[0].get_str();
    std::vector<char> OPreturnData=getOPreturnData(txid);
    if(!OPreturnData.empty())
    {
        std::string blockchainHash=computeHash(OPreturnData.data(), OPreturnData.size());

        std::string  message=request.params[1].get_str();
        std::string hexMsg=HexStr(message.begin(), message.end());
        std::vector<char> messageBinaryData;
        messageBinaryData.resize(hexMsg.length()/2);
        hex2bin(messageBinaryData, hexMsg);
        std::string messageHash=computeHash(messageBinaryData.data(), messageBinaryData.size());

        if(messageHash.compare(blockchainHash))
        {
            return UniValue(UniValue::VSTR, std::string("FAIL"));
        }

        return UniValue(UniValue::VSTR, std::string("PASS"));
    }

    return UniValue(UniValue::VSTR, std::string("FAIL"));
}

UniValue checkdata(const JSONRPCRequest& request)
{
    RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});

    if (request.fHelp || request.params.size() != 2)
    throw std::runtime_error(
        "checkdata \"txid\" \"path to the file\" \n"
        "\nChecks user data file content against the data in a blockchain.\n"

        "\nArguments:\n"
        "1. \"txid\"                        (string, required) A hex-encoded transaction id string\n"
        "2. \"path to the file\"            (string, required) A path to the file\n"

        "\nResult:\n"
        "\"string\"                         (string) PASS or FAIL\n"

        "\nExamples:\n"
        + HelpExampleCli("checkdata", "\"txid\" \"path to the file\"")
        + HelpExampleRpc("checkdata", "\"txid\" \"path to the file\"")
    );

    std::string txid=request.params[0].get_str();
    std::vector<char> OPreturnData=getOPreturnData(txid);

    if(!request.params[1].isNull())
    {
        std::string blockchainHash=computeHash(OPreturnData.data(), OPreturnData.size());

        std::string filePath=request.params[1].get_str();
        std::vector<char> binaryData;

        FileReader<char> fileReader(filePath);
        fileReader.read(binaryData);

        if(binaryData.size()>maxDataSize)
        {
            throw std::runtime_error(strprintf("data size is grater than %d bytes", maxDataSize));
        }

        std::string dataHash=computeHash(binaryData.data(), binaryData.size());
        if(dataHash.compare(blockchainHash))
        {
            return UniValue(UniValue::VSTR, std::string("FAIL"));
        }

        return UniValue(UniValue::VSTR, std::string("PASS"));
    }

    return UniValue(UniValue::VSTR, std::string("FAIL"));
}

UniValue checksignature(const JSONRPCRequest& request)
{
    RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VSTR});

    if (request.fHelp || request.params.size() != 2)
    throw std::runtime_error(
        "checksignature \"txid\" \"path to the file\" \n"
        "\nChecks user data file signature against the signature in a blockchain.\n"

        "\nArguments:\n"
        "1. \"txid\"                        (string, required) A hex-encoded transaction id string\n"
        "2. \"path to the file\"            (string, required) A path to the file\n"

        "\nResult:\n"
        "\"string\"                         (string) PASS or FAIL\n"

        "\nExamples:\n"
        + HelpExampleCli("checksignature", "\"txid\" \"path to the file\"")
        + HelpExampleRpc("checksignature", "\"txid\" \"path to the file\"")
    );

    std::string txid=request.params[0].get_str();
    std::vector<char> OPreturnData=getOPreturnData(txid);
    std::string OPreturnDataStr=byte2str(reinterpret_cast<unsigned char*>(OPreturnData.data()), OPreturnData.size());
    std::transform(OPreturnDataStr.begin(), OPreturnDataStr.end(), OPreturnDataStr.begin(), ::toupper);

    if(!request.params[1].isNull())
    {
        std::string filePath=request.params[1].get_str();
        std::vector<char> binaryData;

        FileReader<char> fileReader(filePath);
        fileReader.read(binaryData);

        if(binaryData.size()>maxDataSize)
        {
            throw std::runtime_error(strprintf("data size is grater than %d bytes", maxDataSize));
        }

        std::string dataHash=computeHash(binaryData.data(), binaryData.size());
        if(dataHash.compare(OPreturnDataStr))
        {
            return UniValue(UniValue::VSTR, std::string("FAIL"));
        }

        return UniValue(UniValue::VSTR, std::string("PASS"));
    }

    return UniValue(UniValue::VSTR, std::string("FAIL"));
}

static const CRPCCommand commands[] =
{ //  category              name                            actor (function)            argNames
  //  --------------------- ------------------------        -----------------------     ----------
    { "blockstamp",         "storemessage",                	&storemessage,             {"message", "replaceable", "conf_target", "estimate_mode"} },
    { "blockstamp",         "retrievemessage",             	&retrievemessage,          {"txid"} },
    { "blockstamp",         "retrievedata",             	&retrievedata,             {"txid"} },
    { "blockstamp",         "storesignature",             	&storesignature,           {"file_path", "replaceable", "conf_target", "estimate_mode"} },
    { "blockstamp",         "storedata",             		&storedata,          	   {"file_path", "replaceable", "conf_target", "estimate_mode"} },
    { "blockstamp",         "checkmessage",             	&checkmessage,             {"txid", "message"} },
    { "blockstamp",         "checkdata",             		&checkdata,          	   {"txid", "file_path"} },
    { "blockstamp",         "checksignature",             	&checksignature,           {"txid", "file_path"} },
};

void RegisterDataRPCCommands(CRPCTable &t)
{
    for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
        t.appendCommand(commands[vcidx].name, &commands[vcidx]);
}

max_stars_repo_name: opodgorska/bst

max_issues_repo_name: opodgorska/bst

max_forks_repo_name: opodgorska/bst


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_FUNCTION_ARG_HPP_INCLUDED
#define BOOST_SIMD_FUNCTION_ARG_HPP_INCLUDED

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-arithmetic
    This function computes the angular orientation of its floating parameter
    (the result is undifined for Nan entries if the @c pedantic_ decorator is not
    used)

    @par Header <boost/simd/function/arg.hpp>

    Using  `arg(x)` is equivalent to  `(is_negative(x)) ? Pi(as(x)) : Zero(as(x))`

    @par Notes

    - always returns \f$+0\f$ or \f$\pi\f$ taking into account the bit of sign
       even in the Nan case.

    - This function implement the restriction to real numbers of the
       complex arg(ument) function.

    @par Decorators

    - `pedantic_`  returns `Nan(as(x))` for a  nan input,

    @see is_negative, Pi, Nan

    @par Example:

      @snippet arg.cpp arg

    @par Possible output:

      @snippet arg.txt arg

  **/
  IEEEValue arg(IEEEValue const & x);
} }
#endif

#include <boost/simd/function/scalar/arg.hpp>
#include <boost/simd/function/simd/arg.hpp>

#endif

ext: hpp

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
// Copyright (c) 2009-2016 Craig Henderson
// https://github.com/cdmh/mapreduce

#pragma once

#include <boost/iostreams/device/mapped_file.hpp>

namespace mapreduce {

namespace datasource {

namespace detail {

template<typename Key, typename Value>
class file_handler : ::mapreduce::detail::noncopyable
{
  public:
    file_handler(mapreduce::specification const &spec);

    bool const get_data(Key const &key, Value &value)   const;
    bool const setup_key(Key &/*key*/)                  const { return false; }

  private:
    mapreduce::specification const &specification_;

    struct data;
    std::shared_ptr<data> data_;
};

template<>
struct file_handler<
    std::string,
    std::ifstream>::data
{
};

template<>
file_handler<
    std::string,
    std::ifstream>::file_handler(mapreduce::specification const &spec)
  : specification_(spec), data_(new data)
{
}

template<>
bool const
file_handler<
    std::string,
    std::ifstream>::get_data(
        std::string const &key,
        std::ifstream &value) const
{
    value.open(key.c_str(), std::ios_base::binary);
    return value.is_open();
}

template<>
struct file_handler<
    std::string,
    std::pair<
        char const *,
        std::uintmax_t> >::data
{
    struct detail
    {
        boost::iostreams::mapped_file mmf;    // memory mapped file
        std::streamsize               size;   // size of the file
        std::streamsize               offset; // offset to map next time
    };

    typedef
    std::map<std::string, std::shared_ptr<detail> >
    maps_t;

    maps_t      maps;
    std::mutex  mutex;
    std::string current_file;
};

template<>
file_handler<
    std::string,
    std::pair<
        char const *,
        std::uintmax_t> >::file_handler(mapreduce::specification const &spec)
  : specification_(spec), data_(new data)
{
}

template<>
bool const
file_handler<
    std::string,
    std::pair<
        char const *,
        std::uintmax_t> >::get_data(
            std::string const &key,
            std::pair<char const *, std::uintmax_t> &value) const
{
    // we need to hold the lock for the duration of this function
    std::lock_guard<std::mutex> l(data_->mutex);
    data::maps_t::const_iterator it;
    if (data_->current_file.empty())
    {
        data_->current_file = key;
        it = data_->maps.insert(std::make_pair(key, std::make_shared<data::detail>())).first;
        auto &detail = it->second;
        auto &mmf = detail->mmf;
        mmf.open(key, BOOST_IOS::in);
        if (!mmf.is_open())
        {
            std::cerr << "\nFailed to map file into memory: " << key;
            return false;
        }

        detail->size   = boost::filesystem::file_size(key);
        detail->offset = std::min(specification_.max_file_segment_size, detail->size);
        value.first    = mmf.const_data();
        value.second   = detail->offset;
    }
    else
    {
        assert(key == data_->current_file);
        it = data_->maps.find(key);
        assert(it != data_->maps.end());
        auto &detail = it->second;

        std::uintmax_t const new_offset = std::min(detail->offset+specification_.max_file_segment_size, detail->size);
        value.first  = detail->mmf.const_data() + detail->offset;
        value.second = new_offset - detail->offset;
        detail->offset = new_offset;
    }

    auto &detail = it->second;
    if (detail->offset == detail->size)
        data_->current_file.clear();
    else
    {
        // break on a line boundary
        char const *ptr = value.first + value.second;
        while (*ptr != '\n'  &&  *ptr != '\r'  &&  detail->offset != detail->size)
        {
            ++ptr;
            ++value.second;
            ++detail->offset;
        }
    }

    return true;
}

template<>
bool const
file_handler<
    std::string,
    std::pair<
        char const *,
        std::uintmax_t> >::setup_key(std::string &key) const
{
    std::lock_guard<std::mutex> l(data_->mutex);
    if (data_->current_file.empty())
        return false;
    key = data_->current_file;
    return true;
}

}   // namespace detail

template<
    typename MapTask,
    typename FileHandler = detail::file_handler<
        typename MapTask::key_type,
        typename MapTask::value_type> >
class directory_iterator : mapreduce::detail::noncopyable
{
  public:
    directory_iterator(mapreduce::specification const &spec)
      : specification_(spec),
        file_handler_(spec)
    {
        it_dir_ = it_dir_t(specification_.input_directory);
    }

    bool const setup_key(typename MapTask::key_type &key) const
    {
        if (!file_handler_.setup_key(key))
        {
            while (it_dir_ != it_dir_t()
                && boost::filesystem::is_directory(*it_dir_))
            {
                ++it_dir_;
            }

            if (it_dir_ == it_dir_t())
                return false;

            path_t path = *it_dir_++;
            key = path.string();
        }
        return true;
    }

    bool const get_data(typename MapTask::key_type &key, typename MapTask::value_type &value) const
    {
        return file_handler_.get_data(key, value);
    }

  private:
    typedef boost::filesystem::path path_t;
    typedef boost::filesystem::directory_iterator it_dir_t;

    mutable it_dir_t                it_dir_;
    std::string                     directory_;
    mapreduce::specification const &specification_;
    FileHandler                     file_handler_;
};

}   // namespace datasource

}   // namespace mapreduce

// 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.

max_stars_repo_name: cdmh/mapreduce

max_issues_repo_name: cdmh/mapreduce

max_forks_repo_name: cdmh/mapreduce


text:
#include "mpfr/mpfr.hpp"

#include <boost/multiprecision/mpfr.hpp>
#include "nanobench.h"

template <int N> using scalar_t = mpfr::mp_float_t<mpfr::digits10{N}>;

auto main() -> int {

  auto bench = ankerl::nanobench::Bench();

  bench.minEpochTime(std::chrono::milliseconds{100UL});

  using T1 = scalar_t<512>;
  using T2 = scalar_t<1024>;

  T1 a = sqrt(T1{2.0});
  T2 b = sqrt(T2{2.0});
  auto a_ = a + 1;
  auto b_ = b + 1;

  T1 c;
  T2 d;

  ankerl::nanobench::doNotOptimizeAway(&a);
  ankerl::nanobench::doNotOptimizeAway(&b);
  ankerl::nanobench::doNotOptimizeAway(&c);
  ankerl::nanobench::doNotOptimizeAway(&d);

  bench.run("copying same size 512", [&] {
    c = a;
    ankerl::nanobench::clobberMemory();
  });
  bench.run("copying same size 1024", [&] {
    d = b;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("copying 512 -> 1024", [&] {
    d = a;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("copying 1024 -> 512", [&] {
    c = b;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("add 512", [&] {
    c = a + a;
    ankerl::nanobench::clobberMemory();
  });

  a_ = 2;
  bench.run("add2 512", [&] {
    c = a_ + a_;
    ankerl::nanobench::clobberMemory();
  });
  a_ = a + 1;

  bench.run("sqr 512", [&] {
    c = a * a;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("mul 512", [&] {
    c = a * a_;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("div 512", [&] {
    c = a / a_;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("mul2 512", [&] {
    c = a * 2;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("add 1024", [&] {
    d = b + b;
    ankerl::nanobench::clobberMemory();
  });

  b_ = 2;
  bench.run("add2 1024", [&] {
    d = b_ + b_;
    ankerl::nanobench::clobberMemory();
  });
  b_ = b + 1;

  bench.run("sqr 1024", [&] {
    d = b * b;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("mul 1024", [&] {
    d = b * b_;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("div 1024", [&] {
    d = b / b_;
    ankerl::nanobench::clobberMemory();
  });

  bench.run("mul2 1024", [&] {
    d = b * 2;
    ankerl::nanobench::clobberMemory();
  });
}

ext: cpp

max_stars_repo_name: kitegi/mpfr-cxx

max_issues_repo_name: kitegi/mpfr-cxx

max_forks_repo_name: kitegi/mpfr-cxx


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

#include "pxr/base/tf/pyUtils.h"
#include "pxr/base/tf/wrapTypeHelpers.h"
#include "pxr/base/tf/pyContainerConversions.h"

#include <boost/python/class.hpp>
#include <boost/python/copy_const_reference.hpp>
#include <boost/python/operators.hpp>
#include <boost/python/return_arg.hpp>

#include <string>

using namespace boost::python;

using std::string;

static string _Repr(GfRect2i const &self) {
    return TF_PY_REPR_PREFIX + "Rect2i(" + TfPyRepr(self.GetLower()) + ", " +
        TfPyRepr(self.GetHigher()) + ")";
}

void wrapRect2i()
{
    typedef GfRect2i This;

    object getLower = make_function(&This::GetLower,
                                    return_value_policy<return_by_value>());

    object getHigher = make_function(&This::GetHigher,
                                     return_value_policy<return_by_value>());

    class_<This>( "Rect2i", init<>() )
        .def(init<const This &>())
        .def(init<const GfVec2i &, const GfVec2i &>())
        .def(init<const GfVec2i &, int, int >())

        .def( TfTypePythonClass() )

        .def("IsNull", &This::IsNull)
        .def("IsEmpty", &This::IsEmpty)
        .def("IsValid", &This::IsValid)

        .add_property("lower", getLower, &This::SetLower)
        .add_property("higher", getHigher, &This::SetHigher)

        .add_property("bottom", &This::GetBottom, &This::SetBottom)
        .add_property("left", &This::GetLeft, &This::SetLeft)
        .add_property("right", &This::GetRight, &This::SetRight)
        .add_property("top", &This::GetTop, &This::SetTop)

        .def("GetLower", getLower)
        .def("GetHigher", getHigher)

        .def("GetBottom", &This::GetBottom)
        .def("GetLeft", &This::GetLeft)
        .def("GetRight", &This::GetRight)
        .def("GetTop", &This::GetTop)

        .def("SetLower", &This::SetLower)
        .def("SetHigher", &This::SetHigher)

        .def("SetBottom", &This::SetBottom)
        .def("SetLeft", &This::SetLeft)
        .def("SetRight", &This::SetRight)
        .def("SetTop", &This::SetTop)

        .def("GetArea", &This::GetArea)
        .def("GetCenter", &This::GetCenter)
        .def("GetHeight", &This::GetHeight)
        .def("GetSize", &This::GetSize)
        .def("GetWidth", &This::GetWidth)

        .def("Translate", &This::Translate, return_self<>())
        .def("GetNormalized", &This::GetNormalized)
        .def("GetIntersection", &This::GetIntersection)
        .def("GetUnion", &This::GetUnion)

        .def("Contains", &This::Contains )

        .def( str(self) )
        .def( self == self )
        .def( self != self )
        .def( self += self )
        .def( self + self )

        .def("__repr__", _Repr)

        ;
    to_python_converter<std::vector<This>,
        TfPySequenceToPython<std::vector<This> > >();

}

max_stars_repo_name: marsupial/USD


text:
//Copyright (c) 2006-2009 Emil Dotchevski and Reverge Studios, Inc.

//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)

//This example shows how to print all data contained in a boost::exception.

#include <boost/exception/all.hpp>
#include <iostream>

void f(); //throws unknown types that derive from boost::exception.

void
g()
    {
    try
        {
        f();
        }
    catch(
    boost::exception & e )
        {
        std::cerr << diagnostic_information(e);
        }
    }

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include "DQMMonitoringService.h"

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

#include <ctime>
#include <iostream>

/*
 * This service is very similar to the FastMonitoringService in the HLT,
 * except that it is used for monitoring online DQM applications
 */

namespace dqmservices {

DQMMonitoringService::DQMMonitoringService(const edm::ParameterSet& pset,
                                           edm::ActivityRegistry& ar) {
  const char* x = getenv("DQM2_SOCKET");
  if (x) {
    std::cerr << "Monitoring pipe: " << x << std::endl;
    mstream_.connect(boost::asio::local::stream_protocol::endpoint(x));
  } else {
    std::cerr << "Monitoring file not found, disabling." << std::endl;
  }

  // init counters
  nevents_ = 0;

  last_lumi_ = 0;
  last_lumi_nevents_ = 0;
  last_lumi_time_ = std::chrono::high_resolution_clock::now();

  run_ = 0;
  lumi_ = 0;

  ar.watchPreGlobalBeginLumi(this, &DQMMonitoringService::evLumi);
  ar.watchPreSourceEvent(this, &DQMMonitoringService::evEvent);
}

DQMMonitoringService::~DQMMonitoringService() {}

void DQMMonitoringService::outputLumiUpdate() {
  using std::chrono::duration_cast;
  using std::chrono::milliseconds;

  auto now = std::chrono::high_resolution_clock::now();

  ptree doc;

  // these might be different than the numbers we want to report
  // rate/stats per lumi are calculated from last_*_ fields
  doc.put("cmssw_run", run_);
  doc.put("cmssw_lumi", lumi_);
  doc.put("events_total", nevents_);

  // do statistics for the last (elapsed) ls
  auto lumi_millis = duration_cast<milliseconds>(now - last_lumi_time_).count();
  auto lumi_events = nevents_ - last_lumi_nevents_;
  auto lumi_last = last_lumi_;

  if ((lumi_last > 0) && (lumi_millis > 0)) {
    doc.put("lumi_number", lumi_last);
    doc.put("lumi_events", lumi_events);
    doc.put("lumi_duration_ms", lumi_millis);

    float rate = ((float)lumi_events * 1000) / lumi_millis;
    doc.put("events_rate", rate);

    // also save the history entry
    ptree plumi;
    plumi.put("n", lumi_last);
    plumi.put("nevents", lumi_events);
    plumi.put("nmillis", lumi_millis);
    plumi.put("rate", rate);

    std::time_t hkey = std::time(nullptr);
    doc.add_child(str(boost::format("extra.lumi_stats.%d") % hkey), plumi);
  }

  outputUpdate(doc);
}

void DQMMonitoringService::evLumi(GlobalContext const& iContext) {
  using std::chrono::duration_cast;
  using std::chrono::milliseconds;

  // these might be different than the numbers we want to report
  // rate/stats per lumi are calculated from last_*_ fields
  run_ = iContext.luminosityBlockID().run();
  lumi_ = iContext.luminosityBlockID().luminosityBlock();

  outputLumiUpdate();

  last_lumi_time_ = std::chrono::high_resolution_clock::now();
  last_lumi_nevents_ = nevents_;
  last_lumi_ = lumi_;
}

void DQMMonitoringService::evEvent(StreamID const& iContext) {
  nevents_ += 1;
  tryUpdate();
}

void DQMMonitoringService::outputUpdate(ptree& doc) {
  using std::chrono::duration_cast;
  using std::chrono::milliseconds;

  if (!mstream_) return;

  try {
    last_update_time_ = std::chrono::high_resolution_clock::now();
    doc.put("update_timestamp", std::time(nullptr));

    write_json(mstream_, doc, false);
    mstream_.flush();
  } catch (...) {
    // pass
  }
}

void DQMMonitoringService::keepAlive() {
  if (!mstream_) return;

  mstream_ << "\n";
  mstream_.flush();

  tryUpdate();
}

void DQMMonitoringService::tryUpdate() {
  using std::chrono::duration_cast;
  using std::chrono::milliseconds;

  if (!mstream_) return;

  // sometimes we don't see any transition for a very long time
  // but we still want updates
  // luckily, keepAlive is called rather often by the input source
  auto now = std::chrono::high_resolution_clock::now();
  auto millis = duration_cast<milliseconds>(now - last_update_time_).count();
  if (millis >= (25 * 1000)) {
    outputLumiUpdate();
  }
}

}  // end-of-namespace

#include "FWCore/ServiceRegistry/interface/ServiceMaker.h"

using dqmservices::DQMMonitoringService;
DEFINE_FWK_SERVICE(DQMMonitoringService);

ext: cc

max_stars_repo_name: nistefan/cmssw

max_issues_repo_name: nistefan/cmssw

max_forks_repo_name: nistefan/cmssw


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

#include <util/driver/value/Value.h>

using namespace izenelib::driver;

namespace { // {anonymous}
template<typename T1, typename T2>
inline bool lessXorGreater(const T1& t1, const T2& t2)
{
    return (t1 < t2) ^ (t2 < t1);
}

} // namespace {anonymous}

BOOST_AUTO_TEST_SUITE(Compare_test)

BOOST_AUTO_TEST_CASE(Equal_test)
{
    BOOST_CHECK(Value(1) == Value(1));
    BOOST_CHECK(Value(1U) == Value(1U));
    BOOST_CHECK(Value(true) == Value(true));
    BOOST_CHECK(Value(1.1) == Value(1.1));
    BOOST_CHECK(Value() == nullValue);
    BOOST_CHECK(Value("abc") == Value("abc"));

    Value::ArrayType array1;
    array1.push_back(1);
    Value::ArrayType array2;
    array2.push_back(1);
    BOOST_CHECK(array1 == array2);

    Value::ObjectType object1;
    object1["test"] = 1;
    Value::ObjectType object2;
    object2["test"] = 1;
    BOOST_CHECK(object1 == object2);
}

BOOST_AUTO_TEST_CASE(SameTypeNotEqual_test)
{
    BOOST_CHECK(Value(1) != Value(2));
    BOOST_CHECK(Value(1U) != Value(2U));
    BOOST_CHECK(Value(true) != Value(false));
    BOOST_CHECK(Value(1.1) != Value(1.2));
    BOOST_CHECK(Value("abc") != Value("abd"));

    Value::ArrayType array1;
    array1.push_back(1);
    Value::ArrayType array2;
    array2.push_back(2);
    BOOST_CHECK(array1 != array2);

    Value::ObjectType object1;
    object1["test1"] = 1;
    Value::ObjectType object2;
    object2["test2"] = 1;
    BOOST_CHECK(object1 != object2);
}

BOOST_AUTO_TEST_CASE(DifferentTypeNotEqual_test)
{
    BOOST_CHECK(Value(1) != Value(1U));
    BOOST_CHECK(Value(true) != Value(1));
    BOOST_CHECK(Value(false) != nullValue);
    BOOST_CHECK(Value("1") != Value(1));

    Value::ArrayType array1;
    array1.push_back(1);

    Value::ObjectType object1;
    object1["test"] = 1;
    BOOST_CHECK(array1 != object1);
}

BOOST_AUTO_TEST_CASE(SameTypeLessThan_test)
{
    BOOST_CHECK(Value(1) < Value(2));
    BOOST_CHECK(Value(1U) < Value(2U));
    BOOST_CHECK(Value(false) < Value(true));
    BOOST_CHECK(Value(1.1) < Value(1.2));
    BOOST_CHECK(Value("abc") < Value("abd"));

    Value::ArrayType array1;
    array1.push_back(1);
    Value::ArrayType array2;
    array2.push_back(2);
    BOOST_CHECK(array1 < array2);

    Value::ObjectType object1;
    object1["test1"] = 1;
    Value::ObjectType object2;
    object2["test2"] = 1;
    BOOST_CHECK(object1 < object2);
}

BOOST_AUTO_TEST_CASE(DifferentTypeLessThan_test)
{
    BOOST_CHECK(lessXorGreater(Value(1), Value(1U)));
    BOOST_CHECK(lessXorGreater(Value(true), Value(1)));
    BOOST_CHECK(lessXorGreater(Value(false), nullValue));
    BOOST_CHECK(lessXorGreater(Value("1"), Value(1)));

    Value::ArrayType array1;
    array1.push_back(1);

    Value::ObjectType object1;
    object1["test"] = 1;
    BOOST_CHECK(lessXorGreater(array1, object1));
}

BOOST_AUTO_TEST_SUITE_END() // Compare_test

max_stars_repo_name: izenecloud/izenelib

max_issues_repo_name: izenecloud/izenelib

max_forks_repo_name: izenecloud/izenelib


text:
/*
 * Copyright (C) 2009, Willow Garage, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *   * Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *   * Neither the names of Stanford University or Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived from
 *     this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "ros/ros.h"
#include "ros/callback_queue.h"
#include "std_msgs/String.h"

#include <boost/thread.hpp>

/**
 * This tutorial demonstrates the use of custom separate callback queues that can be processed
 * independently, whether in different threads or just at different times.
 */

/**
 * This callback gets called from the main queue processed in spin()
 */
void chatterCallbackMainQueue(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO_STREAM("I heard: [ " << msg->data << "] in thread [" << boost::this_thread::get_id() << "] (Main thread)");
}

/**
 * This callback gets called from the custom queue
 */
void chatterCallbackCustomQueue(const std_msgs::String::ConstPtr& msg)
{
  ROS_INFO_STREAM("I heard: [ " << msg->data << "] in thread [" << boost::this_thread::get_id() << "]");
}

/**
 * The custom queue used for one of the subscription callbacks
 */
ros::CallbackQueue g_queue;
void callbackThread()
{
  ROS_INFO_STREAM("Callback thread id=" << boost::this_thread::get_id());

  ros::NodeHandle n;
  while (n.ok())
  {
    g_queue.callAvailable(ros::WallDuration(0.01));
  }
}

int main(int argc, char **argv)
{
  ros::init(argc, argv, "listener_with_custom_callback_processing");
  ros::NodeHandle n;

  /**
   * The SubscribeOptions structure lets you specify a custom queue to use for a specific subscription.
   * You can also set a default queue on a NodeHandle using the NodeHandle::setCallbackQueue() function.
   *
   * AdvertiseOptions and AdvertiseServiceOptions offer similar functionality.
   */
  ros::SubscribeOptions ops = ros::SubscribeOptions::create<std_msgs::String>("chatter", 1000,
                                                                              chatterCallbackCustomQueue,
                                                                              ros::VoidPtr(), &g_queue);
  ros::Subscriber sub = n.subscribe(ops);

  /**
   * Now we subscribe using the normal method, to demonstrate the difference.
   */
  ros::Subscriber sub2 = n.subscribe("chatter", 1000, chatterCallbackMainQueue);

  /**
   * Start a thread to service the custom queue
   */
  boost::thread chatter_thread(callbackThread);

  ROS_INFO_STREAM("Main thread id=" << boost::this_thread::get_id());
  /**
   * Now do a custom spin, to demonstrate the difference.
   */
  ros::Rate r(1);
  while (n.ok())
  {
    ros::spinOnce();
    r.sleep();
  }

  chatter_thread.join();

  return 0;
}


text:
#include "NeighborApi.h"

#include <boost/functional/hash.hpp>

#include <functional>

namespace std {
size_t hash<facebook::fboss::NeighborTypes::NeighborEntry>::operator()(
    const facebook::fboss::NeighborTypes::NeighborEntry& n) const {
  size_t seed = 0;
  boost::hash_combine(seed, n.switchId());
  boost::hash_combine(seed, n.routerInterfaceId());
  boost::hash_combine(seed, std::hash<folly::IPAddress>()(n.ip()));
  return seed;
}
} // namespace std

max_stars_repo_name: axbaretto/fboss

max_issues_repo_name: axbaretto/fboss

max_forks_repo_name: axbaretto/fboss


text:
/*
===========================================================================

This software is licensed under the Apache 2 license, quoted below.

Copyright (C) 2013 Andrey Budnik <budnik27@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.

===========================================================================
*/

#include <boost/bind.hpp>
#include "node_ping.h"
#include "common/log.h"
#include "common/protocol.h"
#include "common/service_locator.h"
#include "worker_manager.h"

namespace master {

void PingReceiver::OnNodePing( const std::string &nodeIP, const std::string &msg )
{
    //PLOG_DBG( nodeIP << " : " << msg );

    std::string protocol, header, body;
    int version;
    if ( !common::Protocol::ParseMsg( msg, protocol, version, header, body ) )
    {
        PLOG_ERR( "PingReceiver::OnNodePing: couldn't parse msg: " << msg );
        return;
    }

    common::ProtocolCreator protocolCreator;
    std::unique_ptr< common::Protocol > parser(
        protocolCreator.Create( protocol, version )
    );
    if ( !parser )
    {
        PLOG_ERR( "PingReceiver::OnNodePing: appropriate parser not found for protocol: "
                  << protocol << " " << version );
        return;
    }

    std::string type;
    parser->ParseMsgType( header, type );
    if ( !parser->ParseMsgType( header, type ) )
    {
        PLOG_ERR( "PingReceiver::OnNodePing: couldn't parse msg type: " << header );
        return;
    }

    if ( type == "ping_response" )
    {
        common::Demarshaller demarshaller;
        if ( parser->ParseBody( body, demarshaller.GetProperties() ) )
        {
            try
            {
                int numCPU;
                int64_t memSizeMb;
                demarshaller( "num_cpu", numCPU )( "mem_size", memSizeMb );
                IWorkerManager *workerManager = common::GetService< IWorkerManager >();
                workerManager->OnNodePingResponse( nodeIP, numCPU, memSizeMb );
            }
            catch( std::exception &e )
            {
                PLOG_ERR( "PingReceiver::OnNodePing: " << e.what() );
            }
        }
        else
        {
            PLOG_ERR( "PingReceiver::OnNodePing: couldn't parse msg body: " << body );
        }
    }
    if ( type == "job_completion" )
    {
        common::Demarshaller demarshaller;
        if ( parser->ParseBody( body, demarshaller.GetProperties() ) )
        {
            try
            {
                int64_t jobId;
                int taskId;
                demarshaller( "job_id", jobId )( "task_id", taskId );
                IWorkerManager *workerManager = common::GetService< IWorkerManager >();
                workerManager->OnNodeTaskCompletion( nodeIP, jobId, taskId );
            }
            catch( std::exception &e )
            {
                PLOG_ERR( "PingReceiver::OnNodePing: " << e.what() );
            }
        }
        else
        {
            PLOG_ERR( "PingReceiver::OnNodePing: couldn't parse msg body: " << body );
        }
    }
}

void PingReceiverBoost::Start()
{
    StartReceive();
}

void PingReceiverBoost::StartReceive()
{
    socket_.async_receive_from(
        boost::asio::buffer( buffer_ ), remote_endpoint_,
        boost::bind( &PingReceiverBoost::HandleRead, this,
                     boost::asio::placeholders::error,
                     boost::asio::placeholders::bytes_transferred ) );
}

void PingReceiverBoost::HandleRead( const boost::system::error_code& error, size_t bytes_transferred )
{
    if ( !error )
    {
        std::string response( buffer_.begin(), buffer_.begin() + bytes_transferred );
        std::string nodeIP( remote_endpoint_.address().to_string() );
        StartReceive();
        OnNodePing( nodeIP, response );
    }
    else
    {
        StartReceive();
        PLOG_ERR( "PingReceiverBoost::HandleRead error=" << error );
    }
}

} // namespace master

max_stars_repo_name: abudnik/prun

max_issues_repo_name: abudnik/prun

max_forks_repo_name: abudnik/prun


text:
/* vim: set sw=4 sts=4 et foldmethod=syntax : */

#include <gcs/constraints/linear_equality.hh>
#include <gcs/problem.hh>
#include <gcs/solve.hh>

#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include <boost/program_options.hpp>

using namespace gcs;

using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::to_string;
using std::pair;
using std::vector;

using namespace std::literals::string_literals;

namespace po = boost::program_options;

auto main(int argc, char * argv[]) -> int
{
    po::options_description display_options{ "Program options" };
    display_options.add_options()
        ("help", "Display help information")
        ("prove", "Create a proof");

    po::options_description all_options{ "All options" };

    all_options.add(display_options);

    po::variables_map options_vars;

    try {
        po::store(po::command_line_parser(argc, argv)
                .options(all_options)
                .run(), options_vars);
        po::notify(options_vars);
    }
    catch (const po::error & e) {
        cerr << "Error: " << e.what() << endl;
        cerr << "Try " << argv[0] << " --help" << endl;
        return EXIT_FAILURE;
    }

    if (options_vars.count("help")) {
        cout << "Usage: " << argv[0] << " [options]" << endl;
        cout << endl;
        cout << display_options << endl;
        return EXIT_SUCCESS;
    }

    Problem p = options_vars.count("prove") ? Problem{ Proof{ "odd_even_sum.opb", "odd_even_sum.veripb" } } : Problem{ };

    auto a = p.create_integer_variable(0_i, 5_i, "a");
    auto b = p.create_integer_variable(0_i, 5_i, "b");
    auto c = p.create_integer_variable(0_i, 5_i, "c");
    auto d = p.create_integer_variable(0_i, 10_i, "d");
    auto e = p.create_integer_variable(0_i, 2_i, "e");

    p.post(LinearEquality{ Linear{ { 2_i, a }, { 2_i, b }, { 2_i, c }, { -2_i, d }, { 1_i, e } }, 1_i, true });

    auto stats = solve(p, [&] (const State & s) -> bool {
            cout << s(a) << " " << s(b) << " " << s(c) << " " << s(d) << " " << s(e) << endl;
            return true;
            });

    cout << stats;

    return EXIT_SUCCESS;
}

max_stars_repo_name: ciaranm/glasgow-constraint-solver

max_issues_repo_name: ciaranm/glasgow-constraint-solver

max_forks_repo_name: ciaranm/glasgow-constraint-solver


text:
/*
 * rule.hpp
 *
 *
 * @date 14-07-2020
 * @author Teddy DIDE
 * @version 1.00
 * cppBase generated by gensources.
 */

#ifndef _RULE_HPP_
#define _RULE_HPP_

#include <boost/shared_ptr.hpp>
#include <boost/container/vector.hpp>
#include "copy_ptr.h"
#include "config.hpp"
#include "convert.hpp"
#include "encoding.hpp"

#include "cppBaseExport.hpp"
#define A(str) encode<EncodingT,ansi>(str)
#define C(str) encode<ansi,EncodingT>(str)

NAMESPACE_BEGIN(data_access)

template <class EncodingT>
class _RuleAccess;

NAMESPACE_END

NAMESPACE_BEGIN(entity)

using namespace log4cpp;
using namespace fctr;
using namespace enc;
using namespace boost;

/// Creation Table________________rule table represents a static analysis rule.
template <class EncodingT>
class  _Rule {
private :
	long long	m_identifier;
	long long	m_number;
	typename EncodingT::string_t	m_description;
	long long	m_enabled;
	Category*	m_logger;

protected :
	friend class data_access::_RuleAccess<EncodingT>;

	/** Creates a new element Rule.
	@param identifier
	@param number
	@param description
	@param enabled
	*/
	_Rule(long long identifier,
				long long number,
				const typename EncodingT::string_t& description,
				long long enabled)
	: m_identifier(identifier),
	  m_number(number),
	  m_description(description),
	  m_enabled(enabled)
	{
		m_logger = &Category::getInstance(LOGNAME);
		m_logger->debugStream() << "constructor _Rule "
				<< m_identifier << ' '
				<< m_number << ' '
				<< A(m_description) << ' '
				<< m_enabled << ' ';
	}

	/** Sets a value of the element identifier in Rule.
	@param identifier
	*/
	void setIdentifier(long long identifier)
	{
		m_identifier = identifier;
	}

public :
	/** Creates a new element Rule.
	*/
	_Rule()
	: m_identifier(-1),
	  m_number(0),
	  m_description(EncodingT::EMPTY),
	  m_enabled(0)
	{
		m_logger = &Category::getInstance(LOGNAME);
		m_logger->debugStream() << "constructor _Rule ";
	}

	/** Creates a new element Rule.
	@param number
	@param description
	@param enabled
	*/
	_Rule(long long number,
				const typename EncodingT::string_t& description,
				long long enabled)
	: m_identifier(-1),
	  m_number(number),
	  m_description(description),
	  m_enabled(enabled)
	{
		m_logger = &Category::getInstance(LOGNAME);
		m_logger->debugStream() << "constructor _Rule "
				<< m_identifier << ' '
				<< m_number << ' '
				<< A(m_description) << ' '
				<< m_enabled << ' ';
	}

	/** Returns a const reference to the element identifier in Rule.
	@return
	*/
	long long getIdentifier() const
	{
		return m_identifier;
	}

	/** Returns a const reference to the element number in Rule.
	@return
	*/
	long long getNumber() const
	{
		return m_number;
	}

	/** Sets a value of the element number in Rule.
	@param number
	*/
	void setNumber(long long number)
	{
		m_number = number;
	}

	/** Returns a const reference to the element description in Rule.
	@return
	*/
	const typename EncodingT::string_t& getDescription() const
	{
		return m_description;
	}

	/** Sets a value of the element description in Rule.
	@param description
	*/
	void setDescription(const typename EncodingT::string_t& description)
	{
		m_description = description;
	}

	/** Returns a const reference to the element enabled in Rule.
	@return
	*/
	long long getEnabled() const
	{
		return m_enabled;
	}

	/** Sets a value of the element enabled in Rule.
	@param enabled
	*/
	void setEnabled(long long enabled)
	{
		m_enabled = enabled;
	}

	/** Prints Rule object on a C++ stream.
	@param o Reference of C++ stream object.
	@return The reference of C++ stream object.
	*/
	ostream& printConsole(ostream& o) const
	{
		return o << "Rule" << endl
		         << "identifier : " << m_identifier << endl
		         << "number : " << m_number << endl
		         << "description : " << A(m_description) << endl
		         << "enabled : " << m_enabled;
	}

	/** Defines  operator<<  for Rule.
	@param o Reference of C++ stream object.
	@param elem Const reference of Rule object.
	@return The reference of C++ stream object.
	*/
	friend ostream& operator<<(ostream& o, const _Rule<EncodingT>& elem)
	{
		return elem.printConsole(o<<"[ ")<<" ]";
	}

	class RuleIDEquality;
	class NumberEquality;
	class NumberInferior;
	class NumberSuperior;
	class DescriptionEquality;
	class DescriptionInferior;
	class DescriptionSuperior;
	class EnabledEquality;
	class EnabledInferior;
	class EnabledSuperior;
};

typedef _Rule<ucs> UniRule;
typedef _Rule<ansi> Rule;

NAMESPACE_END

#undef C
#undef A

#include "rulePredicate.hpp"

#endif


text:
// mapnik-vector-tile
#include "vector_tile_geometry_clipper.hpp"
#include "vector_tile_geometry_feature.hpp"
#include "vector_tile_geometry_simplifier.hpp"
#include "vector_tile_raster_clipper.hpp"
#include "vector_tile_strategy.hpp"
#include "vector_tile_tile.hpp"
#include "vector_tile_layer.hpp"

// mapnik
#include <mapnik/geometry/box2d.hpp>
#include <mapnik/datasource.hpp>
#include <mapnik/feature.hpp>
#include <mapnik/image_scaling.hpp>
#include <mapnik/layer.hpp>
#include <mapnik/map.hpp>
#include <mapnik/version.hpp>
#include <mapnik/attribute.hpp>

#if MAPNIK_VERSION >= 300100
#include <mapnik/geometry/transform.hpp>
#else
#include <mapnik/geometry_transform.hpp>
#endif

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

// std
#include <future>

namespace mapnik
{

namespace vector_tile_impl
{

namespace detail
{

inline void create_geom_layer(tile_layer & layer,
                              double simplify_distance,
                              double area_threshold,
                              polygon_fill_type fill_type,
                              bool strictly_simple,
                              bool multi_polygon_union,
                              bool process_all_rings)
{
    layer_builder_pbf builder(layer.name(), layer.layer_extent(), layer.get_data());

    // query for the features
    mapnik::featureset_ptr features = layer.get_features();

    if (!features)
    {
        return;
    }

    mapnik::feature_ptr feature = features->next();

    if (!feature)
    {
        return;
    }

    using encoding_process = mapnik::vector_tile_impl::geometry_to_feature_pbf_visitor;
    using clipping_process = mapnik::vector_tile_impl::geometry_clipper<encoding_process>;

    mapnik::vector_tile_impl::vector_tile_strategy vs(layer.get_view_transform());
    mapnik::box2d<double> const& buffered_extent = layer.get_target_buffered_extent();
    const mapnik::geometry::point<double> p1_min(buffered_extent.minx(), buffered_extent.miny());
    const mapnik::geometry::point<double> p1_max(buffered_extent.maxx(), buffered_extent.maxy());
    const mapnik::geometry::point<std::int64_t> p2_min = mapnik::geometry::transform<std::int64_t>(p1_min, vs);
    const mapnik::geometry::point<std::int64_t> p2_max = mapnik::geometry::transform<std::int64_t>(p1_max, vs);
    const double minx = std::min(p2_min.x, p2_max.x);
    const double maxx = std::max(p2_min.x, p2_max.x);
    const double miny = std::min(p2_min.y, p2_max.y);
    const double maxy = std::max(p2_min.y, p2_max.y);
    const mapnik::box2d<int> tile_clipping_extent(minx, miny, maxx, maxy);

    if (simplify_distance > 0)
    {
        using simplifier_process = mapnik::vector_tile_impl::geometry_simplifier<clipping_process>;
        if (layer.get_proj_transform().equal())
        {
            using strategy_type = mapnik::vector_tile_impl::vector_tile_strategy;
            using transform_type = mapnik::vector_tile_impl::transform_visitor<strategy_type, simplifier_process>;
            while (feature)
            {
                mapnik::geometry::geometry<double> const& geom = feature->get_geometry();
                encoding_process encoder(*feature, builder);
                clipping_process clipper(tile_clipping_extent,
                                         area_threshold,
                                         strictly_simple,
                                         multi_polygon_union,
                                         fill_type,
                                         process_all_rings,
                                         encoder);
                simplifier_process simplifier(simplify_distance, clipper);
                transform_type transformer(vs, buffered_extent, simplifier);
                mapnik::util::apply_visitor(transformer, geom);
                feature = features->next();
            }
        }
        else
        {
            using strategy_type = mapnik::vector_tile_impl::vector_tile_strategy_proj;
            using transform_type = mapnik::vector_tile_impl::transform_visitor<strategy_type, simplifier_process>;
            strategy_type vs2(layer.get_proj_transform(), layer.get_view_transform());
            mapnik::box2d<double> const& trans_buffered_extent = layer.get_source_buffered_extent();
            while (feature)
            {
                mapnik::geometry::geometry<double> const& geom = feature->get_geometry();
                encoding_process encoder(*feature, builder);
                clipping_process clipper(tile_clipping_extent,
                                         area_threshold,
                                         strictly_simple,
                                         multi_polygon_union,
                                         fill_type,
                                         process_all_rings,
                                         encoder);
                simplifier_process simplifier(simplify_distance, clipper);
                transform_type transformer(vs2, trans_buffered_extent, simplifier);
                mapnik::util::apply_visitor(transformer, geom);
                feature = features->next();
            }
        }
    }
    else
    {
        if (layer.get_proj_transform().equal())
        {
            using strategy_type = mapnik::vector_tile_impl::vector_tile_strategy;
            using transform_type = mapnik::vector_tile_impl::transform_visitor<strategy_type, clipping_process>;
            while (feature)
            {
                mapnik::geometry::geometry<double> const& geom = feature->get_geometry();
                encoding_process encoder(*feature, builder);
                clipping_process clipper(tile_clipping_extent,
                                         area_threshold,
                                         strictly_simple,
                                         multi_polygon_union,
                                         fill_type,
                                         process_all_rings,
                                         encoder);
                transform_type transformer(vs, buffered_extent, clipper);
                mapnik::util::apply_visitor(transformer, geom);
                feature = features->next();
            }
        }
        else
        {
            using strategy_type = mapnik::vector_tile_impl::vector_tile_strategy_proj;
            using transform_type = mapnik::vector_tile_impl::transform_visitor<strategy_type, clipping_process>;
            strategy_type vs2(layer.get_proj_transform(), layer.get_view_transform());
            mapnik::box2d<double> const& trans_buffered_extent = layer.get_source_buffered_extent();
            while (feature)
            {
                mapnik::geometry::geometry<double> const& geom = feature->get_geometry();
                encoding_process encoder(*feature, builder);
                clipping_process clipper(tile_clipping_extent,
                                         area_threshold,
                                         strictly_simple,
                                         multi_polygon_union,
                                         fill_type,
                                         process_all_rings,
                                         encoder);
                transform_type transformer(vs2, trans_buffered_extent, clipper);
                mapnik::util::apply_visitor(transformer, geom);
                feature = features->next();
            }
        }
    }
    layer.build(builder);
    return;
}

inline void create_raster_layer(tile_layer & layer,
                                std::string const& image_format,
                                scaling_method_e scaling_method)
{
    layer_builder_pbf builder(layer.name(), layer.layer_extent(), layer.get_data());

    // query for the features
    mapnik::featureset_ptr features = layer.get_features();

    if (!features)
    {
        return;
    }

    mapnik::feature_ptr feature = features->next();

    if (!feature)
    {
        return;
    }

    mapnik::raster_ptr const& source = feature->get_raster();
    if (!source)
    {
        return;
    }

    mapnik::box2d<double> target_ext = box2d<double>(source->ext_);

    layer.get_proj_transform().backward(target_ext, PROJ_ENVELOPE_POINTS);
    mapnik::box2d<double> ext = layer.get_view_transform().forward(target_ext);

    int start_x = static_cast<int>(std::floor(ext.minx()+.5));
    int start_y = static_cast<int>(std::floor(ext.miny()+.5));
    int end_x = static_cast<int>(std::floor(ext.maxx()+.5));
    int end_y = static_cast<int>(std::floor(ext.maxy()+.5));
    int raster_width = end_x - start_x;
    int raster_height = end_y - start_y;
    if (raster_width > 0 && raster_height > 0)
    {
        builder.make_painted();
        raster_clipper visit(*source,
                             target_ext,
                             ext,
                             layer.get_proj_transform(),
                             image_format,
                             scaling_method,
                             layer.layer_extent(),
                             layer.layer_extent(),
                             raster_width,
                             raster_height,
                             start_x,
                             start_y);
        std::string buffer = mapnik::util::apply_visitor(visit, source->data_);
        raster_to_feature(buffer, *feature, builder);
    }
    layer.build(builder);
    return;
}

} // end ns detail

MAPNIK_VECTOR_INLINE void processor::update_tile(tile & t,
                                                 double scale_denom,
                                                 int offset_x,
                                                 int offset_y)
{
    // Futures
    std::vector<tile_layer> tile_layers;

    for (mapnik::layer const& lay : m_.layers())
    {
        if (t.has_layer(lay.name()))
        {
            continue;
        }
        tile_layers.emplace_back(m_,
                             lay,
                             t.extent(),
                             t.tile_size(),
                             t.buffer_size(),
                             scale_factor_,
                             scale_denom,
                             offset_x,
                             offset_y,
                             vars_);
        if (!tile_layers.back().is_valid())
        {
            t.add_empty_layer(lay.name());
            tile_layers.pop_back();
            continue;
        }
    }

    if (threading_mode_ == std::launch::deferred)
    {
        for (auto & layer_ref : tile_layers)
        {
            if (layer_ref.get_ds()->type() == datasource::Vector)
            {
                detail::create_geom_layer(layer_ref,
                                          simplify_distance_,
                                          area_threshold_,
                                          fill_type_,
                                          strictly_simple_,
                                          multi_polygon_union_,
                                          process_all_rings_
                                         );
            }
            else // Raster
            {
                detail::create_raster_layer(layer_ref,
                                            image_format_,
                                            scaling_method_
                                           );
            }
        }
    }
    else
    {
        std::vector<std::future<void> > future_layers;
        future_layers.reserve(tile_layers.size());

        for (auto & layer_ref : tile_layers)
        {
            if (layer_ref.get_ds()->type() == datasource::Vector)
            {
                future_layers.push_back(std::async(
                                        threading_mode_,
                                        detail::create_geom_layer,
                                        std::ref(layer_ref),
                                        simplify_distance_,
                                        area_threshold_,
                                        fill_type_,
                                        strictly_simple_,
                                        multi_polygon_union_,
                                        process_all_rings_
                            ));
            }
            else // Raster
            {
                future_layers.push_back(std::async(
                                        threading_mode_,
                                        detail::create_raster_layer,
                                        std::ref(layer_ref),
                                        image_format_,
                                        scaling_method_
                ));
            }
        }

        for (auto && lay_future : future_layers)
        {
            if (!lay_future.valid())
            {
                throw std::runtime_error("unexpected invalid async return");
            }
            lay_future.get();
        }
    }

    for (auto & layer_ref : tile_layers)
    {
        t.add_layer(layer_ref);
    }
}

} // end ns vector_tile_impl

} // end ns mapnik

ext: ipp

max_stars_repo_name: Algunenano/mapnik-vector-tile

max_issues_repo_name: Algunenano/mapnik-vector-tile

max_forks_repo_name: Algunenano/mapnik-vector-tile


text:
#include "GeneralUtils.h"
#include <iostream>
#include <boost/archive/iterators/base64_from_binary.hpp>
#include <boost/archive/iterators/binary_from_base64.hpp>
#include <boost/archive/iterators/transform_width.hpp>
#include <boost/archive/iterators/remove_whitespace.hpp>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "../folly/folly/experimental/exception_tracer/ExceptionTracer.h"

// From https://github.com/kenba/via-httplib/blob/master/include/via/http/authentication/base64.hpp
std::string base64Encode(std::string input)
{
    // The input must be in multiples of 3, otherwise the transformation
    // may overflow the input buffer, so pad with zero.
    size_t num_pad_chars((3 - input.size() % 3) % 3);
    input.append(num_pad_chars, 0);

    // Transform to Base64
    using namespace boost::archive::iterators;
    typedef base64_from_binary<transform_width
            <std::string::const_iterator, 6, 8> > ItBase64T;
    std::string output(ItBase64T(input.begin()),
                       ItBase64T(input.end() - num_pad_chars));

    // Pad blank characters with =
    output.append(num_pad_chars, '=');

    return output;
}

// From https://github.com/kenba/via-httplib/blob/master/include/via/http/authentication/base64.hpp
std::string base64Decode(std::string input)
{
    using namespace boost::archive::iterators;
    typedef transform_width<binary_from_base64<remove_whitespace
            <std::string::const_iterator> >, 8, 6> ItBinaryT;

    try
    {
        // If the input isn't a multiple of 4, pad with =
        size_t num_pad_chars((4 - input.size() % 4) % 4);
        input.append(num_pad_chars, '=');

        size_t pad_chars(std::count(input.begin(), input.end(), '='));
        std::replace(input.begin(), input.end(), '=', 'A');
        std::string output(ItBinaryT(input.begin()), ItBinaryT(input.end()));
        output.erase(output.end() - pad_chars, output.end());
        return output;
    }
    catch (std::exception& e)
    {
        dumpExceptions(e);
        return std::string("");
    }
}

std::string generateUUID() {
    return boost::lexical_cast<std::string>(boost::uuids::random_generator()());
}

void dumpExceptions(std::exception& e) {
    std::cerr << "--- Exception: " << e.what() << std::endl;
    auto exceptions = folly::exception_tracer::getCurrentExceptions();
    for (auto& exc : exceptions) {
        std::cerr << exc << "\n";
    }
}


text: #include <boost/log/attributes/named_scope.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//          Copyright Camille Gillot 2012 - 2015.
// 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)

//[mu_multiple
/*`
  The default behaviour of __rtti__ does not support multiple inheritance.
  This design choice is inspired by a concern about performance
  of node retrieval.

  However, multiple inheritance support can be enabled using
  the second argument to `base_rtti`. This is called the /NodeType/.

  Default /NodeType/ is `single_mixin_node`,
  this is well suited for most use cases,
  but only allows for one __rtti__-enabled parent for each class.
  The other possible /NodeType/ is `virtual_mixin_node`.
  This type allows usage of full C++ inheritance features,
  at the expense of performance.

  Internally, `virtual_mixin_node` uses virtual inheritance (hence the name).
  Therefore the performance will be poorer than with `single_mixin_node`
  using only regular inheritance.

  [mu_decl]

  The chosen /NodeType/ is then remembered by the hierarchy
  for calls to `implement_rtti`.
  [mu_impl]

  [important
    All bases involved in the same hierarchy must use the same /NodeType/.
    Otherwise, your compiler will barf.
  ]
 */
//]

#include "mmethod/rtti.hpp"

#include <boost/test/unit_test.hpp>
#include <boost/mpl/vector.hpp>

using namespace rtti;
using boost::mpl::vector;

namespace {

//[mu_decl
struct foo
: base_rtti<foo, virtual_mixin_node>
{
public:
  virtual ~foo() {}
};

struct bar
: base_rtti<bar, virtual_mixin_node>
{
public:
  virtual ~bar() {}
};
//]

//[mu_impl
struct baz
: foo, bar
, implement_rtti<baz, vector<foo, bar> >
{};
//]

} // namespace

BOOST_AUTO_TEST_CASE(test_multiple) {
  foo f; bar r; baz z;

  BOOST_CHECK_EQUAL( static_id<foo>(), get_id(f) );
  BOOST_CHECK_EQUAL( static_id<bar>(), get_id(r) );
  BOOST_CHECK_EQUAL( static_id<baz>(), get_id(z) );
}

max_stars_repo_name: cjgillot/rtti

max_issues_repo_name: cjgillot/rtti

max_forks_repo_name: cjgillot/rtti


text:
/*
// Licensed to DynamoBI Corporation (DynamoBI) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  DynamoBI licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at

//   http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
*/
#include "fennel/common/CommonPreamble.h"
#include "fennel/tuple/TupleDescriptor.h"
#include "fennel/tuple/TupleData.h"
#include "fennel/tuple/TupleAccessor.h"
#include "fennel/tuple/TuplePrinter.h"
#include "fennel/tuple/AttributeAccessor.h"
#include "fennel/tuple/StandardTypeDescriptor.h"
#include "fennel/common/TraceSource.h"

#include <boost/scoped_array.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <limits>
#include <iostream.h>

using namespace fennel;

int const bufferlen = 8;
int const num = 5;

void
tupleFiddle()
{
    bool isNullable = true;    // Can tuple contain nulls?
    int i;

    TupleDescriptor tupleDesc;
    tupleDesc.clear();

    // Build up a description of what we'd like the tuple to look like
    StandardTypeDescriptorFactory typeFactory;
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_VARCHAR);
        tupleDesc.push_back(
            TupleAttributeDescriptor(
                typeDesc,
                isNullable,
                bufferlen));
    }
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_INT_32);
        tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable));
    }
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_UINT_8);
        tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable));
    }
    for (i = 0; i < num; i++) {
        StoredTypeDescriptor const &typeDesc =
            typeFactory.newDataType(STANDARD_TYPE_REAL);
        tupleDesc.push_back(TupleAttributeDescriptor(typeDesc, isNullable));
    }

    // Create a tuple accessor from the description
    //
    // Note: Must use an ALL_FIXED accessor when creating a tuple out of
    // the air like this, otherwise unmarshal() does not know what to
    // do. If you need a STANDARD type tuple with variable-lengty
    // fields, it has to be built as a copy.
    TupleAccessor tupleAccessorFixed;
    tupleAccessorFixed.compute(tupleDesc, TUPLE_FORMAT_ALL_FIXED);

    // Allocate memory for the tuple
    boost::scoped_array<FixedBuffer>
        pTupleBufFixed(new FixedBuffer[tupleAccessorFixed.getMaxByteCount()]);

    // Link memory to accessor
    tupleAccessorFixed.setCurrentTupleBuf(pTupleBufFixed.get(), false);

    // Create a vector of TupleDatum objects based on the description we built
    TupleData tupleDataFixed(tupleDesc);

    // Do something mysterious. Probably binding pointers in the accessor to
    // items in the TupleData vector
    tupleAccessorFixed.unmarshal(tupleDataFixed);

    TupleData::iterator itr = tupleDataFixed.begin();

    TupleDatum pDatum;
    PBuffer pData;

    for (i = 0; i < num; i++, itr++) {
        char buf[bufferlen * 10];
        sprintf(buf, "%d-A-%d-B-%d-C-", i, i, i); // longer than buflen
        strncpy(
            (reinterpret_cast<char *>(const_cast<PBuffer>(itr->pData))),
            buf, bufferlen);
    }
    for (i = 0; i < num; i++, itr++) {
        // exploded form
        pDatum = *itr;
        pData = const_cast<PBuffer>(pDatum.pData);
        *(reinterpret_cast<int32_t *>(pData)) = i;
    }
    for (i = 0; i < num; i++, itr++) {
        // condensed form
        *(reinterpret_cast<uint8_t *>(const_cast<PBuffer>(itr->pData))) = i;
    }
    for (i = 0; i < num; i++, itr++) {
        *(reinterpret_cast<float *>(const_cast<PBuffer>(itr->pData))) = i * 0.5;
    }

    // Print out the tuple
    TuplePrinter tuplePrinter;
    tuplePrinter.print(cout, tupleDesc, tupleDataFixed);
    cout << endl;

    // Create another TupleData object that will be nullable
    TupleData tupleDataNullable = tupleDataFixed;

    // null out last element of each type
    for (i = 1; i <= 3; i++) {
        tupleDataNullable[(i*num)-1].pData = NULL;
    }

    // Print out the nullable tuple
    tuplePrinter.print(cout, tupleDesc, tupleDataNullable);
    cout << endl;

    // Re-point second string to first string
    tupleDataNullable[1].pData = tupleDataNullable[0].pData;

    // Re-point third string to part way into first string
    tupleDataNullable[2].pData = (tupleDataNullable[0].pData + 1);

    // Print out the modified nullable tuple
    tuplePrinter.print(cout, tupleDesc, tupleDataNullable);
    cout << endl;

}

int
main(int argc, char *argv[])
{
    tupleFiddle();
    return 0;
}

boost::unit_test_framework::test_suite *init_unit_test_suite(int,char **)
{
    return NULL;
}

// End tuple.cpp


text:
#include "server/api/url_parser.hpp"
#include "engine/polyline_compressor.hpp"

#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/repository/include/qi_iter_pos.hpp>

#include <string>
#include <type_traits>

BOOST_FUSION_ADAPT_STRUCT(osrm::server::api::ParsedURL,
                          (std::string, service)(unsigned, version)(std::string,
                                                                    profile)(std::string, query))

// Keep impl. TU local
namespace
{
namespace ph = boost::phoenix;
namespace qi = boost::spirit::qi;

template <typename Iterator, typename Into> //
struct URLParser final : qi::grammar<Iterator, Into>
{
    URLParser() : URLParser::base_type(start)
    {
        using boost::spirit::repository::qi::iter_pos;

        alpha_numeral = qi::char_("a-zA-Z0-9");
        percent_encoding = qi::char_('%') > qi::uint_parser<char, 16, 2, 2>()[qi::_val = qi::_1];
        polyline_chars = qi::char_("a-zA-Z0-9_.--[]{}@?|\\~`^") | percent_encoding;
        all_chars = polyline_chars | qi::char_("=,;:&().");

        service = +alpha_numeral;
        version = qi::uint_;
        profile = +alpha_numeral;
        query = +all_chars;

        // Example input: /route/v1/driving/7.416351,43.731205;7.420363,43.736189

        start = qi::lit('/') > service > qi::lit('/') > qi::lit('v') > version > qi::lit('/') >
                profile > qi::lit('/') >
                qi::omit[iter_pos[ph::bind(&osrm::server::api::ParsedURL::prefix_length, qi::_val) =
                                      qi::_1 - qi::_r1]] > query;

        BOOST_SPIRIT_DEBUG_NODES((start)(service)(version)(profile)(query))
    }

    qi::rule<Iterator, Into> start;

    qi::rule<Iterator, std::string()> service;
    qi::rule<Iterator, unsigned()> version;
    qi::rule<Iterator, std::string()> profile;
    qi::rule<Iterator, std::string()> query;

    qi::rule<Iterator, char()> alpha_numeral;
    qi::rule<Iterator, char()> all_chars;
    qi::rule<Iterator, char()> polyline_chars;
    qi::rule<Iterator, char()> percent_encoding;
};

} // anon.

namespace osrm
{
namespace server
{
namespace api
{

boost::optional<ParsedURL> parseURL(std::string::iterator &iter, const std::string::iterator end)
{
    using It = std::decay<decltype(iter)>::type;

    static URLParser<It, ParsedURL(It)> const parser;
    ParsedURL out;

    try
    {
        const auto ok = boost::spirit::qi::parse(iter, end, parser(boost::phoenix::val(iter)), out);

        if (ok && iter == end)
            return boost::make_optional(out);
    }
    catch (const qi::expectation_failure<It> &failure)
    {
        // The grammar above using expectation parsers ">" does not automatically increment the
        // iterator to the failing position. Extract the position from the exception ourselves.
        iter = failure.first;
    }

    return boost::none;
}

} // api
} // server
} // osrm

max_stars_repo_name: jhermsmeier/osrm-backend

max_issues_repo_name: jhermsmeier/osrm-backend

max_forks_repo_name: jhermsmeier/osrm-backend


text:
// Boost.Range library
//
//  Copyright Neil Groves 2010. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#include <boost/range/algorithm_ext/for_each.hpp>

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

#include <boost/range/iterator.hpp>
#include <algorithm>
#include <list>
#include <vector>

namespace
{
    struct MockBinaryFn
    {
        typedef void result_type;
        typedef int first_argument_type;
        typedef int second_argument_type;

        void operator()(int x, int y)
        {
            xs.push_back(x);
            ys.push_back(y);
        }

        std::vector<int> xs;
        std::vector<int> ys;
    };

    template< class Range1, class Range2 >
    void test_for_each_impl( Range1& rng1, Range2& rng2 )
    {
        MockBinaryFn fn = boost::range::for_each(rng1, rng2, MockBinaryFn());

        BOOST_CHECK_EQUAL_COLLECTIONS( ::boost::begin(rng1), ::boost::end(rng1),
            fn.xs.begin(), fn.xs.end() );

        BOOST_CHECK_EQUAL_COLLECTIONS( ::boost::begin(rng2), ::boost::end(rng2),
            fn.ys.begin(), fn.ys.end() );
    }

    template< class Collection1, class Collection2 >
    void test_for_each_impl(const int max_count)
    {
        Collection1 c1;
        for (int i = 0; i < max_count; ++i)
            c1.push_back(i);

        Collection2 c2;
        for (int i = 0; i < max_count; ++i)
            c2.push_back(i);

        test_for_each_impl(c1, c2);

        const Collection1& const_c1 = c1;
        const Collection2& const_c2 = c2;

        test_for_each_impl(c1, const_c2);
        test_for_each_impl(const_c1, c2);
        test_for_each_impl(const_c1, const_c2);
    }

    template< class Collection1, class Collection2 >
    void test_for_each_impl()
    {
        test_for_each_impl< Collection1, Collection2 >(0);
        test_for_each_impl< Collection1, Collection2 >(1);
        test_for_each_impl< Collection1, Collection2 >(10);
    }

    void test_for_each()
    {
        test_for_each_impl< std::vector<int>, std::vector<int> >();
        test_for_each_impl< std::list<int>, std::list<int> >();
        test_for_each_impl< std::vector<int>, std::list<int> >();
        test_for_each_impl< std::list<int>, std::vector<int> >();
    }
}

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

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

    return test;
}

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
/*
    Copyright (c) 2013-2014 Contributors as noted in the AUTHORS file

    This file is part of azmq

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef AZMQ_DETAIL_BASIC_IO_OBJECT_HPP__
#define AZMQ_DETAIL_BASIC_IO_OBJECT_HPP__
#ifdef ASIO_STANDALONE
#include <asio/io_context.hpp>
#include <asio/basic_io_object.hpp>
#else
#include <boost/asio/io_context.hpp>
#include <boost/asio/basic_io_object.hpp>
#endif
namespace azmq {
namespace detail {
    template<typename Service>
    class core_access {
    public:
        using service_type = Service;
        using implementation_type = typename service_type::implementation_type;

        template<typename T>
        core_access(T & that)
            : service_(that.get_service())
            , impl_(that.get_implementation())
        { }

        service_type & service() { return service_; }
        implementation_type & implementation() { return impl_; }

    private:
        service_type & service_;
        implementation_type & impl_;
    };

    template<typename Service>
    class basic_io_object
        : public asio::basic_io_object<Service> {

        friend class core_access<Service>;

    public:
        basic_io_object(asio::io_context& ios)
            : asio::basic_io_object<Service>(ios)
        { }
    };
} // namespace detail
} // namespace azmq
#endif // AZMQ_DETAIL_BASIC_IO_OBJECT_HPP__

max_stars_repo_name: MerlinXYoung/azmq

max_issues_repo_name: MerlinXYoung/azmq

max_forks_repo_name: MerlinXYoung/azmq


text:
#include <NTL/ZZ.h>

template<>
void Elt<NTL::ZZ>::mul(const Elt& x) { NTL::mul(this->t, this->t, x.t); }

template<>
void Elt<NTL::ZZ>::mod(const Elt& x) { NTL::QuickRem(this->t, x.t); }

template<>
void Elt<NTL::ZZ>::div(const Elt& x) { NTL::div(this->t, this->t, x.t); }

template<>
void Elt<NTL::ZZ>::mulmod(const Elt& x, const Elt& y) { NTL::MulMod(this->t, this->t, x.t, y.t); }

ext: tpp

max_stars_repo_name: adienes/remainder-tree

max_issues_repo_name: adienes/remainder-tree

max_forks_repo_name: adienes/remainder-tree


text:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>

#include <TApplication.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TPad.h>
#include <TPaveText.h>

#include <epecur/geometry.hpp>
#include <epecur/loadfile.hpp>
#include <epecur/types.hpp>

#include "../../../contrib/rootlogon.C"

#include "AxialShiftApp.hpp"
#include "AxialShiftHook.hpp"

namespace po = boost::program_options;

using namespace std;

AxialShiftApp::AxialShiftApp( const char* app_name, int &argc, char* argv[] )
	: TApplication(app_name, &argc, argv, nullptr, -1)
{
	ParseCommandLine();

	Init();
}

AxialShiftApp::~AxialShiftApp()
{
	delete hook;

	BOOST_FOREACH(auto hist_tuple, shift_hist)
	{
		TH1I	*hist_ptr = hist_tuple.second;

		delete hist_ptr;
	}

	delete title_text_widget;
	delete hist_pad;
	delete main_canvas;
}

void	AxialShiftApp::ParseCommandLine()
{
	po::options_description cmdline_options;

	po::options_description visible("Allowed options");

	visible.add_options()
		("help,h", "produce this output")
		("geometry-file,g", po::value<string>(), "specify geometry description file")
		;
	cmdline_options.add(visible);

	po::positional_options_description p;
	p.add("input-file", 1);

	po::options_description hidden("Hidden options");

	hidden.add_options()
		("input-file", po::value< vector<string> >(), "input file")
		;
	cmdline_options.add(hidden);

	po::variables_map vm;

	po::store(po::command_line_parser(Argc(), Argv()).
		  options(cmdline_options).positional(p).run(), vm);

	po::notify(vm);

	if (vm.count("help") || !vm.count("input-file") || !vm.count("geometry-file"))
	{
		cerr << "Usage: " << Argv(0) << " data-file -g geometry-file [options]" << endl;
		cerr << endl;
		cerr << visible << endl;
		Terminate(1);
	}

	data_filepath = vm["input-file"].as< vector<string> >()[0];
	geometry_filepath = vm["geometry-file"].as<string>();
}

void	AxialShiftApp::Init()
{
	ifstream	file(geometry_filepath.c_str(), ios::in);

	if (!file.is_open())
	{
		throw "Couldn't open geometry file!";
	}

	Geometry	geom(file);

	init_hists(geom);

	hook = new AxialShiftHook(geom, shift_hist);

	try
	{
		loadfile(data_filepath, *hook);
	}
	catch(const char *e)
	{
		cerr << "Error: " << e << endl;
	}

	cout << "Track miss count (chamber -> count -> part)" << endl;

	BOOST_FOREACH(auto tup, hook->track_miss_count)
	{
		cout << int(tup.first) << " ->\t" << tup.second << "->\t" << tup.second/float(hook->track_count) << endl;
	}

	main_canvas = new TCanvas("main_canvas", ApplicationName(), 200, 10, 1000, 250);
	main_canvas->Connect("Closed()", "TApplication", this, "Terminate()");

	int	rows_count = 4;
	int	cols_count = ceil(shift_hist.size() / (float)rows_count);

	main_canvas->Divide(rows_count, cols_count, 0.005, 0.005);

	int	pad_id = 1;

	BOOST_FOREACH(auto chamb_tup, shift_hist)
	{
		TH1I*	hist = chamb_tup.second;
		double	shift_delta = -hist->GetMean();

		cerr << hist->GetTitle() << ".delta = " << shift_delta << endl;
	}

	BOOST_FOREACH(auto chamb_tup, shift_hist)
	{
		chamber_id_t	chamber_id = chamb_tup.first;
		TH1I*	hist = chamb_tup.second;
		double	new_shift_value = geom.chamber_axial_shift[chamber_id] - hist->GetMean();

		main_canvas->cd(pad_id);

		cout << "// " << hist->GetTitle() << ".axial_shift = " << new_shift_value << endl;

		hist->Draw();

		pad_id++;
	}
}

void	AxialShiftApp::init_hists( Geometry &geom )
{
	init_babar_style();
	gROOT->SetStyle("BABAR");
	gStyle->SetOptTitle(1);
	gStyle->SetTitleX(0.43);
	init_custom_palette();

	BOOST_FOREACH(auto gr_tup, geom.group_chambers)
	{
		group_id_t	group_id = gr_tup.first;
		device_type_t	device_type = geom.group_device_type[group_id];

		if (device_type != DEV_TYPE_PROP)
		{
			continue;
		}

		BOOST_FOREACH(auto axis_tup, gr_tup.second)
		{
			device_axis_t	axis = axis_tup.first;

			BOOST_FOREACH(chamber_id_t chamber_id, axis_tup.second)
			{
				plane_id_t	plane_id = geom.chamber_plane[chamber_id];
				string	hist_name = "F" + boost::lexical_cast<string>(int(group_id)) + (axis == DEV_AXIS_X ? "X" : "Y") + boost::lexical_cast<string>(int(plane_id));

				shift_hist[chamber_id] = new TH1I(hist_name.c_str(), hist_name.c_str(), 50, -5.0, 5.0);

				shift_hist[chamber_id]->GetXaxis()->SetTitle("\\Delta X, [mm]");
				shift_hist[chamber_id]->GetYaxis()->SetTitle("N");
			}
		}

	}
}

int	main( int argc, char* argv[] )
{
	AxialShiftApp	app("Axial shift", argc, argv);
	while(1) { app.Run(); };

	return 0;
}

max_stars_repo_name: veprbl/libepecur

max_issues_repo_name: veprbl/libepecur

max_forks_repo_name: veprbl/libepecur