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

#include <array>
#include <boost/core/lightweight_test.hpp>
#include <boost/histogram.hpp>
#include <boost/histogram/accumulators/weighted_sum.hpp>
#include <boost/histogram/algorithm/sum.hpp>
#include <boost/histogram/axis/integer.hpp>
#include <unordered_map>
#include <vector>
#include "utility_histogram.hpp"

using namespace boost::histogram;
using namespace boost::histogram::literals; // to get _c suffix
using boost::histogram::algorithm::sum;

template <typename Tag>
void run_tests() {
  auto ax = axis::integer<>(0, 100);

  auto h1 = make(Tag(), ax);
  for (unsigned i = 0; i < 100; ++i) h1(i);
  BOOST_TEST_EQ(sum(h1), 100);

  auto h2 = make_s(Tag(), std::vector<double>(), ax, ax);
  for (unsigned i = 0; i < 100; ++i)
    for (unsigned j = 0; j < 100; ++j) h2(i, j);
  BOOST_TEST_EQ(sum(h2), 10000);

  auto h3 = make_s(Tag(), std::array<int, 102>(), ax);
  for (unsigned i = 0; i < 100; ++i) h3(i);
  BOOST_TEST_EQ(sum(h3), 100);

  auto h4 = make_s(Tag(), std::unordered_map<std::size_t, int>(), ax);
  for (unsigned i = 0; i < 100; ++i) h4(i);
  BOOST_TEST_EQ(sum(h4), 100);

  // auto h5 =
  //     make_s(Tag(), std::vector<accumulators::weighted_sum<>>(), axis::integer<>(0, 1),
  //            axis::integer<int, axis::null_type, axis::option::none_t>(2, 4));
  // h5(weight(2), 0, 2);
  // h5(-1, 2);
  // h5(1, 3);

  // const auto v = algorithm::sum(h5);
  // BOOST_TEST_EQ(v.value(), 4);
  // BOOST_TEST_EQ(v.variance(), 6);
}

int main() {
  run_tests<static_tag>();
  run_tests<dynamic_tag>();

  return boost::report_errors();
}


text:
#include <boost/functional/hash.hpp>

#include "pipeline_states.hxx"

namespace graphics
{
    std::size_t hash<graphics::vertex_input_state>::operator() (graphics::vertex_input_state const &state) const
    {
        std::size_t seed = 0;

        graphics::hash<graphics::vertex_input_binding> constexpr binding_hasher;

        boost::hash_combine(seed, binding_hasher(state.binding_description));

        /*for (auto &&binding_description : state.binding_descriptions)
            boost::hash_combine(seed, binding_hasher(binding_description));*/

        graphics::hash<graphics::vertex_input_attribute> constexpr attribute_hasher;

        for (auto &&attribute_description : state.attribute_descriptions)
            boost::hash_combine(seed, attribute_hasher(attribute_description));

        return seed;
    }

    std::size_t hash<graphics::rasterization_state>::operator() (graphics::rasterization_state const &state) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, state.cull_mode);
        boost::hash_combine(seed, state.front_face);
        boost::hash_combine(seed, state.polygon_mode);
        boost::hash_combine(seed, state.line_width);

        return seed;
    }

    std::size_t hash<graphics::stencil_state>::operator() (graphics::stencil_state const &state) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, state.fail);
        boost::hash_combine(seed, state.pass);
        boost::hash_combine(seed, state.depth_fail);

        boost::hash_combine(seed, state.compare_operation);

        boost::hash_combine(seed, state.compare_mask);
        boost::hash_combine(seed, state.write_mask);
        boost::hash_combine(seed, state.reference);

        return seed;
    }

    std::size_t hash<graphics::depth_stencil_state>::operator() (graphics::depth_stencil_state const &state) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, state.depth_test_enable);
        boost::hash_combine(seed, state.depth_write_enable);
        boost::hash_combine(seed, state.depth_compare_operation);

        boost::hash_combine(seed, state.depth_bounds_test_enable);
        boost::hash_combine(seed, state.depth_bounds);

        boost::hash_combine(seed, state.stencil_test_enable);

        graphics::hash<graphics::stencil_state> constexpr stencil_state_hasher;

        boost::hash_combine(seed, stencil_state_hasher(state.front_stencil_state));
        boost::hash_combine(seed, stencil_state_hasher(state.back_stencil_state));

        return seed;
    }

    std::size_t hash<graphics::color_blend_attachment_state>::operator() (graphics::color_blend_attachment_state const &state) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, state.blend_enable);
        boost::hash_combine(seed, state.src_color_blend_factor);
        boost::hash_combine(seed, state.dst_color_blend_factor);
        boost::hash_combine(seed, state.color_blend_operation);
        boost::hash_combine(seed, state.src_alpha_blend_factor);
        boost::hash_combine(seed, state.dst_alpha_blend_factor);
        boost::hash_combine(seed, state.alpha_blend_operation);
        boost::hash_combine(seed, state.color_write_mask);

        return seed;
    }

    std::size_t hash<graphics::color_blend_state>::operator() (graphics::color_blend_state const &state) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, state.logic_operation_enable);
        boost::hash_combine(seed, state.logic_operation);
        boost::hash_combine(seed, state.blend_constants);

        graphics::hash<graphics::color_blend_attachment_state> constexpr hasher;

        for (auto &&attachment : state.attachment_states)
            boost::hash_combine(seed, hasher(attachment));

        return seed;
    }

    std::size_t hash<graphics::pipeline_states>::operator() (graphics::pipeline_states const &states) const
    {
        std::size_t seed = 0;

        boost::hash_combine(seed, states.primitive_topology);

        graphics::hash<graphics::vertex_input_state> constexpr vertex_input_state_hasher;
        boost::hash_combine(seed, vertex_input_state_hasher(states.vertex_input_state));

        graphics::hash<graphics::rasterization_state> constexpr rasterization_state_hasher;
        boost::hash_combine(seed, rasterization_state_hasher(states.rasterization_state));

        graphics::hash<graphics::depth_stencil_state> constexpr depth_stencil_state_hasher;
        boost::hash_combine(seed, depth_stencil_state_hasher(states.depth_stencil_state));

        graphics::hash<graphics::color_blend_state> constexpr color_blend_state_hasher;
        boost::hash_combine(seed, color_blend_state_hasher(states.color_blend_state));

        return seed;
    }
}

ext: cxx

max_stars_repo_name: Alabuta/VulkanIsland

max_issues_repo_name: Alabuta/VulkanIsland

max_forks_repo_name: Alabuta/VulkanIsland


text:
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <iostream>

namespace fs = boost::filesystem;

int main(int argc, char *argv[]) {
    fs::path p(argc>1? argv[1] : ".");

    if(fs::is_directory(p)) {
        std::cout << p << " is a directory containing:\n";

        for(auto& entry : boost::make_iterator_range(fs::directory_iterator(p), {}))
            std::cout << entry.path().string() << "\n";
    }
}

ext: cpp

max_stars_repo_name: devkoriel/AwesomeCppTemplate

max_issues_repo_name: devkoriel/AwesomeCppTemplate

max_forks_repo_name: devkoriel/AwesomeCppTemplate


text:
//  Copyright John Maddock 2010.
//  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_MATH_CONSTANTS_GENERATE_INCLUDED
#define BOOST_MATH_CONSTANTS_GENERATE_INCLUDED

#include <boost/math/constants/constants.hpp>
#include <boost/regex.hpp>
#include <iostream>
#include <iomanip>
#include <sstream>

#ifdef USE_MPFR
#include <boost/math/bindings/mpfr.hpp>
#elif defined(USE_MPREAL)
#include <boost/math/bindings/mpreal.hpp>
#elif defined(USE_CPP_FLOAT)
#include <boost/multiprecision/cpp_dec_float.hpp>
#else
#include <boost/math/bindings/rr.hpp>
#endif

namespace boost{ namespace math{ namespace constants{

#ifdef USE_MPFR
typedef mpfr_class generator_type;
#elif defined(USE_MPREAL)
typedef mpfr::mpreal generator_type;
#elif defined(USE_CPP_FLOAT)
typedef boost::multiprecision::number<boost::multiprecision::cpp_dec_float<500> > generator_type;
#else
typedef ntl::RR generator_type;
#endif

inline void print_constant(const char* name, generator_type(*f)(const std::integral_constant<int, 0>&))
{
#ifdef USE_MPFR
   mpfr_class::set_dprec(((200 + 1) * 1000L) / 301L);
#elif defined(USE_MPREAL)
   mpfr::mpreal::set_default_prec(((200 + 1) * 1000L) / 301L);
#elif defined(USE_CPP_FLOAT)
   // Nothing to do, precision is already set.
#else
   ntl::RR::SetPrecision(((200 + 1) * 1000L) / 301L);
   ntl::RR::SetOutputPrecision(102);
#endif
   generator_type value = f(std::integral_constant<int, 0>());
   std::stringstream os;
   os << std::setprecision(110) << std::scientific;
   os << value;
   std::string s = os.str();
   static const regex e("([+-]?\\d+(?:\\.\\d{0,36})?)(\\d*)(?:e([+-]?\\d+))?");
   smatch what;
   if(regex_match(s, what, e))
   {
      std::cout <<
         "BOOST_DEFINE_MATH_CONSTANT(" << name << ", "
         << what[1] << "e" << (what[3].length() ? what[3].str() : std::string("0")) << ", "
         << "\"" << what[1] << what[2] << "e" << (what[3].length() ? what[3].str() : std::string("0"))
         << "\");" << std::endl;
   }
   else
   {
      std::cout << "Format of numeric constant was not recognised!!" << std::endl;
   }
}

#define BOOST_CONSTANTS_GENERATE(name) \
   boost::math::constants::print_constant(#name, \
   & boost::math::constants::detail::BOOST_JOIN(constant_, name)<boost::math::constants::generator_type>::get)

}}} // namespaces

#endif // BOOST_MATH_CONSTANTS_GENERATE_INCLUDED

ext: hpp

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math


text:
#ifndef _MLES_ACTIVATION_HPP_
#define _MLES_ACTIVATION_HPP_

#include <Eigen/Dense>
#include <string>
#include <ostream>
#include <istream>
#include <memory>

namespace mles
{
    class Activation;
    typedef std::shared_ptr<Activation> ActivationPtr;

    class Activation
    {
        private:
            std::string name;
            int parametersSize;
        public:
            Activation(const std::string& name, int parametersSize = 0)
            {
                this->name = name;
                this->parametersSize = parametersSize;
            }

            virtual ~Activation()
            {

            }

            std::string getName()
            {
                return name;
            }

            int getParametersSize()
            {
                return parametersSize;
            }

            bool is(const std::string& name)
            {
                return name == this->name;
            }

            virtual void getActivation(Eigen::MatrixXd& x, Eigen::MatrixXd& y)
            {
                y.resize(x.rows(), x.cols());
                for(int i = 0; i < x.rows(); i++)
                {
                    for(int j = 0; j < x.cols(); j++)
                        y(i,j) = this->getActivation(x(i,j));
                }
            }

            virtual void getDerivative(Eigen::MatrixXd& x, Eigen::MatrixXd& y)
            {
                y.resize(x.rows(), x.cols());
                for(int i = 0; i < x.rows(); i++)
                {
                    for(int j = 0; j < x.cols(); j++)
                        y(i,j) = this->getDerivative(x(i,j));
                }
            }

            virtual double getActivation(double x)
            {
                return x;
            }

            virtual double getDerivative(double x)
            {
                return 0;
            }

            virtual Activation* clone()
            {
                return new Activation(name);
            }

