text:
/*
 * nghttp2 - HTTP/2 C Library
 *
 * Copyright (c) 2014 Tatsuhiro Tsujikawa
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
// We wrote this code based on the original code which has the
// following license:
//
// main.cpp
// ~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <iostream>
#include <string>
#include <fstream>
#include <thread>
#include <future>
#include <memory>
#include <tuple>
#include <boost/asio/io_service.hpp>
#include <boost/thread/thread.hpp>

#include <nghttp2/asio_http2_server.h>
#include "asio_server_http2_handler.h"
#include "asio_server_stream.h"

#include "H2Server_Config_Schema.h"
#include "H2Server_Request.h"
#include "H2Server.h"

using namespace nghttp2::asio_http2;
using namespace nghttp2::asio_http2::server;

struct ResponseStatistics
{
    uint64_t response_sent = 0;
    uint64_t response_throttled = 0;
};

void close_stream(uint64_t& handler_id, int32_t stream_id)
{
    auto h2_handler = nghttp2::asio_http2::server::http2_handler::find_http2_handler(handler_id);
    if (h2_handler)
    {
        h2_handler->close_stream(stream_id);
    }
}

size_t get_req_name_max_size(const H2Server_Config_Schema& config_schema)
{
    const std::string req_name = "req-name";
    const std::string total = "TOTAL";
    size_t width = req_name.size();
    for (size_t req_index = 0; req_index < config_schema.service.size(); req_index++)
    {
        if (config_schema.service[req_index].request.name.size() > width)
        {
            width = config_schema.service[req_index].request.name.size();
        }
    }
    return width;

}

size_t get_resp_name_max_size(const H2Server_Config_Schema& config_schema)
{
    const std::string resp_name = "resp-name";
    const std::string total = "TOTAL";
    size_t width = resp_name.size();
    for (size_t req_index = 0; req_index < config_schema.service.size(); req_index++)
    {
        for (size_t resp_index = 0; resp_index < config_schema.service[req_index].responses.size(); resp_index++)
        if (config_schema.service[req_index].responses[resp_index].name.size() > width)
        {
            width = config_schema.service[req_index].responses[resp_index].name.size();
        }
    }
    return width;
}

inline void send_response(uint32_t status_code,
                        std::map<std::string, std::string>& resp_headers,
                        std::string& resp_payload,
                        const uint64_t& handler_id,
                        int32_t stream_id,
                        uint64_t& matchedResponsesSent
                        )
{
    auto h2_handler = nghttp2::asio_http2::server::http2_handler::find_http2_handler(handler_id);
    if (!h2_handler)
    {
        return;
    }
    if (!status_code)
    {
        h2_handler->close_stream(stream_id);;
        return;
    }

    auto orig_stream = h2_handler->find_stream(stream_id);
    if (!orig_stream)
    {
        return;
    }
    header_map headers;
    for (auto header: resp_headers)
    {
        nghttp2::asio_http2::header_value hdr_val;
        hdr_val.sensitive = false;
        hdr_val.value = header.second;
        headers.insert(std::make_pair(header.first, hdr_val));
        if (debug_mode)
        {
            std::cout<<"sending header "<<header.first<<": "<<header.second<<std::endl;
        }
    }
    if (resp_payload.size())
    {
        nghttp2::asio_http2::header_value hdr_val;
        hdr_val.sensitive = false;
        hdr_val.value = std::to_string(resp_payload.size());
        headers.insert(std::make_pair("Content-Length", hdr_val));
    }
    if (debug_mode && resp_payload.size())
    {
        std::cout<<"sending header "<<"Content-Length: "<<resp_payload.size()<<std::endl;
        std::cout<<"sending msg body "<<resp_payload<<std::endl;
    }
    if (debug_mode)
    {
        std::cout<<"sending status code: "<<status_code<<std::endl;
    }
    auto& res = orig_stream->response();
    res.write_head(status_code, headers);
    res.end(resp_payload);
    matchedResponsesSent++;
};

void update_response_with_lua(const H2Server_Response* matched_response,
                                        std::multimap<std::string, std::string>& req_headers,
                                        std::string& req_payload,
                                        std::map<std::string, std::string>& resp_headers,
                                        std::string& resp_payload,
                                        uint64_t& handler_id,
                                        int32_t stream_id,
                                        uint64_t& matchedResponsesSent)
{
    matched_response->update_response_with_lua(req_headers, req_payload, resp_headers, resp_payload);
    auto h2_handler = nghttp2::asio_http2::server::http2_handler::find_http2_handler(handler_id);
    if (!h2_handler)
    {
        return;
    }
    auto status_code = matched_response->status_code;
    if (resp_headers.count(status))
    {
        status_code = atoi(resp_headers[status].c_str());
    }
    resp_headers.erase(status);
    auto send_response_routine = std::bind(send_response,
                                           status_code,
                                           resp_headers,
                                           resp_payload,
                                           handler_id,
                                           stream_id,
                                           std::ref(matchedResponsesSent)
                                           );
    h2_handler->io_service().post(send_response_routine);
};

int main(int argc, char *argv[]) {
  try {
    // Check command line arguments.
    if (argc < 2) {
      std::cerr<< "Usage: "<<argv[0]<<" config.json"<<std::endl;
      return 1;
    }

    std::string config_file_name = argv[1];
    std::ifstream buffer(config_file_name);
    std::string jsonStr((std::istreambuf_iterator<char>(buffer)),
                        std::istreambuf_iterator<char>());
    staticjson::ParseStatus result;
    H2Server_Config_Schema config_schema;
    if (!staticjson::from_json_string(jsonStr.c_str(), &config_schema, &result))
    {
        std::cout << "error reading config file:" << result.description() << std::endl;
        exit(1);
    }

    H2Server h2server(config_schema); // sanity check to fail early

    if (config_schema.verbose)
    {
        debug_mode = true;
    }

    boost::asio::io_service work_offload_io_service;
    boost::thread_group work_offload_thread_pool;
    boost::asio::io_service::work work(work_offload_io_service);
    for (size_t i = 0; i < config_schema.service.size(); i++)
    {
        work_offload_thread_pool.create_thread(boost::bind(&boost::asio::io_service::run, &work_offload_io_service));
    }

    boost::system::error_code ec;

    std::string addr = config_schema.address;
    std::string port = std::to_string(config_schema.port);
    std::size_t num_threads = config_schema.threads;
    if (!num_threads)
    {
        num_threads = std::thread::hardware_concurrency();
    }
    if (!num_threads)
    {
        num_threads = 1;
    }
    http2 server;

    std::atomic<uint64_t> threadIndex(0);
    std::vector<uint64_t> totalReqsReceived(num_threads, 0);
    std::vector<std::vector<std::vector<ResponseStatistics>>> respStats;

    for (size_t req_idx = 0; req_idx < config_schema.service.size(); req_idx++)
    {
        std::vector<std::vector<ResponseStatistics>> perServiceStats(config_schema.service[req_idx].responses.size(), std::vector<ResponseStatistics>(num_threads));
        respStats.push_back(perServiceStats);
    }

    server.num_threads(num_threads);

    server.handle("/", [&work_offload_io_service, &config_schema, &respStats, &threadIndex, &totalReqsReceived](const request &req, const response &res, uint64_t handler_id, int32_t stream_id) {

        static thread_local H2Server h2server(config_schema);
        static thread_local auto thread_index = threadIndex++;
        static thread_local auto& reqReceived = totalReqsReceived[thread_index];
        auto init_strand = [&work_offload_io_service]()
        {
          std::map<const H2Server_Response*, boost::asio::io_service::strand> strands;
          for (auto& service: h2server.services)
          {
              for (auto& response: service.second.responses)
              {
                  strands.insert(std::make_pair(&response, boost::asio::io_service::strand(work_offload_io_service)));
              }
          }
          return strands;
        };
        static thread_local auto strands = init_strand();

        H2Server_Request_Message msg(req);
        reqReceived++;
        size_t req_index;
        size_t resp_index;
        auto matched_response = h2server.get_response_to_return(msg, req_index, resp_index);
        if (matched_response)
        {
            if (matched_response->is_response_throttled())
            {
                close_stream(handler_id, stream_id);
                respStats[req_index][resp_index][thread_index].response_throttled++;
                return;
            }
            auto response_headers = matched_response->produce_headers(msg);
            auto response_payload = matched_response->produce_payload(msg);
            auto status_code = matched_response->status_code;
            if (matched_response->luaState.get())
            {
                if (matched_response->lua_offload)
                {
                    auto msg_update_routine = std::bind(update_response_with_lua,
                                                        matched_response,
                                                        msg.headers,
                                                        req.unmutable_payload(),
                                                        response_headers,
                                                        response_payload,
                                                        handler_id,
                                                        stream_id,
                                                        std::ref(respStats[req_index][resp_index][thread_index].response_sent));
                    auto it = strands.find(matched_response);
                    it->second.post(msg_update_routine);
                    return;
                }
                else
                {
                   matched_response->update_response_with_lua(msg.headers, req.unmutable_payload(), response_headers, response_payload);
                   if (response_headers.count(status))
                   {
                       status_code = atoi(response_headers[status].c_str());
                   }
                   response_headers.erase(status);
                }
            }
            send_response(status_code, response_headers, response_payload, handler_id, stream_id, respStats[req_index][resp_index][thread_index].response_sent);
        }
        else
        {
          res.write_head(404, {{"reason", {"no match found"}}});
          res.end("no matched entry found\n");
        }
    });

    std::cout<<"addr: "<<addr<<", port: "<<port<<std::endl;

    std::future<void> fu_tps =
        std::async(std::launch::async, [&totalReqsReceived, &respStats, &config_schema]()
    {
        std::vector<std::vector<uint64_t>> resp_sent_till_now;
        std::vector<std::vector<uint64_t>> resp_throttled_till_now;
        for (size_t i = 0; i < config_schema.service.size(); i++)
        {
            resp_sent_till_now.emplace_back(std::vector<uint64_t>(config_schema.service[i].responses.size(), 0));
            resp_throttled_till_now.emplace_back(std::vector<uint64_t>(config_schema.service[i].responses.size(), 0));
        }
        uint64_t total_req_received_till_now = 0;
        uint64_t total_resp_sent_till_now = 0;
        uint64_t total_resp_throttled_till_now = 0;
        uint64_t counter = 0;

        auto req_name_width = get_req_name_max_size(config_schema);
        auto resp_name_width = get_resp_name_max_size(config_schema);
        size_t request_width = 0;

        auto period_start = std::chrono::steady_clock::now();
        while (true)
        {
            std::stringstream SStream;
            std::this_thread::sleep_for(std::chrono::seconds(1));
            if (counter % 10 == 0)
            {
                SStream << "req-name, resp-name, msg-total, throttled-total, rps, throttled-rps"<<std::endl;
            }
            counter++;

            auto resp_sent_till_last = resp_sent_till_now;
            auto resp_throttled_till_last = resp_throttled_till_now;

            auto total_req_received_till_last = total_req_received_till_now;
            auto total_resp_sent_till_last = total_resp_sent_till_now;
            auto total_resp_throttled_till_last = total_resp_throttled_till_now;

            total_req_received_till_now = std::accumulate(totalReqsReceived.begin(), totalReqsReceived.end(), 0);
            total_resp_sent_till_now = 0;
            total_resp_throttled_till_now = 0;

            for (size_t req_index = 0; req_index < config_schema.service.size(); req_index++)
            {
                for (size_t resp_index = 0; resp_index < config_schema.service[req_index].responses.size(); resp_index++)
                {
                    resp_sent_till_now[req_index][resp_index] =
                    std::accumulate(respStats[req_index][resp_index].begin(),
                                    respStats[req_index][resp_index].end(),
                                    0,
                                    [](uint64_t sum, const ResponseStatistics& val)
                                    {
                                        return sum + val.response_sent;
                                    }
                                    );
                    resp_throttled_till_now[req_index][resp_index] =
                    std::accumulate(respStats[req_index][resp_index].begin(),
                                    respStats[req_index][resp_index].end(),
                                    0,
                                    [](uint64_t sum, const ResponseStatistics& val)
                                    {
                                        return sum + val.response_throttled;
                                    }
                                    );
                    total_resp_sent_till_now += resp_sent_till_now[req_index][resp_index];
                    total_resp_throttled_till_now += resp_throttled_till_now[req_index][resp_index];
                }
            }

            auto delta_Req_Received = total_req_received_till_now - total_req_received_till_last;
            auto delta_Resp = total_resp_sent_till_now + total_resp_throttled_till_now - total_resp_sent_till_last - total_resp_throttled_till_last;
            if (!delta_Req_Received && !delta_Resp)
            {
                continue;
            }

            auto period_end = std::chrono::steady_clock::now();
            auto period_duration = std::chrono::duration_cast<std::chrono::milliseconds>(period_end - period_start).count();
            period_start = period_end;

            for (size_t req_index = 0; req_index < config_schema.service.size(); req_index++)
            {
                for (size_t resp_index = 0; resp_index < config_schema.service[req_index].responses.size(); resp_index++)
                {
                    SStream <<     std::setw(req_name_width) << config_schema.service[req_index].request.name
                            << "," << std::setw(resp_name_width) << config_schema.service[req_index].responses[resp_index].name
                            << "," << std::setw(req_name_width) << resp_sent_till_now[req_index][resp_index]
                            << "," << std::setw(req_name_width) << resp_throttled_till_now[req_index][resp_index]
                            << "," << std::setw(req_name_width) << ((resp_sent_till_now[req_index][resp_index] - resp_sent_till_last[req_index][resp_index])*std::milli::den)/period_duration
                            << "," << std::setw(req_name_width) << ((resp_throttled_till_now[req_index][resp_index] - resp_throttled_till_last[req_index][resp_index])*std::milli::den)/period_duration
                            <<std::endl;
                }
            }
            SStream <<     std::setw(req_name_width) << "SUM"
                    << "," << std::setw(resp_name_width) << "SUM"
                    << "," << std::setw(req_name_width) << total_resp_sent_till_now
                    << "," << std::setw(req_name_width) << total_resp_throttled_till_now
                    << "," << std::setw(req_name_width) << ((total_resp_sent_till_now - total_resp_sent_till_last)*std::milli::den)/period_duration
                    << "," << std::setw(req_name_width) << ((total_resp_throttled_till_now - total_resp_throttled_till_last)*std::milli::den)/period_duration
                    <<std::endl;
            std::cout<<SStream.str();

            SStream <<     std::setw(req_name_width) << "UNMATCHED"
                    << "," << std::setw(resp_name_width) << "---"
                    << "," << std::setw(req_name_width) << total_req_received_till_now - total_resp_sent_till_now - total_resp_throttled_till_now
                    << "," << std::setw(req_name_width) << "---"
                    << "," << std::setw(req_name_width) << ((delta_Req_Received - delta_Resp)*std::milli::den)/period_duration
                    << "," << std::setw(req_name_width) << "---"
                    <<std::endl;
            std::cout<<SStream.str();

            auto new_request_width = std::to_string(total_resp_sent_till_now).size();
            request_width = request_width > new_request_width ? request_width : new_request_width;
        }
    });

    if (config_schema.cert_file.size() && config_schema.private_key_file.size()) {
      if (config_schema.verbose)
      {
          std::cout<<"cert file: "<<config_schema.cert_file<<std::endl;
          std::cout<<"private key file: "<<config_schema.private_key_file<<std::endl;
      }
      boost::asio::ssl::context tls(boost::asio::ssl::context::sslv23);
      tls.use_private_key_file(config_schema.private_key_file, boost::asio::ssl::context::pem);
      tls.use_certificate_chain_file(config_schema.cert_file);
      if (config_schema.enable_mTLS)
      {
          if (config_schema.verbose)
          {
              std::cout<<"ca cert file: "<<config_schema.ca_cert_file<<std::endl;
          }
          if (config_schema.ca_cert_file.size())
          {
              tls.load_verify_file(config_schema.ca_cert_file);
          }
          else
          {
              std::cerr<<"mTLS enabled, but no CA cert file given, mTLS is thus disabled"<<std::endl;
              config_schema.enable_mTLS = false;
          }
      }

      configure_tls_context_easy(ec, tls, config_schema.enable_mTLS);

      if (server.listen_and_serve(ec, tls, addr, port)) {
        std::cerr << "error: " << ec.message() << std::endl;
      }
    } else {
      if (server.listen_and_serve(ec, addr, port)) {
        std::cerr << "error: " << ec.message() << std::endl;
      }
    }
  } catch (std::exception &e) {
    std::cerr << "exception: " << e.what() << "\n";
  }

  return 0;
}

ext: cc

max_stars_repo_name: wallyatgithub/maock

max_issues_repo_name: wallyatgithub/maock

max_forks_repo_name: wallyatgithub/maock


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "nt2 polynom toolbox - polyint/scalar Mode"

//////////////////////////////////////////////////////////////////////////////
// unit test behavior of polynomials components in scalar mode
//////////////////////////////////////////////////////////////////////////////
/// created  by jt the 06/03/2011
///
#include <nt2/include/functions/polyder.hpp>
#include <nt2/include/functions/polyint.hpp>
#include <nt2/include/functions/isequal.hpp>
#include <nt2/include/functions/ones.hpp>
#include <boost/type_traits/is_same.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/memory/buffer.hpp>
#include <nt2/include/constants/real.hpp>
#include <nt2/table.hpp>

#include <boost/array.hpp>

NT2_TEST_CASE_TPL ( polyint_real__1_0,  NT2_REAL_TYPES)
{

  using nt2::polyint;
  using nt2::tag::polyint_;
  nt2::table<T> a =  nt2::_(T(4), T(-1), T(1));
  nt2::table<T> c(nt2::of_size(1, 0));
  NT2_DISPLAY(polyint(a, T(1)));
  nt2::table<T> ia =  polyint(a, T(1));
  NT2_DISPLAY(polyint(c, T(1)));
  NT2_TEST(nt2::isequal(ia, nt2::ones(1,5, nt2::meta::as_<T>())));
} // end of test for floating_

ext: cpp


text:
//
// Copyright (c) 2012-2020 Kris Jusiak (kris at jusiak dot net)
//
// 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 <type_traits>
//->
#include <boost/di.hpp>

namespace di = boost::di;

class Greater;

template <class T = Greater>
struct example {
  using type = T;
};

struct hello {};

int main() {
  // clang-format off
  const auto injector = di::make_injector(
    di::bind<Greater>().to<hello>()
  );
  // clang-format on

  auto object = injector.create<example>();
  static_assert(std::is_same<hello, decltype(object)::type>{}, "");
}

max_stars_repo_name: szigetics/di

max_issues_repo_name: szigetics/di

max_forks_repo_name: szigetics/di


text: #include <boost/graph/distributed/depth_first_search.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
@copyright Louis Dionne 2014
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/foldable/mcd.hpp>

#include <boost/hana/detail/assert.hpp>
#include <boost/hana/detail/constexpr.hpp>
#include <boost/hana/detail/minimal/foldable.hpp>
#include <boost/hana/integral.hpp>

#include <tuple>
using namespace boost::hana;

BOOST_HANA_CONSTEXPR_LAMBDA auto f = [](auto ...xs) {
    return std::make_tuple(xs...);
};

template <typename mcd>
void test() {
    constexpr auto foldable = detail::minimal::foldable<mcd>;

    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(), f) == f());
    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(1), f) == f(1));
    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(1, '2'), f) == f(1, '2'));
    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(1, '2', 3.3), f) == f(1, '2', 3.3));
    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(1, '2', 3.3, nullptr), f) == f(1, '2', 3.3, nullptr));

    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(int_<0>), f) == f(int_<0>));
    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(int_<0>, int_<1>), f) == f(int_<0>, int_<1>));
    BOOST_HANA_CONSTEXPR_ASSERT(unpack(foldable(int_<0>, int_<1>, int_<2>), f) == f(int_<0>, int_<1>, int_<2>));
}

int main() {
    test<Foldable::mcd>();
    test<Foldable::unpack_mcd>();
}

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
#pragma once

#include <httplib/detail/common.hpp>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/optional.hpp>
#include <boost/utility/string_view.hpp>

#include <cstdlib>
#include <iostream>
#include <map>
#include <string>

HTTPLIB_OPEN_NAMESPACE

namespace detail {

    struct ilexicographical_less_t {
        struct is_transparent;

        template<class One, class Another>
        bool operator()(const One &one, const Another &another) const {
            return boost::algorithm::ilexicographical_compare(one, another);
        }
    };

} // namespace detail

class http_headers_t {
public:
    using header_name_t = std::string;
    using header_value_t = std::string;
    using header_values_t = boost::container::small_vector<header_value_t, 3>;

private:
    using container_t = std::map<header_name_t, header_values_t, detail::ilexicographical_less_t>;

public:
    using const_iterator = container_t::const_iterator;
    using const_reverse_iterator = container_t::const_reverse_iterator;

public:
    http_headers_t() :
        m_size(0)
    { }

    template<class It>
    http_headers_t(It begin, It end) :
        http_headers_t()
    {
        for (; begin != end; ++begin) {
            add_header_values(begin->first, begin->second);
        }
    }

    http_headers_t(std::initializer_list<container_t::value_type> list) :
        http_headers_t(list.begin(), list.end())
    { }

    http_headers_t(const http_headers_t &) = default;
    http_headers_t(http_headers_t &&) = default;

    http_headers_t &operator=(const http_headers_t &) = default;
    http_headers_t &operator=(http_headers_t &&) = default;

    bool empty() const {
        return size() == 0;
    }

    size_t size() const {
        return m_size;
    }

    const_iterator begin() const {
        return m_headers.begin();
    }

    const_iterator end() const {
        return m_headers.end();
    }

    const_iterator find(boost::string_view name) const {
        return m_headers.find(name);
    }

    bool has(boost::string_view name) const {
        return static_cast<bool>(get_header_values(name));
    }

    boost::optional<const header_value_t &> get_header(boost::string_view name) const;
    boost::optional<const header_values_t &> get_header_values(boost::string_view name) const;

    void set_header(boost::string_view name, const header_values_t &values);
    void add_header_values(boost::string_view name, const header_values_t &values);
    void remove_header(boost::string_view name);

private:
    size_t m_size;
    container_t m_headers;
};

std::ostream &operator<<(std::ostream &stream, const http_headers_t &headers);

HTTPLIB_CLOSE_NAMESPACE


text:
/*
Header files to implement linear models
X: mat type with shape (M, N), a dataset consisting of 'M' examples each of dimension of 'N'
y: mat type with shape (M, K), the targets for each of the 'M' examples in 'X', where each target has dimension `K`

1. Linear Regression
To apply Ordinary Least Squares with normal equation with formula:
\mathbf{theta}= \left(\mathbf{X}^\top \mathbf{X}\right)^{-1} \mathbf{X}^\top \mathbf{y}

2. Ridge Regression
To apply Ridge regression with normal equation:
 \mathbf{theta} \left(\mathbf{X}^\top \mathbf{X} +
 \lambda \mathbf{I} \right)^{-1}\mathbf{X}^\top \mathbf{y}

where alpha is the paramater for L2 regulization, a greater value has a larger penalty

3. Logistic Regression
To minimize the following loss function:

- \log (\mathcal{L}(\mathbf{theta})) = -\frac{1}{M} \left[
        \left(
            \sum_{i=0}^M \y^((i)) \log(\h_theta(x^((i)))) +
                (1-y^((i))) \log(1-\h_theta(x^((i))))
        \right) - R(\mathbf{theta}, \lambda)
    \right]

Where:
R(mathbf{theta}, lambda) = {(lambda/2||\mathbf{theta}||_2^2\ :\ "penalty" = 'l2'),
(lambda||\mathbf{theta}||_1:\ "penalty" = 'l1'):}

is a regularization penalty, '\lambda' is a regularization weight, 'M' is the number of examples in y
fit with gradient descent algo

*/
#include <iostream>
#include <armadillo>
using namespace std;
using namespace arma;

