text:
/* ------------------------------------------

   ------------------------------------------ */
#include <sstream>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <anchoring/anchor.hpp>

namespace anchoring {

  // Used namespaces
  using namespace std;

  // Declare the static predicate map
  std::map<std::string, int> Anchor::_predicates;

  // Constructor
  Anchor::Anchor(const ros::Time &t, AttributeMap &attributes, PerceptMap &percepts) {

    // Assign (or move) the attributes
    for( auto ite = attributes.begin(); ite != attributes.end(); ++ite) {
      this->_attributes[ite->first] = std::move(ite->second);
    }

    // Assign (or move) the perecpts
    for( auto ite = percepts.begin(); ite != percepts.end(); ++ite) {
      this->_percepts[ite->first] = std::move(ite->second);
    }

    // Generate an id
    this->_id = mongo::Database::generate_id();

    // Set time
    this->_t = t;

    // Set status variables
    this->_persistent = false;
    this->_thread = std::thread( &Anchor::fading, this, 100);
  }

  // Destructor
  Anchor::~Anchor() {
    if( this->_thread.joinable() ) {
      this->_thread.join();
    }
    this->_attributes.clear();
  }

  /**
   * Public load function (retreive the anchor from the database)
   */
  void Anchor::load(const mongo::Database &db) {

    // Load from MongoDB
    try {

      // Load all data as a sub document
      mongo::Database::Document doc = db.get(this->_id);

      // Read the time
      this->_t = ros::Time( doc.get<double>("t") );

      // Read the unique symbol
      this->_x = doc.get<std::string>("x");

      // Read the history
      if( doc.exist("H") ) {
	doc.get<std::string>( "H", this->_history);
      }

      // Read all percepts
      for( mongo::document_iterator ite = doc.begin("percepts"); ite != doc.end("percepts"); ++ite) {

	// Load the type...
	PerceptType type = mapPerceptType(ite->get<std::string>("type"));

	// Load the percepts based on the type
	this->_percepts[type] = createPercept(type);

	// Deserialize the perceptual data
	this->_percepts[type]->deserialize(*ite);
      }

      // Read all attributes
      for( mongo::document_iterator ite = doc.begin("attributes"); ite != doc.end("attributes"); ++ite) {

	// Load the type...
	AttributeType type = mapAttributeType(ite->get<std::string>("type"));
	//AttributeType type = (AttributeType)ite->get<int>("type");

	// Load the attribute based on the type
	this->_attributes[type] = createAttribute(type);

	// Deserialize the attribute data
	this->_attributes[type]->deserialize(*ite);
      }
    }
    catch( const std::exception &e ) {
      std::cout << "[Anchor::load]" << e.what() << std::endl;
    }
  }

  /**
   * Public save function (stores the anchor in the database)
   */
  void Anchor::save(mongo::Database &db) {

    // Safely changed the persistent variable
    std::lock_guard<std::mutex> lock(this->_mtx);
    if( !this->_persistent ) {
      this->_persistent = true; // Lives forever (in the database) from now on...
      if( this->_thread.joinable() ) {
	this->_thread.join();
      }
    }

    // Generate a unique symbol
    if( this->_attributes.find(CATEGORY) != this->_attributes.end() ) {
      auto it = this->_attributes.find(CATEGORY);
      this->_x = this->generateSymbol( it->second->toString(), db);
    }
    else {
      this->_x = this->generateSymbol( "unknown", db );
    }

    // TEMP
    if( db.initialized() ) {
      // Insert the anchor into database
      try {

	// Save document (use this _id as identifier)
	mongo::Database::Document doc(this->_id);

	// Add symbol
	doc.add<std::string>( "x", this->_x);

	// Add the history
	doc.add<std::string>( "H", this->_x);

	// Add time
	doc.add<double>( "t", this->_t.toSec());

	// Add all attributes
	for( auto it = this->_attributes.begin(); it != this->_attributes.end(); ++it) {
	  mongo::Database::Document subdoc = it->second->serialize();
	  subdoc.add<std::string>( "type", it->second->getTypeStr());
	  doc.append( "attributes", subdoc);
	}

	/*
	// Add all percepts
	for( auto it = this->_percepts.begin(); it != this->_percepts.end(); ++it) {
	mongo::Database::Document subdoc = it->second->serialize();
        subdoc.add<std::string>( "type", it->second->getTypeStr());
        doc.append( "percepts", subdoc);
	}
	*/
	auto it = this->_percepts.find(VISUAL);
	mongo::Database::Document subdoc = it->second->serialize();
	subdoc.add<std::string>( "type", it->second->getTypeStr());
	doc.append( "percepts", subdoc);

	// Commit all changes to database
	db.insert(doc);
      }
      catch( const std::exception &e ) {
	std::cout << "[Anchor::save]" << e.what() << std::endl;
      }
    }
  }

  /**
   * Public update function(s)
   */
  void Anchor::update(mongo::Database &db, const ros::Time &t, AttributeMap &attributes, PerceptMap &percepts ) {

    // Update the percepts of this anchor (or move un-exisiting percepts to this anchor)
    for( auto it = percepts.begin(); it != percepts.end(); ++it) {
      if( this->_percepts.find(it->first) == this->_percepts.end() ) {
	this->_percepts[it->first] = std::move(it->second);
      }
      else {
	this->_percepts[it->first]->update(it->second);
      }
    }

    // Make use of function overloading...
    this->update(db, t, attributes);
  }

  void Anchor::update(mongo::Database &db, const ros::Time &t, AttributeMap &attributes ) {

    // Update time
    this->_t = t;

    // Update attributes of this anchor (or move un-exisiting attributes to this anchor)
    for( auto it = attributes.begin(); it != attributes.end(); ++it) {
      if( this->_attributes.find(it->first) == this->_attributes.end() ) {
	this->_attributes[it->first] = std::move(it->second);
      }
      else {
	this->_attributes[it->first]->update(it->second);
      }
    }

    // Save the anchor - the anchor need to be re-acquired within it's life time...
    if( !this->_persistent ) {
      this->save(db);    // ...in order to be saved to the database
    }
    else {

      // Check and update the (unique) symbol
      if( this->_attributes.find(CATEGORY) != this->_attributes.end() ) {
	auto it = this->_attributes.find(CATEGORY);
	std::string symbol = it->second->toString();
	//ROS_WARN("Category is '%s' is x is '%s'", symbol.c_str(), this->_x.c_str());
	if( this->_x.compare( 0, symbol.size(), symbol) != 0 ) {

	  bool found = false;
	  for( auto x : this->_history ) {
	    if( x.compare( 0, symbol.size(), symbol) == 0 ) {
	      this->_x = x;
	      found = true;
	      break;
	    }
	  }
	  if( !found ) {
	    this->_history.push_back(this->_x);
	    this->_x = this->generateSymbol( symbol, db);
	    //db.update<std::string>( this->_id, "x", this->_x);
	    //db.update<std::string>( this->_id, "H", this->_history);
	  }
	}
      }

      if( db.initialized() ) { // TMP
	// Update the database
	try {

	  // TMP
	  db.update<std::string>( this->_id, "x", this->_x);
	  db.update<std::string>( this->_id, "H", this->_history);

	  // Update time
	  db.update<double>( this->_id, "t", this->_t.toSec());

	  // Update all attributes
	  std::vector<mongo::Database::Document> docs;
	  for( auto it = this->_attributes.begin(); it != this->_attributes.end(); ++it) {
	    mongo::Database::Document subdoc = it->second->serialize();
	    subdoc.add<std::string>( "type", it->second->getTypeStr());
	    docs.push_back(subdoc);
	  }
	  db.update<mongo::Database::Document>( this->_id, "attributes", docs);

	  // Update all percepts
	  docs.clear();
	  /*
	    for( auto it = this->_percepts.begin(); it != this->_percepts.end(); ++it) {
	    mongo::Database::Document subdoc = it->second->serialize();
	    subdoc.add<std::string>( "type", it->second->getTypeStr());
	    docs.push_back(subdoc);
	    }
	  */
	  auto it = this->_percepts.find(VISUAL);
	  mongo::Database::Document subdoc = it->second->serialize();
	  subdoc.add<std::string>( "type", it->second->getTypeStr());
	  docs.push_back(subdoc);

	  db.update<mongo::Database::Document>( this->_id, "percepts", docs);

	}
	catch( const std::exception &e ) {
	  std::cout << "[Anchor::update]" << e.what() << std::endl;
	}
      }
    }
  }

  /**
   * Public merge function (combines two anchors)
   */
  void Anchor::merge(mongo::Database &db, AnchorPtr &other) {

    // Merge and update changed attributes
    try {

      // Update the time
      this->_t = ros::Time(other->time());
      db.update<double>( this->_id, "t", this->_t.toSec());

      // Add and update the history
      if( !other->_history.empty() ) {
	this->_history.insert( this->_history.end(), other->_history.begin(), other->_history.end() );
      }
      this->_history.push_back( other->id() );
      db.update<string>( this->_id, "H", this->_history);

      // Update attributes and percepts
      this->update(db, other->_t, other->_attributes, other->_percepts);
    }
    catch( const std::exception &e ) {
      std::cout << "[Anchor::merge]" << e.what() << std::endl;
    }
  }

  /**
   * Matching function
   */
  void Anchor::match( const AttributeMap &attributes,
		      MatchMap &result ) {
    for( auto ite = attributes.begin(); ite != attributes.end(); ++ite) {
      if( this->_attributes.find(ite->first) != this->_attributes.end() ) {
	std::pair<AttributeType, float> rate;
	rate.first = ite->first;
	rate.second = this->_attributes[ite->first]->match(ite->second);
	result.insert(rate);
      }
    }
  }

  /**
   * Get/set functions + private life-span function
   */

  // Set the symbol(s) of an attribute of an anchor
  void Anchor::setSymbols( AttributeType type, const vector<string> &symbols) {
    AttributeMap::iterator ite = this->_attributes.find(type);
    if( ite != this->_attributes.end() ) {
      ite->second->_symbols = symbols;
    }
  }

  // Get the symbol(s) for an attribute of an anchor
  vector<string> Anchor::getSymbols(AttributeType type) {
    AttributeMap::iterator ite = this->_attributes.find(type);
    if( ite != this->_attributes.end() ) {
      return ite->second->_symbols;
    }
    return vector<string>();
  }

  // Get time string
  std::string Anchor::timeStr() {
    boost::posix_time::ptime boost_t = this->_t.toBoost();
    return boost::posix_time::to_simple_string(boost_t);
  }

  // Thread function for decreasing the life of the anchor
  void Anchor::fading(int life) {
    while( life != 0  ) {
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      life--;
      if( this->_persistent ) {
	break;
      }
    }

    // Dead anchor - release this object
    if( !this->_persistent ) {
      this->_attributes.clear();
      this->_percepts.clear();
    }
  }

  std::string Anchor::toString() {
    AttributeMap::iterator ite = this->_attributes.find(POSITION);
    //return this->_x + " " + ite->second->toString();
    return this->_x;
    /*
    std::ostringstream oss;
    for( auto ite = this->_attributes.begin(); ite != this->_attributes.end(); ++ite) {
      oss << ite->second->toString() << " . ";
    }
    return oss.str();
    */
  }

