text:
/*
* Created by Mark Johnson on 3/3/2018.
*/

#ifndef VEHO_REDUCTION_HPP
#define VEHO_REDUCTION_HPP

#include <boost/mp11/list.hpp>
#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/utility.hpp>
#include <boost/mp11/integral.hpp>

#include <veho/facet/receiver/optimization/pass_traits.hpp>

#include "condense_closest_exact_filters_to_range_pass.hpp"
#include "condense_closest_range_filters_to_super_range_pass.hpp"
#include "extend_range_filter_to_encapsulate_closest_exact_filter_pass.hpp"

namespace veho {
    namespace facet {
        namespace receiver {
            namespace optimization {
                namespace reduction {
                    namespace detail {
                        template <typename Controller, typename TypeMap, typename Callbacks, typename QuotedPassList>
                        struct apply_best_reduction_pass {
                            template <typename QuotedPass>
                            using instantiate_quoted_pass = boost::mp11::mp_invoke<QuotedPass, Controller, TypeMap, Callbacks>;

                            template <typename QuotedPass>
                            using is_legal_to_instantiate_pass = boost::mp11::mp_valid<
                                    instantiate_quoted_pass,
                                    QuotedPass
                            >;

                            using all_viable_passes = boost::mp11::mp_copy_if<QuotedPassList, is_legal_to_instantiate_pass>;

                            static_assert(boost::mp11::mp_size<all_viable_passes>::value > 0,
                                          "Optimizer error: No further reduction passes can be instantiated to meet constraints");

                            using preemptively_ran_pass_list = boost::mp11::mp_transform<instantiate_quoted_pass, all_viable_passes>;

                            template <typename FirstPass, typename SecondPass>
                            using reduction_pass_waste_less = boost::mp11::mp_bool<
                                    (pass_traits<FirstPass>::num_frames_wasted < pass_traits<SecondPass>::num_frames_wasted)
                            >;

                            using best_reduction = boost::mp11::mp_min_element<preemptively_ran_pass_list, reduction_pass_waste_less>;

                            constexpr explicit apply_best_reduction_pass(Callbacks&& callbacks)
                                    : new_callbacks(best_reduction(std::forward<Callbacks>(callbacks)).new_callbacks) {}

                            using new_type_map_type = typename best_reduction::updated_type_map_type;

                            using new_callbacks_type = typename best_reduction::updated_callbacks_type;

                            new_callbacks_type new_callbacks;
                        };

                        template <
                                typename Controller, typename TypeMap, typename Callbacks, typename QuotedPassList,
                                std::size_t UsableMailboxCount, std::size_t NumCallbacks = boost::mp11::mp_size<Callbacks>::value
                        >
                        class callback_reducer_impl {
                        private:
                            static_assert(NumCallbacks > UsableMailboxCount,
                                          "Number of callbacks is already less than number of usable mailboxes");

                            using applied_best_pass = apply_best_reduction_pass<
                                    Controller, TypeMap, Callbacks, QuotedPassList
                            >;

                            using next_stage = callback_reducer_impl<
                                    Controller,
                                    typename applied_best_pass::new_type_map_type,
                                    typename applied_best_pass::new_callbacks_type,
                                    QuotedPassList,
                                    UsableMailboxCount
                            >;

                        public:
                            constexpr explicit callback_reducer_impl(Callbacks&& callbacks)
                                    : new_callbacks(next_stage(
                                            applied_best_pass(
                                                    std::forward<Callbacks>(callbacks)
                                            ).new_callbacks
                                    ).new_callbacks) {}

                            using new_type_map_type = typename next_stage::new_type_map_type;

                            using new_callbacks_type = typename next_stage::new_callbacks_type;

                            new_callbacks_type new_callbacks;

                        };

                        template <typename Controller, typename TypeMap, typename Callbacks, typename PassList, std::size_t UsableMailboxCount>
                        class callback_reducer_impl<Controller, TypeMap, Callbacks, PassList, UsableMailboxCount, UsableMailboxCount> {
                        public:
                            constexpr explicit callback_reducer_impl(Callbacks&& callbacks) : new_callbacks(
                                    std::forward<Callbacks>(callbacks)) {}

                            using new_type_map_type = TypeMap;

                            using new_callbacks_type = Callbacks;

                            new_callbacks_type new_callbacks;

                        };
                    }

                    template <typename Controller, typename TypeMap, typename Callbacks, std::size_t UsableMailboxCount>
                    class callback_reducer {
                    private:
                        using reduction_pass_list = boost::mp11::mp_list<
                                boost::mp11::mp_quote<condense_closest_exact_filters_to_range_pass>,
                                boost::mp11::mp_quote<condense_closest_range_filters_to_super_range_pass>,
                                boost::mp11::mp_quote<extend_range_filter_to_encapsulate_closest_exact_filter_pass>
                        >;

                        using impl = detail::callback_reducer_impl<Controller, TypeMap, Callbacks, reduction_pass_list, UsableMailboxCount>;

                    public:
                        constexpr explicit callback_reducer(Callbacks&& callbacks)
                                : new_callbacks(impl(std::forward<Callbacks>(callbacks)).new_callbacks) {}

                        using new_type_map_type = typename impl::new_type_map_type;

                        using new_callbacks_type = typename impl::new_callbacks_type;

                        new_callbacks_type new_callbacks;
                    };
                }
            }
        }
    }
}

#endif //VEHO_REDUCTION_HPP

ext: hpp

max_issues_repo_name: notfoundry/veho

max_forks_repo_name: notfoundry/veho


