text:
/*
 * Copyright (C) 2012 Open Source Robotics Foundation
 *
 * 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.
 *
*/
#ifdef _WIN32
  // Ensure that Winsock2.h is included before Windows.h, which can get
  // pulled in by anybody (e.g., Boost).
  #include <Winsock2.h>
#endif

#include <functional>
#include <boost/bind.hpp>
#include "gazebo/common/Assert.hh"
#include "gazebo/common/Time.hh"

#include "gazebo/physics/PhysicsIface.hh"
#include "gazebo/physics/PhysicsEngine.hh"
#include "gazebo/physics/World.hh"
#include "gazebo/sensors/Sensor.hh"
#include "gazebo/sensors/SensorsIface.hh"
#include "gazebo/sensors/SensorFactory.hh"
#include "gazebo/sensors/SensorManager.hh"
#include "gazebo/util/LogPlay.hh"

using namespace gazebo;
using namespace sensors;

/// \brief A mutex used by SensorContainer and SimTimeEventHandler
/// for timing coordination.
boost::mutex g_sensorTimingMutex;

//////////////////////////////////////////////////
SensorManager::SensorManager()
  : initialized(false), removeAllSensors(false)
{
  // sensors::IMAGE container
  this->sensorContainers.push_back(new ImageSensorContainer());

  // sensors::RAY container
  this->sensorContainers.push_back(new SensorContainer());

  // sensors::OTHER container
  this->sensorContainers.push_back(new SensorContainer());
}

//////////////////////////////////////////////////
SensorManager::~SensorManager()
{
  sensors::disable();
  // Clean up the sensors.
  for (SensorContainer_V::iterator iter = this->sensorContainers.begin();
       iter != this->sensorContainers.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor Constainer is null");
    (*iter)->Stop();
    (*iter)->RemoveSensors();
    delete (*iter);
  }
  this->sensorContainers.clear();

  this->initSensors.clear();
}

//////////////////////////////////////////////////
void SensorManager::RunThreads()
{
  // Start the non-image sensor containers. The first item in the
  // sensorsContainers list are the image-based sensors, which rely on the
  // rendering engine, which in turn requires that they run in the main
  // thread.
  for (SensorContainer_V::iterator iter = ++this->sensorContainers.begin();
       iter != this->sensorContainers.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor Constainer is null");
    (*iter)->Run();
  }
}

//////////////////////////////////////////////////
void SensorManager::Stop()
{
  // Start all the sensor containers.
  for (SensorContainer_V::iterator iter = this->sensorContainers.begin();
       iter != this->sensorContainers.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor Constainer is null");
    (*iter)->Stop();
  }

  if (!physics::worlds_running())
    this->worlds.clear();
}

//////////////////////////////////////////////////
bool SensorManager::Running() const
{
  for (auto const &container : this->sensorContainers)
  {
    if (container->Running())
      return true;
  }
  return false;
}

//////////////////////////////////////////////////
void SensorManager::Update(bool _force)
{
  {
    boost::recursive_mutex::scoped_lock lock(this->mutex);

    if (this->worlds.empty() && physics::worlds_running() && this->initialized)
    {
      auto world = physics::get_world();
      this->worlds[world->Name()] = world;
      world->_SetSensorsInitialized(true);
    }

    if (!this->initSensors.empty())
    {
      // in case things are spawned, sensors length changes
      for (auto &sensor : this->initSensors)
      {
        GZ_ASSERT(sensor != nullptr, "Sensor pointer is null");
        GZ_ASSERT(sensor->Category() < 0 ||
            sensor->Category() < CATEGORY_COUNT, "Sensor category is empty");
        GZ_ASSERT(this->sensorContainers[sensor->Category()] != nullptr,
            "Sensor container is null");

        sensor->Init();
        this->sensorContainers[sensor->Category()]->AddSensor(sensor);
      }
      this->initSensors.clear();
      for (auto &worldName_worldPtr : this->worlds)
        worldName_worldPtr.second->_SetSensorsInitialized(true);
    }

    for (std::vector<std::string>::iterator iter = this->removeSensors.begin();
         iter != this->removeSensors.end(); ++iter)
    {
      GZ_ASSERT(!(*iter).empty(), "Remove sensor name is empty.");

      bool removed = false;
      for (SensorContainer_V::iterator iter2 = this->sensorContainers.begin();
           iter2 != this->sensorContainers.end() && !removed; ++iter2)
      {
        GZ_ASSERT((*iter2) != nullptr, "SensorContainer is null");

        removed = (*iter2)->RemoveSensor(*iter);
      }

      if (!removed)
      {
        gzerr << "RemoveSensor failed. The SensorManager's list of sensors "
              << "changed during sensor removal. This is bad, and should "
              << "never happen.\n";
      }
    }
    this->removeSensors.clear();

    if (this->removeAllSensors)
    {
      for (SensorContainer_V::iterator iter2 = this->sensorContainers.begin();
          iter2 != this->sensorContainers.end(); ++iter2)
      {
        GZ_ASSERT((*iter2) != nullptr, "SensorContainer is null");
        (*iter2)->RemoveSensors();
      }
      this->initSensors.clear();

      // Also clear the list of worlds
      this->worlds.clear();

      this->removeAllSensors = false;
    }
  }

  // Only update if there are sensors
  if (this->sensorContainers[sensors::IMAGE]->sensors.size() > 0)
    this->sensorContainers[sensors::IMAGE]->Update(_force);
}

//////////////////////////////////////////////////
bool SensorManager::SensorsInitialized()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);
  bool result = this->initSensors.empty();
  return result;
}

//////////////////////////////////////////////////
void SensorManager::ResetLastUpdateTimes()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);
  for (SensorContainer_V::iterator iter = this->sensorContainers.begin();
       iter != this->sensorContainers.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "SensorContainer is null");
    (*iter)->ResetLastUpdateTimes();
  }
}

//////////////////////////////////////////////////
void SensorManager::Init()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  this->simTimeEventHandler = new SimTimeEventHandler();

  // Initialize all the sensor containers.
  for (SensorContainer_V::iterator iter = this->sensorContainers.begin();
       iter != this->sensorContainers.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "SensorContainer is null");
    (*iter)->Init();
  }

  // Connect to the time reset event.
  this->timeResetConnection = event::Events::ConnectTimeReset(
      std::bind(&SensorManager::ResetLastUpdateTimes, this));

  // Connect to the remove sensor event.
  this->removeSensorConnection = event::Events::ConnectRemoveSensor(
      std::bind(&SensorManager::RemoveSensor, this, std::placeholders::_1));

  // Connect to the create sensor event.
  this->createSensorConnection = event::Events::ConnectCreateSensor(
      std::bind(&SensorManager::OnCreateSensor, this,
        std::placeholders::_1, std::placeholders::_2,
        std::placeholders::_3, std::placeholders::_4));

  this->initialized = true;
}

//////////////////////////////////////////////////
void SensorManager::Fini()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  // Finalize all the sensor containers.
  for (SensorContainer_V::iterator iter = this->sensorContainers.begin();
       iter != this->sensorContainers.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "SensorContainer is null");
    (*iter)->Fini();
    (*iter)->Stop();
  }

  this->removeSensors.clear();
  this->initSensors.clear();
  this->worlds.clear();

  delete this->simTimeEventHandler;
  this->simTimeEventHandler = nullptr;

  this->initialized = false;
}

//////////////////////////////////////////////////
void SensorManager::GetSensorTypes(std::vector<std::string> &_types) const
{
  sensors::SensorFactory::GetSensorTypes(_types);
}

//////////////////////////////////////////////////
void SensorManager::OnCreateSensor(sdf::ElementPtr _elem,
    const std::string &_worldName,
    const std::string &_parentName,
    const uint32_t _parentId)
{
  this->CreateSensor(_elem, _worldName, _parentName, _parentId);
}

//////////////////////////////////////////////////
std::string SensorManager::CreateSensor(sdf::ElementPtr _elem,
                                        const std::string &_worldName,
                                        const std::string &_parentName,
                                        uint32_t _parentId)
{
  std::string type = _elem->Get<std::string>("type");
  SensorPtr sensor = sensors::SensorFactory::NewSensor(type);

  if (!sensor)
  {
    gzerr << "Unable to create sensor of type[" << type << "]\n";
    return std::string();
  }

  // Must come before sensor->Load
  sensor->SetParent(_parentName, _parentId);

  // Load the sensor
  sensor->Load(_worldName, _elem);
  this->worlds[_worldName] = physics::get_world(_worldName);

  // If the SensorManager has not been initialized, then it's okay to push
  // the sensor into one of the sensor vectors because the sensor will get
  // initialized in SensorManager::Init
  if (!this->initialized)
  {
    this->sensorContainers[sensor->Category()]->AddSensor(sensor);
  }
  // Otherwise the SensorManager is already running, and the sensor will get
  // initialized during the next SensorManager::Update call.
  else
  {
    boost::recursive_mutex::scoped_lock lock(this->mutex);
    this->worlds[_worldName]->_SetSensorsInitialized(false);
    this->initSensors.push_back(sensor);
  }

  return sensor->ScopedName();
}

//////////////////////////////////////////////////
SensorPtr SensorManager::GetSensor(const std::string &_name) const
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  SensorContainer_V::const_iterator iter;
  SensorPtr result;

  // Try to find the sensor in all of the containers
  for (iter = this->sensorContainers.begin();
       iter != this->sensorContainers.end() && !result; ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "SensorContainer is null");
    result = (*iter)->GetSensor(_name);
  }

  // If the sensor was not found, then try to find based on an unscoped
  // name.
  // If multiple sensors exist with the same name, then an error occurs
  // because we don't know which sensor is correct.
  if (!result)
  {
    SensorPtr tmpSensor;
    for (iter = this->sensorContainers.begin();
         iter != this->sensorContainers.end(); ++iter)
    {
      GZ_ASSERT((*iter) != nullptr, "SensorContainer is null");
      tmpSensor = (*iter)->GetSensor(_name, true);

      if (!tmpSensor)
        continue;

      if (!result)
      {
        result = tmpSensor;
        GZ_ASSERT(result != nullptr,
            "SensorContainer contains a nullptr Sensor");
      }
      else
      {
        gzerr << "Unable to get a sensor, multiple sensors with the same "
          << "name[" << _name << "]. Use a scoped name instead, "
          << "world_name::model_name::link_name::sensor_name.\n";
        result.reset();
        break;
      }
    }
  }

  return result;
}

