text:
// Copyright [2019] <Daniel Weber>

#include "interdedup_decompress.h"

#include <cassert>
#include <cstdlib>

#include <algorithm>
#include <iostream>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include <boost/iostreams/copy.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/bzip2.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/iostreams/filter/lzma.hpp>
#include <boost/log/trivial.hpp>

#include "memdump.h"
#include "request_handler.h"
#include "utils.h"

namespace mscr {

enum class compression {
  ZIP7, GZIP, BZIP2, NOINNER
};

static int decompress_file(const std::string &file_in, const compression &inner,
        std::string *file_out) {
  /* returns the decompressed body from the
   * chosen compression */
  BOOST_LOG_TRIVIAL(debug) << "starting inner decompression";
  std::stringstream input_stream(file_in);
  boost::iostreams::filtering_istream in;
  switch (inner) {
    case compression::ZIP7:
      in.push(boost::iostreams::lzma_decompressor());
      break;
    case compression::GZIP:
      in.push(boost::iostreams::gzip_decompressor());
      break;
    case compression::BZIP2:
      in.push(boost::iostreams::bzip2_decompressor());
      break;
    case compression::NOINNER:
      // nothing to do here
      *file_out = file_in;
      BOOST_LOG_TRIVIAL(debug) << "finished inner decompression";
      return 0;
  }
  in.push(input_stream);
  std::stringstream readbuf;
  boost::iostreams::copy(in, readbuf);
  *file_out = readbuf.str();
  BOOST_LOG_TRIVIAL(debug) << "finished inner decompression";
  return 0;
}

static int read_header(std::istream *file, std::string *method,
    uint32_t *pagesize, uint64_t *uncompressed_size) {
  // parse magic number
  std::string magicnum = read_string(file);
  BOOST_LOG_TRIVIAL(debug) << "reading header";
  BOOST_LOG_TRIVIAL(debug) << "\t magicnum: " << magicnum;
  if (magicnum != "MBCR") {
    BOOST_LOG_TRIVIAL(error) << "magic number mismatch";
    return 1;
  }

  // parse method
  *method = read_string(file);
  BOOST_LOG_TRIVIAL(debug) <<  "\t method: " << *method;

  // parse major version
  auto major_version = read_num_LE(file, 2);
  BOOST_LOG_TRIVIAL(debug) << "\t major version: " << major_version;

  // parse minor version
  auto minor_version = read_num_LE(file, 2);
  BOOST_LOG_TRIVIAL(debug) << "\t minor version: " << minor_version;

  // parse page size
  *pagesize = read_num_LE(file, 4);
  BOOST_LOG_TRIVIAL(debug) << "\t pagesize: " << *pagesize;

  // parse uncompressed size
  *uncompressed_size = read_num_LE(file, 8);
  BOOST_LOG_TRIVIAL(debug) << "\t uncompressed size: " << *uncompressed_size;
  BOOST_LOG_TRIVIAL(debug) << "finished reading header";

  return 0;
}

static int parse_method(std::string method, compression *inner, bool *intra,
    bool *diffing) {
  // sanity check for interdedup
  if (method.find("interdedup") == std::string::npos) {
    return 1;
  }
  method.erase(0, ((std::string) "interdedup").size());

  // check intra
  if (str_starts_with(method, "nointra")) {
    *intra = false;
    method.erase(0, ((std::string) "nointra").size());
  } else {
    *intra = true;
  }

  // check diffing
  if (str_starts_with(method, "delta")) {
    *diffing = true;
    method.erase(0, ((std::string) "delta").size());
  } else {
    *diffing = false;
  }

  // check inner compression
  if (str_starts_with(method, "7zip")) {
    *inner = compression::ZIP7;
  } else if (str_starts_with(method, "gzip")) {
    *inner = compression::GZIP;
  } else if (str_starts_with(method, "bzip2")) {
    *inner = compression::BZIP2;
  } else {
    *inner = compression::NOINNER;

    // we should have consumed the whole method string
    if (!method.empty()) {
      BOOST_LOG_TRIVIAL(error) << "Method is not empty after parsing.";
      return 1;
    }
  }
  return 0;
}

static std::vector<uint32_t> parse_pagenr_list(std::istream *fp) {
  // will hold the final list of page numbers
  std::vector<uint32_t> pagenr_list;
  uint32_t sz = read_num_LE(fp, 4);
  pagenr_list.reserve(sz);

  // keeps track of the previous number for delta encoding
  uint32_t prev = 0;

  // go through the list number by number
  for (uint32_t i = 0; i < sz; ++i) {
    // parse number
    uint32_t num;
    uint32_t curr1B = read_num_LE(fp, 1);

    if ((curr1B & 128) == 128) {
      // msb = 1 --> right 7 bits used for number
      num = curr1B & 127;
    } else {
      // msb = 0 --> read 3 more bytes
      uint32_t secByte = read_num_LE(fp, 1);
      uint32_t thirdByte = read_num_LE(fp, 1);
      uint32_t fourthByte = read_num_LE(fp, 1);
      num = (curr1B << 24) | (secByte << 16) | (thirdByte << 8) | fourthByte;
    }

    // decode delta if it's not the first number
    if (i == 0) {
      pagenr_list.push_back(num);
      prev = num;
    } else {
      num = prev + num + 1;
      pagenr_list.push_back(num);
      prev = num;
    }
  }

  return pagenr_list;
}

static void parse_interval(std::istream *fp, bool *last, uint32_t *left,
    uint32_t *right) {
  /* interval [l, r]
   * format:  t[1b], d[2b], l[29b], r-l[{0,1,2,4}B]
   * t = termination bit
   * d = size of r -l
   * l = page number after left side of interval
   * r = offset to the right side
   */

  // parse t, d and l
  uint32_t left4B = read_num_LE(fp, 4);
  uint32_t upper3b = (left4B & (7 << 29)) >> 29;
  uint32_t size = upper3b & 3;
  *last = (upper3b >> 2) == 1;
  *left = left4B & ((1 << 29) - 1);

  // d = 0b11 encodes 4
  if (size == 3) {
    size = 4;
  }

  // compute r
  if (size == 0) {
    *right = *left;
  } else if (size == 1 || size == 2 || size == 4) {
    uint32_t delta = read_num_LE(fp, size);
    *right = *left + delta;
  } else {
    BOOST_LOG_TRIVIAL(error) << "invalid interval size: " << size;
  }
}

static std::vector<std::pair<uint32_t, uint32_t>> parse_interval_list(
    std::istream *fp) {
  // interval list = list of (left, right) pairs
  std::vector<std::pair<uint32_t, uint32_t>> intervals;

  // parse until we see a set termination bit
  bool last = false;
  while (!last) {
    uint32_t left, right;
    parse_interval(fp, &last, &left, &right);
    std::pair<uint32_t, uint32_t> iv = std::make_pair(left, right);
    intervals.push_back(iv);
  }
  return intervals;
}

static std::pair<uint32_t, uint32_t> decode_patch(std::istream *fp) {
  // parse first two bytes
  uint32_t firstB = read_num_LE(fp, 1);
  uint32_t secB = read_num_LE(fp, 1);

  // decode size + offset
  if ((firstB & 128) == 128) {
    // first bit is set --> encoded in 3B
    uint32_t thirdB = read_num_LE(fp, 1);

    // decode patch
    firstB &= 127;
    uint32_t rebuildB = (firstB << 16) | (secB << 8) | thirdB;
    uint32_t size = 1 + ((rebuildB & 0xFFF000) >> 12);
    uint32_t offset = rebuildB & 0xFFF;

    return std::make_pair(size, offset);
  } else {
    // msb is not set --> simply take the two bytes
    firstB += 1;  // we encoded length - 1

    return std::make_pair(firstB, secB);
  }
}

static std::vector<std::pair<uint32_t, std::string>> parse_diff(
    std::istream *fp) {
  // diff = list of patches
  std::vector<std::pair<uint32_t, std::string>> diff;

  // parse number of patches
  uint32_t patch_count = read_num_LE(fp, 2);

  // parse patch by patch
  for (uint32_t i = 0; i < patch_count; i++) {
    std::pair<uint32_t, uint32_t> size_offset = decode_patch(fp);

    // a patch should never be larger than 2KiB
    assert(size_offset.first <= 2048);
    char readbuf[2048];

    // read complete patch and put it into the diff
    fp->read(readbuf, size_offset.first);
    std::string patchbytes(readbuf, readbuf + size_offset.first);
    diff.emplace_back(size_offset.second, patchbytes);
  }
  return diff;
}

static std::string apply_diff(const std::string &refpage,
    const std::vector<std::pair<uint32_t, std::string>> &diff) {
  // will hold the final page after the patches have been applied
  std::string rebuild_page = refpage;

  // apply patch by patch
  uint32_t offset = 0;
  for (auto patch : diff) {
    // "seek" to the right offset
    offset += patch.first;

    // apply the patch by replacing bytes accordingly
    std::string patchbytes = patch.second;
    for (uint32_t i = 0; i < patchbytes.size(); i++) {
      rebuild_page[offset + i] = patchbytes[i];
    }

    // continue "seeking"
    offset += patchbytes.size();
  }
  return rebuild_page;
}

void interdedup_decompress(request_handler *handler, const char *filename_in,
    const char *out_filename) {

  // open compressed file for reading
  std::ifstream f_compressed(filename_in, std::ios::binary);
  if (f_compressed.fail()) {
    BOOST_LOG_TRIVIAL(error) << "error opening dumpfile " << filename_in;
    return;
  }

  // set pagesize + uncompressed_size
  uint32_t pagesize;
  std::string method;
  uint64_t uncompressed_size;
  int ret = read_header(&f_compressed, &method, &pagesize, &uncompressed_size);
  if (ret) {
    BOOST_LOG_TRIVIAL(error) << "error in header parsing";
    return;
  }

  // set inner + intra + diffing
  compression compression_used;
  bool intra_used;
  bool diffing;
  ret = parse_method(method, &compression_used, &intra_used, &diffing);
  if (ret) {
    BOOST_LOG_TRIVIAL(error) << "error in method parsing";
    return;
  }

  // extract body
  std::noskipws(f_compressed);  // prevents iterator from skipping whitespace
  std::string compressed_body(std::istream_iterator<char>(f_compressed), {});

  // decompress body
  std::string file_body;
  int res = decompress_file(compressed_body, compression_used, &file_body);
  if (res != 0 || file_body.empty()) {
    BOOST_LOG_TRIVIAL(error) << "inner decompression failure";
    return;
  }
  // convert body to stream so we can easily operate on it
  std::stringstream f_body(file_body);

  BOOST_LOG_TRIVIAL(debug) << "got uncompressed file body";

  std::string ref_dump_path = read_string(&f_body);
  if (ref_dump_path.empty()) {
    BOOST_LOG_TRIVIAL(error) << "invalid reference dump path in header";
    return;
  }
  BOOST_LOG_TRIVIAL(debug) << "reference dump: " << ref_dump_path;

  // parse reference pagenrs + intervals
  std::unordered_map<uint32_t, uint32_t> fills;
  std::vector<uint32_t> ref_pagenrs = parse_pagenr_list(&f_body);
  for (uint32_t ref_pagenr : ref_pagenrs) {
    auto iv_list = parse_interval_list(&f_body);
    for (std::pair<uint32_t, uint32_t> interval : iv_list) {
      uint32_t left = interval.first;
      uint32_t right = interval.second;
      // sanity check
      if (left > right) {
        BOOST_LOG_TRIVIAL(error) << "invalid interval";
        return;
      }

      // map deduplicated page numbers to page numbers in reference dump
      for (uint32_t pagenr = left; pagenr <= right; ++pagenr) {
        fills[pagenr] = ref_pagenr;
      }
    }
  }

  // parse diffs
  std::unordered_map<uint32_t, std::vector<std::pair<uint32_t, std::string>>>
      diffs;
  if (diffing) {
    std::vector<uint32_t> diffpages = parse_pagenr_list(&f_body);
    for (uint32_t pagenum : diffpages) {
      diffs[pagenum] = parse_diff(&f_body);
    }
  }

  // parse new pages
  std::unordered_map<uint32_t, std::string> newpages;
  std::set<std::string> newdistinct;
  if (!intra_used) {
    auto iv_newpages = parse_interval_list(&f_body);
    auto page_content = new char[pagesize];

    // parse intervals and pages accordingly
    for (std::pair<uint32_t, uint32_t> interval : iv_newpages) {
      uint32_t left = interval.first;
      uint32_t right = interval.second;
      for (uint32_t pagenr = left; pagenr <= right; ++pagenr) {
        f_body.read(page_content, pagesize);

        // explicit cast because of null-byte issues
        std::string page_content_str(page_content, page_content + pagesize);

        newpages[pagenr] = page_content_str;
        newdistinct.insert(page_content_str);
      }
    }
    delete[](page_content);
  } else {
    // number of intradeduplicate new pages
    uint32_t page_count = read_num_LE(&f_body, 4);

    // parse intervals (one for each page)
    std::vector<std::vector<std::pair<uint32_t, uint32_t>>> intervals;
    intervals.reserve(page_count);
    for (uint32_t i = 0; i < page_count; i++) {
      auto iv = parse_interval_list(&f_body);
      intervals.push_back(std::move(iv));
    }

    // unfold intradeduplication
    auto page_content = new char[pagesize];
    for (uint32_t i = 0; i < page_count; i++) {
      f_body.read(page_content, pagesize);
      std::string page(page_content, page_content + pagesize);
      for (auto iv : (intervals[i])) {
        uint32_t left = iv.first;
        uint32_t right = iv.second;
        for (uint32_t pnum = left; pnum <= right; pnum++) {
          newpages[pnum] = page;
        }
      }
    }
    delete[](page_content);
  }

  // load reference dump
  BOOST_LOG_TRIVIAL(debug) << "loading refdump";
  std::shared_ptr<memdump> refdump;
  if (handler != nullptr) {
    refdump = handler->get_refdump(ref_dump_path, pagesize);
  } else {
    refdump = std::make_shared<memdump>(ref_dump_path);
    refdump->readDumpfile(pagesize);
  }

  // parse reference dump (if not done already)
  auto ref_pages = refdump->getNumToPage();

  // open final file (append .processing because we are not finished yet)
  std::string out_filename_processing(out_filename);
  out_filename_processing += ".processing";
  auto f_out = std::ofstream(out_filename_processing.c_str(), std::ios::binary);

  // reconstruct page by page
  for (uint32_t pagenr = 0; pagenr < uncompressed_size / pagesize; pagenr++) {
    if (fills.count(pagenr) > 0) {
      // we got a deduplicated page with a different page number
      uint32_t refnum = fills[pagenr];
      std::string page_content = (*ref_pages)[refnum];
      f_out.write(page_content.c_str(), pagesize);
    } else if (diffing && (diffs.count(pagenr) > 0)) {
      // we got a diffed page
      auto page_content = apply_diff((*ref_pages)[pagenr], diffs[pagenr]);
      if (page_content.empty()) {
        BOOST_LOG_TRIVIAL(error) << "aborting due to error when applying diffs";
        return;
      }
      f_out.write(page_content.c_str(), pagesize);
    } else if (newpages.count(pagenr) > 0) {
      // we got a completely new page
      std::string page_content = newpages[pagenr];
      f_out.write(page_content.c_str(), pagesize);
    } else {
      // we got a deduplicated page at the same page number
      std::string page_content = (*ref_pages)[pagenr];
      f_out.write(page_content.c_str(), pagesize);
    }
  }

  // flush stream before renaming file
  f_out.close();

  // remove the file if it already exists. This is faster than overwriting
  std::remove(out_filename);

  // remove temporary file
  std::rename(out_filename_processing.c_str(), out_filename);
  BOOST_LOG_TRIVIAL(info) << "decompressed file was saved as " << out_filename;
}

}  // namespace mscr

