text:
//###
#if 1

#include <boost/shared_ptr.hpp>

#include <opencv2/opencv.hpp>

#include <sl/Camera.hpp>

//#################### TYPEDEFS ####################

namespace sl {

typedef boost::shared_ptr<Camera> Camera_Ptr;
typedef boost::shared_ptr<const Camera> Camera_CPtr;

}

//#################### FUNCTIONS ####################

void destroy_zed(sl::Camera *zed)
{
  zed->close();
  delete zed;
}

sl::Camera_Ptr init_zed()
{
  sl::Camera *zed = new sl::Camera;

  sl::InitParameters params;
  params.camera_resolution = sl::RESOLUTION_VGA;
  params.depth_mode = sl::DEPTH_MODE_QUALITY;
  params.coordinate_units = sl::UNIT_METER;

  sl::ERROR_CODE err = zed->open(params);
  if(err == sl::SUCCESS)
  {
    return sl::Camera_Ptr(zed, destroy_zed);
  }
  else
  {
    delete zed;
    return sl::Camera_Ptr();
  }
}

/**
 * Conversion function between sl::Mat and cv::Mat.
 */
cv::Mat slMat2cvMat(sl::Mat& input)
{
  // Mapping between MAT_TYPE and CV_TYPE
  int cv_type = -1;
  switch(input.getDataType())
  {
    case sl::MAT_TYPE_32F_C1: cv_type = CV_32FC1; break;
    case sl::MAT_TYPE_32F_C2: cv_type = CV_32FC2; break;
    case sl::MAT_TYPE_32F_C3: cv_type = CV_32FC3; break;
    case sl::MAT_TYPE_32F_C4: cv_type = CV_32FC4; break;
    case sl::MAT_TYPE_8U_C1: cv_type = CV_8UC1; break;
    case sl::MAT_TYPE_8U_C2: cv_type = CV_8UC2; break;
    case sl::MAT_TYPE_8U_C3: cv_type = CV_8UC3; break;
    case sl::MAT_TYPE_8U_C4: cv_type = CV_8UC4; break;
    default: break;
  }

  // Since cv::Mat data requires a uchar* pointer, we get the uchar1 pointer from sl::Mat (getPtr<T>())
  // cv::Mat and sl::Mat will share a single memory structure.
  return cv::Mat(input.getHeight(), input.getWidth(), cv_type, input.getPtr<sl::uchar1>(sl::MEM_CPU));
}

int main()
{
  sl::Camera_Ptr zed = init_zed();
  if(!zed)
  {
    std::cerr << "Error: Could not initialise Zed camera\n";
    return EXIT_FAILURE;
  }

  sl::Resolution imgSize = zed->getResolution();
  sl::Mat colour(imgSize.width, imgSize.height, sl::MAT_TYPE_8U_C4);
  cv::Mat cvColour = slMat2cvMat(colour);

  sl::RuntimeParameters params;
  params.sensing_mode = sl::SENSING_MODE_STANDARD;

  sl::Mat depth;

  if(zed->grab(params) == sl::SUCCESS)
  {
    zed->retrieveMeasure(depth);
    zed->retrieveImage(colour, sl::VIEW_LEFT);

    cv::imshow("Colour", cvColour);

    cv::waitKey();
  }

  return 0;
}

#endif

//###
#if 0

/***********************************************************************************************
 ** This sample demonstrates how to use the ZED SDK with OpenCV.                              **
 ** Depth and images are captured with the ZED SDK, converted to OpenCV format and displayed. **
 ***********************************************************************************************/

 // ZED includes
#include <sl/Camera.hpp>

// OpenCV includes
#include <opencv2/opencv.hpp>

using namespace sl;

cv::Mat slMat2cvMat(Mat& input);
void printHelp();

int main(int argc, char **argv)
{
  // Create a ZED camera object
  Camera zed;

  // Set configuration parameters
  InitParameters init_params;
  init_params.camera_resolution = RESOLUTION_HD1080;
  init_params.depth_mode = DEPTH_MODE_PERFORMANCE;
  init_params.coordinate_units = UNIT_METER;

  // Open the camera
  ERROR_CODE err = zed.open(init_params);
  if(err != SUCCESS)
  {
    printf("%s\n", errorCode2str(err).c_str());
    zed.close();
    return 1; // Quit if an error occurred
  }

  // Display help in console
  printHelp();

  // Set runtime parameters after opening the camera
  RuntimeParameters runtime_parameters;
  runtime_parameters.sensing_mode = SENSING_MODE_STANDARD;

  // Prepare new image size to retrieve half-resolution images
  Resolution image_size = zed.getResolution();
  int new_width = image_size.width / 2;
  int new_height = image_size.height / 2;

  // To share data between sl::Mat and cv::Mat, use slMat2cvMat()
  // Only the headers and pointer to the sl::Mat are copied, not the data itself
  Mat image_zed(new_width, new_height, MAT_TYPE_8U_C4);
  cv::Mat image_ocv = slMat2cvMat(image_zed);
  Mat depth_image_zed(new_width, new_height, MAT_TYPE_8U_C4);
  cv::Mat depth_image_ocv = slMat2cvMat(depth_image_zed);
  Mat point_cloud;

  // Loop until 'q' is pressed
  char key = ' ';
  while(key != 'q')
  {
    if(zed.grab(runtime_parameters) == SUCCESS)
    {
      // Retrieve the left image, depth image in half-resolution
      zed.retrieveImage(image_zed, VIEW_LEFT, MEM_CPU, new_width, new_height);
      zed.retrieveImage(depth_image_zed, VIEW_DEPTH, MEM_CPU, new_width, new_height);

      // Retrieve the RGBA point cloud in half-resolution
      // To learn how to manipulate and display point clouds, see Depth Sensing sample
      zed.retrieveMeasure(point_cloud, MEASURE_XYZRGBA, MEM_CPU, new_width, new_height);

      // Display image and depth using cv:Mat which share sl:Mat data
      cv::imshow("Image", image_ocv);
      cv::imshow("Depth", depth_image_ocv);

      // Handle key event
      key = cv::waitKey(10);
    }
  }

  zed.close();
  return 0;
}

/**
 * Conversion function between sl::Mat and cv::Mat
 **/
cv::Mat slMat2cvMat(Mat& input)
{
  // Mapping between MAT_TYPE and CV_TYPE
  int cv_type = -1;
  switch (input.getDataType())
  {
    case MAT_TYPE_32F_C1: cv_type = CV_32FC1; break;
    case MAT_TYPE_32F_C2: cv_type = CV_32FC2; break;
    case MAT_TYPE_32F_C3: cv_type = CV_32FC3; break;
    case MAT_TYPE_32F_C4: cv_type = CV_32FC4; break;
    case MAT_TYPE_8U_C1: cv_type = CV_8UC1; break;
    case MAT_TYPE_8U_C2: cv_type = CV_8UC2; break;
    case MAT_TYPE_8U_C3: cv_type = CV_8UC3; break;
    case MAT_TYPE_8U_C4: cv_type = CV_8UC4; break;
    default: break;
  }

  // Since cv::Mat data requires a uchar* pointer, we get the uchar1 pointer from sl::Mat (getPtr<T>())
  // cv::Mat and sl::Mat will share a single memory structure
  return cv::Mat(input.getHeight(), input.getWidth(), cv_type, input.getPtr<sl::uchar1>(MEM_CPU));
}

/**
 * This function displays help in console
 **/
void printHelp()
{
  std::cout << " Press 's' to save Side by side images" << std::endl;
  std::cout << " Press 'p' to save Point Cloud" << std::endl;
  std::cout << " Press 'd' to save Depth image" << std::endl;
  std::cout << " Press 'm' to switch Point Cloud format" << std::endl;
  std::cout << " Press 'n' to switch Depth format" << std::endl;
}

#endif

//###
#if 0

#include <sl/Camera.hpp>
using namespace sl;

int main(int argc, char **argv)
{
  // Create a ZED camera object
  Camera zed;

  // Set configuration parameters
  InitParameters init_params;
  init_params.sdk_verbose = false; // Disable verbose mode

  // Open the camera
  ERROR_CODE err = zed.open(init_params);
  if (err != SUCCESS)
      exit(-1);

  // Get camera information (ZED serial number)
  int zed_serial = zed.getCameraInformation().serial_number;
  printf("Hello! This is my serial number: %d\n", zed_serial);

  // Close the camera
  zed.close();
  return 0;
}

#endif

max_stars_repo_name: torrvision/spaint

max_issues_repo_name: torrvision/spaint

max_forks_repo_name: torrvision/spaint


text:
// MIT License
//
// Copyright (c) 2021 Aditya Shridhar Hegde
//
// 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 <HEAAN.h>
#include <cnpy.h>
#include <errno.h>
#include <sys/stat.h>

#include <boost/program_options.hpp>
#include <chrono>
#include <ckp19/dataset.hpp>
#include <ckp19/mean_shift.hpp>
#include <ckp19/plaintext_clustering.hpp>
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
#include <numeric>
#include <string>

#include "utils.hpp"

namespace fs = std::filesystem;
namespace bpo = boost::program_options;
using json = nlohmann::json;
using TimeUnit = std::chrono::system_clock::time_point;

void benchmarkClustering(const bpo::variables_map &opts) {
  long seed = opts["seed"].as<long>();
  long repeat = opts["repeat"].as<long>();
  long threads = opts["threads"].as<long>();
  std::string dataset = opts["dataset"].as<std::string>();

  srand(seed);
  SetNumThreads(threads);

  bool save_data = false;
  fs::path output_dir;
  if (opts.count("output") > 0) {
    save_data = true;
    output_dir = fs::path(opts["output"].as<std::string>());
  }

  long logq = opts["logq"].as<long>();
  long logp = opts["logp"].as<long>();
  long logt = opts["logt"].as<long>();
  long logq_boot = opts["logq-boot"].as<long>();

  long num_dusts = opts["dusts"].as<long>();
  long iterations = opts["iterations"].as<long>();
  long mode_kdegree = opts["mode-kdegree"].as<long>();
  long label_kdegree = opts["label-kdegree"].as<long>();
  long mode_inv_steps = opts["mode-invsteps"].as<long>();
  long label_inv_steps = opts["label-invsteps"].as<long>();
  long minidx_t = opts["min-idx-t"].as<long>();

  json info;

  TimePoint start;
  Ring ring;
  SecretKey secretKey(ring);
  Scheme scheme(secretKey, ring);
  scheme.addLeftRotKeys(secretKey);
  scheme.addRightRotKeys(secretKey);
  TimePoint end;
  info["stats"]["init_scheme"] = end - start;

  Dataset ds = Dataset::loadNpy(dataset);
  ds.rescaleDatasetInPlace(0.5);

  long logl = std::ceil(std::log2(ds[0].size() * num_dusts));
  start = TimePoint();
  scheme.addBootKey(secretKey, logl, logq_boot + logt);
  end = TimePoint();
  info["stats"]["gen_bootstrap_key"] = end - start;

  info["details"] = {{"seed", seed},
                     {"repeat", repeat},
                     {"threads", threads},
                     {"dataset", dataset},
                     {"logN", logN},
                     {"logQ", logQ},
                     {"logq", logq},
                     {"logp", logp},
                     {"logt", logt},
                     {"logq-boot", logq_boot},
                     {"logl", logl},
                     {"dusts", num_dusts},
                     {"iterations", iterations},
                     {"mode-kdegree", mode_kdegree},
                     {"label-kdegree", label_kdegree},
                     {"mode-invsteps", mode_inv_steps},
                     {"label-invsteps", label_inv_steps},
                     {"min-idx-t", minidx_t}};

  std::cout << "--- Information ---\n";
  for (json::iterator it = info["details"].begin(); it != info["details"].end();
       ++it) {
    std::cout << it.key() << " : " << it.value() << "\n";
  }
  std::cout << std::endl;

  std::cout << "--- Setup ---\n";
  for (json::iterator it = info["stats"].begin(); it != info["stats"].end();
       ++it) {
    std::cout << it.key() << " : " << it.value() << "\n";
  }
  std::cout << std::endl;

  info["benchmarks"] = json::array();

  fs::create_directories(output_dir);
  auto info_file = output_dir / "info.json";

  for (long i = 0; i < repeat; ++i) {
    std::cout << "--- Repetition " << i + 1 << " ---\n";

    json iter;

    EncryptedDataset eds;
    start = TimePoint();
    ds.encryptSIMD(eds, scheme, num_dusts, Nh, logp, logq);
    end = TimePoint();
    iter["encrypt_dataset_time"] = end - start;

    if (i == 0) {
      info["details"]["plaintext_points_per_ciphertext"] = eds.npoints;
      info["details"]["num_ciphertexts"] = eds.points.size();
      info["details"]["slots_used"] = eds.log_slots;
    }

    MeanShift meanshift(scheme, eds.log_slots, logq, logq_boot, logp, logt,
                        seed + i);

    std::vector<Ciphertext> clabels;

    TimePoint start;
    meanshift.clusterSIMD(clabels, eds.points, eds.dim, eds.npoints, num_dusts,
                          iterations, mode_kdegree, label_kdegree,
                          mode_inv_steps, label_inv_steps, minidx_t);
    TimePoint end;
    iter["cluster_time"] = end - start;

    std::vector<double> olabels(ds.size() * num_dusts);
    double decrypt_time = 0;
    for (size_t p = 0; p < eds.points.size(); ++p) {
      TimePoint start;
      std::unique_ptr<complex<double>[]> output(
          scheme.decrypt(secretKey, clabels[p]));
      TimePoint end;
      decrypt_time += end - start;

      for (int i = 0; i < num_dusts; ++i) {
        for (int j = 0; j < eds.npoints; ++j) {
          // Store the final label as the value in the first dimension
          olabels[p * eds.npoints * num_dusts + j * num_dusts + i] =
              output[i * eds.npoints * eds.dim + j * eds.dim].real();
        }
      }
    }
    iter["decrypt_output_time"] = decrypt_time;

    if (save_data) {
      info["benchmarks"].push_back(iter);
      saveJson(info, info_file);

      auto data_file =
          (output_dir / ("rep_" + std::to_string(i) + ".npy")).string();
      cnpy::npy_save(data_file, olabels.data(),
                     {ds.size(), static_cast<unsigned long>(num_dusts)}, "w");
    }
  }

  if (save_data) {
    // Highest virutal memory usage and physical memory usage
    info["stats"]["vmpeak"] = getProcStatus("VmPeak:");
    info["stats"]["vmhwm"] = getProcStatus("VmHWM:");
    saveJson(info, info_file);
  }
}

