text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "filter.h"

#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem/fstream.hpp>
#include <boost/functional/hash.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "lo.pb.h"

#include "bc/index.h"
#include "db/read-only-driver.h"
#include "db/statement-driver.h"
#include "filter/spec_loader.h"
#include "lo/layout_loader.h"

namespace flint {
namespace filter {

namespace {

class TimeUnitLoader : db::StatementDriver {
public:
	// Note that db is for read only.
	explicit TimeUnitLoader(sqlite3 *db)
		: db::StatementDriver(db, "SELECT * from time_unit")
	{
	}

	bool Load(std::string *time_unit) {
		int e = sqlite3_step(stmt());
		if (e == SQLITE_DONE) {
			// nothing to do
			sqlite3_reset(stmt());
			return true;
		}
		if (e == SQLITE_ROW) {
			const unsigned char *name = sqlite3_column_text(stmt(), 0);
			*time_unit = std::string(reinterpret_cast<const char *>(name));
			sqlite3_reset(stmt());
			return true;
		}
		std::cerr << "failed to step statement: " << e << std::endl;
		return false;
	}
};

class Spec {
public:
	Spec(const Spec &) = delete;
	Spec &operator=(const Spec &) = delete;

	Spec() = default;

	void AddSpec(const boost::uuids::uuid &u, const char *name) {
		m_[u].insert(name);
	}

	bool Contains(const boost::uuids::uuid &id, const std::string &name) const {
		auto it = m_.find(id);
		if (it == m_.end()) return false;
		return it->second.find(name) != it->second.end();
	}

private:
	std::unordered_map<boost::uuids::uuid,
					   std::unordered_set<std::string>,
					   boost::hash<boost::uuids::uuid> > m_;
};

class Layout {
public:
	Layout(const Layout &) = delete;
	Layout &operator=(const Layout &) = delete;

	Layout() = default;

	void AddTrack(std::unique_ptr<lo::Track> &&track) {
		tv_.push_back(std::move(track));
	}

	void AddSector(std::unique_ptr<lo::Sector> &&sector) {
		sv_.push_back(std::move(sector));
	}

	void AddData(std::unique_ptr<lo::Data> &&data) {
		dv_.push_back(std::move(data));
	}

	int Fill(const std::string &time_unit, const Spec *spec, std::vector<std::unique_ptr<lo::Column> > *columns) const {
		std::unique_ptr<lo::Column> c(new lo::Column);

		char us0[boost::uuids::uuid::static_size()] = {0};
		c->set_position(0);
		c->set_col(1);
		c->set_row(1);
		c->set_uuid(us0, boost::uuids::uuid::static_size());
		c->set_id(0); // no such value, let's use 0 as a fallback
		c->set_name("time");
		c->set_type(lo::T);
		c->set_unit(time_unit);
		columns->push_back(std::move(c));

		int si = 0;
		int di = 0;
		int pos = kOffsetBase;
		for (const auto &tp : tv_) {
			int nos = tp->nos();
			int nod = tp->nod();
			int sie = si + nos;
			int dib = di;
			int die = di + nod;

			while (si < sie) {
				const auto &sp = sv_.at(si++);
				boost::uuids::uuid su;
				std::memcpy(&su, sp->id().data(), su.size());
				di = dib;
				while (di < die) {
					const auto &dp = dv_.at(di++);
					if (spec->Contains(su, dp->name())) {
						c.reset(new lo::Column);
						c->set_position(pos);
						c->set_col(dp->col());
						c->set_row(dp->row());
						c->set_uuid(sp->id().data(), boost::uuids::uuid::static_size());
						c->set_id(dp->id());
						c->set_name(dp->name());
						c->set_type(dp->type());
						c->set_unit(dp->unit());
						if (sp->has_label()) c->set_label(sp->label());
						columns->push_back(std::move(c));
					}
					pos += dp->col() * dp->row();
				}
			}
		}
		return pos;
	}

private:
	typedef std::vector<std::unique_ptr<lo::Track> > TrackVector;
	typedef std::vector<std::unique_ptr<lo::Sector> > SectorVector;
	typedef std::vector<std::unique_ptr<lo::Data> > DataVector;

	TrackVector tv_;
	SectorVector sv_;
	DataVector dv_;
};

}

bool Create(sqlite3 *db,
			const boost::filesystem::path &spec_file,
			const boost::filesystem::path &layout_file,
			const boost::filesystem::path &output_file)
{
	std::string time_unit;
	{
		TimeUnitLoader loader(db);
		if (!loader.Load(&time_unit)) return false;
	}

	std::unique_ptr<Spec> spec(new Spec);
	// load spec
	{
		std::unique_ptr<SpecLoader> loader(new SpecLoader(spec_file));
		if (!loader->Load(spec.get())) return false;
	}

	// load layout
	std::unique_ptr<Layout> layout(new Layout);
	{
		std::unique_ptr<LayoutLoader> loader(new LayoutLoader(layout_file));
		if (!loader->Load(layout.get())) return false;
	}

	std::vector<std::unique_ptr<lo::Column> > columns;
	int size = layout->Fill(time_unit, spec.get(), &columns);
	std::unique_ptr<lo::Header> header(new lo::Header);
	header->set_size(size);

	boost::filesystem::ofstream ofs(output_file, std::ios::out|std::ios::binary);
	if (!ofs.is_open()) {
		std::cerr << "could not open output file: " << output_file << std::endl;
		return false;
	}
	if (!PackToOstream(*header, &ofs)) {
		std::cerr << "failed to pack Header" << std::endl;
		return false;
	}
	for (const auto &cp : columns) {
		if (!PackToOstream(*cp, &ofs)) {
			std::cerr << "failed to pack Column" << std::endl;
			return false;
		}
	}
	ofs.close();
	return true;
}

}
}

max_stars_repo_name: Abhisheknishant/Flint

max_issues_repo_name: Abhisheknishant/Flint

max_forks_repo_name: Abhisheknishant/Flint


text:
// Copyright Vladimir Prus 2004.
// Copyright (c) 2005-2014 Hartmut Kaiser
// 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)

// Make HPX inspect tool happy: hpxinspect:nounnamed

#ifndef HPX_EXPORT_PLUGIN_VP_2004_08_25
#define HPX_EXPORT_PLUGIN_VP_2004_08_25

#include <hpx/config.hpp>
#include <hpx/util/detail/pp/cat.hpp>
#include <hpx/util/detail/pp/stringize.hpp>
#include <hpx/util/plugin/abstract_factory.hpp>
#include <hpx/util/plugin/concrete_factory.hpp>
#include <hpx/util/plugin/config.hpp>

#include <boost/algorithm/string/case_conv.hpp>
#include <boost/any.hpp>

#include <map>
#include <string>
#include <utility>

///////////////////////////////////////////////////////////////////////////////
#define HPX_PLUGIN_NAME_2(name1, name2)                                       \
    HPX_PP_CAT(name1, HPX_PP_CAT(_, name2))                                   \
    /**/

#define HPX_PLUGIN_NAME_3(name, base, cname)                                  \
    HPX_PP_CAT(cname, HPX_PP_CAT(_,                                           \
        HPX_PP_CAT(name, HPX_PP_CAT(_, base))))                               \
    /**/

///////////////////////////////////////////////////////////////////////////////
#define HPX_PLUGIN_LIST_NAME_(prefix, name, base)                             \
    HPX_PP_CAT(                                                               \
        HPX_PP_CAT(prefix, _exported_plugins_list_),                          \
            HPX_PLUGIN_NAME_2(name, base))                                    \
    /**/

#define HPX_PLUGIN_EXPORTER_NAME_(prefix, name, base, cname)                  \
    HPX_PP_CAT(                                                               \
        HPX_PP_CAT(prefix, _plugin_exporter_),                                \
            HPX_PLUGIN_NAME_3(name, base, cname))                             \
    /**/

#define HPX_PLUGIN_EXPORTER_INSTANCE_NAME_(prefix, name, base, cname)         \
    HPX_PP_CAT(                                                               \
        HPX_PP_CAT(prefix, _plugin_exporter_instance_),                       \
            HPX_PLUGIN_NAME_3(name, base, cname))                             \
    /**/

#define HPX_PLUGIN_FORCE_LOAD_NAME_(prefix, name, base)                       \
    HPX_PP_CAT(                                                               \
        HPX_PP_CAT(prefix, _exported_plugins_force_load_),                    \
            HPX_PLUGIN_NAME_2(name, base))                                    \
    /**/

///////////////////////////////////////////////////////////////////////////////
#define HPX_PLUGIN_LIST_NAME(name, base)                                      \
    HPX_PLUGIN_LIST_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX, name, base)              \
    /**/

#define HPX_PLUGIN_EXPORTER_NAME(name, base, cname)                           \
    HPX_PLUGIN_EXPORTER_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX, name, base, cname)   \
    /**/

#define HPX_PLUGIN_EXPORTER_INSTANCE_NAME(name, base, cname)                  \
    HPX_PLUGIN_EXPORTER_INSTANCE_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX,             \
        name, base, cname)                                                    \
    /**/

#define HPX_PLUGIN_FORCE_LOAD_NAME(name, base)                                \
    HPX_PLUGIN_FORCE_LOAD_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX, name, base)        \
    /**/

///////////////////////////////////////////////////////////////////////////////
#define HPX_PLUGIN_LIST_NAME_DYNAMIC(name, base)                              \
    HPX_PLUGIN_LIST_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX_DYNAMIC, name, base),     \
    /**/

#define HPX_PLUGIN_EXPORTER_NAME_DYNAMIC(name, base, cname)                   \
    HPX_PLUGIN_EXPORTER_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX_DYNAMIC, name, base,  \
        cname)                                                                \
    /**/

#define HPX_PLUGIN_EXPORTER_INSTANCE_NAME_DYNAMIC(name, base, cname)          \
    HPX_PLUGIN_EXPORTER_INSTANCE_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX_DYNAMIC,     \
        name, base, cname)                                                    \
    /**/

#define HPX_PLUGIN_FORCE_LOAD_NAME_DYNAMIC(name, base)                        \
    HPX_PLUGIN_FORCE_LOAD_NAME_(HPX_PLUGIN_SYMBOLS_PREFIX_DYNAMIC, name, base)\
    /**/

///////////////////////////////////////////////////////////////////////////////
#define HPX_PLUGIN_EXPORT_(prefix, name, BaseType, ActualType, actualname,    \
        classname)                                                            \
    extern "C" HPX_PLUGIN_EXPORT_API std::map<std::string, boost::any> *      \
        HPX_PLUGIN_API HPX_PLUGIN_LIST_NAME_(prefix, name, classname)();      \
                                                                              \
    namespace {                                                               \
        struct HPX_PLUGIN_EXPORTER_NAME_(prefix, name, actualname, classname) \
        {                                                                     \
            HPX_PLUGIN_EXPORTER_NAME_(prefix, name, actualname, classname)()  \
            {                                                                 \
                static hpx::util::plugin::concrete_factory<                   \
                    BaseType, ActualType > cf;                                \
                hpx::util::plugin::abstract_factory<BaseType>* w = &cf;       \
                std::string actname(HPX_PP_STRINGIZE(actualname));            \
                boost::algorithm::to_lower(actname);                          \
                HPX_PLUGIN_LIST_NAME_(prefix, name, classname)()->insert(     \
                    std::make_pair(actname, w));                              \
            }                                                                 \
        } HPX_PLUGIN_EXPORTER_INSTANCE_NAME_(prefix, name, actualname,        \
            classname);                                                       \
    }                                                                         \
    /**/

