text:
#include "stdlib/caffe/caffe_kernel.h"
#include "scanner/engine/metadata.h"

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/net.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/db.hpp"
#include "caffe/util/io.hpp"
#include "toml/toml.h"

#include <Python.h>
#include <boost/python.hpp>

namespace scanner {

using caffe::Blob;
using caffe::BlobProto;
using caffe::Caffe;
using caffe::Net;

caffe::Caffe::Brew device_type_to_caffe_mode(DeviceType type) {
  caffe::Caffe::Brew caffe_type;

  switch (type) {
    case DeviceType::GPU:
      caffe_type = caffe::Caffe::GPU;
      break;
    case DeviceType::CPU:
      caffe_type = caffe::Caffe::CPU;
      break;
    default:
      // TODO(apoms): error message
      exit(EXIT_FAILURE);
      break;
  }

  return caffe_type;
}

proto::NetDescriptor descriptor_from_net_file(
    const std::string& net_file_path) {
  std::ifstream net_file{net_file_path};

  toml::ParseResult pr = toml::parse(net_file);
  if (!pr.valid()) {
    LOG(FATAL) << pr.errorReason;
  }
  const toml::Value& root = pr.value;

  proto::NetDescriptor descriptor;

  auto net = root.find("net");
  if (!net) {
    std::cout << "Missing 'net': net description map" << std::endl;
    exit(EXIT_FAILURE);
  }

  auto model_path = net->find("model");
  if (!model_path) {
    std::cout << "Missing 'net.model': path to model" << std::endl;
    exit(EXIT_FAILURE);
  }
  auto weights_path = net->find("weights");
  if (!weights_path) {
    std::cout << "Missing 'net.weights': path to model weights" << std::endl;
    exit(EXIT_FAILURE);
  }
  auto input_layers = net->find("input_layers");
  if (!input_layers) {
    std::cout << "Missing 'net.input_layers': name of input layers "
              << std::endl;
    exit(EXIT_FAILURE);
  }
  auto output_layers = net->find("output_layers");
  if (!output_layers) {
    std::cout << "Missing 'net.output_layers': name of output layers "
              << std::endl;
    exit(EXIT_FAILURE);
  }
  auto input_format = net->find("input");
  if (!input_format) {
    std::cout << "Missing 'net.input': description of net input format "
              << std::endl;
    exit(EXIT_FAILURE);
  }
  auto dimensions_ordering = input_format->find("dimensions");
  if (!dimensions_ordering) {
    std::cout << "Missing 'net.input.dimensions': ordering of dimensions "
              << "for input format " << std::endl;
    exit(EXIT_FAILURE);
  }
  auto channel_ordering = input_format->find("channel_ordering");
  if (!channel_ordering) {
    std::cout << "Missing 'net.input.channel_ordering': ordering of channels "
              << "for input format " << std::endl;
    exit(EXIT_FAILURE);
  }

  descriptor.set_model_path(model_path->as<std::string>());
  descriptor.set_model_weights_path(weights_path->as<std::string>());
  for (const toml::Value& v : input_layers->as<toml::Array>()) {
    descriptor.add_input_layer_names(v.as<std::string>());
  }
  for (const toml::Value& v : output_layers->as<toml::Array>()) {
    descriptor.add_output_layer_names(v.as<std::string>());
  }

  auto input_width = net->find("input_width");
  auto input_height = net->find("input_height");
  auto preserve_aspect_ratio = net->find("preserve_aspect_ratio");
  bool preserve_aspect = false;
  if (preserve_aspect_ratio) {
    preserve_aspect = preserve_aspect_ratio->as<bool>();
  }
  descriptor.set_preserve_aspect_ratio(preserve_aspect);

  descriptor.set_input_width(-1);
  descriptor.set_input_height(-1);
  if (preserve_aspect) {
    if (input_height) {
      descriptor.set_input_height(input_height->as<i32>());
    } else if (input_width) {
      descriptor.set_input_width(input_width->as<i32>());
    } else {
      std::cout << "'preserve_aspect_ratio': must specify only one of "
                   "input_width or input_height"
                << std::endl;
      exit(EXIT_FAILURE);
    }
  } else if (input_width && input_height) {
    descriptor.set_input_width(input_width->as<i32>());
    descriptor.set_input_height(input_height->as<i32>());
  }

  auto pad_mod = net->find("pad_mod");
  descriptor.set_pad_mod(pad_mod ? pad_mod->as<i32>() : -1);

  auto uses_python = net->find("uses_python");
  descriptor.set_uses_python(uses_python ? uses_python->as<bool>() : false);

  auto normalize = net->find("normalize");
  descriptor.set_normalize(normalize ? normalize->as<bool>() : false);

  auto transpose = net->find("transpose");
  descriptor.set_transpose(transpose ? transpose->as<bool>() : false);

  auto mean_image = root.find("mean-image");
  if (!mean_image) {
    std::cout << "Missing 'mean-image': mean image descripton map" << std::endl;
    exit(EXIT_FAILURE);
  }

  if (mean_image->has("colors")) {
    auto mean_blue = mean_image->find("colors.blue");
    if (!mean_blue) {
      std::cout << "Missing 'mean-image.colors.blue'" << std::endl;
      exit(EXIT_FAILURE);
    }
    auto mean_green = mean_image->find("colors.green");
    if (!mean_green) {
      std::cout << "Missing 'mean-image.colors.green'" << std::endl;
      exit(EXIT_FAILURE);
    }
    auto mean_red = mean_image->find("colors.red");
    if (!mean_red) {
      std::cout << "Missing 'mean-image.colors.red'" << std::endl;
      exit(EXIT_FAILURE);
    }

    float blue = mean_blue->as<double>();
    float green = mean_green->as<double>();
    float red = mean_red->as<double>();

    for (const toml::Value& v : channel_ordering->as<toml::Array>()) {
      std::string color = v.as<std::string>();
      if (color == "red") {
        descriptor.add_mean_colors(red);
      } else if (color == "green") {
        descriptor.add_mean_colors(green);
      } else if (color == "blue") {
        descriptor.add_mean_colors(blue);
      }
    }
  } else if (mean_image->has("path")) {
    std::string mean_path = mean_image->get<std::string>("path");

    auto mean_image_width = mean_image->find("width");
    if (!mean_image_width) {
      std::cout << "Missing 'mean-image.width': width of mean" << std::endl;
      exit(EXIT_FAILURE);
    }
    auto mean_image_height = mean_image->find("height");
    if (!mean_image_height) {
      std::cout << "Missing 'mean-image.height': height of mean" << std::endl;
      exit(EXIT_FAILURE);
    }

    descriptor.set_mean_width(mean_image_width->as<int>());
    descriptor.set_mean_height(mean_image_height->as<int>());

    int mean_size = descriptor.mean_width() * descriptor.mean_height();

    // Load mean image
    Blob<float> data_mean;
    BlobProto blob_proto;
    bool result = ReadProtoFromBinaryFile(mean_path, &blob_proto);
    data_mean.FromProto(blob_proto);

    memcpy(descriptor.mutable_mean_image(), data_mean.cpu_data(),
           sizeof(float) * mean_size * 3);
  } else if (!mean_image->has("empty")) {
    std::cout << "Missing 'mean-image.{colors,path,empty}': must specify "
              << "color channel values or path of mean image file or that "
              << "there is no mean" << std::endl;
    exit(EXIT_FAILURE);
  }

  return descriptor;
}

bool file_exists(const std::string& path) {
  struct stat buffer;
  return stat(path.c_str(), &buffer) == 0;
}

CaffeKernel::CaffeKernel(const KernelConfig& config)
  : BatchedKernel(config), device_(config.devices[0]) {
  valid_.set_success(true);

  if (!args_.ParseFromArray(config.args.data(), config.args.size())) {
    RESULT_ERROR(&valid_, "CaffeKernel could not parse protobuf args");
    return;
  }

  set_device();
  // Initialize our network
  auto& descriptor = args_.net_descriptor();
  if (!file_exists(descriptor.model_path())) {
    RESULT_ERROR(&valid_, "Model path %s does not exist.",
                 descriptor.model_path().c_str());
    return;
  }
  if (!file_exists(descriptor.model_weights_path())) {
    RESULT_ERROR(&valid_, "Model weights path %s does not exist.",
                 descriptor.model_weights_path().c_str());
    return;
  }

  PyGILState_STATE gstate;
  if (descriptor.uses_python()) {
    gstate = PyGILState_Ensure();
  }
  net_.reset(new caffe::Net<float>(descriptor.model_path(), caffe::TEST));
  net_->CopyTrainedLayersFrom(descriptor.model_weights_path());
  if (descriptor.uses_python()) {
    PyGILState_Release(gstate);
  }

  // Initialize memory
  const boost::shared_ptr<caffe::Blob<float>> input_blob{
      net_->blob_by_name(descriptor.input_layer_names(0))};
  input_blob->Reshape({args_.batch_size(), input_blob->shape(1),
                       input_blob->shape(2), input_blob->shape(3)});

  size_t intended_output = descriptor.output_layer_names().size();
  size_t actual_output = config.output_columns.size();

  if (intended_output != actual_output) {
    RESULT_ERROR(
        &valid_,
        "# output columns in net descriptor (%lu) does not match number of "
        "output columns registered for op (%lu) If you have multiple net "
        "outputs, you must register your own op using the CaffeKernel.",
        intended_output, actual_output);
    return;
  }
}

void CaffeKernel::validate(proto::Result* result) {
  result->set_msg(valid_.msg());
  result->set_success(valid_.success());
}

void CaffeKernel::new_frame_info() {
  i32 frame_width = frame_info_.shape[2];
  i32 frame_height = frame_info_.shape[1];

  set_device();

  auto& descriptor = args_.net_descriptor();
  assert(descriptor.input_layer_names().size() > 0);
  const boost::shared_ptr<caffe::Blob<float>> input_blob{
      net_->blob_by_name(descriptor.input_layer_names(0))};
  if (input_blob->shape(0) != args_.batch_size()) {
    input_blob->Reshape({args_.batch_size(), input_blob->shape(1),
                         input_blob->shape(2), input_blob->shape(3)});
  }

  i32 width, height;
  if (descriptor.transpose()) {
    width = frame_height;
    height = frame_width;
  } else {
    width = frame_width;
    height = frame_height;
  }
  if (descriptor.preserve_aspect_ratio()) {
    if (descriptor.input_width() != -1) {
      width = descriptor.input_width();
      f32 scale = static_cast<f32>(descriptor.input_width()) / width;
      width = width * scale;
      height = height * scale;
    } else if (descriptor.input_height() != -1) {
      f32 scale = static_cast<f32>(descriptor.input_height()) / height;
      width = width * scale;
      height = height * scale;
    }
  } else if (descriptor.input_width() != -1) {
    width = descriptor.input_width();
    height = descriptor.input_height();
  }

  if (descriptor.pad_mod() != -1) {
    i32 pad = descriptor.pad_mod();
    width += (width % pad) ? pad - (width % pad) : 0;
    height += (height % pad) ? pad - (height % pad) : 0;
  }

  input_blob->Reshape(
      {input_blob->shape(0), input_blob->shape(1), height, width});

  net_config();
}

void CaffeKernel::execute(const BatchedColumns& input_columns,
                          BatchedColumns& output_columns) {
  check_frame(device_, input_columns[0][0]);
  set_device();

  auto& descriptor = args_.net_descriptor();
  std::vector<boost::shared_ptr<caffe::Blob<float>>> input_blobs;
  for (const std::string& name : descriptor.input_layer_names()) {
    input_blobs.emplace_back(net_->blob_by_name(name));
  }
  assert(input_blobs.size() > 0);

  PyGILState_STATE gstate;
  if (descriptor.uses_python()) {
    gstate = PyGILState_Ensure();
  }

  size_t num_outputs = descriptor.output_layer_names().size();
  i32 input_count = (i32)input_columns[0].size();
  i32 batch_size = args_.batch_size();
  for (i32 frame = 0; frame < input_count; frame += batch_size) {
    i32 batch_count = std::min(input_count - frame, batch_size);
    if (input_blobs[0]->shape(0) != batch_count) {
      input_blobs[0]->Reshape({batch_count, input_blobs[0]->shape(1),
                               input_blobs[0]->shape(2),
                               input_blobs[0]->shape(3)});
    }

    for (i32 i = 0; i < input_blobs.size(); ++i) {
      f32* net_input_buffer = nullptr;
      if (device_.type == DeviceType::GPU) {
        net_input_buffer = input_blobs[i]->mutable_gpu_data();
      } else {
        net_input_buffer = input_blobs[i]->mutable_cpu_data();
      }

      size_t offset = 0;
      for (i32 j = 0; j < batch_count; ++j) {
        const Frame* fr = input_columns[i][frame + j].as_const_frame();
        memcpy_buffer((u8*)net_input_buffer + offset, device_, fr->data,
                      device_, fr->size());
        offset += fr->size();
      }
    }

    // Compute features
    auto net_start = now();
    try {
      net_->ForwardPrefilled();
    } catch (boost::python::error_already_set) {
      PyErr_Print();
      exit(0);
    }
    if (profiler_) {
      // #ifdef SCANNER_PROFILING
      //      CUDA_PROTECT({ cudaDeviceSynchronize(); });
      // #endif
      profiler_->add_interval("caffe:net", net_start, now());
    }

    // Save batch of frames
    i32 total_rows = num_outputs * batch_count;
    for (size_t i = 0; i < num_outputs; ++i) {
      const std::string& output_layer_name = descriptor.output_layer_names(i);
      const boost::shared_ptr<caffe::Blob<float>> output_blob{
          net_->blob_by_name(output_layer_name)};

      i32 num_axes = output_blob->num_axes();
      FrameInfo info(output_blob->shape(1),
                     num_axes >= 3 ? output_blob->shape(2) : 1,
                     num_axes >= 4 ? output_blob->shape(3) : 1, FrameType::F32);

      // This is a special case to handle networks with multiple
      // outputs (like FRCNN). It checks if the batch size is 1
      // but the number of outputs is higher than that and forces the
      // frame shape to incorporate the batch size dimension
      // (the batch dimension would usually be output as multiple frames).
      // if (batch_size == 1 && output_blob->shape(0) > 1) {
      //   info = FrameInfo(output_blob->shape(0) * output_blob->shape(1),
      //                    info.shape[1],
      //                    info.shape[2],
      //                    FrameType::F32);
      // } else {
      //   assert(batch_size == output_blob->shape(0));
      // }
      u8* output_block = new_block_buffer(
          device_, info.size() * batch_count, batch_count);

      u8* src_buffer =
          (u8*)(device_.type == DeviceType::CPU ? output_blob->cpu_data()
                                                : output_blob->gpu_data());
      memcpy_buffer(output_block, device_, src_buffer, device_,
                    info.size() * batch_count);
      for (i32 b = 0; b < batch_count; b++) {
        insert_frame(output_columns[i],
                     new Frame(info, output_block + info.size() * b));
      }
    }
  }

  if (descriptor.uses_python()) {
    PyGILState_Release(gstate);
  }
}

void CaffeKernel::set_device() {
  caffe::Caffe::set_mode(device_type_to_caffe_mode(device_.type));
  if (device_.type == DeviceType::GPU) {
    CUDA_PROTECT({
      // HACK(apoms): caffe does not keep track of device it was initialized
      //  with. For example, if you call cudaSetDevice here before
      //  Caffe::SetDevice, caffe will think the GPU did not change and not
      //  reinit cublas. Need to patch caffe.
      caffe::Caffe::SetDevice(device_.id);
    });
  }
}
}

