text:
#include "places.h"
#include "xmlrpc_helpers.h"

#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point_xy.hpp>
#include <boost/geometry/geometries/polygon.hpp>

Places::Places(ros::NodeHandle & nh, ros::NodeHandle & nh_priv,
    const std::string & param_name) {

    xh::Array output;
    xh::fetchParam(nh_priv, param_name, output);
    xh::Struct output_i;

    for (int i = 0; i < output.size(); ++i)
    {
        XmlRpc::XmlRpcValue name_list;
        XmlRpc::XmlRpcValue pos_list;
        std::vector<geometry_msgs::Point> pos;

        xh::getArrayItem(output, i, output_i);
        xh::getStructMember(output_i, "boundary", pos_list);
        xh::getStructMember(output_i, "name", name_list);

        for(int j=0; j < pos_list.size(); ++j)
        {
            geometry_msgs::Point pt;

            pt.x = pos_list[j][0];
            pt.y = pos_list[j][1];

            pos.push_back(pt);
        }

        boundary_.push_back(pos);
        places_.push_back(name_list);
    }
}

std::vector<std::string> Places::getPlaces()
{
    return places_;
}

std::vector<std::vector<geometry_msgs::Point> > Places::getBoundary()
{
    return boundary_;
}

std::string Places::where_am_i(geometry_msgs::Point pt)
{
    typedef boost::geometry::model::d2::point_xy<double> point_type;
    typedef boost::geometry::model::polygon<point_type> polygon_type;

    for(int i = 0; i < boundary_.size() ; i++)
    {
        std::string polygon = "POLYGON((";

        for(int j=0; j < boundary_[i].size(); j++)
        {
            polygon.append(std::to_string(boundary_[i][j].y));
            polygon.append(" ");
            polygon.append(std::to_string(boundary_[i][j].x));
            polygon.append(",");
        }

        polygon.append(std::to_string(boundary_[i][0].y));
        polygon.append(" ");
        polygon.append(std::to_string(boundary_[i][0].x));
        polygon.append("))");

        polygon_type poly;
        boost::geometry::read_wkt(polygon, poly);

        point_type p(pt.y, pt.x);

        if(boost::geometry::within(p, poly))
            return places_[i];
    }
    return "";
}

ext: cpp


text:
#define BOOST_TEST_DYN_LINK
#include <canard/net/ofp/v13/table_feature_property/id/oxm_id.hpp>
#include <boost/test/unit_test.hpp>

#include <boost/range/algorithm_ext/push_back.hpp>
#include <canard/net/ofp/v13/common/oxm_match_field.hpp>
#include <canard/net/ofp/v13/io/openflow.hpp>
#include "../../test_utility.hpp"

namespace ofp = canard::net::ofp;
namespace v13 = ofp::v13;
namespace protocol = v13::protocol;
namespace header_ops = v13::oxm_header_ops;

namespace {
  struct oxm_id_fixture
  {
    v13::oxm_id sut{protocol::OFPXMC_OPENFLOW_BASIC, 27, true, 32};
    std::vector<unsigned char> bin = "\x80\x00\x37\x20"_bin;
  };
  struct experimenter_oxm_id_fixture
  {
    v13::oxm_id sut{0x32, true, 16, 0x12345678};
    std::vector<unsigned char> bin = "\xff\xff\x65\x10\x12\x34\x56\x78"_bin;
  };
}

