text:
/*!
 * Copyright (c) 2021 Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See LICENSE file in the project root for
 * license information.
 */
#include "TransformProcessor.h"

#include <ctype.h>
#include <math.h>

#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/lexical_cast.hpp>
#include <cctype>
#include <chrono>
#include <codecvt>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <vector>

#include "common.h"
#include "log.h"

using namespace std;
using namespace DynamicRank;

size_t UIntParseFast(string value) {
  size_t num = 0;
  for (int index = 0; index < value.length(); ++index) {
    num = (size_t)(10 * (int)num + ((int)value[index] - 48));
  }
  return num;
}

double TransformProcessor::ConvertStrToDouble(string val) {
  if (val.empty() || val == "0" || val == "") return 0;
  if (val.find("E") == string::npos) return std::stod(val);
  // case scientific notation.
  vector<string> str_array;
  boost::split(str_array, val, boost::is_any_of("E"), boost::token_compress_on);
  double num1 = std::stod(str_array[0]);
  double num2 = pow(10.0, std::stod((str_array[1])));
  return num1 * num2;
}

bool TransformProcessor::CloseToZero(double val) {
  // Set an EPS to deal with the situation of "-0.00000" and make the result
  // consistent with the previous version.
  if ((val < EPS && val > -EPS) || (val < 0.001 && val > 0.0)) return true;
  return false;
}

vector<FeatureEvaluatorExtendedInfo> GetEvaluators(
    IniFileParserInterface *input_ini_interface,
    std::map<string, int> column_index_mapping) {
  vector<FeatureEvaluatorExtendedInfo> evaluator_extended_info_list;
  for (int i = 0; i < input_ini_interface->GetInputCount(); i++) {
    FeatureEvaluator *evaluator = new FeatureEvaluator(input_ini_interface, i);
    if (evaluator->IsRawFeatureEvaluator()) {
      int num = -1;
      string transform_str = "linear.";
      string key =
          input_ini_interface->GetInputName(i).substr(transform_str.length());
      if (column_index_mapping.find(key) != column_index_mapping.end()) {
        num = column_index_mapping.find(key)->second;
      } else {
        Log::Warning(
            "Feature cannot be found!\n\tFeature: %s\n\tInput expression: %s",
            key.c_str(), input_ini_interface->GetInputName(i).c_str());
      }

      FeatureEvaluatorExtendedInfo evaluator_extended_info;
      evaluator_extended_info.feature_evaluator_ = evaluator;
      evaluator_extended_info.featuremap_ = NULL;
      evaluator_extended_info.required_feature_mapped_indexes_ = vector<int>();
      evaluator_extended_info.index_ = num;
      evaluator_extended_info.israw_ = true;
      evaluator_extended_info_list.push_back(evaluator_extended_info);
    } else {
      string transform_str = "freeform2.";
      string key =
          input_ini_interface->GetInputName(i).substr(transform_str.length());
      IniFileParserInterface *from_freeform2 =
          IniFileParserInterface::Createfromfreeform2(key);
      FeatureEvaluator *evaluator = new FeatureEvaluator(from_freeform2, 0);
      FeatureMap *featuremap = new FeatureMap(from_freeform2);
      vector<int> intList;
      for (int i = 0; i < evaluator->GetRequiredRawFeatureIndices().size();
           i++) {
        int requiredRawFeatureIndex =
            evaluator->GetRequiredRawFeatureIndices()[i];
        int num = -1;
        string rawFeatureName =
            featuremap->GetRawFeatureName(requiredRawFeatureIndex);
        if (column_index_mapping.find(rawFeatureName) !=
            column_index_mapping.end()) {
          num = column_index_mapping.find(rawFeatureName)->second;
        } else {
          Log::Warning(
              "Feature cannot be found!\n\tFeature: %s\n\tInput expression: %s",
              rawFeatureName.c_str(), key.c_str());
        }
        intList.push_back(num);
      }
      FeatureEvaluatorExtendedInfo evaluator_extended_info;
      evaluator_extended_info.feature_evaluator_ = evaluator;
      evaluator_extended_info.featuremap_ = featuremap;
      evaluator_extended_info.required_feature_mapped_indexes_ = intList;
      evaluator_extended_info.index_ = -1;
      evaluator_extended_info.israw_ = false;
      evaluator_extended_info_list.push_back(evaluator_extended_info);
    }
  }
  return evaluator_extended_info_list;
}

TransformProcessor::TransformProcessor(const std::string &transform_str,
                                       const std::string &header_str,
                                       int label_id) {
  auto t0 = std::chrono::high_resolution_clock::now();
  this->_label_id = label_id;
  if (label_id < 0) {
    Log::Warning("Label id %d, found no label.", label_id);
  }
  this->_from_input_str =
      IniFileParserInterface::CreateFromInputStr(transform_str);
  // column Index mapping
  header_str = Common::Trim(header_str);
  string token;
  size_t pos = 0;
  size_t index = 0;
  string delimiter = "\t";
  while ((pos = header_str.find(delimiter)) != string::npos) {
    token = header_str.substr(0, pos);
    this->_column_index_mapping.insert(
        std::pair<string, int>(header_str.substr(0, pos), index));
    index++;
    header_str.erase(0, pos + delimiter.length());
  }
  this->_column_index_mapping.insert(std::pair<string, int>(header_str, index));
  this->_feature_evaluator_list =
      GetEvaluators(this->_from_input_str, this->_column_index_mapping);
  // time
  auto t1 = std::chrono::high_resolution_clock::now();
  Log::Info("Initialize transform time: %.2f seconds",
            std::chrono::duration<double, std::milli>(t1 - t0) * 1e-3);
}

void TransformProcessor::Parse(const char *str,
                               vector<string> *out_feature_strs,
                               double *out_label, string delimiter) {
  string data_line = str;
  data_line = Common::Trim(data_line);
  boost::split(*out_feature_strs, data_line, boost::is_any_of(delimiter));
  if (this->_label_id >= 0 and this->_label_id < out_feature_strs->size()) {
    *out_label = ConvertStrToDouble((*out_feature_strs)[this->_label_id]);
  }
}

void TransformProcessor::Apply(vector<string> *input_row,
                               vector<pair<int, double> > *out_features) {
  int num1 = 0;
  out_features->clear();
  for (vector<FeatureEvaluatorExtendedInfo>::iterator feature_evaluator =
           this->_feature_evaluator_list.begin();
       feature_evaluator != this->_feature_evaluator_list.end();
       feature_evaluator++) {
    double result = 0;
    if (feature_evaluator->israw_) {
      if (feature_evaluator->index_ > -1 &&
          feature_evaluator->index_ < input_row->size()) {
        result = ConvertStrToDouble((*input_row)[feature_evaluator->index_]);
      }
    } else {
      size_t inputsize =
          feature_evaluator->required_feature_mapped_indexes_.size();
      uint32_t *input = new uint32_t[inputsize];
      int index = 0;
      string str2 = "";
      for (int i = 0;
           i < feature_evaluator->required_feature_mapped_indexes_.size();
           i++) {
        input[index] = 0u;
        int feature_mapped_index =
            feature_evaluator->required_feature_mapped_indexes_[i];
        if (feature_mapped_index != -1 &&
            feature_mapped_index < input_row->size()) {
          str2 = (*input_row)[feature_mapped_index];
          if (str2.empty()) {
            input[index] = 0;
          }
          if (!str2.empty()) {
            input[index] = UIntParseFast(str2);
          }
        }
        ++index;
      }

      result = feature_evaluator->feature_evaluator_->Evaluate(&input[0]);
      delete[] input;

      if (std::isinf(result) && result < 0) {
        result = -3.40282346638529E+38;
      } else if (std::isinf(result) && result > 0) {
        result = 3.40282346638529E+38;
      } else if (std::isnan(result)) {
        result = 0.0;
      }
    }
    if (!CloseToZero(result)) {
      out_features->push_back(std::make_pair(num1, result));
    }
    num1++;
  }
}

int TransformProcessor::GetFeatureCount() {
  return this->_feature_evaluator_list.size();
}

vector<TransformedData> TransformProcessor::ApplyForFile(string data_path) {
  ifstream data_fin(data_path.c_str());
  string data_line;
  vector<TransformedData> dataset;
  while (std::getline(data_fin, data_line)) {
    double label;
    vector<string> input_row;
    vector<pair<int, double> > sparse_features;
    this->Parse(data_line.c_str(), &input_row, &label);
    this->Apply(&input_row, &sparse_features);
    dataset.push_back(TransformedData(label, sparse_features));
  }
  return dataset;
}

// Default: precision=5
string TransformedData::ToString(int precision) {
  string output_str = "";
  output_str += to_string((int)this->Label()) + " ";
  for (auto f : this->Features()) {
    std::stringstream ss;
    ss << f.first << ":" << setiosflags(ios::fixed)
       << std::setprecision(precision) << f.second << " ";
    output_str += ss.str();
  }
  return output_str;
}

// Default: precision=5
vector<string> TransformedData::ToString(vector<TransformedData> dataset,
                                         int precision) {
  vector<string> output_vector;
  for (auto d : dataset) output_vector.push_back(d.ToString(precision));
  return output_vector;
}

const double TransformProcessor::EPS = 1E-9;

max_stars_repo_name: ltxtech/lightgbm-transform

max_issues_repo_name: ltxtech/lightgbm-transform

max_forks_repo_name: ltxtech/lightgbm-transform


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

#include <hpx/state.hpp>
#include <hpx/lcos/barrier.hpp>
#include <hpx/lcos/detail/barrier_node.hpp>
#include <hpx/lcos/when_all.hpp>
#include <hpx/runtime.hpp>
#include <hpx/runtime/basename_registration.hpp>
#include <hpx/runtime/components/server/component_heap.hpp>
#include <hpx/runtime/launch_policy.hpp>
#include <hpx/util/assert.hpp>
#include <hpx/util/runtime_configuration.hpp>
#include <hpx/util/unused.hpp>

#include <boost/intrusive_ptr.hpp>

#include <cstddef>
#include <string>
#include <utility>

///////////////////////////////////////////////////////////////////////////////
namespace hpx
{
    bool is_stopped_or_shutting_down();
}

namespace hpx { namespace lcos {
    barrier::barrier(std::string const& base_name)
      : node_(new (hpx::components::component_heap<wrapping_type>().alloc())
            wrapping_type(new wrapped_type(base_name,
                hpx::get_num_localities(hpx::launch::sync),
                hpx::get_locality_id())))
    {
        if ((*node_)->num_ >= (*node_)->cut_off_ || (*node_)->rank_ == 0)
            register_with_basename(
                base_name, node_->get_unmanaged_id(), (*node_)->rank_).get();
    }

    barrier::barrier(std::string const& base_name, std::size_t num)
      : node_(new (hpx::components::component_heap<wrapping_type>().alloc())
            wrapping_type(new wrapped_type(base_name, num, hpx::get_locality_id()
        )))
    {
        if ((*node_)->num_ >= (*node_)->cut_off_ || (*node_)->rank_ == 0)
            register_with_basename(
                base_name, node_->get_unmanaged_id(), (*node_)->rank_).get();
    }

    barrier::barrier(std::string const& base_name, std::size_t num, std::size_t rank)
      : node_(new (hpx::components::component_heap<wrapping_type>().alloc())
            wrapping_type(new wrapped_type(base_name, num, rank)))
    {
        if ((*node_)->num_ >= (*node_)->cut_off_ || (*node_)->rank_ == 0)
            register_with_basename(
                base_name, node_->get_unmanaged_id(), (*node_)->rank_).get();
    }

    barrier::barrier()
    {}

    barrier::barrier(barrier&& other)
      : node_(std::move(other.node_))
    {
        other.node_.reset();
    }

    barrier& barrier::operator=(barrier&& other)
    {
        release();
        node_ = std::move(other.node_);
        other.node_.reset();

        return *this;
    }

    barrier::~barrier()
    {
        release();
    }

    void barrier::wait()
    {
        (*node_)->wait(false).get();
    }

    future<void> barrier::wait(hpx::launch::async_policy)
    {
        return (*node_)->wait(true);
    }

