text:
/*=============================================================================
    Copyright (c) 2006 Tobias Schwinger
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to 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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_SKIPPER_FWD_HPP)
#define BOOST_SPIRIT_SKIPPER_FWD_HPP

#include <boost/spirit/core/scanner/scanner_fwd.hpp>

namespace boost { namespace spirit {

    template <typename BaseT = iteration_policy>
    struct skipper_iteration_policy;

    template <typename BaseT = iteration_policy>
    struct no_skipper_iteration_policy;

    template <typename ParserT, typename BaseT = iteration_policy>
    class skip_parser_iteration_policy;

}} // namespace boost::spirit

#endif

ext: hpp


text:
#ifndef __BOOST_PYTHON_STDCON_MAP_ARG_INCLUDED__
#define __BOOST_PYTHON_STDCON_MAP_ARG_INCLUDED__
#include <boost/python.hpp>
#include <associative_arg.hpp>
#include <map>

namespace boost::python {
  template<typename Key, typename Value, typename Compare, typename Alloc>
  struct arg_from_python<std::map<Key, Value, Compare, Alloc> const&> :
    stdcon::associative_copied_from_python<std::map<Key, Value, Compare, Alloc>>
  {
    typedef stdcon::associative_copied_from_python<std::map<Key, Value, Compare, Alloc>> base_type;
    arg_from_python(PyObject *pyobj) : base_type(pyobj) {}
  };

  template<typename Key, typename Value, typename Compare, typename Alloc>
  struct arg_from_python<std::map<Key, Value, Compare, Alloc> &&> :
    stdcon::associative_copied_from_python<std::map<Key, Value, Compare, Alloc>>
  {
    typedef stdcon::associative_copied_from_python<std::map<Key, Value, Compare, Alloc>> base_type;
    arg_from_python(PyObject *pyobj) : base_type(pyobj) {}
  };

  template<typename Key, typename Value, typename Compare, typename Alloc>
  struct arg_from_python<std::map<Key, Value, Compare, Alloc>> :
    stdcon::associative_copied_from_python<std::map<Key, Value, Compare, Alloc>>
  {
    typedef stdcon::associative_copied_from_python<std::map<Key, Value, Compare, Alloc>> base_type;
    arg_from_python(PyObject *pyobj) : base_type(pyobj) {}
  };

  namespace converter {
    template<typename Key, typename Value, typename Compare, typename Alloc>
    struct expected_pytype_for_arg<std::map<Key, Value, Compare, Alloc> const&> : expecting_pydict {};

    template<typename Key, typename Value, typename Compare, typename Alloc>
    struct expected_pytype_for_arg<std::map<Key, Value, Compare, Alloc> &&> : expecting_pydict {};

    template<typename Key, typename Value, typename Compare, typename Alloc>
    struct expected_pytype_for_arg<std::map<Key, Value, Compare, Alloc>> : expecting_pydict {};
  }
}
#endif

max_stars_repo_name: yjwen/boost-python-stdcon

max_issues_repo_name: yjwen/boost-python-stdcon

max_forks_repo_name: yjwen/boost-python-stdcon


text:
#define BOOST_TEST_MODULE protect pe test
#include <boost/test/included/unit_test.hpp>

#include "pe-protector/PeHeader.h"

using namespace NPeProtector;

BOOST_AUTO_TEST_SUITE(ProtectPeTest);
BOOST_AUTO_TEST_CASE(testProtectPe) {
  // TODO: Your test code here
}
BOOST_AUTO_TEST_SUITE_END();

ext: cpp

max_stars_repo_name: ATsahikian/PeProtector

max_issues_repo_name: ATsahikian/pe-protector

max_forks_repo_name: ATsahikian/pe-protector


text:
//
// Copyright (c) 2020 Richard Hodges (hodges.r@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/madmongo1/webclient
//
// This project was made possible with the generous support of:
// The C++ Alliance (https://cppalliance.org/)
// Jetbrains (https://www.jetbrains.com/)
//
// Talk to us on Slack (https://cppalliance.org/slack/)
//
// Many thanks to Vinnie Falco for continuous mentoring and support
//

#include <boost/webclient/uri/error.hpp>

namespace boost { namespace webclient { namespace uri {

auto check_result(int result, error_code& ec) -> error_code&
{
    if (result == URI_SUCCESS)
        ec.clear();
    else
        ec.assign(result, uri_error_category());
    return ec;
}

}}}


text:
#include <iostream>
#include <string>
#include <cstdlib>

#include <boost/format.hpp>

#include "dexcom.h"

using namespace std;

void usage( const char* a_pszMessage )
{
    cout << "usage:" << endl;
    cout << " " << a_pszMessage << " url" << endl;
}

int main( int argc, char* argv[] )
{
    // http -f POST https://dev.shawanga.com/api/v1/entries.json?count=3 "User-Agent: xDrip+"
    // "http://127.0.0.1/api/v1/entries.json?count=1&rr=1587961452708" -H  "accept: application/json" -H "User-Agent: xDrip+"| python3 -m json.tool

    if( argc != 2 )
    {
        usage( argv[0] );
        return EXIT_FAILURE;
    }

    dexcom dex;
    dex.setUrl( argv[1] );
    uint64_t tmp = 0;

    string strRet;
    while( true )
    {
        auto ret = dex.getBG( strRet );
        if( ret != tmp )
        {
            tmp = ret;
            cout << strRet << endl;
        }

        sleep( 10 );
    }

    return EXIT_SUCCESS;
}

max_stars_repo_name: mutable-dan/dex-tui

max_issues_repo_name: mutable-dan/dex-tui

max_forks_repo_name: mutable-dan/dex-tui


text: #include <boost/intrusive/any_hook.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*This work has been funded by rosin.org (contract agreement 732287)
 through EP project "Robobo AI"*/

/*******************************************************************************
 *
 *   Copyright 2019, Manufactura de Ingenios Tecnológicos S.L.
 *   <http://www.mintforpeople.com>
 *
 *   Redistribution, modification and use of this software are permitted under
 *   terms of the Apache 2.0 License.
 *
 *   This software is distributed in the hope that it will be useful,
 *   but WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND; without even the implied
 *   warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   Apache 2.0 License for more details.
 *
 *   You should have received a copy of the Apache 2.0 License along with
 *   this software. If not, see <http://www.apache.org/licenses/>.
 *
 ******************************************************************************/

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

#ifndef GAZEBO_BATTERY_CONSUMER_H
#define GAZEBO_BATTERY_CONSUMER_H

#include "gazebo/common/Plugin.hh"
#include "gazebo/common/CommonTypes.hh"
#include <boost/thread/mutex.hpp>
#include "robobo_msgs/SetLoad.h"
#include "ros/ros.h"
#include "ros/subscribe_options.h"
#include "ros/callback_queue.h"

namespace gazebo
{
    class GAZEBO_VISIBLE BatteryConsumerPlugin : public ModelPlugin
    {
    // Constructor
    public: BatteryConsumerPlugin();

    public: ~BatteryConsumerPlugin();

    // Inherited from ModelPlugin
    public: virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf);

    public: virtual void Init();

    public: virtual void Reset();

    public: bool SetConsumerPowerLoad(robobo_msgs::SetLoad::Request& req,
                                      robobo_msgs::SetLoad::Response& res);

    // Connection to the World Update events.
    protected: event::ConnectionPtr updateConnection;

    protected: physics::WorldPtr world;

    protected: physics::PhysicsEnginePtr physics;

    protected: physics::ModelPtr model;

    protected: physics::LinkPtr link;

    protected: sdf::ElementPtr sdf;

    // Battery
    private: common::BatteryPtr battery;

    // Consumer identifier
    private: int32_t consumerId;

    protected: double powerLoad;

    // This node is for ros communications
    protected: std::unique_ptr<ros::NodeHandle> rosNode;

    protected: ros::ServiceServer set_power_load;

    protected: boost::mutex lock;

    };

}

#endif //GAZEBO_BATTERY_CONSUMER_H

ext: hh

max_stars_repo_name: BPRamos/robobo-gazebo-simulator

max_issues_repo_name: BPRamos/robobo-gazebo-simulator

max_forks_repo_name: BPRamos/robobo-gazebo-simulator


text:
/**
 * Copyright (c) 2009 Carnegie Mellon University.
 *     All rights reserved.
 *
 *  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.
 *
 * For more about this software visit:
 *
 *      http://www.graphlab.ml.cmu.edu
 *
 */

#ifndef GRAPHLAB_DHT_HPP
#define GRAPHLAB_DHT_HPP

#include <boost/functional/hash.hpp>
#include <boost/unordered_map.hpp>
#include <graphlab/parallel/pthread_tools.hpp>
#include <graphlab/rpc/dc_dist_object.hpp>

namespace graphlab {

  /**
   * \ingroup rpc
   * Implements a very rudimentary distributed key value store.
   */
  template <typename KeyType, typename ValueType>
  class dht {

  public:
    typedef boost::unordered_map<size_t, ValueType> storage_type;

  private:
    mutable dc_dist_object< dht > rpc;

    boost::hash<KeyType> hasher;
    mutex lock;
    storage_type storage;

  public:
    dht(distributed_control &dc) : rpc(dc, this) { }

    /**
     * Get the owner of the key
     */
    procid_t owner(const KeyType& key) const {
      return hasher(key) % rpc.dc().numprocs();
    }

    /**
     * gets the value associated with a key.
     * Returns (true, Value) if the entry is available.
     * Returns (false, undefined) otherwise.
     */
    std::pair<bool, ValueType> get(const KeyType &key) const {
      // who owns the data?

      const size_t hashvalue = hasher(key);
      const size_t owningmachine = hashvalue % rpc.numprocs();
      std::pair<bool, ValueType> retval;
      // if it is me, we can return it
      if (owningmachine == rpc.dc().procid()) {

        lock.lock();
        typename storage_type::const_iterator iter = storage.find(hashvalue);
        retval.first = iter != storage.end();
        if (retval.first) retval.second = iter->second;
        lock.unlock();
      } else {
        retval = rpc.remote_request(owningmachine,
                                         &dht<KeyType,ValueType>::get,
                                         key);
      }
      return retval;
    }

    /**
     * Sets the newval to be the value associated with the key
     */
    void set(const KeyType &key, const ValueType &newval) {
      // who owns the data?
      const size_t hashvalue = hasher(key);
      const size_t owningmachine = hashvalue % rpc.numprocs();

      // if it is me, set it
      if (owningmachine == rpc.dc().procid()) {
        lock.lock();
        storage[hashvalue] = newval;
        lock.unlock();
      } else {
        rpc.remote_call(owningmachine,
                             &dht<KeyType,ValueType>::set,
                             key, newval);
      }
    }

    void print_stats() const {
      std::cerr << rpc.calls_sent() << " calls sent\n";
      std::cerr << rpc.calls_received() << " calls received\n";
    }

    /**
       Must be called by all machines simultaneously
    */
    void clear() {
      rpc.barrier();
      storage.clear();
    }

  };

};
#endif


text:
//==============================================================================
//
//   (c) Copyright, 2014 University Corporation for Atmospheric Research (UCAR).
//       All rights reserved.
//
//       File: $RCSfile: fileheader,v $
//       Version: $Revision: 1.1 $  Dated: $Date: 2010/10/04 14:44:18 $
//
//==============================================================================

/**
 * @file vdt_exception.hh
 *
 * General utility functions.
 *
 * @date 12/23/14
 */

#ifndef VDT_EXCEPTION_HH
#define VDT_EXCEPTION_HH

#include <exception>
#include <string>
#include <boost/format.hpp>
#include <cstring>

#define MAX_ERROR_LEN 512

