text:
///////////////////////////////////////////////////////////////////////////////
//
//  A mini XML-like parser
//
//  [ JDG March 25, 2007 ]   spirit2
//
///////////////////////////////////////////////////////////////////////////////

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/foreach.hpp>

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

namespace client
{
    namespace fusion = boost::fusion;
    namespace phoenix = boost::phoenix;
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;

    ///////////////////////////////////////////////////////////////////////////
    //  Our mini XML tree representation
    ///////////////////////////////////////////////////////////////////////////
    //[tutorial_xml1_structures
    struct mini_xml;

    typedef
        boost::variant<
            boost::recursive_wrapper<mini_xml>
          , std::string
        >
    mini_xml_node;

    struct mini_xml
    {
        std::string name;                           // tag name
        std::vector<mini_xml_node> children;        // children
    };
    //]
}

// We need to tell fusion about our mini_xml struct
// to make it a first-class fusion citizen
//[tutorial_xml1_adapt_structures
BOOST_FUSION_ADAPT_STRUCT(
    client::mini_xml,
    (std::string, name)
    (std::vector<client::mini_xml_node>, children)
)
//]

namespace client
{
    ///////////////////////////////////////////////////////////////////////////
    //  Print out the mini xml tree
    ///////////////////////////////////////////////////////////////////////////
    int const tabsize = 4;

    void tab(int indent)
    {
        for (int i = 0; i < indent; ++i)
            std::cout << ' ';
    }

    struct mini_xml_printer
    {
        mini_xml_printer(int indent = 0)
          : indent(indent)
        {
        }

        void operator()(mini_xml const& xml) const;

        int indent;
    };

    struct mini_xml_node_printer : boost::static_visitor<>
    {
        mini_xml_node_printer(int indent = 0)
          : indent(indent)
        {
        }

        void operator()(mini_xml const& xml) const
        {
            mini_xml_printer(indent+tabsize)(xml);
        }

        void operator()(std::string const& text) const
        {
            tab(indent+tabsize);
            std::cout << "text: \"" << text << '"' << std::endl;
        }

        int indent;
    };

    void mini_xml_printer::operator()(mini_xml const& xml) const
    {
        tab(indent);
        std::cout << "tag: " << xml.name << std::endl;
        tab(indent);
        std::cout << '{' << std::endl;

        BOOST_FOREACH(mini_xml_node const& node, xml.children)
        {
            boost::apply_visitor(mini_xml_node_printer(indent), node);
        }

        tab(indent);
        std::cout << '}' << std::endl;
    }

    ///////////////////////////////////////////////////////////////////////////
    //  Our mini XML grammar definition
    ///////////////////////////////////////////////////////////////////////////
    //[tutorial_xml1_grammar
    template <typename Iterator>
    struct mini_xml_grammar : qi::grammar<Iterator, mini_xml(), ascii::space_type>
    {
        mini_xml_grammar() : mini_xml_grammar::base_type(xml)
        {
            using qi::lit;
            using qi::lexeme;
            using ascii::char_;
            using ascii::string;
            using namespace qi::labels;

            using phoenix::at_c;
            using phoenix::push_back;

            text = lexeme[+(char_ - '<')        [_val += _1]];
            node = (xml | text)                 [_val = _1];

            start_tag =
                    '<'
                >>  !lit('/')
                >>  lexeme[+(char_ - '>')       [_val += _1]]
                >>  '>'
            ;

            end_tag =
                    "</"
                >>  string(_r1)
                >>  '>'
            ;

            xml =
                    start_tag                   [at_c<0>(_val) = _1]
                >>  *node                       [push_back(at_c<1>(_val), _1)]
                >>  end_tag(at_c<0>(_val))
            ;
        }

        qi::rule<Iterator, mini_xml(), ascii::space_type> xml;
        qi::rule<Iterator, mini_xml_node(), ascii::space_type> node;
        qi::rule<Iterator, std::string(), ascii::space_type> text;
        qi::rule<Iterator, std::string(), ascii::space_type> start_tag;
        qi::rule<Iterator, void(std::string), ascii::space_type> end_tag;
    };
    //]
}

///////////////////////////////////////////////////////////////////////////////
//  Main program
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
    char const* filename;
    if (argc > 1)
    {
        filename = argv[1];
    }
    else
    {
        std::cerr << "Error: No input file provided." << std::endl;
        return 1;
    }

    std::ifstream in(filename, std::ios_base::in);

    if (!in)
    {
        std::cerr << "Error: Could not open input file: "
            << filename << std::endl;
        return 1;
    }

    std::string storage; // We will read the contents here.
    in.unsetf(std::ios::skipws); // No white space skipping!
    std::copy(
        std::istream_iterator<char>(in),
        std::istream_iterator<char>(),
        std::back_inserter(storage));

    typedef client::mini_xml_grammar<std::string::const_iterator> mini_xml_grammar;
    mini_xml_grammar xml; // Our grammar
    client::mini_xml ast; // Our tree

    using boost::spirit::ascii::space;
    std::string::const_iterator iter = storage.begin();
    std::string::const_iterator end = storage.end();
    bool r = phrase_parse(iter, end, xml, space, ast);

    if (r && iter == end)
    {
        std::cout << "-------------------------\n";
        std::cout << "Parsing succeeded\n";
        std::cout << "-------------------------\n";
        client::mini_xml_printer printer;
        printer(ast);
        return 0;
    }
    else
    {
        std::string::const_iterator some = iter+30;
        std::string context(iter, (some>end)?end:some);
        std::cout << "-------------------------\n";
        std::cout << "Parsing failed\n";
        std::cout << "stopped at: \": " << context << "...\"\n";
        std::cout << "-------------------------\n";
        return 1;
    }
}

ext: cpp

max_stars_repo_name: dirkcgrunwald/SAM

max_issues_repo_name: dirkcgrunwald/SAM

max_forks_repo_name: dirkcgrunwald/SAM


text:
/**
 * Copyright (c) 2017 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <cstdlib>

#include <boost/format.hpp>

#include <opencv2/highgui/highgui.hpp>

#include "utility/gccversion.hpp"
#include "utility/buildsys.hpp"
#include "service/cmdline.hpp"

#include "imgproc/rastermask/cvmat.hpp"

#include "../registry/po.hpp"
#include "../vts/basetypes.hpp"
#include "../vts/io.hpp"
#include "../vts/tileop.hpp"

namespace po = boost::program_options;
namespace fs = boost::filesystem;
namespace vr = vtslibs::registry;
namespace vts = vtslibs::vts;

class NodeMask : public service::Cmdline
{
public:
    NodeMask()
        : Cmdline("vts-nodemask", BUILD_TARGET_VERSION
                  , service::DISABLE_EXCESSIVE_LOGGING)
        , size_(256, 256)
        , type_(vts::NodeInfo::CoverageType::pixel)
        , dilation_(0)
    {}

private:
    virtual void configuration(po::options_description &cmdline
                               , po::options_description &config
                               , po::positional_options_description &pd)
        UTILITY_OVERRIDE;

    virtual void configure(const po::variables_map &vars)
        UTILITY_OVERRIDE;

    virtual bool help(std::ostream &out, const std::string &what) const
        UTILITY_OVERRIDE;

    virtual int run() UTILITY_OVERRIDE;

    std::string referenceFrame_;
    vts::TileId tileId_;
    math::Size2 size_;
    vts::NodeInfo::CoverageType type_;
    int dilation_;
    fs::path output_;
};

void NodeMask::configuration(po::options_description &cmdline
                             , po::options_description &config
                             , po::positional_options_description &pd)
{
    vr::registryConfiguration(cmdline, vr::defaultPath());

    cmdline.add_options()
        ("referenceFrame", po::value(&referenceFrame_)->required()
         , "Reference frame to query.")
        ("tileId", po::value(&tileId_)->required()
         , "Tile ID to query.")
        ("size", po::value(&size_)->default_value(size_)->required()
         , "Size of mask.")
        ("type", po::value(&type_)->default_value(type_)->required()
         , "Mask type: pixel or grid registration.")
        ("dilation", po::value(&dilation_)
         ->default_value(dilation_)->required()
         , "Mask dilation in pixels.")
        ("output", po::value(&output_)->required()
         , "Path to output file.")
    ;

    pd.add("referenceFrame", 1)
        .add("tileId", 1)
        .add("output", 1);

    (void) config;
}

void NodeMask::configure(const po::variables_map &vars)
{
    vr::registryConfigure(vars);

    if (output_.filename() == ".") {
        output_ /= str(boost::format("%s.png") % tileId_);
    }
}

bool NodeMask::help(std::ostream &out, const std::string &what) const
{
    if (what.empty()) {
        out << R"RAW(vts-nodemask: referenceFrame tileId output [options]
)RAW";
    }
    return false;
}

int NodeMask::run()
{
    const auto referenceFrame(vr::Registry::referenceFrame(referenceFrame_));
    vts::NodeInfo ni(referenceFrame, tileId_);

    cv::imwrite
        (output_.string()
         , asCvMat(ni.coverageMask(type_, size_, dilation_))
         , { CV_IMWRITE_JPEG_QUALITY, 100, CV_IMWRITE_PNG_COMPRESSION, 9 });

    return EXIT_SUCCESS;
}

int main(int argc, char *argv[])
{
    return NodeMask()(argc, argv);
}

max_stars_repo_name: melowntech/vts-libs

max_issues_repo_name: HanochZhu/vts-browser-unity-plugin

max_forks_repo_name: HanochZhu/vts-browser-unity-plugin


text:
#include <iostream>
#include <vector>
#include <array>
#include <algorithm>
#include <fstream>
#include <thread>

#include <boost/filesystem.hpp>

#include <pcl/common/transforms.h>
#include <pcl/common/common.h>
#include <pcl/common/centroid.h>
#include <pcl/common/eigen.h>

#include "fann.h"
#include "floatfann.h"
#include "fann_data.h"
// #include "parallel_fann.h"

#include <pcl/ModelCoefficients.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/passthrough.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/features/vfh.h>
#include <pcl/features/normal_3d.h>
#include <pcl/kdtree/kdtree.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/segmentation/extract_clusters.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/histogram_visualizer.h>
#include <pcl/recognition/linemod/line_rgbd.h>

// argument 1 => folder dataset ex : dataset_washington
// contain list folder of file segmented model .pcd

struct info{
  int no;
  std::string category;
  std::string filename;
} ;

typedef std::pair<info, pcl::PointCloud<pcl::PointXYZRGB>::Ptr> modelRaw;
typedef pcl::VFHEstimation<pcl::PointXYZRGB, pcl::Normal, pcl::VFHSignature308> VFHEstimationType;

//  fann_callback_type callbackTrainning(fann_train_data ann)
int FANN_API callbackTrainning(
    struct fann *ann,
    struct fann_train_data *train,
    unsigned int max_epochs,
    unsigned int epochs_between_reports,
    float desired_error,
    unsigned int epochs
)
{
    ofstream MyFileData("listOwnDataSetv-0.1_error.txt", ios::app);
    MyFileData << epochs << ", "
               << fann_get_MSE(ann) << ", "
               << desired_error << ", "
               << std::endl;
    std::cout  << epochs << ", "
               << fann_get_MSE(ann) << ", "
               << desired_error << ", "
               << std::endl;
    MyFileData.close();
}

// /****************** Filter & Segmentation **************************/
void filtering(pcl::PointCloud<pcl::PointXYZRGB>::Ptr &cloud, pcl::PointCloud<pcl::PointXYZRGB>::Ptr &cloud_filtered){

  // Filter Removing NaN data Pointcloud.
	std::vector<int> mapping;
	pcl::removeNaNFromPointCloud(*cloud, *cloud_filtered, mapping);
  std::cerr << "Pointcloud remove NaN : " << cloud_filtered->size() << " data points." << std::endl;

  // Create the segmentation object for the planar model and set all the parameters
  pcl::SACSegmentation<pcl::PointXYZRGB> seg;
  pcl::PointIndices::Ptr inliers (new pcl::PointIndices);
  pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients);
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_plane (new pcl::PointCloud<pcl::PointXYZRGB> ());
  seg.setOptimizeCoefficients (true);
  seg.setModelType (pcl::SACMODEL_PLANE);
  seg.setMethodType (pcl::SAC_RANSAC);
  // seg.setMaxIterations (100);
  seg.setDistanceThreshold (0.02);