#define HPX_PLUGIN_EXPORT(name, BaseType, ActualType, actualname, classname)  \
    HPX_PLUGIN_EXPORT_(HPX_PLUGIN_SYMBOLS_PREFIX, name, BaseType, ActualType, \
        actualname, classname)                                                \
    /**/

#define HPX_PLUGIN_EXPORT_DYNAMIC(name, BaseType, ActualType, actualname,     \
        classname)                                                            \
    HPX_PLUGIN_EXPORT_(HPX_PLUGIN_SYMBOLS_PREFIX_DYNAMIC, name, BaseType,     \
        ActualType, actualname, classname)                                    \
    /**/

///////////////////////////////////////////////////////////////////////////////
#define HPX_PLUGIN_EXPORT_LIST_(prefix, name, classname)                      \
    extern "C" HPX_PLUGIN_EXPORT_API std::map<std::string, boost::any> *      \
        HPX_PLUGIN_API HPX_PLUGIN_LIST_NAME_(prefix, name, classname)()       \
    {                                                                         \
        static std::map<std::string, boost::any> r;                           \
        return &r;                                                            \
    }                                                                         \
    extern "C" HPX_PLUGIN_EXPORT_API                                          \
        void HPX_PLUGIN_FORCE_LOAD_NAME_(prefix, name, classname)()           \
    {                                                                         \
        HPX_PLUGIN_LIST_NAME_(prefix, name, classname)();                     \
    }                                                                         \
    /**/

#define HPX_PLUGIN_EXPORT_LIST(name, classname)                               \
    HPX_PLUGIN_EXPORT_LIST_(HPX_PLUGIN_SYMBOLS_PREFIX, name, classname)       \
    /**/

#define HPX_PLUGIN_EXPORT_LIST_DYNAMIC(name, classname)                       \
    HPX_PLUGIN_EXPORT_LIST_(HPX_PLUGIN_SYMBOLS_PREFIX_DYNAMIC, name,          \
        classname)                                                            \
    /**/

#endif

ext: hpp


text:
#ifndef SERIALIZATION_FORMAT_TEXT_OUTPUT_HPP
#define SERIALIZATION_FORMAT_TEXT_OUTPUT_HPP

#include "blub/core/globals.hpp"

#include <boost/archive/text_oarchive.hpp>

namespace blub
{
namespace serialization
{
namespace format
{
namespace text
{

typedef boost::archive::text_oarchive output;

}
}
}
}

#endif // SERIALIZATION_FORMAT_TEXT_OUTPUT_HPP


text:
// Copyright 2016 Las Venturas Playground. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

#include <fstream>
#include <iostream>
#include <mutex>
#include <queue>
#include <sstream>
#include <stdexcept>
#include <stdint.h>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/program_options.hpp>
#include <boost/thread.hpp>

#if defined(WIN32)
#include <Windows.h>
#elif defined(LINUX)
#include <sys/time.h>
#include <time.h>
#endif

using boost::asio::deadline_timer;
using boost::asio::ip::udp;

namespace {

// Verbosity setting for the indexer.
enum class Verbosity {
  QUIET,
  DEFAULT,
  VERBOSE,
  DEBUG
};

// Options for the indexer. Sets default values. May be overridden by using the command line flags
// listed next to each option. {@see ParseCommandLine}
struct IndexOptions {
  IndexOptions()
      : retries(2 /* retries */),
        threads(boost::thread::hardware_concurrency()),
        timeout(3 /* seconds */),
        user_agent("SAMPIndexer/1.0 (+https://sa-mp.nl/)") {}

  ~IndexOptions() = default;

  std::string logstash;     // --logstash
  uint32_t retries;         // --retries
  std::string server_list;  // --server-list
  uint32_t threads;         // --threads, -t
  uint32_t timeout;         // --timeout
  std::string user_agent;   // --user-agent

  Verbosity verbosity = Verbosity::DEBUG;  // -v, -quiet
};

// Definition for a server entry, which exists of an IP address and a port number.
using ServerEntry = std::pair<std::string, uint16_t>;

// Provides the ability to hash a ServerEntry value, for the retry set.
struct ServerEntryHasher {
 public:
  std::size_t operator()(const ServerEntry& entry) const {
    return std::hash<std::string>()(entry.first) ^
           std::hash<uint16_t>()(entry.second);
  }
};

// Structure containing the information that can be queried from the server.
struct ServerInfo {
  explicit ServerInfo(const ServerEntry& server)
      : server(server) {}

  ServerEntry server;

  bool has_password = false;

  uint16_t players = 0;
  uint16_t max_players = 0;

  std::string hostname;
  std::string gamemode;
  std::string map;
};

// -------------------------------------------------------------------------------------------------

IndexOptions options;

// Queue and vector used for processing the identified ServerEntries.
std::queue<ServerEntry> server_queue;
std::unordered_map<ServerEntry, uint32_t, ServerEntryHasher> retry_map;

std::vector<ServerEntry> failure_vector;
std::vector<ServerInfo> result_vector;

// Mutexes that protect the aforementioned queue and vector, as well as verbose output.
std::mutex server_queue_mutex, result_mutex, verbose_output_mutex;

// -------------------------------------------------------------------------------------------------

std::string ToDisplay(const ServerEntry& server) {
  return server.first + ":" + std::to_string(server.second);
}

// -------------------------------------------------------------------------------------------------

#if defined(WIN32)

// Difference between January 1st, 1601 and January 1st, 1970 in nanoseconds, to convert from
// the Windows file time epoch to the UNIX timestamp epoch.
const uint64_t kEpochDelta = 116444736000000000ull;

double monotonicallyIncreasingTime() {
  static uint64_t begin_time = 0ull;
  static bool set_begin_time = false;

  FILETIME tm;

  // Use precise (<1us) timing for Windows 8 and above, normal (~1ms) on other versions.
#if defined(NTDDI_WIN8) && NTDDI_VERSION >= NTDDI_WIN8
  GetSystemTimePreciseAsFileTime(&tm);
#else
  GetSystemTimeAsFileTime(&tm);
#endif

  uint64_t time = 0;
  time |= tm.dwHighDateTime;
  time <<= 32;
  time |= tm.dwLowDateTime;
  time -= kEpochDelta;

  if (!set_begin_time) {
    set_begin_time = true;
    begin_time = time;
  }

  return static_cast<double>(time - begin_time) / 10000.0;
}

#elif defined(LINUX)

double monotonicallyIncreasingTime() {
  static uint64_t begin_time = 0ull;
  static bool set_begin_time = false;

  struct timespec ts;
  clock_gettime(CLOCK_MONOTONIC, &ts);

  uint64_t time = static_cast<uint64_t>(ts.tv_sec) * 1000000000u + static_cast<uint64_t>(ts.tv_nsec);

  if (!set_begin_time) {
    set_begin_time = true;
    begin_time = time;
  }

  return static_cast<double>(time - begin_time) / 1000000.0;
}

#endif

// -------------------------------------------------------------------------------------------------

// Parses the command line arguments (|argc| and |argv|) in to the IndexOptions (|options|).
bool ParseCommandLine(IndexOptions* options, int argc, const char** argv) {
  namespace po = boost::program_options;

  uint32_t verbosity = 0;

  po::options_description indexer("SA-MP Indexer");
  indexer.add_options()
      ("logstash", po::value<std::string>(), "Path to the logstash UNIX pipe (instead of STDOUT)")
      ("quiet,q", "Block all output")
      ("retries", po::value<uint32_t>(), "Number of retries for servers that do not respond")
      ("server-list", po::value<std::string>()->required(), "URL of the server list to use")
      ("threads,t", po::value<uint32_t>(), "Number of threads to use")
      ("timeout", po::value<uint32_t>(), "Request timeout for an individual server, in seconds")
      ("user-agent", po::value<std::string>(), "The user agent to use in the request")
      (",v", po::value<uint32_t>(&verbosity)->implicit_value(0), "Enable verbose output");

  po::variables_map variables;
  try {
    po::store(po::parse_command_line(argc, argv, indexer), variables);
    po::notify(variables);

  } catch (po::error& error) {
    std::cerr << "Unable to parse the command line: " << error.what() << std::endl << std::endl;
    std::cerr << indexer << std::endl;
    return false;
  }

  if (variables.count("logstash"))
    options->logstash = variables["logstash"].as<std::string>();

  if (variables.count("retries"))
    options->retries = variables["retries"].as<uint32_t>();
  if (variables.count("server-list"))
    options->server_list = variables["server-list"].as<std::string>();
  if (variables.count("threads"))
    options->threads = variables["threads"].as<uint32_t>();
  if (variables.count("user-agent"))
    options->user_agent = variables["user-agent"].as<std::string>();

  options->verbosity = Verbosity::DEFAULT;

  if (verbosity == 1)
    options->verbosity = Verbosity::VERBOSE;
  else if (verbosity >= 2)
    options->verbosity = Verbosity::DEBUG;
  else if (variables.count("quiet"))
    options->verbosity = Verbosity::QUIET;

  return true;
}

// Fetches and parses a list of servers from the specified |options.server_list|. Synchronous.
// Supports HTTP (non-HTTPS) URLs, as well as file paths relative to the CHDIR.
bool FetchServerList(std::queue<ServerEntry>* servers) {
  const std::string& server_list = options.server_list;

  std::vector<std::string> raw_servers;

  if (server_list.substr(0, 7) == "http://") {
    size_t path_separator = server_list.find_first_of('/', 7 /* after the http:// prefix */);
    if (path_separator == std::string::npos) {
      std::cerr << "Invalid hostname given: " << server_list;
      return false;
    }

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

    boost::asio::io_service io_service;

    std::string hostname = server_list.substr(7, path_separator - 7);
    std::string path = server_list.substr(path_separator);

    try {
      // (1) Resolve the |hostname| to the IP address associated with it.
      tcp::resolver resolver(io_service);
      tcp::resolver::query query(hostname, "http");
      tcp::resolver::iterator endpoints = resolver.resolve(query);

      // (2) Establish a connection to one of the |endpoints|.
      tcp::socket socket(io_service);
      boost::asio::connect(socket, endpoints);

      boost::asio::streambuf request;
      boost::asio::streambuf response;

      // (3) Build the request headers for the server list.
      std::ostream request_stream(&request);

      request_stream << "GET " << path << " HTTP/1.0\r\n";
      request_stream << "Host: " << hostname << "\r\n";
      request_stream << "User-Agent: " << options.user_agent << "\r\n";
      request_stream << "Connection: close\r\n\r\n";

      boost::asio::write(socket, request);

      std::string http_version;
      uint32_t http_status_code;

      // (4) Read the response received from the server and make that it's OK.
      boost::asio::read_until(socket, response, "\r\n");

      std::istream response_stream(&response);

      response_stream >> http_version;
      response_stream >> http_status_code;

      if (!response_stream || http_version.substr(0, 5) != "HTTP/" || http_status_code != 200) {
        if (options.verbosity != Verbosity::QUIET) {
          std::cerr << "Received an invalid HTTP response (" << http_version << "; "
                    << http_status_code << ")" << std::endl;
        }

        return false;
      }

      boost::system::error_code error;

      // (5) Make sure that we've read the entire response in the |response| stream.
      while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) {}

      if (error != boost::asio::error::eof)
        throw boost::system::system_error(error);

      // (6) Skip over the headers included in the |response|.
      for (std::string header; std::getline(response_stream, header) && header != "\r";) {}

      // (7) Interpret the rest of the lines as server definitions.
      for (std::string line; std::getline(response_stream, line);)
        raw_servers.push_back(line);

      socket.close();
    }
    catch (std::exception& e) {
      if (options.verbosity != Verbosity::QUIET) {
        std::cerr << "Unable to fetch the server list: " << e.what() << std::endl;
      }

      return false;
    }
  } else {
    std::ifstream file(server_list, std::ifstream::in);
    if (file.is_open()) {
      for (std::string line; std::getline(file, line);)
        raw_servers.push_back(line);

      file.close();
    }
  }

