text:
#include <algorithm>
#include <iostream>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <mutex>
using namespace std;

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/ip/address.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

#include <redisclient/redisasyncclient.h>

#include "ipfspump.hpp"

void createIpfsPubSubChannel();

IpfsTextPump::IpfsTextPump()
{
  auto uuid = boost::uuids::random_generator()();
  ws_ = "/tmp/wai.native/" + boost::lexical_cast<std::string>(uuid);
  string cmd = "mkdir -p ";
        cmd += ws_;
  ::system(cmd.c_str());
  createIpfsPubSubChannel();
}

#include <thread>

const string strConstRelaySubChannelName("wai.relay.ipfs.to.redis");
const string strConstRelayPubChannelName("wai.relay.redis.to.ipfs");

class RedisRelayClient
{
public:
    RedisRelayClient(boost::asio::io_service &ioService)
        : ioService(ioService)
    {}
    void onMessage(const std::vector<char> &buf);
private:
    boost::asio::io_service &ioService;
};

#include <nlohmann/json.hpp>
using json = nlohmann::json;

static string gBlockCID = "";
static string gTask = "";
static mutex gBlockMutex;

void RedisRelayClient::onMessage(const std::vector<char> &buf) {
  //string msg(buf.begin(),buf.end());
  //DUMP_VAR(msg);
  json jsonMsg = json::parse(buf.begin(),buf.end());
  DUMP_VAR(jsonMsg);
  auto jsonTask = jsonMsg["task"];
  DUMP_VAR(jsonTask);
  if(jsonTask.is_string()){
    auto task = jsonTask.get<std::string>();
    if(task == "wator.ipfs.ostrich.app") {
      DUMP_VAR(task);
      {
        std::lock_guard<std::mutex> guard(gBlockMutex);
        gTask = task;
      }
      auto jsonBlock = jsonMsg["block"];
      if(jsonBlock.is_string()){
        auto block = jsonBlock.get<std::string>();
        DUMP_VAR(block);
        if(boost::starts_with(block,"Qm")) {
          std::lock_guard<std::mutex> guard(gBlockMutex);
          gBlockCID = block;
          DUMP_VAR(gBlockCID);
        }
      }
    }
  }
}

static std::weak_ptr<redisclient::RedisAsyncClient> gPublishRef;

void ipfs_redis_relay_main(void) {
  boost::asio::io_service ioService;
  boost::asio::ip::tcp::resolver resolver(ioService);
  boost::asio::ip::tcp::resolver::query query("127.0.0.1", "6379");
  boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
  boost::asio::ip::tcp::endpoint endpoint = iter->endpoint();
  DUMP_VAR(endpoint);

  auto publish = std::make_shared<redisclient::RedisAsyncClient>(ioService);
  DUMP_VAR(publish);
  publish->connect(endpoint, [&](boost::system::error_code ec) {
    if(ec) {
      DUMP_VAR(ec);
    } else {
      DUMP_VAR(ec);
      gPublishRef = publish;
      DUMP_VAR(gPublishRef.expired());
    }
  });

  redisclient::RedisAsyncClient subscriber(ioService);
  RedisRelayClient client(ioService);
  subscriber.connect(endpoint, [&](boost::system::error_code ec){
    if(ec) {
      DUMP_VAR(ec);
    } else {
      DUMP_VAR(ec);
      subscriber.subscribe(strConstRelaySubChannelName,std::bind(&RedisRelayClient::onMessage, &client, std::placeholders::_1));
    }
  });
  DUMP_VAR(publish);
  DUMP_VAR(gPublishRef.expired());
  ioService.run();
  DUMP_VAR(publish);
}

void createIpfsPubSubChannel(void) {
  std::thread t1(ipfs_redis_relay_main);
  t1.detach();
}
void commitIpfs(const json &response){
  DUMP_VAR(response);
  std::string serialized_string = response.dump();
  DUMP_VAR(gPublishRef.expired());
  if(!gPublishRef.expired()) {
    auto ptr = gPublishRef.lock();
    ptr->publish(strConstRelayPubChannelName,serialized_string,[&](const redisclient::RedisValue &value) {
      DUMP_VAR(1.0);
    });
  }
};

IpfsTextPump::~IpfsTextPump() {}

#include <boost/property_tree/xml_parser.hpp>
namespace pt = boost::property_tree;

string IpfsTextPump::fetchIpfsResource(const string &cid) {
  string result;
  string urlIpfs = url_ + "/" + cid;
  DUMP_VAR(urlIpfs);

  string taskTextPath = ws_ + "/ipfs.text";
  string wget = "wget -6 --tries=3 --connect-timeout=10 \"";
  // string wget =  "wget ";
  wget += urlIpfs;
  wget += "\" -O ";
  wget += taskTextPath;
  DUMP_VAR(wget);
  ::system(wget.c_str());
  try {
    std::ifstream textStream(taskTextPath);
    std::string str((std::istreambuf_iterator<char>(textStream)),
                    std::istreambuf_iterator<char>());
    result = str;
    textStream.close();
  } catch (const std::exception &ex) {
    DUMP_VAR(ex.what());
  }
  return result;
}

void IpfsTextPump::parseResourceBlock(const string & block) {
  json jsonBlock = json::parse(block.begin(),block.end());
  TRACE_VAR(jsonBlock);
  auto resourceJson = jsonBlock["resource"];

  int elementCounter = 0;
  for (auto& element : resourceJson) {
    auto resoureCID = element.get<std::string>();
    TRACE_VAR(resoureCID);
    if(boost::starts_with(resoureCID,"Qm")) {
      if(resoureCIDs_.size() < 20) {
        resoureCIDs_.push_back(resoureCID);
      }
    }
    elementCounter++;
  }
  DUMP_VAR(elementCounter);
  auto groupJson = jsonBlock["group"];
  if(groupJson.is_string()) {
    this->group_ = groupJson.get<std::string>();
  }
}

bool IpfsTextPump::fetchBlockResource(void) {
  std::lock_guard<std::mutex> guard(gBlockMutex);
  if(gBlockCID.empty()) {
    return false;
  }
  DUMP_VAR(gBlockCID);
  auto blocks = this->fetchIpfsResource(gBlockCID);
  TRACE_VAR(blocks);
  this->parseResourceBlock(blocks);
  this->task_ = gTask;
  this->blockCID_ = gBlockCID;
  gBlockCID = "";
  gTask = "";
  return true;
}

bool IpfsTextPump::fetchMasterTask(json &task, string &content) {
  if(resoureCIDs_.empty()) {
    if(isRunBlock_) {
      json block;
      block["task"] = this->task_;
      block["group"] = this->group_;
      block["cid"] = this->blockCID_;
      block["finnish"] = true;
      commitIpfs(block);
    }
    isRunBlock_ = false;
    this->fetchBlockResource();
    return false;
  }
  isRunBlock_ = true;
  auto cid = resoureCIDs_.back();
  content = fetchIpfsResource(cid);
  task["task"] = this->task_;
  task["group"] = this->group_;
  DUMP_VAR(this->task_);
  DUMP_VAR(this->group_);
  TRACE_VAR(content);
  resoureCIDs_.pop_back();
  return true;
}


text:
#include <cstring>
#include <fstream>
#include <unistd.h>

#include <NTL/ZZX.h>
#include <NTL/vector.h>

#include "FHE.h"
#include "timing.h"
#include "EncryptedArray.h"

/**
 *  키를 생성하여 파일로 내보내는 모듈.
 *
 *  원래 RSA 방식과는 다르게 비밀키에서 공개키를 생성하는 구조임.
 *  공개키로 암호화를 하고, 비밀키로 복호화를 함.
 *
 *  키마다 txt파일(ascii)과 bin파일의 두 파일로 내보내짐
 *  공개키 : FHEcontext와 FHEPubKey 두 객체를 내보냄
 *  비밀키 : FHEcontext, FHESecKey, FHEPubKey 세 객체를 내보냄
 *
 */
