text:
/**
 * Copyright (C) 2019-2020 Xilinx, Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may
 * not use this file except in compliance with the License. A copy of the
 * License is located 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.
 */

// ------ I N C L U D E   F I L E S -------------------------------------------
// Local - Include Files
#include "SubCmdValidate.h"
#include "tools/common/ReportHost.h"
#include "tools/common/XBUtilities.h"
#include "tools/common/XBHelpMenus.h"
#include "core/tools/common/ProgressBar.h"
#include "core/tools/common/EscapeCodes.h"
#include "core/common/query_requests.h"
#include "core/pcie/common/dmatest.h"
namespace XBU = XBUtilities;

// 3rd Party Library - Include Files
#include <boost/program_options.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/any.hpp>
namespace po = boost::program_options;

// System - Include Files
#include <iostream>
#include <thread>
#include <regex>

#ifdef _WIN32
#pragma warning (disable : 4996)
/* Disable warning for use of getenv */
#pragma warning (disable : 4996 4100 4505)
/* disable unrefenced params and local functions - Remove these warnings asap*/
#endif

// =============================================================================

// ------ L O C A L   F U N C T I O N S ---------------------------------------

namespace {

enum class test_status
{
  passed,
  warning,
  failed
};

/*
 * mini logger to log errors, warnings and details produced by the test cases
 */
void logger(boost::property_tree::ptree& _ptTest, const std::string& tag, const std::string& msg)
{
  boost::property_tree::ptree _ptLog;
  boost::property_tree::ptree _ptExistingLog;
  boost::optional<boost::property_tree::ptree&> _ptChild = _ptTest.get_child_optional("log");
  if(_ptChild)
    _ptExistingLog = _ptChild.get();

  _ptLog.put(tag, msg);
  _ptExistingLog.push_back(std::make_pair("", _ptLog));
  _ptTest.put_child("log", _ptExistingLog);
}

/*
 * progarm an xclbin
 */
void
programXclbin(const std::shared_ptr<xrt_core::device>& _dev, const std::string& xclbin, boost::property_tree::ptree& _ptTest)
{
  std::ifstream stream(xclbin, std::ios::binary);
  if (!stream) {
    logger(_ptTest, "Error", boost::str(boost::format("Could not open %s for reading") % xclbin));
    _ptTest.put("status", "failed");
    return;
  }

  stream.seekg(0,stream.end);
  size_t size = stream.tellg();
  stream.seekg(0,stream.beg);
  std::vector<char> raw(size);
  stream.read(raw.data(),size);

  std::string ver(raw.data(),raw.data()+7);
  if (ver != "xclbin2") {
    logger(_ptTest, "Error", boost::str(boost::format("Bad binary version '%s' for xclbin") % ver));
    _ptTest.put("status", "failed");
    return;
  }

  auto hdl = _dev->get_device_handle();
  if (xclLoadXclBin(hdl,reinterpret_cast<const axlf*>(raw.data()))) {
    logger(_ptTest, "Error", "Could not load xclbin");
    _ptTest.put("status", "failed");
    return;
  }
}

inline const char*
getenv_or_empty(const char* path)
{
  return getenv(path) ? getenv(path) : "";
}

static void
setShellPathEnv(const std::string& var_name, const std::string& trailing_path)
{
  std::string xrt_path(getenv_or_empty("XILINX_XRT"));
  std::string new_path(getenv_or_empty(var_name.c_str()));
  xrt_path += trailing_path + ":";
  new_path = xrt_path + new_path;
#ifdef __GNUC__
  setenv(var_name.c_str(), new_path.c_str(), 1);
#endif
}

static void
testCaseProgressReporter(std::shared_ptr<XBU::ProgressBar> run_test, bool& is_done)
{
  int counter = 0;
  while(counter < 60 && !is_done) {
    run_test.get()->update(counter);
    counter++;
    std::this_thread::sleep_for(std::chrono::seconds(1));
  }
}

/*
 * run standalone testcases in a fork
 */
void
runShellCmd(const std::string& cmd, boost::property_tree::ptree& _ptTest)
{
#ifdef __GNUC__
  // Fix environment variables before running test case
  setenv("XILINX_XRT", "/opt/xilinx/xrt", 0);
  setShellPathEnv("PYTHONPATH", "/python");
  setShellPathEnv("LD_LIBRARY_PATH", "/lib");
  setShellPathEnv("PATH", "/bin");
  unsetenv("XCL_EMULATION_MODE");

  int stderr_fds[2];
  if (pipe(stderr_fds)== -1) {
    logger(_ptTest, "Error", "Unable to create pipe");
    _ptTest.put("status", "failed");
    return;
  }

  // Save stderr
  int stderr_save = dup(STDERR_FILENO);
  if (stderr_save == -1) {
    logger(_ptTest, "Error", "Unable to duplicate stderr");
    _ptTest.put("status", "failed");
    return;
  }

  // Kick off progress reporter
  bool is_done = false;
  //bandwidth testcase takes up-to a min to run
  auto run_test = std::make_shared<XBU::ProgressBar>("Running Test", 60, XBU::is_esc_enabled(), std::cout);
  std::thread t(testCaseProgressReporter, run_test, std::ref(is_done));

  // Close existing stderr and set it to be the write end of the pipe.
  // After fork below, our child process's stderr will point to the same fd.
  dup2(stderr_fds[1], STDERR_FILENO);
  close(stderr_fds[1]);
  std::shared_ptr<FILE> stderr_child(fdopen(stderr_fds[0], "r"), fclose);
  std::shared_ptr<FILE> stdout_child(popen(cmd.c_str(), "r"), pclose);
  // Restore our normal stderr
  dup2(stderr_save, STDERR_FILENO);
  close(stderr_save);

  if (stdout_child == nullptr) {
    logger(_ptTest, "Error", boost::str(boost::format("Failed to run %s") % cmd));
    _ptTest.put("status", "failed");
    return;
  }

  std::string output = "\n\n";
  // Read child's stdout and stderr without parsing the content
  char buf[1024];
  while (!feof(stdout_child.get())) {
    if (fgets(buf, sizeof (buf), stdout_child.get()) != nullptr) {
      output += buf;
    }
  }
  while (stderr_child && !feof(stderr_child.get())) {
    if (fgets(buf, sizeof (buf), stderr_child.get()) != nullptr) {
      output += buf;
    }
  }
  is_done = true;
  if (output.find("PASS") == std::string::npos) {
    run_test.get()->finish(false, "");
    logger(_ptTest, "Error", output);
    _ptTest.put("status", "failed");
  }
  else {
    run_test.get()->finish(true, "");
    _ptTest.put("status", "passed");
  }
  std::cout << EscapeCodes::cursor().prev_line() << EscapeCodes::cursor().clear_line();
  t.join();

  // Get out max thruput for bandwidth testcase
  size_t st = output.find("Maximum");
  if (st != std::string::npos) {
    size_t end = output.find("\n", st);
    logger(_ptTest, "Details", output.substr(st, end - st));
  }
#endif
}

/*
 * search for xclbin for an SSV2 platform
 */
std::string
searchSSV2Xclbin(const std::shared_ptr<xrt_core::device>& _dev, const std::string& logic_uuid,
                  const std::string& xclbin, boost::property_tree::ptree& _ptTest)
{
  std::string formatted_fw_path("/opt/xilinx/firmware/");
  boost::filesystem::path fw_dir(formatted_fw_path);
  if(!boost::filesystem::is_directory(fw_dir)) {
    logger(_ptTest, "Error", boost::str(boost::format("Failed to find %s") % fw_dir));
    logger(_ptTest, "Error", "Please check if the platform package is installed correctly");
    _ptTest.put("status", "failed");
    return "";
  }

  std::vector<std::string> suffix = { "dsabin", "xsabin" };

  for(const std::string& t : suffix) {
    std::regex e("(^" + formatted_fw_path + "[^/]+/[^/]+/[^/]+/).+\\." + t);
    for(boost::filesystem::recursive_directory_iterator iter(fw_dir,
          boost::filesystem::symlink_option::recurse), end; iter != end;) {
      std::string name = iter->path().string();
      std::smatch cm;
      if (!boost::filesystem::is_directory(boost::filesystem::path(name.c_str()))) {
        iter.no_push();
      }
      else {
        iter.no_push(false);
      }

      std::regex_match(name, cm, e);
      if (cm.size() > 0) {
#ifdef __GNUC__
        auto dtbbuf = XBUtilities::get_axlf_section(name, PARTITION_METADATA);
        if (dtbbuf.empty()) {
          ++iter;
          continue;
        }
        std::vector<std::string> uuids = XBUtilities::get_uuids(dtbbuf.data());
        if (!uuids.size()) {
          ++iter;
		    }
        else if (uuids[0].compare(logic_uuid) == 0) {
          return cm.str(1) + "test/" + xclbin;
        }
#endif
      }
      else if (iter.level() > 4) {
        iter.pop();
        continue;
      }
		  ++iter;
    }
  }
  logger(_ptTest, "Error", boost::str(boost::format("Failed to find xclbin in %s") % fw_dir));
  logger(_ptTest, "Error", "Please check if the platform package is installed correctly");
  _ptTest.put("status", "failed");
  return "";
}

/*
 * search for xclbin for a legacy platform
 */
std::string
searchLegacyXclbin(const std::string& dev_name, const std::string& xclbin, boost::property_tree::ptree& _ptTest)
{
  const std::string dsapath("/opt/xilinx/dsa/");
  const std::string xsapath("/opt/xilinx/xsa/");
  //create possible xclbin paths
  std::string xsaXclbinPath = xsapath + dev_name + "/test/" + xclbin;
  std::string dsaXclbinPath = dsapath + dev_name + "/test/" + xclbin;
  boost::filesystem::path xsa_xclbin(xsaXclbinPath);
  boost::filesystem::path dsa_xclbin(dsaXclbinPath);
  if (boost::filesystem::exists(xsa_xclbin)) {
    return xsaXclbinPath;
  }
  else if (boost::filesystem::exists(dsa_xclbin)) {
    return dsaXclbinPath;
  }

  logger(_ptTest, "Error", boost::str(boost::format("Failed to find %s or %s") % xsaXclbinPath % dsaXclbinPath));
  logger(_ptTest, "Error", "Please check if the platform package is installed correctly");

  _ptTest.put("status", "failed");
  return "";
}

/*
 * helper funtion for kernel and bandwidth test cases
 */
void
runTestCase(const std::shared_ptr<xrt_core::device>& _dev, const std::string& py, const std::string& xclbin,
            boost::property_tree::ptree& _ptTest)
{
    std::string name;
    try{
      name = xrt_core::device_query<xrt_core::query::rom_vbnv>(_dev);
    } catch(...) {
      logger(_ptTest, "Error", "Unable to find device VBNV");

      _ptTest.put("status", "failed");
      return;
    }

    //check if a 2RP platform
    std::vector<std::string> logic_uuid;
    try{
      logic_uuid = xrt_core::device_query<xrt_core::query::logic_uuids>(_dev);
    } catch(...) { }

    std::string xclbinPath;
    if(!logic_uuid.empty()) {
      xclbinPath = searchSSV2Xclbin(_dev, logic_uuid.front(), xclbin, _ptTest);
    } else {
      xclbinPath = searchLegacyXclbin(name, xclbin, _ptTest);
    }

    //check if xclbin is present
    if(xclbinPath.empty()) {
      if(xclbin.compare("bandwidth.xclbin") == 0) {
        //if bandwidth xclbin isn't present, skip the test
        logger(_ptTest, "Details", "Bandwidth xclbin not available. Skipping validation.");
        _ptTest.put("status", "skipped");
      }
      return;
    }

    //check if testcase is present
    std::string xrtTestCasePath = "/opt/xilinx/xrt/test/" + py;
    boost::filesystem::path xrt_path(xrtTestCasePath);
    if (!boost::filesystem::exists(xrt_path)) {
      logger(_ptTest, "Error", boost::str(boost::format("Failed to find %s") % xrtTestCasePath));
      logger(_ptTest, "Error", "Please check if the platform package is installed correctly");
      _ptTest.put("status", "failed");
      return;
    }

    // Program xclbin first.
    programXclbin(_dev, xclbinPath, _ptTest);
    if (_ptTest.get<std::string>("status", "N/A").compare("failed") == 0)
      return;

    //run testcase in a fork
    std::string cmd = "/usr/bin/python " + xrtTestCasePath + " -k " + xclbinPath + " -d " +
                        std::to_string(_dev.get()->get_device_id());
    runShellCmd(cmd, _ptTest);
}

/*
 * helper function for kernelVersionTest
 */
static void
checkOSRelease(const std::vector<std::string> kernel_versions, const std::string& release,
                boost::property_tree::ptree& _ptTest)
{
  for (const auto& ver : kernel_versions) {
    if (release.find(ver) != std::string::npos) {
      _ptTest.put("status", "passed");
      return;
    }
  }
  _ptTest.put("status", "passed");
  logger(_ptTest, "Warning", boost::str(boost::format("Kernel verison %s is not officially supported. %s is the latest supported version")
                            % release % kernel_versions.back()));
}

/*
 * TEST #1
 */
void
kernelVersionTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  //please append the new supported versions
  const std::vector<std::string> ubuntu_kernel_versions = { "4.4.0", "4.13.0", "4.15.0", "4.18.0", "5.0.0", "5.3.0" };
  const std::vector<std::string> centos_rh_kernel_versions = { "3.10.0-693", "3.10.0-862", "3.10.0-957", "3.10.0-1062" };

