text:
/******************************************************************************
 * HMDQ Tools - tools for VR headsets and other hardware introspection        *
 * https://github.com/risa2000/hmdq                                           *
 *                                                                            *
 * Copyright (c) 2019, Richard Musil. All rights reserved.                    *
 *                                                                            *
 * This source code is licensed under the BSD 3-Clause "New" or "Revised"     *
 * License found in the LICENSE file in the root directory of this project.   *
 * SPDX-License-Identifier: BSD-3-Clause                                      *
 ******************************************************************************/

#include "compat.h"
#include "config.h"
#include "except.h"
#include "fmthlp.h"
#include "gitversion.h"
#include "jkeys.h"
#include "json_proxy.h"
#include "jtools.h"
#include "misc.h"
#include "oculus_collector.h"
#include "oculus_config.h"
#include "oculus_processor.h"
#include "openvr_collector.h"
#include "openvr_common.h"
#include "openvr_config.h"
#include "openvr_processor.h"
#include "prtdata.h"
#include "wintools.h"

#include <clipp.h>

#include <botan/version.h>

#include <xtensor/xtensor_config.hpp>
#include <xtl/xtl_config.hpp>

#include <Eigen/Core>

#include <fmt/chrono.h>
#include <fmt/format.h>

#include <ctime>
#include <filesystem>
#include <fstream>
#include <memory>

//  defines
//------------------------------------------------------------------------------
#define xstringify(_s) stringify(_s)
#define stringify(_x) #_x

//  typedefs
//------------------------------------------------------------------------------
//  mode of operation
enum class mode { geom, props, all, info, help };

//  locals
//------------------------------------------------------------------------------
static constexpr int IND = 0;
static constexpr unsigned int CP_UTF8 = 65001;
const auto OPENVR_API_JSON = "openvr_api.json";

//  log versions
//------------------------------------------------------------------------------
//  v1: Original file format defined by the tool.
//  v2: Added secure checksum to the end of the file.
//  v3: Added new section 'openvr'.
//  v4: IPD now reported in meters (was mm).
//  v5: OpenVR related data moved into 'openvr' section.
static constexpr int LOG_VERSION = 5;

//  functions
//------------------------------------------------------------------------------
//  Print version and other usefull info.
void print_info(int ind = 0, int ts = 0)
{
    const auto sf = ind * ts;
    const auto sf1 = (ind + 1) * ts;
    constexpr int tf1 = 8;
    iprint(sf, "{:s} version {:s} - {:s}\n", PROG_NAME, PROG_VERSION, PROG_DESCRIPTION);
    fmt::print("\n");
    iprint(sf, "build info:\n");
    iprint(sf1, "{:>{}s}: {:s}\n", "git repo", tf1, PROG_URL);
    iprint(sf1, "{:>{}s}: {:s}\n", "git ver.", tf1, GIT_REPO_VERSION);
    iprint(sf1, "{:>{}s}: {:s} version {:s} ({:s})\n", "compiler", tf1, CXX_COMPILER_ID,
           CXX_COMPILER_VERSION, CXX_COMPILER_ARCHITECTURE_ID);
    iprint(sf1, "{:>{}s}: {:s} ({:s})\n", "host", tf1, HOST_SYSTEM,
           HOST_SYSTEM_PROCESSOR);
    iprint(sf1, "{:>{}s}: {:s}\n", "date", tf1, BUILD_TIMESTAMP);
    fmt::print("\n");
    iprint(sf, "using libraries:\n");
    constexpr const char* libver_nover_fmt = "{0} (https://github.com/{0})\n";
    constexpr const char* libver_str_fmt = "{0} {1} (https://github.com/{0})\n";
    constexpr const char* libver_num_fmt = "{0} {1}.{2}.{3} (https://github.com/{0})\n";
    constexpr const char* gitlab_libver_num_fmt
        = "{0} {1}.{2}.{3} (https://gitlab.com/{0})\n";
    iprint(sf1, libver_nover_fmt, "muellan/clip");
    iprint(sf1, libver_num_fmt, "nlohmann/json", NLOHMANN_JSON_VERSION_MAJOR,
           NLOHMANN_JSON_VERSION_MINOR, NLOHMANN_JSON_VERSION_PATCH);
    iprint(sf1, libver_num_fmt, "QuantStack/xtl", XTL_VERSION_MAJOR, XTL_VERSION_MINOR,
           XTL_VERSION_PATCH);
    iprint(sf1, libver_num_fmt, "QuantStack/xtensor", XTENSOR_VERSION_MAJOR,
           XTENSOR_VERSION_MINOR, xstringify(XTENSOR_VERSION_PATCH));
    iprint(sf1, libver_str_fmt, "randombit/botan", Botan::short_version_string());
    iprint(sf1, libver_num_fmt, "fmtlib/fmt", FMT_VERSION / 10000,
           (FMT_VERSION % 10000) / 100, FMT_VERSION % 100);
    const auto [vmaj, vmin, vbuild] = openvr::get_sdk_ver();
    iprint(sf1, libver_num_fmt, "ValveSoftware/openvr", vmaj, vmin, vbuild);
    iprint(sf1, "{0:s} {1:s} ({2:s})\n", "Oculus/LibOVR", OVR_VERSION_STRING,
           "https://developer.oculus.com/downloads/package/oculus-sdk-for-windows/");
    iprint(sf1, gitlab_libver_num_fmt, "libeigen/eigen", EIGEN_WORLD_VERSION,
           EIGEN_MAJOR_VERSION, EIGEN_MINOR_VERSION);
}

//  Return some miscellanous info about the app and the OS.
json get_misc()
{
    std::tm tm;

    const std::time_t t = std::time(nullptr);
    localtime_s(&tm, &t);

    json res;
    res[j_time] = fmt::format("{:%F %T}", tm);
    res[j_hmdq_ver] = PROG_VERSION;
    res[j_log_ver] = LOG_VERSION;
    res[j_os_ver] = get_os_ver();
    return res;
}

//  Translate the tool selected mode into print mode.
static pmode mode2pmode(const mode selected)
{
    switch (selected) {
        case mode::props:
            return pmode::props;
        case mode::geom:
            return pmode::geom;
        case mode::all:
            return pmode::all;
        default:
            HMDQ_EXCEPTION(fmt::format("mode2pmode({}) is undefined", selected));
    }
}

//  main runner
int run(const print_options& opts, const std::filesystem::path& api_json,
        const std::filesystem::path& out_json, int ind, int ts)
{
    // initialize config values
    const auto json_indent = g_cfg[j_format][j_json_indent].get<int>();
    const auto vdef = g_cfg[j_verbosity][j_default].get<int>();
    const auto verr = g_cfg[j_verbosity][j_error].get<int>();

    // print the execution header
    print_header(PROG_NAME, PROG_VERSION, PROG_DESCRIPTION, opts.verbosity, ind, ts);
    if (opts.verbosity >= vdef)
        fmt::print("\n");

    // output
    json out;

    // get the miscellanous (system and app) data
    out[j_misc] = get_misc();

    // collector buffer
    colmap_t collectors;
    // processor buffer
    procmap_t processors;

    // create all VR subsystem interfaces
    // OpenVR collector
    const auto openvr_app_type
        = g_cfg[j_openvr][j_app_type].get<vr::EVRApplicationType>();
    auto openvr_collector = new openvr::Collector(api_json, openvr_app_type);
    auto openvr_processor = new openvr::Processor(openvr_collector->get_xapi(),
                                                  openvr_collector->get_data());
    collectors.emplace(openvr_collector->get_id(), openvr_collector);
    processors.emplace(openvr_processor->get_id(), openvr_processor);

    // Oculus VR collector
    const auto init_flags = g_cfg[j_oculus][j_init_flags].get<ovrInitFlags>();
    auto oculus_collector = new oculus::Collector(init_flags);
    auto oculus_processor = new oculus::Processor(oculus_collector->get_data());
    collectors.emplace(oculus_collector->get_id(), oculus_collector);
    processors.emplace(oculus_processor->get_id(), oculus_processor);

    constexpr const char* RAW_JSON_NAME_FMT = "{}_raw.hmdq.json";
    bool raw_read = false;
    for (auto& [col_id, col] : collectors) {
        if (col->try_init()) {
            if (opts.dbg_raw_in) {
                const auto jinpath
                    = std::filesystem::path(fmt::format(RAW_JSON_NAME_FMT, col_id));
                if (std::filesystem::exists(jinpath)) {
                    *col->get_data() = read_json(jinpath);
                    fmt::print("DEBUG: Reading raw collected data <- {}\n",
                               jinpath.string());
                    raw_read = true;
                }
                else {
                    fmt::print("DEBUG: Raw data JSON file {} not found\n",
                               jinpath.string());
                }
            }
            if (!raw_read) {
                col->collect();
                if (opts.dbg_raw_out) {
                    const auto joutpath
                        = std::filesystem::path(fmt::format(RAW_JSON_NAME_FMT, col_id));
                    write_json(joutpath, *col->get_data(), 2);
                    fmt::print("DEBUG: Writing raw collected data -> {}\n",
                               joutpath.string());
                }
            }
            // if there is a processor registered run it now
            if (processors.find(col_id) != processors.end()) {
                auto proc = processors[col_id].get();
                proc->init();
                proc->calculate();
                if (opts.anonymize) {
                    proc->anonymize();
                }
            }
        }
    }

    print_all(opts, out, processors, ind, ts);

    // if verbosity is not high enough (verr + 1) purge the temporary data
    for (auto& [proc_id, proc] : processors) {
        if (opts.verbosity <= verr) {
            proc->purge();
        }
    }

    // put the collected data into the output JSON
    for (auto& [col_id, col] : collectors) {
        if (!col->get_data()->is_null())
            out[col_id] = *col->get_data();
    }

    // dump the data into the optional JSON file
    if (!out_json.empty()) {
        if (!raw_read) {
            // add the checksum (but only when the data are authentic)
            add_checksum(out);
        }
        // save the JSON file with indentation
        write_json(out_json, out, json_indent);
    }

    return 0;
}

//  wrapper for main runner to deal with domestic exceptions
int run_wrapper(const print_options& opts, const std::filesystem::path& api_json,
                const std::filesystem::path& out_json, int ind, int ts)
{
    int res = 0;
    try {
        res = run(opts, api_json, out_json, ind, ts);
    }
    catch (hmdq_error e) {
        fmt::print(stderr, ERR_MSG_FMT_OUT, e.what());
        res = 1;
    }
    catch (std::runtime_error e) {
        fmt::print(stderr, "{}\n", e.what());
    }
    return res;
}