/* loop */
  int i=0, nr_points = (int) cloud_filtered->size ();
  while (cloud_filtered->size () > 0.4 * nr_points)
  {
    // Segment the largest planar component from the remaining cloud
    seg.setInputCloud (cloud_filtered);
    seg.segment (*inliers, *coefficients);
    if (inliers->indices.size () == 0)
    {
      std::cout << "Could not estimate a planar model for the given dataset." << std::endl;
      break;
    }

    // Extract the planar inliers from the input cloud
    pcl::ExtractIndices<pcl::PointXYZRGB> extract;
    extract.setInputCloud (cloud_filtered);
    extract.setIndices (inliers);
    extract.setNegative (false);

    // Get the points associated with the planar surface
    extract.filter (*cloud_plane);
    std::cout << "PointCloud representing the planar component" << i << "th : " << cloud_plane->size () << " data points." << std::endl;

    // Remove the planar inliers, extract the rest
    extract.setNegative (true);
    extract.filter (*cloud_filtered);

    i++;
  }

  // Creating the KdTree object for the search method of the extraction
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_clustered (new pcl::PointCloud<pcl::PointXYZRGB>);
  pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>);
  tree->setInputCloud (cloud_filtered);

  std::vector<pcl::PointIndices> cluster_indices;
  pcl::EuclideanClusterExtraction<pcl::PointXYZRGB> ec;
  ec.setClusterTolerance (0.02); // 2cm
  ec.setMinClusterSize (100);
  ec.setMaxClusterSize (25000);
  ec.setSearchMethod (tree);
  ec.setInputCloud (cloud_filtered);
  ec.extract (cluster_indices);

  std::cout << "cloudClustered : " << cloud_clustered->size() << std::endl;

  int j = 0;
  for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin (); it != cluster_indices.end (); ++it)
  {
    pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_cluster (new pcl::PointCloud<pcl::PointXYZRGB>);
    for (std::vector<int>::const_iterator pit = it->indices.begin (); pit != it->indices.end (); ++pit)
      cloud_cluster->push_back ((*cloud_filtered)[*pit]); //*
    cloud_cluster->width = cloud_cluster->size ();
    cloud_cluster->height = 1;
    cloud_cluster->is_dense = true;

    // take the bigger size point that can be conclusion is main object
    if(cloud_clustered->size() < cloud_cluster->size())
      *cloud_clustered = *cloud_cluster;

    std::cout << "PointCloud representing the Cluster " << j << " th : " << cloud_cluster->size () << " data points." << std::endl;

    j++;
  }

  *cloud_filtered = *cloud_clustered;

}

// /****************** Extrack feature (descriptor) **************************/
void descriptoring(pcl::PointCloud<pcl::PointXYZRGB>::Ptr &cloud_filtered, pcl::PointCloud<pcl::VFHSignature308>::Ptr &vfhFeatures)
{
    // // VFH DESCRIPTOR
    // // std::vector<pcl::PointCloud<pcl::VFHSignature308>::Ptr> modelsVFH;
    // std::vector<std::vector<float> > VFHValues;

    // //write file for data trainninng FANN librray format
    // ofstream MyFile("listOwnDataSetv0.1.data");
    // MyFile << models.size() << " 308 " << category.size() << std::endl; // coutn of row, count of input node ann, count of output node ann

    pcl::NormalEstimation<pcl::PointXYZRGB, pcl::Normal> normalEstimation;
    // typedef pcl::VFHEstimation<pcl::PointXYZRGB, pcl::Normal, pcl::VFHSignature308> VFHEstimationType;
    VFHEstimationType vfhEstimation;

    // std::cout << it.size() << std::endl;

    //  Compute the normals
    normalEstimation.setInputCloud (cloud_filtered);

    pcl::search::KdTree<pcl::PointXYZRGB>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGB>);
    normalEstimation.setSearchMethod (tree);

    normalEstimation.setRadiusSearch (0.01); //0.03

    pcl::PointCloud<pcl::Normal>::Ptr cloudWithNormals (new pcl::PointCloud<pcl::Normal>);
    normalEstimation.compute (*cloudWithNormals);

    std::cout << "Computed " << cloudWithNormals->points.size() << " normals." << std::endl;

    // Setup the feature computation

    // Provide the original point cloud (without normals)
    vfhEstimation.setInputCloud (cloud_filtered);

    // Provide the point cloud with normals
    vfhEstimation.setInputNormals(cloudWithNormals);

    // Use the same KdTree from the normal estimation
    vfhEstimation.setSearchMethod (tree);

    // vfhEstimation.setRadiusSearch (0.2); //nothing effect // With this, error: "Both radius (.2) and K (1) defined! Set one of them to zero first and then re-run compute()"

    // Actually compute the VFH features
    pcl::PointCloud<pcl::VFHSignature308>::Ptr tmpVfhFeatures(new pcl::PointCloud<pcl::VFHSignature308>);
    vfhEstimation.compute (*tmpVfhFeatures);

    *vfhFeatures = *tmpVfhFeatures;

    // std::cout << "output points.size (): " << vfhFeatures->points.size () << std::endl; // This outputs 1 - should be 397!

    // Display and retrieve the shape context descriptor vector for the 0th point.
    // pcl::VFHSignature308 descriptor = vfhFeatures->points[0];
    // VFHEstimationType::PointCloudOut::PointType descriptor2 = vfhFeatures->points[0];
    // std::cout << descriptor << std::endl;

    //push to vector
    // modelsVFH.push_back (vfhFeatures);

    // VFHValues.push_back(vfhFeatures->points[0].histogram);
    // std::vector<float> VFHValues;
    // float vfh[308] = vfhFeatures->points[0].histogram;

    std::cout  << " vfh calculated : "  << std::endl;// << VFHValue.size();
     for(auto it2 : vfhFeatures->points[0].histogram)
      {
          std::cout << it2 << " " ;
          // VFHValue.push_back(it2);
          // MyFile << it2 << " " ;
      }
    std::cout  << " end of vfh calculated : "  << std::endl;
  // std::cout << it.first.no << ". VFH calculated " << it.first.category << " of file : "<< it.first.filename << std::endl;
}