int main(int argc, char *argv[]) {

    ArgMapping amap;

    long r = 1;
    long c = 2;
    long w = 64;
    long k = 80;
    long d = 1;

    long p = 257;
    long L = 8;
    string owner = "owner";
    string dir = "data";

    amap.arg("p", p, "plaintext base");
    amap.arg("L", L, "number of levels wanted");
    amap.arg("o", owner, "owner's address");
    amap.arg("dir", dir, "save directory");
    amap.parse(argc, argv);

    // file names
    const string secretKeyBinaryFile = dir + "/secretKey/" + owner + ".bin";
    const string publicKeyBinaryFile = dir + "/publicKey/" + owner + ".bin";

    ofstream secretBinFile(secretKeyBinaryFile.c_str(), ios::binary);
    assert(secretBinFile.is_open());

    ofstream publicBinFile(publicKeyBinaryFile.c_str(), ios::binary);
    assert(publicBinFile.is_open());

    // create context
    long m = FindM(k, L, c, p, d, 0, 0);
    std::unique_ptr<FHEcontext> context(new FHEcontext(m, p, r));
    buildModChain(*context, L, c);  // Set the modulus chain

    // create key
    std::unique_ptr<FHESecKey> secKey(new FHESecKey(*context));
    FHEPubKey *pubKey = (FHEPubKey *) secKey.get();
    secKey->GenSecKey(w);
    addSome1DMatrices(*secKey);
    addFrbMatrices(*secKey);

    // Secret Bin
    cout << "\tWriting Secret Binary file " << secretKeyBinaryFile << endl;
    writeContextBaseBinary(secretBinFile, *context);
    writeContextBinary(secretBinFile, *context);
    writePubKeyBinary(secretBinFile, *pubKey);
    writeSecKeyBinary(secretBinFile, *secKey);

    // Public Bin
    cout << "\tWriting Public Binary file " << publicKeyBinaryFile << endl;
    writeContextBaseBinary(publicBinFile, *context);
    writeContextBinary(publicBinFile, *context);
    writePubKeyBinary(publicBinFile, *pubKey);

    secretBinFile.close();
    publicBinFile.close();

    cout << "createKey successful.\n\n";
}

ext: cpp

max_stars_repo_name: HanBae/voting-HElib-script

max_issues_repo_name: HanBae/voting-HElib-script

max_forks_repo_name: HanBae/voting-HElib-script


text:
#include <fstream>
#include <iostream>
#include <algorithm>

#include <yaml-cpp/yaml.h>

#include <boost/program_options.hpp>

#include <fcl/fcl.h>

// using namespace std;

#include <sbpl/headers.h>

int main(int argc, char* argv[]) {
  namespace po = boost::program_options;
  // Declare the supported options.
  po::options_description desc("Allowed options");
  std::string inputFile;
  std::string primitivesFile;
  std::string statsFile;
  std::string outputFile;
  desc.add_options()
    ("help", "produce help message")
    ("input,i", po::value<std::string>(&inputFile)->required(), "input file (yaml)")
    ("primitives,p", po::value<std::string>(&primitivesFile)->required(), "primitive file (prim)")
    ("stats", po::value<std::string>(&statsFile)->default_value("stats.yaml"), "output file (yaml)")
    ("output,o", po::value<std::string>(&outputFile)->required(), "output file (yaml)");

  try {
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help") != 0u) {
      std::cout << desc << "\n";
      return 0;
    }
  } catch (po::error& e) {
    std::cerr << e.what() << std::endl << std::endl;
    std::cerr << desc << std::endl;
    return 1;
  }

  // load problem description
  YAML::Node env = YAML::LoadFile(inputFile);

  // load obstacles
  std::vector<fcl::CollisionObjectf *> obstacles;
  for (const auto &obs : env["environment"]["obstacles"])
  {
    if (obs["type"].as<std::string>() == "box")
    {
      const auto &size = obs["size"];
      std::shared_ptr<fcl::CollisionGeometryf> geom;
      geom.reset(new fcl::Boxf(size[0].as<float>(), size[1].as<float>(), 1.0));
      const auto &center = obs["center"];
      auto co = new fcl::CollisionObjectf(geom);
      co->setTranslation(fcl::Vector3f(center[0].as<float>(), center[1].as<float>(), 0));
      co->computeAABB();
      obstacles.push_back(co);
    }
    else
    {
      throw std::runtime_error("Unknown obstacle type!");
    }
  }
  fcl::BroadPhaseCollisionManagerf *bpcm_env = new fcl::DynamicAABBTreeCollisionManagerf();
  bpcm_env->registerObjects(obstacles);
  bpcm_env->setup();

  // logic based on planxythetamlevlat in the offical SBPL test application

  //set the perimeter of the robot (it is given with 0,0,0 robot ref. point for which planning is done)
  //this is for the default level - base level
  std::vector<sbpl_2Dpt_t> perimeterptsV;
  sbpl_2Dpt_t pt_m;
  double halfwidth = 0.5 / 2;
  double halflength = 0.25 / 2;
  pt_m.x = -halflength;
  pt_m.y = -halfwidth;
  perimeterptsV.push_back(pt_m);
  pt_m.x = halflength;
  pt_m.y = -halfwidth;
  perimeterptsV.push_back(pt_m);
  pt_m.x = halflength;
  pt_m.y = halfwidth;
  perimeterptsV.push_back(pt_m);
  pt_m.x = -halflength;
  pt_m.y = halfwidth;
  perimeterptsV.push_back(pt_m);

  //Initialize Environment (should be called before initializing anything else)
  EnvironmentNAVXYTHETAMLEVLAT environment_navxythetalat;

  // NOTE: This assumes that "min" is zero!
  const auto &dims = env["environment"]["max"];
  double cellsize_m = 0.025;// needs to match mprim file
  int width = dims[0].as<double>() / cellsize_m;
  int height = dims[1].as<double>() / cellsize_m;
  std::vector<unsigned char> mapdata(width*height, 0);

  // Use FCL to initialize the discrete map (robot = 1 grid cell)
  std::shared_ptr<fcl::CollisionObjectf> co_robot;
  std::shared_ptr<fcl::CollisionGeometryf> geom;
  geom.reset(new fcl::Boxf(cellsize_m, cellsize_m, 1.0));
  co_robot.reset(new fcl::CollisionObjectf(geom));

  for (int x = 0; x < width; ++x) {
    for (int y = 0; y < height; ++y) {
      float center_x = x * cellsize_m + cellsize_m / 2;
      float center_y = y * cellsize_m + cellsize_m / 2;
      co_robot->setTranslation(fcl::Vector3f(center_x, center_y, 0));
      co_robot->computeAABB();
      fcl::DefaultCollisionData<float> collision_data;
      bpcm_env->collide(co_robot.get(), &collision_data, fcl::DefaultCollisionFunction<float>);
      if (collision_data.result.isCollision()) {
        mapdata[x + y * width] = 255;
      }
    }
  }

  const auto &robot_node = env["robots"][0];
  double startx = robot_node["start"][0].as<double>();
  double starty = robot_node["start"][1].as<double>();
  double starttheta = robot_node["start"][2].as<double>();
  double goalx = robot_node["goal"][0].as<double>();
  double goaly = robot_node["goal"][1].as<double>();
  double goaltheta = robot_node["goal"][2].as<double>();

  bool r = environment_navxythetalat.InitializeEnv(
      width,
      height,
      mapdata.data(),
      startx, starty, starttheta,
      goalx, goaly, goaltheta,
      /*goaltol_x*/ 0, /*goaltol_y*/ 0, /*goaltol_theta*/ 0,
      perimeterptsV,
      cellsize_m,
      /*nominalvel_mpersecs*/ sqrt(0.5),
      /*timetoturn45degsinplace_secs*/ sqrt(0.5 * M_PI_2),
      /*obsthresh*/ 100,
      primitivesFile.c_str());

  if (!r)
  {
    throw SBPL_Exception("ERROR: InitializeEnv failed");
  }

  ARAPlanner *planner = new ARAPlanner(&environment_navxythetalat, /*bforwardsearch*/ true);

  // set planner properties
  MDPConfig MDPCfg;
  // Initialize MDP Info
  if (!environment_navxythetalat.InitializeMDPCfg(&MDPCfg))
  {
    throw SBPL_Exception("ERROR: InitializeMDPCfg failed");
  }

  if (planner->set_start(MDPCfg.startstateid) == 0)
  {
    printf("ERROR: failed to set start state\n");
    throw SBPL_Exception("ERROR: failed to set start state");
  }
  if (planner->set_goal(MDPCfg.goalstateid) == 0)
  {
    printf("ERROR: failed to set goal state\n");
    throw SBPL_Exception("ERROR: failed to set goal state");
  }

  // plan
  std::vector<int> solution_stateIDs_V;
  int cost;
  // ReplanParams params(allocated_time_secs);
  // int bRet = planner->replan(&solution_stateIDs_V, params, &cost);
  double initialEpsilon = 2.0;
  bool bsearchuntilfirstsolution = false;
  double allocated_time_secs = 10.0; // in seconds
  planner->set_initialsolution_eps(initialEpsilon);
  planner->set_search_mode(bsearchuntilfirstsolution);
  int bRet = planner->replan(allocated_time_secs, &solution_stateIDs_V, &cost);
  printf("done planning with cost %d (suboptimality is: %f, desired: %f)\n",
    cost,
    planner->compute_suboptimality(),
    planner->get_solution_eps());
  printf("size of solution (states)=%d\n", (unsigned int)solution_stateIDs_V.size());