    void barrier::release()
    {
        if (node_)
        {
            if (hpx::get_runtime_ptr() != nullptr &&
                hpx::threads::threadmanager_is(state_running) &&
                !hpx::is_stopped_or_shutting_down())
            {
                hpx::future<void> f;
                if ((*node_)->num_ >= (*node_)->cut_off_ || (*node_)->rank_ == 0)
                    f = hpx::unregister_with_basename(
                        (*node_)->base_name_, (*node_)->rank_);

                // we need to wait on everyone to have its name unregistered,
                // and hold on to our node long enough...
                boost::intrusive_ptr<wrapping_type> node = node_;
                hpx::when_all(f, wait(hpx::launch::async)).then(
                    hpx::launch::sync,
                    [node](hpx::future<void> f)
                    {
                        HPX_UNUSED(node);
                        f.get();
                    }
                ).get();
            }
            node_.reset();
        }
    }

    void barrier::detach()
    {
        if (node_)
        {
            if (hpx::get_runtime_ptr() != nullptr &&
                hpx::threads::threadmanager_is(state_running) &&
                !hpx::is_stopped_or_shutting_down())
            {
                if ((*node_)->num_ >= (*node_)->cut_off_ || (*node_)->rank_ == 0)
                    hpx::unregister_with_basename(
                        (*node_)->base_name_, (*node_)->rank_);
            }
            node_.reset();
        }
    }

    barrier barrier::create_global_barrier()
    {
        runtime& rt = get_runtime();
        util::runtime_configuration const& cfg = rt.get_config();
        return barrier("/0/hpx/global_barrier", cfg.get_num_localities());
    }

    barrier& barrier::get_global_barrier()
    {
        static barrier b;
        return b;
    }

    void barrier::synchronize()
    {
        static barrier& b = get_global_barrier();
        HPX_ASSERT(b.node_);
        b.wait();
    }
}}

ext: cpp

max_stars_repo_name: ShmuelLevine/hpx

max_issues_repo_name: Jakub-Golinowski/hpx

max_forks_repo_name: Jakub-Golinowski/hpx


text:
#include <boost/test/unit_test.hpp>
#include <boost/uuid/uuid.hpp>
#include <model/OrdersManager.hpp>
#include <model/Phone.hpp>
#include "Order.hpp"
#include "Client.hpp"

BOOST_AUTO_TEST_SUITE(TestSuiteOrdersManagerCorrect)

    BOOST_AUTO_TEST_CASE(ItemsManagerNewRemoveGetCase) {
        OrdersManager ordersManager;
        ItemSPtr phone = std::make_shared<Phone>(200, "Huawei", 2, 2048, 3200, true);
        ClientSPtr client = std::make_shared<Client>("Jan", "Kowalski", "Woronicza", "22A", "Woronicza", "22A");

        OrderSPtr order = std::make_shared<Order>(client, phone);
        ordersManager.newOrder(order);
        BOOST_REQUIRE_EQUAL(ordersManager.getArchiveOrders().size(), 0);
        BOOST_REQUIRE_EQUAL(ordersManager.getCurrentOrders().size(), 1);

        ordersManager.finishOrder(order);

        BOOST_REQUIRE_EQUAL(ordersManager.getArchiveOrders().size(), 1);
        BOOST_REQUIRE_EQUAL(ordersManager.getCurrentOrders().size(), 0);
    }

    BOOST_AUTO_TEST_CASE(ItemsManagerGetByIdCase) {
        OrdersManager ordersManager;
        ItemSPtr phone = std::make_shared<Phone>(200, "Huawei", 2, 2048, 3200, true);
        ClientSPtr client = std::make_shared<Client>("Jan", "Kowalski", "Woronicza", "22A", "Woronicza", "22A");

        OrderSPtr order = std::make_shared<Order>(client, phone);
        ordersManager.newOrder(order);

        BOOST_REQUIRE(
                ordersManager.findByID(order->getId())->getClient().operator*() == order->getClient().operator*());

    }

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: aantczakpiotr/OOP-final-project

max_issues_repo_name: aantczakpiotr/OOP-final-project

max_forks_repo_name: aantczakpiotr/OOP-final-project


text:
/*=============================================================================
    Copyright (c) 2002-2015 Joel de Guzman

    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)
=============================================================================*/
///////////////////////////////////////////////////////////////////////////////
//
//  A parser for arbitrary tuples. This example presents a parser
//  for an employee structure.
//
//  [ JDG May 9, 2007 ]
//  [ JDG May 13, 2015 ]    spirit X3
//
///////////////////////////////////////////////////////////////////////////////

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>

#include <iostream>
#include <string>

namespace client { namespace ast
{
    ///////////////////////////////////////////////////////////////////////////
    //  Our employee struct
    ///////////////////////////////////////////////////////////////////////////
    struct employee
    {
        int age;
        std::string forename;
        std::string surname;
        double salary;
    };

    using boost::fusion::operator<<;
}}

// We need to tell fusion about our employee struct
// to make it a first-class fusion citizen. This has to
// be in global scope.

BOOST_FUSION_ADAPT_STRUCT(client::ast::employee,
    age, forename, surname, salary
)

namespace client
{
    ///////////////////////////////////////////////////////////////////////////////
    //  Our employee parser
    ///////////////////////////////////////////////////////////////////////////////
    namespace parser
    {
        namespace x3 = boost::spirit::x3;
        namespace ascii = boost::spirit::x3::ascii;

        using x3::int_;
        using x3::lit;
        using x3::double_;
        using x3::lexeme;
        using ascii::char_;

        x3::rule<class employee, ast::employee> const employee = "employee";

        auto const quoted_string = lexeme['"' >> +(char_ - '"') >> '"'];

        auto const employee_def =
            lit("employee")
            >> '{'
            >>  int_ >> ','
            >>  quoted_string >> ','
            >>  quoted_string >> ','
            >>  double_
            >>  '}'
            ;

        BOOST_SPIRIT_DEFINE(employee);
    }
}

////////////////////////////////////////////////////////////////////////////
//  Main program
////////////////////////////////////////////////////////////////////////////
int
main()
{
    std::cout << "/////////////////////////////////////////////////////////\n\n";
    std::cout << "\t\tAn employee parser for Spirit...\n\n";
    std::cout << "/////////////////////////////////////////////////////////\n\n";

    std::cout
        << "Give me an employee of the form :"
        << "employee{age, \"forename\", \"surname\", salary } \n";
    std::cout << "Type [q or Q] to quit\n\n";

    using boost::spirit::x3::ascii::space;
    typedef std::string::const_iterator iterator_type;
    using client::parser::employee;

    std::string str;
    while (getline(std::cin, str))
    {
        if (str.empty() || str[0] == 'q' || str[0] == 'Q')
            break;

        client::ast::employee emp;
        iterator_type iter = str.begin();
        iterator_type const end = str.end();
        bool r = phrase_parse(iter, end, employee, space, emp);

        if (r && iter == end)
        {
            std::cout << boost::fusion::tuple_open('[');
            std::cout << boost::fusion::tuple_close(']');
            std::cout << boost::fusion::tuple_delimiter(", ");

            std::cout << "-------------------------\n";
            std::cout << "Parsing succeeded\n";
            std::cout << "got: " << emp << std::endl;
            std::cout << "\n-------------------------\n";
        }
        else
        {
            std::cout << "-------------------------\n";
            std::cout << "Parsing failed\n";
            std::cout << "-------------------------\n";
        }
    }

    std::cout << "Bye... :-) \n\n";
    return 0;
}

max_issues_repo_name: avplayer/cxxrpc

max_forks_repo_name: avplayer/cxxrpc


text:
#include <sstream>
#include <boost/assert.hpp>
#include "picpac-util.h"

namespace picpac {

    bool is_url (std::string const &url) {
        if (url.compare(0, 7, "http://") == 0) return true;
        if (url.compare(0, 8, "https://") == 0) return true;
        if (url.compare(0, 6, "ftp://") == 0) return true;
        return false;
    }

    string CachedDownloader::DEFAULT_AGENT("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1");

    fs::path CachedDownloader::download (const std::string &url) {
        if (!is_url(url)) return fs::path(url);
        fs::path path = cache_path(url);
        if (fs::exists(path)) {
            return path;
        }
        std::ostringstream ss;
        ss << "wget --output-document=" << path.native() << " --quiet -nv --no-check-certificate";
        if (retry > 0) {
            ss << " --tries=" << retry;
        }
        if (timeout > 0) {
            ss << " --timeout=" << timeout;
        }
        if (agent.size()) {
            ss << " --user-agent=\"" << agent << "\"";
        }
        ss << ' ' << '"' << url << '"';
        string cmd = ss.str();
        LOG(INFO) << cmd;
        int r = ::system(cmd.c_str());
        CHECK(r == 0);
        return path;
    }

    namespace from_boost_uuid_detail {

    BOOST_STATIC_ASSERT(sizeof(unsigned char)*8 == 8);
    BOOST_STATIC_ASSERT(sizeof(unsigned int)*8 == 32);

    inline unsigned int left_rotate(unsigned int x, std::size_t n)
    {
        return (x<<n) ^ (x>> (32-n));
    }

    class sha1
    {
    public:
        typedef unsigned int(&digest_type)[5];
    public:
        sha1();

        void reset();

        void process_byte(unsigned char byte);
        void process_block(void const* bytes_begin, void const* bytes_end);
        void process_bytes(void const* buffer, std::size_t byte_count);

        void get_digest(digest_type digest);

    private:
        void process_block();
        void process_byte_impl(unsigned char byte);

    private:
        unsigned int h_[5];

        unsigned char block_[64];

        std::size_t block_byte_index_;
        std::size_t bit_count_low;
        std::size_t bit_count_high;
    };

    inline sha1::sha1()
    {
        reset();
    }

    inline void sha1::reset()
    {
        h_[0] = 0x67452301;
        h_[1] = 0xEFCDAB89;
        h_[2] = 0x98BADCFE;
        h_[3] = 0x10325476;
        h_[4] = 0xC3D2E1F0;

        block_byte_index_ = 0;
        bit_count_low = 0;
        bit_count_high = 0;
    }

    inline void sha1::process_byte(unsigned char byte)
    {
        process_byte_impl(byte);

        if (bit_count_low < 0xFFFFFFF8) {
            bit_count_low += 8;
        } else {
            bit_count_low = 0;

            if (bit_count_high <= 0xFFFFFFFE) {
                ++bit_count_high;
            } else {
                BOOST_THROW_EXCEPTION(std::runtime_error("sha1 too many bytes"));
            }
        }
    }

    inline void sha1::process_byte_impl(unsigned char byte)
    {
        block_[block_byte_index_++] = byte;

        if (block_byte_index_ == 64) {
            block_byte_index_ = 0;
            process_block();
        }
    }

    inline void sha1::process_block(void const* bytes_begin, void const* bytes_end)
    {
        unsigned char const* begin = static_cast<unsigned char const*>(bytes_begin);
        unsigned char const* end = static_cast<unsigned char const*>(bytes_end);
        for(; begin != end; ++begin) {
            process_byte(*begin);
        }
    }

    inline void sha1::process_bytes(void const* buffer, std::size_t byte_count)
    {
        unsigned char const* b = static_cast<unsigned char const*>(buffer);
        process_block(b, b+byte_count);
    }