  // ---[ Generate a unique symbol ]---
  std::string Anchor::generateSymbol(const std::string &key, mongo::Database &db) {
    std::stringstream ss;
    if( db.initialized() ) {
      try {
	db.set_collection("predicates");

	// Get the id (if document exists)
	std::string id = db.get_id( "symbol", key);
	if( !id.empty() ) {
	  int counter = db.get<int>( id, "count") + 1;
	  db.update<int>( id, "count", counter);
	  ss << key << "-" << counter;
	}
	else {
	  mongo::Database::Document doc;
	  doc.add<std::string>( "symbol", key);
	  doc.add<int>( "count", 1);
	  db.insert(doc);
	  ss << key << "-1";
	}
	db.set_collection("anchors");
      }
      catch( const std::exception &e ) {
	std::cout << "[Anchor::generateSymbol]" << e.what() << std::endl;
      }
    }
    else {
      map<std::string, int>::iterator it = this->_predicates.find(key);
      if( it != this->_predicates.end() ) {
	it->second += 1;
	ss << it->first << "-" << it->second;
      }
      else {
	this->_predicates.insert({key, 1});
	ss << key << "-1";
      }
    }
    return ss.str();
  }

} // namespace anchoring

ext: cpp

max_stars_repo_name: probabilistic-anchoring/probanch

max_issues_repo_name: probabilistic-anchoring/probanch

max_forks_repo_name: probabilistic-anchoring/probanch


text:
#ifndef NPA_FILE_HPP
#define NPA_FILE_HPP

#include <string>
#include <boost/locale.hpp>
using namespace std;

class NpaFile
{
public:
    NpaFile(const string& Name);
    virtual ~NpaFile() = 0;

    static void SetLocale(const char* LocaleStr);
    static string ToUtf8(const char* pBuff, uint32_t Size);
    static string ToUtf8(const string& String);
    static string ToUtf8(const char* pText);
    static string FromUtf8(const string& String);
    static char* Decrypt(char* pBuff, uint32_t Size, uint32_t Offset = 0);
    static char* Encrypt(char* pBuff, uint32_t Size);

protected:
    string Name;
private:
    static locale Locale;
};

#endif

ext: hpp

max_stars_repo_name: pavlukivan/libnpa

max_issues_repo_name: pavlukivan/libnpa

max_forks_repo_name: pavlukivan/libnpa


text:
#include <string>
using namespace std::string_literals;

#include <boost/functional/hash.hpp>

#include <fmt/format.h>

#include "vertex.hxx"

namespace vertex
{
    std::size_t compile_vertex_attributes(graphics::vertex_layout &vertex_layout, vertex::SEMANTIC semantic, graphics::FORMAT format)
    {
        vertex_layout.attributes.push_back(graphics::vertex_attribute{semantic, format});

        if (auto size_bytes = graphics::size_bytes(format); size_bytes != 0)
            return size_bytes;

        else throw graphics::exception("unsupported format"s);
    }
}

namespace graphics
{
    std::uint32_t get_vertex_attribute_semantic_index(graphics::vertex_attribute const &vertex_attribute)
    {
        return static_cast<std::uint32_t>(vertex_attribute.semantic);
        /*return std::visit([] (auto semantic)
        {
            using S = std::remove_cvref_t<decltype(semantic)>;
            return S::index;

        }, vertex_attribute.semantic);*/
    }
}

namespace graphics
{
    std::size_t hash<graphics::vertex_attribute>::operator() (graphics::vertex_attribute const &attribute) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, attribute.semantic);
        //boost::hash_combine(seed, attribute.semantic.index());
        boost::hash_combine(seed, attribute.format);

        return seed;
    }

    std::size_t hash<graphics::vertex_layout>::operator() (graphics::vertex_layout const &layout) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, layout.size_bytes);

        graphics::hash<graphics::vertex_attribute> constexpr attribute_hasher;

        for (auto &&attribute : layout.attributes)
            boost::hash_combine(seed, attribute_hasher(attribute));

        return seed;
    }

    std::size_t hash<graphics::vertex_input_binding>::operator() (graphics::vertex_input_binding const &binding) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, binding.binding_index);
        boost::hash_combine(seed, binding.stride_in_bytes);
        boost::hash_combine(seed, binding.input_rate);

        return seed;
    }

    std::size_t hash<graphics::vertex_input_attribute>::operator() (graphics::vertex_input_attribute const &input_attribute) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, input_attribute.location_index);
        boost::hash_combine(seed, input_attribute.binding_index);
        boost::hash_combine(seed, input_attribute.offset_in_bytes);
        boost::hash_combine(seed, input_attribute.format);

        return seed;
    }
}

namespace graphics
{
    std::string to_string(vertex::SEMANTIC semantic)
    {
        switch (semantic) {
            case vertex::SEMANTIC::POSITION:
                return "position"s;

            case vertex::SEMANTIC::NORMAL:
                return "normal"s;

            case vertex::SEMANTIC::TEXCOORD_0:
                return "texcoord_0"s;

            case vertex::SEMANTIC::TEXCOORD_1:
                return "texcoord_1"s;

            case vertex::SEMANTIC::TANGENT:
                return "tangent"s;

            case vertex::SEMANTIC::COLOR_0:
                return "color_0"s;

            case vertex::SEMANTIC::JOINTS_0:
                return "joints_0"s;

            case vertex::SEMANTIC::WEIGHTS_0:
                return "weights_0"s;

            default:
                return ""s;
        }
    }

    std::string to_string(graphics::FORMAT format)
    {
        switch (format) {
            // Signed and unsigned byte integer formats.
            case graphics::FORMAT::R8_SNORM:			return "r8i_norm"s;
            case graphics::FORMAT::RG8_SNORM:			return "rg8i_norm"s;
            case graphics::FORMAT::RGB8_SNORM:			return "rgb8i_norm"s;
            case graphics::FORMAT::RGBA8_SNORM:			return "rgba8i_norm"s;
            case graphics::FORMAT::R8_UNORM:			return "r8ui_norm"s;
            case graphics::FORMAT::RG8_UNORM:			return "rg8ui_norm"s;
            case graphics::FORMAT::RGB8_UNORM:			return "rgb8ui_norm"s;
            case graphics::FORMAT::RGBA8_UNORM:			return "rgba8ui_norm"s;
            case graphics::FORMAT::BGRA8_UNORM:			return "bgra8ui_norm"s;
            case graphics::FORMAT::RGBA8_SRGB:			return "rgba8_srgb"s;
            case graphics::FORMAT::BGRA8_SRGB:			return "bgra8_srgb"s;
            case graphics::FORMAT::R8_SINT:			    return "r8i"s;
            case graphics::FORMAT::RG8_SINT:			return "rg8i"s;
            case graphics::FORMAT::RGB8_SINT:			return "rgb8i"s;
            case graphics::FORMAT::RGBA8_SINT:			return "rgba8i"s;
            case graphics::FORMAT::R8_UINT:			    return "r8ui"s;
            case graphics::FORMAT::RG8_UINT:			return "rg8ui"s;
            case graphics::FORMAT::RGB8_UINT:			return "rgb8ui"s;
            case graphics::FORMAT::RGBA8_UINT:			return "rgba8ui"s;

            // Signed and unsigned two byte integer formats.
            case graphics::FORMAT::R16_SNORM:			return "r16i_norm"s;
            case graphics::FORMAT::RG16_SNORM:			return "rg16i_norm"s;
            case graphics::FORMAT::RGB16_SNORM:			return "rgb16i_norm"s;
            case graphics::FORMAT::RGBA16_SNORM:		return "rgba16i_norm"s;
            case graphics::FORMAT::R16_UNORM:			return "r16ui_norm"s;
            case graphics::FORMAT::RG16_UNORM:			return "rg16ui_norm"s;
            case graphics::FORMAT::RGB16_UNORM:			return "rgb16ui_norm"s;
            case graphics::FORMAT::RGBA16_UNORM:		return "rgba16ui_norm"s;
            case graphics::FORMAT::R16_SINT:			return "r16i"s;
            case graphics::FORMAT::RG16_SINT:			return "rg16i"s;
            case graphics::FORMAT::RGB16_SINT:			return "rgb16i"s;
            case graphics::FORMAT::RGBA16_SINT:			return "rgba16i"s;
            case graphics::FORMAT::R16_UINT:			return "r16ui"s;
            case graphics::FORMAT::RG16_UINT:			return "rg16ui"s;
            case graphics::FORMAT::RGB16_UINT:			return "rgb16ui"s;
            case graphics::FORMAT::RGBA16_UINT:			return "rgba16ui"s;

            // Signed and unsigned four byte integer formats.
            case graphics::FORMAT::R32_SINT:			return "r32i"s;
            case graphics::FORMAT::RG32_SINT:			return "rg32i"s;
            case graphics::FORMAT::RGB32_SINT:			return "rgb32i"s;
            case graphics::FORMAT::RGBA32_SINT:			return "rgba32i"s;
            case graphics::FORMAT::R32_UINT:			return "r32ui"s;
            case graphics::FORMAT::RG32_UINT:			return "rg32ui"s;
            case graphics::FORMAT::RGB32_UINT:			return "rgb32ui"s;
            case graphics::FORMAT::RGBA32_UINT:			return "rgba32ui"s;

            // Two byte float formats.
            case graphics::FORMAT::R16_SFLOAT:			return "r16f"s;
            case graphics::FORMAT::RG16_SFLOAT:			return "rg16f"s;
            case graphics::FORMAT::RGB16_SFLOAT:		return "rgb16f"s;
            case graphics::FORMAT::RGBA16_SFLOAT:		return "rgba16f"s;

            // Four byte float formats.
            case graphics::FORMAT::R32_SFLOAT:			return "r32f"s;
            case graphics::FORMAT::RG32_SFLOAT:			return "rg32f"s;
            case graphics::FORMAT::RGB32_SFLOAT:		return "rgb32f"s;
            case graphics::FORMAT::RGBA32_SFLOAT:		return "rgba32f"s;

            // Depth-stenci formats.
            case graphics::FORMAT::D16_UNORM:			return "d16ui_norm"s;
            case graphics::FORMAT::D16_UNORM_S8_UINT:	return "d16ui_norm_s8ui"s;
            case graphics::FORMAT::D24_UNORM_S8_UINT:	return "d24ui_norm_s8ui"s;
            case graphics::FORMAT::X8_D24_UNORM_PACK32:	return "x8_d24ui_norm_pack32"s;
            case graphics::FORMAT::D32_SFLOAT:			return "d32f"s;
            case graphics::FORMAT::D32_SFLOAT_S8_UINT:	return "d32f_s8ui"s;

            // Special formats.
            case graphics::FORMAT::B10GR11_UFLOAT_PACK32:	return "b10gr11uf_pack32"s;

            case graphics::FORMAT::UNDEFINED:
            default:
                return ""s;
        }
    }

    std::string to_string(graphics::vertex_layout const &layout)
    {
        std::string str;

        for (auto &&attribute : layout.attributes) {
            auto semantic = graphics::to_string(attribute.semantic);
            auto format = graphics::to_string(attribute.format);

            if (str.empty())
                str = fmt::format("{}:{}"s, semantic, format);

            else str = fmt::format("{}|{}:{}"s, str, semantic, format);
        }

        return str;
    }

    std::string to_string(graphics::PRIMITIVE_TOPOLOGY topology)
    {
        std::string topology_name;

        switch (topology)
        {
            case graphics::PRIMITIVE_TOPOLOGY::POINTS:
                topology_name = "points"s;
                break;

            case graphics::PRIMITIVE_TOPOLOGY::LINES:
            case graphics::PRIMITIVE_TOPOLOGY::LINE_STRIP:
                topology_name = "line_strip"s;
                break;

            case graphics::PRIMITIVE_TOPOLOGY::TRIANGLES:
            case graphics::PRIMITIVE_TOPOLOGY::TRIANGLE_STRIP:
            case graphics::PRIMITIVE_TOPOLOGY::TRIANGLE_FAN:
                topology_name = "triangles"s;
                break;

            default:
                break;
        }

        return topology_name;
    }
}

ext: cxx

max_stars_repo_name: Alabuta/VulkanIsland

max_issues_repo_name: Alabuta/VulkanIsland

max_forks_repo_name: Alabuta/VulkanIsland


