text:
/*
 * @name BookFiler Module - SSH
 * @author Branden Lee
 * @version 1.00
 * @license MIT
 * @brief SSH module for BookFiler™ applications.
 */

#ifndef BOOKFILER_MODULE_SSH_TUNNEL_SERVER_LISTENER_H
#define BOOKFILER_MODULE_SSH_TUNNEL_SERVER_LISTENER_H

// config
#include "config.hpp"

// C++17
//#include <filesystem>
#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <thread>
#include <vector>

/* boost 1.72.0
 * License: Boost Software License (similar to BSD and MIT)
 */
#include <boost/config.hpp>

// Local Project
#include "TunnelServerConnection.hpp"

/*
 * bookfiler - ssh
 * ssh utilities. The main feature is the ssh tunnel for mysql
 */
namespace bookfiler {
namespace ssh {

// Accepts incoming connections and launches the sessions
class ListenerImpl {
private:
  boost::asio::io_context &ioContext;
  boost::asio::ip::tcp::endpoint srcEndpoint, destEndpoint;
  std::shared_ptr<ServerState> serverState;
  unsigned int connectionIdIncrement;

public:
  ListenerImpl(boost::asio::io_context &, boost::asio::ip::tcp::endpoint,
               boost::asio::ip::tcp::endpoint, std::shared_ptr<ServerState>);

  // Start accepting incoming connections
  int run(boost::asio::yield_context yieldContext);
};

} // namespace port
} // namespace bookfiler

#endif
// end BOOKFILER_MODULE_PORT_FORWARDING_SERVER_LISTENER_H

max_stars_repo_name: bradosia/BookFiler-Module-SSH-libssh

max_issues_repo_name: bradosia/BookFiler-Module-SSH-libssh

max_forks_repo_name: bradosia/BookFiler-Module-SSH-libssh


text:
//Copyright (c) 2006-2009 Emil Dotchevski and Reverge Studios, Inc.

//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/exception/detail/is_output_streamable.hpp>
#include <boost/detail/lightweight_test.hpp>

namespace
n1
    {
    class
    c1
        {
        };
    }

namespace
n2
    {
    class
    c2
        {
        };

    std::ostream &
    operator<<( std::ostream & s, c2 const & )
        {
        s << "c2";
        return s;
        }
    }

int
main()
    {
    BOOST_TEST( !boost::is_output_streamable<n1::c1>::value );
    BOOST_TEST( boost::is_output_streamable<n2::c2>::value );
    BOOST_TEST( boost::is_output_streamable<int>::value );
    return boost::report_errors();
    }

ext: cpp

max_issues_repo_name: boost-cmake/vintage

max_forks_repo_name: boost-cmake/vintage


text:
#pragma once

#include <string>

#include <boost/beast/core.hpp>

#include <http/include/models.hpp>

namespace http::client {

constexpr int kHttpVersion = 11;

class HttpClient {
public:
    HttpClient(const std::string& host, int port = 80);
    HttpClient(HttpClient&& client);
    ~HttpClient();

    HttpClient& operator=(HttpClient&& client);

    Response Request(const Request& request);
private:
    HttpClient(const HttpClient&);
    HttpClient& operator=(const HttpClient&);
    void Swap(HttpClient&& other);

    std::string host_;
    std::string port_;
    std::shared_ptr<boost::asio::io_context> context_ptr_;
    boost::beast::flat_buffer buffer_;
};

} // namespace http::client

ext: hpp

max_stars_repo_name: lilSpeedwagon/zoo

max_issues_repo_name: lilSpeedwagon/zoo

max_forks_repo_name: lilSpeedwagon/zoo


text: #include <boost/spirit/home/qi/directive/no_skip.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#if defined(_MSC_VER)
#include <process.h>
#define getpid() _getpid()
#endif

#include <boost/thread.hpp>
#include <glog/logging.h>

#include <atomic>
#include <cmath>
#include <cstdio>
#include <ctime>
#include <mutex>
#include <tuple>
#include <vector>

#include "caffe/common.hpp"

#include "caffe/backend/device.hpp"
#include "caffe/backend/cuda/cuda_device.hpp"
#include "caffe/backend/hip/hip_device.hpp"
#include "caffe/backend/opencl/ocl_device.hpp"
#include "caffe/util/rng.hpp"

#if defined(USE_OPENCL)
  #if defined(USE_CLBLAS)
    #include <clBLAS.h>                     // NOLINT
  #elif defined(USE_CLBLAST)
    #include <clblast.h>                    // NOLINT
  #endif  // USE_CLBLAS or USE_CLBLAST
#endif  // USE_OPENCL

