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 <boost/bind.hpp>
#include <iomanip>

#include "gazebo/common/CommonIface.hh"

#include "gazebo/rendering/RenderingIface.hh"
#include "gazebo/rendering/Scene.hh"

#include "gazebo/gui/GuiPlugin.hh"
#include "gazebo/gui/Actions.hh"
#include "gazebo/gui/GuiIface.hh"
#include "gazebo/gui/GLWidget.hh"
#include "gazebo/gui/GuiEvents.hh"
#include "gazebo/gui/TimePanel.hh"
#include "gazebo/gui/TopToolbar.hh"
#include "gazebo/gui/RenderWidget.hh"

using namespace gazebo;
using namespace gui;

/////////////////////////////////////////////////
RenderWidget::RenderWidget(QWidget *_parent)
  : QWidget(_parent)
{
  this->setObjectName("renderWidget");

  QVBoxLayout *mainLayout = new QVBoxLayout;
  this->mainFrame = new QFrame(this);
  this->mainFrame->setFrameShape(QFrame::NoFrame);
  this->mainFrame->show();

  QVBoxLayout *frameLayout = new QVBoxLayout;

  // Top toolbar
  this->topToolbar = new TopToolbar();

  // GLWigdet
  this->glWidget = new GLWidget(this->mainFrame);

  this->msgOverlayLabel = new QLabel(this->glWidget);
  this->msgOverlayLabel->setStyleSheet(
      "QLabel { background-color : white; color : gray; }");
  this->msgOverlayLabel->setVisible(false);

  QHBoxLayout *bottomPanelLayout = new QHBoxLayout;

  this->timePanel = new TimePanel(this);

  this->bottomFrame = new QFrame;
  this->bottomFrame->setObjectName("renderBottomFrame");
  this->bottomFrame->setSizePolicy(QSizePolicy::Expanding,
      QSizePolicy::Minimum);

  bottomPanelLayout->addWidget(this->timePanel, 0);
  bottomPanelLayout->setSpacing(0);
  bottomPanelLayout->setContentsMargins(0, 0, 0, 0);
  this->bottomFrame->setLayout(bottomPanelLayout);

  QFrame *render3DFrame = new QFrame;
  render3DFrame->setObjectName("render3DFrame");
  QVBoxLayout *render3DLayout = new QVBoxLayout;
  render3DLayout->addWidget(this->topToolbar);
  render3DLayout->addWidget(this->glWidget);
  render3DLayout->setContentsMargins(0, 0, 0, 0);
  render3DLayout->setSpacing(0);
  render3DFrame->setLayout(render3DLayout);

  this->splitter = new QSplitter(this);
  this->splitter->addWidget(render3DFrame);
  QList<int> sizes;
  sizes.push_back(300);
  this->splitter->setSizes(sizes);
  this->splitter->setStretchFactor(0, 1);
  this->splitter->setOrientation(Qt::Vertical);

  frameLayout->addWidget(this->splitter);
  frameLayout->addWidget(this->bottomFrame);
  frameLayout->setContentsMargins(0, 0, 0, 0);
  frameLayout->setSpacing(0);

  this->mainFrame->setLayout(frameLayout);
  this->mainFrame->layout()->setContentsMargins(0, 0, 0, 0);

  mainLayout->addWidget(this->mainFrame);

  this->setLayout(mainLayout);
  this->layout()->setContentsMargins(0, 0, 0, 0);

  this->connections.push_back(
      gui::Events::ConnectFollow(
        boost::bind(&RenderWidget::OnFollow, this, _1)));
}

/////////////////////////////////////////////////
void RenderWidget::Init()
{
  // Load all GUI Plugins.
  // This has to be done here instead of in the constructor because
  // it has to be ensured that the main window already has been
  // created, as some GUI plugins may need it (RenderWidget is
  // created from gui::MainWindow constructor, therefore the main
  // window won't yet be available).

  std::string filenames = getINIProperty<std::string>(
      "overlay_plugins.filenames", "");

  // Split the colon separated libraries
  auto pluginFilenames = common::split(filenames, ":");

  // Load each plugin
  this->AddPlugins(pluginFilenames);
}

/////////////////////////////////////////////////
RenderWidget::~RenderWidget()
{
  // clear the plugins before the widgets are deleted
  this->plugins.clear();

  delete this->glWidget;
  this->glWidget = NULL;

  delete this->topToolbar;
  this->topToolbar = NULL;

  // we created the scene here we are responsible for removing it.
  rendering::remove_scene(gui::get_world());
}

/////////////////////////////////////////////////
void RenderWidget::InsertWidget(unsigned int _index, QWidget *_widget)
{
  if (static_cast<int>(_index) <= this->splitter->count())
  {
    // set equal size for now. There should always be at least one widget
    // (render3DFrame) in the splitter.
    int childCount = this->splitter->count();
    GZ_ASSERT(childCount > 0,
        "RenderWidget splitter has no child widget");

    QSize widgetSize = this->size();
    int newSize = widgetSize.height() / (this->splitter->count()+1);
    QList<int> newSizes;
    for (int i = 0; i < childCount+1; ++i)
      newSizes.append(newSize);

    this->splitter->insertWidget(_index, _widget);
    this->splitter->setSizes(newSizes);
    this->splitter->setStretchFactor(_index, 1);
  }
  else
    gzerr << "Unable to add widget, index out of range " << std::endl;
}

/////////////////////////////////////////////////
void RenderWidget::ShowTimePanel(bool _show)
{
  if (_show)
    this->bottomFrame->show();
  else
    this->bottomFrame->hide();
}

/////////////////////////////////////////////////
TimePanel *RenderWidget::GetTimePanel() const
{
  return this->timePanel;
}

/////////////////////////////////////////////////
void RenderWidget::RemoveScene(const std::string &_name)
{
  rendering::remove_scene(_name);
}

/////////////////////////////////////////////////
void RenderWidget::CreateScene(const std::string &_name)
{
  rendering::create_scene(_name, true);
}

/////////////////////////////////////////////////
void RenderWidget::DisplayOverlayMsg(const std::string &_msg, int _duration)
{
  std::string msg = this->baseOverlayMsg.empty() ? _msg
      : this->baseOverlayMsg + "\n" + _msg;
  this->msgOverlayLabel->setText(tr(msg.c_str()));
  if (msg.empty())
  {
    this->msgOverlayLabel->setVisible(false);
    return;
  }
  this->msgOverlayLabel->resize(
      this->msgOverlayLabel->fontMetrics().width(tr(msg.c_str())),
      this->msgOverlayLabel->fontMetrics().height());
  this->msgOverlayLabel->setVisible(true);

  if (_duration > 0)
    QTimer::singleShot(_duration, this, SLOT(OnClearOverlayMsg()));
}

/////////////////////////////////////////////////
void RenderWidget::SetOverlaysVisible(const bool _visible)
{
  for (auto const &plugin : this->plugins)
    plugin->setVisible(_visible);
}

/////////////////////////////////////////////////
std::string RenderWidget::GetOverlayMsg() const
{
  return this->msgOverlayLabel->text().toStdString();
}

/////////////////////////////////////////////////
void RenderWidget::ShowToolbar(const bool _show)
{
  if (this->topToolbar)
  {
    if (_show)
    {
      this->topToolbar->show();
    }
    else
    {
      this->topToolbar->hide();
    }
  }
}

/////////////////////////////////////////////////
TopToolbar *RenderWidget::GetToolbar() const
{
  return this->topToolbar;
}

/////////////////////////////////////////////////
void RenderWidget::OnClearOverlayMsg()
{
  this->DisplayOverlayMsg("");
}

/////////////////////////////////////////////////
void RenderWidget::OnFollow(const std::string &_modelName)
{
  if (_modelName.empty())
  {
    g_translateAct->setEnabled(true);
    g_rotateAct->setEnabled(true);
  }
  else
  {
    g_translateAct->setEnabled(false);
    g_rotateAct->setEnabled(false);
  }
}

/////////////////////////////////////////////////
void RenderWidget::AddPlugins(const std::vector<std::string> &_pluginFilenames)
{
  // Load each plugin
  for (std::vector<std::string>::const_iterator iter = _pluginFilenames.begin();
       iter != _pluginFilenames.end(); ++iter)
  {
    // Make sure the string is not empty
    if ((*iter).empty()) continue;

    // create an empty element as this function ignores SDF
    sdf::ElementPtr elem(new sdf::Element());
    this->AddPlugin(*iter, elem);
  }
}

/////////////////////////////////////////////////
bool RenderWidget::AddPlugin(const std::string &_filename,
                             sdf::ElementPtr _elem)
{
  if (_filename.empty())
  {
    gzerr << "Unable to create gui overlay plugin from an empty file\n";
    return false;
  }

  // Try to create the plugin
  gazebo::GUIPluginPtr plugin = gazebo::GUIPlugin::Create(_filename, _filename);

  if (!plugin)
  {
    gzerr << "Unable to create gui overlay plugin with filename["
      << _filename << "]\n";
    return false;
  }

  if (plugin->GetType() != gazebo::GUI_PLUGIN)
  {
    gzerr << "System is attempting to load "
      << "a plugin, but detected an incorrect plugin type. "
      << "Plugin filename[" << _filename << "].\n";
    return false;
  }

  this->AddPlugin(plugin, _elem);

  gzlog << "Loaded GUI plugin[" << _filename << "]\n";
  return true;
}

/////////////////////////////////////////////////
void RenderWidget::AddPlugin(GUIPluginPtr _plugin, sdf::ElementPtr _elem)
{
  // Set the plugin's parent and store the plugin
  _plugin->setParent(this->glWidget);
  this->plugins.push_back(_plugin);

  // Load the plugin, if the element is set
  if (_elem)
    _plugin->Load(_elem);

  _plugin->show();
}

max_stars_repo_name: yinnglu/gazebo

max_issues_repo_name: yinnglu/gazebo

max_forks_repo_name: yinnglu/gazebo


text:
#ifndef __LV_HEADER__
#define __LV_HEADER__

#include <Eigen/Dense>

#endif // eof __LV_HEADER__

ext: hpp

max_stars_repo_name: StanJBrown/robotics-playground

max_issues_repo_name: StanJBrown/robotics-playground

max_forks_repo_name: StanJBrown/robotics-playground


text:
// __BEGIN_LICENSE__
// Copyright (C) 2006-2011 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/FileIO.h>
#include <vw/Image.h>
#include <vw/Cartography.h>
#include <vw/InterestPoint.h>
#include <vw/Math.h>
#include <vw/Mosaic/ImageComposite.h>
#include <asp/ControlNetTK/Equalization.h>
#include <asp/Core/Common.h>
#include <asp/Core/Macros.h>
#include <limits>

#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;

using std::cout;
using std::endl;
using std::string;

using namespace vw;
using namespace vw::cartography;
using namespace vw::ip;

// Allows FileIO to correctly read/write these pixel types
namespace vw {
  template<> struct PixelFormatID<Vector3>   { static const PixelFormatEnum value = VW_PIXEL_GENERIC_3_CHANNEL; };
}

template <int dim>
class HomogeneousTransformFunctor : public UnaryReturnSameType {
  Matrix<double,dim+1,dim+1> m_trans;

public:
  HomogeneousTransformFunctor(Matrix<double,dim+1,dim+1> trans) : m_trans(trans) {}

  inline Vector<double,dim> operator()(Vector<double,dim> pt) const {
    if (pt == Vector<double,dim>())
      return pt;

    Vector<double,dim+1> pt_h;
    subvector(pt_h, 0, dim) = pt;
    pt_h[dim] = 1;

    Vector<double,dim+1> result = m_trans * pt_h;
    if (result[dim] != 1)
      result /= result[dim];
    return subvector(result,0,dim);
  }
};