class vdt_exception : public std::exception
{
  char msg[MAX_ERROR_LEN];
public:
  vdt_exception(const std::string& msg, const std::string& funcname, const std::string& filename, unsigned int linum)
  {
      const std::string errorstr = str(boost::format("ERROR in %1% at %2%:%3%\nMessage: %4%") % funcname % filename % linum % msg);
      strncpy(this->msg, errorstr.c_str(), MAX_ERROR_LEN-1);
      this->msg[MAX_ERROR_LEN-1] = '\0';
  }

  virtual const char* what() const throw()
  {
      return msg;
  }
};

#define VDT_EXCEPTION(msg) \
	vdt_exception(msg, __PRETTY_FUNCTION__, __FILE__, __LINE__)

#endif /* VDT_EXCEPTION_HH */

max_stars_repo_name: OSADP/Pikalert-Vehicle-Data-Translator-

max_issues_repo_name: OSADP/Pikalert-Vehicle-Data-Translator-

max_forks_repo_name: OSADP/Pikalert-Vehicle-Data-Translator-


text:
//
// examples/offset_fetch_cxx03.cpp
// -------------------------------
//
// Copyright (c) 2015 Daniel Joos
//
// Distributed under MIT license. (See file LICENSE)
//
// ----------------------------------
//
// This example shows how to fetch offset data for a consumer group using the
// 'OffsetFetch' API of Kafka 0.8.2. On the other side it demonstrates how
// the library can be used in combination with promised/futures and is
// therefore running all IO related work inside of a separate thread.
// The example is mainly a port of the C++11-based example but is using the
// boost library instead of the C++11 standard library.
//

#include <boost/exception_ptr.hpp>
#include <boost/function.hpp>
#include <boost/thread.hpp>
#include <boost/system/system_error.hpp>
#include <libkafka_asio/libkafka_asio.h>

using libkafka_asio::Connection;
using libkafka_asio::String;
using libkafka_asio::Int32;
using libkafka_asio::ConsumerMetadataRequest;
using libkafka_asio::ConsumerMetadataResponse;
using libkafka_asio::OffsetFetchRequest;
using libkafka_asio::OffsetFetchResponse;

// This will create handler functions which will set the value of the given
// promise on success or set the exception on error.
// The promise will be bound to the handler function.
template<typename T>
boost::function<
  void(const Connection::ErrorCodeType&, const typename T::OptionalType&)>
PromiseHandler(boost::shared_ptr<boost::promise<T> > pr)
{
  struct local
  {
    static void Handle(const Connection::ErrorCodeType& err,
                       const typename T::OptionalType& response,
                       boost::shared_ptr<boost::promise<T> > result)
    {
      if (err || !response)
      {
        result->set_exception(
          boost::copy_exception(boost::system::system_error(err)));
        return;
      }
      result->set_value(*response);
    }
  };
  return boost::bind(local::Handle, ::_1, ::_2, pr);
}

// Overload of the above function for boolean promises.
// We will use this as handler for the re-connect operation.
boost::function<void(const Connection::ErrorCodeType&)>
PromiseHandler(boost::shared_ptr<boost::promise<bool> > pr)
{
  struct local
  {
    static void Handle(const Connection::ErrorCodeType& err,
                       boost::shared_ptr<boost::promise<bool> > result)
    {
      if (err)
      {
        result->set_exception(
          boost::copy_exception(boost::system::system_error(err)));
        return;
      }
      result->set_value(true);
    }
  };
  return boost::bind(local::Handle, ::_1, pr);
}

// Discover the coordinating broker for the given consumer group.
// The function schedules a ConsumerMetadata request. The returned future
// object is used to wait for the requested data to be available.
boost::BOOST_THREAD_FUTURE<ConsumerMetadataResponse>
DiscoverCoordinator(Connection& connection, const String& consumer_group)
{
  boost::shared_ptr<boost::promise<ConsumerMetadataResponse> >
    result(new boost::promise<ConsumerMetadataResponse>());
  ConsumerMetadataRequest request;
  request.set_consumer_group(consumer_group);
  connection.AsyncRequest(request, PromiseHandler(result));
  return result->get_future();
}

// Re-connects the given connection to the provided hostname and port.
// This also shows how the connection can be connected without scheduling a
// request. Again, the returned future is used to wait until the operation
// completes successfully.
boost::BOOST_THREAD_FUTURE<bool>
ReConnect(Connection& connection, const String& hostname, Int32 port)
{
  boost::shared_ptr<boost::promise<bool> > result(new boost::promise<bool>());
  connection.Close();
  connection.AsyncConnect(hostname, port, PromiseHandler(result));
  return result->get_future();
}

// Fetch offset data for the given consumer group and topic-partition.
// Same as above: the function returns a future object.
boost::BOOST_THREAD_FUTURE<OffsetFetchResponse>
FetchOffset(Connection& connection,
            const String& consumer_group,
            const String& topic_name,
            Int32 partition)
{
  boost::shared_ptr<boost::promise<OffsetFetchResponse> >
    result(new boost::promise<OffsetFetchResponse>());
  OffsetFetchRequest request;
  request.set_consumer_group(consumer_group);
  request.FetchOffset(topic_name, partition);
  connection.AsyncRequest(request, PromiseHandler(result));
  return result->get_future();
}

// The starting point of our program...
int main(int argc, char **argv)
{
  // Run all IO work inside of another thread.
  // All request handlers are invoked from inside that thread as well.
  boost::asio::io_service ios;
  boost::asio::io_service::work work(ios);
  boost::thread worker(boost::bind(&boost::asio::io_service::run, &ios));

  // Construct a `libkafka_asio` connection object
  Connection::Configuration configuration;
  configuration.auto_connect = true;
  configuration.client_id = "libkafka_asio_example";
  configuration.socket_timeout = 2000;
  configuration.SetBrokerFromString("192.168.59.104:49158");
  String consumer_group = "ExampleGroup";
  String topic_name = "example";
  Int32 partition = 0;
  Connection connection(ios, configuration);

  try
  {
    // First get the broker that is currently coordinating the offset management
    ConsumerMetadataResponse coordinator =
      DiscoverCoordinator(connection, consumer_group).get();

    // Then re-connect the connection to the coordinator
    bool is_connected =
      ReConnect(connection,
                coordinator.coordinator_host(),
                coordinator.coordinator_port()).get();

    // Finally, fetch offset data from the coordinator and print it
    if (is_connected)
    {
      OffsetFetchResponse offset =
        FetchOffset(connection, consumer_group, topic_name, partition).get();
      std::cout
      << "Offset: "
      << offset.topics().find(topic_name)->second.partitions.find(partition)->second.offset
      << std::endl;
    }
  }
  catch (std::exception& e)
  {
    std::cerr << "Error: " << e.what() << std::endl;
  }

  ios.stop();
  worker.join();
  return 0;
}

max_stars_repo_name: perchits/libkafka-asio

max_issues_repo_name: perchits/libkafka-asio

max_forks_repo_name: perchits/libkafka-asio


text:
#define PY_ARRAY_UNIQUE_SYMBOL PyArrayHandleHdf5

#include <boost/python.hpp>
#include <stddef.h>

#include <opengm/python/opengmpython.hxx>

#ifdef WITH_HDF5
#include "pyHdf5.hxx"
#endif

BOOST_PYTHON_MODULE_INIT(_hdf5) {
    Py_Initialize();
    PyEval_InitThreads();
    #ifdef WITH_HDF5
    export_hdf5<opengm::python::GmAdder>();
    #endif
}

max_stars_repo_name: burcin/opengm

max_issues_repo_name: burcin/opengm

max_forks_repo_name: burcin/opengm


text:
#include <clams/trajectory_visualizer.h>
#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>

using namespace std;
using namespace Eigen;
using namespace clams;

int main(int argc, char** argv)
{
  namespace bpo = boost::program_options;
  namespace bfs = boost::filesystem;
  bpo::options_description opts_desc("Allowed options");
  bpo::positional_options_description p;

  string sseq_path;
  string traj_path;
  string map_path;
  opts_desc.add_options()
    ("help,h", "produce help message")
    ("sseq", bpo::value(&sseq_path)->required(), "StreamSequence, i.e. asus data.")
    ("traj", bpo::value(&traj_path)->required(), "Trajectory from slam in CLAMS format.")
    ("map", bpo::value(&map_path)->required(), "Cached map.")
    ;

  p.add("sseq", 1);
  p.add("traj", 1);
  p.add("map", 1);

  bpo::variables_map opts;
  bool badargs = false;
  try {
    bpo::store(bpo::command_line_parser(argc, argv).options(opts_desc).positional(p).run(), opts);
    bpo::notify(opts);
  }
  catch(...) { badargs = true; }
  if(opts.count("help") || badargs) {
    cout << "Usage: " << bfs::basename(argv[0]) << " [OPTS] SSEQ TRAJ MAP" << endl;
    cout << endl;
    cout << opts_desc << endl;
    return 1;
  }

  Trajectory traj;
  traj.load(traj_path);
  StreamSequenceBase::ConstPtr sseq = StreamSequenceBase::initializeFromDirectory(sseq_path);
  Cloud::Ptr map(new Cloud);
  pcl::io::loadPCDFile<pcl::PointXYZRGB>(map_path, *map);

  TrajectoryVisualizer tv(sseq, traj, map, sseq_path);
  tv.run();

  return 0;
}


text: #include <boost/metaparse/limit_sequence_size.hpp>


text:
#include <boost/filesystem.hpp>
#include <iostream>

#include "Utils.h"

using namespace utils;

Utils::Utils() {}

/**
 * @brief find the relative path to the target
 *
 * /!\ - target must be relative to ROOT_DIR
 *     - target must be within (-r) ROOT_DIR
 *
 * dependance:
 *  #include <boost/filesystem.hpp>
 *
 * usage:
 *  std::string rp_font_fps =
 *    utils::Utils::resolveRelative("res/fonts/Square.ttf");
 *
 * @param target
 * @return std::string
 */

std::string Utils::resolveRelative(std::string target) {
  std::string root_dir = Utils::getRootDir();
  boost::filesystem::path path = boost::filesystem::current_path();

  // std::cout << "[DEBUG] path : " << path << std::endl;

  std::string out;

  int distance = -1;
  for (auto it = path.end(); it != path.begin(); --it, ++distance) {
    // std::cout << "[DEBUG] : " << *it << std::endl;

    if ((it->string()).compare(root_dir) == 0) {
      // std::cout << "FOUND !" << distance << std::endl;

      std::string out;
      // prepend with relative parent cd
      const std::string input = "../";
      for (int i = 0; i < distance; ++i)
        out.append(input);
      // std::cout << "out : " << out << std::endl;
      // append the target
      out.append(target);
      // return the resolved path
      return out;
    }
  }

  return std::string();
}

const std::string Utils::getRootDir() { return "PLT_2021"; }

/**
 * @brief convert a color string to a sf::Color
 *
 * ie:
 *  "#4080C8"
 *  r : 40 (16) = 64
 *  g : 80 (16) = 128
 *  b : c8 (16) = 200
 *
 *  => sf:Color(r, g, b)
 *
 * @param str_color
 * @return sf::Color
 */
sf::Color Utils::stringToColor(std::string str_color) {
  sf::Color out(0, 0, 0);
  if (str_color.size() == 7) {
    unsigned int x = std::stoul(str_color.substr(1), nullptr, 16);
    out.b = (sf::Uint8)(x)&0xFF;
    out.g = (sf::Uint8)(x >> 8) & 0xFF;
    out.r = (sf::Uint8)(x >> 16) & 0xFF;
  }
  return out;
}


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

#include "xregImgSimMetric2DGradImgOCL.h"

#include <boost/compute/utility/source.hpp>