int main(int argc, char* argv[])
{
    using namespace clipp;

    // Set UTF-8 code page for the console if available
    // if not, print UTF-8 strings to the console anyway.
    init_console_cp();
    set_console_cp(CP_UTF8);

    // get command line args in Windows Unicode and in UTF-8
    const auto u8args = get_u8args();
    if (u8args.size() == 0) {
        throw hmdq_error("Cannot get the command line arguments");
    }
    // print_u8args(u8args);

    // init global config before anything else
    cfgmap_t cfgs;
    auto openvr_config = new openvr::Config();
    cfgs.emplace(openvr_config->get_id(), openvr_config);
    auto oculus_config = new oculus::Config();
    cfgs.emplace(oculus_config->get_id(), oculus_config);

    const auto cfg_ok = init_config(get_full_prog_path(), cfgs);
    if (!cfg_ok)
        return 1;

    const auto ts = g_cfg[j_format][j_cli_indent].get<int>();
    const auto ind = IND;

    print_options opts;

    // defaults for the arguments
    opts.verbosity = g_cfg[j_verbosity][j_default].get<int>();
    opts.anonymize = g_cfg[j_control][j_anonymize].get<bool>();

    // default command is 'all'
    mode cmd = mode::all;

    // build relative path to OPENVR_API_JSON file
    std::filesystem::path api_json_path = get_full_prog_path();
    api_json_path.replace_filename(OPENVR_API_JSON);
    auto api_json = u8str2str(api_json_path.u8string());

    std::string out_json;
    // custom help texts
    const auto verb_help = fmt::format("verbosity level [{:d}]", opts.verbosity);
    const auto api_json_help
        = fmt::format("OpenVR API JSON definition file [\"{:s}\"]", api_json);
    const auto anon_help
        = fmt::format("anonymize serial numbers in the output [{}]", opts.anonymize);

    // Use this construct to accept an "empty" command. First parse all
    // together (cli_cmds, cli_opts) then cli_opts to accept also only the
    // options without any command.
    const auto cli_opts
        = ((option("-a", "--api_json") & value("name", api_json)) % api_json_help,
           (option("-o", "--out_json") & value("name", out_json)) % "JSON output file",
           (option("-v", "--verb").set(opts.verbosity, 1)
            & opt_value("level", opts.verbosity))
               % verb_help,
           (option("-n", "--anonymize").set(opts.anonymize, !opts.anonymize) % anon_help),
           (option("--openvr").set(opts.oculus, false).set(opts.openvr, true)
            % "show only OpenVR data"),
           (option("--oculus").set(opts.openvr, false).set(opts.oculus, true)
            % "show only Oculus data"),
           (option("--ovr_max_fov").set(opts.ovr_max_fov, true)
            % "show also Oculus max FOV data"),
           (option("--dbg_raw_in").set(opts.dbg_raw_in, true)
            % "read raw collected data from JSON file into the processor (debug)"),
           (option("--dbg_raw_out").set(opts.dbg_raw_out, true)
            % "write raw collected data into JSON file without any processing (debug)"));

    const auto cli_nocmd = cli_opts;
    const auto cli_cmds
        = ((command("geom").set(cmd, mode::geom).doc("show only geometry data")
                | command("props")
                      .set(cmd, mode::props)
                      .doc("show only device properties")
                | command("all")
                      .set(cmd, mode::all)
                      .doc("show all data (default choice)"),
            cli_nocmd)
           | command("version").set(cmd, mode::info).doc("show version and other info")
           | command("help").set(cmd, mode::help).doc("show this help page"));

    const auto cli = cli_cmds;
    const auto cli_dup = (cli_cmds | cli_nocmd);

    // build C-like argument array from UTF-8 arguments
    auto [cargv, buff] = get_c_argv(u8args);
    int res = 0;
    if (parse(cargv->size(), &(*cargv)[0], cli_dup)) {
        switch (cmd) {
            case mode::info:
                print_info(ind, ts);
                break;
            case mode::geom:
            case mode::props:
            case mode::all:
                opts.mode = mode2pmode(cmd);
                res = run_wrapper(opts, std::filesystem::path(api_json),
                                  std::filesystem::path(out_json), ind, ts);
                break;
            case mode::help:
                fmt::print("Usage:\n{:s}\nOptions:\n{:s}\n",
                           usage_lines(cli, PROG_NAME).str(), documentation(cli).str());
                break;
        }
    }
    else {
        if (parse(cargv->size(), reinterpret_cast<char**>(&(*cargv)[0]), cli_nocmd)) {
            opts.mode = mode2pmode(mode::all);
            res = run_wrapper(opts, std::filesystem::path(api_json),
                              std::filesystem::path(out_json), ind, ts);
        }
        else {
            fmt::print("Usage:\n{:s}\n", usage_lines(cli, PROG_NAME).str());
            res = 1;
        }
    }
    return res;
}


text:
#include <boost/interprocess/anonymous_shared_memory.hpp>
#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/errors.hpp>
#include <boost/interprocess/exceptions.hpp>
#include <boost/interprocess/file_mapping.hpp>
#include <boost/interprocess/interprocess_fwd.hpp>
#include <boost/interprocess/managed_external_buffer.hpp>
#include <boost/interprocess/managed_heap_memory.hpp>
#include <boost/interprocess/managed_mapped_file.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/offset_ptr.hpp>
#include <boost/interprocess/permissions.hpp>
#include <boost/interprocess/segment_manager.hpp>
#include <boost/interprocess/shared_memory_object.hpp>

int
main ()
{
  return 0;
}

ext: cpp


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2006-2007. 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)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#include <boost/interprocess/detail/config_begin.hpp>
//[doc_shared_memory
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
#include <cstring>

int main ()
{
   using namespace boost::interprocess;
   try{
      //Erase previous shared memory
      shared_memory_object::remove("shared_memory");

      //Create a shared memory object.
      shared_memory_object shm (create_only, "shared_memory", read_write);

      //Set size
      shm.truncate(1000);

      //Map the whole shared memory in this process
      mapped_region region(shm, read_write);

      //Write all the memory to 1
      std::memset(region.get_address(), 1, region.get_size());
   }
   catch(interprocess_exception &ex){
      shared_memory_object::remove("shared_memory");
      std::cout << ex.what() << std::endl;
      return 1;
   }
   return 0;
}
//]
#include <boost/interprocess/detail/config_end.hpp>


text:
/* parse_context_test.cc                                           -*- C++ -*-
   Jeremy Barnes, 16 February 2007
   Copyright (c) 2007 Jeremy Barnes.  All rights reserved.

   Test of tick counter functionality.
*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include "jml/utils/configuration.h"
#include "jml/utils/enum_info.h"
#include <boost/test/unit_test.hpp>
#include "jml/utils/vector_utils.h"

using namespace ML;
using namespace std;

using boost::unit_test::test_suite;

static const char * config1 =
"\n"
"# classifier-training.txt                                  -*- awk -*-\n"
"#\n"
"# Training parameters for the classifier training\n"
"\n"
"# classifier for small datasets.\n"
"bagged_boosted_trees {\n"
"    # main classifier makes 10 bags for stability\n"
"    type=bagging;\n"
"    num_bags=5;\n"
"    verbosity=3;\n"
"    \n"
"    # weak learner for bagging is boosted decision trees.  Boosting is good\n"
"    # for functions like this as has a smooth profile due to margin\n"
"    # maximization.\n"
"    weak_learner {\n"
"        type=boosting;\n"
"        \n"
"        min_iter=5;\n"
"        max_iter=20;\n"
"        \n"
"        verbosity=3;\n"
"        \n"
"        # weak learner for boosting is decision trees of depth 10.  A high\n"
"        # capacity classifier is needed to model the interraction between "
"        # the categorical variables.\n"
"        weak_learner {\n"
"            type=decision_tree;\n"
"            max_depth=6;\n"
"            \n"
"            # use an update algorithm suitable for boosting\n"
"            update_alg=gentle;\n"
"            \n"
"            # don't print out trees as we go\n"
"            verbosity=0;\n"
"        }\n"
"    }\n"
"}\n"
"\n"
"# classifier for when we have large datasets.\n"
"bagged_trees {\n"
"    # main classifier makes 10 bags for stability\n"
"    type=bagging;\n"
"    num_bags=10;\n"
"    verbosity=3;\n"
"    \n"
"    # weak learner for bagging is decision trees.\n"
"    weak_learner {\n"
"        type=decision_tree;\n"
"        max_depth=12;\n"
"        \n"
"        # don't print out trees as we go\n"
"        verbosity=0;\n"
"    }\n"
"}\n"
"\n"
"# Here we override any specific parameters.\n"
"case1 {\n"
"    sub1 : bagged_trees {\n"
"    }\n"
"\n"
"    sub2 : bagged_trees {\n"
"    }\n"
"\n"
"    sub3 : bagged_trees {\n"
"    }\n"
"\n"
"    sub4 : bagged_trees {\n"
"    }\n"
"\n"
"    sub5 : bagged_trees {\n"
"    }\n"
"}\n"
"\n"
"# Case 2 uses bagged boosted trees as we have less training data\n"
"case2 : case1 {\n"
"    sub1 : bagged_boosted_trees {\n"
"    }\n"
"\n"
"    sub2 : bagged_boosted_trees {\n"
"    }\n"
"\n"
"    sub3 : bagged_boosted_trees {\n"
"    }\n"
"\n"
"    sub4 : bagged_boosted_trees {\n"
"    }\n"
"\n"
"    sub5 : bagged_boosted_trees {\n"
"    }\n"
"}\n"
"\n"
"setting=0;\n"
"outer {\n"
"    setting=1;\n"
"    inner {\n"
"        setting=2;\n"
"    }\n"
"}\n"
"vector_values=1,2,3,4,5,6;\n"
"vector_values2=1,2,3,4,5,6\n"
"vector_values3 = 1,2,3,4,5,6\n"
"vector_values4 = \"w\",\"x\",\"y\";";

enum Update {
    NORMAL = 0,   ///< Normal update
    GENTLE = 1,   ///< Gentle update
    PROB   = 2    ///< Probabilistic update
};

DECLARE_ENUM_INFO(Update, 3);

ENUM_INFO_NAMESPACE

const Enum_Opt<Update>
Enum_Info<Update>::OPT[3] = {
    { "normal",      NORMAL   },
    { "gentle",      GENTLE   },
    { "prob",        PROB     } };

const char * Enum_Info<Update>::NAME = "Update";

END_ENUM_INFO_NAMESPACE

BOOST_AUTO_TEST_CASE( test1 )
{
    Configuration config;
    config.parse_string(config1, "config1 test configuration");

    BOOST_CHECK_EQUAL(config["bagged_boosted_trees.type"], "bagging");
    string t;
    BOOST_CHECK(config.find(t, "bagged_boosted_trees.type"));
    BOOST_CHECK_EQUAL(t, "bagging");

    Configuration config2(config, "bagged_boosted_trees",
                          Configuration::PREFIX_REPLACE);
    BOOST_CHECK_EQUAL(config2["type"], "bagging");
    t = "";
    BOOST_CHECK(config2.find(t, "type"));

    BOOST_CHECK_EQUAL(t, "bagging");
    BOOST_CHECK_THROW(config2["hello"] = "hello", ML::Exception);

    Configuration config3(config2, "weak_learner",
                          Configuration::PREFIX_APPEND);
    BOOST_CHECK_EQUAL(config3["type"], "boosting");
    t = "";
    BOOST_CHECK(config3.find(t, "type"));
    BOOST_CHECK_EQUAL(t, "boosting");
    BOOST_CHECK_THROW(config3["hello"] = "hello", ML::Exception);

    Configuration config4(config3, "weak_learner",
                          Configuration::PREFIX_APPEND);
    BOOST_CHECK_EQUAL(config4["type"], "decision_tree");
    t = "";
    BOOST_CHECK(config4.find(t, "type"));
    BOOST_CHECK_EQUAL(t, "decision_tree");
    BOOST_CHECK_THROW(config4["hello"] = "hello", ML::Exception);

    config["bagged_boosted_trees.weak_learner.weak_learner.type"]
        = "naive_bayes";

    BOOST_CHECK_EQUAL(config["bagged_boosted_trees.weak_learner.weak_learner.type"], "naive_bayes");
    BOOST_CHECK_EQUAL(config2["weak_learner.weak_learner.type"], "naive_bayes");
    BOOST_CHECK_EQUAL(config3["weak_learner.type"], "naive_bayes");
    BOOST_CHECK_EQUAL(config4["type"], "naive_bayes");

    unsigned u = 0;
    BOOST_CHECK(config.get(u, "bagged_boosted_trees.num_bags"));
    BOOST_CHECK_EQUAL(u, 5);
    u = 0;
    BOOST_CHECK(config.find(u, "bagged_boosted_trees.num_bags"));
    BOOST_CHECK_EQUAL(u, 5);
    u = 0;
    config.must_find(u, "bagged_boosted_trees.num_bags");
    BOOST_CHECK_EQUAL(u, 5);
    u = 0;
    config.require(u, "bagged_boosted_trees.num_bags");
    BOOST_CHECK_EQUAL(u, 5);
    u = 0;

    BOOST_CHECK(config2.get(u, "num_bags"));
    BOOST_CHECK_EQUAL(u, 5);
    u = 0;
    BOOST_CHECK(config2.find(u, "num_bags"));
    BOOST_CHECK_EQUAL(u, 5);
    u = 0;
    config2.must_find(u, "num_bags");
    BOOST_CHECK_EQUAL(u, 5);
    u = 0;
    config2.require(u, "num_bags");
    BOOST_CHECK_EQUAL(u, 5);

    /* Test enums */
    Update update = (Update)-1;
    BOOST_CHECK(config.get(update, "bagged_boosted_trees.weak_learner.weak_learner.update_alg"));
    BOOST_CHECK_EQUAL(update, GENTLE);

    BOOST_CHECK_THROW(config.get(update, "bagged_boosted_trees.weak_learner.type"), std::exception);

    vector<string> extra;
    extra.push_back("param1=value1");

    config.parse_command_line(extra);
    BOOST_CHECK_EQUAL(config["param1"], "value1");

    extra.clear();
    extra.push_back("param1.param2=value2");

    config.parse_command_line(extra);
    BOOST_CHECK_EQUAL(config["param1.param2"], "value2");

    extra.clear();
    extra.push_back("weak_learner.weak_learner.type=bonus");

    config.parse_command_line(extra);
    BOOST_CHECK_EQUAL(config["weak_learner.weak_learner.type"], "bonus");

    vector<int> v;
    config.get(v, "vector_values");
    BOOST_CHECK_EQUAL(v.size(), 6);
    BOOST_CHECK_EQUAL(v.at(0), 1);
    BOOST_CHECK_EQUAL(v.at(1), 2);
    BOOST_CHECK_EQUAL(v.at(2), 3);
    BOOST_CHECK_EQUAL(v.at(3), 4);
    BOOST_CHECK_EQUAL(v.at(4), 5);
    BOOST_CHECK_EQUAL(v.at(5), 6);

    v.clear();
    config.get(v, "vector_values2");
    BOOST_CHECK_EQUAL(v.size(), 6);
    BOOST_CHECK_EQUAL(v.at(0), 1);
    BOOST_CHECK_EQUAL(v.at(1), 2);
    BOOST_CHECK_EQUAL(v.at(2), 3);
    BOOST_CHECK_EQUAL(v.at(3), 4);
    BOOST_CHECK_EQUAL(v.at(4), 5);
    BOOST_CHECK_EQUAL(v.at(5), 6);

    v.clear();
    config.get(v, "vector_values3");
    BOOST_CHECK_EQUAL(v.size(), 6);
    BOOST_CHECK_EQUAL(v.at(0), 1);
    BOOST_CHECK_EQUAL(v.at(1), 2);
    BOOST_CHECK_EQUAL(v.at(2), 3);
    BOOST_CHECK_EQUAL(v.at(3), 4);
    BOOST_CHECK_EQUAL(v.at(4), 5);
    BOOST_CHECK_EQUAL(v.at(5), 6);