  boost::property_tree::ptree _pt_host;
  std::make_shared<ReportHost>()->getPropertyTreeInternal(_dev.get(), _pt_host);
  const std::string os = _pt_host.get<std::string>("host.os.distribution");
  const std::string release = _pt_host.get<std::string>("host.os.release");

  if(os.find("Ubuntu") != std::string::npos) {
    checkOSRelease(ubuntu_kernel_versions, release, _ptTest);
  }
  else if(os.find("Red Hat") != std::string::npos || os.find("CentOS") != std::string::npos) {
    checkOSRelease(centos_rh_kernel_versions, release, _ptTest);
  }
  else {
    _ptTest.put("status", "failed");
  }
}

/*
 * TEST #2
 */
void
auxConnectionTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  const std::vector<std::string> auxPwrRequiredDevice = { "VCU1525", "U200", "U250", "U280" };

  std::string name = xrt_core::device_query<xrt_core::query::xmc_board_name>(_dev);
  uint64_t max_power = xrt_core::device_query<xrt_core::query::xmc_max_power>(_dev);

  //check if device has aux power connector
  bool auxDevice = false;
  for (auto bd : auxPwrRequiredDevice) {
    if (name.find(bd) != std::string::npos) {
      auxDevice = true;
      break;
    }
  }

  if (!auxDevice) {
      logger(_ptTest, "Details", "Aux power connector is not available on this board");
      _ptTest.put("status", "skipped");
      return;
  }

  //check aux cable if board u200, u250, u280
  if(max_power == 0) {
    logger(_ptTest, "Warning", "Aux power is not connected");
    logger(_ptTest, "Warning", "Device is not stable for heavy acceleration tasks");
  }
  _ptTest.put("status", "passed");
}

/*
 * TEST #3
 */
void
pcieLinkTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  uint64_t speed     = xrt_core::device_query<xrt_core::query::pcie_link_speed>(_dev);
  uint64_t max_speed = xrt_core::device_query<xrt_core::query::pcie_link_speed_max>(_dev);
  uint64_t width     = xrt_core::device_query<xrt_core::query::pcie_express_lane_width>(_dev);
  uint64_t max_width = xrt_core::device_query<xrt_core::query::pcie_express_lane_width_max>(_dev);
  if (speed != max_speed || width != max_width) {
    logger(_ptTest, "Warning", "Link is active");
    logger(_ptTest, "Warning", boost::str(boost::format("Please make sure that the device is plugged into Gen %dx%d, instead of Gen %dx%d. %s.")
                                          % max_speed % max_width % speed % width % "Lower performance maybe experienced"));
  }
  _ptTest.put("status", "passed");
}

/*
 * TEST #4
 */
void
scVersionTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  auto sc_ver = xrt_core::device_query<xrt_core::query::xmc_bmc_version>(_dev);
  std::string exp_sc_ver = "";
  try{
    exp_sc_ver = xrt_core::device_query<xrt_core::query::expected_bmc_version>(_dev);
  } catch(...) {}

  if (!exp_sc_ver.empty() && sc_ver.compare(exp_sc_ver) != 0) {
    logger(_ptTest, "Warning", "SC firmware misatch");
    logger(_ptTest, "Warning", boost::str(boost::format("SC firmware version %s is running on the board, but SC firmware version %s is expected from the installed shell. %s.")
                                          % sc_ver % exp_sc_ver % "Please use xbmgmt --new status to check the installed shell"));
  }
  _ptTest.put("status", "passed");
}

/*
 * TEST #5
 */
void
verifyKernelTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  runTestCase(_dev, std::string("22_verify.py"), std::string("verify.xclbin"), _ptTest);
}

/*
 * TEST #6
 */
void
dmaTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  // get DDR bank count from mem_topology if possible
  auto membuf = xrt_core::device_query<xrt_core::query::mem_topology_raw>(_dev);
  auto mem_topo = reinterpret_cast<const mem_topology*>(membuf.data());

  for (auto& mem : boost::make_iterator_range(mem_topo->m_mem_data, mem_topo->m_mem_data + mem_topo->m_count)) {
    auto midx = std::distance(mem_topo->m_mem_data, &mem);
    if (mem.m_type == MEM_STREAMING)
      continue;

    if (!mem.m_used)
      continue;

    std::stringstream run_details;
    size_t block_size = 16 * 1024 * 1024; // Default block size 16MB
    xcldev::DMARunner runner(_dev->get_device_handle(), block_size, static_cast<unsigned int>(midx));
    try {
      runner.run(run_details);
      _ptTest.put("status", "passed");
      std::string line;
      while(std::getline(run_details, line))
        logger(_ptTest, "Details", line);
    }
    catch (xrt_core::error& ex) {
      _ptTest.put("status", "failed");
      _ptTest.put("error_msg", ex.what());
    }
  }
}

/*
 * TEST #7
 */
void
bandwidthKernelTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  std::string name;
  try {
    name = xrt_core::device_query<xrt_core::query::rom_vbnv>(_dev);
  } catch(...) {
    logger(_ptTest, "Error", "Unable to find device VBNV");
    _ptTest.put("status", "failed");
    return;
  }
  std::string testcase = (name.find("vck5000") != std::string::npos) ? "versal_23_bandwidth.py" : "23_bandwidth.py";
  runTestCase(_dev, testcase, std::string("bandwidth.xclbin"), _ptTest);
}

/*
 * TEST #8
 */
void
p2pTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  _ptTest.put("status", "skipped");
}

/*
 * TEST #9
 */
void
m2mTest(const std::shared_ptr<xrt_core::device>& _dev, boost::property_tree::ptree& _ptTest)
{
  _ptTest.put("status", "skipped");
}

/*
* helper function to initialize test info
*/
static boost::property_tree::ptree
create_init_test(const std::string& name, const std::string& desc) {
  boost::property_tree::ptree _ptTest;
  _ptTest.put("name", name);
  _ptTest.put("description", desc);
  return _ptTest;
}

struct TestCollection {
  boost::property_tree::ptree ptTest;
  std::function<void(const std::shared_ptr<xrt_core::device>&, boost::property_tree::ptree&)> testHandle;
};

/*
* create test suite
*/
static std::vector<TestCollection> testSuite = {
  { create_init_test("Kernel version", "Check if kernel version is supported by XRT"), kernelVersionTest },
  { create_init_test("Aux connection", "Check if auxiliary power is connected"), auxConnectionTest },
  { create_init_test("PCIE link", "Check if PCIE link is active"), pcieLinkTest },
  { create_init_test("SC version", "Check if SC firmware is up-to-date"), scVersionTest },
  { create_init_test("Verify kernel", "Run 'Hello World' kernel test"), verifyKernelTest },
  { create_init_test("DMA", "Run dma test "), dmaTest },
  { create_init_test("Bandwidth kernel", "Run 'bandwidth kernel' and check the throughput"), bandwidthKernelTest },
  { create_init_test("Peer to peer bar", "Run P2P test"), p2pTest },
  { create_init_test("Memory to memory DMA", "Run M2M test"), m2mTest }
};

/*
 * print basic information about a test
 */
static void
pretty_print_test_desc(const boost::property_tree::ptree& test, int testSuiiteSize)
{
  std::cout << boost::format("%d/%d Test #%-10d: %s\n") % test.get<int>("id") % testSuiiteSize
                    % test.get<int>("id") % test.get<std::string>("name");
  std::cout << boost::format("    %-16s: %s\n") % "Description" % test.get<std::string>("description");
}

/*
 * print test run
 */
static void
pretty_print_test_run(const boost::property_tree::ptree& test, test_status& status)
{
  std::string _status = test.get<std::string>("status");
  auto color = EscapeCodes::FGC_PASS;
  bool warn = false;
  bool error = false;

  try {
    for (const auto& dict : test.get_child("log")) {
      for (const auto& kv : dict.second) {
        std::cout << boost::format("    %-16s: %s\n") % kv.first % kv.second.get_value<std::string>();
        if (boost::iequals(kv.first, "warning"))
          warn = true;
        else if (boost::iequals(kv.first, "error"))
          error = true;
      }
    }
  }
  catch(...) {}

  if(error) {
    color = EscapeCodes::FGC_FAIL;
    status = test_status::failed;
  }
  else if(warn) {
    _status.append(" with warnings");
    color = EscapeCodes::FGC_WARN;
    status = test_status::warning;
  }

  boost::to_upper(_status);
  std::cout << EscapeCodes::fgcolor(color).string() << boost::format("    [%s]\n") % _status
            << EscapeCodes::fgcolor::reset();
  std::cout << "------------------------------------------------------------------" << std::endl;
}

/*
 * print final status of the card
 */
static void
print_status(test_status status)
{
  if (status == test_status::failed)
    std::cout << "Validation failed" << std::endl;
  else
    std::cout << "Validation completed";
  if (status == test_status::warning)
    std::cout << ", but with warnings" << std::endl;
}

/*
 * Get basic information about the platform running on the device
 */

static void
get_platform_info(const std::shared_ptr<xrt_core::device>& device, boost::property_tree::ptree& _ptTree, bool json)
{
  auto bdf = xrt_core::device_query<xrt_core::query::pcie_bdf>(device);
  _ptTree.put("device_id", xrt_core::query::pcie_bdf::to_string(bdf));
  _ptTree.put("platform", xrt_core::device_query<xrt_core::query::rom_vbnv>(device));
  _ptTree.put("sc_version", xrt_core::device_query<xrt_core::query::xmc_bmc_version>(device));
  _ptTree.put("platform_id", (boost::format("0x%x") % xrt_core::device_query<xrt_core::query::rom_time_since_epoch>(device)));
  if(!json) {
    std::cout << boost::format("Validate device[%s]\n") % _ptTree.get<std::string>("device_id");
    std::cout << boost::format("%-20s: %s\n") % "Platform" % _ptTree.get<std::string>("platform");
    std::cout << boost::format("%-20s: %s\n") % "SC Version" % _ptTree.get<std::string>("sc_version");
    std::cout << boost::format("%-20s: %s\n\n") % "Platform ID" % _ptTree.get<std::string>("platform_id");
  }
}

void
run_test_suite_device(const std::shared_ptr<xrt_core::device>& device, boost::property_tree::ptree& _ptDevCollectionTestSuite,
                        bool json, bool quick)
{
  boost::property_tree::ptree _ptDeviceTestSuite;
  boost::property_tree::ptree _ptDeviceInfo;
  test_status status = test_status::passed;
  int _test_suite_size = quick ? 5 : static_cast<int>(testSuite.size());

  get_platform_info(device, _ptDeviceInfo, json);

  for(int i = 0; i < _test_suite_size; i++) {
    testSuite[i].ptTest.put("id", i+1);
    if(!json)
      pretty_print_test_desc(testSuite[i].ptTest, _test_suite_size);
    testSuite[i].testHandle(device, testSuite[i].ptTest);
    _ptDeviceTestSuite.push_back( std::make_pair("", testSuite[i].ptTest) );
    if(!json)
      pretty_print_test_run(testSuite[i].ptTest, status);
    //if a test fails, exit immideately
    if(status == test_status::failed) {
      break;
    }
  }

  if(!json)
    print_status(status);

  _ptDeviceInfo.put_child("tests", _ptDeviceTestSuite);
  _ptDevCollectionTestSuite.push_back( std::make_pair("", _ptDeviceInfo) );
}

}
//end anonymous namespace