BOOST_AUTO_TEST_SUITE(table_feature_property_test)
BOOST_AUTO_TEST_SUITE(oxm_id)

  BOOST_AUTO_TEST_SUITE(constructor)
    BOOST_AUTO_TEST_CASE(constructible_from_oxm_header)
    {
      auto const oxm_header
        = v13::oxm_match_fields::ipv4_src::make_wild_header();

      v13::oxm_id const sut{oxm_header};

      BOOST_TEST(sut.oxm_header() == oxm_header);
      BOOST_TEST(sut.oxm_class() == header_ops::oxm_class(oxm_header));
      BOOST_TEST(sut.oxm_field() == header_ops::oxm_field(oxm_header));
      BOOST_TEST(sut.oxm_type() == header_ops::oxm_type(oxm_header));
      BOOST_TEST(sut.oxm_hasmask() == header_ops::oxm_hasmask(oxm_header));
      BOOST_TEST(sut.oxm_length() == header_ops::oxm_length(oxm_header));
      BOOST_TEST(!sut.is_experimenter());
      BOOST_TEST(sut.length() == sizeof(std::uint32_t));
    }
    BOOST_AUTO_TEST_CASE(constructible_from_experimenter_id_and_data)
    {
      auto const oxm_field = std::uint8_t{0x12};
      auto const oxm_hasmask = true;
      auto const oxm_length = std::uint8_t{8};
      auto const exp_id = std::uint32_t{0x12345678};

      v13::oxm_id const sut{oxm_field, oxm_hasmask, oxm_length, exp_id};

      BOOST_TEST(sut.oxm_header() == header_ops::oxm_header(
            protocol::OFPXMC_EXPERIMENTER, oxm_field, oxm_hasmask, oxm_length));
      BOOST_TEST(sut.oxm_class() == protocol::OFPXMC_EXPERIMENTER);
      BOOST_TEST(sut.oxm_field() == oxm_field);
      BOOST_TEST(sut.oxm_hasmask() == oxm_hasmask);
      BOOST_TEST(sut.oxm_length() == oxm_length);
      BOOST_TEST(sut.is_experimenter());
      BOOST_TEST(sut.experimenter_id() == exp_id);
      BOOST_TEST(sut.length() == sizeof(protocol::ofp_oxm_experimenter_header));
    }
    BOOST_FIXTURE_TEST_CASE(
        copy_constructible_from_non_const_oxm_id, oxm_id_fixture)
    {
      auto copy = sut;

      BOOST_TEST((copy == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
        copy_constructible_from_const_oxm_id, oxm_id_fixture)
    {
      auto const& const_id = sut;

      auto copy = const_id;

      BOOST_TEST((copy == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
        move_constructible_from_oxm_id, oxm_id_fixture)
    {
      auto moved = sut;

      auto copy = std::move(moved);

      BOOST_TEST((copy == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
          copy_constructible_from_non_const_experimenter_oxm_id
        , experimenter_oxm_id_fixture)
    {
      auto copy = sut;

      BOOST_TEST((copy == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
          copy_constructible_from_const_experimenter_oxm_id
        , experimenter_oxm_id_fixture)
    {
      auto const& const_id = sut;

      auto copy = const_id;

      BOOST_TEST((copy == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
          move_constructible_from_experimenter_oxm_id
        , experimenter_oxm_id_fixture)
    {
      auto moved = sut;

      auto copy = std::move(moved);

      BOOST_TEST((copy == sut));
    }
  BOOST_AUTO_TEST_SUITE_END() // constructor

  BOOST_AUTO_TEST_SUITE(equality)
    BOOST_AUTO_TEST_CASE(true_if_same_oxm_id_object)
    {
      auto const sut
        = v13::oxm_id{v13::oxm_match_fields::vlan_vid::make_header()};

      BOOST_TEST((sut == sut));
    }
    BOOST_AUTO_TEST_CASE(true_if_oxm_header_is_equal)
    {
      auto const oxm_header
        = v13::oxm_match_fields::in_port::make_header();

      BOOST_TEST((v13::oxm_id{oxm_header} == v13::oxm_id{oxm_header}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_class_is_not_equal)
    {
      auto const oxm_field = protocol::ofb_match_fields::in_port;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};

      BOOST_TEST(
          (v13::oxm_id{
           protocol::OFPXMC_NXM_0, oxm_field, oxm_hasmask, oxm_length}
        != v13::oxm_id{
           protocol::OFPXMC_NXM_1, oxm_field, oxm_hasmask, oxm_length}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_field_is_not_equal)
    {
      auto const oxm_class = protocol::OFPXMC_OPENFLOW_BASIC;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};
      using protocol::ofb_match_fields;

      BOOST_TEST(
          (v13::oxm_id{
           oxm_class, ofb_match_fields::eth_src, oxm_hasmask, oxm_length}
        != v13::oxm_id{
           oxm_class, ofb_match_fields::eth_dst, oxm_hasmask, oxm_length}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_hasmask_is_not_equal)
    {
      auto const oxm_class = protocol::OFPXMC_OPENFLOW_BASIC;
      auto const oxm_field = protocol::ofb_match_fields::in_port;
      auto const oxm_length = std::uint8_t{4};

      BOOST_TEST(
          (v13::oxm_id{oxm_class, oxm_field, true, oxm_length}
        != v13::oxm_id{oxm_class, oxm_field, false, oxm_length}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_length_is_not_equal)
    {
      auto const oxm_class = protocol::OFPXMC_OPENFLOW_BASIC;
      auto const oxm_field = protocol::ofb_match_fields::in_port;
      auto const oxm_hasmask = false;

      BOOST_TEST(
          (v13::oxm_id{oxm_class, oxm_field, oxm_hasmask, 2}
        != v13::oxm_id{oxm_class, oxm_field, oxm_hasmask, 3}));
    }
    BOOST_AUTO_TEST_CASE(true_if_same_experimenter_oxm_id_object)
    {
      auto const sut = v13::oxm_id{1, false, 4, 0x12345678};

      BOOST_TEST((sut == sut));
    }
    BOOST_AUTO_TEST_CASE(true_if_oxm_header_and_experimenter_id_are_equal)
    {
      auto const oxm_field = 12;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          (v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, exp_id}
        == v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_field_is_not_equal_for_experimenter)
    {
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          (v13::oxm_id{1, oxm_hasmask, oxm_length, exp_id}
        != v13::oxm_id{2, oxm_hasmask, oxm_length, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_hasmask_is_not_equal_for_experimenter)
    {
      auto const oxm_field = 12;
      auto const oxm_length = std::uint8_t{4};
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          (v13::oxm_id{oxm_field, true, oxm_length, exp_id}
        != v13::oxm_id{oxm_field, false, oxm_length, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_length_is_not_equal_for_experimenter)
    {
      auto const oxm_field = 12;
      auto const oxm_hasmask = false;
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          (v13::oxm_id{oxm_field, oxm_hasmask, 1, exp_id}
        != v13::oxm_id{oxm_field, oxm_hasmask, 2, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_experimenter_id_is_not_equal)
    {
      auto const oxm_field = 12;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};

      BOOST_TEST(
          (v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, 1}
        != v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, 2}));
    }
    BOOST_AUTO_TEST_CASE(false_if_one_is_experimenter_and_another_is_not)
    {
      BOOST_TEST(
          (v13::oxm_id{protocol::OFPXMC_OPENFLOW_BASIC, 1, false, 1}
        != v13::oxm_id{1, false, 1, std::uint32_t{0}}));
    }
    BOOST_AUTO_TEST_CASE(false_if_one_is_not_experimenter_and_another_is_that)
    {
      BOOST_TEST(
          (v13::oxm_id{1, false, 1, std::uint32_t{0}}
        != v13::oxm_id{protocol::OFPXMC_OPENFLOW_BASIC, 1, false, 1}));
    }
  BOOST_AUTO_TEST_SUITE_END() // equality

  BOOST_AUTO_TEST_SUITE(equivalent_func)
    BOOST_AUTO_TEST_CASE(true_if_same_oxm_id_object)
    {
      auto const sut
        = v13::oxm_id{v13::oxm_match_fields::vlan_vid::make_header()};

      BOOST_TEST(equivalent(sut, sut));
    }
    BOOST_AUTO_TEST_CASE(true_if_oxm_header_is_equal)
    {
      auto const oxm_header
        = v13::oxm_match_fields::in_port::make_header();

      BOOST_TEST(equivalent(v13::oxm_id{oxm_header}, v13::oxm_id{oxm_header}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_class_is_not_equal)
    {
      auto const oxm_field = protocol::ofb_match_fields::in_port;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{
                protocol::OFPXMC_NXM_0, oxm_field, oxm_hasmask, oxm_length}
            , v13::oxm_id{
                protocol::OFPXMC_NXM_1, oxm_field, oxm_hasmask, oxm_length}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_field_is_not_equal)
    {
      auto const oxm_class = protocol::OFPXMC_OPENFLOW_BASIC;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};
      using protocol::ofb_match_fields;

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{
                oxm_class, ofb_match_fields::eth_src, oxm_hasmask, oxm_length}
            , v13::oxm_id{
                oxm_class, ofb_match_fields::eth_dst, oxm_hasmask, oxm_length}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_hasmask_is_not_equal)
    {
      auto const oxm_class = protocol::OFPXMC_OPENFLOW_BASIC;
      auto const oxm_field = protocol::ofb_match_fields::in_port;
      auto const oxm_length = std::uint8_t{4};

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{oxm_class, oxm_field, true, oxm_length}
            , v13::oxm_id{oxm_class, oxm_field, false, oxm_length}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_length_is_not_equal)
    {
      auto const oxm_class = protocol::OFPXMC_OPENFLOW_BASIC;
      auto const oxm_field = protocol::ofb_match_fields::in_port;
      auto const oxm_hasmask = false;

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{oxm_class, oxm_field, oxm_hasmask, 2}
            , v13::oxm_id{oxm_class, oxm_field, oxm_hasmask, 3}));
    }
    BOOST_AUTO_TEST_CASE(true_if_same_experimenter_oxm_id_object)
    {
      auto const sut = v13::oxm_id{1, false, 4, 0x12345678};

      BOOST_TEST(equivalent(sut, sut));
    }
    BOOST_AUTO_TEST_CASE(true_if_oxm_header_and_experimenter_id_are_equal)
    {
      auto const oxm_field = 12;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          equivalent(
              v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, exp_id}
            , v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_experimenter_id_is_not_equal)
    {
      auto const oxm_field = 12;
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, 1}
            , v13::oxm_id{oxm_field, oxm_hasmask, oxm_length, 2}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_field_is_not_equal_for_experimenter)
    {
      auto const oxm_hasmask = false;
      auto const oxm_length = std::uint8_t{4};
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{1, oxm_hasmask, oxm_length, exp_id}
            , v13::oxm_id{2, oxm_hasmask, oxm_length, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_hasmask_is_not_equal_for_experimenter)
    {
      auto const oxm_field = 12;
      auto const oxm_length = std::uint8_t{4};
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{oxm_field, true, oxm_length, exp_id}
            , v13::oxm_id{oxm_field, false, oxm_length, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_oxm_length_is_not_equal_for_experimenter)
    {
      auto const oxm_field = 12;
      auto const oxm_hasmask = false;
      auto const exp_id = std::uint32_t{0x12345678};

      BOOST_TEST(
          !equivalent(
              v13::oxm_id{oxm_field, oxm_hasmask, 1, exp_id}
            , v13::oxm_id{oxm_field, oxm_hasmask, 2, exp_id}));
    }
    BOOST_AUTO_TEST_CASE(false_if_one_is_experimenter_and_another_is_not)
    {
      BOOST_TEST(
          !equivalent(
              v13::oxm_id{protocol::OFPXMC_OPENFLOW_BASIC, 1, false, 1}
            , v13::oxm_id{1, false, 1, std::uint32_t{0}}));
    }
    BOOST_AUTO_TEST_CASE(false_if_one_is_not_experimenter_and_another_is_that)
    {
      BOOST_TEST(
          !equivalent(
              v13::oxm_id{1, false, 1, std::uint32_t{0}}
            , v13::oxm_id{protocol::OFPXMC_OPENFLOW_BASIC, 1, false, 1}));
    }
  BOOST_AUTO_TEST_SUITE_END() // equivalent_func

  BOOST_AUTO_TEST_SUITE(encode)
    BOOST_FIXTURE_TEST_CASE(
          generate_binary_from_non_experimenter_oxm_id
        , oxm_id_fixture)
    {
      auto buf = std::vector<unsigned char>{};

      sut.encode(buf);

      BOOST_TEST(buf.size() == sut.byte_length());
      BOOST_TEST(buf == bin, boost::test_tools::per_element{});
    }
    BOOST_FIXTURE_TEST_CASE(
          generate_binary_from_experimenter_oxm_id
        , experimenter_oxm_id_fixture)
    {
      auto buf = std::vector<unsigned char>{};

      sut.encode(buf);

      BOOST_TEST(buf.size() == sut.byte_length());
      BOOST_TEST(buf == bin, boost::test_tools::per_element{});
    }
  BOOST_AUTO_TEST_SUITE_END() // encode

  BOOST_AUTO_TEST_SUITE(decode)
    BOOST_FIXTURE_TEST_CASE(
          construct_non_experimenter_oxm_id_from_binary
        , oxm_id_fixture)
    {
      auto it = bin.begin();

      auto const oxm_id = v13::oxm_id::decode(it, bin.end());

      BOOST_TEST((it == bin.end()));
      BOOST_TEST((oxm_id == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
          construct_non_experimenter_oxm_id_from_too_long_binary
        , oxm_id_fixture)
    {
      bin.resize(bin.size() + 1);
      auto it = bin.begin();

      auto const oxm_id = v13::oxm_id::decode(it, bin.end());

      BOOST_TEST((it == std::next(bin.begin(), sizeof(std::uint32_t))));
      BOOST_TEST((oxm_id == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
          construct_experimenter_oxm_id_from_binary
        , experimenter_oxm_id_fixture)
    {
      auto it = bin.begin();

      auto const oxm_id = v13::oxm_id::decode(it, bin.end());

      BOOST_TEST((it == bin.end()));
      BOOST_TEST((oxm_id == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
          construct_experimenter_oxm_id_from_too_long_binary
        , experimenter_oxm_id_fixture)
    {
      bin.resize(bin.size() + 1);
      auto it = bin.begin();

      auto const oxm_id = v13::oxm_id::decode(it, bin.end());

      BOOST_TEST((it == std::next(
              bin.begin(), sizeof(protocol::ofp_oxm_experimenter_header))));
      BOOST_TEST((oxm_id == sut));
    }
    BOOST_FIXTURE_TEST_CASE(
          throw_exception_if_oxm_id_is_experimenter_and_binary_len_is_too_small
        , experimenter_oxm_id_fixture)
    {
      bin.resize(bin.size() - 1);
      auto it = bin.begin();

      BOOST_CHECK_EXCEPTION(
            v13::oxm_id::decode(it, bin.end())
          , v13::exception
          , [](v13::exception const& e) {
              return e.error_type() == protocol::error_type::bad_request
                  && e.error_code() == protocol::bad_request_code::bad_len;
            });
      BOOST_TEST(std::distance(bin.begin(), it) == sizeof(std::uint32_t));
    }
  BOOST_AUTO_TEST_SUITE_END() // encode

BOOST_AUTO_TEST_SUITE_END() // oxm_id
BOOST_AUTO_TEST_SUITE_END() // table_feature_property_test


text:
#include "DictionaryPersistentStorage.h"

#include "gtest/gtest.h"

#include "serialization/DictionarySerializerMock.h"
#include "utils/FileAccessMock.h"
#include <boost/optional/optional_io.hpp>

#include "utils/GetProjectPath.h"

using namespace ::testing;
using namespace glossary::dictionaryService;
using namespace repository;

namespace
{
const std::string filePath{utils::getProjectPath("glossary") + "repositoryFiles/dictionaries.txt"};
const std::string newDictionaryWordTranslation{"newDictionaryWordTranslation"};
const DictionaryName dictionaryName1{"dictionaryName1"};
const DictionaryName dictionaryName2{"dictionaryName2"};
const DictionaryName dictionaryName3{"dictionaryName3"};
const DictionaryName nonExistingDictionaryName{"nonExistingDict"};
const DictionaryWord dictionaryWord1{"englishWord1", std::string{"translation1"}};
const DictionaryWord dictionaryWord1AfterChange{"englishWord1", newDictionaryWordTranslation};
const DictionaryWord dictionaryWord2{"englishWord2", std::string{"translation2"}};
const DictionaryWord dictionaryWord3{"englishWord3", boost::none};
const DictionaryWord dictionaryWord4{"englishWord4", boost::none};
const DictionaryWords dictionaryWords1{dictionaryWord1, dictionaryWord2, dictionaryWord3};
const DictionaryWords dictionaryWords1AfterAddition{dictionaryWord1, dictionaryWord2, dictionaryWord3,
                                                    dictionaryWord4};
const DictionaryWords dictionaryWords1AfterTranslationChange{dictionaryWord1AfterChange, dictionaryWord2,
                                                             dictionaryWord3};
const DictionaryWords dictionaryWords1AfterRemoval{dictionaryWord2, dictionaryWord3};
const DictionaryWords dictionaryWords2{dictionaryWord1, dictionaryWord2};
const Dictionary dictionary1{dictionaryName1, dictionaryWords1};
const Dictionary dictionary1AfterAddition{dictionaryName1, dictionaryWords1AfterAddition};
const Dictionary dictionary1AfterRemoval{dictionaryName1, dictionaryWords1AfterRemoval};
const Dictionary dictionary1AfterTranslationChange{dictionaryName1, dictionaryWords1AfterTranslationChange};
const Dictionary dictionary2{dictionaryName2, dictionaryWords2};
const Dictionary emptyDictionary1{dictionaryName1, {}};
const Dictionary emptyDictionary2{dictionaryName2, {}};
const Dictionaries twoDictionaries{dictionary1, dictionary2};
const Dictionaries twoDictionariesAfterAddition{dictionary1AfterAddition, dictionary2};
const Dictionaries twoDictionariesAfterTranslationChange{dictionary1AfterTranslationChange, dictionary2};
const Dictionaries twoDictionariesAfterRemoval{dictionary1AfterRemoval, dictionary2};
const Dictionaries dictionariesAfterRemoval{dictionary2};
const Dictionaries dictionariesWithOneDictionary{dictionary1};
const Dictionaries dictionariesWithOneEmptyDictionary{emptyDictionary1};
const Dictionaries emptyDictionaries{emptyDictionary1, emptyDictionary2};
const Dictionaries noDictionaries{};
}

class DictionaryPersistentStorageTest : public Test
{
public:
    void expectNoDictionariesLoad()
    {
        EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(true));
        EXPECT_CALL(*fileAccess, readContent(filePath)).WillOnce(Return("some content"));
        EXPECT_CALL(*serializer, deserialize("some content")).WillOnce(Return(noDictionaries));
    }

    void expectTwoDictionariesLoad()
    {
        EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(true));
        EXPECT_CALL(*fileAccess, readContent(filePath)).WillOnce(Return("some content"));
        EXPECT_CALL(*serializer, deserialize("some content")).WillOnce(Return(twoDictionaries));
    }

    void expectSerializeDictionaries(const Dictionaries& dictionaries)
    {
        EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(true));
        EXPECT_CALL(*serializer, serialize(dictionaries)).WillOnce(Return("dictionaries"));
        EXPECT_CALL(*fileAccess, write(filePath, "dictionaries"));
    }

    std::shared_ptr<utils::FileAccessMock> fileAccess = std::make_shared<StrictMock<utils::FileAccessMock>>();
    std::shared_ptr<serialization::DictionarySerializerMock> serializer =
        std::make_shared<StrictMock<serialization::DictionarySerializerMock>>();
};

TEST_F(DictionaryPersistentStorageTest, givenPersistentStorageWithEmptyFile_shouldBeEmpty)
{
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(true));
    EXPECT_CALL(*fileAccess, readContent(filePath)).WillOnce(Return(""));
    EXPECT_CALL(*serializer, deserialize("")).WillOnce(Return(Dictionaries{}));
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    ASSERT_TRUE(persistentStorage.empty());
}

TEST_F(DictionaryPersistentStorageTest, givenPersistentStorageWithFileWithDictionaries_shouldLoadDictionaries)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    const auto actualDictionaries = persistentStorage.getDictionaries();

    ASSERT_EQ(actualDictionaries, twoDictionaries);
}

TEST_F(DictionaryPersistentStorageTest, givenInvalidFile_shouldReturnNoDictionaries)
{
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    const auto actualDictionaries = persistentStorage.getDictionaries();

    EXPECT_TRUE(actualDictionaries.empty());
}

TEST_F(DictionaryPersistentStorageTest, givenDictionaryAdditionByName_shouldAddEmptyDictionaryAndSerialize)
{
    expectNoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(dictionariesWithOneEmptyDictionary);

    persistentStorage.addDictionary(dictionaryName1);

    ASSERT_EQ(*persistentStorage.getDictionary(dictionaryName1), emptyDictionary1);
}

TEST_F(DictionaryPersistentStorageTest, givenDictionaryAddition_shouldAddDictionaryAndSerialize)
{
    expectNoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(dictionariesWithOneDictionary);

    persistentStorage.addDictionary(dictionary1);

    ASSERT_EQ(*persistentStorage.getDictionary(dictionaryName1), dictionary1);
}

TEST_F(DictionaryPersistentStorageTest,
       givenDictionaryAdditionByNameAndNonExistingFile_shouldAddEmptyDictionaryAndNotSerialize)
{
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));

    persistentStorage.addDictionary(dictionaryName1);

    ASSERT_EQ(*persistentStorage.getDictionary(dictionaryName1), emptyDictionary1);
}

TEST_F(DictionaryPersistentStorageTest,
       givenDictionaryAdditionAndNonExistingFile_shouldAddDictionaryAndNotSerialize)
{
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));

    persistentStorage.addDictionary(dictionary1);

    ASSERT_EQ(*persistentStorage.getDictionary(dictionaryName1), dictionary1);
}

TEST_F(DictionaryPersistentStorageTest, givenExistingDictionaryName_shouldReturnThisDictionary)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);

    ASSERT_EQ(*actualDictionary, dictionary1);
}

TEST_F(DictionaryPersistentStorageTest, givenNonExistingDictionary_shouldNotAddWordToDictionary)
{
    expectNoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(noDictionaries);

    persistentStorage.addWordToDictionary(dictionaryWord1, dictionaryName1);

    ASSERT_EQ(persistentStorage.getDictionary(dictionaryName1), boost::none);
}

TEST_F(DictionaryPersistentStorageTest,
       givenExistingWordInDictionary_shouldNotAddWordToDictionaryAndSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(twoDictionaries);

    persistentStorage.addWordToDictionary(dictionaryWord1, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1);
}

TEST_F(DictionaryPersistentStorageTest, givenExistingDictionary_shouldAddWordToDictionaryAndSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(twoDictionariesAfterAddition);

    persistentStorage.addWordToDictionary(dictionaryWord4, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1AfterAddition);
}

TEST_F(DictionaryPersistentStorageTest,
       givenExistingDictionaryAndNotExistingFile_shouldAddWordToDictionaryAndNotSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));

    persistentStorage.addWordToDictionary(dictionaryWord4, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1AfterAddition);
}

TEST_F(DictionaryPersistentStorageTest, givenNonExistingDictionary_shouldNotRemoveDictionaryAndSerialize)
{
    expectNoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(noDictionaries);

    persistentStorage.removeDictionary(dictionaryName1);
}

TEST_F(DictionaryPersistentStorageTest, givenExistingDictionary_shouldRemoveDictionaryAndSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(dictionariesAfterRemoval);

    persistentStorage.removeDictionary(dictionaryName1);

    ASSERT_EQ(persistentStorage.getDictionaries(), dictionariesAfterRemoval);
}

TEST_F(DictionaryPersistentStorageTest,
       givenExistingDictionaryAndNonExistingFile_shouldRemoveDictionaryAndNotSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));

    persistentStorage.removeDictionary(dictionaryName2);

    ASSERT_EQ(persistentStorage.getDictionaries(), dictionariesWithOneDictionary);
}

TEST_F(DictionaryPersistentStorageTest,
       givenNonExistingDictionary_shouldNotRemoveWordFromDictionaryAndSerialize)
{
    expectNoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(noDictionaries);

    persistentStorage.removeWordFromDictionary(dictionaryWord1.englishWord, dictionaryName1);

    ASSERT_EQ(persistentStorage.getDictionary(dictionaryName1), boost::none);
}

TEST_F(DictionaryPersistentStorageTest,
       givenNonExistingWordInDictionary_shouldNotRemoveWordFromDictionaryAndSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(twoDictionaries);

    persistentStorage.removeWordFromDictionary(dictionaryWord4.englishWord, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1);
}

TEST_F(DictionaryPersistentStorageTest,
       givenExistingWordInDictionary_shouldRemoveWordFromDictionaryAndSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(twoDictionariesAfterRemoval);

    persistentStorage.removeWordFromDictionary(dictionaryWord1.englishWord, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1AfterRemoval);
}

TEST_F(DictionaryPersistentStorageTest,
       givenExistingWordInDictionaryAndNotExistingFile_shouldRemoveWordFromDictionaryAndNotSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));

    persistentStorage.removeWordFromDictionary(dictionaryWord1.englishWord, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1AfterRemoval);
}

TEST_F(DictionaryPersistentStorageTest, givenNonExistingDictionary_shouldNotChangeWordTranslationAndSerialize)
{
    expectNoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(noDictionaries);

    persistentStorage.changeWordTranslationFromDictionary(dictionaryWord1.englishWord,
                                                          newDictionaryWordTranslation, dictionaryName1);

    ASSERT_EQ(persistentStorage.getDictionary(dictionaryName1), boost::none);
}

TEST_F(DictionaryPersistentStorageTest,
       givenExistingDictionaryAndExistingWord_shouldChangeWordTranslationInDictionaryAndSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    expectSerializeDictionaries(twoDictionariesAfterTranslationChange);

    persistentStorage.changeWordTranslationFromDictionary(dictionaryWord1.englishWord,
                                                          newDictionaryWordTranslation, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1AfterTranslationChange);
}

TEST_F(DictionaryPersistentStorageTest,
       givenExistingDictionaryAndNotExistingFile_shouldChangeWordTranslationInDictionaryAndNotSerialize)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};
    EXPECT_CALL(*fileAccess, exists(filePath)).WillOnce(Return(false));

    persistentStorage.changeWordTranslationFromDictionary(dictionaryWord1.englishWord,
                                                          newDictionaryWordTranslation, dictionaryName1);

    const auto actualDictionary = persistentStorage.getDictionary(dictionaryName1);
    ASSERT_EQ(actualDictionary->words, dictionaryWords1AfterTranslationChange);
}

TEST_F(DictionaryPersistentStorageTest, givenNonExistingDictionaryName_shouldReturnNone)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    const auto actualDictionary = persistentStorage.getDictionary(nonExistingDictionaryName);

    ASSERT_EQ(actualDictionary, boost::none);
}

TEST_F(DictionaryPersistentStorageTest, givenNoDictionaries_shouldNotContainAnyDictionaries)
{
    expectNoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    ASSERT_FALSE(persistentStorage.containsDictionary(dictionaryName1));
    ASSERT_FALSE(persistentStorage.containsDictionary(dictionaryName2));
    ASSERT_FALSE(persistentStorage.containsDictionary(dictionaryName3));
    ASSERT_FALSE(persistentStorage.containsDictionary(nonExistingDictionaryName));
}

TEST_F(DictionaryPersistentStorageTest, givenTwoDictionaries_shouldContainTheseTwoDictionaries)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    ASSERT_TRUE(persistentStorage.containsDictionary(dictionaryName1));
    ASSERT_TRUE(persistentStorage.containsDictionary(dictionaryName2));
}

TEST_F(DictionaryPersistentStorageTest, givenTwoDictionaries_shouldReturnSizeTwo)
{
    expectTwoDictionariesLoad();
    DictionaryPersistentStorage persistentStorage{fileAccess, serializer};

    ASSERT_EQ(persistentStorage.size(), 2);
}

max_stars_repo_name: michalovsky/Glossary

max_issues_repo_name: michalovsky/Glossary

max_forks_repo_name: michalovsky/Glossary


text:
#include <iostream>

#include <mmt/sentence.h>
#include <sapt/PhraseTable.h>
#include <suffixarray/UpdateBatch.h>
#include <suffixarray/SuffixArray.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <fstream>

using namespace std;
using namespace mmt;
using namespace mmt::sapt;

namespace {
    const size_t ERROR_IN_COMMAND_LINE = 1;
    const size_t GENERIC_ERROR = 2;
    const size_t SUCCESS = 0;

    struct args_t {
        string model_path;
        string dump_file = "/dev/stdout";
    };
} // namespace

namespace po = boost::program_options;
namespace fs = boost::filesystem;

bool ParseArgs(int argc, const char *argv[], args_t *args) {
    po::options_description desc("dump the content of the SuffixArray Phrase Table");
    desc.add_options()
            ("help,h", "print this help message")
            ("model,m", po::value<string>()->required(), "model path")
            ("dump,d", po::value<string>(), "output file where dump the content of the database (default is /dev/stdout)");

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

        if (vm.count("help")) {
            cout << desc << endl;
            return false;
        }

        po::notify(vm);

        args->model_path = vm["model"].as<string>();

        if (vm.count("dump"))
            args->dump_file = vm["dump"].as<string>();

    } catch (po::error &e) {
        cerr << "ERROR: " << e.what() << endl << endl;
        cerr << desc << endl;
        return false;
    }

    return true;
}

int main(int argc, const char *argv[]) {
    args_t args;

    if (!ParseArgs(argc, argv, &args))
        return ERROR_IN_COMMAND_LINE;

    Options options;
    SuffixArray index(args.model_path, options.prefix_length, options.gc_timeout, options.gc_buffer_size);
    cerr << "Model loaded" << endl;

    CorporaStorage *storage = index.GetStorage();

    unordered_set<domain_t> domains;
    storage->GetManifest()->GetDomains(&domains);

    for (auto domain = domains.begin(); domain != domains.end(); ++domain) {
        StorageIterator *it = storage->NewIterator(*domain);

        ofstream output(args.dump_file.c_str());

        vector<wid_t> sourceSentence;
        vector<wid_t> targetSentence;
        alignment_t alignment;

        while (it->Next(&sourceSentence, &targetSentence, &alignment, nullptr)) {
            output << *domain << ": ";
            for (auto w = sourceSentence.begin(); w!=sourceSentence.end(); ++w) { output << *w << " ";}
            output << "||| ";
            for (auto w = targetSentence.begin(); w!=targetSentence.end(); ++w) { output << *w << " ";}
            output << "||| ";
            for (auto a = alignment.begin(); a!=alignment.end(); ++a) { output << a->first << "-" << a->second << " ";}
            output << endl;
        }

        delete it;
    }

    cerr << "Dump ended" << endl;

    return SUCCESS;
}

max_stars_repo_name: ugermann/MMT

max_issues_repo_name: ugermann/MMT

max_forks_repo_name: ugermann/MMT


text:
#include <turbodbc_arrow/arrow_result_set.h>

// Somewhere a macro defines BOOL as a constant. This is in conflict with array/type.h
#undef BOOL
#undef timezone
#include <arrow/api.h>
#include <arrow/python/pyarrow.h>

#include <sql.h>

#include <turbodbc/errors.h>
#include <turbodbc/time_helpers.h>

#include <ciso646>
#include <vector>

#include <boost/locale.hpp>

using arrow::default_memory_pool;
using arrow::AdaptiveIntBuilder;
using arrow::ArrayBuilder;
using arrow::BooleanBuilder;
using arrow::Date32Builder;
using arrow::DoubleBuilder;
using arrow::Int32Builder;
using arrow::Int64Builder;
using arrow::Status;
using arrow::StringBuilder;
using arrow::StringDictionaryBuilder;
using arrow::TimeUnit;
using arrow::TimestampBuilder;
using arrow::Type;

namespace turbodbc_arrow {

namespace {

// We inherit this class to simply provide the same interfaces as StringDictionaryBuilderProxy
//
// Both classes can be removed once we upgrade to an Arrow version where ARROW-4367 is fixed.
class StringBuilderProxy: public StringBuilder {
  public:
    using StringBuilder::StringBuilder;

    Status AppendNullProxy() {
        return AppendNull();
    }

    Status AppendProxy(const char* value, int32_t length) {
        return Append(value, length);
    }
};

class StringDictionaryBuilderProxy: public StringDictionaryBuilder {
  public:
    using StringDictionaryBuilder::StringDictionaryBuilder;

    Status AppendNullProxy() {
        length_++;
        null_count_++;
        return AppendNull();
    }

    Status AppendProxy(const char* value, int32_t length) {
        length_++;
        return Append(value, length);
    }

    Status FinishInternal(std::shared_ptr<arrow::ArrayData>* out) override {
        // ARROW-4367: StringDictionaryBuilder segfaults on Finish with only null entries
        if (length_ == null_count_) {
            auto values = std::make_shared<arrow::StringArray>(0, std::shared_ptr<arrow::Buffer>(), std::shared_ptr<arrow::Buffer>());
            auto type = arrow::dictionary(arrow::int32(), values);
            Int32Builder builder;
            for (size_t i = 0; i != length_; i++) {
                ARROW_RETURN_NOT_OK(builder.AppendNull());
            }
            std::shared_ptr<arrow::Array> indices;
            ARROW_RETURN_NOT_OK(builder.Finish(&indices));
            *out = arrow::DictionaryArray(type, indices).data();

            return Status::OK();
        }
        return StringDictionaryBuilder::FinishInternal(out);
    };

  private:
    size_t length_ = 0;
    size_t null_count_ = 0;
};

std::unique_ptr<ArrayBuilder> make_array_builder(turbodbc::type_code type, bool strings_as_dictionary, bool adaptive_integers)
{
    switch (type) {
        case turbodbc::type_code::floating_point:
            return std::unique_ptr<ArrayBuilder>(new DoubleBuilder());
        case turbodbc::type_code::integer:
            if (adaptive_integers) {
                return std::unique_ptr<ArrayBuilder>(new AdaptiveIntBuilder());
            } else {
                return std::unique_ptr<ArrayBuilder>(new Int64Builder());
            }
        case turbodbc::type_code::boolean:
            return std::unique_ptr<ArrayBuilder>(new BooleanBuilder());
        case turbodbc::type_code::timestamp:
            return std::unique_ptr<TimestampBuilder>(new TimestampBuilder(arrow::timestamp(TimeUnit::MICRO), ::arrow::default_memory_pool()));
        case turbodbc::type_code::date:
            return std::unique_ptr<Date32Builder>(new Date32Builder());
        case turbodbc::type_code::unicode:
            if (strings_as_dictionary) {
                return std::unique_ptr<StringDictionaryBuilderProxy>(new StringDictionaryBuilderProxy(::arrow::utf8(), ::arrow::default_memory_pool()));
            } else {
                return std::unique_ptr<StringBuilderProxy>(new StringBuilderProxy());
            }
        default:
            if (strings_as_dictionary) {
                return std::unique_ptr<StringDictionaryBuilderProxy>(new StringDictionaryBuilderProxy(::arrow::utf8(), ::arrow::default_memory_pool()));
            } else {
                return std::unique_ptr<StringBuilderProxy>(new StringBuilderProxy());
            }
    }
}

template <typename BuilderType>
Status AppendStringsToBuilder(size_t rows_in_batch, BuilderType& builder, cpp_odbc::multi_value_buffer const& input_buffer) {
    for (std::size_t j = 0; j != rows_in_batch; ++j) {
        auto const element = input_buffer[j];
        if (element.indicator == SQL_NULL_DATA) {
            ARROW_RETURN_NOT_OK(builder.AppendNullProxy());
        } else {
            ARROW_RETURN_NOT_OK(builder.AppendProxy(element.data_pointer, element.indicator));
        }
    }
    return Status::OK();
}

template <typename BuilderType>
Status AppendUnicodeStringsToBuilder(size_t rows_in_batch, BuilderType& builder, cpp_odbc::multi_value_buffer const& input_buffer) {
    for (std::size_t j = 0; j != rows_in_batch; ++j) {
        auto const element = input_buffer[j];
        if (element.indicator == SQL_NULL_DATA) {
            ARROW_RETURN_NOT_OK(builder.AppendNullProxy());
        } else {
            std::u16string str_u16(reinterpret_cast<const char16_t*>(element.data_pointer), element.indicator / 2);
            std::string u8string = boost::locale::conv::utf_to_utf<char>(str_u16);;
            ARROW_RETURN_NOT_OK(builder.AppendProxy(u8string.data(), u8string.size()));
        }
    }
    return Status::OK();
}

template <typename BuilderType>
Status AppendIntsToBuilder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t* valid_bytes) {
    auto typed_builder = static_cast<BuilderType*>(builder.get());
    auto data_ptr = reinterpret_cast<const int64_t*>(input_buffer.data_pointer());
    return typed_builder->AppendValues(data_ptr, rows_in_batch, valid_bytes);
}

}

arrow_result_set::arrow_result_set(turbodbc::result_sets::result_set & base, bool strings_as_dictionary, bool adaptive_integers) :
    base_result_(base), strings_as_dictionary_(strings_as_dictionary), adaptive_integers_(adaptive_integers)
{
}

std::shared_ptr<arrow::DataType> turbodbc_type_to_arrow(turbodbc::type_code type) {
    switch (type) {
        case turbodbc::type_code::floating_point:
            return arrow::float64();
        case turbodbc::type_code::integer:
            return arrow::int64();
        case turbodbc::type_code::boolean:
            return arrow::boolean();
        case turbodbc::type_code::timestamp:
            return arrow::timestamp(TimeUnit::MICRO);
        case turbodbc::type_code::date:
            return arrow::date32();
        default:
            return std::make_shared<arrow::StringType>();
    }
}

std::shared_ptr<arrow::Schema> arrow_result_set::schema()
{
    auto const column_info = base_result_.get_column_info();
    auto const n_columns = column_info.size();
    std::vector<std::shared_ptr<arrow::Field>> fields;
    for (std::size_t i = 0; i != n_columns; ++i) {
        std::shared_ptr<arrow::DataType> type = turbodbc_type_to_arrow(column_info[i].type);
        fields.emplace_back(std::make_shared<arrow::Field>(column_info[i].name, type, column_info[i].supports_null_values));
    }
    return std::make_shared<arrow::Schema>(fields);
}

Status append_to_double_builder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t* valid_bytes) {
    auto typed_builder = static_cast<DoubleBuilder*>(builder.get());
    auto data_ptr = reinterpret_cast<const double*>(input_buffer.data_pointer());
    return typed_builder->AppendValues(data_ptr, rows_in_batch, valid_bytes);
}

Status append_to_int_builder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t* valid_bytes, bool adaptive_integers) {
    if (adaptive_integers) {
      return AppendIntsToBuilder<AdaptiveIntBuilder>(rows_in_batch, builder, input_buffer, valid_bytes);
    } else {
      return AppendIntsToBuilder<Int64Builder>(rows_in_batch, builder, input_buffer, valid_bytes);
    }
}

Status append_to_bool_builder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t* valid_bytes) {
    auto typed_builder = static_cast<BooleanBuilder*>(builder.get());
    auto data_ptr = reinterpret_cast<const uint8_t*>(input_buffer.data_pointer());
    return typed_builder->AppendValues(data_ptr, rows_in_batch, valid_bytes);
}