#if 0
    vector<string> v2;
    config.get(v2, "vector_values4");
    BOOST_CHECK_EQUAL(v2.size(), 3);
    BOOST_CHECK_EQUAL(v2.at(0), "w");
    BOOST_CHECK_EQUAL(v2.at(1), "x");
    BOOST_CHECK_EQUAL(v2.at(2), "y");
#endif
}

ext: cc

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: TuanTranEngineer/rtbkit

max_forks_repo_name: TuanTranEngineer/rtbkit


text:
/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * 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 Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 * Author: Julius Kammerl (julius@kammerl.de)
 */

#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>

#include <iostream>
#include <vector>
#include <stdio.h>
#include <sstream>
#include <stdlib.h>
#include <iostream>
#include <string>

#include <boost/asio.hpp>

using boost::asio::ip::tcp;

using namespace pcl;
using namespace pcl::io;

using namespace std;

class SimpleOpenNIViewer
{
  public:
    SimpleOpenNIViewer () :
      viewer_ ("Input Point Cloud - Shift-to-depth conversion viewer"),
      grabber_(0)
    {
    }

    ~SimpleOpenNIViewer ()
    {
      if (grabber_)
        delete grabber_;
    }

    void
    image_callback (const boost::shared_ptr<openni_wrapper::Image> &image,
                    const boost::shared_ptr<openni_wrapper::DepthImage> &depth_image, float)
    {

      vector<uint16_t> raw_shift_data;
      vector<uint16_t> raw_depth_data;

      vector<uint8_t> rgb_data;

      uint32_t width=depth_image->getWidth ();
      uint32_t height=depth_image->getHeight ();

      // copy raw shift data from depth_image
      raw_shift_data.resize(width*height);
      depth_image->fillDepthImageRaw (width, height, &raw_shift_data[0], static_cast<unsigned int> (width * sizeof (uint16_t)));

      // convert raw shift data to raw depth data
      raw_depth_data.resize(width*height);
      grabber_->convertShiftToDepth(&raw_shift_data[0], &raw_depth_data[0], raw_shift_data.size());

      // check for color data
      if (image->getEncoding() != openni_wrapper::Image::RGB)
      {
        // copy raw rgb data from image
        rgb_data.resize(width*height*3);
        image->fillRGB(width, height, &rgb_data[0], static_cast<unsigned int> (width * sizeof (uint8_t) * 3));
      }

      // empty pointcloud
      pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud = pcl::PointCloud<pcl::PointXYZRGB>::Ptr(new pcl::PointCloud<pcl::PointXYZRGB>());

      // convert raw depth and rgb data to pointcloud
      convert (raw_depth_data,
               rgb_data,
               width,
               height,
               depth_image->getFocalLength(),
               *cloud);

      // display pointcloud
      viewer_.showCloud (cloud);
    }

    void
    run ()
    {
      // initialize OpenNIDevice to shift-value mode
      pcl::OpenNIGrabber::Mode image_mode = pcl::OpenNIGrabber::OpenNI_Default_Mode;
      int depthformat = openni_wrapper::OpenNIDevice::OpenNI_shift_values;

      grabber_ = new pcl::OpenNIGrabber("", pcl::OpenNIGrabber::OpenNI_Default_Mode, image_mode);

      // Set the depth output format
      grabber_->getDevice ()->setDepthOutputFormat (static_cast<openni_wrapper::OpenNIDevice::DepthMode> (depthformat));

      // define image callback
      boost::function<void
      (const boost::shared_ptr<openni_wrapper::Image>&, const boost::shared_ptr<openni_wrapper::DepthImage>&, float)> image_cb =
          boost::bind (&SimpleOpenNIViewer::image_callback, this, _1, _2, _3);
      boost::signals2::connection image_connection = grabber_->registerCallback (image_cb);

      // start grabber thread
      grabber_->start ();
      while (true)
      {
        boost::this_thread::sleep (boost::posix_time::seconds (1));
      }
      grabber_->stop ();

  }

protected:

  /* helper method to convert depth&rgb data to pointcloud*/
  void
  convert (std::vector<uint16_t>& depthData_arg,
           std::vector<uint8_t>& rgbData_arg,
           size_t width_arg,
           size_t height_arg,
           float focalLength_arg,
           pcl::PointCloud<PointXYZRGB>& cloud_arg) const
  {
    size_t i;
    size_t cloud_size = width_arg * height_arg;

    int x, y, centerX, centerY;

    // Reset point cloud
    cloud_arg.points.clear ();
    cloud_arg.points.reserve (cloud_size);

    // Define point cloud parameters
    cloud_arg.width = static_cast<uint32_t> (width_arg);
    cloud_arg.height = static_cast<uint32_t> (height_arg);
    cloud_arg.is_dense = false;

    // Calculate center of disparity image
    centerX = static_cast<int> (width_arg / 2);
    centerY = static_cast<int> (height_arg / 2);

    const float fl_const = 1.0f / focalLength_arg;
    static const float bad_point = std::numeric_limits<float>::quiet_NaN ();

    i = 0;
    for (y = -centerY; y < +centerY; ++y)
      for (x = -centerX; x < +centerX; ++x)
      {
        PointXYZRGB newPoint;

        const uint16_t& pixel_depth = depthData_arg[i];

        if (pixel_depth)
        {
          float depth = pixel_depth/1000.0f; // raw mm -> m

          // Define point location
          newPoint.z = depth;
          newPoint.x = static_cast<float> (x) * depth * fl_const;
          newPoint.y = static_cast<float> (y) * depth * fl_const;

          const uint8_t& pixel_r = rgbData_arg[i * 3 + 0];
          const uint8_t& pixel_g = rgbData_arg[i * 3 + 1];
          const uint8_t& pixel_b = rgbData_arg[i * 3 + 2];

          // Define point color
          uint32_t rgb = (static_cast<uint32_t> (pixel_r) << 16 | static_cast<uint32_t> (pixel_g) << 8
              | static_cast<uint32_t> (pixel_b));
          newPoint.rgb = *reinterpret_cast<float*> (&rgb);
        }
        else
        {
          // Define bad point
          newPoint.x = newPoint.y = newPoint.z = bad_point;
          newPoint.rgb = 0.0f;
        }

        // Add point to cloud
        cloud_arg.points.push_back (newPoint);
        // Increment point iterator
        ++i;
      }
  }

  pcl::visualization::CloudViewer viewer_;
  pcl::OpenNIGrabber* grabber_;

};

int
main (int, char **)
{
  SimpleOpenNIViewer v;
  v.run ();

  return (0);
}


