text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 1995, 2007-2011 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 1995 Maarten Hilferink, Amsterdam, the Netherlands

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

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

#ifndef BOOST_GEOMETRY_STRATEGY_AGNOSTIC_SIMPLIFY_DOUGLAS_PEUCKER_HPP
#define BOOST_GEOMETRY_STRATEGY_AGNOSTIC_SIMPLIFY_DOUGLAS_PEUCKER_HPP

#include <cstddef>
#include <vector>

#include <boost/range.hpp>

#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/strategies/distance.hpp>

//#define GL_DEBUG_DOUGLAS_PEUCKER

#ifdef GL_DEBUG_DOUGLAS_PEUCKER
#include <boost/geometry/util/write_dsv.hpp>
#endif

namespace boost { namespace geometry
{

namespace strategy { namespace simplify
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail
{

    /*!
        \brief Small wrapper around a point, with an extra member "included"
        \details
            It has a const-reference to the original point (so no copy here)
        \tparam the enclosed point type
    */
    template<typename Point>
    struct douglas_peucker_point
    {
        Point const& p;
        bool included;

        inline douglas_peucker_point(Point const& ap)
            : p(ap)
            , included(false)
        {}

        // Necessary for proper compilation
        inline douglas_peucker_point<Point> operator=(
                    douglas_peucker_point<Point> const& other)
        {
            return douglas_peucker_point<Point>(*this);
        }
    };
}
#endif // DOXYGEN_NO_DETAIL

/*!
\brief Implements the simplify algorithm.
\ingroup strategies
\details The douglas_peucker strategy simplifies a linestring, ring or
    vector of points using the well-known Douglas-Peucker algorithm.
    For the algorithm, see for example:
\see http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
\see http://www2.dcs.hull.ac.uk/CISRG/projects/Royal-Inst/demos/dp.html
\tparam Point the point type
\tparam PointDistanceStrategy point-segment distance strategy to be used
\note This strategy uses itself a point-segment-distance strategy which
    can be specified
\author Barend and Maarten, 1995/1996
\author Barend, revised for Generic Geometry Library, 2008
*/
template
<
    typename Point,
    typename PointDistanceStrategy
>
class douglas_peucker
{
public :

    typedef typename strategy::distance::services::comparable_type<PointDistanceStrategy>::type distance_strategy_type;
    typedef typename strategy::distance::services::return_type<distance_strategy_type>::type return_type;

private :
    typedef detail::douglas_peucker_point<Point> dp_point_type;
    typedef typename std::vector<dp_point_type>::iterator iterator_type;

    static inline void consider(iterator_type begin,
                iterator_type end,
                return_type const& max_dist, int& n,
                distance_strategy_type const& ps_distance_strategy)
    {
        std::size_t size = end - begin;

        // size must be at least 3
        // because we want to consider a candidate point in between
        if (size <= 2)
        {
#ifdef GL_DEBUG_DOUGLAS_PEUCKER
            if (begin != end)
            {
                std::cout << "ignore between " << dsv(begin->p)
                    << " and " << dsv((end - 1)->p)
                    << " size=" << size << std::endl;
            }
            std::cout << "return because size=" << size << std::endl;
#endif
            return;
        }

        iterator_type last = end - 1;

#ifdef GL_DEBUG_DOUGLAS_PEUCKER
        std::cout << "find between " << dsv(begin->p)
            << " and " << dsv(last->p)
            << " size=" << size << std::endl;
#endif

        // Find most far point, compare to the current segment
        //geometry::segment<Point const> s(begin->p, last->p);
        return_type md(-1.0); // any value < 0
        iterator_type candidate;
        for(iterator_type it = begin + 1; it != last; ++it)
        {
            return_type dist = ps_distance_strategy.apply(it->p, begin->p, last->p);

#ifdef GL_DEBUG_DOUGLAS_PEUCKER
            std::cout << "consider " << dsv(it->p)
                << " at " << double(dist)
                << ((dist > max_dist) ? " maybe" : " no")
                << std::endl;

#endif
            if (dist > md)
            {
                md = dist;
                candidate = it;
            }
        }

        // If a point is found, set the include flag
        // and handle segments in between recursively
        if (md > max_dist)
        {
#ifdef GL_DEBUG_DOUGLAS_PEUCKER
            std::cout << "use " << dsv(candidate->p) << std::endl;
#endif

            candidate->included = true;
            n++;

            consider(begin, candidate + 1, max_dist, n, ps_distance_strategy);
            consider(candidate, end, max_dist, n, ps_distance_strategy);
        }
    }

public :