#ifndef LinearModels_HPP
#define LinearModels_HPP

class LinearRegression {
private:
    //  Whether to fit intercept, with default value true
    bool fit_intercept;

public:
    //  a vector to store coefficents of the results with defult shape of 100 X 1
    vec theta;

    //  constructors
    LinearRegression();
    LinearRegression(bool fit_intercept1);
    LinearRegression(const LinearRegression& source);
    ~LinearRegression();

    //  Assignment operator
    LinearRegression& operator = (const LinearRegression& source);

    //  functions
    const void fit(mat X, const mat& y);   // fit function to calculate the results and store to theta
    const mat predict(mat X);   // return predicted values with trained model
};

class RidgeRegression {
private:
    //  Whether to fit intercept, with default value true
    bool fit_intercept;
    //  Regulation paramater
    double lambda;

public:
    //  a vector to store coefficents of the results with defult shape of 100 X 1
    vec theta;

    //  constructors
    RidgeRegression();
    RidgeRegression(double lambda1, bool fit_intercept1=true);
    RidgeRegression(const RidgeRegression& source);
    ~RidgeRegression();

    //  Assignment operator
    RidgeRegression& operator = (const RidgeRegression& source);

    //  functions
    const void fit(mat X, const mat& y);    // fit function to calculate the results and store to theta
    const mat predict(mat X);   // return predicted values with trained model
};