void LoadModels (const boost::filesystem::path &base_dir, const std::string &extension, std::vector<modelRaw> &models)
{
  static int i = 1;
  if (!boost::filesystem::exists (base_dir) && !boost::filesystem::is_directory (base_dir))
    return;

  for (boost::filesystem::directory_iterator it (base_dir); it != boost::filesystem::directory_iterator (); ++it)
  {
    if (boost::filesystem::is_directory (it->status ()))
    {
      i++;
      std::stringstream ss;
      ss << it->path ();
      pcl::console::print_highlight ("Loading %s (%lu models loaded so far).\n", ss.str ().c_str (), (unsigned long)models.size ());
      LoadModels (it->path (), extension, models);
    }
    if (boost::filesystem::is_regular_file (it->status ()) && boost::filesystem::extension (it->path ()) == extension)
    {
      pcl::PCDReader reader;
      pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
      pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud_filtered (new pcl::PointCloud<pcl::PointXYZRGB>);
      reader.read (it->path ().string(), *cloud);

      info dataInfo;
      dataInfo.no  = i;
      dataInfo.category = base_dir.string();
      dataInfo.filename = it->path().filename().string();
      modelRaw m(dataInfo, cloud);

      models.push_back(m);
      std::cout << "base_dir << '/' "<< it->path ().filename ().string() << std::endl;
      std::cout << dataInfo.no << ". reading " << dataInfo.category << " file : "<< dataInfo.filename << std::endl;

      /** visualize each model
      pcl::visualization::PCLVisualizer::Ptr viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
      // viewer->addPointCloud<pcl::PointXYZRGB> (cloud, "sample cloud");

      int v1(0);
      viewer->createViewPort(0.0, 0.0, 0.5, 1.0, v1);
      viewer->setBackgroundColor (0, 0, 0, v1);
      viewer->addText("original", 10, 10, "v1 text", v1);
      pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb_cloud(cloud);
      viewer->addPointCloud<pcl::PointXYZRGB> (cloud, rgb_cloud, "original", v1);
      **/

      filtering(cloud, cloud_filtered);
      // viewer->addPointCloud<pcl::PointXYZRGB> (cloud_filtered, "sample cloud");

      /** visualize each model after segmentation
      int v2(0);
      viewer->createViewPort(0.5, 0.0, 1.0, 1.0, v2);
      viewer->setBackgroundColor (0, 0, 0, v2);
      viewer->addText("filtered and segmented", 10, 10, "v2 text", v2);
      pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> rgb_cloud_filtered(cloud_filtered);
      viewer->addPointCloud<pcl::PointXYZRGB> (cloud_filtered, rgb_cloud_filtered, "filtered and segmented", v2);

      pcl::PointCloud<pcl::VFHSignature308>::Ptr vfhFeatures1(new pcl::PointCloud<pcl::VFHSignature308>);

      viewer->addCoordinateSystem (1.0);

	    // pcl::visualization::PCLHistogramVisualizer viewerHistogram;
      // viewerHistogram.addFeatureHistogram(*vfhFeatures1, 308);
      // // viewerHistogram.updateFeatureHistogram(*vfhFeatures, 308);

      // viewerHistogram.spinOnce();

      while(!viewer->wasStopped())
      {
        viewer->spinOnce (100);
        // std::this_thread::sleep_for(100ms);
      }
      **/

      pcl::PointCloud<pcl::VFHSignature308>::Ptr vfhFeatures(new pcl::PointCloud<pcl::VFHSignature308>);
      descriptoring(cloud_filtered, vfhFeatures);
std::cout  << " vfh calculated ted : " << vfhFeatures->size() << std::endl;// << VFHValue.size();

    }
  }
}

int main (int argc, char** argv)
{
    std::vector<modelRaw> models;
    std::string extension (".pcd");
    transform (extension.begin (), extension.end (), extension.begin (), (int(*)(int))tolower);

    LoadModels(argv[1], extension, models); // argv[1] = "dataset_washington"

    std::cout << "file readed : " << models.size() << std::endl;

    ofstream MyFileData("listOwnDataSetv0.1.txt");
    int no  = 0;
    std::vector<int> category;
    for(auto it : models)
    {
       if(no != it.first.no)
       {
          MyFileData << it.first.category << std::endl;
          category.push_back(it.first.no);
       }
        no = it.first.no;
    }
    MyFileData.close();

    //  // ARTIFICIAL NEURAL NETOWRK
    // fann_type *calc_out;
    // const unsigned int num_input = 308;
    // const unsigned int num_output = 8;
    // const unsigned int num_layers = 3;
    // const unsigned int num_neurons_hidden = 308;
    // const float desired_error = (const float) 0;
    // const unsigned int max_epochs = 2000;
    // const unsigned int epochs_between_reports = 1;
    // struct fann *ann;
    // struct fann_train_data *data;

    // unsigned int i = 0;
    // unsigned int decimal_point;

    // printf("Creating network.\n");
    // // ann = fann_create_standard(num_layers, num_input, num_neurons_hidden, num_output);
    // ann = fann_create_standard(5, 308, 616, 308, 64, 8); // bbbbbbb
    // // ann = fann_create_standard(5, 308, 616, 308, 64, 8); // ccccccc

    // data = fann_read_train_from_file("listOwnDataSetv0.1.data");

    // fann_set_activation_steepness_hidden(ann, 0.01); //deafault 0.5 //bbbbbb = 0.01
    // fann_set_activation_steepness_output(ann, 0.01); //deafault 0.5

    // // fann_scale_input_train_data(data, (fann_type) (0), (fann_type) 100);
    // // fann_scale_output_train_data(data, (fann_type) (0), (fann_type) 100);

    // fann_set_activation_function_hidden(ann, FANN_SIGMOID_STEPWISE);
    // fann_set_activation_function_output(ann, FANN_SIGMOID_STEPWISE);

    // fann_set_train_stop_function(ann, FANN_STOPFUNC_BIT);
    // // fann_set_bit_fail_limit(ann, 0.01f); //default 0.35

    // fann_set_training_algorithm(ann, FANN_TRAIN_RPROP); //defailt FANN_TRAIN_RPROP

    // fann_init_weights(ann, data);

    // fann_set_callback(ann, (fann_callback_type)&callbackTrainning); //callback to save error

    // printf("Training network.\n");
    // fann_train_on_data(ann, data, max_epochs, epochs_between_reports, desired_error);

    // // float error;
    // // ofstream MyFileData("ccccccc_error.txt", ios::app);
    // // for(i = 1; i <= max_epochs; i++)
    // // {
    // // error = fann_train_epoch_irpropm_parallel(ann, data, 4);
    // // 	printf("Epochs     %8d. Current error: %.10f. Bit Fail: %5d\n", i, error, fann_get_bit_fail(ann));
    // //     MyFileData << i << "#"
    // //             << error << "#"
    // //             << fann_get_bit_fail(ann) << "#"
    // //             << std::endl;
    // // }
    // // MyFileData.close();

    // printf("Testing network. %f\n", fann_test_data(ann, data));

    // for(i = 0; i < fann_length_train_data(data); i++)
    // {
    // calc_out = fann_run(ann, data->input[i]);
    // printf("test (%f,%f) -> %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f \n, should be %.1f %.1f %.1f %.1f %.1f %.1f %.1f %.1f , difference=%f\n",
    //       data->input[i][0], data->input[i][1],
    //             calc_out[0], calc_out[1], calc_out[2], calc_out[3], calc_out[4], calc_out[5], calc_out[6], calc_out[7],
    //             data->output[i][0], data->output[i][1], data->output[i][2], data->output[i][3], data->output[i][4], data->output[i][5], data->output[i][6], data->output[i][7],
    //       fann_abs(calc_out[0] - data->output[i][0]));

    // }

    // printf("Saving network.\n");

    // fann_save(ann, "listOwnDataSetv0.1.net");

    // decimal_point = fann_save_to_fixed(ann, "listOwnDataSetv0.1_fixed.net");
    // fann_save_train_to_fixed(data, "listOwnDataSetv0.1fixed.data", decimal_point);

    // printf("Cleaning up.\n");
    // fann_destroy_train(data);
    // fann_destroy(ann);

    return (0);
}

max_stars_repo_licenses: Intel MIT

max_issues_repo_licenses: Intel MIT

max_forks_repo_licenses: Intel MIT


text:
#include "mjolnir/util.h"

#include <boost/format.hpp>
#include <future>
#include <set>
#include <thread>
#include <utility>

#include "baldr/graphconstants.h"
#include "baldr/graphid.h"
#include "baldr/graphreader.h"
#include "filesystem.h"
#include "midgard/logging.h"
#include "midgard/pointll.h"
#include "midgard/polyline2.h"
#include "midgard/util.h"
#include "skadi/sample.h"
#include "skadi/util.h"

#include "mjolnir/elevationbuilder.h"
#include "mjolnir/graphtilebuilder.h"

#include <deque>

using namespace valhalla::midgard;
using namespace valhalla::baldr;
using namespace valhalla::mjolnir;