text:
/**
 * Copyright 2004-present Facebook. All Rights Reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "source/util/ImageUtil.h"

#include <boost/algorithm/string/split.hpp>

namespace fb360_dep {
namespace image_util {

static inline const std::vector<filesystem::path> checkAndGetSortedFiles(
    const filesystem::path& imageDir,
    const Camera::Rig& rig) {
  CHECK_GT(rig.size(), 0);
  filesystem::path camDir = imageDir / rig[0].id;
  CHECK(filesystem::exists(camDir)) << boost::format("No folder found at %1%") % camDir.string();
  const bool includeHidden = false;
  const std::vector<filesystem::path> sortedFiles =
      filesystem::getFilesSorted(camDir, includeHidden);
  CHECK_GT(sortedFiles.size(), 0) << boost::format("No files found in %1%") % camDir.string();
  return sortedFiles;
}

// Get first lexical frame if flag isn't filled in and validate the frame
int getSingleFrame(const filesystem::path& imageDir, const Camera::Rig& rig, std::string frame) {
  if (frame == "") {
    const std::vector<filesystem::path>& sortedFiles = checkAndGetSortedFiles(imageDir, rig);
    frame = sortedFiles.front().stem().string();
  }
  verifyImagePaths(imageDir, rig, frame, frame);
  return std::stoi(frame);
}

// Gets first and last lexical frame if flags aren't filled in and
// validates the frame range
std::pair<int, int> getFrameRange(
    const filesystem::path& imageDir,
    const Camera::Rig& rig,
    std::string firstFrame,
    std::string lastFrame) {
  if (firstFrame == "" || lastFrame == "") {
    const std::vector<filesystem::path>& sortedFiles = checkAndGetSortedFiles(imageDir, rig);
    if (firstFrame == "") {
      firstFrame = sortedFiles.front().stem().string();
    }
    if (lastFrame == "") {
      lastFrame = sortedFiles.back().stem().string();
    }
  }

  verifyImagePaths(imageDir, rig, firstFrame, lastFrame);

  return std::make_pair<int, int>(std::stoi(firstFrame), std::stoi(lastFrame));
}

// Generates paths to images, one vector per camera
void verifyImagePaths(
    const filesystem::path& imageDir,
    const Camera::Rig& rig,
    const std::string& firstFrame,
    const std::string& lastFrame,
    const std::string& extension) {
  int first;
  int last;
  try {
    first = std::stoi(firstFrame);
  } catch (...) {
    CHECK(false) << "Invalid frame name: " << firstFrame;
  }
  try {
    last = std::stoi(lastFrame);
  } catch (...) {
    CHECK(false) << "Invalid frame name: " << lastFrame;
  }

  CHECK_LE(first, last);
  CHECK_GT(rig.size(), 0);
  const std::string extGuess = filesystem::getFirstExtension(imageDir / rig[0].id);
  const std::string ext = !extension.empty() ? extension : extGuess;
  for (const Camera& cam : rig) {
    const filesystem::path camDir = imageDir / cam.id;
    for (int frameNum = first; frameNum <= last; ++frameNum) {
      const std::string frameName = intToStringZeroPad(frameNum, 6);
      const filesystem::path p = camDir / (frameName + ext);
      const bool exists = filesystem::is_regular_file(p);
      CHECK(exists) << "Missing file: " << p;
    }
  }
}

// Returns a value between min disparity and max disparity.
// Since we take non-rational steps, we cannot guarantee perfect precision on
// ends of the range, but we can on the first one (probe = 0), so we choose it
// to be at the furthest disparity (= closest depth)
double probeDisparity(
    const int probe,
    const int probeCount,
    const double minDisparity,
    const double maxDisparity) {
  const double fraction = double(probe) / double(probeCount - 1);
  return fraction * minDisparity + (1 - fraction) * maxDisparity;
}

// Assuming comma-separated list of destinations as input
Camera::Rig filterDestinations(const Camera::Rig rigIn, const std::string& destinations) {
  Camera::Rig rigOut;
  if (destinations.empty()) {
    return rigIn;
  }
  std::vector<std::string> destVec;
  boost::split(destVec, destinations, [](char c) { return c == ','; });
  for (const std::string& dest : destVec) {
    for (auto& cam : rigIn) {
      if (cam.id == dest) {
        rigOut.push_back(cam);
      }
    }
  }
  return rigOut;
}

Camera::Vector2 worldToEquirect(const Camera::Vector3 world, const int eqrW, const int eqrH) {
  const float depth = world.norm();
  const float x = world.x() / depth;
  const float y = world.y() / depth;
  const float z = world.z() / depth;
  const float phi = acos(z);
  float theta = atan2(y, x);
  if (theta > 0) {
    theta -= 2 * M_PI;
  }
  const float v = phi / M_PI;
  const float u = -theta / (2.0f * M_PI);
  return Camera::Vector2(u * eqrW, v * eqrH);
}

cv::Mat_<cv::Vec2f> computeWarpDstToSrc(const Camera& dst, const Camera& src) {
  const cv::Size srcSize(src.resolution.x(), src.resolution.y());
  const cv::Size dstSize(dst.resolution.x(), dst.resolution.y());
  cv::Mat_<cv::Vec2f> warpMap(dstSize, cv::Vec2f(NAN, NAN));

  if (dst.id == src.id) {
    return warpMap;
  }

  for (int y = 0; y < warpMap.rows; ++y) {
    for (int x = 0; x < warpMap.cols; ++x) {
      const Camera::Vector2 dstPixel(x + 0.5, y + 0.5);
      if (dst.isOutsideImageCircle(dstPixel)) {
        continue;
      }
      const Camera::Vector3 rig = dst.rigNearInfinity(dstPixel);
      Camera::Vector2 srcPixel;
      if (!src.sees(rig, srcPixel)) {
        continue;
      }
      // note: convert to opencv coordinate convention because it must be fed to cv::remap later
      warpMap(y, x) = cv::Vec2f(srcPixel.x() - 0.5f, srcPixel.y() - 0.5f);
    }
  }
  return warpMap;
}

} // namespace image_util
} // namespace fb360_dep

ext: cpp


text:
//////////////////////////////////////////////////////////////////////////////
//   Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand
//   Copyright 2009 and onward LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          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
//////////////////////////////////////////////////////////////////////////////
#define NT2_UNIT_MODULE "nt2 boost.simd.ieee toolbox - saturate_at/simd Mode"

//////////////////////////////////////////////////////////////////////////////
// unit test behavior of boost.simd.ieee components in simd mode
//////////////////////////////////////////////////////////////////////////////

#include <boost/simd/ieee/include/functions/saturate_at.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <boost/simd/sdk/simd/io.hpp>
#include <boost/type_traits/is_same.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/dispatch/functor/meta/call.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/simd/include/constants/one.hpp>
#include <boost/simd/include/constants/mone.hpp>
#include <boost/simd/include/constants/pi.hpp>
#include <boost/simd/include/constants/four.hpp>
#include <boost/simd/include/constants/mten.hpp>
#include <boost/simd/include/constants/ten.hpp>

NT2_TEST_CASE_TPL ( saturate_at_real__1_0,  BOOST_SIMD_SIMD_REAL_TYPES)
{
  using boost::simd::native;
  using boost::simd::saturate_at;
  using boost::simd::tag::saturate_at_;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                        n_t;
  typedef typename boost::dispatch::meta::call<saturate_at_<boost::simd::tag::Pi>(n_t)>::type r_t;
  typedef typename boost::simd::meta::scalar_of<r_t>::type sr_t;

  NT2_TEST_TYPE_IS( r_t, (native<T,ext_t>) );

  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Nan<n_t>())[0] , boost::simd::Nan<sr_t>(), 0);
  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Minf<n_t>())[0], -boost::simd::Pi<sr_t>(), 0);
  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Mten<n_t>())[0], -boost::simd::Pi<sr_t>(), 0);
  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Mone<n_t>())[0], boost::simd::Mone<sr_t>(), 0);
  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Zero<n_t>())[0], boost::simd::Zero<sr_t>(), 0);
  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::One<n_t>())[0] , boost::simd::One<sr_t>(), 0);
  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Ten<n_t>())[0] , boost::simd::Pi<sr_t>(), 0);
  NT2_TEST_ULP_EQUAL(saturate_at<boost::simd::tag::Pi>(boost::simd::Inf<n_t>())[0] , boost::simd::Pi<sr_t>(), 0);
}

NT2_TEST_CASE_TPL ( saturate_at_signed,  BOOST_SIMD_SIMD_INTEGRAL_SIGNED_TYPES)
{
  using boost::simd::native;
  using boost::simd::saturate_at;
  using boost::simd::tag::saturate_at_;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                        n_t;
  typedef typename boost::dispatch::meta::call<saturate_at_<boost::simd::tag::Pi>(n_t)>::type r_t;
  typedef typename boost::simd::meta::scalar_of<r_t>::type sr_t;

  NT2_TEST_TYPE_IS( r_t, (native<T,ext_t>) );

  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Mten<n_t>()), -boost::simd::Four<r_t>() );
  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Mone<n_t>()), boost::simd::Mone<r_t>() );
  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Zero<n_t>()), boost::simd::Zero<r_t>() );
  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::One<n_t>()), boost::simd::One<r_t>() );
  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Ten<n_t>()), boost::simd::Four<r_t>() );
}

NT2_TEST_CASE_TPL ( saturate_at_unsigned,  BOOST_SIMD_SIMD_INTEGRAL_UNSIGNED_TYPES)
{
  using boost::simd::native;
  using boost::simd::saturate_at;
  using boost::simd::tag::saturate_at_;
  typedef BOOST_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>                        n_t;
  typedef typename boost::dispatch::meta::call<saturate_at_<boost::simd::tag::Pi>(n_t)>::type r_t;
  typedef typename boost::simd::meta::scalar_of<r_t>::type sr_t;

  NT2_TEST_TYPE_IS( r_t, (native<T,ext_t>) );

  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Zero<n_t>()), boost::simd::Zero<r_t>() );
  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::One<n_t>()) , boost::simd::One<r_t>() );
  NT2_TEST_EQUAL(saturate_at<boost::simd::tag::Four>(boost::simd::Ten<n_t>()) , boost::simd::Four<r_t>() );
}


text:
#include <iostream>
#include <thread>
#include <fstream>
#include <string>
#include <filesystem>
#include <tuple>
#include <algorithm>
#include <chrono>
#include <regex>

#include <boost/multiprecision/cpp_int.hpp>

using namespace std;

namespace mp = boost::multiprecision;
namespace fs = std::filesystem;

const auto iter = 1 + 28;
const string resultsDirectory = "results";

void saveResult(const mp::cpp_int &power, int num) {
    vector<unsigned char> buffer;
    export_bits(power, back_inserter(buffer), 8);

    fstream file(resultsDirectory + "/" + to_string(num) + ".txt", fstream::out | fstream::trunc);
    for (unsigned char val: buffer) {
        file.put(val);
    }
    file.close();
}

void saveResult(const mp::cpp_int &power, const string &filename) {
    vector<unsigned char> buffer;
    export_bits(power, back_inserter(buffer), 8);

    fstream file(resultsDirectory + "/" + filename + ".txt", fstream::out | fstream::trunc);
    for (unsigned char val: buffer) {
        file.put(val);
    }
    file.close();
}

tuple <mp::cpp_int*, int> loadResults() {
    auto *powers = new mp::cpp_int[iter];
    mp::cpp_int partial;
    vector<int> loadedPowers;
    auto numberToLarge = false;

    for (const auto &entry : fs::directory_iterator(resultsDirectory)) {
        auto filename = fs::path(entry).stem(); // Get filename without path and extension
        int power = atoi(filename.c_str()); // Convert string into integer

        if (power == 0) {
            continue;
        }

        if (power < iter) {
            cout << "Loading " + entry.path().filename().string() << endl;

            vector<unsigned char> buffer;
            fstream file(entry.path(), fstream::in);

            while (!file.eof()) {
                char val;
                file.get(val);
                if (file.eof()) break;
                buffer.push_back(val);
            }
            file.close();

            import_bits(powers[power], buffer.begin(), buffer.end());

            if (powers[power] == 0) {
                continue;
            }
            loadedPowers.push_back(power); // Add read power to loadedPowers
        } else {
            numberToLarge = true;
        }
    }

    cout << "Finished Loading" << endl;
    if (numberToLarge) {
        cout << "Found file with power larger than set possible!" << endl << endl;
    }

    int largestPower = 0;
    sort(loadedPowers.begin(), loadedPowers.end());

    // Find largest power without "gaps" in files, so
    // 0, 1, 2, 3, 5, 6 will return 3
    // We will need all powers in stage two
    for (auto power: loadedPowers) {
        if (power == largestPower + 1){
            largestPower++;
        }
    }

    powers[0] = 9;
    largestPower = max(++largestPower, 1); // Set largestPower to bigger value: 1 or largestPower + 1

    return {powers, largestPower};
}

string prepareTime(chrono::steady_clock::time_point start, chrono::steady_clock::time_point end) {
    auto microseconds = chrono::duration_cast<chrono::microseconds>(end - start).count();
    auto milliseconds = chrono::duration_cast<chrono::milliseconds>(end - start).count();
    auto seconds = chrono::duration_cast<chrono::seconds>(end - start).count();
    auto hours = chrono::duration_cast<chrono::hours>(end - start).count();

    string time;

    if (hours > 0) {
        time += to_string(hours) + "h ";
    }
    if (seconds > 0) {
        time += to_string(seconds % 60) + "s ";
    }
    if (milliseconds > 0) {
        time += to_string(milliseconds % 1000) + "ms ";
    }
    if (microseconds > 0) {
        time += to_string(microseconds % 1000) + "μm";
    }

    if (time.empty()) {
        return "no time";
    } else {
        return time;
    }
}

int main() {
    auto [powers, currentPower] = loadResults();
    thread threads[iter];

    for (; currentPower < iter; ++currentPower) {
        auto startTime = chrono::steady_clock::now();

        powers[currentPower] = pow(powers[currentPower - 1], 2);

        auto endTime = chrono::steady_clock::now();
        cout << "Calculated 9^" << mp::pow(mp::cpp_int(2), currentPower) << ", in " << prepareTime(startTime, endTime) << ", step " << currentPower << endl; // For logging progress

        // thread() can't find rsquare prismight function by its own (there are two),
        // so I point it to right address manually
        auto functionAddress = static_cast<void(*)(const mp::cpp_int&, int)>(saveResult);
        threads[currentPower] = thread(functionAddress, powers[currentPower], currentPower);
    }

    // Stage two: multiply following elements from array:
    // int toMultiply[] =  {28, 26, 25, 24, 20, 18, 17, 16, 15, 12, 8, 6, 3, 0};
    int toMultiply[] = {3, 6, 8, 12, 15, 16, 17, 18, 20, 24, 25, 26, 28};
    // Based on:
    // https://www.wolframalpha.com/input/?i=9%5E9+%3D+2%5E28+%2B+2%5E26+%2B+2%5E25+%2B+2%5E24+%2B+2%5E20+%2B+2%5E18+%2B+2%5E17+%2B+2%5E16+%2B+2%5E15+%2B+2%5E12+%2B+2%5E8+%2B+2%5E6+%2B+2%5E3+%2B+2%5E0

    mp::cpp_int final = powers[0];
    int previous = 0;
    for (int i = 0; i < 13; i++) {
        cout << "Calculating: " << toMultiply[i] << endl;
        final *= powers[toMultiply[i]];

        cout << "Saving..." << endl;
        saveResult(final, "partial." + to_string(toMultiply[i]));
        remove(("partial." + to_string(previous)).c_str());
    }

    for (auto &th: threads) {
        if (th.joinable()) {
            th.join();
        }
    }

    fstream result("result.txt", fstream::out);
    result << final;
    result.close();
    return 0;
}

max_stars_repo_name: WaxyMocha/NineToNineToNine

max_issues_repo_name: WaxyMocha/NineToNineToNine

max_forks_repo_name: WaxyMocha/NineToNineToNine


text:
//
//  x_uuid.hpp
//  x
//
//  Created by Daher Alfawares on 12/14/17.
//  Copyright © 2017 Daher Alfawares. All rights reserved.
//

#ifndef x_uuid_hpp
#define x_uuid_hpp

#include <string>
#include <sstream>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>

namespace x {
    namespace uuid {
        inline std::string string(){
            std::stringstream str;
            boost::uuids::uuid u = boost::uuids::random_generator()();
            str << u;
            return str.str();
        }
    }
}

#endif /* x_uuid_hpp */

max_stars_repo_name: daher-alfawares/venv

max_issues_repo_name: daher-alfawares/venv

max_forks_repo_name: daher-alfawares/venv


text: #include <boost/range/rend.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
Strongly typed languages such as C++ require that each variable has a
specific data type determining the nature of information it can store. To
store arbitrary information in a variable, a language such as JavaScript
can be used which allows storing a character string, a number and a boolean
value using the same variable. Variables in JavaScript allow storing any
kind of information.

The library Boost.Any offers the boost::any class which, similar to
JavaScript, offers the ability to store arbitrary information in C++.
*/

//#include <boost/any.hpp>
//
//int main()
//{
//  boost::any a = 1;
//  a = 3.14;
//  a = true;
//}

