text:
// graph-tool -- a general graph modification and manipulation thingy
//
// Copyright (C) 2006-2015 Tiago de Paula Peixoto <tiago@skewed.de>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include "graph_filtering.hh"
#include "graph_selectors.hh"
#include "graph_properties.hh"
#include "graph.hh"

#include "graph_augment.hh"

#include <boost/graph/max_cardinality_matching.hpp>

#include <boost/bind.hpp>

using namespace graph_tool;
using namespace boost;

struct get_max_cardinality_matching
{
    template <class Graph, class VertexIndex, class MatchMap>
    void operator()(Graph& g, VertexIndex vertex_index, MatchMap match,
                    bool &check) const
    {
        typedef typename graph_traits<Graph>::vertex_descriptor vertex_t;
        unchecked_vector_property_map<vertex_t,VertexIndex>
            mate(vertex_index, num_vertices(g));

        typename graph_traits<Graph>::edge_iterator e, e_end;
        for (tie(e, e_end) = edges(g); e != e_end; ++e)
            match[*e] = false;

        check =
            checked_edmonds_maximum_cardinality_matching(g, mate, vertex_index);

        for (tie(e, e_end) = edges(g); e != e_end; ++e)
        {
            if (mate[source(*e,g)] != graph_traits<Graph>::null_vertex() &&
                mate[source(*e,g)] == target(*e,g))
            {
                // search for an already matched parallel edge
                bool matched = false;
                typename graph_traits<Graph>::out_edge_iterator oe, oe_end;
                for (tie(oe, oe_end) = out_edges(source(*e, g),g); oe != oe_end;
                     ++oe)
                {
                    if (match[*oe])
                    {
                        matched = true;
                        break;
                    }
                }
                if (!matched)
                    match[*e] = true;
            }
        }
    }
};

bool max_cardinality_matching(GraphInterface& gi, boost::any match)
{
    bool check;
    run_action<graph_tool::detail::never_directed>()
        (gi, std::bind(get_max_cardinality_matching(),
                        placeholders::_1, gi.GetVertexIndex(),
                       placeholders::_2, std::ref(check)),
         writable_edge_scalar_properties()) (match);
    return check;
}

ext: cc

max_stars_repo_name: johankaito/fufuka

max_issues_repo_name: johankaito/fufuka

max_forks_repo_name: johankaito/fufuka


text:
// *****************************************************************************
//
// Copyright (c) 2015, Southwest Research Institute® (SwRI®)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Southwest Research Institute® (SwRI®) nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// *****************************************************************************

#include <mapviz_plugins/laserscan_plugin.h>

// C++ standard libraries
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <vector>

// Boost libraries
#include <boost/algorithm/string.hpp>

// QT libraries
#include <QColorDialog>
#include <QDialog>
#include <QGLWidget>

// OpenGL
#include <GL/glew.h>

// QT Autogenerated
#include "ui_topic_select.h"

// ROS libraries
#include <ros/master.h>
#include <swri_transform_util/transform.h>
#include <swri_yaml_util/yaml_util.h>

#include <mapviz/select_topic_dialog.h>

// Declare plugin
#include <pluginlib/class_list_macros.h>
PLUGINLIB_DECLARE_CLASS(
    mapviz_plugins,
    laserscan,
    mapviz_plugins::LaserScanPlugin,
    mapviz::MapvizPlugin)

namespace mapviz_plugins
{
  LaserScanPlugin::LaserScanPlugin() :
      config_widget_(new QWidget()),
          topic_(""),
          alpha_(1.0),
          min_value_(0.0),
          max_value_(100.0),
          point_size_(3)
  {
    ui_.setupUi(config_widget_);

    // Set background white
    QPalette p(config_widget_->palette());
    p.setColor(QPalette::Background, Qt::white);
    config_widget_->setPalette(p);

    // Set status text red
    QPalette p3(ui_.status->palette());
    p3.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p3);

    // Initialize color selector colors
    ui_.min_color->setColor(Qt::white);
    ui_.max_color->setColor(Qt::black);

    // Set color transformer choices
    ui_.color_transformer->addItem(QString("Flat Color"), QVariant(0));
    ui_.color_transformer->addItem(QString("Intensity"), QVariant(1));
    ui_.color_transformer->addItem(QString("Range"), QVariant(2));
    ui_.color_transformer->addItem(QString("X Axis"), QVariant(3));
    ui_.color_transformer->addItem(QString("Y Axis"), QVariant(4));
    ui_.color_transformer->addItem(QString("Z Axis"), QVariant(5));

    QObject::connect(ui_.selecttopic,
        SIGNAL(clicked()),
        this,
        SLOT(SelectTopic()));
    QObject::connect(ui_.topic,
        SIGNAL(editingFinished()),
        this,
        SLOT(TopicEdited()));
    QObject::connect(ui_.alpha,
        SIGNAL(editingFinished()),
        this,
        SLOT(AlphaEdited()));
    QObject::connect(ui_.color_transformer,
        SIGNAL(currentIndexChanged(int)),
        this,
        SLOT(ColorTransformerChanged(int)));
    QObject::connect(ui_.max_color,
        SIGNAL(colorEdited(const QColor &)),
        this,
        SLOT(UpdateColors()));
    QObject::connect(ui_.min_color,
        SIGNAL(colorEdited(const QColor &)),
        this,
        SLOT(UpdateColors()));
    QObject::connect(ui_.minValue,
        SIGNAL(valueChanged(double)),
        this,
        SLOT(MinValueChanged(double)));
    QObject::connect(ui_.maxValue,
        SIGNAL(valueChanged(double)),
        this,
        SLOT(MaxValueChanged(double)));
    QObject::connect(ui_.bufferSize,
        SIGNAL(valueChanged(int)),
        this,
        SLOT(BufferSizeChanged(int)));
    QObject::connect(ui_.pointSize,
        SIGNAL(valueChanged(int)),
        this,
        SLOT(PointSizeChanged(int)));
    QObject::connect(ui_.use_rainbow,
        SIGNAL(stateChanged(int)),
        this,
        SLOT(UseRainbowChanged(int)));

    QObject::connect(ui_.max_color,
        SIGNAL(colorEdited(const QColor &)),
        this,
        SLOT(DrawIcon()));
    QObject::connect(ui_.min_color,
        SIGNAL(colorEdited(const QColor &)),
        this,
        SLOT(DrawIcon()));