    inline void sha1::process_block()
    {
        unsigned int w[80];
        for (std::size_t i=0; i<16; ++i) {
            w[i]  = (block_[i*4 + 0] << 24);
            w[i] |= (block_[i*4 + 1] << 16);
            w[i] |= (block_[i*4 + 2] << 8);
            w[i] |= (block_[i*4 + 3]);
        }
        for (std::size_t i=16; i<80; ++i) {
            w[i] = left_rotate((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1);
        }

        unsigned int a = h_[0];
        unsigned int b = h_[1];
        unsigned int c = h_[2];
        unsigned int d = h_[3];
        unsigned int e = h_[4];

        for (std::size_t i=0; i<80; ++i) {
            unsigned int f;
            unsigned int k;

            if (i<20) {
                f = (b & c) | (~b & d);
                k = 0x5A827999;
            } else if (i<40) {
                f = b ^ c ^ d;
                k = 0x6ED9EBA1;
            } else if (i<60) {
                f = (b & c) | (b & d) | (c & d);
                k = 0x8F1BBCDC;
            } else {
                f = b ^ c ^ d;
                k = 0xCA62C1D6;
            }

            unsigned temp = left_rotate(a, 5) + f + e + k + w[i];
            e = d;
            d = c;
            c = left_rotate(b, 30);
            b = a;
            a = temp;
        }

        h_[0] += a;
        h_[1] += b;
        h_[2] += c;
        h_[3] += d;
        h_[4] += e;
    }

    inline void sha1::get_digest(digest_type digest)
    {
        // append the bit '1' to the message
        process_byte_impl(0x80);

        // append k bits '0', where k is the minimum number >= 0
        // such that the resulting message length is congruent to 56 (mod 64)
        // check if there is enough space for padding and bit_count
        if (block_byte_index_ > 56) {
            // finish this block
            while (block_byte_index_ != 0) {
                process_byte_impl(0);
            }

            // one more block
            while (block_byte_index_ < 56) {
                process_byte_impl(0);
            }
        } else {
            while (block_byte_index_ < 56) {
                process_byte_impl(0);
            }
        }

        // append length of message (before pre-processing)
        // as a 64-bit big-endian integer
        process_byte_impl( static_cast<unsigned char>((bit_count_high>>24) & 0xFF) );
        process_byte_impl( static_cast<unsigned char>((bit_count_high>>16) & 0xFF) );
        process_byte_impl( static_cast<unsigned char>((bit_count_high>>8 ) & 0xFF) );
        process_byte_impl( static_cast<unsigned char>((bit_count_high)     & 0xFF) );
        process_byte_impl( static_cast<unsigned char>((bit_count_low>>24) & 0xFF) );
        process_byte_impl( static_cast<unsigned char>((bit_count_low>>16) & 0xFF) );
        process_byte_impl( static_cast<unsigned char>((bit_count_low>>8 ) & 0xFF) );
        process_byte_impl( static_cast<unsigned char>((bit_count_low)     & 0xFF) );

        // get final digest
        digest[0] = h_[0];
        digest[1] = h_[1];
        digest[2] = h_[2];
        digest[3] = h_[3];
        digest[4] = h_[4];
    }
    }

    void sha1sum (char const *data, unsigned length, std::string *checksum) {
        uint32_t digest[5];
        from_boost_uuid_detail::sha1 sha1;
        sha1.process_block(data, data+length);
        sha1.get_digest(digest);
        static char const digits[] = "0123456789abcdef";
        checksum->clear();
        for(uint32_t c: digest) {
            checksum->push_back(digits[(c >> 28) & 0xF]);
            checksum->push_back(digits[(c >> 24) & 0xF]);
            checksum->push_back(digits[(c >> 20) & 0xF]);
            checksum->push_back(digits[(c >> 16) & 0xF]);
            checksum->push_back(digits[(c >> 12) & 0xF]);
            checksum->push_back(digits[(c >> 8) & 0xF]);
            checksum->push_back(digits[(c >> 4) & 0xF]);
            checksum->push_back(digits[c & 0xF]);
        }
    }
}


text:
#include <boost/test/unit_test.hpp>
#include <vector>
#include <numeric>
#include <limits>
#include <list>
#include <set>
#include <map>
#include <stack>
#include <math.h>
#include <stdio.h>

using namespace std;

struct StudentScore
{
	int ID;
	int Score;
	int Date;
};
typedef list<int> Scores;

class ScoreBoard
{
public:
	typedef map<int, Scores> Board;

	struct InDescendingOrder
	{
		bool operator()( int x, int y )
		{
			return x > y;
		}
	};