//////////////////////////////////////////////////
Sensor_V SensorManager::GetSensors() const
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);
  Sensor_V result;

  // Copy the sensor pointers
  for (SensorContainer_V::const_iterator iter = this->sensorContainers.begin();
       iter != this->sensorContainers.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "SensorContainer is null");
    std::copy((*iter)->sensors.begin(), (*iter)->sensors.end(),
              std::back_inserter(result));
  }

  return result;
}

//////////////////////////////////////////////////
void SensorManager::RemoveSensor(const std::string &_name)
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);
  SensorPtr sensor = this->GetSensor(_name);

  if (!sensor)
  {
    gzerr << "Unable to remove sensor[" << _name << "] because it "
          << "does not exist.\n";
  }
  else
  {
    // Push it on the list, to be removed by the main sensor thread,
    // to ensure correct access to rendering resources.
    this->removeSensors.push_back(sensor->ScopedName());
  }
}

//////////////////////////////////////////////////
void SensorManager::RemoveSensors()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);
  this->removeAllSensors = true;
}

//////////////////////////////////////////////////
SensorManager::SensorContainer::SensorContainer()
{
  this->stop = true;
  this->initialized = false;
  this->runThread = nullptr;
}

//////////////////////////////////////////////////
SensorManager::SensorContainer::~SensorContainer()
{
  this->sensors.clear();
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::Init()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  for (auto &sensor : this->sensors)
  {
    GZ_ASSERT(sensor != nullptr, "Sensor is null");
    sensor->Init();
  }

  this->initialized = true;
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::Fini()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  Sensor_V::iterator iter;

  // Finialize each sensor in the current sensor vector
  for (iter = this->sensors.begin(); iter != this->sensors.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor is null");
    (*iter)->Fini();
  }

  // Remove all the sensors from the current sensor vector.
  this->sensors.clear();

  this->initialized = false;
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::Run()
{
  this->runThread = new boost::thread(
      boost::bind(&SensorManager::SensorContainer::RunLoop, this));

  GZ_ASSERT(this->runThread, "Unable to create boost::thread.");
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::Stop()
{
  this->stop = true;
  this->runCondition.notify_all();
  if (this->runThread)
  {
    // Note: calling interrupt seems to cause the thread to either block
    // or throw an exception, so commenting it out for now.
    // this->runThread->interrupt();
    this->runThread->join();
    delete this->runThread;
    this->runThread = nullptr;
  }
}

//////////////////////////////////////////////////
bool SensorManager::SensorContainer::Running() const
{
  return !this->stop;
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::RunLoop()
{
  this->stop = false;

  physics::WorldPtr world = physics::get_world();
  GZ_ASSERT(world != nullptr, "Pointer to World is null");

  physics::PhysicsEnginePtr engine = world->Physics();
  GZ_ASSERT(engine != nullptr, "Pointer to PhysicsEngine is null");

  engine->InitForThread();

  // The original value was hardcode to 1.0. Changed the value to
  // 1000 * MaxStepSize in order to handle simulation with a
  // large step size.
  double maxSensorUpdate = engine->GetMaxStepSize() * 1000;

  // Release engine pointer, we don't need it in the loop
  engine.reset();

  common::Time sleepTime, startTime, eventTime, diffTime;
  double maxUpdateRate = 0;

  boost::mutex tmpMutex;
  boost::mutex::scoped_lock lock2(tmpMutex);

  // Wait for a sensor to be added.
  // Use a while loop since world resets will notify the runCondition.
  while (this->sensors.empty())
  {
    this->runCondition.wait(lock2);
    if (this->stop)
      return;
  }

  {
    boost::recursive_mutex::scoped_lock lock(this->mutex);

    // Get the minimum update rate from the sensors.
    for (Sensor_V::iterator iter = this->sensors.begin();
        iter != this->sensors.end() && !this->stop; ++iter)
    {
      GZ_ASSERT((*iter) != nullptr, "Sensor is null");
      maxUpdateRate = std::max((*iter)->UpdateRate(), maxUpdateRate);
    }
  }

  // Calculate an appropriate sleep time.
  if (maxUpdateRate > 0)
    sleepTime.Set(1.0 / (maxUpdateRate));
  else
    sleepTime.Set(0, 1e6);

  while (!this->stop)
  {
    // If all the sensors get deleted, wait here.
    // Use a while loop since world resets will notify the runCondition.
    while (this->sensors.empty())
    {
      this->runCondition.wait(lock2);
      if (this->stop)
        return;
    }

    // Get the start time of the update.
    startTime = world->SimTime();

    this->Update(false);

    // Compute the time it took to update the sensors.
    // It's possible that the world time was reset during the Update. This
    // would case a negative diffTime. Instead, just use a event time of zero
    diffTime = std::max(common::Time::Zero, world->SimTime() - startTime);

    // Set the default sleep time
    eventTime = std::max(common::Time::Zero, sleepTime - diffTime);

    // Make sure update time is reasonable.
    // During log playback, time can jump forward an arbitrary amount.
    if (diffTime.sec >= maxSensorUpdate && !util::LogPlay::Instance()->IsOpen())
    {
      gzwarn << "Took over 1000*max_step_size to update a sensor "
        << "(took " << diffTime.sec << " sec, which is more than "
        << "the max update of " << maxSensorUpdate << " sec). "
        << "This warning can be ignored during log playback" << std::endl;
    }

    // Make sure eventTime is not negative.
    if (eventTime < common::Time::Zero)
    {
      gzerr << "Time to next sensor update is negative." << std::endl;
      continue;
    }

    boost::mutex::scoped_lock timingLock(g_sensorTimingMutex);

    // Add an event to trigger when the appropriate simulation time has been
    // reached.
    SensorManager::Instance()->simTimeEventHandler->AddRelativeEvent(
        eventTime, &this->runCondition);

    // This if statement helps prevent deadlock on osx during teardown.
    if (!this->stop)
    {
      this->runCondition.wait(timingLock);
    }
  }
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::Update(bool _force)
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  if (this->sensors.empty())
    gzlog << "Updating a sensor container without any sensors.\n";

  // Update all the sensors in this container.
  for (Sensor_V::iterator iter = this->sensors.begin();
       iter != this->sensors.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor is null");
    (*iter)->Update(_force);
  }
}

//////////////////////////////////////////////////
SensorPtr SensorManager::SensorContainer::GetSensor(const std::string &_name,
                                                    bool _useLeafName) const
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  SensorPtr result;

  // Look for a sensor with the correct name
  for (Sensor_V::const_iterator iter = this->sensors.begin();
       iter != this->sensors.end() && !result; ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor is null");

    // We match on the scoped name (model::link::sensor) because multiple
    // sensors with the same leaf name may exist in a world.
    if ((_useLeafName && (*iter)->Name() == _name) ||
        (!_useLeafName && (*iter)->ScopedName() == _name))
    {
      result = (*iter);
      break;
    }
  }

  return result;
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::AddSensor(SensorPtr _sensor)
{
  GZ_ASSERT(_sensor != nullptr, "Sensor is nullptr when passed to ::AddSensor");

  {
    boost::recursive_mutex::scoped_lock lock(this->mutex);
    this->sensors.push_back(_sensor);
  }

  // Tell the run loop that we have received a sensor
  this->runCondition.notify_one();
}

//////////////////////////////////////////////////
bool SensorManager::SensorContainer::RemoveSensor(const std::string &_name)
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  Sensor_V::iterator iter;

  bool removed = false;

  // Find the correct sensor based on name, and remove it.
  for (iter = this->sensors.begin(); iter != this->sensors.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor is null");

    if ((*iter)->ScopedName() == _name)
    {
      (*iter)->Fini();
      this->sensors.erase(iter);
      removed = true;
      break;
    }
  }

  return removed;
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::ResetLastUpdateTimes()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  Sensor_V::iterator iter;

  // Rest last update times for all contained sensors.
  for (iter = this->sensors.begin(); iter != this->sensors.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor is null");
    (*iter)->ResetLastUpdateTime();
  }

  // Tell the run loop that world time has been reset.
  this->runCondition.notify_one();
}

//////////////////////////////////////////////////
void SensorManager::SensorContainer::RemoveSensors()
{
  boost::recursive_mutex::scoped_lock lock(this->mutex);

  Sensor_V::iterator iter;

  // Remove all the sensors
  for (iter = this->sensors.begin(); iter != this->sensors.end(); ++iter)
  {
    GZ_ASSERT((*iter) != nullptr, "Sensor is null");
    (*iter)->Fini();
  }

  this->sensors.clear();
}

//////////////////////////////////////////////////
void SensorManager::ImageSensorContainer::Update(bool _force)
{
  event::Events::preRender();

  // Tell all the cameras to render
  event::Events::render();

  event::Events::postRender();

  // Update the sensors, which will produce data messages.
  SensorContainer::Update(_force);
}

/////////////////////////////////////////////////
SimTimeEventHandler::SimTimeEventHandler()
{
  this->updateConnection = event::Events::ConnectWorldUpdateBegin(
      boost::bind(&SimTimeEventHandler::OnUpdate, this, _1));
}

/////////////////////////////////////////////////
SimTimeEventHandler::~SimTimeEventHandler()
{
  // Cleanup the events.
  for (std::list<SimTimeEvent*>::iterator iter = this->events.begin();
       iter != this->events.end(); ++iter)
  {
    GZ_ASSERT(*iter != nullptr, "SimTimeEvent is null");
    delete *iter;
  }
  this->events.clear();
}

/////////////////////////////////////////////////
void SimTimeEventHandler::AddRelativeEvent(const common::Time &_time,
                                           boost::condition_variable *_var)
{
  boost::mutex::scoped_lock lock(this->mutex);

  physics::WorldPtr world = physics::get_world();
  GZ_ASSERT(world != nullptr, "World pointer is null");

  // Create the new event.
  SimTimeEvent *event = new SimTimeEvent;
  event->time = world->SimTime() + _time;
  event->condition = _var;

  // Add the event to the list.
  this->events.push_back(event);
}

/////////////////////////////////////////////////
void SimTimeEventHandler::OnUpdate(const common::UpdateInfo &_info)
{
  boost::mutex::scoped_lock timingLock(g_sensorTimingMutex);
  boost::mutex::scoped_lock lock(this->mutex);

  // Iterate over all the events.
  for (std::list<SimTimeEvent*>::iterator iter = this->events.begin();
      iter != this->events.end();)
  {
    GZ_ASSERT(*iter != nullptr, "SimTimeEvent is null");

    // Find events that have a time less than or equal to simulation
    // time.
    if ((*iter)->time <= _info.simTime)
    {
      // Notify the event by triggering its condition.
      (*iter)->condition->notify_all();

      // Remove the event.
      delete *iter;
      this->events.erase(iter++);
    }
    else
      ++iter;
  }
}

ext: cc


text:
//  boost thread_clock.cpp  -----------------------------------------------------------//

//  Copyright 2010 Vicente J. Botet Escriba

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  See http://www.boost.org/libs/chrono for documentation.

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

// define BOOST_CHRONO_SOURCE so that <boost/chrono/config.hpp> knows
// the library is being built (possibly exporting rather than importing code)

#define BOOST_CHRONO_SOURCE

#include <boost/chrono/detail/inlined/thread_clock.hpp>

ext: cpp


text:
/*
    Copyright 2013 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 ADOBE_FUNCTION_HPP
#define ADOBE_FUNCTION_HPP

#include <algorithm>
#include <exception>

#include <tr1/functional>
#include <tr1/type_traits>

#include <boost/bind.hpp>

#include <adobe/cstdint.hpp>
#include <adobe/string.hpp>

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

namespace adobe {

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

class marshaled_exception : public std::exception {
public:
    explicit marshaled_exception(string_t message) : message_m(move(message)) {}
    ~marshaled_exception() throw() {}
    const char* what() const throw() { return message_m.c_str(); }

private:
    string_t message_m;
};

const char* current_exception_what() {
    const char* result = "unknown_exception";

    try {
        throw;
    }
    catch (const std::exception& error) {
        if (error.what())
            result = error.what();
    }
    catch (...) {
    }

    return result;
}

struct void_;
typedef void_* null_ptr_t;

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

namespace implementation {

template <typename T>
class function_base {
public:
    // [3.7.2.2] function modifiers
    void swap(T& x) { std::swap(self()->object_m, x.object_m); }

    // [3.7.2.3] function capacity
    operator bool() const { return self()->object_m; }

    // [3.7.2.5] function target access
    /* Not provided:
        const std::type_info& target_type() const;
        template <typename T> T* target();
        template <typename T> const T* target() const;
    */

    friend inline void swap(T& x, T& y) { x.swap(y); }

private:
    operator int() const; // for safe bool cast

    T* self() { return static_cast<T*>(this); }
    const T* self() const { return static_cast<const T*>(this); }
};

template <typename Concept, typename Apply>
struct vtable {
    void (*destroy)(Concept*);
    Concept* (*copy)(const Concept*, string_t& message);
    Apply apply;
};

template <typename Concept, typename V>
struct concept_base_t {
    explicit concept_base_t(const V* x) : vtable_m(x) {}

    Concept* copy() const {
        string_t message;
        Concept* result = vtable_m->copy(self(), message);
        if (message)
            throw marshaled_exception(move(message));
        return result;
    }

    void destroy() { vtable_m->destroy(self()); }

    Concept* self() { return static_cast<Concept*>(this); }
    const Concept* self() const { return static_cast<const Concept*>(this); }

    const V* vtable_m;
};

template <typename Model, typename Concept>
struct model_base : Concept {
    template <typename T>
    explicit model_base(T x)
        : Concept(x) {}

    static Model* self(Concept* x) { return static_cast<Model*>(x); }
    static const Model* self(const Concept* x) { return static_cast<const Model*>(x); }

    static void destroy(Concept* x) { delete self(x); }

    static Concept* copy(const Concept* x, string_t& message) {
        Concept* result = 0;

        try {
            result = new Model(*self(x));
        }
        catch (...) {
            message = current_exception_what();
        }

        return result;
    }
};

template <typename F, typename T>
typename F::concept_t* make_model(const T& x) {
    return new typename F::template model<T>(x);
}

template <typename F, typename T>
typename F::concept_t* create_model(const T& x, std::tr1::true_type) {
    return x ? make_model<F>(boost::bind<typename F::result_type>(x)) : 0;
}

template <typename F, typename T>
typename F::concept_t* create_model(const T& x, std::tr1::false_type) {
    return make_model<F>(boost::bind<typename F::result_type>(x));
}

template <typename F, typename T>
typename F::concept_t* create_model(const T& x) {
    return create_model<F>(x, std::tr1::is_pointer<T>());
}

} // namespace implementation

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