    PrintInfo("Constructed LaserScanPlugin");
  }

  LaserScanPlugin::~LaserScanPlugin()
  {
  }

  void LaserScanPlugin::DrawIcon()
  {
    if (icon_)
    {
      QPixmap icon(16, 16);
      icon.fill(Qt::transparent);

      QPainter painter(&icon);
      painter.setRenderHint(QPainter::Antialiasing, true);

      QPen pen;
      pen.setWidth(4);
      pen.setCapStyle(Qt::RoundCap);

      pen.setColor(ui_.min_color->color());
      painter.setPen(pen);
      painter.drawPoint(2, 13);

      pen.setColor(ui_.min_color->color());
      painter.setPen(pen);
      painter.drawPoint(4, 6);

      pen.setColor(ui_.max_color->color());
      painter.setPen(pen);
      painter.drawPoint(12, 9);

      pen.setColor(ui_.max_color->color());
      painter.setPen(pen);
      painter.drawPoint(13, 2);

      icon_->SetPixmap(icon);
    }
  }

  QColor LaserScanPlugin::CalculateColor(const StampedPoint& point,
      bool has_intensity)
  {
    double val;
    int color_transformer = ui_.color_transformer->currentIndex();
    if (color_transformer == COLOR_RANGE)
    {
      val = point.range;
    }
    else if (color_transformer == COLOR_INTENSITY && has_intensity)
    {
      val = point.intensity;
    }
    else if (color_transformer == COLOR_X)
    {
      val = point.point.x();
    }
    else if (color_transformer == COLOR_Y)
    {
      val = point.point.y();
    }
    else if (color_transformer == COLOR_Z)
    {
      val = point.transformed_point.z();
    }
    else  // No intensity or  (color_transformer == COLOR_FLAT)
    {
      return ui_.min_color->color();
    }
    if (max_value_ > min_value_)
      val = (val - min_value_) / (max_value_ - min_value_);
    val = std::max(0.0, std::min(val, 1.0));
    if (ui_.use_rainbow->isChecked())
    {
      // Hue Interpolation
      int hue = static_cast<int>(val * 255);
      return QColor::fromHsl(hue, 255, 127, 255);
    }
    else
    {
      const QColor min_color = ui_.min_color->color();
      const QColor max_color = ui_.max_color->color();
      // RGB Interpolation
      int red, green, blue;
      red = static_cast<int>(val * max_color.red()   + ((1.0 - val) * min_color.red()));
      green = static_cast<int>(val * max_color.green() + ((1.0 - val) * min_color.green()));
      blue = static_cast<int>(val * max_color.blue()  + ((1.0 - val) * min_color.blue()));
      return QColor(red, green, blue, 255);
    }
  }

  void LaserScanPlugin::UpdateColors()
  {
    std::deque<Scan>::iterator scan_it = scans_.begin();
    for (; scan_it != scans_.end(); ++scan_it)
    {
      std::vector<StampedPoint>::iterator point_it = scan_it->points.begin();
      for (; point_it != scan_it->points.end(); point_it++)
      {
        point_it->color = CalculateColor(*point_it, scan_it->has_intensity);
      }
    }
  }

  void LaserScanPlugin::SelectTopic()
  {
    ros::master::TopicInfo topic = mapviz::SelectTopicDialog::selectTopic(
      "sensor_msgs/LaserScan");

    if (!topic.name.empty())
    {
      ui_.topic->setText(QString::fromStdString(topic.name));
      TopicEdited();
    }
  }

  void LaserScanPlugin::TopicEdited()
  {
    std::string topic = ui_.topic->text().trimmed().toStdString();
    if (topic != topic_)
    {
      initialized_ = false;
      scans_.clear();
      has_message_ = false;
      PrintWarning("No messages received.");

      laserscan_sub_.shutdown();

      topic_ = topic;
      if (!topic.empty())
      {
        laserscan_sub_ = node_.subscribe(topic_,
                                         100,
                                         &LaserScanPlugin::laserScanCallback,
                                         this);

        ROS_INFO("Subscribing to %s", topic_.c_str());
      }
    }
  }

  void LaserScanPlugin::MinValueChanged(double value)
  {
    min_value_ = value;
    UpdateColors();
  }

  void LaserScanPlugin::MaxValueChanged(double value)
  {
    max_value_ = value;
    UpdateColors();
  }

  void LaserScanPlugin::BufferSizeChanged(int value)
  {
    buffer_size_ = static_cast<size_t>(value);

    if (buffer_size_ > 0)
    {
      while (scans_.size() > buffer_size_)
      {
        scans_.pop_front();
      }
    }
  }

  void LaserScanPlugin::PointSizeChanged(int value)
  {
    point_size_ = static_cast<size_t>(value);
  }

  void LaserScanPlugin::laserScanCallback(const sensor_msgs::LaserScanConstPtr& msg)
  {
    if (!has_message_)
    {
      initialized_ = true;
      has_message_ = true;
    }

    // Note that unlike some plugins, this one does not store nor rely on the
    // source_frame_ member variable.  This one can potentially store many
    // messages with different source frames, so we need to store and transform
    // them individually.

    Scan scan;
    scan.stamp = msg->header.stamp;
    scan.color = QColor::fromRgbF(1.0f, 0.0f, 0.0f, 1.0f);
    scan.source_frame_ = msg->header.frame_id;
    scan.transformed = true;
    scan.has_intensity = !msg->intensities.empty();

    scan.points.clear();

    swri_transform_util::Transform transform;
    if (!GetTransform(scan.source_frame_, msg->header.stamp, transform))
    {
      scan.transformed = false;
      PrintError("No transform between " + source_frame_ + " and " + target_frame_);
    }
    double angle, x, y;
    for (size_t i = 0; i < msg->ranges.size(); i++)
    {
      // Discard the point if it's out of range
      if (msg->ranges[i] > msg->range_max || msg->ranges[i] < msg->range_min)
      {
        continue;
      }
      StampedPoint point;
      angle = msg->angle_min + msg->angle_increment * i;
      x = cos(angle) * msg->ranges[i];
      y = sin(angle) * msg->ranges[i];
      point.point = tf::Point(x, y, 0.0f);
      point.range = msg->ranges[i];
      if (i < msg->intensities.size())
        point.intensity = msg->intensities[i];
      if (scan.transformed)
      {
        point.transformed_point = transform * point.point;
      }
      point.color = CalculateColor(point, scan.has_intensity);
      scan.points.push_back(point);
    }
    scans_.push_back(scan);

    // If there are more items in the scan buffer than buffer_size_, remove them
    if (buffer_size_ > 0)
    {
      while (scans_.size() > buffer_size_)
      {
        scans_.pop_front();
      }
    }
  }

  void LaserScanPlugin::PrintError(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_ERROR("Error: %s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::red);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void LaserScanPlugin::PrintInfo(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_INFO("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::green);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  void LaserScanPlugin::PrintWarning(const std::string& message)
  {
    if (message == ui_.status->text().toStdString())
    {
      return;
    }

    ROS_WARN("%s", message.c_str());
    QPalette p(ui_.status->palette());
    p.setColor(QPalette::Text, Qt::darkYellow);
    ui_.status->setPalette(p);
    ui_.status->setText(message.c_str());
  }

  QWidget* LaserScanPlugin::GetConfigWidget(QWidget* parent)
  {
    config_widget_->setParent(parent);

    return config_widget_;
  }

  bool LaserScanPlugin::Initialize(QGLWidget* canvas)
  {
    canvas_ = canvas;

    DrawIcon();

    return true;
  }

  void LaserScanPlugin::Draw(double x, double y, double scale)
  {
    glPointSize(point_size_);
    glBegin(GL_POINTS);

    std::deque<Scan>::const_iterator scan_it = scans_.begin();
    while (scan_it != scans_.end())
    {
      if (scan_it->transformed)
      {
        std::vector<StampedPoint>::const_iterator point_it = scan_it->points.begin();
        for (; point_it != scan_it->points.end(); ++point_it)
        {
          glColor4d(
              point_it->color.redF(),
              point_it->color.greenF(),
              point_it->color.blueF(),
              alpha_);
          glVertex2d(
              point_it->transformed_point.getX(),
              point_it->transformed_point.getY());
        }
      }
      ++scan_it;
    }

    glEnd();

    PrintInfo("OK");
  }

  void LaserScanPlugin::UseRainbowChanged(int check_state)
  {
    if (check_state == Qt::Checked)
    {
      ui_.max_color->setVisible(false);
      ui_.min_color->setVisible(false);
      ui_.maxColorLabel->setVisible(false);
      ui_.minColorLabel->setVisible(false);
    }
    else
    {
      ui_.max_color->setVisible(true);
      ui_.min_color->setVisible(true);
      ui_.maxColorLabel->setVisible(true);
      ui_.minColorLabel->setVisible(true);
    }
    UpdateColors();
  }

  void LaserScanPlugin::Transform()
  {
    std::deque<Scan>::iterator scan_it = scans_.begin();
    for (; scan_it != scans_.end(); ++scan_it)
    {
      Scan& scan = *scan_it;

      swri_transform_util::Transform transform;

      bool was_using_latest_transforms = this->use_latest_transforms_;
      this->use_latest_transforms_ = false;
      if (GetTransform(scan.source_frame_, scan.stamp, transform))
      {
        scan.transformed = true;
        std::vector<StampedPoint>::iterator point_it = scan.points.begin();
        for (; point_it != scan.points.end(); ++point_it)
        {
          point_it->transformed_point = transform * point_it->point;
        }
      }
      else
      {
        scan.transformed = false;
      }
      this->use_latest_transforms_ = was_using_latest_transforms;
    }
    // Z color is based on transformed color, so it is dependent on the
    // transform
    if (ui_.color_transformer->currentIndex() == COLOR_Z)
    {
      UpdateColors();
    }
  }

  void LaserScanPlugin::LoadConfig(const YAML::Node& node,
      const std::string& path)
  {
    if (node["topic"])
    {
      std::string topic;
      node["topic"] >> topic;
      ui_.topic->setText(boost::trim_copy(topic).c_str());
      TopicEdited();
    }

    if (node["size"])
    {
      node["size"] >> point_size_;
      ui_.pointSize->setValue(static_cast<int>(point_size_));
    }

    if (node["buffer_size"])
    {
      node["buffer_size"] >> buffer_size_;
      ui_.bufferSize->setValue(static_cast<int>(buffer_size_));
    }

    if (node["color_transformer"])
    {
      std::string color_transformer;
      node["color_transformer"] >> color_transformer;
      if (color_transformer == "Intensity")
        ui_.color_transformer->setCurrentIndex(COLOR_INTENSITY);
      else if (color_transformer == "Range")
        ui_.color_transformer->setCurrentIndex(COLOR_RANGE);
      else if (color_transformer == "X Axis")
        ui_.color_transformer->setCurrentIndex(COLOR_X);
      else if (color_transformer == "Y Axis")
        ui_.color_transformer->setCurrentIndex(COLOR_Y);
      else if (color_transformer == "Z Axis")
        ui_.color_transformer->setCurrentIndex(COLOR_Z);
      else
        ui_.color_transformer->setCurrentIndex(COLOR_FLAT);
    }

    if (node["min_color"])
    {
      std::string min_color_str;
      node["min_color"] >> min_color_str;
      ui_.min_color->setColor(QColor(min_color_str.c_str()));
    }

    if (node["max_color"])
    {
      std::string max_color_str;
      node["max_color"] >> max_color_str;
      ui_.max_color->setColor(QColor(max_color_str.c_str()));
    }

    if (node["value_min"])
    {
      node["value_min"] >> min_value_;
      ui_.minValue->setValue(min_value_);
    }

    if (node["max_value"])
    {
      node["value_max"] >> max_value_;
      ui_.maxValue->setValue(max_value_);
    }

    if (node["alpha"])
    {
      node["alpha"] >> alpha_;
      ui_.alpha->setValue(alpha_);
      AlphaEdited();
    }

    if (node["use_rainbow"])
    {
      bool use_rainbow;
      node["use_rainbow"] >> use_rainbow;
      ui_.use_rainbow->setChecked(use_rainbow);
    }

    // UseRainbowChanged must be called *before* ColorTransformerChanged
    UseRainbowChanged(ui_.use_rainbow->checkState());
    // ColorTransformerChanged will also update colors of all points
    ColorTransformerChanged(ui_.color_transformer->currentIndex());
  }

  void LaserScanPlugin::ColorTransformerChanged(int index)
  {
    ROS_DEBUG("Color transformer changed to %d", index);
    switch (index)
    {
      case COLOR_FLAT:
        ui_.min_color->setVisible(true);
        ui_.max_color->setVisible(false);
        ui_.maxColorLabel->setVisible(false);
        ui_.minColorLabel->setVisible(false);
        ui_.minValueLabel->setVisible(false);
        ui_.maxValueLabel->setVisible(false);
        ui_.minValue->setVisible(false);
        ui_.maxValue->setVisible(false);
        ui_.use_rainbow->setVisible(false);
        break;
      case COLOR_INTENSITY:  // Intensity
      case COLOR_RANGE:  // Range
      case COLOR_X:  // X Axis
      case COLOR_Y:  // Y Axis
      case COLOR_Z:  // Z axis
      default:
        ui_.min_color->setVisible(!ui_.use_rainbow->isChecked());
        ui_.max_color->setVisible(!ui_.use_rainbow->isChecked());
        ui_.maxColorLabel->setVisible(!ui_.use_rainbow->isChecked());
        ui_.minColorLabel->setVisible(!ui_.use_rainbow->isChecked());
        ui_.minValueLabel->setVisible(true);
        ui_.maxValueLabel->setVisible(true);
        ui_.minValue->setVisible(true);
        ui_.maxValue->setVisible(true);
        ui_.use_rainbow->setVisible(true);
        break;
    }
    UpdateColors();
  }

  /**
   * Coerces alpha to [0.0, 1.0] and stores it in alpha_
   */
  void LaserScanPlugin::AlphaEdited()
  {
    alpha_ = std::max(0.0f, std::min(ui_.alpha->text().toFloat(), 1.0f));
    ui_.alpha->setValue(alpha_);
  }

  void LaserScanPlugin::SaveConfig(YAML::Emitter& emitter,
      const std::string& path)
  {
    emitter << YAML::Key << "topic" <<
               YAML::Value << boost::trim_copy(ui_.topic->text().toStdString());
    emitter << YAML::Key << "size" <<
               YAML::Value << ui_.pointSize->value();
    emitter << YAML::Key << "buffer_size" <<
               YAML::Value << ui_.bufferSize->value();
    emitter << YAML::Key << "alpha" <<
               YAML::Value << alpha_;
    emitter << YAML::Key << "color_transformer" <<
               YAML::Value << ui_.color_transformer->currentText().toStdString();
    emitter << YAML::Key << "min_color" <<
               YAML::Value << ui_.min_color->color().name().toStdString();
    emitter << YAML::Key << "max_color" <<
               YAML::Value << ui_.max_color->color().name().toStdString();
    emitter << YAML::Key << "value_min" <<
               YAML::Value << ui_.minValue->text().toDouble();
    emitter << YAML::Key << "value_max" <<
               YAML::Value << ui_.maxValue->text().toDouble();
    emitter << YAML::Key << "use_rainbow" <<
               YAML::Value << ui_.use_rainbow->isChecked();
  }
}

ext: cpp

max_stars_repo_name: matt-attack/mapviz

max_issues_repo_name: matt-attack/mapviz

max_forks_repo_name: matt-attack/mapviz


text:
#include "../src/network/message.hpp"

#include <array>
#include <iostream>

#include <boost/asio.hpp>
#include <boost/system/error_code.hpp>

std::string sparql_str_2 =
    "select ?id ?name ?parent ?child where { \
 		   ?id <http://rdf.dingfu.com/ns/business.stock_ticker_symbol.isin> cne100001zg7 .  \
 		   ?id <http://rdf.dingfu.com/ns/business.stock_ticker_symbol.short_name> ?name .  \
 		   ?id <http://rdf.dingfu.com/ns/business.stock_ticker_symbol.parent> ?parent .  \
 		   ?parent <http://rdf.dingfu.com/ns/business.stock_ticker_symbol.child> ?child .  \
        }";

int main(int argc, char** argv) {
  try {
    boost::asio::io_service io_service;
    boost::asio::ip::tcp::resolver r(io_service);
    boost::asio::ip::tcp::resolver::query q("localhost", "6666");
    boost::system::error_code ec;

    boost::asio::ip::tcp::socket socket(io_service);
    boost::asio::connect(socket, r.resolve(q));

    network::Message query_msg(sparql_str_2);
    std::cout << "data length " << sparql_str_2.length() << std::endl;
    std::cout << "data length " << query_msg.data_length() << std::endl;
    boost::asio::write(socket,
                       boost::asio::buffer(query_msg.message_c_str(),
                                           query_msg.message_length()),
                       ec);
    if (ec) {
      throw boost::system::system_error(ec);
    }

    size_t header_buffer;
    boost::asio::read(socket,
                      boost::asio::buffer(&header_buffer, sizeof(size_t)), ec);
    if (ec) {
      throw boost::system::system_error(ec);
    }

    std::cout << "header buffer " << header_buffer << std::endl;

    char* body_buffer = new char[header_buffer];
    boost::asio::read(socket, boost::asio::buffer(body_buffer, header_buffer),
                      ec);
    if (ec) {
      throw boost::system::system_error(ec);
    }
    std::cout << "query result" << std::endl;
    std::cout.write(body_buffer, header_buffer) << "\n";
    delete[] body_buffer;
    std::cin >> header_buffer;
  } catch (std::exception& e) {
    std::cerr << e.what() << std::endl;
  }

  return 0;
}

max_stars_repo_name: WeeJang/fish-db

max_issues_repo_name: WeeJang/fish-db

max_forks_repo_name: WeeJang/fish-db


text:
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

/**
 * \file boost/process/create_pipe.hpp
 *
 * Defines a function to create a pipe.
 */

#ifndef BOOST_PROCESS_CREATE_PIPE_HPP
#define BOOST_PROCESS_CREATE_PIPE_HPP

#include <boost/process/config.hpp>

#include BOOST_PROCESS_PLATFORM_PROMOTE_PATH(create_pipe)
BOOST_PROCESS_PLATFORM_PROMOTE_NAMESPACE(create_pipe)

#if defined(BOOST_PROCESS_DOXYGEN)
namespace boost { namespace process {

/**
 * Creates an anonymous pipe.
 *
 * \note On Windows anonymous pipes don't support
 *       asynchronous I/O.
 *
 * \throws boost::system::system_error in case of an error
 */
pipe create_pipe();

/**
 * Creates an anonymous pipe.
 *
 * \note On Windows anonymous pipes don't support
 *       asynchronous I/O.
 */
pipe create_pipe(boost::system::error_code &ec);

}}
#endif

#endif

ext: hpp

max_stars_repo_name: johny-c/ViZDoom

max_issues_repo_name: johny-c/ViZDoom

max_forks_repo_name: johny-c/ViZDoom


text:
#include "GRU.hpp"
#include "ActFunc.hpp"
#include "Utils.hpp"
#include <Eigen/SVD>

GRU::GRU(const int inputDim, const int hiddenDim){
  this->Wxr = MatD(hiddenDim, inputDim);
  this->Whr = MatD(hiddenDim, hiddenDim);
  this->br = VecD::Zero(hiddenDim);

  this->Wxz = MatD(hiddenDim, inputDim);
  this->Whz = MatD(hiddenDim, hiddenDim);
  this->bz = VecD::Zero(hiddenDim);

  this->Wxu = MatD(hiddenDim, inputDim);
  this->Whu = MatD(hiddenDim, hiddenDim);
  this->bu = VecD::Zero(hiddenDim);
}

void GRU::init(Rand& rnd, const Real scale){
  rnd.uniform(this->Wxr, scale);
  rnd.uniform(this->Whr, scale);

  rnd.uniform(this->Wxz, scale);
  rnd.uniform(this->Whz, scale);

  rnd.uniform(this->Wxu, scale);
  rnd.uniform(this->Whu, scale);

  this->Whr = Eigen::JacobiSVD<MatD>(this->Whr, Eigen::ComputeFullV|Eigen::ComputeFullU).matrixU();
  this->Whz = Eigen::JacobiSVD<MatD>(this->Whz, Eigen::ComputeFullV|Eigen::ComputeFullU).matrixU();
  this->Whu = Eigen::JacobiSVD<MatD>(this->Whu, Eigen::ComputeFullV|Eigen::ComputeFullU).matrixU();
}