void match_orthoimages( string const& left_image_name,
                        string const& right_image_name,
                        std::vector<InterestPoint> & matched_ip1,
                        std::vector<InterestPoint> & matched_ip2,
                        size_t const& max_points )
{

  vw_out() << "\t--> Finding Interest Points for the orthoimages\n";

  fs::path left_image_path(left_image_name), right_image_path(right_image_name);
  string left_ip_file = change_extension(left_image_path, ".vwip").string();
  string right_ip_file = change_extension(right_image_path, ".vwip").string();
  string match_file = (left_image_path.branch_path() / (fs::basename(left_image_path) + "__" + fs::basename(right_image_path) + ".match")).string();

  // Building / Loading Interest point data
  if ( fs::exists(match_file) ) {

    vw_out() << "\t    * Using cached match file.\n";
    read_binary_match_file(match_file, matched_ip1, matched_ip2);
    vw_out() << "\t    * " << matched_ip1.size() << " matches\n";

  } else {
    std::vector<InterestPoint> ip1_copy, ip2_copy;

    if ( !fs::exists(left_ip_file) ||
         !fs::exists(right_ip_file) ) {

      // Worst case, no interest point operations have been performed before
      vw_out() << "\t    * Locating Interest Points\n";
      DiskImageView<PixelGray<float32> > left_disk_image(left_image_name);
      DiskImageView<PixelGray<float32> > right_disk_image(right_image_name);

      // Interest Point module detector code.
      OBALoGInterestOperator obalog_detector(0.03);
      IntegralInterestPointDetector<OBALoGInterestOperator> detector( obalog_detector, 200 );
      std::list<InterestPoint> ip1, ip2;
      vw_out() << "\t    * Processing " << left_image_name << "...\n" << std::flush;
      ip1 = detect_interest_points( left_disk_image, detector );
      vw_out() << "Located " << ip1.size() << " points.\n";
      vw_out() << "\t    * Processing " << right_image_name << "...\n" << std::flush;
      ip2 = detect_interest_points( right_disk_image, detector );
      vw_out() << "Located " << ip2.size() << " points.\n";

      vw_out() << "\t    * Generating descriptors..." << std::flush;
      SGradDescriptorGenerator descriptor;
      descriptor( left_disk_image, ip1 );
      descriptor( right_disk_image, ip2 );
      vw_out() << "done.\n";

      // Writing out the results
      vw_out() << "\t    * Caching interest points: "
               << left_ip_file << " & " << right_ip_file << std::endl;
      write_binary_ip_file( left_ip_file, ip1 );
      write_binary_ip_file( right_ip_file, ip2 );

    }

    vw_out() << "\t    * Using cached IPs.\n";
    ip1_copy = read_binary_ip_file(left_ip_file);
    ip2_copy = read_binary_ip_file(right_ip_file);

    vw_out() << "\t    * Matching interest points\n";
    ip::DefaultMatcher matcher(0.6);

    matcher(ip1_copy, ip2_copy, matched_ip1, matched_ip2,
            false, TerminalProgressCallback( "asp", "\t    Matching: "));
    ip::remove_duplicates(matched_ip1, matched_ip2);
    vw_out(InfoMessage) << "\t    " << matched_ip1.size() << " putative matches.\n";
    asp::cnettk::equalization( matched_ip1, matched_ip2, max_points );
    vw_out(InfoMessage) << "\t    " << matched_ip1.size() << " thinned matches.\n";

    vw_out() << "\t    * Caching matches: " << match_file << "\n";
    write_binary_match_file( match_file, matched_ip1, matched_ip2);
  }

}

struct Options : public asp::BaseOptions {
  Options() : dem1_nodata(std::numeric_limits<double>::quiet_NaN()), dem2_nodata(std::numeric_limits<double>::quiet_NaN()) {}
  // Input
  string dem1_name, dem2_name, ortho1_name, ortho2_name;
  double dem1_nodata, dem2_nodata;
  size_t max_points;

  // Output
  string output_prefix;
};

void handle_arguments( int argc, char *argv[], Options& opt ) {
  po::options_description general_options("");
  general_options.add_options()
    ("max-match-points", po::value(&opt.max_points)->default_value(800), "The max number of points that will be enforced after matching.")
    ("default-value", po::value(&opt.dem1_nodata), "The value of missing pixels in the first dem")
    ("output-prefix,o", po::value(&opt.output_prefix), "Specify the output prefix");
  general_options.add( asp::BaseOptionsDescription(opt) );

  po::options_description positional("");
  positional.add_options()
    ("dem1", po::value(&opt.dem1_name), "Explicitly specify the first dem")
    ("dem2", po::value(&opt.dem2_name), "Explicitly specify the second dem")
    ("ortho1", po::value(&opt.ortho1_name), "Explicitly specify the first orthoimage")
    ("ortho2", po::value(&opt.ortho2_name), "Explicitly specify the second orthoimage");

  po::positional_options_description positional_desc;
  positional_desc.add("dem1", 1);
  positional_desc.add("ortho1", 1);
  positional_desc.add("dem2", 1);
  positional_desc.add("ortho2", 1);

  std::string usage("<dem1> <ortho1> <dem2> <ortho2>");
  po::variables_map vm =
    asp::check_command_line( argc, argv, opt, general_options,
                             positional, positional_desc, usage );

  if ( opt.dem1_name.empty() || opt.dem2_name.empty() ||
       opt.ortho1_name.empty() || opt.ortho2_name.empty() )
    vw_throw( ArgumentErr() << "Missing input files.\n"
              << usage << general_options );
  if ( opt.output_prefix.empty() )
    opt.output_prefix = change_extension(fs::path(opt.dem1_name), "").string();
}

int main( int argc, char *argv[] ) {

  Options opt;
  try {
    handle_arguments( argc, argv, opt );

    DiskImageResourceGDAL ortho1_rsrc(opt.ortho1_name), ortho2_rsrc(opt.ortho2_name),
      dem1_rsrc(opt.dem1_name), dem2_rsrc(opt.dem2_name);

    // Pull out dem nodatas
    if ( opt.dem1_nodata == std::numeric_limits<double>::quiet_NaN() &&
         dem1_rsrc.has_nodata_read() ) {
      opt.dem1_nodata = dem1_rsrc.nodata_read();
      vw_out() << "\tFound DEM1 input nodata value: "
               << opt.dem1_nodata << endl;
    }
    if ( dem2_rsrc.has_nodata_read() ) {
      opt.dem2_nodata = dem2_rsrc.nodata_read();
      vw_out() << "\tFound DEM2 input nodata value: "
               << opt.dem2_nodata << endl;
    } else {
      vw_out() << "\tMissing nodata value for DEM2. Using DEM1 nodata value.\n";
      opt.dem2_nodata = opt.dem1_nodata;
    }

    typedef DiskImageView<double> dem_type;
    dem_type dem1_dmg(opt.dem1_name), dem2_dmg(opt.dem2_name);

    typedef InterpolationView<EdgeExtensionView<dem_type, ConstantEdgeExtension>, BilinearInterpolation> bilinear_type;
    typedef InterpolationView<EdgeExtensionView<dem_type, ConstantEdgeExtension>, NearestPixelInterpolation> nearest_type;
    bilinear_type dem1_interp =
      interpolate(dem1_dmg, BilinearInterpolation(), ConstantEdgeExtension());
    bilinear_type dem2_interp =
      interpolate(dem2_dmg, BilinearInterpolation(), ConstantEdgeExtension());
    nearest_type dem1_nearest =
      interpolate(dem1_dmg, NearestPixelInterpolation(), ConstantEdgeExtension());
    nearest_type dem2_nearest =
      interpolate(dem2_dmg, NearestPixelInterpolation(), ConstantEdgeExtension());

    GeoReference ortho1_georef, ortho2_georef, dem1_georef, dem2_georef;
    read_georeference(ortho1_georef, ortho1_rsrc);
    read_georeference(ortho2_georef, ortho2_rsrc);
    read_georeference(dem1_georef, dem1_rsrc);
    read_georeference(dem2_georef, dem2_rsrc);

    std::vector<InterestPoint> matched_ip1, matched_ip2;

    match_orthoimages(opt.ortho1_name, opt.ortho2_name,
                      matched_ip1, matched_ip2, opt.max_points);

    vw_out() << "\t--> Rejecting outliers using RANSAC.\n";
    std::vector<Vector4> ransac_ip1, ransac_ip2;
    for (size_t i = 0; i < matched_ip1.size(); i++) {
      Vector2 point1 = ortho1_georef.pixel_to_lonlat(Vector2(matched_ip1[i].x, matched_ip1[i].y));
      Vector2 point2 = ortho2_georef.pixel_to_lonlat(Vector2(matched_ip2[i].x, matched_ip2[i].y));

      Vector2 dem_pixel1 = dem1_georef.lonlat_to_pixel(point1);
      Vector2 dem_pixel2 = dem2_georef.lonlat_to_pixel(point2);

      if ( dem1_nearest(dem_pixel1.x(),dem_pixel1.y()) != opt.dem1_nodata &&
           dem2_nearest(dem_pixel2.x(),dem_pixel2.y()) != opt.dem2_nodata ) {

        double alt1 = dem1_georef.datum().radius(point1.x(), point1.y()) + dem1_interp(dem_pixel1.x(), dem_pixel1.y());
        double alt2 = dem2_georef.datum().radius(point2.x(), point2.y()) + dem2_interp(dem_pixel2.x(), dem_pixel2.y());

        Vector3 xyz1 = lon_lat_radius_to_xyz(Vector3(point1.x(), point1.y(), alt1));
        Vector3 xyz2 = lon_lat_radius_to_xyz(Vector3(point2.x(), point2.y(), alt2));

        ransac_ip1.push_back(Vector4(xyz1.x(), xyz1.y(), xyz1.z(), 1));
        ransac_ip2.push_back(Vector4(xyz2.x(), xyz2.y(), xyz2.z(), 1));
      } else {
        vw_out() << "Actually dropped something.\n";
      }
    }

    std::vector<size_t> indices;
    Matrix<double> trans;
    math::RandomSampleConsensus<math::AffineFittingFunctorN<3>,math::L2NormErrorMetric>
      ransac( math::AffineFittingFunctorN<3>(), math::L2NormErrorMetric(), 10);
    trans = ransac(ransac_ip1, ransac_ip2);
    indices = ransac.inlier_indices(trans, ransac_ip1, ransac_ip2);

    vw_out() << "\t    * Ransac Result: " << trans << "\n";
    vw_out() << "\t                     # inliers: " << indices.size() << "\n";

    { // Saving transform to human readable text
      std::string filename = (fs::path(opt.dem1_name).branch_path() / (fs::basename(fs::path(opt.dem1_name)) + "__" + fs::basename(fs::path(opt.dem2_name)) + "-Matrix.txt")).string();
      std::ofstream ofile( filename.c_str() );
      ofile << std::setprecision(15) << std::flush;
      ofile << "# inliers: " << indices.size() << endl;
      ofile << trans << endl;
      ofile.close();
    }

    ImageViewRef<PixelMask<double> > dem1_masked(create_mask(dem1_dmg, opt.dem1_nodata));

    ImageViewRef<Vector3> point_cloud =
      lon_lat_radius_to_xyz(project_point_image(dem_to_point_image(dem1_masked, dem1_georef), dem1_georef, false));
    ImageViewRef<Vector3> point_cloud_trans =
      per_pixel_filter(point_cloud, HomogeneousTransformFunctor<3>(trans));

    DiskImageResourceGDAL point_cloud_rsrc(opt.output_prefix + "-PC.tif",
                                           point_cloud_trans.format(),
                                           opt.raster_tile_size,
                                           opt.gdal_options);
    block_write_image(point_cloud_rsrc, point_cloud_trans,
                      TerminalProgressCallback("asp", "\t--> Transforming: "));
  } ASP_STANDARD_CATCHES;

  return 0;
}

ext: cc

max_stars_repo_name: nasa/StereoPipeline

max_issues_repo_name: imagineagents/StereoPipeline

max_forks_repo_name: imagineagents/StereoPipeline


text:
#include <pybind11/pybind11.h>

#include "wrapper_client.hpp"
#include "wrapper_collection.hpp"
#include "wrapper_database.hpp"
#include "wrapper_cursor.hpp"
#include "wrapper_document_id.hpp"
#include "wrapper_document.hpp"
#include "wrapper_result.hpp"

#include <boost/uuid/uuid.hpp>            // uuid class
#include <boost/uuid/uuid_generators.hpp> // generators
#include <boost/uuid/uuid_io.hpp>         // streaming operators etc.

#include "spaces.hpp"

// The bug related to the use of RTTI by the pybind11 library has been fixed: a
// declaration should be in each translation unit.
PYBIND11_DECLARE_HOLDER_TYPE(T, boost::intrusive_ptr<T>)

using namespace duck_charmer;