// ----- C L A S S   M E T H O D S -------------------------------------------

SubCmdValidate::SubCmdValidate(bool _isHidden, bool _isDepricated, bool _isPreliminary)
    : SubCmd("validate",
             "Validates the basic shell accelleration functionality")
{
  const std::string longDescription = "Validates the given card by executing the platform's validate executable.";
  setLongDescription(longDescription);
  setExampleSyntax("");
  setIsHidden(_isHidden);
  setIsDeprecated(_isDepricated);
  setIsPreliminary(_isPreliminary);
}

void
SubCmdValidate::execute(const SubCmdOptions& _options) const

{
  XBU::verbose("SubCommand: validate");
  // -- Retrieve and parse the subcommand options -----------------------------
  std::vector<std::string> device  = {"all"};
  bool help = false;
  bool json = false;
  bool quick = false;

  po::options_description commonOptions("Commmon Options");
  commonOptions.add_options()
    ("device,d", boost::program_options::value<decltype(device)>(&device)->multitoken(), "The device of interest. This is specified as follows:\n"
                                                                           "  <BDF> - Bus:Device.Function (e.g., 0000:d8:00.0)\n"
                                                                           "  all   - Examines all known devices (default)")
    ("json,j", boost::program_options::bool_switch(&json), "Print in json format")
    ("quick,q", boost::program_options::bool_switch(&quick), "Run a subset of the test suite")
    ("help,h", boost::program_options::bool_switch(&help), "Help to use this sub-command")
  ;

  po::options_description hiddenOptions("Hidden Options");

  po::options_description allOptions("All Options");
  allOptions.add(commonOptions);
  allOptions.add(hiddenOptions);

  // Parse sub-command ...
  po::variables_map vm;

  try {
    po::store(po::command_line_parser(_options).options(allOptions).run(), vm);
    po::notify(vm); // Can throw
  } catch (po::error& e) {
    std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
    printHelp(commonOptions, hiddenOptions);

    // Re-throw exception
    throw;
  }

  // Check to see if help was requested or no command was found
  if (help == true)  {
    printHelp(commonOptions, hiddenOptions);
    return;
  }

  // -- Now process the subcommand --------------------------------------------
  // -- process "device" option -----------------------------------------------
  // Collect all of the devices of interest
  std::set<std::string> deviceNames;
  xrt_core::device_collection deviceCollection;
  for (const auto & deviceName : device)
    deviceNames.insert(boost::algorithm::to_lower_copy(deviceName));

  XBU::collect_devices(deviceNames, true /*inUserDomain*/, deviceCollection);

  //validate all devices
  boost::property_tree::ptree _ptValidate;
  boost::property_tree::ptree _ptDevCollectionTestSuite;
  if(!json)
    std::cout << boost::format("Starting validation for %d devices\n\n") % deviceCollection.size();

  for(auto const& dev : deviceCollection) {
    run_test_suite_device(dev, _ptDevCollectionTestSuite, json, quick);
  }
  _ptValidate.put_child("logical_devices", _ptDevCollectionTestSuite);

  if(json) {
    std::stringstream ss;
    boost::property_tree::json_parser::write_json(ss, _ptValidate);
    std::cout << ss.str() << std::endl;
  }

}

max_stars_repo_name: Pratyushxilinx/XRT

max_issues_repo_name: Pratyushxilinx/XRT

max_forks_repo_name: Pratyushxilinx/XRT


text:
/*Deep Euler implementation of a sonochemical bubble model*/

#include <iostream>
#include <fstream>
#define _USE_MATH_DEFINES
#include <cmath>
#include <vector>
#include <string>
#include <chrono>

#include <torch/script.h>
#include <Eigen/Core>
#include <boost/numeric/odeint.hpp>

const double rho_L = 9.970639504998557e+02;
const double p_inf = 1.0e+5;
const double sigma = 0.071977583160056;
const double gamma = 1.33;
const double c_L = 1.497251785455527e+03; // water 25 Celsius
const double mu_L = 8.902125058209557e-04; //25 Celsius
const double lambda = 0.6084; //water 25 Celsius
const double T_inf = 298.15; // 25 Celsius

const double R_E = 10e-6; //1...10u
const double p_A = 0.5e5; //0.5..2 bar
const double f = 100e3; //20 kHz... 2 MHz

using namespace std;

const int N = 16;
const int N_z = N / 2 - 1;

const int nn_inputs = 2 + 3 + N_z;
const int nn_outputs = 3 + N_z;
const int system_order = nn_outputs + 1;
c10::TensorOptions global_tensor_op;

//Modify these to load the correct model
string file_name = "../simulations/bub_dem_1e-5.txt";
string model_file = "../../../training/traced_model_bub1_e185_2111101855.pt";
string scaler_file = "../../../training/scaler_bub1_2111101855.psca";

typedef double value_type;
typedef vector<value_type> state_type;
typedef Eigen::Matrix<value_type, N / 2, N / 2> matrix_type;

struct std_scaler {
	torch::Tensor mean;
	torch::Tensor scale;

	torch::Tensor operator()(torch::Tensor tensor) {
		return (tensor - mean) / scale;
	}
	torch::Tensor inverse_transform(torch::Tensor tensor) {
		return tensor * scale + mean;
	}
	void parse(istream& is, int numel) {
		mean = torch::ones({ 1, numel });
		is.get();
		double temp = 0.0;
		for (int i = 0; i < numel; i++) {
			is >> temp;
			mean[0][i] = temp;
		}
		is.get();
		is.get();
		scale = torch::ones({ 1, numel });
		is.get();
		for (int i = 0; i < numel; i++) {
			is >> temp;
			scale[0][i] = temp;
		}
		is.get();
		is.get();
	}
};

struct norm_scaler {
	torch::Tensor data_min;
	torch::Tensor data_max;
	double min = 0;
	double max = 0;

	torch::Tensor operator()(torch::Tensor tensor) {
		torch::Tensor X_std = (tensor - data_min) / (data_max - data_min);
		return X_std * (max - min) + min;
	}
	torch::Tensor inverse_transform(torch::Tensor tensor) {
		torch::Tensor Y_std = (tensor - min) / (max - min);
		return Y_std * (data_max - data_min) + data_min;
	}
	void parse(istream& is) {
		data_min = torch::ones({ 1,nn_outputs });
		is.get();
		double temp = 0.0;
		for (int i = 0; i < nn_outputs; i++) {
			is >> temp;
			data_min[0][i] = temp;
		}
		is.get();
		is.get();
		data_max = torch::ones({ 1, nn_outputs });
		is.get();
		for (int i = 0; i < nn_outputs; i++) {
			is >> temp;
			data_max[0][i] = temp;
		}
		is.get(); //']'
		is.get(); //'\n'
		is >> min;
		is >> max;
	}
};

//ode function of Van der Pol equation
class BubDyn {
	double mu = 1.5;
public:
	torch::jit::script::Module model; //the neural network
	torch::Tensor inputs; //reused tensor of inputs
	std_scaler in_transf;
	std_scaler out_transf;

	std::vector<value_type> C; //constants of the right hand side
	Eigen::Matrix<value_type, N / 2, 1> y; //collocation points (half)
	Eigen::Matrix<value_type, N / 2, 1> y_sq; //same, every entry squared
	matrix_type D_E; //Derivative matrix for even functions
	matrix_type D_O; //Derivative matrix for odd functions

	BubDyn() {
		//----------------------------------------------------------
		//bubblemodel initializations
		//----------------------------------------------------------
		const double omega = 2 * M_PI * f;
		value_type pi2wRE = 2 * M_PI / (omega * R_E);

		//constants
		C = std::vector<value_type>(13);
		C[0] = omega * R_E / (2 * M_PI * c_L);
		C[1] = 4 * mu_L / (c_L * rho_L * R_E);
		C[2] = 4 * mu_L / (rho_L * R_E) * pi2wRE;
		C[3] = 2 * sigma * pi2wRE * pi2wRE / (rho_L * R_E);
		C[4] = p_inf / rho_L * pi2wRE * pi2wRE;
		C[5] = p_A / rho_L * pi2wRE * pi2wRE;
		C[6] = pi2wRE * p_inf / (c_L * rho_L);
		C[7] = pi2wRE * p_A / (c_L * rho_L);
		C[8] = 2 * M_PI * pi2wRE * p_A / (c_L * rho_L);
		C[9] = lambda * (gamma - 1) / gamma * pi2wRE / R_E * T_inf / p_inf;
		C[10] = lambda * (gamma - 1) * pi2wRE / R_E * T_inf / p_inf;
		C[11] = (gamma - 1) / gamma;
		C[12] = 1.0 / (3.0 * gamma);

		//Derivative matrices
		Eigen::Matrix<value_type, N, 1> y_full(N);
		value_type rec_cpn = 1.0 / (N - 1);
		for (int i = 0; i < N; i++) {
			y_full[i] = cos(M_PI * i * rec_cpn);
			//std::cout << y_full[i] << std::endl;
		}
		Eigen::Matrix<value_type, N, N> D(N, N);
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				if (i == j) {
					if (i == N - 1) {
						D(N - 1, N - 1) = -(1 + 2 * (N - 1) * (N - 1)) / 6.0;
					}
					else if (i == 0) {
						D(0, 0) = (1 + 2 * (N - 1) * (N - 1)) / 6.0;
					}
					else {
						D(i, i) = -y_full[i] / (2.0 * (1.0 - y_full[i] * y_full[i]));
					}
				}
				else {
					D(i, j) = std::pow(-1, i + j) * (i == 0 || i == N - 1 ? 2.0 : 1.0)
						/ ((j == 0 || j == N - 1 ? 2.0 : 1.0) * (y_full[i] - y_full[j]));
				}
			}
		}
		D_E = matrix_type(N / 2, N / 2);
		D_O = matrix_type(N / 2, N / 2);
		for (int i = 0; i < N / 2; i++) {
			for (int j = 0; j < N / 2; j++) {
				D_E(i, j) = D(i, j) + D(i, N - 1 - j);
			}
		}
		for (int i = 0; i < N / 2; i++) {
			for (int j = 0; j < N / 2; j++) {
				D_O(i, j) = D(i, j) - D(i, N - 1 - j);
			}
		}
		y = y_full.head<N / 2>();
		y_sq = y.cwiseProduct(y);

		//---------------------------------------------------------
		//neural network initializations
		//---------------------------------------------------------
		inputs = torch::ones({ 1, nn_inputs }, global_tensor_op);

		try {
			model = torch::jit::load(model_file);
			std::vector<torch::jit::IValue> inp;
			inp.push_back(torch::ones({ 1, nn_inputs }, global_tensor_op));
			std::cout << inp << endl;
			// Execute the model and turn its output into a tensor.
			at::Tensor output = model.forward(inp).toTensor().detach();
			std::cout << output << endl;
		}
		catch (const c10::Error& e) {
			std::cerr << "Error loading the model: " << e.what() << endl;
			exit(-1);
		}
		ifstream in(scaler_file);
		if (!in) {
			std::cerr << "Error loading the scalers." << endl;
			exit(-1);
		}
		out_transf.parse(in, nn_outputs);
		in_transf.parse(in, nn_inputs);
		in.close();
	}

	//Rewrites the errors array with the predicted local truncation errors
	double* local_error(double t, double t_next, const double* x, double* errors) {

		//updating inputs
		inputs[0][0] = t_next - t;

		for (int i = 0; i < nn_inputs - 1; i++) {
			inputs[0][i + 1] = x[i];
		}
		inputs[0][nn_inputs - 1] = sin(2 * M_PI * t);

		//scaling
		torch::Tensor scaled = in_transf(inputs);
		std::vector<torch::jit::IValue> inps;
		inps.push_back(scaled);
		//evaluating
		torch::Tensor loc_trun_err = model.forward(inps).toTensor().detach();
		loc_trun_err = out_transf.inverse_transform(loc_trun_err);

		for (int i = 0; i < 3; i++) {
			errors[i] = loc_trun_err[0][i].item<double>();
		}
		errors[3] = 0.0; //boundary condition
		for (int i = 3; i < nn_outputs; i++) {
			errors[i + 1] = loc_trun_err[0][i].item<double>();
		}
		return errors;
	}

	//ODE function. In the pointer x the values are rewritten with the computed slopes
	void operator()(double t, const double* x, double* dxdt) {
		value_type rec_xR = 1.0 / x[0];
		value_type rec_xp = 1.0 / x[2];

		Eigen::Map<const Eigen::Matrix<value_type, N / 2, 1>> z(x + 3);
		Eigen::Map<Eigen::Matrix<value_type, N / 2, 1>> dzdt(dxdt + 3);

		Eigen::Matrix<value_type, N / 2, 1> De_x = D_E * z; //derivative of z (dimless temperature)
		/*for(int i = 0; i < N/2; i++){
			std::cout << "t" << y_sq[i] << std::endl;
		}*/

		//bubble pressure evolution
		dxdt[2] = 3 * rec_xR * (C[10] * rec_xR * De_x[0] - gamma * x[1] * x[2]);

		//discretized PDE of bubble temperature
		dzdt = De_x.cwiseProduct(x[1] * rec_xR * y - C[9] * rec_xR * rec_xR * rec_xp * De_x //this might show error, but it will not fail at compile time, valid syntax
			+ C[12] * rec_xp * dxdt[2] * y)
			+ C[11] * rec_xp * dxdt[2] * z + C[9] * rec_xp * rec_xR * rec_xR * z
			.cwiseProduct(y_sq.cwiseInverse()).cwiseProduct(D_O * (y_sq.cwiseProduct(De_x)));
		dxdt[3] = 0.0; //Boundary condition

		//Keller-Miksis equation
		dxdt[0] = x[1];
		value_type sin2pit = sin(2 * M_PI * t);
		value_type den = x[0] - C[0] * x[0] * x[1] + C[1];
		value_type nom = 0.5 * C[0] * x[1] * x[1] * x[1] - 1.5 * x[1] * x[1] - C[2] * x[1] * rec_xR - C[3] * rec_xR
			+ C[4] * x[2] - C[4] - C[5] * sin2pit + C[6] * x[1] * x[2] - C[6] * x[1] - C[7] * x[1] * sin2pit
			- C[8] * x[0] * cos(2 * M_PI * t) + C[6] * x[0] * dxdt[2];
		dxdt[1] = nom / den;
	}
};

