text:
#include <iostream>
#ifdef _MSC_VER
#include <boost/cstdint.hpp>
#include <fcntl.h>
#include <io.h>
#else
#include <inttypes.h>
#endif
#include <string>
#include <cstring>
#include <cstdlib>
//#define NDEBUG
#include <cassert>
using namespace std;

#include <boost/tokenizer.hpp>
#include <boost/static_assert.hpp>
using namespace boost;

#ifdef _MSC_VER
namespace
{
inline long long atoll(const char* s)
{
    return _strtoi64(s, 0, 10);
}
inline uint64_t strtoull(const char* s, char** a, int b)
{
    return _strtoi64(s, a, b);
}
}
#endif

//1|155190|7706|1|17|21168.23|0.04|0.02|N|O|1996-03-13|1996-02-12|1996-03-22|DELIVER IN PERSON|TRUCK|egular courts above the|

#pragma pack(1)
struct lineitem_image
{
    int32_t l_orderkey;
    int32_t l_partkey;
    int32_t l_suppkey;             //12
    int64_t l_linenumber;
    int64_t l_quantity;
    int64_t l_extendedprice;
    int64_t l_discount;
    int64_t l_tax;                //40
    char l_returnflag;
    char l_linestatus;            //2
    int32_t l_shipdate;
    int32_t l_commitdate;
    int32_t l_receiptdate;        //12
    char l_shipinstruct[25];
    char l_shipmode[10];
    char l_comment[44];           //79
};
BOOST_STATIC_ASSERT(sizeof(struct lineitem_image) == 145);

// version of lineitem_image that treats some integer columns as unsigned ints.
// Decimal, date, and date/time columns are still treated as integer.
struct unsigned_lineitem_image
{
    uint32_t l_orderkey;
    uint32_t l_partkey;
    uint32_t l_suppkey;           //12
    uint64_t l_linenumber;
    int64_t  l_quantity;
    int64_t  l_extendedprice;
    int64_t  l_discount;
    int64_t  l_tax;               //40
    char     l_returnflag;
    char     l_linestatus;        //2
    int32_t  l_shipdate;
    int32_t  l_commitdate;
    int32_t  l_receiptdate;       //12
    char     l_shipinstruct[25];
    char     l_shipmode[10];
    char     l_comment[44];       //79
};
BOOST_STATIC_ASSERT(sizeof(struct unsigned_lineitem_image) == 145);

struct Date
{
    unsigned spare  : 6;
    unsigned day    : 6;
    unsigned month  : 4;
    unsigned year   : 16;
};
BOOST_STATIC_ASSERT(sizeof(struct Date) == 4);

union date_image
{
    struct Date d;
    int32_t i;
};

namespace
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

int64_t idbbigdec2(const string& str)
{
    int64_t val = 0;
    string::size_type idx = string::npos;
    string tmp(str);
    idx = tmp.find('.');

    if (idx != string::npos)
        tmp.erase(idx, 1);
    else
        tmp.append("00");

    val = atoll(tmp.c_str());
    return val;
}

int32_t idbdate(const string& str)
{
    date_image di;
    di.i = 0;
    boost::char_separator<char> sep("-");
    tokenizer tokens(str, sep);
    tokenizer::iterator tok_iter = tokens.begin();

    // Note that the spare bits must be set, instead of leaving them
    // initialized to 0; to be compatible with internal date format.
    if (distance(tok_iter, tokens.end()) == 3)
    {
        di.d.spare = 0x3E;
        di.d.year = atoi(tok_iter->c_str());
        ++tok_iter;
        di.d.month = atoi(tok_iter->c_str());
        ++tok_iter;
        di.d.day = atoi(tok_iter->c_str());
        ++tok_iter;
    }

    return di.i;
}

int parseinto(lineitem_image& img, const string& buf)
{
    memset(&img, 0, sizeof(img));

    boost::char_separator<char> sep("|");
    tokenizer tokens(buf, sep);
    tokenizer::iterator tok_iter = tokens.begin();

    if (distance(tok_iter, tokens.end()) < 16)
        return -1;

    img.l_orderkey = atoi(tok_iter->c_str());
    ++tok_iter;
    img.l_partkey = atoi(tok_iter->c_str());
    ++tok_iter;
    img.l_suppkey = atoi(tok_iter->c_str());
    ++tok_iter;
    img.l_linenumber = atoll(tok_iter->c_str());
    ++tok_iter;
    img.l_quantity = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_extendedprice = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_discount = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_tax = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_returnflag = tok_iter->at(0);
    ++tok_iter;
    img.l_linestatus = tok_iter->at(0);
    ++tok_iter;
    img.l_shipdate = idbdate(tok_iter->c_str());
    ++tok_iter;
    img.l_commitdate = idbdate(tok_iter->c_str());
    ++tok_iter;
    img.l_receiptdate = idbdate(tok_iter->c_str());
    ++tok_iter;
    memcpy(&img.l_shipinstruct[0], tok_iter->c_str(), tok_iter->size());
    ++tok_iter;
    memcpy(&img.l_shipmode[0], tok_iter->c_str(), tok_iter->size());
    ++tok_iter;
    memcpy(&img.l_comment[0], tok_iter->c_str(), tok_iter->size());
    ++tok_iter;

    return 0;
}

int unsigned_parseinto(unsigned_lineitem_image& img, const string& buf)
{
    memset(&img, 0, sizeof(img));

    boost::char_separator<char> sep("|");
    tokenizer tokens(buf, sep);
    tokenizer::iterator tok_iter = tokens.begin();

    if (distance(tok_iter, tokens.end()) < 16)
        return -1;

    img.l_orderkey      = strtoul(tok_iter->c_str(), 0, 10);
    ++tok_iter;
    img.l_partkey       = strtoul(tok_iter->c_str(), 0, 10);
    ++tok_iter;
    img.l_suppkey       = strtoul(tok_iter->c_str(), 0, 10);
    ++tok_iter;
    img.l_linenumber    = strtoull(tok_iter->c_str(), 0, 10);
    ++tok_iter;
    img.l_quantity      = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_extendedprice = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_discount      = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_tax           = idbbigdec2(tok_iter->c_str());
    ++tok_iter;
    img.l_returnflag    = tok_iter->at(0);
    ++tok_iter;
    img.l_linestatus    = tok_iter->at(0);
    ++tok_iter;
    img.l_shipdate      = idbdate(tok_iter->c_str());
    ++tok_iter;
    img.l_commitdate    = idbdate(tok_iter->c_str());
    ++tok_iter;
    img.l_receiptdate   = idbdate(tok_iter->c_str());
    ++tok_iter;
    memcpy(&img.l_shipinstruct[0], tok_iter->c_str(), tok_iter->size());
    ++tok_iter;
    memcpy(&img.l_shipmode[0], tok_iter->c_str(), tok_iter->size());
    ++tok_iter;
    memcpy(&img.l_comment[0], tok_iter->c_str(), tok_iter->size());
    ++tok_iter;

    return 0;
}

}