/*
In order to use boost::any, the header file boost/any.hpp must be included.
Objects of type boost::any can then be created to store arbitrary
information.

Please note that variables of type boost::any cannot really store any kind
of information; Boost.Any requires certain preconditions, albeit minimal
ones. Any information, stored in a variable of type boost::any, must be
copy constructible. Hence, to store a character string in a variable of
type boost::any, std::string needs to be explicitly accessed as shown in
the following example.
*/

//#include <boost/any.hpp>
//#include <string>
//
//int main()
//{
//  boost::any a = 1;
//  a = 3.14;
//  a = true;
//  a = std::string("Hello, world!");
//}

/*
If the application would try to assign "Hello, world!" to a directly, the
compiler would abort with an error since character strings are arrays
comprised of elements of type char which are not copy constructible in C++.

To access the content of variables of type boost::any, the cast operator
boost::any_cast must be used.
*/

//#include <boost/any.hpp>
//#include <iostream>
//
//int main()
//{
//  boost::any a = 1;
//  std::cout << boost::any_cast<int>(a) << std::endl;
//  a = 3.14;
//  std::cout << boost::any_cast<double>(a) << std::endl;
//  a = true;
//  std::cout << boost::any_cast<bool>(a) << std::endl;
//}

/*
By passing the corresponding data type as the template argument to
boost::any_cast, the content of the variable is converted accordingly. In
case an invalid data type is specified, an exception of type
boost::bad_any_cast is thrown.
*/

//#include <boost/any.hpp>
//#include <iostream>
//
//int main()
//{
//  try
//  {
//    boost::any a = 1;
//    std::cout << boost::any_cast<float>(a) << std::endl;
//  }
//  catch (boost::bad_any_cast &e)
//  {
//    std::cerr << e.what() << std::endl;
//  }
//}

/*
The above example throws an exception since the template argument of type
float does not match the type int stored in a. It is important to always
specify the same data type as used for the variable of type boost::any. The
application would also throw an exception if either short or long would be
specified as the template argument.

Since boost::bad_any_cast is derived from std::bad_cast, catch handlers can
catch exceptions of this type accordingly.

To check whether or not a variable of type boost::any contains information,
the empty() method is used. To check the data type of the stored information
instead, type() can be used.
*/

#include <boost/any.hpp>
#include <typeinfo>
#include <iostream>

int main()
{
  boost::any a = 1;
  if (!a.empty())
  {
    const std::type_info &ti = a.type();
    std::cout << ti.name() << std::endl;

	int *i = boost::any_cast<int>(&a);
	std::cout << *i << std::endl;
  }
}

/*
The example uses both empty() and type(). While empty() returns a boolean
value, the return value of type() is of type std::type_info which is
defined in typeinfo.
*/

/*
To conclude this section, the final example shows how to obtain a pointer
to the value stored in a variable of type boost::any using boost::any_cast.
*/

//#include <boost/any.hpp>
//#include <iostream>
//
//int main()
//{
//  boost::any a = 1;
//  int *i = boost::any_cast<int>(&a);
//  std::cout << *i << std::endl;
//}

/*
All it takes is passing a pointer to the variable of type boost::any as the
argument to boost::any_cast; the template arguments remain unchanged.
*/


text:
//main.cpp
//Author: Sivert Andresen Cubedo

#if 1
//C++
#include <iostream>
#include <string>
#include <thread>

//Boost
#include <boost/asio.hpp>

//Local
#include "../include/SaivBot.hpp"

void workFunc(boost::asio::io_context & ioc)
{
	while (true) {
		try {
			ioc.run();
			break;
		}
		catch (std::exception & e) {
			std::cout << "[" << std::this_thread::get_id() << "] " << "Exception thrown: " << e.what() << "\n";
		}
	}
}

int main(int argc, char** argv)
{
	boost::asio::io_context ioc;
	std::filesystem::path config_path("Config.txt");
	boost::asio::ssl::context ctx{ boost::asio::ssl::context::sslv23 };
	load_root_certificates(ctx);
	SaivBot client(ioc, std::move(ctx), config_path);
	client.run();

	std::ios::sync_with_stdio(true);

	//unsigned int thread_count = 1;
	unsigned int thread_count = std::thread::hardware_concurrency();
	std::cout << "[" << std::this_thread::get_id() << "] " << "Thread count: " << thread_count << "\n";
	if (thread_count > 0) {
		std::vector<std::thread> threads(thread_count);
		for (auto & t : threads) {
			t = std::thread(workFunc, std::ref(ioc));
		}
		for (auto & t : threads) {
			if (t.joinable()) {
				t.join();
				std::cout << "[" << std::this_thread::get_id() << "] " << "Mainthread join\n";
			}
		}
	}
	else {
		std::cout << "std::this_thread::get_id() error\n";
	}

	std::cout << "[" << std::this_thread::get_id() << "] " << "Mainthread exit\n";

	return 0;
}

#endif

max_stars_repo_name: SaivNator/SaivBot

max_issues_repo_name: sivertac/SaivBot

max_forks_repo_name: sivertac/SaivBot


text:
// this is for emacs file handling -*- mode: c++; indent-tabs-mode: nil -*-

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

//----------------------------------------------------------------------
/*!\file
 *
 * \author  Sebastian Klemm <klemm@fzi.de>
 *
 */
//----------------------------------------------------------------------

#include <boost/tuple/tuple.hpp>
#include "Polygon.hpp"

namespace LLet {

Polygon::Polygon()
{
}

Polygon::Polygon(const lanelet_ptr_t& lanelet)
{
  initialize(*lanelet);
}

Polygon::Polygon(const Lanelet& lanelet)
{
  initialize(lanelet);
}

Polygon::Polygon(const EventRegion& event_region)
{
  addVertices<std::vector<point_with_id_t>::const_iterator >(event_region.getVertices().begin(), event_region.getVertices().end());
}

void Polygon::initialize(const Lanelet& lanelet)
{
  const strip_ptr_t& left = boost::get<LLet::LEFT>(lanelet.bounds());
  const strip_ptr_t& right = boost::get<LLet::RIGHT>(lanelet.bounds());

  addVertices<std::vector<point_with_id_t>::const_iterator >(left->pts().begin(), left->pts().end());
  addVertices<std::vector<point_with_id_t>::const_reverse_iterator >(right->pts().rbegin(), right->pts().rend());
}

bool Polygon::pointInsidePolygon(const point_with_id_t& query) const
{
  if (m_vertices.size() < 3)
  {
    std::logic_error("Cannot work on polygon with too few points.");
  }

  const point_xy_t point = vec(m_reference_point, query);
  const std::size_t nr_vertices = m_vertices.size();

  std::size_t i, j;
  bool inside = false;
  for (i = 0, j = nr_vertices-1; i < nr_vertices; j = i++)
  {
    if (((boost::get<Y>(m_vertices[i]) > boost::get<Y>(point)) != (boost::get<Y>(m_vertices[j]) > boost::get<Y>(point))) &&
        (boost::get<X>(point) < (boost::get<X>(m_vertices[j]) - boost::get<X>(m_vertices[i]))
         * (boost::get<Y>(point) - boost::get<Y>(m_vertices[i]))
         / (boost::get<Y>(m_vertices[j])- boost::get<Y>(m_vertices[i])) + boost::get<X>(m_vertices[i])))
    {
      inside = !inside;
    }
  }
  return inside;
}

void Polygon::clear()
{
  m_vertices.clear();
}

double Polygon::distanceTo(const point_with_id_t &point) const
{
  point_xy_t metric_point = vec(m_reference_point, point);
  vertex_container_t vertices = m_vertices;
  assert(!vertices.empty());
  vertices.push_back(*vertices.begin());
  return dist(metric_point, projected(metric_point, vertices));
}

void Polygon::boundingBox(point_xy_t& lower_left, point_xy_t& upper_right) const
{
  assert(!m_vertices.empty());
  double min_x = std::numeric_limits<double>::infinity();
  double min_y = std::numeric_limits<double>::infinity();
  double max_x = -std::numeric_limits<double>::infinity();
  double max_y = -std::numeric_limits<double>::infinity();

  for (vertex_container_t::const_iterator vertex = m_vertices.begin(); vertex < m_vertices.end(); ++vertex)
  {
    if (boost::get<X>(*vertex) < min_x)
    {
      min_x = boost::get<X>(*vertex);
    }

    if (boost::get<X>(*vertex) > max_x)
    {
      max_x = boost::get<X>(*vertex);
    }

    if (boost::get<Y>(*vertex) < min_y)
    {
      min_y = boost::get<Y>(*vertex);
    }

    if (boost::get<Y>(*vertex) > max_y)
    {
      max_y = boost::get<Y>(*vertex);
    }
  }

  boost::get<X>(lower_left) = min_x;
  boost::get<Y>(lower_left) = min_y;

  boost::get<X>(upper_right) = max_x;
  boost::get<Y>(upper_right) = max_y;
}

void Polygon::addVertex(const point_xy_t& point)
{
  m_vertices.push_back(point);
}

Polygon::Polygon(const std::vector<point_with_id_t>& vertices)
{
  addVertices<std::vector<point_with_id_t>::const_iterator >(vertices.begin(), vertices.end());
}

}


text:
#include <boost/heap/binomial_heap.hpp>
#include <iostream>

using namespace boost::heap;

int main() {
  binomial_heap<int> bh;
  bh.push(2);
  bh.push(3);
  bh.push(1);

  binomial_heap<int> bh2;
  bh2.push(4);
  bh.merge(bh2);

  for (auto it = bh.ordered_begin(); it != bh.ordered_end(); ++it)
    std::cout << *it << " ";
  std::cout << std::endl;
  std::cout << std::boolalpha << bh2.empty() << std::endl;
}


text:
// This file is part of slideio project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://slideio.com/license.html.
#include "slideio/core/imagedriver.hpp"
#include "slideio/drivers/gdal/gdalimagedriver.hpp"
#include "slideio/drivers/gdal/gdalscene.hpp"
#include "slideio/drivers/gdal/gdalslide.hpp"
#include <boost/algorithm/string.hpp>
#include <set>
#include "slideio/gdal_lib.hpp"

slideio::GDALImageDriver::GDALImageDriver()
{
	GDALAllRegister();
}

slideio::GDALImageDriver::~GDALImageDriver()
{
}

std::string slideio::GDALImageDriver::getID() const
{
	return std::string("GDAL");
}

std::shared_ptr<slideio::CVSlide> slideio::GDALImageDriver::openFile(const std::string& filePath)
{
	GDALDatasetH ds = GDALScene::openFile(filePath);
	slideio::CVSlide* slide = new GDALSlide(ds, filePath);
	std::shared_ptr<slideio::CVSlide> ptr(slide);
	return ptr;
}

std::string slideio::GDALImageDriver::getFileSpecs() const
{
	static std::string pattern("*.png;*.jpeg;*.jpg;*.tif;*.tiff;*.bmp;*.gif;*.gtiff;*.gtif;*.ntif;*.jp2");
    return pattern;
}

max_stars_repo_name: Booritas/slideio

max_issues_repo_name: Booritas/slideio

max_forks_repo_name: Booritas/slideio