max_stars_repo_name: photoszzt/scanner

max_issues_repo_name: photoszzt/scanner


text:
// The Reactive C++ Toolbox.
// Copyright (C) 2013-2019 Swirly Cloud Limited
// Copyright (C) 2020 Reactive Markets Limited
//
// 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 "Handle.hpp"

#include <boost/test/unit_test.hpp>

#include <iostream>

using namespace std;
using namespace toolbox;

namespace {
int last_closed{};

struct TestPolicy {

    static constexpr int invalid() noexcept { return -1; }
    static void close(int id) noexcept { last_closed = id; }
};

using TestHandle = BasicHandle<TestPolicy>;

ostream& operator<<(ostream& os, const TestHandle& h)
{
    return os << h.get();
}

} // namespace

BOOST_AUTO_TEST_SUITE(HandleSuite)

BOOST_AUTO_TEST_CASE(HandleInvalidCase)
{
    last_closed = 0;

    BOOST_TEST(!TestHandle{});
    BOOST_TEST(TestHandle{}.get() == -1);
    BOOST_TEST(last_closed == 0);

    BOOST_TEST(!TestHandle{nullptr});
    BOOST_TEST(TestHandle{nullptr}.get() == -1);
    BOOST_TEST(last_closed == 0);
}

BOOST_AUTO_TEST_CASE(HandleCloseCase)
{
    last_closed = 0;

    BOOST_TEST(TestHandle{1});
    BOOST_TEST(TestHandle{1}.get() == 1);
    BOOST_TEST(last_closed == 1);
}

BOOST_AUTO_TEST_CASE(HandleReleaseCase)
{
    last_closed = 0;

    BOOST_TEST(TestHandle{1}.release() == 1);
    BOOST_TEST(last_closed == 0);
}

BOOST_AUTO_TEST_CASE(HandleResetCase)
{
    last_closed = 0;
    {
        TestHandle h{1};
        h.reset(2);
        BOOST_TEST(last_closed == 1);
    }
    BOOST_TEST(last_closed == 2);
}

BOOST_AUTO_TEST_CASE(HandleSwapCase)
{
    last_closed = 0;
    {
        TestHandle h{1};
        TestHandle{2}.swap(h);
        BOOST_TEST(last_closed == 1);
    }
    BOOST_TEST(last_closed == 2);
}

BOOST_AUTO_TEST_CASE(HandleMoveCase)
{
    last_closed = 0;

    TestHandle h{1};
    TestHandle{move(h)};
    BOOST_TEST(last_closed == 1);
    BOOST_TEST(h.get() == -1);

    h.reset(2);
    {
        TestHandle tmp;
        tmp = move(h);
    }
    BOOST_TEST(last_closed == 2);
    BOOST_TEST(h.get() == -1);
}

BOOST_AUTO_TEST_CASE(HandleEqualityCase)
{
    BOOST_TEST(TestHandle{1} == TestHandle{1});
    BOOST_TEST(TestHandle{1} != TestHandle{2});
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: mmitkevich/toolbox-cpp

max_issues_repo_name: mmitkevich/toolbox-cpp

max_forks_repo_name: mmitkevich/toolbox-cpp


text:
//////////////////////////////////////////////////////////////////////////////////////
// distribution::toolkit::distributions::inverse_pdf::description.hpp               //
//                                                                                //
//  (C) Copyright 2009 Erwann Rogard                                                //
//  Use, modification and distribution are subject to the                           //
//  Boost Software License, Version 1.0. (See accompanying file                     //
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)                //
//////////////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_MAP_PDF_INVERSE_PDF_DESCRIPTION_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_TOOLKIT_MAP_PDF_INVERSE_PDF_DESCRIPTION_HPP_ER_2009
#include <string>
#include <boost/format.hpp>
#include <boost/statistics/detail/distribution_toolkit/map_pdf/inverse_pdf/inverse_pdf.hpp>

namespace boost{
namespace statistics{
namespace detail{
namespace distribution{
namespace toolkit{

    template<typename D>
    std::string
    description(const inverse_pdf<D>& dist)
    {
        static const char* msg = "inverse_pdf<%1%>";
        format f(msg); f%description(dist.distribution());
        return (f.str());
    }

}// toolkit
}// distribution
}// detail
}// statistics
}// boost

#endif

ext: hpp


text:
// Copyright (c) 2019-2020 The Bigbang developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "leveldbeng.h"

#include <boost/filesystem/path.hpp>

#include "leveldb/cache.h"
#include "leveldb/filter_policy.h"

using namespace xengine;

namespace bigbang
{
namespace storage
{

CLevelDBArguments::CLevelDBArguments()
{
    cache = 32 << 20;
    syncwrite = false;
    files = 256;
}

CLevelDBArguments::~CLevelDBArguments()
{
}

CLevelDBEngine::CLevelDBEngine(CLevelDBArguments& arguments)
  : path(arguments.path)
{
    options.block_cache = leveldb::NewLRUCache(arguments.cache / 2);
    options.write_buffer_size = arguments.cache / 4;
    options.filter_policy = leveldb::NewBloomFilterPolicy(10);
    options.create_if_missing = true;
    options.compression = leveldb::kNoCompression;
    options.max_open_files = arguments.files;

    pdb = nullptr;
    piter = nullptr;
    pbatch = nullptr;

    readoptions.verify_checksums = true;

    writeoptions.sync = arguments.syncwrite;
    batchoptions.sync = true;
}

CLevelDBEngine::~CLevelDBEngine()
{
    delete pbatch;
    pbatch = nullptr;
    delete piter;
    piter = nullptr;
    delete pdb;
    pdb = nullptr;
    delete options.filter_policy;
    options.filter_policy = nullptr;
    delete options.block_cache;
    options.block_cache = nullptr;
}

bool CLevelDBEngine::Open()
{
    leveldb::Status status = leveldb::DB::Open(options, path, &pdb);
    if (!status.ok())
    {
        return false;
    }

    return true;
}

void CLevelDBEngine::Close()
{
    delete pbatch;
    pbatch = nullptr;
    delete piter;
    piter = nullptr;
    delete pdb;
    pdb = nullptr;
}

bool CLevelDBEngine::TxnBegin()
{
    if (pbatch != nullptr)
    {
        return false;
    }
    return ((pbatch = new leveldb::WriteBatch()) != nullptr);
}

bool CLevelDBEngine::TxnCommit()
{
    if (pbatch != nullptr)
    {
        leveldb::Status status = pdb->Write(batchoptions, pbatch);
        delete pbatch;
        pbatch = nullptr;
        return status.ok();
    }
    return false;
}

void CLevelDBEngine::TxnAbort()
{
    delete pbatch;
    pbatch = nullptr;
}

bool CLevelDBEngine::Get(CBufStream& ssKey, CBufStream& ssValue)
{
    leveldb::Slice slKey(ssKey.GetData(), ssKey.GetSize());
    std::string strValue;
    leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
    if (status.ok())
    {
        ssValue.Write(strValue.data(), strValue.size());
        return true;
    }
    return false;
}

bool CLevelDBEngine::Put(CBufStream& ssKey, CBufStream& ssValue, bool fOverwrite)
{
    leveldb::Slice slKey(ssKey.GetData(), ssKey.GetSize());
    if (!fOverwrite)
    {
        std::string strValue;
        leveldb::Status status = pdb->Get(readoptions, slKey, &strValue);
        if (status.ok() || !status.IsNotFound())
        {
            return false;
        }
    }

    leveldb::Slice slValue(ssValue.GetData(), ssValue.GetSize());
    if (pbatch != nullptr)
    {
        pbatch->Put(slKey, slValue);
        return true;
    }

    leveldb::Status status = pdb->Put(writeoptions, slKey, slValue);

    return status.ok();
}

bool CLevelDBEngine::Remove(CBufStream& ssKey)
{
    leveldb::Slice slKey(ssKey.GetData(), ssKey.GetSize());

    if (pbatch != nullptr)
    {
        pbatch->Delete(slKey);
        return true;
    }

    leveldb::Status status = pdb->Delete(writeoptions, slKey);

    return status.ok();
}

bool CLevelDBEngine::RemoveAll()
{
    Close();

    leveldb::Status status = leveldb::DestroyDB(path, options);
    if (!status.ok())
    {
        return false;
    }

    return Open();
}

bool CLevelDBEngine::MoveFirst()
{
    delete piter;

    if ((piter = pdb->NewIterator(readoptions)) == nullptr)
    {
        return false;
    }

    piter->SeekToFirst();

    return true;
}

bool CLevelDBEngine::MoveTo(CBufStream& ssKey)
{
    delete piter;

    leveldb::Slice slKey(ssKey.GetData(), ssKey.GetSize());

    if ((piter = pdb->NewIterator(readoptions)) == nullptr)
    {
        return false;
    }

    piter->Seek(slKey);

    return true;
}

bool CLevelDBEngine::MoveNext(CBufStream& ssKey, CBufStream& ssValue)
{
    if (piter == nullptr || !piter->Valid())
        return false;

    leveldb::Slice slKey = piter->key();
    leveldb::Slice slValue = piter->value();

    ssKey.Write(slKey.data(), slKey.size());
    ssValue.Write(slValue.data(), slValue.size());

    piter->Next();

    return true;
}

} // namespace storage
} // namespace bigbang

max_stars_repo_name: StoneJobs/BigBang