//  Logistic regression with gradient descent optimizer
class LogisticRegression {
private:
    //  regularization paramater
    double lambda;
    //  regularization type with l2 as default/
    string penalty;
    //  Whether to fit intercept, with default value true
    bool fit_intercept;

public:
    //  a vector to store coefficents of the results with defult shape of 100 X 1
    vec theta;
    //  constructors
    LogisticRegression();
    LogisticRegression(double lambda1 = 0, bool fit_intercept1 = true, string penalty = "l2");
    LogisticRegression(const LogisticRegression& source);
    ~LogisticRegression();

    //  Assignment operator
    LogisticRegression& operator = (const LogisticRegression& source);

    //  functions
    // fit function to calculate the results and store to theta. Apply gradient descent algo to minimize loss function
    const void fit(mat X, const mat& y, double lr = 0.01, double tol = 1e-7, long max_iter = 1e7);
    const mat predict(mat X);   // return predicted values with trained model
    double _NLL(const mat& X, const mat& y, const mat& y_pred); // supplemental function to calculate negative log likelihood under current model
    vec _NLL_grad(const mat& X, const mat& y, const mat& y_pred); // supplemental function to calculate Gradient of the penalized negative log likelihood wrt theta
};

//  supplemental functions

//The logistic sigmoid function
mat sigmoid(const mat& X);
#endif;

max_stars_repo_path: Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.hpp


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

#include "../common.hpp"

using namespace std;

map<int, long> mem;

long dfs(const vector<int> & adapters, int root) {
    assert(root >= 0 && root < adapters.size());

    if (root == adapters.size() - 1) {
        return 1;
    }

    long counts = 0;
    for (int i = root + 1; i < adapters.size(); i++) {
        // Gone too far
        if (adapters[root] + 3 < adapters[i]) {
            break;
        }

        if (mem.find(adapters[i]) != mem.end()) {
            counts += mem[adapters[i]];
        } else {
            counts += dfs(adapters, i);
        }
    }
    return mem[adapters[root]] = counts;
}

int main() {
    ifstream file ("2020/10.txt");
    if (!file.is_open()) {
        cout << "Failed to open file: " << strerror(errno) << endl;
        return -1;
    }

    int answer1 = 0;
    long answer2 = 0;

    vector<int> adapters;
    string line;
    while (getline(file, line, '\n')) {
        boost::trim(line);
        if (line == "") {
            continue;
        }

        adapters.push_back(stoi(line));
    }

    adapters.push_back(0);
    sort(adapters.begin(), adapters.end());
    adapters.push_back(adapters[adapters.size() - 1] + 3);

    map<int, int> diffs;
    for (int i = 1; i < adapters.size(); i++) {
        int diff = adapters[i] - adapters[i-1];

        diffs[diff]++;
    }

    answer1 = diffs[1] * diffs[3];
    answer2 = dfs(adapters, 0);

    cout << "Answer 10.1: " << answer1 << endl;
    cout << "Answer 10.2: " << answer2 << endl;

    file.close();
}

max_stars_repo_name: bramp/aoc

max_issues_repo_name: bramp/aoc

max_forks_repo_name: bramp/aoc


text:
#pragma once

#include "SMT_Graph.hpp"
#include "SMT_Tag_Mapping.hpp"
#include <boost/utility/enable_if.hpp>
#include <boost/foreach.hpp>
#include <boost/dynamic_bitset.hpp>

#include <ostream>
#include <set>

namespace metaSMT {

  namespace predtags = ::metaSMT::logic::tag;
  namespace bvtags = ::metaSMT::logic::QF_BV::tag;
  namespace arraytags = ::metaSMT::logic::Array::tag;
  namespace mpl = boost::mpl;

  void print_SMT_Expression(std::ostream &outfile,
                            SMT_Graph const &g,
                            SMT_Expression const &v);

  struct Vertex_Printer : public boost::static_visitor<void> {
  public:
    Vertex_Printer(std::ostream &outfile,
                   SMT_Graph const &g,
                   SMT_Expression const &v)
      : outfile_(outfile),
        g_(g), v_(v)
    {}

    inline void operator()(bvtags::zero_extend_tag const &tag) const {
      boost::any arg = boost::get(boost::vertex_arg, g_, v_);
      unsigned long width = boost::any_cast<unsigned long>(arg);
      outfile_ << "(zero_extend[" << width << "] ";
      BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
        print_SMT_Expression(outfile_, g_, target(e, g_));
      }
      outfile_ << ')';
    }

    inline void operator()(bvtags::bvbin_tag const &tag) const {
      boost::any arg = boost::get(boost::vertex_arg, g_, v_);
      std::string bin_const = boost::any_cast<std::string>(arg);
      outfile_ << "(bvbin" << bin_const << ")";
    }

    inline void operator()(bvtags::bvhex_tag const &tag) const {
      boost::any arg = boost::get(boost::vertex_arg, g_, v_);
      std::string hex_const = boost::any_cast<std::string>(arg);
      outfile_ << "(bvhex" << hex_const << ")";
    }

    inline void operator()(bvtags::bvsint_tag const &tag) const {
      typedef boost::tuple<long, unsigned long> tuple_type;
      boost::any arg = boost::get(boost::vertex_arg, g_, v_);
      tuple_type const tuple = boost::any_cast<tuple_type>(arg);
      unsigned long const width = tuple.get<1>();
      boost::dynamic_bitset<> bv(width, tuple.get<0>());
      std::string s; to_string(bv, s);
      outfile_ << "(bvbin" << s << ")";
    }

    inline void operator()(bvtags::bvuint_tag const &tag) const {
      typedef boost::tuple<unsigned long, unsigned long> tuple_type;
      boost::any arg = boost::get(boost::vertex_arg, g_, v_);
      tuple_type tuple = boost::any_cast<tuple_type>(arg);
      outfile_ << "(bv" << tuple.get<0>() << "[" << tuple.get<1>() << "])";
    }