text:
/**
 * RPEditor
 *
 * Copyright (c) 2017, Younguk Kim (bluekyu).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "main_window.hpp"
#include "ui_main_window.h"

#include <string>
#include <stdexcept>

#include <QtWidgets/QMessageBox>
#include <QtWidgets/QApplication>
#include <QtWidgets/QProgressBar>
#include <QtCore/QStandardPaths>
#include <QtGui/QCloseEvent>
#include <QtWidgets/QColorDialog>

#include <boost/property_tree/json_parser.hpp>
#include <boost/filesystem.hpp>

#if defined(BOOST_OS_WINDOWS)
#include <Windows.h>
#endif

#include "restapi/restapi_client.hpp"
#include "restapi/restapi_event.hpp"
#include "restapi/resolve_message.hpp"

#include "logger_manager.hpp"

namespace rpeditor {

static const char* SETTING_FILE_NAME = "config.json";

bool MainWindow::is_shown_system_console_ = false;
bool MainWindow::is_created_system_console_ = false;

bool MainWindow::toggle_system_console(void)
{
#if defined(BOOST_OS_WINDOWS)
    if (GetConsoleWindow())
    {
        return is_shown_system_console_ = !ShowWindow(GetConsoleWindow(), is_shown_system_console_ ? SW_HIDE : SW_RESTORE);
    }
    else
    {
        if (!AllocConsole())
        {
            global_logger_->error("Cannot allocate console.");
            return is_shown_system_console_ = false;
        }

        if (AttachConsole(GetCurrentProcessId()))
        {
            global_logger_->error("Cannot attach console.");
            FreeConsole();
            return is_shown_system_console_ = false;
        }

        is_created_system_console_ = true;

        FILE* dummy;
        freopen_s(&dummy, "CON", "w", stdout);
        freopen_s(&dummy, "CON", "w", stderr);

        global_logger_->info("System console is created.");

        return is_shown_system_console_ = true;
    }
#else
    return false;
#endif
}

MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui_(new Ui::MainWindow)
{
    global_logger_->debug("Initializing MainWindow ...");

    ui_->setupUi(this);

    setup_ui();
}

void MainWindow::update_ui(void)
{
//    resize(settings->properties.window.width, settings->properties.window.height);
//
//    ui_->action_save_project->setEnabled(bool(project));
//    ui_->action_save_project_as->setEnabled(bool(project));
//    if (project)
//    {
//        setWindowTitle(QString("rpeditor - ").append(QString::fromStdString(project->get_name())));
//    }
//    else
    {
        setWindowTitle(QApplication::instance()->applicationName());
    }
}

void MainWindow::closeEvent(QCloseEvent* ev)
{
    if (restapi_client_)
    {
        global_logger_->debug("Waiting for closing RESTAPI client ...");
        restapi_client_->close();
    }

    if (restapi_network_thread_ && restapi_network_thread_->joinable())
    {
        global_logger_->info("Wainting for exiting WebSocket network thread ...");
        restapi_network_thread_->join();
        restapi_network_thread_.reset();

        // skip when closing
        //set_enable_restapi_actions(false);
    }

    //save_settings();

#if defined(BOOST_OS_WINDOWS)
    ShowWindow(GetConsoleWindow(), SW_HIDE);

    // avoid crashing in Qt.
    if (is_created_system_console_)
        FreeConsole();
#endif

    ev->accept();
}

bool MainWindow::event(QEvent* ev)
{
    switch (ev->type())
    {
    case RestAPIEvent::EVENT_TYPE:
        resolve_message(static_cast<RestAPIEvent*>(ev)->get_message());
        break;

    default:
        return QMainWindow::event(ev);
    }

    return true;
}

bool MainWindow::load_settings(void)
{
    boost::property_tree::ptree settings;

    const QString& settings_file_path = QStandardPaths::locate(QStandardPaths::StandardLocation::AppConfigLocation, SETTING_FILE_NAME, QStandardPaths::LocateFile);

    if (settings_file_path.isEmpty())
    {
        global_logger_->debug("No '{}' file.", SETTING_FILE_NAME);

        const QString& config_dir_path =  QStandardPaths::writableLocation(QStandardPaths::StandardLocation::AppConfigLocation);
        if (config_dir_path.isEmpty())
        {
            global_logger_->error("Cannot find location to write configuration files.");
        }
        else
        {
            boost::filesystem::path config_path(config_dir_path.toStdString());
            config_dir_path_ = config_path.generic_string();
        }
    }
    else
    {
        config_dir_path_ = boost::filesystem::path(settings_file_path.toStdString()).parent_path().generic_string();

        try
        {
            const std::string& settings_file_path = get_settings_file_path();

            boost::property_tree::read_json(settings_file_path, settings);

            global_logger_->info("Settings loaded: {}", settings_file_path);
        }
        catch (const std::exception& e)
        {
            global_logger_->error("Cannot read setting file: {}", get_settings_file_path());
            global_logger_->error("Error message: {}", e.what());
            return false;
        }
    }

    // TODO: update UI

    return true;
}

bool MainWindow::save_settings(void)
{
    // TODO: save UI
    boost::property_tree::ptree settings;

    boost::filesystem::path settings_file_path(get_settings_file_path());
    if (settings_file_path.empty())
    {
        global_logger_->error("Cannot find location to write setting file.");
        return false;
    }

    try
    {
        boost::property_tree::write_json(settings_file_path.generic_string(), settings, std::locale());
    }
    catch (const std::exception& e)
    {
        global_logger_->error("Cannot write setting file: {}", settings_file_path.generic_string());
        global_logger_->error("Error message: {}", e.what());
        return false;
    }

    global_logger_->info("Settings saved: {}", settings_file_path.generic_string());

    return true;
}

std::string MainWindow::get_settings_file_path(void) const
{
    if (config_dir_path_.empty())
        return "";

    return (boost::filesystem::path(config_dir_path_) / "config.json").generic_string();
}

void MainWindow::setup_ui(void)
{
//    progress_bar = new QProgressBar(this);
//    progress_bar->setRange(0, 100);
//    ui_->status_bar_->addPermanentWidget(progress_bar);

//    setup_project_tree(core::project_dir_path.string(), nullptr);

    setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea);    // dock widget corner

    connect(ui_->main_tab_widget_, &QTabWidget::currentChanged, [this](void) {
        if (QTreeWidgetItem* item = ui_->scenegraph_tree_->currentItem())
            on_scenegraph_item_changed(item);
    });

    // NodePath tab
    ui_->translation_edit_x_->setValidator(new QDoubleValidator(ui_->translation_edit_x_));
    ui_->translation_edit_y_->setValidator(new QDoubleValidator(ui_->translation_edit_y_));
    ui_->translation_edit_z_->setValidator(new QDoubleValidator(ui_->translation_edit_z_));

    ui_->hpr_edit_h_->setValidator(new QDoubleValidator(ui_->hpr_edit_h_));
    ui_->hpr_edit_p_->setValidator(new QDoubleValidator(ui_->hpr_edit_p_));
    ui_->hpr_edit_r_->setValidator(new QDoubleValidator(ui_->hpr_edit_r_));

    ui_->scale_edit_x_->setValidator(new QDoubleValidator(ui_->scale_edit_x_));
    ui_->scale_edit_y_->setValidator(new QDoubleValidator(ui_->scale_edit_y_));
    ui_->scale_edit_z_->setValidator(new QDoubleValidator(ui_->scale_edit_z_));

    connect(ui_->translation_edit_x_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);
    connect(ui_->translation_edit_y_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);
    connect(ui_->translation_edit_z_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);

    connect(ui_->hpr_edit_h_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);
    connect(ui_->hpr_edit_p_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);
    connect(ui_->hpr_edit_r_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);

    connect(ui_->scale_edit_x_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);
    connect(ui_->scale_edit_y_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);
    connect(ui_->scale_edit_z_, &QLineEdit::editingFinished, this, &MainWindow::on_nodepath_changed);

    connect(ui_->visible_checkbox_, &QCheckBox::toggled, this, &MainWindow::on_nodepath_changed);
    connect(ui_->tight_bounds_checkbox_, &QCheckBox::toggled, this, &MainWindow::on_nodepath_changed);
    connect(ui_->wireframe_checkbox_, &QCheckBox::toggled, this, &MainWindow::on_nodepath_changed);

    // Geometry tab
    connect(ui_->geometry_geom_index_spinbox_, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
        if (QTreeWidgetItem* item = ui_->scenegraph_tree_->currentItem())
            on_geometry_tab_selected(item);
    });

    // Material tab
    connect(ui_->material_geom_index_spinbox_, QOverload<int>::of(&QSpinBox::valueChanged), [this](int value) {
        if (QTreeWidgetItem* item = ui_->scenegraph_tree_->currentItem())
            on_material_tab_selected(item);
    });

    connect(ui_->material_shading_model_combobox_, QOverload<int>::of(&QComboBox::activated), this, &MainWindow::on_material_changed);

    connect(ui_->material_matallic_checkbox_, &QCheckBox::stateChanged, this, &MainWindow::on_material_changed);

    connect(ui_->material_base_color_dialog_button_, &QPushButton::pressed, [this]() {
        auto palette = ui_->material_base_color_dialog_button_->palette();

        const auto& color = QColorDialog::getColor(palette.color(QPalette::Button), this, "Base Color Dialog");
        if (!color.isValid())
            return;

        palette.setColor(QPalette::Button, color);
        ui_->material_base_color_dialog_button_->setPalette(palette);
        on_material_changed();
    });

    connect(ui_->material_roughness_slider_, &QSlider::valueChanged, [this](int value) {
        ui_->material_roughness_spinbox_->setValue(value / 100.0);
        on_material_changed();
    });
    connect(ui_->material_roughness_spinbox_, QOverload<double>::of(&QDoubleSpinBox::valueChanged), [this](double value) {
        ui_->material_roughness_slider_->setValue(value * 100.0);
    });

    connect(ui_->material_speuclar_ior_slider_, &QSlider::valueChanged, [this](int value) {
        ui_->material_speuclar_ior_spinbox_->setValue(value / 100.0);
        on_material_changed();
    });
    connect(ui_->material_speuclar_ior_spinbox_, QOverload<double>::of(&QDoubleSpinBox::valueChanged), [this](double value) {
        ui_->material_speuclar_ior_slider_->setValue(value * 100.0);
    });

    connect(ui_->material_normal_strength_slider_, &QSlider::valueChanged, [this](int value) {
        ui_->material_normal_strength_spinbox_->setValue(value / 100.0);
        on_material_changed();
    });
    connect(ui_->material_normal_strength_spinbox_, QOverload<double>::of(&QDoubleSpinBox::valueChanged), [this](double value) {
        ui_->material_normal_strength_slider_->setValue(value * 100.0);
    });

//    ui_->action_new_project->setShortcuts(QKeySequence::New);
//
//    ui_->action_save_project->setShortcuts(QKeySequence::Save);
//    connect(ui_->action_save_project, &QAction::triggered, [this](){
//        // TODO: check dirty.
//        save_project();
//    });
//
//    ui_->action_save_project_as->setShortcuts(QKeySequence::SaveAs);
//    connect(ui_->action_save_project_as, &QAction::triggered, [this]() {
//        save_project(
//            QFileDialog::getSaveFileName(this, "Save Project",
//                QString::fromStdString(core::project_dir_path.generic_string()), "JSON (*.json)"
//            ).toStdString()
//        );
//    });

    connect(ui_->action_import_model_, &QAction::triggered, this, &MainWindow::import_model_tirggered);
    connect(ui_->action_refresh_scenegraph_, &QAction::triggered, this, &MainWindow::refresh_scenegraph_triggered);

    ui_->action_exit->setShortcuts(QKeySequence::Quit);

    connect(ui_->action_run_renderer, &QAction::triggered, this, &MainWindow::connect_rendering_server);

//    ui_->action_options->setShortcuts(QKeySequence::Preferences);
//    connect(ui_->action_options, &QAction::triggered, [this]() {
//        OptionsDialog option_dialog(this);
//        if (option_dialog.exec()) {
//            update_ui();
//        }
//    });

#if defined(BOOST_OS_WINDOWS)
    connect(ui_->action_toggle_system_console_, &QAction::triggered, [this]() {
        ui_->action_toggle_system_console_->setChecked(toggle_system_console());
    });
#else
    // this action can be only used in Windows.
    ui_->action_toggle_system_console_->setEnabled(false);
#endif

    connect(ui_->action_about_qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(ui_->action_about_application, &QAction::triggered, this, &MainWindow::about_application);
    connect(ui_->scenegraph_tree_, &QTreeWidget::currentItemChanged, this, &MainWindow::on_scenegraph_item_changed);

    load_settings();
    update_ui();

    set_enable_restapi_actions(false);

    ui_->status_bar_->showMessage("Ready");
}

void MainWindow::connect_rendering_server(void)
{
    if (!restapi_client_)
    {
        global_logger_->info("Connecting rendering server.");

        restapi_client_ = new RestAPIClient(QUrl(QStringLiteral("ws://localhost:8888")), this);

        QObject::connect(restapi_client_, &RestAPIClient::closed, [this]() {
            global_logger_->info("Rendering server is disconnected.");

            restapi_client_->deleteLater();
            restapi_client_ = nullptr;
            set_enable_restapi_actions(false);

            ui_->status_bar_->showMessage("Rendering server is disconnected");
        });

        set_enable_restapi_actions(true);

        ui_->status_bar_->showMessage("Connecting to rendering server ...");
    }
}

void MainWindow::set_enable_restapi_actions(bool enable)
{
    ui_->action_import_model_->setEnabled(enable);
    ui_->action_refresh_scenegraph_->setEnabled(enable);
    ui_->nodepath_tab_->setEnabled(enable);

    if (!enable)
    {
        ui_->geometry_tab_->setEnabled(enable);
        ui_->material_tab_->setEnabled(enable);
        ui_->scenegraph_tree_->clear();
    }
}

void MainWindow::update_material_tab_ui(void)
{
    bool metallic = ui_->material_matallic_checkbox_->isChecked();
    ui_->material_speuclar_ior_slider_->setEnabled(!metallic);
    ui_->material_speuclar_ior_spinbox_->setEnabled(!metallic);
}

void MainWindow::about_application(void)
{
    QMessageBox::about(this, QString("About ") + QApplication::instance()->applicationName(), "");
}

}   // namespace rpeditor

max_stars_repo_name: bluekyu/rpeditor

max_issues_repo_name: bluekyu/rpeditor

max_forks_repo_name: bluekyu/rpeditor


text:
#pragma once

#if defined(USE_ISOMAP)
#if !defined(USE_SHADERS)
#error in order to build with Iso tiles you need to be building with shaders (USE_SHADERS)
#endif

#include <boost/intrusive_ptr.hpp>
#include <boost/unordered_map.hpp>
#include <vector>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>

#include "geometry.hpp"
#include "graphics.hpp"
#include "formula_callable.hpp"
#include "formula_callable_definition.hpp"
#include "lighting.hpp"
#include "pathfinding.hpp"
#include "raster.hpp"
#include "shaders.hpp"
#include "variant.hpp"

namespace voxel
{
	struct position
	{
		position(int xx, int yy, int zz) : x(xx), y(yy), z(zz) {}
		int x, y, z;
	};
	bool operator==(position const& p1, position const& p2);
	std::size_t hash_value(position const& p);

	struct textured_tile_editor_info
	{
		std::string name;
		std::string group;
		variant id;
		graphics::texture tex;
		rect area;
	};

	struct colored_tile_editor_info
	{
		std::string name;
		std::string group;
		variant id;
		graphics::color color;
	};

	class logical_world;
	typedef boost::intrusive_ptr<logical_world> logical_world_ptr;

	class chunk : public game_logic::formula_callable
	{
	public:
		enum {
			FRONT	= 1,
			RIGHT	= 2,
			TOP		= 4,
			BACK	= 8,
			LEFT	= 16,
			BOTTOM	= 32,
		};

		chunk();
		explicit chunk(gles2::program_ptr shader, logical_world_ptr logic, const variant& node);
		virtual ~chunk();

		void init();
		void build();
		void draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const;
		variant write();

		virtual bool is_solid(int x, int y, int z) const = 0;
		virtual variant get_tile_type(int x, int y, int z) const = 0;
		static variant get_tile_info(const std::string& type);

		void set_tile(int x, int y, int z, const variant& type);
		void del_tile(int x, int y, int z);

		bool textured() const { return textured_; }
		int size_x() const { return size_x_; }
		int size_y() const { return size_y_; }
		int size_z() const { return size_z_; }
		void set_size(int mx, int my, int mz);

		size_t scale_x() const { return scale_x_; }
		size_t scale_y() const { return scale_y_; }
		size_t scale_z() const { return scale_z_; }

		static const std::vector<textured_tile_editor_info>& get_textured_editor_tiles();
		static const std::vector<colored_tile_editor_info>& get_colored_editor_tiles();
	protected:
		enum {
			FRONT_FACE,
			RIGHT_FACE,
			TOP_FACE,
			BACK_FACE,
			LEFT_FACE,
			BOTTOM_FACE,
			MAX_FACES,
		};

		virtual void handle_build() = 0;
		virtual void handle_draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const = 0;
		virtual void handle_set_tile(int x, int y, int z, const variant& type) = 0;
		virtual void handle_del_tile(int x, int y, int z) = 0;
		virtual variant handle_write() = 0;

		void add_vertex_data(int face, GLfloat x, GLfloat y, GLfloat z, GLfloat size, std::vector<GLfloat>& varray);
		std::vector<std::vector<GLfloat> >& get_vertex_data() { return varray_; }
		void add_vertex_vbo_data();
		void clear_vertex_data() { varray_.clear(); }
		const graphics::vbo_array& vbo() const { return vbos_; }
		const std::vector<size_t>& get_vertex_attribute_offsets() const { return vattrib_offsets_; }
		const std::vector<size_t>& get_num_vertices() const { return num_vertices_; }
		const std::vector<glm::vec3>& normals() const { return normals_; }

		GLuint mvp_uniform() const { return u_mvp_matrix_; }
		GLuint normal_uniform() const { return u_normal_; }
		GLuint position_uniform() const { return a_position_; }

		const glm::vec3& worldspace_position() const {return worldspace_position_; }
	private:
		DECLARE_CALLABLE(chunk);

		// Is this a coloured or textured chunk
		bool textured_;
		// VBO's to draw the chunk.
		graphics::vbo_array vbos_;
		// Vertex array data for the chunk
		std::vector<std::vector<GLfloat> > varray_;
		// Vertex attribute offsets
		std::vector<size_t> vattrib_offsets_;
		// Number of vertices to be drawn.
		std::vector<size_t> num_vertices_;

		int size_x_;
		int size_y_;
		int size_z_;

		size_t scale_x_;
		size_t scale_y_;
		size_t scale_z_;

		void get_uniforms_and_attributes(gles2::program_ptr shader);
		GLuint u_mvp_matrix_;
		GLuint u_normal_;
		GLuint a_position_;
		std::vector<glm::vec3> normals_;

		glm::vec3 worldspace_position_;
	};

	class chunk_colored : public chunk
	{
	public:
		chunk_colored();
		explicit chunk_colored(gles2::program_ptr shader, logical_world_ptr logic, const variant& node);
		virtual ~chunk_colored();
		bool is_solid(int x, int y, int z) const;
		variant get_tile_type(int x, int y, int z) const;
	protected:
		void handle_build();
		void handle_draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const;
		variant handle_write();
		void handle_set_tile(int x, int y, int z, const variant& type);
		void handle_del_tile(int x, int y, int z);
	private:
		void add_face_left(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col);
		void add_face_right(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col);
		void add_face_front(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col);
		void add_face_back(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col);
		void add_face_top(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col);
		void add_face_bottom(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const variant& col);

		void add_carray_data(int face, const graphics::color& color, std::vector<uint8_t>& carray);

		std::vector<std::vector<uint8_t> > carray_;
		std::vector<size_t> cattrib_offsets_;
		boost::unordered_map<position, variant> tiles_;

		GLuint a_color_;
	};

	class chunk_textured : public chunk
	{
	public:
		chunk_textured();
		explicit chunk_textured(gles2::program_ptr shader, logical_world_ptr logic, const variant& node);
		virtual ~chunk_textured();
		bool is_solid(int x, int y, int z) const;
		variant get_tile_type(int x, int y, int z) const;
	protected:
		void handle_build();
		void handle_draw(const graphics::lighting_ptr lighting, const camera_callable_ptr& camera) const;
		variant handle_write();
		void handle_set_tile(int x, int y, int z, const variant& type);
		void handle_del_tile(int x, int y, int z);
	private:
		void add_face_left(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid);
		void add_face_right(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid);
		void add_face_front(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid);
		void add_face_back(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid);
		void add_face_top(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid);
		void add_face_bottom(GLfloat x, GLfloat y, GLfloat z, GLfloat size, const std::string& bid);

		void add_tarray_data(int face, const rectf& area, std::vector<GLfloat>& tarray);

		std::vector<std::vector<GLfloat> > tarray_;
		std::vector<size_t> tattrib_offsets_;
		boost::unordered_map<position, std::string> tiles_;

		GLuint u_texture_;
		GLuint a_texcoord_;
	};

	typedef boost::intrusive_ptr<chunk> chunk_ptr;
	typedef boost::intrusive_ptr<const chunk> const_chunk_ptr;

	namespace chunk_factory
	{
		chunk_ptr create(gles2::program_ptr shader, logical_world_ptr logic, const variant& v);
	}
}

#endif // USE_ISOMAP

max_stars_repo_name: sweetkristas/anura

max_issues_repo_name: sweetkristas/anura

max_forks_repo_name: sweetkristas/anura


text:
/**
 * Copyright (c) 2013 Eugene Lazin <4lazin@gmail.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 "metadatastorage.h"
#include "util.h"

#include <sstream>

#include <boost/lexical_cast.hpp>
#include <boost/exception/diagnostic_information.hpp>

#include <sqlite3.h>  // to set trace callback

namespace Akumuli {

void delete_apr_pool(apr_pool_t *p) {
    if (p) {
        apr_pool_destroy(p);
    }
}

AprHandleDeleter::AprHandleDeleter(const apr_dbd_driver_t *driver)
    : driver(driver)
{
}

void AprHandleDeleter::operator()(apr_dbd_t* handle) {
    if (driver != nullptr && handle != nullptr) {
        apr_dbd_close(driver, handle);
    }
}

//-------------------------------MetadataStorage----------------------------------------

static void callback_adapter(void* cb, const char* msg) {
    aku_logger_cb_t logger = (aku_logger_cb_t)cb;
    if (logger != &aku_console_logger) {
        logger(AKU_LOG_TRACE, msg);
    }
}

MetadataStorage::MetadataStorage(const char* db, aku_logger_cb_t logger)
    : pool_(nullptr, &delete_apr_pool)
    , driver_(nullptr)
    , handle_(nullptr, AprHandleDeleter(nullptr))
    , logger_(logger)
{
    apr_pool_t *pool = nullptr;
    auto status = apr_pool_create(&pool, NULL);
    if (status != APR_SUCCESS) {
        // report error (can't return error from c-tor)
        throw std::runtime_error("Can't create memory pool");
    }
    pool_.reset(pool);

    status = apr_dbd_get_driver(pool, "sqlite3", &driver_);
    if (status != APR_SUCCESS) {
        (*logger_)(AKU_LOG_ERROR, "Can't load driver, maybe libaprutil1-dbd-sqlite3 isn't installed");
        throw std::runtime_error("Can't load sqlite3 dirver");
    }

    apr_dbd_t *handle = nullptr;
    status = apr_dbd_open(driver_, pool, db, &handle);
    if (status != APR_SUCCESS) {
        (*logger_)(AKU_LOG_ERROR, "Can't open database, check file path");
        throw std::runtime_error("Can't open database");
    }
    handle_ = HandleT(handle, AprHandleDeleter(driver_));

    auto sqlite_handle = apr_dbd_native_handle(driver_, handle);
    sqlite3_trace((sqlite3*)sqlite_handle, callback_adapter, (void*)logger_);

    create_tables();

    // Create prepared statement
    const char* query = "INSERT INTO akumuli_series (series_id, keyslist, storage_id) VALUES (%s, %s, %d)";
    status = apr_dbd_prepare(driver_, pool_.get(), handle_.get(), query, "INSERT_SERIES_NAME", &insert_);
    if (status != 0) {
        (*logger_)(AKU_LOG_ERROR, "Error creating prepared statement");
        throw std::runtime_error(apr_dbd_error(driver_, handle_.get(), status));
    }
}

int MetadataStorage::execute_query(std::string query) {
    int nrows = -1;
    int status = apr_dbd_query(driver_, handle_.get(), &nrows, query.c_str());
    if (status != 0 && status != 21) {
        // generate error and throw
        (*logger_)(AKU_LOG_ERROR, "Error executing query");
        throw std::runtime_error(apr_dbd_error(driver_, handle_.get(), status));
    }
    return nrows;
}

void MetadataStorage::create_tables() {
    const char* query = nullptr;

    // Create volumes table
    query =
            "CREATE TABLE IF NOT EXISTS akumuli_volumes("
            "id INTEGER UNIQUE,"
            "path TEXT UNIQUE"
            ");";
    execute_query(query);

    // Create configuration table (key-value-commmentary)
    query =
            "CREATE TABLE IF NOT EXISTS akumuli_configuration("
            "name TEXT UNIQUE,"
            "value TEXT,"
            "comment TEXT"
            ");";
    execute_query(query);

    query =
            "CREATE TABLE IF NOT EXISTS akumuli_series("
            "id INTEGER PRIMARY KEY UNIQUE,"
            "series_id TEXT,"
            "keyslist TEXT,"
            "storage_id INTEGER UNIQUE"
            ");";
    execute_query(query);
}

void MetadataStorage::init_config(const char* creation_datetime)
{
    // Create table and insert data into it

    std::stringstream insert;
    insert << "INSERT INTO akumuli_configuration (name, value, comment)" << std::endl;
    insert << "\tSELECT 'creation_time' as name, '" << creation_datetime << "' as value, "
           << "'Compression threshold value' as comment" << std::endl;
    std::string insert_query = insert.str();
    execute_query(insert_query);
}

void MetadataStorage::get_configs(std::string *creation_datetime)
{
    {   // Read creation time
        std::string query = "SELECT value FROM akumuli_configuration WHERE name='creation_time'";
        auto results = select_query(query.c_str());
        if (results.size() != 1) {
            throw std::runtime_error("Invalid configuration (creation_time)");
        }
        auto tuple = results.at(0);
        if (tuple.size() != 1) {
            throw std::runtime_error("Invalid configuration query (creation_time)");
        }
        // This value can be encoded as dobule by the sqlite engine
        *creation_datetime = tuple.at(0);
    }
}

void MetadataStorage::init_volumes(std::vector<VolumeDesc> volumes) {
    std::stringstream query;
    query << "INSERT INTO akumuli_volumes (id, path)" << std::endl;
    bool first = true;
    for (auto desc: volumes) {
        if (first) {
            query << "\tSELECT " << desc.first << " as id, '" << desc.second << "' as path" << std::endl;
            first = false;
        } else {
            query << "\tUNION SELECT " << desc.first << ", '" << desc.second << "'" << std::endl;
        }
    }
    std::string full_query = query.str();
    execute_query(full_query);
}

std::vector<MetadataStorage::UntypedTuple> MetadataStorage::select_query(const char* query) const {
    std::vector<UntypedTuple> tuples;
    apr_dbd_results_t *results = nullptr;
    int status = apr_dbd_select(driver_, pool_.get(), handle_.get(), &results, query, 0);
    if (status != 0) {
        (*logger_)(AKU_LOG_ERROR, "Error executing query");
        throw std::runtime_error(apr_dbd_error(driver_, handle_.get(), status));
    }
    // get rows
    int ntuples = apr_dbd_num_tuples(driver_, results);
    int ncolumns = apr_dbd_num_cols(driver_, results);
    for (int i = ntuples; i --> 0;) {
        apr_dbd_row_t *row = nullptr;
        status = apr_dbd_get_row(driver_, pool_.get(), results, &row, -1);
        if (status != 0) {
            (*logger_)(AKU_LOG_ERROR, "Error getting row from resultset");
            throw std::runtime_error(apr_dbd_error(driver_, handle_.get(), status));
        }
        UntypedTuple tup;
        for (int col = 0; col < ncolumns; col++) {
            const char* entry = apr_dbd_get_entry(driver_, row, col);
            if (entry) {
                tup.emplace_back(entry);
            } else {
                tup.emplace_back();
            }
        }
        tuples.push_back(std::move(tup));
    }
    return tuples;
}

std::vector<MetadataStorage::VolumeDesc> MetadataStorage::get_volumes() const {
    const char* query =
            "SELECT id, path FROM akumuli_volumes;";
    std::vector<VolumeDesc> tuples;
    std::vector<UntypedTuple> untyped = select_query(query);
    // get rows
    auto ntuples = untyped.size();
    for (size_t i = 0; i < ntuples; i++) {
        // get id
        std::string idrepr = untyped.at(i).at(0);
        int id = boost::lexical_cast<int>(idrepr);
        // get path
        std::string path = untyped.at(i).at(1);
        tuples.push_back(std::make_pair(id, path));
    }
    return tuples;
}

struct LightweightString {
    const char* str;
    int len;
};

std::ostream& operator << (std::ostream& s, LightweightString val) {
    s.write(val.str, val.len);
    return s;
}

static bool split_series(const char* str, int n, LightweightString* outname, LightweightString* outkeys) {
    int len = 0;
    while(len < n && str[len] != ' ' && str[len] != '\t') {
        len++;
    }
    if (len >= n) {
        // Error
        return false;
    }
    outname->str = str;
    outname->len = len;
    // Skip space
    auto end = str + n;
    str = str + len;
    while(str < end && (*str == ' ' || *str == '\t')) {
        str++;
    }
    if (str == end) {
        // Error (no keys present)
        return false;
    }
    outkeys->str = str;
    outkeys->len = end - str;
    return true;
}

void MetadataStorage::insert_new_names(std::vector<MetadataStorage::SeriesT> items) {
    if (items.size() == 0) {
        return;
    }

    execute_query("BEGIN TRANSACTION;");

    // Write all data
    while(!items.empty()) {
        const size_t batchsize = 100;
        const size_t newsize = items.size() > batchsize ? items.size() - batchsize : 0;
        std::vector<MetadataStorage::SeriesT> batch(items.begin() + newsize, items.end());
        items.resize(newsize);
        std::stringstream query;
        query << "INSERT INTO akumuli_series (series_id, keyslist, storage_id)" << std::endl;
        bool first = true;
        for (auto item: batch) {
            LightweightString name, keys;
            auto stid = std::get<2>(item);
            if (split_series(std::get<0>(item), std::get<1>(item), &name, &keys)) {
                if (first) {
                    query << "\tSELECT '" << name << "' as series_id, '"
                                          << keys << "' as keyslist, "
                                          << stid << "  as storage_id"
                                          << std::endl;
                    first = false;
                } else {
                    query << "\tUNION "
                          <<   "SELECT '" << name << "', '"
                                          << keys << "', "
                                          << stid
                                          << std::endl;
                }
            }
        }
        std::string full_query = query.str();
        execute_query(full_query);
    }

    execute_query("END TRANSACTION;");
}

uint64_t MetadataStorage::get_prev_largest_id() {
    auto query = "SELECT max(storage_id) FROM akumuli_series;";
    try {
        auto results = select_query(query);
        auto row = results.at(0);
        if (row.empty()) {
            AKU_PANIC("Can't get max storage id");
        }
        auto id = row.at(0);
        if (id == "") {
            // Table is empty
            return 1ul;
        }
        return boost::lexical_cast<uint64_t>(id);
    } catch(...) {
        (*logger_)(AKU_LOG_ERROR, boost::current_exception_diagnostic_information().c_str());
        AKU_PANIC("Can't get max storage id");
    }
}

aku_Status MetadataStorage::load_matcher_data(SeriesMatcher& matcher) {
    auto query = "SELECT series_id || ' ' || keyslist, storage_id FROM akumuli_series;";
    try {
        auto results = select_query(query);
        for(auto row: results) {
            if (row.size() != 2) {
                continue;
            }
            auto series = row.at(0);
            auto id = boost::lexical_cast<uint64_t>(row.at(1));
            matcher._add(series, id);
        }
    } catch(...) {
        (*logger_)(AKU_LOG_ERROR, boost::current_exception_diagnostic_information().c_str());
        return AKU_EGENERAL;
    }
    return AKU_SUCCESS;
}

}

max_stars_repo_name: vladon/Akumuli

max_issues_repo_name: vladon/Akumuli

max_forks_repo_name: vladon/Akumuli


text:
/*
 // Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
 // component of the Texas A&M University System.

 // All rights reserved.

 // The information and source code contained herein is the exclusive
 // property of TEES and may not be disclosed, examined or reproduced
 // in whole or in part without explicit written authorization from TEES.
 */