    template <typename Range, typename OutputIterator>
    static inline OutputIterator apply(Range const& range,
                    OutputIterator out, double max_distance)
    {
        distance_strategy_type strategy;

        // Copy coordinates, a vector of references to all points
        std::vector<dp_point_type> ref_candidates(boost::begin(range),
                        boost::end(range));

        // Include first and last point of line,
        // they are always part of the line
        int n = 2;
        ref_candidates.front().included = true;
        ref_candidates.back().included = true;

        // Get points, recursively, including them if they are further away
        // than the specified distance
        typedef typename strategy::distance::services::return_type<distance_strategy_type>::type return_type;

        consider(boost::begin(ref_candidates), boost::end(ref_candidates), max_distance, n, strategy);

        // Copy included elements to the output
        for(typename std::vector<dp_point_type>::const_iterator it
                        = boost::begin(ref_candidates);
            it != boost::end(ref_candidates);
            ++it)
        {
            if (it->included)
            {
                // copy-coordinates does not work because OutputIterator
                // does not model Point (??)
                //geometry::convert(it->p, *out);
                *out = it->p;
                out++;
            }
        }
        return out;
    }

};

}} // namespace strategy::simplify

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_STRATEGY_AGNOSTIC_SIMPLIFY_DOUGLAS_PEUCKER_HPP

max_stars_repo_name: zigaosolin/Raytracer

max_issues_repo_name: zigaosolin/Raytracer

max_forks_repo_name: zigaosolin/Raytracer


text:
/**
 * @copyright Copyright (c) 2017 B-com http://www.b-com.com/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <iostream>
#include <string>
#include <vector>
#include "xpcf/xpcf.h"

// ADD COMPONENTS HEADERS HERE

#include "api/solver/map/ITriangulator.h"
#include "api/input/devices/ICamera.h"

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

#include <boost/log/core.hpp>

// ADD COMPONENTS HEADERS HERE

#include "xpcf/xpcf.h"
#include "core/Log.h"
#include "api/image/IImageLoader.h"
#include "api/input/devices/ICamera.h"
#include "api/features/IKeypointDetector.h"
#include "api/features/IDescriptorsExtractor.h"
#include "api/features/IDescriptorMatcher.h"
#include "api/features/IMatchesFilter.h"
#include "api/solver/pose/I3DTransformFinderFrom2D2D.h"
#include "api/solver/map/ITriangulator.h"
#include "api/solver/map/IMapFilter.h"
#include "api/display/IMatchesOverlay.h"
#include "api/display/IImageViewer.h"
#include "api/display/I3DPointsViewer.h"

#include <iostream>
#include <fstream>

using namespace SolAR;
using namespace SolAR::datastructure;
using namespace SolAR::api;

namespace xpcf  = org::bcom::xpcf;

void help(){
    std::cout << "\n\n";
    std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n";
    std::cout << "Something went wrong with input files \n";
    std::cout << "please refer to README.adoc in the project directory \n";
    std::cout << "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n\n";
    exit(-1);
}

int main(){

#if NDEBUG
    boost::log::core::get()->set_logging_enabled(false);
#endif
  LOG_ADD_LOG_TO_CONSOLE();

  try {

        SRef<xpcf::IComponentManager> xpcfComponentManager = xpcf::getComponentManagerInstance();

        if(xpcfComponentManager->load("SolARTest_ModuleOpenGV_Triangulation_conf.xml")!=org::bcom::xpcf::_SUCCESS)
        {
            LOG_ERROR("Failed to load the configuration file SolARTest_ModuleOpenGV_Triangulation_conf.xml")
            return -1;
        }

        SRef<input::devices::ICamera> camera =xpcfComponentManager->resolve<input::devices::ICamera>();
        SRef<image::IImageLoader> imageLoader1 =xpcfComponentManager->resolve<image::IImageLoader>("image1");
        SRef<image::IImageLoader> imageLoader2 =xpcfComponentManager->resolve<image::IImageLoader>("image2");
        SRef<features::IKeypointDetector> keypointsDetector =xpcfComponentManager->resolve<features::IKeypointDetector>();
        SRef<features::IDescriptorsExtractor> descriptorExtractor =xpcfComponentManager->resolve<features::IDescriptorsExtractor>();
        SRef<features::IDescriptorMatcher> matcher =xpcfComponentManager->resolve<features::IDescriptorMatcher>();
        SRef<display::IMatchesOverlay> overlayMatches =xpcfComponentManager->resolve<display::IMatchesOverlay>();
        SRef<display::IImageViewer> viewerMatches =xpcfComponentManager->resolve<display::IImageViewer>();
        SRef<solver::pose::I3DTransformFinderFrom2D2D> poseFinderFrom2D2D =xpcfComponentManager->resolve<solver::pose::I3DTransformFinderFrom2D2D>();
        SRef<solver::map::ITriangulator> triangulator_opengv = xpcfComponentManager->resolve<solver::map::ITriangulator>();
        SRef<solver::map::IMapFilter> mapFilter =xpcfComponentManager->resolve<solver::map::IMapFilter>();
        SRef<display::I3DPointsViewer> viewer3DPoints =xpcfComponentManager->resolve<display::I3DPointsViewer>();

        // declarations of data structures used to exange information between components
        SRef<Image>                     image1;
        SRef<Image>                     image2;

        std::vector<Keypoint>           keypoints1;
        std::vector<Keypoint>           keypoints2;

        SRef<DescriptorBuffer>          descriptors1;
        SRef<DescriptorBuffer>          descriptors2;
        std::vector<DescriptorMatch>    matches;

        std::vector<SRef<CloudPoint>>   cloud, filteredCloud;

        SRef<Image>                     matchesImage;

        Transform3Df                    poseFrame1 = Transform3Df::Identity();
        Transform3Df                    poseFrame2;

        // initialize components requiring the camera intrinsic parameters (please refeer to the use of intrinsic parameters file)
        poseFinderFrom2D2D->setCameraParameters(camera->getIntrinsicsParameters(), camera->getDistortionParameters());
        triangulator_opengv->setCameraParameters(camera->getIntrinsicsParameters(), camera->getDistortionParameters());

        // Get first image
        if (imageLoader1->getImage(image1) != FrameworkReturnCode::_SUCCESS){

            LOG_ERROR("Cannot load image 1 with path {}", imageLoader1->bindTo<xpcf::IConfigurable>()->getProperty("pathFile")->getStringValue());
            return -1;
        }

        // Get second image
        if (imageLoader2->getImage(image2) != FrameworkReturnCode::_SUCCESS)
        {
            LOG_ERROR("Cannot load image 2 with path {}", imageLoader2->bindTo<xpcf::IConfigurable>()->getProperty("pathFile")->getStringValue());
            return -1;
        }

        // Detect the keypoints for the first image
        keypointsDetector->detect(image1, keypoints1);
        // Detect the keypoints for the second image
        keypointsDetector->detect(image2, keypoints2);
        // Compute the descriptor for each keypoint extracted from the first image
        descriptorExtractor->extract(image1, keypoints1, descriptors1);
        // Compute the descriptor for each keypoint extracted from the second image
        descriptorExtractor->extract(image2, keypoints2, descriptors2);
        // Compute the matches between the keypoints of the first image and the keypoints of the second image
        matcher->match(descriptors1, descriptors2, matches);
        int nbMatches = (int)matches.size();

        // Estimate the pose of the second frame (the first frame being the reference of our coordinate system)
        poseFinderFrom2D2D->estimate(keypoints1, keypoints2, poseFrame1, poseFrame2, matches);
        LOG_DEBUG("Number of matches used for triangulation {}//{}", matches.size(), nbMatches);
        LOG_DEBUG("Estimated pose of the camera for the frame 2: \n {}", poseFrame2.matrix());

        // Create a image showing the matches used for pose estimation of the second camera
        overlayMatches->draw(image1, image2, matchesImage, keypoints1, keypoints2, matches);

        // Triangulate the inliers keypoints which match
        double reproj_error_opengv = triangulator_opengv->triangulate(keypoints1,keypoints2,matches,std::make_pair(0, 1),poseFrame1,poseFrame2,cloud);

         std::ofstream myfile;
         myfile.open ("debug_point_position.txt");
         myfile << "#p1 and then p1 from open Gv point cloud";

        for ( unsigned int k =0; k <  cloud.size(); k++){

           myfile << cloud[k]->getX()<<" "<<cloud[k]->getY()<<" "<<cloud[k]->getZ();
           myfile<<"\n";
        };

        myfile.close();

        //    LOG_DEBUG("Reprojection error: {}", reproj_error);
        LOG_INFO("\n\n Reprojection error using opengv: {}\n\n", reproj_error_opengv);

        mapFilter->filter(poseFrame1, poseFrame2, cloud, filteredCloud);

        // Display the matches and the 3D point cloudfilteredCloud
        while (true){
            if (viewer3DPoints->display(cloud, poseFrame2) == FrameworkReturnCode::_STOP ||
                viewerMatches->display(matchesImage) == FrameworkReturnCode::_STOP  ){

                LOG_DEBUG("End of Triangulation sample");
               break;
            }
        }
    }
    catch (xpcf::Exception e)
    {
      LOG_ERROR ("The following exception has been catched: {}", e.what());
      return -1;
    }
    return 0;
}

ext: cpp

max_stars_repo_name: SolarFramework/SolARModuleOpenGV

max_issues_repo_name: SolarFramework/SolARModuleOpenGV

max_forks_repo_name: SolarFramework/SolARModuleOpenGV


text:
// Copyright (c) 2019 Weile Wei
// Copyright (c) 2019 Maxwell Reeser
// Copyright (c) 2019 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

////////////////////////////////////////////////////////////////////////////////
/// This is a distributed_object example using HPX component.
///
/// A distributed object is a single logical object partitioned across
/// a set of localities. (A locality is a single node in a cluster or a
/// NUMA domian in a SMP machine.) Each locality constructs an instance of
/// distributed_object<T>, where a value of type T represents the value of this
/// this locality's instance value. Once distributed_object<T> is conctructed, it
/// has a universal name which can be used on any locality in the given
/// localities to locate the resident instance.

#include <phylanx/config.hpp>
#include <phylanx/include/util.hpp>

#include <hpx/hpx_init.hpp>
#include <hpx/lcos/barrier.hpp>
#include <hpx/parallel/algorithms/for_each.hpp>

#include <hpx/lcos/async.hpp>
#include <hpx/lcos/dataflow.hpp>
#include <hpx/lcos/when_all.hpp>
#include <hpx/testing.hpp>

#include <boost/range/irange.hpp>

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

REGISTER_DISTRIBUTED_OBJECT(int);

using vector_int = std::vector<int>;
REGISTER_DISTRIBUTED_OBJECT(vector_int);
using matrix_int = std::vector<std::vector<int>>;
REGISTER_DISTRIBUTED_OBJECT(matrix_int);

REGISTER_DISTRIBUTED_OBJECT(double);
using vector_double = std::vector<double>;
REGISTER_DISTRIBUTED_OBJECT(vector_double);
using matrix_double = std::vector<std::vector<double>>;
REGISTER_DISTRIBUTED_OBJECT(matrix_double);
using vector_double_const = std::vector<double> const;
REGISTER_DISTRIBUTED_OBJECT(vector_double_const);

using int_ref = int&;
REGISTER_DISTRIBUTED_OBJECT(int_ref);
using vector_int_ref = std::vector<int>&;
REGISTER_DISTRIBUTED_OBJECT(vector_int_ref);
using vector_double_const_ref = std::vector<double> const&;
REGISTER_DISTRIBUTED_OBJECT(vector_double_const_ref);

// addition/sum reduced to locality  for distributed_object
void test_distributed_object_int_reduce_to_locality_0()
{
    using phylanx::util::distributed_object;
    size_t num_localities = hpx::get_num_localities(hpx::launch::sync);
    size_t cur_locality = hpx::get_locality_id();

    // Construct a distributed object of type int in all provided localities
    // User needs to provide the distributed object with a unique basename
    // and data for construction. The unique basename string enables HPX
    // register and retrieve the distributed object.
    distributed_object<int> dist_int(
        "test_distributed_object_int_reduce_to_locality_0", cur_locality,
        num_localities, cur_locality);

    // If there exists more than 2 (and include) localities, we are able to
    // asynchronously fetch a future of a copy of the instance of this
    // distributed object associated with the given locality
    if (hpx::get_locality_id() >= 2)
    {
        HPX_TEST_EQ(dist_int.fetch(1).get(), 1);
    }

    if (cur_locality == 0 && num_localities >= 2)
    {
        using hpx::parallel::for_each;
        using hpx::parallel::execution::par;
        auto range = boost::irange(std::size_t(1), num_localities);

        // compute expect result in parallel locality 0 fetches all values
        int expect_res = 0;
        for_each(par, std::begin(range), std::end(range),
            [&](std::uint64_t b) { expect_res += dist_int.fetch(b).get(); });
        hpx::wait_all();

        // compute target result
        // to verify the accumulation results
        int target_res = 0;
        for (int i = 0; i < num_localities; i++)
        {
            target_res += i;
        }

        HPX_TEST_EQ(expect_res, target_res);
    }

    hpx::lcos::barrier wait_for_operation(
        "barrier_test_distributed_object_int_reduce_to_locality_0",
        hpx::get_num_localities(hpx::launch::sync),
        hpx::get_locality_id());
    wait_for_operation.wait();
}

// element-wise addition for vector<int> for distributed_object
void test_distributed_object_vector_elem_wise_add()
{
    using phylanx::util::distributed_object;
    size_t num_localities = hpx::get_num_localities(hpx::launch::sync);
    size_t cur_locality = hpx::get_locality_id();

    // define vector based on the locality that it is running
    int here_ = 42 + static_cast<int>(hpx::get_locality_id());
    int len = 10;

    // data for distributed object
    std::vector<int> local(len, here_);

    // construct a distributed_object with vector<int> type
    distributed_object<std::vector<int>> local_do(
        "test_distributed_object_vector_elem_wise_add", local);

    // testing -> operator
    HPX_TEST_EQ(local_do->size(), static_cast<size_t>(len));

    // testing dist_object and its vector underneath
    // testing * operator
    HPX_TEST((*local_do) == local);

    // perform element-wise addition between distributed_objects
    for (int i = 0; i < len; i++)
    {
        (*local_do)[i] += 1;
    }

    if (cur_locality == 0 && num_localities >= 2)
    {
        using hpx::parallel::for_each;
        using hpx::parallel::execution::par;
        auto range = boost::irange(std::size_t(1), num_localities);

        std::vector<std::vector<int>> res(num_localities);

        // compute expect result in parallel, locality 0 fetches all values
        for_each(par, std::begin(range), std::end(range), [&](std::uint64_t b) {
            res[b] = local_do.fetch(b).get();
            for (int i = 0; i < len; i++)
            {
                HPX_TEST_EQ(res[b][i], static_cast<int>((*local_do)[i] + b));
            }
        });
    }

    hpx::lcos::barrier wait_for_operation(
        "barrier_test_distributed_object_vector_elem_wise_add",
        hpx::get_num_localities(hpx::launch::sync),
        hpx::get_locality_id());
    wait_for_operation.wait();
}

// element-wise addition for vector<vector<double>> for distributed_object
void test_distributed_object_matrix()
{
    using phylanx::util::distributed_object;
    double val = 42.0 + static_cast<double>(hpx::get_locality_id());
    int rows = 5, cols = 5;

    matrix_double lhs_data(rows, std::vector<double>(cols, val));
    matrix_double rhs_data(rows, std::vector<double>(cols, val));
    matrix_double res_data(rows, std::vector<double>(cols, 0));

    distributed_object<matrix_double> lhs(
        "test_distributed_object_matrix_m1", lhs_data);
    distributed_object<matrix_double> rhs(
        "test_distributed_object_matrix_m2", rhs_data);
    distributed_object<matrix_double> res(
        "test_distributed_object_matrix_m3", res_data);

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            (*res)[i][j] = (*lhs)[i][j] + (*rhs)[i][j];
            res_data[i][j] = lhs_data[i][j] + rhs_data[i][j];
        }
    }

    HPX_TEST((*res) == res_data );
    HPX_TEST_EQ(res->size(), static_cast<size_t>(rows));

    // test fetch function when 2 or more localities provided
    if (hpx::get_num_localities(hpx::launch::sync) > 1)
    {
        if (hpx::get_locality_id() == 0)
        {
            hpx::future<matrix_double> res_first = res.fetch(1);
            HPX_TEST_EQ(res_first.get()[0][0], 86);
        }
        else
        {
            hpx::future<matrix_double> res_first = res.fetch(0);
            HPX_TEST_EQ(res_first.get()[0][0], 84);
        }
    }

    hpx::lcos::barrier b_dist_matrix("barrier_test_distributed_object_matrix",
        hpx::get_num_localities(hpx::launch::sync),
        hpx::get_locality_id());
    b_dist_matrix.wait();
}

// test constructor in all_to_all option
void test_distributed_object_matrix_all_to_all()
{
    using phylanx::util::distributed_object;
    double val = 42.0 + static_cast<double>(hpx::get_locality_id());
    int rows = 5, cols = 5;

    matrix_double lhs_data(rows, std::vector<double>(cols, val));
    matrix_double rhs_data(rows, std::vector<double>(cols, val));
    matrix_double res_data(rows, std::vector<double>(cols, 0));

    using c_t = phylanx::util::construction_type;

    distributed_object<matrix_double, c_t::all_to_all> lhs(
        "test_distributed_object_matrix_all_to_all_m1", lhs_data);
    distributed_object<matrix_double, c_t::all_to_all> rhs(
        "test_distributed_object_matrix_all_to_all_m2", rhs_data);
    distributed_object<matrix_double, c_t::all_to_all> res(
        "test_distributed_object_matrix_all_to_all_m3", res_data);

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            (*res)[i][j] = (*lhs)[i][j] + (*rhs)[i][j];
            res_data[i][j] = lhs_data[i][j] + rhs_data[i][j];
        }
    }
    HPX_TEST((*res) == res_data);
    HPX_TEST_EQ(res->size(), static_cast<size_t>(rows));

    // test fetch function when 2 or more localities provided
    if (hpx::get_num_localities(hpx::launch::sync) > 1)
    {
        if (hpx::get_locality_id() == 0)
        {
            hpx::future<matrix_double> res_first = res.fetch(1);
            HPX_TEST_EQ(res_first.get()[0][0], 86);
        }
        else
        {
            hpx::future<matrix_double> res_first = res.fetch(0);
            HPX_TEST_EQ(res_first.get()[0][0], 84);
        }
    }

    hpx::lcos::barrier b_dist_matrix_2(
        "barrier_test_distributed_object_matrix_all_to_all",
        hpx::get_num_localities(hpx::launch::sync),
        hpx::get_locality_id());
    b_dist_matrix_2.wait();
}

// test constructor option with reference to an existing object
void test_distributed_object_ref()
{
    using phylanx::util::distributed_object;
    size_t n = 10;
    int val = 2;

    int val_update = 42;
    vector_int vec1(n, val);
    distributed_object<vector_int&> dist_vec(
        "test_distributed_object_ref", vec1);

    // The update/change to the existing/referring object
    // will reflect the change to the distributed object
    vec1[2] = val_update;

    HPX_TEST_EQ((*dist_vec)[2], val_update);
    HPX_TEST_EQ(dist_vec->size(), static_cast<size_t>(n));

    hpx::lcos::barrier b(
        "barrier_test_distributed_object_ref",
        hpx::get_num_localities(hpx::launch::sync),
        hpx::get_locality_id());
    b.wait();
}

// test constructor option with reference to a const existing object
void test_distributed_object_const_ref()
{
    using phylanx::util::distributed_object;
    int n = 10;
    double val = 42.0;

    vector_double_const vec1(n, val);
    distributed_object<vector_double_const_ref> dist_vec(
        "test_distributed_object_const_ref", vec1);

    hpx::lcos::barrier b(
        "barrier_test_distributed_object_const_ref",
        hpx::get_num_localities(hpx::launch::sync),
        hpx::get_locality_id());
    b.wait();
}

// simple matrix multiplication example
void test_distributed_object_matrix_mul()
{
    using phylanx::util::distributed_object;
    size_t cols = 5;    // Decide how big the matrix should be

    size_t num_locs = hpx::get_num_localities(hpx::launch::sync);
    std::vector<std::pair<size_t, size_t>> ranges(num_locs);

    // Create a list of row ranges for each partition
    size_t start = 0;
    size_t diff = (int) std::ceil((double) cols / ((double) num_locs));
    for (size_t i = 0; i < num_locs; i++)
    {
        size_t second = (std::min)(cols, start + diff);
        ranges[i] = std::make_pair(start, second);
        start += diff;
    }

    // Create our data, stored in all_data's. This way we can check for validity
    // without using anything distributed. The seed being a constant is needed
    // in order for all nodes to generate the same data
    size_t here = hpx::get_locality_id();
    size_t local_rows = ranges[here].second - ranges[here].first;
    std::vector<std::vector<std::vector<int>>> all_data_m1(
        hpx::get_num_localities(hpx::launch::sync));

    std::srand(123456);

    for (size_t i = 0; i < all_data_m1.size(); i++)
    {
        size_t tmp_num_rows = ranges[i].second - ranges[i].first;
        all_data_m1[i] = std::vector<std::vector<int>>(
            tmp_num_rows, std::vector<int>(cols, 0));
        for (size_t j = 0; j < tmp_num_rows; j++)
        {
            for (size_t k = 0; k < cols; k++)
            {
                all_data_m1[i][j][k] = std::rand();
            }
        }
    }

    std::vector<std::vector<std::vector<int>>> all_data_m2(
        hpx::get_num_localities(hpx::launch::sync));

    std::srand(7891011);

    for (size_t i = 0; i < all_data_m2.size(); i++)
    {
        size_t tmp_num_rows = ranges[i].second - ranges[i].first;
        all_data_m2[i] = std::vector<std::vector<int>>(
            tmp_num_rows, std::vector<int>(cols, 0));
        for (size_t j = 0; j < tmp_num_rows; j++)
        {
            for (size_t k = 0; k < cols; k++)
            {
                all_data_m2[i][j][k] = std::rand();
            }
        }
    }

    std::vector<std::vector<int>> here_data_m3(
        local_rows, std::vector<int>(cols, 0));

    using c_t = phylanx::util::construction_type;

    distributed_object<matrix_int, c_t::all_to_all> M1(
        "M1_meta_mat_mul", all_data_m1[here]);
    distributed_object<matrix_int, c_t::all_to_all> M2(
        "M2_meta_mat_mul", all_data_m2[here]);
    distributed_object<matrix_int, c_t::all_to_all> M3(
        "M3_meta_mat_mul", here_data_m3);

    // Actual matrix multiplication. For non-local values, get the data
    // and then use it, for local, just use the local data without doing
    // a fetch to get it
    size_t num_before_me = here;
    for (size_t p = 0; p < num_before_me; p++)
    {
        std::vector<std::vector<int>> non_local = M2.fetch(p).get();
        for (size_t i = 0; i < local_rows; i++)
        {
            for (size_t j = ranges[p].first; j < ranges[p].second; j++)
            {
                for (size_t k = 0; k < cols; k++)
                {
                    (*M3)[i][j] +=
                        (*M1)[i][k] * non_local[j - ranges[p].first][k];
                    here_data_m3[i][j] += all_data_m1[here][i][k] *
                        all_data_m2[p][j - ranges[p].first][k];
                }
            }
        }
    }
    for (size_t i = 0; i < local_rows; i++)
    {
        for (size_t j = ranges[here].first; j < ranges[here].second; j++)
        {
            for (size_t k = 0; k < cols; k++)
            {
                (*M3)[i][j] += (*M1)[i][k] * (*M2)[j - ranges[here].first][k];
                here_data_m3[i][j] += all_data_m1[here][i][k] *
                    all_data_m2[here][j - ranges[here].first][k];
            }
        }
    }
    for (size_t p = here + 1; p < num_locs; p++)
    {
        std::vector<std::vector<int>> non_local = M2.fetch(p).get();
        for (size_t i = 0; i < local_rows; i++)
        {
            for (size_t j = ranges[p].first; j < ranges[p].second; j++)
            {
                for (size_t k = 0; k < cols; k++)
                {
                    (*M3)[i][j] +=
                        (*M1)[i][k] * non_local[j - ranges[p].first][k];
                    here_data_m3[i][j] += all_data_m1[here][i][k] *
                        all_data_m2[p][j - ranges[p].first][k];
                }
            }
        }
    }
    HPX_TEST((*M3) == here_data_m3);

    hpx::lcos::barrier b(
        "barrier_test_distributed_object_const_ref",
        hpx::get_num_localities(hpx::launch::sync),
        hpx::get_locality_id());
    b.wait();
}

void test_dist_object_vector_mo_sub_localities_constructor()
{
    using c_t = phylanx::util::construction_type;
    using phylanx::util::distributed_object;
    size_t num_localities = hpx::get_num_localities(hpx::launch::sync);
    size_t cur_locality = static_cast<size_t>(hpx::get_locality_id());

    // define vector based on the locality that it is running
    int here_ = 42 + static_cast<int>(hpx::get_locality_id());
    int len = 10;

    // prepare vector data
    std::vector<int> local(len, here_);
    std::vector<size_t> sub_localities{0, 1};

    if (num_localities >= 2 &&
        std::find(sub_localities.begin(), sub_localities.end(),
            static_cast<size_t>(cur_locality)) != sub_localities.end())
    {
        // construct a distributed_object with vector<int> type
        distributed_object<std::vector<int>, c_t::all_to_all> local_do(
            "test_dist_object_vector_mo_sub_localities_constructor", local, 2);

        // testing -> operator
        HPX_TEST_EQ(local_do->size(), static_cast<size_t>(len));

        // testing dist_object and its vector underneath
        // testing * operator
        HPX_TEST((*local_do) == local);

        // perform element-wise addition between distributed_objects
        for (int i = 0; i < len; i++)
        {
            (*local_do)[i] += 1;
        }

        hpx::lcos::barrier b(
            "barrier_test_dist_object_vector_mo_sub_localities_constructor",
            sub_localities.size(), cur_locality);
        b.wait();

        std::sort(sub_localities.begin(), sub_localities.end());
        if (cur_locality == sub_localities[0])
        {
            using hpx::parallel::for_each;
            using hpx::parallel::execution::par;

            std::vector<std::vector<int>> res(num_localities);

            // compute expect result in parallel, locality 0 fetches all values
            for_each(par, std::begin(sub_localities) + 1, std::end(sub_localities),
                [&](std::uint64_t b) {
                    res[b] = local_do.fetch(b).get();
                    for (int i = 0; i < len; i++)
                    {
                        HPX_TEST_EQ(
                            res[b][i], static_cast<int>((*local_do)[i] + b));
                    }
                });
        }

        b.wait();
    }
}

void test_distributed_object_sub_localities_constructor()
{
    using phylanx::util::distributed_object;
    std::vector<int> input(10, 1);
    if (hpx::get_locality_id() == 0)
    {
        distributed_object<std::vector<int>> vec1(
            "test_distributed_object_sub_localities_constructor", input, 1, 0);
    }
}

int hpx_main()
{
    {
        test_distributed_object_int_reduce_to_locality_0();
        test_distributed_object_vector_elem_wise_add();
        test_distributed_object_matrix();
        test_distributed_object_matrix_all_to_all();
        test_distributed_object_matrix_mul();
        test_distributed_object_ref();
        test_distributed_object_const_ref();
        test_dist_object_vector_mo_sub_localities_constructor();
        test_distributed_object_sub_localities_constructor();
    }
    hpx::finalize();
    return hpx::util::report_errors();
}

int main(int argc, char* argv[])
{
    std::vector<std::string> cfg = {
        "hpx.run_hpx_main!=1"
    };

    return hpx::init(argc, argv, cfg);
}


text:
//          Copyright Joe Coder 2004 - 2006.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          https://www.boost.org/LICENSE_1_0.txt)

#include <pcap.h>
#include <stdio.h>			//printf(), BUFSIZ
#include <arpa/inet.h>			//inet_ntop()
#include <cstring>			//memcmp(), strncpy()
#include <net/ethernet.h>		//struct ether_header, ETHERTYPE
#include <netinet/ip.h>			//struct ip, IPPROTO
#include <netinet/tcp.h>		//struct tcphdr
#include <sys/ioctl.h>			//ioctl()
#include <net/if.h>			//struct ifreq
#include <omp.h>			//OpenMP
#include <boost/thread/thread.hpp>	//boost::thread
#include <boost/chrono/chrono.hpp>	//boost::chrono
#include <boost/noncopyable.hpp>	//boost::noncopyable
#include <boost/move/unique_ptr.hpp>	//boost::unique_ptr
#include <boost/move/make_unique.hpp>	//boost::make_unique
#include "header.h"

using namespace boost::chrono;
using boost::movelib::unique_ptr;
using boost::movelib::make_unique;
using boost::chrono::steady_clock;
using boost::thread;

class Header : private boost::noncopyable {
	protected:
		virtual void print() = 0;
	public:
		Header() {};
		virtual ~Header() {};
};

class Ethhdr : protected Header {
	private:
		struct ether_header *ether;
	protected:
		void macprint(const uint8_t *src) {
			for(int i = 0; i < ETH_ALEN; i++)
				printf("%02X:", *(src + i));
			printf("\b \n");
		}
		void broadcast() {
			for(int i = 0; i < ETH_ALEN; i++)
				ether->ether_dhost[i] = 0xff;
		}
	public:
		Ethhdr() { this->ether = nullptr; }
		Ethhdr(const u_char **packet) {
			this->ether = (struct ether_header *)*packet;
		}
		~Ethhdr() override { this->ether = nullptr; }
		uint16_t getEthertype() { return ntohs(this->ether->ether_type); }
		void print() override {
			printf("Source MAC Address : ");
			macprint(ether->ether_shost);
			printf("Destination MAC Address : ");
			macprint(ether->ether_dhost);
			printf("Ether Type : %04x\n", getEthertype());
		}
		void ether_build(const uint8_t* const smac,
				const uint8_t* const tmac = nullptr) {
			if(tmac == nullptr)
				broadcast();
			else
				memcpy(this->ether->ether_dhost, tmac,
					sizeof(this->ether->ether_dhost));
			memcpy(this->ether->ether_shost, smac,
				sizeof(this->ether->ether_shost));
			this->ether->ether_type = htons(ETHERTYPE_ARP);
		}
};

class Iphdr : protected Header {
	private:
		const struct ip *ip;
	public:
		Iphdr() { this->ip = nullptr; }
		Iphdr(const u_char **packet) {
			this->ip = (const struct ip *)*packet;
			*packet += this->ip->ip_hl * 4;
		}
		~Iphdr() override { this->ip = nullptr; }
		void print() override;
		uint16_t getIplen() const { return ntohs(this->ip->ip_len); }
		uint8_t getIphl() const { return this->ip->ip_hl; }
		uint8_t getIpproto() const { return this->ip->ip_p; }
};

class Tcphdr : protected Header {
	private:
		const struct tcphdr *tcp;
	public:
		Tcphdr() { this->tcp = nullptr; }
		Tcphdr(const u_char **packet) {
			this->tcp = (const struct tcphdr *)*packet;
			*packet += getThoff() * 4;
		}
		~Tcphdr() override { this->tcp = nullptr; }
		void print() override {
			printf("Source Port Address : %d\n", getThsport());
			printf("Destination Port Address : %d\n", getThdport());
		}
		uint16_t getThsport() const { return ntohs(this->tcp->th_sport); }
		uint16_t getThdport() const { return ntohs(this->tcp->th_dport); }
		uint8_t getThoff() const { return this->tcp->th_off; }
};

class Httphdr : protected Header {
	private:
		const u_char *packet;
		uint8_t len;
	public:
		Httphdr() { this->packet = nullptr; }
		Httphdr(const Iphdr *ip, const Tcphdr *tcp,  const u_char **packet) {
			this->packet = *packet;
			this->len = ip->getIplen() - ip->getIphl() * 4 - tcp->getThoff() * 4;
		}
		~Httphdr() final { this->packet = nullptr; }
		bool Ishttp(uint8_t src, uint8_t dst) {
			if((src == 80 || dst == 80) && this->len) return true;
			else return false;
		}
		void print() final {
			if(this->len > 16)	this->len = 16;
			printf("Http Data : ");
			int i = 0;
			while(i < this->len)
				printf("%c", *(this->packet + i++));
			if(*(this->packet + --i) != '\n') putchar('\n');
		}
};

class Udphdr : protected Header {
	private:
		const struct udphdr *udp;
	protected:
		uint16_t getUhsport() { return ntohs(this->udp->uh_sport); }
		uint16_t getUhdport() { return ntohs(this->udp->uh_dport); }
	public:
		Udphdr() { this->udp = nullptr; }
		Udphdr(const u_char **packet) {
			this->udp = (struct udphdr *)*packet;
			*packet += sizeof(struct udphdr);
		}
		~Udphdr() override { this->udp = nullptr; }
		void print() override {
			printf("Source Port Address : %d\n", getUhsport());
			printf("Destination Port Address : %d\n", getUhdport());
		}
};

class Arphdr : protected Header {
	private:
		struct arphdr *arp;
	protected:
		void macprint(const uint8_t *src) {
			for(int i = 0; i < ETH_ALEN; i++)
				printf("%02X:", *(src + i));
			printf("\b \n");
		}
		void arp_request(const uint8_t* const smac) {
			memcpy(arp->ar_sha, smac, sizeof(arp->ar_sha));
			for(int i = 0; i < ETH_ALEN; i++)
				arp->ar_tha[i] = 0x00;
			arp->ar_op = htons(0x0001);	//Opcode request (1)
		}
		void arp_reply(const uint8_t* const smac,
		const uint8_t* const tmac) {
			memcpy(arp->ar_sha, smac, sizeof(arp->ar_sha));
			memcpy(arp->ar_tha, tmac, sizeof(arp->ar_sha));
			arp->ar_op = htons(0x0002);	//Opcode reply (2)
		}
	public:
		Arphdr() { arp = nullptr; }
		Arphdr(const u_char **packet) {
			arp = (struct arphdr *)(*packet + sizeof(ether_header));
		}
		~Arphdr() override { arp = nullptr; }
		uint16_t getOpcode() { return htons(arp->ar_op); }
		uint32_t getSip() { return htonl(arp->ar_sip.s_addr); }
		uint32_t getTip() { return htonl(arp->ar_tip.s_addr); }
		uint8_t* getSha() { return arp->ar_sha; }
		uint8_t* getTha() { return arp->ar_tha; }
		void print() override;
		void arp_build(struct in_addr* const sip, const uint8_t* const smac,
		struct in_addr* const tip, const uint8_t* const tmac);
};

void Iphdr::print() {
	char src_buf[16], dst_buf[16];

	inet_ntop(AF_INET, &this->ip->ip_src.s_addr, src_buf, sizeof(src_buf));
	inet_ntop(AF_INET, &this->ip->ip_dst.s_addr, dst_buf, sizeof(dst_buf));
	printf("Source IP Address : %s\n", src_buf);
	printf("Destination IP Address : %s\n", dst_buf);
}

void Arphdr::print() {
	char src_buf[16], dst_buf[16];

	inet_ntop(AF_INET, &this->arp->ar_sip.s_addr, src_buf, sizeof(src_buf));
	inet_ntop(AF_INET, &this->arp->ar_tip.s_addr, dst_buf, sizeof(dst_buf));
	printf("Opcode : %02x\n", this->getOpcode());
	printf("Sender MAC Address : ");
	macprint(arp->ar_sha);
	printf("Sender IP Address : %s\n", src_buf);
	printf("Target MAC Address : ");
	macprint(arp->ar_tha);
	printf("Target IP Address : %s\n", dst_buf);
}

void Arphdr::arp_build(struct in_addr* const sip, const uint8_t* const smac,
		struct in_addr* const tip, const uint8_t* const tmac = nullptr) {
	if(tmac == nullptr)
		this->arp_request(smac);
	else
		this->arp_reply(smac, tmac);
	arp->ar_hrd = htons(0x0001);	//0x0001 -> Ethernet
	arp->ar_pro = htons(0x0800);	//0x0800 -> IPv4(default)
	arp->ar_hln = 0x06;	//0x06 -> HA size
	arp->ar_pln = 0x04;	//0x04 -> PA size
	arp->ar_sip.s_addr = htonl(sip->s_addr);
	arp->ar_tip.s_addr = htonl(tip->s_addr);
}

void usage() {
	printf("syntax: adv_send_arp <interface> <sender ip 1> <target ip 1> [<sender ip 2> <target ip 2> ...]\n");
	printf("sample: adv_send_arp wlan0 192.168.0.19 192.168.0.1 192.168.0.1 192.168.0.19\n");
}

int getinfo(const char* const name, struct in_addr* myip,
struct in_addr* gwip, uint8_t** const buf) {
	struct ifreq ifr;
	char src[16];
	struct in_addr tmp;
	FILE *fp = nullptr;
	char cmd[40];
	int s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

	if(s < 0) {
		perror("Socket Open Failed");
		return -1;
	}

	strncpy(ifr.ifr_name, name, sizeof(name));

	//if name is error value, perror() will be called
	if(ioctl(s, SIOCGIFHWADDR, &ifr) >= 0) {
		memcpy(*buf, ifr.ifr_hwaddr.sa_data, sizeof(*buf));
	} else {
		close(s);
		perror("ioctl SIOCGIFHWADDR error");
		return -1;
	}

	if(ioctl(s, SIOCGIFADDR, &ifr) >= 0) {
		myip->s_addr = htonl((&((struct sockaddr_in *)&ifr.ifr_addr)
				->sin_addr)->s_addr);
		sprintf(cmd, "route -n | grep %s | awk '$4==\"UG\"{print $2}'", name);
		//snprintf -> second argument is size, but syntax error
		if((fp = popen(cmd, "r")) == NULL) {
			perror("popen() failed");
			return -1;
		}
		fgets(src, sizeof(src)/sizeof(src[0]), fp);
		fclose(fp);
		for(int i = sizeof(src)/sizeof(src[0]) + 1; --i;)
			if(src[i] == 0x0A) { src[i] = 0x00; break; }
		inet_pton(AF_INET, src, &tmp.s_addr);
		tmp.s_addr = htonl(tmp.s_addr);
		if(tmp.s_addr != gwip->s_addr)
			gwip->s_addr = tmp.s_addr;
	} else {
		close(s);
		perror("ioctl SIOCGIFADDR error");
		return -1;
	}

	close(s);
	return 0;
}

void send_packet(pcap_t** const handle,
const u_char** const packet, const int* const size) {
	if(pcap_sendpacket(*handle, *packet, *size) != 0)
		fprintf(stderr, "Error sending the packet\n");
}

void dump(const u_char** const packet, const int* const size) {
	for(int i = 0; i < *size; i++)
		printf("%02x ", *(*packet + i));
	putchar('\n');
}

void get_tinfo(pcap_t** const handle, const u_char **sent_packet,
uint8_t **mac, int *chk) {
	struct pcap_pkthdr *header;
	int res = 1;
	uint8_t *tmp = (uint8_t *)calloc(ETH_ALEN, sizeof(uint8_t));
	const u_char *packet;
	unique_ptr<Arphdr> sent_arp[chk[1]];

	#pragma omp for
	for(int i = 0; i < chk[1]; i++)
		sent_arp[i] = make_unique<Arphdr>(&sent_packet[i]);

/************************************************/
_ret:
/************************************************/
	steady_clock::time_point start = steady_clock::now();
	while((res = pcap_next_ex(*handle, &header, &packet)) >= 0) {
		if(res == 0) continue;

		#pragma omp parallel schedule(dynamic)
		{
			auto ether(make_unique<Ethhdr>(&packet));
			if(ether->getEthertype() == ETHERTYPE_ARP) {
				auto arp(make_unique<Arphdr>(&packet));
				uint32_t tip = arp->getTip();
				uint32_t sip = arp->getSip();
				uint32_t sent_tip[chk[1]];
				uint32_t sent_sip[chk[1]];
				#pragma omp for
				for(int i = 0; i < chk[1]; i++) {
					sent_tip[i] = sent_arp[i]->getTip();
					sent_sip[i] = sent_arp[i]->getSip();
				}

				#pragma omp for
				for(int i = 0; i < chk[1]; i++) {
					if((sent_arp[i]->getOpcode() == 2 && arp->getOpcode() == 1) &&
						(memcmp(&tip, &sent_sip[i], sizeof(tip)) == 0 &&
						memcmp(&sip, &sent_tip[i], sizeof(sip)) == 0)) {
						puts("ReInfacted");
			//printf("sip : %08x, tip : %08x, sent_tip[i] : %08x, sent_sip[i] = %08x\n",
			//sip, tip, sent_tip[i], sent_sip[i]);
						//dump(&sent_packet[i], &chk[2]);
						send_packet(handle, &sent_packet[i], &chk[2]);
						goto _ret; //_ret is at upper region
					}
					else if((sent_arp[i]->getOpcode() == 1 && arp->getOpcode() == 2) &&
						memcmp(&sent_tip[i], &sip, sizeof(sent_tip[0])) == 0) {
						memcpy(mac[i], arp->getSha(), sizeof(mac[0]));
						puts("Success");
			//for(int i = 0; i < chk[1]; i++)
			//printf("\n\nSender MAC Addr : %02x:%02x:%02x:%02x:%02x:%02x\n\n",
			//**(mac + i), *(*(mac + i) + 1), *(*(mac + i) + 2),
			//*(*(mac + i) + 3), *(*(mac + i) + 4), *(*(mac + i) + 5)); //for debugging
						if(++chk[0]  == chk[1])	return;
					}
				}
			}
			duration<double> used_time = steady_clock::now() - start;
			printf("%lf\n", used_time.count());
			//if -> lost ARP Request resend
			//elif -> time-out ARP Reply resend
			if(sent_arp[0]->getOpcode() == 1 &&
				used_time.count() >= 10.0) {
				#pragma omp for
				for(int i = 0; i < chk[1]; i++)
					if(memcmp(mac[i], tmp, sizeof(mac[i])) == 0) {
						send_packet(handle, &sent_packet[i], &chk[2]);
						goto _ret; //_ret is at get_tinfo()
					}
			} else if(sent_arp[0]->getOpcode() == 2 &&
				used_time.count() >= 25.0) {
				#pragma omp for
				for(int i = 0; i < chk[1]; i++) {
					send_packet(handle, &sent_packet[i], &chk[2]);
					goto _ret; //_ret is at get_tinfo()
				}
			}
		}
	}
}