  if (!raw_servers.size()) {
    if (options.verbosity != Verbosity::QUIET) {
      std::cerr << "Unable to load the list of servers from: " << server_list;
    }

    return false;
  }

  for (const std::string& input_line : raw_servers) {
    std::string line = boost::trim_copy(input_line);

    size_t colon_position = line.find_first_of(':');
    if (colon_position == std::string::npos) {
      if (options.verbosity != Verbosity::QUIET) {
        std::cerr << "Unable to parse server entry: " << line;
      }

      continue;
    }

    uint16_t port_number;
    try {
      port_number = boost::lexical_cast<uint16_t>(line.substr(colon_position + 1));
    } catch (boost::bad_lexical_cast const&) {
      if (options.verbosity != Verbosity::QUIET) {
        std::cerr << "Invalid port number for server entry: " << line;
      }

      continue;
    }

    servers->emplace(line.substr(0, colon_position), port_number);
  }

  return true;
}

// -------------------------------------------------------------------------------------------------

// http://www.boost.org/doc/libs/1_52_0/doc/html/boost_asio/example/timeouts/blocking_udp_client.cpp
class TimedSocket {
 public:
  TimedSocket(boost::asio::io_service& io_service, udp::endpoint& endpoint)
      : io_service_(io_service),
        socket_(io_service),
        deadline_(io_service) {
    deadline_.expires_at(boost::posix_time::pos_infin);
    check_deadline();

    socket_.open(endpoint.protocol());
  }

  std::size_t receive_from(const boost::asio::mutable_buffer& buffer,
                           udp::endpoint& endpoint,
                           boost::system::error_code& ec) {
    deadline_.expires_from_now(boost::posix_time::seconds(options.timeout));

    ec = boost::asio::error::would_block;
    std::size_t length = 0;

    socket_.async_receive_from(boost::asio::buffer(buffer), endpoint,
                               boost::bind(&TimedSocket::handle_receive, _1, _2, &ec, &length));

    do {
      io_service_.run_one();

    } while (ec == boost::asio::error::would_block);

    return length;
  }

  udp::socket& raw() { return socket_; }

 private:
  void check_deadline() {
    if (deadline_.expires_at() <= deadline_timer::traits_type::now()) {
      socket_.cancel();
      deadline_.expires_at(boost::posix_time::pos_infin);
    }

    deadline_.async_wait(boost::bind(&TimedSocket::check_deadline, this));
  }

  static void handle_receive(const boost::system::error_code& ec,
                             std::size_t length,
                             boost::system::error_code* out_ec,
                             std::size_t* out_length) {
    *out_ec = ec;
    *out_length = length;
  }

  boost::asio::io_service& io_service_;
  udp::socket socket_;
  deadline_timer deadline_;
};

// -------------------------------------------------------------------------------------------------

template <typename T>
bool ReadValue(T* storage, const boost::array<char, 256>& buffer, const size_t& bytes, size_t* offset) {
  throw std::runtime_error("Invalid ReadValue() overload reached.");
}

template <>
bool ReadValue(bool* storage, const boost::array<char, 256>& buffer, const size_t& bytes, size_t* offset) {
  if (*offset + sizeof(bool) > bytes)
    return false;

  *storage = !!buffer[*offset];
  *offset += sizeof(bool);

  return true;
}

template <>
bool ReadValue(uint16_t* storage, const boost::array<char, 256>& buffer, const size_t& bytes, size_t* offset) {
  if (*offset + sizeof(uint16_t) > bytes)
    return false;

  *storage = static_cast<unsigned char>(buffer[*offset]) |
             static_cast<unsigned char>(buffer[*offset + 1]) << 8;

  *offset += sizeof(uint16_t);

  return true;
}

template <>
bool ReadValue(std::string* storage, const boost::array<char, 256>& buffer, const size_t& bytes, size_t* offset) {
  if (*offset + sizeof(uint32_t) > bytes)
    return false;

  uint32_t length = static_cast<unsigned char>(buffer[*offset]) |
                    static_cast<unsigned char>(buffer[*offset + 1]) << 8 |
                    static_cast<unsigned char>(buffer[*offset + 2]) << 16 |
                    static_cast<unsigned char>(buffer[*offset + 3]) << 24;

  *offset += sizeof(uint32_t);

  if (*offset + length > bytes)
    return false;

  *storage = std::string(&buffer[*offset], length);
  *offset += length;

  return true;
}

// -------------------------------------------------------------------------------------------------

enum class QueryResult {
  SUCCESS,

  TIMEOUT,
  INVALID_DATA
};

// Queries the server defined in |info|. Writes the results to |info| as well.
QueryResult QueryServer(ServerInfo* info, boost::asio::io_service& io_service) {
  unsigned char packet[11];

  boost::asio::ip::address_v4 address = boost::asio::ip::address_v4::from_string(info->server.first);
  unsigned short port = info->server.second;

  // Compile the information in |packet| necessary to query the server.
  {
    packet[0] = 'S';
    packet[1] = 'A';
    packet[2] = 'M';
    packet[3] = 'P';

    auto address_bytes = address.to_bytes();

    packet[4] = address_bytes[0];
    packet[5] = address_bytes[1];
    packet[6] = address_bytes[2];
    packet[7] = address_bytes[3];

    packet[8] = info->server.second & 0xFF;
    packet[9] = (info->server.second >> 8) & 0xFF;

    packet[10] = 'i';  // information packet identifier
  }

  try {
    udp::endpoint endpoint;
    endpoint.address(address);
    endpoint.port(port);

    boost::system::error_code error;

    TimedSocket socket(io_service, endpoint);

    // Send the |packet| to the |endpoint| over the opened |socket|.
    if (socket.raw().send_to(boost::asio::buffer(packet), endpoint) != sizeof(packet))
      return QueryResult::TIMEOUT;

    boost::array<char, 256> receive_buffer;

    size_t bytes = socket.receive_from(boost::asio::buffer(receive_buffer), endpoint, error);

    if (error == boost::asio::error::operation_not_supported ||
        error == boost::asio::error::operation_aborted)
      return QueryResult::TIMEOUT;  // timed out

    size_t offset = 11;  // the |packet| that we sent

    if (bytes <= offset)
      throw std::runtime_error("Received packet size too short");

    if (ReadValue(&info->has_password, receive_buffer, bytes, &offset) &&
        ReadValue(&info->players, receive_buffer, bytes, &offset) &&
        ReadValue(&info->max_players, receive_buffer, bytes, &offset) &&
        ReadValue(&info->hostname, receive_buffer, bytes, &offset) &&
        ReadValue(&info->gamemode, receive_buffer, bytes, &offset) &&
        ReadValue(&info->map, receive_buffer, bytes, &offset))
      return QueryResult::SUCCESS;

    return QueryResult::INVALID_DATA;

  } catch (std::exception& e) {
    if (options.verbosity == Verbosity::VERBOSE || options.verbosity == Verbosity::DEBUG) {
      std::lock_guard<std::mutex> guard(verbose_output_mutex);
      std::cerr << "[" << ToDisplay(info->server) << "] ERROR: " << e.what() << std::endl;
    }
    return QueryResult::INVALID_DATA;
  }

  return QueryResult::SUCCESS;
}

// Thread responsible for querying servers. It will pick a ServerEntry from the vector of parsed
// server entries, query it, and then write the results to the vector of queried servers. Both
// vectors are protected by mutexes
void QueryThread() {
  boost::asio::io_service io_service;
  ServerEntry server;

  while (true) {
    {
      std::lock_guard<std::mutex> guard(server_queue_mutex);
      if (server_queue.empty())
        return;

      server = server_queue.front();
      server_queue.pop();
    }

    ServerInfo info(server);

    double begin = 0;

    if (options.verbosity == Verbosity::DEBUG) {
      begin = monotonicallyIncreasingTime();

      std::lock_guard<std::mutex> guard(verbose_output_mutex);
      std::cout << "[" << ToDisplay(server) << "] Querying the server..." << std::endl;
    }

    QueryResult result = QueryServer(&info, io_service);

    if (options.verbosity == Verbosity::DEBUG) {
      long int delta = lround(monotonicallyIncreasingTime() - begin);

      std::lock_guard<std::mutex> guard(verbose_output_mutex);
      std::cout << "[" << ToDisplay(server) << "] Finished the query in "
                << std::setprecision(2) << delta << "ms" << std::endl;
    }

    // Retry when they time out. Sometimes this helps.
    if (result == QueryResult::TIMEOUT) {
      if (!retry_map.count(server))
        retry_map[server] = 0;

      ++retry_map[server]; // 1...

      if (retry_map[server] < options.retries) {
        std::lock_guard<std::mutex> guard(server_queue_mutex);
        server_queue.push(server);

        continue;
      }
    }

    // Otherwise write the server to either the success or failure set.
    {
      std::lock_guard<std::mutex> guard(result_mutex);
      if (result == QueryResult::SUCCESS)
        result_vector.push_back(std::move(info));
      else
        failure_vector.push_back(server);
    }
  }
}

}  // namespace

// -------------------------------------------------------------------------------------------------