#include <cstdlib>
#include <boost/program_options.hpp>
#include <stapl/runtime.hpp>
#include <stapl/algorithms/functional.hpp>
#include <stapl/array.hpp>
#include <stapl/algorithms/functional.hpp>
#include <stapl/skeletons/operators/compose.hpp>
#include <stapl/skeletons/executors/execute.hpp>
#include <stapl/skeletons/functional/scan.hpp>
#include <stapl/skeletons/functional/sink.hpp>
#include <stapl/skeletons/functional/zip.hpp>
#include <stapl/skeletons/map_reduce.hpp>
#include <stapl/skeletons/transformations/coarse/butterfly.hpp>
#include <stapl/skeletons/transformations/coarse/compose.hpp>
#include <stapl/skeletons/transformations/coarse/reduce.hpp>
#include <stapl/skeletons/transformations/coarse/scan.hpp>
#include <stapl/skeletons/transformations/coarse/zip.hpp>
#include <stapl/skeletons/utility/coarse_identity_op.hpp>
#include <stapl/skeletons/utility/tags.hpp>
#include <stapl/utility/tuple/tuple.hpp>
#include <stapl/views/metadata/coarseners/null.hpp>
#include <stapl/views/metadata/coarseners/default.hpp>
#include <stapl/views/metadata/coarseners/multiview.hpp>
#include <stapl/utility/integer_sequence.hpp>
#include "../confint.hpp"

