text:
/*
 * IncrementalSharing.cpp
 *
 *  Created on: 14 Jul 2017
 *      Author: araldo
 */

#include <boost/graph/max_cardinality_matching.hpp>
#include "IncrementalSharing.hpp"
#include "geospatial/network/RoadNetwork.hpp"
#include "path/PathSetManager.hpp"

using namespace sim_mob;

void IncrementalSharing::computeSchedules()
{
    //Nothing to be done if there are no requests
    if(requestQueue.empty())
    {
        return;
    }

    //Try to match partially available drivers
    if(!partiallyAvailableDrivers.empty())
    {
        matchPartiallyAvailableDrivers();
    }

    //Can't do anything if there aren't any drivers available
    if (availableDrivers.empty())
    {
        return;
    }

    //This will contain the constructed schedule for every driver
    std::unordered_map<const Person *, Schedule> schedulesComputedSoFar;

    for (const Person *driver : availableDrivers)
    {
        const Node *driverNode = driver->exportServiceDriver()->getCurrentNode(); // the node in which the driver is currently located
        Schedule schedule;
        unsigned aggregatedRequests = 0; // Number of requests that we have aggregated so far

        schedule = buildSchedule(maxAggregatedRequests, maxWaitingTime, driverNode, schedule, &aggregatedRequests);

#ifndef NDEBUG
        if (schedule.size() != aggregatedRequests * 2 )
        {
            throw std::runtime_error("There should be 2 schedule items (1 pickup + 1 dropoff) per each request inserted in this schedule. But it is not the case here.");
        }

        if (aggregatedRequests > maxAggregatedRequests)
        {
            throw std::runtime_error("The number of aggregated requests is incorrect");
        }

        if (schedulesComputedSoFar.find(driver) != schedulesComputedSoFar.end()  )
            throw std::runtime_error("Trying to assign more than one schedule to a single driver");
#endif

        if (!schedule.empty())
        {
            schedulesComputedSoFar.emplace(driver, schedule);
        }
    }

#ifndef NDEBUG
    for (const std::pair<const Person*, Schedule>& s : schedulesComputedSoFar)
    {
        const Person* driver = s.first;
        if (driverSchedules.find(driver) == driverSchedules.end()  )
        {
            throw std::runtime_error("Trying to assign a schedule to a driver that is already occupied as she received a schedule some schedule computation period ago"+
                    std::string(" and she has not finished yet") );
        }
    }
    //
#endif

    assignSchedules(schedulesComputedSoFar);
}

Schedule IncrementalSharing::buildSchedule(unsigned int maxAggregatedRequests, double maxWaitingTime,
                                           const Node *driverNode, Schedule schedule, unsigned int *aggregatedRequests)
{
    for (std::list<TripRequestMessage>::iterator itReq = requestQueue.begin();
         itReq != requestQueue.end() && *aggregatedRequests < maxAggregatedRequests;)
    {
        // We now iterate over all the un-assigned requests and we see if we can assign them to this driver
        const TripRequestMessage request = *itReq;

        // We will set it to true if we observe that this request can be assigned to this driver
        bool isMatchingSuccessful = false;
        unsigned pickupIdx = 0;

        do
        {
            Schedule scheduleHypothesis = schedule;
            // To check if we can assign this request to this driver, we create tentative schedules (like this
            // scheduleHypothesis).
            // We will try to modify this tentative schedule. If we succeed, they will become the real schedule.
            // Otherwise, we will start again from the real schedule and try to insert in it the following requests

            ScheduleItem newPickup(PICKUP, request);
            // First, we have to find a feasible position in the schedule for the pickup of the current request.
            scheduleHypothesis.insert(scheduleHypothesis.begin() + pickupIdx, newPickup);

            double vehicleTime = evaluateSchedule(driverNode, scheduleHypothesis,
                                                  toleratedExtraTime, maxWaitingTime);
            if (vehicleTime > 0)
            {
                // It is possible to insert the pick up. Now, I start from the current scheduleHypothesis, in which the pick up has been successfully inserted,
                // and I seek a feasible position for the dropoff
                unsigned dropoffIdx = pickupIdx + 1;
                do
                {
                    Schedule scheduleHypothesis2 = scheduleHypothesis;
                    ScheduleItem newDropoff(DROPOFF, request);
                    scheduleHypothesis2.insert(scheduleHypothesis2.begin() + dropoffIdx, newDropoff);
                    double vehicleTime = evaluateSchedule(driverNode, scheduleHypothesis2,
                                                          toleratedExtraTime,
                                                          maxWaitingTime);
                    if (vehicleTime > 0)
                    {
                        // I can also insert the dropoff. Perfect, I will make this successful scheduleHypothesis my schedule
                        isMatchingSuccessful = true;
                        schedule = scheduleHypothesis2;
                        (*aggregatedRequests)++;
                        itReq = requestQueue.erase(itReq);
                        // The request is matched now. I can eliminate it, so that I will not assign
                        // it again
                    }
                    else
                    {
                        dropoffIdx++;
                    } // I will try with the subsequent position
                }
                while (dropoffIdx <= schedule.size() && !isMatchingSuccessful);
                // Note: I am using <= and not < in the while condition, since it is possible to insert the dropoff at the end of the schedule
            }

            ++pickupIdx;
            // If we arrived here, it means we did not find a feasible position in the schedule
            // for the dropoff. We can try by changin the position of
            // the pickup. If we find another feasible position for the pickup, it is possible that we will also find a feasible position
            // for a dropoff, given the new pickup position
        }
        while (pickupIdx < schedule.size() && !isMatchingSuccessful);
        // Note: I am using < and not <= in the while condition, since, if I insert the pickup at the end, it is like I am not really sharing this request with

        if (!isMatchingSuccessful)
        {
            // I did not remove the request from the requestQueue, and thus I have to advance the iterator manually
            itReq++;
        }
        // else I do nothing, as I did what was to be done, some lines before
    }

    // Now we are done with this driver.

    return schedule;
}

void IncrementalSharing::matchPartiallyAvailableDrivers()
{
    unsigned maxAggRequests = maxAggregatedRequests - 1;

    //This will contain the constructed schedule for every driver
    std::unordered_map<const Person *, Schedule> schedulesComputedSoFar;

    for (const Person *driver : partiallyAvailableDrivers)
    {
        const Node *driverNode = driver->exportServiceDriver()->getCurrentNode(); // the node in which the driver is currently located

#ifndef NDEBUG
    ControllerLog() << "matchPartiallyAvailableDrivers(): driverSchedules.size() = " << driverSchedules.size() << endl;
#endif
        //Get the schedule assigned to the driver
        Schedule orgSchedule = driverSchedules[driver];

#ifndef NDEBUG
    ControllerLog() << "matchPartiallyAvailableDrivers(): driverSchedules.size() = " << driverSchedules.size() << endl;
#endif

        if(!orgSchedule.empty() && orgSchedule.back().scheduleItemType == PARK)
        {
            //Remove the parking schedule item
            orgSchedule.pop_back();
        }

        if(orgSchedule.empty())
        {
            continue;
        }

        unsigned aggregatedRequests = 0;

        Schedule schedule;
        schedule = buildSchedule(maxAggRequests, maxWaitingTime, driverNode, orgSchedule, &aggregatedRequests);

#ifndef NDEBUG
        if (aggregatedRequests > (maxAggregatedRequests + 1))
        {
            throw std::runtime_error("The number of aggregated requests is incorrect");
        }

        if (schedulesComputedSoFar.find(driver) != schedulesComputedSoFar.end())
            throw std::runtime_error("Trying to assign more than one schedule to a single driver");
#endif

        if (schedule.size() != orgSchedule.size() && !schedule.empty())
        {
            schedulesComputedSoFar.emplace(driver, schedule);
        }
    }

#ifndef NDEBUG
    for (const std::pair<const Person*, Schedule>& s : schedulesComputedSoFar)
    {
        const Person* driver = s.first;
        if (driverSchedules.find(driver) == driverSchedules.end()  )
        {
            throw std::runtime_error("Trying to assign a schedule to a driver that is already occupied as she received a schedule some schedule computation period ago"+
                    std::string(" and she has not finished yet") );
        }
    }
#endif

    assignSchedules(schedulesComputedSoFar, true);
}


text:
#ifndef NK_NRAD6_DHCP_STATE_HPP_
#define NK_NRAD6_DHCP_STATE_HPP_

#include <boost/asio.hpp>

struct dhcpv6_entry {
    dhcpv6_entry(uint32_t iaid_, const boost::asio::ip::address_v6 &addr_, uint32_t lifetime_)
        : address(addr_), iaid(iaid_), lifetime(lifetime_) {}
    boost::asio::ip::address_v6 address;
    uint32_t iaid;
    uint32_t lifetime;
};

struct dhcpv4_entry {
    dhcpv4_entry(const boost::asio::ip::address_v4 &addr_, uint32_t lifetime_)
        : address(addr_), lifetime(lifetime_) {}
    boost::asio::ip::address_v4 address;
    uint32_t lifetime;
};

void create_blobs();
bool emplace_bind(size_t linenum, std::string &&interface, bool is_v4);
bool emplace_interface(size_t linenum, const std::string &interface);
bool emplace_dhcp_state(size_t linenum, const std::string &interface, std::string &&duid,
                        uint32_t iaid, const std::string &v6_addr, uint32_t default_lifetime);
bool emplace_dhcp_state(size_t linenum, const std::string &interface, const std::string &macaddr,
                        const std::string &v4_addr, uint32_t default_lifetime);
bool emplace_dns_server(size_t linenum, const std::string &interface,
                        const std::string &addr, bool is_v4);
bool emplace_ntp_server(size_t linenum, const std::string &interface,
                        const std::string &addr, bool is_v4);
bool emplace_subnet(size_t linenum, const std::string &interface, const std::string &addr);
bool emplace_gateway(size_t linenum, const std::string &interface, const std::string &addr);
bool emplace_broadcast(size_t linenum, const std::string &interface, const std::string &addr);
bool emplace_dynamic_range(size_t linenum, const std::string &interface,
                           const std::string &lo_addr, const std::string &hi_addr,
                           uint32_t dynamic_lifetime);
bool emplace_dns_search(size_t linenum, const std::string &interface, std::string &&label);
const dhcpv6_entry* query_dhcp_state(const std::string &interface, const std::string &duid,
                                     uint32_t iaid);
const dhcpv4_entry* query_dhcp_state(const std::string &interface, const uint8_t *hwaddr);
const std::vector<boost::asio::ip::address_v6> &query_dns6_servers(const std::string &interface);
const std::vector<boost::asio::ip::address_v4> &query_dns4_servers(const std::string &interface);
const std::vector<uint8_t> &query_dns6_search_blob(const std::string &interface);
const std::vector<boost::asio::ip::address_v6> &query_ntp6_servers(const std::string &interface);
const std::vector<boost::asio::ip::address_v4> &query_ntp4_servers(const std::string &interface);
const std::vector<uint8_t> &query_ntp6_fqdns_blob(const std::string &interface);
const std::vector<boost::asio::ip::address_v6> &query_ntp6_multicasts(const std::string &interface);
const std::vector<boost::asio::ip::address_v4> &query_gateway(const std::string &interface);
const boost::asio::ip::address_v4 &query_subnet(const std::string &interface);
const boost::asio::ip::address_v4 &query_broadcast(const std::string &interface);
const std::pair<boost::asio::ip::address_v4, boost::asio::ip::address_v4>
    &query_dynamic_range(const std::string &interface, uint32_t &dynamic_lifetime);
const std::vector<std::string> &query_dns_search(const std::string &interface);
bool query_use_dynamic_v4(const std::string &interface);
bool query_use_dynamic_v6(const std::string &interface);
size_t bound_interfaces_count();
void bound_interfaces_foreach(std::function<void(const std::string&, bool, bool)> fn);

#endif

ext: hpp


text:
//
// Boost.Process
// ~~~~~~~~~~~~~
//
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <boost/process/config.hpp>

#if defined(BOOST_POSIX_API)
#  include "launch_base_test.hpp"
#  include <boost/process/child.hpp>
#  include <boost/process/self.hpp>
#  include <boost/process/posix_child.hpp>
#  include <boost/process/posix_context.hpp>
#  include <boost/process/posix_operations.hpp>
#  include <boost/process/stream_behavior.hpp>
#  include <boost/process/pistream.hpp>
#  include <boost/process/postream.hpp>
#  include <boost/process/status.hpp>
#  include <boost/format.hpp>
#  include <vector>
#  include <string>
#  include <cstdlib>
#  include <unistd.h>