text:
/*
  Copyright (c) 2014-2016 DataStax

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

#ifdef STAND_ALONE
#   define BOOST_TEST_MODULE cassandra
#endif

#include "copy_on_write_ptr.hpp"
#include "ref_counted.hpp"

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

BOOST_AUTO_TEST_SUITE(copy_on_write)

BOOST_AUTO_TEST_CASE(simple)
{
  std::vector<int>* ptr = new std::vector<int>;
  cass::CopyOnWritePtr<std::vector<int> > vec(ptr);

  // Only a single reference so no copy should be made
  BOOST_CHECK(static_cast<const cass::CopyOnWritePtr<std::vector<int> >&>(vec).operator->() == ptr);
  vec->push_back(1);
  BOOST_CHECK(static_cast<const cass::CopyOnWritePtr<std::vector<int> >&>(vec).operator->() == ptr);

  // Make const reference to object
  const cass::CopyOnWritePtr<std::vector<int> > const_vec(vec);
  BOOST_CHECK((*const_vec)[0] == 1);
  BOOST_CHECK(const_vec.operator->() == ptr);

  // Force copy to be made
  vec->push_back(2);
  BOOST_CHECK(static_cast<const cass::CopyOnWritePtr<std::vector<int> >&>(vec).operator->() != ptr);
  BOOST_CHECK(const_vec.operator->() == ptr);
}

struct Table : public cass::RefCounted<Table> {
  typedef cass::SharedRefPtr<Table> Ptr;
  typedef std::map<std::string, Table::Ptr> Map;

  Table(const std::string name)
    : name(name) { }

  std::string name;
private:
  DISALLOW_COPY_AND_ASSIGN(Table);
};

struct Keyspace {
  typedef std::map<std::string, Keyspace> Map;

  Keyspace()
    : tables(new Table::Map) { }

  void add_table(const Table::Ptr& table) {
    (*tables)[table->name] = table;
  }

  cass::CopyOnWritePtr<Table::Map> tables;
};

struct Metadata {
  Metadata()
    : keyspaces(new Keyspace::Map) { }

  Keyspace* get_or_create(const std::string& name) {
    return &(*keyspaces)[name];
  }

  cass::CopyOnWritePtr<Keyspace::Map> keyspaces;
};

BOOST_AUTO_TEST_CASE(nested)
{
  Metadata m1;
  Keyspace* k1 = m1.get_or_create("k1");
  k1->add_table(Table::Ptr(new Table("t1")));
  k1->add_table(Table::Ptr(new Table("t2")));

  Keyspace* k2 = m1.get_or_create("k2");
  k2->add_table(Table::Ptr(new Table("t1")));
  k2->add_table(Table::Ptr(new Table("t2")));

  Metadata m2 = m1;

  m1.get_or_create("k1")->add_table(Table::Ptr(new Table("t2")));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: tcpcloud/debian-cassandra-cpp-driver

max_issues_repo_name: tcpcloud/debian-cassandra-cpp-driver

max_forks_repo_name: tcpcloud/debian-cassandra-cpp-driver


text:
#define BOOST_TEST_MODULE pcraster dal environment
#include <boost/test/unit_test.hpp>
#include "dev_Utils.h"
#include "dal_Environment.h"

BOOST_AUTO_TEST_CASE(dal_formats)
{
  using namespace dal;

#ifdef _WIN32
  BOOST_WARN_MESSAGE(false, "Environment handling does not work on Windows");
#else
  {
    dev::unsetEnvironmentVariable("PCRASTER_DAL_FORMATS");
    BOOST_CHECK(!dev::environmentVariableSet("PCRASTER_DAL_FORMATS"));
    Environment environment("/usr/bin/dal");
    BOOST_CHECK(environment.formatNames().empty());
  }

  {
    dev::setEnvironmentVariable("PCRASTER_DAL_FORMATS", "PCRaster");
    BOOST_CHECK(dev::environmentVariableSet("PCRASTER_DAL_FORMATS"));
    Environment environment("/usr/bin/dal");
    BOOST_REQUIRE_EQUAL(environment.formatNames().size(), size_t(1));
    BOOST_CHECK_EQUAL(environment.formatNames()[0], "PCRaster");
  }

  {
    dev::setEnvironmentVariable("PCRASTER_DAL_FORMATS",
         " PCRaster, HDF4, , ESRI Shapefile , HDF4");
    Environment environment("/usr/bin/dal");
    BOOST_REQUIRE_EQUAL(environment.formatNames().size(), size_t(3));
    BOOST_CHECK_EQUAL(environment.formatNames()[0], "PCRaster");
    BOOST_CHECK_EQUAL(environment.formatNames()[1], "HDF4");
    BOOST_CHECK_EQUAL(environment.formatNames()[2], "ESRI Shapefile");
  }
#endif
}

BOOST_AUTO_TEST_CASE(gdal_data)
{
  using namespace dal;

#ifdef _WIN32
  BOOST_WARN_MESSAGE(false, "Environment handling does not work on Windows");
#else
  // Set variable if it is not already set.
  {
    dev::unsetEnvironmentVariable("GDAL_DATA");
    Environment environment("/usr");
    BOOST_CHECK_EQUAL(environment.gdalData(), "/usr/share/gdal");
  }

  // Don't touch variable if it is already set.
  {
    dev::setEnvironmentVariable("GDAL_DATA", "");
    Environment environment("/usr");
    BOOST_CHECK_EQUAL(environment.gdalData(), "");
  }

  // Don't touch variable if it is already set.
  {
    dev::setEnvironmentVariable("GDAL_DATA", " ");
    Environment environment("/usr");
    BOOST_CHECK_EQUAL(environment.gdalData(), std::string(" "));
  }
#endif
}

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 5/19/2020, 3:57:45 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- LCA -----

class LCA
{
  // helper classes
  struct Edge
  {
    // Initialized by initializer list. Take care fore the order of the field.
    int src, dst;
    ll cost;
  };

  struct Vertex
  {
    int depth;
    ll length;
  };

  // fields
  int N, root, L;
  vector<vector<Edge>> E;
  vector<Vertex> V;
  vector<vector<int>> ancestors;

  // methods
public:
  LCA(int N, int root = 0);
  void add_edge(int a, int b, ll c = 0);
  void init();
  void init(int root); // after adding all edges.

  // LCA
  int operator()(int a, int b);

  int depth(int a, int b) { return V[a].depth + V[b].depth - 2 * V[(*this)(a, b)].depth; }
  int depth(int v) { return depth(v, root); }
  ll length(int a, int b) { return V[a].length + V[b].length - 2 * V[(*this)(a, b)].length; }
  ll length(int v) { return length(v, root); }
  int parent(int v) { return ancestors[v][0]; }

private:
  void dfs(int v, int d = 0, ll l = 0, int p = -1);
};

// LCA: implement

LCA::LCA(int N, int root) : N{N}, root{root}, L{0}, E(N), V(N)
{
  while ((1 << L) < N)
  {
    ++L;
  }
  ancestors = vector<vector<int>>(N + 1, vector<int>(L, N));
}

void LCA::add_edge(int a, int b, ll c)
{
  E[a].push_back(LCA::Edge{a, b, c});
  E[b].push_back(LCA::Edge{b, a, c});
}

void LCA::init(int root)
{
  LCA::root = root;
  init();
}

void LCA::init()
{
  dfs(root);
  for (auto i = 0; i < L - 1; i++)
  {
    for (auto v = 0; v < N; v++)
    {
      if (ancestors[v][i] != -1)
      {
        ancestors[v][i + 1] = ancestors[ancestors[v][i]][i];
      }
    }
  }
}

int LCA::operator()(int a, int b)
{
  if (V[a].depth > V[b].depth)
  {
    swap(a, b);
  }
  int gap = V[b].depth - V[a].depth;
  for (auto i = L - 1; i >= 0; i--)
  {
    int len{1 << i};
    if (gap >= len)
    {
      gap -= len;
      b = ancestors[b][i];
    }
  }
  if (a == b)
  {
    return a;
  }
  for (auto i = L - 1; i >= 0; i--)
  {
    int na{ancestors[a][i]};
    int nb{ancestors[b][i]};
    if (na != nb)
    {
      a = na;
      b = nb;
    }
  }
  return ancestors[a][0];
}

void LCA::dfs(int v, int d, ll l, int p)
{
  if (p != -1)
  {
    ancestors[v][0] = p;
  }
  V[v].depth = d;
  V[v].length = l;
  for (auto const &e : E[v])
  {
    int u{e.dst};
    if (u == p)
    {
      continue;
    }
    dfs(u, d + 1, l + e.cost, v);
  }
}

// ----- main() -----

struct Query
{
  int id, color, y, coefficient;
};

struct Edge
{
  int src, dst, color, cost;
};

class Solve
{
  int N, Q;
  vector<vector<Edge>> V;
  vector<vector<Query>> W;
  LCA lca;
  vector<int> ans;
  vector<int> sum, cnt;

public:
  Solve(int N, int Q) : N{N}, Q{Q}, V(N), W(N), lca{N}, ans(Q), sum(N - 1, 0), cnt(N - 1, 0)
  {
    for (auto i = 0; i < N - 1; ++i)
    {
      int a, b, c, d;
      cin >> a >> b >> c >> d;
      --a;
      --b;
      --c;
      V[a].push_back({a, b, c, d});
      V[b].push_back({b, a, c, d});
      lca.add_edge(a, b, d);
    }
    lca.init(0);
    for (auto i = 0; i < Q; ++i)
    {
      int x, y, u, v;
      cin >> x >> y >> u >> v;
      --x;
      --u;
      --v;
      W[u].push_back({i, x, y, 1});
      W[v].push_back({i, x, y, 1});
      W[lca(u, v)].push_back({i, x, y, -2});
      ans[i] = lca.length(u, v);
    }
  }

  void flush()
  {
    dfs();
    for (auto i = 0; i < Q; ++i)
    {
      cout << ans[i] << endl;
    }
  }

private:
  void dfs(int u = 0, int p = -1)
  {
#if DEBUG == 1
    cerr << "u = " << u << ", p = " << p << endl;
#endif
    for (auto const &q : W[u])
    {
      ans[q.id] += q.coefficient * (-sum[q.color] + cnt[q.color] * q.y);
#if DEBUG == 1
      cerr << "ans[" << q.id << "] += " << q.coefficient << " * (-" << sum[q.color] << " + " << cnt[q.color] << " * " << q.y << ")" << endl;
#endif
    }
    for (auto const &e : V[u])
    {
      if (e.dst == p)
      {
        continue;
      }
      sum[e.color] += e.cost;
      cnt[e.color]++;
      dfs(e.dst, u);
      sum[e.color] -= e.cost;
      cnt[e.color]--;
    }
  }
};

int main()
{
  int N, Q;
  cin >> N >> Q;
  Solve solve(N, Q);
  solve.flush();
}

max_stars_repo_name: kazunetakahashi/atcoder

max_issues_repo_name: kazunetakahashi/atcoder

max_forks_repo_name: kazunetakahashi/atcoder


text:
#include <iostream>
#include <cmath>
#include <Eigen/Dense>
#include "LCPSolve.h"

using namespace Eigen;
using namespace std;

// Forward declarations.
bool checkCompatability(const MatrixXd &M, const int &dim);
bool checkTrivialSol(const VectorXd &q);
MatrixXd constructTableau(const MatrixXd &M, const VectorXd &q);
void pivot(MatrixXd &tableau, const int &row, const int &col);
int initializeTableau(MatrixXd &tableau);
VectorXd basicVars(const MatrixXd &tableau);
bool checkSol(const MatrixXd &tableau);
bool checkRayTermination(const MatrixXd &tableu, const int &pivotCol);
int minRatioTest(const MatrixXd &tableau, const int &pivotCol);
MatrixXd extractSolution(const MatrixXd &tableau);

// Solve LCP by Lemke's Method.
LCP LCPSolve(MatrixXd M, VectorXd q) {
    const int dim = q.size();

    // Initialize LCP data structure.
    LCP solution {};
    solution.M = M;
    solution.q = q;

    // Check that inputs are compatable.
    bool compatable = checkCompatability(M, dim);
    if (!compatable) {
        solution.exitCond = 2;
        return solution;
    }

    // Check for trivial solution.
    bool trivial = checkTrivialSol(q);
    if (trivial) {
        solution.z = VectorXd::Zero(dim);
        solution.w = q;
        solution.exitCond = 0;
        return solution;
    }

    // Construct & initialize tableau.
    MatrixXd tableau = constructTableau(M, q);
    VectorXd index = VectorXd::LinSpaced(dim, 0, dim-1);

    int pivotCol = initializeTableau(tableau);
    int pivotRow = pivotCol - dim;
    index(pivotRow) = 2*dim;

    // Now, the tableau is initialized with a feasible basis. Pivot until there is a feasible basis w/o z0.
    const int maxIter {pow(2, dim)};
    int iter {0};
    bool solFound = false;
    while ((!solFound) && (iter < maxIter)) {
        // Check for ray termination.
        bool rayTermination = checkRayTermination(tableau, pivotCol);
        if (rayTermination) {
            solFound = true;
        } else {
            // Minimum ratio test to determine the pivot row (blocked/dropped variable).
            pivotRow = minRatioTest(tableau, pivotCol);
            pivot(tableau, pivotRow, pivotCol);
            int drop = index(pivotRow);
            index(pivotRow) = pivotCol;

            // Find next entering variable (pivotCol). Dropped variable is pivotRow.
            if (drop > dim-1) {
                pivotCol = drop - dim;
            } else {
                pivotCol = drop + dim;
            }

            // Check for solution.
            solFound = checkSol(tableau);
            iter++;
        }
    }

    // Return solution.
    if (solFound) {
        MatrixXd sols = extractSolution(tableau);
        solution.z = sols.col(0);
        solution.w = sols.col(1);
        solution.exitCond = 0;
    } else {
        MatrixXd sols = extractSolution(tableau);
        solution.z = sols.col(0);
        solution.w = sols.col(1);
        solution.exitCond = 3;
    }

    return solution;
}

// Check that the inputs M and q are compatable.
bool checkCompatability(const MatrixXd &M, const int &dim) {
    const int rows = M.rows();
    const int cols = M.cols();

    if (rows != cols)
        return false;
    else if (rows != dim)
        return false;
    else
        return true;
}

// Check for trivial solution where q is positive.
bool checkTrivialSol(const VectorXd &q) {
    const int dim = q.size();
    for (int i = 0; i < dim; i++)
        if (q[i] <= 0)
            return false;
    return true;
}

// Construct Lemke tableau with auxilillary variable.
MatrixXd constructTableau(const MatrixXd &M, const VectorXd &q) {
    const int dim = q.size();
    MatrixXd tableau = MatrixXd::Zero(dim, 2*dim + 2); // Initialize with zeros.
    VectorXd auxVar = -VectorXd::Ones(dim); // Auxillary variable z_0 = {-1, -1, ... -1}.
    tableau.topLeftCorner(dim, dim) = MatrixXd::Identity(dim, dim); // Enter identity matrix on left side (w_1, w_2, etc).
    tableau.middleCols(dim, dim) = -M; // Enter I-M (z_1, z_2, etc).
    tableau.col(2*dim) = auxVar; // Enter auxiliary variable.
    tableau.col(2*dim + 1) = q; // Enter q.
    return tableau;
}

// Pivot function.
void pivot(MatrixXd &tableau, const int &row, const int &col) {
    const int dim = tableau.rows();
    double pivotElement = tableau(row, col);
    VectorXd newPivotRow = (1/pivotElement)*tableau.row(row);
    tableau.row(row) = newPivotRow;

    VectorXd newNonPivotRow {};
    for (int i = 0; i < dim; i++) {
        if (i != row) {
            newNonPivotRow = tableau.row(i) - tableau(i, col)*tableau.row(row);
            tableau.row(i) = newNonPivotRow;
        }
    }
}

// Initialize tableau.
int initializeTableau(MatrixXd &tableau) {
    const int dim = tableau.rows();
    const int cols = 2*dim +2;

    // Pivot row of min element of q w.r.t. aux column.
    int minRow {0};
    double minVal = tableau.coeff(minRow, cols-1);
    for (int i = 1; i < dim; i++) {
        if (tableau.coeff(i, cols-1) < minVal) {
            minRow = i;
            minVal = tableau(minRow, cols-1);
        }
    }

    pivot(tableau, minRow, cols-2);

    // Return the next entering variable, which is the complement to the non-basic variable.
    int newPivotCol = minRow + dim;
    return newPivotCol;
}

// Return which variables are basic.
VectorXd basicVars(const MatrixXd &tableau) {
    int cols = tableau.cols();
    double varNorm {};
    VectorXd isBasic = VectorXd::Zero(cols - 1);

    double err {1e-8};
    for (int i = 0; i < cols - 1; i++) {
        varNorm = tableau.col(i).norm();
        if (abs(1 - varNorm) < err) {
            isBasic[i] = true;
        } else {
            isBasic[i] = false;
        }
    }

    return isBasic;
}

// Check for solution.
bool checkSol(const MatrixXd &tableau) {

    // Determine basic variables.
    VectorXd isBasic = basicVars(tableau);

    // Size information and initialize q & z0.
    bool solFound {false};
    int dim = tableau.rows();
    int cols = 2*dim + 2;
    VectorXd q = tableau.col(cols-1);
    VectorXd z0 = tableau.col(cols-2);

    // No solution if any element of q is negative.
    for (int i = 0; i <= dim-1; i++) {
        if (q[i] < 0) {
            return solFound;
        }
    }

    // No solution if auxillary variable z0 is basic.
    if (isBasic[cols-2] == 1) {
        return solFound;
    }

    // If q is positive and z0 is non-basic, solution has been found.
    solFound = true;
    return solFound;
}

// Check for secondary ray termination.
bool checkRayTermination(const MatrixXd &tableu, const int &pivotCol) {
    VectorXd column = tableu.col(pivotCol);
    int negTestSum {0};
    for (int i {0}; i < column.size(); i++) {
        if (column(i) <= 0) {
            negTestSum++;
        }
    }

    if (negTestSum == column.size()) {
        return true;
    } else {
        return false;
    }
}

// Minimum ratio test to determine pivot row.
int minRatioTest(const MatrixXd &tableau, const int &pivotCol) {
    const int dim = tableau.rows();

    VectorXd ratioTest = VectorXd::Zero(dim);
    for (int i = 0; i < dim; i++) {
        ratioTest[i] = tableau.coeff(i, 2*dim + 1) / tableau.coeff(i, pivotCol);
        if (ratioTest[i] < 0) {
            ratioTest[i] = 1e10;
        }
    }

    int pivotRow {0};
    double minRatio = ratioTest[0];
    for (int i = 1; i < dim; i++) {
        if (ratioTest[i] < minRatio) {
            minRatio = ratioTest[i];
            pivotRow = i;
        }
    }

    return pivotRow;
}

// Extract solution from tableau.
MatrixXd extractSolution(const MatrixXd &tableau) {
    const int dim = tableau.rows();
    MatrixXd A = MatrixXd::Zero(dim, 2*dim);
    VectorXd z = VectorXd::Zero(dim);
    VectorXd w = VectorXd::Zero(dim);
    VectorXd isBasic = basicVars(tableau);

    for (int i = 0; i < 2*dim; i++)
        if (isBasic[i] == 1)
            A.col(i) = tableau.col(i);

    for (int i = 0; i < 2*dim; i++) {
        if (i < dim) {
            w[i] = A.col(i).dot(tableau.col(2*dim + 1));
        } else {
            z[i-dim] = A.col(i).dot(tableau.col(2*dim + 1));
        }
    }

    MatrixXd sols = MatrixXd::Zero(dim, 2);
    sols.col(0) = z;
    sols.col(1) = w;
    return sols;
}

max_stars_repo_name: Tom-Forsyth/LCPSolve

max_issues_repo_name: Tom-Forsyth/LCPSolve

max_forks_repo_name: Tom-Forsyth/LCPSolve


text:
/**
 * @file   GLVolumeInitializer.cpp
 * @author Sebastian Maisch <sebastian.maisch@uni-ulm.de>
 * @date   2015.09.21
 *
 * @brief
 */