PYBIND11_MODULE(duck_charmer, m) {
    py::class_<wrapper_client>(m, "Client")
        .def(py::init([](){
            auto* spaces =  spaces::get_instance();
            auto dispatcher =  spaces->dispatcher();
            dispatcher->load();
            auto log = spaces::get_instance()->get_log().clone();
            return new wrapper_client(log,dispatcher);
        }))
        .def("__getitem__", &wrapper_client::get_or_create)
        .def("database_names", &wrapper_client::database_names)
        ;

    py::class_<wrapper_database, boost::intrusive_ptr<wrapper_database>>(m, "DataBase")
        .def("collection_names", &wrapper_database::collection_names)
        .def("drop_collection", &wrapper_database::drop_collection)
        .def("__getitem__", &wrapper_database::create)
        ;

    py::class_<wrapper_collection, boost::intrusive_ptr<wrapper_collection>>(m, "Collection")
        .def("__repr__", &wrapper_collection::print)
        .def("__len__", &wrapper_collection::size)
        .def("count", &wrapper_collection::size)
        .def("insert", &wrapper_collection::insert, py::arg("documents"))
        .def("insert_one", &wrapper_collection::insert_one, py::arg("document"))
        .def("insert_many", &wrapper_collection::insert_many, py::arg("documents"))
        .def("update_one", &wrapper_collection::update_one, py::arg("filter"), py::arg("update"), py::arg("upsert") = false)
        .def("update_many", &wrapper_collection::update_many, py::arg("filter"), py::arg("update"), py::arg("upsert") = false)
        .def("find", &wrapper_collection::find, py::arg("filter") = py::dict())
        .def("find_one", &wrapper_collection::find_one, py::arg("filter") = py::dict())
        .def("delete_one", &wrapper_collection::delete_one, py::arg("filter") = py::dict())
        .def("delete_many", &wrapper_collection::delete_many, py::arg("filter") = py::dict())
        .def("drop", &wrapper_collection::drop)
        ;

    py::class_<wrapper_document_id, boost::intrusive_ptr<wrapper_document_id>>(m, "ObjectId")
        .def(py::init([](){
            return wrapper_document_id();
        }))
        .def(py::init([](const py::str& s){
            return wrapper_document_id(s);
        }))
        .def(py::init([](const py::int_& time){
            return wrapper_document_id(time);
        }))
        .def("__repr__", &wrapper_document_id::to_string)
        .def("getTimestamp", &wrapper_document_id::get_timestamp)
        .def("toString", &wrapper_document_id::to_string)
        .def("valueOf", &wrapper_document_id::value_of)
        .def_property_readonly("str", &wrapper_document_id::to_string)
        ;

    py::class_<wrapper_document, boost::intrusive_ptr<wrapper_document>>(m, "Document")
        .def("__repr__", &wrapper_document::print)
        .def("__getitem__", &wrapper_document::get)
        .def("get", &wrapper_document::get)
        ;

    py::class_<wrapper_cursor, boost::intrusive_ptr<wrapper_cursor>>(m, "Cursor")
        .def("__repr__", &wrapper_cursor::print)
        .def("__del__", &wrapper_cursor::close)
        .def("__len__", &wrapper_cursor::size)
        .def("__getitem__", &wrapper_cursor::get)
        .def("__iter__", &wrapper_cursor::iter)
        .def("__next__", &wrapper_cursor::next)
        .def("count", &wrapper_cursor::size)
        .def("close", &wrapper_cursor::close)
        .def("hasNext", &wrapper_cursor::has_next)
        .def("next", &wrapper_cursor::next)
        //.def("paginate", &wrapper_cursor::paginate)
        //.def("_order", &wrapper_cursor::_order)
        .def("sort", &wrapper_cursor::sort, py::arg("key_or_list"), py::arg("direction") = py::none())
        ;

    py::class_<wrapper_result_delete, boost::intrusive_ptr<wrapper_result_delete>>(m, "DeleteResult")
        .def_property_readonly("raw_result", &wrapper_result_delete::raw_result)
        .def_property_readonly("deleted_count", &wrapper_result_delete::deleted_count)
        ;

    py::class_<wrapper_result_update, boost::intrusive_ptr<wrapper_result_update>>(m, "UpdateResult")
        .def_property_readonly("raw_result", &wrapper_result_update::raw_result)
        .def_property_readonly("matched_count", &wrapper_result_update::matched_count)
        .def_property_readonly("modified_count", &wrapper_result_update::modified_count)
        .def_property_readonly("upserted_id", &wrapper_result_update::upserted_id)
        ;
}

ext: cpp

max_stars_repo_name: jinntechio/RocketJoe

max_issues_repo_name: jinntechio/RocketJoe

max_forks_repo_name: jinntechio/RocketJoe


text:
#pragma once

#include <jkl/config.hpp>
#include <jkl/url.hpp>
#include <jkl/tcp.hpp>
#include <jkl/ssl.hpp>
#include <jkl/task.hpp>
#include <jkl/result.hpp>
#include <jkl/ec_awaiter.hpp>
#include <jkl/util/unit.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/ssl/ssl_stream.hpp>

namespace jkl{

namespace http = beast::http;

using beast::simple_rate_policy;
using beast::unlimited_rate_policy;
using beast::flat_buffer;

template<class Stream, class Req, class Res, class ReadBuf>
class http_conn_t
{
    Stream  _s;
    ReadBuf _rb;

    template<class M, class... P>
    auto do_read(M& m, P... p)
    {
        return make_ec_awaiter<size_t>(
            [&](auto&& h) { http::async_read(_s, _rb, m, std::move(h)); }
            p...);
    }

    template<class M, class... P>
    auto do_write(M& m, P... p)
    {
        return make_ec_awaiter<size_t>(
            [&](auto&& h) { http::async_write(_s, m, std::move(h)); }
            p...);
    }

public:
    using stream_type       = Stream;
    using executor_type     = typename Stream::executor_type;
    using next_layer_type   = next_layer_t<Stream>;
    using lowest_layer_type = typename next_layer_type::lowest_layer_type;
    using socket_type       = typename next_layer_type::socket_type;

    using req_type = Req;
    using res_type = Res;

    Req req;
    Res res;

    template<class... A>
    explicit http_conn_t(A&&... streamArgs) : _s(std::forward<A>(streamArgs)...) {}

    //http_conn_t& operator=(socket_type&& s) { socket() = std::move(s); }

    void set_max_read_buf(_B_<size_t> n) { if(n != max_read_buf()) _rb = ReadBuf(n.count()); }
    _B_<size_t> max_read_buf() const noexcept { return _B_(_rb.max_size()); }

    auto      & stream()       noexcept { return _s; }
    auto const& stream() const noexcept { return _s; }
    auto      & astream()       noexcept { return _s; }
    auto const& astream() const noexcept { return _s; }

    // e.g.: beast::basic_stream
    auto      & next_layer()       { return get_next_layer(_s); }
    auto const& next_layer() const { return get_next_layer(_s); }
    // e.g.: asio::basic_stream_socket
    auto      & socket()       { return next_layer().socket(); }
    auto const& socket() const { return next_layer().socket(); }
    // e.g.: asio::basic_socket
    auto      & lowest_layer()       { return socket().lowest_layer(); }
    auto const& lowest_layer() const { return socket().lowest_layer(); }

    decltype(auto) stream_native_handle() { return stream().native_handle(); }
    decltype(auto) socket_native_handle() { return socket().native_handle(); }

    auto      & rate_policy()       { return next_layer().rate_policy(); }
    auto const& rate_policy() const { return next_layer().rate_policy(); }

    auto get_executor() const { return next_layer().get_executor(); }

    void cancel() { next_layer().cancel(); }
    void close () { next_layer().close (); }
    void expires_after(std::chrono::nanoseconds t) { next_layer().expires_after(t); }
    void expires_at(asio::steady_timer::time_point t) { next_layer().expires_at(t); }
    void expires_never() { next_layer().expires_never(); }
    auto release_socket() { return next_layer().release_socket();}

    template<class T>
    aresult<> set_option(T const& t)
    {
        aerror_code e;
        lowest_layer().set_option(t, e);
        return e;
    }

    template<class T>
    aresult<> get_option(T& t)
    {
        aerror_code e;
        lowest_layer().get_option(t, e);
        if(! e)
            return t;
        return e;
    }

    template<class T>
    aresult<T> option()
    {
        T t;
        JKL_TRY(get_option(t));
        return t;
    }

    template<class... P> auto read_req (P... p) { return do_read (req, p...); }
    template<class... P> auto read_res (P... p) { return do_read (res, p...); }
    template<class... P> auto write_req(P... p) { return do_write(req, p...); }
    template<class... P> auto write_res(P... p) { return do_write(res, p...); }

    template<class Ep, class... P>
    auto connect_endpoint(Ep&& ep, P... p)
    {
        return make_ec_awaiter(
            [&, ep = std::forward<Ep>(ep)](auto&& h){ next_layer().async_connect(ep, std::move(h)); },
            p...);
    }

    template<class... P>
    aresult_task<> connect(aurl u, P... p)
    {
        if(auto e = u.endpoint())
            co_return co_await connect_endpoint(*e, p...);

        tcp_resolver_t<executor_type> rsv(get_executor());

        JKL_CO_TRY(eps, co_await rsv.resolve(u.hostname(), u.real_port_or_protocol(), p...));

        co_return co_await connect_endpoint(eps, p...);
    }

    template<class... P>
    auto shutdown(P... p)
    {
        if constexpr(requires{ _s.async_shutdown(null_op); })
            return make_ec_awaiter(
                [&](auto&& h){ _s.async_shutdown(std::move(h)); },
                p...);
        else
            return ec_direct_return_awaiter(
                [&](auto& e){ _s.shutdown(asio::basic_socket::shutdown_both, e); });
    }

    aresult<> shutdown_next_layer(asio::basic_socket::shutdown_type t)
    {
        aerror_code e;
        next_layer().shutdown(t, e);
        return e;
    }

    template<class... P>
    auto handshake(asio::ssl::stream_base::handshake_type t, P... p)
    {
        return make_ec_awaiter(
            [&, t](auto&& h){ _s.async_handshake(t, std::move(h)); },
            p...);
    }

    template<class B, class... P>
    auto buffered_handshake(asio::ssl::stream_base::handshake_type t, B& buf, P... p)
    {
        return make_ec_awaiter(
            [&, t, b = asio_buf(b)](auto&& h){ _s.async_handshake(t, b, std::move(h)); },
        p...);
    }

    // not using aresult<>, as this should only use SSL_set_verify which always succeeds
    template<class = void> // just to avoid instantiating this method when instantiates the class
    void set_verify_mode(asio::ssl::verify_mode m)
    {
        _s.set_verify_mode(m);
    }

    template<class = void>
    void set_verify_depth(int d)
    {
        _s.set_verify_depth(d);
    }

    template<class F>
    void set_verify_callback(F&& f)
    {
        _s.set_verify_callback(std::forward<F>(f));
    }

    template<class Str = std::string_view>
    Str sni_hostname() const noexcept
    {
        if(auto* name = SSL_get_servername(stream_native_handle(), TLSEXT_NAMETYPE_host_name))
            return {name};
        return {};

    }

    // for when this is a client;
    // many hosts need this to handshake successfully;
    template<class Str>
    aresult<> set_sni_hostname(Str const& name) noexcept
    {
        // _s should be ssl stream
        if(SSL_set_tlsext_host_name(stream_native_handle(), as_cstr(name).data()))
            return no_err;
        return aerror_code(static_cast<int>(::ERR_get_error()), asio::error::get_ssl_category());
    }

    // Sets the expected server hostname, which will be checked during the verification process.
    // The hostname must not contain \0 characters.
    template<class Str>
    aresult<> set_server_hostname(Str const& name) noexcept
    {
        auto* param = ::SSL_get0_param(handle);

        ::X509_VERIFY_PARAM_set_hostflags(param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);

        if(X509_VERIFY_PARAM_set1_host(param, str_data(name), str_size(name)))
            return no_err;
        return aerror_code(static_cast<int>(::ERR_get_error()), asio::error::get_ssl_category());
    }
};

template<
    class RatePolicy = unlimited_rate_policy,
    class Req        = http::request<http::string_body>,
    class Res        = http::response<http::dynamic_body>,
    class ReadBuf    = flat_buffer,
    class Executor   = asio::executor
>
using http_plain_conn_t = http_conn_t<beast::basic_stream<asio::ip::tcp, Executor, RatePolicy>, Req, Res, ReadBuf>;

template<
    class RatePolicy = unlimited_rate_policy,
    class Req        = http::request<http::string_body>,
    class Res        = http::response<http::dynamic_body>,
    class ReadBuf    = flat_buffer,
    class Executor   = asio::executor
>
using http_ssl_conn_t = http_conn_t<beast::ssl_stream<beast::basic_stream<asio::ip::tcp, Executor, RatePolicy>>, Req, Res, ReadBuf>;

using http_plain_conn = http_plain_conn_t<>;
using http_ssl_conn   = http_ssl_conn_t<>;

template<class Protocol, class Executor, class RatePolicy>
class basic_var_stream
{
public:
    using plain_stream_type = beast::basic_stream<Protocol, Executor, RatePolicy>;
    using ssl_stream_type   = beast::ssl_stream<plain_stream_type>;