int setPcap(pcap_t **handle, const char* const dev) {
	char errbuf[PCAP_ERRBUF_SIZE];

	if((*handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf)) == NULL) {
		fprintf(stderr, "couldn't open device %s: %s\n", dev, errbuf);
		return -1;
	}

	return 0;
}

int main(int argc, char* argv[]) {
	int size = sizeof(struct ether_header) + sizeof(struct arphdr);
	int max = (argc - 4) / 2 + 1;
	int check[3] = {0, max, size};

	uint8_t *mymac = (uint8_t *)calloc(ETH_ALEN, sizeof(uint8_t));
	uint8_t *gwmac = (uint8_t *)calloc(ETH_ALEN, sizeof(uint8_t));
	uint8_t *smac[max], *tmac[max];
	struct in_addr myip, gwip, sip[max], tip[max];
	pcap_t* handle = nullptr;
	const u_char *packet[max];
	unique_ptr<Ethhdr> ether[max];
	unique_ptr<Arphdr> arp[max];

	for(int i = 0; i < max; i++) {
		smac[i] = (uint8_t *)calloc(ETH_ALEN, sizeof(uint8_t));
		tmac[i] = (uint8_t *)calloc(ETH_ALEN, sizeof(uint8_t));
		packet[i] = (const u_char *)calloc(size, sizeof(const u_char));
		ether[i] = make_unique<Ethhdr>(&packet[i]);
		arp[i] = make_unique<Arphdr>(&packet[i]);
	}

	if(argc < 3 || argc % 2) {
		usage();
		goto _end;
	} else {
		if(setPcap(&handle, argv[1]) == -1)
			goto _end;
		#define	NUM (i - 2) / 2
		for(int i = argc - 1; i > 1; i--)
			if(i % 2) {
				inet_pton(AF_INET, argv[i], &tip[NUM]);
				tip[NUM].s_addr = htonl(tip[NUM].s_addr);
				//printf("argv[%d] = Target %d IP : %08x\n", i, NUM, tip[NUM].s_addr);
			} else {
				inet_pton(AF_INET, argv[i], &sip[NUM]);
				sip[NUM].s_addr = htonl(sip[NUM].s_addr);
				//printf("argv[%d] = Sender %d IP : %08x\n", i, NUM, sip[NUM].s_addr);
			}
		#undef	NUM
	}

	if(getinfo(argv[1], &myip, &gwip, &mymac) == -1) {
		pcap_close(handle);
		goto _end;
	}

	//printf("My IP : %08x\n", myip.s_addr);
	//printf("Gw IP : %08x\n", gwip.s_addr);
	//printf("My MAC Addr : %02x:%02x:%02x:%02x:%02x:%02x\n",
	//	*mymac, *(mymac + 1), *(mymac + 2), *(mymac + 3),
	//	*(mymac + 4), *(mymac + 5)); //for debugging

/***************************************************************
	This routine will be made function required 7 parameters

	unique_ptr<Ethhdr> ether, unique_ptr<Arphdr> arp,
	const int *max, struct in_addr *sip, uint8_t **smac,
	struct in_addr *tip, uint8_t **tmac = nullptr

	example)
	unique_ptr<Ethhdr> ether[max];	-> remove
	unique_ptr<Arphdr> arp[max];	-> remove
	ether[i] = make_unique<Ethhdr>(&packet[i]); -> remove
	arp[i] = make_unique<Arphdr>(&packet[i]);   -> remove
	for(int i = 0; i < max; i++)	//Target Req
		//Sender Req -> tip to sip
		//Reply -> tip to sip, myip to tip,
		//	tmac insert, tmac to smac
		func(make_unique<Ethhdr>(&packet[i]),
			make_unique<Arphdr>(&packet[i]),
			max, &myip, mymac, &tip)
***************************************************************/

	for(int i = 0; i < max; i++) {	//Target Req
		ether[i]->ether_build(mymac);
		arp[i]->arp_build(&myip, mymac, &tip[i]);
		//ether[i]->print();
		//arp[i]->print();
		//putchar('\n');
	}

	{
		thread t([&max, &handle, &packet, &size] {
			for(int i = 0; i < max; i++)
				send_packet(&handle, &packet[i], &size);
		});

		get_tinfo(&handle, (const u_char **)packet, (uint8_t **)tmac, check);
		check[0] = 0;
		//if(t.joinable())	t.join();
	}

	for(int i = 0; i < max; i++) {	//Sender Req
		ether[i]->ether_build(mymac);
		arp[i]->arp_build(&myip, mymac, &sip[i]);
		//ether[i]->print();
		//arp[i]->print();
		//putchar('\n');
	}

	{
		thread t([&max, &handle, &packet, &size] {
			for(int i = 0; i < max; i++)
				send_packet(&handle, &packet[i], &size);
		});

		get_tinfo(&handle, (const u_char **)packet, (uint8_t **)smac, check);
		check[0] = 0;
		//if(t.joinable())	t.join();
	}

	for(int i = 0; i < max; i++) {	//Reply
		ether[i]->ether_build(mymac, smac[i]);
		arp[i]->arp_build(&tip[i], mymac, &sip[i], smac[i]);
		//ether[i]->print();
		//arp[i]->print();
		//putchar('\n');
	}

	{
		thread t([&max, &handle, &packet, &size] {
			for(int i = 0; i < max; i++) {
				send_packet(&handle, &packet[i], &size);
				//printf("Send packet[%d]\n", i);
			}
		});
		//while(1){
			//puts("get_tinfo() called");
			get_tinfo(&handle, (const u_char **)packet,
				(uint8_t **)tmac, check);
		//}
		//if(t.joinable())	t.join();
	}

	pcap_close(handle);

/************************************************/
_end:
/************************************************/
	for(int i = 0; i < max; i++) {
		free(tmac[i]);			free(smac[i]);
		free((void *)packet[i]);	packet[i] = nullptr;
		tmac[i] = nullptr;		smac[i] = nullptr;
	}
		free(mymac);			mymac = nullptr;
		free(gwmac);			gwmac = nullptr;

	return 0;
}