max_issues_repo_name: StoneJobs/BigBang

max_forks_repo_name: StoneJobs/BigBang


text:
///////////////////////////////////////////////////////////////////////////////
// main.hpp
//
//  Copyright 2005 Eric Niebler. 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 <iostream>
#include <fstream> // needed for de/serialization example (4)
#include <algorithm>
#include <boost/ref.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <boost/foreach.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
// needed for de/serialization example (4)
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>

using namespace boost;
using namespace boost::accumulators;

// Helper that uses BOOST_FOREACH to display a range of doubles
template<typename Range>
void output_range(Range const &rng)
{
    bool first = true;
    BOOST_FOREACH(double d, rng)
    {
        if(!first) std::cout << ", ";
        std::cout << d;
        first = false;
    }
    std::cout << '\n';
}

///////////////////////////////////////////////////////////////////////////////
// example1
//
//  Calculate some useful stats using accumulator_set<> and std::for_each()
//
void example1()
{
    accumulator_set<
        double
      , stats<tag::min, tag::mean(immediate), tag::sum, tag::moment<2> >
    > acc;

    boost::array<double, 4> data = {0., 1., -1., 3.14159};

    // std::for_each pushes each sample into the accumulator one at a
    // time, and returns a copy of the accumulator.
    acc = std::for_each(data.begin(), data.end(), acc);

    // The following would be equivalent, and could be more efficient
    // because it doesn't pass and return the entire accumulator set
    // by value.
    //std::for_each(data.begin(), data.end(), bind<void>(ref(acc), _1));

    std::cout << "  min""(acc)        = " << (min)(acc) << std::endl; // Extra quotes are to prevent complaints from Boost inspect tool
    std::cout << "  mean(acc)       = " << mean(acc) << std::endl;

    // since mean depends on count and sum, we can get their results, too.
    std::cout << "  count(acc)      = " << count(acc) << std::endl;
    std::cout << "  sum(acc)        = " << sum(acc) << std::endl;
    std::cout << "  moment<2>(acc)  = " << accumulators::moment<2>(acc) << std::endl;
}

///////////////////////////////////////////////////////////////////////////////
// example2
//
//  Calculate some tail statistics. This demonstrates how to specify
//  constructor and accumulator parameters. Note that the tail statistics
//  return multiple values, which are returned in an iterator_range.
//
//  It pushes data in and displays the intermediate results to demonstrate
//  how the tail statistics are updated.
void example2()
{
    // An accumulator which tracks the right tail (largest N items) and
    // some data that are covariate with them. N == 4.
    accumulator_set<
        double
      , stats<tag::tail_variate<double, tag::covariate1, right> >
    > acc(tag::tail<right>::cache_size = 4);

    acc(2.1, covariate1 = .21);
    acc(1.1, covariate1 = .11);
    acc(2.1, covariate1 = .21);
    acc(1.1, covariate1 = .11);

    std::cout << "  tail            = "; output_range(tail(acc));
    std::cout << "  tail_variate    = "; output_range(tail_variate(acc));
    std::cout << std::endl;

    acc(21.1, covariate1 = 2.11);
    acc(11.1, covariate1 = 1.11);
    acc(21.1, covariate1 = 2.11);
    acc(11.1, covariate1 = 1.11);

    std::cout << "  tail            = "; output_range(tail(acc));
    std::cout << "  tail_variate    = "; output_range(tail_variate(acc));
    std::cout << std::endl;

    acc(42.1, covariate1 = 4.21);
    acc(41.1, covariate1 = 4.11);
    acc(42.1, covariate1 = 4.21);
    acc(41.1, covariate1 = 4.11);

    std::cout << "  tail            = "; output_range(tail(acc));
    std::cout << "  tail_variate    = "; output_range(tail_variate(acc));
    std::cout << std::endl;

    acc(32.1, covariate1 = 3.21);
    acc(31.1, covariate1 = 3.11);
    acc(32.1, covariate1 = 3.21);
    acc(31.1, covariate1 = 3.11);

    std::cout << "  tail            = "; output_range(tail(acc));
    std::cout << "  tail_variate    = "; output_range(tail_variate(acc));
}

///////////////////////////////////////////////////////////////////////////////
// example3
//
//  Demonstrate how to calculate weighted statistics. This example demonstrates
//  both a simple weighted statistical calculation, and a more complicated
//  calculation where the weight statistics are calculated and stored in an
//  external weight accumulator.
void example3()
{
    // weight == double
    double w = 1.;

    // Simple weighted calculation
    {
        // stats that depend on the weight are made external
        accumulator_set<double, stats<tag::mean>, double> acc;

        acc(0., weight = w);
        acc(1., weight = w);
        acc(-1., weight = w);
        acc(3.14159, weight = w);

        std::cout << "  mean(acc)       = " << mean(acc) << std::endl;
    }

    // Weighted calculation with an external weight accumulator
    {
        // stats that depend on the weight are made external
        accumulator_set<double, stats<tag::mean>, external<double> > acc;

        // Here's an external weight accumulator
        accumulator_set<void, stats<tag::sum_of_weights>, double> weight_acc;

        weight_acc(weight = w); acc(0., weight = w);
        weight_acc(weight = w); acc(1., weight = w);
        weight_acc(weight = w); acc(-1., weight = w);
        weight_acc(weight = w); acc(3.14159, weight = w);

        std::cout << "  mean(acc)       = " << mean(acc, weights = weight_acc) << std::endl;
    }
}

///////////////////////////////////////////////////////////////////////////////
// example4
//
//  Show how accumulators could be persisted into a file, and then continued
//  from where they were left of
//
void example4()
{
    accumulator_set<
        double
      , stats<tag::min, tag::mean(immediate), tag::sum, tag::moment<2>, tag::p_square_quantile, tag::kurtosis >
    > acc(quantile_probability = 0.9);

    {
        // accumulate values from array
        boost::array<double, 10> data = {-10., -8., -7., -6., -5., -4., -3., -2., -1., 0.};

        acc = std::for_each(data.begin(), data.end(), acc);
    }

    std::cout << "  min        = " << (min)(acc) << std::endl;
    std::cout << "  mean       = " << mean(acc) << std::endl;
    std::cout << "  count      = " << count(acc) << std::endl;
    std::cout << "  sum        = " << sum(acc) << std::endl;
    std::cout << "  moment<2>  = " << accumulators::moment<2>(acc) << std::endl;
    std::cout << "  p_square_quantile  = " << accumulators::p_square_quantile(acc) << std::endl;
    std::cout << "  kurtosis   = " << accumulators::kurtosis(acc) << std::endl;

    // save accumulator list into a file called "saved-stats"
    const unsigned ACC_VER = 0;
    const char* file_name = "saved-stats";
    {
        std::ofstream ofs(file_name);
        boost::archive::text_oarchive oa(ofs);
        acc.serialize(oa, ACC_VER);
    }

    // create a new accumulator set and initialize from data saved into the file
    accumulator_set<
        double
      , stats<tag::min, tag::mean(immediate), tag::sum, tag::moment<2>, tag::p_square_quantile, tag::kurtosis >
    > restored_acc(quantile_probability = 0.9);

    {
        std::ifstream ifs(file_name);
        boost::archive::text_iarchive ia(ifs);
        restored_acc.serialize(ia, ACC_VER);
    }

    // continue accumulating into both sets
    {
        // accumulate values from array
        boost::array<double, 10> data = {10., 8., 7., 6., 5., 4., 3., 2., 1., 0.};

        acc = std::for_each(data.begin(), data.end(), acc);
        restored_acc = std::for_each(data.begin(), data.end(), restored_acc);
    }

    // validate that both return th same values
    std::cout << std::endl << "Values in original set:" << std::endl;
    std::cout << "  min""(acc)        = " << (min)(acc) << std::endl;
    std::cout << "  mean(acc)       = " << mean(acc) << std::endl;
    std::cout << "  count(acc)      = " << count(acc) << std::endl;
    std::cout << "  sum(acc)        = " << sum(acc) << std::endl;
    std::cout << "  moment<2>(acc)  = " << accumulators::moment<2>(acc) << std::endl;
    std::cout << "  p_square_quantile(acc)  = " << accumulators::p_square_quantile(acc) << std::endl;
    std::cout << "  kurtosis(acc)  = " << accumulators::kurtosis(acc) << std::endl;

    std::cout << std::endl << "Values in restored set:" << std::endl;
    std::cout << "  min""(acc)        = " << (min)(restored_acc) << std::endl;
    std::cout << "  mean(acc)       = " << mean(restored_acc) << std::endl;
    std::cout << "  count(acc)      = " << count(restored_acc) << std::endl;
    std::cout << "  sum(acc)        = " << sum(restored_acc) << std::endl;
    std::cout << "  moment<2>(acc)  = " << accumulators::moment<2>(restored_acc) << std::endl;
    std::cout << "  p_square_quantile(acc)  = " << accumulators::p_square_quantile(restored_acc) << std::endl;
    std::cout << "  kurtosis(acc)  = " << accumulators::kurtosis(restored_acc) << std::endl;

}

///////////////////////////////////////////////////////////////////////////////
// main
int main()
{
    std::cout << "Example 1:\n";
    example1();

    std::cout << "\nExample 2:\n";
    example2();

    std::cout << "\nExample 3:\n";
    example3();

    std::cout << "\nExample 4:\n";
    example4();

    return 0;
}


text:
#include <boost/log/trivial.hpp>

#include "engine/core/app.h"
#include "engine/sounds/streamable.h"
#include "engine/sounds/music.h"

#include <iostream>

namespace po = boost::program_options;

int main(int argc, char ** argv)
{
  try
  {
    std::filesystem::path audioFile;

    engine::App app;
    app.add_options()
      ("file,f", po::value<std::filesystem::path>(&audioFile), "Ogg/Vorbis audio file");

    app
      .enableAudio()
      .enableAsio();

    if(app.run(argc, argv))
    {
      auto streamable = std::make_shared<engine::VorbisStreamable>(audioFile);
      engine::Music music(app.asioContext());
      music.play(streamable);

      std::string command;
      do
      {
        std::getline(std::cin, command);
      }
      while(command != "q");

      app.stopAsio();
    }

    return 0;
  }
  catch(const std::exception & e)
  {
    BOOST_LOG_TRIVIAL(error) << e.what();
    return -1;
  }
}

max_stars_repo_name: smallduckinette/engine

max_issues_repo_name: smallduckinette/engine

max_forks_repo_name: smallduckinette/engine


text:
// Copyright (c) 2016 Matthias Noack <ma.noack.pr@gmail.com>
//
// See accompanying file LICENSE and README for further information.

#ifndef noma_typa_parser_error_hpp
#define noma_typa_parser_error_hpp

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

namespace noma {
namespace typa {

/**
 * Parser exception type to propagate parsing errors.
 */
//class parse_error : public std::runtime_error
//{
//public:
//	parse_error(const std::string& msg) : runtime_error(msg) { };
//};

/**
 * Parser exception type to propagate parsing errors.
 * This implementation is compatible with boost program options which
 * catches bad_lexical_cast, but sadly, doesn't allow to transport a
 * custom message.
 */
class parser_error : public boost::bad_lexical_cast
{
public:
	parser_error(const std::string& msg) {};// : runtime_error(msg) { };
};

} // namespace typa
} // namespace noma

#endif // noma_typa_parser_error_hpp

max_stars_repo_name: noma/typa

max_issues_repo_name: noma/typa

max_forks_repo_name: noma/typa