#include "xregAssert.h"
#include "xregNormDist.h"

namespace
{

// This should actually be set based on the size of the input data (and the GPU HW)
const std::size_t kSOBEL_PROJ_DIMS_WORK_UNIT_DIV = 1;
const std::size_t kSMOOTH_PROJ_DIMS_WORK_UNIT_DIV = 1;

const char* kGRAD_NCC_OPENCL_SRC = BOOST_COMPUTE_STRINGIZE_SOURCE(

__kernel void GaussianKernel(__global float* src_imgs,
                             __global float* smooth_imgs,
                             __global float* smooth_kernel,
                             const uint kernel_width,
                             const uint num_imgs,
                             const uint img_nr,
                             const uint img_nc,
                             const uint proj_off)
{
  const uint row_inc = get_global_size(0);
  const uint col_inc = get_global_size(1);
  const uint img_idx = get_global_id(2);
  const uint img_len = img_nr * img_nc;

  if (img_idx < num_imgs)
  {
    const uint img_nr_minus_1 = img_nr - 1;
    const uint img_nc_minus_1 = img_nc - 1;

    const int kernel_half_width = (int) (kernel_width / 2);

    // this is typically from the ray caster buffer, which can be split up amongst different sim
    // metrics and thus why we need projection offset.
    __global float* cur_src_img = src_imgs + ((proj_off + img_idx) * img_len);

    // this buffer is local to this sim metric and we can just use the beginning section; no need
    // to worry about projection offset
    __global float* cur_smooth_img = smooth_imgs + (img_idx * img_len);

    for (uint row_idx = get_global_id(0); row_idx < img_nr; row_idx += row_inc)
    {
      __global float* smooth_row = cur_smooth_img + (row_idx * img_nc);

      for (uint col_idx = get_global_id(1); col_idx < img_nc; col_idx += col_inc)
      {
        float cur_sum = 0;

        uint kern_idx = 0;
        for (int kr = -kernel_half_width; kr <= kernel_half_width; ++kr)
        {
          const int conv_r_no_clamp = ((int)row_idx) + kr;

          // clamp row used in image
          const uint conv_r_clamp = (conv_r_no_clamp >= 0) ?
                                      ((conv_r_no_clamp < (int)img_nr) ? (uint)conv_r_no_clamp : img_nr_minus_1) : 0u;

          __global float* cur_conv_row = cur_src_img + (conv_r_clamp * img_nc);

          for (int kc = -kernel_half_width; kc <= kernel_half_width; ++kc, ++kern_idx)
          {
            const int conv_c_no_clamp = ((int)col_idx) + kc;

            // clamp column used in image
            const uint conv_c_clamp = (conv_c_no_clamp >= 0) ?
                                      ((conv_c_no_clamp < (int)img_nc) ? (uint)conv_c_no_clamp : img_nc_minus_1) : 0u;

            cur_sum += cur_conv_row[conv_c_clamp] * smooth_kernel[kern_idx];
          }
        }

        smooth_row[col_idx] = cur_sum;
      }
    }
  }
}

__kernel void SobelKernel(__global float* src_imgs,
                          __global float* grad_x_imgs,
                          __global float* grad_y_imgs,
                          const uint num_imgs,
                          const uint img_nr,
                          const uint img_nc,
                          const uint proj_off)
{
  const uint row_inc = get_global_size(0);
  const uint col_inc = get_global_size(1);
  const uint img_idx = get_global_id(2);
  const uint img_len = img_nr * img_nc;

  if (img_idx < num_imgs)
  {
    const uint img_nr_minus_1 = img_nr - 1;
    const uint img_nc_minus_1 = img_nc - 1;

    // this is typically from the ray caster buffer, which can be split up amongst different sim
    // metrics and thus why we need projection offset.
    __global float* cur_src_img = src_imgs + ((proj_off + img_idx) * img_len);

    // this buffer is local to this sim metric and we can just use the beginning section; no need
    // to worry about projection offset
    __global float* cur_grad_x_img = grad_x_imgs + (img_idx * img_len);
    __global float* cur_grad_y_img = grad_y_imgs + (img_idx * img_len);

    for (uint row_idx = get_global_id(0); row_idx < img_nr; row_idx += row_inc)
    {
      const uint cur_row_off  = row_idx * img_nc;
      const uint prev_row_off = (row_idx > 0) ? (cur_row_off - img_nc) : cur_row_off;
      const uint next_row_off = (row_idx < img_nr_minus_1) ? (cur_row_off + img_nc) : cur_row_off;

      __global float* cur_src_row  = cur_src_img + cur_row_off;
      __global float* prev_src_row = cur_src_img + prev_row_off;
      __global float* next_src_row = cur_src_img + next_row_off;

      __global float* grad_x_row = cur_grad_x_img + cur_row_off;
      __global float* grad_y_row = cur_grad_y_img + cur_row_off;

      for (uint col_idx = get_global_id(1); col_idx < img_nc; col_idx += col_inc)
      {
        const uint prev_col = (col_idx > 0) ? (col_idx - 1) : 0;
        const uint next_col = (col_idx < img_nc_minus_1) ? (col_idx + 1) : col_idx;

        // x-direction
        grad_x_row[col_idx] = -prev_src_row[prev_col] + prev_src_row[next_col] +
                              -(2.0f * cur_src_row[prev_col]) + (2.0f * cur_src_row[next_col]) +
                              -next_src_row[prev_col] + next_src_row[next_col];

        // y-direction
        grad_y_row[col_idx] = -prev_src_row[prev_col] - (2.0f * prev_src_row[col_idx]) - prev_src_row[next_col]
                              + next_src_row[prev_col] + (2.0f * next_src_row[col_idx]) + next_src_row[next_col];
      }
    }
  }
}

);

}  // un-named

xreg::ImgSimMetric2DGradImgOCL::ImgSimMetric2DGradImgOCL(const boost::compute::device& dev)
  : ImgSimMetric2DOCL(dev)
{ }

xreg::ImgSimMetric2DGradImgOCL::ImgSimMetric2DGradImgOCL(const boost::compute::context& ctx,
                                                         const boost::compute::command_queue& queue)
  : ImgSimMetric2DOCL(ctx, queue)
{ }

void xreg::ImgSimMetric2DGradImgOCL::allocate_resources()
{
  namespace bc = boost::compute;

  ImgSimMetric2DOCL::allocate_resources();

  const auto itk_size = this->fixed_img_->GetLargestPossibleRegion().GetSize();
  const size_type img_num_rows = itk_size[1];
  const size_type img_num_cols = itk_size[0];

  // compile kernels

  bc::program prog = bc::program::create_with_source(kGRAD_NCC_OPENCL_SRC, this->ctx_);

  try
  {
    prog.build();
  }
  catch (bc::opencl_error &)
  {
    std::cerr << "OpenCL Kernel Compile Error (ImgSimMetric2DGradImgOCL):\n"
              << prog.build_log() << std::endl;
    throw;
  }

  const size_type num_pix_per_img = this->num_pix_per_proj();
  const size_type max_buf_size    = num_pix_per_img * this->num_mov_imgs_;

  if (smooth_img_kernel_rad_)
  {
    // width must be odd
    xregASSERT(smooth_img_kernel_rad_ & 1);

    // Doh... the radius is actually diameter/width
    const size_type tot_kernel_len = smooth_img_kernel_rad_ * smooth_img_kernel_rad_;

    // This is the OpenCV formula; mainly using to get results consistent
    // with the CPU implementation that uses cv::GaussianBlur
    const float sigma = ((((smooth_img_kernel_rad_ - 1) * 0.5f) - 1.0f) * 0.3f) + 0.8f;

    // Create distribution with mean at the kernel center index
    NormalDist2DIndep norm_dist(0, 0, sigma, sigma);

    float kern_sum = 0;
    std::vector<float> tmp_host_kern;
    tmp_host_kern.reserve(tot_kernel_len);

    const int kernel_half_width = static_cast<int>(smooth_img_kernel_rad_) / 2;

    for (int r = -kernel_half_width; r <= kernel_half_width; ++r)
    {
      for (int c = -kernel_half_width; c <= kernel_half_width; ++c)
      {
        const float cur_val = norm_dist(r,c);
        tmp_host_kern.push_back(cur_val);

        kern_sum += cur_val;
      }
    }
    xregASSERT(tmp_host_kern.size() == tot_kernel_len);

    // normalize so kernel has sum of 1
    std::transform(tmp_host_kern.begin(), tmp_host_kern.end(), tmp_host_kern.begin(),
                   [kern_sum] (const float& x)
                   {
                     return x / kern_sum;
                   });

    smooth_kernel_dev_buf_.reset(new DevBuf(this->ctx_));
    smooth_kernel_dev_buf_->assign(tmp_host_kern.begin(), tmp_host_kern.end(),
                                   this->queue_);

    mov_smooth_dev_buf_.reset(new DevBuf(this->ctx_));
    mov_smooth_dev_buf_->resize(max_buf_size, this->queue_);

    smooth_krnl_ = prog.create_kernel("GaussianKernel");

    // smooth the fixed image
    smooth_krnl_.set_arg(0, *this->fixed_img_ocl_buf_);
    smooth_krnl_.set_arg(1, *mov_smooth_dev_buf_);
    smooth_krnl_.set_arg(2, *smooth_kernel_dev_buf_);
    smooth_krnl_.set_arg(3, bc::uint_(smooth_img_kernel_rad_));
    smooth_krnl_.set_arg(4, bc::uint_(1));
    smooth_krnl_.set_arg(5, bc::uint_(img_num_rows));
    smooth_krnl_.set_arg(6, bc::uint_(img_num_cols));
    smooth_krnl_.set_arg(7, bc::uint_(0));

    smooth_ocl_kernel_global_size_[0] = img_num_rows / kSMOOTH_PROJ_DIMS_WORK_UNIT_DIV;
    smooth_ocl_kernel_global_size_[1] = img_num_cols / kSMOOTH_PROJ_DIMS_WORK_UNIT_DIV;
    smooth_ocl_kernel_global_size_[2] = 1 ;
    this->queue_.enqueue_nd_range_kernel(smooth_krnl_, 3, 0, smooth_ocl_kernel_global_size_.data(), 0).wait();
  }

  sobel_krnl_ = prog.create_kernel("SobelKernel");

  fixed_grad_x_dev_buf_ = std::make_shared<DevBuf>(this->ctx_);
  fixed_grad_y_dev_buf_ = std::make_shared<DevBuf>(this->ctx_);

  mov_grad_x_dev_buf_ = std::make_shared<DevBuf>(this->ctx_);
  mov_grad_y_dev_buf_ = std::make_shared<DevBuf>(this->ctx_);

  fixed_grad_x_dev_buf_->resize(num_pix_per_img, this->queue_);
  fixed_grad_y_dev_buf_->resize(num_pix_per_img, this->queue_);

  mov_grad_x_dev_buf_->resize(max_buf_size, this->queue_);
  mov_grad_y_dev_buf_->resize(max_buf_size, this->queue_);

  // compute fixed image sobel grads
  sobel_krnl_.set_arg(0, smooth_img_kernel_rad_ ? *mov_smooth_dev_buf_ :
                                                  *this->fixed_img_ocl_buf_);
  sobel_krnl_.set_arg(1, *fixed_grad_x_dev_buf_);
  sobel_krnl_.set_arg(2, *fixed_grad_y_dev_buf_);
  sobel_krnl_.set_arg(3, bc::uint_(1));
  sobel_krnl_.set_arg(4, bc::uint_(img_num_rows));
  sobel_krnl_.set_arg(5, bc::uint_(img_num_cols));
  sobel_krnl_.set_arg(6, bc::uint_(0));

  sobel_ocl_kernel_global_size_[0] = img_num_rows / kSOBEL_PROJ_DIMS_WORK_UNIT_DIV;
  sobel_ocl_kernel_global_size_[1] = img_num_cols / kSOBEL_PROJ_DIMS_WORK_UNIT_DIV;
  sobel_ocl_kernel_global_size_[2] = 1 ;
  this->queue_.enqueue_nd_range_kernel(sobel_krnl_, 3, 0, sobel_ocl_kernel_global_size_.data(), 0).wait();

  // setup some kernel arguments that will not change
  sobel_krnl_.set_arg(1, *mov_grad_x_dev_buf_);
  sobel_krnl_.set_arg(2, *mov_grad_y_dev_buf_);
  // image dimensions do not change

  if (smooth_img_kernel_rad_)
  {
    smooth_krnl_.set_arg(0, *this->mov_imgs_buf_);
  }
  else
  {
    sobel_krnl_.set_arg(0, *this->mov_imgs_buf_);
  }
}