	void Process( StudentScore* scores, int scoreCount )
	{
		// make a map with id and scores as list
		Board board;
		for( int i=0; i<scoreCount; ++i )
		{
			const StudentScore& s( scores[i] );
			board[ s.ID ].push_back( s.Score );
		}

		// iterate each item in the map and sort and take first 5 and make average
		Board::iterator B;
		for( B = board.begin(); B!= board.end(); ++B )
		{
			Scores& scores(B->second);
			scores.sort( InDescendingOrder() );

			int count = 0;
			int sum = 0;
			for( Scores::iterator S=scores.begin(); S!=scores.end() && count<5; ++S, ++count)
			{
				sum += *S;
			}

			double average = (double)sum / count;
		}
	}
};

BOOST_AUTO_TEST_CASE( TestQuiz3 )
{
	StudentScore scores[] = {
		{ 0, 89, 112233 },
		{ 0, 90, 112233 },
		{ 0, 91, 112233 },
		{ 0, 89, 112233 },
		{ 0, 99, 112233 },
		{ 0, 89, 112233 } };

	ScoreBoard board;
	board.Process( scores, 6 );

}

max_stars_repo_name: SungwooNam/ProgrammingStudy

max_issues_repo_name: SungwooNam/ProgrammingStudy

max_forks_repo_name: SungwooNam/ProgrammingStudy


text:
// File: lb_utils.cpp
// Author: Francesco Giacomini <Francesco.Giacomini@cnaf.infn.it>
// Author: Salvatore Monforte <Salvatore.Monforte@ct.infn.it>

// Copyright (c) Members of the EGEE Collaboration. 2009.
// See http://www.eu-egee.org/partners/ for details on the copyright holders.

// 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 "lb_utils.h"
#include <sys/types.h>
#include <unistd.h>
#include <map>
#include <boost/tuple/tuple.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include "glite/jobid/JobId.h"
#include "common/src/utilities/manipulation.h"
#include "glite/wms/common/utilities/scope_guard.h"
#include "glite/lb/producer.h"
#include "glite/security/proxyrenewal/renewal.h"
#include "glite/wms/common/configuration/Configuration.h"
#include "common/src/configuration/NSConfiguration.h"
#include "common/src/configuration/CommonConfiguration.h"
#include <ctime>

namespace jobid = glite::jobid;

namespace configuration = glite::wms::common::configuration;
namespace utilities = glite::wms::common::utilities;

namespace glite {
namespace wms {
namespace purger {

ContextPtr
create_context(
  jobid::JobId const& id,
  std::string const& x509_proxy,
  std::string const& sequence_code
)
{
  edg_wll_Context context;
  int errcode = edg_wll_InitContext(&context);
  if (errcode) {
    return ContextPtr();
  }

  errcode |= edg_wll_SetParam(context,
                              EDG_WLL_PARAM_SOURCE,
                              EDG_WLL_SOURCE_NETWORK_SERVER);
  errcode |= edg_wll_SetParam(context, EDG_WLL_PARAM_INSTANCE, "NS");

  if(!x509_proxy.empty())
    errcode |= edg_wll_SetParam(context,
                                EDG_WLL_PARAM_X509_PROXY,
                                x509_proxy.c_str());

  const int flag = EDG_WLL_SEQ_NORMAL;
  // the following fails if the sequence code is not formally correct
  errcode |= edg_wll_SetLoggingJob(context, id.c_jobid(), sequence_code.c_str(), flag);

  if (errcode) {
    throw CannotCreateLBContext(errcode);
  }

  return ContextPtr(context, edg_wll_FreeContext);
}

namespace {

bool
proxy_expires_within(std::string const& x509_proxy, time_t seconds)
{
  ::FILE* fd = ::fopen(x509_proxy.c_str(), "r");
  if (!fd) return true; // invalid proxy

  boost::shared_ptr< ::FILE> fd_(fd, ::fclose);

  ::X509* const cert = ::PEM_read_X509(fd, 0, 0, 0);
  if (!cert) return true;

  boost::shared_ptr< ::X509> cert_(cert, ::X509_free);

  return (
    ASN1_UTCTIME_cmp_time_t(
      X509_get_notAfter(cert), std::time(0)+seconds
    ) < 0
  );
}

std::string
get_proxy_subject(std::string const& x509_proxy)
{
  static std::string const null_string;

  ::FILE* fd = ::fopen(x509_proxy.c_str(), "r");
  if (!fd) return null_string;
  boost::shared_ptr< ::FILE> fd_(fd, ::fclose);

  ::X509* const cert = ::PEM_read_X509(fd, 0, 0, 0);
  if (!cert) return null_string;
  boost::shared_ptr< ::X509> cert_(cert, ::X509_free);

  char* const s = ::X509_NAME_oneline(::X509_get_subject_name(cert), 0, 0);
  if (!s) return null_string;
  boost::shared_ptr<char> s_(s, ::free);

  return std::string(s);
}

}

ContextPtr
create_context_proxy(
  jobid::JobId const& id,
  std::string const& x509_proxy,
  std::string const& sequence_code
)
{
  edg_wll_Context context;
  int errcode = edg_wll_InitContext(&context);
  if (errcode) {
    return ContextPtr();
  }

  errcode |= edg_wll_SetParam(
    context,
    EDG_WLL_PARAM_SOURCE,
    EDG_WLL_SOURCE_NETWORK_SERVER
  );
  errcode |= edg_wll_SetParam(
    context,
    EDG_WLL_PARAM_INSTANCE,
    boost::lexical_cast<std::string>(::getpid()).c_str()
  );

  errcode |= edg_wll_SetParam(context,
                              EDG_WLL_PARAM_X509_PROXY,
                              x509_proxy.c_str());

  std::string const user_dn = get_proxy_subject(x509_proxy);
  int const flag = EDG_WLL_SEQ_NORMAL;
  errcode |= edg_wll_SetLoggingJobProxy(
    context,
    id.c_jobid(),
    sequence_code.empty() ? 0 : sequence_code.c_str(),
    user_dn.c_str(),
    flag
  );

  if (errcode) {
    throw CannotCreateLBContext(errcode);
  }

  return ContextPtr(context, edg_wll_FreeContext);
}

std::string
get_original_jdl(edg_wll_Context context, jobid::JobId const& id)
{
  std::string result;

  edg_wll_QueryRec job_conditions[2];
  job_conditions[0].attr    = EDG_WLL_QUERY_ATTR_JOBID;
  job_conditions[0].op      = EDG_WLL_QUERY_OP_EQUAL;
  job_conditions[0].value.j = glite_jobid_t(id.c_jobid());
  job_conditions[1].attr    = EDG_WLL_QUERY_ATTR_UNDEF;

  edg_wll_QueryRec event_conditions[3];
  event_conditions[0].attr    = EDG_WLL_QUERY_ATTR_EVENT_TYPE;
  event_conditions[0].op      = EDG_WLL_QUERY_OP_EQUAL;
  event_conditions[0].value.i = EDG_WLL_EVENT_ENQUEUED;
  event_conditions[1].attr    = EDG_WLL_QUERY_ATTR_SOURCE;
  event_conditions[1].op      = EDG_WLL_QUERY_OP_EQUAL;
  event_conditions[1].value.i = EDG_WLL_SOURCE_NETWORK_SERVER;
  event_conditions[2].attr    = EDG_WLL_QUERY_ATTR_UNDEF;

  edg_wll_Event* events = 0;
  edg_wll_QueryEvents(context, job_conditions, event_conditions, &events);

  if (events) {
    for (int i = 0; events[i].type; ++i) {
      // in principle there is only one, so save the first one and ignore the
      // others
      if (result.empty()
          && events[i].type == EDG_WLL_EVENT_ENQUEUED
          && events[i].enQueued.result == EDG_WLL_ENQUEUED_OK) {
        result = events[i].enQueued.job;
      }
      edg_wll_FreeEvent(&events[i]);
    }
    free(events);
  }

  return result;
}

namespace {

std::string get_lb_proxy_user(ContextPtr context)
{
  char *s = 0;
  utilities::scope_guard free_char(
    boost::bind(std::free, s)
  );
  edg_wll_GetParam(&(*context), EDG_WLL_PARAM_LBPROXY_USER, &s);
  return std::string(s);
}

boost::tuple<int,std::string,std::string>
get_error_info(edg_wll_Context context)
{
  int error;
  std::string error_txt;
  std::string description_txt;

  char* c_error_txt = 0;
  char* c_description_txt = 0;
  error = edg_wll_Error(context, &c_error_txt, &c_description_txt);

  if (c_error_txt) {
    error_txt = c_error_txt;
  }
  free(c_error_txt);
  if (c_description_txt) {
    description_txt = c_description_txt;
  }
  free(c_description_txt);

  return boost::make_tuple(error, error_txt, description_txt);
}

std::string
get_lb_sequence_code(ContextPtr context)
{
  char* c_sequence_code = edg_wll_GetSequenceCode(context.get());
  std::string sequence_code(c_sequence_code);
  free(c_sequence_code);
  return sequence_code;
}

} // anonymous

void change_logging_job(
  ContextPtr context,
  jobid::JobId const& id,
  bool have_lbproxy
)
{
  int const flag = EDG_WLL_SEQ_NORMAL;
  std::string const sequence_code = get_lb_sequence_code(context);

  if (have_lbproxy) {
    std::string const user_dn = get_lb_proxy_user(context);
    edg_wll_SetLoggingJobProxy(
      &(*context),
      id.c_jobid(),
      sequence_code.empty() ? 0 : sequence_code.c_str(),
      user_dn.c_str(),
      flag
    );
  } else {
    edg_wll_SetLoggingJob(
      &(*context),
      id.c_jobid(),
      sequence_code.empty() ? 0 : sequence_code.c_str(),
      flag
    );
  }
}

std::string
get_lb_message(ContextPtr const& context)
{
  return get_lb_message(context.get());
}

std::string
get_lb_message(edg_wll_Context context)
{
  std::string result;

  int error;
  std::string error_txt;
  std::string description_txt;
  boost::tie(error, error_txt, description_txt) = get_error_info(context);

  result += error_txt;
  result += " (";
  result += boost::lexical_cast<std::string>(error);
  result += ") - ";
  result += description_txt;

  return result;
}}}} // glite::wms::purger

max_stars_repo_name: italiangrid/wms

max_issues_repo_name: italiangrid/wms

max_forks_repo_name: italiangrid/wms


text:
/*=============================================================================
    Copyright (c) 2017 Paul Fultz II
    flip.cpp
    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#include <boost/hof/flip.hpp>
#include <boost/hof/placeholders.hpp>
#include "test.hpp"

BOOST_HOF_TEST_CASE()
{
    BOOST_HOF_TEST_CHECK(3 == boost::hof::flip(boost::hof::_ - boost::hof::_)(2, 5));
    BOOST_HOF_STATIC_TEST_CHECK(3 == boost::hof::flip(boost::hof::_ - boost::hof::_)(2, 5));
}

BOOST_HOF_TEST_CASE()
{
    typedef std::integral_constant<int, 1> one;
    typedef std::integral_constant<int, 2> two;
    typedef std::integral_constant<int, 3> three;
    BOOST_HOF_TEST_CHECK(1 == boost::hof::arg(one{})(1, 2, 3, 4));
    BOOST_HOF_STATIC_TEST_CHECK(1 == boost::hof::arg(one{})(1, 2, 3, 4));
    BOOST_HOF_TEST_CHECK(2 == boost::hof::flip(boost::hof::arg(one{}))(1, 2, 3, 4));
    BOOST_HOF_STATIC_TEST_CHECK(2 == boost::hof::flip(boost::hof::arg(one{}))(1, 2, 3, 4));

    BOOST_HOF_TEST_CHECK(2 == boost::hof::arg(two{})(1, 2, 3, 4));
    BOOST_HOF_STATIC_TEST_CHECK(2 == boost::hof::arg(two{})(1, 2, 3, 4));
    BOOST_HOF_TEST_CHECK(1 == boost::hof::flip(boost::hof::arg(two{}))(1, 2, 3, 4));
    BOOST_HOF_STATIC_TEST_CHECK(1 == boost::hof::flip(boost::hof::arg(two{}))(1, 2, 3, 4));

    BOOST_HOF_TEST_CHECK(3 == boost::hof::arg(three{})(1, 2, 3, 4));
    BOOST_HOF_STATIC_TEST_CHECK(3 == boost::hof::arg(three{})(1, 2, 3, 4));
    BOOST_HOF_TEST_CHECK(3 == boost::hof::flip(boost::hof::arg(three{}))(1, 2, 3, 4));
    BOOST_HOF_STATIC_TEST_CHECK(3 == boost::hof::flip(boost::hof::arg(three{}))(1, 2, 3, 4));
}

#if defined(__GNUC__) && !defined (__clang__) && __GNUC__ == 4 && __GNUC_MINOR__ < 7
#define FINAL
#else
#define FINAL final
#endif

struct f FINAL {
    int operator()(int i, void *) const {
        return i;
    }
};

#if BOOST_HOF_HAS_NOEXCEPT_DEDUCTION
BOOST_HOF_TEST_CASE()
{
    static_assert(boost::hof::flip(boost::hof::_ - boost::hof::_)(2, 5), "noexcept flip");
}
#endif

BOOST_HOF_TEST_CASE()
{
    BOOST_HOF_TEST_CHECK(boost::hof::flip(f())(nullptr, 2) == 2);
}


text:
#include "videosourcefactory.h"
#include "videotargetfactory.h"
#include "except.h"
#include "iobservable.h"
#include "gil.h"
#ifdef USE_OPENCV
#include "opencv_video_source.h"
#include "opencv_video_target.h"
#endif // USE_OPENCV
#ifdef USE_EPIPHANSDK
#include "epiphansdk_video_source.h"
#endif
#ifdef USE_LIBVLC
#include "vlc_video_source.h"
#endif
#ifdef USE_BLACKMAGICSDK
#include "blackmagicsdk_video_source.h"
#endif
#ifdef USE_FFMPEG
#include "ffmpeg_video_source.h"
#include "ffmpeg_video_target.h"
#endif
#include <boost/python.hpp>
#include <boost/python/exception_translator.hpp>
#ifdef USE_NUMPY
#include <boost/python/numpy.hpp>
#endif

using namespace boost::python;

class VideoFrameNumPyWrapper : public gg::VideoFrame, public wrapper<gg::VideoFrame>
{
protected:
    //!
    //! \brief Wrapped \c VideoFrame object
    //!
    gg::VideoFrame * _frame;

    //!
    //! \brief \c false indicates the wrapped
    //! \c VideoFrame object is managed externally,
    //! \c true indicates it was created and is
    //! managed by this class
    //! \sa _frame
    //!
    bool _manage_frame;

public:
    //!
    //! \brief Very thinly wrap passed \c frame
    //! \param frame it is the caller's responsibility
    //! to ensure the lifetime of the object pointed to
    //! by this pointer
    //!
    VideoFrameNumPyWrapper(gg::VideoFrame * frame)
        : _frame(frame)
        , _manage_frame(false)
    {
        _manage_data = false;
        sync_specs();
    }

    //!
    //! \brief Copy constructor needs to be defined
    //! here as well for compatibility with exposed
    //! interface
    //! \param rhs
    //!
    VideoFrameNumPyWrapper(const gg::VideoFrame & rhs)
        : _frame(new gg::VideoFrame(rhs))
        , _manage_frame(true)
    {
        _manage_data = false;
        sync_specs();
    }

    //!
    //! \brief This constructor needs to be defined
    //! here as well for compatibility with exposed
    //! interface
    //! \param colour
    //! \param cols
    //! \param rows
    //!
    VideoFrameNumPyWrapper(enum gg::ColourSpace colour,
                           size_t cols, size_t rows)
        : _frame(new gg::VideoFrame(colour, cols, rows))
        , _manage_frame(true)
    {
        _manage_data = false;
        sync_specs();
    }

    //!
    //! \brief This constructor needs to be defined
    //! here as well for compatibility with exposed
    //! interface
    //! \param colour
    //! \param cols
    //! \param rows
    //!
    VideoFrameNumPyWrapper(enum gg::ColourSpace colour,
                           size_t cols, size_t rows,
                           size_t stereo_count)
        : _frame(new gg::VideoFrame(colour, cols, rows,
                                    stereo_count))
        , _manage_frame(true)
    {
        _manage_data = false;
        sync_specs();
    }

    //!
    //! \brief This constructor needs to be defined
    //! here as well for compatibility with exposed
    //! interface
    //! \param colour
    //! \param manage_data
    //!
    VideoFrameNumPyWrapper(enum gg::ColourSpace colour,
                           bool manage_data)
        : _frame(new gg::VideoFrame(colour, manage_data))
        , _manage_frame(true)
    {
        _manage_data = false;
        sync_specs();
    }

    ~VideoFrameNumPyWrapper()
    {
        if (_manage_frame)
            delete _frame;
    }

    const size_t data_length_default_frame() const
    {
        return _frame->data_length();
    }

    const size_t data_length_stereo_frame(size_t stereo_index) const
    {
        return _frame->data_length(stereo_index);
    }

#ifdef USE_NUMPY
    //!
    //! \brief default arguments for both structured flag (i.e. false)
    //! and the stereo index (i.e. 0), see:
    //! http://www.boost.org/doc/libs/1_63_0/
    //! libs/python/doc/html/tutorial/tutorial/
    //! functions.html#tutorial.functions.default_arguments
    //! \return the first stereo frame's data as a flat NumPy array
    //! \sa stereo_data_as_ndarray()
    //!
    numpy::ndarray first_stereo_data_as_flat_ndarray() const
    {
        return stereo_data_as_ndarray(false, 0);
    }

    //!
    //! \brief default argument for stereo index (i.e. 0), see:
    //! http://www.boost.org/doc/libs/1_63_0/
    //! libs/python/doc/html/tutorial/tutorial/
    //! functions.html#tutorial.functions.default_arguments
    //! \param structured
    //! \return the first stereo frame's data as desired NumPy array
    //! \throw gg::BasicException if wrapped gg::VideoFrame has colour
    //! other than BGRA (currently only BGRA data supported for
    //! structured ndarray exposure)
    //! \sa stereo_data_as_ndarray()
    //!
    numpy::ndarray first_stereo_data_as_ndarray(bool structured) const
    {
        return stereo_data_as_ndarray(structured, 0);
    }

    //!
    //! \brief Create a NumPy array referencing gg::VideoFrame::data()
    //! \param structured
    //! \param stereo_index
    //! \return a flat NumPy array if not \c structured; otherwise one
    //! that conforms to the shape SciPy routines expect: (height,
    //! width, channels), e.g. (9, 16, 4) for BGRA data of a 16 x 9
    //! image
    //! \throw gg::BasicException if wrapped gg::VideoFrame has colour
    //! other than BGRA (currently only BGRA data supported for
    //! structured ndarray exposure)
    //! \throw std::out_of_range if stereo index invalid
    //!
    numpy::ndarray stereo_data_as_ndarray(
        bool structured, size_t stereo_index) const
    {
        tuple shape, strides;
        numpy::dtype data_type = numpy::dtype::get_builtin<uint8_t>();
        if (structured)
        {
            switch(colour())
            {
            case gg::BGRA:
                shape = make_tuple(_frame->rows(), _frame->cols(), 4);
                strides = make_tuple(_frame->cols() * 4 * sizeof(uint8_t),
                                     4 * sizeof(uint8_t),
                                     sizeof(uint8_t));
                break;
            // TODO: see issue #155
            case gg::I420:
            case gg::UYVY:
            default:
                throw gg::BasicException("Structured NumPy arrays"
                                         " supported only for BGRA");
                break;
            }
        }
        else
        {
            shape = make_tuple(_frame->data_length(stereo_index));
            strides = make_tuple(sizeof(uint8_t));
        }

        return numpy::from_data(
                    _frame->data(stereo_index), data_type, shape, strides,
                    // owner (dangerous to pass None)
                    object()
               );
    }
#endif

protected:
    void sync_specs()
    {
        _colour = _frame->colour();
        _cols = _frame->cols();
        _rows = _frame->rows();
        _data = _frame->data();
        _data_length = _frame->data_length();
	_stereo_count = _frame->stereo_count();
    }
};

class IObservableWrapper : public gg::IObservable, public wrapper<gg::IObservable>
{
public:
    void attach(gg::IObserver & observer)
    {
        if (override f = this->get_override("attach"))
            f(boost::ref(observer));
        else
            gg::IObservable::attach(boost::ref(observer));
    }

    void default_attach(gg::IObserver & observer)
    {
        gg::IObservable::attach(boost::ref(observer));
    }

    void detach(gg::IObserver & observer)
    {
        if (override f = this->get_override("detach"))
            f(boost::ref(observer));
        else
            gg::IObservable::detach(boost::ref(observer));
    }

    void default_detach(gg::IObserver & observer)
    {
        gg::IObservable::detach(boost::ref(observer));
    }
};

class IVideoSourceWrapper : public IVideoSource, public wrapper<IVideoSource>
{
public:
    bool get_frame_dimensions(int & width, int & height)
    {
        return this->get_override("get_frame_dimensions")(width, height);
    }

    bool get_frame(gg::VideoFrame & frame)
    {
        return this->get_override("get_frame")(frame);
    }

    double get_frame_rate()
    {
        return this->get_override("get_frame_rate")();
    }

    void set_sub_frame(int x, int y, int width, int height)
    {
        this->get_override("set_sub_frame")(x, y, width, height);
    }

    void get_full_frame()
    {
        this->get_override("get_full_frame")();
    }
};

/* The inheritance should be public, in order to preserve
 * the public accessibility of the update() method. The
 * Boost.Python examples feature struct's rather than
 * classes, and in struct's everything is public by
 * definition.
 */
class IObserverWrapper : public gg::IObserver, public wrapper<gg::IObserver>
{
public:
    IObserverWrapper()
    {
        /* Default constructor that needs to be called within
         * child Python class, e.g. super(Child, self).__init__()
         * This is normally generated by the compiler
         * automatically, but we define it here explicitly so
         * that it can serve as an example for this complex case.
         */
    }