namespace caffe {

// Make sure each thread can have different values.
static boost::thread_specific_ptr<Caffe> thread_instance_;

// Pointer to the global instance of Caffe
static Caffe* global_instance_;
static std::mutex instance_mutex_;

// Device contexts are initialized once and shared on all threads
vector< shared_ptr<Device> > Caffe::devices_;

#ifdef USE_OPENCL
inline vector<viennacl::ocl::platform> get_platforms_safe() {
  vector<viennacl::ocl::platform> ret;
  cl_int err;
  cl_uint num_platforms = 0;
  err = clGetPlatformIDs(0, NULL, &num_platforms);
  VIENNACL_ERR_CHECK(err);

  vector<cl_platform_id> ids(num_platforms);
  err = clGetPlatformIDs(num_platforms, &ids[0], &num_platforms);
  VIENNACL_ERR_CHECK(err);

  for (cl_uint i = 0; i < num_platforms; ++i) {
    ret.push_back(viennacl::ocl::platform(ids[i]));
  }

  return ret;
}
#endif  // USE_OPENCL

Caffe& Caffe::Get() {
  instance_mutex_.lock();
  if (global_instance_ == nullptr) {
    // The first call must be single threaded
    // and defines the global instance
    thread_instance_.reset(new Caffe());
    global_instance_ = thread_instance_.get();
  }
  if (!thread_instance_.get()) {
    // Every thread initially gets a copy of the global initialization.
    // Later, every thread can switch to a different default device
    // or change other aspects of the Caffe object
    thread_instance_.reset(new Caffe(*global_instance_));
  }
  instance_mutex_.unlock();
  return *(thread_instance_.get());
}

// random seeding
int64_t cluster_seedgen(void) {
  int64_t s, seed, pid;
  FILE* f = fopen("/dev/urandom", "rb");
  if (f && fread(&seed, 1, sizeof(seed), f) == sizeof(seed)) {
    fclose(f);
    return seed;
  }

  LOG(INFO)<< "System entropy source not available, "
  "using fallback algorithm to generate seed instead.";
  if (f)
    fclose(f);

  pid = getpid();
  s = time(NULL);
  seed = std::abs(((s * 181) * ((pid - 83) * 359)) % 104729);
  return seed;
}

void GlobalInit(int* pargc, char*** pargv) {
  // Google flags.
  ::gflags::ParseCommandLineFlags(pargc, pargv, true);
  // Google logging.
  ::google::InitGoogleLogging(*(pargv)[0]);
  // Provide a backtrace on segfault.

  // Windows port of glogs doesn't have this function built
#if !defined(_MSC_VER)
  ::google::InstallFailureSignalHandler();
#endif
}

Device *Caffe::GetDevice(int id, bool listId) {
  if (Get().devices_.size() == 0) {
    return Get().cpu_device_.get();
  }
  if (listId) {
    return
        id == -1 ?
            Get().default_device_ :
            Get().devices_[id % Get().devices_.size()].get();
  } else {
    for (int i = 0; i < Get().devices_.size(); ++i) {
      Device* device = Get().devices_[i].get();
      if (device->id() == id) {
        return device;
      }
    }
    return GetDefaultDevice();
  }
}

Device *Caffe::GetDefaultDevice() {
  return Get().default_device_;
}

Device *Caffe::GetCPUDevice() {
  return Get().cpu_device_.get();
}

// Copy constructor for thread-local copy
Caffe::Caffe(const Caffe &obj)
    :
#ifdef USE_CUDA
      cublas_handle_(NULL),
      curand_generator_(NULL),
      curand_generator64_(NULL),
#endif  // USE_CUDA
      random_generator_(),
      mode_(Caffe::CPU),
      cpu_device_(new Device()),
      default_device_(cpu_device_.get()),
      solver_count_(1) {
  mode_ = obj.mode_;
  default_device_ = obj.default_device_;
  cpu_device_ = obj.cpu_device_;
  solver_count_ = obj.solver_count_;
}

void Caffe::SelectDevice(int id, bool listId) {
  Caffe::SelectDevice(GetDevice(id, listId));
}

void Caffe::SelectDevice(Device* device_context) {
#ifndef CPU_ONLY
  Get().default_device_ = device_context;

  if (device_context->backend() == Backend::BACKEND_CUDA) {
#ifdef USE_CUDA
    CUDA_CHECK(cudaSetDevice(device_context->id()));

    if (Get().cublas_handle_) {
      CUBLAS_CHECK(cublasDestroy(Get().cublas_handle_));
    }
    if (Get().curand_generator_) {
      CURAND_CHECK(curandDestroyGenerator(Get().curand_generator_));
    }
    if (Get().curand_generator64_) {
      CURAND_CHECK(curandDestroyGenerator(Get().curand_generator64_));
    }
    CUBLAS_CHECK(cublasCreate(&Get().cublas_handle_));

    if (cublasCreate(&(Get().cublas_handle_)) != CUBLAS_STATUS_SUCCESS) {
      LOG(ERROR)<< "Cannot create Cublas handle. Cublas won't be available.";
    }
    // Try to create a curand handler.
    if (curandCreateGenerator(&(Get().curand_generator_),
                              CURAND_RNG_PSEUDO_DEFAULT)
        != CURAND_STATUS_SUCCESS
        || curandSetPseudoRandomGeneratorSeed((Get().curand_generator_),
                                              cluster_seedgen())
            != CURAND_STATUS_SUCCESS) {
      LOG(ERROR)<< "Cannot create Curand generator. Curand won't be available.";
    }
    if (curandCreateGenerator(&(Get().curand_generator64_),
                              CURAND_RNG_QUASI_SOBOL64)
        != CURAND_STATUS_SUCCESS) {
      LOG(ERROR)<< "Cannot create Curand generator. Curand won't be available.";
    }

#endif  // USE_CUDA
  } else if (device_context->backend() == Backend::BACKEND_OPENCL) {
#ifdef USE_OPENCL
#ifdef USE_CLBLAS
    clblasSetup();
#endif  // USE_CLBLAS
#endif  // USE_OPENCL
  }
#endif  // !CPU_ONLY
}

#ifdef CPU_ONLY  // CPU-only Caffe.

Caffe::Caffe() : random_generator_(),
                 mode_(Caffe::CPU),
                 cpu_device_(new Device(-1, -1, Backend::BACKEND_CPU)),
                 default_device_(cpu_device_.get()),
                 solver_count_(1), solver_rank_(0), multiprocess_(false) { }

Caffe::~Caffe() {}

void Caffe::set_random_seed(const size_t seed, Device* device_context) {
  // RNG seed
  Get().random_generator_.reset(new RNG(seed));
}

void Caffe::SetDevices(std::vector<int> device_ids) {
  NO_GPU;
}

void Caffe::SetDevice(const int device_id) {
  NO_GPU;
}

void Caffe::DeviceQuery() {
  NO_GPU;
}

void Caffe::Synchronize(int device_id) {
  NO_GPU;
}

int Caffe::EnumerateDevices(bool silent) {
  NO_GPU;
  return 0;
}

bool Caffe::CheckDevice(const int device_id) {
  NO_GPU;
  return false;
}

int Caffe::FindDevice(const int start_id) {
  NO_GPU;
  return -1;
}

class Caffe::RNG::Generator {
 public:
  Generator() : rng_(new caffe::rng_t(cluster_seedgen())) {}
  explicit Generator(size_t seed) : rng_(new caffe::rng_t(seed)) {}
  caffe::rng_t* rng() {return rng_.get();}
 private:
  shared_ptr<caffe::rng_t> rng_;
};

Caffe::RNG::RNG() : generator_(new Generator()) {}

Caffe::RNG::RNG(size_t seed) : generator_(new Generator(seed)) {}

Caffe::RNG& Caffe::RNG::operator=(const RNG& other) {
  generator_ = other.generator_;
  return *this;
}

void* Caffe::RNG::generator() {
  return static_cast<void*>(generator_->rng());
}

#else  // Normal GPU + CPU Caffe.

Caffe::Caffe()
    :
#ifdef USE_CUDA
      cublas_handle_(NULL),
      curand_generator_(NULL),
      curand_generator64_(NULL),
#endif  // USE_CUDA
      random_generator_(),
      mode_(Caffe::CPU),
      cpu_device_(new Device()),
      default_device_(cpu_device_.get()),
    solver_count_(1), solver_rank_(0), multiprocess_(false) {
}

Caffe::~Caffe() {
  // Make sure all device contexts and
  // dependent memory blocks are freed properly
  if (this == global_instance_) {
      instance_mutex_.lock();
      global_instance_ = NULL;
      instance_mutex_.unlock();
      devices_.clear();
  }
#ifdef USE_CUDA
  if (cublas_handle_)
    CUBLAS_CHECK(cublasDestroy(cublas_handle_));
  cublas_handle_ = nullptr;
  if (curand_generator_) {
    CURAND_CHECK(curandDestroyGenerator(curand_generator_));
    curand_generator_ = nullptr;
  }
  if (curand_generator64_) {
    CURAND_CHECK(curandDestroyGenerator(curand_generator64_));
    curand_generator64_ = nullptr;
  }
#endif  // USE_CUDA
}

void Caffe::set_random_seed(const size_t seed, Device* device_context) {
  if (device_context->backend() == BACKEND_CUDA) {
#ifdef USE_CUDA
    // Curand seed
    static bool g_curand_availability_logged = false;
    if (Get().curand_generator_) {
      CURAND_CHECK(
          curandSetPseudoRandomGeneratorSeed(curand_generator(), seed));
      CURAND_CHECK(curandSetGeneratorOffset(curand_generator(), 0));
    } else {
      if (!g_curand_availability_logged) {
        LOG(ERROR)<<
        "Curand not available. Skipping setting the curand seed.";
        g_curand_availability_logged = true;
      }
    }
    if (Get().curand_generator64_) {
      CURAND_CHECK(curandSetGeneratorOffset(curand_generator64(), 0));
    } else {
      if (!g_curand_availability_logged) {
        LOG(ERROR)<<
        "Curand not available. Skipping setting the curand seed.";
        g_curand_availability_logged = true;
      }
    }
#endif  // USE_CUDA
  } else {
#ifdef USE_OPENCL
// TODO: Proper RNG and Seed for OpenCL
#endif  // USE_OPENCL
  }
  // RNG seed
  Get().random_generator_.reset(new RNG(seed));
}

void Caffe::Synchronize(int device_id) {
  if (Caffe::mode() == Brew::GPU) {
    Device * device_context = Caffe::GetDevice(device_id, true);
    if (device_context->backend() == BACKEND_CUDA) {
#ifdef USE_CUDA
      cudaDeviceSynchronize();
#endif  // USE_CUDA
    } else {
#ifdef USE_OPENCL
      viennacl::ocl::context &ctx = viennacl::ocl::get_context(
          GetDevice(device_id, true)->id());
      ctx.get_queue().finish();
#endif  // USE_OPENCL
    }
  }
}

int Caffe::EnumerateDevices(bool silent) {
  int cuda_device_count = 0;
  int opencl_device_count = 0;

#ifdef USE_CUDA
  cudaGetDeviceCount(&cuda_device_count);
#endif  // USE_CUDA

#ifdef USE_OPENCL
  typedef vector<viennacl::ocl::platform> platforms_type;
  platforms_type platforms = get_platforms_safe();

  vector<std::tuple<viennacl::ocl::platform,
    viennacl::ocl::device>> platform_devices;

  // Loop through devices
  for (std::size_t platform_id = 0; platform_id < platforms.size();
      ++platform_id) {
    typedef vector<viennacl::ocl::device> devices_type;
    try {
      devices_type devices = platforms[platform_id].devices(CL_DEVICE_TYPE_ALL);
      for (std::size_t device_id = 0; device_id < devices.size(); ++device_id) {
        platform_devices.push_back(
            std::make_tuple(platforms[platform_id], devices[device_id]));
        opencl_device_count++;
      }
    } catch (...) {
      if (!silent) {
        LOG(INFO)<< "OpenCL platform: "
        << platforms[platform_id].info()
        << " does not work correctly.";
      }
    }
  }
#endif  // USE_OPENCL

  if (!silent) {
    LOG(INFO)<< "Total devices: " << cuda_device_count + opencl_device_count;
    LOG(INFO)<< "CUDA devices: " << cuda_device_count;
    LOG(INFO)<< "OpenCL devices: " << opencl_device_count;

    // Display info for all devices
#ifdef USE_CUDA
    for (int i = 0; i < cuda_device_count; ++i) {
      cudaDeviceProp prop;
      CUDA_CHECK(cudaGetDeviceProperties(&prop, i));
      LOG(INFO)<< "Device id:                     "
      << i;
      LOG(INFO)<< "Device backend:                "
      << "CUDA";
      LOG(INFO)<< "Backend details:               "
      << "CUDA";
      LOG(INFO)<< "Device vendor:                 "
      << "NVIDIA Corporation";
      LOG(INFO)<< "Name:                          "
      << prop.name;
      LOG(INFO)<< "Total global memory:           "
      << prop.totalGlobalMem;
    }
#endif  // USE_CUDA

#ifdef USE_OPENCL
    for (int i = 0; i < opencl_device_count; ++i) {
      LOG(INFO)<< "Device id:                     "
      << cuda_device_count + i;
      LOG(INFO)<< "Device backend:                "
      << "OpenCL";
      LOG(INFO)<< "Backend details:               "
      << std::get<0>(platform_devices[i]).info();
      LOG(INFO)<< "Device vendor:                 "
      << std::get<1>(platform_devices[i]).vendor();
      LOG(INFO)<< "Name:                          "
      << std::get<1>(platform_devices[i]).name();
      LOG(INFO)<< "Total global memory:           "
      << std::get<1>(platform_devices[i]).global_mem_size();
    }
#endif  // USE_OPENCL
  }

  return cuda_device_count + opencl_device_count;
}

void Caffe::SetDevices(vector<int> device_ids) {
  int initcount = 0;
  Get().devices_.clear();
  int cuda_device_count = 0;

#ifdef USE_CUDA
  cudaGetDeviceCount(&cuda_device_count);
  for (int i = 0; i < cuda_device_count; ++i) {
    for (int j = 0; j < device_ids.size(); ++j) {
      if (device_ids[j] == i) {
        shared_ptr<Device> dev(
            new CudaDevice(i, initcount));
        Get().devices_.emplace_back(dev);
        dev->Init();
        ++initcount;
      }
    }
  }
#endif  // USE_CUDA

  // Initialize OpenCL devices
#ifdef USE_OPENCL
  int opencl_device_count = 0;

  typedef vector<viennacl::ocl::platform> platforms_type;
  platforms_type platforms = get_platforms_safe();

  vector<std::tuple<viennacl::ocl::platform, viennacl::ocl::device> >
                                                               platform_devices;

  // Loop through devices
  for (int platform_id = 0; platform_id < platforms.size();
      ++platform_id) {
    typedef vector<viennacl::ocl::device> devices_type;
    devices_type devices;
    try {
      devices = platforms[platform_id].devices(
      CL_DEVICE_TYPE_ALL);
    } catch (...) {
      LOG(INFO)<< "OpenCL platform: "
      << platforms[platform_id].info()
      << " does not work correctly.";
    }
    for (int device_id = 0; device_id < devices.size(); ++device_id) {
      platform_devices.push_back(
          std::make_tuple(platforms[platform_id], devices[device_id]));
      // Check if this device is really used
      for (int i = 0; i < device_ids.size(); ++i) {
        int device_id = device_ids[i];
        if (device_id == cuda_device_count + opencl_device_count) {
          // Setup actual context for this device
          viennacl::ocl::setup_context(device_id,
                            std::get<1>(platform_devices[opencl_device_count]));

          shared_ptr<Device> dev(new OclDevice(device_id, initcount));
          Get().devices_.emplace_back(dev);
          dev->Init();
          ++initcount;
        }
      }
      opencl_device_count++;
    }
  }

#endif  // USE_OPENCL

  if (Get().devices_.size() == 0) {
    LOG(FATAL) << "No device could be initialized." << std::endl;
  }

  Get().default_device_ = GetDevice(0, true);
  Caffe::SelectDevice(Get().default_device_);
}

void Caffe::SetDevice(const int device_id) {
  // Fix for compatibility to python and other interfaces that do not
  // know or call SetDevices directly
  if (Get().devices_.size() == 0) {
    // No device has been initialized so far
    Caffe::SetDevices(vector<int> { device_id });
  }

  Get().default_device_ = GetDevice(0, true);
#if defined(USE_OPENCL) && defined(USE_FFT)
  Get().cl_fft_state_.setup();
#endif
}

#ifdef USE_OPENCL
const cl_context& Caffe::GetOpenCLContext(const int id, bool list_id) {
  viennacl::ocl::context &ctx = viennacl::ocl::get_context(
         GetDevice(id, list_id)->id());
  return ctx.handle().get();
}

const cl_command_queue& Caffe::GetOpenCLQueue(const int id, bool list_id) {
  viennacl::ocl::context &ctx = viennacl::ocl::get_context(
         GetDevice(id, list_id)->id());
  return ctx.get_queue().handle().get();
}
#endif  // USE_OPENCL

// Should call explicitly for OCL + FFT
void Caffe::TeardownDevice(const int device_id) {
#if defined(USE_OPENCL) &&defined(USE_FFT)
  Get().cl_fft_state_.teardown();
#endif
}

// FIXME: OpenCL equivalent and device abstraction
void Caffe::DeviceQuery() {
  if (Get().default_device_->backend() == BACKEND_CUDA) {
#ifdef USE_CUDA
    cudaDeviceProp prop;
    int device;
    if (cudaSuccess != cudaGetDevice(&device)) {
      printf("No cuda device present.\n");
    } else {
      CUDA_CHECK(cudaGetDeviceProperties(&prop, device));
      LOG(INFO)<< "Device id:                     " << device;
      LOG(INFO)<< "Major revision number:         " << prop.major;
      LOG(INFO)<< "Minor revision number:         " << prop.minor;
      LOG(INFO)<< "Name:                          " << prop.name;
      LOG(INFO)<< "Total global memory:           " << prop.totalGlobalMem;
      LOG(INFO)<< "Total shared memory per block: " << prop.sharedMemPerBlock;
      LOG(INFO)<< "Total registers per block:     " << prop.regsPerBlock;
      LOG(INFO)<< "Warp size:                     " << prop.warpSize;
      LOG(INFO)<< "Maximum memory pitch:          " << prop.memPitch;
      LOG(INFO)<< "Maximum threads per block:     " << prop.maxThreadsPerBlock;
      LOG(INFO)<< "Maximum dimension of block:    "
      << prop.maxThreadsDim[0] << ", " << prop.maxThreadsDim[1] << ", "
      << prop.maxThreadsDim[2];
      LOG(INFO)<< "Maximum dimension of grid:     "
      << prop.maxGridSize[0] << ", " << prop.maxGridSize[1] << ", "
      << prop.maxGridSize[2];
      LOG(INFO)<< "Clock rate:                    " << prop.clockRate;
      LOG(INFO)<< "Total constant memory:         " << prop.totalConstMem;
      LOG(INFO)<< "Texture alignment:             " << prop.textureAlignment;
      LOG(INFO)<< "Concurrent copy and execution: "
      << (prop.deviceOverlap ? "Yes" : "No");
      LOG(INFO)<< "Number of multiprocessors:     " << prop.multiProcessorCount;
      LOG(INFO)<< "Kernel execution timeout:      "
      << (prop.kernelExecTimeoutEnabled ? "Yes" : "No");
    }
#endif  // USE_CUDA
  } else {
#ifdef USE_OPENCL
    // TODO: Complete OpenCL device information of current device
#endif  // USE_OPENCL
  }

  return;
}

bool Caffe::CheckDevice(const int device_id) {
  // TODO: Find some OpenCL equivalent here

  // This function checks the availability of GPU #device_id.
  // It attempts to create a context on the device by calling cudaFree(0).
  // cudaSetDevice() alone is not sufficient to check the availability.
  // It lazily records device_id, however, does not initialize a
  // context. So it does not know if the host thread has the permission to use
  // the device or not.
  //
  // In a shared environment where the devices are set to EXCLUSIVE_PROCESS
  // or EXCLUSIVE_THREAD mode, cudaSetDevice() returns cudaSuccess
  // even if the device is exclusively occupied by another process or thread.
  // Cuda operations that initialize the context are needed to check
  // the permission. cudaFree(0) is one of those with no side effect,
  // except the context initialization.
  bool r = true;
#ifdef USE_CUDA
  r =
      ((cudaSuccess == cudaSetDevice(device_id))
          && (cudaSuccess == cudaFree(0)));
  // reset any error that may have occurred.
  cudaGetLastError();
#endif  // USE_CUDA
  return r;
}

int Caffe::FindDevice(const int start_id) {
  // TODO: Find some OpenCL equivalent here

  // This function finds the first available device by checking devices with
  // ordinal from start_id to the highest available value. In the
  // EXCLUSIVE_PROCESS or EXCLUSIVE_THREAD mode, if it succeeds, it also
  // claims the device due to the initialization of the context.
#ifdef USE_CUDA
  int count = 0;
  CUDA_CHECK(cudaGetDeviceCount(&count));
  for (int i = start_id; i < count; i++) {
    if (CheckDevice(i)) return i;
  }
#endif  // USE_CUDA
  return -1;
}

class Caffe::RNG::Generator {
 public:
  Generator()
      : rng_(new caffe::rng_t(cluster_seedgen())) {
  }
  explicit Generator(size_t seed)
      : rng_(new caffe::rng_t(seed)) {
  }
  caffe::rng_t* rng() {
    return rng_.get();
  }
 private:
  shared_ptr<caffe::rng_t> rng_;
};

Caffe::RNG::RNG()
    : generator_(new Generator()) {
}

Caffe::RNG::RNG(size_t seed)
    : generator_(new Generator(seed)) {
}

Caffe::RNG& Caffe::RNG::operator=(const RNG& other) {
  generator_.reset(other.generator_.get());
  return *this;
}

void* Caffe::RNG::generator() {
  return static_cast<void*>(generator_->rng());
}

#endif  // CPU_ONLY

}  // namespace caffe