            virtual void load(std::istream& f)
            {

            }

            virtual void write(std::ostream& f)
            {

            }
    };
}

#endif

max_stars_repo_name: AlexanderSilvaB/mles

max_issues_repo_name: AlexanderSilvaB/mles

max_forks_repo_name: AlexanderSilvaB/mles


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

#include <boost/any.hpp>

using namespace std;

//class ClassA {
//public:
//    int a;
//    string b;
//};
//
//void log_debug(boost::any obj) {
//   if (obj.type() == typeid(ClassA)) {
//      ClassA objA = boost::any_cast<ClassA>(obj);
//      cout << "found ClassA instance " << objA.a << ", " <<  objA.b << endl;
//   }
//
//}
//
//template<typename ObjectType>
//void template_method( const ObjectType& obj) {
//   cout << "-----------------------" << endl;
//   cout << "template_method, " << typeid(obj).name() << endl;
//
//   log_debug(obj);
//}

std::ofstream log_current_file;
uint32_t log_current_height;

int8_t log(uint32_t height, const string& content) {
//   if (height < log_current_height) {
//      // wtf, ignore
//      return 0;
//   }
//
//   string filepath = "/Volumes/RAMDisk/" + std::to_string(height) + ".txt";
//
//   // close log_current_file if height changed
//   if (height > log_current_height) {
//      if (log_current_file.is_open()) {
//         log_current_file.flush();
//         log_current_file.close();
//      }
//
//      // remove file if exist
//      std::remove(filepath.c_str());
//
//      // remember to update log_current_height
//      log_current_height = height;
//   }
//
//
//   if (!log_current_file.is_open()) {
//      // open new file
//      log_current_file.open(filepath, std::ios_base::app);
//   }
//
//   log_current_file << content << endl;

   return 0;
}

int main()
{
//   cout << "Hello, World!";

//   template_method("Hello, World!");
//   template_method(123);

//   ClassA objA;
//   objA.a = 123;
//   objA.b = "objA";
//
//   template_method(objA);

   log(0, "0_0");
   log(0, "0_1");
   log(0, "0_2");

   log(1, "1_0");
   log(1, "1_1");
   log(1, "1_2");

   log(2, "2_0");
   log(2, "2_1");
   log(2, "2_2");

   return 0;
}

max_stars_repo_name: pranishg/VIDPOW

max_issues_repo_name: pranishg/VIDPOW

max_forks_repo_name: pranishg/VIDPOW


text:
// Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
// Use of this source code is governed by a apache 2.0 license that can be
// found in the LICENSE file.

#include "common/step/rds/step_rds_modify.h"

#include <boost/system/error_code.hpp>

#include <manifest_parser/utils/logging.h>

#include <common/utils/file_util.h>

namespace common_installer {
namespace rds {

namespace bf = boost::filesystem;
namespace bs = boost::system;
namespace ci = common_installer;

StepRDSModify::StepRDSModify(InstallerContext* context)
    : Step(context) {}

Step::Status StepRDSModify::precheck() {
  if (context_->unpacked_dir_path.get().empty()) {
    LOG(ERROR) << "unpacked dir path is not set";
    return common_installer::Step::Status::INVALID_VALUE;
  }
  if (!bf::exists(context_->unpacked_dir_path.get())) {
    LOG(ERROR) << "unpacked_dir_path ("
               << context_->unpacked_dir_path.get()
               << ") path does not exist";
    return Step::Status::INVALID_VALUE;
  }
  if (context_->pkgid.get().empty()) {
    LOG(ERROR) << "pkgid is not set";
    return Step::Status::PACKAGE_NOT_FOUND;
  }
  if (!context_->manifest_data.get()) {
    LOG(ERROR) << "no manifest info available";
    return Step::Status::INVALID_VALUE;
  }
  return Step::Status::OK;
}

Step::Status StepRDSModify::process() {
  LOG(INFO) << "entered process of step modify";
  if (!SetUpTempBackupDir()) {
    LOG(ERROR) << "unable to setup temp directory";
    return Step::Status::ERROR;
  }
  context_->pkg_path.set(
        context_->root_application_path.get() /context_->pkgid.get());
  bf::path install_path = GetAppPath();
  bf::path unzip_path = context_->unpacked_dir_path.get();
  if (!AddFiles(unzip_path, install_path) ||
     !ModifyFiles(unzip_path, install_path) ||
     !DeleteFiles(install_path)) {
    LOG(ERROR) << "error during file operation";
    return Step::Status::ERROR;
  }
  return Step::Status::OK;
}

Step::Status StepRDSModify::undo() {
  RestoreFiles();
  return Step::Status::OK;
}

Step::Status StepRDSModify::clean() {
  if (bf::exists(backup_temp_dir_))
    bf::remove_all(backup_temp_dir_);
  return Step::Status::OK;
}

bool StepRDSModify::AddFiles(bf::path unzip_path, bf::path install_path) {
  LOG(INFO) << "about to add files";
  bs::error_code error;
  for (const auto& file : context_->files_to_add.get()) {
    if (!PerformBackup(file, Operation::ADD)) {
      LOG(ERROR) << "unable to perform backup of added file";
      return false;
    }
    bf::path temp_install_path(install_path / file);
    if (bf::is_directory(temp_install_path)) {
      if (!bf::exists(temp_install_path) &&
         (!CreateDir(temp_install_path))) {
        LOG(ERROR) << "unable to create dir for temp backup data";
        return false;
      }
    } else {
      if (!bf::exists(temp_install_path.parent_path()) &&
          !CreateDir(temp_install_path.parent_path())) {
        LOG(ERROR) << "unable to create dir for temp backup data";
        return false;
      }
      bf::path temp_unzip_path(unzip_path / file);
      bf::copy_file(temp_unzip_path, temp_install_path, error);
      if (error) {
        LOG(ERROR) << "unable to add file " << error.message();
        return false;
      }
    }
  }
  return true;
}

bool StepRDSModify::ModifyFiles(bf::path unzip_path, bf::path install_path) {
  LOG(INFO) << "about to modify files";
  bs::error_code error;
  for (const auto& file : context_->files_to_modify.get()) {
    bf::path temp_install_path(install_path / file);
    bf::path temp_unzip_path(unzip_path / file);
    if (!PerformBackup(file, Operation::MODIFY)) {
      LOG(ERROR) << "unable to perform backup of to be modified file";
      return false;
    }
    bf::copy_file(temp_unzip_path, temp_install_path,
                  bf::copy_option::overwrite_if_exists, error);
    if (error) {
      LOG(ERROR) << "unable to modify file " << error.message();
      return false;
    }
  }
  return true;
}

bool StepRDSModify::DeleteFiles(bf::path install_path) {
  LOG(INFO) << "about to delete files";
  bs::error_code error;
  for (const auto& file : context_->files_to_delete.get()) {
    if (!PerformBackup(file, Operation::DELETE)) {
      LOG(ERROR) << "unable to perform backup of to be deleted file";
      return false;
    }
    bf::remove(install_path / file, error);
    if (error) {
      LOG(ERROR) <<"unable to delete files " << error.message();
      return false;
    }
  }
  return true;
}

bool StepRDSModify::SetUpTempBackupDir() {
  LOG(INFO) << "about to setup tmp backup dir";
  bs::error_code error;
  backup_temp_dir_ = "/tmp/" /
      bf::unique_path("%%%%-%%%%-%%%%-%%%%", error);
  if (error || !CreateDir(backup_temp_dir_)) {
    LOG(ERROR) << "unable to create backup data temp dir";
    return false;
  }

  return true;
}

bool StepRDSModify::PerformBackup(std::string relative_path,
                                  Operation operation) {
  if (backup_temp_dir_.empty())
    return false;
  if (operation == Operation::DELETE || operation == Operation::MODIFY) {
    bf::path app_path = GetAppPath();
    bf::path source_path = app_path  / relative_path;
    if (bf::is_directory(source_path)) {
      if (!CreateDir(backup_temp_dir_ / relative_path)) {
        LOG(ERROR) << "unable to create dir for temp backup data";
        return false;
      }
    } else {
      bs::error_code error;
      bf::path tmp_dest_path = backup_temp_dir_ / relative_path;
      if (!bf::exists((tmp_dest_path).parent_path()) &&
        (!CreateDir((tmp_dest_path).parent_path()))) {
        LOG(ERROR) << "unable to create dir for temp backup data";
        return false;
      }
      bf::copy_file(source_path, tmp_dest_path, error);
      if (error) {
        LOG(ERROR) << "unable to backup file: "
                   << source_path << " : " << error.message();
        return false;
      }
    }
  }
  success_modifications_.push_back(std::make_pair(relative_path, operation));
  return true;
}

void StepRDSModify::RestoreFiles() {
  LOG(ERROR) << "error occured about to restore files";
  bf::path app_path(context_->pkg_path.get());
  for (std::pair<std::string, Operation>& modification :
       success_modifications_) {
    bf::path source_path(backup_temp_dir_ / modification.first);
    bf::path destination_path(app_path / modification.first);
    if (modification.second == Operation::ADD) {
      if (bf::is_directory(source_path)) {
        bf::remove_all(destination_path);
      } else {
        bf::remove(destination_path);
      }
    } else if (modification.second == Operation::MODIFY) {
      bf::copy_file(source_path, destination_path,
                    bf::copy_option::overwrite_if_exists);
    } else {
      if (bf::is_directory(source_path)) {
        CreateDir(destination_path);
      } else {
        bf::copy_file(source_path, destination_path,
                      bf::copy_option::overwrite_if_exists);
      }
    }
  }
  // after files are restore delete temporary location
  bf::remove_all(backup_temp_dir_);
}

}  // namespace rds
}  // namespace common_installer

ext: cc


text:
#define BOOST_THREAD_PROVIDES_FUTURE

#include <iostream>
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>

using namespace std;

int accumulate()
{
    int sum = 0;
    for (int i = 0; i < 5; ++i)
        sum += i;
    return sum;
}

int main()
{
    boost::future<int> f = boost::async(accumulate);
    cout << f.get() << endl;
    return 0;
}


text:
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
//    names, trademarks, service marks, or product names of the Licensor
//    and its affiliates, except as required to comply with Section 4(c) of
//    the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//

#include "pxr/pxr.h"

#include <set>
#include <utility>
#include <vector>
#include <locale>

#include "pxr/usd/sdf/path.h"
#include "pxr/base/tf/pyAnnotatedBoolResult.h"
#include "pxr/base/tf/pyResultConversions.h"
#include "pxr/base/tf/pyContainerConversions.h"
#include "pxr/base/tf/hash.h"
#include "pxr/base/vt/valueFromPython.h"

#include <boost/python.hpp>

#include <thread>
#include <atomic>

using namespace boost::python;
using std::pair;
using std::string;
using std::vector;

PXR_NAMESPACE_USING_DIRECTIVE