namespace {

// How many meters to resample shape to when checking elevations.
constexpr double POSTING_INTERVAL = 60;

// Do not compute grade for intervals less than 10 meters.
constexpr double kMinimumInterval = 10.0f;

/**
 * Adds elevation to a set of tiles. Each thread pulls a tile of the queue
 */
void add_elevation(const boost::property_tree::ptree& pt,
                   std::deque<GraphId>& tilequeue,
                   std::mutex& lock,
                   const std::unique_ptr<valhalla::skadi::sample>& sample,
                   std::promise<uint32_t>& /*result*/) {
  // Local Graphreader
  GraphReader graphreader(pt.get_child("mjolnir"));

  // We usually end up accessing the same shape twice (once for each direction along an edge).
  // Use a cache to record elevation attributes based on the EdgeInfo offset. This includes
  // weighted grade (forward and reverse) as well as max slopes (up/down for forward and reverse).
  std::unordered_map<uint32_t, std::tuple<uint32_t, uint32_t, float, float, float, float>>
      geo_attribute_cache;

  // Check for more tiles
  while (true) {
    lock.lock();
    if (tilequeue.empty()) {
      lock.unlock();
      break;
    }
    // Get the next tile Id
    GraphId tile_id = tilequeue.front();
    tilequeue.pop_front();
    lock.unlock();

    // Get the tile. Serialize the entire tile?
    GraphTileBuilder tilebuilder(graphreader.tile_dir(), tile_id, true);

    // Set the has_elevation flag. TODO - do we need to know if any elevation is actually
    // retrieved/used?
    tilebuilder.header_builder().set_has_elevation(true);

    // Reserve twice the number of directed edges in the tile. We do not directly know
    // how many EdgeInfo records exist but it cannot be more than 2x the directed edge count.
    uint32_t count = tilebuilder.header()->directededgecount();
    geo_attribute_cache.clear();
    geo_attribute_cache.reserve(2 * count);

    // Iterate through the directed edges
    for (uint32_t i = 0; i < count; ++i) {
      // Get a writeable reference to the directed edge
      DirectedEdge& directededge = tilebuilder.directededge_builder(i);

      // Get the edge info offset
      uint32_t edge_info_offset = directededge.edgeinfo_offset();

      // Check if this edge has been cached (based on edge info offset)
      auto found = geo_attribute_cache.find(edge_info_offset);
      if (found == geo_attribute_cache.cend()) {
        // Get the shape and length
        auto shape = tilebuilder.edgeinfo(&directededge).shape();
        auto length = directededge.length();

        // Grade estimation and max slopes
        std::tuple<double, double, double, double> forward_grades(0.0, 0.0, 0.0, 0.0);
        std::tuple<double, double, double, double> reverse_grades(0.0, 0.0, 0.0, 0.0);
        if (!directededge.tunnel() && directededge.use() != Use::kFerry) {
          // Evenly sample the shape. If it is really short or a bridge just do both ends
          auto interval = POSTING_INTERVAL;
          std::vector<PointLL> resampled;
          if (length < POSTING_INTERVAL * 3 || directededge.bridge()) {
            resampled = {shape.front(), shape.back()};
            interval = length;
          } else {
            resampled = valhalla::midgard::resample_spherical_polyline(shape, interval);
          }

          // Get the heights at each sampled point. Compute "weighted"
          // grades as well as max grades in both directions. Valid range
          // for weighted grades is between -10 and +15 which is then
          // mapped to a value between 0 to 15 for use in costing.
          auto heights = sample->get_all(resampled);
          auto grades = valhalla::skadi::weighted_grade(heights, interval);
          if (length < kMinimumInterval) {
            // Keep the default grades - but set the mean elevation
            forward_grades = std::make_tuple(0.0, 0.0, 0.0, std::get<3>(grades));
            reverse_grades = std::make_tuple(0.0, 0.0, 0.0, std::get<3>(grades));
          } else {
            // Set the forward grades. Reverse the path and compute the
            // weighted grade in reverse direction.
            forward_grades = grades;
            std::reverse(heights.begin(), heights.end());
            reverse_grades = valhalla::skadi::weighted_grade(heights, interval);
          }
        }

        // Add elevation info to the geo attribute cache. TODO - add mean elevation.
        float mean_elevation = std::get<3>(forward_grades);
        uint32_t forward_grade = static_cast<uint32_t>(std::get<0>(forward_grades) * .6 + 6.5);
        uint32_t reverse_grade = static_cast<uint32_t>(std::get<0>(reverse_grades) * .6 + 6.5);
        auto inserted = geo_attribute_cache.insert(
            {edge_info_offset,
             std::make_tuple(forward_grade, reverse_grade, std::get<1>(forward_grades),
                             std::get<2>(forward_grades), std::get<1>(reverse_grades),
                             std::get<2>(reverse_grades))});
        found = inserted.first;

        // Set the mean elevation on EdgeInfo
        tilebuilder.set_mean_elevation(edge_info_offset, mean_elevation);
      }

      // Edge elevation information. If the edge is forward (with respect to the shape)
      // use the first value, otherwise use the second.
      bool forward = directededge.forward();
      directededge.set_weighted_grade(forward ? std::get<0>(found->second)
                                              : std::get<1>(found->second));
      float max_up_slope = forward ? std::get<2>(found->second) : std::get<4>(found->second);
      float max_down_slope = forward ? std::get<3>(found->second) : std::get<5>(found->second);
      directededge.set_max_up_slope(max_up_slope);
      directededge.set_max_down_slope(max_down_slope);
    }

    // Update the tile
    tilebuilder.StoreTileData();

    // Check if we need to clear the tile cache
    if (graphreader.OverCommitted()) {
      lock.lock();
      graphreader.Trim();
      lock.unlock();
    }
  }
}

} // namespace

namespace valhalla {
namespace mjolnir {

void ElevationBuilder::Build(const boost::property_tree::ptree& pt) {

  auto hierarchy_properties = pt.get_child("mjolnir");
  std::string tile_dir = hierarchy_properties.get<std::string>("tile_dir");

  // Crack open some elevation data if its there. Return if it is not.
  boost::optional<std::string> elevation = pt.get_optional<std::string>("additional_data.elevation");
  std::unique_ptr<skadi::sample> sample;
  if (elevation && filesystem::exists(*elevation)) {
    sample.reset(new skadi::sample(*elevation));
  } else {
    LOG_INFO("ElevationBuilder: no elevation data, skipping");
    return;
  }

  // Create a randomized queue of tiles (at all levels) to work from
  std::deque<GraphId> tilequeue;
  GraphReader reader(pt.get_child("mjolnir"));
  auto tileset = reader.GetTileSet();
  for (const auto& id : tileset) {
    tilequeue.emplace_back(id);
  }
  std::random_device rd;
  std::shuffle(tilequeue.begin(), tilequeue.end(), std::mt19937(rd()));

  // An mutex we can use to do the synchronization
  std::mutex lock;

  // Setup threads
  uint32_t nthreads =
      std::max(static_cast<unsigned int>(1),
               pt.get<unsigned int>("mjolnir.concurrency", std::thread::hardware_concurrency()));
  std::vector<std::shared_ptr<std::thread>> threads(nthreads);

  // Setup promises. Hold the results for the threads
  std::vector<std::promise<uint32_t>> results(nthreads);

  LOG_INFO("Adding elevation to " + std::to_string(tilequeue.size()) + " tiles with " +
           std::to_string(nthreads) + " threads...");

  // Spawn the threads
  for (auto& thread : threads) {
    results.emplace_back();
    thread.reset(new std::thread(add_elevation, std::cref(pt), std::ref(tilequeue), std::ref(lock),
                                 std::ref(sample), std::ref(results.back())));
  }

  // Wait for threads to finish
  for (auto& thread : threads) {
    thread->join();
  }

  /** // Get the promise from the future
  for (auto& result : results) {
    auto data = result.get_future().get();
    // Total up duplicates for each level
    for (uint8_t i = 0; i < TileHierarchy::levels().size(); ++i) {
      for (auto& d : std::get<1>(data)[i]) {
        densities[i].push_back(d);
      }
    }
  } **/
  LOG_INFO("Finished");
}

} // namespace mjolnir
} // namespace valhalla

ext: cc

max_stars_repo_name: TimMcCauley/valhalla

max_issues_repo_name: TimMcCauley/valhalla

max_forks_repo_name: TimMcCauley/valhalla


text:
#include <boost/python.hpp>
#include <boost/python/make_constructor.hpp>

#include <cuckoo_time_translator/OneWayTranslator.h>
#include <cuckoo_time_translator/ConvexHullOwt.h>
#include <cuckoo_time_translator/KalmanOwt.h>
#include <cuckoo_time_translator/SwitchingOwt.h>

using namespace boost::python;
using namespace cuckoo_time_translator;

template < void (OneWayTranslator::* Method) (std::ostream & o) const>
std::string getString(const OneWayTranslator * owt){
  std::stringstream ss;
  (owt->*Method)(ss);
  return ss.str();
}