max_stars_repo_name: d-we/memscrimper

max_issues_repo_name: d-we/memscrimper

max_forks_repo_name: d-we/memscrimper


text:
//
//  smppserver_runtime.cpp
//  SMPPServer
//
//  Created by Alex on 5/20/15.
//  Copyright (c) 2015 Bifang technology. All rights reserved.
//
#include "algorithm.hpp"
#include "smppserver_runtime.h"
#include "configer.hpp"
#include "logger.hpp"
#include <boost/thread.hpp>
#include "smpp_protocol_impl.hpp"
#include "smis_db.hpp"
#include "records_db.hpp"
#include "md5.h"
#include "vendor_runtime_demo.hpp"

smppserver_runtime* smppserver_runtime::instance_ = NULL;
boost::mutex smppserver_runtime::mutex_;

smppserver_statistic* smppserver_statistic::instance_ = NULL;
boost::mutex smppserver_statistic::mutex_;

boost::shared_ptr<vendor_runtime> vendor_runtime_;

smppserver_runtime::smppserver_runtime()
{
}
bool smppserver_runtime::read_configer()
{
	extern std::string get_config_file_path();
	std::string config_file = get_config_file_path();
	if(boost::filesystem::exists(config_file))
	{
		configer conf(config_file);
		//read server
		std::string sec_smpp_server = "smpp_server";
		std::string sec_db = "db";
		configer_.ip = conf.get_string(sec_smpp_server, "ip", "0.0.0.0");
		configer_.port = conf.get_string(sec_smpp_server, "port", "8800");
		configer_.need_authorize = (conf.get_int(sec_smpp_server, "need_auth", 1) == 1);
		configer_.use_hex_decimal_message_id = (conf.get_int(sec_smpp_server, "use_hex_decimal_message_id", 0) == 1);
		configer_.server_id = conf.get_string(sec_smpp_server, "server_id", "");
		if(configer_.server_id.length() == 0)
		{
			configer_.server_id = "SMPPSERVER " + format_decimal_to_string((unsigned int)time(NULL) - 100000000);
		}
		configer_.total_generated_mos = conf.get_int(sec_smpp_server, "total_generated_mos", 0);
		configer_.vendor_index = conf.get_int(sec_smpp_server, "vendor_index", 0);
		configer_.use_buffer_db = (conf.get_int(sec_smpp_server, "use_buffer_db", 0) == 1);
		configer_.setting_server_url = conf.get_string(sec_smpp_server, "setting_server_url", "");

		configer_.record_mt_mo = (conf.get_int(sec_smpp_server, "record_mt_mo", 0) == 1);

		configer_.smis_buffer_db_host_name = conf.get_string(sec_db, "smis_buffer_db_host_name", "");
		configer_.smis_buffer_db_user_name = conf.get_string(sec_db, "smis_buffer_db_user_name", "");
		configer_.smis_buffer_db_password = conf.get_string(sec_db, "smis_buffer_db_password", "");
		configer_.smis_buffer_db_db_name = conf.get_string(sec_db, "smis_buffer_db_db_name", "");
		if(configer_.use_buffer_db)
		{
			if(configer_.smis_buffer_db_host_name.length() == 0
			   || configer_.smis_buffer_db_user_name.length() == 0
			   || configer_.smis_buffer_db_password.length() == 0
			   || configer_.smis_buffer_db_db_name.length() == 0)
			{
				logger_log(__FUNCTION__, LEVEL_ERROR, "in db mode, smis buffer db information must be set correctly.");
				return false;
			}
		}

		configer_.records_db_host_name = conf.get_string(sec_db, "records_db_host_name", "");
		configer_.records_db_user_name = conf.get_string(sec_db, "records_db_user_name", "");
		configer_.records_db_password = conf.get_string(sec_db, "records_db_password", "");
		configer_.records_db_db_name = conf.get_string(sec_db, "records_db_db_name", "");
		if(configer_.record_mt_mo)
		{
			if(configer_.records_db_host_name.length() == 0
			   || configer_.records_db_user_name.length() == 0
			   || configer_.records_db_password.length() == 0
			   || configer_.records_db_db_name.length() == 0)
			{
				logger_log(__FUNCTION__, LEVEL_ERROR, "in want to record mt and mo, records db information must be set correctly.");
				return false;
			}
		}

		return true;
	}
	else
	{
		logger_log(__FUNCTION__, LEVEL_WARNING, "%s not exist", config_file.c_str());
		return true;
	}
}

bool smppserver_runtime::run_smppserver()
{
	try
	{
		if(!read_configer())
		{
			return false;
		}
		smppserver_datasource::get_instance()->set_configer(configer_);
		std::vector<listen_address> las;
		listen_address la;
		la.ip = configer_.ip;
		la.port = configer_.port;
		las.push_back(la);
		logger_log(__FUNCTION__, LEVEL_DEBUG, "smpp server %s starts at: %s:%s, vendor_index:%d, db mode:%d.", configer_.server_id.c_str(), configer_.ip.c_str(), configer_.port.c_str(), (int)configer_.vendor_index, (int)configer_.use_buffer_db);
		finished_ = false;
		if(configer_.vendor_index == 0)//使用系统自带的模拟网关处理
		{
			vendor_runtime_.reset(new vendor_runtime_demo());
		}
		else if(configer_.vendor_index == 1)
		{
			//
			//自己实现从vendor_runtime类继承的协议
			assert(false);
		}
		vendor_runtime_->run();
		unsigned int cores = boost::thread::hardware_concurrency();
		server_.reset(new server(las, cores));
		server_->run();
	}
	catch (std::exception& e)
	{
		std::cerr << "Exception: " << e.what() << "\n";
	}
	return true;
}

void smppserver_runtime::stop_smppserver()
{
	finished_ = true;
	vendor_runtime_->stop();
	server_->finish();
}

ext: cpp

max_stars_repo_name: dotphoenix/smppserver

max_issues_repo_name: dotphoenix/smppserver

max_forks_repo_name: dotphoenix/smppserver


