text:
/**********************************************************************
*  Copyright (c) 2008-2014, Alliance for Sustainable Energy.
*  All rights reserved.
*
*  This library is free software; you can redistribute it and/or
*  modify it under the terms of the GNU Lesser General Public
*  License as published by the Free Software Foundation; either
*  version 2.1 of the License, or (at your option) any later version.
*
*  This library 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
*  Lesser General Public License for more details.
*
*  You should have received a copy of the GNU Lesser General Public
*  License along with this library; if not, write to the Free Software
*  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
**********************************************************************/

#include "Comments.hpp"
#include "CommentRegex.hpp"

#include <boost/algorithm/string.hpp>

#include <sstream>

namespace openstudio {

namespace detail {

  std::string makeCommentHelper(const std::string& str,
                                const std::string& linePrefix,
                                int indentSize)
  {
    // istream for parsing, ostream for composing comment
    std::stringstream ss(str), comment;

    // helper variables
    boost::smatch m;
    std::string line;
    bool first = true;
    bool commentStarted = false;
    unsigned blankLineQueue = 0; // add blank lines in groups

    // parse and compose comment line-by-line
    while (std::getline(ss,line)) {
      // capture comment already marked as such
      if (boost::regex_match(line,m,commentRegex::editorCommentWhitespaceOnlyLine())) {
        line = std::string(m[1].first,m[1].second);
      }
      if (boost::regex_match(line,m,commentRegex::commentWhitespaceOnlyLine())) {
        line = std::string(m[1].first,m[1].second);
      }
      // handle blank lines separately
      if (boost::regex_match(line,commentRegex::whitespaceOnlyLine())) {
        if (commentStarted) { ++blankLineQueue; } // may need to prepend with linePrefix
        else {
          // no comment yet--leave as pure blank line
          if (!first) { comment << std::endl; }
        }
      }
      else {
        // line has non-whitespace characters. prepend each queued blank line with linePrefix
        for (unsigned i = 0; i < blankLineQueue; ++i) {
          comment << std::endl << linePrefix;
        }
        blankLineQueue = 0;

        // align lefthand edge if not indented by at least indentSize
        std::string temp = boost::trim_left_copy(line);
        if (temp.size() > line.size() - indentSize) { line = temp; }
        // go to next line if this is not the first line
        if (!first) { comment << std::endl; }
        // write out comment line
        comment << linePrefix << line;
        commentStarted = true;
      }
      first = false;
    }

    // write out remaining blank lines w/o commenting them
    for (unsigned i = 0; i < blankLineQueue; ++i) {
      comment << std::endl;
    }

    // append std::endl if str ends with \n or \r
    if (!str.empty()) {
      boost::regex re("[\\n\\r]");
      if (boost::regex_match(str.end()-1,str.end(),re)) {
        comment << std::endl;
      }
    }

    return comment.str();

  }

} // detail

std::string makeComment(const std::string& str) {

  // make sure each line starts with !
  boost::smatch m;
  if (boost::regex_match(str,m,commentRegex::commentWhitespaceOnlyBlock())) {
    // already does, return as-is
    return str;
  }

  // prepend '! ' to each line, as needed
  return detail::makeCommentHelper(str,"! ",2);
}

std::string makeIdfEditorComment(const std::string& str) {
  // make sure each line starts with !-
  boost::smatch m;
  if (boost::regex_match(str,m,commentRegex::editorCommentWhitespaceOnlyBlock())) {
    // already does, return as-is
    return str;
  }

  // prepend '!- ' to each line, as needed
  return detail::makeCommentHelper(str,"!- ",2);
}

} // openstudio


text:
#include "planner.h"
#include <iostream>
#include <queue>
#include "node.h"
#include <unordered_set>
#include <fstream>
#include <omp.h>
#include <chrono>
#include <mutex>

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

Planner::Planner()
{
    std::cout << "Created Planner" << std::endl;
    std::cout << "Using Boost "
              << BOOST_VERSION / 100000 << "."     // major version
              << BOOST_VERSION / 100 % 1000 << "." // minor version
              << BOOST_VERSION % 100               // patch level
              << std::endl;
    // this->graph_ = NULL;
    this->numSamples_ = 0;
    srand(time(0));
    this->dist_threshold_ = 25.0;
}

Planner::Planner(Map *map)
{
    std::cout << "Created Planner with Map" << std::endl;
    this->setMap(map);
}

Planner::~Planner()
{
    // if (this->graph_ != NULL)
    // {
    //     delete this->graph_;
    // }
    std::cout << "Destroyed Planner" << std::endl;

}

void Planner::setNumSamples(int numSamples)
{
    this->numSamples_ = numSamples;
}

void Planner::printGraph()
{
    for (auto vd : boost::make_iterator_range(vertices(this->graph_)))
    {
        std::cout << "Vertex: " << this->graph_[vd].x << "," << this->graph_[vd].y << std::endl;
    }

    for (auto ed : boost::make_iterator_range(edges(this->graph_)))
    {
        std::cout << "Edge: " << source(ed, this->graph_) << "," << target(ed, this->graph_) << std::endl;
    }
}

void Planner::printPath()
{
    std::cout << "PATH: " << std::endl;
    for (auto v : this->path_)
    {
        std::cout << "(" << v[0] << "," << v[1] << ")" << std::endl;
    }
    std::cout << std::endl;
}

int Planner::getPathLength()
{
    return this->path_.size();
}

int Planner::getPathDistance()
{
    int distance = 0;

    // reutrn 0 if path is empty
    if (this->path_.size() == 0)
    {
        return 0;
    }

    // loop over the path and use the distance between each node to calculate the total distance
    for (size_t i = 0; i < this->path_.size() - 1; i++)
    {
        // get the current point x and y
        int x1 = this->path_[i][0];
        int y1 = this->path_[i][1];

        // get the next point x and y
        int x2 = this->path_[i + 1][0];
        int y2 = this->path_[i + 1][1];

        // calculate the distance between the two points
        distance += this->map_->getDistance(x1, y1, x2, y2);
    }

    return distance;
}

// get timing information for connection, generation, and query
double Planner::getConnectionTime()
{
    return this->connection_time_;
}

double Planner::getGenerationTime()
{
    return this->generation_time_;
}

double Planner::getQueryTime()
{
    return this->query_time_;
}

// save path to file
void Planner::savePathToFile(std::string filename)
{
    std::ofstream outfile;
    outfile.open(filename);
    for (auto v : this->path_)
    {
        outfile << "(" << v[0] << "," << v[1] << ")" << std::endl;
    }
    outfile.close();
}

// set start state
void Planner::setStartState(std::vector<int> start)
{
    this->start_ = start;
}

// set goal state
void Planner::setGoalState(std::vector<int> goal)
{
    this->goal_ = goal;
}

int Planner::plan(int numThreads)
{
    // Set the number of threads for the parallel region
    omp_set_num_threads(numThreads);
    std::cout << "Planning" << std::endl;

    // clear the path
    this->path_.clear();

    // time generation phase
    auto start = std::chrono::high_resolution_clock::now();
    if (this->generationPhase(numThreads) != 0)
    {
        std::cout << "Generation failed" << std::endl;
        return -1;
    }
    auto end = std::chrono::high_resolution_clock::now();
    // save the time it took to generate the graph
    this->generation_time_ = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
    std::cout << "Generation time: " << this->generation_time_ << "ns" << std::endl;

    // time connection phase
    start = std::chrono::high_resolution_clock::now();
    if (this->connectionPhase() != 0)
    {
        std::cout << "Connection failed" << std::endl;
        return -1;
    }
    end = std::chrono::high_resolution_clock::now();
    // save the time it took to connect the graph
    this->connection_time_ = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
    std::cout << "Connection time: " << this->connection_time_ << "ns" << std::endl;

    // time query phase
    start = std::chrono::high_resolution_clock::now();
    if (this->queryPhase(numThreads) != 0)
    {
        std::cout << "Query failed" << std::endl;
        return -1;
    }
    end = std::chrono::high_resolution_clock::now();
    // save the time it took to query the graph
    this->query_time_ = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
    std::cout << "Query time: " << this->query_time_ << "ns" << std::endl;

    return 0;
}

void Planner::setMap(Map *map)
{
    this->map_ = map;
}

int Planner::generationPhase(int numThreads)
{
    if (this->numSamples_ == 0)
    {
        std::cout << "numSamples is 0" << std::endl;
        return -1;
    }

    std::cout << "Sampling " << this->numSamples_ << " points" << std::endl;

    // print width and height of map
    std::cout << "Map width: " << this->map_->getWidth() << std::endl;
    std::cout << "Map height: " << this->map_->getHeight() << std::endl;

    // Initialize graph the size of num samples
    this->graph_ = Graph(this->numSamples_);

    int mapWidth = this->map_->getWidth();
    int mapHeight = this->map_->getHeight();

    // int chunk_size = (this->numSamples_ + numThreads - 1) / numThreads;

    #pragma omp parallel for schedule(dynamic)
    for (int i = 0; i < this->numSamples_; i++)
    {

        bool pointIsFree = false;
        vertex_property_t vp;
        int count = 0;
        do
        {
            // pick a random x and y from the map
            vp.x = rand() % mapWidth;
            vp.y = rand() % mapHeight;
            pointIsFree = ((this->map_)->isFree)(vp.x, vp.y);
            count++;
        } while (!pointIsFree);
        // add vertex to graph
        this->graph_[i] = vp;
    }

    return 0;
}

int Planner::connectionPhase()
{
    // For each vertex, connect vertex to its closest neighbors
    #pragma omp parallel for schedule(static)
    for (int vd = 0; vd < this->numSamples_; vd++)
    {
        this->connectVertex(vd);
    }

    return 0;
}

int Planner::connectVertex(vertex_t vd)
{

    for (auto vd2 : boost::make_iterator_range(vertices(this->graph_)))
    {
        if (vd == vd2)
        {
            continue;
        }
        vertex_property_t vp1 = this->graph_[vd];
        vertex_property_t vp2 = this->graph_[vd2];
        double distance = this->map_->getDistance(vp1.x, vp1.y, vp2.x, vp2.y);
        if (distance < this->dist_threshold_)
        {
            // check for a collision free edge between the two vertices
            int direction = this->map_->canConnect(vp1.x, vp1.y, vp2.x, vp2.y);

            if (direction != CANT_CONNECT)
            {
                edge_t e;
                // #pragma omp critical
                // {
                    e = boost::add_edge(vd, vd2, this->graph_).first;
                // }
                this->graph_[e].distance = this->map_->getDistance(vp1.x, vp1.y, vp2.x, vp2.y);
                this->graph_[e].direction = direction;
            }
        }
    }

    return 0;
}

vertex_t Planner::addAndConnectVertex(std::vector<int> point, int &status)
{
    // check if the point is free
    if (!this->map_->isFree(point[0], point[1]))
    {
        status = -1;
        return 0;
    }

    vertex_property_t vp;
    vp.x = point[0];
    vp.y = point[1];

    // add vertex to graph
    vertex_t vd = boost::add_vertex(this->graph_);
    this->graph_[vd] = vp;

    // connect the vertex
    // NOTE this algo has been modified from the original.
    // Here we connect to all k nearest vertices, in the original only the closest is connected.
    this->connectVertex(vd);

    return vd;
}

int Planner::queryPhase(int numThreads)
{
    // Add the start and goal vertex to the graph
    int status = 0;
    this->start_vd_ = addAndConnectVertex(this->start_, status);
    if (status == -1)
    {
        std::cout << "Invalid Start State. Planning Failed." << std::endl;
        return -1;
    }

    this->goal_vd_ = addAndConnectVertex(this->goal_, status);
    if (status == -1)
    {
        std::cout << "Invalid Goal State. Planning Failed." << std::endl;
        return -1;
    }

    // create the waypoint vector
    std::vector<vertex_t> waypoints;

    std::cout << "Starting A*" << std::endl;

    // Try and find a path from start to goal
    this->astar_parallel(waypoints, numThreads);

    if (waypoints.size() == 0)
    {
        std::cout << "No path found. Planning Failed." << std::endl;
        return -1;
    }

    // interpolate the path
    this->interpolate(waypoints);

    return 0;
}

/*
int Planner::astar(std::vector<vertex_t> &waypoints)
{

    vertex_property_t start_properties = this->graph_[this->start_vd_];
    vertex_property_t goal_properties = this->graph_[this->goal_vd_];

    // Create the open list
    priority_queue<AstarNode *, vector<AstarNode *>, OpenListNodeComparator> openList = priority_queue<AstarNode *, vector<AstarNode *>, OpenListNodeComparator>();

    // create the start and goal nodes
    int start_h = this->map_->getDistance(start_properties.x, start_properties.y, goal_properties.x, goal_properties.y);
    AstarNode *startNode = new AstarNode(this->start_vd_, 0, start_h, NULL);
    AstarNode *goalNode = new AstarNode(this->goal_vd_, -1, 0, NULL);
    // int path_size = -1;
    (void)goalNode;

    // add the start node to the open list
    openList.push(startNode);

    // Create the closed list
    unordered_set<AstarNode *, NodeHasher, ClosedListNodeComparator> closedList = unordered_set<AstarNode *, NodeHasher, ClosedListNodeComparator>();

    // while the open list is not empty
    while (!openList.empty())
    {
        // get node with smalled f-value
        AstarNode *currNode = openList.top();
        openList.pop();

        // keep removing until node not in closed list
        if (closedList.find(currNode) != closedList.end())
        {
            continue;
        }

        // insert into the closed list
        closedList.insert(currNode);

        // check if we have reached the goal stage
        if (currNode->vertexDescriptor == this->goal_vd_)
        {
            cout << this->goal_vd_ << std::endl;
            cout << "We have Reached the Goal!!!" << endl;
            goalNode = currNode;
            break;
        }

        // get the vertex descriptor of the current node
        vertex_t currNodeVD = currNode->vertexDescriptor;

        // get neighbors
        auto neighbors = boost::adjacent_vertices(currNode->vertexDescriptor, this->graph_);

        // for each neighbor
        for (vertex_t vd : make_iterator_range(neighbors))
        {
            edge_t e = boost::edge(currNodeVD, vd, this->graph_).first;

            vertex_property_t vdPos = this->graph_[vd];

            // calculate f value
            int newG = currNode->gValue + this->graph_[e].distance;
            int newH = this->map_->getDistance(vdPos.x, vdPos.y, goal_properties.x, goal_properties.y);

            // construct the node
            AstarNode *newNode = new AstarNode(vd, newG, newH, currNode);

            // if node already in closed list then skip
            if (closedList.find(newNode) == closedList.end())
            {
                openList.push(newNode);
            }
        }
    }

    // check if found path
    if (goalNode->parent == NULL)
    {
        cout << "No Path Found" << endl;
        return -1;
    }

    // construct the path
    AstarNode *currNode = goalNode;
    while (currNode != NULL)
    {
        waypoints.push_back(currNode->vertexDescriptor);
        currNode = currNode->parent;
    }

    // reverse the path
    reverse(waypoints.begin(), waypoints.end());

    return 0;
}
*/