Status append_to_timestamp_builder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t*) {
    auto typed_builder = static_cast<TimestampBuilder*>(builder.get());
    for (std::size_t j = 0; j < rows_in_batch; ++j) {
        auto element = input_buffer[j];
        if (element.indicator == SQL_NULL_DATA) {
            ARROW_RETURN_NOT_OK(typed_builder->AppendNull());
        } else {
            ARROW_RETURN_NOT_OK(typed_builder->Append(turbodbc::timestamp_to_microseconds(element.data_pointer)));
        }
    }
    return Status::OK();
}

Status append_to_date_builder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t*) {
    auto typed_builder = static_cast<Date32Builder*>(builder.get());
    for (std::size_t j = 0; j < rows_in_batch; ++j) {
        auto element = input_buffer[j];
        if (element.indicator == SQL_NULL_DATA) {
            ARROW_RETURN_NOT_OK(typed_builder->AppendNull());
        } else {
            ARROW_RETURN_NOT_OK(typed_builder->Append(turbodbc::date_to_days(element.data_pointer)));
        }
    }
    return Status::OK();
}

Status append_to_string_builder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t*, bool strings_as_dictionary) {
    if (strings_as_dictionary) {
        return AppendStringsToBuilder<StringDictionaryBuilderProxy>(rows_in_batch,
            static_cast<StringDictionaryBuilderProxy&>(*builder), input_buffer);
    }

    return AppendStringsToBuilder<StringBuilderProxy>(rows_in_batch,
        static_cast<StringBuilderProxy&>(*builder), input_buffer);
}