xreg::size_type xreg::ImgSimMetric2DGradImgOCL::smooth_img_before_sobel_kernel_radius() const
{
  return smooth_img_kernel_rad_;
}

void xreg::ImgSimMetric2DGradImgOCL::set_smooth_img_before_sobel_kernel_radius(const size_type r)
{
  smooth_img_kernel_rad_ = r;
}

void xreg::ImgSimMetric2DGradImgOCL::compute_sobel_grads()
{
  namespace bc = boost::compute;

  // this should be called by the compute method of the sub-class
  //this->pre_compute();

  sobel_ocl_kernel_global_size_[2]  = this->num_mov_imgs_;
  smooth_ocl_kernel_global_size_[2] = this->num_mov_imgs_;

  // smooth moving images
  if (smooth_img_kernel_rad_)
  {
    smooth_krnl_.set_arg(4, bc::uint_(this->num_mov_imgs_));
    smooth_krnl_.set_arg(7, bc::uint_(this->proj_off_));

    this->queue_.enqueue_nd_range_kernel(smooth_krnl_, 3, 0, smooth_ocl_kernel_global_size_.data(), 0).wait();

    sobel_krnl_.set_arg(6, bc::uint_(0));
  }
  else
  {
    sobel_krnl_.set_arg(6, bc::uint_(this->proj_off_));
  }

  // compute the sobel of moving images
  sobel_krnl_.set_arg(3, bc::uint_(this->num_mov_imgs_));

  this->queue_.enqueue_nd_range_kernel(sobel_krnl_, 3, 0, sobel_ocl_kernel_global_size_.data(), 0).wait();
}


text:
#include <xmorphy/build/DisambDict.h>
#include <boost/algorithm/string.hpp>

namespace X
{
std::size_t DisambDict::getCount(const UniString & word, UniSPTag sp, UniMorphTag mt) const
{
    std::string upCaseWord = word.toUpperCase().getRawString();
    std::vector<std::string> keys = dict->completeKey(upCaseWord + DISAMBIG_SEPARATOR);
    size_t count = 0;
    size_t maxSameBits = 0;
    for (const std::string & key : keys)
    {
        std::vector<std::string> parts;
        size_t i;
        size_t len = 0;
        size_t prev = 0;
        for (i = 0; i < key.size(); ++i)
        {
            if (key[i] == DISAMBIG_SEPARATOR)
            {
                parts.emplace_back(&key[prev], len);
                len = 0;
                prev = i + 1;
            }
            else
            {
                ++len;
            }
        }
        if (prev < key.size() && len > 0)
            parts.emplace_back(key.substr(prev, len));

        if (parts[0] != upCaseWord)
        {
            continue;
        }
        UniSPTag candidateSp = UniSPTag::X;
        from_raw_string(parts[1], candidateSp);
        if (candidateSp != sp)
        {
            continue;
        }
        UniMorphTag candidateMt = UniMorphTag::UNKN;
        from_raw_string(parts[2], candidateMt);
        size_t sameBits = count_intersection(mt, candidateMt);
        size_t currentKeyCount = dict->getValue(key);
        if (sameBits > maxSameBits)
        {
            maxSameBits = sameBits;
            count = currentKeyCount;
        }
        else if (sameBits == maxSameBits && currentKeyCount > count)
        {
            count = currentKeyCount;
        }
    }
    return count;
}

void dropToFiles(const std::unique_ptr<DisambDict> & dct, const std::string & filename)
{
    std::ofstream ofs(filename);
    dct->dict->serialize(ofs);
}

std::unique_ptr<DisambDict> DisambDict::loadFromFiles(std::istream & is)
{
    DisambDictPtr dct = std::make_shared<dawg::Dictionary<std::size_t>>();
    dct->deserialize(is);
    return utils::make_unique<DisambDict>(dct);
}
}


text:
/*
 * UUID.cpp
 *
 *  Created on: 2014-12-21
 *      Author: manson
 */

#include <sstream>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>

#include "UUID.h"

namespace flint {

UUID::UUID() {
	// TODO Auto-generated constructor stub

}

UUID::~UUID() {
	// TODO Auto-generated destructor stub
}

std::string UUID::generateUUID() {
	boost::uuids::uuid uuid = boost::uuids::random_generator()();
	std::stringstream ss;
	ss << uuid;
	std::string _uuid = ss.str();
	return _uuid;
}

} /* namespace flint */

max_stars_repo_name: jsli/flingd-cc


text:
// message_server_port.cpp

/*    Copyright 2009 10gen Inc.
 *
 *    This program is free software: you can redistribute it and/or  modify
 *    it under the terms of the GNU Affero General Public License, version 3,
 *    as published by the Free Software Foundation.
 *
 *    This program 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 Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the GNU Affero General Public License in all respects
 *    for all of the code used other than as permitted herein. If you modify
 *    file(s) with this exception, you may extend this exception to your
 *    version of the file(s), but you are not obligated to do so. If you do not
 *    wish to do so, delete this exception statement from your version. If you
 *    delete this exception statement from all source files in the program,
 *    then also delete it in the license file.
 */

#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kNetwork

#include "mongo/platform/basic.h"

#include <boost/scoped_ptr.hpp>
#include <boost/thread/thread.hpp>
#include <memory>

#include "mongo/base/disallow_copying.h"
#include "mongo/db/lasterror.h"
#include "mongo/db/server_options.h"
#include "mongo/db/stats/counters.h"
#include "mongo/stdx/functional.h"
#include "mongo/util/concurrency/synchronization.h"
#include "mongo/util/concurrency/thread_name.h"
#include "mongo/util/concurrency/ticketholder.h"
#include "mongo/util/debug_util.h"
#include "mongo/util/exit.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/net/listen.h"
#include "mongo/util/net/message.h"
#include "mongo/util/net/message_port.h"
#include "mongo/util/net/message_server.h"
#include "mongo/util/net/ssl_manager.h"
#include "mongo/util/scopeguard.h"

#ifdef __linux__  // TODO: consider making this ifndef _WIN32
# include <sys/resource.h>
#endif

#if !defined(__has_feature)
#define __has_feature(x) 0
#endif

namespace mongo {

    using boost::scoped_ptr;
    using std::endl;

namespace {

    class MessagingPortWithHandler : public MessagingPort {
        MONGO_DISALLOW_COPYING(MessagingPortWithHandler);

    public:
        MessagingPortWithHandler(const boost::shared_ptr<Socket>& socket,
                                 MessageHandler* handler,
                                 long long connectionId)
            : MessagingPort(socket), _handler(handler) {
            setConnectionId(connectionId);
        }

        MessageHandler* getHandler() const { return _handler; }

    private:
        // Not owned.
        MessageHandler* const _handler;
    };

}  // namespace

    class PortMessageServer : public MessageServer , public Listener {
    public:
        /**
         * Creates a new message server.
         *
         * @param opts
         * @param handler the handler to use. Caller is responsible for managing this object
         *     and should make sure that it lives longer than this server.
         */
        PortMessageServer(  const MessageServer::Options& opts, MessageHandler * handler ) :
            Listener( "" , opts.ipList, opts.port ), _handler(handler) {
        }

        virtual void accepted(boost::shared_ptr<Socket> psocket, long long connectionId ) {
            ScopeGuard sleepAfterClosingPort = MakeGuard(sleepmillis, 2);
            std::auto_ptr<MessagingPortWithHandler> portWithHandler(
                new MessagingPortWithHandler(psocket, _handler, connectionId));

            if ( ! Listener::globalTicketHolder.tryAcquire() ) {
                log() << "connection refused because too many open connections: " << Listener::globalTicketHolder.used() << endl;
                return;
            }

            try {
#ifndef __linux__  // TODO: consider making this ifdef _WIN32
                {
                    boost::thread thr(stdx::bind(&handleIncomingMsg, portWithHandler.get()));
                }
#else
                pthread_attr_t attrs;
                pthread_attr_init(&attrs);
                pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);

                static const size_t STACK_SIZE = 1024*1024; // if we change this we need to update the warning

                struct rlimit limits;
                verify(getrlimit(RLIMIT_STACK, &limits) == 0);
                if (limits.rlim_cur > STACK_SIZE) {
                    size_t stackSizeToSet = STACK_SIZE;
#if !__has_feature(address_sanitizer)
                    if (kDebugBuild)
                        stackSizeToSet /= 2;
#endif
                    pthread_attr_setstacksize(&attrs, stackSizeToSet);
                } else if (limits.rlim_cur < 1024*1024) {
                    warning() << "Stack size set to " << (limits.rlim_cur/1024) << "KB. We suggest 1MB" << endl;
                }

                pthread_t thread;
                int failed =
                    pthread_create(&thread, &attrs, &handleIncomingMsg, portWithHandler.get());

                pthread_attr_destroy(&attrs);

                if (failed) {
                    log() << "pthread_create failed: " << errnoWithDescription(failed) << endl;
                    throw boost::thread_resource_error(); // for consistency with boost::thread
                }
#endif  // __linux__

                portWithHandler.release();
                sleepAfterClosingPort.Dismiss();
            }
            catch ( boost::thread_resource_error& ) {
                Listener::globalTicketHolder.release();
                log() << "can't create new thread, closing connection" << endl;
            }
            catch ( ... ) {
                Listener::globalTicketHolder.release();
                log() << "unknown error accepting new socket" << endl;
            }
        }

        virtual void setAsTimeTracker() {
            Listener::setAsTimeTracker();
        }

        virtual void setupSockets() {
            Listener::setupSockets();
        }

        void run() {
            initAndListen();
        }

        virtual bool useUnixSockets() const { return true; }

    private:
        MessageHandler* _handler;