void exportTimestampOwts()
{
  class_<TaggedTime>("LocalTime", init<double>())
    .def("__eq__", &TaggedTime::operator ==, "")
    .def("__ne__", &TaggedTime::operator !=, "")
    .def("__float__", &TaggedTime::operator double, "local time in seconds")
    ;

  class_<LocalTime, bases<TaggedTime>>("LocalTime", init<double>())
    ;
  class_<RemoteTime, bases<TaggedTime>>("RemoteTime", init<double>())
    ;

  class_<OneWayTranslator, boost::noncopyable>("OneWayTranslator", no_init)
    .def("reset", &OneWayTranslator::reset, "void reset()")
    .def("isReady", &OneWayTranslator::isReadyToTranslate, "bool isReady() const")
    .def("translateToLocalTimestamp", &OneWayTranslator::translateToLocalTimestamp, "LocalTime translateToLocalTimestamp(RemoteTime remoteTimeTics) const")
    .def("updateAndTranslateToLocalTimestamp", &OneWayTranslator::updateAndTranslateToLocalTimestamp, "LocalTimestamp updateAndTranslateToLocalTimestamp(RemoteTime remoteTimeTics, LocalTime localTimeSecs)")
    .def("getNameAndConfigString", &getString<&OneWayTranslator::printNameAndConfig>, "std::string getNameAndConfig() const")
    .def("getStateString", &getString<&OneWayTranslator::printState>, "std::string getStateString() const")
    ;

  class_<ConvexHullOwt, bases<OneWayTranslator>>("ConvexHullOwt", init<>())
    .def("getSkew", &ConvexHullOwt::getSkew, "double getSkew() const")
    .def("getOffset", &ConvexHullOwt::getOffset, "LocalTime getOffset() const")
    .def("getStackSize", &ConvexHullOwt::getStackSize, "size_t getStackSize() const")
    ;

  class_<KalmanOwt::Config>("KalmanOwtConfig", init<>())
    .def_readwrite("sigmaInitOffset", &KalmanOwt::Config::sigmaInitOffset)
    .def_readwrite("sigmaInitSkew", &KalmanOwt::Config::sigmaInitSkew)
    .def_readwrite("sigmaOffset", &KalmanOwt::Config::sigmaOffset)
    .def_readwrite("sigmaSkew", &KalmanOwt::Config::sigmaSkew)
    .def_readwrite("updateCooldownSecs", &KalmanOwt::Config::updateCooldownSecs)
    .def_readwrite("outlierThreshold", &KalmanOwt::Config::outlierThreshold)
  ;

  class_<KalmanOwt, bases<OneWayTranslator>>("KalmanOwt", init<>())
    .def("getConfig", &KalmanOwt::getConfig, "const Config& getConfig() const", return_value_policy<boost::python:: copy_const_reference>())
    .def("setConfig", &KalmanOwt::setConfig, "void setConfig(const Config& config)")
    ;

  class_<SwitchingOwt, bases<OneWayTranslator>, boost::noncopyable>("SwitchingOwt", init<double, const OneWayTranslator &>())
    .def("getSwitchingTimeSeconds", &SwitchingOwt::getSwitchingTimeSeconds, "double getSwitchingTimeSeconds() const")
    .def("getCurrentOwt", static_cast<OneWayTranslator& (SwitchingOwt::*)()>(&SwitchingOwt::getCurrentOwt), return_internal_reference<>(), "OneWayTranslator& getCurrentOwt()")
    ;

}

BOOST_PYTHON_MODULE(libcuckoo_time_translator_python)
{
  exportTimestampOwts();
}


text:
/*
 * HttpClient.cc : part of the Mace toolkit for building distributed systems
 *
 * Copyright (c) 2011, James W. Anderson, Ryan Braud, Charles Killian
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *    * Neither the names of the contributors, nor their associated universities
 *      or organizations may be used to endorse or promote products derived from
 *      this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ----END-OF-LEGAL-STUFF---- */
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <getopt.h>
#include <cassert>
#include <sstream>
#include <fstream>
#include <iostream>
#include <errno.h>
#include <boost/lexical_cast.hpp>
#include <signal.h>
#include "m_net.h"

#include "Accumulator.h"
#include "Log.h"
#include "StrUtil.h"
#include "Util.h"
#include "SysUtil.h"
#include "SockUtil.h"
#include "FileUtil.h"
#include "mace-macros.h"

#include "HttpParser.h"
#include "HttpClient.h"

#if (defined _WINSOCK2_H || defined _WINSOCK_H)
#define SHUT_RDWR SD_BOTH
#endif

using namespace std;
using boost::lexical_cast;

const string HttpClient::DEFAULT_USER_AGENT = "MaceHttpClient/1.0";

HttpClient::HttpClient(bool async, const string& userAgent) :
  userAgent(userAgent), s(0) {

  init(async);
} // HttpClient

HttpClient::HttpClient(const string& host, uint16_t p, bool async,
		       const string& userAgent) : userAgent(userAgent), s(0) {

  init(async);
  setServer(host, p);
} // HttpClient

void HttpClient::init(bool async) {
  #ifndef NO_SIGPIPE
  SysUtil::signal(SIGPIPE, SIG_IGN, false);
  #endif

  if (async) {
    requests = new HttpClientRequestQueue(
      HttpClientRequestCallback(this, &HttpClient::execute));
  }
  else {
    requests = 0;
  }
} // init

HttpClient::~HttpClient() {
  closeConnection();

  if (requests) {
    delete requests;
    requests = 0;
  }
} // ~HttpClient

void HttpClient::setServer(const string& host, uint16_t p) {
  if ((server == host) && (port == p)) {
    return;
  }

  closeConnection();

  server = host;
  port = p;
} // setServer

std::string HttpClient::setServerFromUrl(std::string url) {
  string http = "http://";
  if (url.find(http) == 0) {
    url = url.substr(http.size());
  }

  StringList m = StrUtil::match("([^/]+)/(.*)", url);
  if (m.empty()) {
    Log::err() << "bad url " << url << Log::endl;
    assert(0);
  }

  string host = m[0];
  string path = "/" + m[1];

  int p = 80;
  m = StrUtil::match("([^:]+):(\\d+)", host);
  if (!m.empty()) {
    host = m[0];
    p = lexical_cast<int>(m[1]);
  }

  setServer(host, p);

  return path;
} // setServerFromUrl

HttpResponse HttpClient::get(const std::string& url, const std::string& httpVersion)
  throw (HttpClientException) {

  string path = setServerFromUrl(url);
  return getUrl(path, httpVersion);
} // get

HttpResponse HttpClient::post(const std::string& url, const std::string& contentType,
			      const std::string& content, const std::string& httpVersion)
  throw (HttpClientException) {

  string path = setServerFromUrl(url);
  return postUrl(path, contentType, content, httpVersion);
} // post

HttpResponse HttpClient::getUrl(const string& url, const string& httpVersion,
				bool keepAlive, const StringHMap& headers)
  throw (HttpClientException) {

  HttpResponse response(server, port, url);
  response.persistent = isConnected();

  string req = getRequest("GET", url, httpVersion, keepAlive, headers);
  sendRequest(req);
  readResponse(response);

  return response;
} // getUrl

HttpResponse HttpClient::rawRequest(const string& req)
  throw (HttpClientException) {

  HttpResponse response(server, port, req);
  response.persistent = isConnected();
  sendRequest(req);
  readResponse(response);
  return response;
} // rawRequest

void HttpClient::getUrlAsync(const string& url, const string& httpVersion,
			     bool keepAlive, const StringHMap& headers,
			     HttpClientResponseHandler* c,
			     HttpClientResponseCallback f) {
  assert(requests);
  // we are calling this to clear the queue of async callback results
  hasAsyncResponse();
  HttpClientResponseState* rs = new HttpClientResponseState(server, port,
							    url, c, f);
  rs->request = getRequest("GET", url, httpVersion, keepAlive, headers);
  requests->push(rs);
} // getUrlAsync

void HttpClient::postUrlAsync(const string& url, const string& contentType,
			      const string& content, const string& httpVersion,
			      bool keepAlive, const StringHMap& headers,
			      HttpClientResponseHandler* c,
			      HttpClientResponseCallback f) {
  assert(requests);
  // we are calling this to clear the queue of async callback results
  hasAsyncResponse();
  HttpClientResponseState* rs = new HttpClientResponseState(server, port,
							    url, c, f);
  rs->request = getRequest("POST", url, httpVersion, keepAlive, headers,
			   contentType, content);
  requests->push(rs);
} // postUrlAsync

bool HttpClient::hasAsyncResponse() {
  assert(requests);
  if (!requests->empty()) {
    HttpClientResponseState* r = requests->front();
    while (r->obj && r->callback) {
      delete r;
      requests->pop();
      if (requests->empty()) {
	break;
      }
      r = requests->front();
    }
  }
  return !requests->empty();
} // hasAsyncResponse

bool HttpClient::isBusy() const {
  assert(requests);
  return requests->isBusy();
} // isBusy

HttpResponse HttpClient::getAsyncResponse() throw (HttpClientException) {
  assert(requests);
  HttpClientResponseState* r = 0;
  do {
    delete r;
    r = requests->front();
    requests->pop();
  } while (r->obj && r->callback);

  HttpResponse rr;
  HttpClientException e("");
  bool thr = r->hasException;
  if (thr) {
    e = r->exception;
  }
  else {
    rr = r->response;
  }

  delete r;
  r = 0;

  if (thr) {
    closeConnection();
    throw e;
  }

  return rr;
} // getAsyncResponse

HttpResponse HttpClient::postUrl(const string& url, const string& contentType,
				 const string& content,
				 const string& httpVersion,
				 bool keepAlive) throw (HttpClientException) {
  string req = getRequest("POST", url, httpVersion, keepAlive, StringHMap(),
			  contentType, content);
  sendRequest(req);

  HttpResponse response(server, port, url);
  readResponse(response);

  return response;
} // postUrl

bool HttpClient::isConnected() const {
  return s > 0;
}