int main(int argc, const char** argv) {
  if (!ParseCommandLine(&options, argc, argv))
    return 1;  // unable to parse the command line

  if (options.verbosity == Verbosity::VERBOSE)
    std::cout << "Parsing servers from '" << options.server_list << "'..." << std::endl;

  if (!FetchServerList(&server_queue))
    return 1;  // unable to fetch the list of servers

  if (options.verbosity == Verbosity::VERBOSE)
    std::cout << "Found " << server_queue.size() << " servers..." << std::endl;

  const size_t server_count = server_queue.size();
  if (!server_count)
    return 1;  // unable to find servers to index

  double begin = monotonicallyIncreasingTime();

  // Now query all servers in the list in parallel, using |options.threads| threads.
  {
    boost::thread_group query_threads;
    for (size_t i = 0; i < options.threads; ++i)
      query_threads.create_thread(QueryThread);

    query_threads.join_all();
  }

  long int delta = lround(monotonicallyIncreasingTime() - begin);

  // Output the total time taken for the query sequence when verbose output is enabled.
  if (options.verbosity != Verbosity::QUIET) {
    std::cout << "Queried " << server_count << " servers in " << std::setprecision(2) << delta << "ms." << std::endl;
    std::cout << "Successful: " << result_vector.size() << ". Failed: " << failure_vector.size() << std::endl;

    uint32_t player_count = 0;
    uint32_t player_slot_count = 0;

    for (const ServerInfo& info : result_vector) {
      player_count += info.players;
      player_slot_count += info.max_players;
    }

    std::cout << "There are " << player_count << " players online, with a capacity of " << player_slot_count << "."
              << std::endl << std::endl;
  }

  if (!options.logstash.empty()) {
#if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
    boost::asio::io_service logstash_io_service;
    boost::asio::local::stream_protocol::socket logstash_socket(logstash_io_service);

    try {
      logstash_socket.connect(boost::asio::local::datagram_protocol::endpoint(options.logstash));

      for (const ServerInfo& info : result_vector) {
        std::stringstream stream;
        stream << "{";
        {
          stream << "\"type\":\"query\",";
          stream << "\"server\":\"" << info.server.first << ":" << info.server.second << "\",";
          stream << "\"online\":1,";
          stream << "\"players\":" << info.players << ",";
          stream << "\"max_players\":" << info.max_players;
        }
        stream << "}";

        boost::asio::write(logstash_socket, boost::asio::buffer(stream.str()));
      }

      for (const ServerEntry& server : failure_vector) {
        std::stringstream stream;
        stream << "{";
        {
          stream << "\"type\": \"query\",";
          stream << "\"server\": \"" << server.first << ":" << server.second << "\",";
          stream << "\"online\": 0,";
          stream << "\"players\": 0,";
          stream << "\"max_players\": 0";
        }
        stream << "}";

        boost::asio::write(logstash_socket, boost::asio::buffer(stream.str()));
      }

    } catch (std::exception& e) {
      if (options.verbosity != Verbosity::QUIET)
        std::cerr << "LOGSTASH ERROR: " << e.what() << std::endl;
    }
#endif
  }

  if (options.verbosity == Verbosity::DEBUG) {
    for (const ServerInfo& info : result_vector) {
      std::cout << ToDisplay(info.server) << " -- " << info.players << "/" << info.max_players << " -- ";
      std::cout << info.hostname << " (" << info.gamemode << ")" << std::endl;
    }
  }

  return 0;  // no errors \o/
}

ext: cpp

max_stars_repo_name: LVPlayground/samp-indexer

max_issues_repo_name: LVPlayground/samp-indexer

max_forks_repo_name: LVPlayground/samp-indexer


text:
#include "threaded_estop_reader.h"

#include <boost/bind/bind.hpp>
#include <thread>
#include <utility>

#include "software/logger/logger.h"

ThreadedEstopReader::ThreadedEstopReader(std::unique_ptr<UartCommunication> uart_reader,
                                         unsigned int startup_time_ms)
    : estop_state(EstopState::STOP),
      timer(io_service, boost::posix_time::milliseconds(startup_time_ms)),
      uart_reader(std::move(uart_reader))
{
    estop_thread = std::thread(boost::bind(&ThreadedEstopReader::continousRead, this));
}

void ThreadedEstopReader::continousRead()
{
    timer.async_wait(
        boost::bind(&ThreadedEstopReader::tick, this, boost::asio::placeholders::error));
    io_service.run();
}

bool ThreadedEstopReader::isEstopPlay()
{
    return estop_state == EstopState::PLAY;
}

void ThreadedEstopReader::tick(const boost::system::error_code& error)
{
    if (in_destructor)
    {
        timer.cancel();
    }
    else
    {
        std::vector<unsigned char> estop_msg;
        try
        {
            uart_reader->flushSerialPort(uart_reader->flush_receive);
            estop_msg = uart_reader->serialRead(ESTOP_MESSAGE_SIZE_BYTES);
        }
        catch (const std::exception& e)
        {
            LOG(FATAL)
                << "crashing system and timing out robots as we have lost connection to ESTOP source : "
                << e.what();
        }

        EstopState new_state;

        switch (estop_msg.at(0))
        {
            case ESTOP_PLAY_MSG:
                new_state                    = EstopState::PLAY;
                num_consecutive_status_error = 0;
                break;
            case ESTOP_STOP_MSG:
                new_state                    = EstopState::STOP;
                num_consecutive_status_error = 0;
                break;
            default:
                new_state = EstopState::STATUS_ERROR;
                LOG(WARNING) << "read unexpected estop message";
                num_consecutive_status_error++;
                break;
        }

        if (new_state != estop_state)
        {
            LOG(INFO) << "ESTOP changed from " << estop_state << " to " << new_state;
            estop_state = new_state;
        }

        CHECK(num_consecutive_status_error <= MAXIMUM_CONSECUTIVE_STATUS_ERROR)
            << "ESTOP Consecutive Unexpected messages";

        boost::posix_time::milliseconds next_interval(INTERVAL_BETWEEN_READS_MS);

        // Reschedule the timer for interval seconds in the future:
        timer.expires_from_now(next_interval);
        // Posts the timer event
        timer.async_wait(boost::bind(&ThreadedEstopReader::tick, this,
                                     boost::asio::placeholders::error));
    }
}

ThreadedEstopReader::~ThreadedEstopReader()
{
    in_destructor = true;

    // We must wait for the thread to stop, as if we destroy it while it's still
    // running we will segfault
    estop_thread.join();
}


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2017-2017.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/move for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#ifndef BOOST_MOVE_ALGO_UNIQUE_HPP
#define BOOST_MOVE_ALGO_UNIQUE_HPP

#include <boost/move/detail/config_begin.hpp>
#include <boost/move/utility_core.hpp>

namespace boost {
namespace movelib {

//! Requires: The comparison function shall be an equivalence relation.
//! The type of *first shall satisfy the MoveAssignable requirements
//!
//! Effects: For a nonempty range, eliminates all but the first element
//! from every consecutive group
//!   of equivalent elements referred to by the iterator i in the range [first +
//!   1, last) for which the following conditions hold: pred(*(i - 1), *i) !=
//!   false.
//!
//! Returns: The end of the resulting range.
//!
//! Complexity: For nonempty ranges, exactly (last - first) - 1
//! applications of the corresponding predicate.
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator unique(ForwardIterator first, ForwardIterator last,
                       BinaryPredicate pred) {
  if (first != last) {
    ForwardIterator next(first);
    ++next;
    for (; next != last; ++next, ++first) {
      if (pred(*first, *next)) { // Find first equal element
        while (++next != last)
          if (!pred(*first, *next))
            *++first = ::boost::move(*next);
        break;
      }
    }
    ++first;
  }
  return first;
}

} // namespace movelib
} // namespace boost

#include <boost/move/detail/config_end.hpp>

#endif //#define BOOST_MOVE_ALGO_UNIQUE_HPP

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text: #include <boost/log/attributes/current_process_name.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_ObserverPhaseSpaceDimensionDiscretization.hpp
//! \author Alex Robinson
//! \brief  Observer phase space dimension discretization base class decl.
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_OBSERVER_PHASE_SPACE_DIMENSION_DISCRETIZATION_HPP
#define MONTE_CARLO_OBSERVER_PHASE_SPACE_DIMENSION_DISCRETIZATION_HPP

// Std Lib Includes
#include <iostream>

// Boost includes
#include <boost/any.hpp>
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/shared_ptr.hpp>

// FRENSIE Includes
#include "MonteCarlo_ObserverPhaseSpaceDimension.hpp"
#include "MonteCarlo_ObserverParticleStateWrapper.hpp"
#include "MonteCarlo_ParticleHistoryObserver.hpp"
#include "Utility_ExplicitSerializationTemplateInstantiationMacros.hpp"
#include "Utility_SerializationHelpers.hpp"
#include "Utility_Tuple.hpp"
#include "Utility_Vector.hpp"

namespace MonteCarlo{

//! The observer phase space dimension discretization base class
class ObserverPhaseSpaceDimensionDiscretization
{

public:

  //! Typedef for bin index array
  typedef std::vector<size_t> BinIndexArray;

  //! Typedef for bin index and weight pair
  typedef std::pair<size_t,double> BinIndexWeightPair;

  //! Typedef for bin index and weight pair array
  typedef std::vector<BinIndexWeightPair> BinIndexWeightPairArray;

  //! Constructor
  ObserverPhaseSpaceDimensionDiscretization()
  { /* ... */ }

  //! Destructor
  virtual ~ObserverPhaseSpaceDimensionDiscretization()
  { /* ... */ }

  //! Return the dimension that has been discretized
  virtual ObserverPhaseSpaceDimension getDimension() const = 0;

  //! Return the dimension name that has been discretized
  virtual std::string getDimensionName() const = 0;

  //! Return the number of bins in the discretization
  virtual size_t getNumberOfBins() const = 0;

  //! Check if the value is contained in the discretization
  virtual bool isValueInDiscretization(
       const ObserverParticleStateWrapper& particle_state_wrapper ) const = 0;

  //! Check if the value is contained in the discretization
  virtual bool isValueInDiscretization(
                                     const boost::any& any_value ) const = 0;

  //! Check if the range intersects the discretization
  virtual bool doesRangeIntersectDiscretization(
       const ObserverParticleStateWrapper& particle_state_wrapper ) const = 0;

  //! Calculate the index of bins that the value falls in
  virtual void calculateBinIndicesOfValue(
                   const ObserverParticleStateWrapper& particle_state_wrapper,
                   BinIndexArray& bin_indices ) const = 0;

  //! Calculate the index of bins that the value falls in
  virtual void calculateBinIndicesOfValue(
                  const ObserverParticleStateWrapper& particle_state_wrapper,
                  BinIndexWeightPairArray& bin_indices_and_weights ) const = 0;

  //! Calculate the index of bins that the value falls in
  virtual void calculateBinIndicesOfValue(
                             const boost::any& any_value,
                             BinIndexArray& bin_indices ) const = 0;

  //! Calculate the index of bins that the value range falls in
  virtual void calculateBinIndicesOfRange(
                  const ObserverParticleStateWrapper& particle_state_wrapper,
                  BinIndexWeightPairArray& bin_indices_and_weights ) const = 0;

  //! Print the boundaries of a bin
  virtual void printBoundariesOfBin( std::ostream& os,
				     const size_t bin_index ) const = 0;

  //! Print the dimension discretization
  virtual void print( std::ostream& os ) const = 0;

private:

  // Serialize the discretization
  template<typename Archive>
  void serialize( Archive& ar, const unsigned version )
  { /* ... */ }

  // Declare the boost serialization access object as a friend
  friend class boost::serialization::access;
};

} // end MonteCarlo namespace

BOOST_SERIALIZATION_ASSUME_ABSTRACT_CLASS( ObserverPhaseSpaceDimensionDiscretization, MonteCarlo );
BOOST_SERIALIZATION_CLASS_VERSION( ObserverPhaseSpaceDimensionDiscretization, MonteCarlo, 0 );
EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, ObserverPhaseSpaceDimensionDiscretization );

#endif // end MONTE_CARLO_OBSERVER_PHASE_SPACE_DIMENSION_DISCRETIZATION_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_ObserverPhaseSpaceDimensionDiscretization.hpp
//---------------------------------------------------------------------------//


text:
// Copyright 2020 Your Name <your_email>

#ifndef INCLUDE_HEADER_HPP_
#define INCLUDE_HEADER_HPP_
#include <iostream>
#include "../third-party/PicoSHA2/picosha2.h"
#include <string>
#include <chrono>
#include <thread>
#include <csignal>
#include <nlohmann/json.hpp>
#include <mutex>
#include <vector>
#include <unistd.h>
#include <fstream>
#include <sstream>