text:
/*
 *
 *  Copyright (c) 2015-2017 Stanislav Zhukov
 *
 *  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 "Plugin.hpp"

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

Plugin::PluginList Plugin::plugins;
bool init = false;
template<typename... Types>
constexpr char TypeString<Types...>::value[];
constexpr FunctionData Plugin::functions[];
constexpr FunctionCallbackData Plugin::callbacks[];

using namespace std;

Plugin::Plugin(const char *path)
{
    FILE* file = fopen(path, "rb");

    if (!file)
        throw runtime_error("Script not found: " + string(path));
    fclose(file);

    SystemInterface<>::lib_t handle;
    try
    {
#ifdef __WIN32__
        handle = LoadLibrary(path);
#else
        handle = dlopen(path, RTLD_LAZY);
#endif
        lib = handle;

        const char* prefix = GetFunction<const char*>("prefix");
        if(!prefix)
            printf("Prefix not found. %s\n", path);
        string ppf(prefix);
        for (const auto& func : functions)
            if (!SetFunction(string(ppf + func.name), func.func.addr))
                printf("Script function pointer not found: %s\n", func.name);
    }
    catch(exception &e)
    {
#ifdef __WIN32__
        FreeLibrary(handle);
#else
        dlclose(handle);
#endif
        printf("Exception: %s\n", e.what());
        throw;
    }
}

Plugin::~Plugin()
{
#ifdef __WIN32__
    FreeLibrary(lib);
#else
    dlclose(lib);
#endif
}

template<typename R>
bool Plugin::SetFunction(const string& name, R value)
{
    SystemInterface<R*> result(lib, name.c_str());

    if (result)
        *result.result = value;

    return result.operator bool();
}

void Plugin::LoadPlugin(const char* plugin)
{
    try
    {
        Plugin::plugins.emplace_back(new Plugin(plugin));
    }
    catch (...)
    {
        UnloadPlugins();
        throw runtime_error("plugin " + string(plugin)+" not loaded!");
    }
}

void Plugin::UnloadPlugins()
{
    Plugin::Call<Plugin::Hash("OnUnload")>();
    plugins.clear();
}

void Plugin::LoadPlugins(string plugindir)
{
    namespace fs = boost::filesystem;
    try
    {
        string basepath = fs::current_path()/*.parent_path()*/.string();

        fs::path someDir(basepath + static_cast<char>(fs::path::preferred_separator) + plugindir);
        fs::directory_iterator end_iter;

        if (fs::exists(someDir) && fs::is_directory(someDir))
            for (fs::directory_iterator dir_iter(someDir); dir_iter != end_iter; ++dir_iter)
            {
                if (dir_iter->path().string().find(".so") != std::string::npos)
                    Plugin::LoadPlugin(dir_iter->path().string().c_str());
            }
        Plugin::Call<Plugin::Hash("OnLoad")>();
    }
    catch (exception &e)
    {
        cout << e.what() << endl;
    }
}

max_stars_repo_name: Koncord/YAPE

max_issues_repo_name: Koncord/YAPE

max_forks_repo_name: Koncord/YAPE


text:
/*
Copyright 2017 hoxnox <hoxnox@gmail.com>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <sstream>

#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <yandex/disk.hpp>
#include <logging.hpp>

#include "tls_transport.hpp"

namespace yandex {
namespace disk {

class url_t;

struct api::api_impl_
{
	url_t get_upload_url(const std::string& destination, bool overwrite);
	std::shared_ptr<transport> cmd_transport{nullptr};
};

api::api(std::string token, bool cert_check)
	: impl_(new api_impl_)
{
	impl_->cmd_transport = std::make_shared<tls_transport>(token, "cloud-api.yandex.net", 443, !cert_check, 0);
}

api::api(std::shared_ptr<transport> transport)
	: impl_(new api_impl_)
{
	impl_->cmd_transport = transport;
}

api::~api()
{
	if (impl_)
		delete impl_;
}

inline
std::string hex(unsigned char c)
{
	std::string rs;
	const char hex[] = "0123456789ABCDEF";
	rs += hex[c/0x10];
	rs += hex[c%0x10];
	return rs;
}

inline std::string
url_encode(std::string str)
{
	std::stringstream rs;
	for (auto c : str)
	{
		if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~')
			rs << c;
		else if (c == ' ')
			rs << '+';
		else
			rs << '%' << hex(c);
	}
	return rs.str();
}

template<class InIter> inline InIter
check_prefix(InIter begin, InIter end, std::string prefix)
{
	if (end < begin || end - begin < prefix.length())
		return end;
	if (std::equal(begin, begin + prefix.length(), prefix.data()))
		return begin + prefix.length();
	return end;
}

class url_t
{
public:
	url_t(std::string host = "", uint16_t port = 0, std::string suffix = "")
		: host(host), port(port), suffix(suffix)
	{ }
	static url_t from_string(std::string url)
	{
		std::string host, suffix;
		uint16_t port = 0;
		auto pos = url.begin();
		if ((pos = check_prefix(url.begin(), url.end(), "https://")) == url.end())
			return {};
		auto host_end_pos = std::find(pos, url.end(), '/');
		if (host_end_pos != url.end())
			suffix = std::string(host_end_pos, url.end());
		std::string host_port = std::string(pos, host_end_pos);
		size_t colon_pos = host_port.find(':');
		if (colon_pos)
		{
			host = std::string(pos, pos + colon_pos);
			try
			{
				port = boost::lexical_cast<uint16_t>(std::string(pos + colon_pos + 1, host_end_pos));
			}
			catch (boost::bad_lexical_cast& e)
			{
				return {};
			}
		}
		else
		{
			host = host_port;
		}
		return {host, port, suffix};
	}
	std::string str() const
	{
		std::stringstream ss;
		ss << _(" Host: ") << host
		   << _(", port: ") << port
		   << _(", suffix: ") << suffix;
		return ss.str();
	}

	operator bool() { return !host.empty(); }

	std::string host;
	std::string suffix;
	uint16_t port;
};

template<class InIter> inline std::string
bytes2str(InIter begin, InIter end)
{
	std::string rs;
	while (begin != end)
		rs += hex(*begin++);
	return rs;
}

inline const uint8_t*
find_response_body(const uint8_t* begin, const uint8_t* end)
{
	const uint8_t body_end[] = {'\r', '\n', '\r', '\n'};
	const uint8_t* rs = std::search(begin, end, body_end, body_end + sizeof(body_end));
	if (rs == end)
		return end;
	return rs + 4;
}

template<class InIter> inline InIter
find_response_body(InIter begin, InIter end)
{
	const uint8_t body_end[] = {'\r', '\n', '\r', '\n'};
	InIter rs = std::search(begin, end, body_end, body_end + sizeof(body_end));
	if (rs == end)
		return end;
	return rs + 4;
}

inline std::string
fetch_upload_url(std::string str)
{
	auto pos = str.begin();
	auto end = str.end();
	if ((pos = find_response_body(pos, end)) == end)
		return {};
	std::string link_prefix = "\"href\":\"";
	if ((pos = std::search(pos, end, link_prefix.begin(), link_prefix.end())) == end)
		return {};
	pos += link_prefix.length();
	auto href_end = std::find(pos, end, '\"');
	if (href_end == end)
		return {};
	 return {pos, href_end};
}

url_t
api::api_impl_::get_upload_url(const std::string& destination, bool overwrite)
{
	std::string raw_response;
	std::string url = "/v1/disk/resources/upload?path=" + url_encode(destination);
    if (overwrite)
        url += "&overwrite=true";
	auto rs = cmd_transport->get(url,
			[&raw_response, &url](const std::string& url_, const uint8_t* data, size_t datasz)
			{
				if (url == url_)
					raw_response += std::string(data, data + datasz);
			});
	if (!rs || raw_response.empty())
	{
		ELOG << _("Error receiving GET response. ") << rs;
		return {};
	}
	VLOG << _("Successful executed GET request for put data.")
	     << _(" Raw: ") << raw_response;
	std::string upload_url = fetch_upload_url(raw_response);
	if (upload_url.empty())
	{
		ELOG << _("Error fetching upload URL.");
		return {};
	}
	VLOG << _("URL fetched. Parsing. ") << upload_url;
	auto parsed_upload_url = url_t::from_string(upload_url);
	if (!parsed_upload_url)
	{
		ELOG << _("Error parsing upload URL.")
		     << _(" URL: ") << upload_url;
		return {};
	}
	VLOG << ("Got upload url. ") << parsed_upload_url.str();
	return parsed_upload_url;
}

/**@note Don't escape special symbols in parameters. Use UTF-8.*/
bool
api::upload(std::string source, std::string destination, bool overwrite, size_t chunksz)
{
	boost::filesystem::path fs_source(source);
	std::ifstream ifile(fs_source.string().c_str(), std::ios::binary);
	if (!ifile.good())
	{
		ELOG << _("Error opening file.")
		     << _(" Filename: \"") << fs_source.string() << "\"";
		return false;
	}
	return upload(destination, ifile, overwrite, chunksz);
}

bool
api::upload(std::string destination, std::istream& strm, bool overwrite, size_t size, size_t chunksz)
{
	auto url = impl_->get_upload_url(destination, overwrite);
	if (!url)
		return false;

	auto put_transport = impl_->cmd_transport->make_transport(url.host, url.port, chunksz);
	auto rs = put_transport->put(url.suffix, strm, size);
	if (!rs)
	{
		ELOG << _("Error putting. ") << rs;
		return false;
	}
	return true;
}

}} // namespace

max_stars_repo_name: hoxnox/yadisk-upload

max_issues_repo_name: hoxnox/yadisk-upload

max_forks_repo_name: hoxnox/yadisk-upload


text:
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

#include "graph_filtering.hh"
#include "graph_python_interface.hh"

#include <boost/python.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/undirected_dfs.hpp>

#include "graph.hh"
#include "graph_selectors.hh"
#include "graph_util.hh"

using namespace std;
using namespace boost;
using namespace graph_tool;

class DFSVisitorWrapper
{
public:
    DFSVisitorWrapper(python::object& gi, python::object vis)
        : _gi(gi), _vis(vis) {}

    template <class Vertex, class Graph>
    void initialize_vertex(Vertex u, const Graph&)
    {
        _vis.attr("initialize_vertex")(PythonVertex(_gi, u));
    }
    template <class Vertex, class Graph>
    void start_vertex(Vertex u, const Graph&)
    {
        _vis.attr("start_vertex")(PythonVertex(_gi, u));
    }
    template <class Vertex, class Graph>
    void discover_vertex(Vertex u, const Graph&)
    {
        _vis.attr("discover_vertex")(PythonVertex(_gi, u));
    }

    template <class Edge, class Graph>
    void examine_edge(Edge e, const Graph&)
    {
        _vis.attr("examine_edge")
            (PythonEdge<Graph>(_gi, e));
    }

    template <class Edge, class Graph>
    void tree_edge(Edge e, const Graph&)
    {
        _vis.attr("tree_edge")
            (PythonEdge<Graph>(_gi, e));
    }

    template <class Edge, class Graph>
    void back_edge(Edge e, const Graph&)
    {
        _vis.attr("back_edge")
            (PythonEdge<Graph>(_gi, e));
    }

    template <class Edge, class Graph>
    void forward_or_cross_edge(Edge e, const Graph&)
    {
        _vis.attr("forward_or_cross_edge")
            (PythonEdge<Graph>(_gi, e));
    }

    template <class Vertex, class Graph>
    void finish_vertex(Vertex u, const Graph&)
    {
        _vis.attr("finish_vertex")(PythonVertex(_gi, u));
    }

private:
    python::object _gi, _vis;
};

struct do_dfs
{
    template <class Graph, class VertexIndexMap>
    void operator()(Graph& g, VertexIndexMap vertex_index, size_t s,
                    DFSVisitorWrapper vis) const
    {
        typename property_map_type::apply<default_color_type,
                                          VertexIndexMap>::type
            color(vertex_index);
        depth_first_visit(g, vertex(s, g), vis, color);
    }
};

void dfs_search(GraphInterface& g, python::object gi, size_t s,
                python::object vis)
{
    run_action<graph_tool::detail::all_graph_views,mpl::true_>()
        (g, std::bind(do_dfs(), placeholders::_1, g.GetVertexIndex(),
                      s, DFSVisitorWrapper(gi, vis)))();
}

void export_dfs()
{
    using namespace boost::python;
    def("dfs_search", &dfs_search);
}

ext: cc

max_stars_repo_name: johankaito/fufuka

max_issues_repo_name: johankaito/fufuka

max_forks_repo_name: johankaito/fufuka


text:
#include "WindowsEventListener.h"

#include <algorithm>
#include <iterator>
#include <sstream>
#include <fstream>

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/format.hpp>

// Link with the event lib
#pragma comment(lib, "wevtapi.lib")

DWORD WINAPI eventListenerCallback(EVT_SUBSCRIBE_NOTIFY_ACTION action, PVOID context, EVT_HANDLE event_handle)
{
    auto* event_listener = reinterpret_cast<WindowsEventListener*>(context);
    return event_listener->callbackImpl(action, EventHandleUniquePtr(event_handle));
}

WindowsEventListener::WindowsEventListener(
    const std::filesystem::path& query_path,
    const std::optional<std::filesystem::path>& bookmark_path)
    : query_path_(query_path)
    , bookmark_path_(bookmark_path)
{
    if (!std::filesystem::exists(query_path_))
    {
        const auto message = boost::format("Query file doesn't exist: %1%") % query_path;
        throw std::runtime_error(message.str());
    }
}