    inline void operator()(bvtags::extract_tag const &tag) const {
      typedef boost::tuple<unsigned long, unsigned long> tuple_type;
      boost::any arg = boost::get(boost::vertex_arg, g_, v_);
      tuple_type tuple = boost::any_cast<tuple_type>(arg);
      outfile_ << "(extract[" << tuple.get<0>() << ':' << tuple.get<1>() << "] ";
      BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
        print_SMT_Expression(outfile_, g_, target(e, g_));
      }
      outfile_ << ")";
    }

    inline void operator()(predtags::nequal_tag const &tag) const {
      outfile_ << "(not (=";
      BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
        print_SMT_Expression(outfile_, g_, target(e, g_));
      }
      outfile_ << "))";
    }

    inline void operator()(predtags::distinct_tag const &tag) const {
      outfile_ << "(distinct ";
      BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
        print_SMT_Expression(outfile_, g_, target(e, g_));
      }
      outfile_ << ")";
    }

    inline void operator()(predtags::nand_tag const &tag) const {
      outfile_ << "(not (and";
      BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
        print_SMT_Expression(outfile_, g_, target(e, g_));
      }
      outfile_ << "))";
    }

    inline void operator()(predtags::nor_tag const &tag) const {
      outfile_ << "(not (or";
      BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
        print_SMT_Expression(outfile_, g_, target(e, g_));
      }
      outfile_ << "))";
    }

    inline void operator()(predtags::xnor_tag const &tag) const {
      outfile_ << "(not (xor";
      BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
        print_SMT_Expression(outfile_, g_, target(e, g_));
      }
      outfile_ << "))";
    }

    inline void operator()(predtags::var_tag const &tag) const {
      outfile_ << "p_" << tag.id;
    }

    inline void operator()(bvtags::var_tag const &tag) const {
      outfile_ << "bitv_" << tag.id;
    }

    inline void operator()(arraytags::array_var_tag const &tag) const {
      outfile_ << "array_" << tag.id;
    }

    template <typename T>
    inline typename boost::enable_if<
      typename mpl::has_key< SMT_NameMap, T>::type
    >::type
    operator()(T const &t) const {
      typedef typename mpl::at< SMT_NameMap, T >::type name;

      if (out_degree(v_, g_) != 0) {
        outfile_ << '(' << mpl::c_str<name>::value;
        BOOST_FOREACH (SMT_Edge e, out_edges(v_, g_)) {
          outfile_ << ' ';
          print_SMT_Expression(outfile_, g_, target(e, g_));
        }
        outfile_ << ')';
      } else {
        outfile_ << mpl::c_str<name>::value;
      }
    }

    template <typename T>
    inline typename boost::disable_if<
      typename mpl::has_key< SMT_NameMap, T>::type
    >::type
    operator()(T const &t) const {
      outfile_ << "(MISSING " << t <<")";
    }

  private:
    std::ostream &outfile_;
    SMT_Graph const &g_;
    SMT_Expression const &v_;
  };

  inline void print_SMT_Expression(std::ostream & outfile,
                                   SMT_Graph const &g,
                                   SMT_Expression const &v) {
    outfile << ' ';
    metaSMT::Tag tag = boost::get(boost::vertex_tag, g, v);
    boost::apply_visitor(Vertex_Printer(outfile, g, v), tag);
  }

  struct SMT_Declaration_Printer : public boost::static_visitor<void> {
    SMT_Declaration_Printer(std::ostream &outfile,
                            SMT_Graph const &g,
                            SMT_Expression const &v)
      : outfile_(outfile),
        g_(g), v_(v)
    {}

    inline void operator()(predtags::var_tag const &tag) const {
      outfile_ << " :extrapreds ((" << "p_" << tag.id << "))\n";
    }

    inline void operator()(bvtags::var_tag const &tag) const {
      outfile_ << " :extrafuns ((" << "bitv_" << tag.id
               << " BitVec[" << tag.width << "]))\n";
    }

    inline void operator()(arraytags::array_var_tag const &tag) const {
      outfile_ << " :extrafuns ((" << "array_" << tag.id
               << " Array[" << tag.index_width << ':' << tag.elem_width << "]))\n";
    }

    template <typename T>
    inline void operator()(T const &t) const
    {}

  private:
    std::ostream &outfile_;
    SMT_Graph const &g_;
    SMT_Expression const &v_;
  };

  inline void write_smt(std::ostream & outfile,
                        SMT_Graph const & g,
                        std::vector<SMT_Expression> const &assertions) {
    outfile
      << "(benchmark metaSMT.smt\n"
      << " :source { Generated by metaSMT }\n"
      << " :status unknown\n"
      << " :difficulty unknown\n"
      << " :logic QF_BV\n"
    ;

    BOOST_FOREACH (SMT_Expression v, vertices(g)) {
      metaSMT::Tag tag = boost::get(boost::vertex_tag, g, v);
      boost::apply_visitor(SMT_Declaration_Printer(outfile, g, v), tag);
    }

    BOOST_FOREACH (SMT_Expression v, assertions) {
      outfile << " :assumption ";
      print_SMT_Expression(outfile, g, v);
      outfile << '\n'; // assertion
    }

    // outfile << " :formula true\n";

    outfile << ")\n"; // benchmark
  }
}

max_stars_repo_name: finnhaedicke/metaSMT

max_issues_repo_name: finnhaedicke/metaSMT

max_forks_repo_name: finnhaedicke/metaSMT


text:
#if !defined ATTOTEST_INCLUDED_
#define      ATTOTEST_INCLUDED_

#include <string>
#include <type_traits>
#include <functional>
#include <sstream>
#include <boost/fusion/include/is_sequence.hpp>
#include <boost/fusion/include/fold.hpp>
#include <boost/preprocessor/cat.hpp>

#define ATTOTEST_CASE(name) ATTOTEST_CASE_I(name, BOOST_PP_CAT(attotest_test, name))
#define ATTOTEST_CASE_I(name, type) \
    struct type { \
        static int init() { \
            attotest::add_test(test, ATTOTEST_TO_STR(name)); \
            return 0; \
        } \
        static int x; \
        static void test(); \
    }; \
    int type::x = type::init(); \
    void type::test()

#define ATTOTEST_CASE_PARAM(name, ...) ATTOTEST_CASE_PARAM_I(name, BOOST_PP_CAT(attotest_testcase, name), BOOST_PP_CAT(attotest_testfun, name), ATTOTEST_GET_COUNTER(__LINE__)::value, name(__VA_ARGS__))
#define ATTOTEST_CASE_PARAM_I(name, type, testfun, counter, call) \
    template<std::size_t, std::size_t> struct type; \
    template<> struct type<__LINE__, counter> { \
        static int init() { \
            attotest::add_test(testfun, ATTOTEST_TO_STR(call)); \
            return 0; \
        } \
        static int x; \
        static void testfun(); \
    }; \
    int type<__LINE__, counter>::x = type::init(); \
    void type<__LINE__, counter>::testfun() { \
        call; \
    } \
    ATTOTEST_INC_COUNTER(__LINE__)

#define ATTOTEST_ASSERT_BASE(expr, msg) \
    attotest::assert_(expr, __FILE__, __LINE__, [&] { return msg; })

#define ATTOTEST_ASSERT_BINARY_OP(op, x, y) \
    ATTOTEST_ASSERT_BASE(x op y, ATTOTEST_TO_STR(x op y) " | " + ATTOTEST_SHOW(x) + ", " + ATTOTEST_SHOW(y))

#define ATTOTEST_ASSERT_BINARY_FUN(f, x, y) \
    ATTOTEST_ASSERT_BASE(f(x, y), ATTOTEST_TO_STR(f(x, y)) " | " + ATTOTEST_SHOW(x) + ", " + ATTOTEST_SHOW(y))

#define ATTOTEST_ASSERT(x) ATTOTEST_ASSERT_BASE(bool(x), "expected true | " + ATTOTEST_SHOW(x))
#define ATTOTEST_ASSERT_NOT(x) ATTOTEST_ASSERT_BASE(!bool(x), "expected false | " + ATTOTEST_SHOW(x))
#define ATTOTEST_ASSERT_EQUAL(x, y) ATTOTEST_ASSERT_BINARY_OP(==, x, y)
#define ATTOTEST_ASSERT_NOT_EQUAL(x, y) ATTOTEST_ASSERT_BINARY_OP(!=, x, y)
#define ATTOTEST_ASSERT_FAIL() ATTOTEST_ASSERT_BASE(false, "reached to failure code path")

#define ATTOTEST_SHOW(expr) (ATTOTEST_TO_STR(expr) ": " + attotest::to_string_(expr))

#define ATTOTEST_TO_STR(...) ATTOTEST_TO_STR_I(__VA_ARGS__)
#define ATTOTEST_TO_STR_I(...) # __VA_ARGS__

#define ATTOTEST_REQUIRE(...) \
    typename = typename std::enable_if<(__VA_ARGS__)>::type