// clang-format off
bpo::options_description generic_program_options() {
  bpo::options_description desc("Followig options are supported by config file too");
  desc.add_options()
    ("output,o", bpo::value<std::string>(), "Directory to save benchmarks and other data.")
    ("seed", bpo::value<long>()->default_value(2602), "Seed used for RNG.")
    ("repeat,r", bpo::value<long>()->default_value(1), "Number of times to run benchmarks.")
    ("threads", bpo::value<long>()->default_value(1), "Number of threads to use.")
    ("dataset", bpo::value<std::string>()->required(), "Path to dataset in npy format.");

  desc.add_options()
    ("logq", bpo::value<long>()->default_value(logQ), "Log of ciphertext modulus.")
    ("logp", bpo::value<long>()->default_value(30), "Log of noise parameter.")
    ("logt", bpo::value<long>()->default_value(4), "Log of bootstrap noise parameter.")
    ("logq-boot", bpo::value<long>()->default_value(40), "Log of bootstrap ciphertext modulus.");

  desc.add_options()
    ("dusts", bpo::value<long>()->required(), "Number of dusts.")
    ("iterations", bpo::value<long>()->required(), "Number of iterations for mode seeking.")
    ("mode-kdegree", bpo::value<long>()->required(), "Log of kernel degree in mode seeking (\\Gamma_1).")
    ("label-kdegree", bpo::value<long>()->required(), "Log of kernel degree in point labeling (\\Gamma_2).")
    ("mode-invsteps", bpo::value<long>()->required(), "Number of iterations for inverse in mode seeking (\\zeta_1).")
    ("label-invsteps", bpo::value<long>()->required(), "Number of iterations for inverse in point labeling (\\zeta_2).")
    ("min-idx-t", bpo::value<long>()->required(), "Log of degree for minimum index algorithm (t).");

  return desc;
}
// clang-format on

int main(int argc, char *argv[]) {
  auto generic(generic_program_options());

  bpo::options_description cmdline("Run CKP19 mean shift clustering.");
  cmdline.add(generic);
  cmdline.add_options()(
      "config,c", bpo::value<std::string>(),
      "Configuration file for easy specification of cmd line arguments.")(
      "help,h", "Produce help message.");

  bpo::variables_map opts;
  bpo::store(bpo::command_line_parser(argc, argv).options(cmdline).run(), opts);

  if (opts.count("help") != 0) {
    std::cout << cmdline << std::endl;
    return 0;
  }

  if (opts.count("config") != 0) {
    std::string cpath(opts["config"].as<std::string>());
    std::ifstream fin(cpath.c_str());

    if (fin.fail()) {
      std::cerr << "Could not open configuration file at " << cpath << "\n";
      return 1;
    }

    bpo::store(bpo::parse_config_file(fin, generic), opts);
  }

  try {
    bpo::notify(opts);

    // Check if output file already exists
    if (fs::exists(opts["output"].as<std::string>())) {
      throw std::runtime_error("Output directory aready exists.");
    }
  } catch (const std::exception &ex) {
    std::cerr << ex.what() << std::endl;
    return 1;
  }

  try {
    benchmarkClustering(opts);
  } catch (const std::exception &ex) {
    std::cerr << ex.what() << "\nFatal error" << std::endl;
    return 1;
  }

  return 0;
}

ext: cpp


text:
/*
 * @file
 * @author University of Warwick
 * @version 1.0
 *
 * @section LICENSE
 *
 * @section DESCRIPTION
 *
 * Unit Tests for the LinearSolverPETScAlgorithm class
 */

#define BOOST_TEST_MODULE LinearSolverPETScAlgorithm
#include <boost/test/unit_test.hpp>
#include <boost/test/output_test_stream.hpp>
#include <stdexcept>

#include "LinearSolverPETScAlgorithm.h"
#include "Error.h"

// ========================================
// ============== Tests ===================
// ========================================

using namespace cupcfd::linearsolvers;

// Setup
BOOST_AUTO_TEST_CASE(setup)
{
    int argc = boost::unit_test::framework::master_test_suite().argc;
    char ** argv = boost::unit_test::framework::master_test_suite().argv;

    MPI_Init(&argc, &argv);
	PetscInitialize(&argc, &argv, NULL, NULL);
}

// === Constructors ===
// Test 1: Setup a Command Line Variant
BOOST_AUTO_TEST_CASE(constructor_test1)
{

}

// Test 2: Setup a CGAMG Variant
BOOST_AUTO_TEST_CASE(constructor_test2)
{

}

// === Solve ===
// Test 1: Solve a Command Line Variant
BOOST_AUTO_TEST_CASE(solve_test1)
{

}

// Test 2: Solve a CGAMG Variant
BOOST_AUTO_TEST_CASE(solve_test2)
{

}

BOOST_AUTO_TEST_CASE(cleanup)
{
	PetscFinalize();
    MPI_Finalize();
}

max_stars_repo_name: thorbenlouw/CUP-CFD

max_issues_repo_name: thorbenlouw/CUP-CFD

max_forks_repo_name: thorbenlouw/CUP-CFD


text:
//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_INVTRIG_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_DETAIL_SCALAR_F_INVTRIG_HPP_INCLUDED

#include <boost/simd/function/horn.hpp>
#include <boost/simd/constant/constant.hpp>
#include <boost/simd/constant/half.hpp>
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/mhalf.hpp>
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/pi.hpp>
#include <boost/simd/constant/pio_2.hpp>
#include <boost/simd/detail/constant/pio_2lo.hpp>
#include <boost/simd/constant/pio_3.hpp>
#include <boost/simd/constant/pio_4.hpp>
#include <boost/simd/detail/constant/pio_4lo.hpp>
#include <boost/simd/constant/tan_3pio_8.hpp>
#include <boost/simd/constant/tanpio_8.hpp>
#include <boost/simd/constant/two.hpp>
#include <boost/simd/constant/twopio_3.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/abs.hpp>
#include <boost/simd/function/bitofsign.hpp>
#include <boost/simd/function/bitwise_xor.hpp>
#include <boost/simd/function/fma.hpp>
#include <boost/simd/function/is_eqz.hpp>
#include <boost/simd/function/dec.hpp>
#include <boost/simd/function/oneminus.hpp>
#include <boost/simd/function/inc.hpp>
#include <boost/simd/function/rec.hpp>
#include <boost/simd/function/sqr.hpp>
#include <boost/simd/function/sqrt.hpp>
#include <boost/simd/detail/dispatch/meta/scalar_of.hpp>

namespace boost { namespace simd
{
  namespace detail
  {
    namespace bd =  boost::dispatch;
    namespace bs =  boost::simd;

   template < class A0,
             class unit_tag,
             class style,
             class base_A0 = bd::scalar_of_t<A0>
  >
  struct invtrig_base{};

  template < class A0 >
  struct invtrig_base<A0,tag::radian_tag,tag::not_simd_type, float>
  {
    static BOOST_FORCEINLINE A0 asin(A0 a0) BOOST_NOEXCEPT
    {
      A0 sign, x, z;
      x = bs::abs(a0);
      sign = bitofsign(a0);
      if ((x < Constant<A0,0x38d1b717>())) return a0; //1.0e-4
      if ((x >  One<A0>())) return Nan<A0>();
      auto bx_larger_05    = (x > Half<A0>());
      if (bx_larger_05)
      {
        z = Half<A0>()*oneminus(x);
        x =  sqrt(z);
      }
      else
      {
        z = sqr(x);
      }
      A0 z1 = horn<A0,
        0x3e2aaae4,
        0x3d9980f6,
        0x3d3a3ec7,
        0x3cc617e3,
        0x3d2cb352
        > (z);
      z1 = fma(z1, z*x, x);
      if(bx_larger_05)
      {
        z1 = z1+z1;
        z1 = Pio_2<A0>()-z1;
      }
      return bitwise_xor(z1, sign);
    }

    static BOOST_FORCEINLINE A0 acos(const  A0& a0) BOOST_NOEXCEPT
    {
      if (a0 < Mhalf<A0>())
        return Pi<A0>()-asin( sqrt(inc(a0)*Half<A0>()))*Two<A0>();
      else if (a0 > Half<A0>())
        return asin( sqrt(oneminus(a0)*Half<A0>()))*Two<A0>();
      return (Pio_2<A0>()-asin(a0));
    }

    static BOOST_FORCEINLINE A0 atan(A0 a0) BOOST_NOEXCEPT
    {
      A0 x  = abs(a0);
      return bitwise_xor(kernel_atan(x, rec(x)), bitofsign(a0));
    }

    static BOOST_FORCEINLINE A0 acot(A0 a0) BOOST_NOEXCEPT
    {
      A0 x  = abs(a0);
      return bitwise_xor(kernel_atan(rec(x), x), bitofsign(a0));
    }

    static BOOST_FORCEINLINE A0 kernel_atan(A0 x, A0 recx) BOOST_NOEXCEPT
    {
      if (is_eqz(x))  return Zero<A0>();
      if (x == Inf<A0>())  return Pio_2<A0>();
      A0 y = 0.0;
      A0 more = Zero<A0>();
      if( x > Tan_3pio_8<A0>())
      {
        y = Pio_2<A0>();
        more = Pio_2lo<A0>();
        x = -recx;
      }
      else if( x > Tanpio_8<A0>())
      {
        y = Pio_4<A0>();
        more =  Pio_4lo<A0>();
        x = dec(x)/inc(x);
      }
      A0 z = sqr(x);
      A0 z1 = horn<A0
        , 0xbeaaaa2aul  // -3.3333293e-01
        , 0x3e4c925ful  //  1.9991724e-01
        , 0xbe0e1b85ul  // -1.4031009e-01
        , 0x3da4f0d1ul  //  8.5460119e-02
        > (z);
    z1 = fma(x, z1*z, x);

      return y+(z1+more);
    }
  };
}
} }
#endif