text:
/*
 * Copyright (c) 2011-2021, The DART development contributors
 * All rights reserved.
 *
 * The list of contributors can be found at:
 *   https://github.com/dartsim/dart/blob/master/LICENSE
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include "dart/math/TriMesh.hpp"

#include <Eigen/Geometry>

#include "dart/math/Geometry.hpp"

namespace dart {
namespace math {

//==============================================================================
template <typename S>
TriMesh<S>::TriMesh()
{
  // Do nothing
}

//==============================================================================
template <typename S>
void TriMesh<S>::setTriangles(
    const Vertices& vertices, const Triangles& triangles)
{
  clear();

  this->mVertices = vertices;
  mTriangles = triangles;
}

//==============================================================================
template <typename S>
void TriMesh<S>::computeVertexNormals()
{
  computeTriangleNormals();

  this->mVertexNormals.clear();
  this->mVertexNormals.resize(this->mVertices.size(), Vector3::Zero());

  for (auto i = 0u; i < mTriangles.size(); ++i)
  {
    auto& triangle = mTriangles[i];
    this->mVertexNormals[triangle[0]] += mTriangleNormals[i];
    this->mVertexNormals[triangle[1]] += mTriangleNormals[i];
    this->mVertexNormals[triangle[2]] += mTriangleNormals[i];
  }

  this->normalizeVertexNormals();
}

//==============================================================================
template <typename S>
bool TriMesh<S>::hasTriangles() const
{
  return !mTriangles.empty();
}

//==============================================================================
template <typename S>
bool TriMesh<S>::hasTriangleNormals() const
{
  return hasTriangles() && mTriangles.size() == mTriangleNormals.size();
}

//==============================================================================
template <typename S>
const typename TriMesh<S>::Triangles& TriMesh<S>::getTriangles() const
{
  return mTriangles;
}

//==============================================================================
template <typename S>
const typename TriMesh<S>::Normals& TriMesh<S>::getTriangleNormals() const
{
  return mTriangleNormals;
}

//==============================================================================
template <typename S>
void TriMesh<S>::clear()
{
  mTriangles.clear();
  mTriangleNormals.clear();
  Base::clear();
}

//==============================================================================
template <typename S>
TriMesh<S> TriMesh<S>::operator+(const TriMesh& other) const
{
  return (TriMesh(*this) += other);
}

//==============================================================================
template <typename S>
TriMesh<S>& TriMesh<S>::operator+=(const TriMesh& other)
{
  if (other.isEmpty())
    return *this;

  const auto oldNumVertices = this->mVertices.size();
  const auto oldNumTriangles = mTriangles.size();

  Base::operator+=(other);

  // Insert triangle normals if both meshes have normals. Otherwise, clean the
  // triangle normals.
  if ((!hasTriangles() || hasTriangleNormals()) && other.hasTriangleNormals())
  {
    mTriangleNormals.insert(
        mTriangleNormals.end(),
        other.mTriangleNormals.begin(),
        other.mTriangleNormals.end());
  }
  else
  {
    mTriangleNormals.clear();
  }

  const Triangle offset = Triangle::Constant(oldNumVertices);
  mTriangles.resize(mTriangles.size() + other.mTriangles.size());
  for (auto i = 0u; i < other.mTriangles.size(); ++i)
  {
    mTriangles[i + oldNumTriangles] = other.mTriangles[i] + offset;
  }

  return *this;
}

//==============================================================================
template <typename S>
std::shared_ptr<TriMesh<S>> TriMesh<S>::generateConvexHull(bool optimize) const
{
  auto triangles = Triangles();
  auto vertices = Vertices();
  std::tie(vertices, triangles)
      = computeConvexHull3D<S, Index>(this->mVertices, optimize);

  auto mesh = std::make_shared<TriMesh<S>>();
  mesh->setTriangles(vertices, triangles);

  return mesh;
}

//==============================================================================
template <typename S>
void TriMesh<S>::computeTriangleNormals()
{
  mTriangleNormals.resize(mTriangles.size());

  for (auto i = 0u; i < mTriangles.size(); ++i)
  {
    auto& triangle = mTriangles[i];
    const Vector3 v01
        = this->mVertices[triangle[1]] - this->mVertices[triangle[0]];
    const Vector3 v02
        = this->mVertices[triangle[2]] - this->mVertices[triangle[0]];
    mTriangleNormals[i] = v01.cross(v02);
  }

  normalizeTriangleNormals();
}

//==============================================================================
template <typename S>
void TriMesh<S>::normalizeTriangleNormals()
{
  for (auto& normal : mTriangleNormals)
  {
    normal.normalize();
  }
}

} // namespace math
} // namespace dart

ext: hpp


text:
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include "afxdialogex.h"
#include "FirstSetup.h"
#include "FirstSetupDlg2.h"
#include "FirstSetupDlg3.h"
#include "FirstSetupDlg4.h"
#include "wstring_transform.h"
#include "TokenRetriever.h"
#include "Version.h"
#include <memory>
#include <iostream>
#include <string>
#include <cstring>      ///< memset
#include <errno.h>      ///< errno
#include <winsock2.h>   ///< socket
#include <WS2tcpip.h>
#include <boost/format.hpp>
#include "bit7zlibrary.hpp"
#include "bitextractor.hpp"
#include "bitformat.hpp"
#include "bitexception.hpp"
#include "bitmemextractor.hpp"
#include "logging.h"
#include <io.h>
#include <vector>
#include <map>
#include <algorithm>
#include <fstream>
#include <numeric>
#include <assert.h>
#include <shlobj.h>

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "urlmon.lib")

using namespace std;

void FirstSetup::setup_mitm()
{

	// retrieve home path for user running the program
	logging::log_ptr _logger = logging::get_logger(DEFAULT_LOG);

	wchar_t home_path[MAX_PATH];
	HANDLE current_user;
	OpenProcessToken(GetCurrentProcess(), TOKEN_READ, &current_user);
	SHGetFolderPath(NULL, CSIDL_PROFILE, current_user, SHGFP_TYPE_CURRENT, home_path);
	wstring cert_path = wstring(home_path) + L"\\.mitmproxy\\";
	_logger->info("Saving certificates to path {}", transform::ws2s(cert_path));

	CreateDirectory(cert_path.c_str(), NULL);
	// delete existing certificates
	vector<wstring> cert_names = { L"mitmproxy-ca.p12", L"mitmproxy-ca.pem", L"mitmproxy-ca-cert.cer",
		L"mitmproxy-ca-cert.p12", L"mitmproxy-ca-cert.pem", L"mitmproxy-dhparam.pem" };
	for (wstring name : cert_names) {
		DeleteFile((cert_path + name).c_str());
	}

	try {
		bit7z::Bit7zLibrary lib{ L"7zxa.dll" };
		bit7z::BitExtractor extractor{ lib, bit7z::BitFormat::SevenZip };
		extractor.extract(L"mitmproxy_certs.7z", cert_path);
		_logger->info("Successfully extracted mitmproxy certificates.");
	}
	catch (const bit7z::BitException & ex) {
		_logger->error("Failed to extract mitmproxy certificates. ex.what() returned: {}", (string) ex.what());
		AfxMessageBox(transform::s2ws(ex.what()).c_str());
		AfxThrowUserException();
	}
}

HANDLE FirstSetup::job_to_process_handle(HANDLE job_handle) {
	// get process handle from job object
	JOBOBJECT_BASIC_PROCESS_ID_LIST id_list;
	DWORD return_size;
	QueryInformationJobObject(job_handle, JobObjectBasicProcessIdList, &id_list, sizeof(JOBOBJECT_BASIC_PROCESS_ID_LIST), &return_size);
	DWORD process_id = id_list.ProcessIdList[0];
	return OpenProcess(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, true, process_id);
}

void FirstSetup::setup_bs() {
	setup_bs(optional<CWnd*>());
}

BOOL CALLBACK kill_proxywin(HWND hwnd, LPARAM lParam) {
	wchar_t title[1024];
	GetWindowText(hwnd, title, 1024);
	//wcout << title << L"\n";

	bool visibility = IsWindowVisible(hwnd);
	HWND parent = GetParent(hwnd);

	wchar_t parent_title[1024];
	if (parent != NULL)
		GetWindowText(parent, parent_title, 1024);

	WINDOWINFO window_info;
	window_info.cbSize = sizeof(WINDOWINFO);

	GetWindowInfo(hwnd, &window_info);
	auto width = window_info.rcWindow.right - window_info.rcWindow.left;
	auto height = window_info.rcWindow.bottom - window_info.rcWindow.top;

	if (wstring(title) == L"BlueStacks" && to_wstring(window_info.dwExStyle) == L"3758164225" && visibility == true) {
		logging::log_ptr _logger = logging::get_logger(DEFAULT_LOG);

		_logger->info("Closing window with the following parameters:\n\
Window Title: {}\nVisibility: {}\nHas Parent: {}\nWindow rect: {}x{}\nExtended window styles: {}",
transform::ws2s(title), to_string(visibility), to_string(parent != NULL),
to_string(height), to_string(width), to_string(window_info.dwExStyle));
		if (parent != NULL)
			_logger->info("Parent Title: {}", transform::ws2s(parent_title));

		// we send a WM_CLOSE message to the program
		SendMessage(hwnd, WM_CLOSE, NULL, NULL);
	}
	return true;
}

void FirstSetup::setup_bs(optional<CWnd*> feedback_win) {
	CRegKey registry;
	ULONG sz_datadir = MAX_PATH;
	ULONG sz_installdir = MAX_PATH;
	ULONG sz_version = 20;
	CString cstr_datadir = CString();
	CString cstr_installdir = CString();
	CString bs_version_str;

	logging::log_ptr _logger = logging::get_logger(DEFAULT_LOG);

	if (feedback_win) {
		(*feedback_win)->SetWindowTextW(L"Moving emulator data...");
	}
	_logger->info("Moving Root.vdi");

	// Computer\HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks has info we need in DataDir and InstallDir
	registry.Open(HKEY_LOCAL_MACHINE, L"SOFTWARE\\BlueStacks", KEY_READ);
	registry.QueryStringValue(L"DataDir", cstr_datadir.GetBuffer(sz_datadir), &sz_datadir);
	registry.QueryStringValue(L"InstallDir", cstr_installdir.GetBuffer(sz_installdir), &sz_installdir);
	registry.QueryStringValue(L"ClientVersion", bs_version_str.GetBuffer(sz_version), &sz_version);

	wstring datadir = wstring(cstr_datadir);
	wstring installdir = wstring(cstr_installdir);
	Version bs_version = Version::from_string(transform::ws2s(wstring(bs_version_str)));

	_logger->info("DataDir for BlueStacks: {}", transform::ws2s(datadir));
	_logger->info("InstallDir for BlueStacks: {}", transform::ws2s(installdir));

	// move Root.vdi
	wstring vdi_path = datadir + L"Android\\Root.vdi";
	DeleteFile(vdi_path.c_str());
	MoveFile(L"Root.vdi", vdi_path.c_str());

	if (feedback_win)
		(*feedback_win)->SetWindowTextW(L"Adjusting android proxy settings...");

	_logger->info("Adjusting android proxy settings.");

	// launch BlueStacks
	HANDLE bs_handle = TokenRetriever::run_command(datadir + L"..\\Client\\Bluestacks.exe");

	// keep running proxy setup until it returns success code
	DWORD exit_code;
	DWORD gui_count = 0;
	HANDLE process_handle;
	HANDLE exec_handle;
	vector<HANDLE> proxy_handles;
	// run code to set a proxy - this only works when the BlueStacks emulator has loaded, so after this loop ends, we know that the emulator is running
	bool proxy_assigned = false;
	while (!proxy_assigned) {
		exec_handle = TokenRetriever::run_command(wstring(L"\"") + installdir + L"HD-ConfigHttpProxy.exe\" set " + transform::s2ws(get_local_ip()) + L" 8080", installdir.data(), DETACHED_PROCESS);
		proxy_handles.push_back(exec_handle);
		process_handle = job_to_process_handle(exec_handle);
		//WaitForSingleObject(process_handle, INFINITE); //TODO: This would work way better if we regularly checked if the window has opened

		// every second the proxy configurator runs, check if a window is open
		while (WaitForSingleObject(process_handle, 1000) != WAIT_OBJECT_0) {
			// if GetGuiResources returns a non-zero value, a UI window has been opened (which means the proxy change succeeded)
			gui_count = GetGuiResources(process_handle, GR_USEROBJECTS);
			_logger->info("Got GUI count: {}", to_string(gui_count));

			if (!GetExitCodeProcess(process_handle, &exit_code)) {
				_logger->info("GetExitCodeProgress Error: {}", to_string(GetLastError()));
				break; // try to call the proxy configurator again
			}

			_logger->info("Exit code: {}", to_string(exit_code));
			if (exit_code == 259 && gui_count > 3) { // this code is active when a pop-up is on the screen, we can force quit from here
				// close all instances of the proxy program we've opened so far
				EnumWindows(kill_proxywin, NULL); // sends WM_CLOSE to the proxy window
				//for_each(proxy_handles.begin(), proxy_handles.end(), [](HANDLE h) {CloseHandle(h); });
				_logger->info("Sending WM_CLOSE to proxy window");
				proxy_assigned = true;
				break; // since proxy_assigned, this will also leave the overarching loop
			}
		}

		WaitForSingleObject(process_handle, 5000);
		Sleep(10);
	}

	if (feedback_win)
		(*feedback_win)->SetWindowTextW(L"Waiting for emulator to automatically shut down...");

	// we run HD-Quit.exe to quit bluestacks
	HANDLE quit_handle = TokenRetriever::run_command(installdir + L"HD-Quit.exe");
	HANDLE bs_process_handle = job_to_process_handle(bs_handle);

	WaitForSingleObject(bs_process_handle, INFINITE);

	//CloseHandle(bs_handle);

	if (feedback_win)
		(*feedback_win)->SetWindowTextW(L"Installing Nintendo Switch Online app...");

	// run code to install NSO app
	exec_handle = TokenRetriever::run_command(installdir + L"HD-ApkHandler.exe nso.apk");
	process_handle = job_to_process_handle(exec_handle);
	WaitForSingleObject(process_handle, INFINITE);
	GetExitCodeProcess(process_handle, &exit_code);
}

void FirstSetup::cleanup()
{
	DeleteFile(L"Root.7z.001");
	DeleteFile(L"Root.7z.002");
	DeleteFile(L"Root.7z.003");
	DeleteFile(L"Root.7z.004");
	DeleteFile(L"Root.7z");
	DeleteFile(L"nso.apk");
	DeleteFile(L"installer_bs.exe");
	DeleteFile(L"installer_mitm.exe");
	DeleteFile(L"Root.vdi");
	DeleteFile(L"mitmproxy_certs.7z");

	logging::log_ptr _logger = logging::get_logger(DEFAULT_LOG);
	_logger->info("Deleted temporary installer files.");
}

// using script from https://stackoverflow.com/a/49336660
string FirstSetup::get_local_ip() {
	const char* google_dns_server = "8.8.8.8";
	int dns_port = 53;
	int startup_ret;
	int retries = 0;

	logging::log_ptr _logger = logging::get_logger(DEFAULT_LOG);

	do {
		WORD w_version_requested = MAKEWORD(2, 2);
		WSADATA wsa_data;

		startup_ret = WSAStartup(w_version_requested, &wsa_data);
		if (startup_ret != 0)
			_logger->warn("Startup error {}", to_string(startup_ret));

	} while (startup_ret != 0 && ++retries < 2);

	struct sockaddr_in serv;
	SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);

	//Socket could not be created
	if (sock == INVALID_SOCKET)
		_logger->error("Socket error {}", to_string(WSAGetLastError()));

	memset(&serv, 0, sizeof(serv));
	serv.sin_family = AF_INET;
	serv.sin_addr.s_addr = inet_addr(google_dns_server);
	serv.sin_port = htons(dns_port);

	int err = connect(sock, (const struct sockaddr*) & serv, sizeof(serv));
	if (err < 0)
		_logger->error("Error number: {} -- Error message: {}", to_string(errno), strerror(errno));

	struct sockaddr_in name;
	socklen_t namelen = sizeof(name);
	err = getsockname(sock, (struct sockaddr*) & name, &namelen);

	char buffer[80];
	const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, 80);
	if (p != NULL)
		_logger->info("Local IP address is: {}", buffer);
	else
		_logger->error("Error number: {} -- Error message: {}", to_string(errno), strerror(errno));

	closesocket(sock);
	WSACleanup();

	return buffer;
}

int FirstSetup::confirm_exit(HWND owner)
{
	return (MessageBox(owner, L"This will exit the setup process. Are you sure?", L"Exit Setup", MB_YESNO | MB_ICONINFORMATION) == IDYES);
}

max_stars_repo_name: snowpoke/XPowerControl

max_issues_repo_name: snowpoke/XPowerControl

max_forks_repo_name: snowpoke/XPowerControl


text:
#include <gmpxx.h>
#include <boost/test/minimal.hpp>
#include <boost/numeric/mtl/mtl.hpp>

// Check only if malloc error happens as reported by Hui Li

int test_main(int argc, char** argv)
{
    mtl::dense2D<mpq_class> A(2, 2);
    A(0, 0) = mpq_class(0);
    A(0, 1) = 0; // problem
    mpq_class x;
    x = 0;
    return 0;
}

// g++ -g -DMTL_ASSERT_FOR_THROW -I$MTL_BOOST_ROOT -I/home/pgottsch/Download/gmp-4.2.2 -I/home/pgottsch/projects/boost/boost_1_33_1 -o gmp_test gmp_test.cpp -L/home/pgottsch/Download/gmp-4.2.2 -lgmp


text:
/*
 * Copyright 2020 INRIA
 */