    using executor_type = Executor;

    template<class... A>
    explicit basic_var_stream(A&&... args) : _v(std::forward<A>(args)...) {}

    auto& next_layer()
    {
        return std::visit([](auto& s) -> auto& { return get_next_layer(s); }, _v);
    }

    auto const& next_layer() const
    {
        return std::visit([](auto& s) -> auto& { return get_next_layer(s); }, _v);
    }

    template<class... A>
    void async_read_some(A&&... args)
    {
        std::visit([&](auto& s){ s.async_read_some(std::forward<A>(args)...); }, _v);
    }

    template<class... A>
    void async_write_some(A&&... args)
    {
        std::visit([&](auto& s){ s.async_write_some(std::forward<A>(args)...); }, _v);
    }

    // ssl specific

    using native_handle_type = typename ssl_stream_type::native_handle_type;

    native_handle_type native_handle() { return std::get<ssl_stream_type>(_v).native_handle(); }

    template<class... A>
    void async_handshake(A&&... args)
    {
        std::get<ssl_stream_type>(_v).async_handshake(std::forward<A>(args)...);
    }

    template<class... A>
    void set_verify_mode(A&&... args)
    {
        std::get<ssl_stream_type>(_v).set_verify_mode(std::forward<A>(args)...);
    }

    template<class... A>
    void set_verify_depth(A&&... args)
    {
        std::get<ssl_stream_type>(_v).set_verify_depth(std::forward<A>(args)...);
    }

    template<class... A>
    void set_verify_callback(A&&... args)
    {
        std::get<ssl_stream_type>(_v).set_verify_callback(std::forward<A>(args)...);
    }

private:
    std::variant<plain_stream_type, ssl_stream_type> _v;
};

template<
    class RatePolicy = unlimited_rate_policy,
    class Req        = http::request<http::string_body>,
    class Res        = http::response<http::dynamic_body>,
    class ReadBuf    = flat_buffer,
    class Executor   = asio::executor
>
using http_var_conn_t = http_conn_t<basic_var_stream<asio::ip::tcp, Executor, RatePolicy>, Req, Res, ReadBuf>;

// typical usage:
//    http_conn_factory factory;
//    //factory.set_max_read_buf(MiB(6));
//    factory.ssl_ctx().set_verify_mode(asio::ssl::verify_peer);
//    factory.ssl_ctx().use_native_cert_verify();
//    auto conn = co_await factory.connect(url, ...);
//    ... prepare request ...
//    JKL_CO_TRY(co_await conn.write_req(...)); // or handle error manually here.
//    JKL_CO_TRY(co_await conn.read_res(...));
//    ... process response ...
class http_conn_factory
{
    std::optional<ssl_context> _ownSslCtx;

    asio::io_context* _ioc = nullptr;
    ssl_context*      _slc = nullptr;

    _B_<size_t> _maxRdBuf = SIZE_MAX;
    bool        _noDelayWhenHandshake = false;

public:
    explicit http_conn_factory(asio::io_context& ioc = default_ioc())
        : _ioc(&ioc)
    {
        use_own_ssl_ctx();
    }

    explicit http_conn_factory(ssl_context& slc, asio::io_context& ioc = default_ioc())
        : _ioc(&ioc), _slc(&slc)
    {}

    auto& io_ctx() noexcept { return *_ioc; }
    auto& ssl_ctx() noexcept { return *_slc; }

    void set_io_ctx(asio::io_context& c) noexcept { _ioc = &c; }
    void set_ssl_ctx(ssl_context& c) noexcept { _slc = &c; }
    void use_own_ssl_ctx()
    {
        if(! _ownSslCtx)
            _ownSslCtx.emplace(asio::ssl::context::tlsv12_client);
        _slc = & _ownSslCtx.value();
    }

    void set_max_read_buf(_B_<size_t> n) noexcept { _maxRdBuf = n; }

    // https://www.extrahop.com/company/blog/2016/tcp-nodelay-nagle-quickack-best-practices
    void set_no_delay_when_handshake(bool on = true) noexcept { _noDelayWhenHandshake = on; }

    template<
        class RatePolicy = unlimited_rate_policy,
        class Req        = http::request<http::string_body>,
        class Res        = http::response<http::dynamic_body>,
        class ReadBuf    = flat_buffer,
        class Executor   = asio::executor,
        class... P>
    aresult_task<http_var_conn_t<RatePolicy, Req, Res, ReadBuf, Executor>>
    connect_ex(aurl u, Executor const& ex, P... p)
    {
        using conn_t = http_var_conn_t<RatePolicy, Req, Res, ReadBuf, Executor>;
        using plain_stream_t = typename conn_t::stream_type::plain_stream_type;
        using ssl_stream_t = typename conn_t::stream_type::ssl_stream_type;

        if(u.scheme() == "http")
        {
            conn_t conn(std::in_place_type_t<plain_stream_t>, ex, ssl_ctx());

            if(_maxRdBuf != _B_<size_t>(SIZE_MAX))
                conn.set_max_read_buf(_maxRdBuf);

            JKL_CO_TRY(co_await conn.connect(u, p...));
            co_return conn;
        }

        if(u.scheme() == "https")
        {
            conn_t conn(std::in_place_type_t<ssl_stream_t>, ex, ssl_ctx());

            if(_maxRdBuf != _B_<size_t>(SIZE_MAX))
                conn.set_max_read_buf(_maxRdBuf);

            if(u.hostname().size())
                JKL_CO_TRY(conn.set_sni_hostname(u.hostname()));

            if(_verifyMode != -1)
                JKL_CO_TRY(conn.set_verify_mode(_verifyMode));
            if(_verifyDepth != -1)
                JKL_CO_TRY(conn.set_verify_depth(_verifyDepth));
            if(_verifyCallback)
                JKL_CO_TRY(conn.set_verify_callback(_verifyCallback));

            JKL_CO_TRY(co_await conn.connect(u, p...));

            if(_noDelayWhenHandshake)
            {
                JKL_CO_TRY(noDelay, conn.option<asio::ip::tcp::no_delay>());
                if(! noDelay)
                    JKL_CO_TRY(conn.set_option(asio::ip::tcp::no_delay(true)));

                auto r1 = co_await conn.handshake(asio::ssl::stream_base::client, u, p...);

                if(! noDelay)
                {
                    auto r2 = (conn.set_option(asio::ip::tcp::no_delay(false)));
                    JKL_CO_TRY(r1);
                    JKL_CO_TRY(r2);
                }
                else
                {
                    JKL_CO_TRY(r1);
                }
            }
            else
            {
                JKL_CO_TRY(co_await conn.handshake(asio::ssl::stream_base::client, u, p...));
            }

            co_return conn;
        }

        co_return aerrc::protocol_not_supported;
    }

    template<
        class RatePolicy = unlimited_rate_policy,
        class Req        = http::request<http::string_body>,
        class Res        = http::response<http::dynamic_body>,
        class ReadBuf    = flat_buffer,
        class Executor   = asio::executor,
        class... P>
    auto connect(aurl u, P... p)
    {
        return connect_ex(std::move(u), io_ctx().get_executor(), p...);
    }
};

} // namespace jkl

max_stars_repo_name: feverzsj/jkl

max_issues_repo_name: feverzsj/jkl

max_forks_repo_name: feverzsj/jkl


text:
// Distributed under the MIT License.
// See LICENSE.txt for details.

#pragma once

#include <algorithm>
#include <array>
#include <complex>
#include <cstddef>

#include "DataStructures/BoostMultiArray.hpp"
#include "DataStructures/ComplexDataVector.hpp"
#include "DataStructures/ComplexModalVector.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/ModalVector.hpp"
#include "DataStructures/VectorImpl.hpp"

// Boost MultiArray is used internally in odeint, so odeint must be included
// later
#include <boost/numeric/odeint.hpp>

namespace detail {
struct vector_impl_algebra : boost::numeric::odeint::vector_space_algebra {
  template <typename VectorType>
  static double norm_inf(const VectorType& vector) noexcept {
    return max(abs(vector));
  }
};

struct vector_impl_array_algebra : boost::numeric::odeint::array_algebra {
  template <typename VectorType, size_t Size>
  static double norm_inf(
      const std::array<VectorType, Size>& vector_array) noexcept {
    return std::accumulate(
        vector_array.begin(), vector_array.end(), 0.0,
        [](const double maximum_so_far, const VectorType& element) noexcept {
          return std::max(maximum_so_far, max(abs(element)));
        });
  }
};
}  // namespace detail

namespace boost {
namespace numeric {
namespace odeint {

namespace detail {
template <typename V>
struct set_unit_value_impl<ComplexDataVector, V, void> {
  static void set_value(ComplexDataVector& t, const V& v) noexcept {  // NOLINT
    // this ensures that the blaze expression template resolve the result to a
    // complex vector
    t = std::complex<double>(1.0, 0.0) * v;
  }
};
template <typename V>
struct set_unit_value_impl<ComplexModalVector, V, void> {
  static void set_value(ComplexModalVector& t, const V& v) noexcept {  // NOLINT
    // this ensures that the blaze expression template resolve the result to a
    // complex vector
    t = std::complex<double>(1.0, 0.0) * v;
  }
};
}  // namespace detail

// In some integration contexts, boost requires the ability to resize the
// integration arguments in preparation for writing to output buffers passed by
// reference. These specializations make the resize work correctly with spectre
// vector types.
template <class VectorType1, class VectorType2>
struct resize_impl_sfinae<VectorType1, VectorType2,
                          typename boost::enable_if_c<
                              is_derived_of_vector_impl_v<VectorType1> and
                              is_derived_of_vector_impl_v<VectorType2>>::type> {
  static void resize(VectorType1& x1, const VectorType2& x2) noexcept {
    x1.destructive_resize(x2.size());
  }
};

template <class VectorType>
struct is_resizeable_sfinae<
    VectorType,
    typename boost::enable_if_c<is_derived_of_vector_impl_v<VectorType>>::type>
    : boost::true_type {};

template <>
struct algebra_dispatcher<DataVector> {
  using algebra_type = ::detail::vector_impl_algebra;
};

template <>
struct algebra_dispatcher<ComplexDataVector> {
  using algebra_type = ::detail::vector_impl_algebra;
};

template <>
struct algebra_dispatcher<ModalVector> {
  using algebra_type = ::detail::vector_impl_algebra;
};

template <>
struct algebra_dispatcher<ComplexModalVector> {
  using algebra_type = ::detail::vector_impl_algebra;
};

template <size_t Size>
struct algebra_dispatcher<std::array<DataVector, Size>> {
  using algebra_type = ::detail::vector_impl_array_algebra;
};

template <size_t Size>
struct algebra_dispatcher<std::array<ComplexDataVector, Size>> {
  using algebra_type = ::detail::vector_impl_array_algebra;
};

template <size_t Size>
struct algebra_dispatcher<std::array<ModalVector, Size>> {
  using algebra_type = ::detail::vector_impl_array_algebra;
};

template <size_t Size>
struct algebra_dispatcher<std::array<ComplexModalVector, Size>> {
  using algebra_type = ::detail::vector_impl_array_algebra;
};
}  // namespace odeint
}  // namespace numeric
}  // namespace boost

