text:
#ifndef H_ITEM
#define H_ITEM

#include <string>
using std::string;

#include <boost/format.hpp>

#include <Wt/Dbo/Dbo>
namespace dbo = Wt::Dbo;

class Item;

#include "../user/User.hpp"
#include "Order.hpp"

class Item
{
public:
	string shop_name;
	string shop_specific_id;
	string shop_specific_id_2;
	string title;
	string url;
	double price;
	int count;
	dbo::ptr<User> user;
	dbo::ptr<Order> order;

	Item();
	Item(const string shop_name, const string shop_specific_id, const string shop_specific_id_2, const string title, const string url, double price, const int count);

	string formatInto(const boost::format fmt, int number) const;

	template<class Action>
	void persist(Action& a)
	{
		dbo::field(a, shop_name, "shop_name");
		dbo::field(a, shop_specific_id, "shop_specific_id");
		dbo::field(a, shop_specific_id_2, "shop_specific_id_2");
		dbo::field(a, title, "title");
		dbo::field(a, url, "url");
		dbo::field(a, price, "price");
		dbo::field(a, count, "count");
		dbo::belongsTo(a, user, "user");
		dbo::belongsTo(a, order, "ordering", dbo::OnDeleteSetNull);
	}
};

typedef dbo::ptr<Item> PItem;
typedef dbo::collection<PItem> PItems;

#endif //defined H_ITEM

ext: hpp

max_stars_repo_name: hephaisto/sharebuy

max_issues_repo_name: hephaisto/sharebuy

max_forks_repo_name: hephaisto/sharebuy


text:
#include <fstream>
#include <iomanip>
#include <planner/start_plan.h>
#include <gazebo_scene_randomiser_plugin/randomise.h>
#include <ros/ros.h>
#include <ros/package.h>
#include <std_srvs/Empty.h>
#include <boost/filesystem.hpp>
#include "planner/defines.h"

class Tester
{
public:
    Tester(ros::NodeHandle* nh)
        : nh_(*nh)
    {
        this->init();
    }

    ~Tester()
    {

    }

    void run()
    {
        this->initArm();

        int i = 1;
        while (ros::ok())
        {
            ROS_INFO("[TESTER]: Starting run #%d ...", i);

            this->runPlannerAndLog();
            this->resetArm();

            i++;
            if (i > num_runs_)
            {
                ROS_INFO("%s[TESTER]: Test runs completed!", GREEN);
                break;
            }
        }
    }

private:
    void init()
    {
        planning_client_ = nh_.serviceClient<planner::start_plan>("/start_plan");
        randomiser_client_ = nh_.serviceClient<gazebo_scene_randomiser_plugin::randomise>("/gazebo/randomise_scene");
        reset_arm_client_ = nh_.serviceClient<std_srvs::Empty>("/reset_arm");
        init_arm_client_ = nh_.serviceClient<std_srvs::Empty>("/go_to_init");

        if (!(planning_client_.exists() && randomiser_client_.exists()))
        {
            ROS_FATAL("Required services are not up! Make sure the planner and Gazebo nodes are up!");
            exit(-1);
        }

        ros::param::param<int>("~num_runs", num_runs_, 10);
        ros::param::param<std::string>("/gazebo/surface", surface_, "small_table_link_surface");
        ros::param::param<std::string>("/robot_name", robot_name_, "j2s7s300");

        if (num_runs_ <= 0)
        {
            ROS_FATAL("[TESTER]: Invalid number of runs! Value set: %d", num_runs_);
            ros::shutdown();
            exit(-1);
        }

        auto time = std::time(nullptr);
        std::stringstream ss;
        ss << ros::package::getPath("planner") + "/test/logs/" << surface_  << "/";
        if (!boost::filesystem::exists(ss.str()))
        {
            if (!boost::filesystem::create_directories(ss.str()))
            {
                ROS_FATAL("[TESTER]: Failed to create log directory!");
                ros::shutdown();
                exit(-1);
            }
        }

        ss << std::put_time(std::localtime(&time), "%b_%d_%Y_%X") << ".log";

        log_file_ = ss.str();

        ROS_INFO("%s[TESTER]: Performing %d test runs!", BLUE, num_runs_);
        ROS_INFO("%s[TESTER]: Saving log file to:\n%s", BLUE, log_file_.c_str());
        ROS_INFO("%s[TESTER]: Initialised!", GREEN);
    }

    void resetArm()
    {
        std_srvs::Empty empty_req;
        reset_arm_client_.call(empty_req);
    }

    void initArm()
    {
        std_srvs::Empty empty_req;
        init_arm_client_.call(empty_req);
    }

    void runPlannerAndLog()
    {
        planner::start_plan plan_req;
        plan_req.request.target = "cylinder";

        gazebo_scene_randomiser_plugin::randomise randomise_req;
        randomise_req.request.surface = surface_;
        if (!randomiser_client_.call(randomise_req))
        {
            ROS_FATAL("[TESTER]: Error calling randomiser service!");
            ros::shutdown();
            exit(-1);
        }

        if (planning_client_.call(plan_req))
        {
            std::fstream file;
            file.open(log_file_, std::fstream::app);

            // annoyingly, bool variables in ROS srv/msg are represented as uint8, so each one needs to
            // be cast to bool type to print them out correctly
            file << std::fixed << std::setprecision(3) << bool(plan_req.response.path_found) << ","
                << bool(plan_req.response.partial_solution) << "," << bool(plan_req.response.grasp_success)
                << "," << plan_req.response.num_actions << "," << plan_req.response.plan_time << ","
                << plan_req.response.execution_time << "," << randomise_req.response.num_objects << ","
                << randomise_req.response.free_area << "," << randomise_req.response.surface_area << "\n";

            file.flush();
            file.close();
        }
        else
        {
            ROS_FATAL("[TESTER]: Encountered error while requesting a plan!");
            ros::shutdown();
            exit(-1);
        }
    }

    ros::NodeHandle nh_;
    ros::ServiceClient planning_client_;
    ros::ServiceClient randomiser_client_;
    ros::ServiceClient reset_arm_client_;
    ros::ServiceClient init_arm_client_;

    int num_runs_;
    std::string surface_;
    std::string robot_name_;
    std::string log_file_;

};

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

    Tester tester(&nh);
    tester.run();

    return EXIT_SUCCESS;
}

ext: cpp


text:
/**
 ** Isaac Genome Alignment Software
 ** Copyright (c) 2010-2017 Illumina, Inc.
 ** All rights reserved.
 **
 ** This software is provided under the terms and conditions of the
 ** GNU GENERAL PUBLIC LICENSE Version 3
 **
 ** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
 ** along with this program. If not, see
 ** <https://github.com/illumina/licenses/>.
 **
 ** \file BamLoader.hh
 **
 ** Component to read Bam files.
 **
 ** \author Roman Petrovski
 **/

#ifndef iSAAC_BAM_BAM_PARSER_HH
#define iSAAC_BAM_BAM_PARSER_HH

#include <boost/iterator/iterator_facade.hpp>

#include "alignment/Cigar.hh"
#include "common/Endianness.hh"
#include "common/Exceptions.hh"
#include "common/FastIo.hh"
#include "flowcell/ReadMetadata.hh"
#include "oligo/Nucleotides.hh"
#include "reference/ReferencePosition.hh"

namespace isaac
{
namespace bam
{

struct BamParserException : common::IoException
{
    BamParserException(const std::string &message) : common::IoException(EINVAL, message){}
};

inline char bamBase(const unsigned char bamSeq)
{
    static const unsigned char BAM_BASES[] = {'=', 'A', 'C', 'M', 'G', 'R', 'S', 'V', 'T', 'W', 'Y', 'H', 'K', 'D', 'B', 'N'};
    const unsigned char bamBase = BAM_BASES[bamSeq];
    return bamBase;
}

inline unsigned char bamToBcl(const unsigned char qual, const unsigned char bamSeq)
{
    static const oligo::Translator<> translator = {};
    const unsigned char q = 0xFF == qual ? 0 : std::min<unsigned char>(qual, 0x3f);
    const unsigned char base = bamBase(bamSeq);
//            std::cerr << bamBase;
//            std::cerr << char(q + 33);
    const unsigned char baseValue = translator[base];
    return oligo::INVALID_OLIGO == baseValue ? 0 : (baseValue | (q << 2));
}

struct BamBlockHeader : boost::noncopyable
{
protected:
    int32_t block_size;
    int32_t refID;
    int32_t pos;
    uint32_t bin_mq_nl;
    uint32_t flag_nc;
    int32_t l_seq;
    int32_t next_refID;
    int32_t next_pos;
    int32_t tlen;
    char read_name[1];
public:

    static const unsigned MULTI_SEGMENT = 0x01 << 16;
    static const unsigned UNMAPPED_SEGMENT = 0x04 << 16;
    static const unsigned NEXT_UNMAPPED_SEGMENT = 0x08 << 16;
    static const unsigned REV_COMPL = 0x10 << 16;
    static const unsigned NEXT_REV_COMPL = 0x20 << 16;
    static const unsigned FIRST_SEGMENT = 0x40 << 16;
    static const unsigned LAST_SEGMENT = 0x80 << 16;
    static const unsigned VERNDOR_FAILED = 0x200 << 16;
    static const unsigned SECONDARY_ALIGNMENT = 0x100 << 16;
    static const unsigned SUPPLEMENTARY_ALIGNMENT = 0x800 << 16;

    unsigned char getReadNameLength() const {return bin_mq_nl;}
    unsigned short getCigarLength() const {return flag_nc;}
    const char *nameBegin() const {return read_name ;}
    const char *nameEnd() const {return read_name + getReadNameLength();}
    const unsigned *getCigar() const {return reinterpret_cast<const unsigned*>(read_name + getReadNameLength());}
    const unsigned char *getSeq() const {return reinterpret_cast<const unsigned char *>(getCigar() + getCigarLength());}
    const unsigned char *getQual() const {return getSeq() + (getLSeq() + 1) / 2;}
    bool isPaired() const {return flag_nc & MULTI_SEGMENT;}
    bool isReverse() const {return flag_nc & REV_COMPL;}
    bool isNextReverse() const {return flag_nc & NEXT_REV_COMPL;}
    bool isReadOne() const
    {
        // FIRST_SEGMENT is not set for single-ended data
        return !(flag_nc & LAST_SEGMENT);
    }

    bool isPf() const {return !(flag_nc & VERNDOR_FAILED);}
    bool isSupplementaryAlignment() const {return flag_nc & SUPPLEMENTARY_ALIGNMENT;}
    bool isSecondaryAlignment() const {return flag_nc & SECONDARY_ALIGNMENT;}
    bool isUnmapped() const {return flag_nc & UNMAPPED_SEGMENT;}
    bool isNextUnmapped() const {return flag_nc & NEXT_UNMAPPED_SEGMENT;}

    int getRefId() const {return common::extractLittleEndian<int>(&refID);}
    int getNextRefId() const {return common::extractLittleEndian<int>(&next_refID);}

    int getPos() const {return common::extractLittleEndian<int>(&pos);}
    int getNextPos() const {return common::extractLittleEndian<int>(&next_pos);}
    int getLSeq() const {return common::extractLittleEndian<int>(&l_seq);}

    friend std::ostream &seqToStream(std::ostream &os, const BamBlockHeader &bamBlockHeader)
    {
        const unsigned char * const pSeq = bamBlockHeader.getSeq();
        unsigned seqLen = bamBlockHeader.getLSeq();

        unsigned seqOffset = 0;
        while(seqLen--)
        {
            os << bamBase((*(pSeq + seqOffset / 2) >> (4 * ((seqOffset + 1) % 2))) & 0x0F);
            ++seqOffset;
        }

        return os;
    }