ext: hpp

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
//  (C) Copyright Jeremy William Murphy 2016.

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

#ifndef BOOST_INTEGER_COMMON_FACTOR_RT_HPP
#define BOOST_INTEGER_COMMON_FACTOR_RT_HPP

#include <boost/assert.hpp>
#include <boost/core/enable_if.hpp>

#include <boost/config.hpp>  // for BOOST_NESTED_TEMPLATE, etc.
#include <boost/limits.hpp>  // for std::numeric_limits
#include <climits>           // for CHAR_MIN
#include <boost/detail/workaround.hpp>
#include <iterator>
#include <algorithm>
#include <limits>
#ifndef BOOST_NO_CXX11_HDR_TYPE_TRAITS
#include <type_traits>
#endif
#ifdef BOOST_NO_CXX11_HDR_FUNCTIONAL
#include <functional>
#endif

#if ((defined(BOOST_MSVC) && (BOOST_MSVC >= 1600)) || (defined(__clang__) && defined(__c2__)) || (defined(BOOST_INTEL) && defined(_MSC_VER))) && (defined(_M_IX86) || defined(_M_X64))
#include <intrin.h>
#endif

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable:4127 4244)  // Conditional expression is constant
#endif

#if !defined(BOOST_NO_CXX11_HDR_TYPE_TRAITS) && !defined(BOOST_NO_CXX11_NOEXCEPT)
#define BOOST_GCD_NOEXCEPT(T) noexcept(std::is_arithmetic<T>::value)
#else
#define BOOST_GCD_NOEXCEPT(T)
#endif

namespace boost {

   template <class I>
   class rational;

   namespace integer {

      namespace gcd_detail{

         //
         // some helper functions which really should be constexpr already, but sadly aren't:
         //
#ifndef BOOST_NO_CXX14_CONSTEXPR
         template <class T>
         inline constexpr T constexpr_min(T const& a, T const& b) BOOST_GCD_NOEXCEPT(T)
         {
            return a < b ? a : b;
         }
         template <class T>
         inline constexpr auto constexpr_swap(T&a, T& b) BOOST_GCD_NOEXCEPT(T) -> decltype(a.swap(b))
         {
            return a.swap(b);
         }
         template <class T, class U>
         inline constexpr void constexpr_swap(T&a, U& b...) BOOST_GCD_NOEXCEPT(T)
         {
            T t(static_cast<T&&>(a));
            a = static_cast<T&&>(b);
            b = static_cast<T&&>(t);
         }
#else
         template <class T>
         inline T constexpr_min(T const& a, T const& b) BOOST_GCD_NOEXCEPT(T)
         {
            return a < b ? a : b;
         }
         template <class T>
         inline void constexpr_swap(T&a, T& b) BOOST_GCD_NOEXCEPT(T)
         {
            using std::swap;
            swap(a, b);
         }
#endif

      template <class T, bool a =
#ifndef BOOST_NO_CXX11_HDR_TYPE_TRAITS
         std::is_unsigned<T>::value ||
#endif
         (std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_signed)>
      struct gcd_traits_abs_defaults
      {
         inline static BOOST_CXX14_CONSTEXPR const T& abs(const T& val) BOOST_GCD_NOEXCEPT(T) { return val; }
      };
      template <class T>
      struct gcd_traits_abs_defaults<T, false>
      {
         inline static T BOOST_CXX14_CONSTEXPR abs(const T& val) BOOST_GCD_NOEXCEPT(T)
         {
            // This sucks, but std::abs is not constexpr :(
            return val < T(0) ? -val : val;
         }
      };

      enum method_type
      {
         method_euclid = 0,
         method_binary = 1,
         method_mixed = 2
      };

      struct any_convert
      {
         template <class T>
         any_convert(const T&);
      };

      struct unlikely_size
      {
         char buf[9973];
      };

      unlikely_size operator <<= (any_convert, any_convert);
      unlikely_size operator >>= (any_convert, any_convert);

      template <class T>
      struct gcd_traits_defaults : public gcd_traits_abs_defaults<T>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(T& val) BOOST_GCD_NOEXCEPT(T)
         {
            unsigned r = 0;
            while(0 == (val & 1u))
            {
#ifdef _MSC_VER  // VC++ can't handle operator >>= in constexpr code for some reason
               val = val >> 1;
#else
               val >>= 1;
#endif
               ++r;
            }
            return r;
         }
         inline static BOOST_CXX14_CONSTEXPR bool less(const T& a, const T& b) BOOST_GCD_NOEXCEPT(T)
         {
            return a < b;
         }

         static T& get_value();

#ifndef BOOST_NO_SFINAE
         static const bool has_operator_left_shift_equal = sizeof(get_value() <<= 2) != sizeof(unlikely_size);
         static const bool has_operator_right_shift_equal = sizeof(get_value() >>= 2) != sizeof(unlikely_size);
#else
         static const bool has_operator_left_shift_equal = true;
         static const bool has_operator_right_shift_equal = true;
#endif
         static const method_type method = std::numeric_limits<T>::is_specialized && std::numeric_limits<T>::is_integer && has_operator_left_shift_equal && has_operator_right_shift_equal ? method_mixed : method_euclid;
      };
      //
      // Default gcd_traits just inherits from defaults:
      //
      template <class T>
      struct gcd_traits : public gcd_traits_defaults<T> {};

      //
      // Some platforms have fast bitscan operations, that allow us to implement
      // make_odd much more efficiently, unfortunately we can't use these if we want
      // the functions to be constexpr as the compiler intrinsics aren't constexpr.
      //
#if defined(BOOST_NO_CXX14_CONSTEXPR) && ((defined(BOOST_MSVC) && (BOOST_MSVC >= 1600)) || (defined(__clang__) && defined(__c2__)) || (defined(BOOST_INTEL) && defined(_MSC_VER))) && (defined(_M_IX86) || defined(_M_X64))
#pragma intrinsic(_BitScanForward,)
      template <>
      struct gcd_traits<unsigned long> : public gcd_traits_defaults<unsigned long>
      {
         BOOST_FORCEINLINE static unsigned find_lsb(unsigned long val) BOOST_NOEXCEPT
         {
            unsigned long result;
            _BitScanForward(&result, val);
            return result;
         }
         BOOST_FORCEINLINE static unsigned make_odd(unsigned long& val) BOOST_NOEXCEPT
         {
            unsigned result = find_lsb(val);
            val >>= result;
            return result;
         }
      };

#ifdef _M_X64
#pragma intrinsic(_BitScanForward64)
      template <>
      struct gcd_traits<unsigned __int64> : public gcd_traits_defaults<unsigned __int64>
      {
         BOOST_FORCEINLINE static unsigned find_lsb(unsigned __int64 mask) BOOST_NOEXCEPT
         {
            unsigned long result;
            _BitScanForward64(&result, mask);
            return result;
         }
         BOOST_FORCEINLINE static unsigned make_odd(unsigned __int64& val) BOOST_NOEXCEPT
         {
            unsigned result = find_lsb(val);
            val >>= result;
            return result;
         }
      };
#endif
      //
      // Other integer type are trivial adaptations of the above,
      // this works for signed types too, as by the time these functions
      // are called, all values are > 0.
      //
      template <> struct gcd_traits<long> : public gcd_traits_defaults<long>
      { BOOST_FORCEINLINE static unsigned make_odd(long& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
      template <> struct gcd_traits<unsigned int> : public gcd_traits_defaults<unsigned int>
      { BOOST_FORCEINLINE static unsigned make_odd(unsigned int& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
      template <> struct gcd_traits<int> : public gcd_traits_defaults<int>
      { BOOST_FORCEINLINE static unsigned make_odd(int& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
      template <> struct gcd_traits<unsigned short> : public gcd_traits_defaults<unsigned short>
      { BOOST_FORCEINLINE static unsigned make_odd(unsigned short& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
      template <> struct gcd_traits<short> : public gcd_traits_defaults<short>
      { BOOST_FORCEINLINE static unsigned make_odd(short& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
      template <> struct gcd_traits<unsigned char> : public gcd_traits_defaults<unsigned char>
      { BOOST_FORCEINLINE static unsigned make_odd(unsigned char& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
      template <> struct gcd_traits<signed char> : public gcd_traits_defaults<signed char>
      { BOOST_FORCEINLINE static signed make_odd(signed char& val)BOOST_NOEXCEPT{ signed result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
      template <> struct gcd_traits<char> : public gcd_traits_defaults<char>
      { BOOST_FORCEINLINE static unsigned make_odd(char& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
      template <> struct gcd_traits<wchar_t> : public gcd_traits_defaults<wchar_t>
      { BOOST_FORCEINLINE static unsigned make_odd(wchar_t& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; } };
#endif
#ifdef _M_X64
      template <> struct gcd_traits<__int64> : public gcd_traits_defaults<__int64>
      { BOOST_FORCEINLINE static unsigned make_odd(__int64& val)BOOST_NOEXCEPT{ unsigned result = gcd_traits<unsigned __int64>::find_lsb(val); val >>= result; return result; } };
#endif

#elif defined(BOOST_GCC) || defined(__clang__) || (defined(BOOST_INTEL) && defined(__GNUC__))

      template <>
      struct gcd_traits<unsigned> : public gcd_traits_defaults<unsigned>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned find_lsb(unsigned mask)BOOST_NOEXCEPT
         {
            return __builtin_ctz(mask);
         }
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned& val)BOOST_NOEXCEPT
         {
            unsigned result = find_lsb(val);
            val >>= result;
            return result;
         }
      };
      template <>
      struct gcd_traits<unsigned long> : public gcd_traits_defaults<unsigned long>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned find_lsb(unsigned long mask)BOOST_NOEXCEPT
         {
            return __builtin_ctzl(mask);
         }
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned long& val)BOOST_NOEXCEPT
         {
            unsigned result = find_lsb(val);
            val >>= result;
            return result;
         }
      };
      template <>
      struct gcd_traits<boost::ulong_long_type> : public gcd_traits_defaults<boost::ulong_long_type>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned find_lsb(boost::ulong_long_type mask)BOOST_NOEXCEPT
         {
            return __builtin_ctzll(mask);
         }
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(boost::ulong_long_type& val)BOOST_NOEXCEPT
         {
            unsigned result = find_lsb(val);
            val >>= result;
            return result;
         }
      };
      //
      // Other integer type are trivial adaptations of the above,
      // this works for signed types too, as by the time these functions
      // are called, all values are > 0.
      //
      template <> struct gcd_traits<boost::long_long_type> : public gcd_traits_defaults<boost::long_long_type>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(boost::long_long_type& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<boost::ulong_long_type>::find_lsb(val); val >>= result; return result; }
      };
      template <> struct gcd_traits<long> : public gcd_traits_defaults<long>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(long& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; }
      };
      template <> struct gcd_traits<int> : public gcd_traits_defaults<int>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(int& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned long>::find_lsb(val); val >>= result; return result; }
      };
      template <> struct gcd_traits<unsigned short> : public gcd_traits_defaults<unsigned short>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned short& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }
      };
      template <> struct gcd_traits<short> : public gcd_traits_defaults<short>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(short& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }
      };
      template <> struct gcd_traits<unsigned char> : public gcd_traits_defaults<unsigned char>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(unsigned char& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }
      };
      template <> struct gcd_traits<signed char> : public gcd_traits_defaults<signed char>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR signed make_odd(signed char& val)BOOST_NOEXCEPT { signed result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }
      };
      template <> struct gcd_traits<char> : public gcd_traits_defaults<char>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(char& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }
      };
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
      template <> struct gcd_traits<wchar_t> : public gcd_traits_defaults<wchar_t>
      {
         BOOST_FORCEINLINE static BOOST_CXX14_CONSTEXPR unsigned make_odd(wchar_t& val)BOOST_NOEXCEPT { unsigned result = gcd_traits<unsigned>::find_lsb(val); val >>= result; return result; }
      };
#endif
#endif
   //
   // The Mixed Binary Euclid Algorithm
   // Sidi Mohamed Sedjelmaci
   // Electronic Notes in Discrete Mathematics 35 (2009) 169-176
   //
   template <class T>
   BOOST_CXX14_CONSTEXPR T mixed_binary_gcd(T u, T v) BOOST_GCD_NOEXCEPT(T)
   {
      if(gcd_traits<T>::less(u, v))
         constexpr_swap(u, v);

      unsigned shifts = 0;

      if(u == T(0))
         return v;
      if(v == T(0))
         return u;

      shifts = constexpr_min(gcd_traits<T>::make_odd(u), gcd_traits<T>::make_odd(v));

      while(gcd_traits<T>::less(1, v))
      {
         u %= v;
         v -= u;
         if(u == T(0))
            return v << shifts;
         if(v == T(0))
            return u << shifts;
         gcd_traits<T>::make_odd(u);
         gcd_traits<T>::make_odd(v);
         if(gcd_traits<T>::less(u, v))
            constexpr_swap(u, v);
      }
      return (v == 1 ? v : u) << shifts;
   }

    /** Stein gcd (aka 'binary gcd')
     *
     * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose
     */
    template <typename SteinDomain>
    BOOST_CXX14_CONSTEXPR SteinDomain Stein_gcd(SteinDomain m, SteinDomain n) BOOST_GCD_NOEXCEPT(SteinDomain)
    {
        BOOST_ASSERT(m >= 0);
        BOOST_ASSERT(n >= 0);
        if (m == SteinDomain(0))
            return n;
        if (n == SteinDomain(0))
            return m;
        // m > 0 && n > 0
        int d_m = gcd_traits<SteinDomain>::make_odd(m);
        int d_n = gcd_traits<SteinDomain>::make_odd(n);
        // odd(m) && odd(n)
        while (m != n)
        {
            if (n > m)
               constexpr_swap(n, m);
            m -= n;
            gcd_traits<SteinDomain>::make_odd(m);
        }
        // m == n
        m <<= constexpr_min(d_m, d_n);
        return m;
    }

    /** Euclidean algorithm
     *
     * From Mathematics to Generic Programming, Alexander Stepanov, Daniel Rose
     *
     */
    template <typename EuclideanDomain>
    inline BOOST_CXX14_CONSTEXPR EuclideanDomain Euclid_gcd(EuclideanDomain a, EuclideanDomain b) BOOST_GCD_NOEXCEPT(EuclideanDomain)
    {
        while (b != EuclideanDomain(0))
        {
            a %= b;
            constexpr_swap(a, b);
        }
        return a;
    }

    template <typename T>
    inline BOOST_CXX14_CONSTEXPR BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == method_mixed, T>::type
       optimal_gcd_select(T const &a, T const &b) BOOST_GCD_NOEXCEPT(T)
    {
       return gcd_detail::mixed_binary_gcd(a, b);
    }

    template <typename T>
    inline BOOST_CXX14_CONSTEXPR BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == method_binary, T>::type
       optimal_gcd_select(T const &a, T const &b) BOOST_GCD_NOEXCEPT(T)
    {
       return gcd_detail::Stein_gcd(a, b);
    }

    template <typename T>
    inline BOOST_CXX14_CONSTEXPR BOOST_DEDUCED_TYPENAME enable_if_c<gcd_traits<T>::method == method_euclid, T>::type
       optimal_gcd_select(T const &a, T const &b) BOOST_GCD_NOEXCEPT(T)
    {
       return gcd_detail::Euclid_gcd(a, b);
    }

    template <class T>
    inline BOOST_CXX14_CONSTEXPR T lcm_imp(const T& a, const T& b) BOOST_GCD_NOEXCEPT(T)
    {
       T temp = boost::integer::gcd_detail::optimal_gcd_select(a, b);
#if BOOST_WORKAROUND(BOOST_GCC_VERSION, < 40500)
       return (temp != T(0)) ? T(a / temp * b) : T(0);
#else
       return temp != T(0) ? T(a / temp * b) : T(0);
#endif
    }

} // namespace detail

template <typename Integer>
inline BOOST_CXX14_CONSTEXPR Integer gcd(Integer const &a, Integer const &b) BOOST_GCD_NOEXCEPT(Integer)
{
    if(a == (std::numeric_limits<Integer>::min)())
       return a == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(b) : boost::integer::gcd(static_cast<Integer>(a % b), b);
    else if (b == (std::numeric_limits<Integer>::min)())
       return b == static_cast<Integer>(0) ? gcd_detail::gcd_traits<Integer>::abs(a) : boost::integer::gcd(a, static_cast<Integer>(b % a));
    return gcd_detail::optimal_gcd_select(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b)));
}

template <typename Integer>
inline BOOST_CXX14_CONSTEXPR Integer lcm(Integer const &a, Integer const &b) BOOST_GCD_NOEXCEPT(Integer)
{
   return gcd_detail::lcm_imp(static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(a)), static_cast<Integer>(gcd_detail::gcd_traits<Integer>::abs(b)));
}
#ifndef BOOST_NO_CXX11_VARIADIC_TEMPLATES
//
// This looks slightly odd, but the variadic forms must have 3 or more arguments, and the variadic argument pack may be empty.
// This matters not at all for most compilers, but Oracle C++ selects the wrong overload in the 2-arg case unless we do this.
//
template <typename Integer, typename... Args>
inline BOOST_CXX14_CONSTEXPR Integer gcd(Integer const &a, Integer const &b, const Integer& c, Args const&... args) BOOST_GCD_NOEXCEPT(Integer)
{
   Integer t = gcd(b, c, args...);
   return t == 1 ? 1 : gcd(a, t);
}