namespace {

static vector<SdfPath> GetPrefixesHelper( const SdfPath &path ) {
    return path.GetPrefixes();
}

static string
_Repr(const SdfPath &self) {
    if (self.IsEmpty()) {
        return TF_PY_REPR_PREFIX + "Path.emptyPath";
    }
    else {
        return string(TF_PY_REPR_PREFIX +
            "Path(")+TfPyRepr(self.GetAsString())+")";
    }
}

static SdfPathVector
_RemoveDescendentPaths(SdfPathVector paths)
{
    SdfPath::RemoveDescendentPaths(&paths);
    return paths;
}

static SdfPathVector
_RemoveAncestorPaths(SdfPathVector paths)
{
    SdfPath::RemoveAncestorPaths(&paths);
    return paths;
}

static object
_FindPrefixedRange(SdfPathVector const &paths, SdfPath const &prefix)
{
    pair<SdfPathVector::const_iterator, SdfPathVector::const_iterator>
        result = SdfPathFindPrefixedRange(paths.begin(), paths.end(), prefix);
    object start(result.first - paths.begin());
    object stop(result.second - paths.begin());
    handle<> slice(PySlice_New(start.ptr(), stop.ptr(), NULL));
    return object(slice);
}

static object
_FindLongestPrefix(SdfPathVector const &paths, SdfPath const &path)
{
    SdfPathVector::const_iterator result =
        SdfPathFindLongestPrefix(paths.begin(), paths.end(), path);
    if (result == paths.end())
        return object();
    return object(*result);
}

static object
_FindLongestStrictPrefix(SdfPathVector const &paths, SdfPath const &path)
{
    SdfPathVector::const_iterator result =
        SdfPathFindLongestStrictPrefix(paths.begin(), paths.end(), path);
    if (result == paths.end())
        return object();
    return object(*result);
}

struct Sdf_PathIsValidPathStringResult : public TfPyAnnotatedBoolResult<string>
{
    Sdf_PathIsValidPathStringResult(bool val, string const &msg) :
        TfPyAnnotatedBoolResult<string>(val, msg) {}
};

static
Sdf_PathIsValidPathStringResult
_IsValidPathString(string const &pathString)
{
    string errMsg;
    bool valid = SdfPath::IsValidPathString(pathString, &errMsg);
    return Sdf_PathIsValidPathStringResult(valid, errMsg);
}

static
SdfPathVector
_WrapGetAllTargetPathsRecursively(SdfPath const self)
{
    SdfPathVector result;
    self.GetAllTargetPathsRecursively(&result);
    return result;
}

static bool
__nonzero__(SdfPath const &self)
{
    return !self.IsEmpty();
}

constexpr size_t NumStressPaths = 1 << 28;
constexpr size_t NumStressThreads = 16;
constexpr size_t StressIters = 3;
constexpr size_t MaxStressPathSize = 16;

static void _PathStressTask(size_t index, std::vector<SdfPath> &paths)
{
    auto pathsPerThread = NumStressPaths / NumStressThreads;
    auto begin = paths.begin() + pathsPerThread * index;
    auto end = begin + pathsPerThread;

    for (size_t stressIter = 0; stressIter != StressIters; ++stressIter) {
        for (auto i = begin; i != end; ++i) {
            SdfPath p = SdfPath::AbsoluteRootPath();
            //size_t offset = (i - begin) * index + stressIter;
            for (size_t j = 0; j != (rand() % MaxStressPathSize); ++j) {
                char name[2];
                name[0] = 'a' + (rand() % 26);
                name[1] = '\0';
                p = p.AppendChild(TfToken(name));
            }
            //if ((i-begin) % 1000 == 0) {
            //printf("%zu: storing path %zu: <%s>\n",
            //       (i-begin), index, p.GetText());
            //}
            *i = p;
        }
        printf("%zu did iter %zu\n", index, stressIter);
    }
}

static void _PathStress()
{
    TF_PY_ALLOW_THREADS_IN_SCOPE();

    std::vector<SdfPath> manyPaths(NumStressPaths);
    std::vector<std::thread> threads(NumStressThreads);

    size_t index = 0;
    for (auto &t: threads) {
        t = std::thread(_PathStressTask, index++, std::ref(manyPaths));
    }
    for (auto &t: threads) {
        t.join();
    }
}

struct Sdf_PyPathAncestorsRangeIterator {
    Sdf_PyPathAncestorsRangeIterator(
        const SdfPathAncestorsRange::iterator& begin,
        const SdfPathAncestorsRange::iterator& end)
        : _it(begin), _end(end) {}

    SdfPath next() {
        _RaiseIfAtEnd();
        if (_didFirst) {
            ++_it;
            _RaiseIfAtEnd();
        }
        _didFirst = true;
        return *_it;
    }

private:
    void _RaiseIfAtEnd() const {
        if (_it == _end) {
            PyErr_SetString(PyExc_StopIteration, "Iterator at end");
            throw_error_already_set();
        }
    }

    SdfPathAncestorsRange::iterator _it, _end;
    bool _didFirst = false;
};

Sdf_PyPathAncestorsRangeIterator
Sdf_GetIterator(const SdfPathAncestorsRange& range)
{
    return {range.begin(), range.end()};
}

void Sdf_wrapAncestorsRange()
{
    using This = SdfPathAncestorsRange;

    scope s = class_<This>("AncestorsRange", init<const SdfPath&>() )
        .def("GetPath", &This::GetPath,
             return_value_policy<return_by_value>())
        .def("__iter__", &Sdf_GetIterator)
        ;

    using Iter = Sdf_PyPathAncestorsRangeIterator;
    class_<Iter>("_iterator", no_init)
        .def(TfPyIteratorNextMethodName, &Iter::next)
        ;
}

} // anonymous namespace

void wrapPath() {
    typedef SdfPath This;

    def("_PathStress", &_PathStress);
    def("_DumpPathStats", &Sdf_DumpPathStats);

    scope s = class_<This> ( "Path", init< const string & >() )
        .def( init<const SdfPath &>() )
        .def( init<>() )

        // XXX: Document constants
        .def_readonly("absoluteRootPath", &SdfPath::AbsoluteRootPath(),
            "The absolute path representing the top of the \n"
            "namespace hierarchy (</>).")
        .def_readonly("reflexiveRelativePath", &SdfPath::ReflexiveRelativePath(),
            "The relative path representing 'self' (<.>).")
        .def_readonly("emptyPath", &SdfPath::EmptyPath(),
            "The empty path.")

        .add_property("pathElementCount", &This::GetPathElementCount,
            "The number of path elements in this path.")
        .add_property("pathString",
            make_function(&This::GetAsString),
            "The string representation of this path.")
        .add_property("name", make_function(&This::GetName,
                    return_value_policy<copy_const_reference>()),
            "The name of the prim, property or relational\n"
            "attribute identified by the path.\n\n"
            "'' for EmptyPath.  '.' for ReflexiveRelativePath.\n"
            "'..' for a path ending in ParentPathElement.\n")
        .add_property("elementString",
            make_function(&This::GetElementString,
                return_value_policy<return_by_value>()),
            "The string representation of the terminal component of this path."
            "\nThis path can be reconstructed via \n"
            "thisPath.GetParentPath().AppendElementString(thisPath.element).\n"
            "None of absoluteRootPath, reflexiveRelativePath, nor emptyPath\n"
            "possess the above quality; their .elementString is the empty string.")
        .add_property("targetPath", make_function(&This::GetTargetPath,
                    return_value_policy<copy_const_reference>()),
            "The relational attribute target path for this path.\n\n"
            "EmptyPath if this is not a relational attribute path.")

        .def("GetAllTargetPathsRecursively", &_WrapGetAllTargetPathsRecursively,
             return_value_policy<TfPySequenceToList>())

        .def("GetVariantSelection", &This::GetVariantSelection,
             return_value_policy<TfPyPairToTuple>())

        .def("IsAbsolutePath", &This::IsAbsolutePath)
        .def("IsAbsoluteRootPath", &This::IsAbsoluteRootPath)
        .def("IsPrimPath", &This::IsPrimPath)
        .def("IsAbsoluteRootOrPrimPath", &This::IsAbsoluteRootOrPrimPath)
        .def("IsRootPrimPath", &This::IsRootPrimPath)
        .def("IsPropertyPath", &This::IsPropertyPath)
        .def("IsPrimPropertyPath", &This::IsPrimPropertyPath)
        .def("IsNamespacedPropertyPath", &This::IsNamespacedPropertyPath)
        .def("IsPrimVariantSelectionPath", &This::IsPrimVariantSelectionPath)
        .def("ContainsPrimVariantSelection", &This::ContainsPrimVariantSelection)
        .def("ContainsPropertyElements", &This::ContainsPropertyElements)
        .def("IsRelationalAttributePath", &This::IsRelationalAttributePath)
        .def("IsTargetPath", &This::IsTargetPath)
        .def("ContainsTargetPath", &This::ContainsTargetPath)
        .def("IsMapperPath", &This::IsMapperPath)
        .def("IsMapperArgPath", &This::IsMapperArgPath)
        .def("IsExpressionPath", &This::IsExpressionPath)

        .add_property("isEmpty", &This::IsEmpty)

        .def("HasPrefix", &This::HasPrefix)

        .def("MakeAbsolutePath", &This::MakeAbsolutePath)
        .def("MakeRelativePath", &This::MakeRelativePath)

        .def("GetPrefixes", GetPrefixesHelper,
              return_value_policy< TfPySequenceToList >(),
            "Returns the prefix paths of this path.")

        .def("GetAncestorsRange", &This::GetAncestorsRange)

        .def("GetParentPath", &This::GetParentPath)
        .def("GetPrimPath", &This::GetPrimPath)
        .def("GetPrimOrPrimVariantSelectionPath", &This::GetPrimOrPrimVariantSelectionPath)
        .def("GetAbsoluteRootOrPrimPath", &This::GetAbsoluteRootOrPrimPath)
        .def("StripAllVariantSelections", &This::StripAllVariantSelections)

        .def("AppendPath", &This::AppendPath)
        .def("AppendChild", &This::AppendChild)
        .def("AppendProperty", &This::AppendProperty)
        .def("AppendVariantSelection", &This::AppendVariantSelection)
        .def("AppendTarget", &This::AppendTarget)
        .def("AppendRelationalAttribute", &This::AppendRelationalAttribute)
        .def("AppendMapper", &This::AppendMapper)
        .def("AppendMapperArg", &This::AppendMapperArg)
        .def("AppendExpression", &This::AppendExpression)
        .def("AppendElementString", &This::AppendElementString)

        .def("ReplacePrefix", &This::ReplacePrefix,
             ( arg("oldPrefix"),
               arg("newPrefix"),
               arg("fixTargetPaths") = true))
        .def("GetCommonPrefix", &This::GetCommonPrefix)
        .def("RemoveCommonSuffix", &This::RemoveCommonSuffix,
            arg("stopAtRootPrim") = false,
            return_value_policy< TfPyPairToTuple >())
        .def("ReplaceName", &This::ReplaceName)
        .def("ReplaceTargetPath", &This::ReplaceTargetPath)
        .def("MakeAbsolutePath", &This::MakeAbsolutePath)
        .def("MakeRelativePath", &This::MakeRelativePath)

        .def("GetConciseRelativePaths", &This::GetConciseRelativePaths,
            return_value_policy< TfPySequenceToList >())
            .staticmethod("GetConciseRelativePaths")

        .def("RemoveDescendentPaths", _RemoveDescendentPaths,
             return_value_policy< TfPySequenceToList >())
            .staticmethod("RemoveDescendentPaths")
        .def("RemoveAncestorPaths", _RemoveAncestorPaths,
             return_value_policy< TfPySequenceToList >())
            .staticmethod("RemoveAncestorPaths")

        .def("IsValidIdentifier", &This::IsValidIdentifier)
            .staticmethod("IsValidIdentifier")

        .def("IsValidNamespacedIdentifier", &This::IsValidNamespacedIdentifier)
            .staticmethod("IsValidNamespacedIdentifier")

        .def("TokenizeIdentifier",
             &This::TokenizeIdentifier)
            .staticmethod("TokenizeIdentifier")
        .def("JoinIdentifier",
             (std::string (*)(const std::vector<std::string>&))
                 &This::JoinIdentifier)
        .def("JoinIdentifier",
             (std::string (*)(const std::string&, const std::string&))
                 &This::JoinIdentifier)
            .staticmethod("JoinIdentifier")

        .def("StripNamespace",
             (std::string (*)(const std::string&))
                 &This::StripNamespace)
            .staticmethod("StripNamespace")
        .def("StripPrefixNamespace", &This::StripPrefixNamespace,
                return_value_policy<TfPyPairToTuple>())
            .staticmethod("StripPrefixNamespace")

        .def("IsValidPathString", &_IsValidPathString)
             .staticmethod("IsValidPathString")

        .def("FindPrefixedRange", _FindPrefixedRange)
            .staticmethod("FindPrefixedRange")

        .def("FindLongestPrefix", _FindLongestPrefix)
            .staticmethod("FindLongestPrefix")

        .def("FindLongestStrictPrefix", _FindLongestStrictPrefix)
            .staticmethod("FindLongestStrictPrefix")

        .def("__str__", make_function(&This::GetAsString))

        .def(TfPyBoolBuiltinFuncName, __nonzero__)

        .def(self == self)
        .def(self != self)
        .def(self < self)
        .def(self > self)
        .def(self <= self)
        .def(self >= self)
        .def("__repr__", _Repr)
        .def("__hash__", &This::GetHash)
        ;

    s.attr("absoluteIndicator") = &SdfPathTokens->absoluteIndicator;
    s.attr("childDelimiter") = &SdfPathTokens->childDelimiter;
    s.attr("propertyDelimiter") = &SdfPathTokens->propertyDelimiter;
    s.attr("relationshipTargetStart") = &SdfPathTokens->relationshipTargetStart;
    s.attr("relationshipTargetEnd") = &SdfPathTokens->relationshipTargetEnd;
    s.attr("parentPathElement") = &SdfPathTokens->parentPathElement;
    s.attr("mapperIndicator") = &SdfPathTokens->mapperIndicator;
    s.attr("expressionIndicator") = &SdfPathTokens->expressionIndicator;
    s.attr("mapperArgDelimiter") = &SdfPathTokens->mapperArgDelimiter;
    s.attr("namespaceDelimiter") = &SdfPathTokens->namespaceDelimiter;

    // Register conversion for python list <-> vector<SdfPath>
    to_python_converter<SdfPathVector, TfPySequenceToPython<SdfPathVector> >();
    TfPyContainerConversions::from_python_sequence<
        SdfPathVector,
        TfPyContainerConversions::
            variable_capacity_all_items_convertible_policy >();

    // Register conversion for python list <-> set<SdfPath>
    to_python_converter<SdfPathSet, TfPySequenceToPython<SdfPathSet> >();
    TfPyContainerConversions::from_python_sequence<
        std::set<SdfPath>,
        TfPyContainerConversions::set_policy >();

    implicitly_convertible<string, This>();

    VtValueFromPython<SdfPath>();

    Sdf_PathIsValidPathStringResult::
        Wrap<Sdf_PathIsValidPathStringResult>("_IsValidPathStringResult",
                                            "errorMessage");

    Sdf_wrapAncestorsRange();
}