template <typename ExecParams, typename S, typename... V>
void
time_me(ExecParams&& exec_params, std::string const& title, S&& s, V&&... v)
{
  using std::accumulate;
  using std::cout;
  using std::endl;
  using std::inner_product;
  using std::sqrt;
  using std::transform;
  using std::vector;
  using stapl::counter;
  using stapl::default_timer;
  using stapl::do_once;
  using stapl::skeletons::execution_params;

  vector<double> elapseds;
  counter<default_timer> t;
  for (std::size_t i = 0; i < 32; ++i) {
    t.reset();
    t.start();
    stapl::skeletons::execute(exec_params, std::forward<S>(s),
      std::forward<V>(v)...);

    elapseds.push_back(t.stop());
  }

  do_once([&title, &elapseds]() {
    auto&& stats = compute_stats(elapseds);
    cout << "dbx.obs {"
         << R"("title" : ")" << title << "\","
         << R"("mean" : )" << stats.avg << ","
         << R"("stdev" : )" << stats.stddev << ","
         << R"("conf_interval" : )" << stats.conf_interval << ","
         << R"("num_samples" : )" << elapseds.size()
         << "}\n";
  });
}

template <typename T>
auto unary_equal_to(T value)
  -> decltype(std::bind(stapl::equal_to<T>(), value, std::placeholders::_1))
{
  return std::bind(stapl::equal_to<T>(), value, std::placeholders::_1);
}