text:
#pragma once
#ifndef _MIRROR_STRING_CONVERTOR_
#define _MIRROR_STRING_CONVERTOR_

#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "error_handler.hpp"

namespace mirror
{
template <typename T>
struct type_descriptor_resolver;
template <typename T>
class type_descriptor_for_class;

// primitive type 2 string convert func
// template <typename T>
// struct string_converter
// {
//     static bool set_from_string(void *ptr, std::string &string_value)
//     {
//         return false;
//     }

//     static T from_string(std::string &string_value)
//     {
//         auto td = type_descriptor_resolver<T>::get();
//         auto value = T();
//         return value;
//     }

//     static std::string to_string(T value)
//     {
//         return "";
//     }
// };

template <typename T>
struct string_converter
{
    static bool set_from_string(void *ptr, std::string &string_value)
    {
        auto td = dynamic_cast<type_descriptor_for_class<T> *>(type_descriptor_resolver<T>::get());
        bool set = false;

        if (td)
        {
            try
            {
                std::stringstream sstream(string_value);
                boost::property_tree::ptree pt;
                read_json(sstream, pt);

                for (auto it : td->members)
                {
                    boost::optional<std::string> member_string_value = pt.get_optional<std::string>(it->name);
                    if (member_string_value.has_value())
                    {
                        td->set_property_from_string(ptr, it->name, member_string_value.get());
                        set = true;
                    }
                }
            }
            catch (boost::property_tree::ptree_error pte)
            {
                runtime_error_handler(pte);
            }
        }
        return set;
    }

    static T from_string(std::string &string_value)
    {
        auto td = dynamic_cast<type_descriptor_for_class<T> *>(type_descriptor_resolver<T>::get());
        auto value = T();
        if (td)
        {
            try
            {
                std::stringstream sstream(string_value);
                boost::property_tree::ptree pt;
                read_json(sstream, pt);

                for (auto it : td->members)
                {
                    boost::optional<std::string> member_string_value = pt.get_optional<std::string>(it.name);
                    if (member_string_value.has_value())
                    {
                        td->set_property_from_string(&value, it.name, member_string_value.get());
                    }
                }
            }
            catch (boost::property_tree::ptree_error pte)
            {
                runtime_error_handler(pte);
            }
        }
        return value;
    }

    static std::string to_string(T value)
    {
        auto td = dynamic_cast<type_descriptor_for_class<T> *>(type_descriptor_resolver<T>::get());
        if (td)
        {
            try
            {
                boost::property_tree::ptree pt;
                for (auto it : td->members)
                {
                    auto member_string_value = td->get_property_to_string(&value, it->name);
                    pt.put(it->name, member_string_value);
                }
                std::stringstream sstream;
                write_json(sstream, pt);
                return sstream.str();
            }
            catch (boost::property_tree::ptree_error pte)
            {
                runtime_error_handler(pte);
            }
        }

        return "";
    }
};

#define NUMBER_STRING_CONVERTER(_typename, convert_func1, convert_func2)      \
    template <>                                                               \
    struct string_converter<_typename>                                        \
    {                                                                         \
        static bool set_from_string(void *ptr, std::string &string_value)     \
        {                                                                     \
            _typename *ptr_t = static_cast<_typename *>(ptr);                 \
            _typename value = 0;                                              \
            try                                                               \
            {                                                                 \
                *ptr_t = static_cast<_typename>(convert_func1(string_value)); \
                return true;                                                  \
            }                                                                 \
            catch (std::invalid_argument iae)                                 \
            {                                                                 \
                runtime_error_handler(iae);                                   \
            }                                                                 \
            catch (std::out_of_range oore)                                    \
            {                                                                 \
                runtime_error_handler(oore);                                  \
            }                                                                 \
            return false;                                                     \
        }                                                                     \
                                                                              \
        static _typename from_string(std::string &string_value)               \
        {                                                                     \
            try                                                               \
            {                                                                 \
                return static_cast<_typename>(convert_func1(string_value));   \
            }                                                                 \
            catch (std::invalid_argument iae)                                 \
            {                                                                 \
                runtime_error_handler(iae);                                   \
            }                                                                 \
            catch (std::out_of_range oore)                                    \
            {                                                                 \
                runtime_error_handler(oore);                                  \
            }                                                                 \
            return 0;                                                         \
        }                                                                     \
                                                                              \
        static std::string to_string(_typename &value)                        \
        {                                                                     \
            return convert_func2(value);                                      \
        }                                                                     \
    };

NUMBER_STRING_CONVERTER(bool, std::stoi, std::to_string)

NUMBER_STRING_CONVERTER(char, std::stoi, std::to_string)
NUMBER_STRING_CONVERTER(unsigned char, std::stoul, std::to_string)

NUMBER_STRING_CONVERTER(short, std::stoi, std::to_string)
NUMBER_STRING_CONVERTER(unsigned short, std::stoul, std::to_string)

NUMBER_STRING_CONVERTER(int, std::stoi, std::to_string)
NUMBER_STRING_CONVERTER(unsigned int, std::stoul, std::to_string)

NUMBER_STRING_CONVERTER(long, std::stol, std::to_string)
NUMBER_STRING_CONVERTER(unsigned long, std::stoul, std::to_string)

NUMBER_STRING_CONVERTER(long long, std::stol, std::to_string)
NUMBER_STRING_CONVERTER(unsigned long long, std::stoull, std::to_string)

NUMBER_STRING_CONVERTER(wchar_t, std::stoi, std::to_string)

NUMBER_STRING_CONVERTER(float, std::stof, std::to_string)

NUMBER_STRING_CONVERTER(double, std::stod, std::to_string)

NUMBER_STRING_CONVERTER(long double, std::stold, std::to_string)

template <>
struct string_converter<std::string>
{
    static bool set_from_string(void *ptr, std::string &string_value)
    {
        std::string *ptr_t = static_cast<std::string *>(ptr);
        *ptr_t = string_value;
        return true;
    }

    static std::string from_string(std::string &string_value)
    {
        return string_value;
    }

    static std::string to_string(std::string &value)
    {
        return value;
    }
};

} // namespace mirror

#define ENUM_CONVERTER(_typename)                                                                                \
    template <>                                                                                \
    struct mirror::string_converter<_typename>                                                                                \
    {                                                                                \
        static bool set_from_string(void *ptr, std::string &string_value)                                                              \
        {                                                                                \
            _typename *ptr_t = static_cast<_typename *>(ptr);                                                                          \
            auto td = dynamic_cast<mirror::type_descriptor_for_enum<_typename> *>(mirror::type_descriptor_resolver<_typename>::get()); \
            if (td)                                                                                \
            {                                                                                \
                *ptr_t = static_cast<_typename>(td->get_enumerator_value(string_value));                                               \
                return true;                                                                                \
            }                                                                                \
            return false;                                                                                \
        }                                                                                \
                                                                                \
        static _typename from_string(std::string &string_value)                                                                        \
        {                                                                                \
            auto td = dynamic_cast<mirror::type_descriptor_for_enum<_typename> *>(mirror::type_descriptor_resolver<_typename>::get()); \
            if (td)                                                                                \
            {                                                                                \
                return static_cast<_typename>(td->get_enumerator_value(string_value));                                                 \
            }                                                                                \
            return static_cast<_typename>(td->enumerator_unfound_value);                                                               \
        }                                                                                \
                                                                                \
        static std::string to_string(_typename &value)                                                                                \
        {                                                                                \
            auto td = dynamic_cast<type_descriptor_for_enum<_typename> *>(mirror::type_descriptor_resolver<_typename>::get());         \
            if (td)                                                                                \
            {                                                                                \
                return td->get_enumerator_name((int)value);                                                                            \
            }                                                                                \
            return td->enumerator_unfound_string;                                                                                \
        }                                                                                \
    };

#endif


text:
/*
Copyright 2011, 2012, 2014, 2015 Rogier van Dalen.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#ifndef RIME_CORE_HPP_INCLUDED
#define RIME_CORE_HPP_INCLUDED

#include <type_traits>

#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/integral_c_tag.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/equal_to.hpp>

#include <boost/utility/enable_if.hpp>

#include "utility/overload_order.hpp"
#include "utility/disable_if_same.hpp"

namespace rime {

namespace mpl = boost::mpl;

template <class Left, class Right> struct same_constant;

struct constant_base { constant_base () {} };

/**
A compile-time constant that behaves like a normal type ("value").
The advantage is that code can mix it with normal types, and that generic
routines can work with both compile-time constants and values.
They have an implicit conversion to the value type.

Implementation of the Rime compile-time constant concept:
\li value_type is the type of the value, Type;
\li value is a static const value_type equal to content;
\li is_constant returns true for this class and derived classes.

Rime constants are very similar to MPL integral constants.
The difference is their behaviour with operators.
Operators are overloaded (in operators.hpp) to use compile-time knowledge in
Rime constants.
For example, (rime::true_ || rime::true_) is known at compile time to be true,
and it returns a compile-time constant.
The behaviour of (boost::mpl::true_() || boost::mpl::true_()) is not changed.

Rime constants adhere to the Boost MPL Integral Constant concept.
Standard constants (std::integral_constant) and Boost MPL constants are
convertible to Rime constants.
This makes it possible to dispatch to different functions depending on
compile-time properties.
For example, the following adds to numbers, checking for overflow.
For unsigned integers, overflow has defined behaviour, namely wrapping around,
but for signed integers it does not.
The following therefore provides two implementations, and switches between them
based on \c std::is_signed <Type>().

\code
template <class Unsigned>
    Unsigned add_check_overflow_impl (Unsigned i, Unsigned j, rime::false_type)
{
    Unsigned result = i + j;
    if (result < i)
        throw std::overflow_error ("Overflow in addition");
    else
        return result;
}

template <class Signed>
    Signed add_check_overflow_impl (Signed i, Signed j, rime::true_type)
{
    if ((0 < j) && (std::numeric_limits <Signed>::max() - j < i))
        throw std::overflow_error ("Overflow in signed addition");
    if ((j < 0) && (i < std::numeric_limits <Signed>::min() - j))
        throw std::overflow_error ("Overflow in signed addition");
    return i + j;
}

template <class Type> Type add_check_overflow (Type i, Type j) {
    return add_check_overflow_impl (i, j, std::is_signed <Type>());
}
\endcode

\internal
It is necessary to derive from constant_base so that is_decayed_constant can
also pick up types derived from this.
*/
template <class Type, Type content> class constant
: public constant_base {
public:
    constexpr constant() noexcept {}

    constexpr constant (constant const &) noexcept {}
    constexpr constant (constant &&) noexcept {}

    template <class OtherConstant,
        class Enable1 = typename utility::disable_if_same_or_derived <
            constant, OtherConstant>::type,
        class Enable2 = typename
            boost::enable_if <same_constant <constant, OtherConstant>>::type>
    constexpr constant (OtherConstant const &) noexcept {}

    constant & operator= (constant const &) noexcept { return *this; }
    constant & operator= (constant &&) noexcept { return *this; }

    typedef mpl::integral_c_tag tag;
    typedef constant type;
    typedef typename std::decay <Type>::type value_type;

    static constexpr value_type value = content;

    constexpr operator value_type() const { return content; }

    constexpr operator std::integral_constant <Type, content>() const
    { return std::integral_constant <Type, content>(); }
};

// Out-of-class definition is required to allow references to constant<>::value.
template <class Type, Type content>
    constexpr typename std::decay <Type>::type constant <Type, content>::value;