max_issues_repo_name: Miaomz/caffe-opencl

max_forks_repo_name: Miaomz/caffe-opencl


text:
#ifndef MELON_CORE_YAML_CONFIG_HPP_
#define MELON_CORE_YAML_CONFIG_HPP_

#include <melon/core/exception.hpp>
#include <melon/core/export.h>

#include <boost/log/trivial.hpp>
#include <yaml-cpp/yaml.h>

#include <string>
#include <unordered_map>
#include <vector>

namespace melon::core::yaml_conf
{

class MELON_CORE_EXPORT MissingParamsException : public melon::core::Exception
{
public:
    using melon::core::Exception::Exception;
    ~MissingParamsException() override;
};

class MELON_CORE_EXPORT UnknownParamsException : public melon::core::Exception
{
public:
    using melon::core::Exception::Exception;
    ~UnknownParamsException() override;
};

/**
 * Lists top-level keys in a yaml-cpp node, that are missing
 * @tparam It Iterator that satisfies C++ named requirement LegacyForwardIterator
 * @param[in] conf yaml-cpp node we want to check
 * @param[in] begin Iterator, specifying the beginning of a range of std::strings containing keys,
 * are expected then parsing this level
 * @param[in] end Iterator, specifying past-the-end of a range of std::strings containing keys,
 * are expected then parsing this level
 * @return A list of missing keys
 **/
template <typename It>
std::vector<std::string> check_missing_params(const YAML::Node& conf, It begin, It end)
{
    std::vector<std::string> res;
    for (It it = begin; it != end; ++it)
        if (!static_cast<bool>(conf[*it]))
            res.emplace_back(*it);
    return res;
}

/**
 * Lists top-level keys in a yaml-cpp node, that are not excepted
 * @tparam It Iterator that satisfies C++ named requirement LegacyForwardIterator
 * @param[in] conf yaml-cpp node we want to check
 * @param[in] begin Iterator, specifying the beginning of a range of std::strings containing keys,
 * not expected then parsing this level
 * @param[in] end Iterator, specifying past-the-end of a range of std::strings containing keys,
 * not expected then parsing this level
 * @return A list of extra keys
 **/
template <typename It>
std::vector<std::string> check_superfluous_params(const YAML::Node& conf, It begin, It end)
{
    std::vector<std::string> res;
    for (YAML::const_iterator it = conf.begin(); it != conf.end(); ++it)
    {
        auto key = it->first.as<std::string>();
        if (std::find(begin, end, key) == end)
            res.emplace_back(key);
    }
    return res;
}

using ParsedNodes = std::unordered_map<std::string, YAML::Node>;
struct KeyAbnormalities
{
    std::vector<std::string> missing;
    std::vector<std::string> superfluous;
};

/**
 * Parses the yaml-cpp map node with a list of expected keys into lower level nodes.
 * Lists missing and extra parameters
 * @tparam It Iterator that satisfies C++ named requirement LegacyForwardIterator
 * @param[in] parent_node yaml-cpp map node we want to parse
 * @param[in] begin Iterator, specifying the beginning of a range of std::strings containing keys,
 * expected then parsing this level
 * @param[in] end Iterator, specifying past-the-end of a range of std::strings containing keys,
 * expected then parsing this level
 * @param[in] check_for_superfluous Flag. If true, the returns returns a list of extra keys.
 * If false, returns an empty list
 * @return A pair of ParsedNodes and KeyAbnormalities:
 * ParsedNodes is a parsed map.
 * KeyAbnormalities is a list of missing keys and a list of extra keys
 **/
template <typename It>
std::pair<ParsedNodes, KeyAbnormalities>
parse_one_level_down(const YAML::Node& parent_node,
                     It begin,
                     It end,
                     bool check_for_superfluous = true)
{
    std::unordered_map<std::string, YAML::Node> node_res;
    std::vector<std::string> missing_res, superfluous_res;
    if (check_for_superfluous)
        superfluous_res = check_superfluous_params(parent_node, begin, end);
    try
    {
        for (It it = begin; it != end; ++it)
        {
            if (!*parent_node[*it])
                missing_res.emplace_back(*it);
            else
                node_res.insert({*it, parent_node[*it]});
        }
    }
    catch (const YAML::ParserException& e)
    {
        BOOST_LOG_TRIVIAL(error) << "YAML parser error: " << e.what() << std::endl;
    }
    return {node_res, {missing_res, superfluous_res}};
}

}  // namespace melon::core::yaml_conf