        /**
         * Handles incoming messages from a given socket.
         *
         * Terminating conditions:
         * 1. Assertions while handling the request.
         * 2. Socket is closed.
         * 3. Server is shutting down (based on inShutdown)
         *
         * @param arg this method is in charge of cleaning up the arg object.
         *
         * @return NULL
         */
        static void* handleIncomingMsg(void* arg) {
            TicketHolderReleaser connTicketReleaser( &Listener::globalTicketHolder );

            invariant(arg);
            scoped_ptr<MessagingPortWithHandler> portWithHandler(
                static_cast<MessagingPortWithHandler*>(arg));
            MessageHandler* const handler = portWithHandler->getHandler();

            setThreadName(std::string(str::stream() << "conn" << portWithHandler->connectionId()));
            portWithHandler->psock->setLogLevel(logger::LogSeverity::Debug(1));

            Message m;
            int64_t counter = 0;
            try {
                LastError * le = new LastError();
                lastError.reset( le ); // lastError now has ownership

                handler->connected(portWithHandler.get());

                while ( ! inShutdown() ) {
                    m.reset();
                    portWithHandler->psock->clearCounters();

                    if (!portWithHandler->recv(m)) {
                        if (!serverGlobalParams.quiet) {
                            int conns = Listener::globalTicketHolder.used()-1;
                            const char* word = (conns == 1 ? " connection" : " connections");
                            log() << "end connection " << portWithHandler->psock->remoteString()
                                  << " (" << conns << word << " now open)" << endl;
                        }
                        portWithHandler->shutdown();
                        break;
                    }

                    handler->process(m, portWithHandler.get(), le);
                    networkCounter.hit(portWithHandler->psock->getBytesIn(),
                                       portWithHandler->psock->getBytesOut());

                    // Occasionally we want to see if we're using too much memory.
                    if ((counter++ & 0xf) == 0) {
                        markThreadIdle();
                    }
                }
            }
            catch ( AssertionException& e ) {
                log() << "AssertionException handling request, closing client connection: " << e << endl;
                portWithHandler->shutdown();
            }
            catch ( SocketException& e ) {
                log() << "SocketException handling request, closing client connection: " << e << endl;
                portWithHandler->shutdown();
            }
            catch ( const DBException& e ) { // must be right above std::exception to avoid catching subclasses
                log() << "DBException handling request, closing client connection: " << e << endl;
                portWithHandler->shutdown();
            }
            catch ( std::exception &e ) {
                error() << "Uncaught std::exception: " << e.what() << ", terminating" << endl;
                dbexit( EXIT_UNCAUGHT );
            }

            // Normal disconnect path.
#ifdef MONGO_SSL
            SSLManagerInterface* manager = getSSLManager();
            if (manager)
                manager->cleanupThreadLocals();
#endif
            handler->disconnected(portWithHandler.get());

            return NULL;
        }
    };

    MessageServer * createServer( const MessageServer::Options& opts , MessageHandler * handler ) {
        return new PortMessageServer( opts , handler );
    }

}  // namespace mongo

max_stars_repo_name: ramgtv/mongo

max_issues_repo_name: ramgtv/mongo

max_forks_repo_name: ramgtv/mongo


text:
/*
Copyright 2013, 2014 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.
*/

#define BOOST_TEST_MODULE test_rime_call_if
#include "utility/test/boost_unit_test.hpp"

#include "rime/call_if.hpp"

#include <type_traits>
#include <boost/mpl/assert.hpp>

#include "rime/check/check_equal.hpp"

BOOST_AUTO_TEST_SUITE(test_rime_if)

// Has no call operator.
struct fail {};

struct return_as_double {
    double operator() (double d) const { return d; }
};
struct return_as_float {
    float operator() (long l) const { return float (l); }
};
struct return_as_long {
    long operator() (long l) const { return l; }
};

BOOST_AUTO_TEST_CASE (test_rime_call_if) {
    auto vd = rime::call_if (true, return_as_double(), return_as_long(), 2);
    BOOST_CHECK (vd.contains <double>());
    BOOST_CHECK_EQUAL (rime::get <double> (vd), 2.);
    auto vl = rime::call_if (false, return_as_double(), return_as_long(), 3);
    BOOST_CHECK (vl.contains <long>());
    BOOST_CHECK_EQUAL (rime::get <long> (vl), 3l);

    // Compile-time constants: operator() should never be instantiated on
    // "fail()".
    auto d = rime::call_if (rime::true_, return_as_double(), fail(), 5);
    RIME_CHECK_EQUAL (d, 5.);
    auto l = rime::call_if (rime::false_, fail(), return_as_long(), 7);
    RIME_CHECK_EQUAL (l, 7l);
}

template <class Base> struct merge_float {
    template <class Type1, class Type2, class Dummy = void> struct apply
    : Base::template apply <Type1, Type2> {};

    template <class Dummy> struct apply <float, double, Dummy>
    { typedef double type; };
    template <class Dummy> struct apply <double, float, Dummy>
    { typedef double type; };
};

BOOST_AUTO_TEST_CASE (test_rime_call_if_merge) {
    namespace merge_policy = rime::merge_policy;
    typedef merge_policy::to_variant <
        merge_policy::reference <merge_policy::const_ <
            merge_float <merge_policy::same<>>>>> policy;

    auto v1 = rime::call_if <policy> (false,
        return_as_double(), return_as_long(), 2);
    BOOST_CHECK (v1.contains <long>());
    BOOST_CHECK_EQUAL (rime::get <long> (v1), 2);

    auto v2 = rime::call_if <policy> (false,
        return_as_double(), return_as_float(), 7);
    BOOST_MPL_ASSERT ((std::is_same <decltype (v2), double>));
    BOOST_CHECK_EQUAL (v2, 7.);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: rogiervd/rime

max_issues_repo_name: rogiervd/rime

max_forks_repo_name: rogiervd/rime


text:
#ifndef _RYSQ_CUDA_MATRIX_HPP_
#define _RYSQ_CUDA_MATRIX_HPP_

#include <boost/smart_ptr.hpp>

#include "rysq/cuda-memory.hpp"

namespace rysq {
    namespace cuda {

	// struct zero_matrix {
	//     zero_matrix(size_t size1, size_t  size2)
	// 	: size1_(size1), size2_(size2) {}
	//     size_t size1() const { return size1_; }
	//     size_t size2() const { return size2_; }
	// private:
	//     size_t size1_, size2_;
	// };

	template<typename T, class A_ = array<T> >
	struct block_matrix :  block_matrix_base <T> {
	    typedef A_ array_type;
	    typedef block_matrix_base<T> base;
	    typedef rysq::block_matrix<T,boost::shared_array<T> > host_matrix;
	    using base::size1;
	    using base::size2;
	    using base::size;
	    using base::block1;
	    using base::block2;
	    block_matrix() {}
	    T* block(int a,int b) { return data() +  base::layout_.block_at(a,b); }
	    const T* block(int a,int b) const {
		return data() + base::layout_.block_at(a,b);
	    }
	    void clear(){//(const zero_matrix &A) {
		// base::check_size(A);
		memset(device_ptr<void>(data_.data()),  char(0), size()*sizeof(T));
	    }
	    template<class M>
	    void assign(const M &A) {
		base::check_size(A);
		host_matrix B(size1(), size2(), block1(), block2());
		B.assign(A);
		memcpy<T>(B.data(), data_, B.size());
	    }
	    host_matrix copy() const {
		host_matrix B(size1(), size2(), block1(), block2());
		memcpy<T>(data_, B.data(), B.size());
		return B;
	    }
	    void resize(size_t size1, size_t size2, size_t block1, size_t block2) {

		base::layout_ = block_matrix_layout(size1, size2, block1, block2);
		base::size1_ = size1;  base::size2_ = size2;
		data_.resize(size());
		// std:: cout << this->size1() <<this-> size2() <<this-> block1() <<this-> block2() << std::endl;
	    }
	    T* data() { return data_.data(); }
	    const T* data() const { return data_.data(); }
	private:
	    array_type data_;
	};

}
}

#endif /* __RYSQ_CUDA_MATRIX_HPP_ */


text:
#ifndef BRIDGE_HPP
#define BRIDGE_HPP

#include <string>
#include <type_traits>
#include <vector>
#include <boost/any.hpp>
#include <boost/blank.hpp>
#include <boost/optional.hpp>
#include <boost/variant/variant.hpp>
#include <boost/variant/get.hpp>
#include <boost/variant/recursive_wrapper.hpp>

boost::optional<std::string> get_empty_optional_string();
boost::optional<std::string> get_optional_string();

boost::any get_empty_any();
boost::any get_any_int();
boost::any get_any_string();
boost::any get_any_sample();

class sample {
public:
  sample();
  sample(const sample& rhs);
  ~sample();
  sample& operator=(const sample& rhs);
  void run();
};

typedef boost::variant<boost::blank, double, std::string> variant1;

struct node;

typedef boost::variant<boost::blank, std::string, boost::recursive_wrapper<node> > variant2;

struct node {
  std::vector<variant2> data;
};

variant2 get_variant2();

typedef boost::variant<int, char> variant3;

variant3 parse_variant3(const std::string& value);

void add(double a, double b, double* OUTPUT);

#endif


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/boostorg/json
//

#ifndef BOOST_JSON_SERIALIZE_HPP
#define BOOST_JSON_SERIALIZE_HPP

#include <boost/json/detail/config.hpp>
#include <boost/json/value.hpp>
#include <iosfwd>
#include <string>

BOOST_JSON_NS_BEGIN

/** Return a string representing a serialized element.

    This function serializes `t` as JSON and returns
    it as a `std::string`.

    @par Complexity
    Constant or linear in the size of `t`.

    @par Exception Safety
    Strong guarantee.
    Calls to allocate may throw.

    @return The serialized string

    @param t The value to serialize
*/
/** @{ */
BOOST_JSON_DECL
std::string
serialize(value const& t);

BOOST_JSON_DECL
std::string
serialize(array const& t);

BOOST_JSON_DECL
std::string
serialize(object const& t);

BOOST_JSON_DECL
std::string
serialize(string const& t);

BOOST_JSON_DECL
std::string
serialize(string_view t);
/** @} */

/** Serialize an element to an output stream.

    This function serializes the specified element
    as JSON into the output stream.

    @return `os`.

    @par Complexity
    Constant or linear in the size of `t`.

    @par Exception Safety
    Strong guarantee.
    Calls to `memory_resource::allocate` may throw.

    @param os The output stream to serialize to.

    @param t The value to serialize
*/
/** @{ */
BOOST_JSON_DECL
std::ostream&
operator<<(
    std::ostream& os,
    value const& t);

BOOST_JSON_DECL
std::ostream&
operator<<(
    std::ostream& os,
    array const& t);

BOOST_JSON_DECL
std::ostream&
operator<<(
    std::ostream& os,
    object const& t);

BOOST_JSON_DECL
std::ostream&
operator<<(
    std::ostream& os,
    string const& t);
/** @} */

BOOST_JSON_NS_END

#endif


text:
// generate by pypp <https://github.com/mugwort-rc/pypp>
// original source code: SPK_Oriented2DRendererInterface.h

#include <Extensions/Renderers/SPK_Oriented2DRendererInterface.h>
#include <boost/python.hpp>

void init_SPK_Oriented2DRendererInterface_h() {
    boost::python::class_<SPK::Oriented2DRendererInterface, std::shared_ptr<SPK::Oriented2DRendererInterface>>("Oriented2DRendererInterface",
		":brief: Constructor of Oriented2DRendererInterface")
        .def("setOrientation", &SPK::Oriented2DRendererInterface::setOrientation,
			":brief: Sets the way quads are oriented in the universe\n"
			":param orientation: the orientation of the quad\n")
        .def("getOrientation", &SPK::Oriented2DRendererInterface::getOrientation,
			":brief: Gets the orientation of the quads\n"
			":return: the orientation of the quads\n")
        .def_readwrite("orientationVector", &SPK::Oriented2DRendererInterface::orientationVector,
			":brief: The orientation vector\n"
			"\n"
			"It is used in 2 orientation modes :\n"
			"
\n"
			"
ORIENTATION2D_AXIS : The orientation vector is used as the axis
\n"
			"
ORIENTATION2D_POINT : The orientation vector is the point particle look to
\n"
			"
\n"
			"In other modes the orientation vector is not used\n")
        ;
    {
        boost::python::enum_<SPK::Orientation2D>("Orientation2D",
			":brief: Defines the orientation of a particle oriented in 2D\n"
			":since: 1.04.00\n")
            .value("ORIENTATION2D_UP", SPK::ORIENTATION2D_UP)
            .value("ORIENTATION2D_DIRECTION", SPK::ORIENTATION2D_DIRECTION)
            .value("ORIENTATION2D_POINT", SPK::ORIENTATION2D_POINT)
            .value("ORIENTATION2D_AXIS", SPK::ORIENTATION2D_AXIS)
            .export_values()
            ;
    }
}

max_stars_repo_name: chromia/pyspk

max_issues_repo_name: chromia/pyspk

max_forks_repo_name: chromia/pyspk


text:
#ifndef STATE_SYNC_HPP_
#define STATE_SYNC_HPP_

#include <lcm/lcm-cpp.hpp>

#include <boost/shared_ptr.hpp>

#include <map>
#include <model-client/model-client.hpp>

#include "lcmtypes/bot_core.hpp"
#include "lcmtypes/atlas/state_extra_t.hpp"
#include <Eigen/Dense>
#include <Eigen/StdVector>

#include <bot_param/param_client.h>
#include <bot_param/param_util.h>

#include <pronto_utils/pronto_math.hpp>
#include "atlas/AtlasControlTypes.h"
#include "atlas/AtlasJointNames.h"
#include <estimate_tools/simple_kalman_filter.hpp>
#include <estimate_tools/backlash_filter.hpp>
#include <estimate_tools/alpha_filter.hpp>
#include <estimate_tools/torque_adjustment.hpp>

struct Joints {
  std::vector<float> position;
  std::vector<float> velocity;
  std::vector<float> effort;
  std::vector<std::string> name;
};

/////////////////////////////////////
class CommandLineConfig{
  public:
    CommandLineConfig(){
      // Read from command line:
      standalone_head = false;
      standalone_hand = false;
      bdi_motion_estimate = false;
      simulation_mode = false;
      publish_pose_body = true;
      output_channel = "EST_ROBOT_STATE";
      atlas_version = 4;

      // Defaults - not read from command line:
      use_encoder_joint_sensors = false;
      use_joint_kalman_filter = false;
      use_joint_backlash_filter = false;
      use_rotation_rate_alpha_filter = false;
      use_torque_adjustment = false;
    }
    ~CommandLineConfig(){};

    bool standalone_head, standalone_hand;
    bool bdi_motion_estimate;
    bool simulation_mode;
    bool publish_pose_body;
    std::string output_channel;
    int atlas_version;

    bool use_encoder_joint_sensors;
    bool use_joint_kalman_filter;
    bool use_joint_backlash_filter;
    bool use_rotation_rate_alpha_filter;
    bool use_torque_adjustment;
};

///////////////////////////////////////////////////////////////
class state_sync{
  public:
    state_sync(boost::shared_ptr<lcm::LCM> &lcm_, boost::shared_ptr<CommandLineConfig> &cl_cfg_);

    ~state_sync(){
    }
    void Identity();

    void setBotParam(BotParam* new_botparam){
      botparam_ = new_botparam;
    }
    void setEncodersFromParam();

  private:
    boost::shared_ptr<CommandLineConfig> cl_cfg_;
    boost::shared_ptr<lcm::LCM> lcm_;
    boost::shared_ptr<ModelClient> model_;
    BotParam* botparam_;

    long utime_prev_;

    void coreRobotHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::joint_state_t* msg);
    void forceTorqueHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::six_axis_force_torque_array_t* msg);
    void multisenseHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::joint_state_t* msg);
    void leftHandHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::joint_state_t* msg);
    void rightHandHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::joint_state_t* msg);
    void poseBDIHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::pose_t* msg);
    void poseMITHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::pose_t* msg);
    void atlasExtraHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  atlas::state_extra_t* msg);

    void enableEncoderHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const  bot_core::utime_t* msg);
    void enableEncoders(bool enable);

    Joints head_joints_;
    Joints core_robot_joints_;
    Joints left_hand_joints_;
    Joints right_hand_joints_;
    Joints core_robot_joints_out_;

    PoseT pose_BDI_;
    PoseT pose_MIT_;
    void setPoseToZero(PoseT &pose);

    // Kalman/Backlash Filters for joint angles:
    void filterJoints(int64_t utime, std::vector<float> &joint_position, std::vector<float> &joint_velocity);
    std::vector<int> filter_idx_;
    std::vector<EstimateTools::SimpleKalmanFilter*> joint_kf_;
    std::vector<EstimateTools::BacklashFilter*> joint_backlashfilter_;

    // Alpha Filters:
    EstimateTools::AlphaFilter* rotation_rate_alpha_filter_;
    EstimateTools::AlphaFilter* neck_alpha_filter_;

    // Torque Adjustment:
    EstimateTools::TorqueAdjustment* torque_adjustment_;

    // Upper Body Encoder Calibrations:
    std::vector<float> encoder_joint_offsets_;
    std::vector<float> max_encoder_wrap_angle_;
    std::vector<bool> use_encoder_;
    std::vector<int> encoder_joint_indices_;
    std::vector<int> extra_offsettable_joint_indices_;

    void publishRobotState(int64_t utime_in, const  bot_core::six_axis_force_torque_array_t& msg);
    void appendJoints(bot_core::robot_state_t& msg_out, Joints joints);

    bool insertPoseInRobotState(bot_core::robot_state_t& msg, PoseT pose);

    bot_core::six_axis_force_torque_array_t force_torque_; // More recent force torque messurement
    bool force_torque_init_; // Have we received a force torque message?

};