/*!
 * \ingroup NumericalAlgorithmsGroup
 * \brief For ODE integration, we suggest using the boost libraries whenever
 * possible.
 *
 * \details Here we describe briefly the suggested setup to use a boost ODE
 * integrator in SpECTRE. The boost utilities have a number of more elaborate
 * features, including features that may result in simpler function calls than
 * the specific recipes below. For full documentation, see the Boost odeint
 * documentation:
 * https://www.boost.org/doc/libs/1_72_0/libs/numeric/odeint/doc/html/boost_numeric_odeint/
 *
 * The integration methods can be used largely as in the boost documentation. We
 * summarize the salient points necessary to get an example running. The main
 * steps in using a boost integrator are:
 * - define the system
 * - construct the stepper
 * - initialize (might be performed implicitly, depending on the stepper)
 * - perform steps
 * - (compute dense output, for dense-output steppers)
 *
 * For most cases the Dormand-Prince fifth order controlled, dense-output
 * stepper is recommended. That stepper is used in the section "SpECTRE vectors
 * or `std::array` thereof in boost integrators" below.
 *
 * #### Fundamental types or `std::array` thereof in fixed-step integrators
 *
 * Let us consider a simple oscillator system, which we'll declare as a lambda:
 *
 * \snippet Test_OdeIntegration.cpp explicit_fundamental_array_system
 *
 * Note that the first argument is a `const` lvalue reference to the state type,
 * `std::array<double, 2>`, the second argument is an lvalue reference for the
 * time derivatives that is written to by the system function, and the final
 * argument is the current time.
 *
 * The construction and initialization of the stepper is simple:
 *
 * \snippet Test_OdeIntegration.cpp explicit_fundamental_stepper_construction
 *
 * Finally, we can perform the steps and examine the output,
 *
 * \snippet Test_OdeIntegration.cpp explicit_fundamental_stepper_use
 *
 * #### Fundamental types or `std::array` thereof in Dense-output integrators
 *
 * The dense-output and controlled-step-size ODE integrators in boost comply
 * with a somewhat different interface, as significantly more state information
 * must be managed. The result is a somewhat simpler, but more opaque, interface
 * to the user code.
 *
 * Once again, we start by constructing the system we'd like to integrate,
 *
 * \snippet Test_OdeIntegration.cpp dense_output_fundamental_system
 *
 * The constructor for dense steppers takes optional arguments for tolerance,
 * and dense steppers need to be initialized.
 *
 * \snippet Test_OdeIntegration.cpp dense_output_fundamental_construction
 *
 * It is important to take note of the tolerance arguments, as the defaults are
 * `1.0e-6`, which is often looser than we want for calculations in SpECTRE.
 *
 * We then perform the step supplying the system function, and can retrieve the
 * dense output state with `calc_state`, which returns by reference by the
 * second argument.
 *
 * \snippet Test_OdeIntegration.cpp dense_output_fundamental_stepper_use
 *
 * #### SpECTRE vectors or `std::array` thereof in boost integrators
 *
 * The additional template specializations present in the `OdeIntegration.hpp`
 * file ensure that the boost ODE methods work transparently for SpECTRE vectors
 * as well. We'll run through a brief example to emphasize the functionality.
 *
 * \snippet Test_OdeIntegration.cpp dense_output_vector_stepper
 */
namespace OdeIntegration {}


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

Copyright (c) 2015, Carnegie Mellon University
All rights reserved.

Authors: Michael Koval <mkoval@cs.cmu.edu>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

  Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.

  Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.

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

*************************************************************************/
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/make_shared.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/range/adaptor/map.hpp>
#include <ros/ros.h>
#include "markers/LinkMarker.h"
#include "util/ros_conversions.h"

using boost::adaptors::map_keys;
using boost::adaptors::transformed;
using boost::algorithm::join;
using boost::algorithm::iends_with;
using boost::format;
using boost::str;
using geometry_msgs::Vector3;
using OpenRAVE::KinBodyPtr;
using OpenRAVE::RobotBase;
using OpenRAVE::RobotBasePtr;
using OpenRAVE::EnvironmentBasePtr;
using visualization_msgs::Marker;
using visualization_msgs::MarkerPtr;
using visualization_msgs::InteractiveMarker;
using visualization_msgs::InteractiveMarkerPtr;
using visualization_msgs::InteractiveMarkerControl;
using visualization_msgs::InteractiveMarkerFeedbackConstPtr;
using interactive_markers::InteractiveMarkerServer;

using namespace or_rviz::util;

typedef OpenRAVE::KinBody::LinkPtr LinkPtr;
typedef boost::shared_ptr<OpenRAVE::TriMesh> TriMeshPtr;
typedef OpenRAVE::RobotBase::ManipulatorPtr ManipulatorPtr;
typedef OpenRAVE::KinBody::Link::GeometryPtr GeometryPtr;
typedef boost::shared_ptr<InteractiveMarkerServer> InteractiveMarkerServerPtr;

namespace or_rviz {
namespace markers {

OpenRAVE::Vector const LinkMarker::kCollisionColor(0.0, 0.0, 1.0, 0.5);

LinkMarker::LinkMarker(boost::shared_ptr<InteractiveMarkerServer> server,
                       LinkPtr link, bool is_ghost)
    : server_(server)
    , interactive_marker_(boost::make_shared<InteractiveMarker>())
    , view_visual_(true)
    , view_collision_(false)
    , link_(link)
    , is_ghost_(is_ghost)
    , force_update_(true)
{
    BOOST_ASSERT(server);
    BOOST_ASSERT(link);

    // TODO: How should we handle this?
    //manipulator_ = InferManipulator();

    interactive_marker_->header.frame_id = kDefaultWorldFrameId;
    interactive_marker_->name = id();
    interactive_marker_->description = "";
    interactive_marker_->pose = toROSPose(link->GetTransform());
    interactive_marker_->scale = 0.25;

    // Show the visual geometry.
    interactive_marker_->controls.resize(1);
    visual_control_ = &interactive_marker_->controls[0];
    visual_control_->orientation.w = 1;
    visual_control_->name = str(format("%s.Geometry[visual]") % id());
    visual_control_->orientation_mode = InteractiveMarkerControl::INHERIT;
    visual_control_->interaction_mode = InteractiveMarkerControl::BUTTON;
    visual_control_->always_visible = true;
}

LinkMarker::~LinkMarker()
{
    server_->erase(interactive_marker_->name);
}

std::string LinkMarker::id() const
{
    LinkPtr const link = this->link();
    KinBodyPtr const body = link->GetParent();
    EnvironmentBasePtr const env = body->GetEnv();
    int const environment_id = OpenRAVE::RaveGetEnvironmentId(env);

    std::string suffix;
    if (is_ghost_) {
        suffix = ".Ghost";
    }

    return str(format("Environment[%d].KinBody[%s].Link[%s]%s")
               % environment_id % body->GetName() % link->GetName() % suffix);
}

LinkPtr LinkMarker::link() const
{
    return link_.lock();
}

void LinkMarker::set_pose(OpenRAVE::Transform const &pose) const
{
    server_->setPose(interactive_marker_->name, toROSPose(pose),
                     interactive_marker_->header);
}

void LinkMarker::clear_color()
{
    force_update_ = force_update_ || !!override_color_;
    override_color_.reset();
}

void LinkMarker::set_color(OpenRAVE::Vector const &color)
{
    force_update_ = force_update_ || !override_color_
                                  || (color[0] != (*override_color_)[0])
                                  || (color[1] != (*override_color_)[1])
                                  || (color[2] != (*override_color_)[2])
                                  || (color[3] != (*override_color_)[3]);
    override_color_.reset(color);
}

bool LinkMarker::is_view_visual() const
{
    return view_visual_;
}

void LinkMarker::set_view_visual(bool flag)
{
    force_update_ = force_update_ || (flag != view_visual_);
    view_visual_ = flag;
}

bool LinkMarker::is_view_collision() const
{
    return view_collision_;
}

void LinkMarker::set_view_collision(bool flag)
{
    force_update_ = force_update_ || (flag != view_collision_);
    view_collision_ = flag;
}

InteractiveMarkerPtr LinkMarker::interactive_marker()
{
    return interactive_marker_;
}

std::vector<std::string> LinkMarker::group_names() const
{
    OpenRAVE::KinBody::LinkInfo const &link_info = link()->GetInfo();
    auto const range = link_info._mapExtraGeometries | map_keys;
    return std::vector<std::string>(range.begin(), range.end());
}

void LinkMarker::set_parent_frame(std::string const &frame_id)
{
    if (interactive_marker_->header.frame_id != frame_id) {
        interactive_marker_->header.frame_id = frame_id;
        force_update_ = true;
    }
}

void LinkMarker::SwitchGeometryGroup(std::string const &group)
{
    link()->SetGeometriesFromGroup(group);
    force_update_ = true;
}

bool LinkMarker::EnvironmentSync()
{
    LinkPtr const link = this->link();
    bool is_changed = force_update_;

    // Re-create the geometry.
    if (is_changed) {
        CreateGeometry();
        server_->insert(*interactive_marker_);
    }

    force_update_ = false;
    return is_changed;
}

void LinkMarker::Invalidate()
{
    force_update_ = true;
}

void LinkMarker::CreateGeometry()
{
    visual_control_->markers.clear();
    geometry_markers_.clear();

    LinkPtr const link = this->link();

    for (GeometryPtr const geometry : link->GetGeometries()) {
        // Update this geometry's visibility status.
        visibility_map_[geometry.get()] = geometry->IsVisible();

        // Note that this inserts an empty vector if the entry does not already
        // exist. We depend on this for lazy marker creation.
        std::vector<visualization_msgs::Marker *> &markers
                = geometry_markers_[geometry.get()];

        if (view_visual_ && geometry->IsVisible()) {
            // Try loading the visual mesh.
            MarkerPtr visual_marker = CreateVisualGeometry(geometry);

            // Otherwise, fall back on the collision geometry. This mimics the
            // behavior of qtcoin.
            if (!visual_marker) {
                visual_marker = CreateCollisionGeometry(geometry);
            }

            if (visual_marker) {
                visual_control_->markers.push_back(*visual_marker);
                markers.push_back(&visual_control_->markers.back());
            }
        }

        if (view_collision_ && link->IsEnabled()) {
            MarkerPtr const collision_marker = CreateCollisionGeometry(geometry);

            // Make the collision geometry partially transparent if we're also
            // rendering the collision geometry. It's generally true that the
            // collision geometry is larger than the visual geometry.
            if (collision_marker && view_visual_) {
                collision_marker->color = toROSColor(kCollisionColor);
                collision_marker->mesh_use_embedded_materials = false;
            }

            if (collision_marker) {
                visual_control_->markers.push_back(*collision_marker);
                markers.push_back(&visual_control_->markers.back());
            }
        }
    }
}

MarkerPtr LinkMarker::CreateVisualGeometry(GeometryPtr geometry)
{
    MarkerPtr marker = boost::make_shared<Marker>();
    marker->pose = toROSPose(geometry->GetTransform());

    if (override_color_) {
        marker->color = toROSColor(*override_color_);
    } else {
        marker->color = toROSColor(geometry->GetDiffuseColor());
        marker->color.a = 1.0 - geometry->GetTransparency();
    }

    // If a render filename is specified, then we should ignore the rest of the
    // geometry. This is true regardless of the mesh type.
    std::string render_mesh_path = geometry->GetRenderFilename();
    if (boost::algorithm::starts_with(render_mesh_path, "__norenderif__")) {
        render_mesh_path = "";
    }

    // Pass the path to the mesh to RViz and let RViz load it directly. This is
    // only possible if RViz supports the mesh format.
    if (!render_mesh_path.empty() && HasRVizSupport(render_mesh_path)) {
        marker->type = Marker::MESH_RESOURCE;
        marker->scale = toROSVector(geometry->GetRenderScale());
        marker->mesh_resource = "file://" + render_mesh_path;

        bool const has_texture = !override_color_ && HasTexture(render_mesh_path);
        marker->mesh_use_embedded_materials = has_texture;

        // Color must be zero to use the embedded material.
        if (has_texture) {
            marker->color.r = 0;
            marker->color.g = 0;
            marker->color.b = 0;
            marker->color.a = 0;
        }
        return marker;
    }
    // Otherwise, load the mesh with OpenRAVE and serialize the full mesh it
    // into the marker.
    else if (!render_mesh_path.empty()) {
        OpenRAVE::EnvironmentBasePtr const env = link()->GetParent()->GetEnv();
        TriMeshPtr trimesh = boost::make_shared<OpenRAVE::TriMesh>();
        trimesh = env->ReadTrimeshURI(trimesh, render_mesh_path);
        if (trimesh) {
            TriMeshToMarker(*trimesh, marker);
            marker->scale = toROSVector(geometry->GetInfo()._vCollisionScale);

            static bool already_printed = false;
            if (!already_printed) {
                RAVELOG_WARN("Loaded one or more meshes OpenRAVE because this"
                             " format is not" " supported by RViz. This may be"
                             " slow for large files.\n");
                already_printed = true;
            }
            return marker;
        } else {
            RAVELOG_WARN("Loading trimesh '%s' using OpenRAVE failed.",
                render_mesh_path.c_str()
            );
        }
    }
    return MarkerPtr();
}

MarkerPtr LinkMarker::CreateCollisionGeometry(GeometryPtr geometry)
{
    MarkerPtr marker = boost::make_shared<Marker>();
    marker->pose = toROSPose(geometry->GetTransform());

    if (override_color_) {
        marker->color = toROSColor(*override_color_);
    } else {
        marker->color = toROSColor(geometry->GetDiffuseColor());
        marker->color.a = 1.0 - geometry->GetTransparency();
    }

    switch (geometry->GetType()) {
    case OpenRAVE::GeometryType::GT_None:
        return MarkerPtr();

    case OpenRAVE::GeometryType::GT_Box:
        // TODO: This may be off by a factor of two.
        marker->type = Marker::CUBE;
        marker->scale = toROSVector(geometry->GetBoxExtents());
        marker->scale.x *= 2.0;
        marker->scale.y *= 2.0;
        marker->scale.z *= 2.0;
        if (marker->scale.x * marker->scale.y * marker->scale.z == 0.0) {
            return MarkerPtr();
        }
        break;

    case OpenRAVE::GeometryType::GT_Sphere: {
        double const sphere_radius = geometry->GetSphereRadius();
        marker->type = Marker::SPHERE;
        marker->scale.x = 2.0 * sphere_radius;
        marker->scale.y = 2.0 * sphere_radius;
        marker->scale.z = 2.0 * sphere_radius;
        if (sphere_radius == 0.0) {
            return MarkerPtr();
        }
        break;
    }

    case OpenRAVE::GeometryType::GT_Cylinder: {
        // TODO: This may be rotated and/or off by a factor of two.
        double const cylinder_radius = geometry->GetCylinderRadius();
        double const cylinder_height= geometry->GetCylinderHeight();
        marker->type = Marker::CYLINDER;
        marker->scale.x = 2.0 * cylinder_radius;
        marker->scale.y = 2.0 * cylinder_radius;
        marker->scale.z = cylinder_height;
        break;
    }

    case OpenRAVE::GeometryType::GT_TriMesh:
        TriMeshToMarker(geometry->GetCollisionMesh(), marker);
        break;

    default:
        RAVELOG_WARN("Unknown geometry type '%d' for link '%s'.\n",
            geometry->GetType(), link()->GetName().c_str()
        );
        return MarkerPtr();
    }
    return marker;
}

void LinkMarker::TriMeshToMarker(OpenRAVE::TriMesh const &trimesh,
                                 MarkerPtr const &marker)
{
    marker->type = Marker::TRIANGLE_LIST;
    marker->points.clear();

    BOOST_ASSERT(trimesh.indices.size() % 3 == 0);
    for (size_t i = 0; i < trimesh.indices.size() / 3; ++i) {
        int const index1 = trimesh.indices.at(3 * i + 0);
        int const index2 = trimesh.indices.at(3 * i + 1);
        int const index3 = trimesh.indices.at(3 * i + 2);
        OpenRAVE::Vector const &p1 = trimesh.vertices.at(index1);
        OpenRAVE::Vector const &p2 = trimesh.vertices.at(index2);
        OpenRAVE::Vector const &p3 = trimesh.vertices.at(index3);
        marker->points.push_back(toROSPoint(p1));
        marker->points.push_back(toROSPoint(p2));
        marker->points.push_back(toROSPoint(p3));
    }

    if (trimesh.indices.empty())
    {
        geometry_msgs::Point const point = toROSPoint(OpenRAVE::Vector());
        marker->points.resize(3, point);
    }
}

bool LinkMarker::HasTexture(std::string const &uri) const
{
    return iends_with(uri, ".dae");
}

bool LinkMarker::HasRVizSupport(std::string const &uri) const
{
    return iends_with(uri, ".dae")
        || iends_with(uri, ".stl")
        || iends_with(uri, ".mesh");
}

}
}