max_stars_repo_name: imageworks/USD

max_issues_repo_name: davidgyu/USD

max_forks_repo_name: davidgyu/USD


text:
 /*! \mainpage alphaTorrent Documentation
 *
 * \section intro_sec Introduction
 *
 * alphaTorrent is a CLI program that allow to download files by passing a .torrent file.
 * For a detailed explaination of the application workflow see @ref workflow.
 * \section install_sec Installation
 *
 * \subsection step1 Step 1: Clone the repository
 * \code
 * git clone https://github.com/lorisrossi/alphaTorrent.git
 * \endcode
 *
 *
 * \subsection step21 Step2: Install dependencies (Linux)
 * This command will install the openssl, boost and glog libraries
 * \code
 * sudo apt-get install libssl-dev libboost-all-dev libgoogle-glog-dev
 * \endcode
 *
  * \subsection step22 Step2: Install dependencies (Mac OS X)
 * This command will install the openssl
 * \code
 * brew install openssl
 * cd /usr/local/include
 * ln -s ../opt/openssl/include/openssl .
 * \endcode
 * Boost
 * \code
 * brew install boost
 * \endcode
 * Glog
 * \code
 * brew install glog
 * \endcode
 *
 * \subsection compiling Compiling
 * Go to the main folder and execute
 * \code
 * make
 * \endcode
 *
 * \section usage Usage
 * \code
 * ./alphatorrent-cli torrent-file.torrent
 * \endcode
 *
 *
 */

#include <iostream>
#include <string>
#include <string.h>
#include <glog/logging.h>   //Logging Library
#include <boost/asio/signal_set.hpp>  //For interrupt signal

#include "torrentparser.hpp"
#include "tracker.h"
#include "filehandler.hpp"
#include "peer.h"
#include "pwp.hpp"  //For is_inv_address
#include "rang.hpp"

using namespace std;
using namespace torr;
using namespace fileio;
using namespace rang;

#define PEER_TREESHOLD 3  /*!< Number of peer after make another tracker request */

tracker::TParameter set_parameter(const string& torrent_str, const Torrent& torr){
    tracker::TParameter param;

    param.info_hash_raw = get_info_node_hash(&torrent_str, &torr.pieces);  //Extract info_hash
    param.left = torr.piece_length * torr.pieces.size();
    pwp::get_peer_id(&param.peer_id);

    return param;
}

/**
 * @brief Handler of the SIGINT signal
 *
 * This handler clear the memory and stops the threads safely
 *
 * @param t_group The group of active thread
 */

void innerrupt_handler(boost::thread_group &t_group){

  cout << "Handled interrupt signal " << endl;
  cout << "Interrupting thread...";
  t_group.interrupt_all();

  curl_global_cleanup();
  cout << fg::red << "Exiting" << fg::reset << endl;
  exit(1);

}

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

  using namespace rang;
  using namespace std;

  if (argc <= 1) {
    cout << "Usage: pass a .torrent file as a parameter" << endl;
    return 1;
  }

  google::InitGoogleLogging(argv[0]); //Initialize GLog with passed argument
  curl_global_init(CURL_GLOBAL_DEFAULT);

  pwp::PeerList peer_list = make_shared<vector<pwp::peer>>(); //Pre-Allocate the peers list
  boost::thread_group t_group;  //Thread Group for managing the peers

  boost::asio::signal_set signals(_io_service, SIGINT );
  signals.async_wait( boost::bind(&innerrupt_handler, boost::ref(t_group)) );

  Torrent mytorrent;
  string torrent_str;
  // parse .torrent file
  int success = parse_torrent(mytorrent, torrent_str, argv[1]);
  if(success < 0) {
    return success;
  }

  check_files(mytorrent);

  //Populate the torrent parameter
  tracker::TParameter param = set_parameter(torrent_str, mytorrent);

  while(true){

    while(active_peer < PEER_TREESHOLD){

        peer_list->clear();

        //Start contacting the tracker

        cout << fg::gray << bg::magenta << "Start Tracker Request" << style::reset << bg::reset << endl;;
        int error_code = start_tracker_request(&param, mytorrent.trackers, peer_list);
        if(error_code < 0){
          cout << fg::red << "Error while encoding parameters, exit" << fg::reset << endl;
          return -3;
        }

        pwp::remove_invalid_peer(peer_list);

        DLOG(INFO) << "Building handshake..." << endl;
        std::vector<uint8_t> handshake = std::vector<uint8_t>();
        pwp::build_handshake(param.info_hash_raw, handshake);

        //Start the PWP protocol with the peers

        vector<pwp::peer>::iterator it = peer_list->begin();

        for(;it != peer_list->end(); ++it){
            if(!is_inv_address(it->addr)){
              cout<< "Starting executing the protocol with " << it->addr.to_string() << ":" << it->port << "... " << endl;
              t_group.add_thread(new boost::thread( &pwp::pwp_protocol_manager, *it, handshake, param.info_hash_raw, mytorrent));
            }
        }

        if(_io_service.stopped()){
            cout << endl << "-------------------------STOPPED-----------------------" << endl;
            _io_service.reset();
            signals.async_wait( boost::bind(&innerrupt_handler, boost::ref(t_group)) );
            _io_service.run();
        }

        boost::this_thread::sleep_for(boost::chrono::seconds(10));  //Sleep for 10 seconds
    }

    cout << endl << "Having enought active peers (" << active_peer << "), recheck after 10 seconds... " << endl;
    boost::this_thread::sleep_for(boost::chrono::seconds(10));
  }

  t_group.join_all();

  if(param.info_hash_raw != nullptr)
    free(param.info_hash_raw);

  curl_global_cleanup();
  return 0;
}

max_stars_repo_name: lorisrossi/-Torrent

max_issues_repo_name: lorisrossi/-Torrent

max_forks_repo_name: lorisrossi/-Torrent


text:
#include <cmath>

#include <boost/test/unit_test.hpp>

#include "lineside/pwitemmodel.hpp"
#include "lineside/pwitemcontroller.hpp"

#include "exceptionmessagecheck.hpp"

// ===================================

class MockModel : public Lineside::PWItemModel {
public:
  MockModel(Lineside::ItemId id) :
    Lineside::PWItemModel(id),
    onActivateCalled(false),
    onDeactivateCalled(false),
    runThreadId(),
    onRunCallTimes(),
    onRunWait(100),
    stateChange(false) {}

  virtual void OnActivate() override {
    if(this->onActivateCalled) {
      throw std::logic_error("Double call OnActivate");
    }
    this->onActivateCalled = true;
    this->runThreadId = std::this_thread::get_id();
  }

  virtual void OnDeactivate() override {
    if(this->onDeactivateCalled) {
      throw std::logic_error("Double call OnDeactivate");
    }
    if( !this->onActivateCalled ) {
      throw std::logic_error("OnDeactivate called before OnActivate");
    }
    this->onDeactivateCalled = true;
  }

  virtual std::chrono::milliseconds OnRun() override {
    this->onRunCallTimes.push_back(std::chrono::high_resolution_clock::now());
    return this->onRunWait;
  }

  virtual bool HaveStateChange() override {
    bool result = this->stateChange;
    this->stateChange = false;
    return result;
  }

  bool onActivateCalled;
  bool onDeactivateCalled;
  std::thread::id runThreadId;
  std::vector<std::chrono::high_resolution_clock::time_point> onRunCallTimes;
  std::chrono::milliseconds onRunWait;
  bool stateChange;
};

// ===================================

const std::chrono::milliseconds timeFuzz(10);

void PauseForThread() {
  // We are managing a separate thread, but have no direct
  // visibility. Wait a short time to give it an opportunity
  // to run before performing checks
  // Of course, this is still not an absolute guarantee
  std::this_thread::sleep_for(std::chrono::milliseconds(50));
}

// ===================================

BOOST_AUTO_TEST_SUITE(PWItemController,
		      *boost::unit_test::description("Tests of the PWItemController"))

BOOST_AUTO_TEST_CASE(BasicLifeCycle, *boost::unit_test::timeout(2))
{
  Lineside::ItemId id = Lineside::ItemId::Random();
  auto model = std::make_shared<MockModel>(id);

  auto controller = Lineside::PWItemController::Construct(model);
  BOOST_CHECK_EQUAL(controller.use_count(), 1);
  BOOST_CHECK(!model->onActivateCalled);
  BOOST_CHECK_EQUAL(model->onRunCallTimes.size(), 0);

  controller->Activate();
  PauseForThread();
  BOOST_CHECK(model->onActivateCalled);
  BOOST_CHECK( std::this_thread::get_id() != model->runThreadId );

  // Following may fail if thread scheduling is particularly
  // weird
  BOOST_CHECK_EQUAL(model->onRunCallTimes.size(), 1);

  controller->Deactivate();
  PauseForThread();
  BOOST_CHECK( model->onDeactivateCalled );

  // Since we only had a short pause, should not have
  // had more OnRun() calls
  BOOST_CHECK_EQUAL(model->onRunCallTimes.size(), 1);
}