int main(int argc, char** argv)
{
    if ((argc > 1) && (strcmp(argv[1], "-h") == 0))
    {
        std::cerr << "li2bin [-u]" << std::endl;
        std::cerr << "  -u Create first 4 fields as unsigned integers" << std::endl;
        return 0;
    }

    string input;

#ifdef _MSC_VER
    _setmode(1, _O_BINARY);
#endif

    getline(cin, input);

    if ((argc > 1) && (strcmp(argv[1], "-u") == 0))
    {
        unsigned_lineitem_image i;

        while (!cin.eof())
        {
            if (unsigned_parseinto(i, input) == 0)
                cout.write(reinterpret_cast<const char*>(&i), sizeof(i));

            getline(cin, input);
        }
    }
    else
    {
        lineitem_image i;

        while (!cin.eof())
        {
            if (parseinto(i, input) == 0)
                cout.write(reinterpret_cast<const char*>(&i), sizeof(i));

            getline(cin, input);
        }
    }

    return 0;
}
// vim:ts=4 sw=4:

max_stars_repo_name: zettadb/zettalib

max_issues_repo_name: zettadb/zettalib

max_forks_repo_name: zettadb/zettalib


text:
/* ----------------------------------------------------------------------------

 * GTSAM Copyright 2010-2019, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

 * -------------------------------------------------------------------------- */

/**
 * testPowerMethod.cpp
 *
 * @file   testPowerMethod.cpp
 * @date   Sept 2020
 * @author Jing Wu
 * @brief  Check eigenvalue and eigenvector computed by power method
 */

#include <CppUnitLite/TestHarness.h>
#include <gtsam/base/Matrix.h>
#include <gtsam/base/VectorSpace.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/linear/GaussianFactorGraph.h>
#include <gtsam/linear/PowerMethod.h>
#include <gtsam/linear/tests/powerMethodExample.h>

#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Eigenvalues>
#include <iostream>
#include <random>

using namespace std;
using namespace gtsam;

/* ************************************************************************* */
TEST(PowerMethod, powerIteration) {
  // test power iteration, beta is set to 0
  Sparse A(6, 6);
  A.coeffRef(0, 0) = 6;
  A.coeffRef(1, 1) = 5;
  A.coeffRef(2, 2) = 4;
  A.coeffRef(3, 3) = 3;
  A.coeffRef(4, 4) = 2;
  A.coeffRef(5, 5) = 1;
  Vector initial = (Vector(6) << 0.24434602, 0.22829942, 0.70094486, 0.15463092, 0.55871359,
       0.2465342).finished();
  PowerMethod<Sparse> pf(A, initial);
  pf.compute(100, 1e-5);
  EXPECT_LONGS_EQUAL(6, pf.eigenvector().rows());

  Vector6 actual1 = pf.eigenvector();
  const double ritzValue = actual1.dot(A * actual1);
  const double ritzResidual = (A * actual1 - ritzValue * actual1).norm();
  EXPECT_DOUBLES_EQUAL(0, ritzResidual, 1e-5);

  const double ev1 = 6.0;
  EXPECT_DOUBLES_EQUAL(ev1, pf.eigenvalue(), 1e-5);
}

/* ************************************************************************* */
TEST(PowerMethod, useFactorGraphSparse) {
  // Let's make a scalar synchronization graph with 4 nodes
  GaussianFactorGraph fg = gtsam::linear::test::example::createSparseGraph();

  // Get eigenvalues and eigenvectors with Eigen
  auto L = fg.hessian();
  Eigen::EigenSolver<Matrix> solver(L.first);

  // find the index of the max eigenvalue
  size_t maxIdx = 0;
  for (auto i = 0; i < solver.eigenvalues().rows(); ++i) {
    if (solver.eigenvalues()(i).real() >= solver.eigenvalues()(maxIdx).real())
      maxIdx = i;
  }
  // Store the max eigenvalue and its according eigenvector
  const auto ev1 = solver.eigenvalues()(maxIdx).real();

  Vector initial = Vector4::Random();
  PowerMethod<Matrix> pf(L.first, initial);
  pf.compute(100, 1e-5);
  EXPECT_DOUBLES_EQUAL(ev1, pf.eigenvalue(), 1e-8);
  auto actual2 = pf.eigenvector();
  const double ritzValue = actual2.dot(L.first * actual2);
  const double ritzResidual = (L.first * actual2 - ritzValue * actual2).norm();
  EXPECT_DOUBLES_EQUAL(0, ritzResidual, 1e-5);
}

/* ************************************************************************* */
TEST(PowerMethod, useFactorGraphDense) {
  // Let's make a scalar synchronization graph with 10 nodes
  GaussianFactorGraph fg = gtsam::linear::test::example::createDenseGraph();

  // Get eigenvalues and eigenvectors with Eigen
  auto L = fg.hessian();
  Eigen::EigenSolver<Matrix> solver(L.first);

  // find the index of the max eigenvalue
  size_t maxIdx = 0;
  for (auto i = 0; i < solver.eigenvalues().rows(); ++i) {
    if (solver.eigenvalues()(i).real() >= solver.eigenvalues()(maxIdx).real())
      maxIdx = i;
  }
  // Store the max eigenvalue and its according eigenvector
  const auto ev1 = solver.eigenvalues()(maxIdx).real();

  Vector initial = Vector10::Random();
  PowerMethod<Matrix> pf(L.first, initial);
  pf.compute(100, 1e-5);
  EXPECT_DOUBLES_EQUAL(ev1, pf.eigenvalue(), 1e-8);
  auto actual2 = pf.eigenvector();
  const double ritzValue = actual2.dot(L.first * actual2);
  const double ritzResidual = (L.first * actual2 - ritzValue * actual2).norm();
  EXPECT_DOUBLES_EQUAL(0, ritzResidual, 1e-5);
}