    friend std::ostream &operator << (std::ostream &os, const BamBlockHeader &bamBlockHeader)
    {
        return os << "BamBlockHeader("  << bamBlockHeader.read_name <<  "," <<
            bamBlockHeader.refID << ":" << bamBlockHeader.pos <<
            ")";
//        return seqToStream(os, bamBlockHeader) << ")";
    }

#pragma pack(push, 1)
    struct Tag
    {
        char tag[2];
        char value_type;
        union
        {
            char z;
            int8_t c;
            uint8_t C;
            int16_t s;
            uint16_t S;
            int32_t i;
            uint32_t I;

            //TODO: support binary one day.
        } value;

        std::size_t valueLength() const
        {
            switch (value_type)
            {
            case 'Z':
                return strlen(&value.z) + 1;
            case 'c':
            case 'C':
                return 1;
            case 's':
            case 'S':
                return 2;
            case 'i':
            case 'I':
                return 4;
            }
            ISAAC_ASSERT_MSG(false, "Value type " << value_type << " is not supported");
            return -1;
        }

        const Tag * end() const
        {
            return reinterpret_cast<const Tag*>(&value.z + valueLength());
        }

        bool isTag(const char *str) const
        {
            return str[0] == tag[0] && str[1] == tag[1];
        }

        const char *valueBegin() const
        {
            return &value.z;
        }

        const char *valueEnd() const
        {
            return &value.z + valueLength();
        }
        friend std::ostream &operator << (std::ostream &os, const Tag &t)
        {
            return os << "Tag(" << t.tag[0] << t.tag[1] <<
                    "," << t.value_type << "," <<
                    (t.value_type == 'Z' ? &t.value.z : "integer") << ")";
        }
    };
#pragma pack(pop)

    class TagIterator :
        public boost::iterator_facade<
        TagIterator
        , const Tag &
        , boost::forward_traversal_tag
        >
    {
        const Tag* p_;
    public:
        explicit TagIterator(const Tag &tag)
          : p_(&tag)
        {
        }

        explicit TagIterator(const unsigned char *tag)
          : p_(reinterpret_cast<const Tag *>(tag))
        {
        }

    private:
        friend class boost::iterator_core_access;

        void increment() { p_ = p_->end(); }

        bool equal(TagIterator const& other) const
        {
            return this->p_ == other.p_;
        }

        const Tag &dereference() const {
            return *p_; }
    };

    std::size_t blockLength() const
    {
        return common::extractLittleEndian<int32_t>(
                reinterpret_cast<const unsigned char *>(&block_size));
    }
    TagIterator tagsBegin() const
    {
        return TagIterator(getQual() + getLSeq());
    }
    TagIterator tagsEnd() const
    {
        return TagIterator(reinterpret_cast<const unsigned char *>(&refID) + blockLength());
    }
};

class BamParser
{
    unsigned headerBytesToSkip_;
    int referenceSequencesToSkip_;
public:
    BamParser() :
        headerBytesToSkip_(-1U),
        referenceSequencesToSkip_(-1) {}

    void reset()
    {
        headerBytesToSkip_ = -1U;
        referenceSequencesToSkip_ = -1;
    }

    template <typename CollectorT>
    bool parse(
        std::vector<char>::const_iterator &uncompressedIt,
        std::vector<char>::const_iterator uncompressedEnd,
        CollectorT &collector)
    {
        bool moreDataNeeded = true;
        if (headerBytesToSkip_)
        {
            skipHeader(uncompressedIt, uncompressedEnd);
        }

        if (!headerBytesToSkip_)
        {
            if (referenceSequencesToSkip_)
            {
                skipReferences(uncompressedIt, uncompressedEnd);
            }

            if (!referenceSequencesToSkip_)
            {
                while(uncompressedEnd != uncompressedIt)
                {
                    std::vector<char>::const_iterator last = uncompressedIt;
                    moreDataNeeded = parseBamRecord(uncompressedIt, uncompressedEnd, collector);
                    if(!moreDataNeeded || last == uncompressedIt)
                    {
                        // if the uncompressedIt did not move, means we can't parse from this point.
                        // if moreDataNeeded is false, the collector cannot accept anymore data
                        break;
                    }
                }
            }
        }

        return moreDataNeeded;
    }

private:
    bool skipHeader(
        std::vector<char>::const_iterator &it,
        std::vector<char>::const_iterator end);

    bool skipReferences(
        std::vector<char>::const_iterator &it,
        std::vector<char>::const_iterator end);

    template <typename ProcessorT>
    bool parseBamRecord(
        std::vector<char>::const_iterator &it,
        std::vector<char>::const_iterator end,
        ProcessorT &process)
    {
        static const unsigned BLOCK_SIZE_WIDTH = 4;
        const std::vector<char>::const_iterator blockIt = it;
        int block_size = 0;
        if (std::size_t(std::distance(it, end)) < BLOCK_SIZE_WIDTH)
        {
            return true;
        }

        it = common::extractLittleEndian(it, block_size);

        if (std::distance(it, end) < block_size)
        {
            it = blockIt;
            return true;
        }

        ISAAC_ASSERT_MSG(block_size >= int(sizeof(BamBlockHeader)), "bam record size is smaller than the minimum required block_size:" << block_size << " sizeof(BamBlockHeader):" << sizeof(BamBlockHeader));
        const BamBlockHeader &block = *reinterpret_cast<const BamBlockHeader *>(&*it - BLOCK_SIZE_WIDTH);

        const bool lastBlock = std::size_t(std::distance(it + block_size, end)) <= BLOCK_SIZE_WIDTH ||
            std::distance(it + block_size + BLOCK_SIZE_WIDTH, end) < (common::extractLittleEndian<unsigned>(it + block_size));
        const bool ret = process(block, lastBlock);
        it += block_size;

        return ret;
    }

};

/**
 * \brief extracts up to corresponding read length bcl sequence. if bam sequence is shorter than read length, the
 *        rest is padded with 0
 */
template <typename InsertIt, typename UnaryFun>
InsertIt extractBcl(
    const BamBlockHeader &bamBlock,
    InsertIt insertIt,
    UnaryFun translate,
    const flowcell::ReadMetadata &readMetadata)
{
    const unsigned char * const pSeq = bamBlock.getSeq();
    const unsigned char *pQual = bamBlock.getQual();
    const unsigned char * const pQualEnd = pQual + bamBlock.getLSeq();
    unsigned currentCycle = readMetadata.getFirstReadCycle();
    std::vector<unsigned>::const_iterator cycleIterator = readMetadata.getCycles().begin();

    unsigned seqOffset = 0;
    while(pQualEnd != pQual && readMetadata.getCycles().end() != cycleIterator)
    {
        if (*cycleIterator == currentCycle)
        {
            *insertIt++ = translate(bamToBcl(*pQual,
                                             (*(pSeq + seqOffset / 2) >> (4 * ((seqOffset + 1) % 2))) & 0x0F
                                             ));
            ++cycleIterator;
        }
        ++pQual;
        ++seqOffset;
        ++currentCycle;
    }
    insertIt = std::fill_n(insertIt, std::distance(cycleIterator, readMetadata.getCycles().end()), 0);
    return insertIt;
}

template <typename InsertIt>
InsertIt extractForwardBcl(
    const BamBlockHeader &bamBlock,
    InsertIt insertIt,
    const flowcell::ReadMetadata &readMetadata)
{
    return extractBcl(bamBlock, insertIt, [](unsigned char uc){return uc;}, readMetadata);
}

template <typename RandomAccessIt>
RandomAccessIt extractReverseBcl(
    const BamBlockHeader &bamBlock,
    RandomAccessIt randomAccessIt,
    const flowcell::ReadMetadata &readMetadata)
{
    extractBcl(
        bamBlock,
        boost::make_reverse_iterator(randomAccessIt + readMetadata.getLength()),
        &oligo::getReverseBcl,
        readMetadata).base();
    return randomAccessIt + readMetadata.getLength();
}

template <typename RandomAccessIt>
RandomAccessIt extractBcl(
    const BamBlockHeader &bamBlock,
    RandomAccessIt randomAccessIt,
    const flowcell::ReadMetadata &readMetadata)
{
    return bamBlock.isReverse() ?
        extractReverseBcl(bamBlock, randomAccessIt, readMetadata) :
        extractForwardBcl(bamBlock, randomAccessIt, readMetadata);
}

/**
 * \brief retrieve name of the read. Pad up to nameLengthMax with 0
 *
 * \return it + nameLengthMax
 */
template <typename ForwardAccessIt, typename InsertIt>
InsertIt extractReadName(
    ForwardAccessIt nameBegin, const std::size_t nameLength, const unsigned nameLengthMax, InsertIt insertIt)
{
    if (nameLengthMax > nameLength)
    {
        insertIt = std::copy(nameBegin, nameBegin + nameLength, insertIt);
        insertIt = std::fill_n(insertIt, nameLengthMax - nameLength, 0);
        //ISAAC_THREAD_CERR << "Extracting full:" <<  common::makeFastIoString(nameBegin, nameBegin + nameLength) << std::endl;
    }
    else
    {
        insertIt = std::copy(nameBegin + nameLength - nameLengthMax, nameBegin + nameLength, insertIt);
        //ISAAC_THREAD_CERR << "Extracting short:" <<  common::makeFastIoString(nameBegin + nameLength - nameLengthMax, nameBegin + nameLength) << std::endl;
    }
    return insertIt;
}

inline std::size_t formatReadName(
    const BamBlockHeader& block,
    char *szBuffer,
    const unsigned nameLengthMax,
    const flowcell::ReadMetadata &readMetadata)
{
    common::StaticVector<char, 1020> cigarBuffer;

    int pos = -1;
    if (readMetadata.getLength() != unsigned(block.getLSeq()))
    {
        // if input bam was --use-bases-masked, just make the CIGAR up.
        cigarBuffer.resize(100);
        snprintf(&cigarBuffer.front(), cigarBuffer.size(), "%dM", readMetadata.getLength());
    }
    else
    {
        for (BamBlockHeader::TagIterator it = block.tagsBegin(); block.tagsEnd() != it; ++it)
        {
            if (it->isTag("OC"))
            {
                std::copy(it->valueBegin(), it->valueEnd(), std::back_inserter(cigarBuffer));
            }
            else if (it->isTag("OP"))
            {
                // tag position is 1-based
                pos = it->value.i - 1;
            }
        }

        if (cigarBuffer.empty() && block.getCigarLength())
        {
            alignment::Cigar::toString(block.getCigar(), block.getCigar() + block.getCigarLength(), cigarBuffer);
            cigarBuffer.push_back(0);
        }

    }
    snprintf(
        szBuffer, nameLengthMax, "%c:%02d:%010d:%s",
        block.isUnmapped() ? 'u' : block.isReverse() ? 'r' : 'f',
        block.getRefId(), -1 == pos ? block.getPos() : pos,
        cigarBuffer.empty() ? "" : &cigarBuffer.front());

    return strlen(szBuffer);
}

/**
 * \brief retrieve name of the read. Pad up to nameLengthMax with 0
 *
 * \return it + nameLengthMax
 */
template <typename InsertIt>
InsertIt extractReadName(
    const BamBlockHeader &r1Block,
    const BamBlockHeader &r2Block,
    const unsigned nameLengthMax,
    const flowcell::ReadMetadata &r1Metadata,
    const flowcell::ReadMetadata &r2Metadata,
    InsertIt insertIt)
{
#ifdef ISAAC_DEV_STATS_ENABLED
    // ignore part of the name that follows the hash sign
    const char* hashPos = std::find(r1Block.nameBegin(), r1Block.nameEnd() - 1, '#');
    unsigned len = std::distance(r1Block.nameBegin(), hashPos) + 1;
    char szBuffer[std::max(nameLengthMax, len)];
    *std::copy(r1Block.nameBegin(), hashPos, szBuffer) = '#';

    if (len < nameLengthMax)
    {
        len += formatReadName(r1Block, szBuffer + len, nameLengthMax - len, r1Metadata);
        if (len < nameLengthMax)
        {
            szBuffer[len] = '-';
            ++len;
            len += formatReadName(r2Block, szBuffer + len, nameLengthMax - len, r2Metadata);
        }
    }

    return extractReadName(szBuffer, std::min(nameLengthMax, len), nameLengthMax, insertIt);
#else
    return extractReadName(r1Block.nameBegin(), r1Block.getReadNameLength(), nameLengthMax, insertIt);
#endif
}

template <typename InsertIt>
InsertIt extractReadName(
    const BamBlockHeader &bamBlock,
    const unsigned nameLengthMax,
    const flowcell::ReadMetadata &readMetadata,
    InsertIt insertIt)
{
#ifdef ISAAC_DEV_STATS_ENABLED
    ISAAC_ASSERT_MSG(!bamBlock.isPaired(), "TODO: support pairing of unpaired pairs");
    char szBuffer[nameLengthMax];
    const unsigned len = formatReadName(bamBlock, szBuffer, nameLengthMax, readMetadata);
    return extractReadName(szBuffer, std::min(nameLengthMax, len), nameLengthMax, insertIt);
#else
    return extractReadName(bamBlock.nameBegin(), bamBlock.getReadNameLength(), nameLengthMax, insertIt);
#endif
}

} // namespace bam
} // namespace isaac