text:
//==============================================================================
//         Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012          Domagoj Saric, Little Endian Ltd.
//
//          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 NT2_SDK_BENCH_PERFORM_BENCHMARK_HPP_INCLUDED
#define NT2_SDK_BENCH_PERFORM_BENCHMARK_HPP_INCLUDED

#include <nt2/sdk/bench/config.hpp>
#include <nt2/sdk/bench/details/base_experiment.hpp>
#include <nt2/sdk/error/exception.hpp>
#include <nt2/sdk/timing/now.hpp>
#include <boost/dispatch/attributes.hpp>

namespace nt2
{
  typedef std::pair<nt2::cycles_t, nt2::time_quantum_t> intermediate_result_t;

  namespace details
  {
    BOOST_DISPATCH_NOINLINE intermediate_result_t
    perform_benchmark_impl( base_experiment const& test, nt2::seconds_t const d );

    NT2_TEST_BENCHMARK_DECL extern benchmark_result_t reference_timing_value;
  }

  NT2_TEST_BENCHMARK_DECL BOOST_DISPATCH_NOINLINE
  benchmark_result_t perform_benchmark( details::base_experiment const& test
                                      , nt2::seconds_t const duration
                                      );

  NT2_TEST_BENCHMARK_DECL BOOST_DISPATCH_NOINLINE
  benchmark_result_t& reference_timing();
}