BOOST_AUTO_TEST_CASE(ShortDurationSleeps, *boost::unit_test::timeout(2))
{
  Lineside::ItemId id = Lineside::ItemId::Random();
  auto model = std::make_shared<MockModel>(id);
  auto controller = Lineside::PWItemController::Construct(model);
  BOOST_CHECK_EQUAL(model->onRunCallTimes.size(), 0);

  const int nSleepIntervals = 10;

  controller->Activate();
  // Let OnRun() be called a few times
  std::this_thread::sleep_for(model->onRunWait * nSleepIntervals);
  controller->Deactivate();

  // Check how many times OnRun() was called
  double countDeviation = model->onRunCallTimes.size() - nSleepIntervals;
  BOOST_CHECK( std::abs(countDeviation) <= 1 );

  // Check the call times
  for( size_t i=1; i<model->onRunCallTimes.size(); i++ ) {
    auto timediff = model->onRunCallTimes.at(i) - model->onRunCallTimes.at(i-1);

    // No abs() for duration objects....
    auto deviation = timediff - model->onRunWait;
    BOOST_CHECK( deviation < timeFuzz );
    BOOST_CHECK( -deviation < timeFuzz );
  }
}

BOOST_AUTO_TEST_CASE(LongSleepIgnored,
		     *boost::unit_test::timeout(40)
		     *boost::unit_test::label("LongRunning"))
{
  // Shorten the maximum for easier testing
  Lineside::PWItemController::MaximumWaitSeconds = std::chrono::seconds(10);

  Lineside::ItemId id = Lineside::ItemId::Random();
  auto model = std::make_shared<MockModel>(id);
  auto controller = Lineside::PWItemController::Construct(model);
  BOOST_CHECK_EQUAL(model->onRunCallTimes.size(), 0);

  // Set too long sleep request
  model->onRunWait = std::chrono::seconds(550);

  controller->Activate();
  std::this_thread::sleep_for(std::chrono::seconds(35));

  // Should get at least three OnRun() calls due to MaximumWaitTime
  BOOST_CHECK_GE( model->onRunCallTimes.size(), 3 );

}

BOOST_AUTO_TEST_CASE(DestructorDeactivates, *boost::unit_test::timeout(2))
{
  Lineside::ItemId id = Lineside::ItemId::Random();
  auto model = std::make_shared<MockModel>(id);
  model->onRunWait = std::chrono::seconds(4);
  {
    auto controller = Lineside::PWItemController::Construct(model);
    controller->Activate();
  }
  BOOST_CHECK( model->onDeactivateCalled );
}

BOOST_AUTO_TEST_CASE(ModelCanNotify, *boost::unit_test::timeout(2))
{
  Lineside::ItemId id = Lineside::ItemId::Random();
  auto model = std::make_shared<MockModel>(id);
  auto controller = Lineside::PWItemController::Construct(model);
  BOOST_CHECK_EQUAL(model->onRunCallTimes.size(), 0);

  model->onRunWait = std::chrono::seconds(4);
  controller->Activate();

  auto notificationTime = std::chrono::high_resolution_clock::now();
  model->WakeController();
  PauseForThread();
  controller->Deactivate();

  auto lastOnRunTime = model->onRunCallTimes.back();
  auto timeDiff = lastOnRunTime - notificationTime;
  BOOST_CHECK( timeDiff < timeFuzz );
}

BOOST_AUTO_TEST_CASE(IncorrectActivate, *boost::unit_test::timeout(2))
{
  Lineside::ItemId id = Lineside::ItemId::Random();
  auto model = std::make_shared<MockModel>(id);
  auto controller = Lineside::PWItemController::Construct(model);

  controller->Activate();

  std::stringstream msg;
  msg << "Improper Activate() call on " << id;

  // Do a second activate
  BOOST_CHECK_EXCEPTION( controller->Activate(),
			 std::logic_error,
			 GetExceptionMessageChecker<std::logic_error>( msg.str() ) );

  // Also can't re-activate
  controller->Deactivate();
  BOOST_CHECK_EXCEPTION( controller->Activate(),
			 std::logic_error,
			 GetExceptionMessageChecker<std::logic_error>( msg.str() ) );
}