void HttpClient::sendRequest(const string& req) throw (HttpClientException) {
  try {
    connectToServer();

    size_t sendCount = 0;
    bool retrySend = false;
    do {
      sendCount++;
      try {
	FileUtil::write(s, req);
	Accumulator::Instance(Accumulator::HTTP_CLIENT_WRITE)->accumulate(req.size());
	retrySend = false;
      } catch (const PipeClosedException& e) {
	// server closed connection, try to reconnect
	closeConnection();
	if (sendCount > 3) {
	  throw HttpClientException("could not send request to server " +
				    server + ": " + e.toString());
	}

	connectToServer();
	retrySend = true;
      }
    } while (retrySend);

  } catch (const WriteException& e) {
    closeConnection();
    throw HttpClientException("could not send request to server " +
			      server + ": " +
			      e.toString());
  }
} // sendRequest

void HttpClient::readResponse(HttpResponse& response) throw (HttpClientException) {
  ADD_SELECTORS("HttpClient::readResponse");
  Accumulator* accum = Accumulator::Instance(Accumulator::HTTP_CLIENT_READ);
  try {
    mace::string rbuf;
    StringList headerList;
    size_t lengthUsed = 0;
    mace::string buf = readBuffer;
    mace::string headerbuf;
    readBuffer.clear();
    size_t headerLen = 0;
    do {
      headerLen += lengthUsed;
      size_t r = 0;
      try {
	r = FileUtil::read(s, buf);
	accum->accumulate(r);
      } catch (const ReadException& e) {
	closeConnection();
	throw HttpClientException(e.toString());
      }

      if (r == 0) {
	closeConnection();
	throw HttpClientException("server " + server + " closed connection");
      }

      rbuf = buf;
      headerbuf.append(rbuf);
    } while (!HttpParser::readHeader(rbuf, headerList, lengthUsed));
    headerLen += lengthUsed;
    response.rawheaders = headerbuf.substr(0, lengthUsed);

    if (!HttpParser::parseResponseHeaderLine(headerList, response)) {
      closeConnection();
      throw HttpClientException("invalid response from " + server);
    }

    HttpRequestContext context;
    // this is needed so that we can correctly parse content-length
    context.method = "POST";
    size_t contentLength = std::numeric_limits<size_t>::max();
    if (!HttpParser::parseHeaders(headerList, context, contentLength)) {
      closeConnection();
      throw HttpClientException("invalid response from " + server);
    }

    response.headers = context.headers;
    if (context.headers.containsKey("Connection")) {
      response.keepAlive = context.keepAlive;
    }

    if (context.chunked) {
      bool valid = false;
      bool done = false;
      size_t r = 0;
      do {
	HttpParser::readChunked(rbuf, response.content, lengthUsed, valid, done);

	if (!done) {
	  r = FileUtil::read(s, rbuf);
	  accum->accumulate(r);
	}
      } while (!done && (r > 0));

      if (!valid) {
	closeConnection();
	throw HttpClientException("incomplete response: did not receive valid header");
      }

      readBuffer = rbuf;
    }
    else if (std::numeric_limits<size_t>::max() == contentLength) {
      size_t r = 0;
      response.content = rbuf;
      do {
	r = FileUtil::read(s, response.content);
	accum->accumulate(r);
      } while (r > 0);
      ASSERT(r == 0);
    }
    else {
      // read the rest of the content, accounting for data we already have in rbuf
      if (rbuf.size() == contentLength) {
	response.content = rbuf;
      }
      else if (rbuf.size() > contentLength) {
	response.content = rbuf.substr(0, contentLength);
	readBuffer.append(rbuf.substr(contentLength));
      }
      else {
	size_t remaining = contentLength - rbuf.size();
	response.content.append(rbuf);
	size_t r = FileUtil::bufferedRead(s, rbuf, remaining);
	accum->accumulate(r);
	if (r != remaining) {
	  closeConnection();
	  throw HttpClientException("incomplete response: expected " +
				    lexical_cast<std::string>(contentLength) +
				    " but read only " +
				    lexical_cast<std::string>(rbuf.size()) +
				    " r=" + lexical_cast<std::string>(r) +
				    " remaining=" + lexical_cast<std::string>(remaining));
	}
	response.content.append(rbuf);
      }
    }

  } catch (const ReadException& e) {
    closeConnection();
    throw HttpClientException("error reading response from server " + server + ": " +
			      e.toString());
  }

  if (!response.keepAlive) {
    closeConnection();
  }
} // readResponse

string HttpClient::getRequest(const string& method, const string& path,
			      const string& version, bool keepAlive,
			      const StringHMap& headers,
			      const string& contentType, const string& content) {

  string req = method + " " + path + " HTTP/" + version + "\r\n";
  if (!headers.containsKey("Host") && version == "1.1") {
    req += "Host: " + server + "\r\n";
  }
  if (!userAgent.empty()) {
    req += "User-Agent: " + userAgent + "\r\n";
  }
  if (!headers.containsKey("Connection") && keepAlive) {
    req += "Connection: keep-alive\r\n";
  }
  if (!headers.containsKey("Content-Type") && !contentType.empty()) {
    req += "Content-Type: " + contentType + "\r\n";
  }
  if (!headers.containsKey("Content-Length") && !content.empty()) {
    req += "Content-Length: " + lexical_cast<std::string>(content.size()) + "\r\n";
  }

  for (StringHMap::const_iterator i = headers.begin(); i != headers.end(); i++) {
    if (i->first != "User-Agent") {
      req += i->first + ": " + i->second + "\r\n";
    }
  }

  req += "\r\n";

  if (!content.empty()) {
    req += content;
  }

  return req;
} // getRequest

void HttpClient::testServerClosed() {
  fd_set rset;
  FD_ZERO(&rset);
  FD_SET(s, &rset);
  int n = SysUtil::select(s + 1, &rset, 0, 0, 100*1000);
  if (n) {
    ASSERT(FD_ISSET(s, &rset));
    int r = FileUtil::read(s, readBuffer);
    if (r == 0) {
      closeConnection();
    }
  }
} // testServerClosed

void HttpClient::closeConnection() {
  readBuffer.clear();
  if (s) {
    shutdown(s, SHUT_RDWR);
    close(s);
    s = 0;
  }
} // closeConnection

void HttpClient::setResponseSignal(pthread_cond_t* sig, pthread_mutex_t* siglock) {
  assert(requests);
  requests->setResultSignal(sig, siglock);
} // setResponseSignal

void HttpClient::clearResponseSignal() {
  assert(requests);
  requests->clearResultSignal();
} // clearResponseSignal

HttpClientResponseState* HttpClient::execute(HttpClientResponseState* r) {
  try {
    r->response.persistent = isConnected();
    r->response.beginRequest();
    sendRequest(r->request);
    r->response.completeRequest();
    r->response.beginResponse();
    readResponse(r->response);
    r->response.completeResponse();
  } catch (const HttpClientException& e) {
    r->hasException = true;
    r->exception = e;
  }

  if (r->obj && r->callback) {
    ((r->obj)->*(r->callback))(*r);
  }

  return r;
} // execute

void HttpClient::connectToServer() throw (HttpClientException) {
  if (!s) {
    struct sockaddr_in sa;
    SockUtil::fillSockAddr(server, port, sa);

    s = connectToServer(sa);
  }
} // connectToServer

int HttpClient::connectToServer(const struct sockaddr_in& sin)
  throw (HttpClientException) {
  int fd = socket(AF_INET, SOCK_STREAM, 0);
  if (fd < 0) {
    Log::perror("socket");
    assert(0);
  }

  int ret = connect(fd, (struct sockaddr*)&sin, sizeof(sin));

  if (ret == 0) {
    // in progress
  }
  else {
    string errstr = strerror(errno);
    ostringstream os;
    os << "connect: " << errstr << " on " << server << ":" << port;
    closeConnection();
    throw HttpClientException(os.str());
  }

  return fd;
} // connectToServer

max_stars_repo_name: jojochuang/eventwave

max_issues_repo_name: jojochuang/eventwave

max_forks_repo_name: jojochuang/eventwave


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2014 MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_SIGN_HPP_INCLUDED
#define BOOST_SIMD_IEEE_FUNCTIONS_SCALAR_SIGN_HPP_INCLUDED

#include <boost/simd/ieee/functions/sign.hpp>
#include <boost/simd/include/functions/scalar/if_one_else_zero.hpp>
#include <boost/simd/include/functions/scalar/is_ltz.hpp>
#include <boost/simd/include/functions/scalar/is_gtz.hpp>
#include <boost/simd/include/functions/scalar/shift_right.hpp>
#include <boost/simd/sdk/config.hpp>
#include <boost/dispatch/attributes.hpp>

#ifndef BOOST_SIMD_NO_NANS
#include <boost/simd/include/functions/scalar/is_nan.hpp>
#endif