template <typename S>
auto coarsen_skeleton(S&& s, std::true_type)
  -> decltype(stapl::skeletons::coarse(s))
{
  return stapl::skeletons::coarse(s);
}

template <typename T, typename S>
auto add_identity(S&& s, std::true_type)
  -> decltype(
       stapl::skeletons::compose(
         stapl::skeletons::map(stapl::identity<T>()), s))
{
  using stapl::skeletons::compose;
  using stapl::skeletons::map;
  using stapl::identity;
  return compose(map(identity<T>()), s);
}

template <typename T, typename S>
S add_identity(S&& s, std::false_type)
{
  return s;
}

template <typename S>
S coarsen_skeleton(S&& s, std::false_type)
{
  return s;
}

template <typename T>
struct some_op
{
  template <typename... V>
  T operator()(V&&... v) const
  {
    std::initializer_list<T> vs = {v...};
    return std::accumulate(vs.begin(), vs.end(), T{0});
  }
};

void verify(bool is_correct, std::string const& text)
{

  stapl::do_once([&] {
    if (!is_correct){
        std::cout << text << " failed to produce the correct result"
                  << std::endl;
    }
  });
}

template <typename ValueType, bool B>
void test_zip(std::size_t n, std::integral_constant<bool, B> b)
{
  using stapl::all_of;
  using stapl::array;
  using stapl::default_coarsener;
  using stapl::make_array_view;
  using stapl::plus;
  using stapl::skeletons::sink;
  using stapl::skeletons::execution_params;
  using stapl::null_coarsener;

  using coarsener =
    typename std::conditional<B, default_coarsener, null_coarsener>::type;
  auto ep = execution_params(coarsener());
  using stapl::skeletons::zip;

  stapl::array<ValueType> in(n, ValueType{1});
  stapl::array<ValueType> out(n);
  auto in_view = make_array_view(in);
  auto out_view = make_array_view(out);

  std::string prefix = B ? "coarse-" : "";
  std::string title = prefix + "zip<1>";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(zip<1>(some_op<ValueType>())), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "zip<2>";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(zip<2>(some_op<ValueType>())), b),
          in_view, in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(2)),title);

  title = prefix + "zip<3>";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(zip<3>(some_op<ValueType>())), b),
          in_view, in_view, in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(3)),title);

  title = prefix + "zip<4>";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(zip<4>(some_op<ValueType>())), b),
          in_view, in_view, in_view, in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(4)),title);

  title = prefix + "zip<5>";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(zip<5>(some_op<ValueType>())), b),
          in_view, in_view, in_view, in_view, in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(5)),title);
}

/// Composes a given skeleton with itself for N times
template <typename Skeleton, std::size_t... Index>
auto compose_n_times(Skeleton&& s, stapl::index_sequence<Index...>&&)
  -> decltype(
      stapl::skeletons::compose(stapl::get<Index-Index>(
        stapl::make_tuple(s))...)
    )
{
  return stapl::skeletons::compose(stapl::get<Index-Index>(
           stapl::make_tuple(s))...);
}

/// Composes a given skeleton with itself for N times
template <std::size_t N, typename Skeleton>
auto compose_n_times(Skeleton&& s)
  -> decltype(compose_n_times(std::forward<Skeleton>(s),
                              stapl::make_index_sequence<N>()))
{
  return compose_n_times(std::forward<Skeleton>(s),
                         stapl::make_index_sequence<N>());
}

template <typename ValueType, bool B>
void test_compose(std::size_t n, std::integral_constant<bool, B> b)
{
  using stapl::all_of;
  using stapl::array;
  using stapl::default_coarsener;
  using stapl::make_array_view;
  using stapl::plus;
  using stapl::skeletons::compose;
  using stapl::skeletons::map;
  using stapl::skeletons::sink;
  using stapl::skeletons::execution_params;
  using stapl::null_coarsener;

  using coarsener =
    typename std::conditional<B, default_coarsener, null_coarsener>::type;
  auto ep = execution_params(coarsener());
  using stapl::skeletons::zip;

  stapl::array<ValueType> in(n, ValueType{1});
  stapl::array<ValueType> out(n);
  auto in_view = make_array_view(in);
  auto out_view = make_array_view(out);

  std::string prefix = B ? "coarse-" : "";

  auto skeleton = map(some_op<ValueType>());
  auto compose2  = compose_n_times<2>(skeleton);
  auto compose3  = compose_n_times<3>(skeleton);
  auto compose4  = compose_n_times<4>(skeleton);
  auto compose5  = compose_n_times<5>(skeleton);
  auto compose6  = compose_n_times<6>(skeleton);
  auto compose7  = compose_n_times<7>(skeleton);
  auto compose8  = compose_n_times<8>(skeleton);
  auto compose9  = compose_n_times<9>(skeleton);
  auto compose10 = compose_n_times<10>(skeleton);

  std::string title = prefix + "map";
  time_me(ep, title, coarsen_skeleton(sink<ValueType>(skeleton), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [2 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose2), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [3 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose3), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [4 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose4), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [5 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose5), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [6 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose6), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [7 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose7), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [8 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose8), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [9 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose9), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);

  title = prefix + "compose(map...) [10 times]";
  time_me(ep, title,
          coarsen_skeleton(sink<ValueType>(compose10), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(1)),title);
}

template <typename ValueType, bool B>
void test_butterfly(std::size_t n, std::integral_constant<bool, B> b)
{
  using stapl::all_of;
  using stapl::array;
  using stapl::default_coarsener;
  using stapl::make_array_view;
  using stapl::plus;
  using stapl::skeletons::butterfly;
  using stapl::skeletons::reverse_butterfly;
  using stapl::skeletons::sink;
  using stapl::skeletons::execution_params;
  using stapl::null_coarsener;

  using coarsener =
    typename std::conditional<B, default_coarsener, null_coarsener>::type;
  auto ep = execution_params(coarsener());
  using stapl::skeletons::zip;

  stapl::array<ValueType> in(n, ValueType{1});
  stapl::array<ValueType> out(n);
  auto in_view = make_array_view(in);
  auto out_view = make_array_view(out);

  ValueType sum = stapl::accumulate(in_view, ValueType{0});

  std::string prefix = B ? "coarse-" : "";

  std::string title = prefix + "butterfly";
  time_me(ep, title,
          coarsen_skeleton(
            sink<ValueType>(
              add_identity<ValueType>(butterfly(plus<ValueType>()), b)),
            b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(sum)), title);

  title = prefix + "reverse-butterfly";
  time_me(ep, title,
          coarsen_skeleton(
            sink<ValueType>(reverse_butterfly(plus<ValueType>())), b),
          in_view, out_view);
  verify(all_of(out_view, unary_equal_to<ValueType>(sum)), title);
}

template <typename ValueType>
void test_scan(std::size_t n, std::false_type)
{
  using stapl::skeletons::default_execution_params;
  using stapl::skeletons::zip;
  using stapl::skeletons::sink;
  using stapl::skeletons::scan;
  using stapl::array;
  using stapl::plus;
  using stapl::make_array_view;

  auto ep = default_execution_params();

  array<ValueType> in(n, ValueType{1});
  array<ValueType> out(n);
  auto in_view  = make_array_view(in);
  auto out_view = make_array_view(out);
  auto plus_i   = plus<ValueType>();

  ValueType sum = stapl::accumulate(in_view, ValueType{0});

  std::string title = "scan<binomial>";
  time_me(ep, title,
          sink<ValueType>(scan(plus_i)),
          in_view, out_view);
  verify(out_view[n - 1] == sum, title);

  title = "scan<hillis-steele>";
  time_me(ep, title,
          sink<ValueType>(
            scan<stapl::skeletons::tags::hillis_steele>(plus_i)),
          in_view, out_view);
  verify(out_view[n - 1] == sum, title);

  title = "scan<blelloch>";
  time_me(ep, title,
          sink<ValueType>(scan<stapl::skeletons::tags::blelloch>(plus_i, 0)),
          in_view, out_view);
  verify(out_view[n - 1] == (sum - in_view[n - 1]), title);
}

template <typename ValueType>
void test_scan(std::size_t n, std::true_type)
{
  using stapl::skeletons::execution_params;
  using stapl::skeletons::scan;
  using stapl::skeletons::sink;
  using stapl::skeletons::zip;
  using stapl::skeletons::coarse;
  using stapl::array;
  using stapl::default_coarsener;
  using stapl::plus;
  using stapl::make_array_view;

  auto ep = execution_params(default_coarsener());

  array<ValueType> in(n, ValueType{1});
  array<ValueType> out(n);
  auto in_view  = make_array_view(in);
  auto out_view = make_array_view(out);
  auto plus_i   = plus<ValueType>();

  ValueType sum = stapl::accumulate(in_view, ValueType{0});

  std::string title = "coarse-scan<binomial>";
  time_me(ep, title,
          coarse(scan(plus_i)),
          in_view, out_view);
  verify(out_view[n - 1] == sum, title);

  title = "coarse-scan<hillis-steele>";
  time_me(ep, title,
          coarse(
            scan<stapl::skeletons::tags::hillis_steele>(plus_i)),
          in_view, out_view);
  verify(out_view[n - 1] == sum, title);

  title = "coarse-scan<blelloch>";
  time_me(ep, title,
          coarse(
            scan<stapl::skeletons::tags::blelloch>(plus_i, 0)),
          in_view, out_view);
  verify(out_view[n - 1] == (sum - in_view[n - 1]), title);
}

template <typename ValueType, typename Sizes, bool B>
void run_tests(Sizes&& sizes, std::integral_constant<bool, B> b)
{
  std::string coarse_prefix_str = "coarse-";
  auto size =
    sizes[(B ? coarse_prefix_str : "") + "size"]
      .template as<std::size_t>();
  auto butterfly_size =
    sizes[(B ? coarse_prefix_str : "") + "butterfly-size"]
      .template as<std::size_t>();

  test_zip<ValueType>(size, b);
  test_compose<ValueType>(size, b);
  test_scan<ValueType>(size, b);
  test_butterfly<ValueType>(butterfly_size, b);
}

stapl::exit_code stapl_main(int argc, char* argv[])
{
  // The supported options.
  namespace options = boost::program_options;
  options::options_description desc("Allowed options");
  desc.add_options()("help", "produce help message")
     ("size",
      options::value<std::size_t>()->required(),
      "Regular input size for coarse-grain tests")
     ("coarse-size",
      options::value<std::size_t>()->required(),
      "Regular input size for fine-grain-tests")
     ("butterfly-size",
      options::value<std::size_t>()->required(),
      "Input size for fine-grain butterfly tests")
     ("coarse-butterfly-size",
      options::value<std::size_t>()->required(),
      "Input size for coarse-grain butterfly tests");

  options::variables_map vm;
  options::store(options::parse_command_line(argc, argv, desc), vm);

  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return EXIT_SUCCESS;
  }

  options::notify(vm);

  using value_t = int;

  run_tests<value_t>(vm, std::true_type());
  run_tests<value_t>(vm, std::false_type());

  return EXIT_SUCCESS;
}