class ODESolver
{
public:

	ODESolver(int order) :order(order) {};

	bool setInitialCondition(double* conds, double at) {
		begin_t = at;
		init_conds = (double*)malloc(sizeof(double) * order);
		for (int u = 0; u < order; u++) {
			init_conds[u] = conds[u];
		}
		return true;
	}
	void setTimeStep(double dt) {
		delta_t = dt;
	}
	bool setStepNumber(int steps) {
		max_l = steps;
		return true;
	}

	void solve(BubDyn& sys, ostream& os) {

		double* vector = (double*)malloc(sizeof(double) * order);
		for (int u = 0; u < order; u++) {
			vector[u] = init_conds[u];
		}

		//preparations
		double* k = (double*)malloc(sizeof(double) * order);
		double* local_error = (double*)malloc(sizeof(double) * order);
		double t = begin_t;
		int l = 0;

		os << t;
		for (int i = 0; i < order; i++) {
			os << " " << vector[i];
		}
		os << endl;

		#pragma warning(disable:6011)
		while (l < max_l) {

			sys.local_error(t, t + delta_t, vector, local_error);
			sys(t, vector, k);
			for (int j = 0; j < order; j++) {
				vector[j] = vector[j] + delta_t * k[j] + delta_t * delta_t * local_error[j];
				//To change to Euler Method uncomment the following, comment out the previous
				//vector[j] = vector[j] + delta_t * k[j];
			}
			l++;
			t += delta_t;
			os << t;
			for (int i = 0; i < order; i++) {
				os << " " << vector[i];
			}
			os << endl;
		}
		free(k);
		free(vector);
	}

	~ODESolver() {
		free(init_conds);
	}
private:
	int type = 0;
	int order = 1;
	double* init_conds = 0;
	double begin_t = 0;
	double delta_t = 0.1;
	int max_l = 10;
	double distance(double a, double b) {
		if (a < b)return b - a;
		else return a - b;
	}
};

int main() {
	global_tensor_op = torch::TensorOptions().dtype(torch::kFloat64);
	cout << "BubbleDynamics with DEM started\n" << setprecision(17) << endl;

	ofstream ofs(file_name);
	if (!ofs.is_open()) {
		cout << "File could not be opened: " << file_name << endl;
		exit(-1);
	}
	ofs.precision(17);
	ofs.flags(ios::scientific);
	cout << "Writing file: " << file_name << endl;

	//initial conditions
	double* x = new double[system_order] {1.0, 0.0, 1.0 + 2.0 * sigma / (R_E * p_inf), 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};

	double t_start = 0.0;
	cout << "Rarrrr" << endl;
	BubDyn bubi;

	ODESolver solver(system_order);
	solver.setInitialCondition(x, 0.0);
	solver.setTimeStep(2e-5);
	solver.setStepNumber(5/2e-5);

	cout << "Solving..." << endl;
	auto t1 = chrono::high_resolution_clock::now();
	solver.solve(bubi, ofs);
	auto t2 = chrono::high_resolution_clock::now();
	//Not valid measurement of DEM computational time. Just a slight indicator
	cout << "Time (ms):" << std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count() << endl;

	ofs.flush();
	ofs.close();

	cout << "Ready" << endl;
	return 0;
}

ext: cpp

max_stars_repo_name: plaveczlambert/nonlinearbubbledynamics

max_issues_repo_name: plaveczlambert/nonlinearbubbledynamics

max_forks_repo_name: plaveczlambert/nonlinearbubbledynamics


text:
#include <iostream>
#include <math.h>
#include <Eigen/Dense>
#include <vector>

using namespace Eigen;
using namespace std;

MatrixXd prEq(MatrixXd xk_s, Vector2d uk);
vector<MatrixXd> ukfPred(Vector3d xk_1, Matrix3d Pk_1, Vector2d uk, Matrix3d Qk);

int main()
{
  	Vector3d xk_1(1, 2, 3);

	Matrix3d Pk_1;
	Pk_1 << 1, 0, 0,
	        0, 1, 0,
	        0, 0, 1;

	Vector2d uk(11, -0.00606060606060606060606060);

	Matrix3d Qk;
	Qk << 1, 0, 0,
	      0, 1, 0,
	      0, 0, 1;

	vector <MatrixXd> ret;

	ret = ukfPred(xk_1, Pk_1, uk, Qk);

	//cout << ret[0] << endl << ret[1] << endl;

  }

vector<MatrixXd> ukfPred(Vector3d xk_1, Matrix3d Pk_1, Vector2d uk, Matrix3d Qk)
{
	double kappa = 1;

	Vector3d xk;
	Matrix3d Pk;

	MatrixXd xk_s(3,7);

	double wc = kappa / (3 + kappa);
	double we = 1/(2*(3+kappa));

	xk_s.col(0) = xk_1;

	Matrix3d aux = (xk_1 * MatrixXd::Constant(1,3,1));
	Matrix3d aux2 = ((3 + kappa) * Pk_1).llt().matrixL().transpose();

	xk_s.block(0,1,3,3) = aux + aux2;
	xk_s.block(0,4,3,3) = aux - aux2;

	xk_s = prEq(xk_s, uk);

	xk = wc * xk_s.col(0);

	for (int i = 1; i < 7; i++)
	{
		xk = xk + we * xk_s.col(i);
	}

	Pk = wc * ((xk_s.col(0) - xk) * ((xk_s.col(0) - xk).transpose()));
	cout << endl << Pk << endl;

	for (int i = 1; i < 7; i++)
	{
		Pk = Pk + we * ((xk_s.col(i) - xk) * ((xk_s.col(i) - xk).transpose()));
		cout << endl << Pk << endl;
	}

	Pk = Pk + Qk;

	vector <MatrixXd> ret;

	ret.push_back(xk);
	ret.push_back(Pk);

	return ret;
}

MatrixXd prEq(MatrixXd xk_s, Vector2d uk)
{
	int n = xk_s.cols();
	double dt = 0.1;

	Vector3d in(uk(0,0), 0, uk(1,0));
	Matrix3d rotMat;
	MatrixXd xk(3,n);

	for(int i = 0; i < n; i++)
	{
		rotMat << cos(xk_s(2,i)), sin(xk_s(2,i)), 0,
		          sin(xk_s(2,i)), (-cos(xk_s(2,i))), 0,
		          0, 0, 1;

		xk.col(i) = xk_s.col(i) + rotMat * in * dt;
	}

	return xk;
}

max_stars_repo_name: lara-unb/amora

max_issues_repo_name: lara-unb/amora

max_forks_repo_name: lara-unb/amora


text:
#include <iostream>
#include <string>
#include <map>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include "LUrlParser/LUrlParser.h"
#include "stalk/stalk_websocket_client.h"
#include "stalk/stalk_server.h"
#include "logger.h"
#include "test_fixtures.h"

int main(int argc, char* argv[])
{
    if (argc < 2)
    {
        std::cerr << "Usage: " << argv[0] << " <url>" << std::endl;
        return 1;
    }

    auto logger = Logger::get("test_websocket_client");

    LUrlParser::clParseURL url = LUrlParser::clParseURL::ParseURL(std::string(argv[1]));

    boost::asio::io_context ioc;

    auto webServer = std::make_shared<Stalk::WebServer>(ioc, "::1", 0, serverKey(), serverCert());
    webServer->run();

    webServer->addWebsocketRoute(Stalk::Route::Websocket(
        "/websocket_route",
        [logger](bool connected, std::shared_ptr<Stalk::WebsocketSession> session, Stalk::RequestVariables&& variables) {
            logger->info("WebSocket Route Callback: Connected:{}", connected);

            session->send("Hello websocket msg from Stalk");
        },
        [logger](std::shared_ptr<Stalk::WebsocketSession> session, std::string&& msg) {
            logger->info("WebSocket Route Callback: msg:{}", msg);
        }));

    boost::asio::ssl::context ctx{boost::asio::ssl::context::sslv23_client};

    auto client = std::make_shared<Stalk::WebsocketClient>(ioc, ctx);

    bool secureSocket = url.m_Scheme == "wss";

    client->connect(
        secureSocket, "::1", std::to_string(webServer->port()),
        std::move(Stalk::Request().target("/")),
        [logger](const boost::system::error_code& ec, const Stalk::Response& resp) {
            logger->info("WebSocket client Connection CB: Status:{}, Body:{}, ec:{}", resp.status(), resp.body(), ec.message());
        },
        [logger](std::string&& msg) {
            logger->info("WebSocket client msg callback:{}", msg);
        },
        [logger](const boost::system::error_code& ec, std::string&& errMsg) {
            logger->info("WebSocket client error callback: errMsg: {}, ec:{}", errMsg, ec.message());
        });
#if 0
    client->connect(secureSocket, url.m_Host, url.m_Port, Stalk::Request(),
                    [](const boost::system::error_code& ec, const Stalk::Response& resp) {},
                    [](std::string&& msg) {},
                    [](const boost::system::error_code&, std::string&& errMsg) {});
#endif
    ioc.run();

    return 0;
}

max_stars_repo_name: pykel/stalk

max_issues_repo_name: pykel/stalk

max_forks_repo_name: pykel/stalk


text:
#include <UnitTest++.h>

#include "../../common.h"
#include "../../gamefw/gamefw.h"
#include "../objfile.h"

#include <physfs.h>
#include <boost/concept_check.hpp>

using namespace gamefw;

struct ObjFileFixture
{
    ObjFileFixture()
    {
        FileService* fileservice = new FileService();
        Locator::registerFileService(*fileservice);
    }

    ~ObjFileFixture()
    {
        FileService& fileservice = Locator::getFileService();
        delete &fileservice;
    }
};