#include <boost/log/core.hpp>
#include <boost/log/expressions.hpp>
#include <boost/log/trivial.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include <boost/log/sources/logger.hpp>
#include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/console.hpp>
#include <boost/log/utility/setup/common_attributes.hpp>
#include <boost/log/sources/severity_logger.hpp>
#include <boost/log/sources/record_ostream.hpp>
#include <boost/smart_ptr/shared_ptr.hpp>
#include <boost/smart_ptr/make_shared_object.hpp>
#include <boost/log/support/date_time.hpp>
#include <boost/log/attributes/timer.hpp>
#include <boost/log/attributes/named_scope.hpp>

using time_point = std::chrono::system_clock::time_point;
using high_clock = std::chrono::high_resolution_clock;
using std::cout;
using std::endl;
using string = std::string;
using json = nlohmann::json;
using boost::shared_ptr;

namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
namespace attrs = boost::log::attributes;
namespace expr = boost::log::expressions;

static const char Hex_End[] = "0000";

class Hasher {
 public:
  Hasher(int argc, char *argv[]);

  ~Hasher();

  static void signal_catch(int signum){
    write_to_json_file("hash_hex_log.json");
    sleep(1);
    std::cout << "\nProgram aborted with code " << --signum << "\n";
    exit(signum);
  }

  static void write_to_json_file(const string& file_name){
    std::ofstream output_file;
    std::ifstream input_file;
    output_file.open(file_name);
    input_file.open(file_name);
    json out_json;
    if (input_file.peek() != EOF)
      input_file >> out_json;
    for (auto & right_hash : right_hashs) {
      out_json["values"].push_back(right_hash);
    }
    output_file << out_json.dump(4);
    output_file.close();
  }

  void start(const bool& key);

  void sort_hash(string& hash);

  void do_hashing(const bool& key);

 private:
  std::mutex mutex;
  int number_threads;
  int duration;
  string src_str;
  string hash_hex_str;
  std::vector<std::thread> threads;
  static std::vector<json> right_hashs;
  src::severity_logger< boost::log::trivial::severity_level > slg;
};
#endif // INCLUDE_HEADER_HPP_


text:
#pragma once

#include <Core/RaCore.hpp>

#include <Core/Containers/VectorArray.hpp>
#include <Core/Geometry/OpenMesh.hpp>
#include <Core/Geometry/TriangleMesh.hpp>
#include <Core/Types.hpp>
#include <Core/Utils/Index.hpp>
#include <Core/Utils/StdOptional.hpp>

#include <OpenMesh/Core/Mesh/PolyMesh_ArrayKernelT.hh>
#include <OpenMesh/Core/Mesh/Traits.hh>
#include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh>
#include <OpenMesh/Core/Utils/Property.hh>
#include <OpenMesh/Core/Utils/PropertyManager.hh>

#include <Eigen/Core>
#include <Eigen/Geometry>

#include <set>

namespace Ra {
namespace Core {
namespace Geometry {
using namespace Utils; // log, AttribXXX

/**
 * Define the Traits to be used by OpenMesh for TopologicalMesh.
 */
struct TopologicalMeshTraits : OpenMesh::DefaultTraits {
    using Point  = Ra::Core::Vector3;
    using Normal = Ra::Core::Vector3;

    VertexAttributes( OpenMesh::Attributes::Status | OpenMesh::Attributes::Normal );
    FaceAttributes( OpenMesh::Attributes::Status | OpenMesh::Attributes::Normal );
    EdgeAttributes( OpenMesh::Attributes::Status );
    // Add  OpenMesh::Attributes::PrevHalfedge for efficiency ?
    HalfedgeAttributes( OpenMesh::Attributes::Status | OpenMesh::Attributes::Normal );
};

/**
 * This class represents a mesh with topological information on the
 * vertex graph, using a half-edge representation.
 *
 * This integration is inspired by:
 * https://gist.github.com/Unril/03fa353d0461ed6bd41d
 *
 * \todo rename methods to respect Radium guideline (get/set/is, camelCase)
 * \todo private inheritance from OpenMesh, and import relevant methods.
 */
class RA_CORE_API TopologicalMesh : public OpenMesh::PolyMesh_ArrayKernelT<TopologicalMeshTraits>
{
  private:
    using base = OpenMesh::PolyMesh_ArrayKernelT<TopologicalMeshTraits>;
    using base::PolyMesh_ArrayKernelT;
    using Vector3 = Ra::Core::Vector3;
    using Index   = Ra::Core::Utils::Index;
    class Wedge;
    class WedgeCollection;

  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW

    class WedgeData;
    using WedgeIndex = Ra::Core::Utils::Index;

    /**
     * Construct an empty topological mesh, only initialize mandatory properties.
     */
    explicit TopologicalMesh();

    /**
     * \brief Convenience constructor
     * \see TopologicalMesh( const Ra::Core::Geometry::TriangleMesh&, NonManifoldFaceCommand)
     */
    template <typename MeshIndex>
    explicit TopologicalMesh( [[deprecated(
        "Use MultiIndexedGeometry instead" )]] const Ra::Core::Geometry::IndexedGeometry<MeshIndex>&
                                  mesh );

    /**
     * \brief Convenience constructor
     * \see TopologicalMesh( const Ra::Core::Geometry::TriangleMesh&, NonManifoldFaceCommand)
     * @todo, when MultiIndexedGeometry will be operational, will this replace the above ?
     */
    explicit TopologicalMesh(
        const Ra::Core::Geometry::MultiIndexedGeometry& mesh,
        const Ra::Core::Geometry::MultiIndexedGeometry::LayerKeyType& layerKey );

    /**
     * Construct a topological mesh from a triangle mesh.
     * This operation merges vertex with same position, but keeps vertex
     * attributes on halfedges, so that TriangleMesh vertices with the same 3D
     * position are represented only once in the topological mesh.
     * \note This is a costly operation.
     *
     * \tparam NonManifoldFaceCommand Command executed when non-manifold faces are
     * found. API and default implementation:
     * \snippet Core/Geometry/TopologicalMesh.cpp Default command implementation
     *
     */
    template <typename MeshIndex, typename NonManifoldFaceCommand>
    explicit TopologicalMesh( [[deprecated( "Use MultiIndexedGeometry instead" )]] const Ra::Core::
                                  Geometry::IndexedGeometry<MeshIndex>& mesh,
                              NonManifoldFaceCommand command );

    /**
     * Construct a topological mesh from a triangle mesh.
     * This operation merges vertex with same position, but keeps vertex
     * attributes on halfedges, so that TriangleMesh vertices with the same 3D
     * position are represented only once in the topological mesh.
     * \note This is a costly operation.
     *
     * \tparam NonManifoldFaceCommand Command executed when non-manifold faces are
     * found. API and default implementation:
     * \snippet Core/Geometry/TopologicalMesh.cpp Default command implementation
     * @todo, when MultiIndexedGeometry will be operational, will this replace the above ?
     *
     */
    template <typename NonManifoldFaceCommand>
    explicit TopologicalMesh(
        const Ra::Core::Geometry::MultiIndexedGeometry& mesh,
        const Ra::Core::Geometry::MultiIndexedGeometry::LayerKeyType& layerKey,
        NonManifoldFaceCommand command );

    inline void
    initWithWedge( const Ra::Core::Geometry::MultiIndexedGeometry& mesh,
                   const Ra::Core::Geometry::MultiIndexedGeometry::LayerKeyType& layerKey );

    template <typename NonManifoldFaceCommand>
    void initWithWedge( const Ra::Core::Geometry::MultiIndexedGeometry& mesh,
                        const Ra::Core::Geometry::MultiIndexedGeometry::LayerKeyType& layerKey,
                        NonManifoldFaceCommand command );
    /**
     * Return a triangleMesh from the topological mesh.
     * \note This is a costly operation.
     * \warning It uses the attributes defined on halfedges. Do not work well if attribs are defined
     * on wedges (initWithWedge), in this case use toTriangleMeshFromWedges()
     */
    TriangleMesh toTriangleMesh();

    /**
     * Return a triangleMesh from the topological mesh.
     * \note This is a costly operation.
     * \warning It uses the attributes defined on wedges
     */
    PolyMesh toPolyMesh();

    LineMesh toLineMesh();

    /**
     * Update triangle mesh data, assuming the mesh and this topo mesh has the
     * same topology.
     */
    void updateTriangleMesh( Ra::Core::Geometry::MultiIndexedGeometry& mesh );
    void updateTriangleMeshNormals( Ra::Core::Geometry::MultiIndexedGeometry& mesh );
    void updateTriangleMeshNormals( AttribArrayGeometry::NormalAttribHandle::Container& normals );

    void update( const Ra::Core::Geometry::MultiIndexedGeometry& mesh );
    void updateNormals( const Ra::Core::Geometry::MultiIndexedGeometry& mesh );
    void updatePositions( const Ra::Core::Geometry::MultiIndexedGeometry& mesh );
    void updatePositions( const AttribArrayGeometry::PointAttribHandle::Container& vertices );
    // import other version of halfedge_handle method
    using base::halfedge_handle;

    /**
     * Return the half-edge associated with a given vertex and face.
     * \note Asserts if vh is not a member of fh.
     */
    inline HalfedgeHandle halfedge_handle( VertexHandle vh, FaceHandle fh ) const;

    /// Import Base definition of normal and set normal.
    ///@{
    using base::normal;
    using base::set_normal;
    ///@}

    /**
     * Set the normal n to all the wedges that share to vh.
     * If you work with vertex normals, please call this function on all vertex
     * handles before convertion with toTriangleMesh.
     */
    inline void propagate_normal_to_wedges( VertexHandle vh );

    /**
     * Return a handle to the halfedge property storing vertices indices within
     * the TriangleMesh *this has been built on.
     */
    inline const OpenMesh::HPropHandleT<Index>& getInputTriangleMeshIndexPropHandle() const;

    /**
     * Return a handle to the halfedge property storing vertices indices within
     * the TriangleMesh returned by toTriangleMesh().
     * \note This property is valid only after toTriangleMesh() has been called.
     */
    inline const OpenMesh::HPropHandleT<Index>& getOutputTriangleMeshIndexPropHandle() const;

    /**
     * \name Dealing with normals
     * Utils to deal with normals when modifying the mesh topology.
     */
    ///@{

    void updateWedgeNormals();
    ///@}

    /// update wedge's position to correspond to current point position, which might not be the case
    /// if point(handle) = something; has been used.
    void copyPointsPositionToWedges();
    /**
     * \name Topological operations
     */
    ///@{
    /**
     * Apply a 2-4 edge split.
     * \param eh The handle to the edge to split.
     * \param f The interpolation factor to place the new point on the edge.
     *          Must be in [0,1].
     * \return True if the edge has been split, false otherwise.
     * \note Only applies on edges between 2 triangles, and if \a f is in [0,1].
     * \note Mesh attributes are linearly interpolated on the newly created
     * halfedge.
     * \note f=0 correspond to halfedge_handle( eh, 0 ) (i.e. first vertex of
     * the edge)
     */
    bool splitEdge( TopologicalMesh::EdgeHandle eh, Scalar f );

    /**
     * Halfedge collapes \a he.
     * vo=from_vertex_handle(he) is deleted.
     * After collapse vo incoming halfedges points to vh = to_vertex_handle(he).
     * Wedge indices are updated to reflect the change in topology.
     * For detailed topological modifications see \ref develmeshes.
     * \param he halfedge's hangle to collapse.
     */
    void collapse( HalfedgeHandle, bool = false );
    [[deprecated( "use collapse() instead." )]] void
    collapseWedge( TopologicalMesh::HalfedgeHandle he, bool keepFromVertex = false );
    ///@}