#endif

max_stars_repo_name: liangfok/oh-distro

max_issues_repo_name: liangfok/oh-distro

max_forks_repo_name: liangfok/oh-distro


text:
/*
 *          Copyright Andrey Semashev 2007 - 2015.
 * Distributed under the Boost Software License, Version 1.0.
 *    (See accompanying file LICENSE_1_0.txt or copy at
 *          http://www.boost.org/LICENSE_1_0.txt)
 */
/*!
 * \file   windows_version.hpp
 * \author Andrey Semashev
 * \date   07.03.2009
 *
 * \brief  This header is the Boost.Log library implementation, see the library documentation
 *         at http://www.boost.org/doc/libs/release/libs/log/doc/html/index.html.
 */

#ifndef BOOST_LOG_WINDOWS_VERSION_HPP_INCLUDED_
#define BOOST_LOG_WINDOWS_VERSION_HPP_INCLUDED_

#include <boost/log/detail/config.hpp>

#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)

#if defined(BOOST_LOG_USE_WINNT6_API)

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0600 // _WIN32_WINNT_LONGHORN
#endif

#elif !defined(_WIN32_WINNT)

// Use the default WinAPI version
#include <boost/detail/winapi/config.hpp>

#if !defined(_WIN32_WINNT)
#define _WIN32_WINNT BOOST_USE_WINAPI_VERSION
#endif

#endif // BOOST_LOG_USE_WINNT6_API

// This is to make Boost.ASIO happy
#ifndef __USE_W32_SOCKETS
#define __USE_W32_SOCKETS
#endif

#ifndef NOMINMAX
#define NOMINMAX
#endif

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#endif // defined(BOOST_WINDOWS) || defined(__CYGWIN__)

#endif // BOOST_LOG_WINDOWS_VERSION_HPP_INCLUDED_


text:
#include "myslam/visual_odometry.h"
#include "myslam/config.h"

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>

#include <algorithm>
#include <boost/timer.hpp>

namespace myslam{
    VisualOdometry::VisualOdometry():
    state_ ( INITIALIZING ), ref_ ( nullptr ), curr_ ( nullptr ), map_ ( new Map ), num_lost_ ( 0 ), num_inliers_ ( 0 )
    {
        num_of_features_    = Config::get<int> ( "number_of_features" );
        scale_factor_       = Config::get<double> ( "scale_factor" );
        level_pyramid_      = Config::get<int> ( "level_pyramid" );
        match_ratio_        = Config::get<float> ( "match_ratio" );
        max_num_lost_       = Config::get<float> ( "max_num_lost" );
        min_inliers_        = Config::get<int> ( "min_inliers" );
        key_frame_min_rot_   = Config::get<double> ( "keyframe_rotation" );
        key_frame_min_trans_ = Config::get<double> ( "keyframe_translation" );
        orb_ = cv::ORB::create ( num_of_features_, scale_factor_, level_pyramid_ );
    }

    VisualOdometry::~VisualOdometry(){

    }

    bool VisualOdometry::addFrame(Frame::Ptr frame){
        switch (state_)
        {
        case INITIALIZING:{
            state_ = OK;
            curr_ = frame;
            ref_ = frame;
            map_->insertKeyFrame(frame);
            // Extract feature from first frame
            extractKeyPoints();
            computerDescriptors();
            // Treat No.1 Frame as keyframe
            addKeyFrame();
            break;
        }

        case OK:{
            curr_ = frame;
            curr_->T_w_c_ = ref_->T_w_c_;
            extractKeyPoints();
            computerDescriptors();
            featureMatching();
            poseEstimationPnP();

            if (checkEstimatedPose() == true){
                curr_->T_w_c_ = T_c_r_estimated_; // update current camera pose

                optimizeMap();
                num_lost_ = 0;
                if (checkKeyFrame() == true){  // if current frame is a keyframe, add it
                    addKeyFrame();
                }
            }
            else{
                num_lost_++;
                if(num_lost_ > max_num_lost_){
                    state_ = LOST;
                }
                return false;
            }

            break;
        }

        case LOST:{
            // Nothing we can do to invert.
            cout << "SLAM have lost" << endl;
            break;
        }
        default:
            break;
        }

        return true;
    }

    void VisualOdometry::extractKeyPoints(){
        orb_->detect(curr_->color_, keypoints_curr_);
    }

    void VisualOdometry::computerDescriptors(){
        orb_->compute(curr_->color_, keypoints_curr_, descriptors_curr_);
    }

    void VisualOdometry::featureMatching(){
        // Select a portion of Map Points to match current feature
        vector<cv::DMatch> matches;
        boost::timer timer;

        Mat descriptor_map;
        vector<MapPoint::Ptr> candidate;

        for(auto& allpoints:map_->map_points_){
            MapPoint::Ptr& p = allpoints.second;                    // Map as unordered_map
            if(curr_->isInFrame(p->pos_)){
                p->visible_times_++;
                candidate.push_back(p);
                descriptor_map.push_back(p->descriptor_);
            }
        }

        matcher_flann_.match(descriptor_map, descriptors_curr_, matches);

        float min_dis = std::min_element(matches.begin(), matches.end(),
                          [](const cv::DMatch& m1, const cv::DMatch& m2){
                              return m1.distance < m2.distance;
                          })->distance;

        match_3dpts_.clear();
        match_2dkp_index_.clear();
        // filter out long distance matches
        for (cv::DMatch& m:matches){
            if(m.distance < 2*min_dis){
                match_3dpts_.push_back(candidate[m.queryIdx]);
                match_2dkp_index_.push_back(m.trainIdx);
            }
        }
        cout << "good matches number: " << match_3dpts_.size() << endl;
    }

    void VisualOdometry::poseEstimationPnP(){
        vector<cv::Point3f> pts3d;
        vector<cv::Point2f> pts2d;

        for ( int index:match_2dkp_index_ )
        {
            pts2d.push_back ( keypoints_curr_[index].pt );
        }
        for ( MapPoint::Ptr pt:match_3dpts_ )
        {
            pts3d.push_back( pt->getPositionCV() );
        }

        Mat K = (cv::Mat_<double>(3, 3) <<
            ref_->camera_->fx_, 0, ref_->camera_->cx_,
            0, ref_->camera_->fy_, ref_->camera_->cy_,
            0, 0, 1);

        Mat rvec, tvec, inliers;
        cv::solvePnPRansac(pts3d, pts2d, K, Mat(), rvec, tvec, false, 100, 4.0, 0.99, inliers);
        num_inliers_ = inliers.rows;
        cout<<"pnp inliers: "<<num_inliers_<<endl;

        T_c_r_estimated_ = SE3(
            SO3(rvec.at<double>(0, 0), rvec.at<double>(1, 0), rvec.at<double>(2, 0)),
            Vector3d(tvec.at<double>(0, 0), tvec.at<double>(1, 0), tvec.at<double>(2, 0))
        );
    }