namespace bp = ::boost::process;
#endif

#include <boost/filesystem/operations.hpp>
#include <boost/test/unit_test.hpp>

namespace bfs = ::boost::filesystem;
namespace but = ::boost::unit_test;

#if defined(BOOST_POSIX_API)
class launcher
{
public:
    bp::posix_child operator()(const std::vector<std::string> args,
               bp::posix_context ctx,
               bp::stream_behavior bstdin = bp::close_stream(),
               bp::stream_behavior bstdout = bp::close_stream(),
               bp::stream_behavior bstderr = bp::close_stream(),
               bool usein = false)
        const
    {
        if (bstdin.get_type() != bp::stream_behavior::close)
            ctx.input_behavior.insert(bp::behavior_map::value_type(STDIN_FILENO, bstdin));

        if (bstdout.get_type() != bp::stream_behavior::close)
            ctx.output_behavior.insert(bp::behavior_map::value_type(STDOUT_FILENO, bstdout));

        if (bstderr.get_type() != bp::stream_behavior::close)
            ctx.output_behavior.insert(bp::behavior_map::value_type(STDERR_FILENO, bstderr));

        if (ctx.environment.empty())
            ctx.environment = bp::self::get_environment();

        return bp::posix_launch(get_helpers_path(), args, ctx);
    }
};

void test_input()
{
    std::vector<std::string> args;
    args.push_back("helpers");
    args.push_back("stdin-to-stdout");

    bp::posix_context ctx;
    ctx.input_behavior.insert(bp::behavior_map::value_type(STDIN_FILENO, bp::capture_stream()));
    ctx.output_behavior.insert(bp::behavior_map::value_type(STDOUT_FILENO, bp::capture_stream()));
    ctx.environment = bp::self::get_environment();

    bp::posix_child c = bp::posix_launch(get_helpers_path(), args, ctx);

    bp::postream &os = c.get_input(STDIN_FILENO);
    bp::pistream &is = c.get_output(STDOUT_FILENO);

    os << "message-to-process" << std::endl;
    os.close();

    std::string word;
    is >> word;
    BOOST_CHECK_EQUAL(word, "message-to-process");

    const bp::status s = c.wait();
    BOOST_REQUIRE(s.exited());
    BOOST_CHECK_EQUAL(s.exit_status(), EXIT_SUCCESS);
}

void check_output(int desc, const std::string &msg)
{
    std::vector<std::string> args;
    args.push_back("helpers");
    args.push_back("posix-echo-one");
    args.push_back(boost::str(boost::format("%1%") % desc));
    args.push_back(msg);

    bp::posix_context ctx;
    ctx.output_behavior.insert(bp::behavior_map::value_type(desc, bp::capture_stream()));
    ctx.environment = bp::self::get_environment();

    bp::posix_child c = posix_launch(get_helpers_path(), args, ctx);

    bp::pistream &is = c.get_output(desc);
    std::string word;
    is >> word;
    BOOST_CHECK_EQUAL(word, msg);

    const bp::status s = c.wait();
    BOOST_REQUIRE(s.exited());
    BOOST_CHECK_EQUAL(s.exit_status(), EXIT_SUCCESS);
}

static void test_output()
{
    check_output(STDOUT_FILENO, "message1-stdout");
    check_output(STDOUT_FILENO, "message2-stdout");
    check_output(STDERR_FILENO, "message1-stderr");
    check_output(STDERR_FILENO, "message2-stderr");
    check_output(10, "message1-10");
    check_output(10, "message2-10");
}

void check_redirect(int desc1, int desc2, const std::string &msg)
{
    std::vector<std::string> args;
    args.push_back("helpers");
    args.push_back("posix-echo-two");
    args.push_back(boost::str(boost::format("%1%") % desc1));
    args.push_back(boost::str(boost::format("%1%") % desc2));
    args.push_back(msg);

    bp::posix_context ctx;
    ctx.output_behavior.insert(bp::behavior_map::value_type(desc1, bp::capture_stream()));
    ctx.output_behavior.insert(bp::behavior_map::value_type(desc2, bp::posix_redirect_stream(desc1)));
    ctx.environment = bp::self::get_environment();

    bp::posix_child c = posix_launch(get_helpers_path(), args, ctx);

    bp::pistream &is = c.get_output(desc1);
    int dtmp;
    std::string word;
    is >> dtmp;
    BOOST_CHECK_EQUAL(dtmp, desc1);
    is >> word;
    BOOST_CHECK_EQUAL(word, msg);
    is >> dtmp;
    BOOST_CHECK_EQUAL(dtmp, desc2);
    is >> word;
    BOOST_CHECK_EQUAL(word, msg);

    const bp::status s = c.wait();
    BOOST_REQUIRE(s.exited());
    BOOST_CHECK_EQUAL(s.exit_status(), EXIT_SUCCESS);
}

static void test_redirect()
{
    check_redirect(STDOUT_FILENO, STDERR_FILENO, "message");
    check_redirect(STDERR_FILENO, STDOUT_FILENO, "message");
    check_redirect(4, 5, "message");
    check_redirect(10, 20, "message");
}

static void test_default_ids()
{
    bp::posix_context ctx;
    BOOST_CHECK_EQUAL(ctx.gid, ::getgid());
    BOOST_CHECK_EQUAL(ctx.egid, ::getegid());
    BOOST_CHECK_EQUAL(ctx.uid, ::getuid());
    BOOST_CHECK_EQUAL(ctx.euid, ::geteuid());
}
#endif

#if !defined(BOOST_POSIX_API)
static void test_dummy()
{
}
#endif

but::test_suite *init_unit_test_suite(int argc, char *argv[])
{
    bfs::initial_path();

    but::test_suite *test = BOOST_TEST_SUITE("posix_launch test suite");

#if defined(BOOST_POSIX_API)
    add_tests_launch_base<launcher, bp::posix_context, bp::child>(test);
    add_tests_launch_base<launcher, bp::posix_context, bp::posix_child>(test);

    test->add(BOOST_TEST_CASE(&test_output), 0, 10);
    test->add(BOOST_TEST_CASE(&test_redirect), 0, 10);
    test->add(BOOST_TEST_CASE(&test_input), 0, 10);
    test->add(BOOST_TEST_CASE(&test_default_ids));
#else
    test->add(BOOST_TEST_CASE(&test_dummy));
#endif

    return test;
}

ext: cpp

max_stars_repo_name: Flusspferd/flusspferd

max_issues_repo_name: STEllAR-GROUP/octopus

max_forks_repo_name: STEllAR-GROUP/octopus


text:
/*
 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 */

#include <memory>
#include <string>
#include <boost/test/unit_test.hpp>

#include "ServiceManager.h"
#include "BrowserLogger.h"
#include "StorageService.h"
#include "StorageException.h"
//#include "HistoryItem.h"

#define CHANNEL_AUTH01 "Gall Anonim 1"
#define CHANNEL_DESCR01 "Test channel - description 1"
#define CHANNEL_DATE01 "2001-01-20 23:59:59.000"
#define CHANNEL_URL01 "www.gallanonim-test1.com"
#define CHANNEL_TITLE01 "Test CHANNEL title 1"

#define CHANNEL_AUTH02 "Gall Anonim 2"
#define CHANNEL_DESCR02 "Test channel - description 2"
#define CHANNEL_DATE02 "2002-02-22 23:59:59.000"
#define CHANNEL_URL02 "www.gallanonim-test2.com"
#define CHANNEL_TITLE02 "Test CHANNEL title 2"

#define CHANNEL_AUTH11 "Gall Anonim 11"
#define CHANNEL_DESCR11 "Test channel - description 11"
#define CHANNEL_DATE11 "2011-01-20 23:59:59.000"
#define CHANNEL_URL11 "www.gallanonim-test11.com"
#define CHANNEL_TITLE11 "Test CHANNEL title 11"

#define ITEM_DESCRIPTION01 "Test item - description 1"
#define ITEM_DATE01 "1987-01-20 23:59:59.000"
#define ITEM_URL01 "www.item01.com"
#define ITEM_TITLE01 "Test ITEM title 1"

#define ITEM_DESCRIPTION02 "Test item - description 2"
#define ITEM_DATE02 "1988-01-20 23:59:59.000"
#define ITEM_URL02 "www.item02.com"
#define ITEM_TITLE02 "Test ITEM title 2"

#define ITEM_DESCRIPTION11 "Test item - description 11"
#define ITEM_DATE11 "1988-01-20 23:59:59.000"
#define ITEM_URL11 "www.item11.com"
#define ITEM_TITLE11 "Test ITEM title 11"

#define ITEM_DESCRIPTION12 "Test item - description 12"
#define ITEM_DATE12 "1989-01-20 23:59:59.000"
#define ITEM_URL12 "www.item12.com"
#define ITEM_TITLE12 "Test ITEM title 12"

#define ITEM_DESCRIPTION13 "Test item - description 13"
#define ITEM_DATE13 "1990-01-20 23:59:59.000"
#define ITEM_URL13 "www.item13.com"
#define ITEM_TITLE13 "Test ITEM title 13"

#define ITEM_DESCRIPTION14 "Test item - description 14"
#define ITEM_DATE14 "1991-01-20 23:59:59.000"
#define ITEM_URL14 "www.item14.com"
#define ITEM_TITLE14 "Test ITEM title 14"

BOOST_AUTO_TEST_SUITE(StorageService)

BOOST_AUTO_TEST_CASE(storage_settings)
{
    BROWSER_LOGI("[UT] StorageService - storage_settings - START --> ");

    std::shared_ptr<tizen_browser::services::StorageService> storageManager = std::dynamic_pointer_cast <
                                                                              tizen_browser::services::StorageService,
                                                                              tizen_browser::core::AbstractService > (
                                                                                tizen_browser::core::ServiceManager::getInstance().getService(
                                                                                DOMAIN_STORAGE_SERVICE));

    storageManager->init(true);

    const std::string keyInt = "keyINT";
    storageManager->setSettingsInt(keyInt, 12);
    auto i12 = storageManager->getSettingsInt(keyInt, 0);
    BOOST_CHECK(12 == i12);

    const std::string keyDouble = "keyDouble";
    storageManager->setSettingsDouble(keyDouble, 22.45);
    auto d22_45 = storageManager->getSettingsDouble(keyDouble, 0.0);
    BOOST_CHECK(22.45 == d22_45);

    const std::string keyString = "keyString";
    storageManager->setSettingsString(keyString, "String");
    auto sString = storageManager->getSettingsText(keyString, "0.0");
    BOOST_CHECK("String" == sString);

    BROWSER_LOGI("[UT] --> END - StorageService - storage_settings");
}

// Should it be moved to ut_historyService ????
//BOOST_AUTO_TEST_CASE(storage_history)
//{
//    BROWSER_LOGI("StorageService - history - START --> ");
//
//    std::shared_ptr<tizen_browser::services::StorageService> storageManager = std::dynamic_pointer_cast <
//                                                                              tizen_browser::services::StorageService,
//                                                                              tizen_browser::core::AbstractService > (
//                                                                                tizen_browser::core::ServiceManager::getInstance().getService(
//                                                                                DOMAIN_STORAGE_SERVICE));
//
//    storageManager->init(true);
//
//    std::shared_ptr<tizen_browser::tools::BrowserImage> bi = std::make_shared<tizen_browser::tools::BrowserImage>();
//    std::shared_ptr<tizen_browser::services::HistoryItem> hi = std::make_shared<tizen_browser::services::HistoryItem>("URL", "Title", bi);
//    storageManager->addHistoryItem(hi);
//
//    std::shared_ptr<tizen_browser::services::HistoryItem> hi2 = std::make_shared<tizen_browser::services::HistoryItem>("URL2", "Title2", bi);
//    storageManager->addHistoryItem(hi2);
//
//    auto countItems_2 = storageManager->getHistoryItems(100, 2);
//    auto countItems_1 = storageManager->getHistoryItems(100, 1);
//    BOOST_CHECK(countItems_2.size() == 2);
//    BOOST_CHECK(countItems_1.size() == 1);
//    storageManager->deleteHistory(hi2->getUrl());
//
//    auto hiauto = storageManager->getHistoryItem("URL");
//    BOOST_CHECK(hiauto->getTitle() == "Title");
//
//    auto iHistCount = storageManager->getHistoryItemsCount();
//    BROWSER_LOGD("iHistCount = %d", iHistCount);
//    BOOST_CHECK(iHistCount == 1);
//
//    auto iVisitCounter = storageManager->getHistoryVisitCounter(hiauto->getUrl());
//    BROWSER_LOGD("iVisitCounter = %d", iVisitCounter);
//    BOOST_CHECK(iVisitCounter == 1);
//
//    hi->setTitle("New Title");
//    storageManager->insertOrRefresh(hi);
//    auto newHistItem = storageManager->getHistoryItem("URL");
//    BOOST_CHECK(hi->getTitle() == "New Title");
//    auto iNewVisitCounter = storageManager->getHistoryVisitCounter(hi->getUrl());
//    BROWSER_LOGD("iVisitCounter = %d", iNewVisitCounter);
//    BOOST_CHECK(iNewVisitCounter == 2);
//
//    storageManager->deleteHistory();
//    iHistCount = storageManager->getHistoryItemsCount();
//    BROWSER_LOGD("iHistCount = %d", iHistCount);
//    BOOST_CHECK(iHistCount == 0);
//
//    BROWSER_LOGI("<-- StorageService - history - END");
//}