/* ************************************************************************* */
int main() {
  TestResult tr;
  return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */

ext: cpp


text:
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <sdbusplus/asio/connection.hpp>
#include <sdbusplus/asio/object_server.hpp>
#include <sdbusplus/asio/sd_event.hpp>
#include <sdbusplus/bus.hpp>
#include <sdbusplus/exception.hpp>
#include <sdbusplus/server.hpp>
#include <sdbusplus/timer.hpp>

#include <chrono>
#include <ctime>
#include <iostream>
#include <variant>

using variant = std::variant<int, std::string>;

int foo(int test)
{
    std::cout << "foo(" << test << ") -> " << (test + 1) << "\n";
    return ++test;
}

// called from coroutine context, can make yielding dbus calls
int fooYield(boost::asio::yield_context yield,
             std::shared_ptr<sdbusplus::asio::connection> conn, int test)
{
    // fetch the real value from testFunction
    boost::system::error_code ec;
    std::cout << "fooYield(yield, " << test << ")...\n";
    int testCount = conn->yield_method_call<int>(
        yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "xyz.openbmc_project.test", "TestFunction", test);
    if (ec || testCount != (test + 1))
    {
        std::cout << "call to foo failed: ec = " << ec << '\n';
        return -1;
    }
    std::cout << "yielding call to foo OK! (-> " << testCount << ")\n";
    return testCount;
}

int methodWithMessage(sdbusplus::message::message& /*m*/, int test)
{
    std::cout << "methodWithMessage(m, " << test << ") -> " << (test + 1)
              << "\n";
    return ++test;
}

int voidBar(void)
{
    std::cout << "voidBar() -> 42\n";
    return 42;
}

void do_start_async_method_call_one(
    std::shared_ptr<sdbusplus::asio::connection> conn,
    boost::asio::yield_context yield)
{
    boost::system::error_code ec;
    variant testValue;
    conn->yield_method_call<>(yield, ec, "xyz.openbmc_project.asio-test",
                              "/xyz/openbmc_project/test",
                              "org.freedesktop.DBus.Properties", "Set",
                              "xyz.openbmc_project.test", "int", variant(24));
    testValue = conn->yield_method_call<variant>(
        yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.test",
        "int");
    if (!ec && std::get<int>(testValue) == 24)
    {
        std::cout << "async call to Properties.Get serialized via yield OK!\n";
    }
    else
    {
        std::cout << "ec = " << ec << ": " << std::get<int>(testValue) << "\n";
    }
    conn->yield_method_call<void>(
        yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "org.freedesktop.DBus.Properties", "Set", "xyz.openbmc_project.test",
        "int", variant(42));
    testValue = conn->yield_method_call<variant>(
        yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "org.freedesktop.DBus.Properties", "Get", "xyz.openbmc_project.test",
        "int");
    if (!ec && std::get<int>(testValue) == 42)
    {
        std::cout << "async call to Properties.Get serialized via yield OK!\n";
    }
    else
    {
        std::cout << "ec = " << ec << ": " << std::get<int>(testValue) << "\n";
    }
}

void do_start_async_ipmi_call(std::shared_ptr<sdbusplus::asio::connection> conn,
                              boost::asio::yield_context yield)
{
    auto method = conn->new_method_call("xyz.openbmc_project.asio-test",
                                        "/xyz/openbmc_project/test",
                                        "xyz.openbmc_project.test", "execute");
    constexpr uint8_t netFn = 6;
    constexpr uint8_t lun = 0;
    constexpr uint8_t cmd = 1;
    std::map<std::string, variant> options = {{"username", variant("admin")},
                                              {"privilege", variant(4)}};
    std::vector<uint8_t> commandData = {4, 3, 2, 1};
    method.append(netFn, lun, cmd, commandData, options);
    boost::system::error_code ec;
    sdbusplus::message::message reply = conn->async_send(method, yield[ec]);
    std::tuple<uint8_t, uint8_t, uint8_t, uint8_t, std::vector<uint8_t>>
        tupleOut;
    try
    {
        reply.read(tupleOut);
    }
    catch (const sdbusplus::exception::SdBusError& e)
    {
        std::cerr << "failed to unpack; sig is " << reply.get_signature()
                  << "\n";
    }
    auto& [rnetFn, rlun, rcmd, cc, responseData] = tupleOut;
    std::vector<uint8_t> expRsp = {1, 2, 3, 4};
    if (rnetFn == uint8_t(netFn + 1) && rlun == lun && rcmd == cmd && cc == 0 &&
        responseData == expRsp)
    {
        std::cerr << "ipmi call returns OK!\n";
    }
    else
    {
        std::cerr << "ipmi call returns unexpected response\n";
    }
}

auto ipmiInterface(boost::asio::yield_context /*yield*/, uint8_t netFn,
                   uint8_t lun, uint8_t cmd, std::vector<uint8_t>& /*data*/,
                   const std::map<std::string, variant>& /*options*/)
{
    std::vector<uint8_t> reply = {1, 2, 3, 4};
    uint8_t cc = 0;
    std::cerr << "ipmiInterface:execute(" << int(netFn) << int(cmd) << ")\n";
    return std::make_tuple(uint8_t(netFn + 1), lun, cmd, cc, reply);
}

void do_start_async_to_yield(std::shared_ptr<sdbusplus::asio::connection> conn,
                             boost::asio::yield_context yield)
{
    boost::system::error_code ec;
    int testValue = 0;
    testValue = conn->yield_method_call<int>(
        yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "xyz.openbmc_project.test", "TestYieldFunction", int(41));

    if (!ec && testValue == 42)
    {
        std::cout
            << "yielding call to TestYieldFunction serialized via yield OK!\n";
    }
    else
    {
        std::cout << "ec = " << ec << ": " << testValue << "\n";
    }

    ec.clear();
    auto badValue = conn->yield_method_call<std::string>(
        yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "xyz.openbmc_project.test", "TestYieldFunction", int(41));

    if (!ec)
    {
        std::cout
            << "yielding call to TestYieldFunction returned the wrong type\n";
    }
    else
    {
        std::cout << "TestYieldFunction expected error: " << ec << "\n";
    }

    ec.clear();
    auto unUsedValue = conn->yield_method_call<std::string>(
        yield, ec, "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "xyz.openbmc_project.test", "TestYieldFunctionNotExits", int(41));

    if (!ec)
    {
        std::cout << "TestYieldFunctionNotExists returned unexpectedly\n";
    }
    else
    {
        std::cout << "TestYieldFunctionNotExits expected error: " << ec << "\n";
    }
}

int server()
{
    // setup connection to dbus
    boost::asio::io_context io;
    auto conn = std::make_shared<sdbusplus::asio::connection>(io);

    // test object server
    conn->request_name("xyz.openbmc_project.asio-test");
    auto server = sdbusplus::asio::object_server(conn);
    std::shared_ptr<sdbusplus::asio::dbus_interface> iface =
        server.add_interface("/xyz/openbmc_project/test",
                             "xyz.openbmc_project.test");
    // test generic properties
    iface->register_property("int", 33,
                             sdbusplus::asio::PropertyPermission::readWrite);
    std::vector<std::string> myStringVec = {"some", "test", "data"};
    std::vector<std::string> myStringVec2 = {"more", "test", "data"};

    iface->register_property("myStringVec", myStringVec,
                             sdbusplus::asio::PropertyPermission::readWrite);
    iface->register_property("myStringVec2", myStringVec2);

    // test properties with specialized callbacks
    iface->register_property("lessThan50", 23,
                             // custom set
                             [](const int& req, int& propertyValue) {
                                 if (req >= 50)
                                 {
                                     return -EINVAL;
                                 }
                                 propertyValue = req;
                                 return 1; // success
                             });
    iface->register_property(
        "TrailTime", std::string("foo"),
        // custom set
        [](const std::string& req, std::string& propertyValue) {
            propertyValue = req;
            return 1; // success
        },
        // custom get
        [](const std::string& property) {
            auto now = std::chrono::system_clock::now();
            auto timePoint = std::chrono::system_clock::to_time_t(now);
            return property + std::ctime(&timePoint);
        });

    // test method creation
    iface->register_method("TestMethod", [](const int32_t& callCount) {
        return std::make_tuple(callCount,
                               "success: " + std::to_string(callCount));
    });

    iface->register_method("TestFunction", foo);

    // fooYield has boost::asio::yield_context as first argument
    // so will be executed in coroutine context if called
    iface->register_method("TestYieldFunction",
                           [conn](boost::asio::yield_context yield, int val) {
                               return fooYield(yield, conn, val);
                           });

    iface->register_method("TestMethodWithMessage", methodWithMessage);

    iface->register_method("VoidFunctionReturnsInt", voidBar);

    iface->register_method("execute", ipmiInterface);

    iface->initialize();

    io.run();

    return 0;
}

int client()
{
    using GetSubTreeType = std::vector<std::pair<
        std::string,
        std::vector<std::pair<std::string, std::vector<std::string>>>>>;
    using message = sdbusplus::message::message;

    // setup connection to dbus
    boost::asio::io_context io;
    auto conn = std::make_shared<sdbusplus::asio::connection>(io);

    int ready = 0;
    while (!ready)
    {
        auto readyMsg = conn->new_method_call(
            "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
            "xyz.openbmc_project.test", "VoidFunctionReturnsInt");
        try
        {
            message intMsg = conn->call(readyMsg);
            intMsg.read(ready);
        }
        catch (sdbusplus::exception::SdBusError& e)
        {
            ready = 0;
            // pause to give the server a chance to start up
            usleep(10000);
        }
    }

    // test async method call and async send
    auto mesg =
        conn->new_method_call("xyz.openbmc_project.ObjectMapper",
                              "/xyz/openbmc_project/object_mapper",
                              "xyz.openbmc_project.ObjectMapper", "GetSubTree");

    static const auto depth = 2;
    static const std::vector<std::string> interfaces = {
        "xyz.openbmc_project.Sensor.Value"};
    mesg.append("/xyz/openbmc_project/Sensors", depth, interfaces);

    conn->async_send(mesg, [](boost::system::error_code ec, message& ret) {
        std::cout << "async_send callback\n";
        if (ec || ret.is_method_error())
        {
            std::cerr << "error with async_send\n";
            return;
        }
        GetSubTreeType data;
        ret.read(data);
        for (auto& item : data)
        {
            std::cout << item.first << "\n";
        }
    });

    conn->async_method_call(
        [](boost::system::error_code ec, GetSubTreeType& subtree) {
            std::cout << "async_method_call callback\n";
            if (ec)
            {
                std::cerr << "error with async_method_call\n";
                return;
            }
            for (auto& item : subtree)
            {
                std::cout << item.first << "\n";
            }
        },
        "xyz.openbmc_project.ObjectMapper",
        "/xyz/openbmc_project/object_mapper",
        "xyz.openbmc_project.ObjectMapper", "GetSubTree",
        "/org/openbmc/control", 2, std::vector<std::string>());

    std::string nonConstCapture = "lalalala";
    conn->async_method_call(
        [nonConstCapture = std::move(nonConstCapture)](
            boost::system::error_code ec,
            const std::vector<std::string>& /*things*/) mutable {
            std::cout << "async_method_call callback\n";
            nonConstCapture += " stuff";
            if (ec)
            {
                std::cerr << "async_method_call expected failure: " << ec
                          << "\n";
            }
            else
            {
                std::cerr << "async_method_call should have failed!\n";
            }
        },
        "xyz.openbmc_project.ObjectMapper",
        "/xyz/openbmc_project/object_mapper",
        "xyz.openbmc_project.ObjectMapper", "GetSubTree",
        "/xyz/openbmc_project/sensors", depth, interfaces);

    // sd_events work too using the default event loop
    phosphor::Timer t1([]() { std::cerr << "*** tock ***\n"; });
    t1.start(std::chrono::microseconds(1000000));
    phosphor::Timer t2([]() { std::cerr << "*** tick ***\n"; });
    t2.start(std::chrono::microseconds(500000), true);
    // add the sd_event wrapper to the io object
    sdbusplus::asio::sd_event_wrapper sdEvents(io);

    // set up a client to make an async call to the server
    // using coroutines (userspace cooperative multitasking)
    boost::asio::spawn(io, [conn](boost::asio::yield_context yield) {
        do_start_async_method_call_one(conn, yield);
    });
    boost::asio::spawn(io, [conn](boost::asio::yield_context yield) {
        do_start_async_ipmi_call(conn, yield);
    });
    boost::asio::spawn(io, [conn](boost::asio::yield_context yield) {
        do_start_async_to_yield(conn, yield);
    });

    conn->async_method_call(
        [](boost::system::error_code ec, int32_t testValue) {
            if (ec)
            {
                std::cerr << "TestYieldFunction returned error with "
                             "async_method_call (ec = "
                          << ec << ")\n";
                return;
            }
            std::cout << "TestYieldFunction return " << testValue << "\n";
        },
        "xyz.openbmc_project.asio-test", "/xyz/openbmc_project/test",
        "xyz.openbmc_project.test", "TestYieldFunction", int32_t(41));
    io.run();

    return 0;
}

int main(int argc, const char* argv[])
{
    if (argc == 1)
    {
        int pid = fork();
        if (pid == 0)
        {
            return client();
        }
        else if (pid > 0)
        {
            return server();
        }
        return pid;
    }
    if (std::string(argv[1]) == "--server")
    {
        return server();
    }
    if (std::string(argv[1]) == "--client")
    {
        return client();
    }
    std::cout << "usage: " << argv[0] << " [--server | --client]\n";
    return -1;
}

max_stars_repo_name: mkaranki/sdbusplus

max_issues_repo_name: mkaranki/sdbusplus

max_forks_repo_name: mkaranki/sdbusplus


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

#include <boost/hana/assert.hpp>
#include <boost/hana/drop_front.hpp>
#include <boost/hana/drop_while.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/ext/boost/mpl/list.hpp>
#include <boost/hana/ext/std/integral_constant.hpp>
#include <boost/hana/front.hpp>
#include <boost/hana/type.hpp>

#include <boost/mpl/list.hpp>
#include <type_traits>
namespace hana = boost::hana;
namespace mpl = boost::mpl;

BOOST_HANA_CONSTANT_CHECK(hana::front(mpl::list<int, char, void>{}) == hana::type_c<int>);

BOOST_HANA_CONSTANT_CHECK(hana::equal(
    hana::drop_front(mpl::list<int, char, void>{}),
    mpl::list<char, void>{}
));

BOOST_HANA_CONSTANT_CHECK(hana::equal(
    hana::drop_while(mpl::list<float, double const, int, float&>{},
                     hana::trait<std::is_floating_point>),
    mpl::list<int, float&>{}
));

int main() { }


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

#ifndef GLASGOW_SUBGRAPH_SOLVER_TEMPLATE_VOODOO_HH
#define GLASGOW_SUBGRAPH_SOLVER_TEMPLATE_VOODOO_HH 1

#include "fixed_bit_set.hh"

#include <array>
#include <type_traits>
#include <utility>
#include <vector>

#include <boost/dynamic_bitset.hpp>

template <template <typename, typename> class Algorithm_, typename Result_, typename Graph_, unsigned size_, unsigned... other_sizes_, typename... Params_>
auto select_graph_size(const std::integer_sequence<unsigned, size_, other_sizes_...> &, const Graph_ & graph, Params_ && ... params) -> Result_
{
    if (graph.size() < int(size_ * bits_per_word)) {
        Algorithm_<FixedBitSet<size_>, std::array<int, size_ * bits_per_word + 1> > algorithm{ graph, std::forward<Params_>(params)... };
        return algorithm.run();
    }
    else {
        if constexpr (0 == sizeof...(other_sizes_)) {
            Algorithm_<boost::dynamic_bitset<>, std::vector<int> > algorithm{ graph, std::forward<Params_>(params)... };
            return algorithm.run();
        }
        else
            return select_graph_size<Algorithm_, Result_, Graph_>(std::integer_sequence<unsigned, other_sizes_...>{}, graph, std::forward<Params_>(params)...);
    }
}

using AllGraphSizes = std::integer_sequence<unsigned, 1, 2, 3, 4, 5, 6, 7, 8, 16, 20, 24, 28, 32, 64, 128, 256, 512, 1024>;

#endif

ext: hh

max_stars_repo_name: KyleBurns/bigraph-stuff

max_issues_repo_name: KyleBurns/bigraph-stuff

max_forks_repo_name: KyleBurns/bigraph-stuff


text:
//! \file examples/Arrangement_on_surface_2/overlay_unbounded.cpp
// A face overlay of two arrangements with unbounded faces.

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

#include <CGAL/basic.h>
#include <CGAL/Arr_extended_dcel.h>
#include <CGAL/Arr_overlay_2.h>
#include <CGAL/Arr_default_overlay_traits.h>

#include "arr_linear.h"

// Define a functor for creating a label from a characer and an integer.
struct Overlay_label {
  std::string operator()(char c, unsigned int i) const
  { return c + boost::lexical_cast<std::string>(i); }
};

typedef CGAL::Arr_face_extended_dcel<Traits, char>         Dcel_dlue;
typedef CGAL::Arrangement_2<Traits, Dcel_dlue>             Arrangement_blue;
typedef CGAL::Arr_face_extended_dcel<Traits, unsigned int> Dcel_red;
typedef CGAL::Arrangement_2<Traits, Dcel_red>              Arrangement_red;
typedef CGAL::Arr_face_extended_dcel<Traits, std::string>  Dcel_res;
typedef CGAL::Arrangement_2<Traits, Dcel_res>              Arrangement_res;
typedef CGAL::Arr_face_overlay_traits<Arrangement_blue, Arrangement_red,
                                      Arrangement_res, Overlay_label>
                                                           Overlay_traits;

int main() {
  // Construct the first arrangement, induced by two lines y = x and y = -x.
  Arrangement_blue arr1;
  insert(arr1, Line(Point(0, 0), Point(1, 1)));
  insert(arr1, Line(Point(0, 0), Point(1, -1)));

  // Label the four (unbounded) faces of the arrangement as 'A' to 'D' by
  // traversing the faces incident to the halfedges around the single
  // arrangement vertex (0, 0).
  char clabel = 'A';
  auto first = arr1.vertices_begin()->incident_halfedges();
  auto curr = first;
  do curr->face()->set_data(clabel++);
  while (++curr != first);

  // Construct the second arrangement, containing a single square-shaped face.
  Arrangement_red arr2;
  insert_non_intersecting_curve(arr2, Segment(Point(-3, -3), Point(3, -3)));
  insert_non_intersecting_curve(arr2, Segment(Point(3, -3), Point(3, 3)));
  insert_non_intersecting_curve(arr2, Segment(Point(3, 3), Point(-3, 3)));
  insert_non_intersecting_curve(arr2, Segment(Point(-3, 3), Point(-3, -3)));

  // Give the unbounded face the index 1, and the bounded face the index 2.
  for (auto fit = arr2.faces_begin(); fit != arr2.faces_end(); ++fit)
    fit->set_data((fit == arr2.unbounded_face()) ? 1 : 2);

  // Compute the overlay of the two arrangements.
  Arrangement_res overlay_arr;
  Overlay_traits overlay_traits;
  CGAL::overlay(arr1, arr2, overlay_arr, overlay_traits);

  // Go over the faces of the overlay arrangement and print their labels.
  std::cout << "The overlay faces are:\n";
  for (auto res_fit = overlay_arr.faces_begin();
       res_fit != overlay_arr.faces_end(); ++res_fit)
  {
    std::cout << "  " << res_fit->data().c_str() << " ("
              << (res_fit->is_unbounded() ? "unbounded" : "bounded") << ").\n";
  }
  return 0;
}

max_stars_repo_name: ffteja/cgal

max_issues_repo_name: ffteja/cgal

max_forks_repo_name: ffteja/cgal


text:
#include "cpp_hw.hpp"
#include "ValueObjects/vo_hw.hpp"
#include "AddinObjects/obj_hw.hpp"
#include <boost/shared_ptr.hpp>
#include <oh/repository.hpp>

//#include "quantLibAddinTest.hpp"
//#include <oh/objecthandler.hpp>
#include <ql/math/comparison.hpp>
#include <ql/quotes/simplequote.hpp>

static ObjectHandler::Repository repository;

bool QuantLibAddin::qlClose(double x, double y) {
    return QuantLib::close(x, y);
}

std::string QuantLibAddin::qlSimpleQuote(const std::string &objectID, double Value) {
        boost::shared_ptr<ObjectHandler::ValueObject> valueObject(
            new QuantLibAddin::ValueObjects::qlSimpleQuote(
                objectID, Value, false));
        boost::shared_ptr<ObjectHandler::Object> object(
            new QuantLibAddin::SimpleQuote(
                valueObject, Value, false));
        std::string returnValue =
            ObjectHandler::Repository::instance().storeObject(
                objectID, object, false, valueObject);
        return returnValue;
}

double QuantLibAddin::qlSimpleQuoteValue(const std::string &objectID) {
    OH_GET_REFERENCE(x, objectID, QuantLibAddin::SimpleQuote, QuantLib::SimpleQuote);
    return x->value();
}

max_stars_repo_name: frannuca/quantlib

max_issues_repo_name: frannuca/quantlib

max_forks_repo_name: frannuca/quantlib


text:
/// @file
/// @copyright The code is licensed under the BSD License
///            <http://opensource.org/licenses/BSD-2-Clause>,
///            Copyright (c) 2013-2015 Alexandre Hamez.
/// @author Alexandre Hamez

#include <vector>

#include <boost/range/numeric.hpp>

#include "mc/classic/reachability_eval.hh"
#include "support/pn/types.hh"

namespace pnmc { namespace mc { namespace classic {

/*------------------------------------------------------------------------------------------------*/

using boost::accumulate;
using boost::apply_visitor;

namespace /* anonymous */ {

/*------------------------------------------------------------------------------------------------*/

struct integer_eval
{
  using result_type = int;
  const std::vector<pn::valuation_type>& values;

  result_type
  operator()(const integer_constant& e)
  const noexcept
  {
    return e.value;
  }

  result_type
  operator()(const integer_sum& e)
  const noexcept
  {
    return accumulate( e.expressions, 0
                     , [this](auto v, const auto& sub_e){return apply_visitor(*this, sub_e) + v;});
  }

  result_type
  operator()(const integer_product& e)
  const noexcept
  {
    return accumulate( e.expressions, 1
                     , [this](auto v, const auto& sub_e){return apply_visitor(*this, sub_e) * v;});
  }

  result_type
  operator()(const integer_difference& e)
  const noexcept
  {
    return apply_visitor(*this, e.lhs_expression) - apply_visitor(*this, e.rhs_expression);
  }

  result_type
  operator()(const integer_division& e)
  const noexcept
  {
    return apply_visitor(*this, e.lhs_expression) / apply_visitor(*this, e.rhs_expression);
  }

  result_type
  operator()(const integer_tokens&)
  const
  {
//    return values[e.pos];
    throw std::runtime_error(__PRETTY_FUNCTION__);
  }
};

/*------------------------------------------------------------------------------------------------*/

struct boolean_eval
{
  using result_type = bool;
  const integer_eval& integer;

  result_type
  operator()(const invariant&)
  const
  {
    throw std::runtime_error(__PRETTY_FUNCTION__);
  }

  result_type
  operator()(const possibility&)
  const
  {
    throw std::runtime_error(__PRETTY_FUNCTION__);
  }

  result_type
  operator()(const impossibility&)
  const
  {
    throw std::runtime_error(__PRETTY_FUNCTION__);
  }

  result_type
  operator()(const true_&)
  const
  {
    throw std::runtime_error(__PRETTY_FUNCTION__);
  }

  result_type
  operator()(const false_&)
  const
  {
    throw std::runtime_error(__PRETTY_FUNCTION__);
  }

  result_type
  operator()(const negation& e)
  const
  {
    return not apply_visitor(*this, e.expression);
  }

  result_type
  operator()(const conjunction& e)
  const
  {
    for (const auto& sub_e : e.expressions)
    {
      if (not apply_visitor(*this, sub_e))
      {
        return false;
      }
    }
    return true;
  }

  result_type
  operator()(const disjunction& e)
  const
  {
    for (const auto& sub_e : e.expressions)
    {
      if (apply_visitor(*this, sub_e))
      {
        return true;
      }
    }
    return false;
  }

  result_type
  operator()(const exclusive_disjonction& e)
  const
  {
    bool has_true = false;
    for (const auto& sub_e : e.expressions)
    {
      const auto tmp = apply_visitor(*this, sub_e);
      if      (tmp and not has_true) {has_true = true;}
      else if (tmp and has_true)     {return false;}
    }
    return has_true;
  }

  result_type
  operator()(const implication& e)
  const
  {
    return apply_visitor(*this, e.lhs_expression)
         ? apply_visitor(*this, e.rhs_expression)
         : true;
  }

  result_type
  operator()(const equivalence& e)
  const
  {
    return apply_visitor(*this, e.lhs_expression) == apply_visitor(*this, e.rhs_expression);
  }

  result_type
  operator()(const integer_eq& e)
  const noexcept
  {
    return apply_visitor(integer, e.lhs_expression) == apply_visitor(integer, e.rhs_expression);
  }

  result_type
  operator()(const integer_ne& e)
  const noexcept
  {
    return apply_visitor(integer, e.lhs_expression) != apply_visitor(integer, e.rhs_expression);
  }

  result_type
  operator()(const integer_lt& e)
  const noexcept
  {
    return apply_visitor(integer, e.lhs_expression) < apply_visitor(integer, e.rhs_expression);
  }

  result_type
  operator()(const integer_le& e)
  const noexcept
  {
    return apply_visitor(integer, e.lhs_expression) <= apply_visitor(integer, e.rhs_expression);
  }

  result_type
  operator()(const integer_gt& e)
  const noexcept
  {
    return apply_visitor(integer, e.lhs_expression) > apply_visitor(integer, e.rhs_expression);
  }

  result_type
  operator()(const integer_ge& e)
  const noexcept
  {
    return apply_visitor(integer, e.lhs_expression) >= apply_visitor(integer, e.rhs_expression);
  }
};

/*------------------------------------------------------------------------------------------------*/

} // namespace anonymous

/*------------------------------------------------------------------------------------------------*/

int
eval(const integer_ast& a, const SDD&)
{
  if (const auto* ptr = boost::get<integer_constant>(&a))
  {
    return ptr->value;
  }
  std::vector<pn::valuation_type> values;
  return apply_visitor(integer_eval{values}, a);
}

/*------------------------------------------------------------------------------------------------*/

bool
eval(const boolean_ast& a, const SDD&)
{
  if (boost::get<true_>(&a))
  {
    return true;
  }
  else if (boost::get<false_>(&a))
  {
    return false;
  }
  std::vector<pn::valuation_type> values;
  integer_eval integer{values};
  return apply_visitor(boolean_eval{integer}, a);
}

/*------------------------------------------------------------------------------------------------*/

}}} // namespace pnmc::mc::classic

ext: cc

max_stars_repo_name: ahamez/pnmc

max_issues_repo_name: ahamez/pnmc

max_forks_repo_name: ahamez/pnmc


text:
#pragma once

#include <armadillo>
#include <vector>
#include <functional>

#include "io/Writer.hpp"
#include "io/TextWriter.hpp"
#include "solid/Solid.hpp"
#include "solid/Box.hpp"
#include "sph/Particle.hpp"

#include "spdlog/spdlog.h"
using namespace spdlog;
using namespace arma;
using namespace std;

class Solver {
  public:
    Solver(double deltat_t,
           int number_frames,
           int steps_per_frame,
           double part_radius,
           Box domain);

    void addConstraint(Solid constraint);

    void append(shared_ptr<Particle> part);

    void go();
    void step(bool initial);
    VEC getDomainRange() { return domain.localRange();}
  private:
    double smoothing;
    double delta_t;
    int number_frames;
    int steps_per_frame;
    Box domain;
    TextWriter save;

    vector<shared_ptr<Particle>> listPart;
    vector<Solid> listConstraints;

    shared_ptr<logger> console = get("console");
};

ext: hpp

max_stars_repo_name: tychota/pje-sph

max_issues_repo_name: tychota/pje-sph

max_forks_repo_name: tychota/pje-sph


text:
#include <boost/lexical_cast.hpp>

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

#include <boost/foreach.hpp>

#include <iostream>
#include <fstream>

#include "Tools.h"

bool is_Float(std::string someString)
{
/*
  Input: A string
  Output: A boolean
  Function: Check if the string is a float value or not

  https://stackoverflow.com/questions/447206/c-isfloat-function
*/
  using boost::lexical_cast;
  using boost::bad_lexical_cast;

  try
  {
    boost::lexical_cast<float>(someString);
  }
  catch (bad_lexical_cast &)
  {
    return false;
  }

  return true;
}

Eigen::MatrixXd Populate_Transform(std::string fpath, std::string to_get)
{
/*
  Input: The path to the input text file, the transform within the text file to retrieve
  Output: An Eigen Matrix object of the transform
  Function: Populate an Eigen Matrix object with a transform from the provided text file
*/
  std::ifstream file_obj;
  std::string line, transform;

  std::vector<float> float_transform;

  file_obj.open(fpath);
  if (file_obj.is_open())
  {
    while (!file_obj.eof())
    {
      getline(file_obj, line);
      //if (line.find("Tr_velo_to_cam: ") != std::string::npos)
      if (line.find(to_get) != std::string::npos)
      {
        transform = line;
      }
    }
  }

  // https://stackoverflow.com/questions/5888022/split-string-by-single-spaces
  typedef std::vector<std::string> Tokens;
  Tokens tokens;
  boost::split( tokens, transform, boost::is_any_of(" ") );

  BOOST_FOREACH( const std::string& i, tokens )
  {
    if (is_Float(i))
    {
      float_transform.push_back(std::stof(i));
    }
  }

  if (to_get == "Tr_velo_to_cam: ")
  {
    Eigen::MatrixXd output(4,4);

    output(0,0) = float_transform[0];
    output(0,1) = float_transform[1];
    output(0,2) = float_transform[2];
    output(0,3) = float_transform[3];

    output(1,0) = float_transform[4];
    output(1,1) = float_transform[5];
    output(1,2) = float_transform[6];
    output(1,3) = float_transform[7];

    output(2,0) = float_transform[8];
    output(2,1) = float_transform[9];
    output(2,2) = float_transform[10];
    output(2,3) = float_transform[11];

    output(3,0) = 0;
    output(3,1) = 0;
    output(3,2) = 0;
    output(3,3) = 1;

    return output;
  }
  else if (to_get == "R0_rect: ")
  {
    Eigen::MatrixXd output(4,4);

    output(0,0) = float_transform[0];
    output(0,1) = float_transform[1];
    output(0,2) = float_transform[2];
    output(0,3) = 0;

    output(1,0) = float_transform[3];
    output(1,1) = float_transform[4];
    output(1,2) = float_transform[5];
    output(1,3) = 0;

    output(2,0) = float_transform[6];
    output(2,1) = float_transform[7];
    output(2,2) = float_transform[8];
    output(2,3) = 0;

    output(3,0) = 0;
    output(3,1) = 0;
    output(3,2) = 0;
    output(3,3) = 1;

    return output;
  }
  else
  {
    Eigen::MatrixXd output(3,4);

    output(0,0) = float_transform[0];
    output(0,1) = float_transform[1];
    output(0,2) = float_transform[2];
    output(0,3) = float_transform[3];

    output(1,0) = float_transform[4];
    output(1,1) = float_transform[5];
    output(1,2) = float_transform[6];
    output(1,3) = float_transform[7];

    output(2,0) = float_transform[8];
    output(2,1) = float_transform[9];
    output(2,2) = float_transform[10];
    output(2,3) = float_transform[11];

    return output;
  }
}

std::vector<std::vector<float> > Populate_Weights(std::string fpath)
{
/*
  Input: Filepath to the text file
  Output: Matrix in 2D vector form
  Function: Populate a 2D vector with floats
*/
  std::vector<std::vector<float> > output, transpose_output;

  std::ifstream file_obj;
  std::string line;

  std::vector<std::string> string_file;

  file_obj.open(fpath);
  if (file_obj.is_open())
  {
    while (!file_obj.eof())
    {
      getline(file_obj, line);
      string_file.push_back(line);
    }
  }

  // https://stackoverflow.com/questions/5888022/split-string-by-single-spaces
  std::vector<float> temp;
  for (size_t i = 0; i < string_file.size(); i++)
  {
    typedef std::vector<std::string> Tokens;
    Tokens tokens;
    boost::split( tokens, string_file[i], boost::is_any_of(" ") );

    BOOST_FOREACH( const std::string& j, tokens )
    {
      if (is_Float(j))
      {
        temp.push_back(boost::lexical_cast<float>(j));
      }
    }
    if (temp.size() != 0)
    {
      transpose_output.push_back(temp);
      temp.clear();
    }
  }

  temp.clear();
  for (int i = 0; i < transpose_output[0].size(); i++)
  {
    for (int j = 0; j < transpose_output.size(); j++)
    {
      temp.push_back(transpose_output[j][i]);
    }
    output.push_back(temp);
    temp.clear();
  }

  return output;
}

std::vector<float> Populate_Biases(std::string fpath)
{
/*
  Input: Filepath to the text file
  Output: Vector of values
  Function: Populate a vector with floats
*/
  std::vector<float> output;

  std::ifstream file_obj;
  std::string line;

  std::vector<std::string> string_file;

  file_obj.open(fpath);
  if (file_obj.is_open())
  {
    while (!file_obj.eof())
    {
      getline(file_obj, line);
      if (is_Float(line))
      {
        output.push_back(boost::lexical_cast<float>(line));
      }
    }
  }

  return output;
}

float* Columate_Matrix(std::vector<std::vector<float> > input)
{
/*
  Input: A 2D weight matrix
  Output: A pointer to an array
  Function: Populate an array in the mandatory column ordered form for CUBLAS
*/
  const int m = input.size();
  const int n = input[0].size();

  float *output = (float*)malloc(m * n * sizeof(float));

  int ind;
  for (int j = 0; j < n; j++)
  {
    for (int i = 0; i < m; i++)
    {
      ind = i + (m * j);
      output[ind] = input[i][j];
    }
  }

  return output;
}

float* Vectorize(std::vector<float> input)
{
/*
  Input: A bias vector
  Output: A pointer to an array
  Function: Populate an arry for CUBLAS
*/
  const int m = input.size();

  float *output = (float*)malloc(m * sizeof(float));

  for (int i = 0; i < m; i++)
  {
    output[i] = input[i];
  }

  return output;
}


text:
//////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2017 KDE Laboratory, University of Tsukuba, Tsukuba, Japan.            //
//                                                                                //
// The JsSpinnerSPE/StreamingCube and the accompanying materials are made available     //
// under the terms of Eclipse Public License v1.0 which accompanies this distribution   //
// and is available at <https://eclipse.org/org/documents/epl-v10.php>                  //
//////////////////////////////////////////////////////////////////////////////////////////

/*
 * RelationInput.cpp
 *
 *  Created on: May 21, 2015
 *      Author: root
 */

#include "RelationInput.h"

#include <boost/smart_ptr/shared_ptr.hpp>

#include "../BinaryJson/BinaryInline.h"
#include "../BinaryJson/BinaryJsonElement.h"
#include "../BinaryJson/BinaryJsonObjectIterator.h"
#include "../Common/Types.h"
#include "../Schema/SchemaInterpreter.h"
#include "../Utility/DocumentIdentifierGenerator.h"
#include "../Utility/TimestampGenerator.h"

#include <iostream>

//using namespace oracle::occi;
using namespace std;

RelationInput::RelationInput() {

}

RelationInput::~RelationInput() {
	// TODO Auto-generated destructor stub
}

/*
// todo this method should be in SchemaInterpreter?
Document generateDocumentFromResult(Document propertiesDocument, ResultSet * res)
{

	DocumentBuilder documentBuilder;
	DocumentIterator it(propertiesDocument);
	int i = 1;
	while (it.more()) {
		DocumentElement documentElement = it.next();
		std::string fieldName = documentElement.fieldName();
		Document fieldDocument = documentElement.embeddedObject();
		std::string fieldType = std::string(
				fieldDocument.getField(SCHEMA_TYPE).valuestr());
		JSONTYPE jsonType = generateJsonType(fieldType);

		if (jsonType == JSON_TRUE) {
			documentBuilder.appendBool(fieldName, true);
		} else if (jsonType == JSON_FALSE) {
			documentBuilder.appendBool(fieldName, false);
		} else if (jsonType == JSON_ARRAY) {
			Document nestedDocument;
			Document nestedItemsDocument =
					fieldDocument.getField(SCHEMA_ITEMS).embeddedObject();
			documentBuilder.append(fieldName, nestedDocument);
		} else if (jsonType == JSON_NULL) {
			documentBuilder.appendBool(fieldName, NULL);
		} else if (jsonType == JSON_NUMBER) {
			int value = res->getInt(i++);
			documentBuilder.append(fieldName, value);
		} else if (jsonType == JSON_OBJECT) {
			Document nestedDocument;
			Document nestedPropertiesDocument = fieldDocument.getField(
					SCHEMA_PROPERTIES).embeddedObject();
			documentBuilder.append(fieldName, nestedDocument);
		} else if (jsonType == JSON_STRING) {
			string str = res->getString(i++);
			documentBuilder.append(fieldName, str);
		}

	}
	return documentBuilder.obj();
}
*/

RelationInput::RelationInput(std::string ip, std::string port,
		std::string userName, std::string userPassword,
		std::string databaseName, std::string tableName,
		boost::shared_ptr<JsonSchema> schema) {

	this->ip = ip;
	this->port = port;
	this->userName = userName;
	this->userPassword = userPassword;
	this->databaseName = databaseName;
	this->tableName = tableName;
	this->schema = schema;

	this->id = schema->getId();

}

std::string getSqlFromSchema(boost::shared_ptr<JsonSchema> schema, std::string tableName)
{
	Document schemaDocument = schema->getSchemaDocument();
	Document propertiesDocument =
			schemaDocument.getField(SCHEMA_PROPERTIES).embeddedObject();

	DocumentIterator it(propertiesDocument);

	std::string sql = "select ";

	while (it.more()) {
		DocumentElement documentElement = it.next();
		std::string fieldName = documentElement.fieldName();
		sql += fieldName + ", ";
	}
	sql.erase(sql.find_last_of(","));
	sql += " from " + tableName;

	return sql;

}

list<Element> RelationInput::getAllElementsFromDatabase()
{
	// todo	make it general by using schema

	/*
	Environment *env;
	Connection *conn;
	Statement *stmt;
	env = Environment::createEnvironment(Environment::DEFAULT);
	conn = env->createConnection(this->userName, this->userPassword,
			databaseName);
    */

	list<Element> elements;

	/*
	Document schemaDocument = this->schema->getSchemaDocument();
	Document propertiesDocument =
			schemaDocument.getField(SCHEMA_PROPERTIES).embeddedObject();

	string sqlStmt = getSqlFromSchema(this->schema, this->tableName);

	stmt = conn->createStatement(sqlStmt);
	ResultSet *rset = stmt->executeQuery();

	while (rset->next()) {

		Document document = generateDocumentFromResult(propertiesDocument,
				rset);
		Element element;
		element.id =
				DocumentIdentifierGenerator::generateNewDocumentIdentifier();
		element.mark = PLUS_MARK;
		element.timestamp = TimestampGenerator::getCurrentTime();
		element.document = document;
		element.document.getOwned();

		elements.push_back(element);
	}
	*/

	return elements;
}