    /**
     * Return the set of WedgeIndex incident to a given Vertex \a vh.
     * only valid non deleted wedges are present in the set.
     */
    inline std::set<WedgeIndex> getVertexWedges( OpenMesh::VertexHandle vh ) const;

    /**
     * get the wedge index associated with an halfedge
     */
    inline WedgeIndex getWedgeIndex( OpenMesh::HalfedgeHandle heh ) const;

    /**
     * Access to wedge data.
     * \param idx must be valid and correspond to a non delete wedge index.
     */
    inline const WedgeData& getWedgeData( const WedgeIndex& idx ) const;
    template <typename T>
    [[deprecated( "use getWedgeAttrib() instead." )]] const T&
    getWedgeData( const WedgeIndex& idx, const std::string& name ) const;
    template <typename T>
    const T& getWedgeAttrib( const WedgeIndex& idx, const std::string& name ) const;

    /**
     * Return the wedge refcount, for debug purpose.
     */
    inline unsigned int getWedgeRefCount( const WedgeIndex& idx ) const;

    /** set WedgeData \a wd to the wedge with index \a widx.
     * All halfedge that point to widx will get the new values.
     * \param widx index of the wedge
     * \param wd data to set to wedge that correspond to widx
     */
    inline void setWedgeData( WedgeIndex widx, const WedgeData& wd );

    /**
     * Change the WedgeData associated for \a idx, for attrib \a name to \a value.
     * The data is changed for all halfedges referencing this wedge.
     * \return true if the wedge is set, false if nothing set, i.e. if name is not an attrib of
     * type T.
     */
    template <typename T>
    [[deprecated( "use setWedgeAttrib() instead." )]] inline bool
    setWedgeData( const WedgeIndex& idx, const std::string& name, const T& value );

    template <typename T>
    inline bool setWedgeAttrib( const WedgeIndex& idx, const std::string& name, const T& value );

    /** return a WedgeData with all attrib initialized to default values */
    inline WedgeData newWedgeData() const { return m_wedges.newWedgeData(); }
    /** return a WedgeData with position (and vertex handle) initialized from the value of he's to
     * vertex. */
    inline WedgeData newWedgeData( HalfedgeHandle he ) const {
        return m_wedges.newWedgeData( to_vertex_handle( he ), point( to_vertex_handle( he ) ) );
    }

    /**
     * Replace the wedge data associated with an halfedge.
     * The old wedge is "deleted". If wedge data correspond to an already
     * present wedge, it's index is used.
     */
    inline void replaceWedge( OpenMesh::HalfedgeHandle he, const WedgeData& wd );

    template <typename T>
    inline int addWedgeAttrib( const std::string& name, T value = {} ) {
        return m_wedges.addAttrib<T>( name, value );
    }

    /**
     * Replace the wedge index associated with an halfedge.
     * The old wedge is "deleted". The new wedge reference count is incremented.
     */
    inline void replaceWedgeIndex( OpenMesh::HalfedgeHandle he, const WedgeIndex& widx );

    /**
     * call mergeEquelWedges( vh ) for every vertices of the mesh.
     * \see void mergeEqualWedges( OpenMesh::VertexHandle vh );
     */
    inline void mergeEqualWedges();

    /**
     * Merge (make same index) wegdes with the same data around \a vh
     * \param vh vertex handle to process
     */
    inline void mergeEqualWedges( OpenMesh::VertexHandle vh );

    /// Remove deleted element from the mesh, including wedges.
    void garbage_collection();
    inline void clean() {
        base::clean();
        m_wedges.clean();
    }

    inline const std::vector<std::string>& getVec4AttribNames() const;
    inline const std::vector<std::string>& getVec3AttribNames() const;
    inline const std::vector<std::string>& getVec2AttribNames() const;
    inline const std::vector<std::string>& getFloatAttribNames() const;

    /// true if more than one wedge arount vertex \a vh, false if only one wedge
    inline bool isFeatureVertex( const VertexHandle& vh ) const;

    /// true if at least one of edge's vertex as two different wedge arount the
    /// edge.
    /// false if the two vertices have the same wedge for both face aside the edge.
    inline bool isFeatureEdge( const EdgeHandle& eh ) const;

    inline const OpenMesh::HPropHandleT<WedgeIndex>& getWedgeIndexPph() const;

    void delete_face( FaceHandle _fh, bool _delete_isolated_vertices = true );

    /**
     * is the vertex a "bow tie" vertex ?
     * \note Alias for OpenMesh::is_manifold
     */
    bool isManifold( VertexHandle vh ) const;

    /// Check if evrything looks right in the data structure
    /// \return true if ok, false if ko.
    bool checkIntegrity() const;

    void triangulate();

    /**
     * Inner class WedgeData represents the actual data per wedge, including position.
     *
     * At any time m_position as to be equal to the wedge's vertex point.
     * All wedges have the same set of attributes.
     * Access and management is delegated to TopologicalMesh and WedgeCollection
     */
    class WedgeData
    {
      public:
        EIGEN_MAKE_ALIGNED_OPERATOR_NEW

        explicit WedgeData() = default;
        inline bool operator==( const WedgeData& lhs ) const;
        inline bool operator!=( const WedgeData& lhs ) const;
        inline bool operator<( const WedgeData& lhs ) const;

        template <typename T>
        inline VectorArray<T>& getAttribArray();
        template <typename T>
        inline const VectorArray<T>& getAttribArray() const;
        friend Wedge;

        //        Index m_inputTriangleMeshIndex;
        //        Index m_outputTriangleMeshIndex;
        VertexHandle m_vertexHandle;
        Vector3 m_position {};
        VectorArray<Scalar> m_floatAttrib;
        VectorArray<Vector2> m_vector2Attrib;
        VectorArray<Vector3> m_vector3Attrib;
        VectorArray<Vector4> m_vector4Attrib;

      private:
        // return 1 : equals, 2: strict less, 3: strict greater
        template <typename T>
        static int compareVector( const T& a, const T& b );
    };

  private:
    // base on openmesh version
    void collapse_edge( HalfedgeHandle, bool );
    void collapse_loop( HalfedgeHandle );

    /**
     * This private class manage wedge data and refcount, to maintain deleted status
     *
     * \internal We need to export this class to make it accessible in .inl
     */
    class RA_CORE_API Wedge
    {
      public:
        EIGEN_MAKE_ALIGNED_OPERATOR_NEW

        explicit Wedge() {}
        explicit Wedge( const WedgeData& wd ) : m_wedgeData {wd}, m_refCount {1} {};
        const WedgeData& getWedgeData() const { return m_wedgeData; }
        void setWedgeData( const WedgeData& wedgeData ) { m_wedgeData = wedgeData; }
        void setWedgeData( WedgeData&& wedgeData ) { m_wedgeData = std::move( wedgeData ); }
        void incrementRefCount() { ++m_refCount; }
        void decrementRefCount() {
            if ( m_refCount ) --m_refCount;
        }
        /// comparison ignore refCount
        bool operator==( const Wedge& lhs ) const { return m_wedgeData == lhs.m_wedgeData; }

        bool isDeleted() const { return m_refCount == 0; }
        unsigned int getRefCount() const { return m_refCount; }

        friend WedgeCollection;
        friend TopologicalMesh;

      private:
        WedgeData& getWedgeData() { return m_wedgeData; }

        WedgeData m_wedgeData {};
        unsigned int m_refCount {0};
    };

    /**
     * This private class manage the wedge collection.
     * Most of the data members are public so that the enclosing class can
     * easily manage the data.
     *
     * \internal We need to export this class to make it accessible in .inl
     */
    class RA_CORE_API WedgeCollection
    {
      public:
        EIGEN_MAKE_ALIGNED_OPERATOR_NEW

        /**
         * Add wd to the wedge collection, and return the index.
         * If a wedge with same data is already present, it's index is returned,
         * otherwise a new wedge is added to the wedges collection.
         * \param wd Data to insert.
         * \return the index of the inserted (or found) wedge.
         */
        WedgeIndex add( const WedgeData& wd );

        /**
         * Delete the wedge \a idx from the collection.
         * These deletion actually just remove one reference from an halfedge
         * to the wedge data. If the wedge is still referenced by other
         * halfedges, it will not be removed during garbageCollection.
         */
        inline void del( const WedgeIndex& idx );
        WedgeIndex newReference( const WedgeIndex& idx );

        /**
         * Return the wedge data associated with \a idx
         */

        /// Return the wedge (not the data) for in class manipulation.
        /// client code should use getWedgeData only.
        inline const Wedge& getWedge( const WedgeIndex& idx ) const;

        inline const WedgeData& getWedgeData( const WedgeIndex& idx ) const;
        template <typename T>
        inline const T& getWedgeData( const WedgeIndex& idx, const std::string& name ) const;
        template <typename T>
        inline T& getWedgeData( const WedgeIndex& idx, int attribIndex );
        template <typename T>
        inline const T& getWedgeAttrib( const WedgeIndex& idx, const std::string& name ) const;
        template <typename T>
        inline T& getWedgeAttrib( const WedgeIndex& idx, int attribIndex );

        unsigned int getWedgeRefCount( const WedgeIndex& idx ) const;

        /// \see TopologicalMesh::setWedgeData
        inline void setWedgeData( const WedgeIndex& idx, const WedgeData& wd );

        /// change WedgeData member name to value.
        /// wd is moidified accordingly.
        /// \return false if name is not of type T
        /// \retrun true on sucess
        template <typename T>
        inline bool
        setWedgeAttrib( TopologicalMesh::WedgeData& wd, const std::string& name, const T& value );
        template <typename T>
        inline bool
        setWedgeAttrib( const WedgeIndex& idx, const std::string& name, const T& value );
        template <typename T>
        inline void setWedgeAttrib( const TopologicalMesh::WedgeIndex& idx,
                                    const int& attribIndex,
                                    const T& value );

        template <typename T>
        inline int getWedgeAttribIndex( const std::string& name );

        inline bool setWedgePosition( const WedgeIndex& idx, const Vector3& value );

        /// management

        template <typename T>
        inline const std::vector<std::string>& getNameArray() const;

        // name is supposed to be unique within all attribs
        // not checks are performed
        // return the index of the the newly added attrib.
        template <typename T>
        int addAttribName( const std::string& name );

        // add attrib to all wedges with default value value
        template <typename T>
        int addAttrib( const std::string& name, const T& value = {} );

        /// return the offset ot apply to each wedgeindex so that
        /// after garbageCollection all indices are valid and coherent.
        std::vector<int> computeCleanupOffset() const;
        /// \todo removeDuplicateWedge
        /// merge wedges with same data
        /// return old->new index correspondance to update wedgeIndexPph
        /// inline void removeDuplicateWedge

        inline size_t size() const { return m_data.size(); }

        /// remove unreferenced wedge, halfedges need to be reindexed.
        inline void garbageCollection();

        inline void clean();

        // return a new wedgeData with uninit values.
        inline WedgeData newWedgeData() const;
        inline WedgeData newWedgeData( TopologicalMesh::VertexHandle vh,
                                       TopologicalMesh::Point p ) const;

        ///\ todo       private:
        /// attrib names associated to vertex/wedges, getted from CoreMesh, if any,
        std::vector<std::string> m_floatAttribNames;
        std::vector<std::string> m_vector2AttribNames;
        std::vector<std::string> m_vector3AttribNames;
        std::vector<std::string> m_vector4AttribNames;