namespace version_1 {

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

/*!
    \requires \c R must have a non-throwing default constructor. \c R and all argument types
    must be abi safe. Any arguments passed by value must have a non-throwing copy constructor.
*/

template <typename F>
class function;

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

// [3.7.2.7] null pointer comparisons
template <typename F>
bool operator==(const function<F>& x, null_ptr_t) {
    return !x;
}
template <typename F>
bool operator==(null_ptr_t, const function<F>& x) {
    return !x;
}
template <typename F>
bool operator!=(const function<F>& x, null_ptr_t) {
    return x;
}
template <typename F>
bool operator!=(null_ptr_t, const function<F>& x) {
    return x;
}

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

template <typename R>
class function<R()> : public implementation::function_base<function<R()>> {
public:
    typedef R result_type;

    // [3.7.2.1] construction/copy/destroy
    function() : object_m(0) {}
    function(null_ptr_t) : object_m(0) {}
    function(const function& x) : object_m(x.object_m ? x.object_m->copy() : 0) {}
    template <typename T>
    function(T x)
        : object_m(implementation::create_model<function>(x)) {}

    function& operator=(function x) {
        swap(*this, x);
        return *this;
    }
    function& operator=(null_ptr_t) {
        if (object_m)
            object_m->destroy();
        object_m = 0;
    }
    template <typename T>
    function& operator=(T x) {
        return *this = function(x);
    }
    // template<class F> function& operator=(reference_wrapper<F>);

    ~function() {
        if (object_m)
            object_m->destroy();
    }

    // [3.7.2.4] function invocation
    R operator()() const {
        if (!object_m)
            throw std::tr1::bad_function_call();
        return object_m->apply();
    }

    struct concept_t; // implementation

private:
    friend class implementation::function_base<function<R()>>;

    typedef implementation::vtable<concept_t, R (*)(concept_t*, string_t&)> vtable_type;

    /*
    REVISIT (sparent) : This section is an implementation detail - made public until I can
    figure
    out how to make template friends.
    */

public:
    struct concept_t : implementation::concept_base_t<concept_t, vtable_type> {
        typedef implementation::concept_base_t<concept_t, vtable_type> base_type;

        explicit concept_t(const vtable_type* x) : base_type(x) {}
        R apply() { return apply(typename std::tr1::is_void<R>()); }

        void apply(std::tr1::true_type) {
            string_t message;
            this->vtable_m->apply(this, message);
            if (message)
                throw marshaled_exception(move(message));
        }

        R apply(std::tr1::false_type) {
            string_t message;
            R result = this->vtable_m->apply(this, message);
            if (message)
                throw marshaled_exception(move(message));
            return result;
        }
    };

    template <typename T>
    struct model : implementation::model_base<model<T>, concept_t> {
        typedef implementation::model_base<model<T>, concept_t> base_type;

        explicit model(T x) : base_type(&vtable_s), function_m(x) {}

        static R apply(concept_t* x, string_t& message) {
            return apply(x, message, typename std::tr1::is_void<R>());
        }

        static void apply(concept_t* x, string_t& message, std::tr1::true_type) {
            try {
                static_cast<model*>(x)->function_m();
            }
            catch (...) {
                message = current_exception_what();
            }
        }

        static R apply(concept_t* x, string_t& message, std::tr1::false_type) {
            R result;
            try {
                result = static_cast<model*>(x)->function_m();
            }
            catch (...) {
                message = current_exception_what();
            }
            return result;
        }

        static const vtable_type vtable_s;
        T function_m;
    };

private:
    concept_t* object_m;
};

template <typename R>
template <typename T>
const typename function<R()>::vtable_type function<R()>::model<T>::vtable_s = {
    &model::destroy, &model::copy, &model::apply};

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

} // namespace version_1
using namespace version_1;
} // namespace adobe

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

#endif

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

ext: hpp