#endif  // MELON_CORE_YAML_CONFIG_HPP_


text: #include <boost/mpl/aux_/preprocessed/bcc551/placeholders.hpp>


text:
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2019 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "rigid_alignment.h"
#include "polar_svd.h"
#include <Eigen/Sparse>
#include <Eigen/Cholesky>
#include <vector>
#include <iostream>

template <
  typename DerivedX,
  typename DerivedP,
  typename DerivedN,
  typename DerivedR,
  typename Derivedt
>
IGL_INLINE void igl::rigid_alignment(
  const Eigen::MatrixBase<DerivedX> & _X,
  const Eigen::MatrixBase<DerivedP> & P,
  const Eigen::MatrixBase<DerivedN> & N,
  Eigen::PlainObjectBase<DerivedR> & R,
  Eigen::PlainObjectBase<Derivedt> & t)
{
  typedef typename DerivedX::Scalar Scalar;
  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> MatrixXS;
  typedef Eigen::Matrix<Scalar,Eigen::Dynamic,1> VectorXS;
  typedef Eigen::Matrix<Scalar,3,3> Matrix3S;
  const int k = _X.rows();
  VectorXS Z = VectorXS::Zero(k,1);
  VectorXS I = VectorXS::Ones(k,1);

  DerivedX X = _X;
  R = DerivedR::Identity(3,3);
  t = Derivedt::Zero(1,3);
  // See gptoolbox, each iter could be O(1) instead of O(k)
  const int max_iters = 5;
  for(int iters = 0;iters<max_iters;iters++)
  {
    MatrixXS A(k*3,6);
    A <<
               Z, X.col(2),-X.col(1),I,Z,Z,
       -X.col(2),        Z, X.col(0),Z,I,Z,
        X.col(1),-X.col(0),        Z,Z,Z,I;
    VectorXS B(k*3,1);
    B<<
      P.col(0)-X.col(0),
      P.col(1)-X.col(1),
      P.col(2)-X.col(2);
    std::vector<Eigen::Triplet<Scalar> > NNIJV;
    for(int i = 0;i<k;i++)
    {
      for(int c = 0;c<3;c++)
      {
        NNIJV.emplace_back(i,i+k*c,N(i,c));
      }
    }
    Eigen::SparseMatrix<Scalar> NN(k,k*3);
    NN.setFromTriplets(NNIJV.begin(),NNIJV.end());
    A = (NN * A).eval();
    B = (NN * B).eval();
    VectorXS u = (A.transpose() * A).ldlt().solve(A.transpose() * B);
    Derivedt ti = u.tail(3).transpose();

    Matrix3S W;
    W<<
          0, u(2),-u(1),
      -u(2),    0, u(0),
       u(1),-u(0),    0;
    // strayed from a perfect rotation. Correct it.
    const double x = u.head(3).stableNorm();
    DerivedR Ri;
    if(x == 0)
    {
      Ri = DerivedR::Identity(3,3);
    }else
    {
      Ri =
        DerivedR::Identity(3,3) +
        sin(x)/x*W +
        (1.0-cos(x))/(x*x)*W*W;
    }

    R = (R*Ri).eval();
    t = (t*Ri + ti).eval();
    X = ((_X*R).rowwise()+t).eval();
  }
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
template void igl::rigid_alignment<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<double, 3, 3, 0, 3, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3> >(Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, 3, 3, 0, 3, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> >&);
#endif


text:
/*
 *
 *  Copyright 2013 Alan Race
 *
 *  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.
 *
 *
 */
/*
 * OBO.cpp
 *
 *  Created on: 31 Oct 2012
 *      Author: alan
 */

#include "OBO.h"
#include "helpers/trim.h"

#include <iostream>
#include <fstream>
#include <algorithm>

#include <cstdlib>

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

namespace ImzML {

	OBO::OBO()
	{

	}

	OBO::OBO(std::string filename) {
		parse(filename);
	}

	OBO::~OBO()
	{
		cleanup();
	}

	void OBO::cleanup() {
		formatVersion = "";
		data = "";
		savedBy = "";
		autogeneratedBy = "";
		defaultNamespace = "";

		remarks.clear();
		terms.clear();
		imports.clear();
	}

	void OBO::parse(std::string filename) {
		// Make sure that the OBO doesn't have any data in it already
		cleanup();

        boost::filesystem::path filePath = boost::filesystem::path(filename);
        boost::filesystem::path dir = filePath.parent_path();

		std::ifstream oboFile;

		oboFile.open(filename.c_str());

		if(!oboFile) {
            OBOFileNotFound fileNotFound(filename);

            throw fileNotFound;
			std::cout << "ERROR: Could not open " << filename << std::endl;
		}

		std::string line;
		boost::shared_ptr<ImzML::OBOTerm> currentTerm;

		bool processingTerm = false;

		while(getline(oboFile, line)) {
			// Process a line

			// Trim the string
			trim(line);

			if(line.compare("[Term]") == 0) {
				processingTerm = true;

				// ID is on the next line
				getline(oboFile, line);

				line = line.substr(line.find(':') + 1);

				// Trim the string
				trim(line);

				//terms[line].reset(new ImzML::OBOTerm());

				currentTerm = boost::shared_ptr<ImzML::OBOTerm>(new ImzML::OBOTerm());
				currentTerm->setID(line);

				if(terms.size() == 0) {
					ns = line.substr(0, line.find(':'));
				}

				int number = std::atoi(line.substr(line.find(':') + 1).c_str());

				terms.insert(std::make_pair(number, currentTerm));
			} else if(line.compare("[Typedef]") == 0) {
				processingTerm = false;

				// TODO: Do something with typedefs
			} else if(processingTerm) {
				currentTerm->parseLine(line);
			} else {
				// Header information, so extract the tag and the value
				std::string tag = line.substr(0, line.find(':'));
				std::string value = line.substr(line.find(':') + 1);

				// Trim both the tag and the value
				trim(tag);
				trim(value);

				if(tag.compare("import") == 0) {
                    //
                    boost::filesystem::path import = dir / value;

                    imports.push_back(boost::shared_ptr<OBO>(new OBO(import.string())));
				}
			}
		}

		oboFile.close();

		std::map<int, boost::shared_ptr<ImzML::OBOTerm> >::iterator mapIterator;

		// Save all parents in the current OBO to speed up access
//		for(std::vector< boost::shared_ptr<OBO> >::iterator iter = imports.begin(); iter < imports.end(); iter++) {
//			for(mapIterator = (*iter)->terms.begin(); mapIterator != (*iter)->terms.end(); mapIterator++) {
//				terms.insert(std::make_pair((*mapIterator).first, (*mapIterator).second));
//			}
//		}

		// Now all terms have been loaded in we can process the relationships
		// and set up the necessary pointers

		for(mapIterator = terms.begin(); mapIterator != terms.end(); ++mapIterator) {
			if(!mapIterator->second)
				continue;

			// Set up parent/child relationship (is_a)
			std::vector< std::string >::iterator termVectorIterator;

			for(termVectorIterator = mapIterator->second->is_a.begin(); termVectorIterator < mapIterator->second->is_a.end(); termVectorIterator++) {
				boost::shared_ptr<ImzML::OBOTerm> parentTerm = getTerm(*termVectorIterator);

				if(parentTerm) {
					parentTerm->addChild(mapIterator->second);
					mapIterator->second->addParent(parentTerm);
				}
			}

			// Set up parent/child relationship (part_of)
			for(termVectorIterator = mapIterator->second->part_of.begin(); termVectorIterator < mapIterator->second->part_of.end(); termVectorIterator++) {
				boost::shared_ptr<ImzML::OBOTerm> parentTerm = getTerm(*termVectorIterator);

				if(parentTerm) {
					parentTerm->addChild(mapIterator->second);
					mapIterator->second->addParent(parentTerm);
				}
			}

			// Set up units
			for(termVectorIterator = mapIterator->second->has_units.begin(); termVectorIterator < mapIterator->second->has_units.end(); termVectorIterator++) {
				boost::shared_ptr <ImzML::OBOTerm> unitTerm = getTerm(*termVectorIterator);

				if(unitTerm) {
					mapIterator->second->addUnit(unitTerm);
				}
			}
		}
	}

	boost::shared_ptr<ImzML::OBOTerm> OBO::getTerm(std::string id) {
		if(id.empty())
			return boost::shared_ptr<ImzML::OBOTerm>();

		std::string ns = id.substr(0, id.find(':'));
		int number = std::atoi(id.substr(id.find(':') + 1).c_str());

		return getTerm(ns, number);
	}

	boost::shared_ptr<ImzML::OBOTerm> OBO::getTerm(std::string ns, int id) {
		if(ns.compare(this->ns) == 0) {
			return terms[id];
		}

        for(imports_type::size_type i = 0; i < imports.size(); i++) {
			boost::shared_ptr<ImzML::OBOTerm> term = imports[i]->getTerm(ns, id);

			if(term)
				return term;
		}

		return boost::shared_ptr<ImzML::OBOTerm>();
	}

} /* namespace ImzML */

max_stars_repo_name: AlanRace/imzMLParser

max_issues_repo_name: AlanRace/imzMLParser

max_forks_repo_name: AlanRace/imzMLParser


text:
#include "map_loader.h"
#include "agents_loader.h"
#include "egraph_reader.h"
#include <lazycbs/mapf/mapf-solver.h>

#include <string>
#include <cstring>
#include <fstream>
#include <ctime>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <vector>
#include <cstdlib>
#include <cmath>
#include <utility>
#include <boost/program_options.hpp>
#include <boost/tokenizer.hpp>
#include <boost/format.hpp>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

namespace py = pybind11;

#ifndef EXTRA_PEN
#define EXTRA_PEN 0  /* Off by default. */
#endif

/* This flag controls early solver termination */
volatile static sig_atomic_t terminated = 0;

/* The signal handler just sets the flag. */
void catch_int (int sig) {
  terminated = 1;
  // signal (sig, catch_int);
}
void set_handlers(void) {
  signal(SIGINT, catch_int);
}
void clear_handlers(void) {
  signal(SIGINT, SIG_DFL);
}

using namespace boost::program_options;
using namespace std;

AgentsLoader read_movingai(std::string fname, int upto) {
  AgentsLoader al;

  string line;
  ifstream myfile(fname.c_str());

  if (myfile.is_open()) {
    boost::char_separator<char> sep("\t");
    /*
    tokenizer< char_separator<char> > tok(line, sep);
    tokenizer< char_separator<char> >::iterator beg=tok.begin();
    */
    std::getline(myfile,line); // Ditch the first line
    for (int i=0; i < upto; i++) {
      std::getline(myfile, line);
      boost::tokenizer< boost::char_separator<char> > col_tok(line, sep);
      boost::tokenizer< boost::char_separator<char> >::iterator c_beg=col_tok.begin();
      // EX: 64	brc202d.map	530	481	446	403	444	182	259.12489166
      ++c_beg; // Length
      ++c_beg; // Map
      ++c_beg; // Rows
      ++c_beg; // Cols

      // The maps have been padded, so 'real' cells are still indexed from one.
      int c_s = atoi((*c_beg).c_str())+1; ++c_beg;
      int r_s = atoi((*c_beg).c_str())+1; ++c_beg;
      int c_e = atoi((*c_beg).c_str())+1; ++c_beg;
      int r_e = atoi((*c_beg).c_str())+1; ++c_beg;

      al.addAgent(r_s, c_s, r_e, c_e);
    }
    myfile.close();
  }
  else
    cerr << "Agents file not found." << std::endl;
  return al;
}

/*
This function accepts the map path, scenario, agent count and constraints.

The constarints are in the form (agent, ((row1, column1), (row2, column2)), time, cost).

Null locations must have both row and column negative.

Null time must be negative

Null cost must be negative

Agent must be non-negative

If time is negative and at least one location is not nullish, Lazy CBS will return a path where the provided agent does not visit the given location(s).
*/
string init(string map, string scenario, int agentsCount, vector<tuple<int, tuple<tuple<int, int>, tuple<int, int>>, int ,int>> assumptions) {
  bool opt_makespan = false;
  std::clock_t start(std::clock());
  set_handlers();
  MapLoader ml = MapLoader(map);

  AgentsLoader al(agentsCount < INT_MAX ? read_movingai(scenario, agentsCount) : AgentsLoader(scenario));

  // read the egraph (egraph file, experience_weight, weigthedastar_weight)
  EgraphReader egr;
  mapf::MAPF_Solver mapf(ml, al, egr, 1e8);
  clear_handlers();
  bool okay = false;
  try {
    if(terminated)
      throw mapf::MAPF_Solver::SolveAborted {};

    // bool res = mapf.minimizeCost();
    okay = opt_makespan ? MAPF_MinMakespan(mapf) : MAPF_MinCost(mapf, assumptions);
    // bool res = MAPF_MinMakespan(mapf);
  } catch (mapf::MAPF_Solver::SolveAborted& s) {
    // fprintf(stderr, "%% Solve aborted.\n");
  }
  fprintf(stderr, "lazy-cbs ; %s ; %s ; %d ; %s ; %.02lf ; ", map.c_str(), scenario.c_str(), al.num_of_agents, okay ? "done" : "timeout", 1000.0 * (std::clock() - start) / CLOCKS_PER_SEC);
  mapf.printStats(stderr);
  if (okay) {
    std::ostringstream output;
    output << boost::format("Map: %s\n") % map;
    output << mapf.printPaths();
    return output.str();
  } else return "not found";
}

PYBIND11_MODULE(lazycbs, m) {
  m.doc() = "XMAPF + Lazy CBS engine";
  // string map, string scenario, int agent, tuple<int, int> locations, int* time, int* cost, bool forbidden
  m.def(
    "init",
    &init,
    "A function which initiates the pathfinding/explanation engine.",
    py::arg("map"),
    py::arg("scenario"),
    py::arg("agentsCount"),
    py::arg("assumptions"),
    py::return_value_policy::copy
  );
}

ext: cc


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

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

#include "runtime/planner_exec_env.h"
#include "util/global_flags.h"

DECLARE_string(hostname);
DECLARE_int32(planner_port);
DECLARE_string(storage_type);

namespace pegasus {

PlannerExecEnv* PlannerExecEnv::exec_env_ = nullptr;

PlannerExecEnv::PlannerExecEnv()
  : PlannerExecEnv(FLAGS_hostname, FLAGS_planner_port) {}

PlannerExecEnv::PlannerExecEnv(const std::string& hostname, int32_t planner_port)
  : worker_manager_(new WorkerManager()) {

  planner_grpc_hostname_ = hostname;
  planner_grpc_port_ = planner_port;

  exec_env_ = this;
}

Status PlannerExecEnv::Init() {
  RETURN_IF_ERROR(ExecEnv::Init());
  RETURN_IF_ERROR(worker_manager_->Init());

  return Status::OK();
}

std::shared_ptr<WorkerManager> PlannerExecEnv::get_worker_manager() {
  return worker_manager_;
}

std::string PlannerExecEnv::GetPlannerGrpcHost() {
  return planner_grpc_hostname_;
}

int32_t PlannerExecEnv::GetPlannerGrpcPort() {
  return planner_grpc_port_;
}

} // namespace pegasus

max_stars_repo_name: jerrychenhf/pegasus

max_issues_repo_name: jerrychenhf/pegasus

max_forks_repo_name: jerrychenhf/pegasus


text:
#include <sstream>
#include <boost/algorithm/string/join.hpp>

#include "MatchUtils.hpp"

bool Match::hasLabel(const match &m, const label &l)
{
  return Alm::hasLabel(m.first, l) || Alm::hasLabel(m.second, l);
}

bool Match::setHasMatch(const matchSet &ms, const match &ma)
{
  for (const match &m : ms) {
    if (m == ma)
      return true;
  }

  return false;
}

bool Match::empty(const match &m)
{
  return (m.first).empty();
}

std::string Match::toString(const match &m)
{
  std::stringstream res;

  res << "(";
  res << boost::algorithm::join(m.first, ",");
  res << " <> ";
  res << boost::algorithm::join(m.second, ",");
  res << ")";

  return res.str();
}

std::string Match::setToString(const matchSet &ms)
{
  std::stringstream res;
  matchSet::const_iterator it;

  if (ms.empty()) {
    res << "{}";
    return res.str();
  }

  res << "{";

  for (it = ms.begin(); it != ms.end() - 1; ++it) {
    res << Match::toString(*it);
    res << ",";
  }

  res << Match::toString(*it);
  res << "}";

  return res.str();
}

#include <boost/tokenizer.hpp>

match Match::getMatch(const alignment &alm, const label &l1, const label &l2)
{
  match m;
  matchSet res;

  typedef boost::tokenizer<boost::char_separator<char>> tokenizer;

  boost::char_separator<char> sep{" | "};
  tokenizer tok{l2, sep};

  for (const alignmentPair &p : alm) {
    if ((Alm::hasLabel(p.first, l1)) && (Alm::hasLabel(p.second, l2)))
      res.push_back(p);
  }

  if (res.empty())
    return m;

  return res[0];
}

matchSet Match::getMatchSet(const alignment &alm, const matchSet &ms,
                                          const label &l1, const label &l2)
{
  matchSet res;

  match m = Match::getMatch(alm, l1, l2);

  if (Match::empty(m))
    return res;

  if (!Match::setHasMatch(ms, m))
    res.push_back(m);

  return res;
}

matchSet Match::getMatchSet2(const matchSet &ms, const label &l)
{
  matchSet res;

  for (const match &m : ms) {
    if (Match::hasLabel(m, l))
      res.push_back(m);
  }

  return res;
}

void Match::print(const match &m)
{
  Alm::printGroup(m.first);
  std::cout << "\t<> ";
  Alm::printGroup(m.second);

  std::cout << std::endl;

  return;
}

void Match::printSet(const matchSet &ms)
{
  for (const match &m : ms) {
    std::cout << "  ";
    Match::print(m);
  }

  return;
}

max_stars_repo_name: flange/esp

max_issues_repo_name: flange/esp

max_forks_repo_name: flange/esp


text:
/* ---------------------------------------------------------------------------
 *
 * Autonomous Navigation and Perception Lab (ANPL),
 * Technion, Israel Institute of Technology,
 * Faculty of Aerospace Engineering,
 * Haifa, Israel, 32000
 * All Rights Reserved
 *
 * See LICENSE for the license information
 *
 * -------------------------------------------------------------------------- */
/**
 * @file: eigen_utils.hpp
 * @brief:
 * @author: Andrej Kitanov
 *
 */

#ifndef PLANNER_EIGEN_UTILS_HPP
#define PLANNER_EIGEN_UTILS_HPP

#include <Eigen/Dense>
#include <Eigen/Sparse>

// This function performs row or column sum of a sparse matrix X and returns a result in the row vector v
template <typename T, typename S> inline void sumAlongDim(
        const Eigen::SparseMatrix<T>& X,
        const int dim,
        Eigen::Matrix<S, Eigen::Dynamic, 1>& v)
{
    // Get size of input
    int m = X.rows();
    int n = X.cols();
    // resize output
    if(dim==1)
    {
        v = Eigen::Matrix<S, Eigen::Dynamic, 1>(n);
    }else
    {
        v = Eigen::Matrix<S, Eigen::Dynamic, 1>(m);
    }

    v.setZero();

    // Iterate over outside
    for(int k=0; k<X.outerSize(); ++k)
    {
        // Iterate over inside
        for(typename Eigen::SparseMatrix<T>::InnerIterator it(X,k); it; ++it)
        {
            if(dim == 1)
            {
                v[it.col()] += it.value();
            }else
            {
                v[it.row()] += it.value();
            }
        }
    }
}

/*void example () {
    SparseMatrix<double> mat(5,5);
    for (int k = 0; k < mat.outerSize(); ++k)
        for (SparseMatrix<double>::InnerIterator it(mat, k); it; ++it) {
            it.value();
            it.row();   // row index
            it.col();   // col index (here it is equal to k)
            it.index(); // inner index, here it is equal to it.row()
        }
}*/

template<typename MatrixType>
void saveMatrixToFile(const char *filename, const MatrixType& m)
{
    ofstream f(filename, ios::binary);
    typename MatrixType::Index rows, cols;
    rows = m.rows();
    cols = m.cols();
    f.write((char *)&rows, sizeof(m.rows()));
    f.write((char *)&cols, sizeof(m.cols()));
    f.write((const char *)(m.data()), sizeof(typename MatrixType::Scalar)*m.rows()*m.cols());
    f.close();
}

template<typename MatrixType>
void loadMatrixFromFile(const char *filename, MatrixType& m)
{
    typename MatrixType::Index rows, cols;
    ifstream f(filename, ios::binary);
    f.read((char *)&rows, sizeof(rows));
    f.read((char *)&cols, sizeof(cols));
    m.resize(rows, cols);
    typename MatrixType::Scalar* p = m.data();
    f.read((char *)p, sizeof(typename MatrixType::Scalar)*rows*cols);
    if (f.bad())
        throw "Error reading matrix";
    f.close();
}

#include <opencv2/core/core.hpp>
template<typename _Tp, int _rows, int _cols, int _options, int _maxRows, int _maxCols>
void eigen2cv(const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols> &src, cv::Mat &dst) {
    if (!(src.Flags & Eigen::RowMajorBit))
    {
        cv::Mat _src(src.cols(), src.rows(), cv::DataType<_Tp>::type,
                     (void*)src.data(), src.stride() * sizeof(_Tp));
        cv::transpose(_src, dst);
    }
    else
    {
        cv::Mat _src(src.rows(), src.cols(), cv::DataType<_Tp>::type,
                     (void*)src.data(), src.stride() * sizeof(_Tp));
        _src.copyTo(dst);
    }
}

#endif //PLANNER_EIGEN_UTILS_HPP


text:
/* Copyright 2013-present Barefoot Networks, Inc.
 *
 * 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.
 */

/*
 * Antonin Bas (antonin@barefootnetworks.com)
 *
 */

#include <bm/bm_sim/target_parser.h>

#include <boost/program_options.hpp>

#include <string>
#include <vector>
#include <memory>
#include <unordered_set>
#include <ostream>

namespace po = boost::program_options;

namespace bm {

class TargetParserBasicStore {
  using ReturnCode = TargetParserBasic::ReturnCode;

 public:
  template <typename T>
  ReturnCode add_option(const std::string &name, const std::string &help_str) {
    if (has_option(name)) return ReturnCode::DUPLICATE_OPTION;
    description.add_options()(name.c_str(), po::value<T>(), help_str.c_str());
    option_added(name);
    return ReturnCode::SUCCESS;
  }

  int parse(const std::vector<std::string> &more_options,
            std::ostream *errstream) {
    po::command_line_parser parser(more_options);
    try {
      po::store(parser.options(description).run(), vm);
      po::notify(vm);
    }
    catch (const std::exception &e) {
      if (errstream) (*errstream) << e.what() << "\n";
      return 1;
    }
    return 0;
  }

  template <typename T>
  ReturnCode get_option(const std::string &name, T *v) const {
    if (!has_option(name)) return ReturnCode::INVALID_OPTION_NAME;
    if (!vm.count(name)) return ReturnCode::OPTION_NOT_PROVIDED;
    try {
      *v = vm.at(name).as<T>();
      return ReturnCode::SUCCESS;
    }
    catch (...) {
      return ReturnCode::INVALID_OPTION_TYPE;
    }
  }

  void get_description(std::ostream *outstream) const {
    (*outstream) << description;
  }

 private:
  bool has_option(const std::string &name) const {
    return option_names.find(name) != option_names.end();
  }

  void option_added(const std::string &name) {
    option_names.insert(name);
  }

  // could not get boost to throw a duplicate_option_error in case of duplicate
  // option names, so I'm using a set to keep track
  std::unordered_set<std::string> option_names;
  po::options_description description{"Target options"};
  po::variables_map vm;
};

template <>
TargetParserBasic::ReturnCode
TargetParserBasicStore::add_option<bool>(const std::string &name,
                                         const std::string &help_str) {
  if (has_option(name)) return ReturnCode::DUPLICATE_OPTION;
  description.add_options()(name.c_str(), help_str.c_str());
  option_added(name);
  return ReturnCode::SUCCESS;
}

template <>
TargetParserBasic::ReturnCode
TargetParserBasicStore::get_option<bool>(const std::string &name,
                                         bool *v) const {
  if (!has_option(name)) return ReturnCode::INVALID_OPTION_NAME;
  *v = static_cast<bool>(vm.count(name));
  return ReturnCode::SUCCESS;
}

TargetParserBasic::TargetParserBasic()
    : var_store(new TargetParserBasicStore()) { }

TargetParserBasic::~TargetParserBasic() { }

int
TargetParserBasic::parse(const std::vector<std::string> &more_options,
                         std::ostream *errstream) {
  return var_store->parse(more_options, errstream);
}

void
TargetParserBasic::help_msg(std::ostream *outstream) const {
  var_store->get_description(outstream);
}

TargetParserBasic::ReturnCode
TargetParserBasic::add_string_option(const std::string &name,
                                     const std::string &help_str) {
  return var_store->add_option<std::string>(name, help_str);
}

TargetParserBasic::ReturnCode
TargetParserBasic::add_int_option(const std::string &name,
                                  const std::string &help_str) {
  return var_store->add_option<int>(name, help_str);
}

TargetParserBasic::ReturnCode
TargetParserBasic::add_uint_option(const std::string &name,
                                  const std::string &help_str) {
  return var_store->add_option<unsigned>(name, help_str);
}

TargetParserBasic::ReturnCode
TargetParserBasic::add_flag_option(const std::string &name,
                                   const std::string &help_str) {
  return var_store->add_option<bool>(name, help_str);
}

TargetParserBasic::ReturnCode
TargetParserBasic::get_string_option(const std::string &name,
                                     std::string *v) const {
  return var_store->get_option<std::string>(name, v);
}

TargetParserBasic::ReturnCode
TargetParserBasic::get_int_option(const std::string &name, int *v) const {
  return var_store->get_option<int>(name, v);
}

TargetParserBasic::ReturnCode
TargetParserBasic::get_uint_option(const std::string &name, unsigned *v) const {
  return var_store->get_option<unsigned>(name, v);
}

TargetParserBasic::ReturnCode
TargetParserBasic::get_flag_option(const std::string &name, bool *v) const {
  return var_store->get_option<bool>(name, v);
}

}  // namespace bm

max_stars_repo_name: joelwanner/behavioral-model

max_issues_repo_name: joelwanner/behavioral-model

max_forks_repo_name: joelwanner/behavioral-model


text:
#define BOOST_TEST_MODULE test_onecellcadbug

#include <optional>

#include <boost/test/unit_test.hpp>

#include <smtrat-common/smtrat-common.h>
#include <smtrat-mcsat/smtrat-mcsat.h>

#include <carl/core/MultivariatePolynomial.h>
#include <carl/core/Variable.h>
#include <carl/formula/model/evaluation/ModelEvaluation.h>

#include <smtrat-mcsat/explanations/onecellcad/Explanation.h>

using namespace smtrat;

BOOST_AUTO_TEST_CASE(OneCellCadBug) {
	// Variable x cannot be assigned for x^2 + x^4 + b*x^3 <= 0 , x != 0 under b -> -1

	carl::Variable x = carl::freshRealVariable("x");
	carl::Variable b = carl::freshRealVariable("b");
  carl::Variables vars({x,b});

	FormulaT f1(ConstraintT((Poly(x)*x) + (Poly(x)*x*x*x) + (Poly(b)*x*x*x), carl::Relation::LEQ));
  FormulaT f2(ConstraintT(x, carl::Relation::NEQ));

	// generate explanation
  mcsat::Bookkeeping bookkeeping;
  bookkeeping.updateVariables(vars);
  bookkeeping.pushConstraint(f1);
  bookkeeping.pushConstraint(f2);
  bookkeeping.pushAssignment(b, Rational(-1), FormulaT(carl::FormulaType::TRUE));
  ::smtrat::mcsat::onecellcad::Explanation expl;
  auto explanation = expl(bookkeeping, x, FormulasT({f1,f2}));

  // proof that satisfying assignment exist
  Model model;
	model.assign(b, Rational(-5));
  model.assign(x, Rational(1));

  auto res = carl::model::evaluate(f1, model);
	BOOST_CHECK(res.isBool() && res.asBool());
  auto res1 = carl::model::evaluate(f2, model);
	BOOST_CHECK(res1.isBool() && res1.asBool());

  auto res2 = carl::model::evaluate(boost::get<FormulaT>(*explanation), model);
  BOOST_CHECK(res2.isBool());
  BOOST_CHECK(res2.asBool());
}

max_stars_repo_name: modass/smtrat

max_issues_repo_name: modass/smtrat

max_forks_repo_name: modass/smtrat


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

#include <nt2/core/functions/inner_fold.hpp>
#include <nt2/core/functions/details/fold_step.hpp>
#include <boost/fusion/include/pop_front.hpp>
#include <nt2/include/functions/scalar/numel.hpp>
#include <nt2/include/functor.hpp>

namespace nt2 { namespace ext
{

  //============================================================================
  // General inner_fold
  //============================================================================
  BOOST_DISPATCH_IMPLEMENT  ( inner_fold_, tag::cpu_
                            , (Out)(In)(Neutral)(Bop)(Uop)
                            , ((ast_< Out, nt2::container::domain>))
                              ((ast_< In, nt2::container::domain>))
                              (unspecified_<Neutral>)
                              (unspecified_<Bop>)
                              (unspecified_<Uop>)
                            )
  {
    typedef void                                                              result_type;
    typedef typename In::extent_type                                          extent_type;
    typedef typename Out::value_type                                          value_type;

    BOOST_FORCEINLINE result_type
    operator()(Out& out, In& in, Neutral const& neutral, Bop const& bop, Uop const&) const
    {
      extent_type ext = in.extent();
      std::size_t obound = nt2::numel(boost::fusion::pop_front(ext));
      std::size_t ibound  = boost::fusion::at_c<0>(ext);

      for(std::size_t j = 0, k = 0; j < obound; ++j, k+=ibound)
      {
          value_type s_out = details::fold_step(
             neutral(nt2::meta::as_<value_type>()), in, bop, k, ibound, 1
             );

          nt2::run(out, j, s_out);
      }
    }
  };

  } }

#endif


text:
// Copyright (C) 2018 Stephane Raux. Distributed under the MIT license.

#include "client.hpp"
#include "protocol.hpp"
#include "service.hpp"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/system/error_code.hpp>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <memory>
#include <nlohmann/json.hpp>
#include <string>
#include <utility>

using json = nlohmann::json;

namespace {
    class ServiceHandler: public std::enable_shared_from_this<ServiceHandler> {
    private:
        struct Priv {};

    public:
        explicit ServiceHandler(boost::asio::ip::tcp::socket socket,
            ServiceConfiguration config, Priv
        ):
            config(std::move(config)),
            socket(std::move(socket)),
            http_version(11),
            attempts(0)
        {}

        static std::shared_ptr<ServiceHandler> make(
            boost::asio::ip::tcp::socket socket, ServiceConfiguration config)
        {
            return std::make_shared<ServiceHandler>(std::move(socket),
                std::move(config), Priv {});
        }

        void process() {
            auto this_ = shared_from_this();
            boost::beast::http::async_read(socket, buffer, request,
                [this_] (boost::system::error_code ec, std::size_t) {
                    this_->on_request(ec);
                }
            );
        }

    private:
        void finalize_response(Response& response) {
            response.set(boost::beast::http::field::content_type,
                "application/json; charset=utf-8");
        }

        Response make_error_response(const Error& error) {
            json j = {
                {"Err", {
                    {"kind", to_string(error.kind)},
                    {"cause", {error.cause}}
                }}
            };
            boost::beast::http::status status = boost::beast::http::status::ok;
            switch (error.kind) {
            case ErrorKind::BackendFailure:
                break;
            case ErrorKind::BadRequest:
                status = boost::beast::http::status::bad_request;
                break;
            case ErrorKind::LocationNotFound:
                break;
            }
            Response resp(status, http_version, j.dump(2));
            finalize_response(resp);
            return resp;
        }

        Response make_success_response(const Coordinates& coords) {
            json j = {
                {"Ok", {
                    {"latitude", coords.latitude},
                    {"longitude", coords.longitude}
                }}
            };
            Response resp(boost::beast::http::status::ok, http_version,
                j.dump(2));
            finalize_response(resp);
            return resp;
        }

        void on_coordinates(ProtocolResult result) {
            if (std::get_if<Error>(&result)) {
                ++attempts;
                request_coordinates(location);
                return;
            }
            response = make_success_response(std::get<Coordinates>(result));
            respond();
        }

        void on_request(boost::system::error_code ec) {
            if (ec) {return;}
            http_version = request.version();
            const char prefix[] = "/geocode?location=";
            const auto& target = request.target();
            if (request.method() != boost::beast::http::verb::get
                || !boost::starts_with(target, prefix))
            {
                respond_with_error(Error {ErrorKind::BadRequest, ""});
                return;
            }
            location = target.substr(std::size(prefix) - 1).to_string();
            request_coordinates(location);
        }

        void on_responded(boost::system::error_code ec, std::size_t) {
            socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
        }

        void request_coordinates(const std::string& location) {
            if (attempts >= config.protocols.size()) {
                std::string cause;
                if (config.protocols.empty()) {
                    cause = "No backend service configured";
                }
                respond_with_error(Error {ErrorKind::LocationNotFound,
                    std::move(cause)});
                return;
            }
            std::visit([location, this] (auto proto) {
                auto this_ = shared_from_this();
                async_find_lat_long(socket.get_io_context(), proto, location,
                    std::bind(&ServiceHandler::on_coordinates, this_,
                    std::placeholders::_1));
            }, config.protocols[attempts]);
        }

        void respond() {
            auto this_ = shared_from_this();
            boost::beast::http::async_write(socket, response, std::bind(
                &ServiceHandler::on_responded, this_, std::placeholders::_1,
                std::placeholders::_2));
        }

        void respond_with_error(const Error& e) {
            response = make_error_response(e);
            respond();
        }

    private:
        ServiceConfiguration config;
        boost::asio::ip::tcp::socket socket;
        boost::beast::flat_buffer buffer;
        Request request;
        Response response;
        unsigned int http_version;
        unsigned int attempts;
        std::string location;
    };

    class Service: public std::enable_shared_from_this<Service> {
    private:
        struct Priv {};

    public:
        explicit Service(boost::asio::io_context& ioc,
            const ServiceConfiguration& config, Priv
        ):
            config(config),
            acceptor(ioc, config.endpoint)
        {}

        static std::shared_ptr<Service> make(boost::asio::io_context& ioc,
            const ServiceConfiguration& config)
        {
            return std::make_shared<Service>(ioc, config, Priv {});
        }

        void run() {accept();}

    private:
        void accept() {
            auto this_ = shared_from_this();
            auto cfg = config;
            acceptor.async_accept([cfg, this_] (boost::system::error_code ec,
                boost::asio::ip::tcp::socket socket)
            {
                if (!ec) {
                    auto handler = ServiceHandler::make(std::move(socket), cfg);
                    handler->process();
                }
                this_->accept();
            });
        }

    private:
        ServiceConfiguration config;
        boost::asio::ip::tcp::acceptor acceptor;
    };
}

ServiceConfiguration load_service_config(const boost::filesystem::path& path) {
    ServiceConfiguration conf {
        boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 8080),
        {}
    };
    boost::filesystem::ifstream is(path);
    json j;
    is >> j;
    auto sock_addr_iter = j.find("sock_addr");
    if (sock_addr_iter != j.end()) {
        auto sock_addr = sock_addr_iter->get<std::string>();
        auto sep = sock_addr.find_last_of(':');
        if (sep == std::string::npos) {
            throw std::invalid_argument("Invalid address. Missing colon "
                "and port.");
        }
        auto addr = boost::asio::ip::make_address(sock_addr.substr(0, sep));
        auto port = static_cast<unsigned short>(std::atoi(sock_addr.substr(
            sep + 1).c_str()));
        conf.endpoint.address(addr);
        conf.endpoint.port(port);
    }
    auto finder = j.find("finder");
    if (finder != j.end()) {
        auto protocols = finder->find("protocols");
        if (protocols != finder->end()) {
            for (auto&& protocol: *protocols) {
                if (auto p = protocol.find("Here"); p != protocol.end()) {
                    auto app_id = p->at("app_id").get<std::string>();
                    auto app_code = p->at("app_code").get<std::string>();
                    ProtocolHere proto(std::move(app_id), std::move(app_code));
                    conf.protocols.push_back(std::move(proto));
                } else if (auto p = protocol.find("MapQuest");
                    p != protocol.end())
                {
                    auto key = p->at("key").get<std::string>();
                    ProtocolMapQuest proto(std::move(key));
                    conf.protocols.push_back(std::move(proto));
                }
            }
        }
    }
    return conf;
}