#ifndef __eigenpy_numpy_hpp__
#define __eigenpy_numpy_hpp__

#include <boost/python.hpp>
#include "eigenpy/config.hpp"

#ifndef PY_ARRAY_UNIQUE_SYMBOL
  #define PY_ARRAY_UNIQUE_SYMBOL EIGENPY_ARRAY_API
#endif

#include <numpy/numpyconfig.h>
#ifdef NPY_1_8_API_VERSION
  #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#endif

#include <numpy/noprefix.h>

#if defined _WIN32 || defined __CYGWIN__
  #define EIGENPY_GET_PY_ARRAY_TYPE(array) \
    call_PyArray_ObjectType(reinterpret_cast<PyObject *>(array), 0)
#else
  #define EIGENPY_GET_PY_ARRAY_TYPE(array) \
    PyArray_ObjectType(reinterpret_cast<PyObject *>(array), 0)
#endif

namespace eigenpy
{
  void EIGENPY_DLLEXPORT import_numpy();
}

#if defined _WIN32 || defined __CYGWIN__
namespace eigenpy
{
  EIGENPY_DLLEXPORT PyObject*  call_PyArray_SimpleNew(int nd, npy_intp * shape, int np_type);

  EIGENPY_DLLEXPORT PyObject* call_PyArray_New(int nd, npy_intp * shape, int np_type, void * data_ptr, int options);

  EIGENPY_DLLEXPORT int call_PyArray_ObjectType(PyObject *, int);
}
#else
  #define call_PyArray_SimpleNew PyArray_SimpleNew
  #define call_PyArray_New(nd,shape,np_type,data_ptr,options) \
    PyArray_New(&PyArray_Type,nd,shape,np_type,NULL,data_ptr,0,options,NULL)
#endif

#endif // ifndef __eigenpy_numpy_hpp__

max_stars_repo_name: jcarpent/eigenpy

max_issues_repo_name: leggedrobotics/eigenpy

max_forks_repo_name: leggedrobotics/eigenpy


text:
//
// Copyright Jason Rice 2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//

#include <assets/TestContext.hpp>
#include <nbdl/def/builder/context.hpp>
#include <nbdl/make_context.hpp>
#include <nbdl/make_def.hpp>
#include <nbdl/null_store.hpp>

#include <boost/hana.hpp>

namespace hana = boost::hana;

namespace
{
  struct builder_test_context { };
}

namespace nbdl
{
  template <>
  struct make_def_impl<builder_test_context>
  {
    static constexpr auto apply()
    {
      return test_context_def::make(
        test_context::producer_tag<>{},
        test_context::producer_tag<>{},
        test_context::consumer_tag<>{},
        test_context::consumer_tag<>{},
        nbdl::null_store{}
      );
    }
  };
}

int main()
{
  {
    using test_context::int_tag;
    // test single parameter construction
    auto context_ptr = nbdl::make_unique_context<builder_test_context>(
      int_tag<1>{},
      int_tag<2>{},
      int_tag<3>{},
      int_tag<4>{}
    );
  }
  {
    using test_context::int_tag;
    // test single parameter construction
    auto context_ptr = nbdl::make_unique_context<builder_test_context>(
      int_tag<1>{},
      hana::type_c<void>,
      int_tag<3>{},
      int_tag<4>{}
    );
  }
}

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


text:
#include "UserRecognitionServer.h"
#include "UserRecognitionClient.h"
#include <XnCppWrapper.h>
#include "UserDetector.h"
#include "MotionDetector.h"
#include "Xtion.h"
#include "XnErrorChecker.h"
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/Image.h>
#include <string>
#include <iostream>
#include <RDP/UserStatus.h>
#include <RDP/DetectUsers.h>
#include <RDP/DetectMotion.h>
#include <boost/lambda/lambda.hpp>
#include <boost/bind.hpp>

namespace nui{

    static const XnSkeletonJoint UseJointTable[] = {
		XN_SKEL_HEAD,
		XN_SKEL_NECK,
		XN_SKEL_TORSO,
		XN_SKEL_LEFT_ELBOW,
		XN_SKEL_RIGHT_ELBOW,
		XN_SKEL_LEFT_HIP,
		XN_SKEL_RIGHT_HIP,
		XN_SKEL_LEFT_KNEE,
		XN_SKEL_RIGHT_KNEE,
		XN_SKEL_LEFT_HAND,
		XN_SKEL_RIGHT_HAND,
		XN_SKEL_LEFT_SHOULDER,
		XN_SKEL_RIGHT_SHOULDER,
		XN_SKEL_LEFT_FOOT,
		XN_SKEL_RIGHT_FOOT
    };

    static const int JointTableSize = 15;
    static const float PERIOD = 0.5f;    //sec

    class UserRecognitionServer::Impl{
        xn::Context    m_context;
        MotionDetector m_motionDetector;
        boost::shared_ptr<Xtion>           m_device;
        boost::shared_ptr<UserDetector>    m_userDetector;
        ros::Publisher m_rgbPub;
        ros::Publisher m_depthPub;
        ros::Publisher m_detectUsersPub;
        ros::Publisher m_motionPub;

    public:
        Impl(ros::NodeHandle &node) :
            m_rgbPub(node.advertise<sensor_msgs::Image>(RGB_IMAGE, 100)),
            m_depthPub(node.advertise<sensor_msgs::Image>(DEPTH_IMAGE, 100)),
            m_detectUsersPub(node.advertise<RDP::DetectUsers>(DETECT_USERS, 100)),
            m_motionPub(node.advertise<RDP::DetectMotion>(DETECT_MOTION, 100))
        {
            try{
                m_motionDetector.setDetectCb(boost::bind(&UserRecognitionServer::Impl::detectMotionCb, this, boost::lambda::_1));
                m_motionDetector.loadFromMotionFiles(std::string(SHARE_DIR) + "/motions");
                std::string initFile = std::string(SHARE_DIR) + "/InitDevice.xml";
                ROS_INFO("UserRecognition Initfile = %s", initFile.c_str());
                xnErrorCheck(m_context.InitFromXmlFile(initFile.c_str()));
                xnErrorCheck(xnPrintRegisteredLicenses());
                m_context.SetGlobalMirror(true);

                m_device = boost::shared_ptr<Xtion>(new Xtion(m_context));
                m_userDetector = boost::shared_ptr<UserDetector>(new UserDetector(*m_device,m_context));
            }catch(std::exception &ex){
                std::cout << ex.what() << std::endl;
            }
        }

        void detectMotionCb(int id){
            std::cout << "detectMotionCb(" << id << ")" << std::endl;
            RDP::DetectMotion msg;
            msg.id = id;
            m_motionPub.publish(msg);
        }

        void startRecognition(){
            ROS_INFO("start UserRecognition");
			try{
				xnErrorCheck(m_context.StartGeneratingAll());
			}catch(std::exception &ex){
				std::cout << ex.what() << std::endl;
            }
        }

        void waitUpdateAll(){
            m_context.WaitAndUpdateAll();
            m_userDetector->updateAllUserStatus();
        }

        void sendDepthImage(){
            std::vector<UserStatus> status = detectUsers();
            if(status.size() > 0){
                NIMat image = m_userDetector->userDepthMetaData(status[0]);
                if(image){
                    cv_bridge::CvImage depth;
                    depth.image = *image;
                    m_depthPub.publish(depth.toImageMsg());
                }else{
                    std::cout << "Failed sendDepthImage" << std::endl;
                }
            }

            /*
			NIMat image = m_device->depthImage();
			if(image){
            	cv_bridge::CvImage depth;
				depth.image = *image;
            	m_depthPub.publish(depth.toImageMsg());
			}else{
				std::cout << "Failed sendDepthImage" << std::endl;
			}
            */
		}

        void sendRgbImage(){
            NIMat image = m_device->rgbImage();
            if(image){
                cv_bridge::CvImage rgb;
				rgb.image = *image;
				m_rgbPub.publish(rgb.toImageMsg());
			}else{
				std::cout << "Failed sendRgbImage" << std::endl;
			}
		}

		/*
        NIMat userDepthImage(const UserStatus &user){
            NIMat image = m_device->userDepthMetaData(user)

			return m_userDetector->userDepthMetaData(user);
        }
		*/

        const std::vector<UserStatus>& detectUsers(){
            m_userDetector->updateAllUserStatus();
            return m_userDetector->detectUsers();
        }