template <typename Integer, typename... Args>
inline BOOST_CXX14_CONSTEXPR Integer lcm(Integer const &a, Integer const &b, Integer const& c, Args const&... args) BOOST_GCD_NOEXCEPT(Integer)
{
   return lcm(a, lcm(b, c, args...));
}
#endif
//
// Special handling for rationals:
//
template <typename Integer>
inline typename boost::enable_if_c<std::numeric_limits<Integer>::is_specialized, boost::rational<Integer> >::type gcd(boost::rational<Integer> const &a, boost::rational<Integer> const &b)
{
   return boost::rational<Integer>(static_cast<Integer>(gcd(a.numerator(), b.numerator())), static_cast<Integer>(lcm(a.denominator(), b.denominator())));
}

template <typename Integer>
inline typename boost::enable_if_c<std::numeric_limits<Integer>::is_specialized, boost::rational<Integer> >::type lcm(boost::rational<Integer> const &a, boost::rational<Integer> const &b)
{
   return boost::rational<Integer>(static_cast<Integer>(lcm(a.numerator(), b.numerator())), static_cast<Integer>(gcd(a.denominator(), b.denominator())));
}
/**
 * Knuth, The Art of Computer Programming: Volume 2, Third edition, 1998
 * Chapter 4.5.2, Algorithm C: Greatest common divisor of n integers.
 *
 * Knuth counts down from n to zero but we naturally go from first to last.
 * We also return the termination position because it might be useful to know.
 *
 * Partly by quirk, partly by design, this algorithm is defined for n = 1,
 * because the gcd of {x} is x. It is not defined for n = 0.
 *
 * @tparam  I   Input iterator.
 * @return  The gcd of the range and the iterator position at termination.
 */
template <typename I>
std::pair<typename std::iterator_traits<I>::value_type, I>
gcd_range(I first, I last) BOOST_GCD_NOEXCEPT(I)
{
    BOOST_ASSERT(first != last);
    typedef typename std::iterator_traits<I>::value_type T;

    T d = *first++;
    while (d != T(1) && first != last)
    {
        d = gcd(d, *first);
        first++;
    }
    return std::make_pair(d, first);
}
template <typename I>
std::pair<typename std::iterator_traits<I>::value_type, I>
lcm_range(I first, I last) BOOST_GCD_NOEXCEPT(I)
{
    BOOST_ASSERT(first != last);
    typedef typename std::iterator_traits<I>::value_type T;

    T d = *first++;
    while (d != T(1) && first != last)
    {
        d = lcm(d, *first);
        first++;
    }
    return std::make_pair(d, first);
}

template < typename IntegerType >
class gcd_evaluator
#ifdef BOOST_NO_CXX11_HDR_FUNCTIONAL
   : public std::binary_function<IntegerType, IntegerType, IntegerType>
#endif
{
public:
#ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL
   typedef IntegerType first_argument_type;
   typedef IntegerType second_argument_type;
   typedef IntegerType result_type;
#endif
   IntegerType operator()(IntegerType const &a, IntegerType const &b)const
   {
      return boost::integer::gcd(a, b);
   }
};

template < typename IntegerType >
class lcm_evaluator
#ifdef BOOST_NO_CXX11_HDR_FUNCTIONAL
   : public std::binary_function<IntegerType, IntegerType, IntegerType>
#endif
{
public:
#ifndef BOOST_NO_CXX11_HDR_FUNCTIONAL
   typedef IntegerType first_argument_type;
   typedef IntegerType second_argument_type;
   typedef IntegerType result_type;
#endif
   IntegerType operator()(IntegerType const &a, IntegerType const &b)const
   {
      return boost::integer::lcm(a, b);
   }
};

}  // namespace integer
}  // namespace boost

#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

#endif  // BOOST_INTEGER_COMMON_FACTOR_RT_HPP


text:
//
// Copyright (c) 2018 CNRS
// Authors: Pierre Fernbach
//
// This file is part of bezier_COM_traj
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core  If not, see
// <http://www.gnu.org/licenses/>.

#define BOOST_TEST_MODULE transition
#include <boost/test/included/unit_test.hpp>
#include <hpp/bezier-com-traj/solve.hh>
#include <hpp/bezier-com-traj/common_solve_methods.hh>
#include <hpp/bezier-com-traj/data.hh>
#include <hpp/centroidal-dynamics/centroidal_dynamics.hh>
#include "test_helper.hh"
#include <hpp/spline/bezier_curve.h>

using namespace bezier_com_traj;
const double T = 1.5;

ProblemData buildPData(const centroidal_dynamics::EquilibriumAlgorithm algo = centroidal_dynamics::EQUILIBRIUM_ALGORITHM_PP){
    ProblemData pData;
    pData.c0_ = Vector3(0,0.5,5.);
    pData.c1_ = Vector3(2,-0.5,5.);
    pData.dc0_ = Vector3::Zero();
    pData.dc1_ = Vector3::Zero();
    pData.ddc0_ = Vector3::Zero();
    pData.ddc1_ = Vector3::Zero();
    pData.constraints_.flag_ = INIT_POS | INIT_VEL | END_VEL | END_POS;

    MatrixX3 normals(2,3),positions(2,3);
    normals.block<1,3>(0,0)=Vector3(0,0,1);
    positions.block<1,3>(0,0)=Vector3(0,0.1,0);
    normals.block<1,3>(1,0)=Vector3(0,0,1);
    positions.block<1,3>(1,0)=Vector3(0,-0.1,0);
    std::pair<MatrixX3, MatrixX3> contacts = computeRectangularContacts(normals,positions,LX,LY);
    pData.contacts_.push_back(new centroidal_dynamics::Equilibrium(ComputeContactCone(contacts.first,contacts.second,algo)));

    return pData;
}

std::vector<point_t> generate_wps(){
    return computeConstantWaypoints(buildPData(),T);
}

bezier_wp_t::t_point_t generate_wps_symbolic(){

    return computeConstantWaypointsSymbolic(buildPData(),T);
}

VectorX eval(const waypoint_t& w, const point_t& x){
    return w.first*x + w.second;
}

void vectorEqual(const VectorX& a , const VectorX& b, const double EPS = 1e-14){
    BOOST_CHECK_EQUAL(a.size(),b.size());
    BOOST_CHECK((a-b).norm() < EPS);
}