Status append_to_unicode_builder(size_t rows_in_batch, std::unique_ptr<ArrayBuilder> const& builder, cpp_odbc::multi_value_buffer const& input_buffer, uint8_t*, bool strings_as_dictionary) {
    if (strings_as_dictionary) {
        return AppendUnicodeStringsToBuilder<StringDictionaryBuilderProxy>(rows_in_batch,
            static_cast<StringDictionaryBuilderProxy&>(*builder), input_buffer);
    }

    return AppendUnicodeStringsToBuilder<StringBuilderProxy>(rows_in_batch,
        static_cast<StringBuilderProxy&>(*builder), input_buffer);
}

Status arrow_result_set::process_batch(size_t rows_in_batch, std::vector<std::unique_ptr<ArrayBuilder>> const& columns) {
    // TODO: Use a PoolBuffer for this and only allocate it once
    auto const column_info = base_result_.get_column_info();
    auto const n_columns = column_info.size();
    std::vector<std::reference_wrapper<cpp_odbc::multi_value_buffer const>> const buffers = base_result_.get_buffers();

    std::vector<uint8_t> valid_bytes(rows_in_batch);
    for (size_t i = 0; i != n_columns; ++i) {
        auto const indicator_pointer = buffers[i].get().indicator_pointer();
        for (size_t element = 0; element != rows_in_batch; ++element) {
            if (indicator_pointer[element] == SQL_NULL_DATA) {
                valid_bytes[element] = 0;
            } else {
                valid_bytes[element] = 1;
            }
        }
        switch (column_info[i].type) {
            case turbodbc::type_code::floating_point:
                ARROW_RETURN_NOT_OK(append_to_double_builder(rows_in_batch, columns[i], buffers[i].get(), valid_bytes.data()));
                break;
            case turbodbc::type_code::integer:
                ARROW_RETURN_NOT_OK(append_to_int_builder(rows_in_batch, columns[i], buffers[i].get(), valid_bytes.data(), adaptive_integers_));
                break;
            case turbodbc::type_code::boolean:
                ARROW_RETURN_NOT_OK(append_to_bool_builder(rows_in_batch, columns[i], buffers[i].get(), valid_bytes.data()));
                break;
            case turbodbc::type_code::timestamp:
                ARROW_RETURN_NOT_OK(append_to_timestamp_builder(rows_in_batch, columns[i], buffers[i].get(), valid_bytes.data()));
                break;
            case turbodbc::type_code::date:
                ARROW_RETURN_NOT_OK(append_to_date_builder(rows_in_batch, columns[i], buffers[i].get(), valid_bytes.data()));
                break;
            case turbodbc::type_code::unicode:
                ARROW_RETURN_NOT_OK(append_to_unicode_builder(rows_in_batch, columns[i], buffers[i].get(), valid_bytes.data(), strings_as_dictionary_));
                break;
            default:
                // Strings are the only remaining type
                ARROW_RETURN_NOT_OK(append_to_string_builder(rows_in_batch, columns[i], buffers[i].get(), valid_bytes.data(), strings_as_dictionary_));
                break;
        }
    }
    return Status::OK();
}