void run_service(boost::asio::io_context& io_ctx,
    const ServiceConfiguration& config)
{
    auto service = Service::make(io_ctx, config);
    service->run();
}

max_stars_repo_name: stephaneyfx/geocode-cpp

max_issues_repo_name: stephaneyfx/geocode-cpp

max_forks_repo_name: stephaneyfx/geocode-cpp


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

#include "helper.hpp"

#include <data_storage/arbstorage.hpp>
#include <data_storage/readwritetransaction.hpp>
#include <data_storage/storageresult.hpp>
#include <data_storage/value/value.hpp>

#include <avm/machinestate/datastack.hpp>

#include <rocksdb/status.h>

#include <catch2/catch.hpp>

#include <boost/filesystem.hpp>

std::string dbpath =
    boost::filesystem::current_path().generic_string() + "/machineDb";

void checkGetTupleResult(const DbResult<value>& res,
                         uint256_t expected_count,
                         uint256_t expected_hash) {
    REQUIRE(std::holds_alternative<CountedData<value>>(res));
    REQUIRE(
        std::holds_alternative<Tuple>(std::get<CountedData<value>>(res).data));
    REQUIRE(std::get<CountedData<value>>(res).reference_count ==
            expected_count);
    REQUIRE(hash_value(std::get<CountedData<value>>(res).data) ==
            expected_hash);
}