#include "GLVolumeInitializer.h"
#include "app/ApplicationBase.h"
#include "app/Configuration.h"
#include <fstream>
#include <codecvt>
#include <boost/filesystem.hpp>
#include <boost/assign.hpp>

namespace cgu {
    namespace gpgpu {

        GLVolumeInitializer::GLVolumeInitializer(unsigned int width, unsigned int height, unsigned int depth,
            const TextureDescriptor& desc) :
            volSize(width, height, depth),
            texDesc(desc)
        {
        }

        GLVolumeInitializer::~GLVolumeInitializer() = default;

        std::shared_ptr<Volume> GLVolumeInitializer::InitChecker(const std::string& filename, const glm::uvec3& checkerSize, ApplicationBase* app) const
        {
            auto initProg = app->GetGPUProgramManager()->GetResource("synthChecker.cp");
            auto uniformNames = initProg->GetUniformLocations(boost::assign::list_of<std::string>("resultImg")("checkerSize")("offset"));
            return InitGeneral(filename, initProg.get(), uniformNames, app, [&](const glm::uvec3& chunkPos,
                const glm::uvec3& dataSize, const TextureDescriptor& internalTexDesc, std::fstream& rawOut){

                GLTexture resultTex(dataSize.x, dataSize.y, dataSize.z, 1, internalTexDesc, nullptr);

                                   auto numGroups = glm::ivec3(glm::ceil(glm::vec3(dataSize) / 8.0f));
                resultTex.ActivateImage(0, 0, GL_WRITE_ONLY);
                initProg->SetUniform(uniformNames[1], checkerSize);
                initProg->SetUniform(uniformNames[2], chunkPos);
                OGL_CALL(glDispatchCompute, numGroups.x, numGroups.y, numGroups.z);
                OGL_CALL(glMemoryBarrier, GL_ALL_BARRIER_BITS);
                OGL_SCALL(glFinish);

                std::vector<uint8_t> resultData;
                resultTex.DownloadData(resultData);

                WriteRaw(resultData, rawOut, chunkPos, dataSize, volSize, texDesc.bytesPP);
            });
            /*assert(texDesc.format == GL_RED);

            std::string baseFileName = filename.substr(0, filename.find_last_of("."));
            std::string newFilename = app->GetConfig().resourceBase + "/" + baseFileName + ".dat";
            std::string path = newFilename.substr(0, newFilename.find_last_of("/\\"));

            if (!boost::filesystem::exists(newFilename)) {
                std::ofstream datOut(newFilename, std::ofstream::out | std::ofstream::trunc);
                if (!datOut.is_open()) {
                    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
                    LOG(ERROR) << "Could not open file '" << converter.from_bytes(newFilename) << "'.";
                    throw std::runtime_error("Could not open file '" + newFilename + "'.");
                }

                std::string rawFileName = baseFileName + ".raw";

                std::string newFormat = "UCHAR";
                if (texDesc.type == GL_UNSIGNED_SHORT) newFormat = "USHORT";
                else if (texDesc.type == GL_UNSIGNED_INT) newFormat = "UINT";

                datOut << "ObjectFileName:\t" << rawFileName << std::endl;
                datOut << "Resolution:\t" << volSize.x << " " << volSize.y << " " << volSize.z << std::endl;
                datOut << "SliceThickness:\t" << 1 << " " << 1 << " " << 1 << std::endl;
                datOut << "Format:\t" << newFormat << std::endl;
                datOut << "ObjectModel:\tI" << std::endl;

                datOut.close();

                std::fstream rawOut(app->GetConfig().resourceBase + "/" + rawFileName,
                    std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
                if (!rawOut.is_open()) {
                    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
                    LOG(ERROR) << "Could not open file '" << converter.from_bytes(rawFileName) << "'.";
                    throw std::runtime_error("Could not open file '" + rawFileName + "'.");
                }

                TextureDescriptor internalTexDesc = texDesc;
                internalTexDesc.internalFormat = GL_R32F;

                GPUProgram* initProg = app->GetGPUProgramManager()->GetResource("synthChecker.cp");
                std::vector<BindingLocation> uniformNames = initProg->GetUniformLocations(boost::assign::list_of<std::string>("resultImg")("checkerSize")("offset"));

                initProg->UseProgram();
                initProg->SetUniform(uniformNames[0], 0);

                glm::uvec3 chunkSize(256);
                glm::uvec3 chunkPos(0);
                for (; chunkPos.z < volSize.z; chunkPos.z += chunkSize.z) {
                    for (; chunkPos.y < volSize.y; chunkPos.y += chunkSize.y) {
                        for (; chunkPos.x < volSize.x; chunkPos.x += chunkSize.x) {
                            glm::uvec3 dataSize = glm::min(chunkSize, volSize - chunkPos);
                            GLTexture resultTex(dataSize.x, dataSize.y, dataSize.z, 1, internalTexDesc, nullptr);

                            glm::ivec3 numGroups = glm::ivec3(glm::ceil(glm::vec3(dataSize) / 8.0f));
                            resultTex.ActivateImage(0, 0, GL_WRITE_ONLY);
                            initProg->SetUniform(uniformNames[1], checkerSize);
                            initProg->SetUniform(uniformNames[2], chunkPos);
                            OGL_CALL(glDispatchCompute, numGroups.x, numGroups.y, numGroups.z);
                            OGL_CALL(glMemoryBarrier, GL_ALL_BARRIER_BITS);
                            OGL_SCALL(glFinish);

                            std::vector<uint8_t> resultData;
                            resultTex.DownloadData(resultData);

                            WriteRaw(resultData, rawOut, chunkPos, dataSize, volSize, texDesc.bytesPP);
                        }
                        chunkPos.x = 0;
                    }
                    chunkPos.y = 0;
                }
                rawOut.close();
            }

            return app->GetVolumeManager()->GetResource(baseFileName + ".dat");*/
        }