// int_.
template <int content> struct int_ : constant <int, content> {
    constexpr int_() noexcept {}

    constexpr int_ (int_ const &) noexcept {}
    constexpr int_ (int_ &&) noexcept {}

    template <class OtherConstant,
        class Enable1 = typename utility::disable_if_same_or_derived <
            int_, OtherConstant>::type,
        class Enable2 = typename
            boost::enable_if <same_constant <int_, OtherConstant>>::type>
    constexpr int_ (OtherConstant const &) noexcept {}

    int_ & operator= (int_ const &) noexcept { return *this; }
    int_ & operator= (int_ &&) noexcept { return *this; }
};

// size_t.
template <std::size_t content> struct size_t
: constant <std::size_t, content> {
    constexpr size_t() noexcept {}

    constexpr size_t (size_t const &) noexcept {}
    constexpr size_t (size_t &&) noexcept {}

    template <class OtherConstant,
        class Enable1 = typename utility::disable_if_same_or_derived <
            size_t, OtherConstant>::type,
        class Enable2 = typename
            boost::enable_if <same_constant <size_t, OtherConstant>>::type>
    constexpr size_t (OtherConstant const &) noexcept {}

    size_t & operator= (size_t const &) noexcept { return *this; }
    size_t & operator= (size_t &&) noexcept { return *this; }
};

// bool_.
template <bool content> struct bool_ : constant <bool, content> {
    constexpr bool_() noexcept {}

    constexpr bool_ (bool_ const &) noexcept {}
    constexpr bool_ (bool_ &&) noexcept {}

    template <class OtherConstant,
        class Enable1 = typename utility::disable_if_same_or_derived <
            bool_, OtherConstant>::type,
        class Enable2 = typename
            boost::enable_if <same_constant <bool_, OtherConstant>>::type>
    constexpr bool_ (OtherConstant const &) noexcept {}

    bool_ & operator= (bool_ const &) noexcept { return *this; }
    bool_ & operator= (bool_ &&) noexcept { return *this; }
};

typedef bool_<false> false_type;
typedef bool_<true> true_type;

static const auto false_ = false_type();
static const auto true_ = true_type();

/**
Specialise this for Rime constants that don't derive from constant_base.
*/
template <class Type> struct is_decayed_rime_constant
: std::is_base_of <constant_base, Type> {};

/**
True iff Type is a Rime constant.
*/
template <class Type> struct is_rime_constant
: is_decayed_rime_constant <typename std::decay <Type>::type> {};

namespace is_constant_detail {

    struct take_std_integral_constant {
        // Standard library constants derive from std::integral_constant.
        template <class Type, Type value> take_std_integral_constant (
            std::integral_constant <Type, value> const &);
    };

    template <class Type> struct is_std_integral_constant
    : std::is_convertible <Type, take_std_integral_constant> {};

    struct take_mpl_integral_constant {
        // MPL constants have a typedef integral_c_tag tag.
        template <typename Constant> take_mpl_integral_constant (
            Constant const &,
            typename Constant::tag = boost::mpl::integral_c_tag());
    };

    template <class Type> struct is_mpl_integral_constant
    : std::is_convertible <Type, take_mpl_integral_constant> {};

} // namespace is_constant_detail

/**
True iff Type can be used as a compile-time constant.
I.e. iff Type is an integral constant from C++11 or Boost.MPL,
or a Rime constant.
*/
template <class Type> struct is_constant
: mpl::or_ <is_rime_constant <Type>,
    is_constant_detail::is_mpl_integral_constant <Type>,
    is_constant_detail::is_std_integral_constant <Type>> {};

/**
Convert any constant into a rime::constant<>.
*/
template <class Constant> struct as_rime_constant {
    static_assert (is_constant <Constant>::value,
        "Type argument to as_rime_constant must be a constant.");

    typedef constant <typename Constant::value_type, Constant::value> type;
};

/**
Return the type of a compile-time constant.
Compile-time function.
*/
template <class Type> struct constant_value
{ typedef typename std::decay <Type>::type::value_type type; };

template <class Type> struct runtime_value
{ typedef Type type; };

/**
Return the type of a compile-time constant or normal type.
Compile-time function.
*/
template <class Type> struct value
: mpl::if_ <is_constant <Type>,
    constant_value <Type>,
    runtime_value <Type>
>::type {};

/**
Return the value of a compile-time constant of normal type.
\return If the parameter is a compile-time constant, Type::value.
    Otherwise, the parameter itself.
*/
template <class Type> inline
    typename boost::enable_if <
        is_constant <Type>, typename value <Type>::type>::type
    get_value (Type const &)
{ return Type::value; }
template <class Type> inline
    typename boost::disable_if <
        is_constant <Type>, Type const &>::type
    get_value (Type const & value)
{ return value; }

namespace detail {

    // Left and Right must be constants
    template <class Left, class Right> struct constant_equals
    : bool_ <(std::decay <Left>::type::value
        == std::decay <Right>::type::value)> {};

    template <class Left, class Right> struct constant_same
    : mpl::if_ <std::is_same <typename constant_value <Left>::type,
            typename constant_value <Right>::type>,
        constant_equals <Left, Right>, false_type>::type {};

    template <class Constant> struct constant_false
    : rime::constant <bool, !bool (Constant::value)> {};

    template <class Constant> struct constant_true
    : rime::constant <bool, bool (Constant::value)> {};

} // namespace detail

/**
Returns true iff both Left and Right are compile-time constants, and their
value types are the same, and their values compare equal.
*/
template <class Left, class Right> struct same_constant
: as_rime_constant <boost::mpl::and_ <is_constant <Left>, is_constant <Right>,
    detail::constant_same <Left, Right>>>::type {};

/**
Returns true iff both Left and Right are compile-time constants, and their
values compare equal.
Note that this does not check whether the values are comparable.
Comparing constants with signed and unsigned integers is therefore possible,
but may yield compiler errors.
*/
template <class Left, class Right> struct equal_constant
: as_rime_constant <boost::mpl::and_ <is_constant <Left>, is_constant <Right>,
    detail::constant_equals <Left, Right>>>::type {};

/** \brief
Evaluate to \c true iff \a Constant is a compile-time constant and it
evaluates to \c false in a boolean context.

E.g. when applied to \c int_<0>, this returns \c true.
*/
template <class Constant> struct is_constant_false
: as_rime_constant <boost::mpl::and_ <is_constant <Constant>,
    detail::constant_false <Constant>>>::type {};

/** \brief
Evaluate to \c true iff \a Constant is a compile-time constant and it
evaluates to \c true in a boolean context.

E.g. when applied to \c int_<5>, this returns \c true.
*/
template <class Constant> struct is_constant_true
: as_rime_constant <boost::mpl::and_ <is_constant <Constant>,
    detail::constant_true <Constant>>>::type {};

namespace merge_policy {

    /**
    Merge two types, special-casing constants.
    If both types are constants, then an attempt is made to unify their value
    types (using merge policy \a Base) and then to unify their values.
    int_ <5> and constant <unsigned, 5> could therefore become
    constant <unsigned, 5> is Base merges int and unsigned to int.
    */
    template <class Base> class constant {
        template <class Type1, class Type2> struct merge_value_type
        : Base::template apply <
            typename rime::value <Type1>::type,
            typename rime::value <Type2>::type> {};

        template <class Type> struct has_type_implementation {
            template <class Contained> struct yes : true_type {};
            struct no : false_type {};

            template <class TypeAgain>
                static yes <typename TypeAgain::type>
                check_has_type (utility::overload_order <1> *);

            template <class TypeAgain>
                static no check_has_type (utility::overload_order <2> *);

            typedef decltype (check_has_type <Type> (utility::pick_overload()))
                answer;
        };

        /**
        Constant with boolean value which is \c true iff \a Type has a type
        member \c type.
        */
        template <class Type> struct has_type
        : has_type_implementation <Type>::answer {};

        /**
        Merge two constants.
        First merge the value types.
        If the values in this merged value type turn out to be the same, return
        a rime::constant.
        If not, return the merged value type.
        */
        template <class Type1, class Type2> struct merge_constant {
            typedef typename merge_value_type <Type1, Type2>::type value_type;
            static const value_type value1 = std::decay <Type1>::type::value;
            static const value_type value2 = std::decay <Type2>::type::value;
            typedef typename std::conditional <(value1 == value2),
                rime::constant <value_type, value1>, value_type>::type type;
        };

        // Law of least surprise: two constants with the exact same type are
        // merged to the same type.
        template <class Type> struct merge_constant <Type, Type>
        { typedef Type type; };

    public:
        template <class Type1, class Type2, class Enable = void> struct apply
        : merge_value_type <Type1, Type2> {};

        // Specialisation only for when both are constants and the value types
        // can be merged.
        // Then, try to turn this into one constant.
        template <class Type1, class Type2>
            struct apply <Type1, Type2, typename boost::enable_if <
                mpl::and_ <is_constant <Type1>, is_constant <Type2>,
                    has_type <merge_value_type <Type1, Type2>>>>::type>
        : merge_constant <Type1, Type2> {};
    };

} // namespace merge_policy

} // namespace rime

#include "detail/operators.hpp"

#endif // RIME_CORE_HPP_INCLUDED

max_stars_repo_name: rogiervd/rime

max_issues_repo_name: rogiervd/rime

max_forks_repo_name: rogiervd/rime


text:
#pragma once

#include "boost_defs.hpp"

#include "configuration_monitor.hpp"
#include "gcd_utility.hpp"
#include "logger.hpp"
#include "system_preferences_utility.hpp"
#include <boost/optional.hpp>

namespace krbn {
class system_preferences_monitor final {
public:
  typedef std::function<void(const system_preferences& value)> system_preferences_updated_callback;

  system_preferences_monitor(const system_preferences_updated_callback& callback,
                             std::weak_ptr<configuration_monitor> configuration_monitor) : callback_(callback),
                                                                                configuration_monitor_(configuration_monitor) {
    timer_ = std::make_unique<gcd_utility::main_queue_timer>(
        dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC),
        3.0 * NSEC_PER_SEC,
        0,
        ^{
          auto v = make_system_preferences();
          if (!system_preferences_ || *system_preferences_ != v) {
            logger::get_logger().info("system_preferences is updated.");

            system_preferences_ = v;
            if (callback_) {
              callback_(*system_preferences_);
            }
          }
        });
  }

  ~system_preferences_monitor(void) {
    timer_ = nullptr;
  }

private:
  system_preferences make_system_preferences(void) const {
    system_preferences system_preferences;

    if (auto configuration_monitor_ptr = configuration_monitor_.lock()) {
      auto core_configuration = configuration_monitor_ptr->get_core_configuration();
      auto country_code = core_configuration->get_selected_profile().get_virtual_hid_keyboard().get_country_code();

      system_preferences.set_keyboard_fn_state(system_preferences_utility::get_keyboard_fn_state());
      system_preferences.set_swipe_scroll_direction(system_preferences_utility::get_swipe_scroll_direction());
      system_preferences.set_keyboard_type(system_preferences_utility::get_keyboard_type(vendor_id(0x16c0),
                                                                                product_id(0x27db),
                                                                                country_code));
    }

    return system_preferences;
  }

  system_preferences_updated_callback callback_;
  std::weak_ptr<configuration_monitor> configuration_monitor_;

  std::unique_ptr<gcd_utility::main_queue_timer> timer_;

  boost::optional<system_preferences> system_preferences_;
};
} // namespace krbn

max_stars_repo_name: rolandwalker/Karabiner-Elements

max_issues_repo_name: rolandwalker/Karabiner-Elements

max_forks_repo_name: rolandwalker/Karabiner-Elements


text: #include <boost/exception/diagnostic_information.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <thread>
#include <vector>
#include <armadillo>
#include "RHF.hpp"
#include "esp.hpp"

//
// Electrostatic Potential (ESP)
// : calculates partial atomic charges that fit
//   the quantum mechanical electrostatic potential on the selected grid points
//

using namespace std;
using namespace libint2;