BOOST_AUTO_TEST_SUITE_END()


text:
/*
After meeting the different smart pointers of the Boost C++ Libraries, one
should be able to write safe code for dynamically allocated objects as well
as arrays. Many times, these objects are required to be stored within a
container which - as seen above - is fairly easy using boost::shared_ptr
and boost::shared_array.
*/
//#include <boost/shared_ptr.hpp>
//#include <vector>
//
//int main()
//{
//  std::vector<boost::shared_ptr<int> > v;
//  v.push_back(boost::shared_ptr<int>(new int(1)));
//  v.push_back(boost::shared_ptr<int>(new int(2)));
//}

/*
While the code in the above example is absolutely correct and smart pointers
can be used the given way, it is actually impractical for a couple of
reasons. For once, the repetitive declaration of boost::shared_ptr requires
more typing. In addition, copying the boost::shared_ptr to, from or within
the container requires incrementing and decrementing the internal
reference count constantly and thus is deemed very inefficient.
For these reasons, the Boost C++ Libraries provide Pointer Container that
are specialized for the management of dynamically allocated objects.
*/
#include <boost/ptr_container/ptr_vector.hpp>

int main()
{
  boost::ptr_vector<int> v;
  v.push_back(new int(1));
  v.push_back(new int(2));

  std::cout << v[0] << "---" << v[1] << std::endl;
}
/*
The class boost::ptr_vector defined in boost/ptr_container/ptr_vector.hpp
works the same way as the container used and initialized with the
boost::shared_ptr template parameter in the previous example.

Since boost::ptr_vector is specialized for dynamically allocated objects, it
is easier and more efficient to use though. However, as boost::ptr_vector
is the solely owner of all contained objects, the ownership cannot be shared
with a shared pointer not stored inside the container opposed to using
std::vector<boost::shared_ptr<int> >.

Besides boost::ptr_vector, additional containers specialized for managing
dynamically allocated objects are available including
boost::ptr_deque,
boost::ptr_list,
boost::ptr_set,
boost::ptr_map,
boost::ptr_unordered_set
and boost::ptr_unordered_map.
These containers are equivalent to the ones provided by the C++ standard.
The last two containers match the std::unordered_set and std::unordered_map
containers added to the C++ standard as part of the Technical Report 1.
They are also implemented as boost::unordered_set and boost::unordered_map
by the Boost C++ Libraries that can be utilized if the used implementation
of the C++ Standard does not support the Technical Report 1.
*/


text:
#define BOOST_TEST_MODULE "C++ Unit Tests for SEMPR"
#include <boost/test/included/unit_test.hpp>

#include "Core.hpp"
#include "Entity.hpp"
#include "Exception.hpp"
#include "SimpleIncrementalIDGenerator.hpp"
#include "SeparateFileStorage.hpp"
#include "component/TripleVector.hpp"

#include <boost/filesystem.hpp>
#include <iostream>

namespace fs = boost::filesystem;