void initializeDatastack(const ReadTransaction& transaction,
                         uint256_t tuple_hash,
                         uint256_t expected_hash,
                         uint64_t expected_size) {
    ValueCache value_cache{1, 0};
    auto results = ::getValue(transaction, tuple_hash, value_cache);
    REQUIRE(std::holds_alternative<CountedData<value>>(results));
    REQUIRE(std::holds_alternative<Tuple>(
        std::get<CountedData<value>>(results).data));

    Datastack data_stack(
        std::get<Tuple>(std::get<CountedData<value>>(results).data));

    REQUIRE(data_stack.hash() == expected_hash);
    REQUIRE(data_stack.stacksize() == expected_size);
}

void saveDataStack(const Datastack& data_stack) {
    ArbStorage storage(dbpath);
    std::vector<CodePoint> code;
    auto transaction = storage.makeReadWriteTransaction();

    auto tuple_ret = data_stack.getTupleRepresentation();
    auto results = saveValue(*transaction, tuple_ret);

    REQUIRE(transaction->commit().ok());
    REQUIRE(results.status.ok());
    REQUIRE(results.reference_count == 1);
}

void saveDataStackTwice(const Datastack& data_stack) {
    ArbStorage storage(dbpath);
    std::vector<CodePoint> code;
    auto transaction = storage.makeReadWriteTransaction();

    auto tuple_ret = data_stack.getTupleRepresentation();
    auto results = saveValue(*transaction, tuple_ret);
    auto results2 = saveValue(*transaction, tuple_ret);

    REQUIRE(transaction->commit().ok());
    REQUIRE(results2.status.ok());
    REQUIRE(results2.reference_count == 2);
}