namespace willow { namespace qcmol {

static unsigned int num_threads;

static void esp_esp (const int thread_id,
		     const vector<Atom>& atoms,
		     const BasisSet& bs,
		     const arma::mat& Dm,
		     const vector<arma::vec3>& grids,
		     arma::vec& results);

ESP::ESP (const vector<Atom>& atoms,
	  const BasisSet& bs,
	  const Integrals& ints,
	  const int qm_chg,
	  const bool l_print,
	  const vector<QAtom>& atoms_Q)
  : RHF (atoms, bs, ints, qm_chg, l_print, atoms_Q)
{

  num_threads = std::thread::hardware_concurrency();

  if (num_threads == 0)
    num_threads = 1;

  const arma::mat Dm = densityMatrix();

  esp_grid (atoms);

  // ---- Thread
  vector<arma::vec>   grid_t(num_threads);
  vector<std::thread> t_esp (num_threads);

  for (auto id = 0; id < num_threads; ++id) {
    t_esp[id] = std::thread (esp_esp, id,
			     std::cref(atoms),
			     std::cref(bs),
			     std::cref(Dm),
			     std::cref(m_grids),
			     std::ref(grid_t[id]));
  }

  // Join
  for (auto id = 0; id < num_threads; ++id) {
    t_esp[id].join();
  }

  m_grids_val = grid_t[0];

  for (auto id = 1; id < num_threads; ++id) {
    m_grids_val += grid_t[id];
  }
  //---- (done: Thread) ---

  m_qf = esp_fit (atoms);

  if (l_print) {
    for (auto i = 0; i < atoms.size(); i++)
      cout << "ESP " << i+1 << "  " << m_qf(i) << endl;
  }

}

void esp_esp (const int thread_id,
	      const vector<Atom>& atoms,
	      const BasisSet& bs,
	      const arma::mat& Dm,
	      const vector<arma::vec3>& grids,
	      arma::vec& result)
{

  const auto nsize   = grids.size();

  result = arma::vec(nsize, arma::fill::zeros);

  const auto nshells = bs.size();
  const auto nbf     = bs.nbf();

  libint2::Engine engine (libint2::Operator::nuclear,
			  bs.max_nprim(),
			  bs.max_l(),
			  0);

  const auto& buf = engine.results();

  const auto shell2bf = bs.shell2bf ();

  arma::mat Vm(nbf,nbf);

  for (auto ig = 0; ig < grids.size(); ++ig) {

    if (ig % num_threads != thread_id) continue;

    const auto xg = grids[ig](0);
    const auto yg = grids[ig](1);
    const auto zg = grids[ig](2);

    // Interaction with electron density
    vector<pair<double,array<double,3>>> q;
    q.push_back ( {1.0, {{xg, yg, zg}}} );

    engine.set_params (q);

    // calc Vm
    Vm.zeros();

    for (auto s1 = 0; s1 != nshells; ++s1) {
      auto bf1 = shell2bf[s1];
      auto nbf1 = bs[s1].size();

      for (auto s2 = 0; s2 != nshells; ++s2) {
	auto bf2 = shell2bf[s2];
	auto nbf2 = bs[s2].size();

	engine.compute (bs[s1], bs[s2]);
	const auto* buf0 = buf[0];

	for (auto ib = 0, ij = 0; ib < nbf1; ib++) {
	  for (auto jb = 0; jb < nbf2; jb++, ij++) {
	    const double val = buf0[ij];
	    Vm(bf1+ib,bf2+jb) = val;
	    Vm(bf2+jb,bf1+ib) = val;
	  }
	} // ib

      } // s2
    }  // s1

    //
    // get electrostatic potential on the grid points
    // -- from electron density
    double gval = 0.0;

    for (auto i = 0; i < nbf; i++)
      for (auto j = 0; j < nbf; j++)
	gval += Dm(i,j)*Vm(i,j);

    // get electrostatic potential on the grid points
    // -- from nuclei
    auto zval = 0.0;

    for (auto ia = 0; ia < atoms.size(); ++ia) {
      auto xij = atoms[ia].x - xg;
      auto yij = atoms[ia].y - yg;
      auto zij = atoms[ia].z - zg;
      auto r2  = xij*xij + yij*yij + zij*zij;
      auto r   = sqrt(r2);
      zval += static_cast<double>(atoms[ia].atomic_number)/r;
    }

    result(ig) = gval + zval;
  }

}

arma::vec ESP::esp_fit (const vector<Atom>& atoms)
{

  // set up matrix of linear coefficients
  auto natoms = atoms.size();
  auto ndim   = natoms+1;

  arma::mat am(ndim,ndim);
  arma::vec bv(ndim);

  am.zeros();
  bv.zeros();

  for (auto i = 0; i < atoms.size(); ++i) {
    auto xi = atoms[i].x;
    auto yi = atoms[i].y;
    auto zi = atoms[i].z;

    for (auto j = i; j < atoms.size(); ++j) {
      auto xj = atoms[j].x;
      auto yj = atoms[j].y;
      auto zj = atoms[j].z;

      auto sum = 0.0;

      for (auto k = 0; k < m_grids.size(); ++k) {
	auto xg = m_grids[k](0);
	auto yg = m_grids[k](1);
	auto zg = m_grids[k](2);

	auto rig2 = (xi-xg)*(xi-xg) + (yi-yg)*(yi-yg) + (zi-zg)*(zi-zg);
	auto rjg2 = (xj-xg)*(xj-xg) + (yj-yg)*(yj-yg) + (zj-zg)*(zj-zg);

	sum += 1.0/sqrt(rig2*rjg2);
      }

      am(i,j) = sum;
      am(j,i) = sum;
    }

    am(i,natoms) = 1.0;
    am(natoms,i) = 1.0;
  }

  // construct column vector b

  for (auto i = 0; i < atoms.size(); ++i) {
    auto xi = atoms[i].x;
    auto yi = atoms[i].y;
    auto zi = atoms[i].z;

    auto sum = 0.0;
    for (auto k = 0; k < m_grids.size(); ++k) {
      auto xg = m_grids[k](0);
      auto yg = m_grids[k](1);
      auto zg = m_grids[k](2);
      auto val = m_grids_val(k);

      auto rig2 = (xi-xg)*(xi-xg) + (yi-yg)*(yi-yg) + (zi-zg)*(zi-zg);

      sum += val/sqrt(rig2);
    }
    bv(i) = sum;
  }
  bv(natoms) = 0.0; // b(natoms) = charge;

  arma::mat am_inv = am.i();

  arma::vec qf(natoms);
  qf.zeros();

  for (auto i = 0; i < natoms; ++i) {
    auto sum = 0.0;

    for (auto j = 0; j < ndim; ++j) {
    //for (auto j = 0; j < atoms.size(); ++j) {
      sum = sum + am_inv(i,j)*bv(j);
    }
    qf(i) = sum;
    //cout << " qf " << sum << endl;
  }

  return qf;

}

void ESP::esp_grid (const vector<Atom>& atoms)
{

  vector<double> radius(11);

  // A
  radius[0] = 0.0; // Ghost
  radius[1] = 0.3; // H
  radius[2] = 1.22;// He
  radius[3] = 1.23;// Li
  radius[4] = 0.89; // Be
  radius[5] = 0.88; // B
  radius[6] = 0.77; // C
  radius[7] = 0.70; // N
  radius[8] = 0.66; // O
  radius[9] = 0.58; // F
  radius[10]= 1.60; // Ne

  for (auto i = 1; i <= 10; i++) {
    radius[i] = (radius[i] + 0.7)*ang2bohr;
  }
  double grd_min_x = atoms[0].x;
  double grd_min_y = atoms[0].y;
  double grd_min_z = atoms[0].z;

  double grd_max_x = atoms[0].x;
  double grd_max_y = atoms[0].y;
  double grd_max_z = atoms[0].z;

  for (auto ia = 1; ia < atoms.size(); ++ia) {

    grd_min_x = min(grd_min_x, atoms[ia].x);
    grd_min_y = min(grd_min_y, atoms[ia].y);
    grd_min_z = min(grd_min_z, atoms[ia].z);

    grd_max_x = max(grd_max_x, atoms[ia].x);
    grd_max_y = max(grd_max_y, atoms[ia].y);
    grd_max_z = max(grd_max_z, atoms[ia].z);

  }
  //
  // calculate the grid size
  //
  // A --> au
  const double rcut = 3.0*ang2bohr;
  const double rcut2= rcut*rcut;
  const double spac = 0.5*ang2bohr;

  const int ngrid_x = int ((grd_max_x - grd_min_x + 2.0*rcut)/spac) + 1;
  const int ngrid_y = int ((grd_max_y - grd_min_y + 2.0*rcut)/spac) + 1;
  const int ngrid_z = int ((grd_max_z - grd_min_z + 2.0*rcut)/spac) + 1;

  const auto small = 1.0e-8;
  arma::vec3 vg;

  for(auto iz = 0; iz <  ngrid_z; ++iz)
    for(auto iy = 0; iy <  ngrid_y; ++iy)
      for(auto ix = 0; ix <  ngrid_x; ++ix) {

	vg.zeros();

	vg(0) = grd_min_x - rcut + ix*spac;
	vg(1) = grd_min_y - rcut + iy*spac;
	vg(2) = grd_min_z - rcut + iz*spac;

	double dmin = rcut2;

	bool lupdate = true;

	for (auto ia = 0; ia < atoms.size(); ++ia) {
	  int iz    = atoms[ia].atomic_number;
	  auto rad2 = radius[iz]*radius[iz];

	  auto dx = vg(0) - atoms[ia].x;
	  auto dy = vg(1) - atoms[ia].y;
	  auto dz = vg(2) - atoms[ia].z;

	  auto d2  = dx*dx + dy*dy + dz*dz;

	  if ( (rad2 - d2) > small) {
	    lupdate = false;
	    break;
	  }

	  if ( (dmin-d2) > small) dmin = d2;

	}

	if (lupdate) {
	  if ( (rcut2 - dmin) > small) {
	    m_grids.push_back (vg);
	  }
	}

      }

}

} } // namespace willow::qcmol

ext: cc

max_stars_repo_name: swillow/w-qcmol

max_issues_repo_name: swillow/w-qcmol

max_forks_repo_name: swillow/w-qcmol


text:
#include <boost/test/unit_test.hpp>
#include "InductsConfig.h"
#include <boost/make_shared.hpp>
#include "Environment.h"
#include <boost/algorithm/string.hpp>

BOOST_AUTO_TEST_CASE(InductsConfigTestCase)
{
    const boost::filesystem::path jsonRootDir = Environment::GetPathHdtnSourceRoot() / "common" / "config" / "test";
    const std::string jsonFileName = (jsonRootDir / "inducts.json").string();
    InductsConfig_ptr ic1 = InductsConfig::CreateFromJsonFile(jsonFileName);
    BOOST_REQUIRE(ic1);
    const std::string newJson = boost::trim_copy(ic1->ToJson());
    InductsConfig_ptr ic2 = InductsConfig::CreateFromJson(newJson);
    BOOST_REQUIRE(ic2);
    BOOST_REQUIRE(*ic2 == *ic1);

    std::ifstream ifs(jsonFileName);

    BOOST_REQUIRE(ifs.good());

    // get length of file:
    ifs.seekg(0, ifs.end);
    std::size_t length = ifs.tellg();
    ifs.seekg(0, ifs.beg);
    std::string jsonFileContentsInMemory(length, ' ');
    ifs.read(&jsonFileContentsInMemory[0], length);
    boost::trim(jsonFileContentsInMemory);

    ifs.close();

    BOOST_REQUIRE_EQUAL(jsonFileContentsInMemory, newJson);

}


text:
#include <cstdlib>
#include <cmath>

#include <boost/assert.hpp>
#include <boost/foreach.hpp>

#include "TrackReconstructionHook.hpp"