namespace boost { namespace simd { namespace ext
{
  BOOST_DISPATCH_IMPLEMENT          ( sign_, tag::cpu_
                                    , (A0)
                                    , (scalar_< signed_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)
    {
      return if_one_else_zero(is_gtz(a0))-if_one_else_zero(is_ltz(a0));
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( sign_, tag::cpu_
                                    , (A0)
                                    , (scalar_< unsigned_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)
    {
      return !!a0;
    }
  };

  BOOST_DISPATCH_IMPLEMENT          ( sign_, tag::cpu_
                                    , (A0)
                                    , (scalar_< floating_<A0> >)
                                    )
  {
    typedef A0 result_type;
    BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1)
    {
      A0 r = bool(is_gtz(a0))-bool(is_ltz(a0));
      #ifdef BOOST_SIMD_NO_NANS
      return r;
      #else
      return is_nan(a0) ? a0 : r;
      #endif
    }
  };
} } }

#endif

ext: hpp


text: #include <boost/compute/functional/identity.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#define BOOST_TEST_MODULE pcraster com unordered_cross_table
#include <boost/test/unit_test.hpp>
#include "stddefx.h"
#include "com_unorderedcrosstable.h"

// TODO Check that the table mirrors indices.
BOOST_AUTO_TEST_CASE(simple_usage)
{
  using namespace com;

  // Create a cross table.
  UnOrderedCrossTable t(3);
  BOOST_CHECK(t.size() == 3);
  BOOST_CHECK(t.nrCells() == 9);
  BOOST_CHECK(t.cell(0, 0) == 0);
  BOOST_CHECK(t.cell(0, 1) == 0);
  BOOST_CHECK(t.cell(0, 2) == 0);
  BOOST_CHECK(t.cell(1, 1) == 0);
  BOOST_CHECK(t.cell(1, 2) == 0);
  BOOST_CHECK(t.cell(2, 2) == 0);

  // Fill it as folows:
  //   6 5 4
  //   - 0 4
  //   - - 1
  t.cell(0, 0) = 6;
  t.cell(0, 1) = 5;
  t.cell(0, 2) = 4;
  t.cell(1, 1) = 0;
  t.cell(1, 2) = 4;
  t.cell(2, 2) = 1;

  // Check the contents:
  BOOST_CHECK(t.cell(0, 0) == 6);
  BOOST_CHECK(t.cell(0, 1) == 5);
  BOOST_CHECK(t.cell(0, 2) == 4);
  BOOST_CHECK(t.cell(1, 1) == 0);
  BOOST_CHECK(t.cell(1, 2) == 4);
  BOOST_CHECK(t.cell(2, 2) == 1);

  // Fill it as folows:
  // 1 - -
  // 2 3 -
  // 4 5 6
  t.cell(0, 0) = 1;
  t.cell(1, 0) = 2;
  t.cell(1, 1) = 3;
  t.cell(2, 0) = 4;
  t.cell(2, 1) = 5;
  t.cell(2, 2) = 6;

  BOOST_CHECK(t.cell(0, 0) == 1);
  BOOST_CHECK(t.cell(0, 1) == 2);
  BOOST_CHECK(t.cell(0, 2) == 4);
  BOOST_CHECK(t.cell(1, 1) == 3);
  BOOST_CHECK(t.cell(1, 2) == 5);
  BOOST_CHECK(t.cell(2, 2) == 6);
}

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
#pragma once

#include <unordered_map>
#include <string>
#include <Eigen/Dense>
#include "MapOSC.hpp"

using namespace Eigen;
using namespace std;

struct cvglMixer
{

    int nsliders = 9;
    ArrayXd pregain, gain, amp;
    unordered_map<std::string, int> chan;

    double m_min_dB = -60;
    double m_max_dB = 20;
    double m_dB_range = m_max_dB + abs(m_min_dB);

    double m_min_amp_thresh = dbtoa(m_min_dB);

    cvglMixer()
    {
        pregain = ArrayXd::Constant(nsliders, -100);
        gain = ArrayXd::Constant(nsliders, -100);
        amp = ArrayXd::Zero(nsliders);

        chan.emplace("/perc",       0); // zero indexed
        chan.emplace("/gran",       1);
        chan.emplace("/res",        2);
        chan.emplace("/filter",     3);

        chan.emplace("/main",       8);

    }

    void addPregainMidi( MapOSC & b )
    {
        b.addMessage("/mixer/knob/1", getPregainMidi("/perc") );
        b.addMessage("/mixer/knob/2", getPregainMidi("/gran") );
        b.addMessage("/mixer/knob/3", getPregainMidi("/res") );
        b.addMessage("/mixer/knob/4", getPregainMidi("/filter") );
    }

    void applyAddGains( MapOSC & b )
    {
        applyPregain();

        b.addMessage("/perc/amp_scale", getAmp("/perc") );
        b.addMessage("/gran/amp_scale", getAmp("/gran") );
        b.addMessage("/res/amp_scale", getAmp("/res") );
        b.addMessage("/filter/amp_scale", getAmp("/filter") );
        b.addMessage("/main_dB", getGain("/main") );
    }

    void proc( MapOSC & b)
    {

        for( auto& m : b.getMap() )
        {
            const std::string& addr = m.first;
            const auto& atomVec = m.second;

            if( addr == "/mixer/fader/1") {
                midi_gain(1, atomVec.getInt() );
            } else if( addr == "/mixer/fader/2") {
                midi_gain(2, atomVec.getInt() );
            } else if( addr == "/mixer/fader/3") {
                midi_gain(3, atomVec.getInt() );
            } else if( addr == "/mixer/fader/4") {
                midi_gain(4, atomVec.getInt() );
            } else if( addr == "/mixer/fader/5") {
                midi_gain(5, atomVec.getInt() );
            } else if( addr == "/mixer/fader/6") {
                midi_gain(6, atomVec.getInt() );
            } else if( addr == "/mixer/fader/7") {
                midi_gain(7, atomVec.getInt() );
            } else if( addr == "/mixer/fader/8") {
                midi_gain(8, atomVec.getInt() );
            } else if( addr == "/mixer/fader/main") {
                midi_gain(9, atomVec.getInt() );
            } else if( addr == "/mixer/knob/1") {
                midi_pregain(1, atomVec.getInt() );
            } else if( addr == "/mixer/knob/2") {
                midi_pregain(2, atomVec.getInt() );
            } else if( addr == "/mixer/knob/3") {
                midi_pregain(3, atomVec.getInt() );
            } else if( addr == "/mixer/knob/4") {
                midi_pregain(4, atomVec.getInt() );
            } else if( addr == "/mixer/knob/5") {
                midi_pregain(5, atomVec.getInt() );
            } else if( addr == "/mixer/knob/6") {
                midi_pregain(6, atomVec.getInt() );
            } else if( addr == "/mixer/knob/7") {
                midi_pregain(7, atomVec.getInt() );
            } else if( addr == "/mixer/knob/8") {
                midi_pregain(8, atomVec.getInt() );
            }
        }

    }

    // range: -60 to 20 dB
    inline double midi2dB( int midi ){ return ((midi / 127.) * 80.) - 60.; }
    inline int32_t dB2midi( double db ){ return int32_t( ((db + 60.) / 80.) * 127.); }

    inline double dbtoa(double db){ return pow(10., (db / 20.)); }
    inline ArrayXd dbtoa(ArrayXd db){ return pow(10., (db / 20.)); }

    // setters
    inline void midi_gain(int channel, int midi_val)
    {
        if( channel > 0 && channel <= nsliders ) {
            gain(channel-1) = midi2dB( midi_val );
            //    std::cout << gain << std::endl;
        }
    }

    inline void midi_pregain(int channel, int midi_val)
    {
        if( channel > 0 && channel < nsliders ){ // no pregain on the main
            pregain[channel-1] = midi2dB( midi_val );
        }
    }

    inline void set_pregain(const string & channel, double db)
    {
        if( chan.count(channel) ){
            pregain[ chan[channel] ] = db;
        }
    }

    // calc
    void applyPregain()
    {
        amp = dbtoa(gain + pregain).unaryExpr([&](double x){return (x > m_min_amp_thresh ? x : 0.); });

        //     std::cout << amp << std::endl;
    }

    //getters

    inline double getAmp(const string & channel)
    {
        if( chan.count(channel) ){
            //    std::cout << amp( chan[channel] ) << std::endl;
            return amp( chan[channel] );
        }
        return 0;
    }

    inline double getGain(const string & channel)
    {
        if( chan.count(channel) ){
            //    std::cout << amp( chan[channel] ) << std::endl;
            return gain( chan[channel] );
        }
        return 0;
    }

    inline double getPregain(const string & channel)
    {
        if( chan.count(channel) ){
            return pregain( chan[channel] );
        }
        return 0;
    }

    inline int32_t getPregainMidi(const string & channel)
    {
        if( chan.count(channel) ){
            int32_t midi = dB2midi(pregain( chan[channel] ));
            return (midi < 0 ? 0 : (midi > 127 ? 127 : midi));
        }
        return 0;
    }