WindowsEventListener::~WindowsEventListener()
{
    EvtClose(subscription_handle_.release());
    bookmark_.reset();
}

void WindowsEventListener::start()
{
    constexpr EVT_HANDLE local_computer = nullptr;
    constexpr HANDLE null_signal_event_because_using_callback = nullptr;
    constexpr LPCWSTR unused_channel_name = nullptr;
    PVOID context = reinterpret_cast<PVOID>(this);

    if (bookmark_path_.has_value())
    {
        bookmark_.emplace(*bookmark_path_);
    }

    auto query = readXmlFile(query_path_);

    subscription_handle_.reset(EvtSubscribe(local_computer,
        null_signal_event_because_using_callback,
        unused_channel_name,
        query.c_str(),
        bookmark_.has_value() ? bookmark_->getHandle() : nullptr,
        context,
        eventListenerCallback,
        bookmark_.has_value() ? EvtSubscribeStartAfterBookmark : EvtSubscribeStartAtOldestRecord));

    if (subscription_handle_ == nullptr)
    {
        auto status = GetLastError();

        std::stringstream message_stream;

        if (ERROR_EVT_CHANNEL_NOT_FOUND == status)
        {
            message_stream << "Channel was not found\n";
        }
        else if (ERROR_EVT_INVALID_QUERY == status)
        {
            message_stream << "Query is not valid\n";

            DWORD buffer_size = 0;
            EvtGetExtendedStatus(0, nullptr, &buffer_size);
            std::vector<WCHAR> buffer(buffer_size);
            EvtGetExtendedStatus(buffer_size, buffer.data(), &buffer_size);

            message_stream << "details: " << toString(buffer) << "\n";
        }
        else
        {
            message_stream << "EvtSubscribe failed with code: " << status << "\n";
        }

        throw std::runtime_error(message_stream.str());
    }
}

void WindowsEventListener::updateBookmark()
{
    if (bookmark_.has_value())
    {
        bookmark_->save();
    }
}

DWORD WindowsEventListener::callbackImpl(EVT_SUBSCRIBE_NOTIFY_ACTION action, EventHandleUniquePtr event_handle) noexcept
{
    try
    {
        switch (action)
        {
        case EvtSubscribeActionDeliver:
        {
            if (bookmark_.has_value())
            {
                bookmark_->update(event_handle.get());
            }

            constexpr EVT_RENDER_FLAGS render_flag = EvtRenderEventXml;
            const auto event_message = renderEvent(event_handle.get(), render_flag);

            publish(event_message);

            break;
        }
        default:
        {
            throw std::runtime_error("WindowsEventListener::callbackImpl failed with: Unkown action");
        }
        }
    }
    catch (const std::exception&)
    {
        publish(std::current_exception());
    }

    constexpr auto ignored = ERROR_SUCCESS;
    return ignored;
}


text:
#define BOOST_TEST_MODULE PresentationContextAC
#include <boost/test/unit_test.hpp>

#include <sstream>
#include <string>
#include <vector>

#include "odil/Exception.h"
#include "odil/pdu/PresentationContextAC.h"

std::string const data(
    "\x21\x00\x00\x17"
    "\x03\x00\x01\x00"
    "\x40\x00\x00\x0f""transfer_syntax",
    27
);

BOOST_AUTO_TEST_CASE(Constructor)
{
    odil::pdu::PresentationContextAC const context(1, "transfer_syntax", 2);

    BOOST_REQUIRE_EQUAL(context.get_item_type(), 0x21);
    BOOST_REQUIRE_EQUAL(context.get_id(), 0x1);
    BOOST_REQUIRE_EQUAL(context.get_result_reason(), 0x2);
    BOOST_REQUIRE_EQUAL(context.get_transfer_syntax(), "transfer_syntax");
}

BOOST_AUTO_TEST_CASE(Id)
{
    odil::pdu::PresentationContextAC context(1, "transfer_syntax", 1);
    context.set_id(123);
    BOOST_REQUIRE_EQUAL(context.get_id(), 123);
}

BOOST_AUTO_TEST_CASE(TransferSyntax)
{
    odil::pdu::PresentationContextAC context(1, "transfer_syntax", 1);
    context.set_transfer_syntax("foo");
    BOOST_REQUIRE_EQUAL(context.get_transfer_syntax(), "foo");
}

BOOST_AUTO_TEST_CASE(Write)
{
    odil::pdu::PresentationContextAC context(3, "transfer_syntax", 1);

    std::ostringstream stream;
    stream << context;

    BOOST_REQUIRE_EQUAL(stream.str(), data);
}

BOOST_AUTO_TEST_CASE(Read)
{
    std::istringstream stream(data);

    odil::pdu::PresentationContextAC const context(stream);

    BOOST_REQUIRE_EQUAL(context.get_item_type(), 0x21);
    BOOST_REQUIRE_EQUAL(context.get_id(), 3);
    BOOST_REQUIRE_EQUAL(context.get_result_reason(), 1);
    BOOST_REQUIRE_EQUAL(context.get_transfer_syntax(), "transfer_syntax");
}

max_stars_repo_name: genisysram/odil

max_issues_repo_name: genisysram/odil

max_forks_repo_name: genisysram/odil


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Sylko Olzscher
 *
 */

#include <smf/http/srv/auth.h>
#include <cyng/dom/reader.h>
#include <cyng/io/serializer.h>
#include <cyng/value_cast.hpp>
#include <cyng/crypto/base64.h>
#include <cyng/util/split.h>
#include <boost/assert.hpp>
#include <boost/algorithm/string/predicate.hpp>

namespace node
{
	void init(cyng::object obj, auth_dirs& result)
	{
		cyng::vector_t cfg;
		cfg = cyng::value_cast(obj, cfg);
		for (auto d : cfg)
		{
			auto dom = cyng::make_reader(d);

 			result.emplace(std::piecewise_construct,
              std::forward_as_tuple(cyng::io::to_str(dom.get("directory"))),
              std::forward_as_tuple(cyng::io::to_str(dom.get("authType"))
			  , cyng::io::to_str(dom.get("name"))
			  , cyng::io::to_str(dom.get("pwd"))
			  , cyng::io::to_str(dom.get("realm"))
			));
		}
	}

	std::pair<auth, bool> authorization_required(boost::string_view path, auth_dirs const& ad)
	{
		for (auto dir : ad)
		{
			boost::string_view cmp(dir.first.c_str(), dir.first.size());
 			if (boost::algorithm::starts_with(path, cmp))	return std::make_pair(dir.second, true);
		}
		return std::make_pair(auth(), false);
	}

	bool authorization_test(boost::string_view value, auth const& ident)
	{
		std::vector<boost::string_view> parts = cyng::split(value, "\t ");
		BOOST_ASSERT_MSG(parts.size() == 2, "invalid authorization field");
		if (parts.size() == 2 && (parts.at(0) == "Basic"))
		{
			return ident.basic_credentials() == parts.at(1);
		}
		return false;
	}

	auth::auth()
	: type_()
	, user_()
	, pwd_()
	, realm_()
	{}

	auth::auth(std::string const& type, std::string const& user, std::string const& pwd, std::string const& realm)
	: type_(type)
	, user_(user)
	, pwd_(pwd)
	, realm_(realm)
	{}

	std::string auth::basic_credentials() const
	{
		return cyng::crypto::base64_encode(user_ + ":" + pwd_);
	}

}

max_stars_repo_name: solosTec/node

max_issues_repo_name: solosTec/node

max_forks_repo_name: solosTec/node


text:
/*
 * Copyright 2015 David A. Boyuka II
 *
 * 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.
 */

/*
 * sharedfile-format-index-io.hpp
 *
 *  Created on: Sep 5, 2014
 *      Author: David A. Boyuka II
 */
#ifndef SHAREDFILE_FORMAT_INDEX_IO_HPP_
#define SHAREDFILE_FORMAT_INDEX_IO_HPP_

#include <boost/smart_ptr.hpp>
#include <boost/none.hpp>
#include <boost/optional.hpp>

#include "pique/io/index-io.hpp"
#include "pique/util/datatypes.hpp"

/*
 * An abstract helper base class, which must be derived to fill in the actual file IO details.
 * The assumptions/guarantees built into this base class are as follows:
 * > The index will be stored in a single, contiguous file or similar backend
 * > It must be possible to open an std::istream or std::ostream into this file at any time (although istreams will only be requested in read mode and ostreams in write mode)
 * > Partition IDs will be dense; that is, for a file with N partitions, the partition IDs will be 0 through N-1
 * > Partitions commited to the central IndexIO (see on_partition_committed) shall be packed sequentially in file
 */
class SharedFileFormatIndexIO : public IndexIO {
public:
	SharedFileFormatIndexIO();
	virtual ~SharedFileFormatIndexIO() { this->close(); }

private:
	// Return based on internal metadata. Valid in both read and write mode; override to return error if they shouldn't be valid in write mode.
	virtual GlobalMetadata get_global_metadata_impl();
	virtual std::vector< GlobalPartitionMetadata > get_partition_metadata_impl(partition_id_t begin_partition, partition_id_t end_partition);

protected:
	void init_metadata_empty();
	void read_metadata_from_disk();
	void write_metadata_to_disk(); // Call to write IndexIO metadata to disk if in write mode (usually called in close_impl())

	// Accepts any committed partition_id_t, or one past the end, which will return the location where the next committed partition will be located
	uint64_t get_partition_offset_in_file(partition_id_t partition_id);

	// Stores appropriate metadata for the partition, and returns an assigned partition ID. Usually
	// called by child IndexPartitionIOs as part of its commit_partition().
	partition_id_t commit_partition(uint64_t partition_offset_in_file, uint64_t partition_size, GlobalPartitionMetadata pmeta);

	// Derived implementation to-do:
protected:
	// Always call up to these from derived classes
	virtual bool open_impl(std::string path, IndexOpenMode openmode) = 0;
	virtual bool close_impl() = 0;

private:
	virtual boost::shared_ptr< IndexPartitionIO > get_partition_impl(partition_id_t partition) = 0;
	virtual boost::shared_ptr< IndexPartitionIO > append_partition_impl() = 0;

	// Implemented by derived classes, these functions provide a window into the actual underlying shared file
	// for_reading_large_data indicates whether a large amount of data is expected to be read from/written to
	// the file through this stream. Metadata uses false, region data uses true. May safely be ignored, provided
	// only for the purpose of potential optimization.
	virtual std::istream & open_input_stream(bool for_reading_large_data) = 0;
	virtual std::ostream & open_output_stream(bool for_reading_large_data) = 0;
	virtual void close_input_stream(std::istream &in) = 0;
	virtual void close_output_stream(std::ostream &out) = 0;

private:
	// Header/footer structs for (de)serialization
	struct segment_offsets_header_t {
		uint64_t partition_segment_offset;
		uint64_t footer_segment_offset;

	    friend class boost::serialization::access;
	    template<class Archive> void serialize(Archive & ar, const unsigned int version);
	};
	struct footer_t {
		std::vector< uint64_t > partition_offsets; // Absolute in file, last offset is end offset (i.e. N+1 offsets for N partitions)
		std::vector< GlobalPartitionMetadata > partition_metadatas; // Just use GlobalPartitionMetadata directly, since we aren't doing anything fancy here

		friend class boost::serialization::access;
	    template<class Archive> void serialize(Archive & ar, const unsigned int version);
	};

	SerializableChunk< segment_offsets_header_t > segment_offsets_header;
	SerializableChunk< footer_t > footer;

	friend class SharedFileFormatIndexPartitionIO;
};

class SharedFileFormatIndexPartitionIO : public IndexPartitionIO {
public:
	SharedFileFormatIndexPartitionIO(SharedFileFormatIndexIO &parent, boost::optional< partition_id_t > partition_id, boost::optional< uint64_t > partition_offset_in_file);
	virtual ~SharedFileFormatIndexPartitionIO() { this->close(); }

	virtual IOStats get_io_stats() const { return region_io_stats + partition_header.get_stats(); }
	virtual void reset_io_stats() { region_io_stats = IOStats(); }

private:
	virtual PartitionMetadata get_partition_metadata_impl();
	virtual region_count_t get_num_regions_impl();

	virtual uint64_t compute_regions_size_impl(region_id_t lb, region_id_t ub); // [lb, ub)
	virtual bool read_regions_impl(const std::set< region_id_t > &regions_to_read, std::map< region_id_t, boost::shared_ptr< RegionEncoding > > &regions);