TEST_FIXTURE(ObjFileFixture, TestLoadSimpleObj)
{
    string path = Locator::getFileService().getRealPath("src/util/tests/simple.obj");
    ObjFile model(path);
    CHECK_EQUAL(model.getNumMaterials(), 2); // +1 for the default mtl.
    CHECK_EQUAL(model.getNumNormals(), 1);
    CHECK_EQUAL(model.getNumPositions(), 3);
    CHECK_EQUAL(model.getNumTexcoords(), 3);
    CHECK_EQUAL(model.getNumTriangles(), 1);

    float positions[] = {1.0f, -1.0f, 1.0f,
                         -1.0f, -1.0f, 1.0f,
                         -1.0f, -1.0f, -1.0f};

    float normals[] = {0.0f, -1.0f, 0.0f};

    float texcoords[] = {0.0f, 0.5f,
                         0.5f, 0.0f,
                         1.0f, 0.5f};

    CHECK_ARRAY_CLOSE(model.getPositions(), positions, 9, 0.00);
    CHECK_ARRAY_CLOSE(model.getNormals(), normals, 3, 0.00);
    CHECK_ARRAY_CLOSE(model.getTexCoords(), texcoords, 6, 0.00);

    // Indexes should be -1 from the .obj.
    t_obj_triangle triangle1 = {
        {0, 1, 2},
        {0, 0, 0},
        {0, 1, 2},
        1 // Except for the material, because there's a default one on index 0.
    };

    t_obj_triangle triangle2 = *model.getTriangles();

    CHECK_ARRAY_EQUAL(triangle1.pindices, triangle2.pindices, 3);
    CHECK_ARRAY_EQUAL(triangle1.nindices, triangle2.nindices, 3);
    CHECK_ARRAY_EQUAL(triangle1.tindices, triangle2.tindices, 3);
    CHECK_EQUAL(triangle1.material, triangle2.material);

    t_obj_mtl material1 = {
        {0.64f, 0.64f, 0.64f, 1.0f},
        {0.5f, 0.5f, 0.5f, 1.0f},
        128.0,
        {0.0f, 0.0f, 0.0f}
    };

    t_obj_mtl material2 = model.getMaterials()[1];

    CHECK_ARRAY_CLOSE(material1.diffuse, material2.diffuse, 4, 0.00);
    CHECK_ARRAY_CLOSE(material1.specular, material2.specular, 4, 0.00);
    CHECK_CLOSE(material1.shininess, material2.shininess, 0.00);
}

int main(int argc, char* argv[])
{
    PHYSFS_init(argv[0]);

    return UnitTest::RunAllTests();
    return 0;
}

max_stars_repo_name: myrjola/obsbul

max_issues_repo_name: myrjola/obsbul

max_forks_repo_name: myrjola/obsbul


text:
//
//  DataAugmentation.hpp
//  dusthm-cpp
//
//  Created by Brandon Kelly on 4/30/14.
//  Copyright (c) 2014 Brandon C. Kelly. All rights reserved.
//

#ifndef dusthm_cpp_DataAugmentation_hpp
#define dusthm_cpp_DataAugmentation_hpp

// Standard includes
#include <cmath>
#include <vector>
#include <stdio.h>
#include <numeric>

// Boost includes
#include <boost/shared_ptr.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/random/uniform_real_distribution.hpp>

// Local includes
#include "chol_update_r1.hpp"

// Global random number generator and distributions for generating random numbers on the host. The random number generator used
// is the Mersenne Twister mt19937 from the BOOST library.
extern boost::random::mt19937 rng;
extern boost::random::normal_distribution<> snorm; // Standard normal distribution
extern boost::random::uniform_real_distribution<> uniform; // Uniform distribution from 0.0 to 1.0

// Global constants for MCMC sampler
const double target_rate = 0.4; // MCMC sampler target acceptance rate
const double decay_rate = 0.667; // decay rate of robust adaptive metropolis algorithm

// convenience typedefs
typedef std::vector<std::vector<double> > vecvec;
typedef std::vector<double> svector;

template <int mfeat, int pchi, int dtheta> class PopulationPar; // forward declaration

// class for a data augmentation.
template <int mfeat, int pchi, int dtheta>
class DataAugmentation
{
public:
	// Constructor
	DataAugmentation(vecvec& meas2d, vecvec& meas_unc2d) : ndata(meas2d.size()) {
		// set sizes of arrays
		meas.resize(ndata * mfeat);
		meas_unc.resize(ndata * mfeat);
		logdens.resize(ndata);
		chi.resize(ndata * pchi);
		int dim_cholfact = pchi * pchi - ((pchi - 1) * pchi) / 2;
		cholfact.resize(ndata * dim_cholfact);
		naccept.resize(ndata);

		// copy input data to data members
		for (int j = 0; j < mfeat; ++j) {
			for (int i = 0; i < ndata; ++i) {
				meas[ndata * j + i] = meas2d[i][j];
				meas_unc[ndata * j + i] = meas_unc2d[i][j];
			}
		}

        std::fill(cholfact.begin(), cholfact.end(), 0.0);

        save_trace = true;
	}

    virtual double LogDensity(double* chi, double* meas, double* meas_unc) {return 0.0;}

	virtual void Initialize() {
        // initialize all chi values to zero
        std::fill(chi.begin(), chi.end(), 0.0);

        // set initial covariance matrix of the chi proposals as the identity matrix
        double local_chi[pchi];
        double local_meas[mfeat], local_meas_unc[mfeat];
        for (int i=0; i<ndata; i++) {
            int diag_index = 0;
            for (int j=0; j<pchi; j++) {
                cholfact[i + ndata * diag_index] = 1.0;
                diag_index += j + 2;  // cholesky factor is lower diagonal
                local_chi[j] = chi[i + ndata * j];
            }
            for (int j=0; j<mfeat; j++) {
                local_meas[j] = meas[i + ndata * j];
                local_meas_unc[j] = meas_unc[i + ndata * j];
            }
            logdens[i] = LogDensity(local_chi, local_meas, local_meas_unc);
        }

		std::fill(naccept.begin(), naccept.end(), 0);
		current_iter = 1;
	}

	// launch the update kernel on the GPU
	virtual void Update() {

        svector logdens_pop = p_Theta->GetLogDensVec();

        for (int i=0; i<ndata; i++) {
            // copy values for this data point for consistency with CUDAHM
            double snorm_deviate[pchi], scaled_proposal[pchi], proposed_chi[pchi], local_chi[pchi];
            const int dim_cholfact = pchi * pchi - ((pchi - 1) * pchi) / 2;
            double local_cholfact[dim_cholfact];
            int cholfact_index = 0;
            for (int j = 0; j < pchi; ++j) {
                local_chi[j] = chi[j * ndata + i];
                for (int k = 0; k < (j+1); ++k) {
                    local_cholfact[cholfact_index] = cholfact[cholfact_index * ndata + i];
                    cholfact_index++;
                }
            }
            double local_meas[mfeat], local_meas_unc[mfeat];
            for (int j = 0; j < mfeat; ++j) {
                local_meas[j] = meas[j * ndata + i];
                local_meas_unc[j] = meas_unc[j * ndata + i];
            }

            // propose a new value of chi
            Propose(local_chi, local_cholfact, proposed_chi, snorm_deviate, scaled_proposal);

            // get value of log-posterior for proposed chi value
            double logdens_meas_prop = LogDensity(proposed_chi, local_meas, local_meas_unc);
            double logdens_pop_prop = p_Theta->LogDensity(proposed_chi, p_Theta->GetTheta());
            double logpost_prop = logdens_meas_prop + logdens_pop_prop;

            /*
             * Uncomment this bit of code for help when debugging.
             *
             if (idata == 0) {
             printf("current iter, idata, mfeat, pchi, dtheta: %i, %i, %i, %i, %i\n", current_iter, idata, mfeat, pchi, dtheta);
             printf("  measurements: %g, %g, %g, %g, %g\n", local_meas[0], local_meas[1], local_meas[2], local_meas[3], local_meas[4]);
             printf("  measurement sigmas: %g, %g, %g, %g, %g\n", local_meas_unc[0], local_meas_unc[1], local_meas_unc[2],
             local_meas_unc[3], local_meas_unc[4]);
             printf("  cholfact: %g, %g, %g, %g, %g, %g\n", local_cholfact[0], local_cholfact[1], local_cholfact[2], local_cholfact[3],
             local_cholfact[4], local_cholfact[5]);
             printf("  current chi: %g, %g, %g\n", local_chi[0], local_chi[1], local_chi[2]);
             printf("  proposed chi: %g, %g, %g\n", proposed_chi[0], proposed_chi[1], proposed_chi[2]);
             printf("  current logdens_meas, logdens_pop: %g, %g\n", logdens_meas[idata], logdens_pop[idata]);
             printf("  proposed logdens_meas, logdens_pop: %g, %g\n", logdens_meas_prop, logdens_pop_prop);
             printf("\n");
             }
             */

            // accept the proposed value of the characteristic?
            double logdens_meas_i = logdens[i];
            double logdens_pop_i = logdens_pop[i];
            double logpost_current = logdens_meas_i + logdens_pop_i;
            double metro_ratio = 0.0;
            bool accept = AcceptProp(logpost_prop, logpost_current, 0.0, 0.0, metro_ratio);

            // adapt the covariance matrix of the characteristic proposal distribution
            AdaptProp(local_cholfact, snorm_deviate, scaled_proposal, metro_ratio, current_iter);

            for (int j = 0; j < dim_cholfact; ++j) {
                // copy value of this adapted cholesky factor back to global memory
                cholfact[j * ndata + i] = local_cholfact[j];
            }

            // printf("current iter, Accept, idata: %d, %d, %d\n", current_iter, accept, idata);
            for (int j=0; j<pchi; j++) {
                chi[ndata * j + i] = accept ? proposed_chi[j] : local_chi[j];
            }
            logdens[i] = accept ? logdens_meas_prop : logdens_meas_i;
            logdens_pop[i] = accept ? logdens_pop_prop : logdens_pop_i;
            naccept[i] += accept;
        }

        p_Theta->SetLogDens(logdens_pop);

	    current_iter++;
	}

    void Propose(double* p_chi, double* p_cholfact, double* p_proposed_chi, double* p_snorm_deviate,
                 double* p_scaled_proposal)
    {
        // get the unit proposal
        for (int j=0; j<pchi; j++) {
            p_snorm_deviate[j] = snorm(rng);
        }

        // propose a new chi value
        int cholfact_index = 0;
        for (int j=0; j<pchi; j++) {
            double scaled_proposal_j = 0.0;
            for (int k=0; k<(j+1); k++) {
                // transform the unit proposal to the centered proposal, drawn from a multivariate normal.
                scaled_proposal_j += p_cholfact[cholfact_index] * p_snorm_deviate[k];
                cholfact_index++;
            }
            p_proposed_chi[j] = p_chi[j] + scaled_proposal_j;
            p_scaled_proposal[j] = scaled_proposal_j;
        }
    }

    bool AcceptProp(double logdens_prop, double logdens_current, double forward_dens,
                    double backward_dens, double& ratio)
    {
        double lograt = logdens_prop - forward_dens - (logdens_current - backward_dens);
        lograt = std::min(lograt, 0.0);
        ratio = exp(lograt);
        double unif = uniform(rng);
        bool accept = (unif < ratio) && isfinite(ratio);
        return accept;
    }

    void AdaptProp(double* p_cholfact, double* p_snorm_deviate, double* p_scaled_proposal, double metro_ratio, int current_iter)
    {
        double unit_norm = 0.0;
        for (int j=0; j<pchi; j++) {
            unit_norm += p_snorm_deviate[j] * p_snorm_deviate[j];
        }
        unit_norm = sqrt(unit_norm);
        double decay_sequence = 1.0 / pow(current_iter, decay_rate);
        double scaled_coef = sqrt(decay_sequence * fabs(metro_ratio - target_rate)) / unit_norm;
        for (int j=0; j<pchi; j++) {
            p_scaled_proposal[j] *= scaled_coef;
        }
        bool downdate = (metro_ratio < target_rate);
        // do rank-1 cholesky update to update the proposal covariance matrix
        chol_update_r1(p_cholfact, p_scaled_proposal, pchi, downdate);
    }

	void ResetAcceptance() {
		std::fill(naccept.begin(), naccept.end(), 0);
	}

	// setters and getters
	void SetChi(svector& new_chi, bool update_logdens = true) {
		chi = new_chi;
		if (update_logdens) {
            svector logdens_pop = p_Theta->GetLogDens();
            for (int i=0; i<ndata; i++) {
                double local_meas[mfeat], local_meas_unc[mfeat];
                for (int j = 0; j < mfeat; ++j) {
                    local_meas[j] = meas[j * ndata + i];
                    local_meas_unc[j] = meas_unc[j * ndata + i];
                }
                double local_chi[pchi];
                for (int j = 0; j<pchi; j++) {
                    local_chi[j] = chi[j * ndata + i];
                }
                logdens[i] = LogDensity(local_chi, local_meas, local_meas_unc);
                // now update the posteriors of the characteristics | population parameter
                logdens_pop[i] = p_Theta->LogDensity(local_chi);
            }
		}
	}