void saveAndGetDataStack(ReadWriteTransaction& transaction,
                         const Datastack& data_stack,
                         uint256_t expected_hash) {
    auto tuple_ret = data_stack.getTupleRepresentation();
    auto results = saveValue(transaction, tuple_ret);
    REQUIRE(results.status.ok());
    transaction.commit();

    ValueCache value_cache{1, 0};
    auto get_results = getValue(transaction, expected_hash, value_cache);
    checkGetTupleResult(get_results, 1, expected_hash);
}

void saveTwiceAndGetDataStack(ReadWriteTransaction& transaction,
                              const Datastack& data_stack,
                              uint256_t expected_hash) {
    auto tuple_ret = data_stack.getTupleRepresentation();
    auto results = saveValue(transaction, tuple_ret);
    auto results2 = saveValue(transaction, tuple_ret);
    REQUIRE(results.status.ok());
    REQUIRE(results2.status.ok());
    transaction.commit();

    ValueCache value_cache{1, 0};
    auto get_results = getValue(transaction, expected_hash, value_cache);
    checkGetTupleResult(get_results, 2, expected_hash);
}

TEST_CASE("Initialize datastack") {
    DBDeleter deleter;
    ArbStorage storage(dbpath);
    auto transaction = storage.makeReadWriteTransaction();
    Datastack data_stack;

    SECTION("default") {
        auto tuple_ret = data_stack.getTupleRepresentation();
        auto results = saveValue(*transaction, tuple_ret);
        transaction->commit();
        initializeDatastack(*transaction, hash(tuple_ret), data_stack.hash(),
                            0);
    }
    SECTION("push empty tuple") {
        Tuple tuple;
        data_stack.push(tuple);
        auto tuple_ret = data_stack.getTupleRepresentation();
        auto results = saveValue(*transaction, tuple_ret);
        transaction->commit();
        initializeDatastack(*transaction, hash(tuple_ret), data_stack.hash(),
                            1);
    }
    SECTION("push num, tuple") {
        CodePointStub code_point_stub{{0, 0}, 3452345};
        uint256_t num = 1;
        auto tuple = Tuple::createTuple(code_point_stub);
        data_stack.push(num);
        data_stack.push(tuple);
        auto tuple_ret = data_stack.getTupleRepresentation();
        auto results = saveValue(*transaction, tuple_ret);
        transaction->commit();
        initializeDatastack(*transaction, hash(tuple_ret), data_stack.hash(),
                            2);
    }
    SECTION("push codepoint, tuple") {
        CodePointStub code_point_stub{{0, 0}, 3452345};
        uint256_t num = 1;
        auto tuple = Tuple::createTuple(num);
        data_stack.push(code_point_stub);
        data_stack.push(tuple);
        auto tuple_ret = data_stack.getTupleRepresentation();
        auto results = saveValue(*transaction, tuple_ret);
        transaction->commit();
        initializeDatastack(*transaction, hash(tuple_ret), data_stack.hash(),
                            2);
    }
}