	virtual void set_partition_metadata_impl(PartitionMetadata metadata);
	virtual bool write_regions_impl(const std::vector< boost::shared_ptr< RegionEncoding > > &regions);

protected:
	void init_metadata_empty();
	void read_metadata_from_disk();
	void write_partition_to_disk();

protected:
	// Default implementation of open calls init_metadata_empty()/read_metadata_from_disk as appropriate
	// Default implemenation of close calls write_partition_to_disk() if in write mode
	// Optional: override for non-default behavior
	// Always call up to these from derived classes (if overridden)
	virtual bool open_impl(IndexOpenMode openmode);
	virtual bool close_impl();
private:

	// Used by derived classes to specify whether the size of the partition need be computed
	// in order to allocate it.
	virtual bool is_partition_size_needed_to_allocate_partition() const = 0;

	// Called exactly once at some point prior to the completion of close(). Must return
	// a byte offset in the file at which this partition may safely be written.
	// Note: partition_size == 0 iff !is_partition_size_needed_to_allocate_partition()
	virtual uint64_t allocate_partition(uint64_t partition_size, IndexIO::GlobalPartitionMetadata gpmeta) const = 0;

	// Called by commit_partition once the partition is allocated and written.
	// Usually, this will call IndexIO's commit_partition and assign this
	// partition's ID based on its return, but other behaviors are acceptable
	// (e.g., in some implementations, all the work may be done during allocate_partition())
	virtual void on_partition_committed(uint64_t partition_offset_in_file, uint64_t partition_size, IndexIO::GlobalPartitionMetadata gpmeta) = 0;

private:
	struct partition_header_t {
		PartitionMetadata pmeta; // Just store this directly, since we're not doing anything fancy

		std::vector<uint64_t> region_offsets; // Relative to partition, including skip over header. Last offset is partition end offset (i.e., nbins+1 offsets exist)

	    friend class boost::serialization::access;
	    template<class Archive> void serialize(Archive & ar, const unsigned int version);
	};

	SharedFileFormatIndexIO &parent;
	SerializableChunk< partition_header_t > partition_header;

	boost::optional< uint64_t > partition_offset_in_file; // Always set in read mode, set in write mode after a call to allocate_partition

	std::vector< boost::shared_ptr< RegionEncoding > > regions_to_write; // Buffering from the write_regions function

	mutable IOStats region_io_stats;

	friend class SharedFileFormatIndexIO;
};

#endif /* SHAREDFILE_FORMAT_INDEX_IO_HPP_ */

max_stars_repo_name: daboyuka/PIQUE

max_issues_repo_name: daboyuka/PIQUE

max_forks_repo_name: daboyuka/PIQUE


text: #include <boost/test/utils/runtime/finalize.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <wiringPi.h>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
using namespace boost::python;

#include "QTRSensors.h"

class WrapperFuncs{
public:
    static boost::shared_ptr<QTRSensorsRC> init(
	        list _pins, unsigned int timeout, unsigned char emitterPin){
        wiringPiSetup();
        unsigned char __pins[QTRSensorsRC::QTR_MAX_SENSORS];
        for(int i=0; i<len(_pins); i++)
            __pins[i]=extract<int>(_pins[i]);
        return boost::shared_ptr<QTRSensorsRC>(
            new QTRSensorsRC(__pins, (unsigned char)len(_pins), timeout, emitterPin)
        );
    }

    static tuple readLine(QTRSensorsRC &qtrrc, unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON, unsigned char white_line=0){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        int position=qtrrc.readLine(_sv, readMode, white_line);

        list sensorValues;
        for(int i=0; i<qtrrc.numSensors(); i++)
            sensorValues.append(_sv[i]);
        return make_tuple(position, sensorValues);
    }

    static list read(QTRSensorsRC &qtrrc, unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        qtrrc.read(_sv, readMode);

        list sensorValues;
        for(int i=0; i<qtrrc.numSensors(); i++)
            sensorValues.append(_sv[i]);
        return sensorValues;
    }

    static list readCalibrated(QTRSensorsRC &qtrrc, unsigned char readMode=QTRSensorsRC::QTR_EMITTERS_ON){
        unsigned int _sv[QTRSensorsRC::QTR_MAX_SENSORS];
        qtrrc.readCalibrated(_sv, readMode);

        list sensorValues;
        for(int i=0; i<qtrrc.numSensors(); i++)
            sensorValues.append(_sv[i]);
        return sensorValues;
    }

    static list calibratedMinimumOn(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMinimumOn[i]);
        return values;
    }

    static list calibratedMaximumOn(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMaximumOn[i]);
        return values;
    }

    static list calibratedMinimumOff(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMinimumOff[i]);
        return values;
    }

    static list calibratedMaximumOff(QTRSensorsRC& qtrrc){
        list values;
        for(unsigned char i=0; i<qtrrc.numSensors(); i++)
            values.append(qtrrc.calibratedMaximumOff[i]);
        return values;
    }
};

BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(
    calibrate_overloads, QTRSensorsRC::calibrate, 0, 1
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    read_overloads, WrapperFuncs::read, 1, 2
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    readCalibrated_overloads, WrapperFuncs::readCalibrated, 1, 2
)

BOOST_PYTHON_FUNCTION_OVERLOADS(
    readLine_overloads, WrapperFuncs::readLine, 1, 3
)

const char *classDocStr=""
    "This library is for using Pololu QTR reflectance\n"
    "sensors and reflectance sensor arrays: QTR-1RC and\n"
    "QTR-8RC. Simply specify in the constructor which\n"
    "Raspberry Pi pins are connected to a QTR sensor, and the read() method\n"
    "will obtain reflectance measurements for those sensors.  Smaller sensor\n"
    "values correspond to higher reflectance (e.g. white) while larger\n"
    "sensor values correspond to lower reflectance (e.g. black or a void).\n\n"
    "* QTRSensorsRC should be used for QTR-1RC and QTR-8RC sensors.\n"
;

const char *initDocStr=""
    "The list 'pins' contains the Raspberry Pi pin number for each sensor.\n"
    "This library uses the pin number convention defined by WiringPi which \n"
    "can be found at http://wiringpi.com/pins/.\n\n"

    "'timeout' specifies the length of time in microseconds beyond\n"
    "which you consider the sensor reading completely black.  That is to say,\n"
    "if the pulse length for a pin exceeds 'timeout', pulse timing will stop\n"
    "and the reading for that pin will be considered full black.\n"
    "It is recommended that you set timeout to be between 1000 and\n"
    "3000 us, depending on things like the height of your sensors and\n"
    "ambient lighting.  Using timeout allows you to shorten the\n"
    "duration of a sensor-reading cycle while still maintaining\n"
    "useful analog measurements of reflectance.\n\n"

    "'emitterPin' is the Raspberry Pi pin that controls the IR LEDs on the 8RC\n"
    "modules.  If you are using a 1RC (i.e. if there is no emitter pin),\n"
    "or if you just want the emitters on all the time and don't want to\n"
    "use an I/O pin to control it, use a value of 255 (QTR_NO_EMITTER_PIN).\n"
;

const char *calibrateDocStr=""
    "Reads the sensors for calibration.  The sensor values are\n"
    "not returned; instead, the maximum and minimum values found\n"
    "over time are stored internally and used for the\n"
    "readCalibrated() method.\n\n"
    "'readMode' determines if the IR LEDs should be on\n"
    "(QTRSensorsRC.QTR_EMITTERS_ON, default) during calibration or off\n"
    "(QTRSensorsRC.QTR_EMITTERS_OFF)."
;

const char *emittersOnDocStr=""
    "Turn the IR LEDs on. This is mainly for use by the\n"
    "read method, and calling this function before or\n"
    "after reading the sensors will have no effect on the\n"
    "readings, but you may wish to use it for testing purposes.\n"
;

const char *emittersoffDocStr=""
    "Turn the IR LEDs off. This is mainly for use by the\n"
    "read method, and calling this function before or\n"
    "after reading the sensors will have no effect on the\n"
    "readings, but you may wish to use it for testing purposes.\n"
;

const char *resetCalibrationDocStr="Resets all calibration that has been done.\n";

const char *readDocStr=""
    "Reads the sensor values and returns a list.\n\n"
    "Example usage:\n"
    "\tsensorValues=sensors.read()\n\n"
    "The values returned are a measure of the reflectance in abstract units,\n"
    "with higher values corresponding to lower reflectance (e.g. a black\n"
    "surface or a void).\n"
    "If 'readMode' is QTRSensorsRC.QTR_EMITTERS_ON_AND_OFF, measures the values\n"
    "with the emitters on AND off and returns on - (timeout - off). If this\n"
    "value is less than zero, it returns zero.\n"
    "This method will call readPrivate().\n"
;

const char *readCalibratedDocStr=""
    "Returns values calibrated to a value between 0 and 1000, where\n"
    "0 corresponds to the minimum value read by calibrate() and 1000\n"
    "corresponds to the maximum value.  Calibration values are\n"
    "stored separately for each sensor, so that differences in the\n"
    "sensors are accounted for automatically.\n"
;

const char *readLineDocStr=""
    "Operates the same as read calibrated, but also returns an\n"
    "estimated position of the robot with respect to a line. The\n"
    "estimate is made using a weighted average of the sensor indices\n"
    "multiplied by 1000, so that a return value of 0 indicates that\n"
    "the line is directly below sensor 0, a return value of 1000\n"
    "indicates that the line is directly below sensor 1, 2000\n"
    "indicates that it's below sensor 2000, etc.  Intermediate\n"
    "values indicate that the line is between two sensors.  The\n"
    "formula is:\n\n"

    "   0*value0 + 1000*value1 + 2000*value2 + ...\n"
    "  --------------------------------------------\n"
    "        value0  +  value1  +  value2 + ...\n\n"

    "By default, this function assumes a dark line (high values)\n"
    "surrounded by white (low values).  If your line is light on\n"
    "black, set the optional third argument white_line to True.  In\n"
    "this case, each sensor value will be replaced by (1000-value)\n"
    "before the averaging.\n"
;

const char *calibratedMinimumDocStr=""
    "Calibrated minumum values. These start at 1000 and\n"
    "0, respectively, so that the very first sensor reading will\n"
    "update both of them.\n\n"

    "The values are meaningless until calibrate() is called.\n"
    "Depending on the readMode argument to calibrate, only the On or Off values may\n"
    "be allocated, as required.\n\n"

    "These variables are made public so that you can use them for\n"
    "your own calculations and do things like performing sanity checking, etc.\n"
;

const char *calibratedMaximumDocStr=""
    "Calibrated maximum values. These start at 1000 and\n"
    "0, respectively, so that the very first sensor reading will\n"
    "update both of them.\n\n"

    "The values are meaningless until calibrate() is called.\n"
    "Depending on the readMode argument to calibrate, only the On or Off values may\n"
    "be allocated, as required.\n\n"

    "These variables are made public so that you can use them for\n"
    "your own calculations and do things like performing sanity checking, etc.\n"
;

BOOST_PYTHON_MODULE(QTRSensors){
    scope the_scope=class_<QTRSensorsRC, boost::shared_ptr<QTRSensorsRC> >
        ("QTRSensorsRC", classDocStr, no_init)
        .def("__init__", make_constructor(WrapperFuncs::init, default_call_policies(), args("_pins","timeout","emitterPin")), initDocStr)

        // 'Normal' methods
        .def("calibrate", &QTRSensorsRC::calibrate, calibrate_overloads((arg("self"),arg("readeMode")=1), calibrateDocStr))
        .def("emittersOff", &QTRSensorsRC::emittersOff, args("self"), emittersoffDocStr)
        .def("emittersOn", &QTRSensorsRC::emittersOn, args("self"), emittersOnDocStr)
        .def("resetCalibration", &QTRSensorsRC::resetCalibration, args("self"), resetCalibrationDocStr)

        // Wrapped methods
        .def("read", &WrapperFuncs::read, read_overloads((arg("readMode")=1), readDocStr))
        .def("readCalibrated", &WrapperFuncs::readCalibrated, readCalibrated_overloads((arg("readMode")=1), readCalibratedDocStr))
        .def("readLine", &WrapperFuncs::readLine, readLine_overloads((arg("readMode")=1,arg("white_line")=0), readLineDocStr))

        // Getter Methods (wrap exposed array pointers)
        .def("calibratedMinimumOn", &WrapperFuncs::calibratedMinimumOn, calibratedMinimumDocStr)
        .def("calibratedMaximumOn", &WrapperFuncs::calibratedMaximumOn, calibratedMaximumDocStr)
        .def("calibratedMinimumOff", &WrapperFuncs::calibratedMinimumOff, calibratedMinimumDocStr)
        .def("calibratedMaximumOff", &WrapperFuncs::calibratedMaximumOff, calibratedMaximumDocStr)
    ;

    enum_<QTRSensorsRC::QTR>
        ("QTR")
        .value("QTR_EMITTERS_OFF", QTRSensorsRC::QTR_EMITTERS_OFF)
        .value("QTR_EMITTERS_ON", QTRSensorsRC::QTR_EMITTERS_ON)
        .value("QTR_EMITTERS_ON_AND_OFF", QTRSensorsRC::QTR_EMITTERS_ON_AND_OFF)
        .value("QTR_NO_EMITTER_PIN", QTRSensorsRC::QTR_NO_EMITTER_PIN)
        .value("QTR_MAX_SENSORS", QTRSensorsRC::QTR_MAX_SENSORS)
        .export_values()
    ;
}