Status arrow_result_set::fetch_all_native(std::shared_ptr<arrow::Table>* out, bool single_batch)
{
    std::size_t rows_in_batch = base_result_.fetch_next_batch();
    auto const column_info = base_result_.get_column_info();
    auto const n_columns = column_info.size();

    // Construct the Arrow schema from the SQL schema information
    // We only use this schema for the type information. It does not match the
    // resulting Table as for example String columns may also be encoded as
    // dictionaries.
    std::shared_ptr<arrow::Schema> arrow_schema = schema();

    // Create Builders for all columns
    std::vector<std::unique_ptr<ArrayBuilder>> columns;
    for (std::size_t i = 0; i != n_columns; ++i) {
        columns.push_back(make_array_builder(column_info[i].type, strings_as_dictionary_, adaptive_integers_));
    }

    if (single_batch) {
        ARROW_RETURN_NOT_OK(process_batch(rows_in_batch, columns));
    } else {
        do {
            ARROW_RETURN_NOT_OK(process_batch(rows_in_batch, columns));
            rows_in_batch = base_result_.fetch_next_batch();
        } while (rows_in_batch != 0);
    }

    std::vector<std::shared_ptr<arrow::Array>> arrow_arrays;
    std::vector<std::shared_ptr<arrow::Field>> fields;
    for (size_t i = 0; i != n_columns; ++i) {
        std::shared_ptr<arrow::Array> array;
        ARROW_RETURN_NOT_OK(columns[i]->Finish(&array));
        fields.emplace_back(std::make_shared<arrow::Field>(column_info[i].name, array->type(), column_info[i].supports_null_values));
        arrow_arrays.emplace_back(array);
    }
    // Update to the correct schema, account for e.g. Dictionary columns
    arrow_schema = std::make_shared<arrow::Schema>(fields);
    *out = arrow::Table::Make(arrow_schema, arrow_arrays);

    return Status::OK();
}

pybind11::object arrow_result_set::fetch_next_batch()
{
    std::shared_ptr<arrow::Table> table;
    if (not fetch_all_native(&table, true).ok()) {
        throw turbodbc::interface_error("Fetching Arrow result set failed.");
    }

    arrow::py::import_pyarrow();
    return pybind11::reinterpret_steal<pybind11::object>(pybind11::handle(arrow::py::wrap_table(table)));
}

pybind11::object arrow_result_set::fetch_all()
{
    std::shared_ptr<arrow::Table> table;
    if (not fetch_all_native(&table, false).ok()) {
        throw turbodbc::interface_error("Fetching Arrow result set failed.");
    }

    arrow::py::import_pyarrow();
    return pybind11::reinterpret_steal<pybind11::object>(pybind11::handle(arrow::py::wrap_table(table)));
}

}

max_stars_repo_name: fjetter/turbodbc

max_issues_repo_name: fjetter/turbodbc

max_forks_repo_name: fjetter/turbodbc


text:
// Copyright (c) 2017, The Graft Project
//
// 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.
//
// 3. Neither the name of the copyright holder 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 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.
//

#include "PosSaleObject.h"
#include "TxPool.h"
#include "graft_defines.h"
#include <utils/utils.h>
#include <ringct/rctSigs.h>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

using namespace cryptonote;

void supernode::PosSaleObject::Owner(PosProxy* o) { m_Owner = o; }

bool supernode::PosSaleObject::Init(const RTA_TransactionRecordBase& src) {
	BaseRTAObject::Init(src);

	TransactionRecord.PaymentID = GeneratePaymentID();
	TransactionRecord.BlockNum = m_Servant->GetCurrentBlockHeight();
	TransactionRecord.AuthNodes = m_Servant->GetAuthSample( TransactionRecord.BlockNum );
    if( TransactionRecord.AuthNodes.empty() ) { LOG_PRINT_L0("SALE: AuthNodes.empty"); m_Status = NTransactionStatus::Fail; return false; }

    m_Status = NTransactionStatus::InProgress;

	ADD_RTA_OBJECT_HANDLER(GetSaleStatus, rpc_command::POS_GET_SALE_STATUS, PosSaleObject);
	ADD_RTA_OBJECT_HANDLER(PoSTRSigned, rpc_command::POS_TR_SIGNED, PosSaleObject);
	ADD_RTA_OBJECT_HANDLER(PosRejectSale, rpc_command::POS_REJECT_SALE, PosSaleObject);
	ADD_RTA_OBJECT_HANDLER(AuthWalletRejectPay, rpc_command::WALLET_REJECT_PAY, PosSaleObject);

	return true;
}

void supernode::PosSaleObject::ContinueInit() {
	InitSubnet();

	vector<rpc_command::POS_PROXY_SALE::response> outv;
	rpc_command::POS_PROXY_SALE::request inbr;
	rpc_command::ConvertFromTR(inbr, TransactionRecord);
	inbr.SenderIP = m_DAPIServer->IP();
	inbr.SenderPort = m_DAPIServer->Port();
	if( !m_SubNetBroadcast.Send(dapi_call::PosProxySale, inbr, outv) || outv.empty() ) {
        LOG_ERROR("!Send dapi_call::PosProxySale");
		m_Status = NTransactionStatus::Fail;

	}

}

bool supernode::PosSaleObject::AuthWalletRejectPay(const rpc_command::WALLET_REJECT_PAY::request &in, rpc_command::WALLET_REJECT_PAY::response &out) {
	LOG_PRINT_L0("PosSaleObject::AuthWalletRejectPay" << in.PaymentID);
	m_Status = NTransactionStatus::RejectedByWallet;
	return true;
}

bool supernode::PosSaleObject::GetSaleStatus(const rpc_command::POS_GET_SALE_STATUS::request& in, rpc_command::POS_GET_SALE_STATUS::response& out)
{
	LOG_PRINT_L0("PosSaleObject::GetSaleStatus" << in.PaymentID);
	out.Status = int(m_Status);
    out.Result = STATUS_OK;
	return true;
}

bool supernode::PosSaleObject::PoSTRSigned(const rpc_command::POS_TR_SIGNED::request& in, rpc_command::POS_TR_SIGNED::response& out) {
	LOG_PRINT_L0("PosSaleObject::PoSTRSigned" << in.PaymentID);
	{
		boost::lock_guard<boost::recursive_mutex> lock(m_TxInPoolGotGuard);
		if(m_TxInPoolGot) return true;
		m_TxInPoolGot = true;
	}

    // get tranaction from pool by in.TransactionPoolID
    // TODO: make txPool as a member of PosProxy or FSN_Servant?
    TxPool txPool(m_Servant->GetNodeAddress(), m_Servant->GetNodeLogin(), m_Servant->GetNodePassword());
    cryptonote::transaction tx;
    if (!txPool.get(in.TransactionPoolID, tx)) {
        LOG_ERROR("TX " << in.TransactionPoolID << " was not found in pool");
        return false;
    }

    // Get the tx extra
    GraftTxExtra graft_tx_extra;
    if (!cryptonote::get_graft_tx_extra_from_extra(tx, graft_tx_extra)) {
        LOG_ERROR("TX " << in.TransactionPoolID << " : error reading graft extra");
        return false;
    }
    // check all signs
    //LOG_PRINT_L2("AuthNodes.size : " << TransactionRecord.AuthNodes.size());

    if (TransactionRecord.AuthNodes.size() != graft_tx_extra.Signs.size()) {
        LOG_ERROR("TX " << in.TransactionPoolID << " : number of auth nodes and number of signs mismatch");
        return false;
    }

    for (unsigned i = 0; i < graft_tx_extra.Signs.size(); ++i) {
        const string &sign = graft_tx_extra.Signs.at(i);

        if( CheckSign(TransactionRecord.AuthNodes[i]->Stake.Addr, sign) ) {
        	m_Signs++;
        } else {
        	LOG_ERROR("TX " << in.TransactionPoolID << " : signature failed to check for all nodes: " << sign);
        }

        /*
        bool check_result = false;
        // TODO: in some reasons TransactionRecord.AuthNodes order and Signs order mismatch, so it can't be checked
        // by the same index
        for (const auto & authNode : TransactionRecord.AuthNodes) {
            check_result = CheckSign(authNode->Stake.Addr, sign);
            if (check_result)
                break;
        }
        if (!check_result) {
            LOG_ERROR("TX " << in.TransactionPoolID << " : signature failed to check for all nodes: " << sign);
            return false;
        }

        m_Signs++;
           */
    }

    if (m_Signs != m_Servant->AuthSampleSize()) {
        LOG_ERROR("Checked signs number mismatch with auth sample size, " << m_Signs << "/" << m_Servant->AuthSampleSize());
        return false;
    }

    //  check transaction amount against TransactionRecord.Amount using TransactionRecord.POSViewKey
    // get POS address and view key
    cryptonote::account_keys pos_account;
    epee::string_tools::hex_to_pod(TransactionRecord.POSViewKey, pos_account.m_view_secret_key);

    if (!cryptonote::get_account_address_from_str(pos_account.m_account_address, m_Servant->IsTestnet(), TransactionRecord.POSAddress)) {
        LOG_ERROR("Error parsing POS Address: " << TransactionRecord.POSAddress);
        return false;
    }

    uint64_t amount = 0;
    vector<pair<size_t, uint64_t>> outputs;

    if (!Utils::lookup_account_outputs_ringct(pos_account, tx, outputs, amount)) {
        LOG_ERROR("Error checking tx outputs");
        return false;
    }

    if (amount != TransactionRecord.Amount) {
        LOG_ERROR("Tx amount is not equal to TransactionRecord.Amount: " << amount << "/" << TransactionRecord.Amount);
        return false;
    }

    m_Status = NTransactionStatus::Success;
    return true;
}