BOOST_AUTO_TEST_SUITE( symbolic )

BOOST_AUTO_TEST_CASE(symbolic_eval_c){
    std::vector<point_t> pts = generate_wps();
    bezier_wp_t::t_point_t wps =  generate_wps_symbolic();
    point_t y(1,0.2,4.5);
    pts[2] = y;

    bezier_t c (pts.begin(),pts.end(),T);
    bezier_wp_t c_sym (wps.begin(),wps.end(),T);

    double t = 0.;
    while(t<T){
        vectorEqual(c(t),eval(c_sym(t),y));
        t += 0.01;
    }
}

BOOST_AUTO_TEST_CASE(symbolic_eval_dc){
    std::vector<point_t> pts = generate_wps();
    bezier_wp_t::t_point_t wps =  generate_wps_symbolic();
    point_t y(1,0.2,4.5);
    pts[2] = y;

    bezier_t c (pts.begin(),pts.end(),T);
    bezier_t dc = c.compute_derivate(1);
    bezier_wp_t c_sym (wps.begin(),wps.end(),T);
    bezier_wp_t dc_sym = c_sym.compute_derivate(1);

    double t = 0.;
    while(t<T){
        vectorEqual(dc(t),eval(dc_sym(t),y));
        t += 0.01;
    }
}

BOOST_AUTO_TEST_CASE(symbolic_eval_ddc){
    std::vector<point_t> pts = generate_wps();
    bezier_wp_t::t_point_t wps =  generate_wps_symbolic();
    point_t y(1,0.2,4.5);
    pts[2] = y;

    bezier_t c (pts.begin(),pts.end(),T);
    bezier_t ddc = c.compute_derivate(2);
    bezier_wp_t c_sym (wps.begin(),wps.end(),T);
    bezier_wp_t ddc_sym = c_sym.compute_derivate(2);

    double t = 0.;
    while(t<T){
        vectorEqual(ddc(t),eval(ddc_sym(t),y),1e-10);
        t += 0.01;
    }
}

BOOST_AUTO_TEST_CASE(symbolic_eval_jc){
    std::vector<point_t> pts = generate_wps();
    bezier_wp_t::t_point_t wps =  generate_wps_symbolic();
    point_t y(1,0.2,4.5);
    pts[2] = y;

    bezier_t c (pts.begin(),pts.end(),T);
    bezier_t jc = c.compute_derivate(3);
    bezier_wp_t c_sym (wps.begin(),wps.end(),T);
    bezier_wp_t jc_sym = c_sym.compute_derivate(3);

    double t = 0.;
    while(t<T){
        vectorEqual(jc(t),eval(jc_sym(t),y),1e-10);
        t += 0.01;
    }
}

BOOST_AUTO_TEST_CASE(symbolic_split_c){
    std::vector<point_t> pts = generate_wps();
    bezier_wp_t::t_point_t wps =  generate_wps_symbolic();
    point_t y(1,0.2,4.5);
    pts[2] = y;

    bezier_t c (pts.begin(),pts.end(),T);
    bezier_wp_t c_sym (wps.begin(),wps.end(),T);

    double a,b,t,t1,t2;
    for(size_t i = 0 ; i < 100 ; ++i){
        a = (rand()/(double)RAND_MAX ) * T;
        b = (rand()/(double)RAND_MAX ) * T;
        t1 = std::min(a,b);
        t2 = std::max(a,b);
       // std::cout<<"try extract between : ["<<t1<<";"<<t2<<"] "<<std::endl;
        bezier_t c_e = c.extract(t1,t2);
        bezier_wp_t c_sym_e = c_sym.extract(t1,t2);
        t = t1;
        while(t < t2){
            vectorEqual(c_e(t-t1),eval(c_sym_e(t-t1),y));
            vectorEqual(c(t),eval(c_sym_e(t-t1),y));
            t+= 0.01;
        }
    }
}

BOOST_AUTO_TEST_CASE(symbolic_split_c_bench){
    using namespace std;

    std::vector<point_t> pts = generate_wps();
    bezier_wp_t::t_point_t wps =  generate_wps_symbolic();
    point_t y(1,0.2,4.5);
    pts[2] = y;

    bezier_wp_t c_sym (wps.begin(),wps.end(),T);

    std::vector<double> values;
    for (int i =0; i < 100000; ++i)
        values.push_back((double)rand()/RAND_MAX);

    clock_t s0,e0;
    std::pair<bezier_wp_t,bezier_wp_t> splitted = c_sym.split(0.5);
    s0 = clock();
    for(std::vector<double>::const_iterator cit = values.begin(); cit != values.end(); ++cit)
    {
        splitted = c_sym.split(*cit);
    }
    e0 = clock();

    std::cout<<"Time required to split a c curve : "<<((double)(e0-s0)/CLOCKS_PER_SEC)/100.<<" ms "<<std::endl;
}

BOOST_AUTO_TEST_CASE(symbolic_split_w){
    bezier_wp_t::t_point_t wps =  computeWwaypoints(buildPData(),T);
    point_t y(1,0.2,4.5);

    bezier_wp_t w (wps.begin(),wps.end(),T);

    double a,b,t,t1,t2;
    for(size_t i = 0 ; i < 100 ; ++i){
        a = (rand()/(double)RAND_MAX ) * T;
        b = (rand()/(double)RAND_MAX ) * T;
        t1 = std::min(a,b);
        t2 = std::max(a,b);
       // std::cout<<"try extract between : ["<<t1<<";"<<t2<<"] "<<std::endl;
        bezier_wp_t w_e = w.extract(t1,t2);
        t = t1;
        while(t < t2){
            vectorEqual(eval(w(t),y),eval(w_e(t-t1),y),1e-12);
            t+= 0.01;
        }
    }
}

BOOST_AUTO_TEST_CASE(symbolic_split_w_bench){
    bezier_wp_t::t_point_t wps =  computeWwaypoints(buildPData(),T);
    point_t y(1,0.2,4.5);

    bezier_wp_t w (wps.begin(),wps.end(),T);

    std::vector<double> values;
    for (int i =0; i < 100000; ++i)
        values.push_back((double)rand()/RAND_MAX);

    clock_t s0,e0;
    std::pair<bezier_wp_t,bezier_wp_t> splitted = w.split(0.5);
    s0 = clock();
    for(std::vector<double>::const_iterator cit = values.begin(); cit != values.end(); ++cit)
    {
        splitted = w.split(*cit);
    }
    e0 = clock();

    std::cout<<"Time required to split a w curve : "<<((double)(e0-s0)/CLOCKS_PER_SEC)/100.<<" ms "<<std::endl;

}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: jmirabel/hpp-bezier-com-traj

max_issues_repo_name: jmirabel/hpp-bezier-com-traj

max_forks_repo_name: jmirabel/hpp-bezier-com-traj


text:
/// \file   test_mpi_environment_fallback.cpp
///
/// \brief  This tests a multi-process MPI environment. In order to be properly
///         tested, this test case must be run on multiple nodes using an MPI
///         job runner (e.g. mpirun) in the desired computing environment, as
///         common bugs (mis-serialized pointers and uninitialized memory) may
///         go unnoticed on a single machine where processes share memory.
///
///
/// \authors    Maarten P. Scholl
/// \date       2019-10-03
/// \copyright  Copyright 2017-2019 The Institute for New Economic Thinking,
///             Oxford Martin School, University of Oxford
///
///             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.
///
///             You may obtain instructions to fulfill the attribution
///             requirements in CITATION.cff
///

// intrude into the class for testing purposes

// firstly, include other headers, so they are unaffected

#ifdef WITH_MPI

#include <boost/mpi/communicator.hpp>
#include <boost/mpi/environment.hpp>

#include <unordered_map>

#include <esl/agent.hpp>
#include <esl/computation/distributed/protocol.hpp>
#include <esl/computation/environment.hpp>
#include <esl/simulation/identity.hpp>

// then, import the class itself
#define protected public
#define private public
#include <esl/computation/distributed/mpi_environment.hpp>
#undef private
#undef protected

using namespace esl;
using namespace esl::computation::distributed;

#include <esl/computation/environment.hpp>
#include <esl/simulation/model.hpp>

#include <boost/serialization/shared_ptr.hpp>

///
/// \brief  Testing model used to test MPI environment.
///
struct test_model
: public esl::simulation::model
{
    test_model(esl::computation::environment &e,
               esl::simulation::parameter::parametrization parameters)
    : esl::simulation::model(e, parameters)
    {

    }

    void initialize() override
    {

    }

    ///
    esl::simulation::time_point
    step(esl::simulation::time_interval step) override
    {
        return model::step(step);
    }
};

///
/// \brief  We modify the class to test some things that would otherwise be
///         dependent on run-times, such as moving agents around. Only when we
///         can force agents to different processes, we can test interprocess
///         communication
///
class modified_mpi_environment
: public esl::computation::distributed::mpi_environment
{
public:
    using mpi_environment::mpi_environment;

    std::vector<migration> migrate_;
    ///
    ///
    /// \return
    virtual std::vector<migration> migrate_agents() override
    {
        auto result_ = std::vector<migration>(migrate_);
        migrate_.clear();
        return result_;
    }
};

#include <test/shared_property_owner.hpp>

#include <boost/serialization/export.hpp>

BOOST_CLASS_EXPORT(test_property_fungible)
BOOST_CLASS_EXPORT(test_property_infungible)

typedef std::pair<test_property_infungible, esl::quantity> p0;
BOOST_CLASS_EXPORT(p0);
typedef std::pair<test_property_fungible, esl::quantity> p1;
BOOST_CLASS_EXPORT(p1);

int main(int argc, char *argv[])
{
    (void)argc;
    (void)argv;
    modified_mpi_environment e;
    assert(e.communicator_.size() >= 2);
    test_model tm(e, esl::simulation::parameter::parametrization(0, 0, 10));
    if(e.communicator_.rank() == 0) {
        auto o_1    = tm.template create<owner_test_derived_properties>();
        auto o_2    = tm.template create<owner_test_derived_properties>();
        migration m = {0, 1, o_2->identifier};

        auto c = boost::dynamic_pointer_cast<esl::agent>(
            boost::make_shared<owner_test_derived_properties>(
                identity<owner_test_derived_properties>({1, 2, 3})));
        e.communicator_.send(1, 0, c);
        e.migrate_.push_back(m);

        esl::economics::accounting::inventory_filter<esl::law::property> ivf_;
        esl::economics::accounting::inventory_filter<esl::law::property> ivi_;
        auto pf = std::make_shared<test_property_fungible>(
            identity<test_property_fungible>({1}));

        ivf_.insert(pf, quantity(23400));
        auto pi = std::make_shared<test_property_infungible>(
            identity<test_property_infungible>({2}));
        ivi_.insert(pi, quantity(1));

        auto test_message_f = std::make_shared<interaction::transfer>(
            *o_1, *o_2, *o_1, *o_2, ivf_);

        test_message_f->received = 4;

        auto test_message_i = std::make_shared<interaction::transfer>(
            *o_1, *o_2, *o_1, *o_2, ivi_);

        test_message_i->received = 4;

        o_1->inventory.insert({pf, quantity(23400)});
        o_1->inventory.insert({pi, quantity(1)});
        o_1->esl::law::owner<test_property_fungible>::properties.insert(
            pf, quantity(23400));
        o_1->esl::law::owner<test_property_infungible>::properties.insert(pi);

        o_1->inbox.insert({0, test_message_f});
        o_1->outbox.emplace_back(test_message_f);

        o_1->inbox.insert({0, test_message_i});
        o_1->outbox.emplace_back(test_message_i);

    } else {
        boost::shared_ptr<esl::agent> c;
        e.communicator_.recv(0, 0, c);
    }

    tm.step({0, 10});
    if(e.communicator_.rank() == 1) {
        std::cout << "rank 1 now has " << tm.agents.local_agents_.size()
                  << std::endl;
        auto ptr = std::dynamic_pointer_cast<owner_test_derived_properties>(
            (*tm.agents.local_agents_.begin()).second);
        std::cout << ptr->inventory.size() << std::endl;
    }
    return 0;
}