namespace attotest {
namespace here = ::attotest;

using boost::fusion::traits::is_sequence;

void add_test(void(*)(), char const *);
void assert_(bool cond, std::string const & file, std::size_t line, std::function<std::string()> msg);

template<std::size_t N>
using size_t = std::integral_constant<std::size_t, N>;

#define ATTOTEST_GET_COUNTER(id) decltype(attotest_counter(attotest::size_t<id>{}, attotest::max_count{}))
#define ATTOTEST_INC_COUNTER(id) attotest::succ<ATTOTEST_GET_COUNTER(id)> attotest_counter(attotest::size_t<id>, attotest::succ<ATTOTEST_GET_COUNTER(id)>)

template<std::size_t N>
struct count : count<N-1> {
    static constexpr std::size_t value = N;
};
template<>
struct count<0> {
    static constexpr std::size_t value = 0;
};

using max_count = count<256>;

template<typename N>
using succ = count<N::value+1>;

namespace traits {
template<typename T, typename Enable = void> struct to_string : std::false_type {};
}

template<typename T> struct sfinae_test : decltype(T::test(0)) {};

template<typename T>
struct has_begin_end_test {
    template<typename U = T>
    static auto test(int, U * p = nullptr) -> decltype(std::begin(*p), (void)0, std::end(*p), (void)0, std::true_type{});
    static auto test(...) -> std::false_type;
};
template<typename T> using has_begin_end = sfinae_test<has_begin_end_test<T>>;

template<typename T>
struct has_adl_begin_end_test {
    template<typename U = T>
    static auto test(int, U * p = nullptr) -> decltype(begin(*p), (void)0, end(*p), (void)0, std::true_type{});
    static auto test(...) -> std::false_type;
};

template<typename T> using has_adl_begin_end = sfinae_test<has_adl_begin_end_test<T>>;

template<typename T>
struct has_to_string_test {
    template<typename U = T>
    static auto test(int, U * p = nullptr) -> decltype(p->to_string(), (void)0, std::true_type{});
    static auto test(...) -> std::false_type;
};
template<typename T> using has_to_string = sfinae_test<has_to_string_test<T>>;
template<typename T>
struct has_adl_to_string_test {
    template<typename U = T>
    static auto test(int, U * p = nullptr) -> decltype(to_string(*p), (void)0, std::true_type{});
    static auto test(...) -> std::false_type;
};
template<typename T> using has_adl_to_string = sfinae_test<has_adl_to_string_test<T>>;

template<typename T>
struct is_output_streamable_test {
    template<typename U = T>
    static auto test(int, std::ostream * o = nullptr, U const * p = nullptr) -> decltype(*o << *p, (void)0, std::true_type{});
    static auto test(...) -> std::false_type;
};
template<typename T> using is_output_streamable = sfinae_test<is_output_streamable_test<T>>;

std::string to_string_(int);
std::string to_string_(unsigned int);
std::string to_string_(long);
std::string to_string_(unsigned long);
std::string to_string_(long long);
std::string to_string_(unsigned long long);
std::string to_string_(double);
std::string to_string_(bool);
std::string to_string_(std::string const &);
std::string to_string_(std::string &&);
std::string to_string_(char const *);
template<typename ...Elems>
std::string to_string_(std::tuple<Elems...> const &);
template<typename T, typename U>
std::string to_string_(std::pair<T, U> const &);
template<typename T>
std::string to_string_(T const &);

template<typename T, ATTOTEST_REQUIRE(traits::to_string<T>::value)>
std::string to_string_traits(T const & x);
template<typename T, ATTOTEST_REQUIRE(!traits::to_string<T>::value), typename = void>
std::string to_string_traits(T const & x);

template<typename T, ATTOTEST_REQUIRE(is_output_streamable<T>::value)>
std::string to_string_ostream(T const &);
template<typename T, ATTOTEST_REQUIRE(!is_output_streamable<T>::value), typename = void>
std::string to_string_ostream(T const &);

template<typename T, ATTOTEST_REQUIRE(has_to_string<T>::value)>
std::string to_string_memfun(T const &);
template<typename T, ATTOTEST_REQUIRE(!has_to_string<T>::value), typename = void>
std::string to_string_memfun(T const &);

template<typename T, ATTOTEST_REQUIRE(has_adl_to_string<T>::value)>
std::string to_string_adl(T const &);
template<typename T, ATTOTEST_REQUIRE(!has_adl_to_string<T>::value), typename = void>
std::string to_string_adl(T const &);

template<typename Range, ATTOTEST_REQUIRE((has_begin_end<Range>::value || has_adl_begin_end<Range>::value) && !is_sequence<Range>::value)>
std::string to_string_range(Range const &);
template<typename T, ATTOTEST_REQUIRE(!(has_begin_end<T>::value || has_adl_begin_end<T>::value) || is_sequence<T>::value), typename = void>
std::string to_string_range(T const &);

template<typename Seq, ATTOTEST_REQUIRE(is_sequence<Seq>::value)>
std::string to_string_fuseq(Seq const & x);
template<typename T, ATTOTEST_REQUIRE(!is_sequence<T>::value), typename = void>
std::string to_string_fuseq(T const & x);

std::string to_string_fallback();

template<typename Tuple, typename Index, typename Size, ATTOTEST_REQUIRE(!Index::value && Index::value < Size::value)>
std::string to_string_tuple(std::string &&, Tuple const &, Index, Size);
template<typename Tuple, typename Index, typename Size, ATTOTEST_REQUIRE(Index::value && Index::value < Size::value), typename = void>
std::string to_string_tuple(std::string &&, Tuple const &, Index, Size);
template<typename Tuple, typename Index, typename Size, ATTOTEST_REQUIRE(!(Index::value < Size::value)), typename = void, typename = void>
std::string to_string_tuple(std::string &&, Tuple const &, Index, Size);

template<typename ...Elems>
std::string to_string_(std::tuple<Elems...> const & tup) {
    return here::to_string_tuple("(", tup, here::size_t<0>{}, std::tuple_size<std::tuple<Elems...>>{});
}
template<typename T, typename U>
std::string to_string_(std::pair<T, U> const & p) {
    return here::to_string_tuple("(", p, here::size_t<0>{}, std::tuple_size<std::pair<T, U>>{});
}
template<typename T>
std::string to_string_(T const & x) {
    return here::to_string_traits(x);
}

template<typename T, typename>
std::string to_string_traits(T const & x) {
    return traits::to_string<T>()(x);
}
template<typename T, typename, typename>
std::string to_string_traits(T const & x) {
    return here::to_string_ostream(x);
}

template<typename T, typename>
std::string to_string_ostream(T const & x) {
    std::ostringstream oss;
    oss << x;
    return oss.str();
}
template<typename T, typename, typename>
std::string to_string_ostream(T const & x) {
    return here::to_string_memfun(x);
}

template<typename T, typename>
std::string to_string_memfun(T const & x) {
    return x.to_string();
}
template<typename T, typename, typename>
std::string to_string_memfun(T const & x) {
    return here::to_string_range(x);
}

template<typename Range, typename>
std::string to_string_range(Range const & range) {
    std::string str("[");
    bool trailing = false;
    for (auto e : range) {
        if (trailing) str += ", ";
        trailing = true;
        str += here::to_string_(e);
    }
    return str + "]";
}
template<typename T, typename, typename>
std::string to_string_range(T const & x) {
    return here::to_string_fuseq(x);
}

struct to_string_fuseq_t {
    typedef std::string result_type;
    template<typename T>
    std::string operator()(std::true_type, T const & x) const {
        return "(" + here::to_string_(x);
    }
    template<typename T>
    std::string operator()(std::string const & str, T const & x) const {
        return str + ", " + here::to_string_(x);
    }
};
template<typename Seq, typename>
std::string to_string_fuseq(Seq const & x) {
    return boost::fusion::fold(x, std::true_type{}, to_string_fuseq_t()) + ")";
}
template<typename T, typename, typename>
std::string to_string_fuseq(T const & x) {
    return here::to_string_adl(x);
}

template<typename T, typename>
std::string to_string_adl(T const & x) {
    return to_string(x);
}
template<typename T, typename, typename>
std::string to_string_adl(T const &) {
    return to_string_fallback();
}

template<typename Tuple, typename Index, typename Size, typename>
std::string to_string_tuple(std::string && str, Tuple const & tup, Index, Size size) {
    return here::to_string_tuple(str + here::to_string_(std::get<Index::value>(tup)),
                                 tup,
                                 here::size_t<Index::value+1>{},
                                 size);
}
template<typename Tuple, typename Index, typename Size, typename, typename>
std::string to_string_tuple(std::string && str, Tuple const & tup, Index, Size size) {
    return here::to_string_tuple(str + ", " + here::to_string_(std::get<Index::value>(tup)),
                                 tup,
                                 here::size_t<Index::value+1>{},
                                 size);
}
template<typename Tuple, typename Index, typename Size, typename, typename, typename>
std::string to_string_tuple(std::string && str, Tuple const &, Index, Size) {
    return str + ")";
}

}

template<std::size_t N>
attotest::count<0> attotest_counter(attotest::size_t<N>, attotest::count<0> const &);

#endif

max_stars_repo_name: dechimal/desalt

max_issues_repo_name: dechimal/desalt

max_forks_repo_name: dechimal/desalt


text:
#include "moja/flint/operationmanagerublas.h"

#include "moja/flint/flintexceptions.h"
#include "moja/flint/imodule.h"
#include "moja/flint/ioperationresult.h"
#include "moja/flint/ioperationresultflux.h"
#include "moja/flint/operationproportionalublas.h"
#include "moja/flint/operationresultcollection.h"
#include "moja/flint/operationstockublas.h"
#include "moja/flint/poolublas.h"
#include "moja/flint/timing.h"

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

namespace moja {
namespace flint {

OperationManagerUblas::OperationManagerUblas(Timing& timing, const DynamicObject& config)
    : _timing(timing), _poolCount(0) {
   _poolValues = moja_ublas_vector(100);

   _useKahan = false;
   _allowZeroResultTransfers = false;

   if (config.find("use_kahan") != config.end()) {
      _useKahan = config["use_kahan"];
      if (_useKahan) _corrections.reserve(100);
   }
   if (config.find("allow_zero_result_transfers") != config.end()) {
      _allowZeroResultTransfers = config["allow_zero_result_transfers"];
   }
}

std::shared_ptr<IOperation> OperationManagerUblas::createStockOperation(IModule& module) {
   return std::make_shared<StockOperationUblas>(this, _poolValues, _timing.fractionOfStep(),
                                                /*_I, */ &module.metaData());
}

std::shared_ptr<IOperation> OperationManagerUblas::createStockOperation(IModule& module, DynamicVar& dataPackage) {
   return std::make_shared<StockOperationUblas>(this, _poolValues, _timing.fractionOfStep(),
                                                /*_I, */ &module.metaData(), dataPackage);
}

std::shared_ptr<IOperation> OperationManagerUblas::createProportionalOperation(IModule& module) {
   return std::make_shared<ProportionalOperationUblas>(this, _poolValues, _timing.fractionOfStep(),
                                                       /*_I, */ &module.metaData());
}

std::shared_ptr<IOperation> OperationManagerUblas::createProportionalOperation(IModule& module,
                                                                               DynamicVar& dataPackage) {
   return std::make_shared<ProportionalOperationUblas>(this, _poolValues, _timing.fractionOfStep(),
                                                       /*_I, */ &module.metaData(), dataPackage);
}

void OperationManagerUblas::applyOperations() {
   if (_useKahan) {  // used for https://en.wikipedia.org/wiki/Kahan_summation_algorithm
      double y;
      double t;

      for (auto& operationResult : _operationResultsPending) {
         auto fluxes = operationResult->operationResultFluxCollection();
         for (auto flux : fluxes) {
            auto srcIx = flux->source();
            auto dstIx = flux->sink();
            if (srcIx == dstIx) {
               // don't process transfers to same pool
               continue;
            }
            auto val = flux->value();

            // Do source
            y = -val - _corrections[srcIx];
            t = _poolValues[srcIx] + y;
            _corrections[srcIx] = (t - _poolValues[srcIx]) - y;
            _poolValues[srcIx] = t;

            // Do sink
            y = val - _corrections[dstIx];
            t = _poolValues[dstIx] + y;
            _corrections[dstIx] = (t - _poolValues[dstIx]) - y;
            _poolValues[dstIx] = t;
         }
      }
   } else {
      for (auto& operationResult : _operationResultsPending) {
         auto fluxes = operationResult->operationResultFluxCollection();
         for (auto flux : fluxes) {
            auto srcIx = flux->source();
            auto dstIx = flux->sink();
            if (srcIx == dstIx) continue;  // don't process transfers to same pool
            auto val = flux->value();
            _poolValues[srcIx] -= val;
            _poolValues[dstIx] += val;
         }
      }
   }
   commitPendingOperationResults();
}

void OperationManagerUblas::clearAllOperationResults() {
   _operationResultsPending.clear();
   _operationResultsLastApplied.clear();
   _operationResultsCommitted.clear();
}

void OperationManagerUblas::clearLastAppliedOperationResults() { _operationResultsLastApplied.clear(); }

const OperationResultCollection& OperationManagerUblas::operationResultsPending() const {
   return _operationResultsPending;
}

const OperationResultCollection& OperationManagerUblas::operationResultsLastApplied() const {
   return _operationResultsLastApplied;
}

const OperationResultCollection& OperationManagerUblas::operationResultsCommitted() const {
   return _operationResultsCommitted;
}

PoolCollection OperationManagerUblas::poolCollection() {
   return PoolCollection(_poolObjects);
   // return _poolObjects;
}

void OperationManagerUblas::initialisePools() {
   if (_useKahan) std::fill(_corrections.begin(), _corrections.end(), 0.0);

   for (auto& pool : _poolObjects) {
      pool->init();
   }
}

const IPool* OperationManagerUblas::addPool(const std::string& name, double initValue) {
   return addPool(name, "", "", 1.0, 0, initValue);
}

const IPool* OperationManagerUblas::addPool(const std::string& name, const std::string& description,
                                            const std::string& units, double scale, int order, double initValue) {
   if (name.length() == 0 || all(name, boost::algorithm::is_space())) {
      throw std::invalid_argument("name cannot be empty");
   }
   if (initValue < 0.0) {
      throw std::invalid_argument("initValue cannot be less than 0.0");  // TODO: check this is true?
   }
   _poolValues.resize(++_poolCount);

   if (_useKahan) {
      _corrections.resize(_poolValues.size());
      _corrections[_poolValues.size() - 1] = 0.0;
   }

   auto pool =
       std::make_shared<PoolUblas>(_poolValues, name, description, units, scale, order, _poolCount - 1, initValue);
   _poolObjects.push_back(pool);
   _poolNameObjectMap[name] = pool;

   return pool.get();
}

const IPool* OperationManagerUblas::addPool(PoolMetaData& metadata, double initValue) {
   // TODO: finish this
   return nullptr;
}

const IPool* OperationManagerUblas::getPool(const std::string& name) const {
   try {
      auto r = _poolNameObjectMap.at(name);
      return r.get();
   } catch (...) {
      throw PoolNotFoundException() << PoolName(name);
   }
}

const IPool* OperationManagerUblas::getPool(int index) const {
   if (index >= _poolObjects.size() || index < 0) throw PoolNotFoundException() << PoolName("Bad index");
   auto& r = _poolObjects[index];
   return r.get();
}

std::string OperationManagerUblas::config() const {
   std::stringstream ss;
   ss << "("
      << "Kahan[" << (_useKahan ? "ON" : "OFF") << "], "
      << "ZeroTransfers[" << (_allowZeroResultTransfers ? "ON" : "OFF") << "]"
      << ")";
   return ss.str();
}

void OperationManagerUblas::commitPendingOperationResults() {
   std::copy(_operationResultsPending.begin(), _operationResultsPending.end(),
             std::back_inserter(_operationResultsLastApplied));
   std::move(_operationResultsPending.begin(), _operationResultsPending.end(),
             std::back_inserter(_operationResultsCommitted));
   _operationResultsPending.clear();
}

void OperationManagerUblas::submitOperation(IOperation* operation) {
   auto result = operation->computeOperation(_timing);
   if (result != nullptr) _operationResultsPending.push_back(result);
}

bool OperationManagerUblas::hasOperationResultsLastApplied() const { return !_operationResultsLastApplied.empty(); }
}  // namespace flint
}  // namespace moja