text:
#ifndef HOPS_CHAINDATA_HPP
#define HOPS_CHAINDATA_HPP

#include <hops/FileWriter/FileWriter.hpp>
#include "Exceptions.hpp"
#include <Eigen/Core>

#include <vector>
#include <memory>

namespace hops {
    class ChainData {
    public:
        ChainData () : acceptanceRates(nullptr),
                       negativeLogLikelihood(nullptr),
                       states(nullptr),
                       timestamps(nullptr) {
            //
        }

        const std::vector<double>& getAcceptanceRates() const {
            if (!acceptanceRates) throw UninitializedDataFieldException("acceptanceRates");
            return *acceptanceRates;
        }

        void setAcceptanceRates(const std::shared_ptr<std::vector<double>>& acceptanceRates) {
            this->acceptanceRates = std::shared_ptr<std::vector<double>>(acceptanceRates);
        }

        const std::vector<double>& getNegativeLogLikelihood() const {
            if (!negativeLogLikelihood) throw UninitializedDataFieldException("negativeLogLikelihood");
            return *negativeLogLikelihood;
        }

        void setNegativeLogLikelihood(const std::shared_ptr<std::vector<double>>& negativeLogLikelihood) {
            this->negativeLogLikelihood = std::shared_ptr<std::vector<double>>(negativeLogLikelihood);
        }

        const std::vector<Eigen::VectorXd>& getStates() const {
            if (!states) throw UninitializedDataFieldException("states");
            return *states;
        }

        void setStates(const std::shared_ptr<std::vector<Eigen::VectorXd>>& states) {
            this->states = std::shared_ptr<std::vector<Eigen::VectorXd>>(states);
        }

        const std::vector<long>& getTimestamps() const {
            if (!timestamps) throw UninitializedDataFieldException("timestamps");
            return *timestamps;
        }

        void setTimestamps(const std::shared_ptr<std::vector<long>> timestamps) {
            this->timestamps = std::shared_ptr<std::vector<long>>(timestamps);
        }

        void write(FileWriter *const fileWriter) const {
            if (acceptanceRates) {
                fileWriter->write("acceptanceRates", *acceptanceRates);
            }

            if (negativeLogLikelihood) {
                fileWriter->write("negativeLogLikelihood", *negativeLogLikelihood);
            }

            if (states) {
                fileWriter->write("states", *states);
            }

            if (timestamps) {
                fileWriter->write("timestamps", *timestamps);
            }
        }

        void reset() {
			if (acceptanceRates) {
                (*acceptanceRates.get()).clear();
            }

            if (negativeLogLikelihood) {
                negativeLogLikelihood->clear();
            }

            if (states) {
                states->clear();
            }

            if (timestamps) {
                timestamps->clear();
            }
		}

    private:
        std::shared_ptr<std::vector<double>> acceptanceRates;
        std::shared_ptr<std::vector<double>> negativeLogLikelihood;
        std::shared_ptr<std::vector<Eigen::VectorXd>> states;
        std::shared_ptr<std::vector<long>> timestamps;

        friend class Data;
    };
}

#endif // HOPS_CHAINDATA_HPP

max_stars_repo_name: modsim/hops

max_issues_repo_name: modsim/hops

max_forks_repo_name: modsim/hops


text:
#ifndef BOOST_DETAIL_ATOMIC_COUNT_HPP_INCLUDED
#define BOOST_DETAIL_ATOMIC_COUNT_HPP_INCLUDED

// MS compatible compilers support #pragma once

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

//
//  boost/detail/atomic_count.hpp - thread/SMP safe reference counter
//
//  Copyright (c) 2001, 2002 Peter Dimov and Multi Media Ltd.
//
// 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)
//
//  typedef <implementation-defined> boost::detail::atomic_count;
//
//  atomic_count a(n);
//
//    (n is convertible to long)
//
//    Effects: Constructs an atomic_count with an initial value of n
//
//  a;
//
//    Returns: (long) the current value of a
//
//  ++a;
//
//    Effects: Atomically increments the value of a
//    Returns: nothing
//
//  --a;
//
//    Effects: Atomically decrements the value of a
//    Returns: (long) zero if the new value of a is zero,
//      unspecified non-zero value otherwise (usually the new value)
//
//    Important note: when --a returns zero, it must act as a
//      read memory barrier (RMB); i.e. the calling thread must
//      have a synchronized view of the memory
//
//    On Intel IA-32 (x86) memory is always synchronized, so this
//      is not a problem.
//
//    On many architectures the atomic instructions already act as
//      a memory barrier.
//
//    This property is necessary for proper reference counting, since
//      a thread can update the contents of a shared object, then
//      release its reference, and another thread may immediately
//      release the last reference causing object destruction.
//
//    The destructor needs to have a synchronized view of the
//      object to perform proper cleanup.
//
//    Original example by Alexander Terekhov:
//
//    Given:
//
//    - a mutable shared object OBJ;
//    - two threads THREAD1 and THREAD2 each holding
//      a private smart_ptr object pointing to that OBJ.
//
//    t1: THREAD1 updates OBJ (thread-safe via some synchronization)
//      and a few cycles later (after "unlock") destroys smart_ptr;
//
//    t2: THREAD2 destroys smart_ptr WITHOUT doing any synchronization
//      with respect to shared mutable object OBJ; OBJ destructors
//      are called driven by smart_ptr interface...
//

//  Note: atomic_count_linux.hpp has been disabled by default; see the
//        comments inside for more info.

#include <boost/config.hpp>

#ifndef BOOST_HAS_THREADS

namespace boost
{

namespace detail
{

typedef long atomic_count;

}

}

#elif defined(BOOST_USE_ASM_ATOMIC_H)
#  include <boost/detail/atomic_count_linux.hpp>
#elif defined(BOOST_AC_USE_PTHREADS)
#  include <boost/detail/atomic_count_pthreads.hpp>
#elif defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#  include <boost/detail/atomic_count_win32.hpp>
#elif defined(__GLIBCPP__)
#  include <boost/detail/atomic_count_gcc.hpp>
#elif defined(BOOST_HAS_PTHREADS)
#  define BOOST_AC_USE_PTHREADS
#  include <boost/detail/atomic_count_pthreads.hpp>
#else

// Use #define BOOST_DISABLE_THREADS to avoid the error
#error Unrecognized threading platform

#endif

#endif // #ifndef BOOST_DETAIL_ATOMIC_COUNT_HPP_INCLUDED

max_stars_repo_name: Imperator-Knoedel/Sunset

max_issues_repo_name: Imperator-Knoedel/Sunset

max_forks_repo_name: Imperator-Knoedel/Sunset


text:
#ifndef BOOST_CONFIG_HPP
#  include <boost/config.hpp>
#endif
#include <boost/intrusive/detail/workaround.hpp>
#include <boost/intrusive/pointer_rebind.hpp>

namespace boost {
    namespace intrusive {

template<class VoidPointer>
class suffix_automata_node
{
    public:
        typedef typename boost::intrusive::pointer_rebind<VoidPointer, suffix_automata_node>::type  node_ptr;
    public:
        node_ptr children[26];
        node_ptr suffix_link;
        int length;
};
template<class VoidPointer>
class suffix_automata_node_traits
{
    public:
    typedef suffix_automata_node<VoidPointer>      node;
    typedef typename node::node_ptr     node_ptr;
    typedef typename pointer_rebind<VoidPointer, const node>::type   const_node_ptr;
    BOOST_INTRUSIVE_FORCEINLINE static void set_children(node_ptr &target,int child_index,node_ptr &child)
    {
        target->children[child_index]=child;
    }
    BOOST_INTRUSIVE_FORCEINLINE static node_ptr get_children(node_ptr &target,int child_index)
    {
        return target->children[child_index];
    }
    BOOST_INTRUSIVE_FORCEINLINE static void set_suffix_link(node_ptr &target,node_ptr &link)
    {
        target->suffix_link=link;
    }
    BOOST_INTRUSIVE_FORCEINLINE static int get_suffix_link(node_ptr &target)
    {
        return target->suffix_link;
    }
    BOOST_INTRUSIVE_FORCEINLINE static void set_length(node_ptr &target,int length)
    {
        target->length=length;
    }
    BOOST_INTRUSIVE_FORCEINLINE static int get_length(node_ptr &target)
    {
        return target->length;
    }

};
    }
}


text:
#include "stdafx.h"
#include "TypeInfo.h"

#include <regex>
#include <vector>
#include <boost/algorithm/string.hpp>

#if defined(__GNUC__)
# include <cxxabi.h>
#endif /* __GNUC__ */

namespace Disruptor
{

    TypeInfo::TypeInfo(const std::type_info& typeInfo)
        : m_typeInfo(&typeInfo)
        , m_fullyQualifiedName(dotNetify(demangleTypeName(m_typeInfo->name())))
        , m_name(unqualifyName(m_fullyQualifiedName))
    {
    }

    const std::type_info& TypeInfo::intrinsicTypeInfo() const
    {
        return *m_typeInfo;
    }

    const std::string& TypeInfo::fullyQualifiedName() const
    {
        return m_fullyQualifiedName;
    }