		void sendDetectUsers(){
			RDP::DetectUsers users;
			std::vector<UserStatus> status = detectUsers();

			for(int i=0; i < status.size(); i++){
				if(status[i].isTracking){
                    users.data.push_back(RDP::UserStatus());
                    users.data[i].id = i;
                    users.data[i].isTracking = status[i].isTracking;

                    for(int m=0; m < JointTableSize; m++){
                        users.data[i].pose.joints.push_back(RDP::UserJoint());
                        users.data[i].pose.joints[m].type =  status[i].joint(UseJointTable[m]).jointType;
                        users.data[i].pose.joints[m].pos.x = status[i].joint(UseJointTable[m]).x;
                        users.data[i].pose.joints[m].pos.y = status[i].joint(UseJointTable[m]).y;
                        users.data[i].pose.joints[m].pos.z = status[i].joint(UseJointTable[m]).z;
                    }
                }
			}
            m_motionDetector.updateUsers(users.data, PERIOD);
			m_detectUsersPub.publish(users);
		}

        bool isValid() const{
            return m_userDetector->isValid() && m_device->isValid();
        }

        void runServer(){
			startRecognition();
			ros::Rate loopRate(1.f/PERIOD);
			while(ros::ok()){
				waitUpdateAll();
				ros::spinOnce();
				sendRgbImage();
				sendDepthImage();
				sendDetectUsers();
				loopRate.sleep();
			}
        }

        ~Impl(){
            m_context.Shutdown();
        }

    };

    UserRecognitionServer::UserRecognitionServer(ros::NodeHandle &node) : pImpl(new Impl(node))
    {

    }

    bool UserRecognitionServer::isValid() const{
        return pImpl->isValid();
    }

    void UserRecognitionServer::runServer(){
        pImpl->runServer();
    }

} //namespace nui


text:
/****************************************************************************
 *
 * fkie_message_filters
 * Copyright © 2018-2020 Fraunhofer FKIE
 * Author: Timo Röhling
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ****************************************************************************/
#include "test.h"
#include <fkie_message_filters/helpers/access_ros_header.h>
#include <fkie_message_filters/helpers/io.h>
#include <fkie_message_filters/helpers/tuple.h>
#include <boost/shared_ptr.hpp>
#include <memory>
#include <ros/message_event.h>

static std::size_t seq_helper(std::size_t a, std::size_t b, std::size_t c)
{
    return a + b + c;
}

TEST(fkie_message_filters, SequenceHelpers)
{
    std::size_t result = 0;
    mf::helpers::for_each_apply<4>(
        [&](auto Is)
        {
            result += Is;
        }
    );
    ASSERT_EQ(6u, result);
    mf::helpers::for_each_apply<4>(
        [&](auto Is)
        {
            result += Is;
        }
    );
    result = mf::helpers::index_apply<3>(
        [](auto... Is) -> std::size_t
        {
            return seq_helper(Is...);
        }
    );
    ASSERT_EQ(3u, result);
    result = 0;
    mf::helpers::select_apply<4>(2,
        [&](auto Is)
        {
            result += Is;
        }
    );
    ASSERT_EQ(2u, result);
}

TEST(fkie_message_filters, RosHeaderExtraction)
{
    // Verify that the access_ros_header() helper function works with all supported data types
    using IntegerStamped = Stamped<int>;

    IntegerStamped i1{0, std::string(), ros::Time(1, 0)};
    std::shared_ptr<IntegerStamped const> i2 = std::make_shared<IntegerStamped>(0, std::string(), ros::Time(2, 0));
    boost::shared_ptr<IntegerStamped const> i3 = boost::make_shared<IntegerStamped>(0, std::string(), ros::Time(3, 0));
    ros::MessageEvent<IntegerStamped const> i4{boost::make_shared<IntegerStamped>(0, std::string(), ros::Time(4, 0)), boost::shared_ptr<ros::M_string>(), ros::Time(4, 0), false, []() -> boost::shared_ptr<IntegerStamped> { return boost::shared_ptr<IntegerStamped>();}};

    ASSERT_EQ(ros::Time(1,0), mf::helpers::access_ros_header_stamp(i1));
    ASSERT_EQ(ros::Time(2,0), mf::helpers::access_ros_header_stamp(i2));
    ASSERT_EQ(ros::Time(3,0), mf::helpers::access_ros_header_stamp(i3));
    ASSERT_EQ(ros::Time(4,0), mf::helpers::access_ros_header_stamp(i4));
}


text:
/*
 *          Copyright Andrey Semashev 2007 - 2010.
 * 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)
 */
/*!
 * \file   record_ordering.hpp
 * \author Andrey Semashev
 * \date   23.08.2009
 *
 * This header contains ordering predicates for logging records.
 */

#if (defined(_MSC_VER) && _MSC_VER > 1000)
#pragma once
#endif // _MSC_VER > 1000

#ifndef BOOST_LOG_UTILITY_RECORD_ORDERING_HPP_INCLUDED_
#define BOOST_LOG_UTILITY_RECORD_ORDERING_HPP_INCLUDED_

#include <boost/optional.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/log/detail/prologue.hpp>
#include <boost/log/detail/functional.hpp>
#include <boost/log/detail/function_traits.hpp>
#include <boost/log/core/record.hpp>
#include <boost/log/attributes/attribute.hpp>

namespace boost {

namespace BOOST_LOG_NAMESPACE {

/*!
 * \brief Ordering predicate, based on log record handle comparison
 *
 * This predicate offers a quick log record ordering based on the log record handles.
 * It is not specified whether one record is less than another, in terms of the
 * predicate, until the actual comparison is performed. Moreover, the ordering may
 * change every time the application runs.
 *
 * This kind of ordering may be useful if log records are to be stored in an associative
 * container with as least performance overhead as possible.
 */
template< typename FunT = aux::less >
class handle_ordering :
    private FunT
{
public:
    //! Result type
    typedef bool result_type;

public:
    /*!
     * Default constructor. Requires \c FunT to be default constructible.
     */
    handle_ordering() : FunT()
    {
    }
    /*!
     * Initializing constructor. Constructs \c FunT instance as a copy of the \a fun argument.
     */
    explicit handle_ordering(FunT const& fun) : FunT(fun)
    {
    }

    /*!
     * Ordering operator
     */
    template< typename CharT >
    result_type operator() (basic_record< CharT > const& left, basic_record< CharT > const& right) const
    {
        return FunT::operator() (left.handle().get(), right.handle().get());
    }
};

/*!
 * \brief Ordering predicate, based on attribute values associated with records
 *
 * This predicate allows to order log records based on values of a specificly named attribute
 * associated with them. Two given log records being compared should both have the specified
 * attribute value of the specified type to be able to be ordered properly. As a special case,
 * if neither of the records have the value, these records are considered equivalent. Otherwise,
 * the ordering results are unspecified.
 */
template< typename CharT, typename ValueT, typename FunT = aux::less >
class attribute_value_ordering :
    private FunT
{
public:
    //! Result type
    typedef bool result_type;
    //! Character type
    typedef CharT char_type;
    //! Log record type
    typedef basic_record< char_type > record_type;
    //! String type
    typedef typename record_type::string_type string_type;
    //! Compared attribute value type
    typedef ValueT attribute_value_type;

private:
    //! Attribute value name
    const string_type m_Name;

public:
    /*!
     * Initializing constructor.
     *
     * \param name The attribute value name to be compared
     * \param fun The ordering functor
     */
    attribute_value_ordering(string_type const& name, FunT const& fun = FunT()) : FunT(fun), m_Name(name)
    {
    }

    /*!
     * Ordering operator
     */
    result_type operator() (record_type const& left, record_type const& right) const
    {
        optional< attribute_value_type > left_value, right_value;

        typedef typename record_type::values_view_type values_view_type;
        typename values_view_type::const_iterator
            it_left = left.attribute_values().find(m_Name),
            it_right = right.attribute_values().find(m_Name);
        if (it_left != left.attribute_values().end())
            left_value = it_left->second->get< attribute_value_type >();
        if (it_right != right.attribute_values().end())
            right_value = it_right->second->get< attribute_value_type >();

        if (left_value)
        {
            if (right_value)
                return FunT::operator() (left_value.get(), right_value.get());
            else
                return false;
        }
        else
            return !right_value;
    }
};

/*!
 * The function constructs a log record ordering predicate
 */
template< typename ValueT, typename CharT, typename FunT >
inline attribute_value_ordering< CharT, ValueT, FunT >
make_attr_ordering(const CharT* name, FunT const& fun)
{
    typedef attribute_value_ordering< CharT, ValueT, FunT > ordering_t;
    return ordering_t(name, fun);
}

/*!
 * The function constructs a log record ordering predicate
 */
template< typename ValueT, typename CharT, typename FunT >
inline attribute_value_ordering< CharT, ValueT, FunT >
make_attr_ordering(std::basic_string< CharT > const& name, FunT const& fun)
{
    typedef attribute_value_ordering< CharT, ValueT, FunT > ordering_t;
    return ordering_t(name, fun);
}

#if !defined(BOOST_LOG_NO_FUNCTION_TRAITS)

namespace aux {

    //! An ordering predicate constructor that uses SFINAE to disable invalid instantiations
    template<
        typename CharT,
        typename FunT,
        typename ArityCheckT = typename enable_if_c< aux::arity_of< FunT >::value == 2 >::type,
        typename Arg1T = typename aux::first_argument_type_of< FunT >::type,
        typename Arg2T = typename aux::second_argument_type_of< FunT >::type,
        typename ArgsCheckT = typename enable_if< is_same< Arg1T, Arg2T > >::type
    >
    struct make_attr_ordering_type
    {
        typedef attribute_value_ordering< CharT, Arg1T, FunT > type;
    };

} // namespace aux

/*!
 * The function constructs a log record ordering predicate
 */
template< typename CharT, typename FunT >
inline typename aux::make_attr_ordering_type< CharT, FunT >::type
make_attr_ordering(const CharT* name, FunT const& fun)
{
    typedef typename aux::make_attr_ordering_type< CharT, FunT >::type ordering_t;
    return ordering_t(name, fun);
}

/*!
 * The function constructs a log record ordering predicate
 */
template< typename CharT, typename FunT >
inline typename aux::make_attr_ordering_type< CharT, FunT >::type
make_attr_ordering(std::basic_string< CharT > const& name, FunT const& fun)
{
    typedef typename aux::make_attr_ordering_type< CharT, FunT >::type ordering_t;
    return ordering_t(name, fun);
}

#endif // BOOST_LOG_NO_FUNCTION_TRAITS

} // namespace log

} // namespace boost

#endif // BOOST_LOG_UTILITY_RECORD_ORDERING_HPP_INCLUDED_


text:
//  Copyright (C) 2012 Hartmut Kaiser
//  (C) Copyright 2008-10 Anthony Williams
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#include <hpx/hpx_init.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/include/threads.hpp>
#include <hpx/util/lightweight_test.hpp>

#include <utility>
#include <memory>
#include <string>

#include <boost/move/move.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/assign/std/vector.hpp>

///////////////////////////////////////////////////////////////////////////////
int make_int_slowly()
{
    hpx::this_thread::sleep_for(boost::chrono::milliseconds(100));
    return 42;
}

void test_wait_for_two_out_of_five_futures()
{
    unsigned const count = 2;

    hpx::lcos::local::packaged_task<int()> pt1(make_int_slowly);
    hpx::lcos::future<int> f1 = pt1.get_future();
    hpx::lcos::local::packaged_task<int()> pt2(make_int_slowly);
    hpx::lcos::future<int> f2 = pt2.get_future();
    pt2();
    hpx::lcos::local::packaged_task<int()> pt3(make_int_slowly);
    hpx::lcos::future<int> f3 = pt3.get_future();
    hpx::lcos::local::packaged_task<int()> pt4(make_int_slowly);
    hpx::lcos::future<int> f4 = pt4.get_future();
    pt4();
    hpx::lcos::local::packaged_task<int()> pt5(make_int_slowly);
    hpx::lcos::future<int> f5 = pt5.get_future();

    typedef hpx::when_some_result<hpx::util::tuple<
        hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int> > > result_type;
    hpx::lcos::future<result_type> r = hpx::when_some(count, f1, f2, f3, f4, f5);

    result_type result = r.get();

    HPX_TEST(!f1.valid());
    HPX_TEST(!f2.valid());
    HPX_TEST(!f3.valid());
    HPX_TEST(!f4.valid());
    HPX_TEST(!f5.valid());

    HPX_TEST_EQ(result.indices.size(), count);
    HPX_TEST(!hpx::util::get<0>(result.futures).is_ready());
    HPX_TEST(hpx::util::get<1>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<2>(result.futures).is_ready());
    HPX_TEST(hpx::util::get<3>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<4>(result.futures).is_ready());
}