// }

  // write the continuous solution to file
  std::vector<sbpl_xy_theta_pt_t> xythetaPath;
  environment_navxythetalat.ConvertStateIDPathintoXYThetaPath(&solution_stateIDs_V, &xythetaPath);
  printf("size of solution (cont. states)=%d\n", (unsigned int)xythetaPath.size());

  // this function is buggy and misses the goal state
  int x_d, y_d, theta_d;
  int sourceID = solution_stateIDs_V.back();
  environment_navxythetalat.GetCoordFromState(sourceID, x_d, y_d, theta_d);
  double x_c, y_c, theta_c;
  environment_navxythetalat.PoseDiscToCont(x_d, y_d, theta_d, x_c, y_c, theta_c);
  sbpl_xy_theta_pt_t pt(x_c, y_c, theta_c);
  xythetaPath.push_back(pt);

  std::vector<EnvNAVXYTHETALATAction_t> actions;
  environment_navxythetalat.GetActionsFromStateIDPath(&solution_stateIDs_V, &actions);

  std::ofstream out(outputFile);
  out << "result:" << std::endl;
  out << "  - states:" << std::endl;
  for (const auto &state : xythetaPath)
  {
    out << "      - [" << state.x << "," << state.y << "," << std::remainder(state.theta, 2 * M_PI) << "]" << std::endl;
  }
  out << "    actions_mprim:" << std::endl;
  for (const auto &action : actions)
  {
    out << "      - [" << (int)action.starttheta << "," << (int)action.dX << "," << (int)action.dY << "," << (int)action.endtheta << "]" << std::endl;
  }

  // create stats file
  std::ofstream stats(statsFile);
  stats << "stats:" << std::endl;

  std::vector<PlannerStats> planner_stats;
  planner->get_search_stats(&planner_stats);
  double total_time = 0;
  for (const auto& s : planner_stats) {
    total_time += s.time;
    stats << "  - t: " << total_time << std::endl;
    stats << "    cost: " << s.cost / 10.0f << std::endl;
    stats << "    eps: " << s.eps << std::endl;
    stats << "    expands: " << s.expands << std::endl;
  }

  return 0;
}


text:
#include <boost/python.hpp>

char const* hello() {
  return "Hello World";
}

BOOST_PYTHON_MODULE(hello_py) {
  boost::python::def("hello", hello);
}

ext: cc


text:
//
// Created by Samuel Jackson on 29/10/15.
//

#include "BatchDatasetDescriptor.h"

#include <string>
#include <fstream>
#include <algorithm>
#include <iterator>
#include <iostream>

#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>

using namespace std;
using namespace boost;

BatchDatasetDescriptor::BatchDatasetDescriptor(const string &filename, const int batchSize)
        : m_batchSize(batchSize) {

    m_file = openFileStream(filename);
    skipHeader();
}

void BatchDatasetDescriptor::next() {
    resetBatch();
    readCSVFile();
}

void BatchDatasetDescriptor::resetBatch() {
    m_filenames.clear();
    m_filenames.reserve(m_batchSize);

    m_labels.clear();
    m_labels.reserve(m_batchSize);
}

void BatchDatasetDescriptor::readCSVFile() {
    for(int i=0; i < m_batchSize; ++i) {
        readCSVRow();
    }
}

void BatchDatasetDescriptor::readCSVRow() {
    typedef tokenizer< escaped_list_separator<char> > Tokenizer;
    vector<string> vec;
    string line;

    if(!getline(m_file,line)) {
        return;
    }

    Tokenizer tok(line);
    vec.assign(tok.begin(),tok.end());

    if (vec.size() < 3) {
        return;
    }

    m_labels.push_back(lexical_cast<int>(vec[1]));
    m_filenames.push_back(vec[2]);
}