    const std::string& TypeInfo::name() const
    {
        return m_name;
    }

    bool TypeInfo::operator==(const TypeInfo& rhs) const
    {
        return intrinsicTypeInfo() == rhs.intrinsicTypeInfo();
    }

    std::string TypeInfo::dotNetify(const std::string& typeName)
    {
        return boost::algorithm::replace_all_copy(typeName, "::", ".");
    }

    std::string TypeInfo::unqualifyName(const std::string& fullyQualifiedName)
    {
        if (fullyQualifiedName.empty())
            return std::string();

        std::vector< std::string > nameParts;
        boost::split(nameParts, fullyQualifiedName, boost::is_any_of("."));

        if (nameParts.empty())
            return std::string();

        return nameParts[nameParts.size() - 1];
    }

    std::string TypeInfo::demangleTypeName(const std::string& typeName)
    {
#if defined(__GNUC__)
            int status;

            auto demangledName = abi::__cxa_demangle(typeName.c_str(), 0, 0, &status);
            if (demangledName == nullptr)
                return typeName;

            std::string result = demangledName;
            free(demangledName);
            return result;
#else
        std::string demangled = typeName;
        demangled = std::regex_replace(demangled, std::regex("(const\\s+|\\s+const)"), std::string());
        demangled = std::regex_replace(demangled, std::regex("(volatile\\s+|\\s+volatile)"), std::string());
        demangled = std::regex_replace(demangled, std::regex("(static\\s+|\\s+static)"), std::string());
        demangled = std::regex_replace(demangled, std::regex("(class\\s+|\\s+class)"), std::string());
        demangled = std::regex_replace(demangled, std::regex("(struct\\s+|\\s+struct)"), std::string());
        return demangled;
#endif /* defined(__GNUC__) */
    }

} // namespace Disruptor

max_stars_repo_name: ulricheck/Disruptor-cpp

max_issues_repo_name: ulricheck/Disruptor-cpp

max_forks_repo_name: ulricheck/Disruptor-cpp


text:
/*
Copyright (c) Members of the EGEE Collaboration. 2004.
See http://www.eu-egee.org/partners for details on the
copyright holders.

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.
*/

// File: RequestStateMachine.cpp
// Author: Francesco Giacomini <Francesco.Giacomini@cnaf.infn.it>
// Copyright (c) 2002 EU DataGrid.

// $Id: RequestStateMachine.cpp,v 1.4.2.2.8.2.4.2 2010/04/08 13:52:15 mcecchi Exp $

#include <dlfcn.h>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <classad_distribution.h>

#include "glite/wms/helper/RequestStateMachine.h"
#include "glite/wms/helper/Helper.h"
#include "common/interface/glite/wms/common/logger/logger_utils.h"
#include "glite/wmsutils/classads/classad_utils.h"

namespace utils = glite::wmsutils::classads;

namespace glite {
namespace wms {
namespace helper {

typedef RequestStateMachine::state_type state_type;
typedef RequestStateMachine::expression_type expression_type;
typedef RequestStateMachine::initial_states_type initial_states_type;
typedef RequestStateMachine::transition_table_type transition_table_type;
typedef RequestStateMachine::final_states_type final_states_type;

namespace {

const std::string state_machine_reqs("[requirements="
                                     "islist(other.initial_states)"
                                     "&& islist(other.transition_table)"
                                     "&& islist(other.final_states)]");

void init_initial_states(initial_states_type& states,
                         classad::ExprList const* l)
{
  states.insert(std::make_pair(state_type("SimpleLogicalJob"),
                               expression_type("other.type==\"job\"")));
  states.insert(std::make_pair(state_type("DAGJob"),
                               expression_type("other.type==\"dag\"")));
}

class CannotLoadDynamicLibrary {};

class DynamicLibrary
{
  void* m_handle;

public:
  DynamicLibrary(std::string& name)
    : m_handle(dlopen(name.c_str(), RTLD_GLOBAL))
  {
    if (!m_handle) {
      throw CannotLoadDynamicLibrary();
    }
  }
  ~DynamicLibrary()
  {
    dlclose(m_handle);
  }
};

std::vector<boost::shared_ptr<DynamicLibrary> > f_shared_libs;

void load_helpers()
{
  // the following map will be created out of the configuration file
  typedef std::map<std::string, std::string> Helper2LibMap;
  Helper2LibMap helper2lib;
  helper2lib.insert(std::make_pair("BrokerHelper", "libbroker_helper.so"));
  helper2lib.insert(std::make_pair("JobAdapterHelper", "libjobadapter_helper.so"));
  helper2lib.insert(std::make_pair("DAGManHelper", "libdagman_helper.so"));

  for (Helper2LibMap::iterator h = helper2lib.begin();
       h != helper2lib.end();
       ++h)
    try {
      boost::shared_ptr<DynamicLibrary> l(new DynamicLibrary(h->second));
      f_shared_libs.push_back(l);
    } catch (CannotLoadDynamicLibrary&) {
      Error("Cannot load helper library " << h->first);
    }
}

void unload_helpers()
{
  f_shared_libs.clear();
}

void init_transition_table(transition_table_type& table,
                           classad::ExprList const* l)
{
  table.insert(
    std::make_pair(
      state_type("SimpleLogicalJob"),
      boost::make_tuple(
        std::string("BrokerHelper"),
        state_type("SimplePhysicalJob")
      )
    )
  );
  table.insert(
    std::make_pair(
      state_type("SimplePhysicalJob"),
      boost::make_tuple(
        std::string("JobAdapterHelper"),
        state_type("AdaptedJob")
      )
    )
  );
  table.insert(
    std::make_pair(
      state_type("DAGJob"),
      boost::make_tuple(
        std::string("DAGManHelper"),
        state_type("AdaptedJob")
      )
    )
  );
}

void init_final_states(final_states_type& states,
                       classad::ExprList const* l)
{
  states.insert(state_type("AdaptedJob"));
}

bool state_is_final(state_type const& state,
                    final_states_type const& final_states)
{
  return final_states.find(state) != final_states.end();
}

}

RequestStateMachine::RequestStateMachine(classad::ClassAd const* config)
{
  init_initial_states(m_initial_states, 0);
  init_transition_table(m_transition_table, 0);
  //  load_helpers();
  init_final_states(m_final_states, 0);
}

RequestStateMachine::~RequestStateMachine()
{
  //  unload_helpers();
}

class MatchAd: public std::unary_function<initial_states_type::value_type, bool>
{
  classad::ClassAd const* m_ad;
public:
  MatchAd(classad::ClassAd const* ad): m_ad(ad) {}
  result_type operator()(argument_type const& v) const
  {
    expression_type expr = "[requirements=" + v.second + "]";
    boost::scoped_ptr<classad::ClassAd> rhs(utils::parse_classad(expr));

    return utils::left_matches_right(*m_ad, *rhs);
  }
};

void
RequestStateMachine::start(classad::ClassAd const* ad)
{
  initial_states_type::const_iterator it = find_if(m_initial_states.begin(),
                                                   m_initial_states.end(),
                                                   MatchAd(ad));
  if (it == m_initial_states.end()) {
    throw NoValidState();
  }
  m_current_state = it->first;
}

classad::ClassAd*
RequestStateMachine::next_step(
  classad::ClassAd const* ad,
  boost::shared_ptr<std::string> jw_template
)
{
  assert(ad != 0);

  classad::ClassAd* result = 0;

  transition_table_type::const_iterator it = m_transition_table.find(m_current_state);
  if (it == m_transition_table.end()) {
    throw NoValidState();
  }

  std::string helper;
  state_type next_state;
  boost::tie(helper, next_state) = it->second;

  result = Helper(helper).resolve(ad, jw_template);
  m_current_state = next_state;

  assert(result != 0);

  return result;
}

RequestStateMachine::operator void*() const
{
  return state_is_final(m_current_state, m_final_states) ? (void*)0 : (void*)(-1);
}

int
RequestStateMachine::operator!() const
{
  return state_is_final(m_current_state, m_final_states);
}

}}} // glite::wms::helper

max_stars_repo_name: italiangrid/wms

max_issues_repo_name: italiangrid/wms

max_forks_repo_name: italiangrid/wms


text:
/**TODO:  Add copyright*/

#define BOOST_TEST_MODULE ModelResources test suite
#include <boost/test/included/unit_test.hpp>
#include <EvoNet/ml/ModelResources.h>

using namespace EvoNet;
using namespace std;

BOOST_AUTO_TEST_SUITE(ModelResources1)

BOOST_AUTO_TEST_CASE(ModelResourcesConstructor)
{
	ModelResources* ptr = nullptr;
	ModelResources* nullPointer = nullptr;
  ptr = new ModelResources();
  BOOST_CHECK_NE(ptr, nullPointer);
}

BOOST_AUTO_TEST_CASE(ModelResourcesDestructor)
{
	ModelResources* ptr = nullptr;
	ptr = new ModelResources();
  delete ptr;
}

BOOST_AUTO_TEST_SUITE_END()


text:
/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "io/tcp_server.h"

#include <errno.h>

#include <boost/asio/connect.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/bind.hpp>

#include "base/logging.h"
#include "io/event_manager.h"
#include "io/tcp_session.h"
#include "io/io_log.h"
#include "io/io_utils.h"

using boost::asio::placeholders::error;
using boost::asio::socket_base;
using boost::bind;
using boost::system::error_code;

using boost::asio::ip::tcp;
using boost::asio::socket_base;
using std::ostringstream;
using std::string;

TcpServer::TcpServer(EventManager *evm)
    : evm_(evm), socket_open_failure_(false) {
    refcount_ = 0;
    TcpServerManager::AddServer(this);
}

// TcpServer delete procedure:
// 1. Shutdown() to stop accepting incoming sessions.
// 2. Close and terminate current sessions. ASIO callbacks maybe in-flight.
// 3. Optionally: WaitForEmpty().
// 4. Destroy TcpServer.
TcpServer::~TcpServer() {
    assert(acceptor_ == NULL);
    assert(session_ref_.empty());
    assert(session_map_.empty());
}

void TcpServer::SetName(Endpoint local_endpoint) {
    ostringstream out;
    out << local_endpoint;
    name_ = out.str();
}

void TcpServer::ResetAcceptor() {
    acceptor_.reset();
    name_ = "";
}

bool TcpServer::Initialize(unsigned short port) {
    acceptor_.reset(new tcp::acceptor(*evm_->io_service()));
    if (!acceptor_) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA, "Cannot create acceptor");
        return false;
    }

    tcp::endpoint localaddr(tcp::v4(), port);
    error_code ec;
    acceptor_->open(localaddr.protocol(), ec);
    if (ec) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA, "TCP open: " << ec.message());
        ResetAcceptor();
        return false;
    }

    acceptor_->set_option(socket_base::reuse_address(true), ec);
    if (ec) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA, "TCP reuse_address: "
                                                   << ec.message());
        ResetAcceptor();
        return false;
    }

    acceptor_->bind(localaddr, ec);
    if (ec) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA, "TCP bind(" << port << "): "
                                               << ec.message());
        ResetAcceptor();
        return false;
    }

    tcp::endpoint local_endpoint = acceptor_->local_endpoint(ec);
    if (ec) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA,
                             "Cannot retrieve acceptor local-endpont");
        ResetAcceptor();
        return false;
    }

    //
    // Server name can be set after local-endpoint information is available.
    //
    SetName(local_endpoint);

    acceptor_->listen(socket_base::max_connections, ec);
    if (ec) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA, "TCP listen(" << port << "): "
                                                   << ec.message());
        ResetAcceptor();
        return false;
    }

    TCP_SERVER_LOG_DEBUG(this, TCP_DIR_NA, "Initialization complete");
    AsyncAccept();

    return true;
}

void TcpServer::Shutdown() {
    tbb::mutex::scoped_lock lock(mutex_);
    error_code ec;

    if (acceptor_) {
        acceptor_->close(ec);
        if (ec) {
            TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA, "Error during shutdown: "
                                                       << ec.message());
        }
        ResetAcceptor();
    }
}

// Close and remove references from all sessions. The application code must
// make sure it no longer holds any references to these sessions.
void TcpServer::ClearSessions() {
    tbb::mutex::scoped_lock lock(mutex_);
    SessionSet refs;
    session_map_.clear();
    refs.swap(session_ref_);
    lock.release();

    for (SessionSet::iterator iter = refs.begin(), next = iter;
         iter != refs.end(); iter = next) {
        ++next;
        TcpSession *session = iter->get();
        session->Close();
    }
    refs.clear();
    cond_var_.notify_all();
}