int hash_fn(AstarNode *startNode, int numThreads)
{
    return startNode->vertexDescriptor % numThreads;
}

bool isOpenListEmpty(priority_queue<AstarNode *, vector<AstarNode *>, OpenListNodeComparator> *openLists, int procID, std::mutex *openListsMutex)
{
    openListsMutex[procID].lock();
    int ret = openLists[procID].empty();
    openListsMutex[procID].unlock();
    return ret;
}

int isNodeInClosedList(unordered_set<AstarNode *, NodeHasher, ClosedListNodeComparator> *closedLists, int procID, AstarNode *node, std::mutex *closedListsMutex)
{
    closedListsMutex[procID].lock();
    int ret = (closedLists[procID].find(node) != closedLists[procID].end());
    closedListsMutex[procID].unlock();
    return ret;
}

bool allOpenListsEmpty(bool *threadDone, int numThreads)
{
    for (int i = 0; i < numThreads; i++)
    {
        if (!threadDone[i])
        {
            return false;
        }
    }
    return true;
}

int Planner::astar_parallel(std::vector<vertex_t> &waypoints, int numThreads)
{

    vertex_property_t start_properties = this->graph_[this->start_vd_];
    vertex_property_t goal_properties = this->graph_[this->goal_vd_];

    bool threadDone[numThreads];

    // Create the open lists
    priority_queue<AstarNode *, vector<AstarNode *>, OpenListNodeComparator> openLists[numThreads];
    std::mutex openListsMutex[numThreads];

    // Create the closed list
    unordered_set<AstarNode *, NodeHasher, ClosedListNodeComparator> closedLists[numThreads];
    std::mutex closedListsMutex[numThreads];

    for (int i = 0; i < numThreads; i++)
    {
        openLists[i] = priority_queue<AstarNode *, vector<AstarNode *>, OpenListNodeComparator>();
        closedLists[i] = unordered_set<AstarNode *, NodeHasher, ClosedListNodeComparator>();
    }

    // create the start and goal nodes
    int start_h = this->map_->getDistance(start_properties.x, start_properties.y, goal_properties.x, goal_properties.y);
    AstarNode *startNode = new AstarNode(this->start_vd_, 0, start_h, NULL);
    AstarNode *goalNode = NULL;
    (void)goalNode;

    // add the start node to the open list
    int firstProc = hash_fn(startNode, numThreads);
    openListsMutex[firstProc].lock();
    openLists[firstProc].push(startNode);
    openListsMutex[firstProc].unlock();

    int procID;
    #pragma omp parallel default(shared) private(procID)
    {
        procID = omp_get_thread_num();
        do
        {
            threadDone[procID] = false;
            // while the open list is not empty
            while (!isOpenListEmpty(openLists, procID, openListsMutex))
            {
                // get node with smalled f-value
                openListsMutex[procID].lock();
                AstarNode *currNode = openLists[procID].top();
                openLists[procID].pop();
                openListsMutex[procID].unlock();

                // keep removing until node not in closed list
                if (isNodeInClosedList(closedLists, procID, currNode, closedListsMutex))
                {
                    continue;
                }

                // insert into the closed list
                closedListsMutex[procID].lock();
                closedLists[procID].insert(currNode);
                closedListsMutex[procID].unlock();

                // check if we have reached the goal stage
                if (currNode->vertexDescriptor == this->goal_vd_)
                {
                    cout << this->goal_vd_ << std::endl;
                    cout << "We have Reached the Goal!!!" << endl;
                    goalNode = currNode;
                    break;
                }

                // get the vertex descriptor of the current node
                vertex_t currNodeVD = currNode->vertexDescriptor;

                // get neighbors
                auto neighbors = boost::adjacent_vertices(currNode->vertexDescriptor, this->graph_);

                // for each neighbor
                for (vertex_t vd : make_iterator_range(neighbors))
                {
                    edge_t e = boost::edge(currNodeVD, vd, this->graph_).first;

                    vertex_property_t vdPos = this->graph_[vd];

                    // calculate f value
                    int newG = currNode->gValue + this->graph_[e].distance;
                    int newH = this->map_->getDistance(vdPos.x, vdPos.y, goal_properties.x, goal_properties.y);

                    // construct the node
                    AstarNode *newNode = new AstarNode(vd, newG, newH, currNode);
                    int hashedProc = hash_fn(newNode, numThreads);

                    // if node already in closed list then skip
                    if (!isNodeInClosedList(closedLists, hashedProc, newNode, closedListsMutex))
                    {
                        openListsMutex[hashedProc].lock();
                        openLists[hashedProc].push(newNode);
                        openListsMutex[hashedProc].unlock();
                    } else {
                        delete newNode;
                    }
                }
            }

            #pragma omp barrier
            threadDone[procID] = isOpenListEmpty(openLists, procID, openListsMutex);
            if (goalNode != NULL)
            {
                threadDone[procID] = true;
            }

            #pragma omp barrier
        } while (!allOpenListsEmpty(threadDone, numThreads));
    }

    cout << "All threads exited" << endl;
    bool no_path_found = false;

    // check if found path
    if (goalNode == NULL)
    {
        cout << "No Path Found" << endl;
        no_path_found = true;
    }

    if (!no_path_found)
    {
        // construct the path
        AstarNode *currNode = goalNode;
        std::cout << "Path Found" << std::endl;
        while (currNode != NULL)
        {
            waypoints.push_back(currNode->vertexDescriptor);
            currNode = currNode->parent;
        }
    }

    for (int i = 0; i < numThreads; i++)
    {
        while (openLists[i].size() > 0)
        {
            AstarNode *node = openLists[i].top();
            openLists[i].pop();
            delete node;
        }

        for (auto it = closedLists[i].begin(); it != closedLists[i].end(); ++it )
        {
            AstarNode *node = *it;
            delete node;
        }

        while (closedLists[i].size() > 0)
        {
            closedLists[i].erase(closedLists[i].begin());
        }

    }

    // reverse the path
    reverse(waypoints.begin(), waypoints.end());

    return !no_path_found;
}

// interpolate the path
int Planner::interpolate(std::vector<vertex_t> &waypoints)
{
    // hold curr and prev waypoint
    vertex_t currWaypoint;
    vertex_t nextWaypoint;

    // for each waypoint starting at index 1
    for (size_t i = 0; i < waypoints.size(); i++)
    {
        // get the current waypoint
        currWaypoint = waypoints[i];

        // get the x and y of the current waypoint
        int currWaypointX = this->graph_[currWaypoint].x;
        int currWaypointY = this->graph_[currWaypoint].y;

        // push the x and y of the current waypoint onto the path as a vector
        this->path_.push_back({currWaypointX, currWaypointY});

        // if the current waypoint is the last waypoint then break
        if (i == waypoints.size() - 1)
        {
            break;
        }

        // get the next waypoint
        nextWaypoint = waypoints[i + 1];

        // get the x and y of the next waypoint
        int nextWaypointX = this->graph_[nextWaypoint].x;
        int nextWaypointY = this->graph_[nextWaypoint].y;

        // get the edge between the current and next waypoint
        edge_t e = boost::edge(currWaypoint, nextWaypoint, this->graph_).first;

        // get the direction of the edge
        int direction = this->graph_[e].direction;

        // calculate stepx and stepy
        int stepX = (nextWaypointX > currWaypointX) ? 1 : -1;
        int stepY = (nextWaypointY > currWaypointY) ? 1 : -1;

        // if the direction is horizontal
        if (direction == CONNECT_HORIZ)
        {
            // horizontal part first
            for (int x = currWaypointX; x != nextWaypointX; x += stepX)
            {
                // push the point onto the path
                this->path_.push_back({x, currWaypointY});
            }

            // vertical part
            for (int y = currWaypointY; y != nextWaypointY; y += stepY)
            {
                // push the point onto the path
                this->path_.push_back({nextWaypointX, y});
            }
        }

        // else if the direction is vertical
        else if (direction == CONNECT_VERT)
        {
            // vertical part first
            for (int y = currWaypointY; y != nextWaypointY; y += stepY)
            {
                // push the point onto the path
                this->path_.push_back({currWaypointX, y});
            }

            // horizontal part
            for (int x = currWaypointX; x != nextWaypointX; x += stepX)
            {
                // push the point onto the path
                this->path_.push_back({x, nextWaypointY});
            }
        }

    }

    return 0;
}

ext: cpp


text:
#ifndef INCLUDE_SWIFT_VIO_REMOVE_FROM_VECTOR_HPP_
#define INCLUDE_SWIFT_VIO_REMOVE_FROM_VECTOR_HPP_

#include <vector>
#include <Eigen/Core>
#include <Eigen/StdVector>

namespace swift_vio {
template <typename Derived>
void removeUnsetMatrices(
    std::vector<Derived, Eigen::aligned_allocator<Derived>>* matrices,
    const std::vector<bool>& markers) {
  //  if (matrices->size() != markers.size()) {
  //    std::cerr << "The input size of matrices(" << matrices->size()
  //              << ") and markers(" << markers.size() << ") does not
  //              match.\n";
  //  }
  auto iter = matrices->begin();
  auto keepIter = matrices->begin();
  for (size_t i = 0; i < markers.size(); ++i) {
    if (!markers[i]) {
      ++iter;
    } else {
      if (keepIter != iter) *keepIter = *iter;
      ++iter;
      ++keepIter;
    }
  }
  matrices->resize(keepIter - matrices->begin());
}

template <typename T>
void removeUnsetElements(std::vector<T>* elements,
                         const std::vector<bool>& markers) {
  //  if (elements->size() != markers.size()) {
  //    std::cerr << "The input size of elements(" << elements->size()
  //              << ") and markers(" << markers.size() << ") does not
  //              match.\n";
  //  }
  auto iter = elements->begin();
  auto keepIter = elements->begin();
  for (size_t i = 0; i < markers.size(); ++i) {
    if (!markers[i]) {
      ++iter;
    } else {
      *keepIter = *iter;
      ++iter;
      ++keepIter;
    }
  }
  elements->resize(keepIter - elements->begin());
}

template <typename T>
void removeUnsetElements(std::vector<T>* elements,
                         const std::vector<bool>& markers, const int step) {
  //  if (elements->size() != markers.size()) {
  //    std::cerr << "The input size of elements(" << elements->size()
  //              << ") and markers(" << markers.size() << ") does not
  //              match.\n";
  //  }
  auto iter = elements->begin();
  auto keepIter = elements->begin();
  for (size_t i = 0; i < markers.size(); ++i) {
    if (!markers[i]) {
      iter += step;
    } else {
      for (int j = 0; j < step; ++j) {
        *keepIter = *iter;
        ++iter;
        ++keepIter;
      }
    }
  }
  elements->resize(keepIter - elements->begin());
}

/**
 * select matrics from a vector of Eigen types.
 * do not use this function with Eigen types.
 */
template <class T, class Index>
std::vector<T, Eigen::aligned_allocator<T>> selectMatrices(
    const std::vector<T, Eigen::aligned_allocator<T>>& inArray,
    const std::vector<Index>& indices) {
  std::vector<T, Eigen::aligned_allocator<T>> result;
  result.reserve(indices.size());
  for (auto val : indices) {
    result.push_back(inArray[val]);
  }
  return result;
}

/**
 * T, element type
 * Index, index type
 * warning: do not use this function with Eigen types.
 */
template <class T, class Index>
std::vector<T> selectElements(const std::vector<T>& inArray,
                              const std::vector<Index>& indices) {
  std::vector<T> result;
  result.reserve(indices.size());
  for (auto val : indices) {
    result.push_back(inArray[val]);
  }
  return result;
}

/**
 * @brief Does a vector contain a certain element.
 * @tparam Class of a vector element.
 * @param vector Vector to search element in.
 * @param query Element to search for.
 * @return True if query is an element of vector.
 */
template<class T>
bool vectorContains(const std::vector<T> & vector, const T & query){
  for(size_t i=0; i<vector.size(); ++i){
    if(vector[i] == query){
      return true;
    }
  }
  return false;
}

} // namespace swift_vio
#endif  // INCLUDE_SWIFT_VIO_REMOVE_FROM_VECTOR_HPP_

ext: hpp


text:
#include <boost/test/unit_test.hpp>
#include "algorithms/data_structures/queue/sliding_window_max.hpp"

BOOST_AUTO_TEST_SUITE(TestSlidingWindowMax)