max_stars_repo_name: jazzycamel/QTRSensors

max_issues_repo_name: jazzycamel/QTRSensors

max_forks_repo_name: jazzycamel/QTRSensors


text:
#ifndef IMAGE_HPP_7HEI0TM0
#define IMAGE_HPP_7HEI0TM0

#include <log4cxx/logger.h>
#include <log4cxx/basicconfigurator.h>
#include <log4cxx/helpers/exception.h>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include "line_histogram.hpp"
#include "algorithm_otsu.hpp"

typedef vector<cv::Rect> rectangules_list;
typedef boost::multi_array<float, 2> pixel_results;

namespace prhlt {
    class Image{
        public:
            Image();
            ~Image();
            void load_from_file(string file_path);
            bool is_image_loaded();
            void load_from_matrix(cv::Mat &ex_image);
            void load_from_matrix_region(cv::Mat &ex_image, cv::Rect rec);
            int binarize_image(int ex_threshold);
            bool is_image_binarized();
            int get_binarization_threshold();
            int get_num_rows();
            int get_num_columns();
            cv::Mat get_matrix();
            bool is_foreground_pixel(int x,int y);
            bool coordinates_inside_image(int x, int y);
            void display_with_scale(string window_name, float scale,int wait_time, bool destroy_on_exit);
            void overlay_image_with_color(cv::Mat input_mat, cv::Scalar color);
            void display_binarized_with_scale(string window_name, float scale,int wait_time, bool destroy_on_exit);
            Image draw_histogram(cv::Rect area_rectangle , Line_Histogram hist, cv::Scalar color);
            void draw_line(cv::Point2d from, cv::Point2d to,cv::Scalar color);
            void draw_lines(line_array lines,cv::Scalar color);
            void draw_randomed_colored_region(vector<cv::Point2d> points);
            void draw_polyline(vector<cv::Point2d> points, cv::Scalar color);
            void draw_randomed_colored_polyline(vector<cv::Point2d> points);
            void draw_rectangle(cv::Rect rec,cv::Scalar color);
            void draw_rectangles(rectangules_list rec_list);
            void draw_text(cv::Point pos, string text);
		    void encircle_points(vector<cv::Point2d> points,int radius,cv::Scalar color);
            cv::Rect get_area_rectangle();
            int get_num_grey_pixels_in_subregion(cv::Rect rec);
            pixel_results calculate_pixels_in_regions(rectangules_list rec_list);
            cv::Mat get_subregion_matrix(cv::Rect rec);
            void save_image(string path);
            Image clone_image();
        private:
            bool image_loaded;
            bool image_binarized;
            cv::Mat image;
            cv::Mat greyscale_image;
            cv::Mat binary_integral_image;
            cv::Mat binary_image;
            int binarization_threshold;
            log4cxx::LoggerPtr logger;
            cv::Scalar random_color(CvRNG *rng);
            void initialize_greyscale_image();
            void initialize_binary_image_matrixes();
            void release_internal_images();
    };
}
#endif /* end of include guard: IMAGE_HPP_7HEI0TM0 */

max_stars_repo_name: jkloe/pageDistanceBasedContourGenerator

max_issues_repo_name: jkloe/pageDistanceBasedContourGenerator

max_forks_repo_name: jkloe/pageDistanceBasedContourGenerator


text:
#include "math_helper_func.hpp"
#include "utils/algorithms.hpp"
#include <boost/range/algorithm/min_element.hpp>
#include <boost/range/algorithm/transform.hpp>
#include <iterator>
#include <vector>
#include <cmath>
#include <limits>

namespace
{

double calcualte_li(double xi, const std::vector<double>& xd,
        const std::vector<double>& yd);

double calcualte_li(double xi, const std::vector<double>& xd,
        const std::vector<double>& yd)
{
    if (xi <= xd[0]) {
        if (xd[1] == xd[0]) {
            return std::numeric_limits<double>::max();
        }
        auto t = (xi - xd[0]) / (xd[1] - xd[0]);
        return (1.0 - t) * yd[0] + t * yd[1];
    } else if (xd[xd.size()-1] <= xi) {
        if (xd[xd.size()-1] == xd[xd.size()-2]) {
            return std::numeric_limits<double>::max();
        }
        auto t = (xi - xd[xd.size()-2]) / (xd[xd.size()-1] - xd[xd.size()-2]);
        return (1.0 - t) * yd[xd.size()-2] + t * yd[xd.size()-1];
    } else {
        for (auto k = 1u; k < xd.size(); k++) {
            if (xd[k-1u] <= xi &&  xi <= xd[k] && (xd[k] != xd[k-1u])) {
                auto t = (xi - xd[k-1u]) / (xd[k] - xd[k-1u]);
                return (1.0 - t) * yd[k-1u] + t * yd[k];
            }
        }
    }
    return std::numeric_limits<double>::max();  // shold never get here
}

}   // end of local namespace

double linear_interpulation_1d(const std::vector<double>& x_vals,
        const std::vector<double>& y_vals, double x_cord)
{
    if (x_vals.size() == 1) {
        return y_vals[0];
    } else {
        return calcualte_li(x_cord, x_vals, y_vals);
    }
}

//****************************************************************************80
//
//  Purpose:
//
//    PWL_VALUE_1D evaluates the piecewise linear interpolant.
//
//  Discussion:
//
//    The piecewise linear interpolant L(ND,XD,YD)(X) is the piecewise
//    linear function which interpolates the data (XD(I),YD(I)) for I = 1
//    to ND.
//
//  Parameters:
//
//    Input, int ND, the number of data points.
//    ND must be at least 1.
//
//    Input, double XD[ND], the data points.
//
//    Input, double YD[ND], the data values.
//
//    Input, int NI, the number of interpolation points.
//
//    Input, double XI[NI], the interpolation points.
//
//    Output, double PWL_VALUE_1D[NI], the interpolated values.
//
std::vector<double> pwl_value_1d(std::vector<double> xd,
        const std::vector<double>& yd,
        const std::vector<double>& xi)
{

    if (xd.size() == 1u) {
        return yd;
    }

    std::vector<double> yi;
    yi.reserve(xi.size());
    boost::transform(xi, std::back_inserter(yi), [&xd, &yd](auto x) {
                return calcualte_li(x, xd, yd);
            }
    );
    return yi;
}

//****************************************************************************80
//
//  Purpose:
//
//    NEAREST_INTERP_1D evaluates the nearest neighbor interpolant.
//
//  Discussion:
//
//    The nearest neighbor interpolant L(ND,XD,YD)(X) is the piecewise
//    constant function which interpolates the data (XD(I),YD(I)) for I = 1
//    to ND.
//
//  Licensing:
//
//  Parameters:
//
//    Input, int ND, the number of data points.
//    ND must be at least 1.
//
//    Input, double XD[ND], the data points.
//
//    Input, double YD[ND], the data values.
//
//    Input, int NI, the number of interpolation points.
//
//    Input, double XI[NI], the interpolation points.
//
//    Output, double NEAREST_INTERP_1D[NI], the interpolated values.
//

double nearset_interpolations(const std::vector<double>& x_vals,
        const std::vector<double>& y_vals, double x_cord)
{
    auto k = 0u;
    auto d = std::abs(x_cord - x_vals[k]);
    auto d2 = 0.0;
    for (auto j = 1u; j < x_vals.size(); ++j) {
        d2 = std::abs(x_cord - x_vals[j]);
        if (d2 <= d) {
            k = j;
            d = d2;
        }
    }
    return y_vals[k];
}

std::vector<double> nearest_interp_1d(std::vector<double> xd,
                                      std::vector<double> &yd,
                                      std::vector<double> &xi)

{
    std::vector<double> yi;
    yi.reserve(xi.size());
    boost::transform(xi, std::back_inserter(yi), [&xd, &yd] (auto x) {
                    return nearset_interpolations(xd, yd, x);
                }
    );
    return yi;
}


text:
#include "lib_source.h"

#include <boost/assert.hpp>

namespace MyLibrary {
    int getFortyTwo (){
        auto val = 42;
        BOOST_ASSERT_MSG(val == 42, "Value should be 42");
        return val;
    };
}

max_stars_repo_name: erikzenker/cmake-project-template

max_issues_repo_name: erikzenker/cmake-project-template

max_forks_repo_name: erikzenker/cmake-project-template


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

#include <boost/algorithm/string.hpp>
#include "common/command_line.h"
#include "common/varint.h"
#include "cryptonote_basic/cryptonote_boost_serialization.h"
#include "cryptonote_core/tx_pool.h"
#include "cryptonote_core/cryptonote_core.h"
#include "cryptonote_core/blockchain.h"
#include "blockchain_db/blockchain_db.h"
#include "blockchain_db/db_types.h"
#include "version.h"

#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "bcutil"

namespace po = boost::program_options;
using namespace epee;
using namespace cryptonote;

static bool stop_requested = false;