    void initMidi( MapOSC & b )
    {

        int32_t zeroMidi_dB = dB2midi(0);

        b.addMessage("/mixer/knob/1", zeroMidi_dB );
        b.addMessage("/mixer/knob/2", zeroMidi_dB );
        b.addMessage("/mixer/knob/3", zeroMidi_dB );
        b.addMessage("/mixer/knob/4", zeroMidi_dB );
        b.addMessage("/mixer/knob/5", zeroMidi_dB );
        b.addMessage("/mixer/knob/6", zeroMidi_dB );
        b.addMessage("/mixer/knob/7", zeroMidi_dB );
        b.addMessage("/mixer/knob/8", zeroMidi_dB );

        b.addMessage("/mixer/fader/1", zeroMidi_dB );
        b.addMessage("/mixer/fader/2", zeroMidi_dB  );
        b.addMessage("/mixer/fader/3", zeroMidi_dB );
        b.addMessage("/mixer/fader/4", zeroMidi_dB );
        b.addMessage("/mixer/fader/5", zeroMidi_dB );
        b.addMessage("/mixer/fader/6", zeroMidi_dB  );
        b.addMessage("/mixer/fader/7", zeroMidi_dB  );
        b.addMessage("/mixer/fader/8", zeroMidi_dB  );
        b.addMessage("/mixer/fader/main", 0 );

        midi_gain(0, zeroMidi_dB );
        midi_gain(1, zeroMidi_dB );
        midi_gain(2, zeroMidi_dB );
        midi_gain(3, zeroMidi_dB );
        midi_gain(4, zeroMidi_dB );
        midi_gain(5, zeroMidi_dB );
        midi_gain(6, zeroMidi_dB );
        midi_gain(7, zeroMidi_dB );
    }

};


text:
/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  @file JPetFrameTest.cpp
 */

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetFrameTest

#include "JPetFrame/JPetFrame.h"
#include "JPetFrame/JPetFrameFactory.h"

#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(FirstSuite)

BOOST_AUTO_TEST_CASE(default_constructor)
{
  JPetFrame frame;
  BOOST_REQUIRE_EQUAL(frame.getID(), -1);
  BOOST_REQUIRE(!frame.getIsActive());
  BOOST_REQUIRE(frame.getStatus().empty());
  BOOST_REQUIRE(frame.getDescription().empty());
  BOOST_REQUIRE_EQUAL(frame.getVersion(), -1);
  BOOST_REQUIRE_EQUAL(frame.getCreator(), -1);
}

BOOST_AUTO_TEST_CASE(second_constructor)
{
  JPetFrame frame(1, true, "ok", "descr1", 2, 1);
  BOOST_REQUIRE_EQUAL(frame.getID(), 1);
  BOOST_REQUIRE(frame.getIsActive());
  BOOST_REQUIRE(frame.getStatus() == "ok");
  BOOST_REQUIRE(frame.getDescription() == "descr1");
  BOOST_REQUIRE_EQUAL(frame.getVersion(), 2);
  BOOST_REQUIRE_EQUAL(frame.getCreator(), 1);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE(FactorySuite)

class TestParamGetter : public JPetParamGetter
{
  ParamObjectsDescriptions getAllBasicData(ParamObjectType, const int runId)
  {
    ParamObjectsDescriptions result;
    switch (runId)
    {
    case 0: // No frames
      break;
    case 1: // Simple single object
      result = {{1, {{"id", "1"}, {"active", "1"}, {"status", "ok"}, {"description", "descr1"}, {"version", "2"}, {"creator_id", "1"}}}};
      break;
    case 2: // Simple two objects
      result = {
          {1, {{"id", "1"}, {"active", "1"}, {"status", "ok"}, {"description", "descr1"}, {"version", "2"}, {"creator_id", "1"}}},
          {5, {{"id", "5"}, {"active", "0"}, {"status", "fainted"}, {"description", "looks like a fish"}, {"version", "1"}, {"creator_id", "99"}}}};
      break;
    case 3: // Object with missing field
      result = {{1, {{"id", "1"}, {"active", "1"}, {"status", "ok"}, {"version", "2"}, {"creator_id", "1"}}}};
      break;
    case 4: // Object with wrong field
      result = {{1, {{"id", "1"}, {"active", "probably"}, {"status", "ok"}, {"description", "descr1"}, {"version", "2"}, {"creator_id", "1"}}}};
      break;
    }
    return result;
  }
  ParamRelationalData getAllRelationalData(ParamObjectType, ParamObjectType, const int) { return ParamRelationalData(); } // Irrelevant for this test.
};

TestParamGetter paramGetter;

BOOST_AUTO_TEST_CASE(no_frames)
{
  JPetFrameFactory factory(paramGetter, 0);
  auto& frames = factory.getFrames();
  BOOST_REQUIRE_EQUAL(frames.size(), 0u);
}

BOOST_AUTO_TEST_CASE(single_object)
{
  JPetFrameFactory factory(paramGetter, 1);
  auto& frames = factory.getFrames();
  BOOST_REQUIRE_EQUAL(frames.size(), 1u);
  auto frame = frames[1];
  BOOST_REQUIRE_EQUAL(frame->getID(), 1);
  BOOST_REQUIRE(frame->getIsActive());
  BOOST_REQUIRE(frame->getStatus() == "ok");
  BOOST_REQUIRE(frame->getDescription() == "descr1");
  BOOST_REQUIRE_EQUAL(frame->getVersion(), 2);
  BOOST_REQUIRE_EQUAL(frame->getCreator(), 1);
}

BOOST_AUTO_TEST_CASE(two_objects)
{
  JPetFrameFactory factory(paramGetter, 2);
  auto& frames = factory.getFrames();
  BOOST_REQUIRE_EQUAL(frames.size(), 2u);
  auto frame = frames[1];
  BOOST_REQUIRE_EQUAL(frame->getID(), 1);
  BOOST_REQUIRE(frame->getIsActive());
  BOOST_REQUIRE(frame->getStatus() == "ok");
  BOOST_REQUIRE(frame->getDescription() == "descr1");
  BOOST_REQUIRE_EQUAL(frame->getVersion(), 2);
  BOOST_REQUIRE_EQUAL(frame->getCreator(), 1);
  frame = frames[5];
  BOOST_REQUIRE_EQUAL(frame->getID(), 5);
  BOOST_REQUIRE(!frame->getIsActive());
  BOOST_REQUIRE(frame->getStatus() == "fainted");
  BOOST_REQUIRE(frame->getDescription() == "looks like a fish");
  BOOST_REQUIRE_EQUAL(frame->getVersion(), 1);
  BOOST_REQUIRE_EQUAL(frame->getCreator(), 99);
}

BOOST_AUTO_TEST_CASE(missing_field)
{
  JPetFrameFactory factory(paramGetter, 3);
  BOOST_REQUIRE_THROW(factory.getFrames(), std::out_of_range);
}

BOOST_AUTO_TEST_CASE(wrong_field)
{
  JPetFrameFactory factory(paramGetter, 4);
  BOOST_REQUIRE_THROW(factory.getFrames(), std::bad_cast);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: BlurredChoise/j-pet-framework

max_issues_repo_name: BlurredChoise/j-pet-framework

max_forks_repo_name: BlurredChoise/j-pet-framework


text:
//
// Created by FyS on 16/06/17.
//

#define BOOST_TEST_MODULE test_bus

#include <boost/test/unit_test.hpp>
#include <bus/FysBus.hh>
#include <boost/thread.hpp>
#include <thread>

/**
 * ------------------------------------------------------
 *  Bus Initialisation test------------------------------
 * ------------------------------------------------------
 */

BOOST_AUTO_TEST_CASE( test_bus_ini )
{
    fys::mq::FysBus<std::string, 100> bus(2);
}

BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_bus_ini_error1, 1 )
BOOST_AUTO_TEST_CASE( test_bus_ini_error1 )
{
    fys::mq::FysBus<std::string, 100> bus(2);
}

BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES( test_bus_ini_error2, 1 )
BOOST_AUTO_TEST_CASE( test_bus_ini_error2 )
{
    fys::mq::FysBus<std::string, 100> bus(2);
}

/**
 *------------------------------------------------------
 * Bus exections test ----------------------------------
 *------------------------------------------------------
 */
fys::mq::LockFreeQueue<fys::mq::QueueContainer<std::string>, 5000> *lockFreeQueue;
int readValues;

void addinlockfreequeue(fys::mq::QueueContainer<std::string> &&container) {

    for (int i = 0; i < 1500; ++i) {
        lockFreeQueue->push(std::move(container));
    }
}

void readLockFreeQueue() {
    for (int i = 0; i < 10000; ++i) {
        std::optional<fys::mq::QueueContainer<std::string>> container;

        container = lockFreeQueue->pop();
        usleep(100);
        if (container) {
            ++readValues;
//            std::cout << readValues << " | ";
        }
    }
}

void initTestExecution() {
    lockFreeQueue = new fys::mq::LockFreeQueue<fys::mq::QueueContainer<std::string>, 5000>();
    lockFreeQueue->setLockingWhenEmpty(false);
    readValues = 0;
}

void cleanTestExecution() {
    if (lockFreeQueue != nullptr) {
        delete(lockFreeQueue);
        lockFreeQueue = nullptr;
    }
}

BOOST_AUTO_TEST_CASE( test_bus_exec ) {
    initTestExecution();
    std::cout << "begin test exec" << std::endl;
    fys::mq::QueueContainer<std::string> c1("A");
    fys::mq::QueueContainer<std::string> c2("B");
    fys::mq::QueueContainer<std::string> c3("C");
    std::thread workerRead(readLockFreeQueue);
    std::thread w1(addinlockfreequeue, std::move(c1));
    std::thread w2(addinlockfreequeue, std::move(c2));
    std::thread w3(addinlockfreequeue, std::move(c3));

    sleep(2);
    w1.join();
    w2.join();
    w3.join();
    workerRead.join();
    cleanTestExecution();
    std::cout << "end test exec : readValue = " << readValues << std::endl;
    BOOST_ASSERT(readValues == 4500);
}

max_stars_repo_name: FreeYourSoul/LockFreeMQ

max_issues_repo_name: FreeYourSoul/LockFreeMQ

max_forks_repo_name: FreeYourSoul/LockFreeMQ