	// make sure that the data augmentation knows about the population parameters
	void SetPopulationPtr(boost::shared_ptr<PopulationPar<mfeat, pchi, dtheta> > t) { p_Theta = t; }

	void SetLogDens(svector& new_logdens) {
		logdens = new_logdens;
	}
	void SetCholFact(svector& new_cholfact) {
		cholfact = new_cholfact;
	}

	void SetSaveTrace(bool dosave) { save_trace = dosave; }

	bool SaveTrace() { return save_trace; }

	// return the value of the characteristic in a std::vector of std::vectors for convenience
	vecvec GetChi() {
		vecvec new_chi(ndata);
		for (int i = 0; i < ndata; ++i) {
			// organize values into a 2-d array of dimensions ndata x pchi
			svector chi_i(pchi);
			for (int j = 0; j < pchi; ++j) {
				chi_i[j] = chi[ndata * j + i];
			}
			new_chi[i] = chi_i;
		}
		return new_chi;
	}

	svector GetLogDensVec() {return logdens;}
	double GetLogDens() {return std::accumulate(logdens.begin(), logdens.end(), 0.0);}
	svector GetChiVec() {return chi;}
	int GetDataDim() {return ndata;}
	int GetChiDim() {return pchi;}
	boost::shared_ptr<PopulationPar<mfeat, pchi, dtheta> > GetPopulationPtr() { return p_Theta; }
    std::vector<int> GetNaccept() {return naccept;}

protected:
	// measurements and their uncertainties
	svector meas;
	svector meas_unc;
	int ndata;
	// characteristics
	svector chi;
	// population-level parameters
	boost::shared_ptr<PopulationPar<mfeat, pchi, dtheta> > p_Theta;
	// logarithm of conditional posterior densities, y | chi
	svector logdens;
	// cholesky factors of Metropolis proposal covariance matrix
	svector cholfact;
	// MCMC sampler parameters
	int current_iter;
    std::vector<int> naccept;
	bool save_trace;
};

#endif

ext: hpp

max_stars_repo_name: tloredo/CUDAHM

max_issues_repo_name: tloredo/CUDAHM

max_forks_repo_name: tloredo/CUDAHM


text:
#pragma once

#include <Eigen/Dense>

namespace hebi {
namespace input {

// Input manager base class
class InputManager
{
public:
  InputManager() = default;
  virtual ~InputManager() noexcept = default;

  // A debug command that can be used to print the current state of the joystick
  // variables that are stored by the class.
  virtual void printState() const = 0;

  // Read/poll/etc; not needed for all joysticks.  Should be called periodically
  // by the application.
  virtual bool update()
  {
    // indicates joystick connected, not that there were updates
    return true;
  }

  // Get the current translation velocity command
  virtual Eigen::Vector3f getTranslationVelocityCmd() const = 0;

  // Get the current rotation velocity command
  virtual Eigen::Vector3f getRotationVelocityCmd() const = 0;

  // Returns true if the quit button has ever been pushed
  virtual bool getQuitButtonPushed() const = 0;

  // Gets the number of times the mode button has been toggled since the last
  // request.
  virtual size_t getMode() = 0;

  // Is the joystick connected?
  virtual bool isConnected() const = 0;
};

} // namespace input
} // namespace hebi

max_stars_repo_name: HebiRobotics/hebi-cpp-examples

max_issues_repo_name: HebiRobotics/hebi-cpp-examples

max_forks_repo_name: HebiRobotics/hebi-cpp-examples


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2004-2012. 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/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/containers/list.hpp>
#include <iostream>
#include <functional>
#include "print_container.hpp"
#include <string>
#include "get_process_id_name.hpp"

struct InstanceCounter
{
   InstanceCounter(){++counter;}
   InstanceCounter(const InstanceCounter&){++counter;}
   InstanceCounter & operator=(const InstanceCounter&){  return *this;  }
  ~InstanceCounter(){--counter;}
   static std::size_t counter;
};

std::size_t InstanceCounter::counter = 0;

using namespace boost::interprocess;

int main ()
{
   const int memsize = 16384;
   const char *const shMemName = test::get_process_id_name();

   BOOST_TRY{
      shared_memory_object::remove(shMemName);

      //Named allocate capable shared mem allocator
      managed_shared_memory segment(create_only, shMemName, memsize);

      //STL compatible allocator object, uses allocate(), deallocate() functions
      typedef allocator<InstanceCounter,
                        managed_shared_memory::segment_manager>
         inst_allocator_t;
      const inst_allocator_t myallocator (segment.get_segment_manager());

      typedef vector<InstanceCounter, inst_allocator_t> MyVect;

      //We'll provoke an exception, let's see if exception handling works
      BOOST_TRY{
         //Fill vector until there is no more memory
         MyVect myvec(myallocator);
         std::size_t i;
         for(i = 0; true; ++i){
            myvec.push_back(InstanceCounter());
         }
      }
      BOOST_CATCH(boost::interprocess::bad_alloc &){
         if(InstanceCounter::counter != 0)
            return 1;
      } BOOST_CATCH_END

      //We'll provoke an exception, let's see if exception handling works
      BOOST_TRY{
         //Fill vector at the beginning until there is no more memory
         MyVect myvec(myallocator);
         std::size_t i;
         InstanceCounter ic;
         for(i = 0; true; ++i){
            myvec.insert(myvec.begin(), i, ic);
         }
      }
      BOOST_CATCH(boost::interprocess::bad_alloc &){
         if(InstanceCounter::counter != 0)
            return 1;
      }
      BOOST_CATCH(std::length_error &){
         if(InstanceCounter::counter != 0)
            return 1;
      } BOOST_CATCH_END
   }
   BOOST_CATCH(...){
      shared_memory_object::remove(shMemName);
      BOOST_RETHROW
   }
   BOOST_CATCH_END

   shared_memory_object::remove(shMemName);
   return 0;
}


text:
//
// Created by Cephas Svosve on 16/11/2021.
//

//
// Created by Cephas Svosve on 5/8/2021.
//

//
// Created by Cephas Svosve on 17/6/2021.
//

#include "StochasticMath.h"
#include <iostream>
#include <vector>
#include <math.h>
#include <boost/random.hpp>
#include <numeric>

//get process growth rate i.e average of the percentage change in dividend paid-out, dD(t)/D(t-1).
double Stats::getGrowthRate(int tickerID)
{
    return growthRate[tickerID];
}

//get volatility i.e stdev of the growth process.
double Stats::getVolatility(int tickerID)
{
    return volatility[tickerID];
}

double Stats::getAutoCorr(int tickerID)
{
    return autoCorr[tickerID];
}

void Stats::setGrowthRate(double x)
{
    growthRate.push_back(x);
}

void Stats::setVolatility(double x)
{
    volatility.push_back(x);
}

void Stats::setAutoCorr(double x)
{
    autoCorr.push_back(x);
}

void Stats::setCrossCorr()
{

    // std::cout <<  "Div " << crossCorrMat << std::endl;
}