void GRU::forward(const VecD& xt, const GRU::State* prev, GRU::State* cur){
  cur->r = this->br + this->Wxr*xt + this->Whr*prev->h;
  cur->z = this->bz + this->Wxz*xt + this->Whz*prev->h;

  ActFunc::logistic(cur->r);
  ActFunc::logistic(cur->z);

  cur->rh = cur->r.array()*prev->h.array();
  cur->u = this->bu + this->Wxu*xt + this->Whu*cur->rh;
  ActFunc::tanh(cur->u);
  cur->h = (1.0-cur->z.array())*prev->h.array() + cur->z.array()*cur->u.array();
}

void GRU::backward(GRU::State* prev, GRU::State* cur, GRU::Grad& grad, const VecD& xt){
  VecD delr, delz, delu, delrh;

  delz = ActFunc::logisticPrime(cur->z).array()*cur->delh.array()*(cur->u-prev->h).array();
  delu = ActFunc::tanhPrime(cur->u).array()*cur->delh.array()*cur->z.array();
  delrh = this->Whu.transpose()*delu;
  delr = ActFunc::logisticPrime(cur->r).array()*delrh.array()*prev->h.array();

  cur->delx =
    this->Wxr.transpose()*delr+
    this->Wxz.transpose()*delz+
    this->Wxu.transpose()*delu;

  prev->delh.noalias() +=
    this->Whr.transpose()*delr+
    this->Whz.transpose()*delz;
  prev->delh.array() +=
    delrh.array()*cur->r.array()+
    cur->delh.array()*(1.0-cur->z.array());

  grad.Wxr.noalias() += delr*xt.transpose();
  grad.Whr.noalias() += delr*prev->h.transpose();

  grad.Wxz.noalias() += delz*xt.transpose();
  grad.Whz.noalias() += delz*prev->h.transpose();

  grad.Wxu.noalias() += delu*xt.transpose();
  grad.Whu.noalias() += delu*cur->rh.transpose();

  grad.br += delr;
  grad.bz += delz;
  grad.bu += delu;
}

void GRU::sgd(const GRU::Grad& grad, const Real learningRate){
  this->Wxr -= learningRate*grad.Wxr;
  this->Whr -= learningRate*grad.Whr;
  this->br -= learningRate*grad.br;

  this->Wxz -= learningRate*grad.Wxz;
  this->Whz -= learningRate*grad.Whz;
  this->bz -= learningRate*grad.bz;

  this->Wxu -= learningRate*grad.Wxu;
  this->Whu -= learningRate*grad.Whu;
  this->bu -= learningRate*grad.bu;
}

void GRU::save(std::ofstream& ofs){
  Utils::save(ofs, this->Wxr); Utils::save(ofs, this->Whr); Utils::save(ofs, this->br);
  Utils::save(ofs, this->Wxz); Utils::save(ofs, this->Whz); Utils::save(ofs, this->bz);
  Utils::save(ofs, this->Wxu); Utils::save(ofs, this->Whu); Utils::save(ofs, this->bu);
}

void GRU::load(std::ifstream& ifs){
  Utils::load(ifs, this->Wxr); Utils::load(ifs, this->Whr); Utils::load(ifs, this->br);
  Utils::load(ifs, this->Wxz); Utils::load(ifs, this->Whz); Utils::load(ifs, this->bz);
  Utils::load(ifs, this->Wxu); Utils::load(ifs, this->Whu); Utils::load(ifs, this->bu);
}

void GRU::State::clear(){
  this->h = VecD();
  this->u = VecD();
  this->r = VecD();
  this->z = VecD();
  this->rh = VecD();
  this->delh = VecD();
  this->delx = VecD();
}

GRU::Grad::Grad(const GRU& gru){
  this->Wxr = MatD::Zero(gru.Wxr.rows(), gru.Wxr.cols());
  this->Whr = MatD::Zero(gru.Whr.rows(), gru.Whr.cols());
  this->br = VecD::Zero(gru.br.rows());

  this->Wxz = MatD::Zero(gru.Wxz.rows(), gru.Wxz.cols());
  this->Whz = MatD::Zero(gru.Whz.rows(), gru.Whz.cols());
  this->bz = VecD::Zero(gru.bz.rows());

  this->Wxu = MatD::Zero(gru.Wxu.rows(), gru.Wxu.cols());
  this->Whu = MatD::Zero(gru.Whu.rows(), gru.Whu.cols());
  this->bu = VecD::Zero(gru.bu.rows());
};

void GRU::Grad::init(){
  this->Wxr.setZero(); this->Whr.setZero(); this->br.setZero();
  this->Wxz.setZero(); this->Whz.setZero(); this->bz.setZero();
  this->Wxu.setZero(); this->Whu.setZero(); this->bu.setZero();
}

Real GRU::Grad::norm(){
  return
    this->Wxr.squaredNorm()+this->Whr.squaredNorm()+this->br.squaredNorm()+
    this->Wxz.squaredNorm()+this->Whz.squaredNorm()+this->bz.squaredNorm()+
    this->Wxu.squaredNorm()+this->Whu.squaredNorm()+this->bu.squaredNorm();
}

void GRU::Grad::operator += (const GRU::Grad& grad){
  this->Wxr += grad.Wxr; this->Whr += grad.Whr; this->br += grad.br;
  this->Wxz += grad.Wxz; this->Whz += grad.Whz; this->bz += grad.bz;
  this->Wxu += grad.Wxu; this->Whu += grad.Whu; this->bu += grad.bu;
}


text:
/***************************************************************************
   Copyright 2015 Ufora Inc.

   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.
****************************************************************************/
#pragma once

#include <string>
#include <vector>
#include <boost/enable_shared_from_this.hpp>

/*
This file contains tools that allow checksummed file IO.
The desired pattern is one where a user wants to hold an open file for
appending and then perodically read the entire contents at once.
*/

namespace ChecksummedFile {
	namespace FileMode {
		enum ModeType {READ = 0, APPEND = 1};
	}

	namespace detail {
		uint64_t fileSize(FILE* inFile);
		FILE*  openFile(const std::string& fileName, const FileMode::ModeType& mode);
	}

	class ChecksummedWriter : public boost::enable_shared_from_this<ChecksummedWriter> {
	public:
			explicit ChecksummedWriter(std::string path);

			~ChecksummedWriter();

			std::string path() const;

			void flush();

			size_t written() const;

			uint64_t fileSize() const;

			void writeString(const std::string& str);

			bool isDirty() const;

	private:
			// obviously we don't want this to be copied
			ChecksummedWriter(const ChecksummedWriter& other);

			ChecksummedWriter& operator=(const ChecksummedWriter& other);

			FILE* 					mFile;
			std::string				mPath;
			bool					mDataError;
			bool					mIsDirty;
	};

	bool readString(FILE* inFile, std::string& outString, int64_t& remainingBytes);

	bool readAllToVector(std::string path, std::vector<std::string>& outVector);

} // ChecksummedFile namespace

max_stars_repo_name: ufora/ufora


text:
// Copyright David Abrahams 2004. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/iterator/iterator_adaptor.hpp>
#include <boost/pending/iterator_tests.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <cassert>

struct mutable_it : boost::iterator_adaptor<mutable_it,int*>
{
    typedef boost::iterator_adaptor<mutable_it,int*> super_t;

    mutable_it();
    explicit mutable_it(int* p) : super_t(p) {}

    bool equal(mutable_it const& rhs) const
    {
        return this->base() == rhs.base();
    }
};

struct constant_it : boost::iterator_adaptor<constant_it,int const*>
{
    typedef boost::iterator_adaptor<constant_it,int const*> super_t;

    constant_it();
    explicit constant_it(int* p) : super_t(p) {}
    constant_it(mutable_it const& x) : super_t(x.base()) {}

    bool equal(constant_it const& rhs) const
    {
        return this->base() == rhs.base();
    }
};

int main()
{
    int data[] = { 49, 77 };

    mutable_it i(data);
    constant_it j(data + 1);
    BOOST_TEST(i < j);
    BOOST_TEST(j > i);
    BOOST_TEST(i <= j);
    BOOST_TEST(j >= i);
    BOOST_TEST(j - i == 1);
    BOOST_TEST(i - j == -1);

    constant_it k = i;

    BOOST_TEST(!(i < k));
    BOOST_TEST(!(k > i));
    BOOST_TEST(i <= k);
    BOOST_TEST(k >= i);
    BOOST_TEST(k - i == 0);
    BOOST_TEST(i - k == 0);

    return boost::report_errors();
}

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


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

#include <WinUser.h>
#include <set>

#include <boost/thread/win32/recursive_mutex.hpp>
#include <boost/thread/lock_types.hpp>
#include <boost/thread/tss.hpp>

static const TCHAR kOriginWndProcProp[] = L"kOriginWndProcProp";

namespace
{
	void UninstallThreadHHook(HHOOK hhook)
	{
		UnhookWindowsHookEx(hhook);
	}

	typedef std::map<HWND, CCustomFrameWndHandlerPtr>			HWNDToHandlerMapT;
	typedef std::set<CCustomFrameHook::CHookMessageFilter*>		SubThreadMsgFilterContainerT;

	static DWORD												g_main_thread_id = 0;
	static boost::thread_specific_ptr<HHOOK__>					g_thread_hhook(UninstallThreadHHook);

    // g_hwnd_handlers
    // add: main thread
    // remove: main thread
    // use: main/sub thread
    // So remove in OnFinalMessage should be safe enough.
	static HWNDToHandlerMapT									g_hwnd_handlers;
	static CCustomFrameWndHandlerPtr							g_primary_handler;
	static SubThreadMsgFilterContainerT							g_sub_thread_filter;
	static boost::recursive_mutex								g_filter_mutex;

	BOOL PreTranslateSubThreadMsg(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
	{
		assert(GetCurrentThreadId() != g_main_thread_id);
		boost::unique_lock<boost::recursive_mutex> filter_lock(g_filter_mutex);
		if (!g_sub_thread_filter.size())
			return FALSE;

		MSG msg;
		msg.hwnd = hwnd;
		msg.message = uMsg;
		msg.wParam = wParam;
		msg.lParam = lParam;

		SubThreadMsgFilterContainerT::iterator it_filter = g_sub_thread_filter.begin();
		for (; it_filter != g_sub_thread_filter.end(); ++it_filter)
		{
			if ((*it_filter)->CrBrowserMainPreTranslateMessage(&msg))
				return TRUE;
		}

		return FALSE;
	}
}

CCustomFrameHook::CCustomFrameHook()
{
}

CCustomFrameHook::~CCustomFrameHook()
{
}

BOOL CCustomFrameHook::InstallHook()
{
	DWORD thread_id = GetCurrentThreadId();
	if (0 == g_main_thread_id)
		g_main_thread_id = thread_id;
	HHOOK hhook = SetWindowsHookEx(WH_CALLWNDPROC,
		HookWndProcCallback, NULL, thread_id);
	g_thread_hhook.reset(hhook);
	return !!hhook;
}

CCustomFrameWndHandlerPtr CCustomFrameHook::AddTopHWndHandler(HWND hwnd)
{
	assert(GetCurrentThreadId() == g_main_thread_id || g_main_thread_id == 0);

	CCustomFrameWndHandlerPtr handler;
	HWNDToHandlerMapT::iterator it_handler = g_hwnd_handlers.find(hwnd);
	if (it_handler == g_hwnd_handlers.end())
	{
		handler = std::make_shared<CCustomFrameWndHandler>(hwnd);
		if (!g_primary_handler)
			g_primary_handler = handler;
		else
			g_hwnd_handlers.insert(std::make_pair(hwnd, handler));
	}
	else
	{
		handler = it_handler->second;
	}
	return handler;
}

void CCustomFrameHook::RemoveTopWndHandler(HWND hwnd)
{
	assert(GetCurrentThreadId() == g_main_thread_id || g_main_thread_id == 0);

	if (g_primary_handler && g_primary_handler->GetOwnerHwnd() == hwnd)
		g_primary_handler.reset();
	else
	{
		HWNDToHandlerMapT::iterator it_handler = g_hwnd_handlers.find(hwnd);
		if (it_handler != g_hwnd_handlers.end())
			g_hwnd_handlers.erase(it_handler);
	}
}

BOOL CCustomFrameHook::ShouldHookWindow(HWND hwnd)
{
	HWNDToHandlerMapT::iterator it_handler = g_hwnd_handlers.begin();
	for (; it_handler != g_hwnd_handlers.end(); ++it_handler)
	{
		if (it_handler->second->IsChildWindow(hwnd))
			return TRUE;
	}

	if (g_primary_handler && g_primary_handler->IsChildWindow(hwnd))
		return TRUE;

	return FALSE;
}

LRESULT CALLBACK CCustomFrameHook::HookWndProcCallback(int nCode, WPARAM wParam, LPARAM lParam)
{
	assert(g_main_thread_id);

	DWORD thread_id = GetCurrentThreadId();

	if (nCode == HC_ACTION)
	{
		CWPSTRUCT* cwp = (CWPSTRUCT*)lParam;

		if (WM_CREATE == cwp->message)
		{
			// HWND which is not owned by handlers shouldn't be hooked.

			if (ShouldHookWindow(cwp->hwnd))
			{
				WNDPROC old_proc = (WNDPROC)::SetWindowLongPtr(
					cwp->hwnd, GWL_WNDPROC,
					reinterpret_cast<LONG_PTR>(thread_id == g_main_thread_id ?
						MainThreadHookWndProc : SubThreadHookWndProc));
				::SetProp(cwp->hwnd, kOriginWndProcProp, reinterpret_cast<HANDLE>(old_proc));
			}
		}
	}

	return CallNextHookEx(g_thread_hhook.get(), nCode, wParam, lParam);
}

LRESULT CALLBACK CCustomFrameHook::SubThreadHookWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	assert(g_main_thread_id != GetCurrentThreadId());