    void VisualOdometry::poseEstimationPnPwithBA(){

        // construct the 3d 2d observations
        vector<cv::Point3f> pts3d;
        vector<cv::Point2f> pts2d;

        for ( int index:match_2dkp_index_ )
        {
            pts2d.push_back ( keypoints_curr_[index].pt );
        }
        for ( MapPoint::Ptr pt:match_3dpts_ )
        {
            pts3d.push_back( pt->getPositionCV() );
        }

        Mat K = ( cv::Mat_<double>(3,3)<<
            ref_->camera_->fx_, 0, ref_->camera_->cx_,
            0, ref_->camera_->fy_, ref_->camera_->cy_,
            0,0,1
        );
        Mat rvec, tvec, inliers;
        cv::solvePnPRansac( pts3d, pts2d, K, Mat(), rvec, tvec, false, 100, 4.0, 0.99, inliers );
        num_inliers_ = inliers.rows;
        cout<<"pnp inliers: "<<num_inliers_<<endl;
        T_c_r_estimated_ = SE3(
            SO3(rvec.at<double>(0,0), rvec.at<double>(1,0), rvec.at<double>(2,0)),
            Vector3d( tvec.at<double>(0,0), tvec.at<double>(1,0), tvec.at<double>(2,0))
        );

        typedef g2o::BlockSolver<g2o::BlockSolverTraits<6, 2>> Block;
        Block::LinearSolverType* linearSolver = new g2o::LinearSolverDense<Block::PoseMatrixType>();
        Block* solver_ptr = new Block(linearSolver);
        g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg(solver_ptr);
        g2o::SparseOptimizer optimizer;
        optimizer.setAlgorithm(solver);

        // add vertices
        g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap();
        pose->setId(0);
        pose->setEstimate(g2o::SE3Quat(
            T_c_r_estimated_.rotation_matrix(), T_c_r_estimated_.translation()
        ));
        optimizer.addVertex(pose);

        // Add edge
        for(int i = 0;i<inliers.rows; i++){
            int index = inliers.at<int>(i, 0);

            EdgeProjectXYZ2UVPoseOnly* edge = new EdgeProjectXYZ2UVPoseOnly();
            edge->setId(i);
            edge->setVertex(0, pose);
            edge->camera_ = curr_->camera_.get();
            edge->point_ = Vector3d(pts3d[index].x, pts3d[index].y, pts3d[index].z);
            edge->setMeasurement(Vector2d(pts2d[index].x, pts2d[index].y));
            edge->setInformation(Eigen::Matrix2d::Identity());
            optimizer.addEdge(edge);
        }

        optimizer.initializeOptimization();
        optimizer.optimize(10);

        T_c_r_estimated_ = SE3(pose->estimate().rotation(), pose->estimate().translation);
    }

    bool VisualOdometry::checkEstimatedPose(){
        if(num_inliers_ < min_inliers_){
            cout<<"reject because inlier is too small: "<<num_inliers_<<endl;
            return false;
        }
        // if the motion is too large, it is probably wrong
        Sophus::Vector6d d = T_c_r_estimated_.log();
        if ( d.norm() > 5.0 )
        {
            cout<<"reject because motion is too large: "<<d.norm()<<endl;
            return false;
        }
        return true;
    }

    bool VisualOdometry::checkKeyFrame(){
        // simple key frame classification. norm > threshold as Key Frame
        Sophus::Vector6d d = T_c_r_estimated_.log();
        Vector3d trans = d.head<3>();
        Vector2d rot = d.tail<3>();
        if(trans.norm() > key_frame_min_trans_ || rot.norm() > key_frame_min_rot_){
            return true;
        }
        return false;
    }

    void VisualOdometry::addKeyFrame(){
        if(map_->keyframes_.empty()){
            for(size_t i = 0;i<keypoints_curr_.size();i++){
                double d = curr_->findDepth ( keypoints_curr_[i] );
                if ( d < 0 )
                    continue;
                Vector3d p_world = ref_->camera_->pixel2world (
                    Vector2d ( keypoints_curr_[i].pt.x, keypoints_curr_[i].pt.y ), curr_->T_w_c_, d
                );
                Vector3d n = p_world - ref_->getCamCenter();
                n.normalize();
                MapPoint::Ptr map_point = MapPoint::createMapPoint(
                    p_world, n, descriptors_curr_.row(i).clone(), curr_.get()
                );
                map_->insertMapPoint( map_point );
            }
        }
        map_->insertKeyFrame(curr_);
        ref_ = curr_;
    }

    void VisualOdometry::optimizeMap(){
        for(auto iter = map_->map_points_.begin(); iter!=map_->map_points_.end();){
            if(! curr_->isInFrame(iter->second->pos_)){
                iter = map_->map_points_.erase(iter);
                continue;
            }

            float match_ratio = float(iter->second->matched_times_) / iter->second->visible_times_;
            if(match_ratio < map_point_erase_ratio_){
                iter = map_->map_points_.erase(iter);
                continue;
            }

            double angle = getViewAngle( curr_, iter->second);
            if(angle > M_PI/6.){
                iter = map_->map_points_.erase(iter);
            }

            if(iter->second->good_ = false){
                // Triangle

            }
            iter++;

        }

        if(match_2dkp_index_.size() < 100){
            addMapPoints();
        }
        if ( map_->map_points_.size() > 1000 )
        {
            // TODO map is too large, remove some one
            map_point_erase_ratio_ += 0.05;
        }
        else
            map_point_erase_ratio_ = 0.1;
        cout<<"map points: "<<map_->map_points_.size()<<endl;
    }

    double VisualOdometry::getViewAngle(Frame::Ptr frame, MapPoint::Ptr point){
        Vector3d n = point->pos_ - frame->getCamCenter();
        n.normalize();
        return acos(n.transpose() * point->norm_);  // Inner product of two norm vector to calculate the angle between
                                                    // camera axis and mappoint
    }
}


text:
// Boost Includes ==============================================================
#include <boost/python.hpp>
#include <boost/cstdint.hpp>

// Includes ====================================================================
#include <Magick++/Drawable.h>

// Using =======================================================================
using namespace boost::python;

// Module ======================================================================
void Export_pyste_src_Coordinate()
{
    class_< Magick::Coordinate, boost::noncopyable >("Coordinate", init<  >())
        .def(init< double, double >())
        .def("x", (void (Magick::Coordinate::*)(double) )&Magick::Coordinate::x)
        .def("x", (double (Magick::Coordinate::*)() const)&Magick::Coordinate::x)
        .def("y", (void (Magick::Coordinate::*)(double) )&Magick::Coordinate::y)
        .def("y", (double (Magick::Coordinate::*)() const)&Magick::Coordinate::y)
        .def( self >= self )
        .def( self <= self )
        .def( self > self )
        .def( self < self )
        .def( self == self )
        .def( self != self )
    ;

}

max_stars_repo_name: jeikabu/lumberyard

max_issues_repo_name: jeikabu/lumberyard

max_forks_repo_name: jeikabu/lumberyard


text:
#include "Board.hpp"

#include <boost/functional/hash.hpp>