    void update(gg::VideoFrame & frame)
    {
        gg::ScopedPythonGILLock gil_lock;
        VideoFrameNumPyWrapper wrapped_frame(&frame);
        if (override f = this->get_override("update"))
            f(boost::ref(wrapped_frame));
    }
};

class IVideoTargetWrapper : public gg::IVideoTarget, public wrapper<gg::IVideoTarget>
{
public:
    void append(const gg::VideoFrame & frame)
    {
        this->get_override("append")(frame);
    }
};

//!
//! \brief This class is a workaround to the method resolution
//! order problems encountered when implementing Python classes
//! inheriting from both IObservable and IObserver, i.e. a node
//! that receives, processes video data and finally passes this
//! processed data down along the pipeline.
//!
class IObservableObserverWrapper : public gg::IObservable
                                 , public gg::IObserver
                                 , public wrapper<gg::IObserver>
{
public:
    IObservableObserverWrapper()
    {
        // nop
    }

    ~IObservableObserverWrapper()
    {
        // nop
    }

public:
    void attach(gg::IObserver & observer)
    {
        if (override f = this->get_override("attach"))
            f(boost::ref(observer));
        else
            gg::IObservable::attach(boost::ref(observer));
    }

    void default_attach(gg::IObserver & observer)
    {
        gg::IObservable::attach(boost::ref(observer));
    }

    void detach(gg::IObserver & observer)
    {
        if (override f = this->get_override("detach"))
            f(boost::ref(observer));
        else
            gg::IObservable::detach(boost::ref(observer));
    }

    void default_detach(gg::IObserver & observer)
    {
        gg::IObservable::detach(boost::ref(observer));
    }

    void update(gg::VideoFrame & frame)
    {
        {
            gg::ScopedPythonGILLock gil_lock;
            if (override f = this->get_override("update"))
            {
                VideoFrameNumPyWrapper wrapped_frame(&frame);
                f(boost::ref(wrapped_frame));
            }
        }
        notify(frame);
    }
};

void translate_BasicException(gg::BasicException const & e)
{
    std::string msg;
    msg.append("BasicException: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

void translate_VideoSourceError(gg::VideoSourceError const & e)
{
    std::string msg;
    msg.append("VideoSourceError: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

void translate_DeviceAlreadyConnected(gg::DeviceAlreadyConnected const & e)
{
    std::string msg;
    msg.append("DeviceAlreadyConnected: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_DeviceNotFound(gg::DeviceNotFound const & e)
{
    std::string msg;
    msg.append("DeviceNotFound: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_DeviceOffline(gg::DeviceOffline const & e)
{
    std::string msg;
    msg.append("DeviceOffline: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_NetworkSourceUnavailable(gg::NetworkSourceUnavailable const & e)
{
    std::string msg;
    msg.append("NetworkSourceUnavailable: ").append(e.what());
    PyErr_SetString(PyExc_IOError, msg.c_str());
}

void translate_VideoTargetError(gg::VideoTargetError const & e)
{
    std::string msg;
    msg.append("VideoTargetError: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

void translate_ObserverError(gg::ObserverError const & e)
{
    std::string msg;
    msg.append("ObserverError: ").append(e.what());
    PyErr_SetString(PyExc_RuntimeError, msg.c_str());
}

void translate_out_of_range(std::out_of_range const &e)
{
    std::string msg;
    msg.append("std::out_of_range: ").append(e.what());
    PyErr_SetString(PyExc_IndexError, msg.c_str());
}

BOOST_PYTHON_MODULE(pygiftgrab)
{
    PyEval_InitThreads();
#ifdef USE_NUMPY
    boost::python::numpy::initialize();
#endif

    register_exception_translator<gg::BasicException>(&translate_BasicException);
    register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError);
    register_exception_translator<gg::DeviceAlreadyConnected>(&translate_DeviceAlreadyConnected);
    register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound);
    register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline);
    register_exception_translator<gg::NetworkSourceUnavailable>(&translate_NetworkSourceUnavailable);
    register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError);
    register_exception_translator<gg::ObserverError>(&translate_ObserverError);
    register_exception_translator<std::out_of_range>(&translate_out_of_range);

    enum_<gg::ColourSpace>("ColourSpace")
        .value("BGRA", gg::ColourSpace::BGRA)
        .value("I420", gg::ColourSpace::I420)
        .value("UYVY", gg::ColourSpace::UYVY)
    ;

    enum_<gg::Device>("Device")
        .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI)
        .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI)
        .value("DeckLinkSDI4K", gg::Device::DeckLinkSDI4K)
        .value("DeckLink4KExtreme12G", gg::Device::DeckLink4KExtreme12G)
    ;

    enum_<gg::Codec>("Codec")
        .value("HEVC", gg::Codec::HEVC)
        .value("Xvid", gg::Codec::Xvid)
        .value("VP9", gg::Codec::VP9)
    ;

    class_<VideoFrameNumPyWrapper>("VideoFrame", init<enum gg::ColourSpace, bool>())
        .def(init<enum gg::ColourSpace, const size_t, const size_t>())
        .def(init<enum gg::ColourSpace, const size_t, const size_t, const size_t>())
        .def("colour", &VideoFrameNumPyWrapper::colour)
        .def("rows", &VideoFrameNumPyWrapper::rows)
        .def("cols", &VideoFrameNumPyWrapper::cols)
        .def("data_length", &VideoFrameNumPyWrapper::data_length_default_frame)
        .def("data_length", &VideoFrameNumPyWrapper::data_length_stereo_frame)
        .def("stereo_count", &VideoFrameNumPyWrapper::stereo_count)
        .def("required_data_length", &VideoFrameNumPyWrapper::required_data_length)
        .staticmethod("required_data_length")
        .def("required_pixel_length", &VideoFrameNumPyWrapper::required_pixel_length)
        .staticmethod("required_pixel_length")
#ifdef USE_NUMPY
        .def("data", &VideoFrameNumPyWrapper::first_stereo_data_as_flat_ndarray)
        .def("data", &VideoFrameNumPyWrapper::first_stereo_data_as_ndarray)
        .def("data", &VideoFrameNumPyWrapper::stereo_data_as_ndarray)
#endif
    ;

    class_<IObservableWrapper, boost::noncopyable>("IObservable", no_init)
        .def("attach", &IObservableWrapper::attach)
        .def("detach", &IObservableWrapper::detach)
    ;

    class_<IVideoSource, bases<gg::IObservable>, boost::noncopyable>(
                "IVideoSource", no_init)
    ;

#ifdef USE_OPENCV
    class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceOpenCV", init<int>())
        .def(init<char *>())
        .def("get_frame", &VideoSourceOpenCV::get_frame)
        .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions)
        .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate)
        .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame)
        .def("get_full_frame", &VideoSourceOpenCV::get_full_frame)
        .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach)
        .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach)
    ;
#endif // USE_OPENCV

#ifdef USE_EPIPHANSDK
    class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>())
        .def("get_frame", &gg::VideoSourceEpiphanSDK::get_frame)
        .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions)
        .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate)
        .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame)
        .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame)
        .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach)
        .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach)
    ;
#endif

#ifdef USE_LIBVLC
    class_<gg::VideoSourceVLC, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceVLC", init<const std::string>())
        .def("get_frame", &gg::VideoSourceVLC::get_frame)
        .def("get_frame_dimensions", &gg::VideoSourceVLC::get_frame_dimensions)
        .def("get_frame_rate", &gg::VideoSourceVLC::get_frame_rate)
        .def("set_sub_frame", &gg::VideoSourceVLC::set_sub_frame)
        .def("get_full_frame", &gg::VideoSourceVLC::get_full_frame)
        .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach)
        .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach)
    ;
#endif

#ifdef USE_BLACKMAGICSDK
    class_<gg::VideoSourceBlackmagicSDK, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceBlackmagicSDK", init<size_t, gg::ColourSpace>())
        .def("get_frame", &gg::VideoSourceBlackmagicSDK::get_frame)
        .def("get_frame_dimensions", &gg::VideoSourceBlackmagicSDK::get_frame_dimensions)
        .def("get_frame_rate", &gg::VideoSourceBlackmagicSDK::get_frame_rate)
        .def("set_sub_frame", &gg::VideoSourceBlackmagicSDK::set_sub_frame)
        .def("get_full_frame", &gg::VideoSourceBlackmagicSDK::get_full_frame)
        .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach)
        .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach)
    ;
#endif

    class_<IObserverWrapper, boost::noncopyable>("IObserver")
        .def("update", pure_virtual(&gg::IObserver::update))
    ;

    class_<gg::IVideoTarget, bases<gg::IObserver>, boost::noncopyable>(
                "IVideoTarget", no_init)
        .def("update", &gg::IVideoTarget::update)
    ;

#ifdef USE_FFMPEG
    class_<gg::VideoSourceFFmpeg, bases<IVideoSource>, boost::noncopyable>(
                "VideoSourceFFmpeg", init<std::string, enum gg::ColourSpace, bool>())
        .def("get_frame", &gg::VideoSourceFFmpeg::get_frame)
        .def("get_frame_dimensions", &gg::VideoSourceFFmpeg::get_frame_dimensions)
        .def("get_frame_rate", &gg::VideoSourceFFmpeg::get_frame_rate)
        .def("set_sub_frame", &gg::VideoSourceFFmpeg::set_sub_frame)
        .def("get_full_frame", &gg::VideoSourceFFmpeg::get_full_frame)
        .def("attach", &gg::IObservable::attach, &IObservableWrapper::default_attach)
        .def("detach", &gg::IObservable::detach, &IObservableWrapper::default_detach)
    ;
    class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>(
                "VideoTargetFFmpeg", init<std::string, std::string, float>())
        .def("append", &gg::VideoTargetFFmpeg::append)
    ;
#endif

#ifdef USE_OPENCV
    class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>(
                "VideoTargetOpenCV", init<std::string, std::string, float>())
        .def("append", &gg::VideoTargetOpenCV::append)
    ;
#endif // USE_OPENCV

    class_<IObservableObserverWrapper, boost::noncopyable>("IObservableObserver")
        .def("attach", &gg::IObservable::attach, &IObservableObserverWrapper::default_attach)
        .def("detach", &gg::IObservable::detach, &IObservableObserverWrapper::default_detach)
        .def("update", pure_virtual(&gg::IObserver::update))
    ;

    class_<gg::VideoSourceFactory, boost::noncopyable>("VideoSourceFactory", no_init)
        .def("get_device", &gg::VideoSourceFactory::get_device
             /* Keep returned pointer (0) alive as long as factory (1) alive.
              * Boost.Python documentation says reference_existing_object is
              * dangerous, but apparently only when no additional lifetime
              * management with a call policy is provided (for details, see:
              * http://www.boost.org/doc/libs/1_39_0/libs/python/doc/v2/reference_existing_object.html
              * ).
              */
             , return_value_policy<reference_existing_object, with_custodian_and_ward_postcall<1, 0> >()
        )
        .def("free_device", &gg::VideoSourceFactory::free_device)
        .def("connect_network_source", &gg::VideoSourceFactory::connect_network_source
             // see note below about manage_new_object
             , return_value_policy<manage_new_object>())
        .def("get_instance", &gg::VideoSourceFactory::get_instance
             , return_value_policy<reference_existing_object>()
        )
        .staticmethod("get_instance")
        .def("create_file_reader", &gg::VideoSourceFactory::create_file_reader,
             // manage_new_object => give ownership caller
             // see note below for create_file_writer
             return_value_policy<manage_new_object>()
        )
    ;

    class_<gg::VideoTargetFactory, boost::noncopyable>("VideoTargetFactory", no_init)
        .def("create_file_writer", &gg::VideoTargetFactory::create_file_writer,
             /* We use manage_new_object here in order
              * to give ownership is to client. Also
              * this ensures that the newly created
              * object will be destroyed as part of the
              * Python object destruction procedure. See
              * https://wiki.python.org/moin/boost.python/CallPolicy#manage_new_object
              */
             return_value_policy<manage_new_object>()
        )
        .def("get_instance", &gg::VideoTargetFactory::get_instance
             , return_value_policy<reference_existing_object>()
        )
        .staticmethod("get_instance")
    ;
}