        std::shared_ptr<Volume> GLVolumeInitializer::InitStripes(const std::string& filename, unsigned int stripeSize, ApplicationBase* app) const
        {
            auto initProg = app->GetGPUProgramManager()->GetResource("synthStripes.cp");
            auto uniformNames = initProg->GetUniformLocations(boost::assign::list_of<std::string>("resultImg")("stripeSize")("offset"));
            return InitGeneral(filename, initProg.get(), uniformNames, app, [&](const glm::uvec3& chunkPos,
                const glm::uvec3& dataSize, const TextureDescriptor& internalTexDesc, std::fstream& rawOut){

                GLTexture resultTex(dataSize.x, dataSize.y, dataSize.z, 1, internalTexDesc, nullptr);

                                   auto numGroups = glm::ivec3(glm::ceil(glm::vec3(dataSize) / 8.0f));
                resultTex.ActivateImage(0, 0, GL_WRITE_ONLY);
                initProg->SetUniform(uniformNames[1], glm::uvec3(stripeSize));
                initProg->SetUniform(uniformNames[2], chunkPos);
                OGL_CALL(glDispatchCompute, numGroups.x, numGroups.y, numGroups.z);
                OGL_CALL(glMemoryBarrier, GL_ALL_BARRIER_BITS);
                OGL_SCALL(glFinish);

                std::vector<uint8_t> resultData;
                resultTex.DownloadData(resultData);

                WriteRaw(resultData, rawOut, chunkPos, dataSize, volSize, texDesc.bytesPP);
            });
        }

        std::shared_ptr<Volume> GLVolumeInitializer::InitSpherical(const std::string& filename, const glm::vec3& sphereCenter,
            const glm::vec3& sphereScale, ApplicationBase* app) const
        {
            auto initProg = app->GetGPUProgramManager()->GetResource("synthSpherical.cp");
            auto uniformNames = initProg->GetUniformLocations(boost::assign::list_of<std::string>("resultImg")("sphereCenter")("sphereScale")("offset"));
            return InitGeneral(filename, initProg.get(), uniformNames, app, [&](const glm::uvec3& chunkPos,
                const glm::uvec3& dataSize, const TextureDescriptor& internalTexDesc, std::fstream& rawOut){

                GLTexture resultTex(dataSize.x, dataSize.y, dataSize.z, 1, internalTexDesc, nullptr);

                auto numGroups = glm::ivec3(glm::ceil(glm::vec3(dataSize) / 8.0f));
                resultTex.ActivateImage(0, 0, GL_WRITE_ONLY);
                initProg->SetUniform(uniformNames[1], sphereCenter);
                initProg->SetUniform(uniformNames[2], sphereScale);
                initProg->SetUniform(uniformNames[3], chunkPos);
                OGL_CALL(glDispatchCompute, numGroups.x, numGroups.y, numGroups.z);
                OGL_CALL(glMemoryBarrier, GL_ALL_BARRIER_BITS);
                OGL_SCALL(glFinish);

                std::vector<uint8_t> resultData;
                resultTex.DownloadData(resultData);

                WriteRaw(resultData, rawOut, chunkPos, dataSize, volSize, texDesc.bytesPP);
            });
        }

        std::shared_ptr<Volume> GLVolumeInitializer::InitGeneral(const std::string& filename, GPUProgram* initProg,
            const std::vector<BindingLocation>& uniformNames, ApplicationBase* app,
            std::function<void(const glm::uvec3&, const glm::uvec3&, const TextureDescriptor&, std::fstream&)> chunkInitialize) const
        {
            assert(texDesc.format == GL_RED);

            auto baseFileName = filename.substr(0, filename.find_last_of("."));
            auto newFilename = app->GetConfig().resourceBase + "/" + baseFileName + ".dat";
            auto path = newFilename.substr(0, newFilename.find_last_of("/\\"));

            if (!boost::filesystem::exists(newFilename)) {
                std::ofstream datOut(newFilename, std::ofstream::out | std::ofstream::trunc);
                if (!datOut.is_open()) {
                    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
                    LOG(ERROR) << "Could not open file '" << converter.from_bytes(newFilename) << "'.";
                    throw std::runtime_error("Could not open file '" + newFilename + "'.");
                }

                auto rawFileName = baseFileName + ".raw";

                std::string newFormat = "UCHAR";
                if (texDesc.type == GL_UNSIGNED_SHORT) newFormat = "USHORT";
                else if (texDesc.type == GL_UNSIGNED_INT) newFormat = "UINT";

                datOut << "ObjectFileName:\t" << rawFileName << std::endl;
                datOut << "Resolution:\t" << volSize.x << " " << volSize.y << " " << volSize.z << std::endl;
                datOut << "SliceThickness:\t" << 1 << " " << 1 << " " << 1 << std::endl;
                datOut << "Format:\t" << newFormat << std::endl;
                datOut << "ObjectModel:\tI" << std::endl;

                datOut.close();

                std::fstream rawOut(app->GetConfig().resourceBase + "/" + rawFileName,
                    std::ios_base::in | std::ios_base::out | std::ios_base::binary | std::ios_base::trunc);
                if (!rawOut.is_open()) {
                    std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
                    LOG(ERROR) << "Could not open file '" << converter.from_bytes(rawFileName) << "'.";
                    throw std::runtime_error("Could not open file '" + rawFileName + "'.");
                }

                auto internalTexDesc = texDesc;
                internalTexDesc.internalFormat = GL_R32F;

                initProg->UseProgram();
                initProg->SetUniform(uniformNames[0], 0);

                glm::uvec3 chunkSize(256);
                glm::uvec3 chunkPos(0);
                for (; chunkPos.z < volSize.z; chunkPos.z += chunkSize.z) {
                    for (; chunkPos.y < volSize.y; chunkPos.y += chunkSize.y) {
                        for (; chunkPos.x < volSize.x; chunkPos.x += chunkSize.x) {
                            auto dataSize = glm::min(chunkSize, volSize - chunkPos);
                            chunkInitialize(chunkPos, dataSize, internalTexDesc, rawOut);
                        }
                        chunkPos.x = 0;
                    }
                    chunkPos.y = 0;
                }
                rawOut.close();
            }

            return std::move(app->GetVolumeManager()->GetResource(baseFileName + ".dat"));
        }

        void GLVolumeInitializer::ReadRaw(std::vector<uint8_t>& data, std::fstream& fileStream, const glm::uvec3& pos,
            const glm::uvec3& dataSize, const glm::uvec3& volumeSize, unsigned int bytesPV)
        {
            data.resize(volumeSize.x * volumeSize.y * volumeSize.z * bytesPV, 0);
            auto lineSize = volumeSize.x * bytesPV;
            auto dataPtr = reinterpret_cast<char*>(data.data());

            for (unsigned int z = 0; z < dataSize.z; ++z) {
                for (unsigned int y = 0; y < dataSize.y; ++y) {
                    auto lineStartFile = ((pos.z + z) * volumeSize.y * lineSize) + ((pos.y + y) * lineSize) + pos.x * bytesPV;
                    fileStream.seekg(lineStartFile, std::ios::beg);
                    fileStream.read(dataPtr, dataSize.x * bytesPV);
                    dataPtr += volumeSize.x * bytesPV;
                }
            }
        }

        /**
        *  Writes data in 3D chunks to a file.
        *  @param data the raw data of the chunk to write.
        *  @param fileStream the stream to write to.
        *  @param pos the position inside the file to write to.
        *  @param dataSize the dimensions of the data.
        *  @param volumeSize the dimensions of the complete volume.
        *  @param bytesPV the number of bytes per voxel.
        */
        void GLVolumeInitializer::WriteRaw(std::vector<uint8_t>& data, std::fstream& fileStream, const glm::uvec3& pos,
            const glm::uvec3& dataSize, const glm::uvec3& volumeSize, unsigned int bytesPV)
        {
            auto fileLineSize = volumeSize.x * bytesPV;
            auto dataPtr = reinterpret_cast<char*>(data.data());

            for (unsigned int z = 0; z < dataSize.z; ++z) {
                for (unsigned int y = 0; y < dataSize.y; ++y) {
                    auto lineStartFile = ((pos.z + z) * volumeSize.y * fileLineSize)
                        + ((pos.y + y) * fileLineSize)
                        + pos.x * bytesPV;
                    fileStream.seekp(lineStartFile, std::ios::beg);
                    fileStream.write(dataPtr, dataSize.x * bytesPV);
                    dataPtr += dataSize.x * bytesPV;
                }
            }
        }
    }
}


text:
#ifndef FEATUREEXTRACTOR_H
#define FEATUREEXTRACTOR_H

#include <dlib/pixel.h>
#include <dlib/array2d.h>
#include <dlib/image_loader/image_loader.h>
#include <dlib/image_keypoint.h>
#include <dlib/data_io.h>
#include <dlib/image_processing.h>
#include <dlib/image_io.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d.hpp>
#include <boost/filesystem.hpp>
#include "ProjectProperty/include/ProjectProperty.hpp"
#include "ProjectProperty/include/Config.hpp"

class FeatureExtractor{
      public :
      FeatureExtractor( const Extractor_Type & _extractor_type, const std::string & _fileName );
      void extractKeyPoint(std::vector<cv::KeyPoint> & _keyPointList, cv::Mat & _descriptor);
      //void extractDescriptor(std::vector<cv::KeyPoint> & _keyPointList, cv::Mat & _descriptor);
      private :
      Extractor_Type extractor_type;
      std::string fileName;
      Image_Type getImageFormat(const std::string & _fileName );
};
#endif

ext: hpp

max_stars_repo_name: ParoRahul/ImageDetection

max_issues_repo_name: ParoRahul/ImageDetection

max_forks_repo_name: ParoRahul/ImageDetection


text:
#define BOOST_TEST_MAIN

#include <deque>
#include <forward_list>
#include <vector>

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

#include "../py_string.hpp"
#include "tupleplus.hpp"

BOOST_AUTO_TEST_SUITE(pyUtil)