int main(int argc, char* argv[])
{
  TRY_ENTRY();

  epee::string_tools::set_module_name_and_folder(argv[0]);

  std::string default_db_type = "lmdb";

  std::string available_dbs = cryptonote::blockchain_db_types(", ");
  available_dbs = "available: " + available_dbs;

  uint32_t log_level = 0;
  uint64_t block_start = 0;
  uint64_t block_stop = 0;

  tools::on_startup();

  boost::filesystem::path output_file_path;

  po::options_description desc_cmd_only("Command line options");
  po::options_description desc_cmd_sett("Command line options and settings options");
  const command_line::arg_descriptor<std::string> arg_log_level  = {"log-level",  "0-4 or categories", ""};
  const command_line::arg_descriptor<std::string> arg_database = {
    "database", available_dbs.c_str(), default_db_type
  };
  const command_line::arg_descriptor<uint64_t> arg_block_start  = {"block-start", "start at block number", block_start};
  const command_line::arg_descriptor<uint64_t> arg_block_stop = {"block-stop", "Stop at block number", block_stop};
  const command_line::arg_descriptor<bool> arg_inputs  = {"with-inputs", "with input stats", false};
  const command_line::arg_descriptor<bool> arg_outputs  = {"with-outputs", "with output stats", false};
  const command_line::arg_descriptor<bool> arg_ringsize  = {"with-ringsize", "with ringsize stats", false};
  const command_line::arg_descriptor<bool> arg_hours  = {"with-hours", "with txns per hour", false};

  command_line::add_arg(desc_cmd_sett, cryptonote::arg_data_dir);
  command_line::add_arg(desc_cmd_sett, cryptonote::arg_testnet_on);
  command_line::add_arg(desc_cmd_sett, cryptonote::arg_stagenet_on);
  command_line::add_arg(desc_cmd_sett, arg_log_level);
  command_line::add_arg(desc_cmd_sett, arg_database);
  command_line::add_arg(desc_cmd_sett, arg_block_start);
  command_line::add_arg(desc_cmd_sett, arg_block_stop);
  command_line::add_arg(desc_cmd_sett, arg_inputs);
  command_line::add_arg(desc_cmd_sett, arg_outputs);
  command_line::add_arg(desc_cmd_sett, arg_ringsize);
  command_line::add_arg(desc_cmd_sett, arg_hours);
  command_line::add_arg(desc_cmd_only, command_line::arg_help);

  po::options_description desc_options("Allowed options");
  desc_options.add(desc_cmd_only).add(desc_cmd_sett);

  po::variables_map vm;
  bool r = command_line::handle_error_helper(desc_options, [&]()
  {
    auto parser = po::command_line_parser(argc, argv).options(desc_options);
    po::store(parser.run(), vm);
    po::notify(vm);
    return true;
  });
  if (! r)
    return 1;

  if (command_line::get_arg(vm, command_line::arg_help))
  {
    std::cout << "Monero '" << MONERO_RELEASE_NAME << "' (v" << MONERO_VERSION_FULL << ")" << ENDL << ENDL;
    std::cout << desc_options << std::endl;
    return 1;
  }

  mlog_configure(mlog_get_default_log_path("monero-blockchain-stats.log"), true);
  if (!command_line::is_arg_defaulted(vm, arg_log_level))
    mlog_set_log(command_line::get_arg(vm, arg_log_level).c_str());
  else
    mlog_set_log(std::string(std::to_string(log_level) + ",bcutil:INFO").c_str());

  LOG_PRINT_L0("Starting...");

  std::string opt_data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
  bool opt_testnet = command_line::get_arg(vm, cryptonote::arg_testnet_on);
  bool opt_stagenet = command_line::get_arg(vm, cryptonote::arg_stagenet_on);
  network_type net_type = opt_testnet ? TESTNET : opt_stagenet ? STAGENET : MAINNET;
  block_start = command_line::get_arg(vm, arg_block_start);
  block_stop = command_line::get_arg(vm, arg_block_stop);
  bool do_inputs = command_line::get_arg(vm, arg_inputs);
  bool do_outputs = command_line::get_arg(vm, arg_outputs);
  bool do_ringsize = command_line::get_arg(vm, arg_ringsize);
  bool do_hours = command_line::get_arg(vm, arg_hours);

  std::string db_type = command_line::get_arg(vm, arg_database);
  if (!cryptonote::blockchain_valid_db_type(db_type))
  {
    std::cerr << "Invalid database type: " << db_type << std::endl;
    return 1;
  }

  LOG_PRINT_L0("Initializing source blockchain (BlockchainDB)");
  std::unique_ptr<Blockchain> core_storage;
  tx_memory_pool m_mempool(*core_storage);
  core_storage.reset(new Blockchain(m_mempool));
  BlockchainDB *db = new_db(db_type);
  if (db == NULL)
  {
    LOG_ERROR("Attempted to use non-existent database type: " << db_type);
    throw std::runtime_error("Attempting to use non-existent database type");
  }
  LOG_PRINT_L0("database: " << db_type);

  const std::string filename = (boost::filesystem::path(opt_data_dir) / db->get_db_name()).string();
  LOG_PRINT_L0("Loading blockchain from folder " << filename << " ...");

  try
  {
    db->open(filename, DBF_RDONLY);
  }
  catch (const std::exception& e)
  {
    LOG_PRINT_L0("Error opening database: " << e.what());
    return 1;
  }
  r = core_storage->init(db, net_type);

  CHECK_AND_ASSERT_MES(r, 1, "Failed to initialize source blockchain storage");
  LOG_PRINT_L0("Source blockchain storage initialized OK");

  tools::signal_handler::install([](int type) {
    stop_requested = true;
  });

  const uint64_t db_height = db->height();
  if (!block_stop)
      block_stop = db_height;
  MINFO("Starting from height " << block_start << ", stopping at height " << block_stop);

/*
 * The default output can be plotted with GnuPlot using these commands:
set key autotitle columnhead
set title "Monero Blockchain Growth"
set timefmt "%Y-%m-%d"
set xdata time
set xrange ["2014-04-17":*]
set format x "%Y-%m-%d"
set yrange [0:*]
set y2range [0:*]
set ylabel "Txs/Day"
set y2label "Bytes"
set y2tics nomirror
plot 'stats.csv' index "DATA" using (timecolumn(1,"%Y-%m-%d")):4 with lines, '' using (timecolumn(1,"%Y-%m-%d")):7 axes x1y2 with lines
 */

  // spit out a comment that GnuPlot can use as an index
  std::cout << ENDL << "# DATA" << ENDL;
  std::cout << "Date\tBlocks/day\tBlocks\tTxs/Day\tTxs\tBytes/Day\tBytes";
  if (do_inputs)
    std::cout << "\tInMin\tInMax\tInAvg";
  if (do_outputs)
    std::cout << "\tOutMin\tOutMax\tOutAvg";
  if (do_ringsize)
    std::cout << "\tRingMin\tRingMax\tRingAvg";
  if (do_hours) {
    char buf[8];
    unsigned int i;
    for (i=0; i<24; i++) {
      sprintf(buf, "\t%02u:00", i);
      std::cout << buf;
    }
  }
  std::cout << ENDL;

  struct tm prevtm = {0}, currtm;
  uint64_t prevsz = 0, currsz = 0;
  uint64_t prevtxs = 0, currtxs = 0;
  uint64_t currblks = 0;
  uint64_t totins = 0, totouts = 0, totrings = 0;
  uint32_t minins = 10, maxins = 0;
  uint32_t minouts = 10, maxouts = 0;
  uint32_t minrings = 50, maxrings = 0;
  uint32_t io, tottxs = 0;
  uint32_t txhr[24] = {0};
  unsigned int i;

  for (uint64_t h = block_start; h < block_stop; ++h)
  {
    cryptonote::blobdata bd = db->get_block_blob_from_height(h);
    cryptonote::block blk;
    if (!cryptonote::parse_and_validate_block_from_blob(bd, blk))
    {
      LOG_PRINT_L0("Bad block from db");
      return 1;
    }
    time_t tt = blk.timestamp;
    char timebuf[64];
    epee::misc_utils::get_gmt_time(tt, currtm);
    if (!prevtm.tm_year)
      prevtm = currtm;
    // catch change of day
    if (currtm.tm_mday > prevtm.tm_mday || (currtm.tm_mday == 1 && prevtm.tm_mday > 27))
    {
      // check for timestamp fudging around month ends
      if (prevtm.tm_mday == 1 && currtm.tm_mday > 27)
        goto skip;
      strftime(timebuf, sizeof(timebuf), "%Y-%m-%d", &prevtm);
      prevtm = currtm;
      std::cout << timebuf << "\t" << currblks << "\t" << h << "\t" << currtxs << "\t" << prevtxs + currtxs << "\t" << currsz << "\t" << prevsz + currsz;
      prevsz += currsz;
      currsz = 0;
      currblks = 0;
      prevtxs += currtxs;
      currtxs = 0;
      if (!tottxs)
        tottxs = 1;
      if (do_inputs) {
        std::cout << "\t" << (maxins ? minins : 0) << "\t" << maxins << "\t" << totins / tottxs;
        minins = 10; maxins = 0; totins = 0;
      }
      if (do_outputs) {
        std::cout << "\t" << (maxouts ? minouts : 0) << "\t" << maxouts << "\t" << totouts / tottxs;
        minouts = 10; maxouts = 0; totouts = 0;
      }
      if (do_ringsize) {
        std::cout << "\t" << (maxrings ? minrings : 0) << "\t" << maxrings << "\t" << totrings / tottxs;
        minrings = 50; maxrings = 0; totrings = 0;
      }
      tottxs = 0;
      if (do_hours) {
        for (i=0; i<24; i++) {
          std::cout << "\t" << txhr[i];
          txhr[i] = 0;
        }
      }
      std::cout << ENDL;
    }
skip:
    currsz += bd.size();
    for (const auto& tx_id : blk.tx_hashes)
    {
      if (tx_id == crypto::null_hash)
      {
        throw std::runtime_error("Aborting: tx == null_hash");
      }
      if (!db->get_tx_blob(tx_id, bd))
      {
        throw std::runtime_error("Aborting: tx not found");
      }
      transaction tx;
      if (!parse_and_validate_tx_from_blob(bd, tx))
      {
        LOG_PRINT_L0("Bad txn from db");
        return 1;
      }
      currsz += bd.size();
      currtxs++;
      if (do_hours)
        txhr[currtm.tm_hour]++;
      if (do_inputs) {
        io = tx.vin.size();
        if (io < minins)
          minins = io;
        else if (io > maxins)
          maxins = io;
        totins += io;
      }
      if (do_ringsize) {
        const cryptonote::txin_to_key& tx_in_to_key
                       = boost::get<cryptonote::txin_to_key>(tx.vin[0]);
        io = tx_in_to_key.key_offsets.size();
        if (io < minrings)
          minrings = io;
        else if (io > maxrings)
          maxrings = io;
        totrings += io;
      }
      if (do_outputs) {
        io = tx.vout.size();
        if (io < minouts)
          minouts = io;
        else if (io > maxouts)
          maxouts = io;
        totouts += io;
      }
      tottxs++;
    }
    currblks++;

    if (stop_requested)
      break;
  }

  core_storage->deinit();
  return 0;

  CATCH_ENTRY("Stats reporting error", 1);
}

max_stars_repo_name: cryptographicfool/monero

max_issues_repo_name: cryptographicfool/monero

max_forks_repo_name: cryptographicfool/monero


text:
#include "CursATE/Screen/detail/FilterTreeDataSource.hpp"
#include <boost/lexical_cast.hpp>

namespace CursATE::Screen::detail
{

FilterTreeDataSource::FilterTreeDataSource(LogATE::Tree::NodeShPtr root):
  entries_{ constructEntries(root) }
{ }

size_t FilterTreeDataSource::index(Id const& id) const
{
  return boost::lexical_cast<size_t>(id.value_);
}

size_t FilterTreeDataSource::size() const
{
  return entries_.size();
}

But::Optional<FilterTreeDataSource::Id> FilterTreeDataSource::nearestTo(Id const& id) const
{
  if( entries_.empty() )
    return  {};
  if( entries_.size() >= boost::lexical_cast<size_t>(id.value_) )
    return Id{entries_.size()-1u};
  return id;
}

But::Optional<FilterTreeDataSource::Id> FilterTreeDataSource::first() const
{
  BUT_ASSERT( not entries_.empty() );
  return Id{0};
}

But::Optional<FilterTreeDataSource::Id> FilterTreeDataSource::last() const
{
  BUT_ASSERT( not entries_.empty() );
  return Id{entries_.size()-1u};
}

std::map<FilterTreeDataSource::Id, std::string> FilterTreeDataSource::get(size_t before, Id const& id, size_t after) const
{
  const auto idNum = boost::lexical_cast<size_t>(id.value_);
  if( idNum > entries_.size() )
    throw std::logic_error{"requested ID in tree, that is out of range"};
  std::map<Id, std::string> out;
  const auto from = ( before > idNum ) ? 0u : idNum - before;
  const auto to = std::min( entries_.size(), from + before + 1u + after );
  for(auto i=from; i!=to; ++i)
    out[ Id{i} ] = entries_[i].text_;
  return out;
}

FilterTreeDataSource::Id FilterTreeDataSource::node2id(LogATE::Tree::NodeShPtr const& selected) const
{
  for(auto i=0u; i<entries_.size(); ++i)
    if( entries_[i].node_.get() == selected.get() )
      return Id{i};
  BUT_ASSERT( not entries_.empty() );
  // NOTE: entry might be missed, if this was auto-managed node, removed on a fly - default to begin of the list
  return Id{0};
}

LogATE::Tree::NodeShPtr FilterTreeDataSource::id2node(Id const& id) const
{
  const auto idNum = boost::lexical_cast<size_t>(id.value_);
  BUT_ASSERT( idNum < entries_.size() );
  return entries_[idNum].node_;
}

namespace
{
auto nodeName(LogATE::Tree::NodeShPtr const& node)
{
  const auto size = node->clogs()->withLock()->size();
  return node->type().value_ + "::" + node->name().value_ + " (" + std::to_string(size) + ")";
}

template<typename C>
void appendTree(LogATE::Tree::NodeShPtr const& node, C& out, std::string const& prefix)
{
  using E = typename C::value_type;
  out.push_back( E{ node, prefix + nodeName(node) } );
  const auto newPrefix = prefix + "  ";
  for(auto& c: node->children())
    appendTree(c, out, newPrefix);
}
}

std::vector<FilterTreeDataSource::Entry> FilterTreeDataSource::constructEntries(LogATE::Tree::NodeShPtr const& root) const
{
  std::vector<FilterTreeDataSource::Entry> out;
  appendTree(root, out, "");
  return out;
}

}

max_stars_repo_name: qiagen/LogATE

max_issues_repo_name: qiagen/LogATE

max_forks_repo_name: qiagen/LogATE


text: #include <boost/gil/utilities.hpp>