        /// attrib handle from the CoreMesh given at construction, if any.
        /// used by TopologicalMesh::update()
        std::vector<AttribHandle<Scalar>> m_wedgeFloatAttribHandles;
        std::vector<AttribHandle<Vector2>> m_wedgeVector2AttribHandles;
        std::vector<AttribHandle<Vector3>> m_wedgeVector3AttribHandles;
        std::vector<AttribHandle<Vector4>> m_wedgeVector4AttribHandles;

        template <typename T>
        inline std::vector<std::string>& getNameArray();
        AlignedStdVector<Wedge> m_data;
    };

    // internal function to build Core Mesh attribs correspondance to wedge attribs.
    class InitWedgeAttribsFromMultiIndexedGeometry
    {
      public:
        InitWedgeAttribsFromMultiIndexedGeometry(
            TopologicalMesh* topo,
            const Ra::Core::Geometry::MultiIndexedGeometry& triMesh ) :
            m_topo( topo ), m_triMesh( triMesh ) {}
        void operator()( AttribBase* attr ) const;

      private:
        TopologicalMesh* m_topo;
        const Ra::Core::Geometry::MultiIndexedGeometry& m_triMesh;
    };

    //! [Default command implementation]
    /// \todo add layerKey
    struct DefaultNonManifoldFaceCommand {
        /// \brief details string is printed along with the message
        DefaultNonManifoldFaceCommand( const std::string& details = {} ) : m_details {details} {}
        /// \brief Initalize with input Ra::Core::Geometry::TriangleMesh
        inline void initialize( const Ra::Core::Geometry::MultiIndexedGeometry& ) {}
        /// \brief Process non-manifold face
        inline void process( const std::vector<TopologicalMesh::VertexHandle>& /*face_vhandles*/ ) {
            LOG( logWARNING ) << "Invalid face handle returned : face not added " + m_details;
        }
        /// \brief If needed, apply post-processing on the Ra::Core::Geometry::TopologicalMesh
        inline void postProcess( TopologicalMesh& ) {}
        //! [Default command implementation]
      private:
        std::string m_details;
    };

    WedgeData interpolateWedgeAttributes( const WedgeData&, const WedgeData&, Scalar alpha );

    /// @todo when MultiIndexView will be operational, remove the IndexedGeometry<U> version above
    template <typename T>
    inline void copyAttribToWedgeData( const Ra::Core::Geometry::MultiIndexedGeometry& mesh,
                                       unsigned int vindex,
                                       const std::vector<AttribHandle<T>>& attrHandleVec,
                                       VectorArray<T>* to );

    /// @todo when MultiIndexView will be operational, remove the IndexedGeometry<T> version above
    inline void copyMeshToWedgeData( const Ra::Core::Geometry::MultiIndexedGeometry& mesh,
                                     unsigned int vindex,
                                     const std::vector<AttribHandle<Scalar>>& wprop_float,
                                     const std::vector<AttribHandle<Vector2>>& wprop_vec2,
                                     const std::vector<AttribHandle<Vector3>>& wprop_vec3,
                                     const std::vector<AttribHandle<Vector4>>& wprop_vec4,
                                     TopologicalMesh::WedgeData* wd );

    template <typename T>
    using HandleAndValueVector =
        std::vector<std::pair<AttribHandle<T>, T>,
                    Eigen::aligned_allocator<std::pair<AttribHandle<T>, T>>>;

    void split_copy( EdgeHandle _eh, VertexHandle _vh );
    void split( EdgeHandle _eh, VertexHandle _vh );

    OpenMesh::HPropHandleT<WedgeIndex> m_wedgeIndexPph; /**< Halfedges' Wedge index */
    WedgeCollection m_wedges;                           /**< Wedge data management */

    ///\todo to be deleted/updated
    OpenMesh::HPropHandleT<Index> m_inputTriangleMeshIndexPph;
    OpenMesh::HPropHandleT<Index> m_outputTriangleMeshIndexPph;

    int m_normalsIndex {-1};
    // vertex handle idx -> face handle idx -> wedge idx with the same normal
    std::vector<std::map<int, std::vector<int>>> m_vertexFaceWedgesWithSameNormals;

    friend class TMOperations;
};

// heplers
void printWedgesInfo( const TopologicalMesh& );

} // namespace Geometry
} // namespace Core
} // namespace Ra

#include <Core/Geometry/TopologicalMesh.inl>

max_issues_repo_name: neurodiverseEsoteric/Radium-Engine

max_forks_repo_name: neurodiverseEsoteric/Radium-Engine


text:
// http://turtle.sourceforge.net
//
// Copyright Mathieu Champlon 2014
//
// 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)

#ifndef MOCK_MUTEX_HPP_INCLUDED
#define MOCK_MUTEX_HPP_INCLUDED

#include "../config.hpp"
#include "singleton.hpp"
#include <boost/move/move.hpp>
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>

#ifdef MOCK_THREAD_SAFE

#ifdef MOCK_HDR_MUTEX
#include <mutex>
#else
#include <boost/thread/recursive_mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#endif

namespace mock
{
namespace detail
{
#ifdef MOCK_HDR_MUTEX
    typedef std::recursive_mutex mutex;
    typedef std::lock_guard< mutex > scoped_lock;
#else
    typedef boost::recursive_mutex mutex;
    typedef boost::lock_guard< mutex > scoped_lock;
#endif

    struct lock
    {
    private:
        BOOST_MOVABLE_BUT_NOT_COPYABLE(lock)

    public:
        lock( const boost::shared_ptr< mutex >& m )
            : m_( m )
        {
            m_->lock();
        }
        ~lock()
        {
            if( m_ )
                m_->unlock();
        }
        lock( BOOST_RV_REF( lock ) x )
            : m_( x.m_ )
        {
            // Explicit reset to avoid unlock in destructor
            x.m_.reset();
        }
        lock& operator=( BOOST_RV_REF( lock ) x )
        {
            m_ = x.m_;
            x.m_.reset();
            return *this;
        }

    private:
        boost::shared_ptr< mutex > m_;
    };
}
} // mock

#else // MOCK_THREAD_SAFE

namespace mock
{
namespace detail
{
    struct mutex : boost::noncopyable
    {
        void lock()
        {}
        void unlock()
        {}
    };
    // Dummy lock classes.
    // Constructor + Destructor make it RAII classes for compilers and avoid unused variable warnings
    struct scoped_lock : boost::noncopyable
    {
        scoped_lock( mutex& )
        {}
        ~scoped_lock()
        {}
    };
    class lock : boost::noncopyable
    {
    private:
        BOOST_MOVABLE_BUT_NOT_COPYABLE(lock)

    public:
        lock( const boost::shared_ptr< mutex >& )
        {}
        ~lock()
        {}
        lock( BOOST_RV_REF( lock ) )
        {}
        lock& operator=( BOOST_RV_REF( lock ) )
        {
            return *this;
        }
    };
}
} // mock

#endif // MOCK_THREAD_SAFE

namespace mock
{
namespace detail
{
    class error_mutex_t : public singleton< error_mutex_t >,
        public mutex
    {
        MOCK_SINGLETON_CONS( error_mutex_t );
    };
    MOCK_SINGLETON_INST( error_mutex )

#ifdef BOOST_MSVC
#   pragma warning( push )
#   pragma warning( disable: 4702 )
#endif
    template< typename Result, typename Error >
    struct safe_error
    {
        static Result abort()
        {
            scoped_lock _( error_mutex );
            return Error::abort();
        }
        template< typename Context >
        static void fail( const char* message, const Context& context,
            const char* file = "unknown location", int line = 0 )
        {
            scoped_lock _( error_mutex );
            Error::fail( message, context, file, line );
        }
        template< typename Context >
        static void call( const Context& context, const char* file, int line )
        {
            scoped_lock _( error_mutex );
            Error::call( context, file, line );
        }
        static void pass( const char* file, int line )
        {
            scoped_lock _( error_mutex );
            Error::pass( file, line );
        }
    };
#ifdef BOOST_MSVC
#   pragma warning( pop )
#endif
}
} // mock

#endif // MOCK_MUTEX_HPP_INCLUDED

max_stars_repo_name: jonesmz/turtle

max_issues_repo_name: jonesmz/turtle

max_forks_repo_name: jonesmz/turtle


text: #include <boost/compute/types/tuple.hpp>


text:
/*
Modified BSD License

This file is a part of Statistical package and originates from:
http://sf.net/projects/enjomitchsorbit

Copyright (c) 2012, Szymon "Enjo" Ender
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "EigenEigen3.hpp"
#include "../Matrix.hpp"
#include "../../Util/VecD.hpp"
#include <Util/Except.hpp>
#include <Util/CharManipulations.hpp>

#include <STD/VectorCpp.hpp>

//#define EIGEN_USE_MKL_ALL
//#define EIGEN_USE_BLAS // Enables openblas64 - somewhat slower
//#define EIGEN_USE_LAPACKE // Don't use currently
#include <Eigen/Dense>

#include <Util/CoutBuf.hpp>

using namespace std;
using namespace EnjoLib;
//using namespace Eigen;

EigenEigen3::~EigenEigen3(){}
EigenEigen3::EigenEigen3(){}

static Eigen::MatrixXd ConvertMatrix( const Matrix & m )
{
    const int nrows = m.GetNRows();
    const int ncols = m.GetNCols();
    Eigen::MatrixXd mateig(nrows, ncols);
    for ( int i = 0; i < nrows; ++i ) for ( int j = 0; j < ncols; ++j )
            mateig(i, j) = m.at(i).at(j);

    return mateig;
}

std::vector<EigenValueVector> EigenEigen3::GetEigenValVecClient( const Matrix & m ) const
{
    std::vector<EigenValueVector> ret;
    ret.reserve(m.GetNRows());

    //cout << "M = " << m.GetNCols() << ", " << m.GetNRows() << endl;

    Eigen::EigenSolver<Eigen::MatrixXd> es;
    const Eigen::MatrixXd & matE = ConvertMatrix(m);
    //cout << "Pre\n" << m.Print() << endl;
    es.compute(matE, /* computeEigenvectors = */ true);
    //cout << "Post" << endl;
    if (es.info() != Eigen::ComputationInfo::Success)
    {
        ELO
        LOG << "Eigenvalue Calculation not successful: " << es.info() << NL3;
        //cout << m.Print() << endl;
        throw EnjoLib::ExceptRuntimeError("Eigenvalue Calculation not successful " + CharManipulations().ToStr(es.info()));
        LOG << "After throw: " << es.info() << NL3;
    }

    const auto & eval  = es.eigenvalues();
    const auto & evect = es.eigenvectors();
    for ( int i = 0; i < m.GetNRows(); ++i )
    {
        const auto & evali = eval(i);
        const double eigenValue = evali.real();
        VecD eigenVector;
        eigenVector.reserve(m.GetNCols());

        for ( int j = 0; j < m.GetNCols(); ++j )
        {
            const double val = evect(j, i).real(); // Transposition (j, i) due to internal Eigen storage!
            eigenVector.push_back(val);
        }

        ret.push_back( EigenValueVector(eigenValue, eigenVector) );
    }
    return ret;
}


text:
#ifndef TMC_UNIT_TESTS
#define BOOST_TEST_MODULE lib_classifier_creator_train_tmc
#endif
#include <boost/test/included/unit_test.hpp>

#include "feature_names.h"
#include "classifier_creator_train_tmc.h"