#endif

ext: hpp


text:
//          Copyright Gavin Band 2008 - 2012.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef SNPTEST_REGRESSION_LOG_LIKELIHOOD_HPP
#define SNPTEST_REGRESSION_LOG_LIKELIHOOD_HPP

#include <vector>
#include <memory>
#include <boost/noncopyable.hpp>
#include "Eigen/Core"
#include "metro/SmoothFunction.hpp"
#include "metro/regression/Design.hpp"

namespace metro {
	namespace regression {
		/*
		* Base class for classes implementing regression log-likelihoods
		*/
		struct LogLikelihood: public SmoothFunction
		{
		public:
			typedef std::auto_ptr< LogLikelihood > UniquePtr ;
			typedef regression::Design::Point Point ;
			typedef regression::Design::Vector Vector ;
			typedef regression::Design::RowVector RowVector ;
			typedef regression::Design::Matrix Matrix ;
			typedef Eigen::Matrix< int, Eigen::Dynamic, Eigen::Dynamic > IntegerMatrix ;
		public:
			virtual ~LogLikelihood() ;
			virtual regression::Design& design() const = 0 ;
			virtual std::string get_parameter_name( std::size_t i ) const = 0 ;
			std::vector< std::string > get_parameter_names() const ;

			virtual int number_of_parameters() const = 0 ;
			virtual int number_of_outcomes() const = 0 ;
			// Return a lx2 matrix identifying the l parameters.
			// For each parameter the row contains:
			// column 0: the index of the outcome column.
			// column 1: the index of the design matrix column.
			virtual IntegerMatrix identify_parameters() const = 0 ;