max_stars_repo_name: moja-global/flint

max_issues_repo_name: moja-global/flint

max_forks_repo_name: moja-global/flint


text:
//==================================================================================================
/*!
    @file

    @Copyright 2016 Numscale SAS

    Distributed under the Boost Software License, Version 1.0.
    (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_X86_SSE4_1_SIMD_FUNCTION_IF_ELSE_HPP_INCLUDED
#define BOOST_SIMD_ARCH_X86_SSE4_1_SIMD_FUNCTION_IF_ELSE_HPP_INCLUDED

#include <boost/simd/detail/overload.hpp>
#include <boost/simd/function/bitwise_cast.hpp>
#include <boost/simd/function/genmask.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd =  boost::dispatch;
  namespace bs =  boost::simd;

  BOOST_DISPATCH_OVERLOAD ( if_else_
                          , (typename A0, typename A1)
                          , bs::sse4_1_
                          , bs::pack_<bs::logical_<A0>, bs::sse_>
                          , bs::pack_<bd::single_<A1>, bs::sse_>
                          , bs::pack_<bd::single_<A1>, bs::sse_>
                         )
  {
    BOOST_FORCEINLINE A1 operator() ( const A0 & a0
                                    , const A1 & a1
                                    , const A1 & a2) const BOOST_NOEXCEPT
    {
      return _mm_blendv_ps(a2, a1, bitwise_cast<A1>(genmask(a0)));
    }
  };

  BOOST_DISPATCH_OVERLOAD ( if_else_
                          , (typename A0, typename A1)
                          , bs::sse4_1_
                          , bs::pack_<bs::logical_<A0>, bs::sse_>
                          , bs::pack_<bd::double_<A1>, bs::sse_>
                          , bs::pack_<bd::double_<A1>, bs::sse_>
                         )
  {
    BOOST_FORCEINLINE A1 operator() ( const A0 & a0
                                    , const A1 & a1
                                    , const A1 & a2) const BOOST_NOEXCEPT
    {
      return _mm_blendv_pd(a2, a1, bitwise_cast<A1>(genmask(a0)));
    }
  };

  BOOST_DISPATCH_OVERLOAD ( if_else_
                          , (typename A0, typename A1)
                          , bs::sse4_1_
                          , bs::pack_<bs::logical_<A0>, bs::sse_>
                          , bs::pack_<bd::integer_<A1>, bs::sse_>
                          , bs::pack_<bd::integer_<A1>, bs::sse_>
                         )
  {
    BOOST_FORCEINLINE A1 operator() ( const A0 & a0
                                    , const A1 & a1
                                    , const A1 & a2) const BOOST_NOEXCEPT
    {
      return _mm_blendv_epi8(a2, a1, bitwise_cast<A1>(genmask(a0)));
    }
  };
} } }

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#pragma once

#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <math.h>

// STL
#include <algorithm>
#include <functional>
#include <cmath>

#include <list>
#include <map>
#include <unordered_map>
#include <vector>
#include <set>
#include <unordered_set>
#include <iterator>

#include <iostream>
#include <fstream>
#include <sstream>

#include <cerrno>
#include <cassert>

using namespace std;
using namespace std::tr1;

// SFML - http://www.sfml-dev.org/index.php
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/System/String.hpp>
#include <SFML/System/Time.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/OpenGL.hpp>

// Box2D - http://box2d.org/
#include <Box2D/Box2D.h>

// Lua
#include <lua/lua.hpp>
#include <lua/lauxlib.h>
#include <lua/lualib.h>

// Boost - http://www.boost.org/
#define BOOST_NO_MEMBER_TEMPLATE_FRIENDS
#include "boost/multi_index/ordered_index.hpp"
#include "boost/multi_index/hashed_index.hpp"
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/member.hpp>
#include "boost/multi_index/sequenced_index.hpp"
#include "Boost/tuple/tuple.hpp"
#include "Boost/any.hpp"
#include "Boost/bind.hpp"
#include "Boost/function.hpp"
#include "boost/lexical_cast.hpp"
#include "boost/multi_index_container.hpp"
#include "Boost/ref.hpp"
#include "Boost/signals2.hpp"
using namespace boost;
using namespace boost::multi_index;

// RadpiXML
#include "rapidxml/rapidxml.hpp"
using namespace rapidxml;

// typedefs
typedef unsigned int u32;
typedef unsigned short u16;
typedef unsigned char u8;
typedef int s32;
typedef short s16;
typedef char s8;

// helper macros
#define FOREACH( iterator, collection ) for( auto iterator(collection.begin()); iterator != collection.end(); iterator++ )
#define FOREACH_R( iterator, collection ) for( auto iterator(collection.rbegin()); iterator != collection.rend(); iterator++ )

#define COMBINE2(a, b) a##b
#define COMBINE(a, b) COMBINE2(a,b)

#define STATIC_INITIALISE_START			private: static struct StaticInitialise { StaticInitialise()
#define STATIC_INITIALISE_END			} s_xStaticInitialise;
#define STATIC_INITIALISE_RUN( TParentClass )	TParentClass::StaticInitialise TParentClass::s_xStaticInitialise;

// Core classes
#include "Core/Maths/Maths.hpp"
#include "Core/Data/Hash.hpp"
#include "Core/Data/TUID.hpp"
#include "Core/Data/Data.hpp"

max_stars_repo_name: jkeywo/KGE

max_issues_repo_name: jkeywo/KGE

max_forks_repo_name: jkeywo/KGE


text:
// TRENTO: Reduced Thickness Event-by-event Nuclear Topology
// Copyright 2015 Jonah E. Bernhard, J. Scott Moreland
// MIT License

#include "../src/nucleon.h"

#include <cmath>

#include "catch.hpp"
#include "util.h"

#include "../src/eventqty.h"
#include "../src/nucleus.h"
#include "../src/random.h"
#include <boost/math/constants/constants.hpp>
#include <boost/multi_array.hpp>

#include <iostream>

using namespace trento;

TEST_CASE( "nucleon" ) {
  auto fluct = 1. + .5*random::canonical<>();
  auto xsec = 4. + 3.*random::canonical<>();
  auto width = .5 + .2*random::canonical<>();
  auto wsq = width*width;

  auto var_map = make_var_map({
      {"ncoll", false},
      {"fluctuation",   fluct},
      {"cross-section", xsec},
      {"nucleon-width", width},
      {"constit-width", width},
      {"constit-number", 1},
      {"columns", DefaultEventQuantityList},
  });

  NucleonCommon nc{var_map};

  Proton proton{};
  proton.sample_nucleons(0.);
  auto& nucleon = *proton.begin();
  while (!nc.participate(nucleon, nucleon)) {}

  // truncation radius
  auto R = 5*width;

  // random angle
  auto phi = math::double_constants::two_pi * random::canonical<>();
  auto cs = std::cos(phi);
  auto sn = std::sin(phi);

  // thickness function
  // check relative to zero
  auto tzero = nc.thickness(nucleon, 0., 0.);
  CHECK( nc.thickness(nucleon, width*cs, width*sn) == Approx(tzero*std::exp(-.5)) );

  // random point inside radius
  auto x = R * random::canonical<>();
  auto y = R * random::canonical<>();
  auto dsq = x*x + y*y;
  CHECK( nc.thickness(nucleon, x, y) == Approx(tzero*std::exp(-.5*dsq/wsq)).epsilon(1e-5).margin(1e-5) );

  // random point outside radius
  auto d = R * (1 + random::canonical<>());
  CHECK( nc.thickness(nucleon, d*cs, d*sn) == 0. );

  // fluctuations
  // just check they have unit mean -- the rest is handled by the C++ impl.
  auto total = 0.;
  auto n = 1e6;
  for (auto i = 0; i < static_cast<int>(n); ++i) {
    proton.sample_nucleons(0.);
    nucleon = *proton.begin();
    while (!nc.participate(nucleon, nucleon)) {}
    total += nc.thickness(nucleon, 0., 0.) * (2*M_PI*wsq);
  }

  auto mean = total/n;
  CHECK( mean == Approx(1.).epsilon(.003) );

  // must use a Nucleus to set Nucleon position
  // Proton conveniently sets a deterministic position
  // a mock class would be better but this works fine
  Proton A{}, B{};
  A.sample_nucleons(0.);
  B.sample_nucleons(0.);
  auto& nA = *A.begin();
  auto& nB = *B.begin();
  CHECK( nA.x() == 0. );
  CHECK( nA.y() == 0. );
  CHECK( nA.z() == 0. );
  CHECK( !nA.is_participant() );

  // wait until the nucleons participate
  while (!nc.participate(nA, nB)) {}
  CHECK( nA.is_participant() );
  CHECK( nB.is_participant() );

  // resampling nucleons resets participant state
  A.sample_nucleons(0.);
  CHECK( !nA.is_participant() );

  // test cross section
  // min-bias impact params
  auto bmax = nc.max_impact();
  CHECK( bmax == Approx(6*width) );

  auto nev = 1e6;
  auto count = 0;
  for (auto i = 0; i < static_cast<int>(nev); ++i) {
    auto b = bmax * std::sqrt(random::canonical<>());
    A.sample_nucleons(.5*b);
    B.sample_nucleons(-.5*b);
    if (nc.participate(nA, nB))
      ++count;
  }

  auto xsec_mc = M_PI*bmax*bmax * static_cast<double>(count)/nev;

  // precision is better than this, but let's be conservative
  CHECK( xsec_mc == Approx(xsec).epsilon(.02) );

  // impact larger than max should never participate
  auto b = bmax + random::canonical<>();
  A.sample_nucleons(.5*b);
  B.sample_nucleons(-.5*b);
  CHECK( !nc.participate(nA, nB) );

  // very large fluctuation parameters mean no fluctuations
  auto no_fluct_var_map = make_var_map({
      {"ncoll", false},
      {"fluctuation",   1e12},
      {"cross-section", xsec},
      {"nucleon-width", width},
      {"constit-width", width},
      {"constit-number", 1},
  });

  NucleonCommon no_fluct_nc{no_fluct_var_map};

  proton.sample_nucleons(0.);
  nucleon = *proton.begin();
  while (!no_fluct_nc.participate(nucleon, nucleon)) {}
  CHECK( no_fluct_nc.thickness(nucleon, 0, 0) == Approx(1/(2*M_PI*wsq)) );

  CHECK_THROWS_AS([]() {
    // nucleon width too small
    auto bad_var_map = make_var_map({
        {"ncoll", false},
        {"fluctuation",   1.},
        {"cross-section", 5.},
        {"nucleon-width", .1},
        {"constit-width", .1},
        {"constit-number", 1},
    });
    NucleonCommon bad_profile{bad_var_map};
  }(),
  std::domain_error);

  // test nucleon-nucleon cross section with random constituent substructure
  auto nucleon_width = 0.5;
  auto constituent_number = std::uniform_int_distribution<>{2, 6}(random::engine);
  auto constituent_width = .3 + .2*random::canonical<>();

  // Coarse-ish p+p grid.
  auto grid_max = 3.;
  auto grid_step = 0.1;
  auto grid_nsteps = 60;

  // constituent var map
  var_map = make_var_map({
      {"ncoll", false},
      {"grid-max", grid_max},
      {"grid-step", grid_step},
      {"fluctuation",   1e12},
      {"cross-section", xsec},
      {"nucleon-width", nucleon_width},
      {"constit-width", constituent_width},
      {"constit-number", constituent_number},
  });

  NucleonCommon nc_constituent{var_map};
  bmax = nc_constituent.max_impact();

  // inelastic collision counter
  count = 0;

  // measure the cross section with min bias p+p collisions
  for (auto i = 0; i < static_cast<int>(nev); ++i) {
    b = bmax * std::sqrt(random::canonical<>());
    A.sample_nucleons(.5*b);
    B.sample_nucleons(-.5*b);
    if (nc_constituent.participate(*A.begin(), *B.begin()))
      ++count;
  }

  // calculate Monte Carlo cross section
  xsec_mc = M_PI*bmax*bmax * static_cast<double>(count)/nev;

  // assert a rather loose tolerance for the numerical cross section finder
  CHECK( xsec_mc/xsec == Approx(1).epsilon(.02) );

  // verify root-mean-square nucleon width for nucleons with substructure
  double mean_square_width_num = 0.0;
  double mean_square_width_denom = 0.0;

  for (auto i = 0; i < 1000; ++i) {
    A.sample_nucleons(0.);
    auto nucleon = *A.begin();

    while (!nc_constituent.participate(nucleon, nucleon)) {}

    for (auto iy = 0; iy < grid_nsteps; ++iy) {
      for (auto ix = 0; ix < grid_nsteps; ++ix) {
        auto x = (ix + .5) * 2 * grid_max/grid_nsteps - grid_max;
        auto y = (iy + .5) * 2 * grid_max/grid_nsteps - grid_max;
        auto thick = nc_constituent.thickness(nucleon, x, y);
        mean_square_width_num += (x*x + y*y)*thick;
        mean_square_width_denom += 2*thick;
      }
    }
  }

  auto rms_width = std::sqrt(mean_square_width_num / mean_square_width_denom);

  CHECK( rms_width == Approx(nucleon_width).epsilon(.01).margin(.01) );

}

ext: cxx

max_stars_repo_name: dereksoeder/trento

max_issues_repo_name: dereksoeder/trento

max_forks_repo_name: dereksoeder/trento


text:
#define BOOST_APPLICATION_FEATURE_NS_SELECT_BOOST

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

using namespace boost;

inline application::global_context_ptr this_application() {
    return application::global_context::get();
}

class myapp {
public:
    myapp(void);

    ~myapp(void);

    int operator()(void);
};

max_stars_repo_name: NilFoundation/application

max_issues_repo_name: NilFoundation/application

max_forks_repo_name: NilFoundation/application


text:
/*=============================================================================
    Copyright (c) 2014 Kohei Takahashi

    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/config.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/container/deque.hpp>
#include <boost/fusion/container/list.hpp>
#include <boost/fusion/container/set.hpp>
#include <boost/fusion/container/map.hpp>
#include <boost/fusion/support/pair.hpp>
#include <boost/fusion/sequence/intrinsic/size.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/assert.hpp>

#include <boost/array.hpp>
#include <boost/fusion/adapted/boost_array.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/fusion/adapted/boost_tuple.hpp>
#if !defined(BOOST_NO_CXX11_HDR_TUPLE) && \
    !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#include <tuple>
#include <boost/fusion/adapted/std_tuple.hpp>
#endif

template <typename LHS, typename RHS>
void check_(LHS const&, RHS const&)
{
    BOOST_MPL_ASSERT((boost::is_same<LHS, RHS>));
}

template <typename S>
void check()
{
    check_(
        boost::fusion::result_of::size<S>::type::value
      , boost::fusion::result_of::size<S>::value
    );
}

void test()
{
    {
        check<boost::fusion::vector<> >();
        check<boost::fusion::vector<int> >();
        check<boost::fusion::vector<int, int> >();
        check<boost::fusion::vector<int, int, int> >();
    }

    {
        check<boost::fusion::deque<> >();
        check<boost::fusion::deque<int> >();
        check<boost::fusion::deque<int, int> >();
        check<boost::fusion::deque<int, int, int> >();
    }

    {
        check<boost::fusion::list<> >();
        check<boost::fusion::list<int> >();
        check<boost::fusion::list<int, int> >();
        check<boost::fusion::list<int, int, int> >();
    }

    {
        check<boost::fusion::set<> >();
        check<boost::fusion::set<int> >();
        check<boost::fusion::set<int, float> >();
        check<boost::fusion::set<int, float, double> >();
    }

    {
        check<boost::fusion::map<> >();
        check<boost::fusion::map<boost::fusion::pair<int, int> > >();
        check<boost::fusion::map<boost::fusion::pair<int, int> , boost::fusion::pair<float, int> > >();
        check<boost::fusion::map<boost::fusion::pair<int, int> , boost::fusion::pair<float, int> , boost::fusion::pair<double, int> > >();
    }

    {
        check<boost::array<int, 1> >();
        check<boost::array<int, 2> >();
        check<boost::array<int, 3> >();
    }

    {
        check<boost::tuples::tuple<> >();
        check<boost::tuples::tuple<int> >();
        check<boost::tuples::tuple<int, int> >();
        check<boost::tuples::tuple<int, int, int> >();
    }

#if !defined(BOOST_NO_CXX11_HDR_TUPLE) && \
    !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
    {
        check<std::tuple<> >();
        check<std::tuple<int> >();
        check<std::tuple<int, int> >();
        check<std::tuple<int, int, int> >();
    }
#endif
}


text:
/// The MIT License
// (c) 2019 Daniel Williams

#ifndef _TERRAIN_HPP_
#define _TERRAIN_HPP_

// attempt to work through Sean-Parent's talk:
//   https://channel9.msdn.com/Events/GoingNative/2013/Inheritance-Is-The-Base-Class-of-Evil
//   https://sean-parent.stlab.cc/presentations/2013-09-06-inheritance/value-semantics-unique.cpp
// This StackOverflow answer:
//   https://stackoverflow.com/questions/318064/how-do-you-declare-an-interface-in-c/17299151#17299151

#include <cstdio>
#include <string>
#include <vector>

#include <Eigen/Geometry>

#include <nlohmann/json/json_fwd.hpp>

#include "geometry/cell_value.hpp"
#include "geometry/layout.hpp"
#include "geometry/polygon.hpp"

namespace terrain {

///! \brief generates a sample json document, used for creating debug terrain
nlohmann::json generate_diamond(const double width,
                                const double desired_precision);

template<typename T>
class Terrain {
public:
    T& impl;
    std::string error_message;

    Terrain();

    Terrain(T& _ref);

    //copy constructor
    Terrain(const Terrain& t) = delete;

    //move constructor
    Terrain(Terrain&& t) = delete;

    // copy assignment operator
    Terrain& operator=(const Terrain& t) = delete;

    //move assignment operator
    Terrain& operator=(Terrain&& t) = delete;

    ~Terrain();

    geometry::cell_value_t classify(const Eigen::Vector2d& p) const;

    ///! \brief writes debug information to std err
    void debug() const;

    // sets grid to all zeros
    void inline fill(const geometry::cell_value_t _value);

    /**
     * Loads the vector of points as a CCW polygon.
     *
     * @param {std::istream} input stream containing the serialization text
     */
    void inline fill(const geometry::Polygon& source, const geometry::cell_value_t fill_value);

    ///! \brief counts the number of cells *actually* tracked
    size_t get_count() const;

    ///! \brief describes the number of divisions along each of the x, y dimensions
    size_t get_dimension() const;

    const std::string& get_error() const;

    ///! \brief retreives the boundary information
    const geometry::Layout& get_layout() const;

    ///! \brief describes how much of the data structure is actively
    ///! being used
    double get_load_factor() const;

    ///! \brief gets the total count of cells in this data structure
    size_t get_size() const;

    void print() const;

    void inline reset();
    void inline reset(const geometry::Layout& _layout);

    std::string summary() const;

}; // class Terrain<T>

}; // namespace terrain