text:
/******************************************************************************
 * $Id$
 *
 * Project:  libLAS - http://liblas.org - A BSD library for LAS format data.
 * Purpose:  Processing Kernel
 * Author:   Howard Butler, hobu.inc at gmail.com
 *
 ******************************************************************************
 * Copyright (c) 2010, Howard Butler
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following
 * conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of the Martin Isenburg or Iowa Department
 *       of Natural Resources nor the names of its contributors may be
 *       used to endorse or promote products derived from this software
 *       without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef LIBLAS_KERNEL_HPP_INCLUDED
#define LIBLAS_KERNEL_HPP_INCLUDED

#include <liblas/liblas.hpp>
#include <liblas/utility.hpp>
#include <liblas/export.hpp>
#include <liblas/external/property_tree/ptree.hpp>
#include <liblas/external/property_tree/xml_parser.hpp>

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <string>
#include <functional>
#include <algorithm>

#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <boost/array.hpp>
#include <boost/foreach.hpp>

using namespace std;
namespace po = boost::program_options;

#define SEPARATORS ",| "
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

LAS_DLL bool IsDualRangeFilter(std::string parse_string) ;

LAS_DLL liblas::FilterPtr MakeReturnFilter(std::vector<boost::uint16_t> const& returns, liblas::FilterI::FilterType ftype) ;
LAS_DLL liblas::FilterPtr MakeClassFilter(std::vector<liblas::Classification> const& classes, liblas::FilterI::FilterType ftype) ;
LAS_DLL liblas::FilterPtr MakeBoundsFilter(liblas::Bounds<double> const& bounds, liblas::FilterI::FilterType ftype) ;
LAS_DLL liblas::FilterPtr MakeIntensityFilter(std::string intensities, liblas::FilterI::FilterType ftype) ;
LAS_DLL liblas::FilterPtr MakeTimeFilter(std::string times, liblas::FilterI::FilterType ftype) ;
LAS_DLL liblas::FilterPtr MakeScanAngleFilter(std::string intensities, liblas::FilterI::FilterType ftype) ;
LAS_DLL liblas::FilterPtr MakeColorFilter(liblas::Color const& low, liblas::Color const& high, liblas::FilterI::FilterType ftype);

LAS_DLL po::options_description GetFilteringOptions();
LAS_DLL po::options_description GetTransformationOptions();
LAS_DLL po::options_description GetHeaderOptions();

LAS_DLL std::vector<liblas::FilterPtr> GetFilters(po::variables_map vm, bool verbose);
LAS_DLL std::vector<liblas::TransformPtr> GetTransforms(po::variables_map vm, bool verbose, liblas::Header& header);

#ifdef _WIN32
#define compare_no_case(a,b,n)  _strnicmp( (a), (b), (n) )
#else
#define compare_no_case(a,b,n)  strncasecmp( (a), (b), (n) )
#endif

std::istream* OpenInput(std::string const& filename, bool bEnd);
LAS_DLL std::string TryReadFileData(std::string const& filename);
LAS_DLL std::vector<char> TryReadRawFileData(std::string const& filename);
LAS_DLL bool term_progress(std::ostream& os, double complete);
LAS_DLL void SetStreamPrecision(std::ostream& os, double scale);
LAS_DLL void SetHeaderCompression(liblas::Header& header, std::string const& filename);

LAS_DLL liblas::Header FetchHeader(std::string const& filename);
LAS_DLL void RewriteHeader(liblas::Header const& header, std::string const& filename);
LAS_DLL void RepairHeader(liblas::CoordinateSummary const& summary, liblas::Header& header);
LAS_DLL liblas::property_tree::ptree SummarizeReader(liblas::Reader& reader) ;

class OptechScanAngleFixer: public liblas::TransformI
{
public:

    OptechScanAngleFixer() {};
    ~OptechScanAngleFixer() {};

    bool transform(liblas::Point& point);
    bool ModifiesHeader() { return false; }

private:
    OptechScanAngleFixer(OptechScanAngleFixer const& other);
    OptechScanAngleFixer& operator=(OptechScanAngleFixer const& rhs);
};

#endif // LIBLAS_ITERATOR_HPP_INCLUDED


text:
//===-- Exception -----------------------------------------------*- C++ -*-===//
///
/// \file
/// \brief Exception
/// \sa <https://boost.org/doc/libs/master/libs/exception/doc/boost-exception.html>
///
/// \version 2019-09-03
/// \since 2019-09-03
/// \authors zhengrr
/// \copyright Unlicense
///
//===----------------------------------------------------------------------===//

#include <cerrno>
#include <csignal>
#include <iostream>

#include <boost/exception/exception.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <gtest/gtest.h>

namespace {
class base_exception : virtual public std::exception, virtual public boost::exception {};

typedef boost::error_info<struct tag_errno_code, int>        errno_code;
typedef boost::error_info<struct tag_file_name, std::string> file_name;
}

using namespace std;

namespace rrboost {

TEST(exception, gft)
{
    try {
        throw runtime_error {"666"};

    } catch (const base_exception &e) {
        if (const auto ei = boost::get_error_info<file_name>(e))
            cerr << "file name: " << *ei << '\n';
        if (const auto ei = boost::get_error_info<errno_code>(e))
            cerr << "errno code: " << *ei << '\n';

    } catch (...) {
        cerr << boost::current_exception_diagnostic_information();
    }
}

}

max_stars_repo_name: afoolsbag/rrCnCxx

max_issues_repo_name: afoolsbag/rrCnCxx

max_forks_repo_name: afoolsbag/rrCnCxx


text:
// SPDX-FileCopyrightText: 2022 Pepijn de Vos
//
// SPDX-License-Identifier: MPL-2.0

#include <string>

#include "api/Simulator.capnp.h"
#include <kj/debug.h>
#include <kj/filesystem.h>
#include <kj/exception.h>
#include <kj/async-io.h>
#include <capnp/message.h>
#include <capnp/rpc-twoparty.h>

#include "../simserver.h"

#include <boost/asio.hpp>
#include <boost/process.hpp>
#include <boost/dll.hpp>
#include <boost/process/handles.hpp>
#include <boost/process/extend.hpp>

class SimulatorImpl final : public Sim::Simulator<SimCommands>::Server
{
public:
    SimulatorImpl(const kj::Directory &dir) : dir(dir) {}

    kj::Promise<void> loadFiles(LoadFilesContext context) override
    {
        auto files = context.getParams().getFiles();
        for (Sim::File::Reader f : files)
        {
            kj::Path path = kj::Path::parse(f.getName());
            kj::Own<const kj::File> file = dir.openFile(path, kj::WriteMode::CREATE | kj::WriteMode::MODIFY | kj::WriteMode::CREATE_PARENT);
            file->truncate(0);
            file->write(0, f.getContents());
        }

        std::string name = files[0].getName();

        auto res = context.getResults();
        auto commands = kj::heap<SimCommandsImpl>(name);
        res.setCommands(kj::mv(commands));
        return kj::READY_NOW;
    }

    kj::Promise<void> loadPath(LoadPathContext context) override
    {
        auto file = context.getParams().getFile();
        auto res = context.getResults();
        auto commands = kj::heap<SimCommandsImpl>(file);
        res.setCommands(kj::mv(commands));
        return kj::READY_NOW;
    }

    const kj::Directory &dir;
};

using boost::this_process::native_handle_type;

int runchild(kj::LowLevelAsyncIoProvider::Fd fd) {
    kj::AsyncIoContext ctx = kj::setupAsyncIo();
    auto stream = ctx.lowLevelProvider->wrapSocketFd(fd);
    auto network = capnp::TwoPartyVatNetwork(*stream, capnp::rpc::twoparty::Side::SERVER);
    kj::Own<kj::Filesystem> fs = kj::newDiskFilesystem();
    const kj::Directory &dir = fs->getCurrent();
    auto rpc = capnp::makeRpcServer(network, kj::heap<SimulatorImpl>(dir));
    network.onDisconnect().wait(ctx.waitScope);
    std::cout << "Client disconnected" << std::endl;
    return 0;
}

using namespace boost::asio;
using ip::tcp;
using namespace boost::process;
namespace ex = boost::process::extend;

struct do_inherit : boost::process::extend::handler
{
    template<typename Char, typename Sequence>
    void on_setup(ex::windows_executor<Char, Sequence> & exec)
    {
        std::cout << "windows setup" << std::endl;
        exec.inherit_handles = 1;
    }

    template<typename Sequence>
    void on_setup(ex::posix_executor<Sequence> & exec)
    {
        std::cout << "unix setup" << std::endl;
    }
};

int main(int argc, char const *argv[])
{
    int port = 5923;
    if (argc == 2 && strcmp(argv[1], "--help")==0) {
        std::cout << argv[0] << " [port]" << std::endl;
        return 0;
    } else if (argc == 3 && strcmp(argv[1], "--child")==0) {
        kj::LowLevelAsyncIoProvider::Fd fd = std::stoi(argv[2]);
        return runchild(fd);
    } else if (argc == 2)
    {
        port = std::stoi(argv[1]);
    }
    boost::filesystem::path p = boost::dll::program_location();
    boost::asio::io_service io_service;
    tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v6(), port));
    while (1)
    {
        std::cout << "waiting for clients" << std::endl;
        tcp::socket peersocket(io_service);
        acceptor.accept(peersocket);
        auto endpoint = peersocket.remote_endpoint();
        std::cout << "Accepted new connection from a client" << endpoint.address() << ":" << endpoint.port() << std::endl;
        std::string fd = std::to_string(peersocket.release());
        boost::process::spawn(p, "--child", fd, do_inherit());
    }
    return 0;
}

max_stars_repo_name: NyanCAD/Pyttoresque

max_issues_repo_name: NyanCAD/Pyttoresque

max_forks_repo_name: NyanCAD/Pyttoresque


text:
// Copyright Paul A. Bristow 2013
// Copyright John Maddock 2013
// Copyright Christopher Kormanyos

// Use, modification and distribution are 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)

// Examples of std::numeric_limits usage as snippets for multiprecision documentation at multiprecision.qbk.

// Includes text as Quickbook comments.

#include <boost/assert.hpp>

#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/nonfinite_num_facets.hpp>

#include <boost/math/special_functions/factorials.hpp>
#include <boost/math/special_functions/next.hpp>
#include <boost/math/tools/precision.hpp>
#include <boost/multiprecision/cpp_dec_float.hpp> // is decimal.
#include <boost/multiprecision/cpp_bin_float.hpp> // is binary.

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp> // Boost.Test
#include <boost/test/tools/floating_point_comparison.hpp>

#include <iostream>
#include <iomanip>
#include <string>
#include <sstream>
#include <limits> // numeric_limits
#include <iomanip>
#include <locale>

// static long double const log10Two = 0.30102999566398119521373889472449L; // log10(2.)
// It is more portable useful to use a Boost macro
// See https://www.boost.org/doc/libs/release/libs/config/doc/html/boost_config/boost_macro_reference.html
static constexpr long double log10Two = 0.30102999566398119521373889472449L;
// which expands to static constexpr on standard C++11 and up, but static const on earlier versions.

  /*`By default, output would only show the standard 6 decimal digits,
 so set precision to show all 50 significant digits, including any trailing zeros.
 This is generally useful to show the implicit precision of the type of the value.
*/

template <typename T>
int max_digits10()
{
   int significand_digits = std::numeric_limits<T>::digits;
  // constexpr int significand_digits = std::numeric_limits<T>::digits;
   return static_cast<int>(ceil(1 + significand_digits * log10Two));
} // template <typename T> int max_digits10()

// Used to test max_digits10<>() function below.