void test_wait_for_three_out_of_five_futures()
{
    unsigned const count = 3;

    hpx::lcos::local::packaged_task<int()> pt1(make_int_slowly);
    hpx::lcos::future<int> f1 = pt1.get_future();
    pt1();
    hpx::lcos::local::packaged_task<int()> pt2(make_int_slowly);
    hpx::lcos::future<int> f2 = pt2.get_future();
    hpx::lcos::local::packaged_task<int()> pt3(make_int_slowly);
    hpx::lcos::future<int> f3 = pt3.get_future();
    pt3();
    hpx::lcos::local::packaged_task<int()> pt4(make_int_slowly);
    hpx::lcos::future<int> f4 = pt4.get_future();
    hpx::lcos::local::packaged_task<int()> pt5(make_int_slowly);
    hpx::lcos::future<int> f5 = pt5.get_future();
    pt5();

    typedef hpx::when_some_result<hpx::util::tuple<
        hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int> > > result_type;
    hpx::lcos::future<result_type> r = hpx::when_some(count, f1, f2, f3, f4, f5);

    result_type result = r.get();

    HPX_TEST(!f1.valid());
    HPX_TEST(!f2.valid());
    HPX_TEST(!f3.valid());
    HPX_TEST(!f4.valid());
    HPX_TEST(!f5.valid());

    HPX_TEST_EQ(result.indices.size(), count);
    HPX_TEST(hpx::util::get<0>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<1>(result.futures).is_ready());
    HPX_TEST(hpx::util::get<2>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<3>(result.futures).is_ready());
    HPX_TEST(hpx::util::get<4>(result.futures).is_ready());
}

void test_wait_for_two_out_of_five_late_futures()
{
    unsigned const count = 2;

    hpx::lcos::local::packaged_task<int()> pt1(make_int_slowly);
    hpx::lcos::future<int> f1 = pt1.get_future();
    hpx::lcos::local::packaged_task<int()> pt2(make_int_slowly);
    hpx::lcos::future<int> f2 = pt2.get_future();
    hpx::lcos::local::packaged_task<int()> pt3(make_int_slowly);
    hpx::lcos::future<int> f3 = pt3.get_future();
    hpx::lcos::local::packaged_task<int()> pt4(make_int_slowly);
    hpx::lcos::future<int> f4 = pt4.get_future();
    hpx::lcos::local::packaged_task<int()> pt5(make_int_slowly);
    hpx::lcos::future<int> f5 = pt5.get_future();

    typedef hpx::when_some_result<hpx::util::tuple<
        hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int> > > result_type;
    hpx::lcos::future<result_type> r = hpx::when_some(count, f1, f2, f3, f4, f5);

    HPX_TEST(!f1.valid());
    HPX_TEST(!f2.valid());
    HPX_TEST(!f3.valid());
    HPX_TEST(!f4.valid());
    HPX_TEST(!f5.valid());

    pt2();
    pt4();

    result_type result = r.get();

    HPX_TEST_EQ(result.indices.size(), count);
    HPX_TEST(!hpx::util::get<0>(result.futures).is_ready());
    HPX_TEST(hpx::util::get<1>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<2>(result.futures).is_ready());
    HPX_TEST(hpx::util::get<3>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<4>(result.futures).is_ready());
}

void test_wait_for_two_out_of_five_deferred_futures()
{
    unsigned const count = 2;

    hpx::lcos::future<int> f1 = hpx::async(hpx::launch::deferred, &make_int_slowly);
    hpx::lcos::future<int> f2 = hpx::async(hpx::launch::deferred, &make_int_slowly);
    hpx::lcos::future<int> f3 = hpx::async(hpx::launch::deferred, &make_int_slowly);
    hpx::lcos::future<int> f4 = hpx::async(hpx::launch::deferred, &make_int_slowly);
    hpx::lcos::future<int> f5 = hpx::async(hpx::launch::deferred, &make_int_slowly);

    typedef hpx::when_some_result<hpx::util::tuple<
        hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int>
      , hpx::lcos::future<int> > > result_type;
    hpx::lcos::future<result_type> r = hpx::when_some(count, f1, f2, f3, f4, f5);

    HPX_TEST(!f1.valid());
    HPX_TEST(!f2.valid());
    HPX_TEST(!f3.valid());
    HPX_TEST(!f4.valid());
    HPX_TEST(!f5.valid());

    result_type result = r.get();

    HPX_TEST_EQ(result.indices.size(), count);
    HPX_TEST(hpx::util::get<0>(result.futures).is_ready());
    HPX_TEST(hpx::util::get<1>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<2>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<3>(result.futures).is_ready());
    HPX_TEST(!hpx::util::get<4>(result.futures).is_ready());
}

///////////////////////////////////////////////////////////////////////////////
using boost::program_options::variables_map;
using boost::program_options::options_description;

int hpx_main(variables_map&)
{
    {
        test_wait_for_two_out_of_five_futures();
        test_wait_for_three_out_of_five_futures();
        test_wait_for_two_out_of_five_late_futures();
        test_wait_for_two_out_of_five_deferred_futures();
    }

    hpx::finalize();
    return hpx::util::report_errors();
}

///////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    // Configure application-specific options
    options_description cmdline("Usage: " HPX_APPLICATION_STRING " [options]");

    // We force this test to use several threads by default.
    using namespace boost::assign;
    std::vector<std::string> cfg;
    cfg += "hpx.os_threads=" +
        boost::lexical_cast<std::string>(hpx::threads::hardware_concurrency());

    // Initialize and run HPX
    return hpx::init(cmdline, argc, argv, cfg);
}

max_stars_repo_name: kempj/hpx

max_issues_repo_name: kempj/hpx

max_forks_repo_name: kempj/hpx


text:
#include <Aquila/core/Algorithm.hpp>
#include <Aquila/utilities/container.hpp>

#include <MetaObject/params/IParam.hpp>
#include <MetaObject/params/ISubscriber.hpp>
#include <MetaObject/params/buffers/IBuffer.hpp>

#include <RuntimeObjectSystem/ISimpleSerializer.h>

#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/rolling_mean.hpp>
#include <boost/accumulators/statistics/rolling_window.hpp>

using namespace mo;
using namespace aq;

Algorithm::Algorithm()
{
    m_logger = mo::getLogger();
}

void Algorithm::setEnabled(bool value)
{
    m_enabled = value;
}

bool Algorithm::getEnabled() const
{
    return m_enabled;
}

mo::ConstParamVec_t Algorithm::getComponentParams(const std::string& filter) const
{
    mo::ConstParamVec_t output; // = mo::IMetaObject::getParams(filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto output2 = shared->getParams(filter);
            output.insert(output.end(), output2.begin(), output2.end());
        }
    }
    return output;
}

mo::ParamVec_t Algorithm::getComponentParams(const std::string& filter)
{
    mo::ParamVec_t output; // = mo::IMetaObject::getParams(filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto output2 = shared->getParams(filter);
            output.insert(output.end(), output2.begin(), output2.end());
        }
    }
    return output;
}

mo::ParamVec_t Algorithm::getParams(const std::string& filter)
{
    mo::ParamVec_t output = mo::MetaObject::getParams(filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto output2 = shared->getParams(filter);
            output.insert(output.end(), output2.begin(), output2.end());
        }
    }
    return output;
}

mo::ConstParamVec_t Algorithm::getParams(const std::string& filter) const
{
    mo::ConstParamVec_t output = mo::MetaObject::getParams(filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto output2 = shared->getParams(filter);
            output.insert(output.end(), output2.begin(), output2.end());
        }
    }
    return output;
}

const mo::IControlParam* Algorithm::getParam(const std::string& name) const
{
    auto output = IAlgorithm::getParam(name);
    if (output)
    {
        return output;
    }

    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            output = shared->getParam(name);
            if (output)
            {
                return output;
            }
        }
    }
    return output;
}

mo::IControlParam* Algorithm::getParam(const std::string& name)
{
    auto output = IAlgorithm::getParam(name);
    if (output)
    {
        return output;
    }

    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            output = shared->getParam(name);
            if (output)
            {
                return output;
            }
        }
    }
    return output;
}

bool Algorithm::process()
{
    mo::Lock_t lock(getMutex());
    if (m_enabled == false)
    {
        return false;
    }
    if (checkInputs() == InputState::kNONE_VALID)
    {
        return false;
    }
    if (processImpl())
    {
        clearModifiedInputs();
        return true;
    }
    return false;
}

const mo::IPublisher* Algorithm::getOutput(const std::string& name) const
{
    auto output = mo::MetaObject::getOutput(name);
    if (output)
    {
        return output;
    }
    if (!output)
    {
        for (auto& component : m_algorithm_components)
        {
            auto shared = component.lock();
            if (shared)
            {
                output = shared->getOutput(name);
                if (output)
                {
                    return output;
                }
            }
        }
    }
    return nullptr;
}

mo::IPublisher* Algorithm::getOutput(const std::string& name)
{
    auto output = mo::MetaObject::getOutput(name);
    if (output)
    {
        return output;
    }
    if (!output)
    {
        for (auto& component : m_algorithm_components)
        {
            auto shared = component.lock();
            if (shared)
            {
                output = shared->getOutput(name);
                if (output)
                {
                    return output;
                }
            }
        }
    }
    return nullptr;
}

IMetaObject::PublisherVec_t Algorithm::getOutputs(const std::string& name_filter)
{
    auto outputs = mo::MetaObject::getOutputs(name_filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto comp_outputs = shared->getOutputs(name_filter);
            outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end());
        }
    }
    return outputs;
}

IMetaObject::ConstPublisherVec_t Algorithm::getOutputs(const std::string& name_filter) const
{
    auto outputs = mo::MetaObject::getOutputs(name_filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto comp_outputs = shared->getOutputs(name_filter);
            outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end());
        }
    }
    return outputs;
}

IMetaObject::PublisherVec_t Algorithm::getOutputs(const mo::TypeInfo& type_filter, const std::string& name_filter)
{
    auto outputs = mo::MetaObject::getOutputs(type_filter, name_filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto comp_outputs = shared->getOutputs(type_filter, name_filter);
            outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end());
        }
    }
    return outputs;
}

IMetaObject::ConstPublisherVec_t Algorithm::getOutputs(const mo::TypeInfo& type_filter,
                                                       const std::string& name_filter) const
{
    auto outputs = mo::MetaObject::getOutputs(type_filter, name_filter);
    for (auto& component : m_algorithm_components)
    {
        auto shared = component.lock();
        if (shared)
        {
            auto comp_outputs = shared->getOutputs(type_filter, name_filter);
            outputs.insert(outputs.end(), comp_outputs.begin(), comp_outputs.end());
        }
    }
    return outputs;
}

bool Algorithm::checkModified(const std::vector<mo::ISubscriber*>& inputs) const
{
    for (auto input : inputs)
    {
        if (input->hasNewData())
        {
            LOG_ALGO(trace, "param {} has new data", input->getName());
            return true;
        }
    }
    return false;
}

bool Algorithm::checkModifiedControlParams() const
{
    auto params = this->getParams();
    for (auto param : params)
    {
        if (param->checkFlags(mo::ParamFlags::kCONTROL))
        {
            if (auto control = static_cast<const mo::IControlParam*>(param))
            {
                if (control->getModified())
                {
                    LOG_ALGO(trace, "control param {} has been modified", param->getName());
                    return true;
                }
            }
        }
    }
    return false;
}