bool supernode::PosSaleObject::PosRejectSale(const supernode::rpc_command::POS_REJECT_SALE::request &in, supernode::rpc_command::POS_REJECT_SALE::response &out) {
	LOG_PRINT_L0("PosSaleObject::PosRejectSale" << in.PaymentID);
    m_Status = NTransactionStatus::RejectedByPOS;

    //TODO: Add impl

    out.Result = STATUS_OK;
    return true;
}

string supernode::PosSaleObject::GeneratePaymentID() {
    boost::uuids::random_generator gen;
    boost::uuids::uuid id = gen();
    return boost::uuids::to_string(id);
}


text:
#include <boost/program_options.hpp>
#include <string>

#include "Expr.h"
#include "ExprAttachment.h"
#include "ExprUtil.h"
#include "Model.h"
#include "Verbosity.h"
#include "options.h"
#include "COI.h"
#include "ProofAttachment.h"
#include "CNFAttachment.h"
#include "Quip.h"

ID var(Expr::Manager::View * ev, std::string name) {
  return ev->newVar(name);
}

class TestUMCAction : public Model::Action {
public:
  TestUMCAction(Model & m) : Model::Action(m)
  {
    ExprAttachment::Factory eaf;
    requires(Key::EXPR, &eaf);
    COIAttachment::Factory caf;
    requires(Key::COI, &caf);
    ProofAttachment::Factory paf;
    requires(Key::PROOF, &paf);
    CNFAttachment::Factory cnfaf;
    requires(Key::CNF, &cnfaf);
  }

  virtual void exec();

private:
  static ActionRegistrar action;
};

void TestUMCAction::exec() {
  UMC::QuipOptions opts;
  UMC::QuipSolver solver(model(), opts);
  UMC::ReturnValue rv = solver.solve();
  assert(rv.returnType == MC::CEX);
}

int main(void) {
  boost::program_options::variables_map opts;

  Model model(opts, "test");
  model.setVerbosity(Options::Verbose);
  model.setOptionValue("input-file", std::string("examples/quip_tests/unsafe/syncarb16.aig"));

  Model::Action * action = new TestUMCAction(model);
  action->make();
}

max_stars_repo_name: ryanberryhill/iimc

max_issues_repo_name: ryanberryhill/iimc

max_forks_repo_name: ryanberryhill/iimc


text:
#include <boost/program_options.hpp>
#include <boost/process.hpp>
#include <iostream>
#include <string>
#include <chrono>
using namespace std;

boost::process::child Build(int clock = 0)
{
	string cmake = "cmake --build _builds";
	cout << "Command = " << cmake << endl;
	boost::process::child process(cmake, boost::process::std_out > stdout);
	if (clock != 0)
	{
		if (!process.wait_for(chrono::seconds(clock)));
		process.terminate();
	}
	else process.wait();
	return process;
}

boost::process::child Target(string install)
{
	string cmake = "cmake --build _builds --target " + install;
	cout << "Command = " << cmake << endl;
	boost::process::child process(cmake, boost::process::std_out > stdout);
	process.wait();
	return process;
}

boost::process::child Make(int clock = 0, string configuration = "Debug")
{
	string cmake = "cmake -H. -B_build -DCMAKE_INSTALL_PREFIX=_install -DCMAKE_BUILD_TYPE=" + configuration;
	cout << "Command : " << cmake << endl;
	boost::process::child process(cmake, boost::process::std_out > stdout);
	if (clock != 0)
	{
		if (!process.wait_for(chrono::seconds(clock)));
		process.terminate();
	}
	else process.wait();
	return process;
}

int main(int argc, char *argv[])
{
	boost::program_options::options_description options("Allowed options");
	options.add_options()
		("help", "выводим вспомогательное сообщение")
		("config", boost::program_options::value<string>(), "указываем конфигурацию сборки (по умолчанию Debug)")
		("install", "добавляем этап установки (в директорию _install)")
		("pack", "добавляем этап упакови (в архив формата tar.gz)")
		("timeout", boost::program_options::value<int>(), "указываем время ожидания (в секундах)");
	boost::program_options::variables_map varMap;
	boost::program_options::store(boost::program_options::parse_command_line(argc, argv, options), varMap);
	boost::program_options::notify(varMap);
	int code;
	if (varMap.count("help")) cout << options << endl;
	else if (varMap.count("config"))
	{
		string par(varMap["config"].as<string>());
		code = Make(0, par).exit_code();
		if (code == 0) code = Build().exit_code();
		cout << "Code : " << code << endl;
	}
	else if (varMap.count("pack"))
	{
		code = Make().exit_code();
		if (code == 0) code = Build().exit_code();
		if (code == 0) code = Target("package").exit_code();
		cout << "code == " << code << endl;
	}
	else if (varMap.count("install"))
	{
		code = Make().exit_code();
		if (code == 0) code = Build().exit_code();
		if (code == 0) code = Target("install").exit_code();
		cout << "Code : " << code << endl;
	}
	else if (varMap.count("pack") && varMap.count("install"))
	{
		code = Make().exit_code();
		if (code == 0) code = Build().exit_code();
		if (code == 0) code = Target("install").exit_code();
		if (code == 0) code = Target("pack").exit_code();
		cout << "Code : " << code << endl;
	}
	else if (varMap.count("timeout"))
	{
		int time = varMap["timeout"].as<int>();
		code = Make(time).exit_code();
		if (code == 0) code = Build(time).exit_code();
		cout << "code == " << code << endl;
	}
	else
	{
		code = Make().exit_code();
		if (code == 0) code = Build().exit_code();
		cout << "Code : " << code << endl;
	}
	system("pause");
	return 0;
}


text:
#include <opencv2/opencv.hpp>
#include <vector>
#include <string>
#include <Eigen/Core>
#include <pangolin/pangolin.h>
#include <unistd.h>

using namespace std;
using namespace Eigen;

// 文件路径
string left_file = "./left.png";
string right_file = "./right.png";

void showPointCloud(
    const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud);

int main(int argc, char **argv) {
    double fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;
    double b=0.573;

    cv::Mat left=cv::imread(left_file);
    cv::Mat right=cv::imread(right_file);
    cv::Ptr<cv::StereoSGBM> sgbm = cv::StereoSGBM::create(0, 96, 9, 8 * 9 * 9, 32 * 9 * 9, 1, 63, 10, 100, 32);
    cv::Mat disparity_sgbm, disparity;
    sgbm->compute(left,right,disparity_sgbm);
    disparity_sgbm.convertTo(disparity,CV_32F,1.0/16.0f);//signed short 2byte -> float 4byte

    vector<Vector4d,Eigen::aligned_allocator<Vector4d>> pointcloud;

    cout<<left.rows<<" "<<left.cols<<" "<<left.step[0]<<" "<<left.step[1]<<" "<<left.channels()<<endl;
    cout<<disparity_sgbm.rows<<" "<<disparity_sgbm.cols<<" "<<disparity_sgbm.step[0]<<" "<<disparity_sgbm.step[1]<<" "<<disparity_sgbm.channels()<<endl;
    cout<<disparity.rows<<" "<<disparity.cols<<" "<<disparity.step[0]<<" "<<disparity.step[1]<<" "<<disparity.channels()<<endl;

    cout<<disparity_sgbm.type()<<" "<<disparity.type()<<" "<<disparity_sgbm.at<short>(10,0)<<" "<< disparity.at<float>(10,0)<<endl;
/*
+--------+----+----+----+----+------+------+------+------+
|        | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) |
+--------+----+----+----+----+------+------+------+------+
| CV_8U  |  0 |  8 | 16 | 24 |   32 |   40 |   48 |   56 |
| CV_8S  |  1 |  9 | 17 | 25 |   33 |   41 |   49 |   57 |
| CV_16U |  2 | 10 | 18 | 26 |   34 |   42 |   50 |   58 |
| CV_16S |  3 | 11 | 19 | 27 |   35 |   43 |   51 |   59 |
| CV_32S |  4 | 12 | 20 | 28 |   36 |   44 |   52 |   60 |
| CV_32F |  5 | 13 | 21 | 29 |   37 |   45 |   53 |   61 |
| CV_64F |  6 | 14 | 22 | 30 |   38 |   46 |   54 |   62 |
+--------+----+----+----+----+------+------+------+------+
*/
    for(int v=0;v<left.rows;v++)
    {
        for(int u=0;u<left.cols;u++)
        {
            if(disparity.at<float>(v,u)<=0||disparity.at<float>(v,u)>=96.0) continue;

            Vector4d point(0,0,0,left.at<uchar>(v,u)/255.0);

            double depth=b*fx/(disparity.at<float>(v,u));//disparity in pixel
            double x=depth*(u-cx)/fx;
            double y=depth*(v-cy)/fy;

            point[0]=x;
            point[1]=y;
            point[2]=depth;

            pointcloud.push_back(point);
            //cout<<(int)left.at<Eigen::Matrix<uchar,3,1>>(v,u)[0]<<" "<<(int)left.at<Eigen::Matrix<uchar,3,1>>(v,u)[1]<<" "<<(int)left.at<Eigen::Matrix<uchar,3,1>>(v,u)[2]<<" "<<endl;
            //cout<<point<<endl;

        }

    }
    cv::imshow("disparity",disparity/255.0);
    cv::waitKey(0);
    showPointCloud(pointcloud);
    return 0;

}

void showPointCloud(const vector<Vector4d, Eigen::aligned_allocator<Vector4d>> &pointcloud) {

    if (pointcloud.empty()) {
        cerr << "Point cloud is empty!" << endl;
        return;
    }

    pangolin::CreateWindowAndBind("Point Cloud Viewer", 1024, 768);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    pangolin::OpenGlRenderState s_cam(
        pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),
        pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)
    );

    pangolin::View &d_cam = pangolin::CreateDisplay()
        .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)
        .SetHandler(new pangolin::Handler3D(s_cam));

    while (pangolin::ShouldQuit() == false) {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        d_cam.Activate(s_cam);
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

        glPointSize(2);
        glBegin(GL_POINTS);
        for (auto &p: pointcloud) {
            glColor3f(p[3], p[3], p[3]);
            glVertex3d(p[0], p[1], p[2]);
        }
        glEnd();
        pangolin::FinishFrame();
        usleep(5000);   // sleep 5 ms
    }
    return;
}