#include "terrain.inl"

#endif  // #ifdef _TERRAIN_HPP_

max_stars_repo_name: teyrana/quadtree

max_issues_repo_name: teyrana/quadtree

max_forks_repo_name: teyrana/quadtree


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.

#pragma once
#ifndef _EXTENSIONINFO_HH_
#define _EXTENSIONINFO_HH_

#include <string>
#include <ctime>
#include <map>
#include <mutex>
#include <functional>
#include <set>
#include <unordered_set>
#include <vector>
#include <future>
#include <stddef.h>
#include <boost/asio.hpp>
#include <atomic>

extern "C" {
#include <unistd.h>
#include <semaphore.h>
}

/// <summary>
/// Keep track of an extension's meta data. Any of these data change
/// will mean the extension definition changed.
/// </summary>
struct ExtensionMetaData
{
    std::string Name;
    std::string CommandLine;
    std::string Body;
    std::string AlterLocation;

    ExtensionMetaData()
    {
    }

    ExtensionMetaData(
        const std::string & name,
        const std::string & cmdline,
        const std::string & body,
        const std::string & loc
        ) : Name(name), CommandLine(cmdline), Body(body), AlterLocation(loc)
    {}

    /// <summary>
    /// Compare this extension's meta data with some other meta data.
    /// Return true if they are the same, return false otherwise.
    /// </summary>
    bool operator==(const ExtensionMetaData & other) const;
};

/// <summary>
/// Keep track an extension process's information.
/// </summary>
class ExtensionInfo
{
public:
    enum ExtStatus {
        NORMAL,     // A new extension.
        BAD,        // An extension starts to run but failed in the middle.
        KILLING,    // An extension killed by SIGINT, or killed externally.
        EXIT,       // An extension stopped and killed already.
        UNKNOWN     // Unknown. Should be never in this status.
    };