TcpSession *TcpServer::CreateSession() {
    TcpSession *session = AllocSession(false);
    {
        tbb::mutex::scoped_lock lock(mutex_);
        session_ref_.insert(TcpSessionPtr(session));
    }
    return session;
}

void TcpServer::DeleteSession(TcpSession *session) {
    // The caller will typically close the socket before deleting the
    // session.
    session->Close();
    {
        tbb::mutex::scoped_lock lock(mutex_);
        assert(session->refcount_);
        session_ref_.erase(TcpSessionPtr(session));
        if (session_ref_.empty()) {
            cond_var_.notify_all();
        }
    }
}

//
// Insert into SessionMap.
// Assumes that caller has the mutex.
//
void TcpServer::InsertSessionToMap(Endpoint remote, TcpSession *session) {
    session_map_.insert(make_pair(remote, session));
}

//
// Remove from SessionMap.
// Assumes that caller has the mutex.
// Return true if the session is found.
//
bool TcpServer::RemoveSessionFromMap(Endpoint remote, TcpSession *session) {
    for (SessionMap::iterator iter = session_map_.find(remote);
         iter != session_map_.end() && iter->first == remote; ++iter) {
        if (iter->second == session) {
            session_map_.erase(iter);
            return true;
        }
    }
    return false;
}

void TcpServer::OnSessionClose(TcpSession *session) {
    tbb::mutex::scoped_lock lock(mutex_);

    // CloseSessions closes and removes all the sessions from the map.
    if (session_map_.empty()) {
        return;
    }

    bool found = RemoveSessionFromMap(session->remote_endpoint(), session);
    assert(found);
}

// This method ensures that the application code requested the session to be
// deleted (which may be a delayed action). It does not guarantee that the
// session object has actually been freed yet as ASIO callbacks can be in
// progress.
void TcpServer::WaitForEmpty() {
    tbb::interface5::unique_lock<tbb::mutex> lock(mutex_);
    while (!session_ref_.empty()) {
        cond_var_.wait(lock);
    }
}

void TcpServer::AsyncAccept() {
    tbb::mutex::scoped_lock lock(mutex_);
    if (acceptor_ == NULL) {
        return;
    }
    set_accept_socket();
    acceptor_->async_accept(*accept_socket(),
        bind(&TcpServer::AcceptHandlerInternal, this,
            TcpServerPtr(this), error));
}

int TcpServer::GetPort() const {
    tbb::mutex::scoped_lock lock(mutex_);
    if (acceptor_.get() == NULL) {
        return -1;
    }
    error_code ec;
    tcp::endpoint ep = acceptor_->local_endpoint(ec);
    if (ec) {
        return -1;
    }
    return ep.port();
}

bool TcpServer::HasSessions() const {
    tbb::mutex::scoped_lock lock(mutex_);
    return !session_map_.empty();
}

bool TcpServer::HasSessionReadAvailable() const {
    tbb::mutex::scoped_lock lock(mutex_);
    error_code error;
    if (accept_socket()->available(error) > 0) {
        return  true;
    }
    for (SessionMap::const_iterator iter = session_map_.begin();
         iter != session_map_.end();
         ++iter) {
        if (iter->second->socket()->available(error) > 0) {
            return true;
        }
    }
    return false;
}

TcpServer::Endpoint TcpServer::LocalEndpoint() const {
    tbb::mutex::scoped_lock lock(mutex_);
    if (acceptor_.get() == NULL) {
        return Endpoint();
    }
    error_code ec;
    Endpoint local = acceptor_->local_endpoint(ec);
    if (ec) {
        return Endpoint();
    }
    return local;
}

TcpSession *TcpServer::AllocSession(bool server_session) {
    TcpSession *session;
    if (server_session) {
        session = AllocSession(so_accept_.get());

        // if session allocate succeeds release ownership to so_accept.
        if (session != NULL) {
            so_accept_.release();
        }
    } else {
        Socket *socket = new Socket(*evm_->io_service());
        session = AllocSession(socket);
    }

    return session;
}

TcpServer::Socket *TcpServer::accept_socket() const {
    return so_accept_.get();
}

void TcpServer::set_accept_socket() {
    so_accept_.reset(new Socket(*evm_->io_service()));
}

bool TcpServer::AcceptSession(TcpSession *session) {
    return true;
}

//
// concurrency: called from the event_manager thread.
//
// accept() tcp connections. Once done, must register with boost again
// via AsyncAccept() in order to process future accept calls
//
void TcpServer::AcceptHandlerInternal(TcpServerPtr server,
        const error_code& error) {
    tcp::endpoint remote;
    error_code ec;
    TcpSessionPtr session;
    bool need_close = false;

    if (error) {
        goto done;
    }

    remote = accept_socket()->remote_endpoint(ec);
    if (ec) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_IN,
                             "Accept: No remote endpoint: " << ec.message());
        goto done;
    }

    if (acceptor_ == NULL) {
        TCP_SESSION_LOG_DEBUG(session, TCP_DIR_IN,
                              "Session accepted after server shutdown: "
                                  << remote.address().to_string()
                                  << ":" << remote.port());
        accept_socket()->close(ec);
        goto done;
    }

    session.reset(AllocSession(true));
    if (session == NULL) {
        TCP_SERVER_LOG_DEBUG(this, TCP_DIR_IN, "Session not created");
        goto done;
    }

    ec = session->SetSocketOptions();
    if (ec) {
        TCP_SESSION_LOG_ERROR(session, TCP_DIR_IN,
                              "Accept: Non-blocking error: " << ec.message());
        need_close = true;
        goto done;
    }

    session->SessionEstablished(remote, TcpSession::PASSIVE);
    AcceptHandlerComplete(session);

done:
    if (need_close) {
        session->CloseInternal(ec, false, false);
    }
    AsyncAccept();
}

void TcpServer::AcceptHandlerComplete(TcpSessionPtr session) {
    tcp::endpoint remote = session->remote_endpoint();
    {
        tbb::mutex::scoped_lock lock(mutex_);
        if (AcceptSession(session.get())) {
            TCP_SESSION_LOG_UT_DEBUG(session, TCP_DIR_IN,
                                     "Accepted session from "
                                         << remote.address().to_string()
                                         << ":" << remote.port());
            session_ref_.insert(session);
            InsertSessionToMap(remote, session.get());
        } else {
            TCP_SESSION_LOG_UT_DEBUG(session, TCP_DIR_IN,
                                     "Rejected session from "
                                         << remote.address().to_string()
                                         << ":" << remote.port());
            error_code ec;
            session->CloseInternal(ec, false, false);
            return;
        }
    }

    session->Accepted();
}

TcpSession *TcpServer::GetSession(Endpoint remote) {
    tbb::mutex::scoped_lock lock(mutex_);
    SessionMap::const_iterator iter = session_map_.find(remote);
    if (iter != session_map_.end()) {
        return iter->second;
    }
    return NULL;
}

void TcpServer::ConnectHandler(TcpServerPtr server, TcpSessionPtr session,
                               const error_code &error) {
    if (error) {
        TCP_SERVER_LOG_UT_DEBUG(server, TCP_DIR_OUT,
                                "Connect failure: " << error.message());
        session->ConnectFailed();
        return;
    }

    ConnectHandlerComplete(session);
}

void TcpServer::ConnectHandlerComplete(TcpSessionPtr session) {
    error_code ec;
    Endpoint remote = session->socket()->remote_endpoint(ec);
    if (ec) {
        TCP_SERVER_LOG_INFO(this, TCP_DIR_OUT,
                            "Connect getsockaddr: " << ec.message());
        session->ConnectFailed();
        return;
    }

    {
        tbb::mutex::scoped_lock lock(mutex_);
        InsertSessionToMap(remote, session.get());
    }

    // Connected verifies whether the session has been closed or is still
    // active.
    if (!session->Connected(remote)) {
        tbb::mutex::scoped_lock lock(mutex_);
        RemoveSessionFromMap(remote, session.get());
    }
}

void TcpServer::Connect(TcpSession *session, Endpoint remote) {
    assert(session->refcount_);
    Socket *socket = session->socket();
    socket->async_connect(remote,
        bind(&TcpServer::ConnectHandler, this, TcpServerPtr(this),
                    TcpSessionPtr(session), error));
}

int TcpServer::SetMd5SocketOption(int fd, uint32_t peer_ip,
                                  const string &md5_password) {
    assert(md5_password.size() <= TCP_MD5SIG_MAXKEYLEN);
    if (!peer_ip) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA, "Invalid peer IP");
        return 0;
    }

    struct sockaddr_in local_addr;
    memset(&local_addr, 0, sizeof(local_addr));

    local_addr.sin_family = AF_INET;
    local_addr.sin_addr.s_addr = htonl(peer_ip);

    struct tcp_md5sig md5sig;
    memset(&md5sig, 0, sizeof (md5sig));

    memcpy(md5sig.tcpm_key, md5_password.c_str(), md5_password.size());
    md5sig.tcpm_keylen = md5_password.size();
    memcpy(&md5sig.tcpm_addr, &local_addr, sizeof(local_addr));
    int retval = setsockopt(fd, IPPROTO_TCP, TCP_MD5SIG, &md5sig,
                            sizeof(md5sig));
    if (retval < 0) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA,
            "Failure in setting md5 key on the socket " +
            integerToString(fd) + " for peer " + integerToString(peer_ip) +
            " with errno " + strerror(errno));
    } else {
        TCP_SERVER_LOG_DEBUG(this, TCP_DIR_NA,
            "Success in setting md5 key on the socket " +
            integerToString(fd) + " for peer " + integerToString(peer_ip));
    }
    return retval;
}

int TcpServer::SetListenSocketMd5Option(uint32_t peer_ip,
                                        const string &md5_password) {
    int retval = 0;
    if (acceptor_) {
        retval = SetMd5SocketOption(acceptor_->native_handle(), peer_ip,
                                    md5_password);
    }
    return retval;
}

int TcpServer::SetDscpSocketOption(int fd, uint8_t value) {
    int retval = setsockopt(fd, IPPROTO_IP, IP_TOS, &value, sizeof(value));
    if (retval < 0) {
        TCP_SERVER_LOG_ERROR(this, TCP_DIR_NA,
            "Failure in setting DSCP value on the socket " +
            integerToString(fd) + " for value " + integerToString(value) +
            " with errno " + strerror(errno));
    }
    return retval;
}

void TcpServer::GetRxSocketStats(SocketIOStats *socket_stats) const {
    stats_.GetRxStats(socket_stats);
}

void TcpServer::GetTxSocketStats(SocketIOStats *socket_stats) const {
    stats_.GetTxStats(socket_stats);
}

//
// TcpServerManager class routines
//
ServerManager<TcpServer, TcpServerPtr> TcpServerManager::impl_;

void TcpServerManager::AddServer(TcpServer *server) {
    impl_.AddServer(server);
}

void TcpServerManager::DeleteServer(TcpServer *server) {
    impl_.DeleteServer(server);
}

size_t TcpServerManager::GetServerCount() {
    return impl_.GetServerCount();
}

max_stars_repo_name: sagarc-contrail/contrail-controller

max_issues_repo_name: sagarc-contrail/contrail-controller

max_forks_repo_name: sagarc-contrail/contrail-controller


text:
/* Last Revised Date: 22_MAY_2015 */
/* Lastest status: not checked   */

// Package include header files

#include "insilico-0.25/include/insilico/core.hpp"
#include <boost/numeric/odeint.hpp>

// Global custom header files

#include "insilico-test/Global_variable_declarations.hpp"

// Main header files for Neurons & Astrocyte

#include "insilico-test/ip3_receptor_test/ip3_receptor_test_neuron.hpp"

// C++ Header files

#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

namespace gvars=astron::globals;

int main(int argc, char **argv) {

  newinsilico::initialize(argc, argv);

  newinsilico::observe("ca_cyt");
  newinsilico::observe("ca_er");
  newinsilico::observe("ip3_cyt");
  //newinsilico::observe("ip3r_yk_s110");
  //newinsilico::observe("ip3r_yk_flux");
  newinsilico::generate_neuron<ip3_receptor_test_neuron>(1);

  state_type variables = newinsilico::get_variables();
  integrate_const(boost::numeric::odeint::runge_kutta4<state_type>(),
                  newinsilico::driver(), variables,
                  0.0, 100.0, gvars::DELTA_T, newinsilico::observer());

  newinsilico::finalize();
}

max_stars_repo_name: anupgp/astron

max_issues_repo_name: anupgp/astron

max_forks_repo_name: anupgp/astron