BOOST_AUTO_TEST_CASE(test_numeric_limits_snips)
{
#if !(defined(CI_SUPPRESS_KNOWN_ISSUES) && defined(BOOST_MSVC) && (BOOST_MSVC == 1600))
  try
  {

// Example of portable way to get `std::numeric_limits<T>::max_digits10`.
//[max_digits10_1

/*`For example, to be portable (including obselete platforms) for type `T` where `T` may be:
 `float`, `double`, `long double`, `128-bit quad type`, `cpp_bin_float_50` ...
*/

  typedef float T;

  std::cout.precision(std::numeric_limits<T>::max_digits10);
  std::cout.precision(std::numeric_limits<T>::digits10);
  std::cout.setf(std::ios_base::showpoint); // Append any trailing zeros,
  // or more memorably
  std::cout << std::showpoint << std::endl; //

  std::cout << "std::cout.precision(max_digits10) = " << std::cout.precision() << std::endl; // 9

  double x = 1.2345678901234567889;

  std::cout << "x = " << x << std::endl; //

/*`which should output:

  std::cout.precision(max_digits10) = 9
  x = 1.23456789
*/

//] [/max_digits10_1]

  {
//[max_digits10_2

  double write = 2./3; // Any arbitrary value that cannot be represented exactly.
  double read = 0;
  std::stringstream s;
  s.precision(std::numeric_limits<double>::digits10); // or `float64_t` for 64-bit IEE754 double.
  s << write;
  s >> read;
  if(read != write)
  {
    std::cout <<  std::setprecision(std::numeric_limits<double>::digits10)
      << read << " != " << write << std::endl;
  }

//] [/max_digits10_2]
  // 0.666666666666667 != 0.666666666666667
  }

  {
//[max_digits10_3

  double pi = boost::math::double_constants::pi;
  std::cout.precision(std::numeric_limits<double>::max_digits10);
  std::cout << pi << std::endl; // 3.1415926535897931

//] [/max_digits10_3]
  }
  {
//[max_digits10_4
/*`and similarly for a much higher precision type:
*/

  using namespace boost::multiprecision;

  typedef number<cpp_dec_float<50> > cpp_dec_float_50; // 50 decimal digits.

  // or using boost::multiprecision::cpp_dec_float_50;

  cpp_dec_float_50 pi = boost::math::constants::pi<cpp_dec_float_50>();
  std::cout.precision(std::numeric_limits<cpp_dec_float_50>::max_digits10);
  std::cout << pi << std::endl;
  // 3.141592653589793238462643383279502884197169399375105820974944592307816406
//] [/max_digits10_4]
  }

  {
//[max_digits10_5

  for (int i = 2; i < 15; i++)
  {
    std::cout << std::setw(std::numeric_limits<int>::max_digits10)
      << boost::math::factorial<double>(i)  << std::endl;
  }

//] [/max_digits10_5]
  }

  }
  catch(const std::exception& ex)
  {
    std::cout << "Caught Exception " << ex.what() << std::endl;
  }

  {
//[max_digits10_6

  typedef double T;

  bool denorm = std::numeric_limits<T>::denorm_min() < (std::numeric_limits<T>::min)();
  BOOST_MP_ASSERT(denorm);

//] [/max_digits10_6]
  }

  {
    unsigned char c = 255;
    std::cout << "char c = " << (int)c << std::endl;
  }

  {
//[digits10_1
    std::cout
      << std::setw(std::numeric_limits<short>::digits10 +1 +1) // digits10+1, and +1 for sign.
      << std::showpos << (std::numeric_limits<short>::max)() // +32767
      << std::endl
      << std::setw(std::numeric_limits<short>::digits10 +1 +1)
      << (std::numeric_limits<short>::min)() << std::endl;   // -32767
//] [/digits10_1]
  }

  {
//[digits10_2
    std::cout
      << std::setw(std::numeric_limits<unsigned short>::digits10 +1 +1) // digits10+1, and +1 for sign.
      << std::showpos << (std::numeric_limits<unsigned short>::max)() //  65535
      << std::endl
      << std::setw(std::numeric_limits<unsigned short>::digits10 +1 +1) // digits10+1, and +1 for sign.
      << (std::numeric_limits<unsigned short>::min)() << std::endl;   //      0
//] [/digits10_2]
  }

  std::cout <<std::noshowpos << std::endl;

  {
//[digits10_3
  std::cout.precision(std::numeric_limits<double>::max_digits10);
  double d =  1e15;
  double dp1 = d+1;
  std::cout << d << "\n" << dp1 << std::endl;
  // 1000000000000000
  // 1000000000000001
  std::cout <<  dp1 - d << std::endl; // 1
//] [/digits10_3]
  }

  {
//[digits10_4
  std::cout.precision(std::numeric_limits<double>::max_digits10);
  double d =  1e16;
  double dp1 = d+1;
  std::cout << d << "\n" << dp1 << std::endl;
  // 10000000000000000
  // 10000000000000000
    std::cout << dp1 - d << std::endl; // 0 !!!
//] [/digits10_4]
  }

  {
//[epsilon_1
  std::cout.precision(std::numeric_limits<double>::max_digits10);
  double d = 1.;
  double eps = std::numeric_limits<double>::epsilon();
  double dpeps = d+eps;
  std::cout << std::showpoint // Ensure all trailing zeros are shown.
    << d << "\n"           // 1.0000000000000000
    << dpeps << std::endl; // 2.2204460492503131e-016
  std::cout << dpeps - d   // 1.0000000000000002
    << std::endl;
//] [epsilon_1]
  }

  {
//[epsilon_2
  double one = 1.;
  double nad = boost::math::float_next(one);
  std::cout << nad << "\n"  //  1.0000000000000002
    << nad - one // 2.2204460492503131e-016
    << std::endl;
//] [epsilon_2]
  }
  {
//[epsilon_3
  std::cout.precision(std::numeric_limits<double>::max_digits10);
  double d = 1.;
  double eps = std::numeric_limits<double>::epsilon();
  double dpeps = d + eps/2;

  std::cout << std::showpoint // Ensure all trailing zeros are shown.
    << dpeps << "\n"       // 1.0000000000000000
    << eps/2 << std::endl; // 1.1102230246251565e-016
  std::cout << dpeps - d   // 0.00000000000000000
    << std::endl;
//] [epsilon_3]
  }

  {
    typedef double RealType;
//[epsilon_4
/*`A tolerance might be defined using this version of epsilon thus:
*/
    RealType tolerance = boost::math::tools::epsilon<RealType>() * 2;
//] [epsilon_4]
    (void)tolerance; // warning suppression
  }

  {
    bool b =
//[digits10_5
    -(std::numeric_limits<double>::max)() == std::numeric_limits<double>::lowest();
//] [/digits10_5]
    (void)b;  // warning suppression
  }

  {
//[denorm_min_1
  std::cout.precision(std::numeric_limits<double>::max_digits10);
  if (std::numeric_limits<double>::has_denorm == std::denorm_present)
  {
    double d = std::numeric_limits<double>::denorm_min();

      std::cout << d << std::endl; //  4.9406564584124654e-324

      int exponent;

      double significand = frexp(d, &exponent);
      std::cout << "exponent = " << std::hex << exponent << std::endl; //  fffffbcf
      std::cout << "significand = " << std::hex << significand << std::endl; // 0.50000000000000000
  }
  else
  {
    std::cout << "No denormalization. " << std::endl;
  }
//] [denorm_min_1]
  }

  {
//[round_error_1
    double round_err = std::numeric_limits<double>::epsilon() // 2.2204460492503131e-016
                     * std::numeric_limits<double>::round_error(); // 1/2
    std::cout << round_err << std::endl; // 1.1102230246251565e-016
//] [/round_error_1]
  }

  {
    typedef double T;
//[tolerance_1
/*`For example, if we want a tolerance that might suit about 9 arithmetical operations,
say sqrt(9) = 3,  we could define:
*/

    T tolerance =  3 * std::numeric_limits<T>::epsilon();

/*`This is very widely used in Boost.Math testing
with Boost.Test's macro `BOOST_CHECK_CLOSE_FRACTION`
*/

    T expected = 1.0;
    T calculated = 1.0 + std::numeric_limits<T>::epsilon();

    BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);

//] [/tolerance_1]
  }

#if !(defined(CI_SUPPRESS_KNOWN_ISSUES) && defined(__GNUC__) && defined(_WIN32))
  {
//[tolerance_2

  using boost::multiprecision::number;
  using boost::multiprecision::cpp_dec_float;
  using boost::multiprecision::et_off;

  typedef number<cpp_dec_float<50>, et_off > cpp_dec_float_50; // 50 decimal digits.
/*`[note that Boost.Test does not yet allow floating-point comparisons with expression templates on,
so the default expression template parameter has been replaced by `et_off`.]
*/

  cpp_dec_float_50 tolerance =  3 * std::numeric_limits<cpp_dec_float_50>::epsilon();
  cpp_dec_float_50 expected = boost::math::constants::two_pi<cpp_dec_float_50>();
  cpp_dec_float_50 calculated = 2 * boost::math::constants::pi<cpp_dec_float_50>();

  BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);

//] [/tolerance_2]
  }

  {
//[tolerance_3

  using boost::multiprecision::cpp_bin_float_quad;

  cpp_bin_float_quad tolerance =  3 * std::numeric_limits<cpp_bin_float_quad>::epsilon();
  cpp_bin_float_quad expected = boost::math::constants::two_pi<cpp_bin_float_quad>();
  cpp_bin_float_quad calculated = 2 * boost::math::constants::pi<cpp_bin_float_quad>();

  BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);