Algorithm::InputState Algorithm::syncTimestamp(const mo::Time& ts, const std::vector<mo::ISubscriber*>& inputs)
{
    if (m_ts && (*m_ts == ts))
    {
        // return InputState::kNOT_UPDATED;
        if (!checkModified(inputs) && !checkModifiedControlParams())
        {
            LOG_ALGO(debug, "Timestamp already processed and no inputs have been modified");
            return InputState::kNOT_UPDATED;
        }
    }
    FrameNumber fn;
    mo::Header header(ts);
    for (auto input : inputs)
    {
        auto data = input->getData(&header);
        if (data)
        {
            LOG_ALGO(trace,
                     "Got data at {} when requesting data at {} from input {}",
                     data->getHeader().timestamp,
                     ts,
                     input->getName());
        }
        else
        {
            if (input->checkFlags(mo::ParamFlags::kDESYNCED))
            {
                data = input->getData();
                if (data != nullptr)
                {
                    continue;
                }
            }
            if (input->checkFlags(mo::ParamFlags::kOPTIONAL))
            {
                // If the input isn't set and it's optional then this is ok
                if (auto input_param = input->getPublisher())
                {
                    // Input is optional and set, but couldn't get the right timestamp, error
                    if (auto buf_ptr = dynamic_cast<mo::buffer::IBuffer*>(input_param))
                    {
                        mo::OptionalTime start, end;
                        buf_ptr->getTimestampRange(start, end);
                        LOG_ALGO(debug,
                                 "Failed to get input '{}' at timestamp {} buffer range [{}, {}]",
                                 input->getTreeName(),
                                 ts,
                                 start,
                                 end);
                    }
                    else
                    {
                        LOG_ALGO(debug, "Failed to get input '{}' at timestamp {}", input->getTreeName(), ts);
                    }
                }
                else
                {
                    LOG_ALGO(trace, "Optional input not set '{}'", input->getTreeName());
                }
            }
            else
            {
                // Input is not optional
                if (auto param = input->getPublisher())
                {
                    if (param->checkFlags(mo::ParamFlags::kUNSTAMPED))
                    {
                        continue;
                    }
                    if (param->checkFlags(mo::ParamFlags::kBUFFER))
                    {
                        auto buffer = dynamic_cast<mo::buffer::IBuffer*>(param);
                        mo::OptionalTime begin, end;
                        if (buffer->getTimestampRange(begin, end))
                        {
                            if (begin && end)
                            {
                                LOG_ALGO(trace,
                                         "Failed to get input for '{}' ({}) at timestamp {}, input buffer: {} -> {}",
                                         input->getTreeName(),
                                         param->getTreeName(),
                                         ts,
                                         *begin,
                                         *end);
                            }
                            else
                            {
                                LOG_ALGO(trace,
                                         "Failed to get input for '{}' ({}) at timestamp {}, input buffer is empty",
                                         input->getTreeName(),
                                         param->getTreeName(),
                                         ts);
                            }
                        }
                    }
                    else
                    {
                        auto data = param->getData();
                        if (data)
                        {
                            LOG_ALGO(trace,
                                     "Failed to get input for '{}' ({}) at timestamp {}, input contains {}",
                                     input->getTreeName(),
                                     param->getTreeName(),
                                     ts,
                                     data->getHeader());
                        }
                        else
                        {
                            LOG_ALGO(trace,
                                     "Failed to get input for '{}' ({}) at timestamp {}, input is empty",
                                     input->getTreeName(),
                                     param->getTreeName(),
                                     ts);
                        }
                    }

                    return InputState::kNONE_VALID;
                }

                LOG_ALGO(trace, "Input not set '{}'", input->getTreeName());

                return InputState::kNONE_VALID;
            }
        }
    }
    m_ts = ts;
    m_fn = fn;
    LOG_ALGO(debug, "All inputs pass, ready to process");
    return Algorithm::InputState::kALL_VALID;
}

Algorithm::InputState Algorithm::syncFrameNumber(size_t fn, const std::vector<mo::ISubscriber*>& inputs)
{
    boost::optional<mo::Time> ts;
    std::vector<mo::OptionalTime> tss;
    mo::Header header(fn);
    for (auto input : inputs)
    {
        if (!input->isInputSet() && !input->checkFlags(mo::ParamFlags::kOPTIONAL))
        {
            MO_LOG(trace, "Input not set '{}'", input->getTreeName());
            return InputState::kNONE_VALID;
        }
        auto data = input->getData(&header);
        if (data)
        {
            tss.push_back(data->getHeader().timestamp);
        }
        else
        {
            if (input->checkFlags(mo::ParamFlags::kDESYNCED))
            {
                continue;
            }
            if (input->checkFlags(mo::ParamFlags::kOPTIONAL))
            {
                // If the input isn't set and it's optional then this is ok
                if (input->isInputSet())
                {
                    // Input is optional and set, but couldn't get the right timestamp, error
                    MO_LOG(
                        debug, "Input is set to \"{}\" but could not get at frame number {}", input->getTreeName(), fn);
                }
                else
                {
                    MO_LOG(trace, "Optional input not set '{}'", input->getTreeName());
                }
            }
            else
            {
                // Input is not optional
                if (auto param = input->getPublisher())
                {
                    if (param->checkFlags(mo::ParamFlags::kBUFFER))
                    {
                        auto buffer = dynamic_cast<mo::buffer::IBuffer*>(param);
                        uint64_t begin, end;
                        if (buffer->getFrameNumberRange(begin, end))
                        {
                            LOG_ALGO(trace,
                                     "Failed to get input for '{}' ({}) at framenumber {}, input buffer: {} -> {}",
                                     input->getTreeName(),
                                     param->getTreeName(),
                                     fn,
                                     begin,
                                     end);
                        }
                    }
                    else
                    {
                        auto data = param->getData();
                        if (data)
                        {
                            LOG_ALGO(trace,
                                     "Failed to get input for '{}' ({}) at timestamp {}, input contains {}",
                                     input->getTreeName(),
                                     param->getTreeName(),
                                     fn,
                                     data->getHeader());
                        }
                        else
                        {
                            LOG_ALGO(trace,
                                     "Failed to get input for '{}' ({}) at timestamp {}, input is empty",
                                     input->getTreeName(),
                                     param->getTreeName(),
                                     fn);
                        }
                    }
                    return InputState::kNONE_VALID;
                }
                else
                {
                    MO_LOG(trace, "Input not set for '{}'", input->getTreeName());
                }
            }
        }
    }
    if (m_fn == fn)
    {
        if (!checkModified(inputs))
        {
            return InputState::kNOT_UPDATED;
        }
    }
    if (m_ts)
    {
        if (std::count(tss.begin(), tss.end(), m_ts) == tss.size())
        {
            return InputState::kNOT_UPDATED;
        }
    }
    if (ts)
    {
        m_ts = ts;
    }
    m_fn = fn;
    return InputState::kALL_VALID;
}

void Algorithm::removeTimestampFromBuffer(const mo::Time& ts)
{
    mo::Lock_t lock(m_mtx);
    for (auto& itr : m_buffer_timing_data)
    {
        auto itr2 = std::find_if(itr.second.begin(), itr.second.end(), [ts](const SyncData& st) {
            if (st.ts)
            {
                return *st.ts == ts;
            }
            return false;
        });
        if (itr2 != itr.second.end())
        {
            itr.second.erase(itr2);
        }
    }
}

void Algorithm::removeFrameNumberFromBuffer(size_t fn)
{
    mo::Lock_t lock(m_mtx);
    for (auto& itr : m_buffer_timing_data)
    {
        auto itr2 = std::find_if(itr.second.begin(), itr.second.end(), [fn](const SyncData& st) {
            if (st.ts)
            {
                return st.fn == fn;
            }
            return false;
        });
        if (itr2 != itr.second.end())
        {
            itr.second.erase(itr2);
        }
    }
}

mo::OptionalTime Algorithm::findBufferedTimestamp()
{
    mo::Lock_t lock(m_mtx);
    if (!m_buffer_timing_data.empty())
    {
        // Search for the smallest timestamp common to all buffers
        std::vector<mo::Time> tss;
        for (const auto& itr : m_buffer_timing_data)
        {
            if (!itr.second.empty())
            {
                auto& ts = itr.second.front().ts;
                if (ts)
                {
                    tss.push_back(*ts);
                }
            }
        }
        // assuming time only moves forward, pick the largest of the min timestamps
        if (!tss.empty())
        {
            auto max_elem = std::max_element(tss.begin(), tss.end());
            bool all_found = true;
            // Check if the value is in the other timing buffers
            for (const auto& itr : m_buffer_timing_data)
            {
                bool found = false;
                for (const auto& itr2 : itr.second)
                {
                    if (itr2.ts && *(itr2.ts) == *max_elem)
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    all_found = false;
                    break;
                }
            }
            if (all_found)
            {
                return *max_elem;
            }
        }
    }
    return {};
}

mo::OptionalTime Algorithm::findDirectTimestamp(bool& buffered, const std::vector<ISubscriber*>& inputs)
{
    mo::OptionalTime ts;
    for (auto input : inputs)
    {
        auto input_param = input->getPublisher();
        if (input_param)
        {
            const auto buffered_flag = input_param->checkFlags(mo::ParamFlags::kBUFFER);
            const auto unstamped_flag = input_param->checkFlags(mo::ParamFlags::kUNSTAMPED);
            const auto modified_flag = input->hasNewData();
            if (!buffered_flag && !unstamped_flag)
            {
                if (modified_flag)
                {
                    auto headers = input_param->getAvailableHeaders();
                    if (!headers.empty())
                    {
                        auto in_ts = headers.back().timestamp;
                        if (in_ts)
                        {
                            if (!ts)
                            {
                                ts = in_ts;
                                continue;
                            }
                            ts = std::min<mo::Time>(*ts, *in_ts);
                        }
                    }
                }
            }
            else
            {
                buffered = true;
            }
        }
    }
    return ts;
}

Algorithm::InputState Algorithm::checkInputs()
{
    auto inputs = this->getInputs();
    if (inputs.empty())
    {
        return InputState::kALL_VALID;
    }
    for (auto input : inputs)
    {
        if (!input->isInputSet() && !input->checkFlags(mo::ParamFlags::kOPTIONAL))
        {
            LOG_ALGO(trace, "Required input ({}) is not connected", input->getTreeName());
            return InputState::kNONE_VALID;
        }
    }
    boost::optional<mo::Time> ts;
    FrameNumber fn;
    // First check to see if we have a sync input, if we do then use its synchronizatio method
    // TODO: Handle processing queue
    bool buffered = false;
    if (m_sync_input)
    {
        mo::Lock_t lock(m_mtx);
        auto input_param = m_sync_input->getPublisher();
        if (input_param && input_param->checkFlags(mo::ParamFlags::kBUFFER))
        {
            if (!m_ts_processing_queue.empty())
            {
                if (m_sync_method == SyncMethod::kEVERY)
                {
                    ts = m_ts_processing_queue.front();
                }
                else
                {
                    ts = m_ts_processing_queue.back();
                }
                m_ts_processing_queue.pop();
            }
        }
        else
        {
            auto header = m_sync_input->getNewestHeader();
            if (header && !header->timestamp)
            {
                fn = header->frame_number;
            }
        }
    }
    else
    {
        // first look for any direct connections, if so use the timestamp from them
        ts = findDirectTimestamp(buffered, inputs);
        if (!ts && buffered)
        {
            ts = findBufferedTimestamp();
        }
        if (!ts)
        {
            for (auto input : inputs)
            {
                if (input->isInputSet())
                {
                    auto header = input->getNewestHeader();
                    if (header)
                    {
                        auto in_fn = header->frame_number;
                        fn = std::min(fn.val, in_fn.val);
                    }
                }
            }
        }
    }
    // Synchronizing on timestamp

    if (ts)
    {
        auto ret = syncTimestamp(*ts, inputs);
        if (ret == InputState::kALL_VALID)
        {
            LOG_ALGO(trace, "Syncing to {}", *ts);
            if (buffered)
            {
                removeTimestampFromBuffer(*ts);
            }
        }
        else
        {
            LOG_ALGO(debug, "Unable to sync timestamp to {} due to {}", *ts, ct::toString(ret));
        }
        return ret;
    }
    if (fn.valid())
    {
        auto ret = syncFrameNumber(fn, inputs);
        if (ret == InputState::kALL_VALID)
        {
            LOG_ALGO(trace, "Syncing to {}", fn);
            if (buffered)
            {
                removeFrameNumberFromBuffer(fn);
            }
        }
        else
        {
            LOG_ALGO(debug, "Unable to sync frame number to {} due to {}", fn, ct::toString(ret));
        }
        return ret;
    }
    LOG_ALGO(debug, "Nothing to sync to ");
    return InputState::kNONE_VALID;
}