//because our system depends on accuracy of the randomness of the random matrix,
//we create a function that carefully generates a purely random matrix,
//i.e. auto-correlation is 0 precise to the order of e-03 as well as the cross-sectional correlation

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
MatrixXd Stats::generateWhiteNoise(int numOfAssets, int numOfTicks)
{
    MatrixXd randoms(numOfAssets,numOfTicks);
      VectorXd a;

    //algorithm for generating random numbers that are seeded on changing time
      time_t now = 3;
        boost::random::mt19937 gen{static_cast<uint32_t>(now)};
          boost::normal_distribution<> nd(0.0, 1.);
            boost::variate_generator<boost::mt19937&,
              boost::normal_distribution<> > var_nor(gen, nd);

    //we generate the matrix of random numbers
    for(int rw=0; rw < numOfAssets; rw++)
    {
        //we make sure the naturally occurring auto-correlation is sufficiently small by using a do-while loop
          do
            {
              //here we load each row with appropriate random numbers
                a = VectorXd(numOfTicks);
                  for(int i = 0; i < numOfTicks; ++i)
                    {
                      a(i) = var_nor();
            }
        }
        while (abs(lateralcorrcoef(a)) > 0.001);

        randoms.row(rw) = a;
    }

    //We then remove any cross-sectional correlation

    return verticallyWhiten(randoms);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//this function removes cross-sectional correlation by multiplying a matrix
// by the inverse of its lower cholesky decomposition matrix
MatrixXd Stats::verticallyWhiten(MatrixXd mx)
{
    MatrixXd X = crossCorr(mx);
      LLT<MatrixXd> llt(X);
        MatrixXd L = llt.matrixL();
          MatrixXd vWhite = L.inverse() * mx;

            return vWhite;
}

//function that mmodels cross-sectional correlation on non-cross-sectionally correlated processes
MatrixXd Stats::verticallyColor(MatrixXd dZ, MatrixXd corr)
{
    LLT<MatrixXd> llt(corr);
    MatrixXd L = llt.matrixL();
    MatrixXd vColored = L * dZ;

    return vColored;
}

//function that generates a noise process with specific one time lag autocorrelation
VectorXd Stats::laterallyColor(VectorXd dZ, double corr)
{
    int n      = dZ.size();
    VectorXd dU = VectorXd(n);
    dU(0) = dZ(0);

    for(int i = 0; i < n-1; i++)
    {
        dU(i+1) = sqrt(1-pow(corr,2))*dZ(i) + corr*dU(i);
    }
    return dU;
}

//computes stdev
double Stats::stdev(VectorXd X)
{
    double sum = X.sum();
    double m =  sum / X.size();

    double accum = 0.0;

    for(int d = 0; d < X.size(); d++)
    {
        accum += pow((X(d) - m),2);
    };

    double stdev = sqrt(accum / (X.size()-1));

    return stdev;
}

//standardizes a set of random numbers to a standard normal distribution
VectorXd Stats::standardize(VectorXd X)
{
    double mean = X.mean();
    double sigma= stdev(X);

    VectorXd sX = VectorXd(X.size());

    for(int i =0; i< X.size(); i++)
    {
        sX(i) = (X(i)-mean)/sigma;
    }

    return sX;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//generates an nxm matrix of both auto- and cross-sectionally correlated processes
MatrixXd Stats::generateColoredNoise(int numOfTicks, VectorXd &autoCorrMat, MatrixXd &crossCorrMat)
{
    int numOfAssets = crossCorrMat.row(0).size();

    //create a random matrix
    MatrixXd X = generateWhiteNoise(numOfAssets, numOfTicks);
    MatrixXd Y = verticallyWhiten(X);

    MatrixXd W(numOfAssets,numOfTicks);
    MatrixXd Z(numOfAssets,numOfTicks);
    MatrixXd OUTPUT(numOfAssets,numOfTicks);

    //put auto-correlation
    for(int i = 0; i < numOfAssets; i++)
    {
        W.row(i) =  standardize(laterallyColor(Y.row(i), autoCorrMat(i)));

    }

    Z = verticallyWhiten(W);
    OUTPUT = verticallyColor(Z,crossCorrMat);

    return OUTPUT;

}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//this function calculates the coefficient of determination -correlation- between two vectors
//it requires the two vectors x and y, then computes the variables required for the formula
//i.e. variables xx = x^2  ,xy = x*y  and yy = y^2

double Stats::corrcoef(VectorXd x, VectorXd y)
{
    if(x.size() == y.size()) {

        int n = x.size();

        //variable xx represents x^2
        double xx[n];
        double xy[n];
        double yy[n];

        //sumx is the sum of random variables x
        double sumx = x.sum();
        double sumy = y.sum();

        //sumxx is the sum of random variables x^2
        double sumxx;
        double sumxy;
        double sumyy;

        for (int i=0; i < x.size(); i++)
        {
            xx[i] = pow(x[i],2);
            xy[i] = x[i] * y[i];
            yy[i] = pow(y[i],2);

            sumxx = sumxx + xx[i];
            sumxy = sumxy + xy[i];
            sumyy = sumyy + yy[i];
        }

        //this is the formula used to calculate coefficient of determination, *see
        //https://www.jstor.org/stable/2965177?seq=6#metadata_info_tab_contents
        //Reed, William Gardner. “The Coefficient of Correlation.” Publications of the American Statistical Association, vol. 15, no. 118, 1917, pp. 675–684. JSTOR, www.jstor.org/stable/2965177. Accessed 20 June 2021.

        double r = (n*sumxy - sumx*sumy)/sqrt((n*sumxx-pow(sumx,2))*(n*sumyy-pow(sumy,2)));

        return r;
    }
    else
    {throw "found vectors of different size on computing correlation";}

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////
double Stats::lateralcorrcoef(VectorXd a){

    int n = a.size()-1;

    double x[n];
    double y[n];
    double xx[n];
    double xy[n];
    double yy[n];

    double sumx;
    double sumy;
    double sumxx;
    double sumxy;
    double sumyy;

    for (int i=0; i < n; i++)
    {
        x[i] = a[i+1];
        y[i] = a[i];
        xx[i] = pow(x[i],2);
        xy[i] = x[i] * y[i];
        yy[i] = pow(y[i],2);

        sumx = sumx + x[i];
        sumy = sumy + y[i];

        sumxx = sumxx + xx[i];
        sumxy = sumxy + xy[i];
        sumyy = sumyy + yy[i];
    }

    double r = (n*sumxy - sumx*sumy)/sqrt((n*sumxx-pow(sumx,2))*(n*sumyy-pow(sumy,2)));

    return r;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//computes cross-sectional correlation
MatrixXd Stats::crossCorr(MatrixXd x){
    int m = x.col(0).size();
    int n = x.row(0).size();

    MatrixXd corrMat(m,m);

    for(int i = 0; i < m; i++){
        for(int j = 0; j <= i; j++){

            corrMat(i,j) = corrcoef( x.row(i),x.row(j));
            corrMat(j,i) = corrMat(i,j);
        }
    }

    return corrMat;
}


text:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstdlib>
#include <msgpack.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

using std::cerr;
using std::endl;
using std::move;
namespace asio = boost::asio;
using asio::local::stream_protocol;

enum {
    REQUEST = 0,
    RESPONSE = 1,
    NOTIFY = 2
};

template<typename response_handler, typename event_handler> class BaseNvimClient {
    asio::io_service io;
    // TODO: virtualize the socket, to allow multible connection types
    stream_protocol::socket s{io};
    msgpack::unpacker up;
    uint64_t sid = 0;
    std::unordered_map<uint64_t, response_handler> waiting;
    bool running = false;

    void read_more() {
        up.reserve_buffer(32*1024ul);
        s.async_read_some(asio::buffer(up.buffer(), up.buffer_capacity()),
                boost::bind(&BaseNvimClient::handle_read, this, _1, _2));
    }

    void handle_read(const boost::system::error_code& error, size_t read) {
        if (error) {
            exit(1);
        }
        msgpack::unpacked result;
        up.buffer_consumed(read);
        while (up.next(result)) {
            handle_message(result);
        }
        if (running) read_more();
    }

    void handle_message(msgpack::unpacked &result) {
        // TODO: typesafe
        const msgpack::object_array & res = result.get().via.array;
        auto msg = res.ptr;
        if (msg[0].as<int>() == RESPONSE) {
            uint64_t myid = msg[1].as<uint64_t>();
            auto it = waiting.find(myid);
            if (msg[2].type != msgpack::type::NIL) {
                //cerr << msg[2] << endl;
            }
            it->second(msg[3]); //TODO: error
            waiting.erase(it);
        }
    }

public:
    template<typename... Args> void request_async(const char* name, response_handler &&handler, Args... args) {
        uint64_t myid = sid++;
        std::stringstream sb;
        msgpack::packer<decltype(sb)> p(sb);
        waiting.emplace(myid, move(handler));
        p.pack_array(4);
        p.pack_int(REQUEST).pack(myid).pack(name);
        // TODO: we might need to template this to make the handling of typed arrays safe.
        p.pack(std::tuple<Args...>(args...));
        //cerr << sb.str();
        asio::write(s, asio::buffer(sb.str()));
    }

    bool connect(const std::string address) {
        s.connect(stream_protocol::endpoint(address));
    }

    void run() {
        running = true;
        read_more();
        io.run();
    }

    void stop() {
        running = false;
    }

};

// unityped objects for now
struct NvimObject {
    int8_t tag;
    //uint64_t id;
    int8_t len;
    char data[9];
    NvimObject( msgpack::object & o) {
        assert(o.type == msgpack::type::EXT);
        auto & ext = o.via.ext;
        tag = ext.type();
        // TODO: unpack the nested msgpack number
        len = (int8_t)ext.size;
        assert(len <= 9);
        memcpy(data, ext.data(), len);
    }

    template <typename Packer>
    void msgpack_pack(Packer& pk) const {
        pk.pack_ext(len, tag);
        pk.pack_ext_body(data, len);
    }
};

std::ostream& operator<<(std::ostream& os, const NvimObject& o)
{
    os << "NvimObject(" << (int)o.tag << ")";
    return os;
}

using objhandler = std::function<void(msgpack::object&)>;

template<class T> struct _handler_t {
    using handler_t = std::function<void(T)>;

    static objhandler convert_return(handler_t && handler) {
        return [handler](msgpack::object &o) { handler(o.as<T>()); };
    }
};

template<> struct _handler_t<void> {
    // std::function cannot <void(void)>
    using handler_t = std::function<void()>;
    static objhandler convert_return(handler_t && handler) {
        return [handler](msgpack::object &o) { (void)o; handler(); };
    }
};

// TODO: probably should replace this with a NvimObject ADT
template<> struct _handler_t<msgpack::object&> {
    using handler_t = objhandler;
    static objhandler convert_return(handler_t && handler) {
        return [handler](msgpack::object &o) { handler(o); };
    }
};

template<> struct _handler_t<NvimObject> {
    using handler_t = std::function<void(NvimObject)>;
    static objhandler convert_return(handler_t && handler) {
        return [handler](msgpack::object &o) { handler(NvimObject(o)); };
    }
};

class HandlerNvimClient : public BaseNvimClient<std::function<void(msgpack::object &)>, int> {
protected:
    template<class T> using handler_t = typename _handler_t<T>::handler_t;

    template<class T, typename... Args> void request(const char* name, handler_t<T> &&handler, Args... args) {
        request_async(name, _handler_t<T>::convert_return(move(handler)), args...);
    }

};

/*
class NvimApiClient : public HandlerNvimClient {
public:
void eval(std::string a_str, handler_t<msgpack::object&> && handler)
    { request<msgpack::object&>("vim_eval", move(handler), a_str); }

void strwidth(std::string a_str, handler_t<int64_t> && handler)
    { request<int64_t>("vim_strwidth", move(handler), a_str); }

};
*/

#include "api_gen.hpp"

max_stars_repo_name: bfredl/nvim-cxx

max_issues_repo_name: bfredl/nvim-cxx

max_forks_repo_name: bfredl/nvim-cxx


text:
#pragma once

// reference : https://github.com/MurakamiShun/HttpClient

#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <string>

#include "Result.hpp"

namespace http {
    using char_type = char;
    using string_type = std::basic_string<char_type>;

    using field = boost::beast::http::field;
    using verb = boost::beast::http::verb;
    using http_status = boost::beast::http::status;

    namespace version {
        static constexpr unsigned int _10 = 10;  // HTTP/1.0
        static constexpr unsigned int _11 = 11;  // HTTP/1.1
        static constexpr unsigned int _20 = 11;  // HTTP/2.0
    }

    struct BodyAccesable {
        virtual string_type& body() & noexcept = 0;
        virtual const string_type& body() const & noexcept = 0;
    };

    class ConnectionError : public BodyAccesable {
    public:
        ConnectionError(const string_type& message);

        /// <summary>
        /// 接続エラーのメッセージを返す
        /// </summary>
        string_type& body() & noexcept override;

        /// <summary>
        /// 接続エラーのメッセージを返す
        /// </summary>
        const string_type& body() const & noexcept override;

    private:
        string_type message_;
    };

    class Response : public BodyAccesable {
    public:
        Response();
        Response(boost::beast::http::response<boost::beast::http::string_body>& response);
        Response(boost::beast::http::response<boost::beast::http::string_body>&& response);

        /// <summary>
        /// HTTPレスポンスステータスコードを返す
        /// </summary>
        /// <returns>
        /// ステータスコードを表現するenum class
        /// </returns>
        http_status status() const;

        /// <summary>
        /// HTTPレスポンスステータスコードを返す
        /// </summary>
        /// <returns>
        /// ステータスコードを表す符号なし整数
        /// </returns>
        unsigned int status_code() const;

        /// <summary>
        /// レスポンスのボディを返す
        /// </summary>
        string_type& body() & noexcept override;

        /// <summary>
        /// レスポンスのボディを返す
        /// </summary>
        const string_type& body() const & noexcept override;

        /// <summary>
        /// レスポンスのヘッダを返す
        /// </summary>
        boost::beast::http::fields& header() noexcept;

        const boost::beast::http::fields& header() const noexcept;

    private:
        boost::beast::http::response<boost::beast::http::string_body> response_;
    };

    class Request : public BodyAccesable {
    public:
        Request();
        Request(verb method, const string_type& uri, unsigned int http_version = version::_11);

        Request& set(verb method, const string_type& uri, unsigned int http_version);
        Request& set(field field_name, const string_type& value);
        Request& set(unsigned int http_version);
        Request& set(verb method, const string_type& uri);
        Request& set_body(const string_type& value);

        string_type& body() & noexcept override;
        const string_type& body() const & noexcept override;

        [[nodiscard]] Result<Response, ConnectionError> send(const string_type& host, const string_type& port);

    private:
        boost::beast::http::request<boost::beast::http::string_body> request_;
    };

    using result_type = Result<Response, ConnectionError>;
}


text:
// Copyright (C) 2014-2017 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef VSOMEIP_SERVER_IMPL_HPP
#define VSOMEIP_SERVER_IMPL_HPP

#include <deque>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <vector>

#include <boost/array.hpp>
#include <boost/asio/io_service.hpp>

#include "buffer.hpp"
#include "endpoint_impl.hpp"

namespace vsomeip {

template<typename Protocol>
class server_endpoint_impl: public endpoint_impl<Protocol>,
        public std::enable_shared_from_this<server_endpoint_impl<Protocol> > {
public:
    typedef typename Protocol::socket socket_type;
    typedef typename Protocol::endpoint endpoint_type;
    typedef typename std::map<endpoint_type, std::pair<size_t, std::deque<message_buffer_ptr_t>>> queue_type;
    typedef typename queue_type::iterator queue_iterator_type;

    server_endpoint_impl(std::shared_ptr<endpoint_host> _host,
                         endpoint_type _local, boost::asio::io_service &_io,
                         std::uint32_t _max_message_size,
                         configuration::endpoint_queue_limit_t _queue_limit);
    virtual ~server_endpoint_impl();

    bool is_client() const;
    void restart(bool _force);
    bool is_connected() const;
    void set_connected(bool _connected);

    bool send(const uint8_t *_data, uint32_t _size, bool _flush);
    bool send(const std::vector<byte_t>& _cmd_header, const byte_t *_data,
              uint32_t _size, bool _flush = true);

    virtual void stop();
    bool flush(endpoint_type _target);

public:
    void connect_cbk(boost::system::error_code const &_error);
    void send_cbk(const queue_iterator_type _queue_iterator,
                  boost::system::error_code const &_error, std::size_t _bytes);
    void flush_cbk(endpoint_type _target,
                   const boost::system::error_code &_error);

public:
    virtual bool send_intern(endpoint_type _target, const byte_t *_data,
                             uint32_t _port, bool _flush);
    virtual void send_queued(const queue_iterator_type _queue_iterator) = 0;

    virtual bool get_default_target(service_t _service,
            endpoint_type &_target) const = 0;

    virtual void print_status() = 0;

protected:
    std::map<endpoint_type, message_buffer_ptr_t> packetizer_;
    queue_type queues_;

    std::mutex clients_mutex_;
    std::map<client_t, std::map<session_t, endpoint_type> > clients_;
    std::map<endpoint_type, client_t> endpoint_to_client_;

    boost::asio::steady_timer flush_timer_;

    std::mutex mutex_;

private:
    virtual std::string get_remote_information(
            const queue_iterator_type _queue_iterator) const = 0;
};

} // namespace vsomeip

#endif // VSOMEIP_SERVICE_ENDPOINT_IMPL_HPP

max_stars_repo_name: MicrochipTech/some-ip

max_issues_repo_name: MicrochipTech/some-ip

max_forks_repo_name: MicrochipTech/some-ip


text:
#pragma once
//=====================================================================//
/*!	@file
	@brief	GUI Widget ファイラー（ヘッダー）@n
			ファイル選択を行う GUI モジュール
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2017 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/glfw_app/blob/master/LICENSE
*/
//=====================================================================//
#include <vector>
#include <boost/unordered_map.hpp>
#include <boost/optional.hpp>
#include "utils/files.hpp"
#include "utils/drive_info.hpp"
#include "widgets/widget_director.hpp"
#include "widgets/widget_null.hpp"
#include "widgets/widget_label.hpp"
#include "widgets/widget_button.hpp"
#include "widgets/spring_damper.hpp"

namespace gui {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	GUI filer クラス（ファイル選択）
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	struct widget_filer : public widget {

		typedef widget_filer value_type;

		typedef std::function< void (const std::string&) > select_file_func_type;
		typedef std::function< void (void) > cancel_file_func_type;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief	widget_filer パラメーター
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		struct param {
			plate_param		plate_param_;
			color_param		color_param_;
			text_param		text_param_;
			shift_param		shift_param_;

			std::string		path_;		///< 初期ファイル・パス
			std::string		filter_;	///< 初期ファイル・フィルター

			short			path_height_;
			short			label_height_;

			bool			every_top_;		///< 有効なら、常に手前
			bool			acc_focus_;		///< アクセレーターキーによるフォーカス

			bool			new_file_;		///< 新規ファイル作成

			select_file_func_type	select_file_func_;	///< セレクト関数
			cancel_file_func_type	cancel_file_func_;	///< 選択キャンセル関数

			param(const std::string& path = "", const std::string& filter = "", bool new_file = false) :
				plate_param_(),
				color_param_(widget_director::default_frame_color_),
				text_param_(), shift_param_(),
				path_(path), filter_(filter),
				path_height_(32), label_height_(32),
				every_top_(true), acc_focus_(true),
				new_file_(new_file),
				select_file_func_(nullptr), cancel_file_func_(nullptr)
			{ }
		};

	private:
		widget_director&	wd_;

		param				param_;

		gl::mobj::handle	objh_;

		utils::files		fsc_;
		std::string			fsc_path_;
		bool				fsc_wait_;
		utils::file_infos	file_infos_;
		utils::drive_info	drv_;

		widget_button*	info_;	///< インフォメーション切り替えボタン
		widget*			main_;	///< メイン・フレーム
		widget*			files_;	///< ファイル・フレーム

		// 情報の状態
		struct info_state {
			enum type {
				NONE,	///< 情報無し
				SIZE,	///< サイズ表示
				TIME,	///< 時間表示
				MODE,	///< モード表示
				ALIAS,	///< エイリアス表示
				limit_
			};
		};
		info_state::type	info_state_;

		struct widget_file {
			widget_null*	base;
			widget_label*	name;
			widget_label*	info;
			size_t			size;
			time_t			time;
			mode_t			mode;
			bool			dir;
			widget_file() : base(0), name(0), info(0),
							size(0), time(0), mode(0),
							dir(false) { }
		};
		typedef std::vector<widget_file> widget_files;
		typedef std::vector<widget_file>::iterator widget_files_it;
		typedef std::vector<widget_file>::const_iterator widget_files_cit;

		typedef boost::unordered_map<std::string, uint32_t>	name_map;

		typedef boost::optional<const widget_file&>  widget_file_copt;

		widget_files	left_;
		widget_files	center_;
		widget_files	right_;

		bool			request_right_;

		vtx::fpos	speed_;
		vtx::fpos	position_;
		float		move_speed_;
		uint32_t	select_pos_;

		std::string	file_;

		struct file_t {
			vtx::ipos	position_;
			uint32_t	select_pos_;
			file_t() : position_(0), select_pos_(0) { }
		};

		typedef boost::unordered_map<std::string, file_t>	file_map;
		file_map	file_map_;

		uint32_t	select_file_id_;

		std::string	focus_path_;

		static const char* key_path_;
		static const char* key_locate_;
		static const char* key_size_;

		char				acc_key_;
		char				acc_key_ch_;
		uint32_t			acc_cnt_;

		bool		back_directory_;
		bool		center_update_;

		void create_file_(widget_file& wf, const vtx::irect& rect, int ofs, const std::string& str);
		void create_files_(widget_files& wfs, int ofs);
		widget_files_cit scan_select_in_file_(widget_files& wfs) const;
		widget_files_cit scan_select_file_(widget_files& wfs) const;
		widget_files_cit scan_selected_file_(widget_files& wfs) const;
		void un_selected_(widget_files& wfs);
		void resize_files_(widget_files& wfs, short ofs, short width);
		void update_files_info_(widget_files& wfs);
		void update_files_alias_(widget_files& wfs);
		void destroy_files_(widget_files& wfs);
		void get_regist_state_();
		void set_regist_state_();
		void set_select_pos_(uint32_t pos);
		void destroy_();
		widget_file_copt scan_item_(const std::string& path) const;
		bool focus_(const std::string& fn);
		std::string make_path_(const std::string path);
		void select_path_(const std::string& n);

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-----------------------------------------------------------------//
		widget_filer(widget_director& wd, const widget::param& bp, const param& p) :
			widget(bp), wd_(wd), param_(p), objh_(0),
			fsc_(), fsc_path_(), fsc_wait_(false),
			info_(0), main_(0), files_(0),
			info_state_(info_state::NONE),
			request_right_(false),
			speed_(0.0f), position_(0.0f), move_speed_(0.0f), select_pos_(0),
			file_(),
			select_file_id_(0),
			acc_key_(0), acc_key_ch_(0), acc_cnt_(0),
			back_directory_(false), center_update_(false)
			{ }

		//-----------------------------------------------------------------//
		/*!
			@brief	デストラクター
		*/
		//-----------------------------------------------------------------//
		virtual ~widget_filer() { destroy_(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	型を取得
		*/
		//-----------------------------------------------------------------//
		type_id type() const override { return get_type_id<value_type>(); }

		//-----------------------------------------------------------------//
		/*!
			@brief	widget 型の基本名称を取得
			@return widget 型の基本名称
		*/
		//-----------------------------------------------------------------//
		const char* type_name() const override { return "filer"; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ハイブリッド・ウィジェットのサイン
			@return ハイブリッド・ウィジェットの場合「true」を返す。
		*/
		//-----------------------------------------------------------------//
		bool hybrid() const override { return true; }

		//-----------------------------------------------------------------//
		/*!
			@brief	個別パラメーターへの取得(ro)
			@return 個別パラメーター
		*/
		//-----------------------------------------------------------------//
		const param& get_local_param() const { return param_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	個別パラメーターへの取得
			@return 個別パラメーター
		*/
		//-----------------------------------------------------------------//
		param& at_local_param() { return param_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ファイラーの状態を取得
			@return ファイラーの状態「true」なら有効
		*/
		//-----------------------------------------------------------------//
		bool get_enable() const { return get_state(state::ENABLE); }

		//-----------------------------------------------------------------//
		/*!
			@brief	許可
			@param[in]	f	「false」を指定すると不許可
		*/
		//-----------------------------------------------------------------//
		void enable(bool f = true) {
			wd_.enable(this, f, true);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	初期化
		*/
		//-----------------------------------------------------------------//
		void initialize() override;

		//-----------------------------------------------------------------//
		/*!
			@brief	アップデート
		*/
		//-----------------------------------------------------------------//
		void update() override;

		//-----------------------------------------------------------------//
		/*!
			@brief	サービス
		*/
		//-----------------------------------------------------------------//
		void service() override;

		//-----------------------------------------------------------------//
		/*!
			@brief	レンダリング
		*/
		//-----------------------------------------------------------------//
		void render() override
		{
			if(objh_ == 0) return;

			wd_.at_mobj().resize(objh_, get_param().rect_.size);
			glEnable(GL_TEXTURE_2D);
			wd_.at_mobj().draw(objh_, gl::mobj::attribute::normal, vtx::spos(0));

			shift_text_render(wd_, get_param(), param_.text_param_, param_.plate_param_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	状態のセーブ
			@param[in]	pre	プリファレンス参照
			@return エラーが無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool save(sys::preference& pre) override
		{
			std::string path;
			path += '/';
			path += wd_.create_widget_name(this);
			int err = 0;
			if(!pre.put_text(path + "/current_path", param_.path_)) ++err;
			if(!pre.put_position(path + "/locate", vtx::ipos(get_rect().org))) ++err;
			if(!pre.put_position(path + "/size", vtx::ipos(get_rect().size))) ++err;
///			if(!pre.put_integer(key_info_, info_state_) ++err;
			return err == 0;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	状態のロード
			@param[in]	pre	プリファレンス参照
			@return エラーが無い場合「true」
		*/
		//-----------------------------------------------------------------//
		bool load(const sys::preference& pre) override
		{
			std::string path;
			path += '/';
			path += wd_.create_widget_name(this);

			int err = 0;
			std::string s;
			if(pre.get_text(path + "/current_path", s)) {
				if(utils::probe_file(s, true)) {
					param_.path_ = s;
				} else {
					param_.path_ = "/";
				}
				file_infos_.clear();
				fsc_path_.clear();
				fsc_.set_path(param_.path_, param_.filter_);
				fsc_wait_ = true;
				destroy_files_(left_);
				destroy_files_(center_);
				destroy_files_(right_);
			} else {
				++err;
			}

			vtx::ipos p;
			if(pre.get_position(path + "/locate", p)) {
				at_rect().org = p;
			} else {
				++err;
			}
			if(pre.get_position(path + "/size", p)) {
				at_rect().size = p;
			} else {
				++err;
			}
#if 0
			int i;
			if(pre.get_integer(key_info_, i)) {
				info_state_ = static_cast<info_state::type>(i);
			} else {
				++err;
			}
#endif
			return err == 0;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ファイル選択 ID を取得
			@return ファイル選択 ID
		*/
		//-----------------------------------------------------------------//
		uint32_t get_select_file_id() const { return select_file_id_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ファイル取得ステータス
			@return 「true」なら取得中、「false」で取得済み
		*/
		//-----------------------------------------------------------------//
		bool get_file_state() const { return fsc_wait_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	選択されたファイルを返す
			@return 選択されたファイル
		*/
		//-----------------------------------------------------------------//
		const std::string& get_file() const { return file_; }

		//-----------------------------------------------------------------//
		/*!
			@brief	ファイル・リストを取得
			@param[in]	dir	ディレクトリーを含める場合「true」
			@return ファイル・リスト
		*/
		//-----------------------------------------------------------------//
		utils::strings get_file_list(bool dir = false) const
		{
			utils::strings ss;
			const widget_files& wfs = center_;
			for(widget_files_cit cit = wfs.begin(); cit != wfs.end(); ++cit) {
				const widget_file& wf = *cit;
				if(wf.size == 0 && wf.time == 0 && wf.mode == 0) continue;
				const std::string& fp = wf.name->get_text();
				if(fp == "..") continue;
				std::string fn = utils::append_path(param_.path_, fp);
				if(dir) {
					fn += '/';
					ss.push_back(fn);
				} else {
					if(wf.dir) continue;
					ss.push_back(fn);
				}
			}
			return ss;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ファイルをフォーカスする
			@param[in]	path	選択するファイルパス
			@return 該当するファイルが無い場合「false」
		*/
		//-----------------------------------------------------------------//
		bool focus_file(const std::string& path)
		{
			focus_path_ = make_path_(path);
			return focus_(focus_path_);
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	代替テキスト（エリアス）を設定
			@param[in]	path	選択するファイルパス
			@param[in]	alias	代替テキスト
		*/
		//-----------------------------------------------------------------//
		void set_alias(const std::string& path, const std::string& alias)
		{
			widget_file_copt wfo = scan_item_(path);
			if(wfo) {
				const widget_file& wf = *wfo;
				if(wf.name) {
					wf.name->set_alias(alias);
				}
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	代替テキスト（エリアス）を有効、無効
			@param[in]	path	選択するファイルパス
			@param[in]	ena		無効にする場合「false」
		*/
		//-----------------------------------------------------------------//
		void enable_alias(const std::string& path, bool ena = true)
		{
			widget_file_copt wfo = scan_item_(path);
			if(wfo) {
				const widget_file& wf = *wfo;
				if(wf.name) {
					wf.name->enable_alias(ena);
				}
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief	ファイル情報収集をやり直す
		*/
		//-----------------------------------------------------------------//
		void rescan_center() {
			file_infos_.clear();
			fsc_path_.clear();
			fsc_.set_path(param_.path_, param_.filter_);
			fsc_wait_ = true;
			destroy_files_(center_);
		}
	};
}