max_stars_repo_name: mhubii/GIFT-Grab

max_issues_repo_name: mhubii/GIFT-Grab

max_forks_repo_name: mhubii/GIFT-Grab


text:
//
// Copyright © 2017 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "RefNormalizationFloat32Workload.hpp"

#include "RefWorkloadUtils.hpp"
#include "TensorBufferArrayView.hpp"

#include "Profiling.hpp"

#include <armnn/Tensor.hpp>

#include <boost/log/trivial.hpp>
#include <boost/numeric/conversion/cast.hpp>

using namespace armnnUtils;

namespace armnn
{

// Helper function to compute "Within" normalization using Krichevsky 2012: Local Brightness Normalization.
static void NormalizeWithinUingLbr(const float*       inputData,
                                   float*             outputData,
                                   const TensorShape& tensorShape,
                                   uint32_t           norm_size,
                                   float              alpha,
                                   float              beta,
                                   float              kappa)
{
    const unsigned int batchSize = tensorShape[0];
    const unsigned int depth = tensorShape[1];
    const unsigned int rows = tensorShape[2];
    const unsigned int cols = tensorShape[3];

    int radius = boost::numeric_cast<int>(norm_size / 2u); /* Strong Assumption on rounding Mode */

    for (unsigned int n = 0; n < batchSize; n++)
    {
        for (unsigned int c = 0; c < depth; c++)
        {
            for (unsigned int h = 0; h < rows; h++)
            {
                for (unsigned int w = 0; w < cols; w++)
                {
                    float accumulated_scale = 0.0;
                    for (int y = -radius; y <= radius; y++)
                    {
                        for (int x = -radius; x <= radius; x++)
                        {
                            int i = boost::numeric_cast<int>(w) + x;
                            int j = boost::numeric_cast<int>(h) + y;

                            if ((i < 0) || (i >= boost::numeric_cast<int>(cols)))
                            {
                                continue;
                            }

                            if ((j < 0) || (j >= boost::numeric_cast<int>(rows)))
                            {
                                continue;
                            }

                            float inval = inputData[n * cols * rows * depth +
                                                    c * cols * rows +
                                                    boost::numeric_cast<unsigned int>(j) * cols +
                                                    boost::numeric_cast<unsigned int>(i)];

                            accumulated_scale += inval*inval;
                        }
                    }
                    outputData[n * cols * rows * depth +
                               c * cols * rows +
                               h * cols +
                               w] = inputData[n * cols * rows * depth +
                                              c * cols * rows +
                                              h * cols +
                                              w] / (powf((kappa + (accumulated_scale * alpha)), beta));
                }
            }
        }
    }
}

// Helper function to compute "Across" normalization using Krichevsky 2012: Local Brightness Normalization.
void NormalizeAcrossUingLbr(const float*       inputData,
                            float*             outputData,
                            const TensorShape& tensorShape,
                            uint32_t           norm_size,
                            float              alpha,
                            float              beta,
                            float              kappa,
                            DataLayout         dataLayout)
{
    TensorBufferArrayView<const float> input(tensorShape,
                                             inputData,
                                             dataLayout);
    TensorBufferArrayView<float> output(tensorShape,
                                        outputData,
                                        dataLayout);

    DataLayoutIndexed dataLayoutIndexed(dataLayout);

    const unsigned int batchSize = tensorShape[0];
    const unsigned int depth     = tensorShape[dataLayoutIndexed.GetChannelsIndex()];
    const unsigned int rows      = tensorShape[dataLayoutIndexed.GetHeightIndex()];
    const unsigned int cols      = tensorShape[dataLayoutIndexed.GetWidthIndex()];

    int radius = boost::numeric_cast<int>(norm_size / 2u); /* Strong Assumption on rounding Mode */

    for (unsigned int n = 0; n < batchSize; n++)
    {
        for (unsigned int c = 0; c < depth; c++)
        {
            for (unsigned int h = 0; h < rows; h++)
            {
                for (unsigned int w = 0; w < cols; w++)
                {
                    float accumulated_scale = 0.0;
                    for (int z = -radius; z <= radius; z++)
                    {
                        int k = boost::numeric_cast<int>(c) + z;

                        if ((k < 0) || (k >= boost::numeric_cast<int>(depth)))
                        {
                            continue;
                        }

                        float inval = input.Get(n, boost::numeric_cast<unsigned int>(k), h, w);

                        accumulated_scale += inval * inval;
                    }

                    float scale = kappa + (accumulated_scale * alpha);
                    scale = powf(scale, -beta);

                    output.Get(n, c, h, w) = scale * input.Get(n, c, h, w);
                }
            }
        }
    }
}

void RefNormalizationFloat32Workload::Execute() const
{
    ARMNN_SCOPED_PROFILING_EVENT(Compute::CpuRef, "RefNormalizationFloat32Workload_Execute");

    const TensorInfo& inputInfo = GetTensorInfo(m_Data.m_Inputs[0]);

    float*       outputData = GetOutputTensorDataFloat(0, m_Data);
    const float* inputData = GetInputTensorDataFloat(0, m_Data);

    if (NormalizationAlgorithmMethod::LocalBrightness == m_Data.m_Parameters.m_NormMethodType)
    {
        if (NormalizationAlgorithmChannel::Within == m_Data.m_Parameters.m_NormChannelType)
        {
            NormalizeWithinUingLbr(inputData,
                                   outputData,
                                   inputInfo.GetShape(),
                                   m_Data.m_Parameters.m_NormSize,
                                   m_Data.m_Parameters.m_Alpha,
                                   m_Data.m_Parameters.m_Beta,
                                   m_Data.m_Parameters.m_K);
        }
        else if (NormalizationAlgorithmChannel::Across == m_Data.m_Parameters.m_NormChannelType)
        {
            NormalizeAcrossUingLbr(inputData,
                                   outputData,
                                   inputInfo.GetShape(),
                                   m_Data.m_Parameters.m_NormSize,
                                   m_Data.m_Parameters.m_Alpha,
                                   m_Data.m_Parameters.m_Beta,
                                   m_Data.m_Parameters.m_K,
                                   m_Data.m_Parameters.m_DataLayout);
        }
        else
        {
            BOOST_LOG_TRIVIAL(warning) << "Illegal NORMALIZATION mode in normalization_f32";
            return;
        }
    }
    else
    {
        BOOST_LOG_TRIVIAL(warning) << "Lcr method (Jarret 2009: Local Contrast Normalization) not supported yet.";
        return;
    }
}

} //namespace armnn

max_stars_repo_name: jnorwood/armnn

max_issues_repo_name: jnorwood/armnn

max_forks_repo_name: jnorwood/armnn


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

#include <boost/program_options.hpp>
#include <boost/filesystem.hpp>
#include <boost/config.hpp>
#include <boost/predef.h>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <iostream>
#include <limits>
#include <CYNG_project_info.h>
#include "filters/hexdump.h"
#include "filters/hexdump_cpp.h"
#include "filters/cu.h"
#if BOOST_OS_WINDOWS
#define NOMINMAX
#include <windows.h>
#endif

/**
 * Decrypt log files.
 * Read a log file of several formats and convert into different formats include
 * the original binary file.
 *
 * Start with
 * @code
 * build/unlog -hexdump app0.log
 * @endcode
 */
int main(int argc, char* argv[]) {

	try
	{
		const boost::filesystem::path cwd = boost::filesystem::current_path();
		const boost::filesystem::path temp = boost::filesystem::temp_directory_path();

		std::string config_file;
#ifdef _DEBUG
		std::string inp_file = std::string(CYNG_SOURCE_DIRECTORY) + "/tools/unlog/examples/app0.log";
#else
		std::string inp_file = "input.log";
#endif
		std::string out_file = (cwd / "out.bin").string();
		std::string filter = "hexdump";

		//
		//	generic options
		//
		boost::program_options::options_description generic("Generic options");
		generic.add_options()

			("help,h", "print usage message")
			("version,v", "print version string")
			("build,b", "last built timestamp and platform")
			("config,C", boost::program_options::value<std::string>(&config_file)->default_value("unlog.cfg"), "configuration file")

			;

		//
		//	all unlog options
		//
		boost::program_options::options_description unlog("unlog");
		unlog.add_options()

			("source,S", boost::program_options::value(&inp_file)->default_value(inp_file), "source file")
			("output,O", boost::program_options::value(&out_file)->default_value(out_file), "output file")
			//	verbose level
			("verbose,V", boost::program_options::value<int>()->default_value(0)->implicit_value(1), "verbose level")
			("filter,F", boost::program_options::value(&filter)->default_value(filter), "the filter to apply")
			("begin,B", boost::program_options::value<std::size_t>()->default_value(std::numeric_limits<std::size_t>::min())->implicit_value(std::numeric_limits<std::size_t>::min()), "line to start")
			("end,E", boost::program_options::value<std::size_t>()->default_value(std::numeric_limits<std::size_t>::max())->implicit_value(std::numeric_limits<std::size_t>::max()), "max. line number")
			;

		//
		//	all you can grab from the command line
		//
		boost::program_options::options_description cmdline_options;
		cmdline_options.add(generic).add(unlog);

		//
		//	positional arguments
		//
		boost::program_options::positional_options_description p;
		p.add("source", -1);

		boost::program_options::variables_map vm;
		boost::program_options::store(boost::program_options::command_line_parser(argc, argv).options(cmdline_options).positional(p).run(), vm);
		boost::program_options::notify(vm);

		if (vm.count("help"))
		{
			std::cout
				<< cmdline_options
				<< std::endl
				;
			return EXIT_SUCCESS;
		}

		if (vm.count("version"))
		{
			std::cout
				<< "unlog v"
				<< CYNG_VERSION
				<< std::endl
				;
			return EXIT_SUCCESS;
		}

		if (vm.count("build"))
		{
			std::cout
				<< "last built at : "
				<< __DATE__
				<< " "
				<< __TIME__
				<< std::endl
				<< "Platform      : "
				<< CYNG_PLATFORM
				<< std::endl
				<< "Compiler      : "
				<< BOOST_COMPILER
				<< std::endl
				<< "StdLib        : "
				<< BOOST_STDLIB
				<< std::endl

#if defined(BOOST_LIBSTDCXX_VERSION)
				<< "StdLib++      : "
				<< BOOST_LIBSTDCXX_VERSION
				<< std::endl
#endif

				<< "BOOSTLib      : "
				<< BOOST_LIB_VERSION
				<< " ("
				<< BOOST_VERSION
				<< ")"
				<< std::endl

// 				<< "build type    : "
// 				<< CYX_BUILD_TYPE
// 				<< std::endl
// 				<< "ODBC available: "
// #if defined(CYNG_ODBC_HEADER_AVAILABLE)
// 				<< "yes"
// #else
// 				<< "no"
// #endif
// 				<< std::endl
				<< "shared mutex  : "
#if defined(BOOST_NO_CXX14_HDR_SHARED_MUTEX)
				<< "no"
#else
				<< "yes"
#endif
				<< std::endl
				<< std::endl
				;
			return EXIT_SUCCESS;
		}

		std::ifstream ifs(config_file);
		if (!ifs)
		{
			std::cout
				<< "***info: config file: "
				<< config_file
				<< " not found"
				<< std::endl
				;
		}
		else
		{
			boost::program_options::store(boost::program_options::parse_config_file(ifs, unlog), vm);
			boost::program_options::notify(vm);
		}

		const int verbose = vm["verbose"].as< int >();
		if (verbose > 0)
		{
			std::cout
				<< "***info: verbose level: "
				<< verbose
				<< std::endl
				;
		}

#if BOOST_OS_WINDOWS
		//
		//	set console outpt code page to UTF-8
		//	requires a TrueType font like Lucida
		//
		if (::SetConsoleOutputCP(65001) == 0)
		{
			std::cerr
				<< "Cannot set console code page"
				<< std::endl
				;

		}
#endif

		//
		//	Construct selected filter
		//
		if (boost::algorithm::equals("hexdump", filter)) {
			return cyng::hexdump(inp_file, out_file, verbose).run(vm["begin"].as< std::size_t >(), vm["end"].as< std::size_t >());
		}
		else if (boost::algorithm::equals("hexdumcpp", filter)) {
			if (vm["output"].defaulted()) {
				//
				//	Derive an output name from the input name
				//	if no name was explicitely defined.
				//
				boost::filesystem::path tmp = inp_file;
				out_file = tmp.replace_extension(".ipp").string();

				if (verbose > 1)
				{
					std::cout
						<< "***info: output file is: "
						<< out_file
						<< std::endl
						;
				}
			}
			return cyng::hexdump_cpp(inp_file, out_file, verbose).run(vm["begin"].as< std::size_t >(), vm["end"].as< std::size_t >());
		}
		else if (boost::algorithm::equals("cu", filter)) {
			if (vm["output"].defaulted()) {
				//
				//	Derive an output name from the input name
				//	if no name was explicitely defined.
				//temp
				boost::filesystem::path tmp = inp_file;
				out_file = tmp.parent_path().string();

				if (verbose > 1)
				{
					std::cout
						<< "***info: output path is: "
						<< out_file
						<< std::endl
						;
				}
			}
			return cyng::cu(inp_file, out_file, verbose).run(vm["begin"].as< std::size_t >(), vm["end"].as< std::size_t >());
		}

		std::cerr << "unknown filter: " << filter << std::endl;

	}
	catch (std::exception& e)
	{
		std::cerr
			<< e.what()
			<< std::endl
			;
	}

	return EXIT_FAILURE;

}