namespace WayoutPlayer {

S32 Board::getRowCount() const {
  return static_cast<S32>(matrix.size());
}

S32 Board::getColumnCount() const {
  return static_cast<S32>(matrix.front().size());
}

bool Board::mayNeedMultipleClicks() const {
  return startedWithBlockedTiles;
}

bool Board::canBeSolvedOptimallyDirectionally() const {
  for (S32 i = 0; i < getRowCount(); i++) {
    for (S32 j = 0; j < getColumnCount(); j++) {
      if (hasTile(i, j)) {
        const auto type = getTile(i, j).type;
        if (type == TileType::Blocked || type == TileType::Chain || type == TileType::Twin) {
          return false;
        }
      }
    }
  }
  return true;
}

void Board::safeInvert(IndexType i, IndexType j, bool clicked, InversionHistory &history) {
  if (!hasTile(i, j)) {
    return;
  }
  if (matrix[i][j]->type == TileType::Tap) {
    if (clicked) {
      matrix[i][j]->up = !matrix[i][j]->up;
      history.inversions.emplace_back(i, j);
    }
  } else if (matrix[i][j]->type == TileType::Blocked) {
    if (clicked) {
      throw std::runtime_error("Cannot click on a blocked tile.");
    }
    matrix[i][j]->type = TileType::Default;
  } else if (matrix[i][j]->type == TileType::Chain) {
    matrix[i][j]->up = !matrix[i][j]->up;
    history.inversions.emplace_back(i, j);
    // This will work as a default tile unless it was not clicked.
    if (clicked) {
      return;
    }
    const auto propagate = [this, &history](IndexType ni, IndexType nj) {
      const auto begin = std::begin(history.inversions);
      const auto end = std::end(history.inversions);
      if (std::find(begin, end, Position{ni, nj}) == end) {
        safeInvert(ni, nj, false, history);
      }
    };
    propagate(i - 1, j);
    propagate(i, j - 1);
    propagate(i, j + 1);
    propagate(i + 1, j);
  } else if (matrix[i][j]->type == TileType::Twin) {
    if (!history.twinFinalState) {
      history.twinFinalState = !matrix[i][j]->up;
    }
    matrix[i][j]->up = *history.twinFinalState;
  } else {
    matrix[i][j]->up = !matrix[i][j]->up;
    history.inversions.emplace_back(i, j);
  }
}

Board::Board(std::vector<std::vector<std::optional<Tile>>> tileMatrix) : matrix(std::move(tileMatrix)) {
  const auto firstRowSize = matrix.front().size();
  for (const auto &row : matrix) {
    if (row.size() != firstRowSize) {
      throw std::invalid_argument("Matrix is not rectangular.");
    }
    for (const auto tile : row) {
      if (tile && tile->type == TileType::Blocked) {
        startedWithBlockedTiles = true;
      }
    }
  }
}

bool Board::hasUnsolvedTilesAtRow(IndexType i) const {
  if (i < 0 || i >= getRowCount()) {
    return false;
  }
  for (S32 j = 0; j < getColumnCount(); j++) {
    if (hasTile(i, j)) {
      if (matrix[i][j]->up || matrix[i][j]->type == TileType::Blocked) {
        return true;
      }
    }
  }
  return false;
}

bool Board::hasTile(IndexType i, IndexType j) const {
  return i >= 0 && i < getRowCount() && j >= 0 && j < getColumnCount() && matrix[i][j].has_value();
}

Tile Board::getTile(IndexType i, IndexType j) const {
  return matrix[i][j].value();
}

bool Board::isSolved() const {
  for (S32 i = 0; i < getRowCount(); i++) {
    for (S32 j = 0; j < getColumnCount(); j++) {
      if (hasTile(i, j)) {
        if (matrix[i][j]->up || matrix[i][j]->type == TileType::Blocked) {
          return false;
        }
      }
    }
  }
  return true;
}

void Board::activate(IndexType i, IndexType j) {
  if (!hasTile(i, j)) {
    return;
  }
  const auto tile = getTile(i, j);
  const auto type = tile.type;
  InversionHistory history;
  safeInvert(i, j, true, history);
  if (type == TileType::Default || type == TileType::Tap || type == TileType::Chain || type == TileType::Twin) {
    safeInvert(i - 1, j, false, history);
    safeInvert(i, j - 1, false, history);
    safeInvert(i, j + 1, false, history);
    safeInvert(i + 1, j, false, history);
  } else if (type == TileType::Horizontal) {
    safeInvert(i, j - 1, false, history);
    safeInvert(i, j + 1, false, history);
  } else if (type == TileType::Vertical) {
    safeInvert(i - 1, j, false, history);
    safeInvert(i + 1, j, false, history);
  } else if (type == TileType::Blocked) {
    throw std::runtime_error("Cannot activate a blocked tile.");
  } else {
    throw std::invalid_argument("Did not match the tile type.");
  }
  if (history.twinFinalState) {
    // Set all other twins to this state.
    for (S32 otherI = 0; otherI < getRowCount(); otherI++) {
      for (S32 otherJ = 0; otherJ < getColumnCount(); otherJ++) {
        if (otherI == i && otherJ == j) {
          continue;
        }
        if (hasTile(otherI, otherJ)) {
          if (matrix[otherI][otherJ]->type == TileType::Twin) {
            matrix[otherI][otherJ]->up = *history.twinFinalState;
          }
        }
      }
    }
  }
}

std::size_t Board::hash() const {
  std::size_t seed = 0;
  for (S32 i = 0; i < getRowCount(); i++) {
    for (S32 j = 0; j < getColumnCount(); j++) {
      if (hasTile(i, j)) {
        boost::hash_combine(seed, tileTypeToInteger(matrix[i][j]->type));
        boost::hash_combine(seed, matrix[i][j]->up);
      }
    }
  }
  return seed;
}

bool Board::operator==(const Board &rhs) const {
  return matrix == rhs.matrix;
}

bool Board::operator!=(const Board &rhs) const {
  return !(rhs == *this);
}

std::vector<Board> Board::splitComponents() const {
  using TagType = U32;
  const auto NoTag = std::numeric_limits<TagType>::max();
  using TaggedTileMatrix = std::vector<std::vector<TagType>>;
  const auto rowCount = getRowCount();
  const auto columnCount = getColumnCount();
  TaggedTileMatrix tagMatrix(rowCount, std::vector<TagType>(columnCount, NoTag));
  TagType currentTag = 0;
  auto foundTwin = false;
  using PositionFunction = std::function<void(S32, S32)>;
  const PositionFunction propagateTag = [this, &tagMatrix, &currentTag, &foundTwin, &propagateTag](S32 i, S32 j) {
    if (!hasTile(i, j)) {
      return;
    }
    if (tagMatrix[i][j] == NoTag) {
      tagMatrix[i][j] = currentTag;
      // Propagate to all other twins.
      const auto rowCount = getRowCount();
      const auto columnCount = getColumnCount();
      if (getTile(i, j).type == TileType::Twin) {
        // This check is important to prevent an infinite recursion.
        if (!foundTwin) {
          foundTwin = true;
          for (S32 oi = 0; oi < rowCount; oi++) {
            for (S32 oj = 0; oj < columnCount; oj++) {
              if (oi == i && oj == j) {
                continue;
              }
              if (hasTile(oi, oj)) {
                if (getTile(oi, oj).type == TileType::Twin) {
                  propagateTag(oi, oj);
                }
              }
            }
          }
        }
      }
      propagateTag(i - 1, j);
      propagateTag(i, j - 1);
      propagateTag(i, j + 1);
      propagateTag(i + 1, j);
    } else if (tagMatrix[i][j] != currentTag) {
      throw std::runtime_error("Should not happen: found a tile tagged with another tag while propagating a tag.");
    }
  };
  for (S32 i = 0; i < rowCount; i++) {
    for (S32 j = 0; j < columnCount; j++) {
      if (hasTile(i, j)) {
        if (tagMatrix[i][j] == NoTag) {
          propagateTag(i, j);
          currentTag++;
        }
      }
    }
  }
  const auto componentCount = currentTag;
  const auto emptyRow = std::vector<std::optional<Tile>>(columnCount);
  using TileMatrix = std::vector<std::vector<std::optional<Tile>>>;
  const auto emptyTileMatrix = TileMatrix(rowCount, emptyRow);
  auto tileMatrices = std::vector<TileMatrix>(componentCount, emptyTileMatrix);
  for (S32 i = 0; i < rowCount; i++) {
    for (S32 j = 0; j < columnCount; j++) {
      if (tagMatrix[i][j] != NoTag) {
        tileMatrices[tagMatrix[i][j]][i][j] = getTile(i, j);
      }
    }
  }
  auto components = std::vector<Board>{};
  for (const auto &tileMatrix : tileMatrices) {
    components.emplace_back(tileMatrix);
  }
  return components;
}

Board Board::mergeComponents(const std::vector<Board> &components) {
  if (components.empty()) {
    throw std::invalid_argument("Components should not be empty.");
  }
  const auto rowCount = components.front().getRowCount();
  const auto columnCount = components.front().getColumnCount();
  for (const auto &component : components) {
    if (component.getRowCount() != rowCount) {
      throw std::invalid_argument("Components have different number of rows.");
    } else {
      if (component.getColumnCount() != columnCount) {
        throw std::invalid_argument("Components have different number of columns.");
      }
    }
  }
  Board merge(std::vector<std::vector<std::optional<Tile>>>(rowCount, std::vector<std::optional<Tile>>(columnCount)));
  for (const auto &component : components) {
    for (S32 i = 0; i < rowCount; i++) {
      for (S32 j = 0; j < columnCount; j++) {
        if (component.hasTile(i, j)) {
          if (merge.hasTile(i, j)) {
            const auto position = Position(i, j);
            throw std::invalid_argument("Found two occurrences of tile " + position.toString() + ".");
          } else {
            merge.matrix[i][j] = component.matrix[i][j];
          }
        }
      }
    }
  }
  return merge;
}

std::string Board::toString() const {
  const auto rowCount = getRowCount();
  const auto columnCount = getColumnCount();
  std::string board;
  for (S32 i = 0; i < rowCount; i++) {
    for (S32 j = 0; j < columnCount; j++) {
      if (hasTile(i, j)) {
        board += matrix[i][j]->toString();
      } else {
        board += "  ";
      }
      if (j + 1 < columnCount) {
        board += ' ';
      }
    }
    if (i + 1 < rowCount) {
      board += '\n';
    }
  }
  return board;
}

Board Board::fromString(const std::string &string) {
  if (string.empty()) {
    throw std::invalid_argument("Cannot create a board from an empty string.");
  }
  std::vector<std::vector<std::optional<Tile>>> matrix(1);
  auto atNextTile = true;
  for (std::size_t i = 0; i < string.size(); i++) {
    const auto character = string[i];
    if (atNextTile) {
      if (isalpha(character)) {
        matrix.back().emplace_back(Tile(false, tileTypeFromCharacter(character)));
        atNextTile = false;
      } else if (character == ' ') {
        matrix.back().push_back(std::nullopt);
        atNextTile = false;
        i++;
      } else {
        throw std::invalid_argument("Found an unexpected start of tile: " + std::string(1, character) + ".");
      }
    } else {
      if (isdigit(character)) {
        matrix.back().back()->up = character == '1';
      } else if (character == '\n') {
        matrix.emplace_back();
        atNextTile = true;
      } else if (character == ' ') {
        atNextTile = true;
      } else {
        const auto message = "String has an invalid character: '" + std::string(1, character) + "'.";
        throw std::invalid_argument(message);
      }
    }
  }
  while (matrix.back().empty()) {
    matrix.pop_back();
  }
  return Board(matrix);
}
} // namespace WayoutPlayer

max_stars_repo_name: bernardosulzbach/wayout-player

max_issues_repo_name: bernardosulzbach/wayout-player

max_forks_repo_name: bernardosulzbach/wayout-player


text:
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/assert.hpp>

#include <support/cnumeric.hpp>
namespace hana = boost::hana;

template <bool value>
auto constant_bool() { return make_cnumeric<bool, value>(); }

template <bool value>
constexpr auto constexpr_constant_bool() { return make_cnumeric<bool, value>(); }

// Make sure it works at global scope
BOOST_HANA_CONSTANT_ASSERT(constant_bool<true>());
BOOST_HANA_CONSTANT_ASSERT_MSG(constant_bool<true>(), "message");

// Make sure it works at namespace scope
namespace ns {
    BOOST_HANA_CONSTANT_ASSERT(constant_bool<true>());
    BOOST_HANA_CONSTANT_ASSERT_MSG(constant_bool<true>(), "message");
}

// Make sure it works in a constexpr context
constexpr bool constexpr_context() {
    BOOST_HANA_CONSTANT_ASSERT(constexpr_constant_bool<true>());
    BOOST_HANA_CONSTANT_ASSERT_MSG(constexpr_constant_bool<true>(), "message");
    return true;
}
static_assert(constexpr_context(), "");

int main() {
    // Make sure it works at function scope
    BOOST_HANA_CONSTANT_ASSERT(constant_bool<true>());
    BOOST_HANA_CONSTANT_ASSERT_MSG(constant_bool<true>(), "message");

    // Make sure it works inside a lambda
    auto lambda = []{
        BOOST_HANA_CONSTANT_ASSERT(constant_bool<true>());
        BOOST_HANA_CONSTANT_ASSERT_MSG(constant_bool<true>(), "message");
    };
    lambda();

    // Make sure we can reference a local variable
    auto yes = constant_bool<true>();
    BOOST_HANA_CONSTANT_ASSERT(yes);
    BOOST_HANA_CONSTANT_ASSERT_MSG(yes, "message");
}


text:
/*!
@file
Forward declares `boost::hana::Logical`.

@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#ifndef BOOST_HANA_LOGICAL_LOGICAL_HPP
#define BOOST_HANA_LOGICAL_LOGICAL_HPP

#include <boost/hana/logical/detail/logical_fwd.hpp>

#include <boost/hana/core/typeclass.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/detail/variadic/foldl.hpp>

namespace boost { namespace hana {
    //! Minimal complete definition: `eval_if` and `not_`
    struct Logical::mcd {
        template <typename X, typename Y>
        static constexpr auto or_impl(X x, Y y)
        { return if_(x, x, y); }

        template <typename X, typename Y>
        static constexpr auto and_impl(X x, Y y)
        { return if_(x, y, x); }

        template <typename C, typename T, typename E>
        static constexpr auto if_impl(C c, T t, E e) {
            return eval_if(c,
                [=](auto) { return t; },
                [=](auto) { return e; }
            );
        }
    };

    //! Instance of `Logical` for objects with a data type that can be
    //! converted to `bool` implicitly.
    //!
    //! Any object whose data type can be converted to `bool` implicitly is
    //! an instance of `Logical` by converting that object to `bool` and then
    //! using the obvious instance for `bool`.
    template <typename T>
    struct Logical::instance<T, when<is_valid<decltype(*(T*)0 ? (void)0 : (void)0)>>>
        : Logical::mcd
    {
        template <typename Then, typename Else>
        static constexpr auto eval_if_impl(bool cond, Then t, Else e) {
            auto id = [](auto x) { return x; };
            return cond ? t(id) : e(id);
        }

        static constexpr auto not_impl(bool cond)
        { return !cond; }
    };
}} // end namespace boost::hana

#endif // !BOOST_HANA_LOGICAL_LOGICAL_HPP

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


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

#ifndef BINSPECTOR_DOT_HPP
#define BINSPECTOR_DOT_HPP

// boost
#include <boost/filesystem.hpp>

// application
#include <binspector/analyzer.hpp>

/****************************************************************************************************/

void dot_graph(const binspector_analyzer_t::structure_map_t& struct_map,
               const std::string&                            starting_struct,
               const boost::filesystem::path&                output_root);

/****************************************************************************************************/
// BINSPECTOR_DOT_HPP
#endif

/****************************************************************************************************/