//] [/tolerance_3]
  }

  {
//[tolerance_4

  using boost::multiprecision::cpp_bin_float_oct;

  cpp_bin_float_oct tolerance =  3 * std::numeric_limits<cpp_bin_float_oct>::epsilon();
  cpp_bin_float_oct expected = boost::math::constants::two_pi<cpp_bin_float_oct>();
  cpp_bin_float_oct calculated = 2 * boost::math::constants::pi<cpp_bin_float_oct>();

  BOOST_CHECK_CLOSE_FRACTION(expected, calculated, tolerance);

//] [/tolerance_4]
  }

  {
//[nan_1]

/*`NaN can be used with binary multiprecision types like `cpp_bin_float_quad`:
*/
  using boost::multiprecision::cpp_bin_float_quad;

  if (std::numeric_limits<cpp_bin_float_quad>::has_quiet_NaN == true)
  {
    cpp_bin_float_quad NaN =  std::numeric_limits<cpp_bin_float_quad>::quiet_NaN();
    std::cout << "cpp_bin_float_quad NaN is "  << NaN << std::endl; //   cpp_bin_float_quad NaN is nan

    cpp_bin_float_quad expected = NaN;
    cpp_bin_float_quad calculated = 2 * NaN;
    // Comparisons of NaN's always fail:
    bool b = expected == calculated;
    std::cout << b << std::endl;
    BOOST_CHECK_NE(expected, expected);
    BOOST_CHECK_NE(expected, calculated);
  }
  else
  {
    std::cout << "Type " << typeid(cpp_bin_float_quad).name() << " does not have NaNs!" << std::endl;
  }

//]  [/nan_1]
  }

  {
//[facet_1]

/*`
See [@boost:/libs/math/example/nonfinite_facet_sstream.cpp]
and we also need

  #include <boost/math/special_functions/nonfinite_num_facets.hpp>

Then we can equally well use a multiprecision type cpp_bin_float_quad:

*/
  using boost::multiprecision::cpp_bin_float_quad;

  typedef cpp_bin_float_quad T;

  using boost::math::nonfinite_num_put;
  using boost::math::nonfinite_num_get;
  {
    std::locale old_locale;
    std::locale tmp_locale(old_locale, new nonfinite_num_put<char>);
    std::locale new_locale(tmp_locale, new nonfinite_num_get<char>);
    std::stringstream ss;
    ss.imbue(new_locale);
    T inf = std::numeric_limits<T>::infinity();
    ss << inf; // Write out.
   BOOST_MP_ASSERT(ss.str() == "inf");
    T r;
    ss >> r; // Read back in.
    BOOST_MP_ASSERT(inf == r); // Confirms that the floating-point values really are identical.
    std::cout << "infinity output was " << ss.str() << std::endl;
    std::cout << "infinity input was " << r << std::endl;
  }

/*`
``
  infinity output was inf
  infinity input was inf
``
Similarly we can do the same with NaN (except that we cannot use `assert` (because any comparisons with NaN always return false).
*/
  {
    std::locale old_locale;
    std::locale tmp_locale(old_locale, new nonfinite_num_put<char>);
    std::locale new_locale(tmp_locale, new nonfinite_num_get<char>);
    std::stringstream ss;
    ss.imbue(new_locale);
    T n;
    T NaN = std::numeric_limits<T>::quiet_NaN();
    ss << NaN; // Write out.
    BOOST_MP_ASSERT(ss.str() == "nan");
    std::cout << "NaN output was " << ss.str() << std::endl;
    ss >> n; // Read back in.
    std::cout << "NaN input was " << n << std::endl;
  }
/*`
``
  NaN output was nan
  NaN input was nan
``
*/
//]  [/facet_1]
  }

#endif
#endif
} // BOOST_AUTO_TEST_CASE(test_numeric_limits_snips)

max_stars_repo_name: mariospr/multiprecision

max_issues_repo_name: mariospr/multiprecision

max_forks_repo_name: mariospr/multiprecision


text:
#ifndef TEST_UTILS_H
#define TEST_UTILS_H

#include <vector>
#include <tuple>
#include <iostream>
#include <iomanip>

#include <boost/io/ios_state.hpp>

#include <Eigen/Sparse>

#include "SparseLinearSolvers.hpp"
#include "Converters.hpp"
#include "IO.hpp"

#include <dfesnippets/NumericUtils.hpp>

namespace cask {
  namespace test {

    using Td = Eigen::Triplet<double>;
    using Vd = Eigen::VectorXd;
    using Md = Eigen::SparseMatrix<double>;

    using MismatchT = std::vector<std::tuple<int, double, double>>;

    MismatchT check(
        const std::vector<double>& got,
        const std::vector<double>& exp
        )
    {
      std::vector<std::tuple<int, double, double>> mismatches;
      for (int i = 0; i < got.size(); i++) {
        if (!dfesnippets::numeric_utils::almost_equal(got[i], exp[i], 1E-8, 1E-11))
          mismatches.push_back(std::make_tuple(i, got[i], exp[i]));
      }

      return mismatches;
    }

    MismatchT check(
        const Eigen::VectorXd& got,
        const Eigen::VectorXd& exp)
    {
      return
        check(cask::converters::eigenVectorToStdVector(got),
            cask::converters::eigenVectorToStdVector(exp));
    }

    void print_mismatches(const MismatchT& mismatches) {
      boost::io::ios_all_saver guard(std::cout);
      if (!mismatches.empty()) {
        std::cerr << "Results didn't match" << std::endl;
        for (int i = 0; i < mismatches.size(); i++) {
          std::cerr << std::fixed << std::setprecision(10);
          std::cerr << "At " << std::get<0>(mismatches[i]);
          std::cerr << " got: " << std::get<1>(mismatches[i]);
          std::cerr << " exp: "  << std::get<2>(mismatches[i]) << std::endl;
        }
      }
    }

    struct SimpleVectorGenerator {
      std::tuple<Vd, Vd> operator()(Md mat, int m) {
        Eigen::VectorXd x(m);
        for (int i = 0; i < m; i++)
          x[i] = i * 0.25;
        return std::make_tuple(
            mat * x,
            x);
      }
    };

    Md one(int m) {
      std::vector<Td> nnzs;
      for (int i = 0; i < m; i++)
        nnzs.push_back(Td(i, i, 1));
      Md a(m, m);
      a.setFromTriplets(nnzs.begin(), nnzs.end());
      return a;
    }

    // functor to generate a matrix
    struct IdentityGenerator {
      Md operator()(int m) {
        return one(m);
      }
    };

    struct RandomGenerator {
      Md operator()(int m) {
        return one(m) * 2;
      }
    };

    struct EigenMatrixGenerator {
      Md matrix;
      EigenMatrixGenerator(Md _matrix) : matrix(_matrix) {}
      Md operator()(int m) {
        return matrix;
      }
    };

    struct EigenVectorGenerator {
      Vd vd;
      EigenVectorGenerator(Vd _vd) : vd(_vd) {}
      std::tuple<Vd, Vd> operator()(Md mat, int m) {
        std::cout << "Running eigen solver" << std::endl;
        cask::sparse_linear_solvers::EigenSolver es;
        Vd sol = es.solve(mat, vd);
        std::cout << "Eigen solver complete!" << std::endl;
        return std::make_tuple(vd, sol);
      }
    };

    template<typename MatrixGenerator, typename RhsGenerator>
      int test(int m, MatrixGenerator mg, RhsGenerator rhsg,
          cask::sparse_linear_solvers::Solver &solver) {
        Md a = mg(m);
        auto tpl =  rhsg(a, m);
        Vd b = std::get<0>(tpl);
        Vd exp = std::get<1>(tpl);

        std::cout << "Running DFE Solver" << std::endl;
        Vd sol = solver.solve(a, b);
        std::cout << "DFE solver complete!" << std::endl;

        auto mismatches = cask::test::check(sol, exp);
        if (mismatches.empty())
          return 0;
        cask::test::print_mismatches(mismatches);

        return 1;
      }

    int runTest(
        std::string path,
        cask::sparse_linear_solvers::Solver& solver) {
      cask::io::MmReader<double> m(path);
      auto eigenMatrix = cask::converters::tripletToEigen(m.mmreadMatrix(path));
      return test(eigenMatrix->rows(),
          EigenMatrixGenerator{*eigenMatrix},
          cask::test::SimpleVectorGenerator{},
          solver);
    }

    int runTest(
        std::string path,
        std::string vectorPath,
        cask::sparse_linear_solvers::Solver& solver) {
      cask::io::MmReader<double> m(path);
      auto eigenMatrix = cask::converters::tripletToEigen(m.mmreadMatrix(path));
      cask::io::MmReader<double> mv(vectorPath);
      auto eigenVector = cask::converters::stdvectorToEigen(mv.readVector());
      return test(eigenMatrix->rows(),
          EigenMatrixGenerator{*eigenMatrix},
          EigenVectorGenerator{eigenVector},
          solver);
    }

  }
}

#endif /* end of include guard: TEST_UTILS_H */

max_stars_repo_name: paul-g/spark

max_issues_repo_name: caskorg/cask

max_forks_repo_name: caskorg/cask


text:
/*
==============================================================================
KratosFluiDynamicsApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).

Copyright 2007
Pooyan Dadvand, Riccardo Rossi
pooyan@cimne.upc.edu
rrossi@cimne.upc.edu
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain

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 condition:

Distribution of this code for  any  commercial purpose  is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.

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.

==============================================================================
 */

//
//   Project Name:        Kratos
//   Last modified by:    $Author:  $
//   Date:                $Date:  $
//   Revision:            $Revision: 1.2 $
//
//

// System includes

// External includes
#include <boost/python.hpp>

// Project includes
#include "includes/define.h"
#include "includes/model_part.h"
#include "processes/process.h"
#include "custom_python/add_custom_processes_to_python.h"

//#include "custom_processes/node_and_element_erase_process.h"
#include "spaces/ublas_space.h"

namespace Kratos
{

namespace Python
{

void AddCustomProcessesToPython()
{
    using namespace boost::python;

//    typedef UblasSpace<double, CompressedMatrix, Vector> SparseSpaceType;
//    typedef UblasSpace<double, Matrix, Vector> LocalSpaceType;

//    typedef LinearSolver<SparseSpaceType, LocalSpaceType > LinearSolverType;
//    typedef Scheme< SparseSpaceType, LocalSpaceType > BaseSchemeType;

//    class_<NodeAndElementEraseProcess>("NodeAndElementEraseProcess", init < ModelPart& >())
//    .def("Execute", &NodeAndElementEraseProcess::Execute);
}

} // namespace Python.

} // Namespace Kratos

max_stars_repo_name: lcirrott/Kratos

max_issues_repo_name: lcirrott/Kratos

max_forks_repo_name: lcirrott/Kratos