TrackReconstructionHook::TrackReconstructionHook(
	Geometry &g,
	StdHits::calibration_curve_t *c
	)
	: StdHits(g, c),
	  geom(g)
{
	// nothing
}

void	TrackReconstructionHook::handle_event_start()
{
	StdHits::handle_event_start();

	BOOST_FOREACH(auto gr_tup, last_tracks)
	{
		BOOST_FOREACH(auto axis_tup, gr_tup.second)
		{
			axis_tup.second.clear();
		}
	}
}

void	TrackReconstructionHook::handle_event_end()
{
	StdHits::handle_event_end();

	vector< vector<wire_pos_t>* >	block;

	BOOST_FOREACH(auto &gr_tup, geom.group_chambers)
	{
		group_id_t	group_id = gr_tup.first;
		device_type_t	device_type = geom.group_device_type[group_id];
		double	max_chisq = geom.group_max_chisq[group_id];

		BOOST_FOREACH(auto &axis_tup, gr_tup.second)
		{
			device_axis_t	axis = axis_tup.first;
			const vector<chamber_id_t>	&chambers = axis_tup.second;

			block.clear();

			BOOST_FOREACH(chamber_id_t chamber_id, chambers)
			{
				block.push_back(&last_event[chamber_id]);
			}

			vector<double>	&normal_pos = geom.normal_pos[group_id][axis];

			if ((device_type == DEV_TYPE_PROP) ||
			    ((device_type == DEV_TYPE_DRIFT) && (calibration_curve == NULL)))
			{
				last_tracks[group_id][axis] = reconstruct_all_tracks<track_type_t::prop>(block, normal_pos, max_chisq);
			}
			else if (device_type == DEV_TYPE_DRIFT)
			{
				last_tracks[group_id][axis] = reconstruct_all_tracks<track_type_t::drift>(block, normal_pos, max_chisq);
			}
			else
			{
				throw "Invalid dev type";
			}
		}
	}
}

max_stars_repo_name: veprbl/libepecur

max_issues_repo_name: veprbl/libepecur

max_forks_repo_name: veprbl/libepecur


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2019-2021 The SorachanCoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <util/thread.h>
#include <util/logging.h>
#include <util/exception.h>
#include <boost/thread.hpp>

template <typename Callable>
static void TraceThread(const char *name, Callable func) {
    std::string s = tfm::format("SorachanCoin-%s", name);
    bitthread::RenameThread(s.c_str());
    try {
        logging::LogPrintf("%s thread start\n", name);
        func();
        logging::LogPrintf("%s thread exit\n", name);
    } catch (const boost::thread_interrupted &) {
        logging::LogPrintf("%s thread interrupt\n", name);
        throw;
    } catch (const std::exception &e) {
        excep::PrintExceptionContinue(&e, name);
        throw;
    } catch (...) {
        excep::PrintExceptionContinue(nullptr, name);
        throw;
    }
}

template <typename Callable>
static void TraceThread2(Callable func) {
    try {
        debugcs::instance() << "thread start" << debugcs::endl();
        func();
        debugcs::instance() << "thread exit" << debugcs::endl();
    } catch (const boost::thread_interrupted &) {
        debugcs::instance() << "thread interrupt" << debugcs::endl();
        throw;
    } catch (const std::exception &e) {
        excep::PrintExceptionContinue(&e, "");
        throw;
    } catch (...) {
        excep::PrintExceptionContinue(nullptr, "");
        throw;
    }
}

void bitthread::thread_error(const std::string &e) noexcept {
    std::string err(e);
    err += " :thread_error";
    logging::LogPrintf(err.c_str());
}

bool bitthread::NewThread(void(*pfn)(void *), void *parg) noexcept {
    try {
        boost::thread(pfn, parg); // thread detaches when out of scope
    } catch (boost::thread_resource_error &e) {
        logging::LogPrintf("Error creating thread: %s\n", e.what());
        return false;
    }
    return true;
}


text:
//
// Copyright (c) 2019 Vinnie Falco (vinnie.falco@gmail.com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_DETAIL_CONFIG_HPP
#define BOOST_HTTP_PROTO_DETAIL_CONFIG_HPP

#include <boost/config.hpp>

namespace boost {

namespace http_proto {

#if defined(BOOST_HTTP_PROTO_DOCS)
# define BOOST_HTTP_PROTO_DECL
# define BOOST_HTTP_PROTO_PROTECTED private
#else
# define BOOST_HTTP_PROTO_PROTECTED protected
# if (defined(BOOST_HTTP_PROTO_DYN_LINK) || defined(BOOST_ALL_DYN_LINK)) && !defined(BOOST_HTTP_PROTO_STATIC_LINK)
#  if defined(BOOST_HTTP_PROTO_SOURCE)
#   define BOOST_HTTP_PROTO_DECL        BOOST_SYMBOL_EXPORT
#   define BOOST_HTTP_PROTO_CLASS_DECL  BOOST_SYMBOL_EXPORT
#   define BOOST_HTTP_PROTO_BUILD_DLL
#  else
#   define BOOST_HTTP_PROTO_DECL        BOOST_SYMBOL_IMPORT
#   define BOOST_HTTP_PROTO_CLASS_DECL  BOOST_SYMBOL_IMPORT
#  endif
# endif // shared lib
# ifndef  BOOST_HTTP_PROTO_DECL
#  define BOOST_HTTP_PROTO_DECL
# endif
# if !defined(BOOST_HTTP_PROTO_SOURCE) && !defined(BOOST_ALL_NO_LIB) && !defined(BOOST_HTTP_PROTO_NO_LIB)
#  define BOOST_LIB_NAME boost_json
#  if defined(BOOST_ALL_DYN_LINK) || defined(BOOST_HTTP_PROTO_DYN_LINK)
#   define BOOST_DYN_LINK
#  endif
#  include <boost/config/auto_link.hpp>
# endif
#endif

} // http_proto

#if 1
// lift bnf into our namespace
namespace urls { namespace grammar {} }
namespace http_proto {
namespace grammar = ::boost::urls::grammar;
} // http_proto
#endif

} // boost

#endif


text:
/**
 * Copyright (c) 2021 Nobuo Tsukamoto
 *
 * This software is released under the MIT License.
 * See the LICENSE file in the project root for more information.
 */

#include <fstream>
#include <iostream>
#include <map>

#include <opencv2/opencv.hpp>

#include <boost/algorithm/string.hpp>

#include "object_detector.h"

const cv::String kKeys =
    "{help h usage ? |    | show help command.}"
    "{s score        |0.5 | score threshold.}"
    "{w width        |512 | input model width.}"
    "{H height       |512 | input model height.}"
    "{l label        |.   | path to label file.}"
    "{@input         |    | path to trt engine file.}"
    "{@image         |    | path to image engine file.}"
    ;

const cv::Scalar kWhiteColor = cv::Scalar(246, 250, 250);
const cv::Scalar kBuleColor = cv::Scalar(255, 209, 0);

std::unique_ptr<std::map<long, std::string>> ReadLabelFile(const std::string& label_path)
{
    auto labels = std::make_unique<std::map<long, std::string>>();

    std::ifstream ifs(label_path);
    if (ifs.is_open())
    {
        std::string label = "";
        while (std::getline(ifs, label))
        {
            std::vector<std::string> result;

            boost::algorithm::split(result, label, boost::is_any_of(" ")); // Split by space.
            if (result.size() < 2)
            {
                std::cout << "Expect 2-D input label (" << result.size() << ")." << std::endl;
                continue;
            }

            auto label_string = result[2];
            for (size_t i = 3; i < result.size(); i++)
            {
                label_string += " " + result[i];
            }
            auto id = std::stol(result[0]);
            labels->insert(std::make_pair(id, label_string));
        }
    }
    else
    {
        std::cout << "Label file not found. : " << label_path << std::endl;
    }
    return labels;
}

void DrawCaption(
    cv::Mat& im,
    const cv::Point& point,
    const std::string& caption)
{
    cv::putText(im, caption, point, cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(0, 0, 0), 2);
    cv::putText(im, caption, point, cv::FONT_HERSHEY_SIMPLEX, 0.8, cv::Scalar(255, 255, 255), 1);
}