#else

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

#endif

max_stars_repo_name: rht/ESL

max_issues_repo_name: rht/ESL

max_forks_repo_name: vishalbelsare/ESL


text: #include <boost/mpl/aux_/preprocessed/mwcw/equal_to.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//------------------------------------------------------------------------------
/// \file GetCurrentDirectory_tests.cpp
/// \date 20201028 03:44
//------------------------------------------------------------------------------
#include <boost/test/unit_test.hpp>
#include <filesystem>

namespace fs = std::filesystem;

BOOST_AUTO_TEST_SUITE(Cpp)
BOOST_AUTO_TEST_SUITE(FileIO)
BOOST_AUTO_TEST_SUITE(GetCurrentDirectory_tests)
BOOST_AUTO_TEST_SUITE(StdFilesystemCurrent_Path_tests)

//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(StdFilesystemCurrentPathGetsCurrentPath)
{
  const fs::path current_path_object {fs::current_path()};

  BOOST_TEST(true);
}

BOOST_AUTO_TEST_SUITE_END() // StdFilesystemCurrent_Path_tests

BOOST_AUTO_TEST_SUITE_END() // CStyleFileIO_tests
BOOST_AUTO_TEST_SUITE_END() // FileIO
BOOST_AUTO_TEST_SUITE_END() // Cpp

max_stars_repo_name: ernestyalumni/HrdwCCppCUDA

max_issues_repo_name: ernestyalumni/HrdwCCppCUDA

max_forks_repo_name: ernestyalumni/HrdwCCppCUDA


text:
#ifndef BOOST_MP11_BIND_HPP_INCLUDED
#define BOOST_MP11_BIND_HPP_INCLUDED

//  Copyright 2017 Peter Dimov.
//
//  Distributed under the Boost Software License, Version 1.0.
//
//  See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt

#include <boost/mp11/algorithm.hpp>
#include <boost/mp11/utility.hpp>
#include <cstddef>

namespace boost
{
namespace mp11
{

// mp_arg
template<std::size_t I> struct mp_arg
{
    template<class... T> using fn = mp_at_c<mp_list<T...>, I>;
};

using _1 = mp_arg<0>;
using _2 = mp_arg<1>;
using _3 = mp_arg<2>;
using _4 = mp_arg<3>;
using _5 = mp_arg<4>;
using _6 = mp_arg<5>;
using _7 = mp_arg<6>;
using _8 = mp_arg<7>;
using _9 = mp_arg<8>;

// mp_bind
template<template<class...> class F, class... T> struct mp_bind;

namespace detail
{

template<class V, class... T> struct eval_bound_arg
{
    using type = V;
};

template<std::size_t I, class... T> struct eval_bound_arg<mp_arg<I>, T...>
{
    using type = typename mp_arg<I>::template fn<T...>;
};

template<template<class...> class F, class... U, class... T> struct eval_bound_arg<mp_bind<F, U...>, T...>
{
    using type = typename mp_bind<F, U...>::template fn<T...>;
};

} // namespace detail

template<template<class...> class F, class... T> struct mp_bind
{
    template<class... U> using fn = F<typename detail::eval_bound_arg<T, U...>::type...>;
};

template<class Q, class... T> using mp_bind_q = mp_bind<Q::template fn, T...>;

// mp_bind_front
template<template<class...> class F, class... T> struct mp_bind_front
{
    // the indirection through mp_defer works around the language inability
    // to expand U... into a fixed parameter list of an alias template

    template<class... U> using fn = typename mp_defer<F, T..., U...>::type;
};

template<class Q, class... T> using mp_bind_front_q = mp_bind_front<Q::template fn, T...>;

// mp_bind_back
template<template<class...> class F, class... T> struct mp_bind_back
{
    template<class... U> using fn = typename mp_defer<F, U..., T...>::type;
};

template<class Q, class... T> using mp_bind_back_q = mp_bind_back<Q::template fn, T...>;

} // namespace mp11
} // namespace boost

#endif // #ifndef BOOST_MP11_BIND_HPP_INCLUDED


text:
/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 */

#include <iostream>
#include <sot/core/debug.hh>

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

using namespace std;

int main() {

  boost::filesystem::create_directory("foobar");
  ofstream file("foobar/cheeze");
  file << "tastes good!\n";
  file.close();
  if (!boost::filesystem::exists("foobar/cheeze"))
    std::cout << "Something is rotten in foobar\n";

  return 0;
}

max_stars_repo_name: Rascof/sot-core

max_issues_repo_name: Rascof/sot-core

max_forks_repo_name: Rascof/sot-core


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

#include <cstdlib>
#include <cstring>
#include <exception>
#include <iostream>

#include <boost/lexical_cast.hpp>

#include "search_domains/movingai_benchmark/benchmark/RandomChanges.h"
#include "search_domains/movingai_benchmark/Domain.h"
#include "search_domains/movingai_benchmark/loader/MapLoader.h"
#include "search_domains/movingai_benchmark/loader/ScenarioDirectoryLoader.h"

namespace movingai_benchmark{
namespace benchmark{

//const char UNKNOWN_TERRAIN = '.';
//const char PASSABLE_TERRAIN = '.';
//const char PASSABLE_TERRAIN_G = 'G';
//const char OUT_OF_BOUNDS = '@';
//const char OUT_OF_BOUNDS_O = 'O';
//const char TREES = 'T';
//const char SWAMP = 'S';
//const char WATER = 'W';
bool isObstacle(unsigned char map_value)
{
    switch(map_value)
    {
        case movingai_benchmark::PASSABLE_TERRAIN: return false;
        case movingai_benchmark::PASSABLE_TERRAIN_G: return false;
        case movingai_benchmark::OUT_OF_BOUNDS: return true;
        case movingai_benchmark::OUT_OF_BOUNDS_O: return true;
        case movingai_benchmark::TREES: return true;
        case movingai_benchmark::SWAMP: return true;
        case movingai_benchmark::WATER: return true;
    }

    return true;
}

void drawBlock( unsigned char * map,
        int W, int H, int x, int y,
        int block_size, unsigned char map_value)
{
    for(int i=std::max(0,x-block_size); i<=std::min(W-1,x+block_size); ++i)
    {
        for(int j=std::max(0,y-block_size); j<=std::min(H-1,y+block_size); ++j)
        {
            map[j*W + i] = map_value;
        }
    }

}

unsigned char * createMapWithRandomChanges( unsigned char const* map,
        int W, int H, double change_rate)
{
    int cells_number = W*H;
    int unblock = change_rate/2.0 * cells_number;
    int block = change_rate/2.0 * cells_number;

//    int block_size = W/2;

    unsigned char *changed_map = new unsigned char[W*H];
    std::memcpy(changed_map, map, W*H*sizeof(unsigned char));

    int i=0;
    while(i<unblock)
    {
        int id = std::rand()%cells_number;

        if(isObstacle(map[id]))
        {
//            int bs = std::rand()%(block_size+1);
            int bs = 0;
            drawBlock(changed_map, W, H, id%W, id/W, bs,
                    movingai_benchmark::PASSABLE_TERRAIN);
            i+=(bs+1)*(bs+1);
        }
    }

    i=0;
    while(i<block)
    {
        int id = std::rand()%cells_number;

        if(!isObstacle(map[id]))
        {
//            int bs = std::rand()%(block_size+1);
            int bs = 0;
            drawBlock(changed_map, W, H, id%W, id/W, bs,
                    movingai_benchmark::TREES);
            i+=(bs+1)*(bs+1);
        }
    }

    return changed_map;
}

DynamicExperiment initializeExperimentWithRandomChanges(
    loader::Experiment const& experiment, int observation_range, double change_rate)
{
    DynamicExperiment unknown_terrain_experiment;

    int W;
    int H;
    unsigned char *map;

    if(!movingai_benchmark::loader::loadMap(experiment.GetMapName(),W,H,map))
    {
        std::cerr << "Couldn't open file " << experiment.GetMapName() << std::endl;

        return unknown_terrain_experiment;
    }

    unknown_terrain_experiment.experiment = experiment;
    unknown_terrain_experiment.observation_range = observation_range;
    unknown_terrain_experiment.W = W;
    unknown_terrain_experiment.H = H;
    unknown_terrain_experiment.true_map = map;
    unknown_terrain_experiment.known_map = createMapWithRandomChanges(
            map, W, H, change_rate);

    return unknown_terrain_experiment;
}

void runBenchmarkWithRandomChanges(
    std::string hog_benchmarks_dir,
    std::string problems_name,
    std::string test_name,
    bool preinitialized,
    int observation_range,
    double change_rate,
    std::vector<std::function<heuristic_search::loggers::Log(DynamicExperiment const&)> > algorithms,
    int problems_count,
    std::function<int(std::vector<loader::Experiment> const&)> experiment_id_selector,
    std::function<heuristic_search::loggers::Log(DynamicExperiment const&)> problem_validator
    )
{
    loader::ScenarioDirectoryLoader scenarios(
            hog_benchmarks_dir+"/problems/" + problems_name,
            hog_benchmarks_dir);

    if(scenarios.experiments().empty())
    {
        return;
    }

    auto result = heuristic_search::benchmark::runBenchmark<loader::Experiment, DynamicExperiment>(
            scenarios.experiments(),
            problem_validator, algorithms,
            problems_count,
            experiment_id_selector,
            std::bind(initializeExperimentWithRandomChanges, std::placeholders::_1, observation_range, change_rate));

    auto logs = result.first;
    auto experiments = result.second;

    heuristic_search::benchmark::printSummary(logs, 4, 1);

    std::string preinit = (preinitialized)?"preinit":"uninit";
    std::string observ = boost::lexical_cast<std::string>(observation_range);
    std::string cr_id = boost::lexical_cast<std::string>(int(change_rate*100));
    if(cr_id.size()==1)
        cr_id = "0" + cr_id;

    heuristic_search::benchmark::writeResults(hog_benchmarks_dir,
            test_name+"/"+problems_name + "/" + problems_name + "_cr"+cr_id + "_" + preinit + "_obs" + observ,
            experiments, logs, 4, 1);
}

}//namespace benchmark
}//namespace movingai_benchmark


text:
// Copyright 2015-2017 Hans Dembinski
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/core/lightweight_test.hpp>
#include <boost/histogram/detail/static_if.hpp>
#include "throw_exception.hpp"

using namespace boost::histogram::detail;

int main() {
  using T = std::true_type;
  using F = std::false_type;

  // check that branch not taken does not have to compile
  BOOST_TEST_EQ(static_if<T>([](auto) { return 1; }, [] {}, 0), 1);
  BOOST_TEST_EQ(static_if<F>([] {}, [](auto) { return 1; }, 0), 1);

  BOOST_TEST_EQ(static_if_c<true>([](auto) { return 1; }, [] {}, 0), 1);
  BOOST_TEST_EQ(static_if_c<false>([] {}, [](auto) { return 1; }, 0), 1);

  // check that noexcept is correctly propagated
  auto may_throw = [](auto x) { return x; };
  auto no_throw = [](auto x) noexcept { return x; };

  // make this work with -fno-exceptions
  BOOST_TEST_EQ(noexcept(static_if<F>(no_throw, may_throw, 0)), noexcept(may_throw(0)));
  BOOST_TEST(noexcept(static_if<T>(no_throw, may_throw, 0)));

  return boost::report_errors();
}

max_issues_repo_name: qingkouwei/mediaones


text:
//=======================================================================
// Copyright 2015 - 2020 Jeff Linahan
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/copy.hpp>
#include <iostream>
using namespace std;

typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, uint32_t, float> AdjacencyList;

typedef AdjacencyList::vertex_descriptor VertexID;

    struct custom_property {
        //custom_property(uint32_t label = 0, float f = 0) : label(label), f(f) {}
        uint32_t label;
        float f;
    };

typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS, custom_property, float> AdjacencyListCustom;

struct vertex_copier {
    AdjacencyList& from;
    AdjacencyListCustom& to;