TEST_CASE("Save datastack") {
    DBDeleter deleter;
    Datastack datastack;

    SECTION("save empty") { saveDataStack(datastack); }
    SECTION("save empty twice") { saveDataStackTwice(datastack); }
    SECTION("save with values") {
        uint256_t num = 1;
        uint256_t intVal = 5435;
        auto tuple = Tuple::createTuple(intVal);
        datastack.push(num);
        datastack.push(tuple);
        Tuple tup0;
        auto tup1 = Tuple(num, tup0);
        auto tup_rep = Tuple(tuple, tup1);
        saveDataStack(datastack);
    }
    SECTION("save with values, twice") {
        uint256_t num = 1;
        uint256_t intVal = 5435;
        auto tuple = Tuple::createTuple(intVal);
        datastack.push(num);
        datastack.push(tuple);
        Tuple tup0;
        auto tup1 = Tuple(num, tup0);
        auto tup_rep = Tuple(tuple, tup1);
        saveDataStackTwice(datastack);
    }
}

TEST_CASE("Save and get datastack") {
    DBDeleter deleter;
    ArbStorage storage(dbpath);
    Datastack datastack;

    SECTION("save datastack and get") {
        uint256_t intVal = 5435;
        auto transaction = storage.makeReadWriteTransaction();
        uint256_t num = 1;
        auto tuple = Tuple::createTuple(intVal);
        datastack.push(num);
        datastack.push(tuple);
        Tuple tup0;
        auto tup1 = Tuple(num, tup0);
        auto tup_rep = Tuple(tuple, tup1);
        saveAndGetDataStack(*transaction, datastack, hash(tup_rep));
    }
    SECTION("save datastack twice and get") {
        uint256_t intVal = 5435;
        auto transaction = storage.makeReadWriteTransaction();
        uint256_t num = 1;
        auto tuple = Tuple::createTuple(intVal);
        datastack.push(num);
        datastack.push(tuple);
        Tuple tup0;
        auto tup1 = Tuple(num, tup0);
        auto tup_rep = Tuple(tuple, tup1);
        saveTwiceAndGetDataStack(*transaction, datastack, hash(tup_rep));
    }
}

TEST_CASE("Initial VM Values") {
    SECTION("parse invalid path") {
        CHECK_THROWS(loadExecutable("nonexistent/path"));
    }
    boost::filesystem::remove_all(dbpath);
}

max_issues_repo_name: dionyziz/arbitrum

max_forks_repo_name: dionyziz/arbitrum