int main(int argc, char* argv[]) try
{
    // Argument parsing
    cv::String model_path;
    cv::String image_path;
    cv::CommandLineParser parser(argc, argv, kKeys);
    if (parser.has("h"))
    {
        parser.printMessage();
        return 0;
    }
    auto input_width = parser.get<int>("width");
    auto input_height = parser.get<int>("height");
    auto score_threshold = parser.get<float>("score");
    auto label_path = parser.get<cv::String>("label");
    if (parser.has("@input"))
    {
        model_path = parser.get<cv::String>("@input");
    }
    else
    {
        std::cout << "No model file path." << std::endl;
        return 0;
    }
    if (parser.has("@image"))
    {
        image_path = parser.get<cv::String>("@image");
    }
    else
    {
        std::cout << "No image file path." << std::endl;
        return 0;
    }
    if (!parser.check()) {
        parser.printErrors();
        return 1;
    }
    std::cout << "model path      : " << model_path << std::endl;
    std::cout << "image path      : " << image_path << std::endl;
    std::cout << "label path      : " << label_path << std::endl;
    std::cout << "input width     : " << input_width << std::endl;
    std::cout << "input height    : " << input_height << std::endl;
    std::cout << "score threshold : " << score_threshold << std::endl;

    // Create Object detector
    auto detector = std::make_unique<ObjectDetector>(input_width, input_height, score_threshold);

    detector->LoadEngine(model_path);
    auto width = detector->Width();
    auto height = detector->Height();

    // Load label file
    auto labels = ReadLabelFile(label_path);

    // Load image
    cv::Mat frame, input_im;
    frame = cv::imread(image_path);
    int cap_width = frame.cols;
    int cap_height = frame.rows;
    auto scale_width = (double)cap_width / input_width;
    auto scale_height = (double)cap_height / input_height;

    std::cout << "scale width  : " << scale_width << std::endl;
    std::cout << "scale height : " << scale_height << std::endl;

    // Run inference.
    std::chrono::duration<double, std::milli> inference_time_span;

    const auto& result = detector->RunInference(frame, inference_time_span);

    cv::resize(frame, frame, cv::Size(input_width, input_height));
    for (const auto& object : *result)
    {
        /*
        auto x = int(object.x * cap_width / input_width);
        auto y = int(object.y * cap_height / input_heigth);
        auto w = int(object.width * cap_width / input_width);
        auto h = int(object.height * cap_height / input_heigth);
        */
        auto x = int(object.x * scale_width);
        auto y = int(object.y * scale_height);
        auto w = int(object.width * scale_width);
        auto h = int(object.height * scale_height);

        // Draw bounding box
        cv::rectangle(frame, cv::Rect(x, y, w, h), kBuleColor, 2);

        // Draw Caption
        std::ostringstream caption;

        auto it = labels->find(object.class_id);
        if (it != std::end(*labels))
        {
            caption << it->second;
        }
        else
        {
            caption << "ID: " << std::to_string(object.class_id);
        }
        caption << "(" << std::fixed << std::setprecision(2) << object.scores << ")";
        DrawCaption(frame, cv::Point(x, y), caption.str());
    }

    // Calc fps and draw fps and inference time.
    std::ostringstream time_caption;

    time_caption << std::fixed << std::setprecision(2) << inference_time_span.count() << " ms";
    DrawCaption(frame, cv::Point(10, 60), time_caption.str());

    // Output Image
    cv::imwrite("output.png", frame);

    return EXIT_SUCCESS;

}
catch (const cv::Exception& e)
{
    std::cerr << "OpenCV error calling :\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch (const std::exception& e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}

max_stars_repo_name: NobuoTsukamoto/tensorrt-examples

max_issues_repo_name: NobuoTsukamoto/tensorrt-examples

max_forks_repo_name: NobuoTsukamoto/tensorrt-examples


text:
#include <string>
#include <vector>

#include "mjolnir/graphvalidator.h"
#include "mjolnir/pbfgraphparser.h"
#include "mjolnir/graphbuilder.h"
#include "mjolnir/transitbuilder.h"
#include "mjolnir/graphenhancer.h"
#include "mjolnir/hierarchybuilder.h"
#include "mjolnir/shortcutbuilder.h"
#include "mjolnir/restrictionbuilder.h"
#include "baldr/tilehierarchy.h"
#include "config.h"

using namespace valhalla::mjolnir;

#include <ostream>
#include <boost/program_options.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/optional.hpp>

#include "midgard/point2.h"
#include "midgard/aabb2.h"
#include "midgard/polyline2.h"
#include "midgard/logging.h"

namespace bpo = boost::program_options;

int main(int argc, char** argv) {
  // Program options
  boost::filesystem::path config_file_path;
  std::vector<std::string> input_files;
  bpo::options_description options(
    "valhalla_build_tiles " VERSION "\n\n"
    "Usage: valhalla_build_tiles [options] <protocolbuffer_input_file>\n\n"
    "valhalla_build_tiles is a program that creates the route graph from an osm.pbf "
    "extract. Sample json configs are located in ../conf directory.\n\n");

  options.add_options()
      ("help,h", "Print this help message.")
      ("version,v", "Print the version of this software.")
      ("config,c",
        boost::program_options::value<boost::filesystem::path>(&config_file_path),
        "Path to the json configuration file.")
      // positional arguments
      ("input_files", boost::program_options::value<std::vector<std::string> >(&input_files)->multitoken());

  bpo::positional_options_description pos_options;
  pos_options.add("input_files", 16);
  bpo::variables_map vm;
  try {
    bpo::store(bpo::command_line_parser(argc, argv).options(options).positional(pos_options).run(), vm);
    bpo::notify(vm);

  } catch (std::exception &e) {
    std::cerr << "Unable to parse command line options because: " << e.what() << "\n";
    return EXIT_FAILURE;
  }

  // Print out help or version and return
  if (vm.count("help")) {
    std::cout << options << "\n";
    return EXIT_SUCCESS;
  }
  if (vm.count("version")) {
    std::cout << "valhalla_build_tiles " << VERSION << "\n";
    return EXIT_SUCCESS;
  }

  // Exit if no config file or no input pbf files
  if (!vm.count("config") || !boost::filesystem::is_regular_file(config_file_path)) {
    std::cerr << "Configuration file is required\n\n" << options << "\n\n";
    return EXIT_FAILURE;
  }
  if (input_files.size() == 0) {
    std::cerr << "Input file is required\n\n" << options << "\n\n";
    return EXIT_FAILURE;
  }

  // Read the config file
  boost::property_tree::ptree pt;
  boost::property_tree::read_json(config_file_path.c_str(), pt);

  //configure logging
  boost::optional<boost::property_tree::ptree&> logging_subtree = pt.get_child_optional("mjolnir.logging");
  if(logging_subtree) {
    auto logging_config = valhalla::midgard::ToMap<const boost::property_tree::ptree&, std::unordered_map<std::string, std::string> >(logging_subtree.get());
    valhalla::midgard::logging::Configure(logging_config);
  }

  //set up the directories and purge old tiles
  pt.get_child("mjolnir").erase("tile_extract");
  auto tile_dir = pt.get<std::string>("mjolnir.tile_dir");
  for(const auto& level : valhalla::baldr::TileHierarchy::levels()) {
    auto level_dir = tile_dir + "/" + std::to_string(level.first);
    if(boost::filesystem::exists(level_dir) && !boost::filesystem::is_empty(level_dir)) {
      LOG_WARN("Non-empty " + level_dir + " will be purged of tiles");
      boost::filesystem::remove_all(level_dir);
    }
  }

  //check for transit level.
  auto level_dir = tile_dir + "/" +
      std::to_string(valhalla::baldr::TileHierarchy::levels().rbegin()->second.level+1);
  if(boost::filesystem::exists(level_dir) && !boost::filesystem::is_empty(level_dir)) {
    LOG_WARN("Non-empty " + level_dir + " will be purged of tiles");
    boost::filesystem::remove_all(level_dir);
  }

  boost::filesystem::create_directories(tile_dir);

  // Read the OSM protocol buffer file. Callbacks for nodes, ways, and
  // relations are defined within the PBFParser class
  auto osm_data = PBFGraphParser::Parse(pt.get_child("mjolnir"), input_files, "ways.bin",
                                        "way_nodes.bin", "access.bin", "complex_restrictions.bin");

  // Build the graph using the OSMNodes and OSMWays from the parser
  GraphBuilder::Build(pt, osm_data, "ways.bin", "way_nodes.bin", "complex_restrictions.bin");

  // Enhance the local level of the graph. This adds information to the local
  // level that is usable across all levels (density, administrative
  // information (and country based attribution), edge transition logic, etc.
  GraphEnhancer::Enhance(pt, "access.bin");

  // Add transit
  TransitBuilder::Build(pt);

  // Builds additional hierarchies based on the config file. Connections
  // (directed edges) are formed between nodes at adjacent levels.
  HierarchyBuilder::Build(pt);

  // Build shortcuts
  ShortcutBuilder::Build(pt);

  // Build the Complex Restrictions
  RestrictionBuilder::Build(pt,"complex_restrictions.bin", osm_data.end_map);

  // Validate the graph and add information that cannot be added until
  // full graph is formed.
  GraphValidator::Validate(pt);

  return EXIT_SUCCESS;
}

max_stars_repo_name: molind/valhalla

max_issues_repo_name: molind/valhalla

max_forks_repo_name: molind/valhalla


text:
// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-fcl.
// hpp-fcl is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-fcl is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-fcl. If not, see <http://www.gnu.org/licenses/>.

#include <boost/filesystem.hpp>

#include <hpp/fcl/internal/traversal_node_setup.h>
#include <hpp/fcl/internal/traversal_node_bvhs.h>
#include "../src/collision_node.h"
#include <hpp/fcl/internal/BV_splitter.h>

#include "utility.h"
#include "fcl_resources/config.h"

#define RUN_CASE(BV,tf,models,split) \
  run<BV>(tf, models, split, #BV " - " #split ":\t")

using namespace hpp::fcl;

bool verbose = false;
FCL_REAL DELTA = 0.001;

template<typename BV>
void makeModel (const std::vector<Vec3f>& vertices, const std::vector<Triangle>& triangles,
    SplitMethodType split_method, BVHModel<BV>& model);

template<typename BV, typename TraversalNode>
double distance (const std::vector<Transform3f>& tf,
               const BVHModel<BV>& m1, const BVHModel<BV>& m2,
               bool verbose);

template<typename BV, typename TraversalNode>
double collide (const std::vector<Transform3f>& tf,
               const BVHModel<BV>& m1, const BVHModel<BV>& m2,
               bool verbose);

template<typename BV>
double run (const std::vector<Transform3f>& tf,
    const BVHModel<BV> (&models)[2][3], int split_method,
          const char* sm_name);

template <typename BV> struct traits {
};

template <> struct traits <RSS> {
  typedef MeshCollisionTraversalNodeRSS CollisionTraversalNode;
  typedef MeshDistanceTraversalNodeRSS  DistanceTraversalNode;
};

template <> struct traits <kIOS> {
  typedef MeshCollisionTraversalNodekIOS CollisionTraversalNode;
  typedef MeshDistanceTraversalNodekIOS  DistanceTraversalNode;
};

template <> struct traits <OBB> {
  typedef MeshCollisionTraversalNodeOBB CollisionTraversalNode;
  // typedef MeshDistanceTraversalNodeOBB  DistanceTraversalNode;
};

template <> struct traits <OBBRSS> {
  typedef MeshCollisionTraversalNodeOBBRSS CollisionTraversalNode;
  typedef MeshDistanceTraversalNodeOBBRSS  DistanceTraversalNode;
};

template<typename BV>
void makeModel (const std::vector<Vec3f>& vertices, const std::vector<Triangle>& triangles,
    SplitMethodType split_method, BVHModel<BV>& model)
{
  model.bv_splitter.reset(new BVSplitter<BV>(split_method));
  model.bv_splitter.reset(new BVSplitter<BV>(split_method));

  model.beginModel();
  model.addSubModel(vertices, triangles);
  model.endModel();
}

template<typename BV, typename TraversalNode>
double distance (const std::vector<Transform3f>& tf,
               const BVHModel<BV>& m1, const BVHModel<BV>& m2,
               bool verbose)
{
  Transform3f pose2;

  DistanceResult local_result;
  DistanceRequest request(true);
  TraversalNode node;

  node.enable_statistics = verbose;

  BenchTimer timer;
  timer.start();

  for (std::size_t i = 0; i < tf.size(); ++i) {
    if(!initialize(node, m1, tf[i], m2, pose2, request, local_result))
      std::cout << "initialize error" << std::endl;

    distance(&node, NULL);
  }
  timer.stop();
  return timer.getElapsedTimeInMicroSec();
}

template<typename BV, typename TraversalNode>
double collide (const std::vector<Transform3f>& tf,
               const BVHModel<BV>& m1, const BVHModel<BV>& m2,
               bool verbose)
{
  Transform3f pose2;

  CollisionResult local_result;
  CollisionRequest request;
  TraversalNode node (request);

  node.enable_statistics = verbose;

  BenchTimer timer;
  timer.start();

  for (std::size_t i = 0; i < tf.size(); ++i) {
    bool success (initialize(node, m1, tf[i], m2, pose2, local_result));
    (void)success;
    assert (success);

    CollisionResult result;
    collide(&node, request, result);
  }

  timer.stop();
  return timer.getElapsedTimeInMicroSec();
}

template<typename BV>
double run (const std::vector<Transform3f>& tf,
          const BVHModel<BV> (&models)[2][3], int split_method,
          const char* prefix)
{
  double col  = collide <BV, typename traits<BV>::CollisionTraversalNode>
    (tf, models[0][split_method], models[1][split_method], verbose);
  double dist = distance<BV, typename traits<BV>::DistanceTraversalNode>
    (tf, models[0][split_method], models[1][split_method], verbose);

  std::cout << prefix << " (" << col << ", " << dist << ")\n";
  return col + dist;
}

template<>
double run<OBB> (const std::vector<Transform3f>& tf,
                 const BVHModel<OBB> (&models)[2][3], int split_method,
                 const char* prefix)
{
  double col  = collide <OBB,traits<OBB>::CollisionTraversalNode>
    (tf, models[0][split_method], models[1][split_method], verbose);
  double dist = 0;

  std::cout << prefix << " (\t" << col << ", \tNaN)\n";
  return col + dist;
}

int main (int, char*[])
{
  std::vector<Vec3f> p1, p2;
  std::vector<Triangle> t1, t2;
  boost::filesystem::path path(TEST_RESOURCES_DIR);
  loadOBJFile((path / "env.obj").string().c_str(), p1, t1);
  loadOBJFile((path / "rob.obj").string().c_str(), p2, t2);

  // Make models
  BVHModel<RSS> ms_rss[2][3];
  makeModel (p1, t1, SPLIT_METHOD_MEAN     , ms_rss[0][SPLIT_METHOD_MEAN     ]);
  makeModel (p1, t1, SPLIT_METHOD_BV_CENTER, ms_rss[0][SPLIT_METHOD_BV_CENTER]);
  makeModel (p1, t1, SPLIT_METHOD_MEDIAN   , ms_rss[0][SPLIT_METHOD_MEDIAN   ]);
  makeModel (p2, t2, SPLIT_METHOD_MEAN     , ms_rss[1][SPLIT_METHOD_MEAN     ]);
  makeModel (p2, t2, SPLIT_METHOD_BV_CENTER, ms_rss[1][SPLIT_METHOD_BV_CENTER]);
  makeModel (p2, t2, SPLIT_METHOD_MEDIAN   , ms_rss[1][SPLIT_METHOD_MEDIAN   ]);

  BVHModel<kIOS> ms_kios[2][3];
  makeModel (p1, t1, SPLIT_METHOD_MEAN     , ms_kios[0][SPLIT_METHOD_MEAN     ]);
  makeModel (p1, t1, SPLIT_METHOD_BV_CENTER, ms_kios[0][SPLIT_METHOD_BV_CENTER]);
  makeModel (p1, t1, SPLIT_METHOD_MEDIAN   , ms_kios[0][SPLIT_METHOD_MEDIAN   ]);
  makeModel (p2, t2, SPLIT_METHOD_MEAN     , ms_kios[1][SPLIT_METHOD_MEAN     ]);
  makeModel (p2, t2, SPLIT_METHOD_BV_CENTER, ms_kios[1][SPLIT_METHOD_BV_CENTER]);
  makeModel (p2, t2, SPLIT_METHOD_MEDIAN   , ms_kios[1][SPLIT_METHOD_MEDIAN   ]);

  BVHModel<OBB> ms_obb[2][3];
  makeModel (p1, t1, SPLIT_METHOD_MEAN     , ms_obb[0][SPLIT_METHOD_MEAN     ]);
  makeModel (p1, t1, SPLIT_METHOD_BV_CENTER, ms_obb[0][SPLIT_METHOD_BV_CENTER]);
  makeModel (p1, t1, SPLIT_METHOD_MEDIAN   , ms_obb[0][SPLIT_METHOD_MEDIAN   ]);
  makeModel (p2, t2, SPLIT_METHOD_MEAN     , ms_obb[1][SPLIT_METHOD_MEAN     ]);
  makeModel (p2, t2, SPLIT_METHOD_BV_CENTER, ms_obb[1][SPLIT_METHOD_BV_CENTER]);
  makeModel (p2, t2, SPLIT_METHOD_MEDIAN   , ms_obb[1][SPLIT_METHOD_MEDIAN   ]);

  BVHModel<OBBRSS> ms_obbrss[2][3];
  makeModel (p1, t1, SPLIT_METHOD_MEAN     , ms_obbrss[0][SPLIT_METHOD_MEAN     ]);
  makeModel (p1, t1, SPLIT_METHOD_BV_CENTER, ms_obbrss[0][SPLIT_METHOD_BV_CENTER]);
  makeModel (p1, t1, SPLIT_METHOD_MEDIAN   , ms_obbrss[0][SPLIT_METHOD_MEDIAN   ]);
  makeModel (p2, t2, SPLIT_METHOD_MEAN     , ms_obbrss[1][SPLIT_METHOD_MEAN     ]);
  makeModel (p2, t2, SPLIT_METHOD_BV_CENTER, ms_obbrss[1][SPLIT_METHOD_BV_CENTER]);
  makeModel (p2, t2, SPLIT_METHOD_MEDIAN   , ms_obbrss[1][SPLIT_METHOD_MEDIAN   ]);

  std::vector<Transform3f> transforms; // t0
  FCL_REAL extents[] = {-3000, -3000, -3000, 3000, 3000, 3000};
  std::size_t n = 10000;

  generateRandomTransforms(extents, transforms, n);
  double total_time = 0;

  total_time += RUN_CASE(RSS, transforms, ms_rss, SPLIT_METHOD_MEAN);
  total_time += RUN_CASE(RSS, transforms, ms_rss, SPLIT_METHOD_BV_CENTER);
  total_time += RUN_CASE(RSS, transforms, ms_rss, SPLIT_METHOD_MEDIAN);

  total_time += RUN_CASE(kIOS, transforms, ms_kios, SPLIT_METHOD_MEAN);
  total_time += RUN_CASE(kIOS, transforms, ms_kios, SPLIT_METHOD_BV_CENTER);
  total_time += RUN_CASE(kIOS, transforms, ms_kios, SPLIT_METHOD_MEDIAN);

  total_time += RUN_CASE(OBB, transforms, ms_obb, SPLIT_METHOD_MEAN);
  total_time += RUN_CASE(OBB, transforms, ms_obb, SPLIT_METHOD_BV_CENTER);
  total_time += RUN_CASE(OBB, transforms, ms_obb, SPLIT_METHOD_MEDIAN);

  total_time += RUN_CASE(OBBRSS, transforms, ms_obbrss, SPLIT_METHOD_MEAN);
  total_time += RUN_CASE(OBBRSS, transforms, ms_obbrss, SPLIT_METHOD_BV_CENTER);
  total_time += RUN_CASE(OBBRSS, transforms, ms_obbrss, SPLIT_METHOD_MEDIAN);

  std::cout << "\n\nTotal time: " << total_time << std::endl;
}

max_stars_repo_name: lmontaut/hpp-fcl

max_issues_repo_name: lmontaut/hpp-fcl

max_forks_repo_name: jcarpent/hpp-fcl


text:
#include "pre.h"

#include "label.h"

#ifdef CMAKE_USE_DLIB
#include <dlib/statistics.h>
#include <dlib/svm.h>
#endif

#include <cassert>
#include <cmath>

namespace pre
{

dat::Dataset logarithm( const dat::Dataset & d )
{
    double min {};
    dat::apply( [ & ] ( label::Num, const dat::Spectrum & s )
        {
            for( const auto & point : s._y )
            {
                if( point < min )
                {
                    min = point;
                }
            }
        }     , d );

    dat::Dataset ret{ {}, d.second };
    dat::apply( [ & ] ( label::Num l, const dat::Spectrum & s )
        {
            dat::Spectrum transformed{};
            unsigned i {};
            for( const auto & intensity : s._y )
            {
                const auto positive = intensity - min + 1;
                const auto point = std::log( positive );
                transformed._y[ i++ ] = point;
            }
            ret.first[ l ].push_back( transformed );
        }      , ret );

    return ret;
}

Log::Log( const dat::Dataset & )
{
}

dat::Dataset Log::operator()( const dat::Dataset & d ) const
{
    return logarithm( d );
}

void normalize( dat::Dataset & d )
{
    dat::Spectrum mean {};
    dat::apply( [ & ] ( label::Num, const dat::Spectrum & s )
    {
        auto src = s._y.cbegin();
        const auto end = s._y.cend();
        auto dest = mean._y.begin();
        while( src < end )
        {
            * dest++ += * src++;
        }
    }      , d );
    const auto c = dat::count( d );
    for( auto & point : mean._y )
    {
        point /= c;
    }

    dat::Spectrum variance;
    dat::apply( [ & ] ( label::Num, const dat::Spectrum & s )
    {
        auto sp = s._y.cbegin();
        const auto end = s._y.cend();
        auto dest = variance._y.begin();
        while( sp < end )
        {
            const auto a = mean._y[ sp - s._y.cbegin()] ;
            const auto diff = * sp - a;
            * dest += diff * diff;
            assert( diff * diff >= 0 );
            ++ sp;
            ++ dest;
        }
    }      , d );
    for( auto & point : variance._y )
    {
        point = sqrt( point / ( c - 1 ) );
        assert( point >= 0 );
    }

    dat::mutate( [ & ] ( label::Num, dat::Spectrum & s )
    {
        auto src = s._y.begin();
        const auto end = s._y.cend();
        auto m_it = mean._y.cbegin();
        auto v_it = variance._y.cbegin();
        while( src < end )
        {
            if( * v_it < 1e-12  )
            {
                * src = * m_it;
            }
            else
            {
                * src = ( * src - * m_it ) / * v_it;
            }

            ++src;
            ++m_it;
            ++v_it;
        }
    }      , d );
}

Norm::Norm( const dat::Dataset & )
{
}

dat::Dataset Norm::operator()( const dat::Dataset & d ) const
{
    dat::Dataset ret{ d };
    normalize( ret );
    return ret;
}

std::vector< size_t > rank_features( const dat::Dataset & )
{
    return {};
}

#ifdef CMAKE_USE_DLIB
dat::Dataset lda( const dat::Dataset & d )
{
    dlib::matrix< double > samples;
    samples.set_size( static_cast< long >( dat::count( d ) )
                    , dat::Spectrum::_num_points );
    std::vector< unsigned long > labels;
    auto i = 0u;
    dat::apply( [ & ] ( const label::Num l, const dat::Spectrum & s )
        {
            labels.push_back( static_cast< unsigned long >( l ) );
            std::copy( s._y.cbegin()
                     , s._y.cend()
                     , samples.begin() + dat::Spectrum::_num_points * i++ );
        }     , d );
    const auto samples2 = samples;

    dlib::matrix< double, 0, 1 > means;
    dlib::compute_lda_transform( samples, means, labels );

    dlib::matrix< double > ret = samples2 * samples - means; //crash
    std::cout << samples.nc() << ", " << samples.nr() << std::endl;
    std::cout << samples2.nc() << ", " << samples2.nr() << std::endl;
    std::cout << ret.nc() << ", " << ret.nr() << std::endl;

    return {};
}
#endif // CMAKE_USE_DLIB

shark::LinearModel<>
train_encoder( std::vector< shark::RealVector > & inputs
             , unsigned N
             )
{
    const auto dataset{ shark::createUnlabeledDataFromRange( inputs ) };
    shark::PCA pca{ dataset };
    shark::LinearModel<> enc;
    pca.encoder( enc, N );
    return enc;
}

shark::LinearModel<> train_encoder( const dat::Dataset & train
                                  , unsigned N
                                  )
{
    std::vector< shark::RealVector > inputs;
    dat::apply( [ & ] ( auto, const dat::Spectrum & s )
    {
        inputs.push_back( dat::to_shark_vector( s ) );
    }
    , train
    );

    return train_encoder( inputs, N );
}

shark::LinearModel<>
train_encoder( const shark::ClassificationDataset & train
             , unsigned N
             )
{
    std::vector< shark::RealVector > vec;
    for( auto e{ train.elements().begin()}; e < train.elements().end(); ++e )
    {
        vec.push_back( e->input );
    }

    return train_encoder( vec, N );
}

PCA::PCA( const dat::Dataset & train, unsigned dim )
    : _enc{ train_encoder( train, dim ) }
{
}

PCA::PCA( const shark::ClassificationDataset & train, unsigned dim )
    : _enc{ train_encoder( train, dim ) }
{
}

dat::Dataset PCA::operator()( const dat::Dataset & d ) const
{
    if( d.first.empty() )
    {
        return {};
    }

    std::vector< shark::RealVector > inputs;
    std::vector< label::Num > labels;
    dat::apply( [&] ( label::Num l, const dat::Spectrum & s )
    {
        shark::RealVector enc;
        const auto vec{ dat::to_shark_vector( s ) };
        _enc.eval( vec, enc );
        inputs.push_back( std::move( enc ) );
        labels.push_back( l );
    }
              , d );

    const auto sharked{ shark::createLabeledDataFromRange( inputs, labels ) };
    return dat::from_shark_dataset( sharked, d.second );
}

const std::vector< std::string > ALL_PRE{ "log"
                                        , "norm"

#if defined(CMAKE_USE_OPENCV) || defined(CMAKE_USE_SHARK)
                                         , "pca"
#endif
#if defined (CMAKE_USE_OPENCV) || defined (CMAKE_USE_DLIB)
                                        , "lda"
#endif
                                        };

}  // namespace pre

max_stars_repo_name: MiroslavVitkov/rocks

max_issues_repo_name: MiroslavVitkov/rocks

max_forks_repo_name: MiroslavVitkov/rocks