    void operator()(AdjacencyList::vertex_descriptor input, AdjacencyListCustom::vertex_descriptor output) const {
        to[output] = { from[input], 0.f };
    }
};

int main(int argc, char **argv) {

	cout << "copy test\n";
	AdjacencyList adj;
	VertexID id_0 = boost::add_vertex(0, adj);
	VertexID id_1 = boost::add_vertex(1, adj);
	VertexID id_2 = boost::add_vertex(2, adj);
	VertexID id_3 = boost::add_vertex(4, adj);
	boost::add_edge(id_0, id_1, 1.0f, adj);
	boost::add_edge(id_2, id_3, 2.0f, adj);

	AdjacencyListCustom adj_custom;
	//boost::copy_graph(adj, adj_custom, boost::vertex_copy(vertex_copier{adj, adj_custom}));
}

max_stars_repo_name: jeffythedragonslayer/lipton-tarjan

max_issues_repo_name: jeffythedragonslayer/lipton-tarjan

max_forks_repo_name: jeffythedragonslayer/lipton-tarjan


text:
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/program_options.hpp>

#include <assert.h>
#include <cmath>
#include <iomanip>
#include <string>

#include "fcs-genome/BackgroundExecutor.h"
#include "fcs-genome/BamInput.h"
#include "fcs-genome/common.h"
#include "fcs-genome/config.h"
#include "fcs-genome/Executor.h"
#include "fcs-genome/workers.h"

namespace fcsgenome {

int htc_main(int argc, char** argv,
    boost::program_options::options_description &opt_desc)
{
  namespace po = boost::program_options;

  // Define arguments
  po::variables_map cmd_vm;
  bool opt_bool = false;

  opt_desc.add_options()
    ("ref,r", po::value<std::string>()->required(), "reference genome path")
    ("input,i", po::value<std::string>()->required(), "input BAM file or dir")
    ("output,o", po::value<std::string>()->required(), "output GVCF/VCF file")
    ("produce-vcf,v", "produce VCF files from HaplotypeCaller instead of GVCF")
    ("intervalList,L", po::value<std::string>()->implicit_value(""), "interval list file")
    ("sample-id", po::value<std::string>()->implicit_value(""), "sample id for log files")
    ("skip-concat,s", "(deprecated) produce a set of GVCF/VCF files instead of one")
    ("gatk4,g", "use gatk4 to perform analysis");

  // Parse arguments
  po::store(po::parse_command_line(argc, argv, opt_desc),
      cmd_vm);

  if (cmd_vm.count("help")) {
    throw helpRequest();
  }

  // check configurations
  check_nprocs_config("htc");
  check_memory_config("htc");

  // Check if required arguments are presented
  bool flag_f             = get_argument<bool>(cmd_vm, "force", "f");
  bool flag_vcf           = get_argument<bool>(cmd_vm, "produce-vcf", "v");
  bool flag_gatk          = get_argument<bool>(cmd_vm, "gatk4", "g");
  std::string ref_path    = get_argument<std::string>(cmd_vm, "ref", "r");
  std::string input_path  = get_argument<std::string>(cmd_vm, "input", "i");
  std::string output_path = get_argument<std::string>(cmd_vm, "output", "o");
  std::string sample_id   = get_argument<std::string>(cmd_vm, "sample-id");
  std::string intv_list   = get_argument<std::string>(cmd_vm, "intervalList", "L");
  std::vector<std::string> extra_opts =
          get_argument<std::vector<std::string>>(cmd_vm, "extra-options", "O");

  // finalize argument parsing
  po::notify(cmd_vm);

  if (cmd_vm.count("sample-id") && sample_id.empty()) {
    throw pathEmpty("sample-id");
  }

  if (cmd_vm.count("intervalList") || cmd_vm.count("L")) {
    if (intv_list.empty()) throw pathEmpty("intervalList");
  }

  std::string temp_dir = conf_temp_dir + "/htc";

  // TODO: deal with the case where
  // 1. output_path is a dir but should not be deleted
  // 2. output_path is a file
  std::string output_dir;
  //output_dir = check_output(output_path, flag_f);
  output_dir = temp_dir;

  std::string temp_gvcf_path = output_dir + "/" + get_basename(output_path);

  create_dir(output_dir);
  std::vector<std::string> output_files(get_config<int>("gatk.ncontigs"));

  // Defining Interval File :
  std::vector<std::string> intv_paths;
  if (!intv_list.empty()) {
   intv_paths.push_back(intv_list);
  }

  // If BAM input is a regular file, post the intervals from Reference:
  std::vector<std::string> temp_intv;
  if (boost::filesystem::is_regular_file(input_path)){
    temp_intv=init_contig_intv(ref_path);
  }

  // start an executor for NAM
  Worker_ptr blaze_worker(new BlazeWorker(
        get_config<std::string>("blaze.nam_path"),
        get_config<std::string>("blaze.conf_path")));

  std::string tag;
  if (!sample_id.empty()) {
    tag = "blaze-nam-" + sample_id;
  }
  else {
    tag = "blaze-nam";
  }

  BackgroundExecutor bg_executor(tag, blaze_worker);
  Executor executor("Haplotype Caller", get_config<int>("gatk.htc.nprocs", "gatk.nprocs"));

  bool flag_htc_f = flag_f;
  for (int contig = 0; contig < get_config<int>("gatk.ncontigs"); contig++) {

    std::string file_ext = "vcf";
    if (!flag_vcf) {
      file_ext = "g." + file_ext;
    }

    if (boost::filesystem::is_regular_file(input_path)){
      intv_paths.push_back(temp_intv[contig]);
    }

    std::string output_file = get_contig_fname(output_dir, contig, file_ext);
    Worker_ptr worker(new HTCWorker(ref_path,
       intv_paths,
       input_path,
       output_file,
       extra_opts,
       contig,
       flag_vcf,
       flag_htc_f,
       flag_gatk)
    );

    output_files[contig] = output_file;
    executor.addTask(worker,sample_id);
    if (boost::filesystem::is_regular_file(input_path)){
      intv_paths.pop_back();
    }

  }

  bool flag = true;
  bool flag_a = false;
  bool flag_bgzip = false;

  std::string process_tag;

  { // concat gvcfs
    Worker_ptr worker(new VCFConcatWorker(
        output_files,
        temp_gvcf_path,
        flag_a,
        flag_bgzip,
        flag)
    );
    executor.addTask(worker, sample_id, true);
  }
  { // bgzip gvcf
    Worker_ptr worker(new ZIPWorker(
        temp_gvcf_path,
        output_path+".gz",
        flag_f)
    );
    executor.addTask(worker, sample_id, true);
  }
  { // tabix gvcf
    Worker_ptr worker(new TabixWorker(
        output_path + ".gz")
    );
    executor.addTask(worker, sample_id, true);
  }

  executor.run();

  return 0;
}
} // namespace fcsgenome

max_stars_repo_name: FCS-holding/falcon-genome

max_issues_repo_name: FCS-holding/falcon-genome

max_forks_repo_name: FCS-holding/falcon-genome


text:
//----------------------------------------------------------------------------
/// @file test_block_indirect_sort.cpp
/// @brief Test program of the block_indirect_sort algorithm
///
/// @author Copyright (c) 2016 Francisco Jose Tapia (fjtapia@gmail.com )\n
///         Distributed under the Boost Software License, Version 1.0.\n
///         ( See accompanying file LICENSE_1_0.txt or copy at
///           http://www.boost.org/LICENSE_1_0.txt  )
/// @version 0.1
///
/// @remarks
//-----------------------------------------------------------------------------
#include <algorithm>
#include <random>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <ciso646>
#include <boost/test/included/test_exec_monitor.hpp>
#include <boost/test/test_tools.hpp>
#include <boost/sort/sort.hpp>

namespace bsc = boost::sort::common;
namespace bsp = boost::sort;
using boost::sort::block_indirect_sort;
using bsc::range;

// ------------------- vector with 64 bits random numbers --------------------
std::vector< uint64_t > Vrandom;
const uint64_t NELEM = 2000000;

void test1 (void)
{
    const uint32_t NElem = 500000;
    std::vector< uint64_t > V1;
    V1.reserve (NElem);

    //------------------ sorted elements  4 threads --------------------------
    V1.clear ( );
    for (uint32_t i = 0; i < NElem; ++i) V1.push_back (i);

    block_indirect_sort ( V1.begin ( ), V1.end ( ), 4);
    for (unsigned i = 1; i < NElem; i++)
    {   BOOST_CHECK (V1[ i - 1 ] <= V1[ i ]);
    };

    //-------------------- reverse sorted elements 4 threads ------------------
    V1.clear ( );
    for (uint32_t i = 0; i < NElem; ++i) V1.push_back (NElem - i);

    block_indirect_sort ( V1.begin ( ), V1.end ( ), 4);
    for (unsigned i = 1; i < NElem; i++)
    {   BOOST_CHECK (V1[ i - 1 ] <= V1[ i ]);
    };

    //-------------------- equal elements 4 threads ---------------------------
    V1.clear ( );
    for (uint32_t i = 0; i < NElem; ++i) V1.push_back (1000);

    block_indirect_sort (V1.begin ( ), V1.end ( ), 4);
    for (unsigned i = 1; i < NElem; i++)
    {   BOOST_CHECK (V1[ i - 1 ] == V1[ i ]);
    };

    //------------------ sorted elements  8 threads --------------------------
    V1.clear ( );
    for (uint32_t i = 0; i < NElem; ++i) V1.push_back (i);

     block_indirect_sort ( V1.begin ( ), V1.end ( ), 8);
    for (unsigned i = 1; i < NElem; i++)
    {   BOOST_CHECK (V1[ i - 1 ] <= V1[ i ]);
    };

    //-------------------- reverse sorted elements 8 threads ------------------
    V1.clear ( );
    for (uint32_t i = 0; i < NElem; ++i) V1.push_back (NElem - i);

    block_indirect_sort ( V1.begin ( ), V1.end ( ), 8);
    for (unsigned i = 1; i < NElem; i++)
    {   BOOST_CHECK (V1[ i - 1 ] <= V1[ i ]);
    };

    //-------------------- equal elements 8 threads ---------------------------
    V1.clear ( );
    for (uint32_t i = 0; i < NElem; ++i) V1.push_back (1000);

    block_indirect_sort (V1.begin ( ), V1.end ( ), 8);
    for (unsigned i = 1; i < NElem; i++)
    {   BOOST_CHECK (V1[ i - 1 ] == V1[ i ]);
    };
};

void test2 (void)
{
    typedef std::less<uint64_t> compare;
    std::vector< uint64_t > V1, V2;
    V1.reserve ( NELEM ) ;

    V2 = Vrandom;
    std::sort (V2.begin ( ), V2.end ( ));

    //------------------- random elements 0 threads ---------------------------
    V1 = Vrandom;
    block_indirect_sort (V1.begin ( ), V1.end ( ), compare(), 0);
    for (unsigned i = 0; i < V1.size(); i++)
    {   BOOST_CHECK (V1[i] == V2[i]);
    };

    //------------------- random elements 4 threads ---------------------------
    V1 = Vrandom;
    block_indirect_sort (V1.begin ( ), V1.end ( ), compare(), 4);
    for (unsigned i = 0; i < V1.size(); i++)
    {   BOOST_CHECK (V1[i] == V2[i]);
    };

    //------------------- random elements 8 threads ---------------------------
    V1 = Vrandom;
    block_indirect_sort (V1.begin ( ), V1.end ( ), compare(), 8);
    for (unsigned i = 0; i < V1.size(); i++)
    {   BOOST_CHECK (V1[i] == V2[i]);
    };

    //------------------- random elements 16 threads ---------------------------
    V1 = Vrandom;
    block_indirect_sort ( V1.begin ( ), V1.end ( ), compare(), 16);
    for (unsigned i = 0; i < V1.size(); i++)
    {   BOOST_CHECK (V1[i] == V2[i]);
    };

    //------------------- random elements 100 threads ---------------------------
    V1 = Vrandom;
    block_indirect_sort ( V1.begin ( ), V1.end ( ), compare(), 100);
    for (unsigned i = 1; i < V1.size(); i++)
    {   BOOST_CHECK (V1[i] == V2[i]);
    };
};