	if (PreTranslateSubThreadMsg(hwnd, uMsg, wParam, lParam))
		return FALSE;

	WNDPROC old_proc = reinterpret_cast<WNDPROC>(::GetProp(hwnd, kOriginWndProcProp));

	{
		HWNDToHandlerMapT::iterator it_handler = g_hwnd_handlers.begin();
		for (; it_handler != g_hwnd_handlers.end(); ++it_handler)
		{
			if (it_handler->second->IsChildWindow(hwnd))
				return it_handler->second->SubThreadHandle(
					hwnd, uMsg, wParam, lParam, old_proc);
		}
		if (g_primary_handler && g_primary_handler->IsChildWindow(hwnd))
			return g_primary_handler->SubThreadHandle(
				hwnd, uMsg, wParam, lParam, old_proc);
	}

	return old_proc(hwnd, uMsg, wParam, lParam);
}

LRESULT CALLBACK CCustomFrameHook::MainThreadHookWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	assert(g_main_thread_id == GetCurrentThreadId());

	WNDPROC old_proc = reinterpret_cast<WNDPROC>(::GetProp(hwnd, kOriginWndProcProp));

	HWNDToHandlerMapT::iterator it_handler = g_hwnd_handlers.begin();
	for (; it_handler != g_hwnd_handlers.end(); ++it_handler)
	{
		if (it_handler->second->IsChildWindow(hwnd))
			return it_handler->second->MainThreadHandle(
				hwnd, uMsg, wParam, lParam, old_proc);
	}
	if (g_primary_handler && g_primary_handler->IsChildWindow(hwnd))
		return g_primary_handler->MainThreadHandle(
			hwnd, uMsg, wParam, lParam, old_proc);

	return old_proc(hwnd, uMsg, wParam, lParam);
}

BOOL CCustomFrameHook::InstallSubThreadMsgFilter(CHookMessageFilter* filter)
{
	assert(GetCurrentThreadId() == g_main_thread_id);

	boost::unique_lock<boost::recursive_mutex> filter_lock(g_filter_mutex);
	SubThreadMsgFilterContainerT::iterator it_filter = g_sub_thread_filter.find(filter);
	if (it_filter == g_sub_thread_filter.end())
	{
		g_sub_thread_filter.insert(filter);
		return TRUE;
	}
	return FALSE;
}

BOOL CCustomFrameHook::UninstallSubThreadMsgFilter(CHookMessageFilter* filter)
{
	assert(GetCurrentThreadId() == g_main_thread_id);

	boost::unique_lock<boost::recursive_mutex> filter_lock(g_filter_mutex);
	SubThreadMsgFilterContainerT::iterator it_filter = g_sub_thread_filter.find(filter);
	if (it_filter != g_sub_thread_filter.end())
	{
		g_sub_thread_filter.erase(it_filter);
		return TRUE;
	}
	return FALSE;
}


text:
///3
// ALGOLAB BGL Tutorial 3
// Flow example demonstrating
// - breadth first search (BFS) on the residual graph

// Compile and run with one of the following:
// g++ -std=c++11 -O2 bgl_residual_bfs.cpp -o bgl_residual_bfs ./bgl_residual_bfs
// g++ -std=c++11 -O2 -I path/to/boost_1_58_0 bgl_residual_bfs.cpp -o bgl_residual_bfs; ./bgl_residual_bfs

// Includes
// ========
// STL includes
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
// BGL includes
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/push_relabel_max_flow.hpp>
#include <boost/tuple/tuple.hpp>

// BGL graph definitions
// =====================
// Graph Type with nested interior edge properties for Flow Algorithms
typedef  boost::adjacency_list_traits<boost::vecS, boost::vecS, boost::directedS> traits;
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::directedS, boost::no_property,
  boost::property<boost::edge_capacity_t, long,
    boost::property<boost::edge_residual_capacity_t, long,
      boost::property<boost::edge_reverse_t, traits::edge_descriptor> > > >  graph;
// Interior Property Maps
typedef traits::vertex_descriptor vertex_desc;

typedef  boost::graph_traits<graph>::edge_descriptor      edge_desc;
typedef  boost::graph_traits<graph>::out_edge_iterator      out_edge_it;

// Custom Edge Adder Class, that holds the references
// to the graph, capacity map and reverse edge map
// ===================================================
class edge_adder {
 graph &G;

 public:
  explicit edge_adder(graph &G) : G(G) {}

  void add_edge(int from, int to, long capacity) {
    auto c_map = boost::get(boost::edge_capacity, G);
    auto r_map = boost::get(boost::edge_reverse, G);
    const edge_desc e = boost::add_edge(from, to, G).first;
    const edge_desc rev_e = boost::add_edge(to, from, G).first;
    c_map[e] = capacity;
    c_map[rev_e] = 0; // reverse edge has no capacity!
    r_map[e] = rev_e;
    r_map[rev_e] = e;
  }
};

void add_if_present(edge_adder & adder, std::vector<int> &present, int n, int u, int i, int j, int c) {
  if(i >= 0 && j >= 0 && i <= (n-1) && j <= (n-1)) {
    if(present[i * n + j]) {
      adder.add_edge(u, i * n + j, c);
    }
  }
}

// Main
void testcase() {
  // build graph
  int n;
  std::cin >> n;
  graph G(n * n);
  edge_adder adder(G);
  // auto rc_map = boost::get(boost::edge_residual_capacity, G);
  const vertex_desc v_source = boost::add_vertex(G);
  const vertex_desc v_sink = boost::add_vertex(G);
  std::vector<int> present(n*n);

  int sum_present = 0;
  for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
      std::cin >> present[i * n + j];
      if(present[i * n + j]) {
        sum_present++;
        if((i + j) % 2 == 0)
          adder.add_edge(v_source, i * n + j, 1);
        else
          adder.add_edge(i * n + j, v_sink, 1);
      }
    }
  }

  for(int i = 0; i < n; i++) {
    for(int j = 0; j < n; j++) {
      int ij = i * n + j;
      if(present[ij] && (i + j) % 2 == 0) {
        add_if_present(adder, present, n, ij, (i - 1), j - 2, 1);
        add_if_present(adder, present, n, ij, (i - 1), j + 2, 1);
        add_if_present(adder, present, n, ij, (i + 1), j - 2, 1);
        add_if_present(adder, present, n, ij, (i + 1), j + 2, 1);
        add_if_present(adder, present, n, ij, (i - 2), j - 1, 1);
        add_if_present(adder, present, n, ij, (i - 2), j + 1, 1);
        add_if_present(adder, present, n, ij, (i + 2), j - 1, 1);
        add_if_present(adder, present, n, ij, (i + 2), j + 1, 1);
      //   if(i > 0 && j > 1)
      //     adder.add_edge(ij, (i - 1) * n + j - 2, 1);
      //   if(i > 0 && j < (n - 2))
      //     adder.add_edge(ij, (i - 1) * n + j + 2, 1);
      //   if(i < (n - 1) && j > 1)
      //     adder.add_edge(ij, (i + 1) * n + j - 2, 1);
      //   if(i < (n - 1) && j < (n - 2))
      //     adder.add_edge(ij, (i + 1) * n + j + 2, 1);
      //   if(i > 1 && j > 0)
      //     adder.add_edge(ij, (i - 2) * n + j - 1, 1);
      //   if(i > 1 && j < (n - 1))
      //     adder.add_edge(ij, (i - 2) * n + j + 1, 1);
      //   if(i < (n - 2) && j > 0)
      //     adder.add_edge(ij, (i + 2) * n + j - 1, 1);
      //   if(i < (n - 2) && j < (n - 1))
      //     adder.add_edge(ij, (i + 2) * n + j + 1, 1);
      }
    }
  }

  // for(int i = 0; i < n; i++) {
  //   // adder.add_edge(v_source, i, 1);
  //   adder.add_edge(i, v_sink,  std::numeric_limits<int>::max());
  // }

  int flow = boost::push_relabel_max_flow(G, v_source, v_sink);
  // auto c_map = boost::get(boost::edge_capacity, G);
  // auto rc_map = boost::get(boost::edge_residual_capacity, G);
  // Find a min cut via maxflow
  std::cout << sum_present - flow << "\n";
  // std::cerr << std::endl;
  // // Retrieve the capacity map and reverse capacity map
  // const auto c_map = boost::get(boost::edge_capacity, G);
  // const auto rc_map = boost::get(boost::edge_residual_capacity, G);

  // // Iterate over all the edges to print the flow along them
  // auto edge_iters = boost::edges(G);
  // for (auto edge_it = edge_iters.first; edge_it != edge_iters.second; ++edge_it) {
  //   const edge_desc edge = *edge_it;
  //   const long flow_through_edge = c_map[edge] - rc_map[edge];
  //   std::cerr << "edge from " << boost::source(edge, G) << " to " << boost::target(edge, G)
  //             << " runs " << flow_through_edge
  //             << " units of flow (negative for reverse direction). \n";
  // }
}

int main() {
  std::ios_base::sync_with_stdio(false);
  std::size_t t;
  for (std::cin >> t; t > 0; --t) testcase();
  return 0;
}

max_stars_repo_name: haeggee/algolab

max_issues_repo_name: haeggee/algolab

max_forks_repo_name: haeggee/algolab


text:
#include <pthread.h>
//#include <stdio.h>
//#include <stdlib.h>
//#include <unistd.h>
//#include <iostream>
//#include <fstream>
//#include <cmath>
//#include <math.h>

#include "pevents/pevents.h"	//Includes event handling (https://github.com/NeoSmart/PEvents)
#include "I2C/i2c.h"
#include "control/MatricesAndVectors.h"
#include "control/QuatRotEuler.h"
#include "control/AttitudeControl.h"
#include "control/PID_3DOF.h"

#include "rosserial/ros.h"
#include "rosserial/geometry_msgs/Wrench.h"
#include "rosserial/qcontrol_defs/PVA.h"
#include <Eigen/Dense>
#include "threads/keyboard_thread.h"
#include "threads/control_thread.h"
#include "threads/pca_thread.h"
#include "threads/print_thread.h"
#include "threads/mpu_thread.h"
#include "threads/stateMachine.h"
#include "threads/Ros_threads.h"
#include "threads/logger_thread.h"
// #include "overo/overo.h"

#include "kalman.h"

//TODO add feed-forward from position to attitude. Check yawref when changing from att to pos mode

using namespace neosmart;
using namespace std;
using Eigen::Matrix;

#define PI 3.1415

int currentState = INITIALIZING;
int YawSource = _IMU;

//Ros handle and IP variable
ros::NodeHandle  _nh;
char *rosSrvrIp;
qcontrol_defs::PVA PVA_quadVicon;
qcontrol_defs::PVA PVA_quadKalman;
qcontrol_defs::PVA PVA_RefJoy;
qcontrol_defs::PVA PVA_RefClient;

//Events and mutexes
neosmart_event_t e_Key1, e_Key2, e_Key3, e_Key4, e_Key5, e_Key6, e_Key7, e_Key8, e_Key9, e_KeyESC;
// neosmart_event_t e_ButtonLB, e_ButtonRB;
neosmart_event_t e_buttonX, e_buttonY, e_buttonA, e_buttonB;
neosmart_event_t e_Motor_Up, e_Motor_Down, e_Motor_Kill;
neosmart_event_t e_Timeout; //Always false event for forcing timeout of WaitForEvent
neosmart_event_t e_SwitchYawSource;
neosmart_event_t e_IMU_trigger;
neosmart_event_t e_PCA_trigger;
neosmart_event_t e_Log_trigger;
neosmart_event_t e_AttControl_trigger, e_PosControl_trigger;
neosmart_event_t e_Kalman_Trigger;
neosmart_event_t e_endInit; //Event that indicates that initialization is done
pthread_mutex_t IMU_Mutex;	//protect IMU data
pthread_mutex_t PCA_Mutex;
pthread_mutex_t ThrustJoy_Mutex;
pthread_mutex_t ThrustPosControl_Mutex;
pthread_mutex_t attRefJoy_Mutex, posRefJoy_Mutex;
pthread_mutex_t posRefClient_Mutex;
pthread_mutex_t attRefPosControl_Mutex;
pthread_mutex_t Contr_Input_Mutex;
pthread_mutex_t PID_Mutex;
pthread_mutex_t stateMachine_Mutex;
pthread_mutex_t PVA_Vicon_Mutex;
pthread_mutex_t PVA_Kalman_Mutex;
pthread_mutex_t ROS_Mutex;
pthread_mutex_t YawSource_Mutex;

//Global variables
float ThrustJoy = 0;
float ThrustPosControl = 0;
Matrix<float, 3, 1> IMU_Data_RPY, IMU_Data_RPY_ViconYaw;
Matrix<float, 3, 1> IMU_Data_Accel, IMU_Data_AngVel;
Matrix<float, 4, 1> IMU_Data_Quat, IMU_Data_QuatNoYaw, IMU_Data_Quat_ViconYaw;
Matrix<float, 3, 1> attRefJoy, angVelRefJoy;
Matrix<float, 3, 3> Rdes_PosControl;
Matrix<float, 4, 1> Contr_Input;
Matrix<float, 4, 1> PCA_Data;
PID_3DOF PID_angVel, PID_att, PID_pos; 	//Control PIDs
int threadCount = 0;		//Counts active threads