text:
/*
 * Primitive.cpp
 *
 *  Created on: 2012-02-19
 *      Author: leo
 */

#include <fruitpunch/Graphics/Vertex.h>
#include <fruitpunch/Graphics/Matrices.h>
#include <fruitpunch/Graphics/Renderer.h>
#include <fruitpunch/Graphics/Window.h>
#include <fruitpunch/Graphics/Primitive.h>
#include <fruitpunch/Graphics/Image.h>
#include <fruitpunch/Common/Runtime.h>
#include <fruitpunch/Elements/Scene.h>

#include <boost/shared_ptr.hpp>
#include <list>
#include <stdio.h>
#include <armadillo>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;
using namespace arma;
using namespace fp_core::common;

namespace fp_core {

Primitive::Primitive() : Element(), m_trans_vertices(NULL) {

  point zero;
  zero.x = 0;
  zero.y = 0;

  point one;
  one.x = 1;
  one.y = 1;
  m_center = zero;
  m_rotation = 0;
  m_scale = one;
  m_position = zero;

  point center;
  center.x = 0.5f;
  center.y = 0.5f;
  mTexScale = one;
  mTexPosition = zero;
  mTexRotation = 0;
  mTexCenter = center;

  m_alpha = 1;

  m_window = Runtime::getCurrent()->getWindow().get();
}

//______________________________________________________________________________

Primitive::Primitive(const Primitive & p) : m_trans_vertices(NULL) {
  copy_from(p);
}

//______________________________________________________________________________

Primitive::~Primitive() {

}

//______________________________________________________________________________

Primitive & Primitive::operator =(const Primitive & p) {
  copy_from(p);
  return *this;
}

//______________________________________________________________________________

void Primitive::addVertex(const Vertex& vertex) {
  m_vertices.push_back(vertex);

  // if we have at least three vertices, generate a center
  if (m_vertices.size() >= 3) {
    m_center = verticesCenter();
  }
}

//______________________________________________________________________________

point * Primitive::pointArray() const {

  // Allocates memory
  point * result = new point[m_vertices.size()];

  // Gets the transformation matrix
  fmat33 main = transformationMatrix();

  // create point array
  for (unsigned int i = 0; i < m_vertices.size(); i++) {

    // gets the point
    point p = m_vertices[i].getPosition();

    // transforms the point
    p = getWindow()->getRenderer()->transform_point(p, main);
    result[i] = p;
  }

  return result;
}

//______________________________________________________________________________

void Primitive::move(float x, float y) {
  m_position.x = m_position.x + x;
  m_position.y = m_position.y + y;
}

//______________________________________________________________________________

void Primitive::rotate(float amount) {
  m_rotation = m_rotation + amount;
}

//______________________________________________________________________________

void Primitive::scale(float x, float y) {
  m_scale.x = m_scale.x * x;
  m_scale.y = m_scale.y * y;
}

//______________________________________________________________________________

void Primitive::copy_from(const Primitive & p) {
  m_center = p.getCenter();
  m_rotation = p.getRotation();
  m_position = p.getPosition();
  m_scale = p.getScale();
  m_stick = p.isStick();
  m_vertices = p.getVertices();
  m_window = p.getWindow();
  mImage = p.getImage();
  mTexCenter = p.getTexCenter();
  mTexPosition = p.getTexPosition();
  mTexRotation = p.getTexRotation();
  mTexScale = p.getTexScale();
  m_alpha = p.getAlpha();
}

//______________________________________________________________________________

std::vector<point> Primitive::boundaries() const {
  vector<point> positions = Vertex::positionPointVector(m_vertices);
  return point::boundaries(positions);
}

//______________________________________________________________________________

Box Primitive::boundingBox() const {
  vector<point> bounds = boundaries();
  Box b;
  point bottom_left;
  point bottom_right;
  point top_left;
  point top_right;

  bottom_left.x = bounds[0].x;
  bottom_left.y = bounds[0].y;
  bottom_right.x = bounds[1].x;
  bottom_right.y = bounds[0].y;
  top_left.x = bounds[0].x;
  top_left.y = bounds[1].y;
  top_right.x = bounds[1].x;
  top_right.y = bounds[1].y;

  b.setCoordinates(top_left, top_right, bottom_left, bottom_right);
  return b;
}

//______________________________________________________________________________

point Primitive::verticesCenter() const {
  vector<point> bounds = boundaries();
  point center;
  point min = bounds[0];
  point max = bounds[1];
  center.x = (min.x + max.x) / 2;
  center.y = (min.y + max.y) / 2;
  return center;
}

//______________________________________________________________________________

point * Primitive::uvPointArray() const {
  vector<Vertex>::const_iterator it;

  fmat33 main;
  main.eye(); // assigns identity

  // ---------------------------------------------------------------------------
  // Uv Transformations
  // ---------------------------------------------------------------------------

  // goes to local space
   main = (arma::fmat33) (to_local_space_matrix(mTexCenter) * main);

   // concatenates the transformations
   main = (arma::fmat33) (rotation_matrix(mTexRotation) * main);
   main = (arma::fmat33) (scale_matrix(mTexScale) * main);

   // goes to world space
   main = (arma::fmat33) (to_global_space_matrix(mTexCenter) * main);

   // moves to position
   main = (arma::fmat33) (translation_matrix(mTexPosition) * main);

   point * result = new point[m_vertices.size()];
   int i = 0;
  for (it = m_vertices.begin(); it != m_vertices.end(); it++) {
    point uv = it->getUvmap();

    // transforms the UV coordinates before pushing it
    uv = getWindow()->getRenderer()->transform_point(uv, main);

    result[i] = uv;
    i++;
  }
  return result;
}

//______________________________________________________________________________

struct Primitive::comparator {
  boost::shared_ptr<Renderer> renderer;
  point center;

  bool operator ()(const point& i, const point& j) const {
    Renderer& r = *renderer;
    return point::comesBeforeCC(i, j, center, r);
  }
};

bool Primitive::contains(point p) {

  vector<point> V = this->pointVector();
  if (V.size() < 3) return false;

  // checks if the point intersects any of the vertices
  vector<point>::iterator it = V.begin();
  for (; it != V.end(); it++) {
      if (it->x == p.x && it->y == p.y) {
          return true;
      }
  }

  /*
   * Checks if the point is inside the primitive (polygon) by using the
   * first algorithm described in
   * http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/
   */

  // Order points counter clockwise
  comparator comp;
  comp.renderer = getWindow()->getRenderer();
  comp.center = getCenter();
  std::sort(V.begin(), V.end(), comp);

  // close the polygon
  V.push_back(V[0]);

  int crossings = 0;

  // loops through all the edges
  for (unsigned int i=0; i<V.size()-1; i++) {
    point vA = V[i];
    point vB = V[i+1];

    // orders vA and vB according to which one is at the bottom - biggest
    // Y coordinate. vB will always be the highest Y.
    if (vA.y > vB.y) {
      point temp = vA;
      vA = vB;
      vB = temp;
    }

    // gets the minimum and maximum x,y values and checks if the point
    // falls right on the edge
    vector<point> edge;
    edge.push_back(vA);
    edge.push_back(vB);
    vector<point> bounds = point::boundaries(edge);
    if (p.x <= bounds[1].x && p.x >= bounds[0].x && p.y <= bounds[1].y && p.y >= bounds[0].y) {
        return true;
    }

    //printf("vA: (%f,%f), vB: (%f,%f) \n", vA.x, vA.y, vB.x, vB.y);
    // Checks if the point is between the Ys of the edges
    if (vA.y == vB.y) continue; // no point doing anything if its a horizontal line
    if (p.y > vB.y || p.y < vA.y) continue;

    // Checks if its a vertical edge and if the point comes to the left of the
    // edge
    if (vA.x == vB.x && p.x <= vA.x) {
      crossings++;
      continue;
    }

    // If it gets here, its because the edge is not a horizontal or vertical
    // line. In this case, we have to get a line equation in the form
    // f(x) = ax + b in order to get the X value of the edge that intercepts
    // the Y value of our point.
    float a = (vA.y - vB.y) / (vA.x - vB.x);
    float b = vB.y - a * vB.x;
    float ex = (p.y - b) / a;
    if (p.x <= ex) crossings++;
  }

  return (crossings % 2 != 0); // true if its odd
}

//______________________________________________________________________________

std::vector<point> Primitive::transformedBounds() {
  vector<point> points = pointVector();
  return point::boundaries(points);
}

//______________________________________________________________________________

vector<point> Primitive::pointVector() {
	vector<point> result;
	point * points = pointArray();
	for (int i =0; i<m_vertices.size(); i++) {
		result.push_back(points[i]);
	}
	delete points;
	return result;
}

//______________________________________________________________________________

vector<point> Primitive::uvPointVector() {
	vector<point> result;
	point * points = uvPointArray();
	for (int i =0; i<m_vertices.size(); i++) {
		result.push_back(points[i]);
	}
	delete points;
	return result;
}

//______________________________________________________________________________

arma::fmat33 Primitive::transformationMatrix() const {
  fmat33 main;
  main.eye(); // assigns identity

  // goes to local space
  main = (arma::fmat33) (to_local_space_matrix(m_center) * main);

  // concatenates the transformations
  main = (arma::fmat33) (rotation_matrix(m_rotation) * main);
  main = (arma::fmat33) (scale_matrix(m_scale) * main);

  // goes to world space
  main = (arma::fmat33) (to_global_space_matrix(m_center) * main);

  // moves to position
  main = (arma::fmat33) (translation_matrix(m_position) * main);

  return main;
}

// ---------------------------------------------------------------------------
// Getters and setters
// ---------------------------------------------------------------------------

float Primitive::getWidth() const {
  vector<point> bounds = boundaries();

  // original width is the maximum X - minimum X
  float origWidth = bounds[1].x - bounds[0].x;

  return origWidth * m_scale.x;
}

float Primitive::getHeight() const {
  vector<point> bounds = boundaries();

  // original width is the maximum X - minimum X
  float origHeight = bounds[1].y - bounds[0].y;

  return origHeight * m_scale.y;
}

void Primitive::setWidth(float width) {
  vector<point> bounds = boundaries();

  // original width is the maximum X - minimum X
  float origWidth = bounds[1].x - bounds[0].x;

  m_scale.x = width / origWidth;
}

void Primitive::setHeight(float height) {
  vector<point> bounds = boundaries();

  // original width is the maximum X - minimum X
  float origHeight = bounds[1].y - bounds[0].y;

  m_scale.y = height / origHeight;
}

float Primitive::getTop() {
  return transformedBounds()[0].y;
}

float Primitive::getLeft() {
  return transformedBounds()[0].x;
}

void Primitive::setTop(float top) {
  // we need minimum Y
  vector<point> bounds = transformedBounds();
  float minY = bounds[0].y;

  // calculates the difference
  float delta = top - minY;

  // corrects it
  move(0, delta);

}

void Primitive::setLeft(float left) {
  // we need minimum X
  vector<point> bounds = transformedBounds();
  float minX = bounds[0].x;

  // calculates the difference
  float delta = left - minX;

  // corrects it
  move(delta, 0);
}

float Primitive::getX() const {
  return m_position.x;
}

float Primitive::getY() const {
  return m_position.y;
}

void Primitive::setX(float x) {
  m_position.x = x;
}

void Primitive::setY(float y) {
  m_position.y = y;
}

point Primitive::getCenter() const {
  return m_center;
}

point Primitive::getPosition() const {
  return m_position;
}

float Primitive::getRotation() const {
  return m_rotation;
}

point Primitive::getScale() const {
  return m_scale;
}

vector<Vertex> Primitive::getVertices() const {
  return m_vertices;
}

Window *Primitive::getWindow() const {
  return m_window;
}

void Primitive::setCenter(point center) {
  m_center = center;
}

void Primitive::setPosition(point position) {
  m_position = position;
}

void Primitive::setRotation(float rotation) {
  m_rotation = rotation;
}

void Primitive::setScale(point scale) {
  m_scale = scale;
}

void Primitive::setWindow(Window *window) {
  m_window = window;
}

bool Primitive::isStick() const {
  return m_stick;
}

void Primitive::setStick(bool stick) {
  m_stick = stick;
}

point * Primitive::getTransVertices() const
{
    return m_trans_vertices;
}

void Primitive::setTransVertices(point * transVertices)
{
	if (m_trans_vertices != NULL) {
		delete[] m_trans_vertices;
	}

	m_trans_vertices = new point[m_vertices.size()];
	for (int i=0; i<m_vertices.size(); i++) {
		m_trans_vertices[i] = transVertices[i];
	}
}

Vertex& Primitive::getVertex(int index) {
	return m_vertices[index];
}

boost::shared_ptr<Image> Primitive::getImage() const {
  return mImage;
}

void Primitive::setImage(boost::shared_ptr<Image> image) {
  mImage = image;
}

point Primitive::getTexCenter() const {
  return mTexCenter;
}

float Primitive::getAlpha() const {
	return m_alpha;
}
point Primitive::getTexPosition() const {
  return mTexPosition;
}

void Primitive::setAlpha(float alpha) {
	m_alpha = alpha;
}
point Primitive::getTexScale() const {
  return mTexScale;
}

void Primitive::setTexCenter(point texCenter) {
  mTexCenter = texCenter;
}

void Primitive::setTexPosition(point texPosition) {
  mTexPosition = texPosition;
}

void Primitive::setTexScale(point texScale) {
  mTexScale = texScale;
}

float Primitive::getTexRotation() const {
  return mTexRotation;
}

void Primitive::setTexRotation(float texRotation) {
  mTexRotation = texRotation;
}

void fp_core::Primitive::onAdd() {
  Runtime::getCurrent()->getWindow()->addPrimitive(getThis<Primitive>());
}

void fp_core::Primitive::onRemove() {
	getScene()->getWindow()->removePrimitive(getThis<Primitive>());
}

float Primitive::getTexX() {
	return mTexPosition.x;
}

float Primitive::getTexY() {
	return mTexPosition.y;
}

void Primitive::setTexX(float val) {
	mTexPosition.x = val;
}

void Primitive::setTexY(float val) {
	mTexPosition.y = val;
}

/* namespace fp_core */
}