			virtual void evaluate_at( Point const& parameters, int const numberOfDerivatives = 2 ) = 0 ;
			virtual Point const& parameters() const = 0 ;
			virtual double get_value_of_function() const = 0 ;
			virtual Vector get_value_of_first_derivative() const = 0 ;
			virtual Matrix get_value_of_second_derivative() const = 0 ;

			virtual std::string get_summary() const = 0 ;
		} ;
	}
}

#endif

max_stars_repo_name: gavinband/qctool

max_issues_repo_name: gavinband/qctool

max_forks_repo_name: gavinband/qctool


text:
/**
 * @file multicast_receiver_example.cpp
 *
 * @author Lucas Haug <lucas.haug@thuneratz.org>
 * @author Lucas Schneider <lucas.schneider@thuneratz.org>
 *
 * @brief Example on how to use the MulticastReceiver
 *
 * @date 04/2021
 *
 * @note This example depends on ROS
 *
 * @copyright MIT License - Copyright (c) 2021 ThundeRatz
 */

#include <ros/ros.h>

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include "boost/bind.hpp"

#include "travesim_adapters/udp/multicast_receiver.hpp"

/*****************************************
 * Private Constants
 *****************************************/

#define BUFFER_SIZE 1024U

/*****************************************
 * Main Function
 *****************************************/