// ofstream kalman_v;
// ofstream vicon_p;

I2C i2c('3');

void *rosSpinTask(void *threadID){
	int SamplingTime = 10;	//Sampling time in milliseconds
	int localCurrentState;
	printf("rosSpinTask has started!\n");

	//ros joy subscriber
	ros::Subscriber<sensor_msgs::Joy> sub_mp_joy("/joy", handle_mp_joy_msg);
	_nh.subscribe(sub_mp_joy);

	ros::Subscriber<qcontrol_defs::PVA> sub_ros_pva("/pva", handle_client_pva_msg);
	_nh.subscribe(sub_ros_pva);

  	ros::Subscriber<geometry_msgs::TransformStamped> sub_tform("/vicon/Quad7/Quad7", handle_Vicon);
  	_nh.subscribe(sub_tform);

  	while(1){
		WaitForEvent(e_Timeout,SamplingTime);

		//Check system state
		pthread_mutex_lock(&stateMachine_Mutex);
			localCurrentState = currentState;
		pthread_mutex_unlock(&stateMachine_Mutex);

		//check if system should be terminated
		if(localCurrentState == TERMINATE){
			break;
		}

		//Trigger subscribers
	  	pthread_mutex_lock(&ROS_Mutex);
		    _nh.spinOnce();
	    pthread_mutex_unlock(&ROS_Mutex);

  	}

  	printf("rosSpinTask stopping...\n");
	threadCount -= 1;
	pthread_exit(NULL);
}

void *rosPublisherTask(void *threadID){
	printf("rosPublisherTask has started!\n");
	int SamplingTime = 50;	//Sampling time in milliseconds
	int localCurrentState, localYawSource;
	Matrix<float, 3, 1> RPY;

	//ros publisher
  	geometry_msgs::Point RPY_IMU;
  	geometry_msgs::Point RPY_Ref;
  	geometry_msgs::Wrench controlInputs;
  	qcontrol_defs::PVA PVA_EstimatedPVA;
  	qcontrol_defs::PVA PVA_PVARef;
  	qcontrol_defs::PVA PVA_Vicon;

  	ros::Publisher imurpy_pub("Quad_RPY", &RPY_IMU);
  	ros::Publisher Refrpy_pub("Quad_RPYRef", &RPY_Ref);
  	ros::Publisher imuWrench_pub("Quad_Inputs", &controlInputs);
  	ros::Publisher PvaEst_pub("Quad_EstimatedPVA", &PVA_EstimatedPVA);
  	ros::Publisher PvaRef_pub("Quad_PVARef", &PVA_PVARef);
  	ros::Publisher PvaVicon_pub("Quad_ViconPVA", &PVA_Vicon);
  	_nh.advertise(imurpy_pub);
  	_nh.advertise(Refrpy_pub);
  	_nh.advertise(imuWrench_pub);
	_nh.advertise(PvaEst_pub);
	_nh.advertise(PvaRef_pub);
	_nh.advertise(PvaVicon_pub);

	  while(1){
		WaitForEvent(e_Timeout,SamplingTime);

		//Check system state
		pthread_mutex_lock(&stateMachine_Mutex);
			localCurrentState = currentState;
		pthread_mutex_unlock(&stateMachine_Mutex);

		//check if system should be terminated
		if(localCurrentState == TERMINATE){
			break;
		}

		//Check if yaw source should come from IMU of Vicon
		pthread_mutex_lock(&YawSource_Mutex);
			localYawSource = YawSource;
		pthread_mutex_unlock(&YawSource_Mutex);

		//Get IMU roll pitch yaw data
		if (localYawSource == _IMU){
		  	pthread_mutex_lock(&IMU_Mutex);
			  	RPY_IMU.x = IMU_Data_RPY(0);
			  	RPY_IMU.y = IMU_Data_RPY(1);
			  	RPY_IMU.z = IMU_Data_RPY(2);
		  	pthread_mutex_unlock(&IMU_Mutex);
		}
		else{ //Get IMU roll and pitch; yaw comes from vicon
			pthread_mutex_lock(&PVA_Vicon_Mutex);
				RPY_IMU.x = IMU_Data_RPY_ViconYaw(0);
			  	RPY_IMU.y = IMU_Data_RPY_ViconYaw(1);
			  	RPY_IMU.z = IMU_Data_RPY_ViconYaw(2);
			pthread_mutex_unlock(&PVA_Vicon_Mutex);
		}

		//Get position/velocity estimations
		pthread_mutex_lock(&PVA_Kalman_Mutex);
			PVA_EstimatedPVA = PVA_quadKalman;
		pthread_mutex_unlock(&PVA_Kalman_Mutex);

		//Get position and attitude from vicon
	 	pthread_mutex_lock(&PVA_Vicon_Mutex);
	 		PVA_Vicon = PVA_quadVicon;
	  	pthread_mutex_unlock(&PVA_Vicon_Mutex);

		//Get attitude references
		if(localCurrentState == ATTITUDE_MODE){
			pthread_mutex_lock(&attRefJoy_Mutex);
				RPY_Ref.x = attRefJoy(0);
				RPY_Ref.y = attRefJoy(1);
				RPY_Ref.z = attRefJoy(2);
			pthread_mutex_unlock(&attRefJoy_Mutex);
		}
		else if(localCurrentState == POSITION_JOY_MODE){
			pthread_mutex_lock(&attRefPosControl_Mutex);
				RPY = Quat2RPY(Rot2quat(Rdes_PosControl));
			pthread_mutex_unlock(&attRefPosControl_Mutex);
			RPY_Ref.x = RPY(0);
			RPY_Ref.y = RPY(1);
			RPY_Ref.z = RPY(2);
		}
		else{
			RPY_Ref.x = 0;
			RPY_Ref.y = 0;
			RPY_Ref.z = 0;
		}

		pthread_mutex_lock(&posRefJoy_Mutex);
			PVA_PVARef.pos.position = PVA_RefJoy.pos.position;
	  	pthread_mutex_unlock(&posRefJoy_Mutex);

	  	//Get inputs for quadcopter
		pthread_mutex_lock(&Contr_Input_Mutex);
			controlInputs.force.x = 0;
			controlInputs.force.y = 0;
			controlInputs.force.z =  Contr_Input(0);
			controlInputs.torque.x = Contr_Input(1);
			controlInputs.torque.y = Contr_Input(2);
			controlInputs.torque.z = Contr_Input(3);
		pthread_mutex_unlock(&Contr_Input_Mutex);

	  	//Publish everything
	  	pthread_mutex_lock(&ROS_Mutex);
		    imurpy_pub.publish( &RPY_IMU);
		    Refrpy_pub.publish( &RPY_Ref);
		    imuWrench_pub.publish( &controlInputs);
		    PvaEst_pub.publish( &PVA_EstimatedPVA);
		    PvaRef_pub.publish ( &PVA_PVARef);
		    PvaVicon_pub.publish(&PVA_Vicon);
	    pthread_mutex_unlock(&ROS_Mutex);

  	}

  	printf("rosPublisherTask stopping...\n");
	threadCount -= 1;
	pthread_exit(NULL);
}

// //change red light to green after restart
// void set_pwm_mux_to_ap() {
//   // This function is intended to toggle the PWM mux on the MikiPilot AP Board (R2) to autopilot
//   // mode (green LED). Once done, the channel is turned back into an input to avoid contention
//   // if something is driving this GPIO. It is assumed that JP2 is populated (see page 5 of
//   // MikiPilot AP Board (R2) Schematics).
//   mc_overo.gpio_set_direction(overo::GPIO_147,overo::OUT);
//   mc_overo.gpio_set_value(overo::GPIO_147,overo::HIGH);
//   mc_overo.gpio_set_value(overo::GPIO_147,overo::LOW);
//   mc_overo.gpio_set_direction(overo::GPIO_147,overo::IN);
// }

void *Kalman_Timer(void *threadID){
	printf("Kalman_Timer has started!\n");
	int SamplingTime = 10;	//Sampling time in milliseconds
	int localCurrentState;

	//setup();

	while(1){
		WaitForEvent(e_Timeout,SamplingTime);

		//Check system state
		pthread_mutex_lock(&stateMachine_Mutex);
		localCurrentState = currentState;
		pthread_mutex_unlock(&stateMachine_Mutex);

		//check if system should be terminated
		if(localCurrentState == TERMINATE){
			break;
		}

		SetEvent(e_Kalman_Trigger);

	}

	printf("Kalman_Timer stopping...\n");
	threadCount -= 1;
	pthread_exit(NULL);
}