    // An extension's metadata.
    ExtensionMetaData MetaData;

    // Process id of the extension process.
    pid_t Pid = 0;

    // Process start time in number of seconds in UTC.
    time_t StartTime = 0;

    // Number of times the extension is retried since last reset.
    unsigned int RetryCount = 0;

    // Extension status.
    ExtStatus Status = UNKNOWN;

    // asio timer to kill the extension by force.
    boost::asio::deadline_timer * StopTimer;

    // whether the extension timer is already cancelled or not.
    std::atomic<bool> StopTimerCancelled;

    ExtensionInfo();

    ~ExtensionInfo();

    /// <summary>
    /// Get the string format of the status.
    /// </summary>
    std::string GetStatus() const;

    /// <summary>
    /// Get the string format of the status.
    /// </summary>
    static std::string StatusToString(ExtStatus s);

private:
    static std::map<ExtStatus, std::string> _statusMap;
};

/// <summary>
/// Keep track of all extension processes.
/// </summary>
class ExtensionList
{
public:

    /// <summary>
    /// Get number of items.
    /// </summary>
    static size_t GetSize();

    /// <summary>
    /// Add an item to the list. If the item already exists, free the memory of
    /// existing one and add the new one.
    /// Return true if no error. Return false if the input is invalid.
    /// </summary>
    static bool AddItem(ExtensionInfo * extObj);

    /// <summary>
    /// Get an item given its name.
    /// Return the object pointer.
    /// Return nullptr if not found or given name is invalid.
    /// The caller shouldn't free the object pointer.
    /// </summary>
    static ExtensionInfo * GetItem(const std::string & extname);

    /// <summary>
    /// Get an item given its process id.
    /// Return the object pointer.
    /// Return nullptr if not found or given pid is invalid.
    /// The caller shouldn't free the object pointer.
    /// </summary>
    static ExtensionInfo * GetItem(pid_t extPid);

    /// <summary>
    /// Update an existing item's pid.
    /// Return true if success, false if any error.
    /// </summary>
    static bool UpdateItem(pid_t oldpid, pid_t newpid);

    /// <summary>
    /// Delete an item from the list.
    /// Return true if the item is actually deleted.
    /// Return false if the given name is invalid or not found.
    /// </summary>
    static bool DeleteItem(const std::string & extname);

    /// <summary>
    /// Delete a set of items with given names.
    /// Return true if all items are actually deleted, or set is empty.
    /// Return false if any item is not found.
    /// </summary>
    static bool DeleteItems(const std::set<std::string>& extnames);
    static void DeleteAllItems();

    /// <summary>
    /// Use a given function to iterate over each extension object.
    /// </summary>
    static void ForeachExtension(const std::function<void(ExtensionInfo*)>& fn);

    /// <summary>
    /// Add a pid to the pid set.
    /// </summary>
    static void AddPid(pid_t pid);

    /// <summary>
    /// Get all pids of the pid set. Clear the original one.
    /// </summary>
    static std::unordered_set<pid_t> GetAndClearPids();

private:
    static std::map<const std::string, ExtensionInfo*> _extlistByName;
    static std::map<pid_t, ExtensionInfo*> _extlistByPid;

    static std::mutex _listmutex;

    /// Store a list of PIDs that needs to be killed because their
    /// meta data are changed.
    static std::unordered_set<pid_t> _killList;
    static std::mutex _klmutex;
};

class MdsdExtension;
class MdsdConfig;

/// <summary>
/// Use configuration to create new extension processes, then manage
/// the extension processes.
/// </summary>
class ExtensionMgmt
{
public:
    /// <summary>
    /// Free all resources.
    /// </summary>
    ~ExtensionMgmt();

    /// <summary>
    /// Get a singleton instance.
    /// </summary>
    static ExtensionMgmt* GetInstance();

    /// <summary>
    /// Start all extensions given a config synchronously. It will also
    /// stop any obsolete extension.
    /// Return true if success; Return false for any error.
    /// </summary>
    static bool StartExtensions(MdsdConfig * config);

    /// <summary>
    /// Calls StartExtensions() in async.
    /// </summary>
    static void StartExtensionsAsync(MdsdConfig * config);

    /// <summary>
    /// Stop all extensions.
    /// Return true for success, false for any error.
    /// </summary>
    bool StopAllExtensions();

    /// <summary>
    /// Defines SIGCHLD signal handler, which is from child extension process. It will
    /// - release child process resources.
    /// - change extension object status.
    /// - update the extension object in ExtensionList.
    /// </summary>
    void CatchSigChld(int signo);

private:
    ExtensionMgmt();

    /// <summary>
    /// Define semaphore to synchronize between stopped extensions
    /// (handled in SIGCHLD signal handler) and creating new ones (in main thread)
    /// </summary>
    sem_t _extsem;

    /// <summary>
    /// True if semaphore is initialized properly, false if any error.
    /// </summary>
    bool _extsemInitOK;

    /// <summary>
    /// Singleton instance.
    /// </summary>
    static ExtensionMgmt * _extInstance;

    /// <summary>
    /// Environment name for extension. Extension uses it to read the value defined in <Body>
    /// </summary>
    static constexpr const char* BODYENV = "MON_EXTENSION_BODY";

    /// <summary>
    /// The grace period in number of seconds for the extension process to
    /// terminate itself before it is killed by force. Because mdsd service's
    /// grace period is 30-second, make it shorter than that.
    /// </summary>
    static const unsigned int EXT_TERMINATE_GRACE_SECONDS = 20;

    /// <summary>
    /// The maximum number of retries to start extension within
    /// given window seconds.
    /// </summary>
    static const unsigned int EXT_MAX_RETRIES = 3;

    /// <summary>
    /// Numbe of seconds to wait before retrying the extension
    /// </summary>
    static const unsigned int EXT_RETRY_WAIT_SECONDS = 5;

    /// <summary>
    /// Extension restart retry timeout in number of seconds.
    /// If the time difference is bigger than this window, reset
    /// extension's RetryCount to be 0.
    /// </summary>
    static const unsigned int EXT_RETRY_TIMEOUT_SECONDS = 60;

    /// <summary>
    /// Initialize semaphore. Return true if no error; return false for any error.
    /// </summary>
    bool InitSem();

    /// <summary>
    /// Start all extensions defined in a config. It won't stop any extension.
    /// It will return the extension names defined in the config in extlistInConfig.
    /// Return true for success, false for any error.
    /// </summary>
    bool StartExtensionsFromConfig(
        MdsdConfig * config,
        std::set<std::string> & extlistInConfig);

    /// <summary>
    /// Restart all extensions whose meta data were changed.
    /// Return true if success, false for any error.
    /// <param name="changedList">List of changed extensions.</param>
    /// <param name="newDataList">The meta data for the changed extensions. Key is old extension pid. </param>
    /// </summary>
    bool RestartChangedExtensions(const std::vector<ExtensionInfo*> & changedList,
        const std::map<pid_t, ExtensionMetaData> & newDataList);

    /// <summary>
    /// Wait until any extension's change status SIGCHLD caught, or until timed out
    /// after SEM_WAIT_SECONDS seconds.
    /// Return true if success, false if error or timed out.
    /// </summary>
    bool WaitForAnyExtStop();

    /// <summary>
    /// Start all extensions whose meta data were changed.
    /// Return true for success, false for any error.
    /// </summary>
    bool StartAllChangedExts(const std::unordered_set<pid_t> changedPids,
        const std::map<pid_t, ExtensionMetaData> & newDataList) const;

    /// <summary>
    /// Start one extension instance whose meta data were changed.
    /// Return true for success, false for any error.
    /// </summary>
    bool StartOneChangedExt(pid_t changedPid, const ExtensionMetaData & metadata) const;

    /// <summary>
    /// Any extension that's not in given set is obsolete.
    /// For each obsolete extension, delete it from ExtensionList and Stop it.
    /// Return true if no error is found. Otherwise, return false.
    /// </summary>
    bool StopObsoleteExtensions(const std::set<std::string> & extlistInConfig) const;

    /// <summary>
    /// Block or unblock a given signal to the process.
    /// </summary>
    bool MaskSignal(bool isBlock, int signum) const;

    /// <summary>
    /// Attempt to start a given extension process.
    /// Return true if it starts OK, return false for any error.
    /// If starting OK, the extensionInfo object will be added to ExtensionList. Its memory
    /// will be managed there.
    /// </summary>
    bool StartExtension(
        const std::string & extName,
        const std::string & cmdline,
        const std::string & body,
        const std::string & alterLocation) const;

    /// <summary>
    /// Start an extension process given its meta data.
    /// Return true if it starts OK, return false for any error.
    /// </summary>
    bool StartExtension(const ExtensionMetaData & metaData) const;

    /// <summary>
    /// Either create a new ExtensionInfo object or update existing one in
    /// the extension list. If an extension failed to be created, it should not be
    /// retried.
    /// </summary>
    bool UpdateExtensionList(
        ExtensionInfo * oldExtInfo,
        const std::string & extName,
        const std::string & cmdline,
        const std::string & body,
        const std::string & alterLocation,
        pid_t pid,
        bool extFailed) const;

    /// <summary>
    /// Stop an extension process. It won't remove the ExtensionInfo item from ExtensionList.
    /// </summary>
    bool StopExtension(ExtensionInfo * extObj) const;

    /// <summary>
    /// Update the information of extension given its pid.
    /// Return true for success, false for error.
    /// </summary>
    bool UpdateStoppedExtension(pid_t extpid);

    /// <summary>
    /// Handle extension that fails itself. Either retry it or delete it forever based on its status.
    /// Return true if success, false if any error.
    /// </summary>
    bool HandleExtensionFailure(ExtensionInfo * extObj);

    /// <summary>
    /// This is to unblock all signal mask. For example, in child process, child process
    /// may use this function to unblock signal mask inherited from parent process.
    /// Return errno.
    /// <summary>
    int UnblockSignals() const;

    /// <summary>
    /// Kill a process by sending it SIGKILL. It doesn't validate whether
    /// the process is actually killed or not.
    /// Return true if signal is sent out properly.
    /// Return false if signal is not sent out, or the operation is aborted.
    /// <summary>
    bool KillProcessByForce(pid_t pid, const boost::system::error_code& error) const;

    /// <summary>
    /// Send signal signum to process id pid.
    /// Return whether the process exists or not through pIsPsExist.
    /// Return true if signal is sent out properly, false if error. If process doesn't exist,
    /// also return true.
    /// <param name="pid"> process id </param>
    /// <param name="signum"> signal number </param>
    /// <param name="pIsPsExist"> Return whether the process exists or not </param>
    /// <summary>
    bool SendSignalToProcess(pid_t pid, int signum, bool *pIsPsExist) const;

};

#endif // _EXTENSIONINFO_HH_

ext: hh

max_stars_repo_name: shridpant/azure-linux-extensions

max_issues_repo_name: shridpant/azure-linux-extensions

max_forks_repo_name: shridpant/azure-linux-extensions