BOOST_AUTO_TEST_CASE(test) {
    {
        const std::vector<int> input = {};
        const size_t window_size = 0;
        const std::vector<int> expected = {};
        const auto result =
                Algo::DS::Queue::SlidingWindow<int>::Max(input, window_size);
        BOOST_CHECK(expected == result);
    }

    {
        const std::vector<int> input = {1};
        const size_t window_size = 1;
        const std::vector<int> expected = {1};
        const auto result =
                Algo::DS::Queue::SlidingWindow<int>::Max(input, window_size);
        BOOST_CHECK(expected == result);
    }

    {
        const std::vector<int> input = {2, 3, 4};
        const size_t window_size = 1;
        const std::vector<int> expected = {2, 3, 4};
        const auto result =
                Algo::DS::Queue::SlidingWindow<int>::Max(input, window_size);
        BOOST_CHECK(expected == result);
    }

    {
        const std::vector<int> input = {1, 3, -1, -3, 5, 3, 6, 7};
        const size_t window_size = 3;
        const std::vector<int> expected = {3, 3, 5, 5, 6, 7};
        const auto result =
                Algo::DS::Queue::SlidingWindow<int>::Max(input, window_size);
        BOOST_CHECK(expected == result);
    }

    {
        const std::vector<int> input = {7, 2, 4};
        const size_t window_size = 2;
        const std::vector<int> expected = {7, 4};
        const auto result =
                Algo::DS::Queue::SlidingWindow<int>::Max(input, window_size);
        BOOST_CHECK(expected == result);
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: iamantony/CppNotes

max_issues_repo_name: iamantony/CppNotes

max_forks_repo_name: iamantony/CppNotes


text:
//
// Copyright (c) 2016 Marat Abrarov (abrarov@gmail.com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <cstddef>
#include <boost/noncopyable.hpp>
#include <gtest/gtest.h>
#include <ma/handler_allocator.hpp>

namespace ma {
namespace test {
namespace handler_allocator {

template <typename Allocator>
class alloc_guard : private boost::noncopyable
{
public:
  typedef Allocator allocator_type;

  alloc_guard(void* ptr, allocator_type& allocator)
    : ptr_(ptr)
    , allocator_(allocator)
  {
  }

  ~alloc_guard()
  {
    allocator_.deallocate(ptr_);
  }

private:
  void* ptr_;
  allocator_type& allocator_;
}; // class alloc_guard

template <typename Allocator>
void test_max_size_allocation(Allocator& allocator)
{
  void* ptr = allocator.allocate(allocator.size());
  alloc_guard<Allocator> guard(ptr, allocator);
  ASSERT_NE(static_cast<void*>(0), ptr);
  (void) guard;
}

template <typename Allocator>
void test_min_size_allocation(Allocator& allocator)
{
  void* ptr = allocator.allocate(1);
  alloc_guard<Allocator> guard(ptr, allocator);
  ASSERT_NE(static_cast<void*>(0), ptr);
  (void) guard;
}

template <typename Allocator>
void test_failed_allocation(Allocator& allocator)
{
  void* ptr = allocator.allocate(allocator.size() + 1);
  alloc_guard<Allocator> guard(ptr, allocator);
  ASSERT_EQ(static_cast<void*>(0), ptr);
  (void) guard;
}

TEST(in_place_handler_allocator, allocation_of_max_size)
{
  in_place_handler_allocator<32> allocator;
  test_max_size_allocation(allocator);
}

TEST(in_place_handler_allocator, allocation_of_min_size)
{
  in_place_handler_allocator<32> allocator;
  test_min_size_allocation(allocator);
}

TEST(in_place_handler_allocator, failed_allocation)
{
  in_place_handler_allocator<32> allocator;
  test_failed_allocation(allocator);
}

TEST(in_heap_handler_allocator, allocation_of_max_size)
{
  in_heap_handler_allocator allocator(128, false);
  test_max_size_allocation(allocator);
}

TEST(in_heap_handler_allocator, allocation_of_min_size)
{
  in_heap_handler_allocator allocator(128, false);
  test_min_size_allocation(allocator);
}

TEST(in_heap_handler_allocator, failed_allocation)
{
  in_heap_handler_allocator allocator(128, false);
  test_failed_allocation(allocator);
}

TEST(lazy_in_heap_handler_allocator, allocation_of_max_size)
{
  in_heap_handler_allocator allocator(16, true);
  test_max_size_allocation(allocator);
}

TEST(lazy_in_heap_handler_allocator, allocation_of_min_size)
{
  in_heap_handler_allocator allocator(16, true);
  test_min_size_allocation(allocator);
}

TEST(lazy_in_heap_handler_allocator, failed_allocation)
{
  in_heap_handler_allocator allocator(16, true);
  test_failed_allocation(allocator);
}

template <typename Allocator>
void test_null_ptr_deallocation(Allocator& allocator)
{
  void* ptr1 = allocator.allocate(allocator.size());
  alloc_guard<Allocator> guard1(ptr1, allocator);
  // Just check that no exception is thrown
  allocator.deallocate(0);
  // Check that deallocation of null ptr doesn't change state of allocator
  void* ptr2 = allocator.allocate(allocator.size());
  alloc_guard<Allocator> guard2(ptr2, allocator);
  ASSERT_EQ(static_cast<void*>(0), ptr2);
  (void) guard2;
  (void) guard1;
}

TEST(in_place_handler_allocator, null_ptr_deallocation)
{
  in_place_handler_allocator<32> allocator;
  test_null_ptr_deallocation(allocator);
}

TEST(in_heap_handler_allocator, null_ptr_deallocation)
{
  in_heap_handler_allocator allocator(16, false);
  test_null_ptr_deallocation(allocator);
}

TEST(lazy_in_heap_handler_allocator, null_ptr_deallocation)
{
  in_heap_handler_allocator allocator(8, true);
  test_null_ptr_deallocation(allocator);
}

template <typename Allocator>
void test_deallocation(Allocator& allocator)
{
  {
    // Ensure that after allocation we can not allocate one more time because
    // allocator is fully loaded
    void* ptr1 = allocator.allocate(allocator.size());
    alloc_guard<Allocator> guard1(ptr1, allocator);
    void* ptr2 = allocator.allocate(allocator.size());
    alloc_guard<Allocator> guard2(ptr2, allocator);
    ASSERT_EQ(static_cast<void*>(0), ptr2);
    (void) guard2;
    (void) guard1;
  }
  {
    // Ensure that after deallocation we can allocate one more time
    void* ptr = allocator.allocate(allocator.size());
    alloc_guard<Allocator> guard(ptr, allocator);
    ASSERT_NE(static_cast<void*>(0), ptr);
    (void) guard;
  }
}

TEST(in_place_handler_allocator, deallocation)
{
  in_place_handler_allocator<32> allocator;
  test_deallocation(allocator);
}

TEST(in_heap_handler_allocator, deallocation)
{
  in_heap_handler_allocator allocator(16, false);
  test_deallocation(allocator);
}

TEST(lazy_in_heap_handler_allocator, deallocation)
{
  in_heap_handler_allocator allocator(8, true);
  test_deallocation(allocator);
}

template<typename Allocator>
void test_ownership_range(Allocator& allocator, void* ptr)
{
  ASSERT_TRUE(allocator.owns(ptr));
  ASSERT_FALSE(allocator.owns(static_cast<char*>(ptr) - 1));
  ASSERT_TRUE(allocator.owns(static_cast<char*>(ptr) + 1));
  ASSERT_TRUE(allocator.owns(static_cast<char*>(ptr) + allocator.size() - 1));
  ASSERT_FALSE(allocator.owns(static_cast<char*>(ptr) + allocator.size()));
}

TEST(in_place_handler_allocator, ownership_of_null)
{
  in_place_handler_allocator<32> allocator;
  ASSERT_FALSE(allocator.owns(0));
}

TEST(in_place_handler_allocator, ownership_of_allocated)
{
  typedef in_place_handler_allocator<32> allocator_type;
  allocator_type allocator;
  void* ptr = allocator.allocate(allocator.size());
  alloc_guard<allocator_type> guard(ptr, allocator);
  test_ownership_range(allocator, ptr);
  (void) guard;
}

TEST(in_place_handler_allocator, ownership_of_free)
{
  in_place_handler_allocator<32> allocator;
  void* ptr = allocator.allocate(allocator.size());
  allocator.deallocate(ptr);
  test_ownership_range(allocator, ptr);
}

TEST(in_heap_handler_allocator, ownership_of_null)
{
  in_heap_handler_allocator allocator(64, false);
  ASSERT_FALSE(allocator.owns(0));
}

TEST(in_heap_handler_allocator, ownership_of_allocated)
{
  typedef in_heap_handler_allocator allocator_type;
  allocator_type allocator(64, false);
  void* ptr = allocator.allocate(allocator.size());
  alloc_guard<allocator_type> guard(ptr, allocator);
  test_ownership_range(allocator, ptr);
  (void) guard;
}

TEST(in_heap_handler_allocator, ownership_of_free)
{
  in_heap_handler_allocator allocator(64, false);
  void* ptr = allocator.allocate(allocator.size());
  allocator.deallocate(ptr);
  test_ownership_range(allocator, ptr);
}

TEST(lazy_in_heap_handler_allocator, ownership_of_null)
{
  in_heap_handler_allocator allocator(128, true);
  ASSERT_FALSE(allocator.owns(0));
}

TEST(lazy_in_heap_handler_allocator, ownership_of_near_null)
{
  in_heap_handler_allocator allocator(128, true);
  ASSERT_FALSE(allocator.owns(static_cast<char*>(0) + 1));
}

TEST(lazy_in_heap_handler_allocator, ownership_of_allocated)
{
  typedef in_heap_handler_allocator allocator_type;
  allocator_type allocator(128, true);
  void* ptr = allocator.allocate(allocator.size());
  alloc_guard<allocator_type> guard(ptr, allocator);
  test_ownership_range(allocator, ptr);
  (void) guard;
}

TEST(lazy_in_heap_handler_allocator, ownership_of_free)
{
  in_heap_handler_allocator allocator(128, true);
  void* ptr = allocator.allocate(allocator.size());
  allocator.deallocate(ptr);
  test_ownership_range(allocator, ptr);
}

} // namespace handler_allocator
} // namespace test
} // namespace ma


text:
#include "./rpc/core/rpcserver.h"
#include "./rpc/core/rpcclient.h"
#include "commons/util/util.h"
#include "config/chainparams.h"
#include <boost/test/unit_test.hpp>
#include <boost/assign/list_of.hpp>
#include "tx/tx.h"
using namespace std;
using namespace boost;
using namespace json_spirit;
#include "../test/systestbase.h"
map<string, string> mapDesAddress[] = {
        boost::assign::map_list_of
        ("000000000900",	"dsjkLDFfhenmx2JkFMdtJ22TYDvSGgmJem")
        ("000000000500",	"dsGb9GyDGYnnHdjSvRfYbj9ox2zPbtgtpo")
        ("000000000300",	"dejEcGCsBkwsZaiUH1hgMapjbJqPdPNV9U")
        ("000000000800",	"e21rEzVwkPFQYfgxcg7xLp7DKeYrW4Fpoz")
        ("000000000700",	"dd936HZcwj9dQkefHPqZpxzUuKZZ2QEsbN")
        ("000000000400",	"dkoEsWuW3aoKaGduFbmjVDbvhmjxFnSbyL")
        ("000000000100",	"dggsWmQ7jH46dgtA5dEZ9bhFSAK1LASALw")
        ("000000000600",	"doym966kgNUKr2M9P7CmjJeZdddqvoU5RZ")
        ("000000000200",	"dtKsuK9HUvLLHtBQL8Psk5fUnTLTFC83GS"),

        boost::assign::map_list_of
        ("010000003300",	"mm8f5877wY4u2WhhX2JtGWPTPKwLbGJi37")
        ("010000002d00",	"n31DG5wjP1GcKyVMupGBvjvweNkM75MPuR")
        ("010000002a00",	"mkeict2uyvmb4Gjx3qXh6vReoTw1A2gkLZ")
        ("010000002600",	"mqwRHqjQZcJBqJP46E256Z2VuqqRAkZkKH")
        ("010000004300",	"mvV1fW4NMv9MGoRwHw583TDi8gnqqjQovZ")
        ("010000003500",	"mzGkgfAkWtkQ4AP2Ut4yiAzCNx6EDzWjW8")
        ("010000002500",	"n3wo9Ts6AUmHdGM1PixpRnLRFrG5G8a5QA")
        ("010000004600",	"mxrmM6qNswgZHmp1u2HTu2soncQLkud7tF")
        ("010000004500",	"mmBBV47uFguukjceTXkPsB3izndht2YXx7"),

        boost::assign::map_list_of
        ("010000003200",	"n3eyjajBMwXiK56ohkzvA2Xu53W9E6jj8K")
        ("010000002900",	"muDs5TAdk6n8rSyLdq6HTzBkJT2XxPF1wP")
        ("010000003700",	"mxZqVtfao3A6dbwymKtn6oE4GacXoJNsac")
        ("010000004000",	"mspw67fn4KGwUrG9oo9mvLJQAPrTYwxQ6w")
        ("010000004700",	"mvNmNnB98GDSeYqg2jH2gSU557XEivs3N5")
        ("010000003a00",	"mjEGztB67nfscqSg5ryUGtzyTGwwEASZeQ")
        ("010000004100",	"mmCvt8WZzF27VGBMWWVkED3vsDRdpnigGV")
        ("010000003100",	"miUVkZNCDaKLTveqT3uWcy8kkpkA94gNvS")
        ("010000004200",	"mxx4MohV2ZfifQiZnmU4yVUVf2QUVM2grx"),

		boost::assign::map_list_of
        ("010000003f00",	"mjuZWVqVQ2cmFoB8pJRj7XWVCPkeoiWJAq")
        ("010000002b00",	"n2tTaaF8xoWWYvaxSDkfQP5GeEcCCsjq1t")
        ("010000002700",	"mw1XUknDsVtb68BUJNj25rKAikYG8qELHJ")
        ("010000002f00",	"mgE3hASaGCRPxJdZruAsydr2ygQz2UBWZM")
        ("010000003400",	"n1vNXyu2GNypJGdZYxzCBCeQFVt1Fd42Qn")
        ("010000003d00",	"n4Cti65cSeufvfxStKUozHNGX3fQSHsDe5")
        ("010000003c00",	"mnZUhyb83ZTQWc9TXXFfhjJEu65q4cFj4S")
        ("010000004800",	"muGiULSeqi2FQ2ypzU7aP8Uu1SWC5kRBki")
        ("010000003900",	"mrMFs4kk8sqZ7iE8DquqPLL8udyGNDUZ8T"),

        boost::assign::map_list_of
        ("010000003800",	"mogX7FTZ9Yuu6gYscKaEf2oxroeRuNDi76")
        ("010000002e00",	"mgs1mDsaXuj16aJ5YMHqLx7xsQ88snsZmB")
        ("010000003b00",	"mzUKrawp7a7LNB7D7kKzKEpgAStsAAHz18")
        ("010000002800",	"miNou7awKXUPN9wbzVP32zTXcWvPsZBpYg")
        ("010000003e00",	"mnnd1QQx2dM5yfp1j8Vp7Dcq7BhiS6bNEQ")
        ("010000004400",	"muS2Nxtva88d45uN6up7WeHszi3oWAcadK")
        ("010000003600",	"mw8yB7Pp7GYiDHhLQT2GNsLc439rfJ3Fai")
        ("010000002c00",	"miRVDrwxtJJh4XnZFnYR6YbdqpAuirVDzZ")
        ("010000003000",	"mvqUh3LR4R7cDWfw4AW7mRUSxfZbvonQ8v")};

int64_t sendValues[] = {1000000000, 2000000000, 3000000000, 4000000000, 5000000000, 6000000000, 7000000000, 8000000000, 9000000000, 10000000000};

void SubmitBlock(vector<string> &param) {
	if(1 != param.size())
			return;
	param.insert(param.begin(), "submitblock");
	param.insert(param.begin(), "rpctest");

	char *argv[param.size()];
	for(size_t i=0; i<param.size(); ++i) {
		argv[i] = const_cast<char *>(param[i].c_str());
		++i;
	}
	CommandLineRPC(param.size(), argv);
}

bool readblock(const string &filePath)
{
	CBlock block;
    FILE* fp = fopen(filePath.c_str(), "rb");
    if (!fp) return false;

    fseek(fp, 8, SEEK_SET); // skip msgheader/size

    CAutoFile filein = CAutoFile(fp, SER_DISK, CLIENT_VERSION);
    if (!filein) return false;
    while(!feof(fp)) {
    	filein >> block;
		CDataStream ds(SER_DISK, CLIENT_VERSION);
		ds << block;
    	vector<string> param;
    	param.push_back(HexStr(ds));
    	SubmitBlock(param);
    }
    return true;
}

class CMiningTest {
public:
	//????????л?????????Block???
	CMiningTest() {

	}
	~CMiningTest() {};

};

class CSendItem:public SysTestBase{
private:
	string m_strRegId;
	string m_strAddress;
	int64_t m_llSendValue;
public:
	CSendItem(){
	};
	CSendItem(const string &strRegId, const string &strDesAddr, const int64_t &llSendValue)
	{
		m_strRegId = strRegId;
		m_strAddress = strDesAddr;
		m_llSendValue = llSendValue;
	}
	void GetContranctData(vector<unsigned char> &vContranct ) {
		//vector<unsigned char> temp = ParseHex(m_strRegId);
		CRegID reg(m_strRegId);
		vContranct.insert(vContranct.end(), reg.GetRegIdRaw().begin(), reg.GetRegIdRaw().end());
		//temp.clear();
		CDataStream ds(SER_DISK, CLIENT_VERSION);
		ds << m_llSendValue;
		vector<unsigned char> temp(ds.begin(), ds.end());
		//string strSendValue = HexStr(temp);
		vContranct.insert(vContranct.end(), temp.begin(), temp.end());
	}
	//index ????Χ1~5?????1~5???????
	static CSendItem GetRandomSendItem(int index) {
		int randAddr = std::rand() % 9;
		int randSendValue = std::rand() % 10;
		map<string, string>::iterator iterAddr = mapDesAddress[index - 1].begin();
		map<string, string>::iterator iterLast = mapDesAddress[index - 1].end();
		--iterLast;
		do {
			iterAddr++;
		} while (--randAddr > 0 && iterAddr != iterLast);
		return CSendItem(iterAddr->first, iterAddr->second, sendValues[randSendValue]);
	}
	string GegRegId() {
		return m_strRegId;
	}

	string GetInvolvedKeyIds() {
		return m_strAddress;
	}

	uint64_t GetSendValue() {
		char cSendValue[12] = {0};
		sprintf(&cSendValue[0], "%ld", m_llSendValue);
		string strSendValue(cSendValue);
		cout << "GetSendValue:" << strSendValue << endl;
		return m_llSendValue;
	}

};

/**
 *构建普通交易
 * @param param
 * param[0]:源地址
 * param[1]:目的地址
 * param[2]:转账金额
 * param[3]:手续费
 * param[4]:有效期高度
 */
void CreateNormalTx(vector<string> &param) {
	if(3 != param.size())
		return;
	param.insert(param.begin(), "sendtoaddress");
	param.insert(param.begin(), "rpctest");
	char *argv[param.size()];
	for(size_t i=0; i<param.size();++i) {
	     argv[i] = const_cast<char *>(param[i].c_str());
	}
	CommandLineRPC(param.size(), argv);
}

/**
 * 构建合约交易
 * @param param
 * param[0]:脚本注册ID
 * param[1]:账户地址列表,json的数组格式
 * param[2]:合约内容
 * param[3]:手续费
 * param[4]:有效期高度
 */
void CallContractTx(vector<string> &param) {
	if(5 != param.size())
		return;
	param.insert(param.begin(), "CallContractTx");
	param.insert(param.begin(), "rpctest");
	char *argv[param.size()];
	for(size_t i=0; i<param.size();++i) {
	     argv[i] = const_cast<char *>(param[i].c_str());
	}
	CommandLineRPC(param.size(), argv);
}

/**
 * 构建注册脚本交易
 * @param param
 * param[0]:注册脚本的账户地址
 * param[1]:注册脚本标识位，0-标识脚本内容的文件路径，1-已注册脚本ID
 * param[2]:文件路径或注册脚本ID
 * param[3]:手续费
 * param[4]:有效期高度
 * param[5]:脚本描述 （针对新注册脚本,可选）
 * param[6]:脚本授权时间 （可选）
 * param[7]:授权脚本每次从账户中扣减金额上限 （可选）
 * param[8]:授权脚本总共扣钱金额上限 （可选）
 * param[9]:授权脚本每天扣钱金额上限 （可选）
 * param[10]:用户自定义数据
 *
 */
void CreateRegScriptTx(vector<string> &param) {
	if(5 > param.size())
		return;
	param.insert(param.begin(), "submitcontractdeploytx");
	param.insert(param.begin(), "rpctest");

	char *argv[param.size()];
	for(size_t i=0; i<param.size();++i) {
	     argv[i] = const_cast<char *>(param[i].c_str());
	}
	CommandLineRPC(param.size(), argv);
}

time_t sleepTime = 500;     //每隔1秒发送一个交易
int64_t llTime = 24*60*60;   //每隔1秒发送一个交易

time_t string2time(const char * str,const char * formatStr)
{
  struct tm tm1;
  int year,mon,mday,hour,min,sec;
  if( -1 == sscanf(str,formatStr,&year,&mon,&mday,&hour,&min,&sec)) return -1;
  tm1.tm_year=year-1900;
  tm1.tm_mon=mon-1;
  tm1.tm_mday=mday;
  tm1.tm_hour=hour;
  tm1.tm_min=min;
  tm1.tm_sec=sec;
  return mktime(&tm1);
}
BOOST_FIXTURE_TEST_SUITE(auto_mining_test, CSendItem)
BOOST_FIXTURE_TEST_CASE(regscript,CSendItem) {
	//注册脚本交易
	SysTestBase::DeployContractTx("dsjkLDFfhenmx2JkFMdtJ22TYDvSGgmJem","unit_test.bin",0);
}
BOOST_FIXTURE_TEST_CASE(test1, CSendItem)
{
	const char *argv[] = {"progname", "-datadir=D:\\bitcoin\\1"};
	int argc = sizeof(argv) / sizeof(char*);
	CBaseParams::InitializeParams(argc, argv);
//	time_t t1 = string2time("2014-12-01 17:30:00","%d-%d-%d %d:%d:%d");

	Value resulut = DeployContractTx("dsjkLDFfhenmx2JkFMdtJ22TYDvSGgmJem","unit_test.bin",0);
	string scripthash = "";
	BOOST_CHECK(GetHashFromCreatedTx(resulut,scripthash));
	string scriptid = "";
	BOOST_CHECK(GetTxConfirmedRegID(scripthash,scriptid));

	int64_t runTime = GetTime()+llTime;
	vector<string> param;
	while (GetTime() < runTime) {
		//创建客户端1->客户端2的普通交易
		CSendItem sendItem = CSendItem::GetRandomSendItem(1);
		CSendItem recItem = CSendItem::GetRandomSendItem(2);
		CreateNormalTx(sendItem.GetInvolvedKeyIds(),recItem.GetInvolvedKeyIds(),recItem.GetSendValue());  //创建普通交易
		MilliSleep(sleepTime);

		//创建客户端1->客户端2的合约交易
		CSendItem sendItem1 = CSendItem::GetRandomSendItem(1);

		CallContractTx(scriptid,sendItem1.GetInvolvedKeyIds(),"01",0);  //创建合约交易
		MilliSleep(sleepTime);
	}
}
BOOST_AUTO_TEST_CASE(test2)
{
	const char *argv[] = {"progname", "-datadir=D:\\bitcoin\\2"};
	int argc = sizeof(argv) / sizeof(char*);
	CBaseParams::InitializeParams(argc, argv);
	int64_t runTime = GetTime()+llTime;
	Value resulut = DeployContractTx("dsjkLDFfhenmx2JkFMdtJ22TYDvSGgmJem","unit_test.bin",0);
	string scripthash = "";
	BOOST_CHECK(GetHashFromCreatedTx(resulut,scripthash));
	string scriptid = "";
	BOOST_CHECK(GetTxConfirmedRegID(scripthash,scriptid));

	while(GetTime()<runTime) {
		//创建客户端2->客户端3的普通交易
		CSendItem sendItem = CSendItem::GetRandomSendItem(2);
		CSendItem recItem = CSendItem::GetRandomSendItem(3);
		CreateNormalTx(sendItem.GetInvolvedKeyIds(),recItem.GetInvolvedKeyIds(),recItem.GetSendValue());
		MilliSleep(sleepTime);

		//创建客户端2->客户端3的合约交易
		CSendItem sendItem1 = CSendItem::GetRandomSendItem(2);
		CallContractTx(scriptid,sendItem1.GetInvolvedKeyIds(),"01",0); //创建合约交易
		MilliSleep(sleepTime);
	}
}

BOOST_AUTO_TEST_CASE(test3)
{
	const char *argv[] = {"progname", "-datadir=D:\\bitcoin\\3"};
	int argc = sizeof(argv) / sizeof(char*);
	CBaseParams::InitializeParams(argc, argv);
	int64_t runTime = GetTime()+llTime;

	Value resulut = DeployContractTx("dsjkLDFfhenmx2JkFMdtJ22TYDvSGgmJem","unit_test.bin",0);
	string scripthash = "";
	BOOST_CHECK(GetHashFromCreatedTx(resulut,scripthash));
	string scriptid = "";
	BOOST_CHECK(GetTxConfirmedRegID(scripthash,scriptid));
	while(GetTime()<runTime) {
		//创建客户端3->客户端4的普通交易
		CSendItem sendItem = CSendItem::GetRandomSendItem(3);
		CSendItem recItem = CSendItem::GetRandomSendItem(4);
		CreateNormalTx(sendItem.GetInvolvedKeyIds(),recItem.GetInvolvedKeyIds(),recItem.GetSendValue());
		MilliSleep(sleepTime);

		//创建客户端3->客户端4的合约交易
		CSendItem sendItem1 = CSendItem::GetRandomSendItem(3);
		CallContractTx(scriptid,sendItem1.GetInvolvedKeyIds(),"01",0);
		MilliSleep(sleepTime);
	}
}

BOOST_AUTO_TEST_CASE(test4)
{

	const char *argv[] = {"progname", "-datadir=D:\\bitcoin\\4"};
	int argc = sizeof(argv) / sizeof(char*);
	CBaseParams::InitializeParams(argc, argv);
	int64_t runTime = GetTime()+llTime;

	Value resulut = DeployContractTx("dsjkLDFfhenmx2JkFMdtJ22TYDvSGgmJem","unit_test.bin",0);
	string scripthash = "";
	BOOST_CHECK(GetHashFromCreatedTx(resulut,scripthash));
	string scriptid = "";
	BOOST_CHECK(GetTxConfirmedRegID(scripthash,scriptid));
	while(GetTime()<runTime) {
		//创建客户端4->客户端5的普通交易
		CSendItem sendItem = CSendItem::GetRandomSendItem(4);
		CSendItem recItem = CSendItem::GetRandomSendItem(5);
		CreateNormalTx(sendItem.GetInvolvedKeyIds(),recItem.GetInvolvedKeyIds(),recItem.GetSendValue());  //创建普通交易
		MilliSleep(sleepTime);

		//创建客户端4->客户端5的合约交易
		CSendItem sendItem1 = CSendItem::GetRandomSendItem(4);
		CallContractTx(scriptid,sendItem1.GetInvolvedKeyIds(),"01",0);
		MilliSleep(sleepTime);
	}
}
BOOST_AUTO_TEST_CASE(test5)
{
	const char *argv[] = {"progname", "-datadir=D:\\bitcoin\\5"};
	int argc = sizeof(argv) / sizeof(char*);
	CBaseParams::InitializeParams(argc, argv);

	int64_t runTime = GetTime()+llTime;
	Value resulut = DeployContractTx("dsjkLDFfhenmx2JkFMdtJ22TYDvSGgmJem", "unit_test.bin",0);
	string scripthash = "";
	BOOST_CHECK(GetHashFromCreatedTx(resulut,scripthash));
	string scriptid = "";
	BOOST_CHECK(GetTxConfirmedRegID(scripthash,scriptid));
	while(GetTime()<runTime) {
		//创建客户端5->客户端1的普通交易
		CSendItem sendItem = CSendItem::GetRandomSendItem(5);
		CSendItem recItem = CSendItem::GetRandomSendItem(1);
		CreateNormalTx(sendItem.GetInvolvedKeyIds(),recItem.GetInvolvedKeyIds(),recItem.GetSendValue());
		MilliSleep(sleepTime);

		//创建客户端5->客户端1的合约交易
		CSendItem sendItem1 = CSendItem::GetRandomSendItem(5);
		CallContractTx(scriptid,sendItem1.GetInvolvedKeyIds(),"01",0);
		MilliSleep(sleepTime);
	}

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: nondejus/WaykiChain

max_issues_repo_name: nondejus/WaykiChain

max_forks_repo_name: nondejus/WaykiChain


text:
#include <iostream>
#include <unistd>

#include <boost/numeric/mtl/mtl.hpp>
#include <boost/timer.hpp>

/*
  First run: 87ns + 74ns dynamic types
             67ns + 42ns static types (r6809) (CET needs 52ns if run alone???)
             71ns + 46ns static types with unrolled by hand (r6810)
*/

#define STATIC_TYPES

#ifdef STATIC_TYPES
   typedef mtl::dense_vector<double, mtl::parameters<mtl::tag::col_major, mtl::fixed::dimension<3>, true> > vec;
#else
   typedef mtl::dense_vector<double> vec;
#endif

using namespace std;

int main()
{

    vec u(3), v(3), w(3), x(3);

    u= 3., 4, 6; v= 7, 9, 3; w= 7, 2, 4;

    const int rep= 10000000;
    boost::timer time;
    for(int i= 0; i < rep; i++) {
	x= dot(v, u) * w + 4.0 * v + 2 * w;
    }
    std::cout << "Compute time (CET) = " << 1000000000.*time.elapsed() / rep << "ns" << std::endl;

    time.restart();
    for(int i= 0; i < rep; i++) {
	x= dot(v, u) * (w+= 4.0 * v + 2 * w);
    }
    std::cout << "Compute time (RET) = " << 1000000000.*time.elapsed() / rep << "ns" << std::endl;

    return 0;
}


text:
#ifdef ROBOTRACONTEUR_USE_STDAFX
#include "stdafx.h"
#endif

#include <RobotRaconteur.h>

#include "AsyncMessageTest.h"

#include <boost/shared_array.hpp>

#include "MessageSerializationTest.h"
#include "MessageSerializationTest4.h"

#include <boost/range.hpp>

using namespace boost::random;

using namespace RobotRaconteur;

namespace RobotRaconteurTest
{
	void AsyncMessageReaderTest::Test()
	{
		Test1();
	}

	void AsyncMessageReaderTest::Test1()
	{
		mt19937 rng;
		rng.seed((uint32_t)std::time(0));

		{
			RR_INTRUSIVE_PTR<Message> m1 = MessageSerializationTest::NewTestMessage();
			m1->header->MessageID = 10322;
			m1->header->MessageResID = 8364;
			DoTest(m1, 2, rng);
		}
		{
			RR_INTRUSIVE_PTR<Message> m2 = MessageSerializationTest::NewTestMessage();
			m2->entries.push_back(CreateMessageEntry());
			DoTest(m2, 3, rng);
		}
		{
			RR_INTRUSIVE_PTR<Message> m3 = MessageSerializationTest::NewTestMessage();
			m3->entries.resize(1);
			DoTest(m3, 4, rng);
		}
		{
			RR_INTRUSIVE_PTR<Message> m4 = MessageSerializationTest::NewTestMessage();

			m4->entries.at(1)->EntryFlags = MessageEntryFlags_ERROR;
			m4->entries.at(1)->Error = MessageErrorType_DataSerializationError;
			m4->entries.at(1)->RequestID = 0;
			m4->entries.at(2)->EntryFlags = MessageEntryFlags_SERVICE_PATH_CODE | MessageEntryFlags_MEMBER_NAME_CODE;
			m4->entries.at(2)->ServicePathCode = 7;
			m4->entries.at(2)->MemberNameCode = 13;
			m4->entries.at(0)->elements.at(0)->ElementFlags = MessageElementFlags_ELEMENT_NUMBER;
			m4->entries.at(0)->elements.at(0)->ElementNumber = 7483948;
			m4->entries.at(0)->elements.at(1)->ElementFlags = MessageElementFlags_ELEMENT_NAME_CODE | MessageElementFlags_ELEMENT_TYPE_NAME_CODE;
			m4->entries.at(0)->elements.at(1)->ElementNameCode = 5;
			m4->entries.at(0)->elements.at(1)->ElementTypeNameCode = 11;
			m4->entries.at(0)->elements.at(2)->ElementNumber = -113;
			DoTest(m4, 4, rng);
		}
	}

	void AsyncMessageReaderTest::DoTest(RR_INTRUSIVE_PTR<Message> m, uint16_t version, boost::random::mt19937& rng)
	{
		boost::shared_array<uint8_t> buf;
		size_t message_size = 0;

		if (version == 2)
		{
			//Write to stream and read back
			message_size = m->ComputeSize();
			buf.reset(new uint8_t[message_size]);
			ArrayBinaryWriter w(buf.get(), 0, message_size);
			m->Write(w);

			if (w.Position() != m->ComputeSize())
				throw std::runtime_error("");
		}
		else if (version == 4)
		{
			//Write to stream and read back
			message_size = m->ComputeSize4();
			buf.reset(new uint8_t[message_size]);
			ArrayBinaryWriter w(buf.get(), 0, message_size);
			m->Write4(w);

			/*std::ofstream f("message.dat", std::ios::binary);
			f.unsetf(std::ios::skipws);
			std::copy(buf.get(), buf.get() + message_size, std::ostream_iterator<uint8_t>(f));
			f.close();*/

			if (w.Position() != m->ComputeSize4())
				throw std::runtime_error("");
		}
		else
		{
			throw std::runtime_error("Invalid version");
		}

		RR_SHARED_PTR<AsyncMessageReader> r = AsyncMessageReader::CreateInstance();
		r->Reset();
		const_buffers buf2;
		buf2.push_back(boost::asio::buffer(buf.get(), message_size));
		mutable_buffers continue_bufs;
		while (boost::asio::buffer_size(buf2) > 0)
		{
			size_t n1 = boost::asio::buffer_size(buf2);
			n1 = std::min(n1, (size_t)16193);
			boost::random::uniform_int_distribution<size_t> size_dist(0, n1);
			size_t new_size = size_dist(rng);
			new_size = std::max(new_size, (size_t)16);
			new_size = std::min(new_size, n1);

			const_buffers buf3 = buffers_truncate(buf2, new_size);
			size_t buf_used;
			if (boost::asio::buffer_size(continue_bufs) == 0)
			{
				continue_bufs.clear();
				if (version == 2)
				{
					r->Read(buf3, buf_used, 0, continue_bufs);
				}
				else
				{
					r->Read4(buf3, buf_used, 0, continue_bufs);
				}
				buffers_consume(buf2, buf_used);
			}
			else
			{
				size_t n = boost::asio::buffer_copy(continue_bufs, buf3);
				const_buffers empty;
				continue_bufs.clear();
				if (version == 2)
				{
					r->Read(empty, buf_used, n, continue_bufs);
				}
				else
				{
					r->Read4(empty, buf_used, n, continue_bufs);
				}
				if (buf_used != 0) throw std::runtime_error("huh?");
				buffers_consume(buf2, n);
			}
			//std::cout << "Read " << buf_used << " continue_bufs: " << boost::asio::buffer_size(continue_bufs) << std::endl;
		}

		if (!r->MessageReady()) throw std::runtime_error("no message");
		RR_INTRUSIVE_PTR<Message> m2 = r->GetNextMessage();

		MessageSerializationTest::CompareMessage(m, m2);

		//std::cout << "Got message" << std::endl;

	}

	void AsyncMessageReaderTest::RandomTest(size_t iterations)
	{
		mt19937 rng;
		rng.seed((uint32_t)std::time(0));

		for (size_t i = 0; i < iterations; i++)
		{
			RR_INTRUSIVE_PTR<Message> m = MessageSerializationTest::NewRandomTestMessage(rng);
			DoTest(m, 2, rng);
			if (i % 10 == 0)
			{
				std::cout << "Message read: " << i << " size: " << m->ComputeSize() << std::endl;
			}
		}
	}

	void AsyncMessageReaderTest::RandomTest4(size_t iterations)
	{
		mt19937 rng;
		rng.seed((uint32_t)std::time(0));

		for (size_t i = 0; i < iterations; i++)
		{
			RR_INTRUSIVE_PTR<Message> m = MessageSerializationTest4::NewRandomTestMessage4(rng);
			DoTest(m, 4, rng);
			if (i % 10 == 0)
			{
				std::cout << "Message4 read: " << i << " size: " << m->ComputeSize4() << std::endl;
			}
		}
	}

	void AsyncMessageReaderTest::LoadRandomTest()
	{
		boost::shared_array<uint8_t> buf;
		size_t message_size = 0;

		std::ifstream f("message.dat", std::ios::binary);
		f.unsetf(std::ios::skipws);

		//Write to stream and read back
		f.seekg(0, std::ios::end);
		message_size = f.tellg();
		f.seekg(0, std::ios::beg);
		buf.reset(new uint8_t[message_size]);

		std::copy(std::istream_iterator<uint8_t>(f), std::istream_iterator<uint8_t>(), buf.get());
		f.close();

		RR_INTRUSIVE_PTR<Message> m = CreateMessage();
		ArrayBinaryReader a_reader(buf.get(), 0, message_size);

		m->Read4(a_reader);

		RR_SHARED_PTR<AsyncMessageReader> r = AsyncMessageReader::CreateInstance();
		r->Reset();
		const_buffers buf2;
		buf2.push_back(boost::asio::buffer(buf.get(), message_size));
		mutable_buffers continue_bufs;
		while (boost::asio::buffer_size(buf2) > 0)
		{
			size_t n1 = boost::asio::buffer_size(buf2);
			n1 = std::min(n1, (size_t)23);
			size_t new_size = (n1 * rand()) / RAND_MAX;
			new_size = std::max(new_size, (size_t)16);
			new_size = std::min(new_size, n1);

			const_buffers buf3 = buffers_truncate(buf2, new_size);
			size_t buf_used;
			if (boost::asio::buffer_size(continue_bufs) == 0)
			{
				r->Read4(buf3, buf_used, 0, continue_bufs);
				buffers_consume(buf2, buf_used);
			}
			else
			{
				size_t n = boost::asio::buffer_copy(continue_bufs, buf3);
				const_buffers empty;
				continue_bufs.clear();

				r->Read4(empty, buf_used, n, continue_bufs);

				if (buf_used != 0) throw std::runtime_error("huh?");
				buffers_consume(buf2, n);
			}
			//std::cout << "Read " << buf_used << " continue_bufs: " << boost::asio::buffer_size(continue_bufs) << std::endl;
		}

		if (!r->MessageReady()) throw std::runtime_error("no message");
		RR_INTRUSIVE_PTR<Message> m2 = r->GetNextMessage();

		MessageSerializationTest::CompareMessage(m, m2);

		std::cout << "Read message" << std::endl;

	}

	void AsyncMessageWriterTest::Test()
	{
		Test1();
	}
	void AsyncMessageWriterTest::Test1()
	{
		mt19937 rng;
		rng.seed((uint32_t)std::time(0));

		{
			RR_INTRUSIVE_PTR<Message> m1 = MessageSerializationTest::NewTestMessage();
			m1->header->MessageID = 10322;
			m1->header->MessageResID = 8364;
			DoTest(m1, 2, rng);
		}
		{
			RR_INTRUSIVE_PTR<Message> m2 = MessageSerializationTest::NewTestMessage();
			m2->entries.push_back(CreateMessageEntry());
			DoTest(m2, 4, rng);
		}
		{
			RR_INTRUSIVE_PTR<Message> m3 = MessageSerializationTest::NewTestMessage();
			m3->entries.resize(1);
			DoTest(m3, 4, rng);
		}
		{
			RR_INTRUSIVE_PTR<Message> m4 = MessageSerializationTest::NewTestMessage();

			m4->entries.at(1)->EntryFlags = MessageEntryFlags_ERROR;
			m4->entries.at(1)->Error = MessageErrorType_DataSerializationError;
			m4->entries.at(1)->RequestID = 0;
			m4->entries.at(2)->EntryFlags = MessageEntryFlags_SERVICE_PATH_CODE | MessageEntryFlags_MEMBER_NAME_CODE;
			m4->entries.at(2)->ServicePathCode = 7;
			m4->entries.at(2)->MemberNameCode = 13;
			m4->entries.at(0)->elements.at(0)->ElementFlags = MessageElementFlags_ELEMENT_NUMBER;
			m4->entries.at(0)->elements.at(0)->ElementNumber = 7483948;
			m4->entries.at(0)->elements.at(1)->ElementFlags = MessageElementFlags_ELEMENT_NAME_CODE | MessageElementFlags_ELEMENT_TYPE_NAME_CODE;
			m4->entries.at(0)->elements.at(1)->ElementNameCode = 5;
			m4->entries.at(0)->elements.at(1)->ElementTypeNameCode = 11;
			m4->entries.at(0)->elements.at(2)->ElementNumber = -113;
			DoTest(m4, 4, rng);
		}
	}

	void AsyncMessageWriterTest::DoTest(RR_INTRUSIVE_PTR<RobotRaconteur::Message> m, uint16_t version, boost::random::mt19937& rng)
	{
		//WriteMessage(m, version);

		boost::shared_array<uint8_t> buf;
		size_t message_size = 0;

		if (version == 2)
		{
			message_size = m->ComputeSize();
		}
		else if (version == 4)
		{
			message_size = m->ComputeSize4();
			boost::shared_array<uint8_t> sync_buf(new uint8_t[message_size]);
			ArrayBinaryWriter sync_writer(sync_buf.get(), 0, message_size);
			m->Write4(sync_writer);
		}
		else
		{
			throw std::runtime_error("");
		}

		buf.reset(new uint8_t[message_size]);
		boost::asio::mutable_buffer buf2(buf.get(), message_size);

		AsyncMessageWriter::return_type ret = AsyncMessageWriter::WriteReturn_continue;

		RR_SHARED_PTR<AsyncMessageWriter> wr = AsyncMessageWriter::CreateInstance();
		wr->BeginWrite(m, version);

		do
		{
			boost::shared_array<uint8_t> work_buf1(new uint8_t[4096]);
			mutable_buffers work_bufs;
			work_bufs.push_back(boost::asio::buffer(work_buf1.get(), 4096));
			const_buffers write_bufs;
			size_t work_bufs_used;

			boost::random::uniform_int_distribution<size_t> quota_dist(0, 16*1024);
			size_t quota = quota_dist(rng);

			if (version == 2)
			{
				ret = wr->Write(quota, work_bufs, work_bufs_used, write_bufs);
			}
			else if (version == 4)
			{
				ret=wr->Write4(quota, work_bufs, work_bufs_used, write_bufs);
			}
			else
			{
				throw std::runtime_error("");
			}

			size_t n = boost::asio::buffer_copy(buf2, write_bufs);
			buf2 = buf2 + n;
		} while (ret != AsyncMessageWriter::WriteReturn_done);

		if (boost::asio::buffer_size(buf2) != 0) throw std::runtime_error("");

		RR_INTRUSIVE_PTR<Message> m2=CreateMessage();
		ArrayBinaryReader r(buf.get(), 0, message_size);
		if (version == 2)
		{
			m2->Read(r);
			if (r.Position() != message_size)
				throw std::runtime_error("");
		}
		else if (version == 4)
		{
			m2->Read4(r);
			if (r.Position() != message_size)
				throw std::runtime_error("");
		}
		else
		{
			throw std::runtime_error("");
		}

		MessageSerializationTest::CompareMessage(m, m2);
	}

	void AsyncMessageWriterTest::RandomTest(size_t iterations)
	{
		mt19937 rng;
		rng.seed((uint32_t)std::time(0));

		for (size_t i = 0; i < iterations; i++)
		{
			RR_INTRUSIVE_PTR<Message> m = MessageSerializationTest::NewRandomTestMessage(rng);
			DoTest(m, 2, rng);
			if (i % 10 == 0)
			{
				std::cout << "Message write: " << i << " size: " << m->ComputeSize() << std::endl;
			}
		}
	}

	void AsyncMessageWriterTest::RandomTest4(size_t iterations)
	{
		mt19937 rng;
		rng.seed((uint32_t)std::time(0));

		for (size_t i = 0; i < iterations; i++)
		{
			RR_INTRUSIVE_PTR<Message> m = MessageSerializationTest4::NewRandomTestMessage4(rng);

			DoTest(m, 4, rng);
			if (i % 10 == 0)
			{
				std::cout << "Message4 write: " << i << " size: " << m->ComputeSize4() << std::endl;
			}

		}
	}

	void AsyncMessageWriterTest::WriteMessage(RR_INTRUSIVE_PTR<Message> m, uint16_t version)
	{
		size_t message_size;
		boost::shared_array<uint8_t> buf;
		if (version == 2)
		{
			message_size = m->ComputeSize();
			buf.reset(new uint8_t[message_size]);
			ArrayBinaryWriter w(buf.get(), 0, message_size);
			m->Write(w);
		}
		else if (version==4)
		{
			message_size = m->ComputeSize4();
			buf.reset(new uint8_t[message_size]);
			ArrayBinaryWriter w(buf.get(), 0, message_size);
			m->Write4(w);
		}
		else
		{
			throw std::runtime_error("");
		}

		std::ofstream f("message.dat", std::ios::binary);
		f.unsetf(std::ios::skipws);
		std::copy(buf.get(), buf.get() + message_size, std::ostream_iterator<uint8_t>(f));
		f.close();
	}

	void AsyncMessageWriterTest::LoadRandomTest()
	{
		mt19937 rng;
		rng.seed((uint32_t)std::time(0));

		boost::shared_array<uint8_t> buf;
		size_t message_size = 0;

		std::ifstream f("message.dat", std::ios::binary);
		f.unsetf(std::ios::skipws);

		//Write to stream and read back
		f.seekg(0, std::ios::end);
		message_size = f.tellg();
		f.seekg(0, std::ios::beg);
		buf.reset(new uint8_t[message_size]);

		std::copy(std::istream_iterator<uint8_t>(f), std::istream_iterator<uint8_t>(), buf.get());
		f.close();

		RR_INTRUSIVE_PTR<Message> m = CreateMessage();
		ArrayBinaryReader a_reader(buf.get(), 0, message_size);
		uint16_t version_minor;
		m->Read4(a_reader);

		DoTest(m, 4, rng);

	}

}

max_stars_repo_name: robotraconteur/robotraconteur

max_issues_repo_name: robotraconteur/robotraconteur

max_forks_repo_name: robotraconteur/robotraconteur


text:
#define BOOST_TEST_MODULE ygodata
#include <boost/test/unit_test.hpp>
#include <ygo/data/Serialize.h>

BOOST_AUTO_TEST_SUITE(Serialize)

// check for round trip
#define RT_CHECK(x, t) ygo::data::t::x == \
    ygo::data::to##t (ygo::data::from##t (ygo::data::t::x))

BOOST_AUTO_TEST_CASE(CardType)
{
    BOOST_CHECK(RT_CHECK(MONSTER, CardType));
    BOOST_CHECK(RT_CHECK(SPELL, CardType));
    BOOST_CHECK(RT_CHECK(TRAP, CardType));
}

BOOST_AUTO_TEST_CASE(Attribute)
{
    BOOST_CHECK(RT_CHECK(NONE, Attribute));
    BOOST_CHECK(RT_CHECK(DARK, Attribute));
    BOOST_CHECK(RT_CHECK(DIVINE, Attribute));
    BOOST_CHECK(RT_CHECK(EARTH, Attribute));
    BOOST_CHECK(RT_CHECK(FIRE, Attribute));
    BOOST_CHECK(RT_CHECK(LIGHT, Attribute));
    BOOST_CHECK(RT_CHECK(WATER, Attribute));
    BOOST_CHECK(RT_CHECK(WIND, Attribute));
}

BOOST_AUTO_TEST_CASE(Type)
{
    BOOST_CHECK(RT_CHECK(NONE, Type));
    BOOST_CHECK(RT_CHECK(AQUA, Type));
    BOOST_CHECK(RT_CHECK(BEAST, Type));
    BOOST_CHECK(RT_CHECK(BEASTWARRIOR, Type));
    BOOST_CHECK(RT_CHECK(CREATORGOD, Type));
    BOOST_CHECK(RT_CHECK(DINOSAUR, Type));
    BOOST_CHECK(RT_CHECK(DIVINEBEAST, Type));
    BOOST_CHECK(RT_CHECK(DRAGON, Type));
    BOOST_CHECK(RT_CHECK(FAIRY, Type));
    BOOST_CHECK(RT_CHECK(FIEND, Type));
    BOOST_CHECK(RT_CHECK(FISH, Type));
    BOOST_CHECK(RT_CHECK(INSECT, Type));
    BOOST_CHECK(RT_CHECK(MACHINE, Type));
    BOOST_CHECK(RT_CHECK(PLANT, Type));
    BOOST_CHECK(RT_CHECK(PSYCHIC, Type));
    BOOST_CHECK(RT_CHECK(PYRO, Type));
    BOOST_CHECK(RT_CHECK(REPTILE, Type));
    BOOST_CHECK(RT_CHECK(ROCK, Type));
    BOOST_CHECK(RT_CHECK(SEASERPENT, Type));
    BOOST_CHECK(RT_CHECK(SPELLCASTER, Type));
    BOOST_CHECK(RT_CHECK(THUNDER, Type));
    BOOST_CHECK(RT_CHECK(WARRIOR, Type));
    BOOST_CHECK(RT_CHECK(WINGEDBEAST, Type));
    BOOST_CHECK(RT_CHECK(WYRM, Type));
    BOOST_CHECK(RT_CHECK(ZOMBIE, Type));
}

BOOST_AUTO_TEST_CASE(MonsterType)
{
    BOOST_CHECK(RT_CHECK(NONE, MonsterType));
    BOOST_CHECK(RT_CHECK(NORMAL, MonsterType));
    BOOST_CHECK(RT_CHECK(EFFECT, MonsterType));
    BOOST_CHECK(RT_CHECK(FUSION, MonsterType));
    BOOST_CHECK(RT_CHECK(RITUAL, MonsterType));
    BOOST_CHECK(RT_CHECK(SYNCHRO, MonsterType));
    BOOST_CHECK(RT_CHECK(XYZ, MonsterType));
    BOOST_CHECK(RT_CHECK(PENDULUM, MonsterType));
    BOOST_CHECK(RT_CHECK(TOKEN, MonsterType));
    BOOST_CHECK(RT_CHECK(FLIP, MonsterType));
    BOOST_CHECK(RT_CHECK(TOON, MonsterType));
    BOOST_CHECK(RT_CHECK(SPIRIT, MonsterType));
    BOOST_CHECK(RT_CHECK(UNION, MonsterType));
    BOOST_CHECK(RT_CHECK(GEMINI, MonsterType));
    BOOST_CHECK(RT_CHECK(TUNER, MonsterType));
}

BOOST_AUTO_TEST_CASE(SpellType)
{
    BOOST_CHECK(RT_CHECK(NONE, SpellType));
    BOOST_CHECK(RT_CHECK(NORMAL, SpellType));
    BOOST_CHECK(RT_CHECK(CONTINUOUS, SpellType));
    BOOST_CHECK(RT_CHECK(FIELD, SpellType));
    BOOST_CHECK(RT_CHECK(EQUIP, SpellType));
    BOOST_CHECK(RT_CHECK(QUICK, SpellType));
    BOOST_CHECK(RT_CHECK(RITUAL, SpellType));
}

BOOST_AUTO_TEST_CASE(TrapType)
{
    BOOST_CHECK(RT_CHECK(NONE, TrapType));
    BOOST_CHECK(RT_CHECK(NORMAL, TrapType));
    BOOST_CHECK(RT_CHECK(CONTINUOUS, TrapType));
    BOOST_CHECK(RT_CHECK(COUNTER, TrapType));
}

BOOST_AUTO_TEST_CASE(Location)
{
    BOOST_CHECK(RT_CHECK(DECK, Location));
    BOOST_CHECK(RT_CHECK(EXTRA, Location));
    BOOST_CHECK(RT_CHECK(HAND, Location));
    BOOST_CHECK(RT_CHECK(GRAVEYARD, Location));
    BOOST_CHECK(RT_CHECK(BANISHED, Location));
    BOOST_CHECK(RT_CHECK(FIELD, Location));
    BOOST_CHECK(RT_CHECK(LPENDULUM, Location));
    BOOST_CHECK(RT_CHECK(RPENDULUM, Location));
    BOOST_CHECK(RT_CHECK(LIMBO, Location));
    BOOST_CHECK(RT_CHECK(M1, Location));
    BOOST_CHECK(RT_CHECK(M2, Location));
    BOOST_CHECK(RT_CHECK(M3, Location));
    BOOST_CHECK(RT_CHECK(M4, Location));
    BOOST_CHECK(RT_CHECK(M5, Location));
    BOOST_CHECK(RT_CHECK(S1, Location));
    BOOST_CHECK(RT_CHECK(S2, Location));
    BOOST_CHECK(RT_CHECK(S3, Location));
    BOOST_CHECK(RT_CHECK(S4, Location));
    BOOST_CHECK(RT_CHECK(S5, Location));
}

BOOST_AUTO_TEST_CASE(Position)
{
    BOOST_CHECK(RT_CHECK(FACEDOWN, Position));
    BOOST_CHECK(RT_CHECK(FACEUP, Position));
}

BOOST_AUTO_TEST_CASE(BattlePosition)
{
    BOOST_CHECK(RT_CHECK(NONE, BattlePosition));
    BOOST_CHECK(RT_CHECK(ATTACK, BattlePosition));
    BOOST_CHECK(RT_CHECK(DEFENSE, BattlePosition));
}

BOOST_AUTO_TEST_CASE(Format)
{
    BOOST_CHECK(RT_CHECK(TRADITIONAL, Format));
    BOOST_CHECK(RT_CHECK(ADVANCED, Format));
    BOOST_CHECK(RT_CHECK(MEGABANNED, Format));
}

BOOST_AUTO_TEST_CASE(Limitation)
{
    BOOST_CHECK(RT_CHECK(ILLEGAL, Limitation));
    BOOST_CHECK(RT_CHECK(FORBIDDEN, Limitation));
    BOOST_CHECK(RT_CHECK(LIMITED, Limitation));
    BOOST_CHECK(RT_CHECK(SEMILIMITED, Limitation));
    BOOST_CHECK(RT_CHECK(UNLIMITED, Limitation));
}

BOOST_AUTO_TEST_CASE(DeckType)
{
    BOOST_CHECK(RT_CHECK(MAIN, DeckType));
    BOOST_CHECK(RT_CHECK(SIDE, DeckType));
    BOOST_CHECK(RT_CHECK(EXTRA, DeckType));
}

void scd_check_eq(ygo::data::StaticCardData s, ygo::data::StaticCardData rts)
{
    BOOST_CHECK(s.name == rts.name);
    BOOST_CHECK(s.cardType == rts.cardType);
    BOOST_CHECK(s.attribute == rts.attribute);
    BOOST_CHECK(s.monsterType == rts.monsterType);
    BOOST_CHECK(s.type == rts.type);
    BOOST_CHECK(s.monsterAbility == rts.monsterAbility);
    BOOST_CHECK(s.level == rts.level);
    BOOST_CHECK(s.attack == rts.attack);
    BOOST_CHECK(s.defense == rts.defense);
    BOOST_CHECK(s.lpendulum == rts.lpendulum);
    BOOST_CHECK(s.rpendulum == rts.rpendulum);
    BOOST_CHECK(s.spellType == rts.spellType);
    BOOST_CHECK(s.trapType == rts.trapType);
    BOOST_CHECK(s.text == rts.text);
}

BOOST_AUTO_TEST_CASE(CardMap)
{
    ygo::data::StaticCardData c1 = {
        "Test1",
        ygo::data::CardType::MONSTER,
        ygo::data::Attribute::DARK,
        ygo::data::MonsterType::NORMAL,
        ygo::data::Type::BEAST,
        ygo::data::MonsterType::NONE,
        4,
        1000,
        2000,
        0,
        0,
        ygo::data::SpellType::NONE,
        ygo::data::TrapType::NONE,
        "Example card 1"
    };

    ygo::data::StaticCardData c2 = {
        "Test2",
        ygo::data::CardType::SPELL,
        ygo::data::Attribute::NONE,
        ygo::data::MonsterType::NONE,
        ygo::data::Type::NONE,
        ygo::data::MonsterType::NONE,
        0,
        0,
        0,
        0,
        0,
        ygo::data::SpellType::CONTINUOUS,
        ygo::data::TrapType::NONE,
        "Example card 2"
    };

    ygo::data::StaticCardData c3 = {
        "Test3",
        ygo::data::CardType::TRAP,
        ygo::data::Attribute::NONE,
        ygo::data::MonsterType::NONE,
        ygo::data::Type::NONE,
        ygo::data::MonsterType::NONE,
        0,
        0,
        0,
        0,
        0,
        ygo::data::SpellType::NONE,
        ygo::data::TrapType::COUNTER,
        "Example card 3"
    };

    ygo::data::StaticCardData c4 = {
        "Test4",
        ygo::data::CardType::TRAP,
        ygo::data::Attribute::NONE,
        ygo::data::MonsterType::NONE,
        ygo::data::Type::NONE,
        ygo::data::MonsterType::NONE,
        0,
        0,
        0,
        0,
        0,
        ygo::data::SpellType::NONE,
        ygo::data::TrapType::NORMAL,
        "Example card 4"
    };

    ygo::data::StaticCardData c5 = {
        "Test5",
        ygo::data::CardType::MONSTER,
        ygo::data::Attribute::FIRE,
        ygo::data::MonsterType::SYNCHRO,
        ygo::data::Type::DINOSAUR,
        ygo::data::MonsterType::EFFECT,
        8,
        2500,
        1700,
        0,
        0,
        ygo::data::SpellType::NONE,
        ygo::data::TrapType::NONE,
        "Example card 5"
    };

    ygo::data::CardMap deck = {
        {ygo::data::DeckType::MAIN, { c1, c2, c3 }},
        {ygo::data::DeckType::SIDE, { c2, c4 }},
        {ygo::data::DeckType::EXTRA, { c5 } } };
    auto main = deck[ygo::data::DeckType::MAIN];
    auto side = deck[ygo::data::DeckType::SIDE];
    auto extra = deck[ygo::data::DeckType::EXTRA];

    auto rtdeck = ygo::data::toCardMap(fromCardMap(deck));
    auto rtmain = rtdeck[ygo::data::DeckType::MAIN];
    auto rtside = rtdeck[ygo::data::DeckType::SIDE];
    auto rtextra = rtdeck[ygo::data::DeckType::EXTRA];

    BOOST_CHECK_EQUAL(deck.size(), rtdeck.size());
    BOOST_CHECK_EQUAL(main.size(), rtmain.size());
    BOOST_CHECK_EQUAL(side.size(), rtside.size());
    BOOST_CHECK_EQUAL(extra.size(), rtextra.size());

    for (auto i = 0; i < main.size(); i++) {
        scd_check_eq(main[i], rtmain[i]);
    }

    for (auto i = 0; i < side.size(); i++) {
        scd_check_eq(side[i], rtside[i]);
    }

    for (auto i = 0; i < extra.size(); i++) {
        scd_check_eq(extra[i], rtextra[i]);
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: DeonPoncini/ygodata

max_issues_repo_name: DeonPoncini/ygodata

max_forks_repo_name: DeonPoncini/ygodata


text:
/**
 * BCL to FASTQ file converter
 * Copyright (c) 2007-2017 Illumina, Inc.
 *
 * This software is covered by the accompanying EULA
 * and certain third party copyright/licenses, and any user of this
 * source file is bound by the terms therein.
 *
 * \file CsvGrammar.hpp
 *
 * \brief Basic CSV grammar.
 *
 * \author Roman Petrovski
 * \author Marek Balint
 */

#ifndef BCL2FASTQ_COMMON_CSVGRAMMAR_HPP
#define BCL2FASTQ_COMMON_CSVGRAMMAR_HPP

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>

#include "common/Exceptions.hh"

namespace bcl2fastq {

namespace common {

template <typename Iterator>
CsvGrammar<Iterator>::CsvGrammar()
: CsvGrammar::base_type(start_)
{
    using boost::spirit::omit;
    using boost::spirit::qi::_val;
    using boost::spirit::qi::_1;
    using boost::spirit::ascii::char_;
    using boost::phoenix::push_back;

    // CSV ABNF mainly taken from http://www.ietf.org/rfc/rfc4180.txt
    // with some modification to make sample sheet users life easier
    cr_ = char_('\x0d');
    lf_ = char_('\x0a');
    crlf_ = +(cr_ | lf_); // unlike the real csv, sample sheets often get mixed line endings
    comma_ = char_(',');
    comma_.name(",");
    dquote_ = char_('"');

    //textData_ = char_('\x20', '\x21') | char_('\x23', '\x2b') | char_('\x2d', '\x7e');
    textData_ = char_('\x20', '\x7e') - (char_(',') | char_('"'));

    /// \todo Refactoring: Probably omit[dquote_] should be used.
    escaped_ = dquote_
        >> *(textData_[push_back(_val, _1)] |
            comma_[push_back(_val, _1)] |
            cr_[push_back(_val, _1)] |
            lf_[push_back(_val, _1)] |
            (dquote_ >> dquote_)[push_back(_val, '"')])
        >> dquote_
    ;

    nonEscaped_ = *textData_;

    field_ = escaped_ | nonEscaped_;

    commentLine_ = char_('#') >> *(char_('\x00', '\x7e') - crlf_);

    dataLine_ = field_ % comma_;

    line_ = *(commentLine_ >> +crlf_) >> dataLine_ >> *(+crlf_ >> commentLine_);

    start_ = line_ % crlf_ >> *crlf_;
}

template<typename Iterator>
CsvGrammarAttribute parseCsvData(Iterator csvDataBegin, Iterator csvDataEnd)
{
    common::CsvGrammar<Iterator> parser;

    common::CsvGrammarAttribute csvData;
    if (!boost::spirit::qi::parse(csvDataBegin, csvDataEnd, parser, csvData) || csvDataEnd != csvDataBegin)
    {
        int errnum = errno;
        const std::string message = "Could not parse the CSV stream text:\n"
             + std::string(csvDataBegin, csvDataEnd)
        ;
        BOOST_THROW_EXCEPTION(common::InputDataError(errnum, message));
    }

    correctCsvColumnsCount(csvData, "");
    return csvData;
}

} // namespace common

} // namespace bcl2fastq

#endif //BCL2FASTQ_COMMON_CSVGRAMMAR_HPP


text:
#include <azule/utilities/String.h>
#include <boost/spirit/include/karma.hpp>

// AMS // 10/6/2019 // Unsupported by gcc v9.0.1
// std::string age::core::ToString(float x, int precision, std::chars_format fmt)
// {
// 	// Defined a buffer size that can support std::numeric_limits<float>::max() with max precision std::numeric_limits<float>::maxdigits10.
// 	std::array<char, 64> buffer{};
//
// 	auto [p, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), x, fmt, precision);
//
// 	if(ec == std::errc())
// 	{
// 		return std::string(buffer.data(), static_cast<size_t>(p - buffer.data()));
// 	}
//
// 	return {};
// }

// AMS // 10/6/2019 // Unsupported by gcc v9.0.1
// std::string age::core::ToString(double x, int precision, std::chars_format fmt)
// {
// 	// Defined a buffer size that can support std::numeric_limits<double>::max() with max precision std::numeric_limits<double>::maxdigits10.
// 	std::array<char, 512> buffer{};
//
// 	auto [p, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), x, fmt, precision);
//
// 	if(ec == std::errc())
// 	{
// 		return std::string(buffer.data(), static_cast<size_t>(p - buffer.data()));
// 	}
//
// 	return {};
// }

namespace
{
	///
	/// http://stackoverflow.com/questions/42255919/using-boost-karma-to-replace-stdstringstream-for-double-to-stdstring-convers
	///
	struct precision_policy_double : boost::spirit::karma::real_policies<double>
	{
		precision_policy_double(int prec) : precision_(prec)
		{
		}

		int precision(double) const
		{
			return precision_;
		}
		int precision_;
	};

	struct precision_policy_float : boost::spirit::karma::real_policies<float>
	{
		precision_policy_float(int prec) : precision_(prec)
		{
		}

		int precision(float) const
		{
			return precision_;
		}
		int precision_;
	};
}

std::string azule::ToString(float x, int precision)
{
	using boost::spirit::ascii::space;
	using boost::spirit::karma::generate;
	using boost::spirit::karma::real_generator;

	real_generator<float, precision_policy_float> value(precision);

	std::string s;
	std::back_insert_iterator<std::string> sink(s);
	generate(sink, value, x);
	return s;
}

std::string azule::ToString(double x, int precision)
{
	using boost::spirit::ascii::space;
	using boost::spirit::karma::generate;
	using boost::spirit::karma::real_generator;

	real_generator<double, precision_policy_double> value(precision);

	std::string s;
	std::back_insert_iterator<std::string> sink(s);
	generate(sink, value, x);
	return s;
}


text:
#include "tag_hierarchy/tag_hierarchy.h"

#include "models/models.h"

#include <boost/graph/adj_list_serialize.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/pending/indirect_cmp.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/variant.hpp>
#include <boost/serialization/vector.hpp>

#include <functional>
#include <tag_hierarchy/commands/command.h>

using VertexIterator = boost::graph_traits<TagHierarchyGraph>::vertex_iterator;
using InEdgeIterator = TagHierarchyGraph::in_edge_iterator;
using OutEdgeIterator = TagHierarchyGraph::out_edge_iterator;

using DispatchFunction =
    std::function<std::vector<NodeType>(std::vector<NodeType>&)>;

class TagHierarchyImpl {
private:
    TagHierarchyGraph graph_;
    std::unordered_map<std::string, VertexT> vertices_;
    std::map<std::string, DispatchFunction> command_func_dispatch_;
    EdgeLabelMap edge_labels_;
    VertexT root_;

public:

    TagHierarchyGraph& GetGraph() {
        return graph_;
    }

    std::unordered_map<std::string, VertexT>& GetVertices() {
        return vertices_;
    }

    EdgeLabelMap& GetEdgeLabels() {
        return edge_labels_;
    }

    VertexT& GetRoot() {
        return root_;
    }

    std::map<std::string, DispatchFunction> GetDispatchMap() {
        return command_func_dispatch_;
    }

    std::vector<NodeType>
    Store(std::vector<NodeType>& message) {
        auto retval = std::vector<NodeType>();
        std::ostringstream stream;
        {
            boost::iostreams::filtering_stream<boost::iostreams::output> f;
            f.push(boost::iostreams::gzip_compressor());
            f.push(stream);
            boost::archive::binary_oarchive archive(f);
            archive << *this;
        }
        retval.push_back({{"serialized_graph", stream.str()}});
        return retval;
    }

    std::vector<NodeType>
    Restore(std::vector<NodeType>& message) {
        ClearGraph();
        auto retval = std::vector<NodeType>();
        const std::string graph_state =
            boost::get<std::string>(message[0]["serialized_hierarchy"]);
        std::istringstream buffer(graph_state);
        boost::iostreams::filtering_stream<boost::iostreams::input> f;
        f.push(boost::iostreams::gzip_decompressor());
        f.push(buffer);
        boost::archive::binary_iarchive archive(f);
        archive >> *this;
        retval.push_back({{"success", true}});
        return retval;
    }

    std::vector<NodeType>
    HealthCheck(std::vector<NodeType>& message) {
        auto retval = std::vector<NodeType>();
        if (root_ == std::numeric_limits<VertexT>::max()) {
            retval.push_back({{std::string("ok"), false},
                              {std::string("error"), std::string("Cache not populated")}});
            return retval;
        }
        retval.push_back({{std::string("ok"), true}});
        return retval;
    }

    void
    ClearGraph() {
        graph_.clear();
        vertices_.clear();
        root_ = std::numeric_limits<VertexT>::max();
    }

    std::vector<NodeType>
    Handle(std::vector<NodeType> &message)
    {
        auto command_map = message.at(0);
        std::string command = boost::get<std::string>(command_map["command"]);
        auto func = command_func_dispatch_[command];
        auto retval = func(message);
        return retval; //command_func_dispatch_[command](message);
    }

    TagHierarchyImpl() : command_func_dispatch_({
                             {"store", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {
                                  return this->Store(nodes);
                              }},
                             {"restore", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {
                                  return this->Restore(nodes);
                              }},
                             {"flush", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {
                                  this->ClearGraph();
                                  return {{{std::string("success"), std::string("hierarchy flushed")}}};
                              }},
                             {"healthcheck", [this](std::vector<NodeType> &nodes) -> std::vector<NodeType> {
                                  return this->HealthCheck(nodes);
                              }},
                         }),
                         edge_labels_({{{"Physical hierarchy", 0}}}),
                         root_(std::numeric_limits<VertexT>::max())
    {
    };
    TagHierarchyImpl(const TagHierarchyImpl& in) : command_func_dispatch_(in.command_func_dispatch_) {}

    void Register(Command& in, std::string name) {
        auto func = in.Function();
        command_func_dispatch_[name] = func;
    }

    template<typename Archive>
    void save(Archive& ar, const unsigned int version) const {
        ar & graph_;
        ar & edge_labels_;
    }

    template<typename Archive>
    void load(Archive& ar, const unsigned int version) {
        ar & graph_;
        ar & edge_labels_;
        auto [start, end] = boost::vertices(graph_);
        for (auto iter = start; iter != end; ++iter) {
            if (graph_[*iter].id == "root") {
                root_ = *iter;
            }
            vertices_[graph_[*iter].id] = *iter;
        }
    }
    BOOST_SERIALIZATION_SPLIT_MEMBER()
};

std::vector<NodeType>
TagHierarchy::Handle(std::vector<NodeType>& message) {
    return GetTagHierarchy().Handle(message);
}

TagHierarchyImpl&
TagHierarchy::GetTagHierarchy() {
    static TagHierarchyImpl taghierarchy_impl;
    return taghierarchy_impl;
}

TagHierarchyGraph&
TagHierarchy::GetGraph() {
    return GetTagHierarchy().GetGraph();
}

std::unordered_map<std::string, VertexT>&
TagHierarchy::GetVertices() {
    return GetTagHierarchy().GetVertices();
}

EdgeLabelMap &
TagHierarchy::GetEdgeLabels() {
    return GetTagHierarchy().GetEdgeLabels();
}

VertexT&
TagHierarchy::GetRoot() {
    return GetTagHierarchy().GetRoot();
}

void
TagHierarchy::Register(Command &in, std::string name) {
    GetTagHierarchy().Register(in, name);
}

max_stars_repo_name: equinor/ioc-hierarchy-service

max_issues_repo_name: equinor/ioc-hierarchy-service

max_forks_repo_name: equinor/ioc-hierarchy-service


text:
#include "../src/History.h"
#include "../src/KDOPBroadPhase.h"
#include "../src/Mesh.h"
#include "../src/SeparatingPlaneNarrowPhase.h"
#include "../src/CTCDNarrowPhase.h"
#include <iostream>
#include <fstream>
#include <vector>
#include "Distance.h"
#include <Eigen/Core>
#include "CTCD.h"

using namespace std;
using namespace Eigen;

void loadMesh(const char *filename, VectorXd &verts, Matrix3Xi &faces)
{
	ifstream ifs(filename);
	if(!ifs)
		return;

	vector<double> pos;
	vector<int> faceidx;

	while(true)
	{
		char c;
		ifs >> c;
		if(!ifs)
			break;
		if(c == 'v')
		{
			for(int i=0; i<3; i++)
			{
				double p;
				ifs >> p;
				pos.push_back(p);
			}
		}
		if(c == 'f')
		{
			for(int i=0; i<3; i++)
			{
				int vert;
				ifs >> vert;
				faceidx.push_back(vert);
			}
		}
	}

	int nverts = pos.size()/3;
	int nfaces = faceidx.size()/3;

	verts.resize(3*nverts);
	for(int i=0; i<3*nverts; i++)
		verts[i] = pos[i];

	faces.resize(3, nfaces);
	for(int i=0; i<nfaces; i++)
		for(int j=0; j<3; j++)
			faces.coeffRef(j, i) = faceidx[3*i+j]-1;
}

int main(int argc, char *argv[])
{
	if(argc != 3)
	{
		std::cerr << "Usage: AlecTest (initial mesh) (final mesh)" << std::endl;
		return -1;
	}
	VectorXd initialv;
	Matrix3Xi faces;
	loadMesh(argv[1], initialv, faces);
	int numcoarseverts = initialv.size()/3;
	std::cout << "Loaded initial mesh with " << numcoarseverts << " vertices and " << faces.cols() << " faces" << std::endl;

	VectorXd finalv;
	loadMesh(argv[2], finalv, faces);
	std::cout << "Loaded final mesh with " << finalv.size()/3 << " vertices and " << faces.cols() << " faces" << std::endl;

  // Build data structures: mesh and history (trajectories)
  Mesh m;
  m.faces = faces;
  // These are needed but ignored
  m.vertices = initialv;
  History h(initialv);
  h.finishHistory( finalv);

  // Broadphase to collect candidate vertex-face and edge-edge collisions
  const double outerEta = 1e-8;
  std::set<VertexFaceStencil> can_vfs;
  std::set<EdgeEdgeStencil> can_ees;
  std::set<std::pair<VertexFaceStencil,double> > can_vfs_eta;
  std::set<std::pair<EdgeEdgeStencil,double> > can_ees_eta;
  // No fixed vertices
  const std::set<int> fixedVerts;
  KDOPBroadPhase().findCollisionCandidates(h,m,outerEta,can_vfs,can_ees,fixedVerts);
  // Narrowphase
  const double innerEta = 1e-8;
  for(std::set<VertexFaceStencil>::iterator it = can_vfs.begin(); it != can_vfs.end(); ++it)
  {
    can_vfs_eta.insert(std::pair<VertexFaceStencil,double>(*it, innerEta));
  }
  for(std::set<EdgeEdgeStencil>::iterator it = can_ees.begin(); it != can_ees.end(); ++it)
  {
    can_ees_eta.insert(std::pair<EdgeEdgeStencil,double>(*it, innerEta));
  }
  std::set<VertexFaceStencil> ctcdvfs;
  {
    std::set<EdgeEdgeStencil> ees;
    CTCDNarrowPhase().findCollisions(h,can_vfs_eta,can_ees_eta,ctcdvfs,ees);
    std::cout<<"CTCDNarrowPhase:"<<std::endl;
    std::cout<<"  "<<ctcdvfs.size()<<" vf collisions"<<std::endl;
    std::cout<<"  "<<ees.size()<<" ee collisions"<<std::endl;
  }
  {
    std::set<VertexFaceStencil> vfs;
    std::set<EdgeEdgeStencil> ees;
    SeparatingPlaneNarrowPhase().findCollisions(h,can_vfs_eta,can_ees_eta,vfs,ees);
    std::cout<<"SeparatingPlaneNarrowPhase:"<<std::endl;
    std::cout<<"  "<<vfs.size()<<" vf collisions"<<std::endl;
    std::cout<<"  "<<ees.size()<<" ee collisions"<<std::endl;

   for(std::set<VertexFaceStencil>::iterator it = ctcdvfs.begin(); it != ctcdvfs.end(); ++it)
	{
		if(vfs.count(*it) == 0)
			cout << it->p << " " << it->q0 << " " << it->q1 << " " << it->q2 << " " << endl;
	}
  }
}

max_stars_repo_name: LamWS/ClothSimulation

max_issues_repo_name: LamWS/ClothSimulation

max_forks_repo_name: LamWS/ClothSimulation


text:
#include <boost/test/unit_test.hpp>
#include "tests/unit/definitions.hpp"
#include "TestContext.hpp"
#include "netlist_paths/Utilities.hpp"

BOOST_FIXTURE_TEST_SUITE(names, TestContext);

/// Verilator cannot inline packages with functions.
BOOST_AUTO_TEST_CASE(orphan_package) {
  BOOST_CHECK_NO_THROW(compile("orphan_package.sv"));
  BOOST_TEST(!np->isEmpty());
}

/// Verilator cannot inline classes.
BOOST_AUTO_TEST_CASE(module_class_no_inline) {
  BOOST_CHECK_NO_THROW(compile("module_class_no_inline.sv"));
  BOOST_TEST(!np->isEmpty());
}

/// Verilator cannot inline interfaces.
BOOST_AUTO_TEST_CASE(interface_no_inline) {
  BOOST_CHECK_NO_THROW(compile("interface_no_inline.sv"));
  BOOST_TEST(np->isEmpty());
}

/// Verilator can flatten public modules.
BOOST_AUTO_TEST_CASE(module_public_no_inline) {
  BOOST_CHECK_NO_THROW(compile("public_module_no_inline.sv"));
  BOOST_TEST(!np->isEmpty());
}

/// Verilator can flatten public modules.
BOOST_AUTO_TEST_CASE(module_no_inline_pragma) {
  BOOST_CHECK_NO_THROW(compile("module_no_inline_pragma.sv"));
  BOOST_TEST(!np->isEmpty());
}

/// Verilator can order variable declarations after their references in the
/// typetable.
BOOST_AUTO_TEST_CASE(dtype_forward_refs) {
  BOOST_CHECK_NO_THROW(load("dtype_forward_refs.xml"));
}

/// Verilator can introduce new variables that are the target of delayed
/// assignments. Since the LHS of delayed assignments are how registers are
/// identified, register types are propagated through assign aliases.
BOOST_AUTO_TEST_CASE(assign_alias_regs) {
  BOOST_CHECK_NO_THROW(load("assign_alias_regs.xml"));
  BOOST_TEST(np->regExists("assign_alias_regs.sum.add.register_q"));
  BOOST_TEST(np->regExists("assign_alias_regs.__Vcellout__sum.add__register_q"));
}

/// Verilator can introduce references to variables in packages that do not
/// have a corresponding variable declaration in a varscope. See
/// https://github.com/jameshanlon/netlist-paths/issues/7
BOOST_AUTO_TEST_CASE(var_no_scope) {
  netlist_paths::Options::getInstance().setLoggingErrorOnly(); // Supress warning about missing scope.
  BOOST_CHECK_NO_THROW(compile("var_no_scope.sv"));
  BOOST_TEST(!np->isEmpty());
  netlist_paths::Options::getInstance().setLoggingQuiet();
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: heiner-bauer/netlist-paths

max_issues_repo_name: heiner-bauer/netlist-paths

max_forks_repo_name: heiner-bauer/netlist-paths


text: #include <boost/interprocess/allocators/cached_adaptive_pool.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#include "test_helpers.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <dirent.h>
#include <errno.h>
#include <ifaddrs.h>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>

#include <boost/filesystem.hpp>

#include "do_persistence.h"
#include "do_port_finder.h"

#include "do_test_helpers.h"
namespace dtu = dotest::util;

#include "test_data.h"

namespace msdod = microsoft::deliveryoptimization::details;

bool TestHelpers::IsActiveProcess(std::string procName)
{
    return _GetPidFromProcName(procName) != -1;
}

// TODO(jimson): Enable starting/shutting down docs as service
int TestHelpers::ShutdownProcess(std::string procName)
{
    if (IsActiveProcess(procName))
    {
        return _KillProcess(_GetPidFromProcName(procName), SIGINT);
    }
    return -1;
}

void TestHelpers::RestartService(const std::string& name)
{
    const auto resetCmd = dtu::FormatString("systemctl reset-failed %s", name.c_str());
    dtu::ExecuteSystemCommand(resetCmd.data()); // avoids hitting start-limit-hit error in systemd

    const auto restartCmd = dtu::FormatString("systemctl restart %s", name.c_str());
    dtu::ExecuteSystemCommand(restartCmd.data());
}

void TestHelpers::StartService(const std::string& name)
{
    dtu::ExecuteSystemCommand(dtu::FormatString("systemctl start %s", name.c_str()).data());
}

void TestHelpers::StopService(const std::string& name)
{
    dtu::ExecuteSystemCommand(dtu::FormatString("systemctl stop %s", name.c_str()).data());
}

int TestHelpers::_KillProcess(int pid, int signal)
{
    try
    {
        return kill(pid, signal);
    }
    catch (...)
    {
        // TODO(jimson): Implement Logging for Tests
        return -1;
    }
}

int TestHelpers::_GetPidFromProcName(std::string procName)
{
    int pid = -1;

    // Open the /proc directory
    DIR *dp = opendir("/proc");
    if (dp != NULL)
    {
        // Enumerate all entries in directory until process found
        struct dirent *dirp;
        while (pid < 0 && (dirp = readdir(dp)))
        {
            // Skip non-numeric entries
            int id = atoi(dirp->d_name);
            if (id > 0)
            {
                // Read contents of virtual /proc/{pid}/cmdline file
                std::string cmdPath = std::string("/proc/") + dirp->d_name + "/cmdline";
                std::ifstream cmdFile(cmdPath.c_str());
                std::string cmdLine;
                getline(cmdFile, cmdLine);
                if (!cmdLine.empty())
                {
                    // Keep first cmdline item which contains the program path
                    size_t pos = cmdLine.find('\0');
                    if (pos != std::string::npos)
                        cmdLine = cmdLine.substr(0, pos);
                    // Keep program name only, removing the path
                    pos = cmdLine.rfind('/');
                    if (pos != std::string::npos)
                        cmdLine = cmdLine.substr(pos + 1);
                    // Compare against requested process name
                    if (procName == cmdLine)
                        pid = id;
                }
            }
        }
    }
    closedir(dp);

    return pid;
}

void TestHelpers::CreateRestPortFiles(int numFiles)
{
    std::string portFile;
    for (int i = 0; i < numFiles; i++)
    {
        portFile = std::string(msdod::GetRuntimeDirectory()) + std::string("/restport.") + std::to_string(i);
        std::ofstream file(portFile);
        file << std::to_string(50000 + i).c_str() << std::endl;
    }
}

void TestHelpers::DeleteRestPortFiles()
{
    for (boost::filesystem::directory_iterator itr(msdod::GetRuntimeDirectory()); itr != boost::filesystem::directory_iterator(); ++itr)
    {
        auto& dirEntry = itr->path();
        if (dirEntry.filename().string().find("restport") != std::string::npos)
        {
            boost::filesystem::remove(dirEntry);
        }
    }
}

unsigned int TestHelpers::CountRestPortFiles()
{
    unsigned int count = 0;
    for (boost::filesystem::directory_iterator itr(msdod::GetRuntimeDirectory()); itr != boost::filesystem::directory_iterator(); ++itr)
    {
        auto& dirEntry = itr->path();
        if (dirEntry.filename().string().find("restport") != std::string::npos)
        {
            ++count;
        }
    }
    return count;
}

void TestHelpers::CleanTestDir()
{
    if (boost::filesystem::exists(g_tmpFileName))
    {
        boost::filesystem::remove(g_tmpFileName);
    }
    if (boost::filesystem::exists(g_tmpFileName2))
    {
        boost::filesystem::remove(g_tmpFileName2);
    }
    if (boost::filesystem::exists(g_tmpFileName3))
    {
        boost::filesystem::remove(g_tmpFileName3);
    }
}

void TestHelpers::DisableNetwork()
{
    dtu::ExecuteSystemCommand("ifconfig eth0 down");
    std::cout << "Disabled eth0" << '\n';
}

void TestHelpers::EnableNetwork()
{
    dtu::ExecuteSystemCommand("ifconfig eth0 up");
    std::cout << "Enabled eth0" << '\n';
}

std::string TestHelpers::GetLocalIPv4Address()
{
    struct ifaddrs* ifaddr;
    if (getifaddrs(&ifaddr) == -1)
    {
        std::cout << "getifaddrs() failed, errno: " << errno;
        return {};
    }

    std::string localIPv4;
    for (auto ifa = ifaddr; (ifa != nullptr) && localIPv4.empty(); ifa = ifa->ifa_next)
    {
        if ((ifa->ifa_addr == nullptr) || (ifa->ifa_addr->sa_family != AF_INET))
        {
            continue;
        }

        auto foundPos = strcasestr(ifa->ifa_name, "eth");
        if ((foundPos == nullptr) || (foundPos != ifa->ifa_name))
        {
            foundPos = strcasestr(ifa->ifa_name, "wlan");
            if ((foundPos == nullptr) || (foundPos != ifa->ifa_name))
            {
                continue;
            }
        }

        char ifAddrStr[32] = {};
        inet_ntop(AF_INET, &reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr, ifAddrStr, 32);
        localIPv4 = ifAddrStr;
        std::cout << "Network interface detected: " << ifa->ifa_name << ", addr: " << localIPv4 << std::endl;
    }

    freeifaddrs(ifaddr);
    return localIPv4;
}