void Algorithm::clearModifiedInputs()
{
    auto inputs = getInputs();
    // TODO what do we do now after the refactor?
    /*for (auto input : inputs)
    {
        input->modified(false);
    }*/
}

void Algorithm::clearModifiedControlParams()
{
    auto params = this->getParams();
    for (auto param : params)
    {
        if (param->checkFlags(mo::ParamFlags::kCONTROL))
        {
            param->setModified(false);
        }
    }
}

boost::optional<mo::Time> Algorithm::getTimestamp()
{
    return m_ts;
}

void Algorithm::setSyncInput(const std::string& name)
{
    m_sync_input = getInput(name);
    if (m_sync_input)
    {
        LOG_ALGO(info, "Updating sync parameter for {} to {}", this->GetTypeName(), name);
    }
    else
    {
        LOG_ALGO(warn, "Unable to set sync input for {} to {}", this->GetTypeName(), name);
    }
}

int Algorithm::setupParamServer(const std::shared_ptr<mo::IParamServer>& mgr)
{
    int count = mo::MetaObject::setupParamServer(mgr);
    for (auto& child : m_algorithm_components)
    {
        auto shared = child.lock();
        if (shared)
        {
            count += shared->setupParamServer(mgr);
        }
    }
    return count;
}

int Algorithm::setupSignals(const std::shared_ptr<mo::RelayManager>& mgr)
{
    int cnt = IAlgorithm::setupSignals(mgr);
    for (const auto& cmp : m_algorithm_components)
    {
        auto shared = cmp.lock();
        if (shared)
        {
            cnt += shared->setupSignals(mgr);
        }
    }
    return cnt;
}

void Algorithm::setSyncMethod(SyncMethod _method)
{
    if (m_sync_method == SyncMethod::kEVERY && _method != SyncMethod::kEVERY)
    {
        // std::swap(_ts_processing_queue, std::queue<long long>());
        m_ts_processing_queue = std::queue<mo::Time>();
    }
    m_sync_method = _method;
}

void Algorithm::onParamUpdate(const mo::IParam& param, mo::Header hdr, mo::UpdateFlags fg, IAsyncStream& stream)
{
    mo::MetaObject::onParamUpdate(param, hdr, fg, stream);
    if (param.checkFlags(mo::ParamFlags::kSOURCE))
    {
        sig_update();
    }
    auto ts = hdr.timestamp;
    auto fn = hdr.frame_number;
    if (m_sync_method == SyncMethod::kEVERY)
    {
        if (&param == m_sync_input)
        {
            auto input_param = m_sync_input->getPublisher();
            mo::Lock_t lock(m_mtx);
            if (input_param && input_param->checkFlags(mo::ParamFlags::kBUFFER))
            {
                if (ts)
                {
                    if (m_ts_processing_queue.empty() || m_ts_processing_queue.back() != *ts)
                        m_ts_processing_queue.push(*ts);
                }
                else
                {
                    if (m_fn_processing_queue.empty() || m_fn_processing_queue.back() != fn)
                        m_fn_processing_queue.push(fn);
                }
            }
        }
    }
    if (fg & ct::value(UpdateFlags::kBUFFER_UPDATED))
    {
        auto in_param = dynamic_cast<const mo::ISubscriber*>(&param);
        auto buf = dynamic_cast<mo::buffer::IBuffer*>(in_param->getPublisher());

        if (in_param)
        {
            mo::Lock_t lock(m_mtx);
            auto itr = m_buffer_timing_data.find(in_param);
            if (itr == m_buffer_timing_data.end())
            {
                boost::circular_buffer<SyncData> data_buffer;
                data_buffer.set_capacity(100);
                if (buf)
                {
                    auto capacity = buf->getFrameBufferCapacity();
                    if (capacity)
                    {
                        data_buffer.set_capacity(*capacity);
                    }
                }
                auto result = m_buffer_timing_data.insert(std::make_pair(in_param, std::move(data_buffer)));
                if (result.second)
                {
                    itr = result.first;
                }
            }
            SyncData data(ts, fn);
            if (itr->second.empty() || itr->second.back() != data)
            {
                itr->second.push_back(std::move(data));
            }
        }
    }
}

void Algorithm::setStream(const mo::IAsyncStreamPtr_t& ctx)
{
    mo::MetaObject::setStream(ctx);
    for (auto& child : m_algorithm_components)
    {
        auto shared = child.lock();
        if (shared)
        {
            shared->setStream(ctx);
        }
    }
}

void Algorithm::postSerializeInit()
{
    auto stream = getStream();
    for (auto& child : m_algorithm_components)
    {
        auto shared = child.lock();
        if (shared)
        {
            shared->setStream(stream);
            shared->postSerializeInit();
        }
    }
}

void Algorithm::Init(bool first_init)
{
    if (!first_init)
    {
        for (auto& cmp : m_algorithm_components)
        {
            auto shared = cmp.lock();
            if (shared)
            {
                shared->Init(first_init);
                this->addComponent(cmp);
            }
        }
    }
    mo::MetaObject::Init(first_init);
}

void Algorithm::addComponent(const rcc::weak_ptr<IAlgorithm>& component)
{
    auto ptr = component.lock();
    if (ptr == nullptr)
    {
        return;
    }
    if (!aq::contains(m_algorithm_components, component))
    {
        m_algorithm_components.push_back(component);
    }
    mo::ISlot* slot =
        this->getSlot("param_updated", mo::TypeInfo::create<void(IParam*, Header, UpdateFlags, IAsyncStream&)>());
    if (slot)
    {
        auto params = ptr->getParams();
        for (auto param : params)
        {
            param->registerUpdateNotifier(*slot);
        }
    }
    else
    {
        m_logger->warn("Unable to get param_updated slot from self");
    }
    auto manager = getRelayManager();
    if (manager)
    {
        ptr->setupSignals(manager);
    }
    sig_componentAdded(ptr);
}

std::vector<rcc::weak_ptr<IAlgorithm>> Algorithm::getComponents() const
{
    return m_algorithm_components;
}

void Algorithm::Serialize(ISimpleSerializer* pSerializer)
{
    mo::MetaObject::Serialize(pSerializer);
    SERIALIZE(m_algorithm_components);
}

Algorithm::SyncData::SyncData(const boost::optional<mo::Time>& ts_, mo::FrameNumber fn_)
    : ts(ts_)
    , fn(fn_)
{
}

bool Algorithm::SyncData::operator==(const SyncData& other)
{
    if (ts && other.ts)
        return *ts == *other.ts;
    return fn == other.fn;
}

bool Algorithm::SyncData::operator!=(const SyncData& other)
{
    return !(*this == other);
}

void Algorithm::setLogger(const std::shared_ptr<spdlog::logger>& logger)
{
    m_logger = logger;
}

max_stars_repo_name: dtmoodie/Acquilla

max_issues_repo_name: dtmoodie/Acquilla

max_forks_repo_name: dtmoodie/Acquilla


text:
// https://www.boost.org/doc/libs/1_67_0/doc/html/atomic/usage_examples.html#boost_atomic.usage_examples.example_ringbuffer

#include <boost/atomic.hpp>

template <typename T, size_t Size>
class ringbuffer
{
  public:
    ringbuffer() : head_(0), tail_(0) {}

    bool push(const T &value)
    {
        size_t head = head_.load(boost::memory_order_relaxed);
        size_t next_head = next(head);
        if (next_head == tail_.load(boost::memory_order_acquire))
            return false;
        ring_[head] = value;
        head_.store(next_head, boost::memory_order_release);
        return true;
    }
    bool pop(T &value)
    {
        size_t tail = tail_.load(boost::memory_order_relaxed);
        if (tail == head_.load(boost::memory_order_acquire))
            return false;
        value = ring_[tail];
        tail_.store(next(tail), boost::memory_order_release);
        return true;
    }

  private:
    size_t next(size_t current)
    {
        return (current + 1) % Size;
    }
    T ring_[Size];
    boost::atomic<size_t> head_, tail_;
};

int main()
{
    ringbuffer<int, 32> r;

    // try to insert an element
    if (r.push(42))
    { /* succeeded */
    }
    else
    { /* buffer full */
    }

    // try to retrieve an element
    int value;
    if (r.pop(value))
    { /* succeeded */
    }
    else
    { /* buffer empty */
    }
}


text:
/***********************************************************************************************************************
*  OpenStudio(R), Copyright (c) 2008-2019, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
*  following conditions are met:
*
*  (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
*  disclaimer.
*
*  (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
*  disclaimer in the documentation and/or other materials provided with the distribution.
*
*  (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
*  derived from this software without specific prior written permission from the respective party.
*
*  (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
*  may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
*  written permission from Alliance for Sustainable Energy, LLC.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
*  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
*  STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
*  STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
*  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/

#ifndef SHAREDGUICOMPONENTS_FIELDMETHODTYPEDEFS_HPP
#define SHAREDGUICOMPONENTS_FIELDMETHODTYPEDEFS_HPP

#include "../model/Model.hpp"
#include "../model/Model_Impl.hpp"
#include "../model/ModelObject.hpp"
#include "../model/ModelObject_Impl.hpp"

#include <boost/optional.hpp>

#include <vector>

namespace openstudio {

typedef std::function<bool ()> BoolGetter;
typedef std::function<double ()> DoubleGetter;
typedef std::function<int ()> IntGetter;
typedef std::function<std::string ()> StringGetter;
typedef std::function<unsigned ()> UnsignedGetter;
typedef std::function<model::ModelObject ()> ModelObjectGetter;

typedef std::function<boost::optional<double> ()> OptionalDoubleGetter;
typedef std::function<boost::optional<int> ()> OptionalIntGetter;
typedef std::function<boost::optional<std::string> ()> OptionalStringGetter;
typedef std::function<boost::optional<std::string> (bool)> OptionalStringGetterBoolArg;
typedef std::function<boost::optional<unsigned> ()> OptionalUnsignedGetter;
typedef std::function<boost::optional<model::ModelObject> ()> OptionalModelObjectGetter;

typedef std::function<void(bool)> BoolSetter;
typedef std::function<bool(bool)> BoolSetterBoolReturn;
typedef std::function<bool(double)> DoubleSetter;
typedef std::function<void (double)> DoubleSetterVoidReturn;
typedef std::function<bool (int)> IntSetter;
typedef std::function<bool(std::string)> StringSetter;
typedef std::function<void(std::string)> StringSetterVoidReturn;
typedef std::function<boost::optional<std::string>(const std::string &)> StringSetterOptionalStringReturn;
typedef std::function<bool (unsigned)> UnsignedSetter;
typedef std::function<bool (const model::ModelObject &)> ModelObjectSetter;

typedef std::function<void ()> NoFailAction;
typedef std::function<bool ()> BasicQuery;

}

#endif // SHAREDGUICOMPONENTS_FIELDMETHODTYPEDEFS_HPP

max_stars_repo_name: hellok-coder/OS-Testing

max_issues_repo_name: hellok-coder/OS-Testing

max_forks_repo_name: hellok-coder/OS-Testing