BOOST_AUTO_TEST_CASE(DeactivateWithoutActivate, *boost::unit_test::timeout(1))
{
  Lineside::ItemId id = Lineside::ItemId::Random();
  auto model = std::make_shared<MockModel>(id);
  auto controller = Lineside::PWItemController::Construct(model);

  BOOST_CHECK_NO_THROW( controller->Deactivate() );
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: freesurfer-rge/linesidecabinet

max_issues_repo_name: freesurfer-rge/linesidecabinet

max_forks_repo_name: freesurfer-rge/linesidecabinet


text:
//    Copyright The asap Project Authors 2018.
//    Distributed under the 3-Clause BSD License.
//    (See accompanying file LICENSE or copy at
//   https://opensource.org/licenses/BSD-3-Clause)

#include <imgui_runner.h>

#include <fstream>

#include <boost/asio.hpp>

// clang-format off
// Include order is important
#include <glad/gl.h>
#include <GLFW/glfw3.h>

#include <imgui.h>
#include <imgui/imgui_impl_glfw.h>
#include <imgui/imgui_impl_opengl3.h>
// clang-format on

#include <yaml-cpp/yaml.h>

#include <common/assert.h>
#include <ui/application.h>
#include <fsl.h>

namespace bfs = boost::filesystem;

namespace {
void glfw_error_callback(int error, const char *description) {
  auto &logger = asap::logging::Registry::GetLogger(asap::logging::Id::NDAGENT);
  ASLOG_TO_LOGGER(logger, critical, "Glfw Error {}: {}", error, description);
}
}  // namespace

namespace asap {

ImGuiRunner::ImGuiRunner(RunnerBase::shutdown_function_type f)
    : RunnerBase(std::move(f)) {
  SetupSignalHandler();
  InitGraphics();
}

ImGuiRunner::~ImGuiRunner() {
  if (!io_context_->stopped()) io_context_->stop();
  delete signals_;
  delete io_context_;
}

void ImGuiRunner::SetupSignalHandler() {
  ASLOG(info, "Setup termination signal handlers");
  // Set signal handler
  io_context_ = new boost::asio::io_context(1);
  signals_ = new boost::asio::signal_set(*io_context_);
  // Register to handle the signals that indicate when the server should exit.
  // It is safe to register for the same signal multiple times in a program,
  // provided all registration for the specified signal is made through Asio.
  signals_->add(SIGINT);
  signals_->add(SIGTERM);
}

void ImGuiRunner::InitGraphics() {
  ASLOG(info, "Initialize graphical subsystem...");
  // Setup window
  glfwSetErrorCallback(glfw_error_callback);
  if (!glfwInit()) {
    throw std::runtime_error("Failed to initialize GLFW");
  }
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if __APPLE__
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

  ASLOG(debug, "  GLFW init done");
}

void ImGuiRunner::SetupContext() {
  ASAP_ASSERT(window != nullptr);
  glfwMakeContextCurrent(window);
  gladLoadGL((GLADloadfunc) glfwGetProcAddress);
  ASLOG(debug, "  context setup done");
}

void ImGuiRunner::InitImGui() {
  // Setup Dear ImGui binding
  IMGUI_CHECKVERSION();
  ImGui::CreateContext();
  ImGuiIO &io = ImGui::GetIO();
  (void) io;
  // io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;  // Enable
  // Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
  // // Enable Gamepad Controls

  ImGui_ImplGlfw_InitForOpenGL(window, true);
  ImGui_ImplOpenGL3_Init();
  ASLOG(debug, "  ImGui init done");
}

void ImGuiRunner::Windowed(int width, int height, char const *title) {
  window_title_ = title;

  if (windowed_ && !full_screen_) {
    GetWindowPosition(saved_position_);
  }

  windowed_ = true;
  full_screen_ = false;

  if (!window) {
    ASLOG(debug, "  starting in 'Windowed' mode: w={}, h={}, t='{}'", width,
          height, title);
    glfwWindowHint(GLFW_SAMPLES, MultiSample());  // multisampling
    window = glfwCreateWindow(width, height, title, nullptr, nullptr);
    if (!window) {
      glfwTerminate();
      exit(EXIT_FAILURE);
    }
    SetupContext();
    glfwSwapInterval(Vsync()?1:0);  // Enable vsync
    InitImGui();
  } else {
    ASLOG(debug, "setting 'Windowed' mode: w={}, h={}, t={}", width, height,
          title);
    // Restore the window position when you switch to windowed mode
    glfwSetWindowMonitor(window, nullptr, saved_position_[0],
                         saved_position_[1], width, height, 60);
    glfwSetWindowTitle(window, title);
  }
}

namespace {
GLFWmonitor *GetMonitorByNumber(int monitor) {
  GLFWmonitor *the_monitor{nullptr};
  if (monitor == 0)
    the_monitor = glfwGetPrimaryMonitor();
  else {
    int count;
    GLFWmonitor **monitors = glfwGetMonitors(&count);
    if (monitor >= 0 && monitor < count)
      the_monitor = monitors[monitor];
    else {
      auto &logger = asap::logging::Registry::GetLogger(
          asap::logging::Id::NDAGENT);
      ASLOG_TO_LOGGER(
          logger, error,
          "requested monitor {} is not connected, using primary monitor");
      the_monitor = monitors[0];
    }
  }
  return the_monitor;
}
}  // namespace

void ImGuiRunner::FullScreenWindowed(char const *title, int monitor) {
  window_title_ = title;
  windowed_ = true;
  full_screen_ = false;

  GLFWmonitor *the_monitor = GetMonitorByNumber(monitor);
  const GLFWvidmode *mode = glfwGetVideoMode(the_monitor);
  if (!window) {
    ASLOG(debug,
          "  starting in 'Full Screen Windowed' mode: w={}, h={}, r={}, "
          "t='{}', m={}",
          mode->width/2, mode->height/2, mode->refreshRate, title, monitor);
    glfwWindowHint(GLFW_RED_BITS, mode->redBits);
    glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
    glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
    glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
    glfwWindowHint(GLFW_SAMPLES, MultiSample());  // multisampling
    window = glfwCreateWindow(mode->width, mode->height, title, the_monitor,
                              nullptr);
    if (!window) {
      glfwTerminate();
      exit(EXIT_FAILURE);
    }
    SetupContext();
    glfwSwapInterval(Vsync()?1:0);  // Enable vsync
    InitImGui();
  } else {
    ASLOG(
        debug,
        "setting 'Full Screen Windowed' mode: w={}, h={}, r= {}, t='{}', m={}",
        mode->width, mode->height, mode->refreshRate, title, monitor);

    // Save the window position
    GetWindowPosition(saved_position_);

    glfwSetWindowMonitor(window, the_monitor, 0, 0, mode->width, mode->height,
                         mode->refreshRate);
    glfwSetWindowTitle(window, title);
  }
}
void ImGuiRunner::FullScreen(int width, int height, char const *title,
                             int monitor, int refresh_rate) {
  window_title_ = title;
  windowed_ = false;
  full_screen_ = true;

  GLFWmonitor *the_monitor = GetMonitorByNumber(monitor);
  if (!window) {
    ASLOG(debug,
          "  starting in 'Full Screen' mode: w={}, h={}, t='{}', m={}, r={}",
          width, height, title, monitor, refresh_rate);
    glfwWindowHint(GLFW_REFRESH_RATE, refresh_rate);
    glfwWindowHint(GLFW_SAMPLES, MultiSample());  // multisampling
    window = glfwCreateWindow(width, height, title, the_monitor, nullptr);
    if (!window) {
      glfwTerminate();
      exit(EXIT_FAILURE);
    }
    SetupContext();
    glfwSwapInterval(Vsync()?1:0);  // Enable vsync
    InitImGui();
  } else {
    ASLOG(debug, "setting 'Full Screen' mode: w={}, h={}, t='{}', m={}, r={}",
          width, height, title, monitor, refresh_rate);

    // Save the window position
    GetWindowPosition(saved_position_);

    glfwSetWindowMonitor(window, the_monitor, 0, 0, width, height,
                         refresh_rate);
    glfwSetWindowTitle(window, title);
  }
}

void ImGuiRunner::CleanUp() {
  ASLOG(info, "Cleanup graphical subsystem...");

  // Cleanup ImGui
  ASLOG(debug, "  shutdown OpenGL3");
  ImGui_ImplOpenGL3_Shutdown();
  ASLOG(debug, "  shutdown ImGui/GLFW");
  ImGui_ImplGlfw_Shutdown();
  ASLOG(debug, "  destroy ImGui context");
  ImGui::DestroyContext();

  ASLOG(debug, "  destroy window");
  glfwDestroyWindow(window);
  ASLOG(debug, "  terminate GLFW");
  glfwTerminate();

  // Call the shutdown hook
  ASLOG(debug, "  call shutdown handler");
  shutdown_function_();
}

void ImGuiRunner::Run(AbstractApplication &app) {
  app.Init();

  // Main loop
  bool interrupted = false;
  bool sleep_when_inactive = true;
  while (!glfwWindowShouldClose(window) && !interrupted) {
    signals_->async_wait(
        [this, &interrupted](boost::system::error_code /*ec*/, int /*signo*/) {
          ASLOG(info, "Signal caught");
          // Once all operations have finished the io_context::run() call will
          // exit.
          interrupted = true;
          io_context_->stop();
        });

    if (sleep_when_inactive && !glfwGetWindowAttrib(window, GLFW_FOCUSED)) {
      static float wanted_fps = 5.0f;
      float current_fps = ImGui::GetIO().Framerate;
      float frame_time = 1000 / current_fps;
      auto wait_time = std::lround(1000 / wanted_fps - frame_time);
      if (wanted_fps < current_fps) {
        io_context_->run_for(std::chrono::milliseconds(wait_time));
      }
    } else {
      io_context_->poll_one();
    }

    // Poll and handle events (inputs, window resize, etc.)
    // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to
    // tell if dear imgui wants to use your inputs.
    // - When io.WantCaptureMouse is true, do not dispatch mouse input data
    // to your main application.
    // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input
    // data to your main application. Generally you may always pass all
    // inputs to dear imgui, and hide them from your application based on
    // those two flags.
    glfwPollEvents();

	// Skip frame rendering if the window width or heigh is 0
	// Not doing so will cause the docking system to lose its mind
	int size[2];
	GetWindowSize(size);
	if (size[0] == 0 || size[1] == 0) continue;

    // Start the ImGui frame
    ImGui_ImplOpenGL3_NewFrame();
    ImGui_ImplGlfw_NewFrame();
    ImGui::NewFrame();

    // Draw the Application
    sleep_when_inactive = app.Draw();

    // Rendering
    ImGui::Render();
    int display_w, display_h;
    glfwMakeContextCurrent(window);
    glfwGetFramebufferSize(window, &display_w, &display_h);
    glViewport(0, 0, display_w, display_h);
    glClearColor(0, 0, 0, 255);
    glClear(GL_COLOR_BUFFER_BIT);
    ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

    glfwMakeContextCurrent(window);
    glfwSwapBuffers(window);
  }

  SaveSetting();

  app.ShutDown();
  CleanUp();
}
void ImGuiRunner::EnableVsync(bool state) {
  glfwSwapInterval(state ? 1 : 0);
  vsync_ = state;
}
void ImGuiRunner::MultiSample(int samples) {
  if (samples < 0 || samples > 4) samples = GLFW_DONT_CARE;
  samples_ = samples;
  glfwWindowHint(GLFW_SAMPLES, MultiSample());
}
std::string const &ImGuiRunner::GetWindowTitle() const { return window_title_; }
void ImGuiRunner::SetWindowTitle(char const *title) {
  if (window) {
    window_title_ = title;
    glfwSetWindowTitle(window, title);
  } else {
    ASLOG(error, "call SetWindowTitle() only after the window is created");
  }
}
GLFWmonitor *ImGuiRunner::GetMonitor() const {
  ASAP_ASSERT(window && "don't call GetMonitor() before the window is created");
  return glfwGetWindowMonitor(window);
}
void ImGuiRunner::GetWindowSize(int size[2]) const {
  ASAP_ASSERT(window &&
                  "don't call GetWindowSize() before the window is created");
  glfwGetWindowSize(window, &size[0], &size[1]);
}
void ImGuiRunner::GetWindowPosition(int position[2]) const {
  ASAP_ASSERT(window && "don't call GetMonitor() before the window is created");
  glfwGetWindowPos(window, &position[0], &position[1]);
}

int ImGuiRunner::RefreshRate() const {
  auto vid_mode = glfwGetVideoMode(GetMonitor());
  return vid_mode->refreshRate;
}

int ImGuiRunner::GetMonitorId() const {
  int count = 0;
  GLFWmonitor **monitors = glfwGetMonitors(&count);
  while (--count >= 0 && monitors[count] != GetMonitor());
  return count;
}

// -------------------------------------------------------------------------
// Settings load/save
// -------------------------------------------------------------------------

namespace {
void ConfigSanityChecks(YAML::Node &config) {
  auto &logger = asap::logging::Registry::GetLogger(asap::logging::Id::NDAGENT);

  auto display = config["display"];
  if ( !display) {
    ASLOG_TO_LOGGER(logger, warn, "missing 'display' in config");
  }

  if ( !display["mode"]) {
    ASLOG_TO_LOGGER(logger, warn, "missing 'display/mode' in config");
  }

  if (!display["multi-sampling"]) {
    ASLOG_TO_LOGGER(logger, warn, "missing 'display/multi-sampling' in config");
  }
  if (!display["vsync"]) {
    ASLOG_TO_LOGGER(logger, warn, "missing 'display/vsync' in config");
  }

  auto mode = display["mode"].as<std::string>();
  if (mode == "Full Screen") {
    if (!display["size"]["width"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/size/width' in config");
    }
    if (!display["size"]["height"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/size/height' in config");
    }
    if (!display["title"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/title' in config");
    }
    if (!display["monitor"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/monitor' in config");
    }
    if (!display["refresh-rate"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/refresh-rate' in config");
    }
  } else if (mode == "Full Screen Windowed") {
    if (!display["title"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/title' in config");
    }
    if (!display["monitor"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/monitor' in config");
    }
  } else if (mode == "Windowed") {
    if (!display["size"]["width"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/size/width' in config");
    }
    if (!display["size"]["height"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/size/height' in config");
    }
    if (!display["title"]) {
      ASLOG_TO_LOGGER(logger, warn, "missing 'display/title' in config");
    }
  } else {
    ASLOG_TO_LOGGER(logger, error, "invalid 'display/mode' ({})", mode);
  }
}
}

void ImGuiRunner::LoadSetting() {
  YAML::Node config;
  auto display_settings =
      asap::fs::GetPathFor(asap::fs::Location::F_DISPLAY_SETTINGS);
  auto has_config = false;
  if (bfs::exists(display_settings)) {
    try {
      config = YAML::LoadFile(display_settings.string());
      ASLOG(info, "display settings loaded from {}",
            display_settings);
      has_config = true;
    } catch (std::exception const &ex) {
      ASLOG(error,
            "error () while loading settings from {}", ex.what(),
            display_settings);
    }
  } else {
    ASLOG(info, "file {} does not exist", display_settings);
  }

  if (has_config) {
    ConfigSanityChecks(config);

    auto display = config["display"];
    if (display["multi-sampling"]) {
      MultiSample(display["multi-sampling"].as<int>());
    }
    auto mode = display["mode"].as<std::string>();
    if (mode == "Full Screen") {
      FullScreen(display["size"]["width"].as<int>(),
                 display["size"]["height"].as<int>(),
                 display["title"].as<std::string>().c_str(),
                 display["monitor"].as<int>(),
                 display["refresh-rate"].as<int>());
    } else if (mode == "Full Screen Windowed") {
      FullScreenWindowed(display["title"].as<std::string>().c_str(),
                         display["monitor"].as<int>());
    } else if (mode == "Windowed") {
      Windowed(display["size"]["width"].as<int>(),
               display["size"]["height"].as<int>(),
               display["title"].as<std::string>().c_str());
    } else {
      FullScreenWindowed("ASAP Application", 0);
    }
    if (display["vsync"]) {
      EnableVsync(display["vsync"].as<bool>());
    }
  } else {
    FullScreenWindowed("ASAP Application", 0);
  }
}

void ImGuiRunner::SaveSetting() {
  YAML::Emitter out;
  out << YAML::BeginMap;
  {
    out << YAML::Key << "display";
    out << YAML::BeginMap;
    {
      out << YAML::Key << "title";
      out << YAML::Value << GetWindowTitle();
      out << YAML::Key << "mode";
      if (IsFullScreen()) {
        if (IsWindowed()) {
          out << YAML::Value << "Full Screen Windowed";
          out << YAML::Key << "monitor";
          out << YAML::Value << GetMonitorId();
        } else {
          out << YAML::Value << "Full Screen";
          out << YAML::Key << "size";
          int size[2];
          GetWindowSize(size);
          out << YAML::BeginMap;
          {
            out << YAML::Key << "width";
            out << YAML::Value << size[0];
            out << YAML::Key << "height";
            out << YAML::Value << size[1];
          }
          out << YAML::EndMap;
          out << YAML::Key << "monitor";
          out << YAML::Value << GetMonitorId();
          out << YAML::Key << "refresh-rate";
          out << YAML::Value << RefreshRate();
        }
      } else {
        out << YAML::Value << "Windowed";
        out << YAML::Key << "size";
        int size[2];
        GetWindowSize(size);
        out << YAML::BeginMap;
        {
          out << YAML::Key << "width";
          out << YAML::Value << size[0];
          out << YAML::Key << "height";
          out << YAML::Value << size[1];
        }
        out << YAML::EndMap;
      }
    }
    out << YAML::Key << "multi-sampling";
    out << YAML::Value << MultiSample();
    out << YAML::Key << "vsync";
    out << YAML::Value << Vsync();
    out << YAML::EndMap;
  }
  out << YAML::EndMap;

  auto display_settings =
      asap::fs::GetPathFor(asap::fs::Location::F_DISPLAY_SETTINGS);
  auto ofs = std::ofstream();
  ofs.open(display_settings.string());
  ofs << out.c_str() << std::endl;
  ofs.close();
}

}  // namespace asap

max_stars_repo_name: iznotek/blocxxi

max_issues_repo_name: iznotek/blocxxi

max_forks_repo_name: iznotek/blocxxi


text:
#include <dlfcn.h>
#include <iostream>
#include <fstream>
#include <boost/thread.hpp>
#include <boost/program_options.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include "algo_plugin_manager.h"
#include "ialgo_plugin.h"
#include "city.h"

DEFINE_int32(reloading_period_seconds, 3600, "Num of seconds between two reloadings of the configs.");

namespace {
typedef recomm_engine::IAlgoPlugin *(*create_plugin_function_t)();

recomm_engine::IAlgoPlugin* GetPluginFromDylib(
    const std::string& dylib_file,
    const std::string& symbol_name,
    const std::string& config) {

  LOG(INFO) << "lib name: " << dylib_file << ", symbol name: " << symbol_name;

  void* so_handle = dlopen(dylib_file.c_str(), RTLD_NOW);
  if (NULL == so_handle) {
    LOG(ERROR) << "Failed dlopen " << dylib_file << ", due to " << dlerror();
    return NULL;
  }
  create_plugin_function_t create_plugin_function;
  create_plugin_function = (create_plugin_function_t)dlsym(so_handle, symbol_name.c_str());
  if (NULL == create_plugin_function || NULL == *create_plugin_function) {
    LOG(ERROR) << "Failed load symbol <" << symbol_name << "> for " << dylib_file << ", due to " << dlerror();
    return NULL;
  }
  recomm_engine::IAlgoPlugin* result = (*create_plugin_function)();
  if (NULL == result) {
    LOG(ERROR) << "Failed creating plugin object using <" << dylib_file << ">, due to " << dlerror();
    return NULL;
  }

  int status = result->Initialize(config.c_str());
  if (0 != status) {
    LOG(ERROR) << "Failed configuring plugin [" << config << "], status is " << status;
    delete result;
    return NULL;
  }

  // XXX(baigang): Do not dlclose, otherwise we will miss all function definitions and encounter segment faults...
  // dlclose(so_handle);
  return result;
}
}  // unnamed namespace

namespace recomm_engine {

AlgoPluginManager* AlgoPluginManager::instance_ = new AlgoPluginManager;

AlgoPluginManager::AlgoPluginManager()
  : current_index_(0) {
}

AlgoPluginManager::~AlgoPluginManager() {

}

// @static
void AlgoPluginManager::PeriodicalReloadingThread(AlgoPluginManager* handle) {
  while (true) {
    boost::this_thread::sleep(boost::posix_time::seconds(FLAGS_reloading_period_seconds));
    LOG_IF(ERROR, !handle->LoadPlugins()) << "Failed reloading plugin configs.";
  }
}

bool AlgoPluginManager::Initialize(const std::string& config_file) {
  config_file_ = config_file;
  if (!LoadPlugins()) {
    LOG(ERROR) << "Initialization failed due to failure to load config file " << config_file;
    return false;
  }
  boost::thread config_reloading_thread(&(AlgoPluginManager::PeriodicalReloadingThread), this);
  return true;
}

bool AlgoPluginManager::LoadPlugins() {
  // use the write buffer
  int index = 1 - current_index_;
  plugins_[index].clear();
  std::ifstream config_file(config_file_.c_str());
  if (!config_file.good()) {
    LOG(ERROR) << "Failed open config file [" << config_file_ << "]";
    return false;
  }
  boost::program_options::options_description desc("bucket configs");
  int default_bucket = 0;
  std::string buckets;
  std::string plugin_path;
  desc.add_options()
    ("num_buckets",    boost::program_options::value<int>(&num_plugins_[index]),
         "Num of traffic buckets.")
    ("default_bucket", boost::program_options::value<int>(&default_bucket)->default_value(0),
         "The default bucket, used when no bucket conf is specified.")
    ("plugin_path",    boost::program_options::value<std::string>(&plugin_path),
         "The path to the plugin libs.")
    ("buckets",        boost::program_options::value<std::string>(&buckets)->multitoken(),
         "A series of bucket specifications.")
  ;
  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_config_file(config_file, desc), vm);
  config_file.close();
  boost::program_options::notify(vm);

  LOG(INFO) << "Buckets specification is: {" << buckets << "}";

  boost::char_separator<char> space_sep(" \t");
  boost::char_separator<char> colon_sep(":");
  boost::tokenizer<boost::char_separator<char> > bucket_items(buckets, space_sep);
  for (boost::tokenizer<boost::char_separator<char> >::iterator it = bucket_items.begin();
       it != bucket_items.end(); ++it) {
    boost::tokenizer<boost::char_separator<char> > fields(*it, colon_sep);
    boost::tokenizer<boost::char_separator<char> >::iterator field = fields.begin();

    // 1. bucket id
    int bucket_id = 0;
    try {
      bucket_id = boost::lexical_cast<int>(*field);
    } catch (boost::bad_lexical_cast &) {
      LOG(ERROR) << "Failed reading bucket_id on \"" << *it << "\"";
      return false;
    }

    // 2. bucket name
    std::string bucket_name = *(++field);

    // 3. bucket plugin
    std::string plugin_name = *(++field);
    std::string plugin_libfile = plugin_path + "/lib" + plugin_name + ".so";
    std::string plugin_config  = plugin_path + "/lib" + plugin_name + ".conf";
    std::string plugin_symbol  = "__create_" + plugin_name;

    LOG(INFO) << "Loading config for bucket [" << bucket_id << "].";

    boost::shared_ptr<IAlgoPlugin> this_plugin(GetPluginFromDylib(
        plugin_libfile, plugin_symbol, plugin_config));

    if (NULL == this_plugin) {
      LOG(ERROR) << "Failed loading plugin [" << bucket_id << "-" << plugin_name << "]";
      return false;
    }

    plugins_[index][bucket_id] = this_plugin;
    LOG(INFO) << " Name [" << bucket_name << "].";
    LOG(INFO) << " Lib file: [" << plugin_libfile << "].";
    LOG(INFO) << " Lib interface symbol name file: [" << plugin_symbol << "].";
    LOG(INFO) << " Config file: [" << plugin_config << "]";
    LOG(INFO) << "Done loading for bucket " << bucket_id;
  }

  // FIXME(baigang): use safe access
  LOG(INFO) << "Default bucket is: " << default_bucket;
  default_plugin_[index] = plugins_[index][default_bucket];
  LOG(INFO) << "Size of effective plugins is " << plugins_[index].size();

  // swap read/write buffer
  current_index_ = index;
  return true;
}

const boost::shared_ptr<IAlgoPlugin> AlgoPluginManager::Select(uint64_t id) {
  int index = current_index_;
  int mod = id % num_plugins_[index];
  boost::unordered_map<int, boost::shared_ptr<IAlgoPlugin> >::const_iterator iter = plugins_[index].find(mod);
  if (plugins_[index].end() == iter) {
    return default_plugin_[index];
  }
  return iter->second;
}

const boost::shared_ptr<IAlgoPlugin> AlgoPluginManager::Select(const std::string& id) {
  return Select(CityHash64(id.data(), id.length()));
}

}  // namespace recomm_engine


text:
/*ckwg +29
 * Copyright 2015 by Kitware, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 *  * Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 *  * Neither name of Kitware, Inc. nor the names of any 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 AUTHORS 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 <test_common.h>
#include <test_math.h>
#include <test_scene.h>

#include <maptk/projected_track_set.h>
#include <maptk/metrics.h>
#include <maptk/epipolar_geometry.h>
#include <maptk/plugins/vxl/estimate_fundamental_matrix.h>
#include <maptk/plugins/vxl/register_algorithms.h>

#include <Eigen/LU>

#define TEST_ARGS ()

DECLARE_TEST_MAP();

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

  kwiver::maptk::vxl::register_algorithms();

  testname_t const testname = argv[1];

  RUN_TEST(testname);
}

using namespace kwiver::vital;

IMPLEMENT_TEST(create)
{
  using namespace kwiver::maptk;
  algo::estimate_fundamental_matrix_sptr est_e = algo::estimate_fundamental_matrix::create("vxl");
  if (!est_e)
  {
    TEST_ERROR("Unable to create vxl::estimate_fundamental_matrix by name");
  }
}

// Print epipolar distance of pairs of points given a fundamental matrix
void print_epipolar_distances(const kwiver::vital::matrix_3x3d& F,
                              const std::vector<kwiver::vital::vector_2d> right_pts,
                              const std::vector<kwiver::vital::vector_2d> left_pts)
{
  using namespace kwiver::maptk;
  matrix_3x3d Ft = F.transpose();
  for(unsigned i=0; i<right_pts.size(); ++i)
  {
    const vector_2d& pr = right_pts[i];
    const vector_2d& pl = left_pts[i];
    vector_3d vr(pr.x(), pr.y(), 1.0);
    vector_3d vl(pl.x(), pl.y(), 1.0);
    vector_3d lr = F * vr;
    vector_3d ll = Ft * vl;
    double sr = 1.0 / sqrt(lr.x()*lr.x() + lr.y()*lr.y());
    double sl = 1.0 / sqrt(ll.x()*ll.x() + ll.y()*ll.y());
    // sum of point to epipolar line distance in both images
    double d = vr.dot(ll);
    std::cout <<" dist right = "<<d*sr<<"  dist left = "<<d*sl << std::endl;
  }
}

// test fundamental matrix estimation with ideal points
IMPLEMENT_TEST(ideal_points)
{
  using namespace kwiver::maptk;
  vxl::estimate_fundamental_matrix est_f;

  // create landmarks at the random locations
  landmark_map_sptr landmarks = testing::init_landmarks(100);
  landmarks = testing::noisy_landmarks(landmarks, 1.0);

  // create a camera sequence (elliptical path)
  camera_map_sptr cameras = testing::camera_seq();

  // create tracks from the projections
  track_set_sptr tracks = projected_tracks(landmarks, cameras);

  const frame_id_t frame1 = 0;
  const frame_id_t frame2 = 10;

  camera_map::map_camera_t cams = cameras->cameras();
  camera_sptr cam1 = cams[frame1];
  camera_sptr cam2 = cams[frame2];
  camera_intrinsics_sptr cal1 = cam1->intrinsics();
  camera_intrinsics_sptr cal2 = cam2->intrinsics();

  // compute the true fundamental matrix from the cameras
  fundamental_matrix_sptr true_F = fundamental_matrix_from_cameras(*cam1, *cam2);

  // extract coresponding image points
  std::vector<track_sptr> trks = tracks->tracks();
  std::vector<vector_2d> pts1, pts2;
  for(unsigned int i=0; i<trks.size(); ++i)
  {
    pts1.push_back(trks[i]->find(frame1)->feat->loc());
    pts2.push_back(trks[i]->find(frame2)->feat->loc());
  }

  // print the epipolar distances using this essential matrix
  print_epipolar_distances(true_F->matrix(), pts1, pts2);

  // compute the fundmental matrix from the corresponding points
  std::vector<bool> inliers;
  fundamental_matrix_sptr F_sptr = est_f.estimate(pts1, pts2,
                                                  inliers, 1.5);
  matrix_3x3d F = F_sptr->matrix();
  // check for sign difference
  if( true_F->matrix().cwiseProduct(F).sum() < 0.0 )
  {
    F *= -1;
  }

  // compare true and computed fundamental matrices
  std::cout << "true F = "<<*true_F<<std::endl;
  std::cout << "Estimated F = "<< F <<std::endl;
  TEST_NEAR("Fundamental Matrix Estimate", F, true_F->matrix(), 1e-8);

  unsigned num_inliers = static_cast<unsigned>(std::count(inliers.begin(),
                                                          inliers.end(), true));
  std::cout << "num inliers "<<num_inliers<<std::endl;
  TEST_EQUAL("All points are inliers", num_inliers, pts1.size());
}

// test essential matrix estimation with noisy points
IMPLEMENT_TEST(noisy_points)
{
  using namespace kwiver::maptk;
  vxl::estimate_fundamental_matrix est_f;

  // create landmarks at the random locations
  landmark_map_sptr landmarks = testing::init_landmarks(100);
  landmarks = testing::noisy_landmarks(landmarks, 1.0);

  // create a camera sequence (elliptical path)
  camera_map_sptr cameras = testing::camera_seq();

  // create tracks from the projections
  track_set_sptr tracks = projected_tracks(landmarks, cameras);

  // add random noise to track image locations
  tracks = testing::noisy_tracks(tracks, 0.5);

  const frame_id_t frame1 = 0;
  const frame_id_t frame2 = 10;

  camera_map::map_camera_t cams = cameras->cameras();
  camera_sptr cam1 = cams[frame1];
  camera_sptr cam2 = cams[frame2];
  camera_intrinsics_sptr cal1 = cam1->intrinsics();
  camera_intrinsics_sptr cal2 = cam2->intrinsics();

  // compute the true fundamental matrix from the cameras
  fundamental_matrix_sptr true_F = fundamental_matrix_from_cameras(*cam1, *cam2);

  // extract coresponding image points
  std::vector<track_sptr> trks = tracks->tracks();
  std::vector<vector_2d> pts1, pts2;
  for(unsigned int i=0; i<trks.size(); ++i)
  {
    pts1.push_back(trks[i]->find(frame1)->feat->loc());
    pts2.push_back(trks[i]->find(frame2)->feat->loc());
  }

  print_epipolar_distances(true_F->matrix(), pts1, pts2);

  // compute the essential matrix from the corresponding points
  std::vector<bool> inliers;
  fundamental_matrix_sptr F_sptr = est_f.estimate(pts1, pts2,
                                                inliers, 1.5);
  matrix_3x3d F = F_sptr->matrix();
  // check for sign difference
  if( true_F->matrix().cwiseProduct(F).sum() < 0.0 )
  {
    F *= -1;
  }

  // compare true and computed fundamental matrices
  std::cout << "true F = "<<*true_F<<std::endl;
  std::cout << "Estimated F = "<< F <<std::endl;
  TEST_NEAR("Fundamental Matrix Estimate", F, true_F->matrix(), 0.01);

  unsigned num_inliers = static_cast<unsigned>(std::count(inliers.begin(),
                                                          inliers.end(), true));
  std::cout << "num inliers "<<num_inliers<<std::endl;
  bool enough_inliers = num_inliers > pts1.size() / 3;
  TEST_EQUAL("Enough inliers", enough_inliers, true);
}

max_stars_repo_name: Purg/maptk

max_issues_repo_name: Purg/maptk

max_forks_repo_name: Purg/maptk


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

#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <fc/log/logger.hpp>
#include <fc/io/json.hpp>

size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
   ((std::string*)userp)->append((char*)contents, size * nmemb);
   return size * nmemb;
}

namespace graphene { namespace utilities {

bool checkES(ES& es)
{
   graphene::utilities::CurlRequest curl_request;
   curl_request.handler = es.curl;
   curl_request.url = es.elasticsearch_url + "_nodes";
   curl_request.auth = es.auth;
   curl_request.type = "GET";

   if(doCurl(curl_request).empty())
      return false;
   return true;

}
const std::string simpleQuery(ES& es)
{
   graphene::utilities::CurlRequest curl_request;
   curl_request.handler = es.curl;
   curl_request.url = es.elasticsearch_url + es.endpoint;
   curl_request.auth = es.auth;
   curl_request.type = "POST";
   curl_request.query = es.query;

   return doCurl(curl_request);
}

bool SendBulk(ES& es)
{
   std::string bulking = joinBulkLines(es.bulk_lines);

   graphene::utilities::CurlRequest curl_request;
   curl_request.handler = es.curl;
   curl_request.url = es.elasticsearch_url + "_bulk";
   curl_request.auth = es.auth;
   curl_request.type = "POST";
   curl_request.query = bulking;

   auto curlResponse = doCurl(curl_request);

   if(handleBulkResponse(getResponseCode(curl_request.handler), curlResponse))
      return true;
   return false;
}

const std::string joinBulkLines(const std::vector<std::string>& bulk)
{
   auto bulking = boost::algorithm::join(bulk, "\n");
   bulking = bulking + "\n";

   return bulking;
}
long getResponseCode(CURL *handler)
{
   long http_code = 0;
   curl_easy_getinfo (handler, CURLINFO_RESPONSE_CODE, &http_code);
   return http_code;
}

bool handleBulkResponse(long http_code, const std::string& CurlReadBuffer)
{
   if(http_code == 200) {
      // all good, but check errors in response
      fc::variant j = fc::json::from_string(CurlReadBuffer);
      bool errors = j["errors"].as_bool();
      if(errors == true) {
         return false;
      }
   }
   else {
      if(http_code == 413) {
         elog( "413 error: Can be low disk space" );
      }
      else if(http_code == 401) {
         elog( "401 error: Unauthorized" );
      }
      else {
         elog( std::to_string(http_code) + " error: Unknown error" );
      }
      return false;
   }
   return true;
}

const std::vector<std::string> createBulk(const fc::mutable_variant_object& bulk_header, const std::string& data)
{
   std::vector<std::string> bulk;
   fc::mutable_variant_object final_bulk_header;
   final_bulk_header["index"] = bulk_header;
   bulk.push_back(fc::json::to_string(final_bulk_header));
   bulk.push_back(data);

   return bulk;
}

bool deleteAll(ES& es)
{
   graphene::utilities::CurlRequest curl_request;
   curl_request.handler = es.curl;
   curl_request.url = es.elasticsearch_url + es.index_prefix + "*";
   curl_request.auth = es.auth;
   curl_request.type = "DELETE";

   auto curl_response =  doCurl(curl_request);
   if(curl_response.empty())
      return false;
   else
      return true;
}
const std::string getEndPoint(ES& es)
{
   graphene::utilities::CurlRequest curl_request;
   curl_request.handler = es.curl;
   curl_request.url = es.elasticsearch_url + es.endpoint;
   curl_request.auth = es.auth;
   curl_request.type = "GET";

   return doCurl(curl_request);
}

const std::string generateIndexName(const fc::time_point_sec& block_date, const std::string& _elasticsearch_index_prefix)
{
   auto block_date_string = block_date.to_iso_string();
   std::vector<std::string> parts;
   boost::split(parts, block_date_string, boost::is_any_of("-"));
   std::string index_name = _elasticsearch_index_prefix + parts[0] + "-" + parts[1];
   return index_name;
}

const std::string doCurl(CurlRequest& curl)
{
   std::string CurlReadBuffer;
   struct curl_slist *headers = NULL;
   headers = curl_slist_append(headers, "Content-Type: application/json");

   curl_easy_setopt(curl.handler, CURLOPT_HTTPHEADER, headers);
   curl_easy_setopt(curl.handler, CURLOPT_URL, curl.url.c_str());
   curl_easy_setopt(curl.handler, CURLOPT_CUSTOMREQUEST, curl.type.c_str());
   if(curl.type == "POST")
   {
      curl_easy_setopt(curl.handler, CURLOPT_POST, true);
      curl_easy_setopt(curl.handler, CURLOPT_POSTFIELDS, curl.query.c_str());
   }
   curl_easy_setopt(curl.handler, CURLOPT_WRITEFUNCTION, WriteCallback);
   curl_easy_setopt(curl.handler, CURLOPT_WRITEDATA, (void *)&CurlReadBuffer);
   curl_easy_setopt(curl.handler, CURLOPT_USERAGENT, "libcrp/0.1");
   if(!curl.auth.empty())
      curl_easy_setopt(curl.handler, CURLOPT_USERPWD, curl.auth.c_str());
   curl_easy_perform(curl.handler);

   return CurlReadBuffer;
}

} } // end namespace graphene::utilities


text:
#include <bunsan/pm/entry.hpp>

#include <bunsan/pm/error.hpp>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/assert.hpp>

namespace bunsan::pm {

bool entry::is_allowed_symbol(char c) {
  return ('0' <= c && c <= '9') || ('a' <= c && c <= 'z') ||
         ('A' <= c && c <= 'Z') || c == '_' || c == '-' || c == '.';
}

bool entry::is_allowed_subpath(const std::string &subpath) {
  return !subpath.empty() &&
         boost::algorithm::all(subpath, entry::is_allowed_symbol);
}

entry::entry(const std::string &name_, char delim) { build(name_, delim); }

entry::entry(const char *name_, char delim) { build(name_, delim); }

void entry::build(const std::string &name_, char delim) {
  m_location.clear();
  boost::algorithm::split(m_location, name_, [delim](char c) {
    return delim == c;
  }, boost::algorithm::token_compress_on);
  for (const std::string &i : m_location)
    if (!is_allowed_subpath(i))
      BOOST_THROW_EXCEPTION(invalid_entry_name_error()
                            << invalid_entry_name_error::entry_name(name_));
  BOOST_ASSERT(!empty());
}

entry &entry::operator=(entry &&e) noexcept {
  swap(e);
  return *this;
}

entry &entry::operator=(const entry &e) {
  entry ent(e);
  swap(ent);
  return *this;
}

entry &entry::operator=(const std::string &name_) {
  entry ent(name_);
  swap(ent);
  return *this;
}

bool entry::operator==(const entry &e) const {
  return m_location == e.m_location;
}

bool entry::operator<(const entry &e) const {
  return m_location < e.m_location;
}

bool entry::empty() const {
  return m_location.empty();
}

entry entry::operator/(const entry &e) const {
  entry ent(*this);
  ent.m_location.insert(ent.m_location.end(), e.m_location.begin(),
                        e.m_location.end());
  return ent;
}

entry entry::absolute(const entry &root) const {
  entry ent(*this);
  ent.make_absolute(root);
  return ent;
}

void entry::make_absolute(const entry &root) {
  if (empty()) return;
  if (m_location.front() == "." || m_location.front() == "..") {
    m_location.insert(m_location.begin(), root.m_location.begin(),
                      root.m_location.end());
  }
  std::vector<std::string> location;
  for (const std::string &e : m_location) {
    if (e == ".") {
      // nothing
    } else if (e == "..") {
      if (!location.empty()) location.pop_back();
    } else {
      location.push_back(e);
    }
  }
  m_location.swap(location);
}

boost::filesystem::path entry::location() const {
  boost::filesystem::path loc;
  for (const std::string &i : m_location) loc /= i;
  return loc;
}

const std::vector<std::string> &entry::decomposition() const {
  return m_location;
}

boost::property_tree::ptree::path_type entry::ptree_path() const {
  return boost::property_tree::ptree::path_type(name('/'), '/');
}

std::string entry::name(const std::string &delim) const {
  if (empty()) BOOST_THROW_EXCEPTION(empty_entry_error());
  return boost::algorithm::join(m_location, delim);
}

std::string entry::name(char delim) const {
  std::string d = {delim};
  return name(d);
}

void entry::swap(entry &e) noexcept { m_location.swap(e.m_location); }

std::string entry::remote_resource(const std::string &repository,
                                   const boost::filesystem::path &name_) const {
  std::string full = repository;
  if (!full.empty() && full.back() != '/') full.push_back('/');
  full += name('/');
  for (const boost::filesystem::path &i : name_) {
    full.push_back('/');
    full += i.string();
  }
  return full;
}

boost::filesystem::path entry::local_resource(
    const boost::filesystem::path &dir,
    const boost::filesystem::path &name_) const {
  return dir / location() / name_;
}

}  // namespace bunsan::pm

max_stars_repo_name: bacsorg/bacs

max_issues_repo_name: bacsorg/bacs

max_forks_repo_name: bacsorg/bacs