BOOST_AUTO_TEST_SUITE( classifier_creator_train_tmc )

BOOST_AUTO_TEST_CASE( basics )
{
    const std::string names_file("data/4layers_36points/4layers_36points.names");
    const std::string data_file("data/4layers_36points/4layers_36points.data");
    BOOST_TEST_MESSAGE("Creating sample from file: " << data_file);

    std::shared_ptr<FeatureNames> pFN = std::make_shared<FeatureNames>(names_file);

    SampleCreator sample_creator;
    sample_creator.set_feature_names(pFN);

    std::shared_ptr<Sample> pSample = sample_creator.from_file(data_file);

    BOOST_TEST_MESSAGE("Resulting sample: " << *pSample);
    BOOST_CHECK_EQUAL(pSample->dim(), 2);
    BOOST_CHECK_EQUAL(pSample->size(), 36);

    std::shared_ptr<ClassifierCreatorTrain> pTC = std::make_shared<ClassifierCreatorTrainTmc>();
    (*pTC).init(pSample).train();
    (*pTC).init(pSample).train();

    std::shared_ptr<Classifier> pClTmc = pTC->get_classifier();

    std::vector<double> p;  std::pair<double, double> conf;
    p = {10,2}; conf = {1.0/6.0,1.0/6.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), conf.first);
    p = {16,1}; conf = {1.0/3.0,1.0/3.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), conf.first);
    p = {7,10}; conf = {2.0/3.0,2.0/3.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), conf.first);
    p = {11,10}; conf = {5.0/6.0,5.0/6.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), conf.first);
    p = {4,6}; conf = {0,1.0/6.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), conf.second);
    p = {7,13}; conf = {5.0/6.0,1}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), conf.first);
    p = {14.5,0.5}; conf = {0,1.0/3.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (10+8)/(double)(50+10+16+8));
    p = {-1,16}; conf = {0,5.0/6.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (10+8+18+45)/(double)(50+10+16+8+9+18+9+45));
    p = {-1,18}; conf = {0,1}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (10+8+18+45)/(double)(50+10+16+8+9+18+9+45));
    p = {12.5,1.5}; conf = {1.0/6.0,1.0/3.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (10+8)/(double)(50+10+16+8));
    p = {4,8}; conf = {1.0/6.0,2.0/3.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (10+8+18)/(double)(50+10+16+8+9+18));
    p = {3,13}; conf = {1.0/6.0,5.0/6.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (10+8+18+45)/(double)(50+10+16+8+9+18+9+45));
    p = {1,18};  conf = {1.0/6.0,1}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (10+8+18+45)/(double)(50+10+16+8+9+18+9+45));
    p = {15,5.5}; conf = {1.0/3.0,5.0/6.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (8+18+45)/(double)(16+8+9+18+9+45));
    p = {18,1}; conf = {1.0/3.0,1}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (8+18+45)/(double)(16+8+9+18+9+45));
    p = {8,12}; conf = {2.0/3.0,5.0/6.0}; BOOST_CHECK(pClTmc->confidence_interval(p) == conf);
    BOOST_CHECK_EQUAL(pClTmc->confidence(p), (18+45)/(double)(9+18+9+45));
}

BOOST_AUTO_TEST_SUITE_END()

ext: cc

max_stars_repo_name: tmcombi/tmcombi

max_issues_repo_name: tmcombi/tmcombi

max_forks_repo_name: tmcombi/tmcombi


text:
//---------------------------------------------------------------------------------------------------------------------
//  Cameras wrapper MICO plugin
//---------------------------------------------------------------------------------------------------------------------
//  Copyright 2020 Pablo Ramon Soria (a.k.a. Bardo91) pabramsor@gmail.com
//---------------------------------------------------------------------------------------------------------------------
//  Permission is hereby granted, free of charge, to any person obtaining a copy of this software
//  and associated documentation files (the "Software"), to deal in the Software without restriction,
//  including without limitation the rights to use, copy, modify, merge, publish, distribute,
//  sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all copies or substantial
//  portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
//  BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
//  OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//---------------------------------------------------------------------------------------------------------------------

#ifndef MICO_ML_DETECTION_H_
#define MICO_ML_DETECTION_H_

#include <mico/ml/Detection.h>
#include <mico/core/TemplatesConversion.h>

#include <Eigen/Eigen>

#include <QComboBox>
#include <QHBoxLayout>
#include <QGroupBox>
#include <QSpinBox>

namespace mico{
    namespace ml{
        BlockTriggerDetection::BlockTriggerDetection(){

            labelSelection_ = new QSpinBox();
            typeSelection_ = new QComboBox();
            typeSelection_->addItem("Has label");
            typeSelection_->addItem("Has not label");

            createPipe<bool>("trigger");
            createPolicy({  flow::makeInput<std::vector<Detection>>("detections") });

            registerCallback(   {"detections"},
                                [&](flow::DataFlow _data){
                                    if(!idle_)
                                        return;

                                    idle_ = false;
                                    if(getPipe("trigger")->registrations()){
                                        auto detections = _data.get<std::vector<Detection>>("detections");
                                        auto result = std::find_if(detections.begin(), detections.end(), [&](const Detection &_d){
                                            return _d.label_ == labelSelection_->value();
                                        });

                                        if(typeSelection_->currentText() == "Has label"){
                                            getPipe("trigger")->flush(result != detections.end());
                                        }else if(typeSelection_->currentText() == "Has not label"){
                                            getPipe("trigger")->flush(result == detections.end());
                                        }
                                    }
                                    idle_ = true;
                                }
            );
        }

        QWidget * BlockTriggerDetection::customWidget(){
            QGroupBox *gb = new QGroupBox();
            QHBoxLayout *l = new QHBoxLayout();
            gb->setLayout(l);
            l->addWidget(typeSelection_);
            l->addWidget(labelSelection_);
            return gb;
        }
    }
}

// -------------------------- Type conversions ------------

typedef std::vector<mico::ml::Detection> StlVectorDetection;
typedef mico::ml::Detection micoMlDetection;
typedef cv::Mat cvMat;
const auto flatVectorDetectionConversion    = simpleFlatVectorTakeFirst<StlVectorDetection, micoMlDetection>;
FLOW_CONVERSION_REGISTER(StlVectorDetection, micoMlDetection, flatVectorDetectionConversion);

boost::any DetectionToMat(boost::any &_input){
    return boost::any_cast<mico::ml::Detection>(_input).crop_;
}

boost::any StlVectorDetectionToMat(boost::any &_input){
    return boost::any_cast<StlVectorDetection>(_input)[0].crop_;
}

FLOW_CONVERSION_REGISTER(micoMlDetection, cvMat, &DetectionToMat);
FLOW_CONVERSION_REGISTER(StlVectorDetection, cvMat, &StlVectorDetectionToMat);

boost::any DetectionToStlVectorFloat(boost::any &_input){
    const auto bb = boost::any_cast<mico::ml::Detection>(_input).bb_;
    float x = bb.x + bb.width/2;
    float y = bb.y + bb.height/2;
    return std::vector<float>{x,y};
}

boost::any DetectionToCvPoint(boost::any &_input){
    const auto bb = boost::any_cast<mico::ml::Detection>(_input).bb_;
    float x = bb.x + bb.width/2;
    float y = bb.y + bb.height/2;
    return cv::Point2f(x, y);
}

boost::any DetectionToEigen(boost::any &_input){
    const auto bb = boost::any_cast<mico::ml::Detection>(_input).bb_;
    float x = bb.x + bb.width/2;
    float y = bb.y + bb.height/2;
    return Eigen::Vector2f(x, y);
}

typedef Eigen::Vector2f EigenVector2f;
typedef cv::Point2f CvPoint2f;
typedef std::vector<float> StlVectorFloat;
FLOW_CONVERSION_REGISTER(micoMlDetection, StlVectorFloat, &DetectionToStlVectorFloat);
FLOW_CONVERSION_REGISTER(micoMlDetection, CvPoint2f, &DetectionToCvPoint);
FLOW_CONVERSION_REGISTER(micoMlDetection, EigenVector2f, &DetectionToEigen);

boost::any StlVectorDetectionToStlVectorFloat(boost::any &_input){
    const auto bb = boost::any_cast<StlVectorDetection>(_input)[0].bb_;
    float x = bb.x + bb.width/2;
    float y = bb.y + bb.height/2;
    return std::vector<float>{x,y};
}

boost::any StlVectorDetectionToCvPoint(boost::any &_input){
    const auto bb = boost::any_cast<StlVectorDetection>(_input)[0].bb_;
    float x = bb.x + bb.width/2;
    float y = bb.y + bb.height/2;
    return cv::Point2f(x, y);
}

boost::any StlVectorDetectionToEigen(boost::any &_input){
    const auto bb = boost::any_cast<StlVectorDetection>(_input)[0].bb_;
    float x = bb.x + bb.width/2;
    float y = bb.y + bb.height/2;
    return Eigen::Vector2f(x, y);
}

FLOW_CONVERSION_REGISTER(StlVectorDetection, StlVectorFloat, &StlVectorDetectionToStlVectorFloat);
FLOW_CONVERSION_REGISTER(StlVectorDetection, CvPoint2f, &StlVectorDetectionToCvPoint);
FLOW_CONVERSION_REGISTER(StlVectorDetection, EigenVector2f, &StlVectorDetectionToEigen);

#endif

max_stars_repo_name: mico-corp/mico

max_issues_repo_name: mico-corp/mico

max_forks_repo_name: mico-corp/mico


text:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <opencv2/opencv.hpp>
#include <dlib/svm_threaded.h>

using namespace cv;

extern void init_embedding();
extern void embedding(const unsigned char *img, float *features);

static void *classifier(void *arg);

float diff_time_ms(struct timespec start, struct timespec end) {
  return (1e9 * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec)/1e6;
}

typedef dlib::matrix<float,128,1> sample_type;
typedef dlib::linear_kernel<sample_type> lin_kernel;

static pthread_t thread;
static sem_t *semStart, *semDone;

static Mat image;
static dlib::multiclass_linear_decision_function<lin_kernel,std::string> df;
static std::pair<std::string,float> guess;

void init_classify(sem_t *start, sem_t *done) {
  semStart = start;
  semDone = done;

  init_embedding();

  std::ifstream inf("faces.svm");
  dlib::deserialize(df, inf);

  pthread_create(&thread, NULL, classifier, NULL);
}

void classify_image(Mat& next) {
  image = next.clone();
}

void classify_label(char *buf) {
  sprintf(buf, "%s (%f)", guess.first.c_str(), guess.second);
}

static void *classifier(void *arg) {
  float features[128];
  sample_type mat;
  struct timespec t1,t2,t3;

  while (sem_wait(semStart) == 0) {
    clock_gettime(CLOCK_MONOTONIC, &t1);
    embedding(image.ptr(0), features);
    clock_gettime(CLOCK_MONOTONIC, &t2);
    for (int i=0; i<128; i++) mat(i) = features[i];
    guess = df.predict(mat);
    clock_gettime(CLOCK_MONOTONIC, &t3);
    //printf("\n%s %f (%0.1f %0.1f)\n", guess.first.c_str(), guess.second, diff_time_ms(t1, t2), diff_time_ms(t2, t3));
    sem_post(semDone);
  }
  return NULL;
}

max_stars_repo_name: sathibault/greenlight-poc

max_issues_repo_name: sathibault/greenlight-poc

max_forks_repo_name: sathibault/greenlight-poc