max_stars_repo_name: solosTec/cyng

max_issues_repo_name: solosTec/cyng

max_forks_repo_name: solosTec/cyng


text:
#include <cassert>
#include <cmath>
#include <complex>
#include <vector>
#include <Eigen/Core>

#include "Const.h"
#include "Tract.h"

using namespace std;
using namespace Eigen;

Tract::Tract(double c1, double dl, const double S[], int length) :
	a	(130 * Const::pi),
	b	(std::pow(30 * Const::pi, 2)),
	om0	(pow(406 * Const::pi, 2)),
	c1	(c1),
	dl	(dl),
	S	(length)
{
	for (int i = 0; i < length; i++)
		this->S[i] = S[i];
}
Tract::Tract(double c1, double dl, vector<double> &S) :
	a	(130 * Const::pi),
	b	(std::pow(30 * Const::pi, 2)),
	om0	(pow(406 * Const::pi, 2)),
	c1	(c1),
	dl	(dl),
	S	(S)
{
}

Tract::~Tract(void)
{
}

complex<double> Tract::GetBeta(double f)
{
	double omg = 2.0 * Const::pi * f;
	complex<double> s(0, omg);
	return s * om0 / ((s + a) * s + b) + sqrt(s * c1);
}

vector<double> Tract::GetArea(void)
{
	return S;
}

double Tract::GetStartArea(void)
{
	return S.front();
}

double Tract::GetEndArea(void)
{
	return S.back();
}

double Tract::GetElemLength(void)
{
	return dl;
}

Matrix2cd Tract::ChainMatrix(double freq, int from)
{
	return ChainMatrix(freq, from, S.size() - 1);
}
Matrix2cd Tract::ChainMatrix(double freq, int from, int to)
{
	double n = to - from + 1;

	double omg = 2.0 * Const::pi * freq;
	complex<double> s(0, omg);

	complex<double> loss = s * om0 / ((s + a) * s + b) + sqrt(s * c1);
	complex<double> gamma = sqrt((a + s) / (loss + s));
	complex<double> sigma = gamma * (loss + s) / Const::c;

	Matrix2cd r = Matrix2cd::Identity();
	complex<double> sh = sinh(sigma * dl);
	Matrix2cd K;
    K(0, 0) = K(1, 1) = cosh(sigma * dl);

    for (int i = 0; i < n; i++)
    {
        complex<double> coeff = -Const::rho * Const::c / S[from + i] * gamma;

		K(0, 1) = coeff * sh;
        K(1, 0) = 1.0 / coeff * sh;

        r = K * r;
    }

    return r;
}

ext: cxx

max_stars_repo_name: kinoh/VoiceSynthesis

max_issues_repo_name: kinoh/VoiceSynthesis

max_forks_repo_name: kinoh/VoiceSynthesis


text:
// (C) Copyright Mac Murrett 2001.
// 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)

// See http://www.boost.org for most recent version.

#include "remote_call_manager.hpp"

#include <boost/bind.hpp>

namespace boost {

namespace threads {

namespace mac {

namespace detail {

using detail::delivery_man;

remote_call_manager::remote_call_manager():
    m_oDTDeliveryMan(),
    m_oSTDeliveryMan(),
    m_oDTFunction(bind(&delivery_man::accept_deliveries, &m_oDTDeliveryMan)),
    m_oSTFunction(bind(&delivery_man::accept_deliveries, &m_oSTDeliveryMan)),
    m_oDTPeriodical(m_oDTFunction),
    m_oSTPeriodical(m_oSTFunction)
{
    m_oDTPeriodical.start();
    m_oSTPeriodical.start();
}

remote_call_manager::~remote_call_manager()
{
}

} // namespace detail

} // namespace mac

} // namespace threads

} // namespace boost

max_stars_repo_name: dbremner/framewave

max_issues_repo_name: dbremner/framewave

max_forks_repo_name: dbremner/framewave


text:
// #include <map>
// #include <string>
// #include <Eigen/Dense>
// #include "simple_layer.h"
// #include "simple_mlp.h"

// namespace MyDL{

//     using namespace Eigen;

//     TwoLayerNetwork::TwoLayerNetwork(int input_size, int hidden_size, int output_size, double weight_init_std){
//         _input_size = input_size;
//         _hidden_size = hidden_size;
//         _output_size = output_size;

//         _params["W1"] = weight_init_std * MatrixXd::Random(input_size, hidden_size);
//         _params["b1"] = VectorXd::Zero(hidden_size);
//         _params["W2"] = weight_init_std * MatrixXd::Random(hidden_size, output_size);
//         _params["b1"] = VectorXd::Zero(output_size);

//     }

//     MatrixXd TwoLayerNetwork::predict(MatrixXd& X){

//     }

// }


text:
#include <iostream>
#include <boost/timer/timer.hpp>
#include <boost/tokenizer.hpp>

//configuration
#define ST_ASIO_SERVER_PORT		9527
#define ST_ASIO_REUSE_OBJECT //use objects pool
#define ST_ASIO_DELAY_CLOSE		5 //define this to avoid hooks for async call (and slightly improve efficiency)
#define ST_ASIO_SYNC_DISPATCH
//#define ST_ASIO_WANT_MSG_SEND_NOTIFY
#define ST_ASIO_MSG_BUFFER_SIZE	65536
#define ST_ASIO_DEFAULT_UNPACKER stream_unpacker //non-protocol
#define ST_ASIO_DECREASE_THREAD_AT_RUNTIME
//configuration

#include "../include/ext/tcp.h"
using namespace st_asio_wrapper;
using namespace st_asio_wrapper::tcp;
using namespace st_asio_wrapper::ext;
using namespace st_asio_wrapper::ext::tcp;

#define QUIT_COMMAND	"quit"
#define STATUS			"status"
#define STATISTIC		"statistic"
#define LIST_ALL_CLIENT	"list all client"
#define INCREASE_THREAD	"increase thread"
#define DECREASE_THREAD	"decrease thread"

boost::timer::cpu_timer begin_time;
#if BOOST_VERSION >= 105300
boost::atomic_ushort completed_session_num;
#else
atomic<unsigned short> completed_session_num;
#endif

class echo_socket : public client_socket
{
public:
	echo_socket(i_matrix& matrix_) : client_socket(matrix_) {}

	void begin(size_t msg_num, const char* msg, size_t msg_len)
	{
		total_bytes = msg_len;
		total_bytes *= msg_num;
		send_bytes = recv_bytes = 0;

		send_native_msg(msg, msg_len, false);
	}

protected:
	virtual void on_connect() {boost::asio::ip::tcp::no_delay option(true); lowest_layer().set_option(option); client_socket::on_connect();}

	//msg handling, must define macro ST_ASIO_SYNC_DISPATCH
	//do not hold msg_can for further usage, access msg_can and return from on_msg as quickly as possible
	//access msg_can freely within this callback, it's always thread safe.
	virtual size_t on_msg(list<out_msg_type>& msg_can)
	{
		st_asio_wrapper::do_something_to_all(msg_can, boost::bind(&echo_socket::handle_msg, this, boost::placeholders::_1));
		BOOST_AUTO(re, msg_can.size());
		msg_can.clear(); //if we left behind some messages in msg_can, they will be dispatched via on_msg_handle asynchronously, which means it's
		//possible that on_msg_handle be invoked concurrently with the next on_msg (new messages arrived) and then disorder messages.
		//here we always consumed all messages, so we can use sync message dispatching, otherwise, we should not use sync message dispatching
		//except we can bear message disordering.

		return re;
	}
	//msg handling end

#ifdef ST_ASIO_WANT_MSG_SEND_NOTIFY
	virtual void on_msg_send(in_msg_type& msg)
	{
		send_bytes += msg.size();
		if (send_bytes < total_bytes)
			direct_send_msg(msg, true);
	}

private:
	void handle_msg(out_msg_ctype& msg)
	{
		recv_bytes += msg.size();
		if (recv_bytes >= total_bytes && 0 == --completed_session_num)
			begin_time.stop();
	}
#else
private:
	void handle_msg(out_msg_type& msg)
	{
		if (0 == total_bytes)
			return;

		recv_bytes += msg.size();
		if (recv_bytes >= total_bytes)
		{
			total_bytes = 0;
			if (0 == --completed_session_num)
				begin_time.stop();
		}
		else
			direct_send_msg(msg, true);
		//if the type of out_msg_type and in_msg_type are not identical, the compilation will fail, then you should use send_native_msg instead.
	}
#endif

private:
	boost::uint64_t total_bytes, send_bytes, recv_bytes;
};

class echo_client : public multi_client_base<echo_socket>
{
public:
	echo_client(service_pump& service_pump_) : multi_client_base<echo_socket>(service_pump_) {}

	void begin(size_t msg_num, const char* msg, size_t msg_len) {do_something_to_all(boost::bind(&echo_socket::begin, boost::placeholders::_1, msg_num, msg, msg_len));}
};

int main(int argc, const char* argv[])
{
	printf("usage: %s [<service thread number=1> [<port=%d> [<ip=%s> [link num=16]]]]\n", argv[0], ST_ASIO_SERVER_PORT, ST_ASIO_SERVER_IP);
	if (argc >= 2 && (0 == strcmp(argv[1], "--help") || 0 == strcmp(argv[1], "-h")))
		return 0;
	else
		puts("type " QUIT_COMMAND " to end.");

	///////////////////////////////////////////////////////////
	size_t link_num = 16;
	if (argc > 4)
		link_num = std::min(ST_ASIO_MAX_OBJECT_NUM, std::max(atoi(argv[4]), 1));

	printf("exec: pingpong_client with " ST_ASIO_SF " links\n", link_num);
	///////////////////////////////////////////////////////////

	service_pump sp;
	echo_client client(sp);

//	argv[3] = "::1" //ipv6
//	argv[3] = "127.0.0.1" //ipv4
	std::string ip = argc > 3 ? argv[3] : ST_ASIO_SERVER_IP;
	unsigned short port = argc > 2 ? atoi(argv[2]) : ST_ASIO_SERVER_PORT;

	int thread_num = 1;
	if (argc > 1)
		thread_num = std::min(16, std::max(thread_num, atoi(argv[1])));
	//add one thread will seriously impact IO throughput when doing performance benchmark, this is because the business logic is very simple (send original messages back,
	//or just add up total message size), under this scenario, just one service thread without receiving buffer will obtain the best IO throughput.
	//the server has such behavior too.

	for (size_t i = 0; i < link_num; ++i)
		client.add_socket(port, ip);

	sp.start_service(thread_num);
	while(sp.is_running())
	{
		std::string str;
		std::getline(std::cin, str);
		if (str.empty())
			;
		else if (QUIT_COMMAND == str)
			sp.stop_service();
		else if (STATISTIC == str)
		{
			printf("link #: " ST_ASIO_SF ", valid links: " ST_ASIO_SF ", invalid links: " ST_ASIO_SF "\n\n", client.size(), client.valid_size(), client.invalid_object_size());
			puts(client.get_statistic().to_string().data());
		}
		else if (STATUS == str)
			client.list_all_status();
		else if (LIST_ALL_CLIENT == str)
			client.list_all_object();
		else if (INCREASE_THREAD == str)
			sp.add_service_thread(1);
		else if (DECREASE_THREAD == str)
			sp.del_service_thread(1);
		else
		{
			size_t msg_num = 1024;
			size_t msg_len = 1024; //must greater than or equal to sizeof(size_t)
			char msg_fill = '0';

			boost::char_separator<char> sep(" \t");
			boost::tokenizer<boost::char_separator<char> > tok(str, sep);
			BOOST_AUTO(iter, tok.begin());
			if (iter != tok.end()) msg_num = std::max((size_t) atoi(iter++->data()), (size_t) 1);
			if (iter != tok.end()) msg_len = std::min((size_t) ST_ASIO_MSG_BUFFER_SIZE, std::max((size_t) atoi(iter++->data()), (size_t) 1));
			if (iter != tok.end()) msg_fill = *iter++->data();

			printf("test parameters after adjustment: " ST_ASIO_SF " " ST_ASIO_SF " %c\n", msg_num, msg_len, msg_fill);
			puts("performance test begin, this application will have no response during the test!");

			completed_session_num = (unsigned short) link_num;
			char* init_msg = new char[msg_len];
			memset(init_msg, msg_fill, msg_len);
			client.begin(msg_num, init_msg, msg_len);
			begin_time.start();

			while (0 != completed_session_num)
				boost::this_thread::sleep_for(boost::chrono::milliseconds(50));

			boost::uint64_t total_msg_bytes = link_num; total_msg_bytes *= msg_len; total_msg_bytes *= msg_num;
			double used_time = (double) begin_time.elapsed().wall / 1000000000;
			printf("finished in %f seconds, TPS: %f(*2), speed: %f(*2) MBps.\n", used_time, link_num * msg_num / used_time, total_msg_bytes / used_time / 1024 / 1024);

			delete[] init_msg;
		}
	}

    return 0;
}