BOOST_AUTO_TEST_CASE(sign)
{
  using py::util::sign;

  BOOST_CHECK_EQUAL(sign(0), 0);
  BOOST_CHECK_EQUAL(sign(-2), -1);
  BOOST_CHECK_EQUAL(sign(3), 1);
}
BOOST_AUTO_TEST_CASE(optional)
{
  using py::optional_int;
  optional_int null = py::nullopt;
  optional_int i = 1;
  optional_int null2 = py::nullopt;

  BOOST_CHECK(null == null);
  BOOST_CHECK(null == null2);
  BOOST_CHECK(null == py::nullopt);
  BOOST_CHECK(null != i);
  BOOST_CHECK(i == i);

  BOOST_CHECK(i == 1);
  BOOST_CHECK(i != 2);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(pyString)

BOOST_AUTO_TEST_CASE(adjustIndex)
{
  using py::util::adjust_index;
  using std::make_tuple;

  BOOST_CHECK(adjust_index<int>(py::nullopt, py::nullopt, 1, 5)
              == make_tuple(0, 5, 1, 5));
  BOOST_CHECK(adjust_index<int>(py::nullopt, py::nullopt, 2, 5)
              == make_tuple(0, 5, 2, 3));
  BOOST_CHECK(adjust_index<int>(py::nullopt, py::nullopt, -1, 5)
              == make_tuple(4, -1, -1, 5));
  BOOST_CHECK(adjust_index<int>(1, 2, 3, 5) == make_tuple(1, 2, 3, 1));
  BOOST_CHECK(adjust_index<int>(-5, -1, -2, 6) == make_tuple(1, 5, -2, 0));
  BOOST_CHECK(adjust_index<int>(10, 0, 1, 10) == make_tuple(10, 0, 1, 0));
}
BOOST_AUTO_TEST_CASE(slice)
{
  using py::string;
  string s = "01234";
  string t = "012345";

  BOOST_CHECK_EQUAL((s[{ py::nullopt, py::nullopt, -1 }]), "43210");

  BOOST_CHECK_EQUAL((s[{ py::nullopt, py::nullopt, -2 }]), "420");

  BOOST_CHECK_EQUAL((t[{ py::nullopt, py::nullopt, -1 }]), "543210");

  BOOST_CHECK_EQUAL((t[{ py::nullopt, py::nullopt, -2 }]), "531");

  BOOST_CHECK_EQUAL((t[{ -5, -1, 1 }]), "1234");

  BOOST_CHECK_EQUAL((s[{ 1, 5, -2 }]), "");
}

BOOST_AUTO_TEST_CASE(repeat)
{
  using py::string;
  string str = "str";
  BOOST_CHECK_EQUAL(str * 2, "strstr");

  BOOST_CHECK_EQUAL(str * 0, "");

  BOOST_CHECK_EQUAL(str * 1, "str");

  str *= 2;
  BOOST_CHECK_EQUAL(str, "strstr");

  BOOST_CHECK_THROW(str * -1, std::length_error);
  /* Exceeds buffer length that can be held by string class */
}

BOOST_AUTO_TEST_CASE(arraySubscript)
{
  using py::string;
  string str = "012345";
  BOOST_CHECK_EQUAL(str[0], '0');
  BOOST_CHECK_EQUAL(str.at(0), '0');

  BOOST_CHECK_EQUAL(str[-1], '5');
  BOOST_CHECK_EQUAL(str.at(-1), '5');

  BOOST_CHECK_NO_THROW(str[-10]);
  BOOST_CHECK_THROW(str.at(-10), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(capitalize)
{
  using py::string;
  string str = "str";
  string Str = "Str";
  string empty = "";

  BOOST_CHECK_EQUAL(str.capitalize(), "Str");
  BOOST_CHECK_EQUAL(Str.capitalize(), "Str");
  BOOST_CHECK_EQUAL(empty.capitalize(), "");
}

BOOST_AUTO_TEST_CASE(center)
{
  using py::string;
  string str = "string";
  string empty = "";

  BOOST_CHECK_EQUAL(str.center(10), "  string  ");
  BOOST_CHECK_EQUAL(str.center(6), "string");
  BOOST_CHECK_EQUAL(str.center(9), " string  ");
  BOOST_CHECK_EQUAL(str.center(0), "string");
  BOOST_CHECK_EQUAL(str.center(8, 'Q'), "QstringQ");

  BOOST_CHECK_EQUAL(empty.center(10), "          ");
  BOOST_CHECK_EQUAL(empty.center(0), "");
  BOOST_CHECK_EQUAL(empty.center(8, 'e'), "eeeeeeee");
}

BOOST_AUTO_TEST_CASE(count)
{
  using py::string;
  string str = "str";
  string empty = "";
  string one = "a";
  string two = "ab";
  string three = "aba";

  BOOST_CHECK_EQUAL((str * 10).count("str"), 10);
  BOOST_CHECK_EQUAL(str.count(""), 4);
  BOOST_CHECK_EQUAL(empty.count("a"), 0);
  BOOST_CHECK_EQUAL(empty.count(""), 1);
  BOOST_CHECK_EQUAL((one * 10).count("a"), 10);
  BOOST_CHECK_EQUAL((two * 10).count("ab"), 10);
  BOOST_CHECK_EQUAL((two * 10).count("ba"), 9);
  BOOST_CHECK_EQUAL((three * 10).count("aba"), 10);
  BOOST_CHECK_EQUAL((three * 10).count("aa"), 9);

  BOOST_CHECK_EQUAL(empty.count("", 1, 2), 1);
  BOOST_CHECK_EQUAL(str.count("t", 1, 3), 1);
}

BOOST_AUTO_TEST_CASE(expandtabs)
{
  using py::string;
  string tab = "\t\t";
  string empty = "";
  string tab2 = "\t as\t";
  BOOST_CHECK_EQUAL(tab.expandtabs().size(), 16);
  BOOST_CHECK_EQUAL(tab.expandtabs(4).size(), 8);
  BOOST_CHECK_EQUAL(empty.expandtabs().size(), 0);
  BOOST_CHECK_EQUAL(tab2.expandtabs(4).size(), 11);
}

BOOST_AUTO_TEST_CASE(endswith)
{
  using py::string;

  string str = "strstr";

  BOOST_CHECK(str.endswith("str"));
  BOOST_CHECK(str.endswith("st", 0, -1));
  BOOST_CHECK(str.endswith("str", 0, -3));
  BOOST_CHECK(!str.endswith("str", 0, -1));
  BOOST_CHECK(!str.endswith("str", 0, 1));
}

BOOST_AUTO_TEST_CASE(find)
{
  using py::string;
  string str = "strstr";

  BOOST_CHECK_EQUAL(str.pyfind("t"), 1);
  BOOST_CHECK_EQUAL(str.pyfind("t", 1), 1);
  BOOST_CHECK_EQUAL(str.pyfind("t", 2), 4);
  BOOST_CHECK_EQUAL(str.pyfind("t", 3), 4);
  BOOST_CHECK_EQUAL(str.pyfind("t", 4), 4);
  BOOST_CHECK_EQUAL(str.pyfind("t", -1), -1);
  BOOST_CHECK_EQUAL(str.pyfind("t", -2), 4);
  BOOST_CHECK_EQUAL(str.pyfind("t", -3), 4);
  BOOST_CHECK_EQUAL(str.pyfind("t", -4), 4);

  BOOST_CHECK_EQUAL(str.pyfind(""), 0);
  BOOST_CHECK_EQUAL(str.pyfind("", 1), 1);
}

BOOST_AUTO_TEST_CASE(join_with_vector)
{
  using py::string;
  using std::vector;

  string sep = "-";
  string empty = "";
  vector<string> items = { "a", "b", "c" };
  vector<string> no_item = {};

  BOOST_CHECK_EQUAL(sep.join(items), "a-b-c");
  BOOST_CHECK_EQUAL(sep.join(vector<string> { "a", "b", "c" }), "a-b-c");
  BOOST_CHECK_EQUAL(sep.join(no_item), "");
  BOOST_CHECK_EQUAL(empty.join(items), "abc");
  BOOST_CHECK_EQUAL(empty.join(no_item), "");
}

BOOST_AUTO_TEST_CASE(join_with_deque)
{
  using py::string;
  using std::deque;

  string sep = "-";
  deque<string> items = { "a", "b", "c" };
  BOOST_CHECK_EQUAL(sep.join(items), "a-b-c");
}

BOOST_AUTO_TEST_CASE(join_with_list)
{
  using py::string;
  using std::list;

  string sep = "-";
  list<string> items = { "a", "b", "c" };
  BOOST_CHECK_EQUAL(sep.join(items), "a-b-c");
}

BOOST_AUTO_TEST_CASE(join_with_forward_list)
{
  using py::string;
  using std::forward_list;

  string sep = "-";
  forward_list<string> items = { "a", "b", "c" };
  BOOST_CHECK_EQUAL(sep.join(items), "a-b-c");
}

BOOST_AUTO_TEST_CASE(join_with_array)
{
  using py::string;
  using std::array;

  string sep = "-";
  array<string, 3> items = { "a", "b", "c" };
  BOOST_CHECK_EQUAL(sep.join(items), "a-b-c");
}

BOOST_AUTO_TEST_CASE(ljust)
{
  using py::string;
  string str = "str";
  string empty = "";
  BOOST_CHECK_EQUAL(str.ljust(10), "str       ");
  BOOST_CHECK_EQUAL(str.ljust(10, '&'), "str&&&&&&&");
  BOOST_CHECK_EQUAL(str.ljust(2), "str");
  BOOST_CHECK_EQUAL(empty.ljust(5), "     ");
  BOOST_CHECK_EQUAL(empty.ljust(5, 'f'), "fffff");
}

BOOST_AUTO_TEST_CASE(lower)
{
  using py::string;
  string upper = "STRING";
  string lower = "string";
  string empty = "";

  BOOST_CHECK_EQUAL(upper.lower(), lower);
  BOOST_CHECK_EQUAL(lower.lower(), lower);
  BOOST_CHECK_EQUAL(empty.lower(), empty);
}
BOOST_AUTO_TEST_CASE(lstrip)
{
  using py::string;
  string spacious = "    spacious    ";
  string domain = "www.example.com";
  string empty = "";
  BOOST_CHECK_EQUAL(spacious.lstrip(), "spacious    ");
  BOOST_CHECK_EQUAL(domain.lstrip("comwz."), "example.com");
  BOOST_CHECK_EQUAL(domain.lstrip(""), domain);
  BOOST_CHECK_EQUAL(empty.lstrip(), "");
  BOOST_CHECK_EQUAL(empty.lstrip(""), "");
}

BOOST_AUTO_TEST_CASE(partition)
{
  using py::string;
  using std::make_tuple;

  string str = "1-2-3-4-5";

  BOOST_CHECK(str.partition("-") == make_tuple("1", "-", "2-3-4-5"));
  BOOST_CHECK(str.partition("p") == make_tuple("1-2-3-4-5", "", "" ));
}

BOOST_AUTO_TEST_CASE(replace)
{
  using py::string;
  string nice_language = "Python is nice programming language!";
  string str = "aaaaaaaaaa";

  BOOST_CHECK_EQUAL(nice_language.pyreplace("Python", "C++"),
                    "C++ is nice programming language!");
  BOOST_CHECK_EQUAL(str.pyreplace("a", "A", 5), "AAAAAaaaaa");
}

BOOST_AUTO_TEST_CASE(rfind)
{
  using py::string;
  string str = "strstr";

  BOOST_CHECK_EQUAL(str.pyrfind("tr"), 4);
  BOOST_CHECK_EQUAL(str.pyrfind("tr", 0, -1), 1);
  BOOST_CHECK_EQUAL(str.pyrfind(""), 6);
}

BOOST_AUTO_TEST_CASE(rjust)
{
  using py::string;

  string str = "str";
  string empty = "";
  BOOST_CHECK_EQUAL(str.rjust(10), "       str");
  BOOST_CHECK_EQUAL(str.rjust(10, '&'), "&&&&&&&str");
  BOOST_CHECK_EQUAL(str.rjust(2), "str");
  BOOST_CHECK_EQUAL(empty.rjust(5), "     ");
  BOOST_CHECK_EQUAL(empty.rjust(5, 'f'), "fffff");
}

BOOST_AUTO_TEST_CASE(rpartition)
{
  using py::string;
  using std::make_tuple;

  string str = "1-2-3-4-5";

  BOOST_CHECK(str.rpartition("-") == make_tuple("1-2-3-4", "-", "5"));
  BOOST_CHECK(str.rpartition("p") == make_tuple("", "", "1-2-3-4-5"));
}

BOOST_AUTO_TEST_CASE(rsplit)
{
  using py::string;
  using std::vector;
  string str = "1,1,1,1,1,";
  string space = "1 1 1 1 1";
  string empty = "";
  vector<string> tmp = {};
  vector<string> ep = {};

  empty.rsplit(tmp);
  BOOST_CHECK(tmp == ep);

  str.rsplit(tmp, ",");
  BOOST_CHECK(tmp == (vector<string> { "1", "1", "1", "1", "1", "" }));

  str.rsplit(tmp, ",", 2);
  BOOST_CHECK(tmp == (vector<string> { "1,1,1,1", "1", "" }));

  space.rsplit(tmp);
  BOOST_CHECK(tmp == (vector<string> { "1", "1", "1", "1", "1" }));

  space.rsplit(tmp, 2);
  BOOST_CHECK(tmp == (vector<string> { "1 1 1", "1", "1" }));
}

BOOST_AUTO_TEST_CASE(rstrip)
{
  using py::string;
  string spacious = "    spacious    ";
  string domain = "www.example.com";
  string empty = "";
  BOOST_CHECK_EQUAL(spacious.rstrip(), "    spacious");
  BOOST_CHECK_EQUAL(domain.rstrip("comwz."), "www.example");
  BOOST_CHECK_EQUAL(domain.rstrip(""), domain);
  BOOST_CHECK_EQUAL(empty.rstrip(), "");
  BOOST_CHECK_EQUAL(empty.rstrip(""), "");
}

BOOST_AUTO_TEST_CASE(split)
{
  using py::string;
  using std::vector;
  string str = "1,1,1,1,1,";
  string space = "1 1 1 1 1";
  string empty = "";
  vector<string> tmp = {};
  vector<string> ep = {};

  empty.split(tmp);
  BOOST_CHECK(tmp == ep);

  str.split(tmp, ",");
  BOOST_CHECK(tmp == (vector<string> { "1", "1", "1", "1", "1", "" }));

  str.split(tmp, ",", 2);
  BOOST_CHECK(tmp == (vector<string> { "1", "1", "1,1,1," }));

  space.split(tmp);
  BOOST_CHECK(tmp == (vector<string> { "1", "1", "1", "1", "1" }));

  space.split(tmp, 2);
  BOOST_CHECK(tmp == (vector<string> { "1", "1", "1 1 1" }));
}

BOOST_AUTO_TEST_CASE(splitlines)
{
  using py::string;
  using std::vector;

  string lines = "Python\nC++";
  string lines_end = "Python\nC++\n";
  vector<string> tmp = {};

  lines.splitlines(tmp);
  BOOST_CHECK(tmp == (vector<string> { "Python", "C++" }));

  lines.splitlines(tmp, true);
  BOOST_CHECK(tmp == (vector<string> { "Python\n", "C++" }));

  lines_end.splitlines(tmp);
  BOOST_CHECK(tmp == (vector<string> { "Python", "C++" }));

  lines_end.splitlines(tmp, true);
  BOOST_CHECK(tmp == (vector<string> { "Python\n", "C++\n" }));
}

BOOST_AUTO_TEST_CASE(startswith)
{
  using py::string;

  string str = "strstr";

  BOOST_CHECK(str.startswith("str"));
  BOOST_CHECK(str.startswith("tr", 1));
  BOOST_CHECK(str.startswith("str", 3));
  BOOST_CHECK(!str.startswith("str", 1));
  BOOST_CHECK(!str.startswith("str", 0, 1));
}

BOOST_AUTO_TEST_CASE(strip)
{
  using py::string;

  string spacious = "    spacious    ";
  string domain = "www.example.com";
  string empty = "";
  BOOST_CHECK_EQUAL(spacious.strip(), "spacious");
  BOOST_CHECK_EQUAL(domain.strip("comwz."), "example");
  BOOST_CHECK_EQUAL(domain.strip(""), domain);
  BOOST_CHECK_EQUAL(empty.strip(), "");
  BOOST_CHECK_EQUAL(empty.strip(""), "");
}

BOOST_AUTO_TEST_CASE(swapcase)
{
  using py::string;

  string str = "String";
  string str2 = "py_string";

  BOOST_CHECK_EQUAL(str.swapcase(), "sTRING");
  BOOST_CHECK_EQUAL(str2.swapcase(), "PY_STRING");
}

BOOST_AUTO_TEST_CASE(title)
{
  using py::string;

  string str = "string is like vector<char>";

  BOOST_CHECK_EQUAL(str.title(), "String Is Like Vector<Char>");
}

BOOST_AUTO_TEST_CASE(upper)
{
  using py::string;

  string upper = "STRING";
  string lower = "string";
  string empty = "";

  BOOST_CHECK_EQUAL(upper.upper(), upper);
  BOOST_CHECK_EQUAL(lower.upper(), upper);
  BOOST_CHECK_EQUAL(empty.upper(), empty);
}

BOOST_AUTO_TEST_CASE(zfill)
{
  using py::string;

  string b = "100";
  string c = "-100";
  string d = "+100";
  string e = "=100";
  string empty = "";

  BOOST_CHECK_EQUAL(b.zfill(5), "00100");
  BOOST_CHECK_EQUAL(b.zfill(3), "100");
  BOOST_CHECK_EQUAL(b.zfill(2), "100");
  BOOST_CHECK_EQUAL(c.zfill(5), "-0100");
  BOOST_CHECK_EQUAL(c.zfill(4), "-100");
  BOOST_CHECK_EQUAL(c.zfill(3), "-100");
  BOOST_CHECK_EQUAL(c.zfill(2), "-100");
  BOOST_CHECK_EQUAL(d.zfill(5), "+0100");
  BOOST_CHECK_EQUAL(e.zfill(5), "0=100");
  BOOST_CHECK_EQUAL(empty.zfill(5), "00000");
}

BOOST_AUTO_TEST_SUITE_END()


text:
/*
 * Copyright (C) 2014 Open Source Robotics Foundation
 *
 * 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 <string>
#include <vector>
#include <boost/lexical_cast.hpp>
#include "gazebo/test/ServerFixture.hh"
#include "gazebo/test/helper_physics_generator.hh"

using namespace gazebo;
class WorldEnvPopulationTest : public ServerFixture,
                               public testing::WithParamInterface<const char*>
{
  public: void LoadEnvironment(const std::string &_physicsType);
  public: void EmptyPopulation(const std::string &_physicsType);
};

////////////////////////////////////////////////////////////////////////
// EmptyPopulation: Try to generate a population with an incorrect 'model_count'
// value.
////////////////////////////////////////////////////////////////////////
void WorldEnvPopulationTest::EmptyPopulation(const std::string &/*_physicsEng*/)
{
  Load("test/worlds/empty_population.world");
  physics::WorldPtr world = physics::get_world("default");
  ASSERT_TRUE(world != NULL);

  // The models should not load because we are trying to load a population with
  // a non positive 'model_count' value. In any case. let's wait some time to
  // verify it. We should only see two models (ground plane and sun).
  int i = 0;
  int retries = 20;
  while (world->ModelCount() < 2u && i < retries)
  {
    common::Time::MSleep(100);
    ++i;
  }
  ASSERT_GE(i, retries);
}

////////////////////////////////////////////////////////////////////////
// LoadEnvironment: Verify that the number of elements populated is correct
// and the objects are distributed as expected.
////////////////////////////////////////////////////////////////////////
void WorldEnvPopulationTest::LoadEnvironment(const std::string &/*_physicsEng*/)
{
  Load("worlds/population.world");
  physics::WorldPtr world = physics::get_world("default");
  ASSERT_TRUE(world != NULL);

  // Wait some time while the models are being loaded.
  int i = 0;
  int retries = 200;
  while (world->ModelCount() < 65u && i < retries)
  {
    common::Time::MSleep(100);
    ++i;
  }
  ASSERT_LT(i, retries);

  // We should have multiple cloned models + the ground plane.
  EXPECT_EQ(world->ModelCount(), 64u + 1u);

  // Check elements distributed as a grid.
  double tolerance = 0.25;
  ignition::math::Vector3d initialPos(-0.25, -0.25 / 2.0, 0);
  ignition::math::Vector3d expectedPos(initialPos);
  ignition::math::Vector3d step(0.25, 0.25, 0);

  for (int i = 0; i < 2; ++i)
  {
    for (int j = 0; j < 3; ++j)
    {
      std::string name = std::string("can2_clone_" +
        boost::lexical_cast<std::string>(i * 3 + j));
      physics::ModelPtr model = world->ModelByName(name);
      ASSERT_TRUE(model != NULL);
      auto pos = model->WorldPose().Pos();
      EXPECT_NEAR(pos.Distance(expectedPos), 0.0, tolerance);

      expectedPos.X() += step.X();
    }
    expectedPos.X() = initialPos.X();
    expectedPos.Y() += step.Y();
  }

  // Check that the objects are within the expected box.
  std::vector<physics::ModelPtr> models = world->Models();
  for (size_t i = 0; i < models.size(); ++i)
  {
    physics::ModelPtr model = models[i];
    ASSERT_TRUE(model != NULL);

    // This is not a cloned object, skip it.
    if (model->GetName().find("can1_clone") != std::string::npos)
    {
      EXPECT_GE(model->WorldPose().Pos().X(), 2.5 - tolerance);
      EXPECT_GE(model->WorldPose().Pos().Y(), 2.5 - tolerance);
      EXPECT_GE(model->WorldPose().Pos().Z(), 0 - tolerance);
      EXPECT_LE(model->WorldPose().Pos().X(), 3.5 + tolerance);
      EXPECT_LE(model->WorldPose().Pos().Y(), 3.5 + tolerance);
      EXPECT_LE(model->WorldPose().Pos().Z(), 0.1 + tolerance);
    }
    else if (model->GetName().find("can3_clone") != std::string::npos)
    {
      ignition::math::Vector3d center(-3, 3, 0);
      double radius = 1.0;
      EXPECT_LE(model->WorldPose().Pos().Distance(center), radius + tolerance);
    }
    else if (model->GetName().find("can4_clone") != std::string::npos)
    {
      EXPECT_GE(model->WorldPose().Pos().X(), -1 - tolerance);
      EXPECT_GE(model->WorldPose().Pos().Y(), -5 - tolerance);
      EXPECT_GE(model->WorldPose().Pos().Z(), 0 - tolerance);
      EXPECT_LE(model->WorldPose().Pos().X(), 3 + tolerance);
      EXPECT_LE(model->WorldPose().Pos().Y(), -3 + tolerance);
      EXPECT_LE(model->WorldPose().Pos().Z(), 0.01 + tolerance);
    }
    else if (model->GetName().find("can5_clone") != std::string::npos)
    {
      ignition::math::Vector3d center(-3, -3, 0);
      double radius = 1.0;
      EXPECT_LE(model->WorldPose().Pos().Distance(center), radius + tolerance);
    }
    else if (model->GetName().find("can6_clone") != std::string::npos)
    {
      EXPECT_GE(model->WorldPose().Pos().X(), -1 - tolerance);
      EXPECT_GE(model->WorldPose().Pos().Z(), 0 - tolerance);
      EXPECT_LE(model->WorldPose().Pos().X(), 1 + tolerance);
      EXPECT_LE(model->WorldPose().Pos().Z(), 0.01 + tolerance);
      EXPECT_NEAR(model->WorldPose().Pos().Y(), 4, tolerance);
    }
    else if (model->GetName().find("can7_clone") != std::string::npos)
    {
      EXPECT_GE(model->WorldPose().Pos().Y(), -2 - tolerance);
      EXPECT_GE(model->WorldPose().Pos().Z(), 0 - tolerance);
      EXPECT_LE(model->WorldPose().Pos().Y(), 0 + tolerance);
      EXPECT_LE(model->WorldPose().Pos().Z(), 0.01 + tolerance);
      EXPECT_NEAR(model->WorldPose().Pos().X(), -5, tolerance);
    }
    else if (model->GetName().find("can8_clone") != std::string::npos)
    {
      EXPECT_GE(model->WorldPose().Pos().Z(), 0 - tolerance);
      EXPECT_LE(model->WorldPose().Pos().Z(), 1.4 + tolerance);
      EXPECT_NEAR(model->WorldPose().Pos().X(), 4.0, tolerance);
      EXPECT_NEAR(model->WorldPose().Pos().Y(), 0, tolerance);
    }
  }
}

////////////////////////////////////////////////////////////////////////
TEST_P(WorldEnvPopulationTest, EmptyPopulation)
{
  EmptyPopulation(GetParam());
}

////////////////////////////////////////////////////////////////////////
TEST_P(WorldEnvPopulationTest, LoadEnvironment)
{
  LoadEnvironment(GetParam());
}

INSTANTIATE_TEST_CASE_P(PhysicsEngines, WorldEnvPopulationTest,
                        PHYSICS_ENGINE_VALUES);

////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}