text:
/*=============================================================================
    Copyright (c) 2001-2007 Joel de Guzman
    Copyright (c) 2007 Dan Marsden
    Copyright (c) 2009-2011 Christopher Schmidt

    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 BOOST_FUSION_ADAPTED_STRUCT_ADAPT_ASSOC_STRUCT_HPP
#define BOOST_FUSION_ADAPTED_STRUCT_ADAPT_ASSOC_STRUCT_HPP

#include <boost/fusion/support/config.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/comparison/less.hpp>
#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/empty.hpp>

#include <boost/fusion/adapted/struct/detail/adapt_base.hpp>
#include <boost/fusion/adapted/struct/detail/adapt_base_assoc_attr_filler.hpp>
#include <boost/fusion/adapted/struct/detail/at_impl.hpp>
#include <boost/fusion/adapted/struct/detail/begin_impl.hpp>
#include <boost/fusion/adapted/struct/detail/category_of_impl.hpp>
#include <boost/fusion/adapted/struct/detail/deref_data_impl.hpp>
#include <boost/fusion/adapted/struct/detail/deref_impl.hpp>
#include <boost/fusion/adapted/struct/detail/end_impl.hpp>
#include <boost/fusion/adapted/struct/detail/extension.hpp>
#include <boost/fusion/adapted/struct/detail/is_sequence_impl.hpp>
#include <boost/fusion/adapted/struct/detail/is_view_impl.hpp>
#include <boost/fusion/adapted/struct/detail/key_of_impl.hpp>
#include <boost/fusion/adapted/struct/detail/size_impl.hpp>
#include <boost/fusion/adapted/struct/detail/value_at_impl.hpp>
#include <boost/fusion/adapted/struct/detail/value_of_data_impl.hpp>
#include <boost/fusion/adapted/struct/detail/value_of_impl.hpp>

#define BOOST_FUSION_ADAPT_ASSOC_STRUCT_C_BASE(TEMPLATE_PARAMS_SEQ, NAME_SEQ,  \
                                               IS_VIEW, I, PREFIX, ATTRIBUTE)  \
                                                                               \
  BOOST_FUSION_ADAPT_STRUCT_C_BASE(                                            \
      TEMPLATE_PARAMS_SEQ, NAME_SEQ, IS_VIEW, I,                               \
      BOOST_PP_IIF(IS_VIEW, BOOST_FUSION_PROXY_PREFIX, BOOST_PP_EMPTY),        \
      BOOST_FUSION_ADAPT_STRUCT_WRAPPEDATTR(ATTRIBUTE),                        \
      BOOST_FUSION_ADAPT_STRUCT_WRAPPEDATTR_SIZE(ATTRIBUTE),                   \
      BOOST_PP_LESS(BOOST_FUSION_ADAPT_STRUCT_WRAPPEDATTR_SIZE(ATTRIBUTE), 3)) \
                                                                               \
  template <BOOST_FUSION_ADAPT_STRUCT_UNPACK_TEMPLATE_PARAMS(                  \
      TEMPLATE_PARAMS_SEQ)>                                                    \
  struct struct_assoc_key<BOOST_FUSION_ADAPT_STRUCT_UNPACK_NAME(NAME_SEQ),     \
                          I> {                                                 \
    typedef BOOST_FUSION_ADAPT_ASSOC_STRUCT_WRAPPEDATTR_GET_KEY(               \
        ATTRIBUTE) type;                                                       \
  };

#define BOOST_FUSION_ADAPT_ASSOC_STRUCT_C(TEMPLATE_PARAMS_SEQ, NAME_SEQ,       \
                                          IS_VIEW, I, ATTRIBUTE)               \
                                                                               \
  BOOST_FUSION_ADAPT_ASSOC_STRUCT_C_BASE(                                      \
      TEMPLATE_PARAMS_SEQ, NAME_SEQ, IS_VIEW, I, BOOST_PP_EMPTY, ATTRIBUTE)

#define BOOST_FUSION_ADAPT_ASSOC_TPL_STRUCT(TEMPLATE_PARAMS_SEQ, NAME_SEQ,     \
                                            ATTRIBUTES)                        \
                                                                               \
  BOOST_FUSION_ADAPT_STRUCT_BASE(                                              \
      (1)TEMPLATE_PARAMS_SEQ, (1)NAME_SEQ, assoc_struct_tag, 0,                \
      BOOST_PP_CAT(                                                            \
          BOOST_FUSION_ADAPT_ASSOC_STRUCT_FILLER_0(0, 0, 0) ATTRIBUTES, _END), \
      BOOST_FUSION_ADAPT_ASSOC_STRUCT_C)

#define BOOST_FUSION_ADAPT_ASSOC_STRUCT(NAME, ATTRIBUTES)                      \
  BOOST_FUSION_ADAPT_STRUCT_BASE(                                              \
      (0), (0)(NAME), assoc_struct_tag, 0,                                     \
      BOOST_PP_CAT(                                                            \
          BOOST_FUSION_ADAPT_ASSOC_STRUCT_FILLER_0(0, 0, 0) ATTRIBUTES, _END), \
      BOOST_FUSION_ADAPT_ASSOC_STRUCT_C)

#define BOOST_FUSION_ADAPT_ASSOC_STRUCT_AS_VIEW(NAME, ATTRIBUTES)              \
  BOOST_FUSION_ADAPT_STRUCT_BASE(                                              \
      (0), (0)(NAME), assoc_struct_tag, 1,                                     \
      BOOST_PP_CAT(                                                            \
          BOOST_FUSION_ADAPT_ASSOC_STRUCT_FILLER_0(0, 0, 0) ATTRIBUTES, _END), \
      BOOST_FUSION_ADAPT_ASSOC_STRUCT_C)

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


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

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/type_traits/is_nothrow_move_constructible.hpp>
#include <boost/type_traits/is_nothrow_move_assignable.hpp>
#include <boost/type_traits/has_nothrow_constructor.hpp>
#include <boost/type_traits/has_nothrow_assign.hpp>
#include <boost/type_traits/has_nothrow_copy.hpp>
#include <boost/static_assert.hpp>

typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::int128_t::backend_type> > rat128_t;
typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::uint128_t::backend_type> > urat128_t;
typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::int512_t::backend_type> > rat512_t;
typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::uint512_t::backend_type> > urat512_t;

typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::checked_int128_t::backend_type> > checked_rat128_t;
typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::checked_uint128_t::backend_type> > checked_urat128_t;
typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::checked_int512_t::backend_type> > checked_rat512_t;
typedef boost::multiprecision::number<boost::multiprecision::rational_adaptor<boost::multiprecision::checked_uint512_t::backend_type> > checked_urat512_t;

#ifndef BOOST_NO_CXX11_NOEXCEPT

#if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_SFINAE_EXPR) || defined(BOOST_IS_NOTHROW_MOVE_CONSTRUCT)
//
// Move construct:
//
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<boost::multiprecision::cpp_rational>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<rat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<checked_rat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<urat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<checked_urat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<rat512_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<checked_rat512_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<urat512_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<checked_urat512_t>::value);

#endif

#if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_SFINAE_EXPR) || defined(BOOST_IS_NOTHROW_MOVE_ASSIGN)
//
// Move assign:
//
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<boost::multiprecision::cpp_rational>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<rat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<checked_rat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<urat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<checked_urat128_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<rat512_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<checked_rat512_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<urat512_t>::value);
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<checked_urat512_t>::value);

#endif

#if 0
//
// Everything below could/should be made to work, given modifications to Boost.Rational
//

//
// Construct:
//
#ifdef BOOST_HAS_NOTHROW_CONSTRUCTOR
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<boost::multiprecision::cpp_rational>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<rat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<checked_rat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<urat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<checked_urat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<rat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<checked_rat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<urat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<checked_urat512_t>::value);
#endif
//
// Copy construct:
//
#ifdef BOOST_HAS_NOTHROW_COPY
BOOST_STATIC_ASSERT(!boost::has_nothrow_copy<boost::multiprecision::cpp_rational>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<rat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<checked_rat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<urat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<checked_urat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<rat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<checked_rat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<urat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<checked_urat512_t>::value);
#endif
//
// Assign:
//
#ifdef BOOST_HAS_NOTHROW_ASSIGN
BOOST_STATIC_ASSERT(!boost::has_nothrow_assign<boost::multiprecision::cpp_rational>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<rat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<checked_rat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<urat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<checked_urat128_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<rat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<checked_rat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<urat512_t>::value);
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<checked_urat512_t>::value);
#endif
//
// Construct from int:
//
BOOST_STATIC_ASSERT(noexcept(boost::multiprecision::cpp_rational(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat128_t(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat128_t(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat128_t(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(!noexcept(checked_urat128_t(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat512_t(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat512_t(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat512_t(std::declval<boost::multiprecision::signed_limb_type>())));
BOOST_STATIC_ASSERT(!noexcept(checked_urat512_t(std::declval<boost::multiprecision::signed_limb_type>())));
//
// Construct from unsigned int:
//
BOOST_STATIC_ASSERT(noexcept(boost::multiprecision::cpp_rational(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat128_t(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat128_t(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat128_t(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_urat128_t(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat512_t(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat512_t(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat512_t(std::declval<boost::multiprecision::limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_urat512_t(std::declval<boost::multiprecision::limb_type>())));
//
// Assign from int:
//
BOOST_STATIC_ASSERT(noexcept(std::declval<boost::multiprecision::cpp_rational>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat128_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat128_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat128_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(!noexcept(std::declval<checked_urat128_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat512_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat512_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat512_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
BOOST_STATIC_ASSERT(!noexcept(std::declval<checked_urat512_t>() = std::declval<boost::multiprecision::signed_limb_type>()));
//
// Assign from unsigned int:
//
BOOST_STATIC_ASSERT(noexcept(std::declval<boost::multiprecision::cpp_rational>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat128_t>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat128_t>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat128_t>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_urat128_t>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat512_t>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat512_t>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat512_t>() = std::declval<boost::multiprecision::limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_urat512_t>() = std::declval<boost::multiprecision::limb_type>()));

#if defined(BOOST_LITTLE_ENDIAN)
//
// Construct from int:
//
BOOST_STATIC_ASSERT(noexcept(boost::multiprecision::cpp_rational(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat128_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat128_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat128_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(!noexcept(checked_urat128_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat512_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat512_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat512_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
BOOST_STATIC_ASSERT(!noexcept(checked_urat512_t(std::declval<boost::multiprecision::signed_double_limb_type>())));
//
// Construct from unsigned int:
//
BOOST_STATIC_ASSERT(noexcept(boost::multiprecision::cpp_rational(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat128_t(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat128_t(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat128_t(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_urat128_t(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(rat512_t(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_rat512_t(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(urat512_t(std::declval<boost::multiprecision::double_limb_type>())));
BOOST_STATIC_ASSERT(noexcept(checked_urat512_t(std::declval<boost::multiprecision::double_limb_type>())));
//
// Assign from int:
//
BOOST_STATIC_ASSERT(noexcept(std::declval<boost::multiprecision::cpp_rational>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat128_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat128_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat128_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(!noexcept(std::declval<checked_urat128_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat512_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat512_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat512_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
BOOST_STATIC_ASSERT(!noexcept(std::declval<checked_urat512_t>() = std::declval<boost::multiprecision::signed_double_limb_type>()));
//
// Assign from unsigned int:
//
BOOST_STATIC_ASSERT(noexcept(std::declval<boost::multiprecision::cpp_rational>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat128_t>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat128_t>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat128_t>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_urat128_t>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<rat512_t>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_rat512_t>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<urat512_t>() = std::declval<boost::multiprecision::double_limb_type>()));
BOOST_STATIC_ASSERT(noexcept(std::declval<checked_urat512_t>() = std::declval<boost::multiprecision::double_limb_type>()));

#endif
#endif // little endian
#endif // noexcept


text:
//*****************************************************************************
// RCF - Remote Call Framework
// Copyright (c) 2005, Jarl Lindrud.
// Contact: jlindrud@hotmail.com .
//
// Distributed under the so-called MIT license, see accompanying file license.txt.
//*****************************************************************************

#ifndef _RCF_SERVERSTUB_HPP_
#define _RCF_SERVERSTUB_HPP_

#include <RCF/Connection.hpp>
#include <boost/shared_ptr.hpp>
#include <memory>

#include <RCF/Token.hpp>

namespace RCF {

    class Connection;

    class I_ServerStub
    {
    public:
        virtual ~I_ServerStub() {}
        virtual void invoke(int id, Connection &connection) = 0;
        virtual void setToken(Token token) = 0;
        virtual Token getToken() = 0;
    };

    template<typename StubT, typename ImplementationT>
    class ServerStub : public I_ServerStub, boost::noncopyable
    {
    public:
        ServerStub(ImplementationT &x);
        ServerStub(std::auto_ptr<ImplementationT> px);
        ServerStub(boost::shared_ptr<ImplementationT> px);

    private:
        void invoke(int id, RCF::Connection &connection);
        template<typename IdT> void invoke(StubT &stub, const IdT &id, Connection &connection, ImplementationT &t);
        Token getToken();
        void setToken(Token token);

        StubT stub;
        Token token;
        boost::shared_ptr<ImplementationT> px;
        ImplementationT &x;
    };

    class StubAccess
    {
    public:
        template<typename StubT, typename IdT, typename T>
        void invoke(StubT &stub, const IdT &id, Connection &connection, T &t);
    };

} // namespace RCF

#include <RCF/ServerStub.inl>

#endif // ! _RCF_SERVERSTUB_HPP_

max_stars_repo_name: importlib/klib

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
#pragma once
#include <string>
#include "Command.hpp"
#include <boost/serialization/base_object.hpp>

namespace vizkit3dDebugDrawings
{

/**A command that draws a primitive */
class ClearPlotCommand : public Command
{