#endif // #ifndef iSAAC_BAM_BAM_PARSER_HH

ext: hh


text:
/*
 * Deadlocks
 */
#include <iostream>
#include "seastar/core/do_with.hh"
#include "seastar/core/future.hh"
#include <seastar/core/app-template.hh>
#include <seastar/core/when_all.hh>
#include <seastar/core/loop.hh>
#include <seastar/core/condition-variable.hh>
#include <seastar/core/sleep.hh>
#include <boost/iterator/counting_iterator.hpp>

using namespace std::chrono_literals;

seastar::future<> maybe_sleep(bool sleep) {
    if (sleep) {
        return seastar::sleep(10ms);
    } else {
        return seastar::make_ready_future<>();
    }
}

seastar::future<> test(seastar::semaphore& limit) {
    return limit.wait().then([&limit] {
        return limit.wait();
    }).then([&limit] {
        limit.signal(2);
        return maybe_sleep(true);
    });
}

int main(int argc, char* argv[]) {
    seastar::app_template app;
    app.run(argc, argv, [] {
        return seastar::do_with(seastar::semaphore(2), [](auto& limit) {
            return seastar::when_all(seastar::do_for_each(boost::counting_iterator(0), boost::counting_iterator(3), [&limit](int) {
                return test(limit).then([&limit] {
                    return seastar::do_with(0, [&limit](int) {
                        return test(limit);
                    });
                });
            }));
        }).discard_result();
    });
}

ext: cc

max_stars_repo_name: haaawk/seastar

max_issues_repo_name: haaawk/seastar

max_forks_repo_name: haaawk/seastar


text:
/**********************************************************************
 * Software License Agreement (BSD License)
 *
 * Copyright (c) 2014, Christian Gehring
 * All rights reserved.
 *
 *  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 name of Autonomous Systems Lab nor ETH Zurich
 *     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.
 */

/*!
 * @file     ControllerAdapter.hpp
 * @author   Christian Gehring, Dario Bellicoso, Gabriel Hottiger
 * @date     Dec, 2014
 * @note     Restructured, June 2016
 */
#pragma once

// Roco
#include "roco/controllers/controllers.hpp"
#include "roco/model/CommandInterface.hpp"
#include "roco/model/StateInterface.hpp"

// Rocoma
#include "rocoma/controllers/ControllerExtensionImplementation.hpp"

// Boost
#include <boost/thread.hpp>

// STL
#include <atomic>
#include <cassert>
#include <exception>
#include <memory>
#include <type_traits>

namespace rocoma {

template <typename Controller_, typename State_, typename Command_>
class ControllerAdapter : virtual public roco::ControllerAdapterInterface,
                          public ControllerExtensionImplementation<Controller_, State_, Command_> {
 public:
  //! Convenience typedefs
  using Base = ControllerExtensionImplementation<Controller_, State_, Command_>;
  using Controller = Controller_;
  using State = State_;
  using Command = Command_;

 public:
  //! Default constructor
  ControllerAdapter() = default;

  //! Default destructor
  ~ControllerAdapter() override = default;

  //! Implementation of the adapter interface (roco::ControllerAdapterInterface)
  /*! Adapts the adaptees create(dt) function.
   * @param dt  time step [s]
   * @returns true if successful
   */
  bool createController(double dt) override;

  /*! Adapts the adaptees initialize(dt) function.
   * @param dt  time step [s]
   * @returns true if successful
   */
  bool initializeController(double dt) override;

  /*! Adapts the adaptees advance(dt) function.
   * @param dt  time step [s]
   * @returns true if successful
   */
  bool advanceController(double dt) override;

  /*! Adapts the adaptees reset(dt) function.
   * @param dt  time step [s]
   * @returns true if successful
   */
  bool resetController(double dt) override;

  /*! Adapts the adaptees prestop(dt) function.
   * @returns true if successful
   */
  bool preStopController() override;

  /*! Adapts the adaptees stop(dt) function.
   * @returns true if successful
   */
  bool stopController() override;

  /*! Adapts the adaptees cleanup() function.
   * @returns true if successful
   */
  bool cleanupController() override;

  /*! Adapts the adaptees swap() function.
   * @param dt  time step [s]
   * @param state  state of the previous controller
   * @returns true if successful
   */
  bool swapController(double dt, const roco::ControllerSwapStateInterfacePtr& swapState) override;

  /*! Use this method to get the state of the controller. Must be thread-safe parallel to advance.
   * @returns state
   */
  bool getControllerSwapState(roco::ControllerSwapStateInterfacePtr& swapState) override;

  /*! Use this method to set a shared module to the controller.
   * @param   module reference to module to be set
   * @returns true if successful
   */
  bool addControllerSharedModule(const roco::SharedModulePtr& module) override;

  /*! Sets if the real robot is controlled or only a simulated version.
   * @param flag indicating robot type
   */
  void setIsRealRobot(bool isRealRobot) override { this->isRealRobot_ = isRealRobot; }

  /*! This function gets the name of the controller.
   * @returns controller name
   */
  const std::string& getControllerName() const override { return this->getName(); }

  /*! This function indicates whether the controller was initialized.
   * @returns true iff controller is initialized
   */
  bool isControllerInitialized() const override { return this->isInitialized(); }

  /*! This function indicates whether the controller is being stopped
   * @returns true iff controller is being stopped
   */
  bool isBeingStopped() const override { return isBeingStopped_; }

  /*! This function sets whether the controller is being stopped
   * @param isBeeingStopped flag indicating whether controller is being stopped
   */
  void setIsBeingStopped(bool isBeingStopped) override { isBeingStopped_ = isBeingStopped; }

  /*! This function indicates whether the controller is running (meaning it is the currently advanced controller)
   * @returns true iff controller is being stopped
   */
  bool isRunning() const override { return this->isRunning_; }

  /*! This function sets whether the controller is running (meaning it is the currently advanced controller)
   * @param isRunning flag indicating whether controller is running
   */
  void setIsRunning(bool isRunning) override { this->isRunning_ = isRunning; }

 protected:
  /*! Update the robot state. (Check for limits)
   * @param dt          time step [s]
   * @param checkState  indicates if state should be checked against its limits
   * @returns true if successful
   */
  bool updateState(double dt, bool checkState = true);

  /*! Update the command. (Limit the references)
   * @param dt          time step [s]
   * @returns true if successful
   */
  bool updateCommand(double dt);

 protected:
  std::atomic_bool isBeingStopped_{false};
};

}  // namespace rocoma

#include <rocoma/controllers/ControllerAdapter.tpp>

max_stars_repo_name: matthewgan/rocoma

max_issues_repo_name: matthewgan/rocoma

max_forks_repo_name: matthewgan/rocoma


text: #include <boost/spirit/include/qi_lexeme.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#pragma once
#include "expression.hpp"
#include "../support/DefaultSymbolTable.hpp"
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/karma_eps.hpp>
#include <boost/spirit/include/karma_string.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_bind.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/algorithm/string/trim.hpp>

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::expression::bv_const<metaSMT::logic::QF_BV::tag::bvuint_tag>,
  (unsigned long, value)
  (unsigned long, width)
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::expression::bv_const<metaSMT::logic::QF_BV::tag::bvsint_tag>,
  (unsigned long, value)
  (unsigned long, width)
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::expression::bv_const<metaSMT::logic::QF_BV::tag::bvhex_tag>,
  (std::string, str)
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::expression::bv_const<metaSMT::logic::QF_BV::tag::bvbin_tag>,
  (std::string, str)
)

BOOST_FUSION_ADAPT_TPL_STRUCT(
  (ReturnTag)(OpTag),
  (metaSMT::expression::unary_expression)(ReturnTag)(OpTag),
  (metaSMT::expression::logic_expression,expr)
)

BOOST_FUSION_ADAPT_TPL_STRUCT(
  (ReturnTag)(OpTag),
  (metaSMT::expression::binary_expression)(ReturnTag)(OpTag),
  (metaSMT::expression::logic_expression,left)
  (metaSMT::expression::logic_expression,right)
)

BOOST_FUSION_ADAPT_TPL_STRUCT(
  (ReturnTag)(OpTag),
  (metaSMT::expression::ternary_expression)(ReturnTag)(OpTag),
  (metaSMT::expression::logic_expression,expr1)
  (metaSMT::expression::logic_expression,expr2)
  (metaSMT::expression::logic_expression,expr3)
)

BOOST_FUSION_ADAPT_TPL_STRUCT(
  (ReturnTag)(OpTag),
  (metaSMT::expression::nary_expression)(ReturnTag)(OpTag),
  (std::vector<metaSMT::expression::logic_expression>,exprs)
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::logic::predicate,
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::logic::QF_BV::bitvector,
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::logic::Array::array,
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::logic::QF_UF::Uninterpreted_Function,
)

BOOST_FUSION_ADAPT_TPL_STRUCT(
  (OpTag),
  (metaSMT::expression::extend_expression)(OpTag),
  (unsigned long,by)
  (metaSMT::expression::logic_expression,expr)
)

BOOST_FUSION_ADAPT_TPL_STRUCT(
  (OpTag),
  (metaSMT::expression::extract_expression)(OpTag),
  (unsigned long,from)
  (unsigned long,to)
  (metaSMT::expression::logic_expression,expr)
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::expression::select_expression,
  (metaSMT::expression::logic_expression,array)
  (metaSMT::expression::logic_expression,index)
)

BOOST_FUSION_ADAPT_STRUCT(
  metaSMT::expression::store_expression,
  (metaSMT::expression::logic_expression,array)
  (metaSMT::expression::logic_expression,index)
  (metaSMT::expression::logic_expression,value)
)

namespace metaSMT {
  namespace expression {
    namespace spirit = boost::spirit;
    namespace karma = boost::spirit::karma;

    std::string print_expression( logic_expression const &expr,
                                  boost::function<std::string(unsigned)> const &table = support::default_symbol_table );

    template < typename OutputIterator >
    struct grammar : karma::grammar< OutputIterator, logic_expression() > {
      void predicate_to_string(std::string &s, metaSMT::logic::predicate const &p) {
        predtags::var_tag tag = boost::proto::value(p);
        assert( tag.id != 0 && "predicate id number must not be zero" );

        std::ostringstream os;
        os << table(tag.id);
        s = os.str();
      }

      void bitvector_to_string(std::string &s, metaSMT::logic::QF_BV::bitvector const &bv) {
        bvtags::var_tag tag = boost::proto::value(bv);
        assert( tag.id != 0 && "bit-vector id number must not be zero" );
        assert( tag.width != 0 && "bit-vector width must not be zero" );

        std::stringstream os;
        os << table(tag.id);
        s = os.str();
      }