ext: cc


text:
/*=============================================================================
    Copyright (c) 2003 Hartmut Kaiser
    http://spirit.sourceforge.net/

    Use, modification and distribution is subject to the Boost Software
    License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
    http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#include <iostream>
#include <boost/detail/lightweight_test.hpp>

using namespace std;

#define BOOST_SPIRIT_SWITCH_CASE_LIMIT 6
#define BOOST_SPIRIT_SELECT_LIMIT 6
#define PHOENIX_LIMIT 6

//#define BOOST_SPIRIT_DEBUG
#include <boost/mpl/list.hpp>
#include <boost/mpl/for_each.hpp>

#include <boost/spirit/include/classic_primitives.hpp>
#include <boost/spirit/include/classic_numerics.hpp>
#include <boost/spirit/include/classic_actions.hpp>
#include <boost/spirit/include/classic_operators.hpp>
#include <boost/spirit/include/classic_rule.hpp>
#include <boost/spirit/include/classic_grammar.hpp>
#include <boost/spirit/include/classic_switch.hpp>
#include <boost/spirit/include/classic_select.hpp>
#include <boost/spirit/include/classic_closure.hpp>

using namespace BOOST_SPIRIT_CLASSIC_NS;

namespace test_grammars {

///////////////////////////////////////////////////////////////////////////////
//  Test the direct switch_p usage (with default_p)
    struct switch_grammar_direct_default4
    :   public grammar<switch_grammar_direct_default4>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_direct_default4 const& /*self*/)
            {
                r = switch_p [
                        case_p<'a'>(int_p),
                        case_p<'b'>(ch_p(',')),
                        case_p<'c'>(str_p("bcd")),
                        default_p
                    ];
            }

            rule<ScannerT> r;
            rule<ScannerT> const& start() const { return r; }
        };
    };

    struct switch_grammar_direct_default5
    :   public grammar<switch_grammar_direct_default5>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_direct_default5 const& /*self*/)
            {
                r = switch_p [
                        case_p<'a'>(int_p),
                        case_p<'b'>(ch_p(',')),
                        default_p,
                        case_p<'c'>(str_p("bcd"))
                    ];
            }

            rule<ScannerT> r;
            rule<ScannerT> const& start() const { return r; }
        };
    };

    struct switch_grammar_direct_default6
    :   public grammar<switch_grammar_direct_default6>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_direct_default6 const& /*self*/)
            {
                r = switch_p [
                        default_p,
                        case_p<'a'>(int_p),
                        case_p<'b'>(ch_p(',')),
                        case_p<'c'>(str_p("bcd"))
                    ];
            }

            rule<ScannerT> r;
            rule<ScannerT> const& start() const { return r; }
        };
    };

///////////////////////////////////////////////////////////////////////////////
//  Test the switch_p usage given a parser as the switch condition
    struct switch_grammar_parser_default4
    :   public grammar<switch_grammar_parser_default4>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_parser_default4 const& /*self*/)
            {
                r = switch_p(anychar_p) [
                        case_p<'a'>(int_p),
                        case_p<'b'>(ch_p(',')),
                        case_p<'c'>(str_p("bcd")),
                        default_p
                    ];
            }

            rule<ScannerT> r;
            rule<ScannerT> const& start() const { return r; }
        };
    };

    struct switch_grammar_parser_default5
    :   public grammar<switch_grammar_parser_default5>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_parser_default5 const& /*self*/)
            {
                r = switch_p(anychar_p) [
                        case_p<'a'>(int_p),
                        case_p<'b'>(ch_p(',')),
                        default_p,
                        case_p<'c'>(str_p("bcd"))
                    ];
            }

            rule<ScannerT> r;
            rule<ScannerT> const& start() const { return r; }
        };
    };

    struct switch_grammar_parser_default6
    :   public grammar<switch_grammar_parser_default6>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_parser_default6 const& /*self*/)
            {
                r = switch_p(anychar_p) [
                        default_p,
                        case_p<'a'>(int_p),
                        case_p<'b'>(ch_p(',')),
                        case_p<'c'>(str_p("bcd"))
                    ];
            }

            rule<ScannerT> r;
            rule<ScannerT> const& start() const { return r; }
        };
    };

///////////////////////////////////////////////////////////////////////////////
//  Test the switch_p usage given an actor as the switch condition
    struct select_result : public BOOST_SPIRIT_CLASSIC_NS::closure<select_result, int>
    {
        member1 val;
    };

    struct switch_grammar_actor_default4
    :   public grammar<switch_grammar_actor_default4>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_actor_default4 const& /*self*/)
            {
                using phoenix::arg1;
                r = select_p('a', 'b', 'c', 'd')[r.val = arg1] >>
                    switch_p(r.val) [
                        case_p<0>(int_p),
                        case_p<1>(ch_p(',')),
                        case_p<2>(str_p("bcd")),
                        default_p
                    ];
            }

            rule<ScannerT, select_result::context_t> r;
            rule<ScannerT, select_result::context_t> const&
            start() const { return r; }
        };
    };

    struct switch_grammar_actor_default5
    :   public grammar<switch_grammar_actor_default5>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_actor_default5 const& /*self*/)
            {
                using phoenix::arg1;
                r = select_p('a', 'b', 'c', 'd')[r.val = arg1] >>
                    switch_p(r.val) [
                        case_p<0>(int_p),
                        case_p<1>(ch_p(',')),
                        default_p,
                        case_p<2>(str_p("bcd"))
                    ];
            }

            rule<ScannerT, select_result::context_t> r;
            rule<ScannerT, select_result::context_t> const&
            start() const { return r; }
        };
    };

    struct switch_grammar_actor_default6
    :   public grammar<switch_grammar_actor_default6>
    {
        template <typename ScannerT>
        struct definition
        {
            definition(switch_grammar_actor_default6 const& /*self*/)
            {
                using phoenix::arg1;
                r = select_p('a', 'b', 'c', 'd')[r.val = arg1] >>
                    switch_p(r.val) [
                        default_p,
                        case_p<0>(int_p),
                        case_p<1>(ch_p(',')),
                        case_p<2>(str_p("bcd"))
                    ];
            }

            rule<ScannerT, select_result::context_t> r;
            rule<ScannerT, select_result::context_t> const&
            start() const { return r; }
        };
    };

}   // namespace test_grammars

///////////////////////////////////////////////////////////////////////////////
namespace tests {

    //  Tests for known (to the grammars) sequences
    struct check_grammar_known {

        template <typename GrammarT>
        void operator()(GrammarT)
        {
            GrammarT g;

            BOOST_TEST(parse("a1", g).full);
            BOOST_TEST(!parse("a,", g).hit);
            BOOST_TEST(!parse("abcd", g).hit);

            BOOST_TEST(parse("a 1", g, space_p).full);
            BOOST_TEST(!parse("a ,", g, space_p).hit);
            BOOST_TEST(!parse("a bcd", g, space_p).hit);

            BOOST_TEST(!parse("b1", g).hit);
            BOOST_TEST(parse("b,", g).full);
            BOOST_TEST(!parse("bbcd", g).hit);

            BOOST_TEST(!parse("b 1", g, space_p).hit);
            BOOST_TEST(parse("b ,", g, space_p).full);
            BOOST_TEST(!parse("b bcd", g, space_p).hit);

            BOOST_TEST(!parse("c1", g).hit);
            BOOST_TEST(!parse("c,", g).hit);
            BOOST_TEST(parse("cbcd", g).full);

            BOOST_TEST(!parse("c 1", g, space_p).hit);
            BOOST_TEST(!parse("c ,", g, space_p).hit);
            BOOST_TEST(parse("c bcd", g, space_p).full);
        }
    };

    //  Tests for known (to the grammars) sequences
    //  Tests for the default branches (without parsers) of the grammars
    struct check_grammar_default_plain {

        template <typename GrammarT>
        void operator()(GrammarT)
        {
            GrammarT g;

            BOOST_TEST(parse("d", g).full);
            BOOST_TEST(parse(" d", g, space_p).full); // JDG 10-18-2005 removed trailing ' ' to
                                                  // avoid post skip problems
        }
    };

}   // namespace tests

int
main()
{
    //  Test switch_p parsers containing special (epsilon) default_p case
    //  branches
    typedef boost::mpl::list<
    // switch_p syntax
        test_grammars::switch_grammar_direct_default4,
        test_grammars::switch_grammar_direct_default5,
        test_grammars::switch_grammar_direct_default6,

    // switch_p(parser) syntax
        test_grammars::switch_grammar_parser_default4,
        test_grammars::switch_grammar_parser_default5,
        test_grammars::switch_grammar_parser_default6,

    // switch_p(actor) syntax
        test_grammars::switch_grammar_actor_default4,
        test_grammars::switch_grammar_actor_default5,
        test_grammars::switch_grammar_actor_default6
    > default_epsilon_list_t;

    boost::mpl::for_each<default_epsilon_list_t>(tests::check_grammar_known());
    boost::mpl::for_each<default_epsilon_list_t>(
        tests::check_grammar_default_plain());

    return boost::report_errors();
}


text:
// Copyright Yamaha 2021
// MIT License
// https://github.com/yamaha-bps/ros2_pcl_utils/blob/master/LICENSE

#ifndef PCL_UTILS__FILTER_HPP_
#define PCL_UTILS__FILTER_HPP_

#include <Eigen/Geometry>
#include <sensor_msgs/msg/camera_info.hpp>
#include <sensor_msgs/msg/image.hpp>
#include <sensor_msgs/msg/point_cloud2.hpp>

#include <unordered_set>

namespace cbr
{

/**
 * @brief Filter a pointcloud with respect to an image
 *
 * @param[in] img a segmentation image of type mono8
 * @param cam_info calibration info for the camera
 * @param good_idx the image indices to preserve in the filtered point cloud
 * @param T_CF translation from camera to frame
 * @param R_CF rotation from camera to frame
 * @param[in, out] pcl incoming pointcloud
 */
void filter(
  const sensor_msgs::msg::Image & img,
  const sensor_msgs::msg::CameraInfo & cam_info,
  const std::unordered_set<uint8_t> & good_idx,
  const Eigen::Vector3f & T_CF,
  const Eigen::Quaternionf & R_CF,
  sensor_msgs::msg::PointCloud2 & pcl);

}  // namespace cbr

#endif  // PCL_UTILS__FILTER_HPP_