BOOST_AUTO_TEST_SUITE(FileStorageTest)

    // to be used across test. We are testing storage, not id generation.
    const std::string entityID = "Entity_0";

    BOOST_AUTO_TEST_CASE(persist)
    {
        fs::path folder("./db");
        if (fs::exists(folder)) fs::remove_all(folder);

        sempr::SeparateFileStorage::Ptr store;
        // throws as the folder does not exists
        BOOST_CHECK_THROW(store = std::make_shared<sempr::SeparateFileStorage>(folder.string()), sempr::Exception);

        // create the folder
        fs::create_directory(folder);
        // and the storage module
        store = std::make_shared<sempr::SeparateFileStorage>(folder.string());

        // create the core (use store for storage AND idgen!, though we don't test idgen here).
        sempr::Core core(store, store);

        // create an entity, and add a triplevector component
        auto entity = sempr::Entity::create();
        entity->setId(entityID);

        // add to core -> persist
        core.addEntity(entity);

        // entity should be persisted now
        BOOST_CHECK(fs::exists(folder / (entity->id() + ".json")));

        // create a temporary entity
        auto tmp = sempr::Entity::createTemporary();
        tmp->setId(entityID + "_tmp");
        core.addEntity(tmp);

        // entity should *not* be persisted
        BOOST_CHECK(!fs::exists(folder / (tmp->id() + ".json")));
    }

    BOOST_AUTO_TEST_CASE(load)
    {
        fs::path folder("./db");
        BOOST_CHECK(fs::exists(folder / (entityID + ".json"))); // check if the entity was persisted. precondition for this test...

        auto store = std::make_shared<sempr::SeparateFileStorage>(folder.string());
        auto entity = store->load(entityID);

        BOOST_CHECK(entity != nullptr);

        sempr::Core core(store, store);
        core.addEntity(entity); // triggers persistence... the architecture is not very clever, yet, when it comes to persistence.
    }

    BOOST_AUTO_TEST_CASE(remove)
    {
        fs::path folder("./db");
        auto store = std::make_shared<sempr::SeparateFileStorage>(folder.string());

        auto entities = store->loadAll();
        BOOST_CHECK(entities.size() > 0); // precondition for the remove test: there have to be entities to remove

        // directly test the remove of the store, not going through the core here.
        for (auto e : entities)
        {
            store->remove(e);
        }

        entities = store->loadAll();
        BOOST_CHECK(entities.size() == 0);
    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: niniemann/sempr

max_issues_repo_name: niniemann/sempr

max_forks_repo_name: niniemann/sempr


text:
// (C) Copyright David James Pearce 2003. Permission to copy, use,
// modify, sell and distribute this software is granted provided this
// copyright notice appears in all copies. This software is provided
// "as is" without express or implied warranty, and with no claim as
// to its suitability for any purpose.
//
// Email: david.pearce@mcs.vuw.ac.nz
//
// Notes
// =====
// This is basically a very simplistic approach
// to topological ordering the graph. It uses
// the standard (exhaustive) topological sort
// function.

#ifndef SIMPLE_TOPOLOGICAL_ORDER_HPP
#define SIMPLE_TOPOLOGICAL_ORDER_HPP

#include <stdexcept>
#include <boost/property_map.hpp>
#include <boost/graph/topological_sort.hpp>
#include "oto_tags.hpp"

#ifdef SOTO_GENERATE_STATS
extern unsigned int algo_count;
#endif

template<class T, class N2I>
class simple_topological_order;

template<class T, class N2I>
void sto_dfs_visit(unsigned int n, unsigned int &count,
		   typename boost::property_map<T, N2I>::type &n2i,
		   simple_topological_order<T,N2I> &g) {
  // some useful typedefs

#ifdef SOTO_GENERATE_STATS
  ++algo_count;
#endif

  typedef typename T::out_edge_iterator out_iterator;

  // could undoubtedly optimise this get away. It
  // might be expensive for all I know ...

  g._visited[n]=true;

  out_iterator i,iend;
  for(tie(i,iend) = out_edges(n,g); i!=iend;++i) {

#ifdef SOTO_GENERATE_STATS
    ++algo_count;
#endif

    unsigned int w(target(*i,g));
    if(!g._visited[w]) {
      sto_dfs_visit(w,count,n2i,g);
    }
  }

  n2i[n] = --count;
}

template<class InputIter, class T, class N2I>
void add_edges(InputIter b, InputIter e,
	       simple_topological_order<T,N2I> &g) {
  bool flag(false);

  typedef typename boost::property_map<T, N2I>::type N2iMap;
  N2iMap n2i = get(N2I(),g);

  for(;b!=e;++b) {
    if(add_edge(static_cast<typename T::vertex_descriptor>(b->first),
		static_cast<typename T::vertex_descriptor>(b->second),
		static_cast<T&>(g)).second) {
      unsigned int hn2i(n2i[b->second]);
      unsigned int tn2i(n2i[b->first]);

      if(hn2i < tn2i) { flag = true; }
    }
  }

  if(flag) {
    unsigned int c(num_vertices(g));
    unsigned int count(num_vertices(g));
    for(unsigned int i=0;i!=c;++i) {
      if(!g._visited[i]) {
	sto_dfs_visit(i,count,n2i,g);
      }
    }
    fill(g._visited.begin(),g._visited.end(),false);
  }
}

template<class T, class N2I = n2i_t>
class simple_topological_order : public T {
public:
  typedef simple_topological_order<T,N2I> self;
  friend void add_edges<>(typename std::vector<std::pair<unsigned int, unsigned int> >::iterator,
			  typename std::vector<std::pair<unsigned int, unsigned int> >::iterator,
			  self &);
  friend void sto_dfs_visit<>(unsigned int, unsigned int &,
			      typename boost::property_map<T, N2I>::type &,
			      self &);
private:
  std::vector<bool> _visited; // useful and not too expensive.
public:
  simple_topological_order(T const &g, unsigned int acc = 1)
    : T(g), _visited(num_vertices(g),false) {

    // use the topological sort function to
    // order the vertices correctly ...

    typedef typename boost::property_map<T, N2I>::type N2iMap;
    N2iMap n2i = get(N2I(),*this);

    unsigned int count(num_vertices(g));
    for(unsigned int i=0;i!=num_vertices(g);++i) {
      if(!_visited[i]) {
	sto_dfs_visit(i,count,n2i,*this);
      }
    }
    assert(count == 0);
    fill(_visited.begin(),_visited.end(),false);
  }

  simple_topological_order(typename T::vertices_size_type n,
			       unsigned int acc = 1)
    : T(n), _visited(n,false) {
    typedef typename boost::property_map<T, N2I>::type N2iMap;
    N2iMap n2i = get(N2I(),*this);

    unsigned int counter(0);
    typename T::vertex_iterator i,iend;
    for(tie(i,iend) = vertices(*this);i!=iend;++i) {
      n2i[*i]=counter++;
    }
  }
};

#endif

max_stars_repo_name: DavePearce/DynamicTopologicalSort

max_issues_repo_name: DavePearce/DynamicTopologicalSort

max_forks_repo_name: DavePearce/DynamicTopologicalSort


text:
#include "BayesFilters/SIS.h"

#include <fstream>
#include <iostream>
#include <utility>

#include <Eigen/Dense>

using namespace bfl;
using namespace Eigen;

SIS::SIS() noexcept { }

SIS::~SIS() noexcept { }

SIS::SIS(SIS&& sir_pf) noexcept :
    ParticleFilter(std::move(sir_pf)) { }

SIS& SIS::operator=(SIS&& sir_pf) noexcept
{
    ParticleFilter::operator=(std::move(sir_pf));

    return *this;
}

void SIS::initialization()
{
    /* INITIALIZATION */
    simulation_time_ = 100;
    num_particle_    = 900;
    surv_x_          = 1000;
    surv_y_          = 1000;

    /* GENERATE MEASUREMENTS */
    measurement_.resize(2, simulation_time_);
    object_.resize(4, simulation_time_);

    object_.col(0) << 0, 10, 0, 10;
    correction_->getObservationModel().measure(object_.col(0), measurement_.col(0));
    for (int k = 1; k < simulation_time_; ++k)
    {
        prediction_->getStateModel().motion(object_.col(k-1), object_.col(k));
        correction_->getObservationModel().measure(object_.col(k), measurement_.col(k));
    }

    /* INITIALIZE FILTER */
    pred_particle_.resize(4, num_particle_);
    pred_weight_.resize(num_particle_, 1);

    cor_particle_.resize(4, num_particle_);
    cor_weight_.resize(num_particle_, 1);

    pred_weight_.setConstant(1.0/num_particle_);

    int particle_spread = std::sqrt(num_particle_);
    for (int i = 0; i < particle_spread; ++i)
        for (int j = 0; j < particle_spread; ++j)
            pred_particle_.col(i*particle_spread + j) << (surv_x_ / particle_spread) * i, 0, (surv_y_ / particle_spread) * j, 0;

    result_pred_particle_.resize(simulation_time_);
    result_pred_weight_.resize(simulation_time_);

    result_cor_particle_.resize(simulation_time_);
    result_cor_weight_.resize(simulation_time_);
}

void SIS::filteringStep()
{
    unsigned int k = getFilteringStep();

    if (k != 0)
        prediction_->predict(cor_particle_, cor_weight_,
                             pred_particle_, pred_weight_);

    correction_->correct(pred_particle_, pred_weight_, measurement_.col(k),
                         cor_particle_, cor_weight_);

    cor_weight_ /= cor_weight_.sum();

    /* Here results should be save. */
    /* Proper stragy is WIP. */
    result_pred_particle_[k] = pred_particle_;
    result_pred_weight_  [k] = pred_weight_;

    result_cor_particle_[k]  = cor_particle_;
    result_cor_weight_  [k]  = cor_weight_;

    if (resampling_->neff(cor_weight_) < static_cast<float>(num_particle_)/3.0)
    {
        MatrixXf res_particle(4, num_particle_);
        VectorXf res_weight(num_particle_, 1);
        VectorXf res_parent(num_particle_, 1);

        resampling_->resample(cor_particle_, cor_weight_,
                              res_particle, res_weight, res_parent);

        cor_particle_ = res_particle;
        cor_weight_   = res_weight;
    }
}

void SIS::getResult()
{
    std::ofstream result_file_object;
    std::ofstream result_file_measurement;
    std::ofstream result_file_pred_particle;
    std::ofstream result_file_pred_weight;
    std::ofstream result_file_cor_particle;
    std::ofstream result_file_cor_weight;

    result_file_object.open       ("./result_object.txt");
    result_file_measurement.open  ("./result_measurement.txt");
    result_file_pred_particle.open("./result_pred_particle.txt");
    result_file_pred_weight.open  ("./result_pred_weight.txt");
    result_file_cor_particle.open ("./result_cor_particle.txt");
    result_file_cor_weight.open   ("./result_cor_weight.txt");

    result_file_object       << object_;
    result_file_measurement  << measurement_;
    for (unsigned int k = 0; k < getFilteringStep(); ++k)
    {
        result_file_pred_particle << result_pred_particle_[k] << std::endl << std::endl;
        result_file_pred_weight   << result_pred_weight_[k]   << std::endl << std::endl;

        result_file_cor_particle  << result_cor_particle_[k]  << std::endl << std::endl;
        result_file_cor_weight    << result_cor_weight_[k]    << std::endl << std::endl;
    }

    result_file_object.close();
    result_file_measurement.close();
    result_file_pred_particle.close();
    result_file_pred_weight.close();
    result_file_cor_particle.close();
    result_file_cor_weight.close();
}

max_stars_repo_name: claudiofantacci/bayes-filters-lib

max_issues_repo_name: claudiofantacci/bayes-filters-lib

max_forks_repo_name: claudiofantacci/bayes-filters-lib


text:
/*
@copyright Louis Dionne 2015
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_TEST_LAWS_MONOID_HPP
#define BOOST_HANA_TEST_LAWS_MONOID_HPP

#include <boost/hana/assert.hpp>
#include <boost/hana/comparable.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/core/models.hpp>
#include <boost/hana/core/operators.hpp>
#include <boost/hana/core/when.hpp>
#include <boost/hana/monoid.hpp>

#include <laws/base.hpp>

namespace boost { namespace hana { namespace test {
    template <typename M, typename = when<true>>
    struct TestMonoid : TestMonoid<M, laws> {
        using TestMonoid<M, laws>::TestMonoid;
    };

    template <typename M>
    struct TestMonoid<M, laws> {
        static_assert(_models<Monoid, M>{}, "");

        template <typename Xs>
        TestMonoid(Xs xs) {
            foreach3(xs, [](auto a, auto b, auto c) {

                // left identity
                BOOST_HANA_CHECK(hana::equal(
                    hana::plus(zero<M>(), a),
                    a
                ));

                // right identity
                BOOST_HANA_CHECK(hana::equal(
                    hana::plus(a, zero<M>()),
                    a
                ));

                // associativity
                BOOST_HANA_CHECK(equal(
                    hana::plus(a, hana::plus(b, c)),
                    hana::plus(hana::plus(a, b), c)
                ));

                // operators
                only_when_(bool_<has_operator<M, decltype(plus)>{}>, [=](auto _) {
                    BOOST_HANA_CHECK(hana::equal(
                        hana::plus(a, b),
                        _(a) + _(b)
                    ));
                });

            });
        }
    };

    template <typename C>
    struct TestMonoid<C, when<_models<Constant, C>{}>>
        : TestMonoid<C, laws>
    {
        template <typename Xs>
        TestMonoid(Xs xs) : TestMonoid<C, laws>{xs} {
            foreach2(xs, [](auto x, auto y) {

                BOOST_HANA_CHECK(hana::equal(
                    hana::value(zero<C>()),
                    zero<typename C::value_type>()
                ));

                BOOST_HANA_CHECK(hana::equal(
                    hana::plus(hana::value(x), hana::value(y)),
                    hana::value(hana::plus(x, y))
                ));

            });
        }
    };
}}} // end namespace boost::hana::test

#endif // !BOOST_HANA_TEST_LAWS_MONOID_HPP

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
/*
 * Copyright (c) 2014 CodiLime, Inc. All rights reserved.
 */

#include "bfd/rest_api/bfd_rest_server.h"

#include <vector>
#include <string>

#include <boost/assign.hpp>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include <boost/random.hpp>

#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>

#include "base/logging.h"
#include "base/regex.h"
#include "base/address_util.h"
#include "bfd/bfd_common.h"
#include "bfd/bfd_session.h"
#include "bfd/rest_api/bfd_json_config.h"
#include "bfd/rest_api/bfd_rest_common.h"

using contrail::regex;
using contrail::regex_match;
using contrail::regex_search;

namespace BFD {

void RESTServer::SessionHandler(const struct RESTData& data) {
    CreateRESTClientSession(data.session, data.request);
}

void RESTServer::ClientHandler(const struct RESTData& data) {
    const std::string& client_id = (*data.match)[1];
    DeleteRESTClientSession(atoi(client_id.c_str()), data.session,
                            data.request);
}

void RESTServer::ClientIPConnectionHandler(const struct RESTData& data) {
    const std::string& client_id = (*data.match)[1];
    CreateBFDConnection(atoi(client_id.c_str()), data.session,
                             data.request);
}

void RESTServer::ClientIPAddressHandlerGet(const struct RESTData& data) {
    const std::string& client_id = (*data.match)[1];
    boost::system::error_code ec;
    boost::asio::ip::address ip =
        AddressFromString((*data.match)[2], &ec);
    GetBFDConnection(atoi(client_id.c_str()), ip, data.session, data.request);
}

void RESTServer::ClientIPAddressHandlerDelete(const struct RESTData& data) {
    const std::string& client_id = (*data.match)[1];
    boost::system::error_code ec;
    boost::asio::ip::address ip =
        AddressFromString((*data.match)[2], &ec);
    DeleteBFDConnection(atoi(client_id.c_str()), ip,
                        data.session, data.request);
}

void RESTServer::ClientMonitorHandler(const struct RESTData& data) {
    const std::string& client_id = (*data.match)[1];
    MonitorRESTClientSession(atoi(client_id.c_str()), data.session,
                                  data.request);
}

const std::vector<RESTServer::HandlerSpecifier> RESTServer::RESTHandlers_ =
    boost::assign::list_of
    (HandlerSpecifier(
        regex("/Session"),
        HTTP_PUT,
        &RESTServer::SessionHandler))
    (HandlerSpecifier(
        regex("/Session/([[:digit:]]{1,9})"),
        HTTP_DELETE,
        &RESTServer::ClientHandler))
    (HandlerSpecifier(
        regex("/Session/([[:digit:]]{1,9})/IpConnection"),
        HTTP_PUT,
        &RESTServer::ClientIPConnectionHandler))
    (HandlerSpecifier(
        regex("/Session/([[:digit:]]{1,9})/IpConnection/"
              "([[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\."
              "[[:digit:]]{1,3}\\.[[:digit:]]{1,3})"),
        HTTP_GET,
        &RESTServer::ClientIPAddressHandlerGet))
    (HandlerSpecifier(
        regex("/Session/([[:digit:]]{1,9})/IpConnection/"
              "([[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\."
              "[[:digit:]]{1,3}\\.[[:digit:]]{1,3})"),
        HTTP_DELETE,
        &RESTServer::ClientIPAddressHandlerDelete))
    (HandlerSpecifier(
        regex("/Session/([[:digit:]]{1,9})/Monitor"),
        HTTP_GET,
        &RESTServer::ClientMonitorHandler));

RESTServer::RESTServer(Server* bfd_server) :
        bfd_server_(bfd_server) {
}

RESTClientSession* RESTServer::GetClientSession(ClientId client_id,
                                                HttpSession* session) {
    ClientMap::iterator it = client_sessions_.find(client_id);
    if (it != client_sessions_.end())
        return it->second;

    REST::SendErrorResponse(session, "Unknown client-id: " +
                        boost::lexical_cast<std::string>(client_id), 404);
    return NULL;
}

void RESTServer::CreateRESTClientSession(HttpSession* session,
                                         const HttpRequest* request) {
    ClientId client_id = UniqClientId();
    RESTClientSession* client_session =
        new RESTClientSession(bfd_server_, client_id);
    client_sessions_[client_id] = client_session;

    contrail_rapidjson::Document document;
    document.SetObject();
    document.AddMember("client-id", client_id, document.GetAllocator());
    contrail_rapidjson::StringBuffer strbuf;
    contrail_rapidjson::Writer<contrail_rapidjson::StringBuffer> writer(strbuf);
    document.Accept(writer);
    REST::SendResponse(session, strbuf.GetString());
}

void RESTServer::DeleteRESTClientSession(ClientId client_id,
                                            HttpSession* session,
                                            const HttpRequest* request) {
    RESTClientSession* client_session = GetClientSession(client_id, session);
    if (client_session == NULL) {
        LOG(DEBUG, __PRETTY_FUNCTION__ << ": Couldn't get session.");
        return;
    }

    delete client_session;
    client_sessions_.erase(client_id);
    REST::SendResponse(session, "{}");
}

void RESTServer::CreateBFDConnection(ClientId client_id,
                HttpSession* session, const HttpRequest* request) {
    RESTClientSession* client_session = GetClientSession(client_id, session);
    if (client_session == NULL) {
        LOG(DEBUG, __PRETTY_FUNCTION__ << ": Couldn't get session.");
        return;
    }

    REST::JsonConfig bfd_session_data;
    if (bfd_session_data.ParseFromJsonString(request->Body())) {
        SessionConfig config;
        config.desiredMinTxInterval =
            bfd_session_data.desired_min_tx_interval;
        config.requiredMinRxInterval =
            bfd_session_data.required_min_rx_interval;
        config.detectionTimeMultiplier =
            bfd_session_data.detection_time_multiplier;
        ResultCode result = client_session->AddBFDConnection(
            SessionKey(bfd_session_data.address), config);
        if (kResultCode_Ok != result) {
            REST::SendErrorResponse(session, "Unable to create session", 500);
        } else {
            REST::SendResponse(session, "{}");
        }
    } else {
        REST::SendErrorResponse(session, "Invalid arguments", 400);
    }
}

void RESTServer::GetBFDConnection(ClientId client_id,
            const boost::asio::ip::address& ip, HttpSession* session,
            const HttpRequest* request) {
    RESTClientSession* client_session = GetClientSession(client_id, session);
    if (client_session == NULL) {
        LOG(DEBUG, __PRETTY_FUNCTION__ << ": Couldn't get session.");
        REST::SendErrorResponse(session, "Unknown client session", 404);
        return;
    }
    Session* bfd_session = client_session->GetSession(ip);
    if (bfd_session == NULL) {
        LOG(DEBUG, __PRETTY_FUNCTION__ << ": Couldn't get session.");
        REST::SendErrorResponse(session, "Unknown bfd session", 404);
        return;
    }

    BFDRemoteSessionState remote_state = bfd_session->remote_state();
    SessionConfig config = bfd_session->config();
    REST::JsonState session_state;
    session_state.local_discriminator = bfd_session->local_discriminator();
    session_state.remote_discriminator = remote_state.discriminator;
    session_state.bfd_local_state = bfd_session->local_state();
    session_state.bfd_remote_state = remote_state.state;
    session_state.remote_min_rx_interval = remote_state.minRxInterval;
    REST::JsonConfig& session_data = session_state.session_config;
    session_data.address = bfd_session->key().remote_address;
    session_data.desired_min_tx_interval = config.desiredMinTxInterval;
    session_data.required_min_rx_interval = config.requiredMinRxInterval;
    session_data.detection_time_multiplier = config.detectionTimeMultiplier;
    std::string json;
    session_state.EncodeJsonString(&json);
    REST::SendResponse(session, json);
}

void RESTServer::DeleteBFDConnection(ClientId client_id,
            const boost::asio::ip::address& ip, HttpSession* session,
            const HttpRequest* request) {
    RESTClientSession* client_session = GetClientSession(client_id, session);
    if (client_session == NULL) {
        LOG(DEBUG, __PRETTY_FUNCTION__ << ": Couldn't get session.");
        REST::SendErrorResponse(session, "Unknown client session", 404);
        return;
    }
    ResultCode result = client_session->DeleteBFDConnection(SessionKey(ip));
    if (result != kResultCode_Ok) {
        REST::SendErrorResponse(session, "Unable to delete session");
    } else {
        REST::SendResponse(session, "{}");
    }
}

void RESTServer::MonitorRESTClientSession(ClientId client_id,
            HttpSession* session, const HttpRequest* request) {
    RESTClientSession* client_session = GetClientSession(client_id, session);
    if (client_session == NULL) {
        LOG(DEBUG, __PRETTY_FUNCTION__ << ": Couldn't get session.");
        REST::SendErrorResponse(session, "Unknown client session", 404);
        return;
    }
    client_session->AddMonitoringHttpSession(session);
}

void RESTServer::HandleRequest(HttpSession* session,
                                    const HttpRequest* request) {
    tbb::mutex::scoped_lock lock(mutex_);

    std::string path = request->UrlPath();
    BOOST_FOREACH(const RESTServer::HandlerSpecifier& hs, RESTHandlers_) {
        boost::smatch match;
        if (regex_match(path, match, hs.request_regex) &&
            request->GetMethod() == hs.method) {
            struct RESTData data = {
                &match,
                request->GetMethod(),
                session,
                request
            };
            LOG(INFO, "Handling request: " << path);
            (this->*hs.handler_func)(data);
            // Though IMHO it contradicts most programmers' intuition,
            // currently handlers are responsible for freeing handled
            // requests.
            delete request;
            return;
        }
    }
    LOG(ERROR, "Couldn't handle request: " << path);
    REST::SendErrorResponse(session, "Unknown Request", 404);
}

ClientId RESTServer::UniqClientId() {
    ClientId client_id;
    boost::random::uniform_int_distribution<> dist(0, 1e9);
    do {
        client_id = dist(randomGen);
    } while (client_sessions_.find(client_id) != client_sessions_.end());
    return client_id;
}

RESTServer::~RESTServer() {
    for (ClientMap::iterator it = client_sessions_.begin();
        it != client_sessions_.end(); ++it) {
        delete it->second;
    }
}

}  // namespace BFD

ext: cc

max_stars_repo_name: jnpr-pranav/contrail-controller

max_issues_repo_name: jnpr-pranav/contrail-controller

max_forks_repo_name: jnpr-pranav/contrail-controller


text: #include <boost/geometry/algorithms/within.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "ifmap/ifmap_link_table.h"

#include <boost/bind.hpp>

#include "db/db.h"
#include "db/db_graph.h"
#include "db/db_table_partition.h"
#include "ifmap/ifmap_link.h"
#include "ifmap/ifmap_log.h"
#include "ifmap/ifmap_log_types.h"

using namespace std;

IFMapLinkTable::IFMapLinkTable(DB *db, const string &name, DBGraph *graph)
        : DBGraphTable(db, name, graph) {
}

void IFMapLinkTable::Input(DBTablePartition *partition, DBClient *client,
                           DBRequest *req) {
    assert(false);
}

std::auto_ptr<DBEntry> IFMapLinkTable::AllocEntry(
        const DBRequestKey *key) const {
    const RequestKey *rkey = static_cast<const RequestKey *>(key);
    auto_ptr<DBEntry> entry(new IFMapLink(rkey->name));
    return entry;
}

// Generate an unique name for the link node and it should
// be independent of the order in which the right and left nodes are specified
std::string IFMapLinkTable::LinkKey(const string &metadata,
                                        IFMapNode *left, IFMapNode *right) {
    ostringstream oss;
    if (left->ToString() < right->ToString()) {
        oss << metadata << "," << left->ToString() << "," << right->ToString();
    } else {
        oss << metadata << "," << right->ToString() << "," << left->ToString();
    }
    return oss.str();
}

IFMapLink *IFMapLinkTable::AddLink(IFMapNode *left, IFMapNode *right,
                             const string &metadata, uint64_t sequence_number,
                             const IFMapOrigin &origin) {
    DBTablePartition *partition =
        static_cast<DBTablePartition *>(GetTablePartition(0));

    string link_name = LinkKey(metadata, left, right);
    IFMapLink *link = FindLink(link_name);
    if (link) {
        assert(link->IsDeleted());
        link->SetLinkRevival(true);
        link->ClearDelete();
        link->set_last_change_at_to_now();
        partition->Change(link);
    } else {
        link = new IFMapLink(link_name);
        partition->Add(link);
    }
    link->SetProperties(left, right, metadata, sequence_number, origin);
    assert(dynamic_cast<IFMapNode *>(left));
    assert(dynamic_cast<IFMapNode *>(right));
    return link;
}

IFMapLink *IFMapLinkTable::FindLink(const string &metadata, IFMapNode *left, IFMapNode *right) {
    string link_name = LinkKey(metadata, left, right);
    return FindLink(link_name);
}

IFMapLink *IFMapLinkTable::FindLink(const string &name) {

    DBTablePartition *partition =
        static_cast<DBTablePartition *>(GetTablePartition(0));
    RequestKey key;
    key.name = name;
    return static_cast<IFMapLink *>(partition->Find(&key));
}

IFMapLink *IFMapLinkTable::FindNextLink(const string &name) {

    DBTablePartition *partition =
        static_cast<DBTablePartition *>(GetTablePartition(0));
    RequestKey key;
    key.name = name;
    return static_cast<IFMapLink *>(partition->FindNext(&key));
}

void IFMapLinkTable::DeleteLink(IFMapLink *link) {
    DBGraphEdge *edge = static_cast<DBGraphEdge *>(link);
    graph()->Unlink(edge);
    link->set_last_change_at_to_now();
    link->ClearNodes();
    DBTablePartition *partition =
        static_cast<DBTablePartition *>(GetTablePartition(0));
    partition->Delete(edge);
}

void IFMapLinkTable::DeleteLink(IFMapLink *link, const IFMapOrigin &origin) {
    link->RemoveOriginInfo(origin.origin);
    if (link->is_origin_empty()) {
        DeleteLink(link);
    }
}

DBTable *IFMapLinkTable::CreateTable(DB *db, const string &name,
                                     DBGraph *graph) {
    IFMapLinkTable *table = new IFMapLinkTable(db, name, graph);
    table->Init();
    return table;
}

void IFMapLinkTable::Clear() {
    DBTablePartition *partition = static_cast<DBTablePartition *>(
        GetTablePartition(0));

    assert(!HasListeners());
    for (IFMapLink *link = static_cast<IFMapLink *>(partition->GetFirst()),
                 *next = NULL; link != NULL; link = next) {
        next = static_cast<IFMapLink *>(partition->GetNext(link));
        if (link->IsDeleted()) {
            continue;
        }
        graph()->Unlink(link);
        partition->Delete(link);
    }
}

void IFMapLinkTable_Init(DB *db, DBGraph *graph) {
    DBTable *table =
            IFMapLinkTable::CreateTable(db, "__ifmap_metadata__.0", graph);
    db->AddTable(table);
}

void IFMapLinkTable_Clear(DB *db) {
    IFMapLinkTable *ltable = static_cast<IFMapLinkTable *>(
            db->FindTable("__ifmap_metadata__.0"));
    ltable->Clear();
}

max_stars_repo_name: atsgen/tf-controller

max_issues_repo_name: atsgen/tf-controller

max_forks_repo_name: atsgen/tf-controller


text:
/*
 ******************************************************************************
 Project:      OWA EPANET
 Version:      2.2
 Module:       test_overflow.cpp
 Description:  Tests EPANET toolkit api functions
 Authors:      see AUTHORS
 Copyright:    see AUTHORS
 License:      see LICENSE
 Last Updated: 06/16/2019
 ******************************************************************************
*/

/*
   Tests the EN_CANOVERFLOW option for Tank nodes
*/

#include <boost/test/unit_test.hpp>

#include "test_toolkit.hpp"

BOOST_AUTO_TEST_SUITE (test_overflow)

BOOST_AUTO_TEST_CASE(test_tank_overflow)

{
    int error = 0;
    int Nindex, Lindex;
    double level, spillage, spillage2, inflow;
    char testFile[] = "test_overflow.inp";

    EN_Project ph = NULL;

    error = EN_createproject(&ph);
    error = EN_open(ph, DATA_PATH_NET1, DATA_PATH_RPT, "");

    // Get index of the tank and its inlet/outlet pipe
    error = EN_getnodeindex(ph, (char *)"2", &Nindex);
    BOOST_REQUIRE(error == 0);
    error = EN_getlinkindex(ph, (char *)"110", &Lindex);
    BOOST_REQUIRE(error == 0);

    // Set initial & maximum level to 130
    error = EN_setnodevalue(ph, Nindex, EN_TANKLEVEL, 130);
    BOOST_REQUIRE(error == 0);
    error = EN_setnodevalue(ph, Nindex, EN_MAXLEVEL, 130);
    BOOST_REQUIRE(error == 0);

    // Set duration to 1 hr
    error = EN_settimeparam(ph, EN_DURATION, 3600);
    BOOST_REQUIRE(error == 0);

    // Solve hydraulics with default of no tank spillage allowed
    error = EN_solveH(ph);
    BOOST_REQUIRE(error == 0);

    // Check that tank remains full
    error = EN_getnodevalue(ph, Nindex, EN_TANKLEVEL, &level);
    BOOST_REQUIRE(error == 0);
    BOOST_REQUIRE(abs(level - 130.0) < 0.0001);

    // Check that there is no spillage
    error = EN_getnodevalue(ph, Nindex, EN_DEMAND, &spillage);
    BOOST_REQUIRE(error == 0);
    BOOST_REQUIRE(abs(spillage) < 0.0001);

    // Check that inflow link is closed
    error = EN_getlinkvalue(ph, Lindex, EN_FLOW, &inflow);
    BOOST_REQUIRE(error == 0);
    BOOST_REQUIRE(abs(inflow) < 0.0001);

    // Turn tank overflow option on
    error = EN_setnodevalue(ph, Nindex, EN_CANOVERFLOW, 1);
    BOOST_REQUIRE(error == 0);

    // Solve hydraulics again
    error = EN_solveH(ph);
    BOOST_REQUIRE(error == 0);

    // Check that tank remains full
    error = EN_getnodevalue(ph, Nindex, EN_TANKLEVEL, &level);
    BOOST_REQUIRE(error == 0);
    BOOST_REQUIRE(abs(level - 130.0) < 0.0001);

    // Check that there is spillage equal to tank inflow
    // (inflow has neg. sign since tank is start node of inflow pipe)
    error = EN_getnodevalue(ph, Nindex, EN_DEMAND, &spillage);
    BOOST_REQUIRE(error == 0);
    BOOST_REQUIRE(spillage > 0.0001);
    error = EN_getlinkvalue(ph, Lindex, EN_FLOW, &inflow);
    BOOST_REQUIRE(error == 0);
    BOOST_REQUIRE(abs(-inflow - spillage) < 0.0001);

    // Save project to file and then close it
    error = EN_saveinpfile(ph, testFile);
    BOOST_REQUIRE(error == 0);
    error = EN_close(ph);
    BOOST_REQUIRE(error == 0);

    // Re-open saved file & run it
    error = EN_open(ph, testFile, DATA_PATH_RPT, "");
    BOOST_REQUIRE(error == 0);
    error = EN_solveH(ph);
    BOOST_REQUIRE(error == 0);

    // Check that tank spillage has same value as before
    error = EN_getnodevalue(ph, Nindex, EN_DEMAND, &spillage2);
    BOOST_REQUIRE(error == 0);
    BOOST_REQUIRE(abs(spillage - spillage2) < 0.0001);

    // Clean up
    error = EN_close(ph);
    BOOST_REQUIRE(error == 0);
    error = EN_deleteproject(ph);
    BOOST_REQUIRE(error == 0);

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ajholguin/EPANET

max_issues_repo_name: ajholguin/EPANET

max_forks_repo_name: ajholguin/EPANET


text:
//---------------------------------------------------------------------------//
//!
//! \file   tstInverseMomentumConversion.cpp
//! \author Alex Robinson
//! \brief  The inverse momentum conversion unit tests
//!
//---------------------------------------------------------------------------//

// Std Lib Includes
#include <iostream>

// Boost Includes
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/units/quantity.hpp>
#include <boost/units/systems/si.hpp>
#include <boost/units/systems/cgs.hpp>

// FRENSIE Includes
#include "Utility_InverseMomentumUnits.hpp"
#include "Utility_RawPhysicalConstants.hpp"

using namespace Utility::Units;

//---------------------------------------------------------------------------//
// Tests
//---------------------------------------------------------------------------//
// Check that the inverse momentum units can be converted
BOOST_AUTO_TEST_CASE( convert )
{
  boost::units::quantity<Utility::Units::InverseAtomicMomentum>
    inverse_atomic_momentum_q( 1.0*inverse_mec_momentum );

  boost::units::quantity<Utility::Units::InverseMeCMomentum>
    inverse_mec_momentum_q( 1.0*inverse_atomic_momentum );

  BOOST_CHECK_CLOSE_FRACTION(
			inverse_atomic_momentum_q.value(),
			Utility::RawPhysicalConstants::fine_structure_constant,
			1e-15 );
  BOOST_CHECK_CLOSE_FRACTION(
		inverse_mec_momentum_q.value(),
		Utility::RawPhysicalConstants::inverse_fine_structure_constant,
		1e-15 );
}

//---------------------------------------------------------------------------//
// end tstInverseMomentumConversion.cpp
//---------------------------------------------------------------------------//


text:
#include <vector>

#include <boost/mpi.hpp>
#include <boost/test/minimal.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

//#include "../../sketch/CT.hpp"
//#include "../../sketch/CWT.hpp"
#include "../../sketch/sketch.hpp"

// TODO: Are these includes really needed?
#include <elemental.hpp>
#include <skylark.hpp>
#include "../../sketch/CT.hpp"
#include "../../sketch/CWT.hpp"

#include "../../base/context.hpp"

int test_main(int argc, char *argv[]) {

    //////////////////////////////////////////////////////////////////////////
    //[> Parameters <]
    const size_t n   = 10;
    const size_t m   = 5;
    const size_t n_s = 6;
    const size_t m_s = 3;

    const int seed = static_cast<int>(rand() * 100);

    typedef FullyDistVec<size_t, double> mpi_vector_t;
    typedef SpDCCols<size_t, double> col_t;
    typedef SpParMat<size_t, double, col_t> DistMatrixType;

    namespace mpi = boost::mpi;
    mpi::environment env(argc, argv);
    mpi::communicator world;
    const size_t rank = world.rank();
    skylark::base::context_t context (seed);

    double count = 1.0;

    const size_t matrix_full = n * m;
    mpi_vector_t colsf(matrix_full);
    mpi_vector_t rowsf(matrix_full);
    mpi_vector_t valsf(matrix_full);

    for(size_t i = 0; i < matrix_full; ++i) {
        colsf.SetElement(i, i % m);
        rowsf.SetElement(i, i / m);
        valsf.SetElement(i, count);
        count++;
    }

    DistMatrixType A(n, m, rowsf, colsf, valsf);

    //////////////////////////////////////////////////////////////////////////
    //[> Setup test <]

    //[> 1. Create the sketching matrix and dump JSON <]
    skylark::sketch::CWT_t<DistMatrixType, DistMatrixType>
        Sparse(n, n_s, context);

    // dump to property tree
    boost::property_tree::ptree pt = Sparse.get_data()->to_ptree();

    //[> 2. Dump the JSON string to file <]
    std::ofstream out("sketch.json");
    write_json(out, pt);
    out.close();

    //[> 3. Create a sketch from the JSON file. <]
    std::ifstream file;
    std::stringstream json;
    file.open("sketch.json", std::ios::in);

    boost::property_tree::ptree json_tree;
    boost::property_tree::read_json(file, json_tree);

    skylark::sketch::CWT_t<DistMatrixType, DistMatrixType> tmp(json_tree);

    //[> 4. Both sketches should compute the same result. <]
    mpi_vector_t zero;
    DistMatrixType sketch_A(n_s, m, zero, zero, zero);
    DistMatrixType sketch_Atmp(n_s, m, zero, zero, zero);

    Sparse.apply(A, sketch_A, skylark::sketch::columnwise_tag());
    tmp.apply(A, sketch_Atmp, skylark::sketch::columnwise_tag());

    if (!static_cast<bool>(sketch_A == sketch_Atmp))
        BOOST_FAIL("Applied sketch did not result in same result");

    return 0;
}

max_issues_repo_name: cjiyer/libskylark

max_forks_repo_name: cjiyer/libskylark


text:
/**
 * Copyright (c) 2018, University Osnabrück
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University Osnabrück 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 University Osnabrück 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 <iostream>
#include <memory>
#include <tuple>
#include <stdlib.h>

#include <boost/optional.hpp>

#include "lvr2/config/lvropenmp.hpp"

#include "lvr2/geometry/HalfEdgeMesh.hpp"
#include "lvr2/geometry/BaseVector.hpp"
#include "lvr2/geometry/Normal.hpp"
#include "lvr2/attrmaps/StableVector.hpp"
#include "lvr2/attrmaps/VectorMap.hpp"
#include "lvr2/algorithm/FinalizeAlgorithms.hpp"
#include "lvr2/algorithm/NormalAlgorithms.hpp"
#include "lvr2/algorithm/ColorAlgorithms.hpp"
#include "lvr2/geometry/BoundingBox.hpp"
#include "lvr2/algorithm/Tesselator.hpp"
#include "lvr2/algorithm/ClusterPainter.hpp"
#include "lvr2/algorithm/ClusterAlgorithms.hpp"
#include "lvr2/algorithm/CleanupAlgorithms.hpp"
#include "lvr2/algorithm/ReductionAlgorithms.hpp"
#include "lvr2/algorithm/Materializer.hpp"
#include "lvr2/algorithm/Texturizer.hpp"
//#include "lvr2/algorithm/ImageTexturizer.hpp"

#include "lvr2/reconstruction/AdaptiveKSearchSurface.hpp"
#include "lvr2/reconstruction/BilinearFastBox.hpp"
#include "lvr2/reconstruction/TetraederBox.hpp"
#include "lvr2/reconstruction/FastReconstruction.hpp"
#include "lvr2/reconstruction/PointsetSurface.hpp"
#include "lvr2/reconstruction/SearchTree.hpp"
#include "lvr2/reconstruction/SearchTreeFlann.hpp"
#include "lvr2/reconstruction/HashGrid.hpp"
#include "lvr2/reconstruction/PointsetGrid.hpp"
#include "lvr2/reconstruction/SharpBox.hpp"
#include "lvr2/io/PointBuffer.hpp"
#include "lvr2/io/MeshBuffer.hpp"
#include "lvr2/io/ModelFactory.hpp"
#include "lvr2/io/PlutoMapIO.hpp"
#include "lvr2/util/Factories.hpp"
#include "lvr2/algorithm/GeometryAlgorithms.hpp"
#include "lvr2/algorithm/UtilAlgorithms.hpp"

#include "lvr2/geometry/BVH.hpp"

#include "lvr2/reconstruction/DMCReconstruction.hpp"

#include "Options.hpp"

#if defined LVR2_USE_CUDA
    #define GPU_FOUND

    #include "lvr2/reconstruction/cuda/CudaSurface.hpp"

    typedef lvr2::CudaSurface GpuSurface;
#elif defined LVR2_USE_OPENCL
    #define GPU_FOUND

    #include "lvr2/reconstruction/opencl/ClSurface.hpp"
    typedef lvr2::ClSurface GpuSurface;
#endif

using boost::optional;
using std::unique_ptr;
using std::make_unique;

using namespace lvr2;

using Vec = BaseVector<float>;
using PsSurface = lvr2::PointsetSurface<Vec>;

template <typename BaseVecT>
PointsetSurfacePtr<BaseVecT> loadPointCloud(const reconstruct::Options& options)
{
    // Create a point loader object
    ModelPtr model = ModelFactory::readModel(options.getInputFileName());

    // Parse loaded data
    if (!model)
    {
        cout << timestamp << "IO Error: Unable to parse " << options.getInputFileName() << endl;
        return nullptr;
    }

    PointBufferPtr buffer = model->m_pointCloud;

    // Create a point cloud manager
    string pcm_name = options.getPCM();
    PointsetSurfacePtr<Vec> surface;

    // Create point set surface object
    if(pcm_name == "PCL")
    {
        cout << timestamp << "Using PCL as point cloud manager is not implemented yet!" << endl;
        panic_unimplemented("PCL as point cloud manager");
    }
    else if(pcm_name == "STANN" || pcm_name == "FLANN" || pcm_name == "NABO" || pcm_name == "NANOFLANN")
    {

        int plane_fit_method = 0;

        if(options.useRansac())
        {
            plane_fit_method = 1;
        }

        // plane_fit_method
        // - 0: PCA
        // - 1: RANSAC
        // - 2: Iterative

        surface = make_shared<AdaptiveKSearchSurface<BaseVecT>>(
            buffer,
            pcm_name,
            options.getKn(),
            options.getKi(),
            options.getKd(),
            plane_fit_method,
            options.getScanPoseFile()
        );
    }
    else
    {
        cout << timestamp << "Unable to create PointCloudManager." << endl;
        cout << timestamp << "Unknown option '" << pcm_name << "'." << endl;
        return nullptr;
    }

    // Set search options for normal estimation and distance evaluation
    surface->setKd(options.getKd());
    surface->setKi(options.getKi());
    surface->setKn(options.getKn());

    // Calculate normals if necessary
    if(!buffer->hasNormals() || options.recalcNormals())
    {
        if(options.useGPU())
        {
            #ifdef GPU_FOUND
                std::vector<float> flipPoint = options.getFlippoint();
                size_t num_points = buffer->numPoints();
                floatArr points = buffer->getPointArray();
                floatArr normals = floatArr(new float[ num_points * 3 ]);
                std::cout << timestamp << "Generating GPU kd-tree" << std::endl;
                GpuSurface gpu_surface(points, num_points);

                gpu_surface.setKn(options.getKn());
                gpu_surface.setKi(options.getKi());
                gpu_surface.setFlippoint(flipPoint[0], flipPoint[1], flipPoint[2]);

                std::cout << timestamp << "Estimating Normals GPU" << std::endl;
                gpu_surface.calculateNormals();
                gpu_surface.getNormals(normals);

                buffer->setNormalArray(normals, num_points);
                gpu_surface.freeGPU();
            #else
                std::cout << timestamp << "ERROR: GPU Driver not installed" << std::endl;
                surface->calculateSurfaceNormals();
            #endif
        }
        else
        {
            surface->calculateSurfaceNormals();
        }
    }
    else
    {
        cout << timestamp << "Using given normals." << endl;
    }

    return surface;
}

std::pair<shared_ptr<GridBase>, unique_ptr<FastReconstructionBase<Vec>>>
    createGridAndReconstruction(
        const reconstruct::Options& options,
        PointsetSurfacePtr<Vec> surface
    )
{
    // Determine whether to use intersections or voxelsize
    bool useVoxelsize = options.getIntersections() <= 0;
    float resolution = useVoxelsize ? options.getVoxelsize() : options.getIntersections();

    // Create a point set grid for reconstruction
    string decompositionType = options.getDecomposition();

    // Fail safe check
    if(decompositionType != "MT" && decompositionType != "MC" && decompositionType != "DMC" && decompositionType != "PMC" && decompositionType != "SF" )
    {
        cout << "Unsupported decomposition type " << decompositionType << ". Defaulting to PMC." << endl;
        decompositionType = "PMC";
    }

    if(decompositionType == "MC")
    {
        auto grid = std::make_shared<PointsetGrid<Vec, FastBox<Vec>>>(
            resolution,
            surface,
            surface->getBoundingBox(),
            useVoxelsize,
            options.extrude()
        );
        grid->calcDistanceValues();
        auto reconstruction = make_unique<FastReconstruction<Vec, FastBox<Vec>>>(grid);
        return make_pair(grid, std::move(reconstruction));
    }
    else if(decompositionType == "PMC")
    {
        BilinearFastBox<Vec>::m_surface = surface;
        auto grid = std::make_shared<PointsetGrid<Vec, BilinearFastBox<Vec>>>(
            resolution,
            surface,
            surface->getBoundingBox(),
            useVoxelsize,
            options.extrude()
        );
        grid->calcDistanceValues();
        auto reconstruction = make_unique<FastReconstruction<Vec, BilinearFastBox<Vec>>>(grid);
        return make_pair(grid, std::move(reconstruction));
    }
    // else if(decompositionType == "DMC")
    // {
    //     auto reconstruction = make_unique<DMCReconstruction<Vec, FastBox<Vec>>>(
    //         surface,
    //         surface->getBoundingBox(),
    //         options.extrude()
    //     );
    //     return make_pair(nullptr, std::move(reconstruction));
    // }
    else if(decompositionType == "MT")
    {
        auto grid = std::make_shared<PointsetGrid<Vec, TetraederBox<Vec>>>(
            resolution,
            surface,
            surface->getBoundingBox(),
            useVoxelsize,
            options.extrude()
        );
        grid->calcDistanceValues();
        auto reconstruction = make_unique<FastReconstruction<Vec, TetraederBox<Vec>>>(grid);
        return make_pair(grid, std::move(reconstruction));
    }
    else if(decompositionType == "SF")
    {
        SharpBox<Vec>::m_surface = surface;
        auto grid = std::make_shared<PointsetGrid<Vec, SharpBox<Vec>>>(
            resolution,
            surface,
            surface->getBoundingBox(),
            useVoxelsize,
            options.extrude()
        );
        grid->calcDistanceValues();
        auto reconstruction = make_unique<FastReconstruction<Vec, SharpBox<Vec>>>(grid);
        return make_pair(grid, std::move(reconstruction));
    }

    return make_pair(nullptr, nullptr);
}

int main(int argc, char** argv)
{
    // =======================================================================
    // Parse and print command line parameters
    // =======================================================================
    // Parse command line arguments
    reconstruct::Options options(argc, argv);

    options.printLogo();

    // Exit if options had to generate a usage message
    // (this means required parameters are missing)
    if (options.printUsage())
    {
        return EXIT_SUCCESS;
    }

    std::cout << options << std::endl;

    // =======================================================================
    // Load (and potentially store) point cloud
    // =======================================================================
    OpenMPConfig::setNumThreads(options.getNumThreads());

    auto surface = loadPointCloud<Vec>(options);
    if (!surface)
    {
        cout << "Failed to create pointcloud. Exiting." << endl;
        return EXIT_FAILURE;
    }

    // Save points and normals only
    if(options.savePointNormals())
    {
        ModelPtr pn(new Model(surface->pointBuffer()));
        ModelFactory::saveModel(pn, "pointnormals.ply");
    }

    // =======================================================================
    // Reconstruct mesh from point cloud data
    // =======================================================================
    // Create an empty mesh
    lvr2::HalfEdgeMesh<Vec> mesh;

    shared_ptr<GridBase> grid;
    unique_ptr<FastReconstructionBase<Vec>> reconstruction;
    std::tie(grid, reconstruction) = createGridAndReconstruction(options, surface);

    // Reconstruct mesh
    reconstruction->getMesh(mesh);

    // Save grid to file
    if(options.saveGrid() && grid)
    {
        grid->saveGrid("fastgrid.grid");
    }

    // =======================================================================
    // Optimize mesh
    // =======================================================================
    if(options.getDanglingArtifacts())
    {
        cout << timestamp << "Removing dangling artifacts" << endl;
        removeDanglingCluster(mesh, static_cast<size_t>(options.getDanglingArtifacts()));
    }

    // Magic number from lvr1 `cleanContours`...
    cleanContours(mesh, options.getCleanContourIterations(), 0.0001);

    // Fill small holes if requested
    if(options.getFillHoles())
    {
        naiveFillSmallHoles(mesh, options.getFillHoles(), false);
    }

    // Calculate initial face normals
    auto faceNormals = calcFaceNormals(mesh);

    // Reduce mesh complexity
    const auto reductionRatio = options.getEdgeCollapseReductionRatio();
    if (reductionRatio > 0.0)
    {
        if (reductionRatio > 1.0)
        {
            throw "The reduction ratio needs to be between 0 and 1!";
        }

        // Each edge collapse removes two faces in the general case.
        // TODO: maybe we should calculate this differently...
        const auto count = static_cast<size_t>((mesh.numFaces() / 2) * reductionRatio);
        auto collapsedCount = simpleMeshReduction(mesh, count, faceNormals);
    }

    ClusterBiMap<FaceHandle> clusterBiMap;
    if(options.optimizePlanes())
    {
        clusterBiMap = iterativePlanarClusterGrowingRANSAC(
            mesh,
            faceNormals,
            options.getNormalThreshold(),
            options.getPlaneIterations(),
            options.getMinPlaneSize()
        );

        if(options.getSmallRegionThreshold() > 0)
        {
            deleteSmallPlanarCluster(mesh, clusterBiMap, static_cast<size_t>(options.getSmallRegionThreshold()));
        }

        if(options.getFillHoles())
        {
            naiveFillSmallHoles(mesh, options.getFillHoles(), false);
        }

        cleanContours(mesh, options.getCleanContourIterations(), 0.0001);

        if (options.retesselate())
        {
            Tesselator<Vec>::apply(mesh, clusterBiMap, faceNormals, options.getLineFusionThreshold());
        }
    }
    else
    {
        clusterBiMap = planarClusterGrowing(mesh, faceNormals, options.getNormalThreshold());
    }

    // =======================================================================
    // Finalize mesh
    // =======================================================================
    // Prepare color data for finalizing
    ClusterPainter painter(clusterBiMap);
    auto clusterColors = boost::optional<DenseClusterMap<Rgb8Color>>(painter.simpsons(mesh));
    auto vertexColors = calcColorFromPointCloud(mesh, surface);

    // Calc normals for vertices
    auto vertexNormals = calcVertexNormals(mesh, faceNormals, *surface);

    // Prepare finalize algorithm
    TextureFinalizer<Vec> finalize(clusterBiMap);
    finalize.setVertexNormals(vertexNormals);

    // TODO:
    // Vielleicht sollten indv. vertex und cluster colors mit in den Materializer aufgenommen werden
    // Dafür spricht: alles mit Farben findet dann an derselben Stelle statt
    // dagegen spricht: Materializer macht aktuell nur face colors und keine vertex colors

    // Vertex colors:
    // If vertex colors should be generated from pointcloud:
    if (options.vertexColorsFromPointcloud())
    {
        // set vertex color data from pointcloud
        finalize.setVertexColors(*vertexColors);
    }
    else if (clusterColors)
    {
        // else: use simpsons painter for vertex coloring
        finalize.setClusterColors(*clusterColors);
    }

    // Materializer for face materials (colors and/or textures)
    Materializer<Vec> materializer(
        mesh,
        clusterBiMap,
        faceNormals,
        *surface
    );

    // ImageTexturizer<Vec> img_texter(
    //     options.getTexelSize(),
    //     options.getTexMinClusterSize(),
    //     options.getTexMaxClusterSize()
    // );

    Texturizer<Vec> texturizer(
        options.getTexelSize(),
        options.getTexMinClusterSize(),
        options.getTexMaxClusterSize()
    );

    // When using textures ...
    if (options.generateTextures())
    {
        if (!options.texturesFromImages())
        {
            materializer.setTexturizer(texturizer);
        }
        else
        {
            // cout << "ScanProject" << endl;
            // ScanprojectIO project;

            // if (options.getProjectDir().empty())
            // {
            //     cout << "Empty" << endl;
            //     project.parse_project(options.getInputFileName());
            // }
            // else
            // {
            //     cout << "Not empty" << endl;
            //     project.parse_project(options.getProjectDir());
            // }

            // img_texter.set_project(project.get_project());

            // materializer.setTexturizer(img_texter);
        }
    }

    // Generate materials
    MaterializerResult<Vec> matResult = materializer.generateMaterials();

    // Add material data to finalize algorithm
    finalize.setMaterializerResult(matResult);
    // Run finalize algorithm
    auto buffer = finalize.apply(mesh);

    // When using textures ...
    if (options.generateTextures())
    {
        // Set optioins to save them to disk
        materializer.saveTextures();
        buffer->addIntAtomic(1, "mesh_save_textures");
        buffer->addIntAtomic(1, "mesh_texture_image_extension");
    }

    // =======================================================================
    // Write all results (including the mesh) to file
    // =======================================================================
    // Create output model and save to file
    auto m = ModelPtr( new Model(buffer));

    if(options.saveOriginalData())
    {
        m->m_pointCloud = surface->pointBuffer();

        cout << "REPAIR SAVING" << endl;
    }

    for(const std::string& output_filename : options.getOutputFileNames())
    {
        cout << timestamp << "Saving mesh to "<< output_filename << "." << endl;
        ModelFactory::saveModel(m, output_filename);
    }

    if (matResult.m_keypoints)
    {
        // save materializer keypoints to hdf5 which is not possible with ModelFactory
        //PlutoMapIO map_io("triangle_mesh.h5");
        //map_io.addTextureKeypointsMap(matResult.m_keypoints.get());
    }

    cout << timestamp << "Program end." << endl;

    return 0;
}

max_stars_repo_name: uos/lvr

max_issues_repo_name: uos/lvr

max_forks_repo_name: uos/lvr


text:
#define BOOST_TEST_MODULE array_test
#include <boost/test/unit_test.hpp>
#include <rabbit.hpp>

BOOST_AUTO_TEST_CASE(size_test)
{
  rabbit::value v;
  BOOST_CHECK_THROW(v.size(), rabbit::type_mismatch);

  rabbit::array a;
  BOOST_CHECK_EQUAL(a.size(), 0);
  a.push_back(1);
  BOOST_CHECK_EQUAL(a.size(), 1);
  a.push_back(2);
  BOOST_CHECK_EQUAL(a.size(), 2);
}

BOOST_AUTO_TEST_CASE(empty_test)
{
  rabbit::value v;
  BOOST_CHECK_THROW(v.empty(), rabbit::type_mismatch);

  rabbit::array a;
  BOOST_CHECK(a.empty());
  a.push_back(1);
  BOOST_CHECK(!a.empty());
}

BOOST_AUTO_TEST_CASE(at_test)
{
  rabbit::value v;
  BOOST_CHECK_THROW(v.at(0), rabbit::type_mismatch);

  rabbit::array a;
  BOOST_CHECK_THROW(a.at(0), std::out_of_range);
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);
  BOOST_CHECK(a.at(0).is_int());
  BOOST_CHECK(a.at(1).is_int());
  BOOST_CHECK(a.at(2).is_int());
  BOOST_CHECK_EQUAL(a.at(0).as_int(), 1);
  BOOST_CHECK_EQUAL(a.at(1).as_int(), 2);
  BOOST_CHECK_EQUAL(a.at(2).as_int(), 3);
}

BOOST_AUTO_TEST_CASE(push_back_test)
{
  rabbit::value v;
  BOOST_CHECK_THROW(v.size(), rabbit::type_mismatch);

  rabbit::object o;
  o["foo"] = 456;

  rabbit::array a;
  a.push_back(123);
  a.push_back(1.0);
  a.push_back("str");
  a.push_back(o);
  BOOST_CHECK_EQUAL(a.size(), 4);
  BOOST_CHECK_EQUAL(a[0].as_int(), 123);
  BOOST_CHECK_CLOSE(a[1].as_double(), 1.0, 0.000001);
  BOOST_CHECK_EQUAL(a[2].as_string(), "str");
  BOOST_CHECK_EQUAL(a[3]["foo"].as_int(), 456);
}

BOOST_AUTO_TEST_CASE(pop_back_test)
{
  rabbit::value v;
  BOOST_CHECK_THROW(v.pop_back(), rabbit::type_mismatch);

  rabbit::array a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);
  BOOST_CHECK_EQUAL(a.size(), 3);
  BOOST_CHECK_EQUAL(a.at(a.size() - 1).as_int(), 3);
  a.pop_back();
  BOOST_CHECK_EQUAL(a.size(), 2);
  BOOST_CHECK_EQUAL(a.at(a.size() - 1).as_int(), 2);
  a.pop_back();
  BOOST_CHECK_EQUAL(a.size(), 1);
  BOOST_CHECK_EQUAL(a.at(a.size() - 1).as_int(), 1);
}

BOOST_AUTO_TEST_CASE(erase_itr){
  rabbit::array a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);
  BOOST_CHECK_EQUAL(a.size(), 3);

  rabbit::array::value_iterator itr = a.erase(++a.value_begin());
  BOOST_CHECK_EQUAL(a.size(), 2);
  BOOST_CHECK_EQUAL(a[0].as_int(), 1);
  BOOST_CHECK_EQUAL(a[1].as_int(), 3);
  BOOST_CHECK(itr == (a.begin()+1)); //Can't use equal here because equal tries to print iterators which isn't defined
}

BOOST_AUTO_TEST_CASE(erase_itr_range){
  rabbit::array a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);
  BOOST_CHECK_EQUAL(a.size(), 3);

  rabbit::array::value_iterator itr = a.erase(a.value_begin()+1, a.value_end());
  BOOST_CHECK_EQUAL(a.size(), 1);
  BOOST_CHECK_EQUAL(a[0].as_int(), 1);
  BOOST_CHECK(itr == a.end()); //Can't use equal here because equal tries to print iterators which isn't defined
}

BOOST_AUTO_TEST_CASE(erase_const_itr){
  rabbit::array a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);
  BOOST_CHECK_EQUAL(a.size(), 3);

  rabbit::array::const_value_iterator itr = a.erase(++a.value_cbegin());
  BOOST_CHECK_EQUAL(a.size(), 2);
  BOOST_CHECK_EQUAL(a[0].as_int(), 1);
  BOOST_CHECK_EQUAL(a[1].as_int(), 3);
  BOOST_CHECK(itr == (a.begin()+1)); //Can't use equal here because equal tries to print iterators which isn't defined
}

BOOST_AUTO_TEST_CASE(erase_const_itr_range){
  rabbit::array a;
  a.push_back(1);
  a.push_back(2);
  a.push_back(3);
  BOOST_CHECK_EQUAL(a.size(), 3);

  rabbit::array::const_value_iterator itr = a.erase(a.value_cbegin()+1, a.value_cend());
  BOOST_CHECK_EQUAL(a.size(), 1);
  BOOST_CHECK_EQUAL(a[0].as_int(), 1);
  BOOST_CHECK(itr == a.end()); //Can't use equal here because equal tries to print iterators which isn't defined
}

BOOST_AUTO_TEST_CASE(iterator_test)
{
  rabbit::array a;
  a.push_back(123);
  a.push_back(1.0);
  a.push_back("str");

  int n = 0;
  typedef rabbit::array::iterator iter_t;
  for (iter_t it = a.begin(); it != a.end(); ++it, ++n)
  {
    if      (n == 0) BOOST_CHECK_EQUAL(it->as_int(), 123);
    else if (n == 1) BOOST_CHECK_CLOSE(it->as_double(), 1.0, 0.000001);
    else if (n == 2) BOOST_CHECK_EQUAL(it->as_string(), "str");
    else BOOST_ERROR("illegal value");
  }
}

BOOST_AUTO_TEST_CASE(const_iterator_test)
{
  rabbit::array a;
  a.push_back(123);
  a.push_back(1.0);
  a.push_back("str");

  int n = 0;
  typedef rabbit::array::const_iterator iter_t;
  for (iter_t it = a.begin(); it != a.end(); ++it, ++n)
  {
    if      (n == 0) BOOST_CHECK_EQUAL(it->as_int(), 123);
    else if (n == 1) BOOST_CHECK_CLOSE(it->as_double(), 1.0, 0.000001);
    else if (n == 2) BOOST_CHECK_EQUAL(it->as_string(), "str");
    else BOOST_ERROR("illegal value");
  }
}

BOOST_AUTO_TEST_CASE(push_back_strings){
  rabbit::array a;
  a.push_back("abc");

  std::string s("some sort of string");
  a.push_back(s);

  char * cs = (char *) calloc(sizeof(char), 4);
  memcpy(cs, "def", 4);
  a.push_back(cs);

  BOOST_CHECK(a.size() == 3);
  BOOST_CHECK(a[0].as_string() == "abc");
  BOOST_CHECK(a[1].as_string() == s);
  BOOST_CHECK(a[2].as_string() == "def");
}

max_stars_repo_name: csteifel/rabbit

max_issues_repo_name: csteifel/rabbit

max_forks_repo_name: csteifel/rabbit


text:
#define BOOST_TEST_DYN_LINK
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/unit_test.hpp>

#include <luacxx/binding/class.hpp>
#include <luacxx/binding/function.hpp>
#include <luacxx/binding/engine.hpp>

#include <config.h>

namespace
{
  class Class1
  {
    public:
      Class1()
      {
        last = this;
        ++nb_init;
      }

      ~Class1()
      {
        ++nb_destroy;
      }

      static size_t  nb_init;
      static size_t  nb_destroy;
      static Class1* last;
  };

  Class1* Class1::last =  nullptr;
  size_t Class1::nb_init = 0;
  size_t Class1::nb_destroy = 0;
  std::shared_ptr<Class1> global_class1;

  bool fct1(const std::shared_ptr<Class1>& c)
  {
    return c.get() == Class1::last;
  }

  bool fct2(const Class1& c)
  {
    return &c == Class1::last;
  }

  bool fct3(const Class1* c)
  {
    return c == Class1::last;
  }

  bool fct4(Class1* c)
  {
    return c == Class1::last;
  }

  std::shared_ptr<Class1> fct5()
  {
    return std::make_shared<Class1>();
  }

  Class1* fct6()
  {
    return new Class1();
  }

  Class1* fct7()
  {
    return global_class1.get();
  }

  bool is_global(const Class1* c)
  {
    return global_class1.get() == c;
  }

  void setup(bool global)
  {
    Class1::last =  nullptr;
    Class1::nb_init = 0;
    Class1::nb_destroy = 0;

    if(global)
    {
      global_class1 = std::make_shared<Class1>();
    }
  }

  void teardown()
  {
    global_class1.reset();
  }
}

BOOST_AUTO_TEST_CASE( class_01 )
{
  setup(false);
  {
    luacxx::engine engine;
    luacxx::make_class<Class1>(engine, "Class1")
        .ctor();
    luacxx::make_function(engine, "fct1", fct1);
    luacxx::make_function(engine, "fct2", fct2);
    luacxx::make_function(engine, "fct3", fct3);
    luacxx::make_function(engine, "fct4", fct4);
    BOOST_CHECK(engine.bind());

    std::pair<bool, std::string> ret = engine.do_file(LUACXX_TESTS_DIR "class_01.lua");
    if(!ret.first)
    {
      BOOST_FAIL(ret.second);
    }
  }
  teardown();

  BOOST_CHECK(Class1::nb_init    == 1);
  BOOST_CHECK(Class1::nb_destroy == 1);
}

BOOST_AUTO_TEST_CASE( class_02 )
{
  setup(true);
  {
    luacxx::engine engine;
    luacxx::make_class<Class1>(engine, "Class1")
        .ctor();
    luacxx::make_function(engine, "fct1", fct1);
    luacxx::make_function(engine, "fct4", fct4);
    luacxx::make_function(engine, "fct5", fct5);
    luacxx::make_function(engine, "fct6", fct6)
        .get_policy()
        .get(0).delegate_owner();
    luacxx::make_function(engine, "fct7", fct7);
    luacxx::make_function(engine, "is_global", is_global);
    BOOST_CHECK(engine.bind());

    std::pair<bool, std::string> ret = engine.do_file(LUACXX_TESTS_DIR "class_02.lua");
    if(!ret.first)
    {
      BOOST_FAIL(ret.second);
    }
  }
  teardown();

  BOOST_CHECK(Class1::nb_init    == 3);
  BOOST_CHECK(Class1::nb_destroy == 3);
}

BOOST_AUTO_TEST_CASE( class_03 )
{
  setup(false);
  {
    luacxx::engine engine;
    luacxx::make_class<Class1>(engine, "Class1")
        .ctor();
    luacxx::make_function(engine, "fct1", fct1);
    luacxx::make_function(engine, "fct2", fct2);
    luacxx::make_function(engine, "fct3", fct3);
    luacxx::make_function(engine, "fct4", fct4);
    luacxx::make_function(engine, "fct7", fct7);
    BOOST_CHECK(engine.bind());

    std::pair<bool, std::string> ret = engine.do_file(LUACXX_TESTS_DIR "class_03.lua");
    if(!ret.first)
    {
      BOOST_FAIL(ret.second);
    }
  }
  teardown();

  BOOST_CHECK(Class1::nb_init    == 0);
  BOOST_CHECK(Class1::nb_destroy == 0);
}

max_stars_repo_name: EVaillant/luacxx

max_issues_repo_name: EVaillant/luacxx

max_forks_repo_name: EVaillant/luacxx


text:
#include <boost/test/unit_test.hpp>
#include <toscore/utils/JsonUtils.h>
#include <stdio.h>
#include <toscore/log/Log.h>
#include <toscore/crypto/SHA3.h>
#include <toscore/common/Common.h>
#include <toscore/log/Log.h>
#include <toscore/crypto/Hash.h>
#include <secp256k1_sha256.h>
#include <toscore/crypto/FixedHash.h>
#include <toscore/common/vector_ref.h>
#include <test/tools/TosTestUtils.h>
#include <boost/test/included/unit_test.hpp>
#include <toscore/crypto/Base64.h>
#include <boost/filesystem.hpp>
#include <toscore/jsonspirit/json_spirit.h>
#include <toscore/jsonspirit/JsonSpiritHeaders.h>
#include <set>
#include <toscore/utils/FileUtils.h>
using std::cout;
using namespace boost;
using namespace boost::unit_test;
using namespace dev;
using namespace json_spirit;

class Test
{
  public:
    bool validateFieldNames1(json_spirit::mObject const &_obj, std::set<std::string> const &_allowedFields)
    {
        for (auto const &elm : _obj)
        {
            if (_allowedFields.find(elm.first) == _allowedFields.end())
            {
                std::string const comment = "Unknown field in config: " + elm.first;
                std::cerr << comment << "\n";
                return false;
            }
        }
        return true;
    }
};

BOOST_AUTO_TEST_CASE(jsontests)
{

    // Test t;
    boost::filesystem::path filePath("demo.json");
    json_spirit::Value_impl<json_spirit::Config_map<std::string> > value;

    std::string fileName = filePath.string();
    std::ifstream is(fileName);

    json_spirit::read(is, value);
    std::set<std::string> mySet;
    mySet.insert("Code");
    mySet.insert("Description");

    // t.validateFieldNames1(value, mySet);
}

max_stars_repo_name: TOSIO/tos

max_issues_repo_name: TOSIO/tos

max_forks_repo_name: TOSIO/tos