      void array_to_string(std::string &s, metaSMT::logic::Array::array const &array) {
        arraytags::array_var_tag tag = boost::proto::value(array);
        assert( tag.id != 0 && "array id number must not be zero" );

        std::ostringstream os;
        os << table(tag.id);
        s = os.str();
      }

      void uf_to_string(std::string &s, metaSMT::logic::QF_UF::Uninterpreted_Function const &uf) {
        uftags::function_var_tag tag = boost::proto::value(uf);
        assert( tag.id != 0 && "uninterpreted function id number must not be zero" );

        std::ostringstream os;
        os << table(tag.id);
        s = os.str();
      }

      grammar( boost::function<std::string(unsigned)> const &table )
        : grammar::base_type(main_rule)
        , table(table) {

        main_rule %=
        // constants
          bool_rule
        | bit0_rule
        | bit1_rule
        | bvuint_rule
        | bvsint_rule
        | bvhex_rule
        | bvbin_rule

        // variables
        | predicate_rule
        | bitvector_rule
        | array_rule
        | uf_rule

        // unary_expressions
        | not_rule
        | bvnot_rule
        | bvneg_rule

        // binary_expressions
        | equal_rule
        | nequal_rule
        | distinct_rule
        | implies_rule
        | nand_rule
        | nor_rule
        | xor_rule
        | xnor_rule

        | bvand_rule
        | bvnand_rule
        | bvor_rule
        | bvnor_rule
        | bvxor_rule
        | bvxnor_rule

        | bvadd_rule
        | bvsub_rule
        | bvmul_rule
        | bvudiv_rule
        | bvurem_rule
        | bvsdiv_rule
        | bvsrem_rule

        | bvshl_rule
        | bvshr_rule
        | bvashr_rule

        | bvcomp_rule
        | bvslt_rule
        | bvsle_rule
        | bvsge_rule
        | bvsgt_rule
        | bvult_rule
        | bvule_rule
        | bvuge_rule
        | bvugt_rule

        | concat_rule

        // ternary expressions
        | ite_rule

        // nary expressions
        | nary_uf_rule
        | nary_and_rule
        | nary_or_rule

        // expressions with special syntax
        | extract_rule
        | zero_extend_rule
        | sign_extend_rule
        | select_rule
        | store_rule

        | spirit::eps
        ;

        // constants
        bool_rule %= spirit::bool_;
        bit0_rule %= spirit::eps << spirit::lit("#b0");
        bit1_rule %= spirit::eps << spirit::lit("#b1");
        bvuint_rule %= spirit::eps << spirit::lit("(_ bv") << spirit::ulong_ << spirit::lit(' ') << spirit::ulong_ << spirit::lit(')');
        bvsint_rule %= spirit::eps << spirit::lit("(_ bv") << spirit::ulong_ << spirit::lit(' ') << spirit::ulong_ << spirit::lit(')');
        bvbin_rule %= spirit::eps << spirit::lit("#b") << spirit::ascii::string;
        bvhex_rule %= spirit::eps << spirit::lit("#x") << spirit::ascii::string;

        // variables
        predicate_rule = karma::string[boost::phoenix::bind(&grammar<OutputIterator>::predicate_to_string, this, spirit::_1, spirit::_val)];
        bitvector_rule = karma::string[boost::phoenix::bind(&grammar<OutputIterator>::bitvector_to_string, this, spirit::_1, spirit::_val)];
        array_rule = karma::string[boost::phoenix::bind(&grammar<OutputIterator>::array_to_string, this, spirit::_1, spirit::_val)];
        uf_rule = karma::string[boost::phoenix::bind(&grammar<OutputIterator>::uf_to_string, this, spirit::_1, spirit::_val)];

        // unary_expression
        not_rule %= spirit::eps << spirit::lit("(not ") << main_rule << spirit::lit(")");
        bvnot_rule %= spirit::eps << spirit::lit("(bvnot ") << main_rule << spirit::lit(")");
        bvneg_rule %= spirit::eps << spirit::lit("(bvneg ") << main_rule << spirit::lit(")");

        // binary_expressions
        implies_rule %= spirit::eps << spirit::lit("(=> ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        xor_rule %= spirit::eps << spirit::lit("(xor ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        nand_rule %= spirit::eps << spirit::lit("(not (and ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit("))");
        nor_rule %= spirit::eps << spirit::lit("(not (or ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit("))");
        xnor_rule %= spirit::eps << spirit::lit("(not (xor ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit("))");
        equal_rule %= spirit::eps << spirit::lit("(= ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        nequal_rule %= spirit::eps << spirit::lit("(not (= ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit("))");
        distinct_rule %= spirit::eps << spirit::lit("(distinct ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");

        bvand_rule %= spirit::eps << spirit::lit("(bvand ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvor_rule %= spirit::eps << spirit::lit("(bvor ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvxor_rule %= spirit::eps << spirit::lit("(bvxor ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvnand_rule %= spirit::eps << spirit::lit("(bvnand ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvnor_rule %= spirit::eps << spirit::lit("(bvnor ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvxnor_rule %= spirit::eps << spirit::lit("(bvxnor ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");

        bvadd_rule %= spirit::eps << spirit::lit("(bvadd ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvsub_rule %= spirit::eps << spirit::lit("(bvsub ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvmul_rule %= spirit::eps << spirit::lit("(bvmul ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvudiv_rule %= spirit::eps << spirit::lit("(bvudiv ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvurem_rule %= spirit::eps << spirit::lit("(bvurem ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvsdiv_rule %= spirit::eps << spirit::lit("(bvsdiv ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvsrem_rule %= spirit::eps << spirit::lit("(bvsrem ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");

        bvshl_rule %= spirit::eps << spirit::lit("(bvshl ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvshr_rule %= spirit::eps << spirit::lit("(bvlshr ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvashr_rule %= spirit::eps << spirit::lit("(bvashr ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");

        bvcomp_rule %= spirit::eps << spirit::lit("(bvcomp ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvslt_rule %= spirit::eps << spirit::lit("(bvslt ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvsle_rule %= spirit::eps << spirit::lit("(bvsle ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvsge_rule %= spirit::eps << spirit::lit("(bvsge ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvsgt_rule %= spirit::eps << spirit::lit("(bvsgt ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvult_rule %= spirit::eps << spirit::lit("(bvult ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvule_rule %= spirit::eps << spirit::lit("(bvule ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvuge_rule %= spirit::eps << spirit::lit("(bvuge ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        bvugt_rule %= spirit::eps << spirit::lit("(bvugt ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");

        concat_rule %= spirit::eps << spirit::lit("(concat ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");

        // ternary expressions
        ite_rule %= spirit::eps << spirit::lit("(ite ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");

        // nary expressions
        nary_uf_rule %= spirit::eps << spirit::lit("(") << *(main_rule << spirit::lit(" ")) << spirit::lit(")");
        nary_and_rule %= spirit::eps << spirit::lit("(and ") << *(main_rule << spirit::lit(" ")) << spirit::lit(")");
        nary_or_rule %= spirit::eps << spirit::lit("(or ") << *(main_rule << spirit::lit(" ")) << spirit::lit(")");

        // expressions with special syntax
        extract_rule %= spirit::eps << spirit::lit("((_ extract ") << spirit::ulong_ << spirit::lit(" ") << spirit::ulong_ << spirit::lit(")") << spirit::lit(" ") << main_rule << spirit::lit(")");
        zero_extend_rule %= spirit::eps << spirit::lit("((_ zero_extend ") << spirit::uint_ << spirit::lit(") ") << main_rule << spirit::lit(")");
        sign_extend_rule %= spirit::eps << spirit::lit("((_ sign_extend ") << spirit::uint_ << spirit::lit(") ") << main_rule << spirit::lit(")");
        select_rule %= spirit::eps << spirit::lit("(select ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
        store_rule %= spirit::eps << spirit::lit("(store ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(" ") << main_rule << spirit::lit(")");
      }

      boost::function<std::string(unsigned)> const &table;

      // main rule
      karma::rule<OutputIterator, logic_expression()> main_rule;

      // constants
      karma::rule<OutputIterator, bool()> bool_rule;
      karma::rule<OutputIterator, bit0_const()> bit0_rule;
      karma::rule<OutputIterator, bit1_const()> bit1_rule;
      karma::rule<OutputIterator, bv_const<bvtags::bvuint_tag>()> bvuint_rule;
      karma::rule<OutputIterator, bv_const<bvtags::bvsint_tag>()> bvsint_rule;
      karma::rule<OutputIterator, bv_const<bvtags::bvbin_tag>()> bvbin_rule;
      karma::rule<OutputIterator, bv_const<bvtags::bvhex_tag>()> bvhex_rule;

      // variables
      karma::rule<OutputIterator, metaSMT::logic::predicate()> predicate_rule;
      karma::rule<OutputIterator, metaSMT::logic::QF_BV::bitvector()> bitvector_rule;
      karma::rule<OutputIterator, metaSMT::logic::Array::array()> array_rule;
      karma::rule<OutputIterator, metaSMT::logic::QF_UF::Uninterpreted_Function()> uf_rule;

      // unary_expression
      karma::rule<OutputIterator, unary_expression<logic_tag, predtags::not_tag>()> not_rule;
      karma::rule<OutputIterator, unary_expression<bv_tag, bvtags::bvnot_tag>()> bvnot_rule;
      karma::rule<OutputIterator, unary_expression<bv_tag, bvtags::bvneg_tag>()> bvneg_rule;

      // binary expression
      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::implies_tag>()> implies_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::xor_tag>()> xor_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::nand_tag>()> nand_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::nor_tag>()> nor_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::xnor_tag>()> xnor_rule;

      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::equal_tag>()> equal_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::nequal_tag>()> nequal_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, predtags::distinct_tag>()> distinct_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvand_tag>()> bvand_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvor_tag>()> bvor_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvxor_tag>()> bvxor_rule;

      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvnand_tag>()> bvnand_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvnor_tag>()> bvnor_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvxnor_tag>()> bvxnor_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvadd_tag>()> bvadd_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvsub_tag>()> bvsub_rule;

      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvmul_tag>()> bvmul_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvudiv_tag>()> bvudiv_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvurem_tag>()> bvurem_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvsdiv_tag>()> bvsdiv_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvsrem_tag>()> bvsrem_rule;

      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvshl_tag>()> bvshl_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvshr_tag>()> bvshr_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvashr_tag>()> bvashr_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::bvcomp_tag>()> bvcomp_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvslt_tag>()> bvslt_rule;

      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvsle_tag>()> bvsle_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvsge_tag>()> bvsge_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvsgt_tag>()> bvsgt_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvult_tag>()> bvult_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvule_tag>()> bvule_rule;

      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvuge_tag>()> bvuge_rule;
      karma::rule<OutputIterator, binary_expression<logic_tag, bvtags::bvugt_tag>()> bvugt_rule;
      karma::rule<OutputIterator, binary_expression<bv_tag, bvtags::concat_tag>()> concat_rule;

      // ternary expressions
      karma::rule<OutputIterator, ternary_expression<logic_tag, predtags::ite_tag>()> ite_rule;

      // nary expression
      karma::rule<OutputIterator, nary_expression<uf_tag, proto::tag::function>()> nary_uf_rule;
      karma::rule<OutputIterator, nary_expression<logic_tag, predtags::and_tag>()> nary_and_rule;
      karma::rule<OutputIterator, nary_expression<logic_tag, predtags::or_tag>()> nary_or_rule;

      // expressions with special syntax
      karma::rule<OutputIterator, extract_expression<bvtags::extract_tag>()> extract_rule;
      karma::rule<OutputIterator, extend_expression<bvtags::zero_extend_tag>()> zero_extend_rule;
      karma::rule<OutputIterator, extend_expression<bvtags::sign_extend_tag>()> sign_extend_rule;
      karma::rule<OutputIterator, select_expression()> select_rule;
      karma::rule<OutputIterator, store_expression()> store_rule;
    }; // grammar

    template < typename OutputIterator >
    bool print_expression( OutputIterator &out_it,
                           logic_expression const &expr,
                           boost::function<std::string(unsigned)> const &table ) {
      grammar<OutputIterator> g(table);
      return karma::generate_delimited(out_it, g, spirit::ascii::space, expr);
    }

  } // expression
} // metaSMT

max_stars_repo_name: humeafo/metaSMT

max_issues_repo_name: humeafo/metaSMT

max_forks_repo_name: humeafo/metaSMT


text:
#include <memory>
#include <random>

#include <Eigen/Core>
#include <aslam/common/memory.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <maplab-common/pose_types.h>
#include <maplab-common/test/testing-entrypoint.h>
#include <maplab-common/test/testing-predicates.h>
#include <maplab-common/unique-id.h>
#include <posegraph/edge.h>
#include <posegraph/vertex.h>

#include "vi-map/loopclosure-edge.h"
#include "vi-map/mission.h"
#include "vi-map/test/vi-map-test-helpers.h"
#include "vi-map/vi-map.h"
#include "vi-map/vi_map.pb.h"

namespace vi_map {

class VIMapEdgeRemovalTest : public ::testing::Test {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW

 protected:
  virtual void SetUp() {
    vi_map::test::generateMap<TransformationEdge>(kTestDataVertexCount, &map_);
    initial_mission_ = map_.getIdOfFirstMission();
    map_.getAllEdgeIds(&initial_edges_);
    map_.getAllVertexIds(&initial_vertices_);
    map_.getAllLandmarkIds(&initial_landmarks_);
  }

  size_t numVertices() const {
    return kTestDataVertexCount;
  }

  size_t numLoopClosureEdges() const;
  void addRandomLoopClosureEdges(const size_t number_of_edges);

  size_t removeLoopClosureEdges() {
    return map_.removeLoopClosureEdges();
  }

  vi_map::VIMap map_;
  pose_graph::VertexIdList initial_vertices_;
  pose_graph::EdgeIdList initial_edges_;
  vi_map::LandmarkIdSet initial_landmarks_;
  vi_map::MissionId initial_mission_;

 private:
  // Modify if test dataset with different vertex count used.
  static constexpr size_t kTestDataVertexCount = 405u;
  static constexpr double kSwitchVariable = 1.0;
  static constexpr double kSwitchVariableVariance = 1e-3;
};

size_t VIMapEdgeRemovalTest::numLoopClosureEdges() const {
  size_t number_of_loop_edges = 0u;
  pose_graph::EdgeIdList edges;
  map_.getAllEdgeIds(&edges);

  for (const pose_graph::EdgeId& edge : edges) {
    number_of_loop_edges += static_cast<int>(
        map_.getEdgeType(edge) == pose_graph::Edge::EdgeType::kLoopClosure);
  }
  return number_of_loop_edges;
}

void VIMapEdgeRemovalTest::addRandomLoopClosureEdges(
    const size_t number_of_edges_to_add) {
  Eigen::Matrix<double, 6, 6> T_A_B_covariance;
  pose::Transformation T_A_B;

  constexpr size_t kSeed = 85u;
  std::srand(kSeed);

  std::mt19937 integer_generator(kSeed);
  constexpr size_t kLowerBound = 0u;
  constexpr size_t kUpperBound = kTestDataVertexCount - 1u;
  std::uniform_int_distribution<> vertex_index_uniform_distribution(
      kLowerBound, kUpperBound);

  constexpr size_t kVerticesOffset = 10u;
  for (size_t edges_added = 0u; edges_added < number_of_edges_to_add;
       ++edges_added) {
    const size_t vertex_idx_from =
        vertex_index_uniform_distribution(integer_generator);
    const size_t vertex_idx_to =
        (vertex_idx_from + kVerticesOffset) % kTestDataVertexCount;
    ASSERT_NE(vertex_idx_from, vertex_idx_to);

    T_A_B.setRandom();
    T_A_B_covariance.setRandom();

    pose_graph::EdgeId edge_id;
    common::generateId(&edge_id);
    ASSERT_TRUE(edge_id.isValid());

    const pose_graph::VertexId& from = initial_vertices_[vertex_idx_from];
    const pose_graph::VertexId& to = initial_vertices_[vertex_idx_to];

    map_.addEdge(
        vi_map::Edge::UniquePtr(
            new LoopClosureEdge(
                edge_id, from, to, kSwitchVariable, kSwitchVariableVariance,
                T_A_B, T_A_B_covariance)));
  }
}

TEST_F(VIMapEdgeRemovalTest, RemoveLoopClosureEdgesTest) {
  EXPECT_EQ(numLoopClosureEdges(), 0u);

  constexpr size_t kNumNewLoopEdges = 100u;
  addRandomLoopClosureEdges(kNumNewLoopEdges);

  EXPECT_EQ(numLoopClosureEdges(), kNumNewLoopEdges);
  EXPECT_EQ(removeLoopClosureEdges(), kNumNewLoopEdges);
  EXPECT_EQ(numLoopClosureEdges(), 0u);
}

}  // namespace vi_map

MAPLAB_UNITTEST_ENTRYPOINT


text:
// -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Copyright (c) 2010-2015 Illumina, Inc.
// All rights reserved.

// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:

// 1. Redistributions of source code must retain the above copyright notice, this
//    list of conditions and the following disclaimer.

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

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

/**
 *  \brief Fasta wrapper implementation
 *
 * \file Fasta.cpp
 * \author Peter Krusche
 * \email pkrusche@illumina.com
 *
 */

#include "Fasta.hh"
#include "Error.hh"
#include "helpers/StringUtil.hh"

#include <boost/filesystem.hpp>
#include <iostream>
#include <cstdio>
#include <limits>
#include <map>
#include <fstream>
#include <mutex>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

#include <boost/algorithm/string.hpp>

extern "C" {

// GCC warns us about some things in htslib here. We don't care.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wredundant-decls"

#include <htslib/faidx.h>

#pragma GCC diagnostic pop
}

//#define DEBUG_FASTAFILE

class MMappedFastaFile {
public:
    explicit MMappedFastaFile(std::string const & _filename) :
        filename(_filename)
    {
        struct stat st;
        stat(_filename.c_str(), &st);
        filesize = (size_t) st.st_size;
        fd = open(_filename.c_str(), O_RDONLY, 0);
        assert(fd != -1);
#if __APPLE__
        base = (uint8_t *) mmap(NULL, filesize, PROT_READ, MAP_PRIVATE, fd, 0);
#else
        base = (uint8_t *) mmap(NULL, filesize, PROT_READ, MAP_PRIVATE | MAP_POPULATE, fd, 0);
#endif
        if(base == MAP_FAILED)
        {
            const int err = errno;
            error("Cannot mmap %s (errno=%i / %s) -- do you have enough memory available?",
                  _filename.c_str(), err, strerror(err));
        }

        auto fai_fp = fopen((filename + ".fai").c_str(), "r");
        if(!fai_fp)
        {
            assert(fai_build(filename.c_str()) == 0);
        }
        else
        {
            fclose(fai_fp);
        }

        std::ifstream index_in(filename + ".fai");
        while(index_in.good())
        {
            std::string line;
            std::getline(index_in, line);
            std::vector<std::string> parts;
            stringutil::split(line, parts, "\n\t", false);
            if(parts.size() == 5)
            {
                const std::string contig = parts[0];
                index_entry ientry;
                sscanf(parts[1].c_str(), "%zu", &ientry.length);
                sscanf(parts[2].c_str(), "%zu", &ientry.start_offset);
                sscanf(parts[3].c_str(), "%zu", &ientry.chars_per_line);
                sscanf(parts[4].c_str(), "%zu", &ientry.bytes_per_line);
                fai[contig] = ientry;

                // determine non-N length; we don't do this because it's pretty slow.
//                size_t offset = ientry.start_offset;
//                const size_t line_number = (ientry.length - 1) / ientry.chars_per_line;
//                size_t offset_in_line = (ientry.length - 1) % ientry.chars_per_line;
//                size_t offset_end = ientry.start_offset + line_number*ientry.bytes_per_line + offset_in_line + 1;
//                size_t ns = 0;
//
//                while(offset < offset_end)
//                {
//                    if(std::tolower(base[offset - 1]) == 'n')
//                    {
//                        ++ns;
//                    }
//                    ++offset;
//                }
//                fai[contig].non_n_length = fai[contig].length - ns;

                // length trimming off N's at start and end
                size_t pos = 0;
                size_t ns_at_start = 0;
                bool done = false;

                // start of contig
                while(pos < ientry.length && !done)
                {
                    const std::string s = get(contig, pos, 10000);

                    for(size_t j = 0; j < s.size(); ++j)
                    {
                        if(std::tolower(s.at(j)) == 'n')
                        {
                            ++ns_at_start;
                        }
                        else
                        {
                            done = true;
                            break;
                        }
                    }

                    pos += s.size();
                }

                size_t ns_at_end = 0;
                // check if we had all Ns
                if(ns_at_start < ientry.length)
                {
                    const size_t line_number = (ientry.length - 1) / ientry.chars_per_line;
                    size_t offset_in_line = (ientry.length - 1) % ientry.chars_per_line;
                    size_t offset = ientry.start_offset + line_number*ientry.bytes_per_line + offset_in_line + 1;

                    // end of contig
                    while(offset > ientry.start_offset)
                    {
                        if (base[offset - 1] == '\n' || base[offset - 1] == '\r')
                        {
                            // skip newlines
                        }
                        else if(std::tolower(base[offset - 1]) == 'n')
                        {
                            ++ns_at_end;
                        }
                        else
                        {
                            break;
                        }
                        --offset;
                    }
                }
                fai[contig].non_n_length = fai[contig].length - (ns_at_start + ns_at_end);
            }
            else if(parts.size() > 0)
            {
                error("invalid fai line %s in %s", line.c_str(), (filename + ".fai").c_str());
            }
        }
    }

    ~MMappedFastaFile()
    {
        const int rc = munmap(base, filesize);
        assert(rc == 0);
        close(fd);
    }

    std::string get(std::string const & contig, size_t start, size_t len)
    {
        auto ientry = fai.find(contig);
        if(ientry == fai.end())
        {
            error("Contig %s is not known", contig.c_str());
        }

        if(start >= ientry->second.length)
        {
            return "";
            /* TODO: handle downstream */
            /* error("Position %zu is past the end of contig %s", start, contig.c_str()); */
        }

        const size_t line = start / ientry->second.chars_per_line;
        size_t offset_in_line = start % ientry->second.chars_per_line;
        size_t chars_in_line = ientry->second.chars_per_line - offset_in_line;
        size_t line_offset = ientry->second.start_offset + line*ientry->second.bytes_per_line;

        chars_in_line = std::min(chars_in_line, ientry->second.length - start);

        std::string result;
        while(len > 0)
        {
            const size_t to_read = std::min(len, chars_in_line);
            result += std::string((const char *)(base + line_offset + offset_in_line), to_read);
            len -= to_read;
            start += to_read;
            offset_in_line = 0;
            line_offset += ientry->second.bytes_per_line;
            if(start >= ientry->second.length)
            {
                break;
            }
            chars_in_line = std::min(ientry->second.chars_per_line, ientry->second.length - start);
        }
        return result;
    }

    /**
     * return the size of a contig. Sum of all contig sizes if contig == 0
     * @param contig name of contig, or empty
     * @return number of bases in the contig
     */
    size_t contigSize(std::string const & contig) const
    {
        size_t result = 0;
        if(contig.empty())
        {
            for(const auto & ix : fai)
            {
                result += ix.second.length;
            }
        }
        else
        {
            auto k = fai.find(contig);
            if(k != fai.end())
            {
                result += k->second.length;
            }
        }

        return result;
    }

    /**
     * return the non-N padded size of a contig. This is calculated
     * as the size of the contig minus any N's at the beginning or
     * at the end.
     *
     * Returns the sum of all contig sizes if contig == 0
     * @param contig name of contig, or empty
     * @return number of bases in the contig
     */
    size_t contigNonNSize(std::string const & contig) const
    {
        size_t result = 0;
        if(contig.empty())
        {
            for(const auto & ix : fai)
            {
                result += ix.second.non_n_length;
            }
        }
        else
        {
            auto k = fai.find(contig);
            if(k != fai.end())
            {
                result += k->second.non_n_length;
            }
        }

        return result;
    }

    std::list<std::string> getContigNames() const
    {
        std::list<std::string> names;
        for(auto const & c : fai)
        {
            names.push_back(c.first);
        }
        return names;
    }

private:
    typedef struct _index_entry
    {
        size_t length;
        size_t start_offset;
        size_t chars_per_line;
        size_t bytes_per_line;
        size_t non_n_length;
    } index_entry;

    std::string filename;
    int fd;
    size_t filesize;
    uint8_t * base;

    std::map<std::string, index_entry> fai;
};

class FastaFileCache
{
public:
    std::shared_ptr<MMappedFastaFile> operator() (std::string const & filename)
    {
        std::lock_guard<std::mutex> write_lock(write_mutex);
        auto it = cache.find(filename);
        if(it == cache.end())
        {
#ifdef DEBUG_FASTAFILE
            std::cerr << "fastafile: adding " << filename << std::endl;
#endif
            it = cache.emplace(filename, std::make_shared<MMappedFastaFile>(filename)).first;

#ifdef DEBUG_FASTAFILE
            std::cerr << "fastafile: added " << filename << std::endl;
        }
        else
        {
            std::cerr << "fastafile: reused " << filename << std::endl;
#endif
        }
        return it->second;
    }
private:
    static std::map<std::string, std::shared_ptr<MMappedFastaFile>> cache;
    static std::mutex write_mutex;
};

std::map<std::string, std::shared_ptr<MMappedFastaFile>> FastaFileCache::cache;
std::mutex FastaFileCache::write_mutex;

struct FastaFileImpl
{
    explicit FastaFileImpl(const char * _filename) :
        filename(_filename)
    {
        FastaFileCache cache;
        contigs = cache(filename);
    }

    ~FastaFileImpl() {}

    std::string filename;
    std::shared_ptr<MMappedFastaFile> contigs;
};

FastaFile::FastaFile() {
    _impl = NULL;
}

FastaFile::FastaFile(const char * filename)
{
    _impl = new FastaFileImpl(filename);
}

FastaFile::~FastaFile()
{
    if(_impl) {
        delete _impl;
    }
}

std::string FastaFile::getFilename() const
{
    if(!_impl) return "";
    return _impl->filename;
}

FastaFile::FastaFile(FastaFile const & rhs)
{
    _impl = new FastaFileImpl(rhs._impl->filename.c_str());
}

FastaFile & FastaFile::operator=(FastaFile const & rhs)
{
    if (&rhs == this)
    {
        return *this;
    }
    if(_impl) delete _impl;
    _impl = new FastaFileImpl(rhs._impl->filename.c_str());
    return *this;
}

std::string FastaFile::query(std::string const & location) const
{
    std::string chr;
    int64_t start = -1;
    int64_t end = -1;

    stringutil::parsePos(location, chr, start, end);
    return query(chr.c_str(), start, end);
}

std::string FastaFile::query(const char * chr, int64_t start, int64_t end) const
{
    if(end < start)
    {
        return "";
    }

    start = std::max(start, (int64_t )0l);

    const int64_t requested_length = end - start + 1;
    if(requested_length <= 0)
    {
        return "";
    }

    std::string result = _impl->contigs->get(chr, (size_t) start, (size_t) requested_length);
    boost::to_upper(result);
    return result;
}

/**
 * return the size of a contig. Sum of all contig sizes if contig == 0
 * @param contig name of contig, or empty
 * @return number of bases in the contig
 */
size_t FastaFile::contigSize(std::string const & contig) const
{
    return _impl->contigs->contigSize(contig);
}

/**
 * return the non-N padded size of a contig. This is calculated
 * as the size of the contig minus any N's at the beginning or
 * at the end.
 *
 * Returns the sum of all contig sizes if contig == 0
 * @param contig name of contig, or empty
 * @return number of bases in the contig
 */
size_t FastaFile::contigNonNSize(std::string const & contig) const
{
    return _impl->contigs->contigNonNSize(contig);
}

/**
 * @return all contig names
 */
std::list<std::string> FastaFile::getContigNames() const
{
    return _impl->contigs->getContigNames();
}


text:
/*

Copyright (c) 2018, Brian Bingham
All rights reserved

This file is part of the usv_gazebo_dynamics_plugin package, known as this Package.

This Package free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This Package s distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this package.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <boost/thread.hpp>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/JointState.h>
#include <ros/time.h>
#include <tf2/LinearMath/Transform.h>

#include <usv_gazebo_plugins/usv_gazebo_wind_plugin.h>

#define GRAVITY 9.815

using namespace gazebo;

UsvWindPlugin::UsvWindPlugin()
{
}

UsvWindPlugin::~UsvWindPlugin()
{
  rosnode_->shutdown();
  spinner_thread_->join();
  delete rosnode_;
  delete spinner_thread_;
}

void UsvWindPlugin::FiniChild()
{
}

double UsvWindPlugin::getSdfParamDouble(sdf::ElementPtr sdfPtr, const std::string &param_name, double default_val)
{
  double val = default_val;
  if (sdfPtr->HasElement(param_name) && sdfPtr->GetElement(param_name)->GetValue())
  {
    val = sdfPtr->GetElement(param_name)->Get<double>();
    ROS_INFO_STREAM("Parameter found - setting <" << param_name << "> to <" << val << ">.");

  }
  else{
    ROS_INFO_STREAM("Parameter <" << param_name << "> not found: Using default value of <" << val << ">.");
  }
  return val;
}

void UsvWindPlugin::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf )
{
  ROS_INFO("Loading usv_gazebo_wind_plugin");
  model_ = _parent;
  world_ = model_->GetWorld();

  // Retrieve model paramters from SDF
  // Set default values
  node_namespace_ = "";

  //  Enumerating model
  ROS_INFO_STREAM("Enumerating Model...");
  ROS_INFO_STREAM("Model name = "<< model_->GetName());
  physics::Link_V links = model_->GetLinks();
  for (int ii=0; ii<links.size(); ii++){
    ROS_INFO_STREAM("Link: "<<links[ii]->GetName());
  }

  // Get parameters from SDF
  if (_sdf->HasElement("robotNamespace"))
  {
    node_namespace_ = _sdf->GetElement("robotNamespace")->Get<std::string>() + "/";
  }

  if (!_sdf->HasElement("bodyName") || !_sdf->GetElement("bodyName")->GetValue())
  {
    link_ = model_->GetLink();
    link_name_ = link_->GetName();
    ROS_INFO_STREAM("Did not find SDF parameter bodyName");
  }
  else {
    link_name_ = _sdf->GetElement("bodyName")->Get<std::string>();
    //link_name_ = "thrust_link";
    link_ = model_->GetLink(link_name_);

    ROS_INFO_STREAM("Found SDF parameter bodyName as <"<<link_name_<<">");
  }
  if (!link_)
  {
    ROS_FATAL("usv_gazebo_wind_plugin error: bodyName: %s does not exist\n", link_name_.c_str());
    return;
  }
  else
  {
    ROS_INFO_STREAM("USV Model Link Name = " << link_name_);
  }

  if (_sdf->HasElement("wind_velocity_vector")){
    param_wind_velocity_vector_ = _sdf->GetElement("wind_velocity_vector")->Get<math::Vector3>();
  }
  else{
    param_wind_velocity_vector_ = math::Vector3(0,0,0);
  }
  ROS_INFO_STREAM("Wind velocity vector = "<<param_wind_velocity_vector_.x << " , " << param_wind_velocity_vector_.y << " , " << param_wind_velocity_vector_.z);

  if (_sdf->HasElement("wind_coeff_vector")){
    param_wind_coeff_vector_ = _sdf->GetElement("wind_coeff_vector")->Get<math::Vector3>();
  }
  else{
    param_wind_coeff_vector_ = math::Vector3(0,0,0);
  }
  ROS_INFO_STREAM("Wind coefficient vector = "<<param_wind_coeff_vector_.x << " , " << param_wind_coeff_vector_.y << " , " << param_wind_coeff_vector_.z);

  // Initialize the ROS node and subscribe to cmd_drive
  int argc = 0;
  char** argv = NULL;
  ros::init(argc, argv, "usv_wind_gazebo",
	    ros::init_options::NoSigintHandler|ros::init_options::AnonymousName);
  rosnode_ = new ros::NodeHandle( node_namespace_ );

  // Listen to the update event. This event is broadcast every
  // simulation iteration.
  this->spinner_thread_ = new boost::thread( boost::bind( &UsvWindPlugin::spin, this) );
  this->updateConnection = event::Events::ConnectWorldUpdateBegin(
    boost::bind(&UsvWindPlugin::UpdateChild, this));
}
void UsvWindPlugin::UpdateChild()
{
  // Wind
  // Transform wind from world coordinates to body coordinates
  math::Vector3 relative_wind = link_->GetWorldPose().rot.GetInverse().RotateVector(param_wind_velocity_vector_);
  // Calculate apparent wind
  math::Vector3 apparent_wind = relative_wind - link_->GetRelativeLinearVel();
  ROS_DEBUG_STREAM_THROTTLE(1.0,"Relative wind: " << relative_wind);
  ROS_DEBUG_STREAM_THROTTLE(1.0,"Apparent wind: " << apparent_wind);
  // Calculate wind force - body coordinates
  math::Vector3 wind_force(
			   param_wind_coeff_vector_.x * relative_wind.x * abs(relative_wind.x),
			   param_wind_coeff_vector_.y * relative_wind.y * abs(relative_wind.y),
			   -2.0*param_wind_coeff_vector_.z * relative_wind.x * relative_wind.y);

  // Add forces/torques to link at CG
  link_->AddRelativeForce(math::Vector3(wind_force.x, wind_force.y, 0.0));
  link_->AddRelativeTorque(math::Vector3(0.0,0.0,wind_force.z));
}

void UsvWindPlugin::spin()
{
    while(ros::ok()) ros::spinOnce();
}

GZ_REGISTER_MODEL_PLUGIN(UsvWindPlugin);


text:
/***************************************************************************
 * Copyright 1998-2017 by authors (see AUTHORS.txt)                        *
 *                                                                         *
 *   This file is part of LuxRender.                                       *
 *                                                                         *
 * 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/detail/container_fwd.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/format.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>

#include "slg/scene/scene.h"

#include "slg/shapes/meshshape.h"
#include "slg/shapes/pointiness.h"
#include "slg/shapes/strands.h"

using namespace std;
using namespace luxrays;
using namespace slg;

void Scene::ParseShapes(const Properties &props) {
	vector<string> shapeKeys = props.GetAllUniqueSubNames("scene.shapes");
	if (shapeKeys.size() == 0) {
		// There are not shape definitions
		return;
	}

	double lastPrint = WallClockTime();
	u_int shapeCount = 0;
	BOOST_FOREACH(const string &key, shapeKeys) {
		// Extract the shape name
		const string shapeName = Property::ExtractField(key, 2);
		if (shapeName == "")
			throw runtime_error("Syntax error in shape definition: " + shapeName);

		ExtMesh *mesh = CreateShape(shapeName, props);
		if (extMeshCache.IsExtMeshDefined(shapeName)) {
			// A replacement for an existing mesh
			const ExtMesh *oldMesh = extMeshCache.GetExtMesh(shapeName);

			// Replace old mesh direct references with new one and get the list
			// of scene objects referencing the old mesh
			boost::unordered_set<SceneObject *> modifiedObjsList;
			objDefs.UpdateMeshReferences(oldMesh, mesh, modifiedObjsList);

			// For each scene object
			BOOST_FOREACH(SceneObject *o, modifiedObjsList) {
				// Check if is a light source
				if (o->GetMaterial()->IsLightSource()) {
					const string objName = o->GetName();

					// Delete all old triangle lights
					lightDefs.DeleteLightSourceStartWith(objName + TRIANGLE_LIGHT_POSTFIX);

					// Add all new triangle lights
					SDL_LOG("The " << objName << " object is a light sources with " << mesh->GetTotalTriangleCount() << " triangles");

					for (u_int i = 0; i < mesh->GetTotalTriangleCount(); ++i) {
						TriangleLight *tl = new TriangleLight();
						tl->lightMaterial = o->GetMaterial();
						tl->mesh = mesh;
						tl->triangleIndex = i;
						tl->Preprocess();

						lightDefs.DefineLightSource(objName + TRIANGLE_LIGHT_POSTFIX + ToString(i), tl);
					}

					editActions.AddActions(LIGHTS_EDIT | LIGHT_TYPES_EDIT);
				}
			}
		}

		extMeshCache.DefineExtMesh(shapeName, mesh);

		++shapeCount;

		const double now = WallClockTime();
		if (now - lastPrint > 2.0) {
			SDL_LOG("Shape count: " << shapeCount);
			lastPrint = now;
		}
	}
	SDL_LOG("Shape count: " << shapeCount);

	editActions.AddActions(GEOMETRY_EDIT);
}

ExtMesh *Scene::CreateInlinedMesh(const string &shapeName, const string &propName, const Properties &props) {
	// The mesh definition is in-lined
	u_int pointsSize;
	Point *points;
	if (props.IsDefined(propName + ".vertices")) {
		Property prop = props.Get(propName + ".vertices");
		if ((prop.GetSize() == 0) || (prop.GetSize() % 3 != 0))
			throw runtime_error("Wrong shape vertex list length: " + shapeName);

		pointsSize = prop.GetSize() / 3;
		points = TriangleMesh::AllocVerticesBuffer(pointsSize);
		for (u_int i = 0; i < pointsSize; ++i) {
			const u_int index = i * 3;
			points[i] = Point(prop.Get<float>(index), prop.Get<float>(index + 1), prop.Get<float>(index + 2));
		}
	} else
		throw runtime_error("Missing shape vertex list: " + shapeName);

	u_int trisSize;
	Triangle *tris;
	if (props.IsDefined(propName + ".faces")) {
		Property prop = props.Get(propName + ".faces");
		if ((prop.GetSize() == 0) || (prop.GetSize() % 3 != 0))
			throw runtime_error("Wrong shape face list length: " + shapeName);

		trisSize = prop.GetSize() / 3;
		tris = TriangleMesh::AllocTrianglesBuffer(trisSize);
		for (u_int i = 0; i < trisSize; ++i) {
			const u_int index = i * 3;
			tris[i] = Triangle(prop.Get<u_int>(index), prop.Get<u_int>(index + 1), prop.Get<u_int>(index + 2));
		}
	} else {
		delete[] points;
		throw runtime_error("Missing shape face list: " + shapeName);
	}

	Normal *normals = NULL;
	if (props.IsDefined(propName + ".normals")) {
		Property prop = props.Get(propName + ".normals");
		if ((prop.GetSize() == 0) || (prop.GetSize() / 3 != pointsSize))
			throw runtime_error("Wrong shape normal list length: " + shapeName);

		normals = new Normal[pointsSize];
		for (u_int i = 0; i < pointsSize; ++i) {
			const u_int index = i * 3;
			normals[i] = Normal(prop.Get<float>(index), prop.Get<float>(index + 1), prop.Get<float>(index + 2));
		}
	}

	UV *uvs = NULL;
	if (props.IsDefined(propName + ".uvs")) {
		Property prop = props.Get(propName + ".uvs");
		if ((prop.GetSize() == 0) || (prop.GetSize() / 2 != pointsSize))
			throw runtime_error("Wrong shape uv list length: " + shapeName);

		uvs = new UV[pointsSize];
		for (u_int i = 0; i < pointsSize; ++i) {
			const u_int index = i * 2;
			uvs[i] = UV(prop.Get<float>(index), prop.Get<float>(index + 1));
		}
	}

	return new ExtTriangleMesh(pointsSize, trisSize, points, tris, normals, uvs);
}

ExtMesh *Scene::CreateShape(const string &shapeName, const Properties &props) {
	const string propName = "scene.shapes." + shapeName;

	// Get the shape type
	const string shapeType = props.Get(Property(propName + ".type")("mesh")).Get<string>();

	// Define the shape
	Shape *shape;
	if (shapeType == "mesh") {
		const string meshName = props.Get(Property(propName + ".ply")("")).Get<string>();

		MeshShape *meshShape = new MeshShape(meshName);

		if (props.IsDefined(propName + ".transformation")) {
			// Apply the transformation
			const Matrix4x4 mat = props.Get(Property(propName +
					".transformation")(Matrix4x4::MAT_IDENTITY)).Get<Matrix4x4>();
			meshShape->ApplyTransform(Transform(mat));
		}

		shape = meshShape;
	} else if (shapeType == "inlinedmesh") {
		MeshShape *meshShape = new MeshShape(CreateInlinedMesh(shapeName, propName, props));

		if (props.IsDefined(propName + ".transformation")) {
			// Apply the transformation
			const Matrix4x4 mat = props.Get(Property(propName +
					".transformation")(Matrix4x4::MAT_IDENTITY)).Get<Matrix4x4>();
			meshShape->ApplyTransform(Transform(mat));
		}

		shape = meshShape;
	} else if (shapeType == "pointiness") {
		const string sourceMeshName = props.Get(Property(propName + ".source")("")).Get<string>();
		if (!extMeshCache.IsExtMeshDefined(sourceMeshName))
			throw runtime_error("Unknown shape name in a pointiness shape: " + shapeName);

		shape = new PointinessShape((ExtTriangleMesh *)extMeshCache.GetExtMesh(sourceMeshName));
	} else if (shapeType == "strands") {
		const string fileName = props.Get(Property(propName + ".file")("strands.hair")).Get<string>();

		// For compatibility with the past
		string tessellationTypeStr = props.Get(Property(propName + ".tesselation.type")("ribbon")).Get<string>();
		tessellationTypeStr = props.Get(Property(propName + ".tessellation.type")(tessellationTypeStr)).Get<string>();

		StrendsShape::TessellationType tessellationType;
		if (tessellationTypeStr == "ribbon")
			tessellationType = StrendsShape::TESSEL_RIBBON;
		else if (tessellationTypeStr == "ribbonadaptive")
			tessellationType = StrendsShape::TESSEL_RIBBON_ADAPTIVE;
		else if (tessellationTypeStr == "solid")
			tessellationType = StrendsShape::TESSEL_SOLID;
		else if (tessellationTypeStr == "solidadaptive")
			tessellationType = StrendsShape::TESSEL_SOLID_ADAPTIVE;
		else
			throw runtime_error("Tessellation type unknown: " + tessellationTypeStr);

		// For compatibility with the past
		u_int adaptiveMaxDepth = Max(0, props.Get(Property(propName + ".tesselation.adaptive.maxdepth")(8)).Get<int>());
		adaptiveMaxDepth = Max(0, props.Get(Property(propName + ".tessellation.adaptive.maxdepth")(adaptiveMaxDepth)).Get<int>());
		// For compatibility with the past
		float adaptiveError = props.Get(Property(propName + ".tesselation.adaptive.error")(.1f)).Get<float>();
		adaptiveError = props.Get(Property(propName + ".tessellation.adaptive.error")(adaptiveError)).Get<float>();

		// For compatibility with the past
		u_int solidSideCount = Max(0, props.Get(Property(propName + ".tesselation.solid.sidecount")(3)).Get<int>());
		solidSideCount = Max(0, props.Get(Property(propName + ".tessellation.solid.sidecount")(solidSideCount)).Get<int>());
		// For compatibility with the past
		bool solidCapBottom = props.Get(Property(propName + ".tesselation.solid.capbottom")(false)).Get<bool>();
		solidCapBottom = props.Get(Property(propName + ".tessellation.solid.capbottom")(solidCapBottom)).Get<bool>();
		// For compatibility with the past
		bool solidCapTop = props.Get(Property(propName + ".tesselation.solid.captop")(false)).Get<bool>();
		solidCapTop = props.Get(Property(propName + ".tessellation.solid.captop")(solidCapTop)).Get<bool>();

		// For compatibility with the past
		bool useCameraPosition = props.Get(Property(propName + ".tesselation.usecameraposition")(false)).Get<bool>();
		useCameraPosition = props.Get(Property(propName + ".tessellation.usecameraposition")(useCameraPosition)).Get<bool>();

		cyHairFile strandsFile;
		const int strandsCount = strandsFile.LoadFromFile(fileName.c_str());
		if (strandsCount <= 0)
			throw runtime_error("Unable to read strands file: " + fileName);

		shape = new StrendsShape(this,
				&strandsFile, tessellationType,
				adaptiveMaxDepth, adaptiveError,
				solidSideCount, solidCapBottom, solidCapTop,
				useCameraPosition);
	} else
		throw runtime_error("Unknown shape type: " + shapeType);

	ExtMesh *mesh = shape->Refine(this);
	delete shape;

	return mesh;
}

max_stars_repo_name: LuxRender/LuxRays

max_issues_repo_name: LuxRender/LuxRays

max_forks_repo_name: LuxRender/LuxRays


text:
/*
 Copyright (C) 2018 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include <boost/make_shared.hpp>
// clang-format off
#include <boost/test/unit_test.hpp>
#include <boost/test/data/test_case.hpp>
// clang-format on
#include <oret/datapaths.hpp>
#include <oret/toplevelfixture.hpp>

#include <ql/math/comparison.hpp>
#include <ql/math/interpolations/linearinterpolation.hpp>
#include <ql/math/interpolations/loginterpolation.hpp>
#include <ql/time/daycounters/actualactual.hpp>

#include <ored/configuration/curveconfigurations.hpp>
#include <ored/marketdata/commoditycurve.hpp>
#include <ored/marketdata/csvloader.hpp>
#include <ored/marketdata/curvespec.hpp>
#include <ored/marketdata/loader.hpp>
#include <ored/marketdata/todaysmarket.hpp>
#include <ored/utilities/csvfilereader.hpp>
#include <ored/utilities/to_string.hpp>

using namespace std;
using namespace boost::unit_test_framework;
using namespace QuantLib;
using namespace QuantExt;
using namespace ore::data;

namespace bdata = boost::unit_test::data;

namespace {

// List of curve configuration file names for data test case below
vector<string> curveConfigFiles = {"curveconfig_linear.xml",    "curveconfig_linear_flat.xml",
                                   "curveconfig_loglinear.xml", "curveconfig_loglinear_flat.xml",
                                   "curveconfig_cubic.xml",     "curveconfig_cubic_flat.xml"};

// The expected commodity curve
map<Date, Real> expectedCurve = {{Date(29, Jul, 2019), 1417.8998900}, {Date(30, Jul, 2019), 1417.9999450},
                                 {Date(31, Jul, 2019), 1418.1000000}, {Date(1, Aug, 2019), 1418.2000550},
                                 {Date(30, Aug, 2019), 1421.1016535}, {Date(30, Sep, 2019), 1424.1312750}};

// Pillars for interpolated curve tests (purposely leave out elements below spot to test interpolation there)
map<Date, Real> expectedInterpCurvePillars = {{Date(31, Jul, 2019), 1418.1000000},
                                              {Date(1, Aug, 2019), 1418.2000550},
                                              {Date(30, Aug, 2019), 1421.1016535},
                                              {Date(30, Sep, 2019), 1424.1312750}};

// Expected results for extrapolation below spot, interpolation and extrapolation beyond max date for the
// various interpolation methods
vector<Date> offPillarDates = {Date(29, Jul, 2019), Date(15, Sep, 2019), Date(1, Nov, 2019)};

map<string, vector<Real>> expectedInterpCurveOffPillars = {
    {"curveconfig_linear.xml", {1417.89989, 1422.6653291129, 1427.2586262258}},
    {"curveconfig_linear_flat.xml", {1418.1, 1422.6653291129, 1424.131275}},
    {"curveconfig_loglinear.xml", {1417.89991117635, 1422.66452345277, 1427.26540106042}},
    {"curveconfig_loglinear_flat.xml", {1418.1, 1422.66452345277, 1424.131275}},
    {"curveconfig_cubic.xml", {1417.89988981896, 1422.67192914531, 1427.25983144911}},
    {"curveconfig_cubic_flat.xml", {1418.1, 1422.67192914531, 1424.131275}}};

boost::shared_ptr<CommodityCurve> createCurve(const string& inputDir,
                                              const string& curveConfigFile = "curveconfig.xml") {

    // As of date
    Date asof(29, Jul, 2019);

    Conventions conventions;
    string filename = inputDir + "/conventions.xml";
    conventions.fromFile(TEST_INPUT_FILE(filename));
    CurveConfigurations curveConfigs;
    filename = inputDir + "/" + curveConfigFile;
    curveConfigs.fromFile(TEST_INPUT_FILE(filename));
    filename = inputDir + "/market.txt";
    CSVLoader loader(TEST_INPUT_FILE(filename), TEST_INPUT_FILE("fixings.txt"), false);

    // Commodity curve spec
    CommodityCurveSpec curveSpec("USD", "PM:XAUUSD");

    // Check commodity curve construction works
    boost::shared_ptr<CommodityCurve> curve;
    BOOST_REQUIRE_NO_THROW(curve =
                               boost::make_shared<CommodityCurve>(asof, curveSpec, loader, curveConfigs, conventions));

    return curve;
}

boost::shared_ptr<TodaysMarket> createTodaysMarket(const Date& asof, const string& inputDir) {

    Conventions conventions;
    conventions.fromFile(TEST_INPUT_FILE(string(inputDir + "/conventions.xml")));

    CurveConfigurations curveConfigs;
    curveConfigs.fromFile(TEST_INPUT_FILE(string(inputDir + "/curveconfig.xml")));

    TodaysMarketParameters todaysMarketParameters;
    todaysMarketParameters.fromFile(TEST_INPUT_FILE(string(inputDir + "/todaysmarket.xml")));

    string fixingsFile = inputDir + "/fixings_" + to_string(io::iso_date(asof)) + ".txt";
    CSVLoader loader(TEST_INPUT_FILE(string(inputDir + "/market.txt")), TEST_INPUT_FILE(fixingsFile), false);

    return boost::make_shared<TodaysMarket>(asof, todaysMarketParameters, loader, curveConfigs, conventions);
}

void checkCurve(const boost::shared_ptr<PriceTermStructure>& priceCurve, const map<Date, Real>& expectedValues) {

    for (const auto& kv : expectedValues) {
        Real price = priceCurve->price(kv.first);
        BOOST_CHECK_CLOSE(price, kv.second, 1e-12);
    }
}

} // namespace

BOOST_FIXTURE_TEST_SUITE(OREDataTestSuite, ore::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(CommodityCurveTests)

BOOST_AUTO_TEST_CASE(testCommodityCurveTenorBasedOnTnPoints) {

    BOOST_TEST_MESSAGE("Testing commodity curve building with tenor based points quotes including ON and TN");

    boost::shared_ptr<CommodityCurve> curve = createCurve("tenor_based_on_tn_points");
    checkCurve(curve->commodityPriceCurve(), expectedCurve);
}

BOOST_AUTO_TEST_CASE(testCommodityCurveFixedDatePoints) {

    BOOST_TEST_MESSAGE("Testing commodity curve building with fixed date quotes");

    boost::shared_ptr<CommodityCurve> curve = createCurve("fixed_date_points");
    checkCurve(curve->commodityPriceCurve(), expectedCurve);
}

// Testing various interpolation methods
BOOST_DATA_TEST_CASE(testCommodityInterpolations, bdata::make(curveConfigFiles), curveConfigFile) {

    BOOST_TEST_MESSAGE("Testing with configuration file: " << curveConfigFile);

    boost::shared_ptr<CommodityCurve> curve = createCurve("different_interpolations", curveConfigFile);
    checkCurve(curve->commodityPriceCurve(), expectedInterpCurvePillars);

    BOOST_REQUIRE(expectedInterpCurveOffPillars.count(curveConfigFile) == 1);
    for (Size i = 0; i < offPillarDates.size(); i++) {
        Real price = curve->commodityPriceCurve()->price(offPillarDates[i]);
        Real expPrice = expectedInterpCurveOffPillars.at(curveConfigFile)[i];
        BOOST_CHECK_CLOSE(price, expPrice, 1e-12);
    }
}

// Basis test cases for data test below.
struct BasisTestCase {
    Date asof;
    string name;
    string curveName;
};

// List of basis test case directories for the data test case below.
vector<BasisTestCase> basisTestCases = {{Date(30, Sep, 2019), "wti_midland_cm", "NYMEX:FF"},
                                        {Date(30, Sep, 2019), "wti_midland_tm", "NYMEX:WTT"},
                                        {Date(30, Sep, 2019), "wti_midland_cm_base_ave", "NYMEX:FF"},
                                        {Date(30, Sep, 2019), "houston_ship_channel", "ICE:HXS"},
                                        {Date(23, Jan, 2020), "wti_midland_cm", "NYMEX:FF"},
                                        {Date(23, Jan, 2020), "wti_midland_tm", "NYMEX:WTT"},
                                        {Date(23, Jan, 2020), "wti_midland_cm_base_ave", "NYMEX:FF"},
                                        {Date(23, Jan, 2020), "houston_ship_channel", "ICE:HXS"}};

// Needed for BOOST_DATA_TEST_CASE below as it writes out the case.
ostream& operator<<(ostream& os, BasisTestCase testCase) {
    return os << "[" << io::iso_date(testCase.asof) << "," << testCase.name << "," << testCase.curveName << "]";
}

BOOST_DATA_TEST_CASE(testCommodityBasisCurve, bdata::make(basisTestCases), basisTestCase) {

    BOOST_TEST_MESSAGE("Testing commodity basis curve building " << basisTestCase << "...");

    Settings::instance().evaluationDate() = basisTestCase.asof;
    string dir = "basis/" + basisTestCase.name;

    boost::shared_ptr<TodaysMarket> tm;
    BOOST_REQUIRE_NO_THROW(tm = createTodaysMarket(basisTestCase.asof, dir));

    auto pts = tm->commodityPriceCurve(basisTestCase.curveName);

    for (const Date& d : pts->pillarDates()) {
        BOOST_TEST_MESSAGE(io::iso_date(d) << "," << fixed << setprecision(12) << pts->price(d));
    }

    // Tolerance for float comparison
    Real tol = 1e-12;

    // Read in the expected pillar results for the given date.
    vector<Date> expPillarDates;
    string filename = dir + "/expected_" + to_string(io::iso_date(basisTestCase.asof)) + ".csv";
    CSVFileReader reader(TEST_INPUT_FILE(filename), true, ",");
    BOOST_REQUIRE_EQUAL(reader.numberOfColumns(), 2);

    while (reader.next()) {
        // Get the expected expiry pillar date and price.
        Date expiry = parseDate(reader.get(0));
        Real price = parseReal(reader.get(1));
        expPillarDates.push_back(expiry);

        // Check the surface on the grid point.
        Real calcPrice = pts->price(expiry);
        BOOST_TEST_MESSAGE(io::iso_date(expiry) << "," << fixed << setprecision(12) << calcPrice);
        BOOST_CHECK_SMALL(price - calcPrice, tol);
    }

    vector<Date> calcPillarDates = pts->pillarDates();
    BOOST_CHECK_EQUAL_COLLECTIONS(expPillarDates.begin(), expPillarDates.end(), calcPillarDates.begin(),
                                  calcPillarDates.end());

    // Set up has flat extrapolation. Check it here.
    Real lastPrice = pts->price(calcPillarDates.back());
    Date extrapDate = calcPillarDates.back() + 1 * Years;
    Real extrapPrice = pts->price(extrapDate);
    BOOST_CHECK_SMALL(lastPrice - extrapPrice, tol);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: nvolfango/Engine

max_issues_repo_name: zhangjiayin/Engine

max_forks_repo_name: zhangjiayin/Engine


text:
#include "ingester.h"
#include <iostream>
#include <csignal>
#include <boost/program_options.hpp>
#include <glog/logging.h>

using namespace std;
namespace po = boost::program_options;

bool terminated = false;

void signal_handler(int) {
    LOG(INFO) << "SIGINT/SIGTERM received. Gracefully stopping..." << endl;
    terminated = true;
}

int main(int argc, char **argv) {
    google::InitGoogleLogging("river");

    string redis_hostname;
    int redis_port;
    string redis_password;
    string redis_password_file;
    string output_directory;
    string stream_name;
    int samples_per_row_group;
    int minimum_age_seconds_before_deletion;

  po::options_description desc("Allowed options");
    desc.add_options()
            ("help", "produce help message")
            ("redis_hostname,h", po::value<string>(&redis_hostname)->required(), "Redis hostname [required]")
            ("redis_port,p", po::value<int>(&redis_port)->default_value(6379), "Redis port [optional]")
            ("redis_password,w", po::value<string>(&redis_password), "Redis password [optional]")
            ("redis_password_file,f", po::value<string>(&redis_password_file), "Redis password file [optional]")
            ("output_directory,o", po::value<string>(&output_directory)->required(),
             "Output directory for all files [required]")
            ("stream_name", po::value<string>(&stream_name),
             "Single stream to process directly [optional]")
            ("samples_per_row_group", po::value<int>(&samples_per_row_group)->default_value(128 * 1024),
             "Number of samples to read at a time before persisting to disk [optional]")
            ("minimum_seconds_age_before_deletion,m", po::value<int>(&minimum_age_seconds_before_deletion)->default_value(60),
             "Minimum age of a sample, in seconds, before it can be considered for deletion [optional]");

  po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);

    if (vm.count("help")) {
        cerr << desc << endl;
        return 1;
    }

    try {
        po::notify(vm);
    } catch (boost::program_options::required_option &e) {
        cerr << e.what() << endl;
        cerr << desc << endl;
        return 1;
    }

    if (!redis_password_file.empty() && redis_password.empty()) {
        ifstream infile;
        infile.open(redis_password_file);
        infile >> redis_password;
    }

    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    river::RedisConnection rc(redis_hostname, redis_port, redis_password);
    {
        river::StreamIngester ingester(
            rc,
            output_directory,
            &terminated,
            stream_name,
            samples_per_row_group,
            minimum_age_seconds_before_deletion);
        LOG(INFO) << "Beginning ingestion forever." << endl;
        while (!terminated) {
            ingester.Ingest();
            this_thread::sleep_for(chrono::seconds(10));
        }
    }
    LOG(INFO) << "Ingestion terminated." << endl;
    return 0;
}

max_stars_repo_name: mjsML/river

max_issues_repo_name: mjsML/river

max_forks_repo_name: mjsML/river