void BatchDatasetDescriptor::skipHeader(const size_t skipLines) {
    for (size_t i = 0; i < skipLines; ++i) {
        m_file.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}

std::ifstream BatchDatasetDescriptor::openFileStream(const std::string &filename) {
    ifstream in(filename.c_str());

    if (!in.is_open()) {
        throw runtime_error("Could not open file: " + filename);
    }
    return in;
}

bool BatchDatasetDescriptor::hasNext() {
    return (m_file && m_file.peek() != EOF);
}


text:
#include <fstream>
#include <regex>
#include <boost/algorithm/string.hpp>

#include <Foundation/OS/File.h>

#include "Settings.h"

namespace MoonGlare {

Settings::Settings() { }

Settings::Settings(std::shared_ptr<Settings> upperLayerSettings) :upperLayer(std::move(upperLayerSettings)){

}

Settings::~Settings() {}

//---------------------------------------------------------

std::string Settings::Serialize(bool FollowLayers) const {
    std::stringstream ss;
    for (auto &key : GetKeys()) {
        auto it = values.find(key);
        ss << key << "=";
        std::visit([&ss](const auto &value) {
            using type_t = std::remove_cv_t<std::remove_reference_t<decltype(value)>>;
            if constexpr (std::is_same_v<int, type_t>)
                ss << value;
            else if constexpr (std::is_same_v<float, type_t>)
                ss << value;
            else if constexpr (std::is_same_v<std::string, type_t>)
                ss << value;
            else if constexpr (std::is_same_v<bool, type_t>)
                ss << (value ? "true" : "false");
            else {
                __debugbreak();
            }
        }, it->second);

        ss << std::endl;
    }
    if (FollowLayers && upperLayer) {
        ss << "#Upper Layers:\n";
        ss << upperLayer->Serialize(true);
    }
    return ss.str();
}

void Settings::Deserialize(const std::string &data) {
    values.clear();
    changed = false;
    std::vector<std::string> lines;
    boost::split(lines, data, boost::is_any_of("\n"));
    for (auto &line : lines) {
        auto comment = line.find("#");
        if (comment != std::string::npos)
            line.erase(line.begin() + comment, line.end());

        AppendString(std::move(line));
    }
}

void Settings::AppendString(std::string line) {
    boost::trim(line);
    if (line.empty())
        return;
    auto pos = line.find('=');
    if (pos == std::string::npos) {
        values[line] = true;
    } else {
        std::string key = line.substr(0, pos);
        std::string value = line.substr(pos + 1);
        boost::trim(key);
        boost::trim(value);

        std::smatch base_match;
        if (value == "true")
            values[key] = true;
        else if (value == "false")
            values[key] = false;
        else if (std::regex_match(value, base_match, std::regex("\\d+")))
            values[key] = strtol(value.c_str(), nullptr, 10);
        else if (std::regex_match(value, base_match, std::regex("\\d+.\\d+")))
            values[key] = strtof(value.c_str(), nullptr);
        else
            values[key] = value;
    }
}
void Settings::SaveToFile(const std::string &fileName) const {
    OS::WriteStringToFile(fileName, Serialize());
}

void Settings::LoadFromFile(const std::string &fileName) {
    std::string data;
    if(OS::GetFileContent(fileName, data))
        Deserialize(data);
}

std::vector<std::string> Settings::GetKeys() const {
    std::vector<std::string> r;
    r.reserve(values.size());
    for (auto &it : values) {
        r.emplace_back(it.first);
    }
    std::sort(r.begin(), r.end());
    return r;
}

//---------------------------------------------------------

std::string Settings::ToString(const ValueVariant &vv) {
    return std::visit([](auto &value) -> std::string {
        using type_t = std::remove_cv_t<std::remove_reference_t<decltype(value)>>;
        if constexpr (std::is_same_v<nullptr_t, type_t>)
            return "";
        else if constexpr (std::is_same_v<int, type_t>)
            return std::to_string(value);
        else if constexpr (std::is_same_v<float, type_t>)
            return std::to_string(value);
        else if constexpr (std::is_same_v< std::string, type_t>)
            return value;
        else if constexpr (std::is_same_v<bool, type_t>)
            return value ? "true" : "false";
        else {
            __debugbreak();
            throw std::runtime_error("reached unreachable code!");
        }
    }, vv);
}

bool Settings::HasValue(const std::string &key) const {
    auto it = values.find(key);
    if (it != values.end())
        return true;
    if (upperLayer)
        return upperLayer->HasValue(key);
    return false;
}

std::string Settings::GetString(const std::string &key, const std::string &default) {
    if (upperLayer && upperLayer->HasValue(key)) {
        return upperLayer->GetString(key, default);
    }
    auto it = values.find(key);
    if (it == values.end()) {
#ifdef DEBUG
        SetValue(key, default);
#endif
        return default;
    }
    return ToString(it->second);
}

int Settings::GetInt(const std::string &key, int default) {
    if (upperLayer && upperLayer->HasValue(key)) {
        return upperLayer->GetInt(key, default);
    }
    auto it = values.find(key);
    if (it == values.end()) {
#ifdef DEBUG
        SetValue(key, default);
#endif
        return default;
    }
    return std::visit([](auto &value) -> int {
        using type_t = std::remove_cv_t<std::remove_reference_t<decltype(value)>>;
        if constexpr (std::is_same_v<nullptr_t, type_t>)
            return 0;
        else if constexpr (std::is_same_v<int, type_t>)
            return value;
        else if constexpr (std::is_same_v<float, type_t>)
            return static_cast<int>(value);
        else if constexpr (std::is_same_v<std::string, type_t>)
            return strtol(value.c_str(), nullptr, 10);
        else if constexpr (std::is_same_v<bool, type_t>)
            return value ? 1 : 0;
        else {
            __debugbreak();
            throw std::runtime_error("reached unreachable code!");
        }
    }, it->second);
}

float Settings::GetFloat(const std::string &key, float default)  {
    if (upperLayer && upperLayer->HasValue(key)) {
        return upperLayer->GetFloat(key, default);
    }
    auto it = values.find(key);
    if (it == values.end()) {
#ifdef DEBUG
        SetValue(key, default);
#endif
        return default;
    }
    return std::visit([](auto &value) -> float {
        using type_t = std::remove_cv_t<std::remove_reference_t<decltype(value)>>;
        if constexpr (std::is_same_v<nullptr_t, type_t>)
            return 0.0;
        else if constexpr (std::is_same_v<int, type_t>)
            return value;
        else if constexpr (std::is_same_v<float, type_t>)
            return value;
        else if constexpr (std::is_same_v<std::string, type_t>)
            return strtof(value.c_str(), nullptr);
        else if constexpr (std::is_same_v<bool, type_t>)
            return value ? 1 : 0;
        else {
            __debugbreak();
            throw std::runtime_error("reached unreachable code!");
        }
    }, it->second);
}

bool Settings::GetBool(const std::string &key, bool default) {
    if (upperLayer && upperLayer->HasValue(key)) {
        return upperLayer->GetBool(key, default);
    }
    auto it = values.find(key);
    if (it == values.end()) {
#ifdef DEBUG
        SetValue(key, default);
#endif
        return default;
    }
    return std::visit([](auto &value) -> bool {
        using type_t = std::remove_cv_t<std::remove_reference_t<decltype(value)>>;
        if constexpr (std::is_same_v<nullptr_t, type_t>)
            return false;
        else if constexpr (std::is_same_v<int, type_t>)
            return value > 0;
        else if constexpr (std::is_same_v<float, type_t>)
            return value != 0.0f;
        else if constexpr (std::is_same_v<std::string, type_t>)
            return value == "true";
        else if constexpr (std::is_same_v<bool, type_t>)
            return value;
        else {
            __debugbreak();
            throw std::runtime_error("reached unreachable code!");
        }
    }, it->second);
}

Settings::ValueVariant Settings::GetValue(const std::string &key) {
    if (upperLayer && upperLayer->HasValue(key)) {
        return upperLayer->GetValue(key);
    }
    auto it = values.find(key);
    if (it == values.end()) {
        return nullptr;
    }
    return it->second;
}

Settings::ApplyMethod Settings::SetValue(const std::string &key, ValueVariant value) {
    if (std::holds_alternative<nullptr_t>(value))
        values.erase(key);
    else
        values[key] = std::move(value);
    changed = true;
    return NotifyChange(key);
}

Settings::ApplyMethod Settings::SetValue(const std::string &key, int value) {
    values[key] = value;
    changed = true;
    return NotifyChange(key);
}

Settings::ApplyMethod Settings::SetValue(const std::string &key, float value) {
    values[key] = value;
    changed = true;
    return NotifyChange(key);
}

Settings::ApplyMethod Settings::SetValue(const std::string &key, bool value) {
    values[key] = value;
    changed = true;
    return NotifyChange(key);
}

Settings::ApplyMethod Settings::SetValue(const std::string &key, std::string value) {
    values[key] = std::move(value);
    changed = true;
    return NotifyChange(key);
}

//---------------------------------------------------------

void Settings::Subscribe(std::shared_ptr<Settings::iChangeCallback> cb) {
    callbackList.emplace_back(cb);
}

Settings::ApplyMethod Settings::NotifyChange(const std::string &key) {
    AddLogf(Info, "Settings changed key:%s value:%s", key.c_str(), GetString(key).c_str());
    ApplyMethod r = ApplyMethod::DontCare;
    for (auto &wcb : callbackList) {
        auto cb = wcb.lock();
        if (!cb)
            continue;
        switch (cb->ValueChanged(key, this)) {
        case ApplyMethod::Restart:
            r = ApplyMethod::Restart;
            break;
        case ApplyMethod::Immediate:
            if (r != ApplyMethod::Restart)
                r = ApplyMethod::Immediate;
            continue;
        case ApplyMethod::DontCare:
        default:
            continue;
        }
    }
    if (r == ApplyMethod::DontCare)
        return ApplyMethod::Restart;
    return r;
}

}

max_stars_repo_name: pgrabas/MoonGlare

max_issues_repo_name: pgrabas/MoonGlare

max_forks_repo_name: pgrabas/MoonGlare


text:
#pragma once

#include <string>
#include <vector>
#include <cstdint>
#include <cmath>
#include <memory>
#include <unqlite.h>
#include <boost/iterator/iterator_facade.hpp>

namespace blib {
    namespace bun {
        namespace __private {
            using ByteVctorType = std::vector<std::uint8_t>;

            template<typename T = std::string>
            struct ToByte {
                static std::vector<std::uint8_t> to_byte(T const& val) {
                    std::vector<std::uint8_t> ret;
                    for (const auto v : val) {
                        ret.push_back(static_cast<std::uint8_t>(v));
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::uint16_t> {
                static std::vector<std::uint8_t> to_byte(std::uint16_t const val) {
                    using T = std::uint16_t;
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t  i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::int16_t> {
                static std::vector<std::uint8_t> to_byte(std::int16_t const val) {
                    using T = std::int16_t;
                    static const std::size_t  size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::uint32_t> {
                static std::vector<std::uint8_t> to_byte(std::uint32_t const val) {
                    using T = std::uint32_t;
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::int32_t> {
                static std::vector<std::uint8_t> to_byte(std::int32_t const val) {
                    using T = std::int32_t;
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::uint64_t> {
                static std::vector<std::uint8_t> to_byte(std::uint64_t const val) {
                    using T = std::uint64_t;
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::int64_t> {
                static std::vector<std::uint8_t> to_byte(std::int64_t const val) {
                    using T = std::int64_t;
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::float_t> {
                static std::vector<std::uint8_t> to_byte(std::float_t const val) {
                    using T = std::float_t;
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::double_t> {
                static std::vector<std::uint8_t> to_byte(std::double_t const val) {
                    using T = std::double_t;
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    std::vector<std::uint8_t> ret(size);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(T const val) {
                            v = val;
                        }
                    };
                    const V v = val;
                    for (std::size_t i = 0; i < size; ++i) {
                        ret[i] = v.c[i];
                    }
                    return ret;
                }
            };

            template<>
            struct ToByte<std::uint8_t> {
                using T = std::uint8_t;
                static ByteVctorType to_byte(T const val) {
                    ByteVctorType vec;
                    vec.push_back(val);
                    return vec;
                }
            };

            template<>
            struct ToByte<std::int8_t> {
                using T = std::int8_t;
                static ByteVctorType to_byte(T const val) {
                    ByteVctorType vec;
                    vec.push_back(static_cast<std::uint8_t>(val));
                    return vec;
                }
            };

            /// @class FromByte
            /// @brief A class to convert byte vectors to different data structures
            template<typename T = std::string>
            struct FromByte {
                static void from_byte(ByteVctorType const& vec, T& value) {
                    for (const auto v : vec) {
                        value.push_back(v);
                    }
                }
            };

            template<>
            struct FromByte<std::uint16_t> {
                using T = std::uint16_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val) :v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::int16_t> {
                using T = std::int16_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val):v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::uint32_t> {
                using T = std::uint32_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val) : v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::int32_t> {
                using T = std::int32_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val) :v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::uint64_t> {
                using T = std::uint64_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val) :v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::int64_t> {
                using T = std::int64_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val) :v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::float_t> {
                using T = std::float_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val) :v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::double_t> {
                using T = std::double_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    static const std::size_t size = sizeof(T) / sizeof(std::uint8_t);
                    union V {
                        std::uint8_t c[size];
                        T v;
                        V(ByteVctorType const& val) :v() {
                            for (std::size_t i = 0; i < size && i < val.size(); ++i) {
                                c[i] = val[i];
                            }
                        }
                    };

                    V v = vec;
                    value = v.v;
                }
            };

            template<>
            struct FromByte<std::uint8_t> {
                using T = std::uint8_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    if (vec.size()) {
                        value = vec[0];
                    }
                }
            };

            template<>
            struct FromByte<std::int8_t> {
                using T = std::int8_t;
                static void from_byte(ByteVctorType const& vec, T& value) {
                    if (vec.size()) {
                        value = static_cast<std::int8_t>(vec[0]);
                    }
                }
            };
        }

        using ByteVctorType = __private::ByteVctorType;

        struct DbKVStoreType {};
        struct DBKVStoreUnqlite : DbKVStoreType {};

        template<typename T>
        inline std::vector<std::uint8_t> to_byte_vec(T const& val) {
            return __private::ToByte<T>::to_byte(val);
        }

        template<typename T>
        inline void from_byte_vec(ByteVctorType const& vec, T& value) {
            __private::FromByte<T>::from_byte(vec, value);
        }

        template<typename T = DBKVStoreUnqlite>
        class KVIterator : public boost::iterator_facade<
            KVIterator<DBKVStoreUnqlite>,
            std::pair<ByteVctorType, ByteVctorType>,
            boost::forward_traversal_tag
        > {
        public:
            using ByteVecPair = std::pair<ByteVctorType, ByteVctorType>;

        private:
            std::unique_ptr<ByteVecPair> _val;
            unqlite* _db;
            unqlite_kv_cursor* _pcursor;

        public:
            KVIterator() noexcept :
                _val(std::make_unique<ByteVecPair>()),
                _db(nullptr),
                _pcursor(nullptr) {}

            KVIterator(unqlite* db) :
                _val(std::make_unique<ByteVecPair>()),
                _db(db),
                _pcursor(nullptr) {
                open();
            }

            KVIterator(KVIterator const& in_other) :
                _val(std::make_unique<ByteVecPair>()),
                _db(in_other._db),
                _pcursor(in_other._pcursor) {

            }

            ~KVIterator() {
                close();
            }

        private:
            friend class boost::iterator_core_access;

            void open() {
                if(_db != nullptr) {
                    if(_pcursor != nullptr) {
                        const auto rc = unqlite_kv_cursor_valid_entry(_pcursor);
                        if (rc != UNQLITE_OK) {
                            close();
                        }
                    }
                    else{
                        const auto rc = unqlite_kv_cursor_init(_db, &_pcursor);
                        if (rc != UNQLITE_OK) {
                            close();
                        }
                    }
                }

                if(_pcursor != nullptr) {
                    const auto rc = unqlite_kv_cursor_first_entry(_pcursor);
                    if (rc != UNQLITE_OK) {
                        close();
                    }
                }
            }

            void close() {
                unqlite_kv_cursor_release(_db, _pcursor);
                _pcursor = nullptr;
                _db = nullptr;
            }

            void increment() {
                const auto rc = unqlite_kv_cursor_next_entry(_pcursor);
                _val->first.clear();
                _val->second.clear();
                if (rc != UNQLITE_OK) {
                    close();
                }
            }

            bool equal(KVIterator const& other) const {
                return _pcursor == other._pcursor;
            }

            ByteVecPair& dereference() const {
                populate_key();
                populate_value();
                return *_val;
            }

            void populate_key() const {
                int buff_size = 0;
                const auto rc = unqlite_kv_cursor_key(_pcursor, nullptr, &buff_size);
                if (rc == UNQLITE_OK) {
                    std::unique_ptr<std::uint8_t[]> buffer = std::make_unique<std::uint8_t[]>(buff_size);
                    const auto rc = unqlite_kv_cursor_key(_pcursor, buffer.get(), &buff_size);
                    if (rc == UNQLITE_OK) {
                        _val->first.reserve(buff_size);
                        for (int i = 0; i < buff_size; ++i) {
                            _val->first.push_back(buffer[i]);
                        }
                    }
                }
            }

            void populate_value() const {
                unqlite_int64 buff_size = 0;
                const auto rc = unqlite_kv_cursor_data(_pcursor, nullptr, &buff_size);
                if (rc == UNQLITE_OK) {
                    std::unique_ptr<std::uint8_t[]> buffer = std::make_unique<std::uint8_t[]>(buff_size);
                    const auto rc = unqlite_kv_cursor_data(_pcursor, buffer.get(), &buff_size);
                    if (rc == UNQLITE_OK) {
                        _val->second.reserve(buff_size);
                        for (int i = 0; i < buff_size; ++i) {
                            _val->second.push_back(buffer[i]);
                        }
                    }
                }
            }
        };

        /// @class KVDb
        /// @brief The main class for the key value store
        template<typename T = DBKVStoreUnqlite>
        class KVDb {
        public:
            using ByteVctorType = std::vector<std::uint8_t>;

        private:
            /// @var _db
            /// @brief The default is of type unqlite
            unqlite* _db;
            /// @var _ok
            /// @brief The value is true if all things is right with the database else it is false
            bool _ok;

        public:
            /// @fn KVDb
            /// @param param
            /// @brief The constructor for the KV class
            KVDb(std::string const& param) :_db(nullptr), _ok(false) {
                const auto rc = unqlite_open(&_db, param.c_str(), UNQLITE_OPEN_CREATE);
                if ( UNQLITE_OK == rc) {
                    _ok = true;
                }
            }

            /// @fn KVDb
            /// @param other. The other KVDb from which we can copy values.
            /// @brief The copy constructor for the KV class
            KVDb(KVDb const& other) {
                _db = other._db;
                _ok = other._ok;
            }

            /// @fn ~KVDb
            /// @brief destructor for the KV class
            ~KVDb() {
                if (nullptr != _db) {
                    unqlite_close(_db);
                }
            }

            /// @fn ok
            /// @brief Returns Ok
            bool ok() const {
                return _ok;
            }

            std::string last_status() const {
                const char *zBuf = nullptr;
                int iLen = 0;
                unqlite_config(_db, UNQLITE_CONFIG_ERR_LOG, &zBuf, &iLen);
                const std::string ret(zBuf);
                return ret;
            }

            /// @fn put
            /// @param key The key
            /// @param value the value that needs to be stored
            /// @details Put stores the key and value and returns true of the store is done, else it returns false
            ///          All primary C++ data types including std::string is supported as key and value
            template<typename Key, typename Value>
            bool put(Key const& key, Value const& value) {
                const auto key_vec = to_byte_vec(key);
                const auto val_vec = to_byte_vec(value);
                const auto rc = unqlite_kv_store(_db, key_vec.data(), key_vec.size(), val_vec.data(), val_vec.size());
                const bool ret = rc == UNQLITE_OK ? true : false;
                return ret;
            }

            /// @fn get
            /// @param key The key
            /// @param value the value is of type ByteVctorType. This carries the out value
            /// @details Gets the value corresponding the key. If the retrieval it returns true else it returns false.
            ///          All primary C++ data types including std::string is supported as key. The value is a byte (std::uint8_t) value
            template<typename Key>
            bool get(Key const& key, ByteVctorType& value) {
                const auto key_vec = to_byte_vec(key);
                unqlite_int64 buff_size = 0;
                auto rc = unqlite_kv_fetch(_db, key_vec.data(), key_vec.size(), NULL, &buff_size);
                if ( UNQLITE_OK == rc) {
                    std::unique_ptr<std::uint8_t[]> buffer = std::make_unique<std::uint8_t[]>(buff_size);
                    rc = unqlite_kv_fetch(_db, key_vec.data(), key_vec.size(), buffer.get(), &buff_size);
                    value.reserve(buff_size);
                    for (int i = 0; i < buff_size; ++i) {
                        value.push_back(buffer[i]);
                    }
                }

                const bool ret = rc == UNQLITE_OK ? true : false;
                return ret;
            }

            /// @fn get
            /// @param key The key
            /// @param value the value is of type ByteVctorType. This carries the out value
            /// @details Gets the value corresponding the key. If the retrieval it returns true else it returns false.
            ///          All primary C++ data types including std::string is supported as key. The value C++ primary datatype.
            ///          This function is a wrapper on top of the previous function which returns the byte vector.
            template<typename Key, typename Value>
            bool get(Key const& key, Value& value) {
                bool ret = false;
                ByteVctorType vec;
                const bool rc = get(key, vec);
                if (true == rc) {
                    from_byte_vec(vec, value);
                    ret = true;
                }
                return ret;
            }

            /// @fn del
            /// @param key The key
            /// @details Delete the value corresponding to key. If delete is success then returns true else returns false.
            ///          All primary C++ data types including std::string is supported as key.
            template<typename Key>
            bool del(Key const& key) {
                const auto key_vec = to_byte_vec(key);
                const auto rc = unqlite_kv_delete(_db, key_vec.data(), key_vec.size());
                const bool ret = rc == UNQLITE_OK ? true : false;
                return ret;
            }

            KVIterator<> begin() {
                return KVIterator<>(_db);
            }

            KVIterator<> end() {
                return KVIterator<>();
            }
        };
    }
}

ext: hpp

max_stars_repo_name: sp-mishra/bun

max_issues_repo_name: sp-mishra/bun

max_forks_repo_name: sp-mishra/bun


text:
#include <cstdlib>

#include "util/random.hh"

#define BOOST_TEST_MODULE RandomTest
#include <boost/test/unit_test.hpp>

namespace util
{
namespace
{

BOOST_AUTO_TEST_CASE(rand_int_returns_positive_no_greater_than_RAND_MAX)
{
  rand_init();
  for (int i=0; i<100; i++)
  {
    const int random_number = rand<int>();
    BOOST_CHECK(random_number >= 0);
    BOOST_CHECK(random_number <= RAND_MAX);
  }
}

BOOST_AUTO_TEST_CASE(rand_int_returns_different_consecutive_numbers)
{
  rand_init(99);
  const int first = rand<int>(), second = rand<int>(), third = rand<int>();
  // Sometimes you'll get the same number twice in a row, but generally the
  // randomizer returns different numbers.
  BOOST_CHECK(second != first || third != first);
}

BOOST_AUTO_TEST_CASE(rand_int_returns_different_numbers_for_different_seeds)
{
  rand_init(1);
  const int one1 = rand<int>(), one2 = rand<int>();
  rand_init(2);
  const int two1 = rand<int>(), two2 = rand<int>();
  BOOST_CHECK(two1 != one1 || two2 != one2);
}

BOOST_AUTO_TEST_CASE(rand_int_returns_same_sequence_for_same_seed)
{
  rand_init(1);
  const int first = rand<int>();
  rand_init(1);
  const int second = rand<int>();
  BOOST_CHECK_EQUAL(first, second);
}

BOOST_AUTO_TEST_CASE(rand_excl_int_returns_number_in_range)
{
  const int bottom = 10, top = 50;
  for (int i=0; i<100; i++)
  {
    const int random_number = rand_excl(bottom, top);
    BOOST_CHECK(random_number >= bottom);
    BOOST_CHECK(random_number < top);
  }
}

BOOST_AUTO_TEST_CASE(rand_excl_int_covers_full_range)
{
  // The spread of random numbers really goes all the way from 0 (inclusive)
  // to "top" (exclusive).  It's not some smaller subset.
  // This test will randomly fail sometimes, though very very rarely, when the
  // random numbers don't actually have enough different values.
  const int bottom = 1, top = 4;
  int lowest = 99, highest = -1;
  for (int i=0; i<100; i++)
  {
    const int random_number = rand_excl(bottom, top);
    lowest = std::min(lowest, random_number);
    highest = std::max(highest, random_number);
  }

  BOOST_CHECK_EQUAL(lowest, bottom);
  BOOST_CHECK_EQUAL(highest, top - 1);
}

BOOST_AUTO_TEST_CASE(rand_incl_int_returns_number_in_range)
{
  const int bottom = 10, top = 50;
  for (int i=0; i<100; i++)
  {
    const int random_number = rand_incl(bottom, top);
    BOOST_CHECK(random_number >= 0);
    BOOST_CHECK(random_number <= top);
  }
}

BOOST_AUTO_TEST_CASE(rand_incl_int_covers_full_range)
{
  // The spread of random numbers really goes all the way from 0 to "top"
  // inclusive.  It's not some smaller subset.
  // This test will randomly fail sometimes, though very very rarely, when the
  // random numbers don't actually have enough different values.
  const int bottom = 1, top = 4;
  int lowest = 99, highest = -1;
  for (int i=0; i<100; i++)
  {
    const int random_number = rand_incl(bottom, top);
    lowest = std::min(lowest, random_number);
    highest = std::max(highest, random_number);
  }

  BOOST_CHECK_EQUAL(lowest, bottom);
  BOOST_CHECK_EQUAL(highest, top);
}

BOOST_AUTO_TEST_CASE(rand_excl_float_returns_float_in_range)
{
  const float bottom = 5, top = 10;
  for (int i=0; i<100; i++)
  {
    const float random_number = rand_excl(bottom, top);
    BOOST_CHECK(random_number >= bottom);
    BOOST_CHECK(random_number < top);
  }
}

BOOST_AUTO_TEST_CASE(rand_excl_float_returns_different_values)
{
  const float bottom = 5, top = 10;
  float lowest = 99, highest = -1;
  for (int i=0; i<10; i++)
  {
    const float random_number = rand_excl(bottom, top);
    lowest = std::min(lowest, random_number);
    highest = std::max(highest, random_number);
  }
  BOOST_CHECK(lowest < highest);
}

BOOST_AUTO_TEST_CASE(rand_float_incl_returns_float_in_range)
{
  const float bottom = 5, top = 10;
  for (int i=0; i<1000; i++)
  {
    const float random_number = rand_excl(bottom, top);
    BOOST_CHECK(random_number >= bottom);
    BOOST_CHECK(random_number <= top);
  }
}

BOOST_AUTO_TEST_CASE(rand_float_incl_returns_different_values)
{
  const float bottom = 0, top = 10;
  float lowest = 99, highest = -1;
  for (int i=0; i<10; i++)
  {
    const float random_number = rand_excl(bottom, top);
    lowest = std::min(lowest, random_number);
    highest = std::max(highest, random_number);
  }
  BOOST_CHECK(lowest < highest);
}

BOOST_AUTO_TEST_CASE(wide_rand_int_returns_different_numbers_in_range)
{
  for (int i=0; i<100; i++)
  {
    const int random_number = wide_rand<int>();
    BOOST_CHECK(random_number >= 0);
    BOOST_CHECK(random_number <= RAND_MAX);
  }
}

BOOST_AUTO_TEST_CASE(wide_rand_long_long_returns_big_numbers)
{
  long long one = wide_rand<long long>(), two = wide_rand<long long>();
  // This test will fail sometimes because of unlucky random numbers, but only
  // very very rarely.
  BOOST_CHECK(one > RAND_MAX || two > RAND_MAX);
}

BOOST_AUTO_TEST_CASE(wide_rand_excl_supports_larger_range)
{
  const long long top = 1000 * (long long)RAND_MAX;
  long long
    one = wide_rand_excl<long long>(top),
    two = wide_rand_excl<long long>(top);
  BOOST_CHECK(one < top);
  BOOST_CHECK(two < top);
  // This test will fail sometimes because of unlucky random numbers, but only
  // very very rarely.
  BOOST_CHECK(one > RAND_MAX || two > RAND_MAX);
}

} // namespace
} // namespace util

max_issues_repo_name: Pangeamt/nectm

max_forks_repo_name: Pangeamt/nectm


text:
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@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 "main.h"

#include <Eigen/CXX11/Tensor>

using Eigen::Tensor;
using Eigen::array;

template <int DataLayout>
static void test_simple_shuffling()
{
  Tensor<float, 4, DataLayout> tensor(2,3,5,7);
  tensor.setRandom();
  array<ptrdiff_t, 4> shuffles;
  shuffles[0] = 0;
  shuffles[1] = 1;
  shuffles[2] = 2;
  shuffles[3] = 3;

  Tensor<float, 4, DataLayout> no_shuffle;
  no_shuffle = tensor.shuffle(shuffles);

  VERIFY_IS_EQUAL(no_shuffle.dimension(0), 2);
  VERIFY_IS_EQUAL(no_shuffle.dimension(1), 3);
  VERIFY_IS_EQUAL(no_shuffle.dimension(2), 5);
  VERIFY_IS_EQUAL(no_shuffle.dimension(3), 7);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      for (int k = 0; k < 5; ++k) {
        for (int l = 0; l < 7; ++l) {
          VERIFY_IS_EQUAL(tensor(i,j,k,l), no_shuffle(i,j,k,l));
        }
      }
    }
  }

  shuffles[0] = 2;
  shuffles[1] = 3;
  shuffles[2] = 1;
  shuffles[3] = 0;
  Tensor<float, 4, DataLayout> shuffle;
  shuffle = tensor.shuffle(shuffles);

  VERIFY_IS_EQUAL(shuffle.dimension(0), 5);
  VERIFY_IS_EQUAL(shuffle.dimension(1), 7);
  VERIFY_IS_EQUAL(shuffle.dimension(2), 3);
  VERIFY_IS_EQUAL(shuffle.dimension(3), 2);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      for (int k = 0; k < 5; ++k) {
        for (int l = 0; l < 7; ++l) {
          VERIFY_IS_EQUAL(tensor(i,j,k,l), shuffle(k,l,j,i));
        }
      }
    }
  }
}

template <int DataLayout>
static void test_expr_shuffling()
{
  Tensor<float, 4, DataLayout> tensor(2,3,5,7);
  tensor.setRandom();

  array<ptrdiff_t, 4> shuffles;
  shuffles[0] = 2;
  shuffles[1] = 3;
  shuffles[2] = 1;
  shuffles[3] = 0;
  Tensor<float, 4, DataLayout> expected;
  expected = tensor.shuffle(shuffles);

  Tensor<float, 4, DataLayout> result(5,7,3,2);

  array<int, 4> src_slice_dim{{2,3,1,7}};
  array<int, 4> src_slice_start{{0,0,0,0}};
  array<int, 4> dst_slice_dim{{1,7,3,2}};
  array<int, 4> dst_slice_start{{0,0,0,0}};

  for (int i = 0; i < 5; ++i) {
    result.slice(dst_slice_start, dst_slice_dim) =
        tensor.slice(src_slice_start, src_slice_dim).shuffle(shuffles);
    src_slice_start[2] += 1;
    dst_slice_start[0] += 1;
  }

  VERIFY_IS_EQUAL(result.dimension(0), 5);
  VERIFY_IS_EQUAL(result.dimension(1), 7);
  VERIFY_IS_EQUAL(result.dimension(2), 3);
  VERIFY_IS_EQUAL(result.dimension(3), 2);

  for (int i = 0; i < expected.dimension(0); ++i) {
    for (int j = 0; j < expected.dimension(1); ++j) {
      for (int k = 0; k < expected.dimension(2); ++k) {
        for (int l = 0; l < expected.dimension(3); ++l) {
          VERIFY_IS_EQUAL(result(i,j,k,l), expected(i,j,k,l));
        }
      }
    }
  }

  dst_slice_start[0] = 0;
  result.setRandom();
  for (int i = 0; i < 5; ++i) {
    result.slice(dst_slice_start, dst_slice_dim) =
        tensor.shuffle(shuffles).slice(dst_slice_start, dst_slice_dim);
    dst_slice_start[0] += 1;
  }

  for (int i = 0; i < expected.dimension(0); ++i) {
    for (int j = 0; j < expected.dimension(1); ++j) {
      for (int k = 0; k < expected.dimension(2); ++k) {
        for (int l = 0; l < expected.dimension(3); ++l) {
          VERIFY_IS_EQUAL(result(i,j,k,l), expected(i,j,k,l));
        }
      }
    }
  }
}

template <int DataLayout>
static void test_shuffling_as_value()
{
  Tensor<float, 4, DataLayout> tensor(2,3,5,7);
  tensor.setRandom();
  array<ptrdiff_t, 4> shuffles;
  shuffles[2] = 0;
  shuffles[3] = 1;
  shuffles[1] = 2;
  shuffles[0] = 3;
  Tensor<float, 4, DataLayout> shuffle(5,7,3,2);
  shuffle.shuffle(shuffles) = tensor;

  VERIFY_IS_EQUAL(shuffle.dimension(0), 5);
  VERIFY_IS_EQUAL(shuffle.dimension(1), 7);
  VERIFY_IS_EQUAL(shuffle.dimension(2), 3);
  VERIFY_IS_EQUAL(shuffle.dimension(3), 2);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      for (int k = 0; k < 5; ++k) {
        for (int l = 0; l < 7; ++l) {
          VERIFY_IS_EQUAL(tensor(i,j,k,l), shuffle(k,l,j,i));
        }
      }
    }
  }

  array<ptrdiff_t, 4> no_shuffle;
  no_shuffle[0] = 0;
  no_shuffle[1] = 1;
  no_shuffle[2] = 2;
  no_shuffle[3] = 3;
  Tensor<float, 4, DataLayout> shuffle2(5,7,3,2);
  shuffle2.shuffle(shuffles) = tensor.shuffle(no_shuffle);
  for (int i = 0; i < 5; ++i) {
    for (int j = 0; j < 7; ++j) {
      for (int k = 0; k < 3; ++k) {
        for (int l = 0; l < 2; ++l) {
          VERIFY_IS_EQUAL(shuffle2(i,j,k,l), shuffle(i,j,k,l));
        }
      }
    }
  }
}

template <int DataLayout>
static void test_shuffle_unshuffle()
{
  Tensor<float, 4, DataLayout> tensor(2,3,5,7);
  tensor.setRandom();

  // Choose a random permutation.
  array<ptrdiff_t, 4> shuffles;
  for (int i = 0; i < 4; ++i) {
    shuffles[i] = i;
  }
  array<ptrdiff_t, 4> shuffles_inverse;
  for (int i = 0; i < 4; ++i) {
    const ptrdiff_t index = internal::random<ptrdiff_t>(i, 3);
    shuffles_inverse[shuffles[index]] = i;
    std::swap(shuffles[i], shuffles[index]);
  }

  Tensor<float, 4, DataLayout> shuffle;
  shuffle = tensor.shuffle(shuffles).shuffle(shuffles_inverse);

  VERIFY_IS_EQUAL(shuffle.dimension(0), 2);
  VERIFY_IS_EQUAL(shuffle.dimension(1), 3);
  VERIFY_IS_EQUAL(shuffle.dimension(2), 5);
  VERIFY_IS_EQUAL(shuffle.dimension(3), 7);

  for (int i = 0; i < 2; ++i) {
    for (int j = 0; j < 3; ++j) {
      for (int k = 0; k < 5; ++k) {
        for (int l = 0; l < 7; ++l) {
          VERIFY_IS_EQUAL(tensor(i,j,k,l), shuffle(i,j,k,l));
        }
      }
    }
  }
}

EIGEN_DECLARE_TEST(cxx11_tensor_shuffling)
{
  CALL_SUBTEST(test_simple_shuffling<ColMajor>());
  CALL_SUBTEST(test_simple_shuffling<RowMajor>());
  CALL_SUBTEST(test_expr_shuffling<ColMajor>());
  CALL_SUBTEST(test_expr_shuffling<RowMajor>());
  CALL_SUBTEST(test_shuffling_as_value<ColMajor>());
  CALL_SUBTEST(test_shuffling_as_value<RowMajor>());
  CALL_SUBTEST(test_shuffle_unshuffle<ColMajor>());
  CALL_SUBTEST(test_shuffle_unshuffle<RowMajor>());
}

max_stars_repo_name: sergiosvieira/mog

max_issues_repo_name: sergiosvieira/mog

max_forks_repo_name: sergiosvieira/mog


text:
#include <utilmm/system/process.hh>
#include <utilmm/system/system.hh>

#include "boost/thread/mutex.hpp"

#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <cstring>
#include <stdio.h>

#include <iostream>
#include <boost/version.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/exception.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

using std::list;
using std::string;
using std::cout;
using std::cerr;
using std::endl;

using namespace boost::filesystem;

namespace utilmm
{
    bool process::output_file::is_null() const
    {
        try { handle<int>(); }
        catch(std::bad_cast) { return true; }
        return false;
    }

    void process::output_file::redirect(FILE* stream)
    {
        if (is_null())
            return;

        if (dup2(handle<int>(), fileno(stream)) < 0)
            throw unix_error();
    }
}

namespace
{
    char* const* stringlist_to_execlist(list<string>& strlist)
    {
        char** ret = new char* [ strlist.size() + 1 ];
        int i = 0;
        for (list<string>::iterator it = strlist.begin(); it != strlist.end(); ++it)
            ret[i++] = const_cast<char*>(it->c_str());
        ret[ i ] = 0;
        return ret;
    }

    using utilmm::process;
    using boost::mutex;

    boost::mutex mtx_processes;
    typedef std::list<process*> ProcessList;
    typedef ProcessList::iterator       ProcessHandle;
    std::list<process*> managed_processes;

    void register_process(process* process)
    {
        sigset_t set, old_set;
        sigemptyset(&set);
        sigaddset(&set, SIGINT);

        sigprocmask(SIG_BLOCK, &set, &old_set);
        managed_processes.push_back(process);
        sigprocmask(SIG_SETMASK, &old_set, 0);
    }

    void deregister_process(process* process)
    {
        sigset_t set, old_set;
        sigemptyset(&set);
        sigaddset(&set, SIGINT);

        sigprocmask(SIG_BLOCK, &set, &old_set);
        managed_processes.remove(process);
        sigprocmask(SIG_SETMASK, &old_set, 0);
    }

    RETSIGTYPE (*old_sigint_handler)(int) = 0;
    RETSIGTYPE sigint_handler(int signum)
    {
        if (old_sigint_handler)
            old_sigint_handler(signum);
        else
            abort();
    }

}

using namespace utilmm;

process::process()
    : m_running(false), m_pid(0), m_normalexit(true), m_status(0), m_do_setpgid(false)
{
    register_process(this);
}
process::~process()
{
    deregister_process(this);
    if (m_running)
    {
        signal();
        wait(true);
    }
}

boost::filesystem::path process::workdir() const { return m_wdir; }
void        process::set_workdir(boost::filesystem::path const& wdir)
{ m_wdir = wdir; }

list<string> process::cmdline() const { return m_cmdline; }
void         process::push(const std::string& argument) { m_cmdline.push_back(argument); }
process&     process::operator << (std::string const& newarg)
{
    push(newarg);
    return *this;
}
void         process::clear() { m_cmdline.clear(); }

void process::install_sigint_handler()
{
    static bool setup = false;
    if (setup)
        return;

    struct sigaction action;
    memset(&action, 0, sizeof(struct sigaction));
    action.sa_handler = sigint_handler;

    struct sigaction old_action;
    sigaction(SIGINT, &action, &old_action);
    if (old_action.sa_flags & SA_SIGINFO)
        std::cerr << "WARNING: overriding previous SIGINT signal handler" << std::endl;
    else if (old_action.sa_handler != SIG_IGN && old_action.sa_handler != SIG_DFL)
        old_sigint_handler = old_action.sa_handler;

    setup = true;
}

void process::killall()
{
    for (ProcessList::iterator it = managed_processes.begin(); it != managed_processes.end(); ++it)
        kill((*it)->pid(), SIGINT);
}
void process::erase_redirection(Stream stream) { redirect_to(stream, ""); }
void process::redirect_to( Stream stream, boost::filesystem::path const& file)
{
#if BOOST_VERSION >= 104600
    int handle = open(file.string().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
#else
    int handle = open(file.native_file_string().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
#endif
    if (handle == -1)
        throw unix_error();

    redirect_to(stream, handle, true);
}

void process::redirect_to( Stream stream, FILE* handle, bool close_on_exit)
{
    redirect_to(stream, dup(fileno(handle)), close_on_exit);
    if (close_on_exit)
        fclose(handle);
}

void process::redirect_to( Stream stream, int handle, bool close_on_exit)
{
    if (!close_on_exit)
    {
        handle = dup(handle);
        if (handle == -1)
            throw unix_error();
    }
    get_stream(stream).reset(handle);
}

process::output_file& process::get_stream(Stream stream)
{
    switch(stream)
    {
        case Stdout: return m_stdout;
        case Stderr: return m_stderr;
    }

    // Never reached
    assert(false);
    return m_stdout;
}

void process::set_pgid(pid_t pgid)
{
    m_do_setpgid = true;
    m_pgid = pgid;
}

static const int CHDIR_ERROR = 0;
static const int EXEC_ERROR  = 1;
void process::start()
{
    if (running())
        throw already_running();

    list<string> argv = m_cmdline;
    Env          env  = m_env;

    int pc_comm[2];
    pipe(pc_comm);
    auto_close read_guard(pc_comm[0]);
    auto_close write_guard(pc_comm[1]);

    pid_t child_pid = fork();
    if (child_pid == -1)
        throw unix_error(errno);
    else if (child_pid)
    {
        // close fds on the parent side
        m_stdout.close();
        m_stderr.close();
        write_guard.close();

        // wait for the exec() to happen
        process_child_error(pc_comm[0]);

        m_pid = child_pid;
        m_running = true;
        return;
    }
    else
    {
        // in the child
        char* const* exec_argv = stringlist_to_execlist(argv);
        char* prog = exec_argv[0];

        m_stdout.redirect(stdout);
        m_stderr.redirect(stderr);
        read_guard.close();

	if (m_do_setpgid)
	    setpgid(0, m_pgid);

        // must use execvp bec. we want exec to search for prog for us
        // so, should set environment variables ourselves
        for (Env::const_iterator it = env.begin(); it != env.end(); ++it)
        {
            std::string putenv_arg = (it->first + "=" + it->second);
            putenv( strdup(putenv_arg.c_str()) );
        }

        if (!m_wdir.empty())
        {
#if BOOST_VERSION >= 104600
            if (chdir(m_wdir.string().c_str()) == -1)
#else
            if (chdir(m_wdir.native_file_string().c_str()) == -1)
#endif
                send_child_error(pc_comm[1], CHDIR_ERROR);
        }

        fcntl(pc_comm[1], F_SETFD, FD_CLOEXEC);
        execvp(prog, exec_argv);

        // Error if reached
        send_child_error(pc_comm[1], EXEC_ERROR);
    }
}

void process::process_child_error(int fd)
{
    int error_type;
    int error;
    if (read(fd, &error_type, sizeof(error_type)) == 0)
        return;
    read(fd, &error, sizeof(error));

    throw unix_error(error);
}

void process::send_child_error(int fd, int error_type)
{
    int error = errno;
    write(fd, &error_type, sizeof(error_type));
    write(fd, &error, sizeof(error));
    exit(1);
}

void process::detach()
{
    m_running = false;
    m_pid = 0;
}
void process::signal(int signo)
{
    if (!running())
        return;

    if (::kill(m_pid, signo) == 0)
        return;

    if (errno != ESRCH)
        throw unix_error();
}

void process::wait() { wait(true); }
bool process::wait(bool hang)
{
    int status;

    pid_t wait_ret = -1;
    do
    { wait_ret = waitpid(m_pid, &status, (hang ? 0 : WNOHANG) ); }
    while (wait_ret == -1 && errno == EINTR);

    if (!hang && wait_ret == 0)
        return false;

    // We consider that ECHILD means the process has terminated
    // EINTR is taken care of
    // EINVAL is an internal error

    m_running = false;

    if (wait_ret != -1) // no status information if wait_ret == -1
    {
        m_normalexit = WIFEXITED(status);
        if (m_normalexit)
            m_status = WEXITSTATUS(status);
        else m_status = 0;
    }
    return true;
}

bool  process::exit_normal() const { return m_normalexit; }
int   process::exit_status() const { return m_status; }
bool  process::running()
{
    if (! m_running)
        return false;

    wait(false);
    return m_running;
}
pid_t process::pid() const { return m_pid; }

void process::set_environment(const std::string& key, const std::string& value)
{ m_env[key] = value; }
std::string process::environment(const std::string& key) const
{
    Env::const_iterator it = m_env.find(key);
    if (it == m_env.end()) return string();
    return it->second;
}
void process::clear_environment() { m_env.clear(); }

max_stars_repo_name: annaborn/utilmm

max_issues_repo_name: annaborn/utilmm

max_forks_repo_name: annaborn/utilmm