text:
/*!
  @file
  @author Shin'ichiro Nakaoka
*/

#include "GRobotBar.h"
#include <boost/bind.hpp>
#include "gettext.h"

using namespace boost;
using namespace cnoid;

GRobotBar* GRobotBar::instance()
{
    static GRobotBar* instance = new GRobotBar();
    return instance;
}

GRobotBar::GRobotBar() : ToolBar(N_("GRobotBar"))
{
    addImage(":/GRobot/icons/grobo-logo.png")
        ->setToolTip(_("G-Robot toolbar which provides buttons for handling actual G-Robots"));

    addSpacing(4);
    addSeparator();

    addToggleButton(QIcon(":/GRobot/icons/servo-on.png"), _("Turn on / off servo gains"))
        ->sigToggled().connect(bind(&GRobotBar::onServoButtonToggled, this, _1));

    addButton(QIcon(":/GRobot/icons/sendpose.png"), _("Send the current pose of virtual robots to actual robots"))
        ->sigClicked().connect(bind(ref(sigPoseSendRequest_)));

    syncCheck = addToggleButton(QIcon(":/GRobot/icons/syncpose.png"), _("Synchronize the pose of actual robots pose with virtual robots"));

    syncCheck->sigToggled().connect(bind(ref(sigSyncModeToggled_),  _1));
}

void GRobotBar::onServoButtonToggled(bool on)
{
    sigServoSwitchRequest_(on);
}

max_stars_repo_name: snozawa/choreonoid

max_issues_repo_name: snozawa/choreonoid

max_forks_repo_name: snozawa/choreonoid


text:
//
// Boost.Process
// ~~~~~~~~~~~~~
//
// Copyright (c) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Boris Schaeling
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <boost/process/config.hpp>

#if defined(BOOST_POSIX_API)
#  include <sys/stat.h>
#  include <fcntl.h>
#  include <unistd.h>
#elif defined(BOOST_WINDOWS_API)
#  include <windows.h>
#else
#  error "Unsupported platform."
#endif

#include <boost/process/detail/systembuf.hpp>
#include <boost/test/unit_test.hpp>
#include <istream>
#include <ostream>
#include <fstream>
#include <cstddef>

namespace bp = ::boost::process;
namespace bpd = ::boost::process::detail;
namespace but = ::boost::unit_test;

static void check_data(std::istream &is, std::size_t length)
{
    char ch = 'A', chr;
    std::size_t cnt = 0;
    while (is >> chr)
    {
        BOOST_CHECK(ch == chr);
        if (ch == 'Z')
            ch = 'A';
        else
            ++ch;
        ++cnt;
    }
    BOOST_CHECK(cnt == length);
}

static void write_data(std::ostream &os, std::size_t length)
{
    char ch = 'A';
    for (std::size_t i = 0; i < length; ++i)
    {
        os << ch;
        if (ch == 'Z')
            ch = 'A';
        else
            ++ch;
    }
    os.flush();
}

static void remove_file(const std::string &name)
{
#if defined(BOOST_WINDOWS_API)
    ::DeleteFileA(name.c_str());
#else
    ::unlink(name.c_str());
#endif
}

static void test_read(std::size_t length, std::size_t bufsize)
{
    std::ofstream f("test_read.txt");
    write_data(f, length);
    f.close();

#if defined(BOOST_WINDOWS_API)
    HANDLE hfile = ::CreateFileA("test_read.txt",
        GENERIC_READ, 0, NULL, OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, NULL);
    BOOST_REQUIRE(hfile != INVALID_HANDLE_VALUE);
    bpd::systembuf sb(hfile, bufsize);
    std::istream is(&sb);
    check_data(is, length);
    ::CloseHandle(hfile);
#else
    int fd = ::open("test_read.txt", O_RDONLY);
    BOOST_CHECK(fd != -1);
    bpd::systembuf sb(fd, bufsize);
    std::istream is(&sb);
    check_data(is, length);
    ::close(fd);
#endif
    remove_file("test_read.txt");
}

static void test_short_read()
{
    test_read(64, 1024);
}

static void test_long_read()
{
    test_read(64 * 1024, 1024);
}

static void test_write(std::size_t length, std::size_t bufsize)
{
#if defined(BOOST_WINDOWS_API)
    HANDLE hfile = ::CreateFileA("test_write.txt",
        GENERIC_WRITE, 0, NULL, CREATE_NEW,
        FILE_ATTRIBUTE_NORMAL, NULL);
    BOOST_REQUIRE(hfile != INVALID_HANDLE_VALUE);
    bpd::systembuf sb(hfile, bufsize);
    std::ostream os(&sb);
    write_data(os, length);
    ::CloseHandle(hfile);
#else
    int fd = ::open("test_write.txt", O_WRONLY | O_CREAT | O_TRUNC,
        S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
    BOOST_CHECK(fd != -1);
    bpd::systembuf sb(fd, bufsize);
    std::ostream os(&sb);
    write_data(os, length);
    ::close(fd);
#endif

    std::ifstream is("test_write.txt");
    check_data(is, length);
    is.close();
    remove_file("test_write.txt");
}

static void test_short_write()
{
    test_write(64, 1024);
}

static void test_long_write()
{
    test_write(64 * 1024, 1024);
}

but::test_suite *init_unit_test_suite(int argc, char *argv[])
{
    but::test_suite *test = BOOST_TEST_SUITE("detail::systembuf test suite");

    test->add(BOOST_TEST_CASE(&test_short_read));
    test->add(BOOST_TEST_CASE(&test_long_read));
    test->add(BOOST_TEST_CASE(&test_short_write));
    test->add(BOOST_TEST_CASE(&test_long_write));

    return test;
}

max_stars_repo_name: Flusspferd/flusspferd

max_issues_repo_name: STEllAR-GROUP/octopus

max_forks_repo_name: STEllAR-GROUP/octopus


text: #include <boost/move/make_unique.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef VISUALIZATION_HPP
#define VISUALIZATION_HPP

// vta
#include <cluster/Edge.hpp>
#include <cluster/Cluster.hpp>

// cpp
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <pthread.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>

// boost
#include <boost/lexical_cast.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/filesystem.hpp>
#include <boost/tokenizer.hpp>

//wikidb
#include <contract.h>
#include <record_not_found.h>
#include <SimPair.h>
#include <wikidb.h>

namespace vta
{

  class Cluster;

  class Visualization
  {
    public:

      // class constructor
      Visualization();

      // class destructor
      virtual ~Visualization();

      // Create Nodes and Edges
      Node* create_node(long, std::string const, Article);
      Edge* create_edge(Node*, Node*, double);

      // Get Nodes and Edges
      Node* get_node_by_index(long); /// delete
      Edge* get_edge_by_index(long); /// delete

      int get_node_num() const; // replace durch unsigned counter?
      int get_edge_num() const; // replace durch unsigned counter?

      // Cluster getter
      unsigned get_cluster_num() const;
      Cluster* get_cluster_by_index(unsigned);

      // Create Visualization from data base
      void create_graph_from_db(const char input_file_name[], const char offset_file_name[]); // replace durch get cluster

      // Get cluster size
      double get_cluster_size() const; // Allgemeine Cluster size
      // Get amount of clusters per row
      unsigned get_clusters_per_row_num() const; // wichtig fuer cluster index bei mouse over

      // Index of Cluster that will be displayed in the detail view
      unsigned _detail_view_cluster_index; // wichtig fuer Cluster window

      // Cluster algorithms
      void visit_node(Node*, Cluster*); /// delete
      void search_clusters(); /// delete

      // Set all cluster position
      void set_cluster_positions();

    private:
      std::vector<Node*> _nodes; /// delete
      std::vector<Edge*> _edges; /// delete

      std::map<uint32_t,Node*> _index2node; /// delete

      // Clustering
      std::vector<Cluster*> _clusters;

      // Amount of clusters per row
      unsigned _clusters_per_row;
      double _cluster_size;

      //
      bool node_map_contains_id(int); /// delete

  };

} // Namespace vta

#endif // VISUALIZATION_HPP


text:
#ifndef IO_ENUM_TRANSLATOR_HPP
#define IO_ENUM_TRANSLATOR_HPP

#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include "../exception/enum_convert_error.h"

namespace io{
template<typename T>
struct EnumTranslator{
    // type
    using internal_type = boost::property_tree::ptree::data_type;
    using external_type = T;
    // tlanslator
    virtual external_type to_enum(const internal_type& data) const = 0;
    virtual internal_type to_string(const external_type& data) const = 0;
    // property_tree -> T
    boost::optional<external_type> get_value(
                const internal_type& data) const{
        try{
            const external_type value = to_enum(data);
            return value;
        }catch(const exception::EnumConvertError& e){
            std::cerr << e.what() << std::endl;
            return boost::none;
        }
    }
    // T -> property_tree
    boost::optional<internal_type> put_value(
                const external_type& data) const{
        return to_string(data);
    }
};
}// end namespace io
#endif// IO_ENUM_TRANSLATOR_HPP


text:
#include <ros/ros.h>
#include <ros/spinner.h>
#include "epos_hardware/epos_hardware.h"
#include <controller_manager/controller_manager.h>
#include <vector>
#include "walrus_base_hw/realtime_rate.h"
#include "walrus_base_hw/util.h"
#include <boost/assign/list_of.hpp>

int main(int argc, char** argv) {
  ros::init(argc, argv, "epos_hw_node");
  ros::NodeHandle nh;
  ros::NodeHandle pnh("~");

  double controller_rate;
  pnh.param<double>("controller_rate", controller_rate, 10);

  std::vector<std::string> epos_names;
  pnh.getParam("names", epos_names);

  epos_hardware::EposHardware robot(nh, pnh, epos_names);

  ros::AsyncSpinner spinner(1);
  spinner.start();

  ROS_INFO("Initializing Motors");
  if(!robot.init()) {
    ROS_FATAL("Failed to initialize motors");
    return 1;
  }
  ROS_INFO("Motors Initialized");

  controller_manager::ControllerManager cm(&robot, pnh);
  ros::Timer controller_load_timer = walrus_base_hw::createControllerLoadTimer(pnh, &cm);

  ROS_INFO("Running loop");
  walrus_base_hw::RealtimeRate rate(controller_rate);
  while (ros::ok()) {
    ros::Duration dt;
    ros::Time now;
    rate.beginLoop(&now, &dt);

    robot.read();
    cm.update(now, dt);
    robot.write();

    robot.update_diagnostics();

    rate.sleep();
  }
  return 0;
}

max_stars_repo_name: RIVeR-Lab/walrus

max_issues_repo_name: RIVeR-Lab/walrus

max_forks_repo_name: RIVeR-Lab/walrus