int main(int argc, char* argv[]) {
    const std::string listen_address_str = "0.0.0.0";
    const std::string multicast_address_str = "239.255.0.1";
    const short multicast_port = 30001;

    char data_buff[BUFFER_SIZE];

    ros::init(argc, argv, "reset_example_node", ros::init_options::AnonymousName);
    ros::NodeHandle nh;

    bool reset = false;

    ros::param::set("reset", reset);

    try {
        travesim::udp::MulticastReceiver my_receiver(multicast_address_str, multicast_port);

        my_receiver.force_specific_source(true);

        size_t data_size = 0;

        int counter = 0;

        ros::Rate loop_rate(60);

        while (ros::ok()) {
            data_size = my_receiver.receive(data_buff, BUFFER_SIZE);

            if (data_size > 0) {
                std::string received_msg(data_buff, data_size);
                ROS_INFO_STREAM(received_msg << std::endl);
            }

            if (counter % 100 == 0) {
                ROS_INFO_STREAM("Loop count: " << counter << std::endl);
            }

            ros::param::get("reset", reset);

            if (reset) {
                ROS_INFO_STREAM("Receiver reseted!" << std::endl);
                reset = false;
                ros::param::set("reset", reset);
                my_receiver.reset();
            }

            counter++;

            ros::spinOnce();
            loop_rate.sleep();
        }
    } catch (std::exception& e) {
        std::cerr << "Exception: " << e.what() << "\n";
    }

    return 0;
}