template<uint32_t NN>
struct int_array
{
    uint64_t M[NN];

    int_array(uint64_t number = 0)
    {   for (uint32_t i = 0; i < NN; ++i) M[i] = number;
    };

    bool operator<(const int_array<NN> &A) const
    {   return M[0] < A.M[0];
    };
};

template<class IA>
void test_int_array(uint32_t NELEM)
{
    std::vector<IA> V1;
    V1.reserve(NELEM);

    for (uint32_t i = 0; i < NELEM; ++i)
        V1.emplace_back(Vrandom[i]);

    bsp::block_indirect_sort(V1.begin(), V1.end());
    for (unsigned i = 1; i < NELEM; i++)
    {   BOOST_CHECK(not (V1[i] < V1[i-1]));
    };
};
void test3 (void)
{
    test_int_array<int_array<1> >(1u << 20);
    test_int_array<int_array<2> >(1u << 19);
    test_int_array<int_array<8> >(1u << 17);
}

int test_main (int, char *[])
{
    std::mt19937 my_rand (0);
    Vrandom.reserve (NELEM);
    for (uint32_t i = 0; i < NELEM; ++i) Vrandom.push_back (my_rand ( ));

    test1  ( );
    test2  ( );
    test3  ( );

    return 0;
};

max_stars_repo_name: Jackarain/tinyrpc

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
#if !BOOST_PHOENIX_IS_ITERATING

#ifndef BOOST_PHOENIX_STATEMENT_DETAIL_CATCH_PUSH_BACK_HPP
#define BOOST_PHOENIX_STATEMENT_DETAIL_CATCH_PUSH_BACK_HPP

#include <boost/phoenix/support/iterate.hpp>

#if !defined(BOOST_PHOENIX_DONT_USE_PREPROCESSED_FILES)

#include <boost/phoenix/statement/detail/preprocessed/catch_push_back.hpp>

#else

#if defined(__WAVE__) && defined(BOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 2, line: 0, output: "preprocessed/catch_push_back_" BOOST_PHOENIX_LIMIT_STR ".hpp")
#endif

/*==============================================================================
    Copyright (c) 2005-2010 Joel de Guzman
    Copyright (c) 2010 Thomas Heller

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/

#if defined(__WAVE__) && defined(BOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(preserve: 1)
#endif

    #define BOOST_PHOENIX_CATCH_PUSH_BACK_R0(Z, N, DATA)                        \
        BOOST_PP_COMMA_IF(N)                                                    \
        typename proto::result_of::child_c<TryCatch, N>::type                   \
    /**/

    #define BOOST_PHOENIX_CATCH_PUSH_BACK_R1(Z, N, DATA)                        \
        BOOST_PP_COMMA_IF(N) proto::child_c<N>(try_catch)                       \
    /**/

#define BOOST_PHOENIX_ITERATION_PARAMS                                          \
        (3, (2, BOOST_PHOENIX_CATCH_LIMIT,                                      \
        <boost/phoenix/statement/detail/catch_push_back.hpp>))
#include BOOST_PHOENIX_ITERATE()

    #undef BOOST_PHOENIX_CATCH_PUSH_BACK_R0
    #undef BOOST_PHOENIX_CATCH_PUSH_BACK_R1

#if defined(__WAVE__) && defined(BOOST_PHOENIX_CREATE_PREPROCESSED_FILES)
#pragma wave option(output: null)
#endif

#endif // BOOST_PHOENIX_DONT_USE_PREPROCESSED_FILES

#endif

#else
        template <typename TryCatch, typename Exception, typename Expr>
        struct catch_push_back<TryCatch, Exception, Expr, BOOST_PHOENIX_ITERATION>
        {
            typedef
                typename proto::result_of::make_expr<
                    phoenix::tag::catch_
                  , proto::basic_default_domain
                  , catch_exception<Exception>
                  , Expr
                >::type
                catch_expr;

            typedef phoenix::expression::try_catch<
                BOOST_PP_REPEAT(BOOST_PHOENIX_ITERATION, BOOST_PHOENIX_CATCH_PUSH_BACK_R0, _)
              , catch_expr> gen_type;
            typedef typename gen_type::type type;

            static type
            make(
                TryCatch const& try_catch
              , Expr const& catch_
            )
            {
                return
                    gen_type::make(
                        BOOST_PP_REPEAT(
                            BOOST_PHOENIX_ITERATION
                          , BOOST_PHOENIX_CATCH_PUSH_BACK_R1
                          , _
                        )
                      , proto::make_expr<
                            phoenix::tag::catch_
                          , proto::basic_default_domain
                        >(catch_exception<Exception>(), catch_)
                    );
            }
        };

        template <typename TryCatch, typename Expr>
        struct catch_all_push_back<TryCatch, Expr, BOOST_PHOENIX_ITERATION>
        {
            typedef
                typename proto::result_of::make_expr<
                    phoenix::tag::catch_all
                  , proto::basic_default_domain
                  , Expr
                >::type
                catch_expr;

            typedef phoenix::expression::try_catch<
                BOOST_PP_REPEAT(BOOST_PHOENIX_ITERATION, BOOST_PHOENIX_CATCH_PUSH_BACK_R0, _)
              , catch_expr> gen_type;
            typedef typename gen_type::type type;

            static type
            make(
                TryCatch const& try_catch
              , Expr const& catch_
            )
            {
                return
                    gen_type::make(
                        BOOST_PP_REPEAT(
                            BOOST_PHOENIX_ITERATION
                          , BOOST_PHOENIX_CATCH_PUSH_BACK_R1
                          , _
                        )
                      , proto::make_expr<
                            phoenix::tag::catch_all
                          , proto::basic_default_domain
                        >(catch_)
                    );
            }
        };

#endif

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#include "json_utility.h"

#include <boost/filesystem.hpp>
#include <fstream>
#include "utilities/error.h"

namespace bfs = boost::filesystem;

namespace cpt {

nlohmann::json load_json_from_file(const std::string& filename) {
    CHECK_AND_THROW_ERROR(bfs::exists(filename), "Can not load JSON from a file that does not exist [" << filename << "].");
    std::ifstream f(filename);

    nlohmann::json jobj;
    f >> jobj;
    return jobj;
}

}


text:
#include <vector>
#include <iostream>
#include <fstream>
#include <thread>
#include <filesystem>

#include <sys/time.h>
#include <sys/resource.h>

#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/awaitable.hpp>
#include <boost/program_options.hpp>

#include "aamp.h"

using namespace std;

Config config;

int main(int argc, char **argv) {
    try {
        locale loc("");
    } catch (const std::exception& e) {
        std::cout << "Locales in Linux are fundamentally broken. Never worked. Never will. Overriding the current mess with LC_ALL=C" << endl;
        setenv("LC_ALL", "C", 1);
    }

    approaches_t approaches;
    // Eager
    addAsioCallbacksEager(approaches);
    addAsioCallbacksEagerAsyncPost(approaches);
    addAsioStackfulEager(approaches);
    addAsioStacklessEager(approaches);
    addAsioCpp20CoroEager(approaches);

    // Lazy
    addAsioStackfulLazy(approaches);
    addAsioStacklessLazy(approaches);

    namespace po = boost::program_options;
    po::options_description general("Options");
    general.add_options()
        ("help,h", "Print help and exit")
        ("approach,a",
            po::value<size_t>(&config.approach)->default_value(config.approach),
            "What approach (implementation) to use.")
        ("sessions",
            po::value<uint64_t>(&config.numSessions)->default_value(config.numSessions),
            "Number of \"sessions\" to run.")
        ("threads",
            po::value<uint64_t>(&config.numThreads)->default_value(config.numThreads),
            "Number of threads to use.")
        ("buffers",
            po::value<uint64_t>(&config.numBuffers)->default_value(config.numBuffers),
            "Number of \"buffers\" to work with for each session.")
        ("buffer-size",
            po::value<uint64_t>(&config.bufferSize)->default_value(config.bufferSize),
            "Size of one buffer in bytes.")
        ("sleep-interval",
            po::value<uint64_t>(&config.numCharsBetweenWait)->default_value(config.numCharsBetweenWait),
            "Number of \"input\" characters between sleep.")
        ("sleep-time",
            po::value<int>(&config.waitTimeMillisec)->default_value(config.waitTimeMillisec),
            "Number of milliseconds to sleep.")
        ("report-path,r",
            po::value<string>(&config.reportPath)->default_value(config.reportPath),
            "CSV file where to append the results")
        ;

    po::options_description cmdline_options;
    cmdline_options.add(general);
    po::variables_map vm;
    po::store(po::command_line_parser(argc, argv).options(cmdline_options).run(), vm);
    po::notify(vm);
    if (vm.count("help")) {
        cout << filesystem::path(argv[0]).stem().string() << " [options]";
        cout << cmdline_options << endl;
        cout << "Approaches: " << endl;

        int i = 0;
        for(const auto& a: approaches) {
            cout << "  " << i++ << ' ' << a->name() << endl;
        }
        return -1;
    }

    const auto sessionBytes = config.numBuffers * config.bufferSize;
    const auto totalBytes = sessionBytes * config.numSessions;
    const auto totalSleep = (totalBytes / config.numCharsBetweenWait) * config.waitTimeMillisec;

    cout << "Starting up." << endl
         << "Will run " << format(config.numSessions) << " sessions using "
         << format(config.numThreads) << " thread(s), each manipulating "
         << format(sessionBytes) << " bytes" << endl
         << "Total bytes is " << format(totalBytes) << endl
         << "Will suspend sessions " << format(totalBytes / config.numCharsBetweenWait)
         << " times for a total of "
         << format(totalSleep)
         << " milliseconds (" << format(totalSleep / 1000) << " seconds)." << endl;

    cout << "Exceuting " << approaches.at(config.approach)->name() << endl;
    approaches.at(config.approach)->go();

    rusage ru = {};
    getrusage(RUSAGE_SELF, &ru);

    cout << "cputime=" << (ru.ru_utime.tv_sec + ru.ru_utime.tv_usec / 1000000.0)
         << ", system=" << (ru.ru_stime.tv_sec + ru.ru_stime.tv_usec / 1000000.0)
         << ", minflt=" << ru.ru_minflt
         << ", majflt=" << ru.ru_majflt
         << ", nswap=" << ru.ru_nswap
         << ", nsignals=" << ru.ru_nsignals
         << ", nvcsw=" << ru.ru_nvcsw
         << ", nivcsw=" << ru.ru_nivcsw
         << ", maxrss=" << ru.ru_maxrss
         << ", ixrss=" << ru.ru_ixrss
         << ", idrss=" << ru.ru_idrss
         << ", isrss=" << ru.ru_isrss
         << endl;

    if (!config.reportPath.empty()) {
        if (!filesystem::is_regular_file(config.reportPath)) {
            ofstream hdr{config.reportPath};
            hdr << "Approach, cputime, system, minflt, majflt, nswap, "
                << "nsignals, nvcsw, nivcsw, maxrss, ixrss, idrss, isrss" << endl;
        }

        ofstream data{config.reportPath, ::ios_base::app};
        data << approaches.at(config.approach)->name()
             << "," << (ru.ru_utime.tv_sec + ru.ru_utime.tv_usec / 1000000.0)
             << "," << (ru.ru_stime.tv_sec + ru.ru_stime.tv_usec / 1000000.0)
             << "," << ru.ru_minflt
             << "," << ru.ru_majflt
             << "," << ru.ru_nswap
             << "," << ru.ru_nsignals
             << "," << ru.ru_nvcsw
             << "," << ru.ru_nivcsw
             << "," << ru.ru_maxrss
             << "," << ru.ru_ixrss
             << "," << ru.ru_idrss
             << "," << ru.ru_isrss
             << endl;
    }

    cout << "Done" << endl;
    return 0;
}

max_stars_repo_name: jgaa/asio-async-model-perftest

max_issues_repo_name: jgaa/asio-async-model-perftest

max_forks_repo_name: jgaa/asio-async-model-perftest