max_stars_repo_name: submain/fruitpunch

max_issues_repo_name: submain/fruitpunch

max_forks_repo_name: submain/fruitpunch


text:
/*
 * copyright svante karlsson at csi dot se 2021
 */
#include "qtr/io/csv_file_source.h"
#include <filesystem>
#include <fstream>
#include <boost/tokenizer.hpp>
#include <glog/logging.h>

namespace qtr {

typedef boost::tokenizer<boost::escaped_list_separator<char>,
                         std::string::const_iterator, std::string>
    Tokenizer;

inline bool ends_with(std::string const &value, std::string const &ending) {
  if (ending.size() > value.size())
    return false;
  return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}

// TODO fix so we can use arrow fs stuff ie a s3 bucket
csv_file_source::csv_file_source(std::string filename)
    : seps_('\\', ',', '\"') {
  if (!std::filesystem::exists(filename)) {
    LOG(ERROR) << "cannot find " << filename << std::endl;
    throw std::runtime_error("cannot find " + filename);
  }

  if (ends_with(filename, ".gz")) {
    // Read from the first command line argument, assume it's gzipped
    file_ = std::make_unique<std::ifstream>(
        filename, std::ios_base::in | std::ios_base::binary);
    inbuf_ = std::make_unique<
        boost::iostreams::filtering_streambuf<boost::iostreams::input>>();
    inbuf_->push(boost::iostreams::gzip_decompressor());
    inbuf_->push(*file_.get());
    // Convert streambuf to istream
    instream_ = std::make_unique<std::istream>(inbuf_.get());
  } else if (ends_with(filename, ".csv")) {
    instream_ = std::make_unique<std::ifstream>(
        filename, std::ios_base::in | std::ios_base::binary);
  } else {
    throw std::runtime_error("dont know how to parse " + filename);
  }
  // get column names
  // tokenizer

  // consume 1st line (ie header)
  std::string line;
  std::getline(*instream_, line);
  Tokenizer tok(line, seps_);
  for (auto i : tok)
    column_names_.emplace_back(i);

  // read first line
  read_row_();
}

csv_file_source::~csv_file_source() {}

std::vector<std::string> csv_file_source::get_row() {
  std::vector<std::string> v = std::move(next_row_);
  read_row_();
  return v;
}

void csv_file_source::read_row_() {
  std::string line;
  if (std::getline(*instream_, line)) {
    Tokenizer tok(line, seps_);
    next_row_.clear();
    for (auto i : tok)
      next_row_.emplace_back(i);
  } else {
    eof_ = true;
  }
}

} // namespace qtr

max_stars_repo_name: bitbouncer/qtr

max_issues_repo_name: bitbouncer/qtr

max_forks_repo_name: bitbouncer/qtr


text:
#ifndef SHIFT_SERIALIZATION_TYPES_HPP
#define SHIFT_SERIALIZATION_TYPES_HPP

#include <cstdint>
#include <memory>
#include <shift/core/exception.hpp>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/endian/conversion.hpp>
#include <shift/core/boost_restore_warnings.hpp>

namespace shift::serialization
{
using SerializationErrorInfo =
  boost::error_info<struct TagSerializationErrorInfo, std::string>;

/// An exception type used to report (de-)serialization errors.
struct SerializationError : virtual core::runtime_error
{
};

using protocol_version_t = std::uint32_t;
using message_uid_t = std::uint32_t;

class message;

template <typename Stream, boost::endian::order Order>
class archive;

template <boost::endian::order Order = boost::endian::order::native>
class compact_input_archive;

template <boost::endian::order Order = boost::endian::order::native>
class compact_output_archive;
}

#endif

ext: hpp

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
#pragma once

#include <golos/protocol/authority.hpp>
#include <golos/protocol/operations.hpp>
#include <golos/protocol/steem_operations.hpp>

#include <chainbase/chainbase.hpp>

#include <golos/chain/index.hpp>
#include <golos/chain/steem_object_types.hpp>

#include <boost/multi_index/composite_key.hpp>

//
// Plugins should #define their SPACE_ID's so plugins with
// conflicting SPACE_ID assignments can be compiled into the
// same binary (by simply re-assigning some of the conflicting #defined
// SPACE_ID's in a build script).
//
// Assignment of SPACE_ID's cannot be done at run-time because
// various template automagic depends on them being known at compile
// time.
//

#ifndef OPERATION_HISTORY_SPACE_ID
#define OPERATION_HISTORY_SPACE_ID 14
#endif

namespace golos { namespace plugins { namespace operation_history {

    enum account_object_types {
        operation_object_type = (OPERATION_HISTORY_SPACE_ID << 8),
    };

    using namespace golos::chain;
    using namespace chainbase;

    class operation_object final: public object<operation_object_type, operation_object> {
    public:
        operation_object() = delete;

        template<typename Constructor, typename Allocator>
        operation_object(Constructor &&c, allocator <Allocator> a)
            : serialized_op(a.get_segment_manager()) {
            c(*this);
        }

        id_type id;

        transaction_id_type trx_id;
        uint32_t block = 0;
        uint32_t trx_in_block = 0;
        uint16_t op_in_trx = 0;
        uint32_t virtual_op = 0;
        time_point_sec timestamp;
        buffer_type serialized_op;
    };

    using operation_id_type = object_id<operation_object>;

    struct by_location;
    struct by_transaction_id;
    using operation_index = multi_index_container<
        operation_object,
        indexed_by<
            ordered_unique<
                tag<by_id>,
                member<operation_object, operation_id_type, &operation_object::id>>,
            ordered_unique<
                tag<by_location>,
                composite_key<
                    operation_object,
                    member<operation_object, uint32_t, &operation_object::block>,
                    member<operation_object, uint32_t, &operation_object::trx_in_block>,
                    member<operation_object, uint16_t, &operation_object::op_in_trx>,
                    member<operation_object, uint32_t, &operation_object::virtual_op>,
                    member<operation_object, operation_id_type, &operation_object::id>>>,
            ordered_unique<
                tag<by_transaction_id>,
                composite_key<
                    operation_object,
                    member<operation_object, transaction_id_type, &operation_object::trx_id>,
                    member<operation_object, operation_id_type, &operation_object::id>>>>,
        allocator<operation_object>>;

} } } // golos::plugins::operation_history

CHAINBASE_SET_INDEX_TYPE(
    golos::plugins::operation_history::operation_object,
    golos::plugins::operation_history::operation_index)

max_stars_repo_name: rusladder/LadderChain

max_issues_repo_name: rusladder/LadderChain

max_forks_repo_name: rusladder/LadderChain


text:
/*!
@file
Defines `boost::hana::replace`.

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

#ifndef BOOST_HANA_REPLACE_HPP
#define BOOST_HANA_REPLACE_HPP

#include <boost/hana/fwd/replace.hpp>

#include <boost/hana/concept/functor.hpp>
#include <boost/hana/config.hpp>
#include <boost/hana/core/dispatch.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/replace_if.hpp>

BOOST_HANA_NAMESPACE_BEGIN
    //! @cond
    template <typename Xs, typename OldVal, typename NewVal>
    constexpr auto replace_t::operator()(Xs&& xs, OldVal&& oldval, NewVal&& newval) const {
        using S = typename hana::tag_of<Xs>::type;
        using Replace = BOOST_HANA_DISPATCH_IF(replace_impl<S>,
            hana::Functor<S>::value
        );

    #ifndef BOOST_HANA_CONFIG_DISABLE_CONCEPT_CHECKS
        static_assert(hana::Functor<S>::value,
        "hana::replace(xs, oldval, newval) requires 'xs' to be a Functor");
    #endif

        return Replace::apply(static_cast<Xs&&>(xs),
                              static_cast<OldVal&&>(oldval),
                              static_cast<NewVal&&>(newval));
    }
    //! @endcond

    template <typename Fun, bool condition>
    struct replace_impl<Fun, when<condition>> : default_ {
        template <typename Xs, typename OldVal, typename NewVal>
        static constexpr decltype(auto)
        apply(Xs&& xs, OldVal&& oldval, NewVal&& newval) {
            return hana::replace_if(
                static_cast<Xs&&>(xs),
                hana::equal.to(static_cast<OldVal&&>(oldval)),
                static_cast<NewVal&&>(newval)
            );
        }
    };
BOOST_HANA_NAMESPACE_END

#endif // !BOOST_HANA_REPLACE_HPP

max_stars_repo_name: rudylee/expo

max_issues_repo_name: rudylee/expo

max_forks_repo_name: rudylee/expo