    friend class boost::serialization::access;
    template<class Archive>
    void serialize(Archive & ar, const unsigned int version)
    {
        // serialize base class information
        ar & boost::serialization::base_object<Command>(*this);
    }

public:
    ClearPlotCommand(const std::string& drawingChannel);
    ClearPlotCommand();

    virtual void execute(DrawingManager* drawingManager) const;

    virtual ClearPlotCommand* clone() const;

    virtual ~ClearPlotCommand();
};
}


text:
//
// Created by xt on 12/9/20.
//

//aka Levenshtein distance

#include "edit_distance_common.hpp"
// get the edit_alignment() function
#include <boost/algorithm/sequence/edit_distance.hpp>
using boost::algorithm::sequence::edit_distance;
using namespace boost::algorithm::sequence::parameter;
using boost::algorithm::sequence::unit_cost;

#include <stdio.h>
#include <string>
#include <stdint.h>
#include <iomanip>
#include <sstream>

//OPE library
#include "sope_encode.h"
#include "ope.hh"
using namespace std;
#include <chrono>

#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <openssl/pem.h>

int do_evp_sign(FILE * rsa_pkey_file, FILE * in_file)
{
    OpenSSL_add_all_digests();
    ERR_load_crypto_strings();

    EVP_PKEY * pkey = PEM_read_PrivateKey(rsa_pkey_file, NULL, NULL, NULL);
    if (pkey == NULL) {
        ERR_print_errors_fp(stderr);
        return 1;
    }

    fseek(in_file, 0, SEEK_END);
    const size_t lSize = ftell(in_file);
    rewind(in_file);

    EVP_MD_CTX md_ctx;
    EVP_SignInit(&md_ctx, EVP_sha1());

    size_t len;
    unsigned char buffer[4096];

    size_t bytesLeft = lSize;
    while (bytesLeft > 0) {
        const size_t count = (bytesLeft > sizeof(buffer) ? sizeof(buffer) : bytesLeft);
        len = fread(buffer, 1, count, in_file);
        if (len != count) {
            fprintf(stderr, "Read error! len (%u) != count (%u).\n", len, count);
            EVP_PKEY_free(pkey);
            return 1;
        }
        if (!EVP_SignUpdate(&md_ctx, buffer, len))
        {
            ERR_print_errors_fp(stderr);
            EVP_PKEY_free(pkey);
            return 1;
        }
        bytesLeft -= len;
    }

    unsigned int sig_len;
    unsigned char * sig = (unsigned char *)malloc(EVP_PKEY_size(pkey));

    if (!sig) {
        fprintf(stderr, "Couldn't allocate %u bytes of memory.\n", EVP_PKEY_size(pkey));
        EVP_PKEY_free(pkey);
        return 1;
    }

    //run 1000 times to see the time

    //for (int x  = 0; x < 1000; x++){
    if (!EVP_SignFinal(&md_ctx, sig, &sig_len, pkey))
    {
        ERR_print_errors_fp(stderr);
        EVP_PKEY_free(pkey);
        free(sig);
        return 1;
    }
    //}

    /*
    FILE * fTemp = fopen("out.sig", "wb");
    if (fTemp) {
        printf("Writing the signature to a file. Number of bytes: %u.\n", sig_len);
        fwrite(sig, 1, sig_len, fTemp);
        fclose(fTemp);
    }

    printf("Signature: \n");
    for (unsigned int i = 0; i != sig_len; ++i)
    {
        printf("%02x", sig[i]);
        if (i % 16 == 15)
            printf("\n");
    }
    printf("\n");
    */
    //printf("free!!!\n");
    EVP_PKEY_free(pkey);
    free(sig);

    return 0;
}

/*
 *  input: int i: plaintext
 *  return: NTL:ZZ: Order-repserving ciphertexts
 *
*/
NTL::ZZ OPEncryption(int plaintext){
    NTL::ZZ m1 = NTL::to_ZZ(plaintext);

    // plaintext range's length in bits (plaintexts are in [0, 2**P-1]
    unsigned int P = 32;
    // ciphertext range's length in bits (ciphertexts are in [0, 2**C-1]
    unsigned int C = 64;

    //OPE o("S0M3 $TR@NG Key", P, C);
    OPE o("S0M3$TR@NGKeySSSSSSSSSSSSSSSS", P, C);

    // it works with ZZ instead of usual integers
    //NTL::ZZ m1 = NTL::to_ZZ(13);
    //NTL::ZZ m2 = NTL::to_ZZ(50);

    NTL::ZZ c1 = o.encrypt(m1);
    //NTL::ZZ c2 = o.encrypt(m2);

    //cout << "m1 = " << m1 << endl;
    //cout << "m2 = " << m2 << endl;
    //cout << "enc(m1) = " << c1 << endl;
    //cout << "enc(m2) = " << c2 << endl;

    /*
  if (c1 < c2){
      cout << "Preserving the order!" << endl;
  }else{
      cout << "o.O ????? OPE not working!" << endl;
  }

  NTL::ZZ dec_m1 = o.decrypt(c1);
  NTL::ZZ dec_m2 = o.decrypt(c2);

  if (m1 == dec_m1 && m2 == dec_m2){
      cout << "Decryption working fine." << endl;
  }else{
      cout << "Decryption NOT working." << endl;
  }
  */

    return c1;

}

int main(int argc, char** argv) {
    char const* str1_user = "Oh, hello world.";
    char const* str1_id = "Hello world!!";

    // edit distance time

    //stringstream_tuple_output<unit_cost, char const*> out;
    //unsigned dist = edit_distance(str1_user, str1_id, _script = out);
    //std::cout << "dist= " << dist << "   edit operations= " << out.ss.str() << "\n";
    auto t1 = chrono::high_resolution_clock::now();
    for (int x = 0; x < 50; x++){
        unsigned dist = edit_distance(str1_user, str1_id);
    }
    auto t2 = chrono::high_resolution_clock::now();
    auto duration1 = chrono::duration_cast<chrono::microseconds>(t2 - t1).count();

    cout << "1000 times Edit Distance:" << duration1 << endl;

    auto t3 = chrono::high_resolution_clock::now();
    for (int x  = 0; x < 10; x++){
        OPEncryption(13);
    }
    auto t4 = chrono::high_resolution_clock::now();
    auto duration2 = chrono::duration_cast<chrono::microseconds>(t4 - t3).count();
    cout << "1000 times OPE:" << duration2 << endl;

    //sha256 1000 times test
    auto t5 = chrono::high_resolution_clock::now();
    for (int x  = 0; x < 1000; x++){
        auto v = sha256::hash(str1_user);
    }
    auto t6 = chrono::high_resolution_clock::now();
    auto duration3 = chrono::duration_cast<chrono::microseconds>(t6 - t5).count();
    cout << "1000 SHA256:" << duration3 << endl;

    // 1000 times PKI ESign
    t1 = chrono::high_resolution_clock::now();
    for (int x = 0; x < 10; x++){
        FILE *keyfile = fopen("/home/xt/mpkix-judgement/key-and-file/key", "r");
        FILE *contentfile = fopen("/home/xt/mpkix-judgement/key-and-file/info", "r");
        do_evp_sign(keyfile, contentfile);
    }
    t2 = chrono::high_resolution_clock::now();
    duration1 = chrono::duration_cast<chrono::microseconds>(t2 - t1).count();
    cout << "1000 times ESign:" << duration1 << endl;

    return 0;
}