void *Kalman_Task(void *threadID){
	// int SamplingTime = 5;	//Sampling time in milliseconds
	int localCurrentState;

	Matrix<float, 3, 1> Zeros = Matrix<float, 3, 1>::Zero();

	ros::Time current_time = ros::Time(0,0);
	ros::Time prev_time = ros::Time(0,0);

	Eigen::Matrix<float, 12, 1> kalman_state = Eigen::Matrix<float, 12, 1>::Zero();
    Eigen::Matrix<float, 3, 1> z;   // measurement vector
    qcontrol_defs::PVA localPVA_quadVicon;
    Matrix<float, 3, 1> IMU_localData_Accel = Zeros;
    Matrix<float, 3, 1> prev_IMU_localData_Accel = Zeros;
    Matrix<float, 4, 1> IMU_localData_Quat;
    Matrix<float, 3, 3> Rbw;

    kalman_init(); //Initialize kalman filter

  	while(1){

		WaitForEvent(e_Kalman_Trigger,500);

		pthread_mutex_lock(&stateMachine_Mutex);
			localCurrentState = currentState;
		pthread_mutex_unlock(&stateMachine_Mutex);

		if(localCurrentState == TERMINATE){
			break;
		}

		kalman_state = kalman_propagate();

		//Check system state
		pthread_mutex_lock(&PVA_Vicon_Mutex);
			localPVA_quadVicon = PVA_quadVicon;
		pthread_mutex_unlock(&PVA_Vicon_Mutex);

		pthread_mutex_lock(&IMU_Mutex);
			IMU_localData_Accel = IMU_Data_Accel;
		pthread_mutex_unlock(&IMU_Mutex);

		//Check if there is a new measurement. If so, update estimation
		current_time = localPVA_quadVicon.t;

		if (prev_time.toSec() != current_time.toSec())
		{
			//Measurement vector z
			z <<  localPVA_quadVicon.pos.position.x,
			      localPVA_quadVicon.pos.position.y,
			      localPVA_quadVicon.pos.position.z;

			kalman_state = kalman_estimate_pos(z);
		}

		prev_time = current_time;

		if (prev_IMU_localData_Accel != IMU_localData_Accel)
		{
			//Get vehicle orientation
			IMU_localData_Quat(0) = localPVA_quadVicon.pos.orientation.w;
			IMU_localData_Quat(1) = localPVA_quadVicon.pos.orientation.x;
			IMU_localData_Quat(2) = localPVA_quadVicon.pos.orientation.y;
			IMU_localData_Quat(3) = localPVA_quadVicon.pos.orientation.z;

			Rbw = Quat2rot(IMU_localData_Quat);

			//Rotate acceleration into inertial frame
			IMU_localData_Accel = Rbw*IMU_localData_Accel;

			//Measurement vector z
			z <<  IMU_localData_Accel(0),
			      IMU_localData_Accel(1),
			      IMU_localData_Accel(2);

			kalman_state = kalman_estimate_acc(z);
		}

		prev_IMU_localData_Accel = IMU_localData_Accel;

		pthread_mutex_lock(&PVA_Kalman_Mutex);
			PVA_quadKalman.pos.position.x = kalman_state(0,0);
			PVA_quadKalman.pos.position.y = kalman_state(1,0);
			PVA_quadKalman.pos.position.z = kalman_state(2,0);
			PVA_quadKalman.vel.linear.x = kalman_state(3,0);
			PVA_quadKalman.vel.linear.y = kalman_state(4,0);
			PVA_quadKalman.vel.linear.z = kalman_state(5,0);
			PVA_quadKalman.acc.linear.x = kalman_state(6,0);
			PVA_quadKalman.acc.linear.y = kalman_state(7,0);
			PVA_quadKalman.acc.linear.z = kalman_state(8,0);
			PVA_quadKalman.pos.orientation = localPVA_quadVicon.pos.orientation;
		pthread_mutex_unlock(&PVA_Kalman_Mutex);
	  	// kalman_v << kalman_state(3,0) << "," << kalman_state(4,0) << "," << kalman_state(5,0) << "\n";
	  	// vicon_p << z(0,0) << "," << z(1,0) << "," << z(2,0) << "\n";
		//check if system should be terminated

  	}

	printf("Kalman_Task stopping...\n");
	threadCount -= 1;
	pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
	//handles for threads
	pthread_t keyboardThread;		//Handle for keyboard thread
	pthread_t Motor_ControlThread;
	pthread_t StateMachine_Thread;
	pthread_t AttControl_Thread;
	pthread_t AttControl_TimerThread;
	pthread_t PosControl_Thread;
	pthread_t PosControl_TimerThread;
	pthread_t IMU_Thread;			//handle for IMU thread
	pthread_t IMU_TimerThread;		//handle for IMU Timer thread
	pthread_t PCA_Thread;			//handle for PCA thread
	pthread_t PCA_TimerThread;		//handle for PCA Timer thread
	pthread_t MAG_Thread;			//handle for MAG thread
	pthread_t PrintThread;			//handle for Printing thread
	pthread_t rosSpinThread;
	pthread_t rosPublisherThread;
	pthread_t Kalman_Thread;
	pthread_t Kalman_TimerThread;
	pthread_t LoggerTrigger;
	pthread_t LoggerThread;
	//long IDthreadKeyboard, IDthreadIMU, IDthreadMAG; //Stores ID for threads
	int ReturnCode;

	// kalman_v.open ("kalman_velocity.txt");
	// vicon_p.open ("vicon_position.txt");

	//Check if number of arguments are correct
	printf("Number of arguments: %d\n",argc);
	if(argc != 2) {
	  _nh.logfatal("Incorrect number of arguments\n");
	  return -1;
	}
	else {
	  rosSrvrIp = argv[1];
	}

	//Start ROS handle
	_nh.initNode(rosSrvrIp);

	//Set initial reference
	attRefJoy(0) = 0; attRefJoy(1) = 0; attRefJoy(2) = 0;
	PVA_RefJoy.pos.position.x = 0;
	PVA_RefJoy.pos.position.y = 0;
	PVA_RefJoy.pos.position.z = 1;
	PVA_RefJoy.vel.linear.x = 0;
	PVA_RefJoy.vel.linear.y = 0;
	PVA_RefJoy.vel.linear.z = 0;

	//event that signalizes end of initialization
	e_endInit = CreateEvent(false,false);

	//switch source of yaw (vicon x imu)
	e_SwitchYawSource = CreateEvent(true,false);

	//Keyboard Events for printing information
	e_Key1 = CreateEvent(true,false); 			//manual-reset event
	e_Key2 = CreateEvent(true,false); 			//manual-reset event
	e_Key3 = CreateEvent(true,false);           //manual-reset event
	e_Key4 = CreateEvent(true,false);           //manual-reset event
	e_Key5 = CreateEvent(true,false);           //manual-reset event
	e_Key6 = CreateEvent(true,false);           //manual-reset event
	e_Key7 = CreateEvent(true,false);           //manual-reset event
	e_Key8 = CreateEvent(true,false);           //manual-reset event
	e_Key9 = CreateEvent(true,false);           //manual-reset event

	//Keyboard event for execution termination
	e_KeyESC = CreateEvent(true,false); 		//abort manual-reset event

	//Joystick events for changing flight modes
	e_buttonX = CreateEvent(true,false);
	e_buttonY = CreateEvent(true,false);
	e_buttonA = CreateEvent(true,false);
	e_buttonB = CreateEvent(true,false);
	// e_ButtonLB = CreateEvent(true,false);
	// e_ButtonRB = CreateEvent(true,false);

	//Events for changing thrust values
	e_Motor_Up = CreateEvent(false,false);      //auto-reset event
	e_Motor_Down = CreateEvent(false,false);    //auto-reset event
	e_Motor_Kill = CreateEvent(false,false);    //auto-reset event

	//Events that trigget threads
	e_Timeout = CreateEvent(false,false);		//timeout event (always false)
	e_IMU_trigger = CreateEvent(false,false); 	//auto-reset event
	e_PCA_trigger = CreateEvent(false,false); 	//auto-reset event
	e_AttControl_trigger = CreateEvent(false, false);  //auto-reset event
	e_PosControl_trigger = CreateEvent(false, false);  //auto-reset event
	e_Log_trigger = CreateEvent(false,false);
	e_Kalman_Trigger = CreateEvent(false,false);

	//Create mutexes
	pthread_mutex_init(&IMU_Mutex, NULL);
	pthread_mutex_init(&PCA_Mutex, NULL);
	pthread_mutex_init(&ThrustJoy_Mutex, NULL);
	pthread_mutex_init(&Contr_Input_Mutex, NULL);
	pthread_mutex_init(&PID_Mutex, NULL);
	pthread_mutex_init(&attRefJoy_Mutex, NULL);
	pthread_mutex_init(&stateMachine_Mutex, NULL);
	pthread_mutex_init(&PVA_Vicon_Mutex, NULL);
	pthread_mutex_init(&ROS_Mutex, NULL);
	pthread_mutex_init(&posRefJoy_Mutex, NULL);
	pthread_mutex_init(&ThrustPosControl_Mutex, NULL);
	pthread_mutex_init(&YawSource_Mutex, NULL);

	//Load PID parameters from file
	pthread_mutex_lock(&PID_Mutex);
		updatePar(&PID_att, &PID_angVel, &PID_pos,"configAtt.txt","configPos.txt");
		PrintVec3(PID_att.K_p, "PID_att Kp");
	    PrintVec3(PID_att.K_i, "PID_att Ki");
	    PrintVec3(PID_att.K_d, "PID_att Kd");
	    PrintVec3(PID_angVel.K_p, "PID_w Kp");
	    PrintVec3(PID_angVel.K_i, "PID_w Ki");
	    PrintVec3(PID_angVel.K_d, "PID_w Kd");
	    PrintVec3(PID_pos.K_p, "PID_pos Kp");
	    PrintVec3(PID_pos.K_i, "PID_pos Ki");
	    PrintVec3(PID_pos.K_d, "PID_pos Kd");
	pthread_mutex_unlock(&PID_Mutex);

	//Start keyboard task
	if (ReturnCode = pthread_create(&keyboardThread, NULL, KeyboardTask, NULL)){
		printf("Start KeyboardTask failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start rosSpin task
	if (ReturnCode = pthread_create(&rosSpinThread, NULL, rosSpinTask, NULL)){
		printf("Start rosSpin failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start ros publisher task
	if (ReturnCode = pthread_create(&rosPublisherThread, NULL, rosPublisherTask, NULL)){
		printf("Start rosPublisher failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start state StateMachineTask
	if (ReturnCode = pthread_create(&StateMachine_Thread, NULL, StateMachineTask, NULL)){
		printf("Start StateMachineTask failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start Attitude Control timer task
	if (ReturnCode = pthread_create(&AttControl_TimerThread, NULL, AttControl_Timer, NULL)){
		printf("Start Control_TimerTask failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start Attitude Control task
	if (ReturnCode = pthread_create(&AttControl_Thread, NULL, AttControl_Task, NULL)){
		printf("Start Control_Task failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
			threadCount += 1;

	//Start Position Control timer task
	if (ReturnCode = pthread_create(&PosControl_TimerThread, NULL, PosControl_Timer, NULL)){
		printf("Start PosControl_Timer failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start position Control task
	if (ReturnCode = pthread_create(&PosControl_Thread, NULL, PosControl_Task, NULL)){
		printf("Start PosControl_Task failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
			threadCount += 1;

	//Start keyboard control task
	if (ReturnCode = pthread_create(&Motor_ControlThread, NULL, Motor_KeyboardControl, NULL)){
		printf("Start Motor_ContorlTask failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start IMU task
	if (ReturnCode = pthread_create(&IMU_Thread, NULL, IMU_Task, NULL)){
		printf("Start IMU_Task failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start IMU timer task
	if (ReturnCode = pthread_create(&IMU_TimerThread, NULL, IMU_Timer, NULL)){
		printf("Start IMU_TimerTask failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start PCA task
	if (ReturnCode = pthread_create(&PCA_Thread, NULL, PCA_Task, NULL)){
		printf("Start PCA_Task failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start PCA timer task
	if (ReturnCode = pthread_create(&PCA_TimerThread, NULL, PCA_Timer, NULL)){
		printf("Start PCA_TimerTask failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start printing task
	if (ReturnCode = pthread_create(&PrintThread, NULL, PrintTask, NULL)){
		printf("Start PrintThread failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start kalman filter timer task
	if (ReturnCode = pthread_create(&Kalman_TimerThread, NULL, Kalman_Timer, NULL)){
		printf("Start Kalman_TimerThread failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	//Start kalman filter task
	if (ReturnCode = pthread_create(&Kalman_Thread, NULL, Kalman_Task, NULL)){
		printf("Start PrintThread failed; return code from pthread_create() is %d\n", ReturnCode);
		exit(-1);
	}
	else
		threadCount += 1;

	// //Start logger timer task
	// if (ReturnCode = pthread_create(&LoggerTrigger, NULL, Logger_Timer, NULL)){
	// 	printf("Start LoggerTrigger failed; return code from pthread_create() is %d\n", ReturnCode);
	// 	exit(-1);
	// }
	// else
	// 	threadCount += 1;

	// //Start logger task
	// if (ReturnCode = pthread_create(&LoggerThread, NULL, Log_Task, NULL)){
	// 	printf("Start LoggerThread failed; return code from pthread_create() is %d\n", ReturnCode);
	// 	exit(-1);
	// }
	// else
	// 	threadCount += 1;

	//This has to be removed from here and put somewhere that indicates configurating the vechicle has been done
	SetEvent(e_endInit);

	//Check every 500ms if all threads have returned
	while(1){
		WaitForEvent(e_Timeout,500);
		if(threadCount == 0)
			break;
	}

	printf("Closing program... \n");

	//Destroy events
	DestroyEvent(e_Key1);
	DestroyEvent(e_Key2);
	DestroyEvent(e_Key3);
	DestroyEvent(e_Key4);
	DestroyEvent(e_Key5);
	DestroyEvent(e_Key6);
	DestroyEvent(e_Key7);
	DestroyEvent(e_Key8);
	DestroyEvent(e_Key9);
	DestroyEvent(e_KeyESC);
	DestroyEvent(e_buttonX);
	DestroyEvent(e_buttonY);
	DestroyEvent(e_buttonA);
	DestroyEvent(e_buttonB);
	DestroyEvent(e_Motor_Up);
	DestroyEvent(e_Motor_Down);
	DestroyEvent(e_Motor_Kill);
	DestroyEvent(e_Timeout);
	DestroyEvent(e_IMU_trigger);
	DestroyEvent(e_PCA_trigger);
	DestroyEvent(e_AttControl_trigger);
	DestroyEvent(e_PosControl_trigger);
	DestroyEvent(e_endInit);
	DestroyEvent(e_SwitchYawSource);
	DestroyEvent(e_Log_trigger);
	DestroyEvent(e_Kalman_Trigger);

	//Destroy mutexes
	pthread_mutex_destroy(&IMU_Mutex);
	pthread_mutex_destroy(&PCA_Mutex);
	pthread_mutex_destroy(&ThrustJoy_Mutex);
	pthread_mutex_destroy(&Contr_Input_Mutex);
	pthread_mutex_destroy(&PID_Mutex);
	pthread_mutex_destroy(&attRefJoy_Mutex);
	pthread_mutex_destroy(&stateMachine_Mutex);
	pthread_mutex_destroy(&PVA_Vicon_Mutex);
	pthread_mutex_destroy(&ROS_Mutex);
	pthread_mutex_destroy(&posRefJoy_Mutex);
	pthread_mutex_destroy(&ThrustPosControl_Mutex);
	pthread_mutex_destroy(&YawSource_Mutex);

   /* Last thing that main() should do */
	// vicon_p.close();
	// kalman_v.close();
    pthread_exit(NULL);
}

max_stars_repo_name: khairulislam/phys

max_issues_repo_name: khairulislam/phys

max_forks_repo_name: khairulislam/phys


text: #include <boost/multiprecision/cpp_int/serialize.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// The MIT License
// (c) 2019 Daniel Williams

#ifndef _QUAD_TREE_HPP_
#define _QUAD_TREE_HPP_

#define QUAD_TREE_VERSION "0.0.1"

#include <cmath>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>

#include <Eigen/Geometry>

#include <nlohmann/json/json_fwd.hpp>

#include "geometry/cell_value.hpp"
#include "geometry/layout.hpp"
#include "geometry/sample.hpp"

#include "quadtree/node.hpp"

using std::unique_ptr;

using namespace terrain::geometry;

namespace terrain::quadtree {

/**
 * Datastructure: A point Quad Tree for representing 2D data. Each
 * region has the same ratio as the bounds for the tree.
 *
 * The implementation currently requires pre-determined bounds for data as it
 * can not rebalance itself to that degree.
 */
class Tree {
public:
    /**
     * Constructs a new quad tree, centered at 0,0 and 1024 units wide, square
     *
     * Use this constructor if the tree will be loaded from a config file, and the initialization values do not matter.
     */
    Tree();

    /**
     * Constructs a new quad tree.
     *
     * @param x, y coordinates of tree's center point.
     * @param tree width.  Tree is square. (i.e. height === width)
     */
    Tree(const Layout& _layout);

    /**
     *  Releases all memory associated with this quad tree.
     */
    ~Tree();

    static size_t calculate_complete_tree(const size_t height);

    /**
     * Returns true if the point at (x, y) exists in the tree.
     *
     * @param {double} x The x-coordinate.
     * @param {double} y The y-coordinate.
     * @return {bool} Whether the tree contains a point at (x, y).
     */
    bool contains(const Eigen::Vector2d& p) const;

    /**
     * retrieve the value of the requested point `p`.
     *
     * @param {double} x The x-coordinate.
     * @param {double} y The y-coordinate.
     * @param {cell_value_t} opt_default The default value to return if the node doesn't
     *                 exist.
     * @return {cell_value_t} The value of the node, if available; or the default value.
     */
    cell_value_t classify(const Eigen::Vector2d& p) const;

    /**
     * Draws a simple debug representation of this tree to the given
     * output stream.
     *
     */
    void debug_tree(const bool show_pointer=false) const;

    /**
     * Gets the value of the point at (x, y).  If the point is not close to the center of a node, this function interpolates or extrapolates an appropriate value.
     *
     * @param {double} x The x-coordinate.
     * @param {double} y The y-coordinate.
     * @return {cell_value_t} The resultant value
     */
    cell_value_t interp(const Eigen::Vector2d& at) const;

    ///! \brief sets all leaf nodes to the given value
    ///! \param fill_value - value to write
    void fill(const cell_value_t fill_value);

    cell_value_t operator()(const double x, const double y);

    ///! \brief Get the overall layout of this tree
    ///!
    ///! \return layout object describing the tree's overall bounds.
    ///!
    inline const Layout& get_layout() const { return layout; }

    size_t get_height() const;

    double get_load_factor() const;

    size_t get_memory_usage() const;

    /**
     * Loads the vector of points as a CCW polygon.
     *
     * @param {std::istream} input stream containing the serialization text
     */
    void load_polygon(const std::vector<Eigen::Vector2d>& source);

    /**
     * Loads a representation of a tree from the data source.  The the form source is assumed to
     * contain a serialization of a tree, as represented in valid json.  That is, in the same
     * format as Tree::serialize(...).
     *
     * @param tree - input json object containing a tree structure
     */
    bool load_tree(const nlohmann::json& tree);

    void prune();

    void reset();

    ///! \brief resets _the tree_ to fully populate the bounds at the given precision
    ///!
    ///! \param bounds - new bounds to describe
    ///! \param precision - describe the bounds to at least this precision
    void reset(const Layout& new_layout);

    ///! \brief Classify what value the requested point `p` has.
    ///!
    ///! This method is designed for use with an interpolation algorithm.
    ///!
    ///! \param location to sample near
    ///! @return the point-value-pair _actually_ contained in the tree.
    Sample sample(const Eigen::Vector2d& p) const;

    size_t size() const;

    ///! \brief store a value in the tree, at point `p`
    ///!
    ///! This is the primary method to populate a useable tree.
    ///!
    ///! \param p - the x,y coordinates to write to
    ///! \param new_value - the value to write at point 'p'
    ///! \return success - fails if out-of-bounds.
    bool store(const Eigen::Vector2d& p, const cell_value_t new_value);

    ///! \brief generates a json structure, describing the tree itself
    nlohmann::json to_json_tree() const;

    bool write_png(const std::string filename) const;

private:
    ///! the data layout this tree represents
    geometry::Layout layout;

    unique_ptr<terrain::quadtree::Node> root;

private:
    friend class QuadTreeTest_ConstructDefault_Test;
    friend class QuadTreeTest_LoadValidTree_Test;
    friend class QuadTreeTest_CalculateLoadFactor_Test;
    friend class QuadTreeTest_LoadGridFromJSON_Test;
    friend class QuadTreeTest_WriteLoadCycle_Test;
    friend class QuadTreeTest_SearchExplicitTree_Test;
    friend class QuadTreeTest_InterpolateTree_Test;

};
} // namespace terrain::quadtree

#endif // _QUADTREE_QUAD_TREE_HPP_

max_stars_repo_name: teyrana/quadtree

max_issues_repo_name: teyrana/quadtree

max_forks_repo_name: teyrana/quadtree


text:
/*
  Copyright (c) 2020, Robin Zimmeck <robin@robin-zimmeck.de>

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

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

  2. 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.

  3. Neither the name of the copyright holder nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

  This software is provided by the copyright holders and contributors "as is"
  and any express or implied warranties, including, but not limited to, the
  implied warranties of merchantability and fitness for a particular purpose are
  disclaimed. In no event shall the copyright 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.
*/

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include "minisi/math.h"
#include "minisi/io.h"

using namespace minisi;

BOOST_AUTO_TEST_CASE(basic_operations_test)
{
  BOOST_CHECK_EQUAL(abs(5.0 * metre), 5.0 * metre);
  BOOST_CHECK_EQUAL(abs(-5.0 * metre), 5.0 * metre);

  BOOST_CHECK_EQUAL(fmod(8.5 * second, 1.0 * second), 0.5);

  BOOST_CHECK_EQUAL(remainder(8.5 * second, 1.0 * second), 0.5);

  BOOST_CHECK_EQUAL(fma(1.0 * metre, 2.0 / second, 3.0 * metre / second), 5.0 * metre / second);
}

BOOST_AUTO_TEST_CASE(power_functions_test)
{
  BOOST_CHECK_EQUAL(pow<2>(2.0 * metre), 4.0 * metre * metre);
  BOOST_CHECK_EQUAL((pow<1, 2>(4.0 * metre * metre)), (2.0 * metre));
  BOOST_CHECK_EQUAL(sqrt(4.0 * metre * metre), 2.0 * metre);
  BOOST_CHECK_EQUAL(cbrt(8.0 * metre * metre * metre), 2.0 * metre);
  BOOST_CHECK_EQUAL(hypot(3.0 * metre, 4.0 * metre), 5.0 * metre);
  BOOST_CHECK_EQUAL(hypot(3.0 * metre, 4.0 * metre, 12.0 * metre), 13.0 * metre);
}

BOOST_AUTO_TEST_CASE(rouding_functions_test)
{
  BOOST_CHECK_EQUAL(ceil(3.2 * metre), 4.0 * metre);
  BOOST_CHECK_EQUAL(floor(3.8 * metre), 3.0 * metre);
  BOOST_CHECK_EQUAL(trunc(3.8 * metre), 3.0 * metre);
  BOOST_CHECK_EQUAL(round(3.5 * metre), 4.0 * metre);
  BOOST_CHECK_EQUAL(nearbyint(3.9 * metre), 4.0 * metre);
  BOOST_CHECK_EQUAL(rint(3.9 * metre), 4.0 * metre);
  BOOST_CHECK_EQUAL(nextafter(1.0 * metre, 2.0 * metre), std::nextafter(1.0, 2.0) * metre);
  BOOST_CHECK_EQUAL(copysign(2.0 * metre, -0.1 * metre), -2.0 * metre);
}

BOOST_AUTO_TEST_CASE(classification_test)
{
  BOOST_CHECK_EQUAL(isfinite(42.0 * metre), true);
  BOOST_CHECK_EQUAL(isfinite(std::numeric_limits<double>::quiet_NaN() * metre), false);

  BOOST_CHECK_EQUAL(isinf(42.0 * metre), false);
  BOOST_CHECK_EQUAL(isinf(std::numeric_limits<double>::infinity() * metre), true);

  BOOST_CHECK_EQUAL(isnan(42.0 * metre), false);
  BOOST_CHECK_EQUAL(isnan(std::numeric_limits<double>::quiet_NaN() * metre), true);

  BOOST_CHECK_EQUAL(isnormal(1.0 * metre), true);
}

max_stars_repo_name: jhunold/minisi

max_issues_repo_name: jhunold/minisi

max_forks_repo_name: jhunold/minisi


text:
/*!
	\file ConvergenceGenerator.cpp
	\author Andrew Kerr <arkerr@gatech.edu>
	\brief identifies warp-synchronous blocks
*/

// C++ includes
#include <iostream>
#include <fstream>

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

// Ocelot includes
#include <traces/interface/ConvergenceGenerator.h>
#include <traces/interface/TraceConfiguration.h>
#include <ocelot/trace/interface/TraceEvent.h>
#include <ocelot/executive/interface/EmulatedKernel.h>
#include <ocelot/ir/interface/Module.h>

// Hydrazine includes
#include <hydrazine/interface/debug.h>
#include <hydrazine/interface/string.h>

// Debugging messages
#ifdef REPORT_BASE
#undef REPORT_BASE
#endif

#define REPORT_BASE 0
#define REPORT_KERNEL_INSTRUCTIONS 0

//////////////////////////////////////////////////////////////////////////////////////////////////

unsigned int trace::ConvergenceGenerator::_counter = 0;

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::ConvergenceGenerator::Counter::Counter():
	hasSync(false),
	threads(0),
	dynInstructions(0),
	warpInstructions(0)
{

}

//////////////////////////////////////////////////////////////////////////////////////////////////

trace::ConvergenceGenerator::ConvergenceGenerator() {

}

trace::ConvergenceGenerator::~ConvergenceGenerator() {

}

//////////////////////////////////////////////////////////////////////////////////////////////////

void trace::ConvergenceGenerator::initialize(const executive::ExecutableKernel &kernel) {

	const executive::EmulatedKernel & emuKernel =
		static_cast<const executive::EmulatedKernel &>(kernel);

	//
	// initialize kernel header
	//
	_entry.name = kernel.name;
	_entry.module = kernel.module->path();
	_entry.format = TraceGenerator::ConvergenceTraceFormat;
	_entry.path = "";
	_entry.header = "";
	_entry.program = "";
	_entry.gridDim = kernel.gridDim();
	_entry.blockDim = kernel.blockDim();
		std::string name = kernel.name;

	if( name.size() > 20 ) {
		name.resize( 20 );
	}

	std::stringstream stream;
	stream << _entry.format << "_" << trace::ConvergenceGenerator::_counter++;

	boost::filesystem::path path( database );
	path = path.parent_path();
	path /= _entry.program + "_" + name + "_" + stream.str() + ".json";
	path = boost::filesystem::system_complete( path );

	_entry.header = path.string();

	this->kernel = (& emuKernel);
	analyzeKernel(emuKernel);
}

//! \brief visits each basic block and initializes a counter for each block
void trace::ConvergenceGenerator::analyzeKernel(const executive::EmulatedKernel &kernel) {
	ir::ControlFlowGraph *cfg = const_cast<ir::ControlFlowGraph *>(kernel.cfg());
	ir::ControlFlowGraph::BlockPointerVector blocks = cfg->executable_sequence();
	ir::ControlFlowGraph::BlockPointerVector::iterator bb_it;
	for (bb_it = blocks.begin(); bb_it != blocks.end(); ++bb_it) {
		Counter counter;
		counter.threads = _entry.blockDim.x * _entry.blockDim.y * _entry.blockDim.z;
		ir::ControlFlowGraph::BasicBlock::InstructionList::const_iterator inst_it =
			(*bb_it)->instructions.begin();
		for (; inst_it != (*bb_it)->instructions.end(); ++inst_it) {
			const ir::Instruction *inst = (*inst_it);
			if (inst && inst->ISA == ir::Instruction::PTX &&
				static_cast<const ir::PTXInstruction *>(inst)->opcode == ir::PTXInstruction::Bar) {
				counter.hasSync = true;
				break;
			}
		}
		counterMap[(*bb_it)->label()] = counter;
	}

	Counter counter;
	counter.threads = _entry.blockDim.x * _entry.blockDim.y * _entry.blockDim.z;
	counterMap["entry"] = counter;
}

//////////////////////////////////////////////////////////////////////////////////////////////////

std::ostream & operator<<(std::ostream &out, const trace::ConvergenceGenerator::Counter &counter) {

	size_t ideal = (counter.warpInstructions * counter.threads);
	double activity = (ideal ? (double)counter.dynInstructions / (double)ideal : 0.0);
	out << " | dynamic instructions: " << counter.dynInstructions
		<< " | warp instructions: " << counter.warpInstructions
		<< " | activity: " << activity;

	return out;
}

//////////////////////////////////////////////////////////////////////////////////////////////////

class ConvergenceFormatter : public ir::ControlFlowGraph::BasicBlock::DotFormatter {
public:
	ConvergenceFormatter(trace::ConvergenceGenerator * gen): generator(gen) {
		for (std::map< int, std::string >::const_iterator bl_it = generator->kernel->basicBlockPC.begin();
			bl_it != generator->kernel->basicBlockPC.end(); ++bl_it) {

			blocksToPC[bl_it->second] = bl_it->first;
		}
	}

	/*!

	*/
	virtual std::string entryLabel(const ir::ControlFlowGraph::BasicBlock *block) {
		std::stringstream out;
		out << "[shape=record,style=\"bold,filled\",fillcolor=\"#4444cc\",";
		out << "label=";
		out << "\"{ ENTRY: " << hydrazine::toGraphVizParsableLabel(generator->kernel->name);

		if (generator->counterMap.find(block->label()) != generator->counterMap.end()) {

			const trace::ConvergenceGenerator::Counter &
				counter = generator->counterMap[block->label()];

			size_t ideal = (counter.warpInstructions * counter.threads);
			double activity = (ideal ? (double)counter.dynInstructions / (double)ideal : 0.0);
			out << " | blocks: " << generator->_entry.gridDim.x * generator->_entry.gridDim.y * generator->_entry.gridDim.z;
			out << " | threads: " << counter.threads;
			out << " | aggregate dynamic instructions: " << counter.dynInstructions
				<< " | aggregate warp instructions: " << counter.warpInstructions
				<< " | average activity: " << activity;
		}

		out << "}\"]";
		return out.str();
	}

	/*!
		\brief prints string representation of
	*/
	virtual std::string toString(const ir::ControlFlowGraph::BasicBlock *block) {
		std::stringstream out;

		bool convergent = false;
		bool sync = false;
		out << "[shape=record,";

		out << "label=";
		out << "\"{" << hydrazine::toGraphVizParsableLabel(block->label());

		if (generator->counterMap.find(block->label()) != generator->counterMap.end()) {

			const trace::ConvergenceGenerator::Counter &
				counter = generator->counterMap[block->label()];

			if (blocksToPC.find(block->label()) != blocksToPC.end()) {
				out << " | near " << generator->kernel->location(blocksToPC[block->label()]);
			}

			out << counter;

			if (counter.dynInstructions == counter.warpInstructions * counter.threads) {
				convergent = true;
				out << " | *** convergent *** ";
			}
			if (counter.hasSync) {
				sync = true;
				out << " | *** bar.sync *** ";
			}
		}

		out << "}\"";

		if (convergent && !sync) {
			out << ",style=\"filled\",fillcolor=\"#ff0000\"";
		}
		else if (sync && !convergent) {
			out << ",style=\"filled\",fillcolor=\"#0000ff\"";
		}
		else if (convergent && sync) {
			out << ",style=\"filled\",fillcolor=\"#ff00ff\"";
		}

		out << "]";

		return out.str();
	}

public:

	std::map< std::string, int > blocksToPC;

	trace::ConvergenceGenerator *generator;

};

//! \brief writes a DOT-format CFG to an output stream
void trace::ConvergenceGenerator::writeCFG() {

	ConvergenceFormatter formatter(this);

	std::stringstream ss;

	boost::filesystem::path path( database );
	path = path.parent_path();
	path = boost::filesystem::system_complete( path );
	ss << path.string() << "/" << _entry.program << "_" << _entry.name << "."
		<< _counter << ".convergence.dot";

	std::string filename = ss.str();

	ir::ControlFlowGraph *controlFlowGraph = const_cast<ir::ControlFlowGraph*>(kernel->cfg());
	std::ofstream cfgFile(filename.c_str());
	cfgFile << "/*\n";
	cfgFile << "     kernel: " << kernel->name << "\n";
	cfgFile << "*/\n";

	controlFlowGraph->write(cfgFile, formatter);
	cfgFile.close();

	if (TraceConfiguration::Singleton.convergence.render) {
		std::stringstream ss;
		ss << "dot -Tpdf -o " << path.string() << "/" << _entry.program << "_" << _entry.name << "." << _counter
			<< ".convergence.pdf " << filename;
		if (system(ss.str().c_str()) != 0) {
			report("system(" << ss.str() << ") failed");
		}
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////

//! \brief aggregates statistics and emits kernel results
void trace::ConvergenceGenerator::finish() {

	// aggregate entry statistics
	for (OperationCounterMap::const_iterator op_it = counterMap.begin();
		op_it != counterMap.end(); ++op_it) {

		if (op_it->first != "entry" && op_it->first != "exit") {
			counterMap["entry"] += op_it->second;
		}
	}

	boost::filesystem::path path( database );
	path = path.parent_path();
	path = boost::filesystem::system_complete( path );

	std::fstream resultFile(
		TraceConfiguration::Singleton.convergence.logfile.c_str(),
		std::ios_base::out | std::ios_base::app);

	write(resultFile);

	if (TraceConfiguration::Singleton.convergence.dot) {
		writeCFG();
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////

void trace::ConvergenceGenerator::event(const trace::TraceEvent &event) {
	std::string bbLabel = kernel->getInstructionBlock(event.PC);
	if (bbLabel == "") {
		report("event.PC = " << event.PC << " does not correspond to a BB");
		return;  // PC doesn't correspond to a basic block
	}

	OperationCounterMap::iterator op = counterMap.find(bbLabel);
	if (op == counterMap.end()) {
		report(" counter not found ");
		return;  // counter not found
	}

	op->second.dynInstructions += event.active.count();
	op->second.warpInstructions ++;
}

//////////////////////////////////////////////////////////////////////////////////////////////////

void trace::ConvergenceGenerator::write(std::fstream &out) {
	// invocation #, kernel, blocks, threads, block-label, dyn-instructions, warp instructions, activity, convergent (0, 1), sync (0, 1)
	const char *delimiter = ",";

	size_t blockCount = _entry.gridDim.x * _entry.gridDim.y;
	size_t threadCount = _entry.blockDim.x * _entry.blockDim.y * _entry.blockDim.z;

	OperationCounterMap::const_iterator op = counterMap.begin();
	for (; op != counterMap.end(); ++op) {

	size_t ideal = (op->second.warpInstructions * op->second.threads);
	double activity = (ideal ? (double)op->second.dynInstructions / (double)ideal : 0.0);
		out
			<< _counter << delimiter
			<< kernel->name << delimiter
			<< blockCount << delimiter
			<< threadCount << delimiter
			<< op->first << delimiter
			<< op->second.dynInstructions << delimiter
			<< op->second.warpInstructions << delimiter
			<< activity << delimiter
			<< (op->second.warpInstructions * threadCount == op->second.dynInstructions ? 1 : 0)
			<< (op->second.hasSync ? 1 : 0)
			<< std::endl;
	}
}

//////////////////////////////////////////////////////////////////////////////////////////////////

max_stars_repo_name: florianjacob/gpuocelot

max_issues_repo_name: mprevot/gpuocelot

max_forks_repo_name: mprevot/gpuocelot


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#include "fboss/agent/hw/sai/api/MplsApi.h"

#include <boost/functional/hash.hpp>
#include "fboss/agent/Constants.h"

namespace std {
size_t hash<facebook::fboss::SaiInSegTraits::InSegEntry>::operator()(
    const facebook::fboss::SaiInSegTraits::InSegEntry& entry) const {
  size_t seed = 0;
  boost::hash_combine(seed, entry.switchId());
  boost::hash_combine(seed, entry.label());
  return seed;
}
} // namespace std

namespace facebook::fboss {

std::string SaiInSegTraits::InSegEntry::toString() const {
  return folly::to<std::string>(
      "InSegEntry(switch:", switchId(), ", label: ", label());
}
folly::dynamic SaiInSegTraits::InSegEntry::toFollyDynamic() const {
  folly::dynamic json = folly::dynamic::object;
  json[kSwitchId] = switchId();
  json[kLabel] = label();
  return json;
}

SaiInSegTraits::InSegEntry SaiInSegTraits::InSegEntry::fromFollyDynamic(
    const folly::dynamic& json) {
  sai_object_id_t switchId = json[kSwitchId].asInt();
  auto label = json[kLabel].asInt();
  return InSegEntry(switchId, label);
}
} // namespace facebook::fboss

max_stars_repo_name: nathanawmk/fboss

max_issues_repo_name: nathanawmk/fboss

max_forks_repo_name: nathanawmk/fboss


text:
// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff/
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Tobias Leibner

#ifndef DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH
#define DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH

#include <cmath>
#include <limits>
#include <type_traits>

#include <boost/numeric/conversion/cast.hpp>

#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>

namespace Dune {
namespace Stuff {
namespace LA {

enum class ChooseBackend
{
  common_dense,
  istl_sparse,
  eigen_dense,
  eigen_sparse,
  none
}; // enum class ChooseBackend

static constexpr ChooseBackend default_backend =
#if HAVE_EIGEN
    ChooseBackend::eigen_sparse;
#elif HAVE_DUNE_ISTL
    ChooseBackend::istl_sparse;
#else
    ChooseBackend::common_dense;
#endif

static constexpr ChooseBackend default_sparse_backend =
#if HAVE_EIGEN
    ChooseBackend::eigen_sparse;
#elif HAVE_DUNE_ISTL
    ChooseBackend::istl_sparse;
#else
    ChooseBackend::none;
#endif

static constexpr ChooseBackend default_dense_backend =
#if HAVE_EIGEN
    ChooseBackend::eigen_dense;
#else
    ChooseBackend::common_dense;
#endif

/**
 *  \brief  Contains tags mostly needed for python bindings.
 */
namespace Tags {

class ContainerInterface
{
};
class ProvidesDataAccess
{
};

} // namespace Tags
namespace internal {

/**
 * \brief Tries a boost::numeric_cast and throws an Exceptions::wrong_input_given on failure.
 *
 *        This can be used in the ctor initializer list.
 */
template <class Out, class In>
static Out boost_numeric_cast(const In& in)
{
  try {
    return boost::numeric_cast<Out>(in);
  } catch (boost::bad_numeric_cast& ee) {
    DUNE_THROW(Exceptions::wrong_input_given,
               "There was an error in boost converting '" << in << "' to '" << Common::Typename<Out>::value() << "': "
                                                          << ee.what());
  }
} // ... boost_numeric_cast(...)

} // namespace internal

template <class Traits>
class ProvidesBackend : public CRTPInterface<ProvidesBackend<Traits>, Traits>
{
public:
  typedef typename Traits::BackendType BackendType;

  inline BackendType& backend()
  {
    CHECK_CRTP(this->as_imp().backend());
    return this->as_imp().backend();
  }

  inline const BackendType& backend() const
  {
    CHECK_CRTP(this->as_imp().backend());
    return this->as_imp().backend();
  }
}; // class ProvidesBackend

/**
 * \brief Interface for all containers (vectors and matrices).
 *
 * \note  All derived classes are supposed to implement copy-on-write. This can be achieved by internally holding a
 *        shared_prt to the appropriate backend and by passing this shared_prt around on copy, move or assingment. Any
 *        class method that writes to the backend or exposes a reference to the backend is then required to make a deep
 *        copy of the backend, if it is not the sole owner of this resource. This can for instance be achieved by
 *        calling a private method:
\code
  inline void ensure_uniqueness() const
  {
    if (!backend_.unique())
      backend_ = std::make_shared< BackendType >(*backend_);
  }
\endcode
 */
template <class Traits, class ScalarImp = typename Traits::ScalarType>
class ContainerInterface : public Tags::ContainerInterface,
                           public CRTPInterface<ContainerInterface<Traits, ScalarImp>, Traits>
{
  typedef CRTPInterface<ContainerInterface<Traits, ScalarImp>, Traits> CRTP;
  static_assert(std::is_same<ScalarImp, typename Traits::ScalarType>::value, "");

public:
  typedef ScalarImp ScalarType;
  typedef typename Traits::RealType RealType;

  using typename CRTP::derived_type;

  virtual ~ContainerInterface() {}

  /// \name Have to be implemented by a derived class!
  /// \{

  /**
   * \brief   Creates a (deep) copy of the underlying resource
   * \return  A new container
   */
  inline derived_type copy() const
  {
    CHECK_CRTP(this->as_imp().copy());
    return this->as_imp().copy();
  }

  /**
   * \brief BLAS SCAL operation (in-place sclar multiplication).
   * \param alpha The scalar coefficient with which each element of the container is multiplied.
   */
  inline void scal(const ScalarType& alpha) { CHECK_AND_CALL_CRTP(this->as_imp().scal(alpha)); }

  /**
   * \brief BLAS AXPY operation.
   * \param alpha The scalar coefficient with which each element of the container is multiplied
   * \param xx    Container that is to be elementwise added.
   */
  inline void axpy(const ScalarType& alpha, const derived_type& xx)
  {
    CHECK_AND_CALL_CRTP(this->as_imp().axpy(alpha, xx));
  }

  /**
   * \brief Test for equal sizes.
   * \param other Container the sizes of which this is to be compared to.
   */
  inline bool has_equal_shape(const derived_type& other) const
  {
    CHECK_CRTP(this->as_imp().has_equal_shape(other));
    return this->as_imp().has_equal_shape(other);
  }

  /// \}
  /// \name Are provided by the interface for convenience!
  /// \note Those marked as virtual may be implemented more efficiently in a derived class!
  /// \{

  static std::string type_this() { return Common::Typename<derived_type>::value(); }

  virtual derived_type& operator*=(const ScalarType& alpha)
  {
    scal(alpha);
    return this->as_imp();
  }
  /// \}
}; // class ContainerInterface

namespace internal {

template <class C>
struct is_container_helper
{
  DSC_has_typedef_initialize_once(Traits) DSC_has_typedef_initialize_once(ScalarType)

      static const bool is_candidate = DSC_has_typedef(Traits)<C>::value && DSC_has_typedef(ScalarType)<C>::value;
}; // class is_container_helper

} // namespace internal

template <class C, bool candidate = internal::is_container_helper<C>::is_candidate>
struct is_container : public std::is_base_of<ContainerInterface<typename C::Traits, typename C::ScalarType>, C>
{
};

template <class C>
struct is_container<C, false> : public std::false_type
{
};

template <class Traits>
class ProvidesConstContainer : public CRTPInterface<ProvidesConstContainer<Traits>, Traits>
{
public:
  typedef typename Traits::ContainerType ContainerType;

  inline std::shared_ptr<const ContainerType> container() const
  {
    CHECK_CRTP(this->as_imp().container());
    return this->as_imp().container();
  }
}; // class ProvidesConstContainer

template <class Traits>
class ProvidesContainer : public ProvidesConstContainer<Traits>
{
  typedef ProvidesConstContainer<Traits> BaseType;

public:
  typedef typename Traits::ContainerType ContainerType;

  using BaseType::container;

  inline std::shared_ptr<ContainerType> container()
  {
    CHECK_CRTP(this->as_imp().container());
    return this->as_imp().container();
  }
}; // class ProvidesContainer

template <class Traits>
class ProvidesDataAccess : public CRTPInterface<ProvidesDataAccess<Traits>, Traits>, public Tags::ProvidesDataAccess
{
public:
  typedef typename Traits::ScalarType ScalarType;

  inline ScalarType* data()
  {
    CHECK_CRTP(this->as_imp().data());
    return this->as_imp().data();
  }
}; // class ProvidesDataAccess

} // namespace LA
} // namespace Stuff
} // namespace Dune

#endif // #ifndef DUNE_STUFF_LA_CONTAINER_CONTAINER_INTERFACE_HH

ext: hh

max_stars_repo_name: ftalbrecht/dune-stuff-simplified

max_issues_repo_name: ftalbrecht/dune-stuff-simplified

max_forks_repo_name: ftalbrecht/dune-stuff-simplified