text:
/**
 *
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 20220523
 *
 *
 * NOTE: This class is auto generated by OpenAPI-Generator 5.4.0.
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#include <corvusoft/restbed/byte.hpp>
#include <corvusoft/restbed/string.hpp>
#include <corvusoft/restbed/settings.hpp>
#include <corvusoft/restbed/request.hpp>
#include <corvusoft/restbed/uri.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include "SuperContestEffectApi.h"

namespace org {
namespace openapitools {
namespace server {
namespace api {

using namespace org::openapitools::server::model;

SuperContestEffectApiException::SuperContestEffectApiException(int status_code, std::string what)
  : m_status(status_code),
    m_what(what)
{

}
int SuperContestEffectApiException::getStatus() const
{
    return m_status;
}
const char* SuperContestEffectApiException::what() const noexcept
{
    return m_what.c_str();
}

template<class MODEL_T>
std::shared_ptr<MODEL_T> extractJsonModelBodyParam(const std::string& bodyContent)
{
    std::stringstream sstream(bodyContent);
    boost::property_tree::ptree pt;
    boost::property_tree::json_parser::read_json(sstream, pt);

    auto model = std::make_shared<MODEL_T>(pt);
    return model;
}

template<class MODEL_T>
std::vector<std::shared_ptr<MODEL_T>> extractJsonArrayBodyParam(const std::string& bodyContent)
{
    std::stringstream sstream(bodyContent);
    boost::property_tree::ptree pt;
    boost::property_tree::json_parser::read_json(sstream, pt);

    auto arrayRet = std::vector<std::shared_ptr<MODEL_T>>();
    for (const auto& child: pt) {
        arrayRet.emplace_back(std::make_shared<MODEL_T>(child.second));
    }
    return arrayRet;
}

template <class KEY_T, class VAL_T>
std::string convertMapResponse(const std::map<KEY_T, VAL_T>& map)
{
    boost::property_tree::ptree pt;
    for(const auto &kv: map) {
    pt.push_back(boost::property_tree::ptree::value_type(
        boost::lexical_cast<std::string>(kv.first),
        boost::property_tree::ptree(
        boost::lexical_cast<std::string>(kv.second))));
    }
    std::stringstream sstream;
    write_json(sstream, pt);
    std::string result = sstream.str();
    return result;
}

SuperContestEffectApiApiV2Super-contest-effectResource::SuperContestEffectApiApiV2Super-contest-effectResource(const std::string& context /* = "" */)
{
	this->set_path(context + "/api/v2/super-contest-effect//");
	this->set_method_handler("GET",
		std::bind(&SuperContestEffectApiApiV2Super-contest-effectResource::handler_GET_internal, this,
			std::placeholders::_1));
}

SuperContestEffectApiApiV2Super-contest-effectResource::~SuperContestEffectApiApiV2Super-contest-effectResource()
{
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectResource::handleSuperContestEffectApiException(const SuperContestEffectApiException& e)
{
    return std::make_pair<int, std::string>(e.getStatus(), e.what());
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectResource::handleStdException(const std::exception& e)
{
    return std::make_pair<int, std::string>(500, e.what());
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectResource::handleUnspecifiedException()
{
    return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}

void SuperContestEffectApiApiV2Super-contest-effectResource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
    session->set_header(header, "");
}

void SuperContestEffectApiApiV2Super-contest-effectResource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
    session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}

void SuperContestEffectApiApiV2Super-contest-effectResource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
    session->close(status, result, { {"Connection", "close"} });
}

void SuperContestEffectApiApiV2Super-contest-effectResource::handler_GET_internal(const std::shared_ptr<restbed::Session> session)
{
    const auto request = session->get_request();

    // Getting the query params
    const int32_t limit = getQueryParam_limit(request);
    const int32_t offset = getQueryParam_offset(request);

    int status_code = 500;
    std::string resultObject = "";
    std::string result = "";

    try {
        std::tie(status_code, resultObject) =
             handler_GET(limit, offset);
    }
    catch(const SuperContestEffectApiException& e) {
        std::tie(status_code, result) = handleSuperContestEffectApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 0) {
        result = resultObject;

        const constexpr auto contentType = "application/json";
        returnResponse(session, 0, result.empty() ? "Default response" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectResource::handler_GET(
        int32_t const & limit, int32_t const & offset)
{
    throw SuperContestEffectApiException(501, "Not implemented");
}

std::string SuperContestEffectApiApiV2Super-contest-effectResource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
  const auto request = session->get_request();
  int content_length = request->get_header("Content-Length", 0);
  std::string bodyContent;
  session->fetch(content_length,
                 [&bodyContent](const std::shared_ptr<restbed::Session> session,
                                const restbed::Bytes &body) {
                   bodyContent = restbed::String::format(
                       "%.*s\n", (int)body.size(), body.data());
                 });
  return bodyContent;
}
SuperContestEffectApiApiV2Super-contest-effectIdResource::SuperContestEffectApiApiV2Super-contest-effectIdResource(const std::string& context /* = "" */)
{
	this->set_path(context + "/api/v2/super-contest-effect/{id: .*}//");
	this->set_method_handler("GET",
		std::bind(&SuperContestEffectApiApiV2Super-contest-effectIdResource::handler_GET_internal, this,
			std::placeholders::_1));
}

SuperContestEffectApiApiV2Super-contest-effectIdResource::~SuperContestEffectApiApiV2Super-contest-effectIdResource()
{
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectIdResource::handleSuperContestEffectApiException(const SuperContestEffectApiException& e)
{
    return std::make_pair<int, std::string>(e.getStatus(), e.what());
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectIdResource::handleStdException(const std::exception& e)
{
    return std::make_pair<int, std::string>(500, e.what());
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectIdResource::handleUnspecifiedException()
{
    return std::make_pair<int, std::string>(500, "Unknown exception occurred");
}

void SuperContestEffectApiApiV2Super-contest-effectIdResource::setResponseHeader(const std::shared_ptr<restbed::Session>& session, const std::string& header)
{
    session->set_header(header, "");
}

void SuperContestEffectApiApiV2Super-contest-effectIdResource::returnResponse(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result, const std::string& contentType)
{
    session->close(status, result, { {"Connection", "close"}, {"Content-Type", contentType} });
}

void SuperContestEffectApiApiV2Super-contest-effectIdResource::defaultSessionClose(const std::shared_ptr<restbed::Session>& session, const int status, const std::string& result)
{
    session->close(status, result, { {"Connection", "close"} });
}

void SuperContestEffectApiApiV2Super-contest-effectIdResource::handler_GET_internal(const std::shared_ptr<restbed::Session> session)
{
    const auto request = session->get_request();

    // Getting the path params
    const int32_t id = getPathParam_id(request);

    int status_code = 500;
    std::string resultObject = "";
    std::string result = "";

    try {
        std::tie(status_code, resultObject) =
             handler_GET(id);
    }
    catch(const SuperContestEffectApiException& e) {
        std::tie(status_code, result) = handleSuperContestEffectApiException(e);
    }
    catch(const std::exception& e) {
        std::tie(status_code, result) = handleStdException(e);
    }
    catch(...) {
        std::tie(status_code, result) = handleUnspecifiedException();
    }

    if (status_code == 0) {
        result = resultObject;

        const constexpr auto contentType = "application/json";
        returnResponse(session, 0, result.empty() ? "Default response" : result, contentType);
        return;
    }
    defaultSessionClose(session, status_code, result);
}

std::pair<int, std::string> SuperContestEffectApiApiV2Super-contest-effectIdResource::handler_GET(
        int32_t const & id)
{
    throw SuperContestEffectApiException(501, "Not implemented");
}

std::string SuperContestEffectApiApiV2Super-contest-effectIdResource::extractBodyContent(const std::shared_ptr<restbed::Session>& session) {
  const auto request = session->get_request();
  int content_length = request->get_header("Content-Length", 0);
  std::string bodyContent;
  session->fetch(content_length,
                 [&bodyContent](const std::shared_ptr<restbed::Session> session,
                                const restbed::Bytes &body) {
                   bodyContent = restbed::String::format(
                       "%.*s\n", (int)body.size(), body.data());
                 });
  return bodyContent;
}

SuperContestEffectApi::SuperContestEffectApi(std::shared_ptr<restbed::Service> const& restbedService)
: m_service(restbedService)
{
}

SuperContestEffectApi::~SuperContestEffectApi() {}

void SuperContestEffectApi::setSuperContestEffectApiApiV2Super-contest-effectResource(std::shared_ptr<SuperContestEffectApiApiV2Super-contest-effectResource> spSuperContestEffectApiApiV2Super-contest-effectResource) {
    m_spSuperContestEffectApiApiV2Super-contest-effectResource = spSuperContestEffectApiApiV2Super-contest-effectResource;
    m_service->publish(m_spSuperContestEffectApiApiV2Super-contest-effectResource);
}
void SuperContestEffectApi::setSuperContestEffectApiApiV2Super-contest-effectIdResource(std::shared_ptr<SuperContestEffectApiApiV2Super-contest-effectIdResource> spSuperContestEffectApiApiV2Super-contest-effectIdResource) {
    m_spSuperContestEffectApiApiV2Super-contest-effectIdResource = spSuperContestEffectApiApiV2Super-contest-effectIdResource;
    m_service->publish(m_spSuperContestEffectApiApiV2Super-contest-effectIdResource);
}

void SuperContestEffectApi::publishDefaultResources() {
    if (!m_spSuperContestEffectApiApiV2Super-contest-effectResource) {
        setSuperContestEffectApiApiV2Super-contest-effectResource(std::make_shared<SuperContestEffectApiApiV2Super-contest-effectResource>());
    }
    if (!m_spSuperContestEffectApiApiV2Super-contest-effectIdResource) {
        setSuperContestEffectApiApiV2Super-contest-effectIdResource(std::make_shared<SuperContestEffectApiApiV2Super-contest-effectIdResource>());
    }
}

std::shared_ptr<restbed::Service> SuperContestEffectApi::service() {
    return m_service;
}

}
}
}
}

max_stars_repo_name: cliffano/pokeapi-clients

max_issues_repo_name: cliffano/pokeapi-clients

max_forks_repo_name: cliffano/pokeapi-clients


text:
//  Copyright (c) 2005-2007 Andre Merzky (andre@merzky.net)
//
//  Use, modification and distribution is subject to the Boost Software
//  License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

#ifndef _SAGA_PROCESS_H_
#define _SAGA_PROCESS_H_ 1

#include <map>
#include <vector>
#include <iostream>

// other includes from SAGA (this pulls export definitions, which we actually
// want, but can't include directly for some reason
#include <saga/saga/util.hpp>

// boost process
#include <boost/process.hpp>

// suppress warnings about dependent classes not being exported from the dll
#if defined(BOOST_MSVC)
#pragma warning(push)
#pragma warning(disable : 4251 4231 4660)
#endif

namespace saga
{
  namespace adaptors
  {
    namespace utils
    {
      class SAGA_EXPORT process
      {
        private:
          std::string                            cmd_;
          std::vector <std::string>              args_;
          std::map    <std::string, std::string> env_;

          boost::process::child c_;

          std::vector <std::string> out_v_;
          std::vector <std::string> err_v_;

          int         exit_;
          bool        done_;
          bool        fail_;
          std::string msg_;

        public:
          process (void);

          process (std::string                            cmd);
          process (std::vector <std::string>              const& args);
          process (std::map    <std::string, std::string> const& env);

          process (std::string                            cmd,
                   std::vector <std::string>              const& args);
          process (std::string                            cmd,
                   std::map    <std::string, std::string> const& env);

          process (std::string                            cmd,
                   std::vector <std::string>              const& args,
                   std::map    <std::string, std::string> const& env);

          void clear      (void);
          void set_cmd    (std::string cmd);

          void clear_args (void);
          void set_args   (std::vector <std::string> const& args);
          void add_arg    (std::string arg);
          void add_args   (std::string arg_1,
                           std::string arg_2);

          void clear_env  (void);
          void set_env    (std::map <std::string, std::string> const& env);
          void add_env    (std::string key, std::string val);

          std::vector <std::string>  run_sync  (bool io = true);

          void                       clear_out (void);
          void                       clear_err (void);

          boost::process::pistream & get_out   (void);
          boost::process::pistream & get_err   (void);

          std::string                get_out_s (void);
          std::string                get_err_s (void);

          std::vector <std::string>  get_out_v (void);
          std::vector <std::string>  get_err_v (void);

          int         exitcode (void) { return exit_; }
          bool        done     (void) { return done_; }
          bool        fail     (void) { return fail_; }
          std::string msg      (void) { return msg_;  }
      };

    } // namespace utils

  } // namespace adaptors

} // namespace saga

#if defined(BOOST_MSVC)
#pragma warning(pop)
#endif

#endif // _SAGA_PROCESS_H_

ext: hpp

max_stars_repo_name: saga-project/saga-cpp

max_issues_repo_name: saga-project/saga-cpp

max_forks_repo_name: saga-project/saga-cpp


text:
/*!
@file
Internal header to break cyclic dependencies.

@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)
 */

#ifndef BOOST_HANA_GROUP_DETAIL_GROUP_FWD_HPP
#define BOOST_HANA_GROUP_DETAIL_GROUP_FWD_HPP

#include <boost/hana/core/typeclass.hpp>
#include <boost/hana/detail/constexpr.hpp>

namespace boost { namespace hana {
    namespace group_detail { namespace operators { struct enable { }; }}

    //! @ingroup group-typeclasses
    //! The `Group` type class is used for `Monoid`s where all objects have
    //! an inverse w.r.t. the `Monoid`'s binary operation.
    //!
    //! The method names refer to the group of numbers under addition.
    //!
    //! ### Requires
    //! `Monoid`
    //!
    //! ### Laws
    //! For all objects `x` of a `Group` `G`, the following laws must be
    //! satisfied:
    //! @code
    //!     plus(x, negate(x)) == zero<G> // right inverse
    //!     plus(negate(x), x) == zero<G> // left inverse
    //! @endcode
    struct Group {
        BOOST_HANA_BINARY_TYPECLASS(Group);
        template <typename G1, typename G2>
        struct negate_mcd;
        template <typename G1, typename  G2>
        struct minus_mcd;
        struct laws;
        using operators = group_detail::operators::enable;
    };

    //! Subtract two elements of a group.
    //! @relates Group
    //!
    //! Specifically, this performs the `Monoid` operation on the first
    //! argument and on the inverse of the second argument, thus being
    //! equivalent to:
    //! @code
    //!     minus(x, y) == plus(x, negate(y))
    //! @endcode
    //!
    //! ### Example
    //! @snippet example/group/minus.cpp main
    BOOST_HANA_CONSTEXPR_LAMBDA auto minus = [](auto x, auto y) {
        return Group::instance<
            datatype_t<decltype(x)>, datatype_t<decltype(y)>
        >::minus_impl(x, y);
    };

    //! Return the inverse of an element of a group.
    //! @relates Group
    //!
    //! Since `Group` is a binary type class and `negate` is a unary method,
    //! `negate(x)` is dispatched to the type class instance for `G` and `G`,
    //! i.e. `Group::instance<G, G>`, where `G` is the data type of `x`.
    //!
    //! ### Example
    //! @snippet example/group/negate.cpp main
    BOOST_HANA_CONSTEXPR_LAMBDA auto negate = [](auto x) {
        return Group::instance<
            datatype_t<decltype(x)>, datatype_t<decltype(x)>
        >::negate_impl(x);
    };

    namespace group_detail { namespace operators {
        //! Equivalent to `minus`.
        //! @relates boost::hana::Group
        template <typename C1, typename C2>
        constexpr auto operator-(C1 c1, C2 c2)
        { return minus(c1, c2); }

        //! Equivalent to `negate`.
        //! @relates boost::hana::Group
        template <typename C1>
        constexpr auto operator-(C1 c1)
        { return negate(c1); }
    }}
}} // end namespace boost::hana

#endif // !BOOST_HANA_GROUP_DETAIL_GROUP_FWD_HPP

max_stars_repo_name: rbock/hana

max_issues_repo_name: rbock/hana

max_forks_repo_name: rbock/hana


text:
/*
 * Copyright 2020 Autoware Foundation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @file memory_monitor.cpp
 * @brief Memory monitor class
 */

#include <string>
#include <vector>
#include <boost/format.hpp>
#include <boost/process.hpp>
#include <system_monitor/mem_monitor/mem_monitor.h>

namespace bp = boost::process;

MemMonitor::MemMonitor(const ros::NodeHandle &nh, const ros::NodeHandle &pnh)
  : nh_(nh), pnh_(pnh)
{
  gethostname(hostname_, sizeof(hostname_));

  pnh_.param<float>("usage_warn", usage_warn_, 0.95);
  pnh_.param<float>("usage_error", usage_error_, 0.99);

  updater_.setHardwareID(hostname_);
  updater_.add("Memory Usage", this, &MemMonitor::checkUsage);
}

void MemMonitor::run(void)
{
  ros::Rate rate(1.0);

  while (ros::ok())
  {
    ros::spinOnce();
    updater_.force_update();
    rate.sleep();
  }
}

void MemMonitor::checkUsage(diagnostic_updater::DiagnosticStatusWrapper &stat)
{
  // Get total amount of free and used memory
  bp::ipstream is_out;
  bp::ipstream is_err;
  bp::child c("free -tb", bp::std_out > is_out, bp::std_err > is_err);
  c.wait();
  if (c.exit_code() != 0)
  {
    std::ostringstream os;
    is_err >> os.rdbuf();
    stat.summary(DiagStatus::ERROR, "free error");
    stat.add("free", os.str().c_str());
    return;
  }

  int level = DiagStatus::OK;
  std::string line;
  int index = 0;
  std::vector<std::string> list;
  float usage;

  while (std::getline(is_out, line) && !line.empty())
  {
    // Skip header
    if ( index <= 0 )
    {
      ++index;
      continue;
    }

    boost::split(list, line, boost::is_space(), boost::token_compress_on);

    // Physical memory
    if (index == 1)
    {
      // used divided by total is usage
      usage = std::atof(list[2].c_str()) / std::atof(list[1].c_str());

      if (usage >= usage_error_) level = DiagStatus::ERROR;
      else if (usage >= usage_warn_) level = DiagStatus::WARN;

      stat.addf((boost::format("%1% usage") % list[0]).str(), "%.2f%%", usage*1e+2);
    }

    stat.add((boost::format("%1% total") % list[0]).str(), toHumanReadable(list[1]));
    stat.add((boost::format("%1% used") % list[0]).str(), toHumanReadable(list[2]));
    stat.add((boost::format("%1% free") % list[0]).str(), toHumanReadable(list[3]));

    ++index;
  }

  stat.summary(level, usage_dict_.at(level));
}

std::string MemMonitor::toHumanReadable(const std::string &str)
{
  const char* units[] = {"B", "K", "M", "G", "T"};
  int count = 0;
  double size = std::atol(str.c_str());

  while (size > 1024)
  {
      size /= 1024;
      ++count;
  }
  const char* format = (size > 0 && size < 10) ? "%.1f%s" : "%.0f%s";
  return (boost::format(format) % size % units[count]).str();
}

ext: cpp


text:
//          Copyright Carl Philipp Reh 2009 - 2016.
// 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 <fcppt/cast/size.hpp>
#include <fcppt/container/grid/apply.hpp>
#include <fcppt/container/grid/object.hpp>
#include <fcppt/math/at_c.hpp>
#include <fcppt/math/dim/comparison.hpp>
#include <fcppt/math/dim/output.hpp>
#include <fcppt/preprocessor/disable_gcc_warning.hpp>
#include <fcppt/preprocessor/pop_warning.hpp>
#include <fcppt/preprocessor/push_warning.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/test/unit_test.hpp>
#include <string>
#include <fcppt/config/external_end.hpp>

FCPPT_PP_PUSH_WARNING
FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++)

BOOST_AUTO_TEST_CASE(
	container_grid_apply
)
{
FCPPT_PP_POP_WARNING

	typedef
	fcppt::container::grid::object<
		std::string,
		2
	>
	string_grid;

	typedef
	fcppt::container::grid::object<
		unsigned,
		2
	>
	uint_grid;

	uint_grid const grid1(
		uint_grid::dim{
			2u,
			3u
		},
		[](
			uint_grid::pos const _pos
		)
		{
			return
				fcppt::cast::size<
					unsigned
				>(
					fcppt::math::at_c<
						0
					>(
						_pos
					)
					+
					fcppt::math::at_c<
						1
					>(
						_pos
					)
				);
		}
	);

	string_grid const grid2(
		string_grid::dim{
			2u,
			3u
		},
		[](
			string_grid::pos const _pos
		)
		{
			return
				std::to_string(
					fcppt::math::at_c<
						0
					>(
						_pos
					)
					+
					fcppt::math::at_c<
						1
					>(
						_pos
					)
				);
		}
	);

	auto const function(
		[](
			unsigned const _value1,
			std::string const &_value2
		)
		{
			return
				std::to_string(
					_value1
				)
				+
				_value2
				;
		}
	);

	string_grid const result(
		fcppt::container::grid::apply(
			function,
			grid1,
			grid2
		)
	);

	BOOST_REQUIRE_EQUAL(
		grid1.size(),
		result.size()
	);

	BOOST_CHECK_EQUAL(
		result[
			string_grid::pos(
				0u,
				0u
			)
		],
		std::string(
			"00"
		)
	);

	BOOST_CHECK_EQUAL(
		result[
			string_grid::pos(
				1u,
				2u
			)
		],
		std::string(
			"33"
		)
	);

	BOOST_REQUIRE_EQUAL(
		fcppt::container::grid::apply(
			function,
			grid1,
			string_grid()
		).size(),
		string_grid::dim(
			0u,
			0u
		)
	);
}

max_stars_repo_name: vinzenz/fcppt

max_issues_repo_name: vinzenz/fcppt

max_forks_repo_name: vinzenz/fcppt


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

#define BOOST_TEST_MODULE Peerplays SON Tests

BOOST_AUTO_TEST_CASE(peerplays_sidechain) {
}

#include <boost/test/included/unit_test.hpp>
#include <cstdlib>
#include <iostream>

boost::unit_test::test_suite *init_unit_test_suite(int argc, char *argv[]) {
   std::srand(time(NULL));
   std::cout << "Random number generator seeded to " << time(NULL) << std::endl;

   return nullptr;
}


text:
//------------------------------------------------------------------------------
/*
    This file is part of rippled: https://github.com/ripple/rippled
    Copyright (c) 2017 Ripple Labs Inc.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose  with  or without fee is hereby granted, provided that the above
    copyright notice and this permission notice appear in all copies.

    THE  SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    WITH  REGARD  TO  THIS  SOFTWARE  INCLUDING  ALL  IMPLIED  WARRANTIES  OF
    MERCHANTABILITY  AND  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    ANY  SPECIAL ,  DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    WHATSOEVER  RESULTING  FROM  LOSS  OF USE, DATA OR PROFITS, WHETHER IN AN
    ACTION  OF  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <ripple/net/RegisterSSLCerts.h>
#include <boost/predef.h>

#if BOOST_OS_WINDOWS
#include <boost/asio/ssl/error.hpp>
#include <boost/system/error_code.hpp>
#include <memory>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <wincrypt.h>
#endif

namespace ripple {

void
registerSSLCerts(
    boost::asio::ssl::context& ctx,
    boost::system::error_code& ec,
    beast::Journal j)
{
#if BOOST_OS_WINDOWS
    auto certStoreDelete = [](void* h) {
        if (h != nullptr)
            CertCloseStore(h, 0);
    };
    std::unique_ptr<void, decltype(certStoreDelete)> hStore{
        CertOpenSystemStore(0, "ROOT"), certStoreDelete};

    if (!hStore)
    {
        ec = boost::system::error_code(
            GetLastError(), boost::system::system_category());
        return;
    }

    ERR_clear_error();

    std::unique_ptr<X509_STORE, decltype(X509_STORE_free)*> store{
        X509_STORE_new(), X509_STORE_free};

    if (!store)
    {
        ec = boost::system::error_code(
            static_cast<int>(::ERR_get_error()),
            boost::asio::error::get_ssl_category());
        return;
    }

    auto warn = [&](std::string const& mesg) {
        // Buffer based on asio recommended size
        char buf[256];
        ::ERR_error_string_n(ec.value(), buf, sizeof(buf));
        JLOG(j.warn()) << mesg << " " << buf;
        ::ERR_clear_error();
    };

    PCCERT_CONTEXT pContext = NULL;
    while ((pContext = CertEnumCertificatesInStore(hStore.get(), pContext)) !=
           NULL)
    {
        const unsigned char* pbCertEncoded = pContext->pbCertEncoded;
        std::unique_ptr<X509, decltype(X509_free)*> x509{
            d2i_X509(NULL, &pbCertEncoded, pContext->cbCertEncoded), X509_free};
        if (!x509)
        {
            warn("Error decoding certificate");
            continue;
        }

        if (X509_STORE_add_cert(store.get(), x509.get()) != 1)
        {
            warn("Error adding certificate");
        }
        else
        {
            // Successfully adding to the store took ownership
            x509.release();
        }
    }

    // This takes ownership of the store
    SSL_CTX_set_cert_store(ctx.native_handle(), store.release());

#else
    ctx.set_default_verify_paths(ec);
#endif
}

}  // namespace ripple

// There is a very unpleasant interaction between <wincrypt> and
// openssl x509 types (namely the former has macros that stomp
// on the latter), these undefs allow this TU to be safely used in
// unity builds without messing up subsequent TUs.
#if BOOST_OS_WINDOWS
#undef X509_NAME
#undef X509_EXTENSIONS
#undef X509_CERT_PAIR
#undef PKCS7_ISSUER_AND_SERIAL
#undef OCSP_REQUEST
#undef OCSP_RESPONSE
#endif

max_stars_repo_name: fff-source/rippled

max_issues_repo_name: madilraza/rippled

max_forks_repo_name: madilraza/rippled


text:
/*
 Copyright (C) GridGain Systems. All Rights Reserved.

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

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

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

/*  _________        _____ __________________        _____
 *  __  ____/___________(_)______  /__  ____/______ ____(_)_______
 *  _  / __  __  ___/__  / _  __  / _  / __  _  __ `/__  / __  __ \
 *  / /_/ /  _  /    _  /  / /_/ /  / /_/ /  / /_/ / _  /  _  / / /
 *  \____/   /_/     /_/   \_,__/   \____/   \__,_/  /_/   /_/ /_/
 */

#ifndef GRID_UUID_HPP_INCLUDED
#define GRID_UUID_HPP_INCLUDED

#include <iostream>
#include <string>
#include <functional>

#include <boost/uuid/uuid.hpp>

#include <gridgain/gridhasheableobject.hpp>

/**
 * Globally unique universal identifier.
 */
class GRIDGAIN_API GridClientUuid: public GridClientHasheableObject {
    class Impl {
    public:
        /** Wrapped Boost uuid. */
        boost::uuids::uuid uuid_;
    };
public:
    /**
     * Public default constructor. Creates an empty UUID.
     */
    GridClientUuid();

    /**
     * Reconstructs UUID from string.
     *
     * @param str String representation of UUID.
     */
    GridClientUuid(const char* str);

    /**
     * Reconstructs UUID from string.
     *
     * @param str String representation of UUID.
     */
    GridClientUuid(const std::string& str);

    /**
     * Copy constructor.
     *
     * @param other Another instance of UUID.
     */
    GridClientUuid(const GridClientUuid& other);

    /**
     * Constructs a new UUID from raw bytes.
     *
     * @param bytes Raw bytes.
     * @return A new UUID.
     */
    static GridClientUuid fromBytes(const std::string& bytes);

    /**
     * Generates a random UUID.
     *
     * @return New random UUID.
     */
    static GridClientUuid randomUuid();

    /**
     * Assignment operator override.
     *
     * @param rhs Right-hand side of the assignment operator.
     * @return This instance of the class.
     */
    GridClientUuid& operator=(const GridClientUuid& rhs);

    /** Destructor. */
    virtual ~GridClientUuid();

    /**
     * Comparison operator for UUID.
     *
     * @param other UUID to compare this UUID to.
     * @return <tt>true</tt> if this UUID is less than other, <tt>false</tt> otherwise.
     */
    bool operator <(const GridClientUuid& other) const;

    /**
     * Comparison operator for UUID.
     *
     * @param other UUID to compare this UUID to.
     * @return <tt>true</tt> if this UUID equals another, <tt>false</tt> otherwise.
     */
    bool operator ==(const GridClientUuid& other) const;

    /**
     * Returns hash code for this UUID following Java conventions.
     *
     * @return Hash code.
     */
    virtual int32_t hashCode() const;

    /**
     * Converts UUID to string.
     *
     * @return String representation iof UUID.
     */
    const std::string uuid() const;

    /**
     * Least significant bits in UUID.
     *
     * @return 4 least significant bits packed in 64-bit integer.
     */
    int64_t leastSignificantBits() const;

    /**
     * Most significant bits in UUID.
     *
     * @return 4 most significant bits packed in 64-bit integer.
     */
    int64_t mostSignificantBits() const;

    /**
     * Converts this UUID to byte array.
     *
     * This method is used for hash calculation and uses
     * special byte ordering.
     *
     * @param bytes Vector to fill.
     */
    virtual void convertToBytes(std::vector<int8_t>& bytes) const;

    /**
     * Reads the UUID raw bytes to byte vector.
     *
     * Byte order is not changed.
     *
     * @param bytes Vector to fill.
     */
    void rawBytes(std::vector<int8_t>& bytes) const;
private:
    Impl pimpl;

    /**
     * Prints UUID to stream
     *
     * @param out Stream to output UUID to.
     * @param u UUID.
     */
    friend std::ostream& operator<<(std::ostream &out, const GridClientUuid& u);
};

inline std::ostream& operator<<(std::ostream &out, const GridClientUuid& u) {
    return out << u.uuid();
}

namespace std {

/** Hash code for UUID for unordered_map. */
#ifdef _MSC_VER
template<> inline
size_t hash<GridClientUuid>::operator()(const GridClientUuid& u) const {
    return u.hashCode();
}
#else
template<> struct hash<GridClientUuid> {
    size_t operator()(GridClientUuid u) const {
        return u.hashCode();
    }
};
#endif

}

#endif

max_stars_repo_name: cybernetics/gridgain

max_issues_repo_name: cybernetics/gridgain

max_forks_repo_name: cybernetics/gridgain


text:
#ifndef YAC_EXPRESSION_GRAMMAR_HPP
#define YAC_EXPRESSION_GRAMMAR_HPP
/*=============================================================================
    Copyright (c) 2004 Angus Leeming

    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 "yac_binary_op_parser.hpp"
#include "yac_lazy_functions.hpp"
#include "yac_name_grammar.hpp"
#include "yac_stack_closure.hpp"
#include "yac_virtual_machine.hpp"

#include <boost/spirit/core.hpp>
#include <boost/spirit/phoenix.hpp>
#include <boost/spirit/utility/lists.hpp>
#include <boost/spirit/symbols/symbols.hpp>
#include <boost/spirit/dynamic/if.hpp>

#include <string>

namespace spirit = boost::spirit;

namespace yac {

boost::shared_ptr<function>
checked_find(spirit::symbols<boost::shared_ptr<function> > const & symbols,
             std::string const & name)
{
    boost::shared_ptr<function> * ptr = find(symbols, name.c_str());
    BOOST_ASSERT(ptr && ptr->get());
    return *ptr;
}

struct checked_find_impl {
    typedef boost::shared_ptr<function> function_ptr_t;
    typedef spirit::symbols<function_ptr_t> function_table_t;

    template <typename T1, typename T2>
    struct result {
        typedef function_ptr_t type;
    };

    function_ptr_t operator()(function_table_t const & symbols,
                              std::string const & name) const
    {
        function_ptr_t * ptr = find(symbols, name.c_str());
        return ptr ? *ptr : function_ptr_t();
    }
};

phoenix::function<checked_find_impl> const checked_find_ = checked_find_impl();

struct func_expr_closure
    : spirit::closure<func_expr_closure,
                      stack, std::string, int, boost::shared_ptr<function> >
{
    member1 stk;
    member2 name;
    member3 arity;
    member4 func_ptr;
};

struct logical_closure
    : spirit::closure<logical_closure, stack, bool>
{
    member1 stk;
    member2 or_op;
};

struct conditional_closure
    : spirit::closure<conditional_closure, stack, stack, stack>
{
    member1 stk;
    member2 stk1;
    member3 stk2;
};

struct expression_grammar
    : spirit::grammar<expression_grammar, stack_closure::context_t>
{
    typedef boost::shared_ptr<function> function_ptr_t;
    typedef spirit::symbols<function_ptr_t> function_table_t;
    typedef spirit::symbols<double> var_table_t;

    var_table_t const dummy_local_vars;

    function_table_t const & functions;
    var_table_t const & global_vars;
    var_table_t const & local_vars;

    expression_grammar(function_table_t const & funcs,
                       var_table_t const & gvars)
        : functions(funcs), global_vars(gvars), local_vars(dummy_local_vars)
    {}

    expression_grammar(function_table_t const & funcs,
                       var_table_t const & gvars,
                       var_table_t const & lvars)
        : functions(funcs), global_vars(gvars), local_vars(lvars)
    {}

    template <typename ScannerT>
    struct definition {
        definition(expression_grammar const & self)
            : name(false)
        {
            using phoenix::arg1;
            using phoenix::arg2;
            using phoenix::construct_;
            using phoenix::if_;
            using phoenix::new_;
            using phoenix::var;

            using spirit::ch_p;
            using spirit::epsilon_p;
            using spirit::if_p;
            using spirit::list_p;
            using spirit::nothing_p;
            using spirit::real_p;
            using spirit::str_p;

            boolean_op.add
                ("&&", false)
                ("||", true);

            add_op.add
                ("+", checked_find(self.functions, "add##2"))
                ("-", checked_find(self.functions, "subtract##2"));

            bitwise_op.add
                ("&", checked_find(self.functions, "bitwise_and##2"))
                ("|", checked_find(self.functions, "bitwise_or##2"))
                ("^", checked_find(self.functions, "bitwise_xor##2"));

            compare_op.add
                ("<",  checked_find(self.functions, "less##2"))
                (">",  checked_find(self.functions, "greater##2"))
                ("<=", checked_find(self.functions, "less_equal##2"))
                (">=", checked_find(self.functions, "greater_equal##2"));

            equality_op.add
                ("==", checked_find(self.functions, "equal##2"))
                ("!=", checked_find(self.functions, "not_equal##2"));

            mult_op.add
                ("*", checked_find(self.functions, "multiply##2"))
                ("/", checked_find(self.functions, "divide##2"))
                ("%", checked_find(self.functions, "mod##2"));

            shift_op.add
                ("<<", checked_find(self.functions, "shift_left##2"))
                (">>", checked_find(self.functions, "shift_right##2"));

            unary_op.add
                ("+", function_ptr_t())
                ("-", checked_find(self.functions, "negate##1"))
                ("!", checked_find(self.functions, "logical_not##1"));

            top = expr[self.stk = arg1];

            expr
                =  logical_expr[expr.stk = arg1]
                >> !conditional_expr_helper[expr.stk += arg1];

            conditional_expr_helper
                =  (ch_p('?')
                >>  expr
                    [
                        conditional_expr_helper.stk1 = arg1
                    ]
                >>  ':'
                >>  expr
                    [
                        conditional_expr_helper.stk2 = arg1
                    ]
                >>  !conditional_expr_helper
                    [
                        conditional_expr_helper.stk2 += arg1
                    ]
                   )
                   [
                       push_back(conditional_expr_helper.stk,
                                 new_<branch_node>(
                                     conditional_expr_helper.stk1,
                                     conditional_expr_helper.stk2))
                   ]
                ;

           logical_expr
                =  bitwise_expr
                   [
                       logical_expr.stk = arg1
                   ]
                >> *(logical_expr_helper
                     [
                         logical_expr.stk += arg1
                     ]
                    )
                ;

            logical_expr_helper
                =  boolean_op
                   [
                       logical_expr_helper.or_op = arg1
                   ]
                >> bitwise_expr
                   [
                       if_(logical_expr_helper.or_op)
                       [
                           push_back(logical_expr_helper.stk,
                                     new_<or_node>(arg1))
                       ]
                       .else_
                       [
                           logical_expr_helper.stk = arg1,
                           push_back(logical_expr_helper.stk,
                                     new_<sys_function_node>(
                                         checked_find(self.functions, "logical_and##2")))
                       ]
                   ]
                ;

            bitwise_expr
                = binary_op_p(equality_expr, bitwise_op)[bitwise_expr.stk = arg1];

            equality_expr
                = binary_op_p(compare_expr, equality_op)[equality_expr.stk = arg1];

            compare_expr
                = binary_op_p(shift_expr, compare_op)[compare_expr.stk = arg1];

            shift_expr
                = binary_op_p(add_expr, shift_op)[shift_expr.stk = arg1];

            add_expr
                = binary_op_p(mult_expr, add_op)[ add_expr.stk = arg1 ];

            mult_expr
                = binary_op_p(expr_atom, mult_op)[ mult_expr.stk = arg1 ];

            expr_atom
                = number
                  [
                      expr_atom.stk = arg1
                  ]
                | func
                  [
                      expr_atom.stk = arg1
                  ]
                | ('(' >>
                   expr
                   [
                       expr_atom.stk = arg1
                   ]
                   >> ')')
                | unary_expr
                  [
                      expr_atom.stk = arg1
                  ]
                ;

            unary_expr
                =  unary_op
                   [
                      unary_expr.func_ptr = arg1
                   ]
                >> expr_atom
                   [
                       unary_expr.stk = arg1,
                       if_(unary_expr.func_ptr != function_ptr_t())
                       [
                           push_back(unary_expr.stk,
                                     new_<sys_function_node>(unary_expr.func_ptr))
                       ]
                   ]
                ;

            number
                = real_p
                  [
                      push_back(number.stk,
                                new_<const_value_node>(arg1))
                  ]
                | self.local_vars
                  [
                      push_back(number.stk,
                                new_<variable_node>(address_of(arg1)))
                  ]
                | self.global_vars
                  [
                      push_back(number.stk,
                                new_<variable_node>(address_of(arg1)))
                  ]
	      | str_p("x")
	      [
	       push_back(number.stk, new_<x_node>())
		]
	      | str_p("y")
	      [
	       push_back(number.stk, new_<y_node>())
		]
	      | str_p("t")
	      [
	       push_back(number.stk, new_<t_node>())
	       ]
                ;

            func
                =  name
                   [
                       func.arity = 0,
                       func.name = construct_<std::string>(arg1, arg2)
                   ]
                >> ('(' >> !list_p(arg, ',') >> ')')
                   [
                       func.func_ptr
                           = checked_find_(var(self.functions),
                                           mangled_name(func.name, func.arity))
                   ]
                   // If the function is found in the symbol table, then
                   // add it to the stack. Else fail the parser.
                >> if_p(func.func_ptr != function_ptr_t())
                   [
                       epsilon_p
                       [
                           push_back(func.stk,
                                     new_<sys_function_node>(func.func_ptr))
                       ]
                   ]
                  .else_p[nothing_p]
                ;

            arg
                = expr
                  [
                      func.arity += 1,
                      func.stk += arg1
                  ]
                ;
        }

        typedef ScannerT scanner_t;
        typedef spirit::rule<scanner_t> rule_t;

        rule_t const & start() const { return top; }

    private:
        typedef spirit::rule<scanner_t, stack_closure::context_t> srule_t;
        typedef spirit::rule<scanner_t, func_expr_closure::context_t> frule_t;
        typedef spirit::rule<scanner_t, logical_closure::context_t> lrule_t;
        typedef spirit::rule<scanner_t, conditional_closure::context_t> crule_t;

        rule_t arg, top;
        srule_t add_expr, and_expr, bitwise_expr, compare_expr,
            equality_expr, expr, expr_atom, logical_expr,
            number, or_expr, or_op, mult_expr, shift_expr;
        frule_t unary_expr, func;
        crule_t conditional_expr_helper;
        lrule_t logical_expr_helper;
        name_grammar name;

        spirit::symbols<bool> boolean_op;
        function_table_t and_op, add_op, bitwise_op, compare_op, equality_op,
            shift_op, mult_op, unary_op;
    };
};

} // namespace yac

#endif // YAC_EXPRESSION_GRAMMAR_HPP

max_stars_repo_name: Devaraj-G/volna

max_issues_repo_name: Devaraj-G/volna

max_forks_repo_name: Devaraj-G/volna


text:
//==============================================================================
//         Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011 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
//==============================================================================
#ifndef NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_IMPL_LOGS_F_LOG_HPP_INCLUDED
#define NT2_EXPONENTIAL_FUNCTIONS_SIMD_COMMON_IMPL_LOGS_F_LOG_HPP_INCLUDED

#include <nt2/include/functions/simd/multiplies.hpp>
#include <nt2/include/functions/simd/plus.hpp>
#include <nt2/include/functions/simd/fma.hpp>
#include <nt2/include/functions/simd/is_eqz.hpp>
#include <nt2/include/functions/simd/if_allbits_else.hpp>
#include <nt2/include/functions/simd/if_else.hpp>
#include <nt2/include/functions/simd/if_else_zero.hpp>
#include <nt2/include/functions/simd/is_ltz.hpp>
#include <nt2/exponential/functions/scalar/impl/logs/f_kernel.hpp>
#include <nt2/include/constants/mhalf.hpp>
#include <nt2/include/constants/minf.hpp>
#include <nt2/include/constants/log_2hi.hpp>
#include <nt2/include/constants/log_2lo.hpp>
#include <nt2/include/constants/log2_em1.hpp>
#include <nt2/include/constants/log10_ehi.hpp>
#include <nt2/include/constants/log10_elo.hpp>
#include <nt2/include/constants/log10_2hi.hpp>
#include <nt2/include/constants/log10_2lo.hpp>
#include <nt2/sdk/meta/as_logical.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/sdk/meta/scalar_of.hpp>
#include <boost/simd/sdk/config.hpp>
#include <boost/simd/sdk/meta/as_logical.hpp>

#ifndef BOOST_SIMD_NO_NANS
#include <nt2/include/functions/simd/is_nan.hpp>
#include <nt2/include/functions/simd/logical_or.hpp>
#endif
#ifndef BOOST_SIMD_NO_INFINITIES
#include <nt2/include/constants/inf.hpp>
#include <nt2/include/functions/simd/is_equal.hpp>
#endif
#ifndef BOOST_SIMD_NO_DENORMALS
#include <nt2/include/functions/simd/abs.hpp>
#include <nt2/include/functions/simd/is_less.hpp>
#include <nt2/include/constants/smallestposval.hpp>
#include <nt2/include/constants/twotonmb.hpp>
#include <nt2/include/constants/mlogtwo2nmb.hpp>
#include <nt2/include/constants/mlog2two2nmb.hpp>
#include <nt2/include/constants/mlog10two2nmb.hpp>
#endif

  //////////////////////////////////////////////////////////////////////////////
  // how to compute the various logarithms
  //////////////////////////////////////////////////////////////////////////////
  // The method is mainly taken from the cephes library:
  // first reduce the the data
  // a0 is supposed > 0
  // the input a0 is split into a mantissa and an exponent
  // the mantissa m is between sqrt(0.5) and sqrt(2) and the correspondint exponent is e
  // a0 = m*2^e
  // then the log? calculus is split in two parts (? being nothing: natural logarithm,  2: base 2 logarithm,  10 base ten logarithm)
  // as log?(a) = log?(2^e)+log?(m)
  // 1) computing log?(m)
  //   first put x = m-1 (so -0.29 <  x < 0.414)
  //   write log(m)   = log(1+x)   = x + x*x/2 + x*x*x*g(x)
  //   write log2(m)  = log2(1+x)  = C2*log(x)   C2 =  log(2)  the multiplication have to be taken seriously as C2 is not exact
  //   write log10(m) = log10(1+x) = C10*log(x)  C10=  log(10) the multiplication have to be taken seriously as C10 is not exact
  // then g(x) has to be approximated
  // g is ((log(1+x)/x-1)/x-1/2)/x
  // It is not a good idea to approximate directly log(1+x) instead of g,  because this will lead to bad precision around 1.
  //
  // in this approximation one can choose a best approximation rational function given by remez algorithm.
  // there exist a classical solution which is a polynomial p8 one of degree 8 that gives 0.5ulps everywhere
  // this is what is done in the kernel_t::log impl;
  // Now,  it is possible to choose a rational fraction or a polynomial of lesser degree to approximate g
  // providing faster but less accurate logs.
  // 2) computing log?(2^e)
  // see the explanations relative to each case
  // 3) finalize
  // This is simply treating invalid entries
  // 4) For denormal we use the fact that log(x) =  log?(x*y)-log?(y) and that if y is
  // the constant two2nmb if x is denormal x*y and y are not.
  //////////////////////////////////////////////////////////////////////////////

namespace nt2 { namespace details
{
  //////////////////////////////////////////////////////////////////////////////
  // math log functions
  //////////////////////////////////////////////////////////////////////////////

  template < class A0 >
  struct logarithm< A0, tag::simd_type, float>
  {
    typedef typename meta::as_logical<A0>::type                 lA0;
    typedef typename meta::as_integer<A0, signed>::type    int_type;
    typedef typename meta::scalar_of<A0>::type                  sA0;
    typedef kernel<A0, tag::simd_type, float>              kernel_t;

    static inline A0 log(const A0& a0)
    {
      A0 z = a0;
#ifndef BOOST_SIMD_NO_DENORMALS
      A0 t = Zero<A0>();
      lA0 denormal = lt(nt2::abs(z), Smallestposval<A0>());
      z = if_else(denormal, z*Twotonmb<A0>(), z);
      t = if_else_zero(denormal, Mlogtwo2nmb<A0>());
#endif
      //log(2.0) in double is 6.931471805599453e-01
      //double(0.693359375f)+double(-0.00021219444f)  is  6.931471805600000e-01 at 1.0e-14 of log(2.0)
      // let us call Log_2hi 0.693359375f anf Log_2lo -0.00021219444f
      // We use thi to correct the sum where this could matter a lot
      // log(a0) = fe*Log_2hi+ (0.5f*x*x +(fe*Log_2lo+y))
      // These operations are order dependent: the parentheses do matter
      A0 x, fe, x2, y;
      kernel_t::log(z, fe, x, x2, y);
      y = nt2::fma(fe, Log_2lo<A0>(), y);
      y = nt2::fma(Mhalf<A0>(), x2, y);
#ifdef BOOST_SIMD_NO_DENORMALS
      return finalize(a0, nt2::fma(Log_2hi<A0>(), fe, x+y));
#else
      return finalize(a0, nt2::fma(Log_2hi<A0>(), fe, x+y+t));
#endif
    }

    static inline A0 log2(const A0& a0)
    {
      A0 z =  a0;
#ifndef BOOST_SIMD_NO_DENORMALS
      lA0 denormal = lt(nt2::abs(z), Smallestposval<A0>());
      z = if_else(denormal, z*Twotonmb<A0>(), z);
      A0 t = if_else_zero(denormal, Mlog2two2nmb<A0>());
#endif
      //here let l2em1 = log2(e)-1, the computation is done as:
      //log2(a0) = ((l2em1*x+(l2em1*(y+x*x/2)))+(y+x*x/2)))+x+fe for best results
      // once again the order is very important.
      A0 x, fe, x2, y;
      kernel_t::log(z, fe, x, x2, y);
      y =  nt2::fma(Mhalf<A0>(),x2, y);
      z = nt2::fma(x,Log2_em1<A0>(),y*Log2_em1<A0>());
#ifdef BOOST_SIMD_NO_DENORMALS
      return finalize(a0, ((z+y)+x)+fe);
#else
      return finalize(a0, ((z+y)+x)+fe+t);
#endif
    }

    static inline A0 log10(const A0& a0)
    {
      A0 z = a0;
#ifndef BOOST_SIMD_NO_DENORMALS
      lA0 denormal = lt(nt2::abs(z), Smallestposval<A0>());
      z = if_else(denormal, z*Twotonmb<A0>(), z);
      A0 t = if_else_zero(denormal, Mlog10two2nmb<A0>());
#endif
      // here there are two multiplication:  log of fraction by log10(e) and base 2 exponent by log10(2)
      // and we have to split log10(e) and log10(2) in two parts to get extra precision when needed
      A0 x, fe, x2, y;
      kernel_t::log(z, fe, x, x2, y);
      y = nt2::amul(y, Mhalf<A0>(), x2);
      z = mul(x+y, Log10_elo<A0>());
      z = nt2::amul(z, y, Log10_ehi<A0>());
      z = nt2::amul(z, x, Log10_ehi<A0>());
      z = nt2::amul(z, fe, Log10_2hi<A0>());
#ifdef BOOST_SIMD_NO_DENORMALS
      return finalize(a0, nt2::amul(z, fe, Log10_2lo<A0>()));
#else
      return finalize(a0, nt2::amul(z+t, fe, Log10_2lo<A0>()));
#endif
    }
  private:
    static inline A0 finalize(const A0& a0, const A0& y)
    {
      typedef typename meta::as_logical<A0>::type              lA0;
    #ifdef BOOST_SIMD_NO_NANS
      lA0 test = nt2::is_ltz(a0);
    #else
      lA0 test = nt2::logical_or(nt2::is_ltz(a0), nt2::is_nan(a0));
    #endif
      A0 y1 = nt2::if_nan_else(test, y);
    #ifndef BOOST_SIMD_NO_INFINITIES
      y1 = if_else(nt2::is_equal(a0, nt2::Inf<A0>()), a0, y1);
    #endif
      return if_else(is_eqz(a0), nt2::Minf<A0>(), y1);
    }
  };
} }

#endif


text:
#include <boost/hana/assert.hpp>
#include <boost/hana/at.hpp>
#include <boost/hana/core/to.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/integral_constant.hpp>
#include <boost/hana/not.hpp>

#include <literal/basic_string.hpp>

#include <gtest/gtest.h>
#include <type_traits>

namespace hana = boost::hana;

// bool test
template <typename T>
struct BoolTest : public ::testing::Test {
  // concept declarations of type T
  using expected_type = typename T::first_type;
  using actual_type = typename T::second_type;
  static_assert(std::is_same<typename expected_type::value_type, bool>::value,
                "first_type must be a bool");
  static_assert(std::is_same<typename actual_type::value_type, bool>::value,
                "second_type must be a bool");
};

TYPED_TEST_CASE_P(BoolTest);

// true test
template <typename T>
struct TrueTest : public ::testing::Test {
  // concept declarations of type T
  using actual_type = T;
  static_assert(std::is_same<typename actual_type::value_type, bool>::value,
                "type must be a bool");
};

TYPED_TEST_CASE_P(TrueTest);

template <typename T>
struct SameTest : public ::testing::Test {
  // concept declarations of type T
  using expected_type = typename T::first_type;
  using actual_type = typename T::second_type;
};

TYPED_TEST_CASE_P(SameTest);

template <typename Ex,
          typename T,
          template <T...> typename S,
          char... c>
struct AliasPair {
  using expected_type = Ex;
  using char_type = T;
  using str_type = S<static_cast<T>(c)...>;

  AliasPair() {
  }

  bool isExpected() const noexcept {
    return std::is_same<expected_type, str_type>::value;
  }
};

template <typename T>
struct AliasTest : public ::testing::Test {
};

template <typename T>
struct HanaTest : public ::testing::Test {
};

TYPED_TEST_CASE_P(AliasTest);
TYPED_TEST_CASE_P(HanaTest);

TYPED_TEST_P(BoolTest, CheckBoolean) {
  bool actual = typename TypeParam::second_type();
  if (typename TypeParam::first_type()) {
    ASSERT_TRUE(actual);
  } else {
    ASSERT_FALSE(actual);
  }
}

TYPED_TEST_P(TrueTest, CheckTrue) {
  bool actual = typename TypeParam::type();
  ASSERT_TRUE(actual);
}

TYPED_TEST_P(SameTest, CheckSame) {
  auto r =std::is_same<
    typename TypeParam::first_type,
    typename TypeParam::second_type>::value;
  ASSERT_TRUE(r);
}

TYPED_TEST_P(AliasTest, AliasCheckSame) {
  ASSERT_TRUE(TypeParam().isExpected());
}

REGISTER_TYPED_TEST_CASE_P(BoolTest, CheckBoolean);
REGISTER_TYPED_TEST_CASE_P(TrueTest, CheckTrue);
REGISTER_TYPED_TEST_CASE_P(SameTest, CheckSame);
REGISTER_TYPED_TEST_CASE_P(AliasTest, AliasCheckSame);

// short hand
template <typename T0, typename T1>
using p = std::pair<T0, T1>;

template <typename Ex,
          typename T,
          template <T...> typename S,
          char... c>
using a = AliasPair<Ex, T, S, c...>;

using true_type = std::true_type;
using false_type = std::false_type;

// construct macro
template <typename C>
auto macro_test_s1 = BOOST_HANA_BASIC_STRING(C, "");
template <typename C>
auto macro_test_s2 = BOOST_HANA_BASIC_STRING(C, "a");
template <typename C>
auto macro_test_s3 = BOOST_HANA_BASIC_STRING(C, "abcd");
template <typename C>
auto macro_test_s4 = BOOST_HANA_BASIC_STRING(C, "\x80\xff\xa0");

#if 0
template <typename C>
using MacroTarget = ::testing::Types<
  p<true_type, std::is_same<decltype(macro_test_s1<C>),
                            hana::basic_string<C>>>,
  p<true_type, std::is_same<decltype(macro_test_s2<C>),
                            hana::basic_string<C, (C)'a'>>>,
  p<true_type, std::is_same<decltype(macro_test_s3<C>),
                            hana::basic_string<C, (C)'a', (C)'b', (C)'c', (C)'d'>>>
  >;
#endif
template <typename C>
using MacroTarget = ::testing::Types<
  p<decltype(macro_test_s1<C>),
    hana::basic_string<C>>,
  p<decltype(macro_test_s2<C>),
    hana::basic_string<C, (C)'a'>>,
  p<decltype(macro_test_s3<C>),
    hana::basic_string<C, (C)'a', (C)'b', (C)'c', (C)'d'>>,
  p<decltype(macro_test_s4<C>),
    hana::basic_string<C, (C)0x080, (C)0x0ff, (C)0x0a0>>
  >;

using AliasMacroTarget = ::testing::Types<
  a<decltype(macro_test_s1<char>), char, hana::string_b>,
  a<decltype(macro_test_s2<char>), char, hana::string_b, 'a'>,
  a<decltype(macro_test_s3<char>), char, hana::string_b, 'a', 'b', 'c', 'd'>,
  a<decltype(macro_test_s1<wchar_t>), wchar_t, hana::wstring>,
  a<decltype(macro_test_s2<wchar_t>), wchar_t, hana::wstring, 'a'>,
  a<decltype(macro_test_s3<wchar_t>), wchar_t, hana::wstring, 'a', 'b', 'c', 'd'>,
  a<decltype(macro_test_s1<char16_t>), char16_t, hana::u16string>,
  a<decltype(macro_test_s2<char16_t>), char16_t, hana::u16string, 'a'>,
  a<decltype(macro_test_s3<char16_t>), char16_t, hana::u16string, 'a', 'b', 'c', 'd'>,
  a<decltype(macro_test_s1<char32_t>), char32_t, hana::u32string>,
  a<decltype(macro_test_s2<char32_t>), char32_t, hana::u32string, 'a'>,
  a<decltype(macro_test_s3<char32_t>), char32_t, hana::u32string, 'a', 'b', 'c', 'd'>
  >;

INSTANTIATE_TYPED_TEST_CASE_P(BStrCharMacro, SameTest,
                              MacroTarget<char>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrWCharMacro, SameTest,
                              MacroTarget<wchar_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar16Macro, SameTest,
                              MacroTarget<char16_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar32Macro, SameTest,
                              MacroTarget<char32_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrAliasMacro, AliasTest,
                              AliasMacroTarget);

// make
template <typename C>
using MakeTarget = ::testing::Types<
  decltype(hana::equal(hana::make<hana::basic_string_tag<C>>(),
                       hana::basic_string_c<C>)),
  decltype(hana::equal(hana::make<hana::basic_string_tag<C>>(
                         hana::basic_char_c<C, (C)'a'>),
                       hana::basic_string_c<C, (C)'a'>)),
  decltype(hana::equal(hana::make<hana::basic_string_tag<C>>(
                         hana::basic_char_c<C, (C)'a'>,
                         hana::basic_char_c<C, (C)'b'>
                       ),
                       hana::basic_string_c<C, (C)'a', (C)'b'>)),
  decltype(hana::equal(hana::make<hana::basic_string_tag<C>>(
                         hana::basic_char_c<C, (C)'a'>,
                         hana::basic_char_c<C, (C)'b'>,
                         hana::basic_char_c<C, (C)'c'>
                       ),
                       hana::basic_string_c<C, (C)'a', (C)'b', (C)'c'>)),
  decltype(hana::equal(hana::make<hana::basic_string_tag<C>>(
                         hana::basic_char_c<C, (C)'a'>,
                         hana::basic_char_c<C, (C)'b'>,
                         hana::basic_char_c<C, (C)'c'>,
                         hana::basic_char_c<C, (C)'d'>
                       ),
                       hana::basic_string_c<C, (C)'a', (C)'b', (C)'c', (C)'d'>)),
  decltype(hana::equal(hana::make_basic_string<C>(
                         hana::basic_char_c<C, (C)'a'>,
                         hana::basic_char_c<C, (C)'b'>,
                         hana::basic_char_c<C, (C)'c'>),
                       hana::make<hana::basic_string_tag<C>>(
                         hana::basic_char_c<C, (C)'a'>,
                         hana::basic_char_c<C, (C)'b'>,
                         hana::basic_char_c<C, (C)'c'>
                       )))
  >;

INSTANTIATE_TYPED_TEST_CASE_P(BStrCharMake, TrueTest,
                              MakeTarget<char>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrWCharMake, TrueTest,
                              MakeTarget<wchar_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar16Make, TrueTest,
                              MakeTarget<char16_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar32Make, TrueTest,
                              MakeTarget<char32_t>);

// to
template <typename C>
using ToTarget0 = ::testing::Types<
  p<true_type, hana::is_convertible<hana::basic_string_tag<C>, C const*>>,
  p<false_type, hana::is_embedded<hana::basic_string_tag<C>, C const*>>
  >;

INSTANTIATE_TYPED_TEST_CASE_P(BStrCharTo, BoolTest,
                              ToTarget0<char>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrWCharTo, BoolTest,
                              ToTarget0<wchar_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar16To, BoolTest,
                              ToTarget0<char16_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar32To, BoolTest,
                              ToTarget0<char32_t>);

// any_of
template <typename C>
using AnyOfTarget = ::testing::Types<
  p<true_type, decltype(hana::any_of(
                          macro_test_s3<C>,
                          hana::equal.to(hana::basic_char_c<C, (C)'d'>)))>,
  p<true_type, decltype(hana::not_(hana::any_of(
                          macro_test_s1<C>,
                          hana::always(hana::true_c))))>,
  p<true_type, decltype(hana::not_(hana::any_of(
                          macro_test_s3<C>,
                          hana::equal.to(hana::basic_char_c<C, (C)'z'>))))>
  >;

INSTANTIATE_TYPED_TEST_CASE_P(BStrCharAnyOf, BoolTest,
                              AnyOfTarget<char>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrWCharAnyOf, BoolTest,
                              AnyOfTarget<wchar_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar16AnyOf, BoolTest,
                              AnyOfTarget<char16_t>);
INSTANTIATE_TYPED_TEST_CASE_P(BStrChar32AnyOf, BoolTest,
                              AnyOfTarget<char32_t>);

// at
TYPED_TEST_P(HanaTest, CheckHanaAt) {
  using C = TypeParam;

  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(BOOST_HANA_BASIC_STRING(C, "abcd")[hana::size_c<2>],
                hana::basic_char_c<C, 'c'>));

  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "a"), hana::size_c<0>),
                hana::basic_char_c<C, 'a'>));
  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "ab"), hana::size_c<0>),
                hana::basic_char_c<C, 'a'>));
  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "abc"), hana::size_c<0>),
                hana::basic_char_c<C, 'a'>));

  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "ab"), hana::size_c<1>),
                hana::basic_char_c<C, 'b'>));
  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "abc"), hana::size_c<1>),
                hana::basic_char_c<C, 'b'>));
  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "abcd"), hana::size_c<1>),
                hana::basic_char_c<C, 'b'>));

  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "abc"), hana::size_c<2>),
                hana::basic_char_c<C, 'c'>));
  BOOST_HANA_CONSTANT_CHECK(
    hana::equal(hana::at(BOOST_HANA_BASIC_STRING(C, "abcd"), hana::size_c<2>),
                hana::basic_char_c<C, 'c'>));

  ASSERT_TRUE(true);
}

// c_str
template <typename C>
int basic_strcmp(C const* l, C const* r) {
  for (;*l != static_cast<C>('\0'); l++, r++) {
    if (*l != *r) {
      return *l < *r ? -1 : 1;
    }
  }
  return *r == static_cast<C>('\0') ? 0 : -1;
}

struct LiteralChooser {
  char const* char_literal;
  wchar_t const* wchar_literal;
  char16_t const* char16_literal;
  char32_t const* char32_literal;

  constexpr LiteralChooser(
    char const* char_literal,
    wchar_t const* wchar_literal,
    char16_t const* char16_literal,
    char32_t const* char32_literal
  ) : char_literal(char_literal),
    wchar_literal(wchar_literal),
    char16_literal(char16_literal),
    char32_literal(char32_literal)
  {
  }
  template <typename Ch>
  constexpr operator Ch const *() const noexcept;
};

template <>
constexpr LiteralChooser::operator char const*()
  const noexcept {
  return char_literal;
}

template <>
constexpr LiteralChooser::operator wchar_t const*()
  const noexcept {
  return wchar_literal;
}

template <>
constexpr LiteralChooser::operator char16_t const*()
  const noexcept {
  return char16_literal;
}

template <>
constexpr LiteralChooser::operator char32_t const*()
  const noexcept {
  return char32_literal;
}

#define CNV_CHTYPE(CH, PREFIX) (PREFIX ## CH)
#define CONVERT_CH(TYPE, CH) \
  LiteralChooser{ CH, CNV_CHTYPE(CH,L), CNV_CHTYPE(CH,u), CNV_CHTYPE(CH,U) }

TYPED_TEST_P(HanaTest, CheckHanaCStr) {
  using C = TypeParam;

  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "").c_str(),
      CONVERT_CH(C, "")) == 0);

  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "a").c_str(),
      CONVERT_CH(C, "a")) == 0);

  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "ab").c_str(),
      CONVERT_CH(C, "ab")) == 0);
  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "abc").c_str(),
      CONVERT_CH(C, "abc")) == 0);
  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "ab").c_str(),
      CONVERT_CH(C, "a")) > 0);
  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "a").c_str(),
      CONVERT_CH(C, "ab")) < 0);
  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "a").c_str(),
      CONVERT_CH(C, "b")) < 0);
  BOOST_HANA_RUNTIME_CHECK(
    basic_strcmp<C>(
      BOOST_HANA_BASIC_STRING(C, "\x80\xa0\xff").c_str(),
      CONVERT_CH(C, "\x80\xa0\xff")) == 0);

  {
    auto str = BOOST_HANA_BASIC_STRING(C, "abcdef");
    constexpr C const* c_str = str.c_str();
    (void)c_str;
  }

  {
    constexpr C const* c_str = hana::basic_string<C, 'f', 'o', 'o'>::c_str();
    (void)c_str;
  }

  ASSERT_TRUE(true);
}

REGISTER_TYPED_TEST_CASE_P(HanaTest, CheckHanaAt, CheckHanaCStr);

using HanaTestTypes = ::testing::Types<
  char, wchar_t, char16_t, char32_t
  >;
INSTANTIATE_TYPED_TEST_CASE_P(BStrCharAt, HanaTest,
                              HanaTestTypes);

ext: cxx

max_stars_repo_name: yamasdais/asaki-yumemishi

max_issues_repo_name: yamasdais/asaki-yumemishi

max_forks_repo_name: yamasdais/asaki-yumemishi


text:
/*=============================================================================
    Copyright (c) 2001-2011 Joel de Guzman

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(PAWN_LCAST_HPP)
#define PAWN_LCAST_HPP

#include <boost/config/warning_disable.hpp>
#include <boost/variant/recursive_variant.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/io.hpp>
#include <boost/optional.hpp>
#include <list>
#include <map>
#include <dlfcn.h>

#include <helper.hpp>

namespace client { namespace logicalc { namespace ast {

    struct quoted {
      std::string val;
    };

    struct expr {
      quoted path;
      std::string fn;
    };

    struct printer {
    public:
        void operator()(expr const& x) const {
            std::cout << x.path.val;
            std::cout << ' ';
            std::cout << x.fn;
        }
    };

    struct colsEval {
    private:
        using ColIndices = client::helper::ColIndices;
    public:
        using result_type = std::pair<ColIndices, std::string>;
        using retFnT = std::function<bool(const std::vector<std::string>&, const std::vector<double>&)>;
        colsEval(const ColIndices &, const helper::Global &) {}
        colsEval() {}
        void setHeaders(const std::vector<std::string>& h) {}
        void notInitial() {}
        result_type operator()(expr const& e) const {
            auto pLib = ::dlopen(e.path.val.c_str(), RTLD_LAZY);
            if (!pLib) {
                return std::make_pair(ColIndices{}, std::string{"Error opening " + e.path.val});
            }
            auto fn = ::dlsym(pLib, e.fn.c_str());
            if (!fn) {
                std::make_pair(ColIndices{}, std::string{"Error locating " + e.fn + " in " + e.path.val});
            }
            ::dlclose(pLib);
            return result_type{};
        }
    };

    struct whatever {
      whatever(bool x) : _x{x} {}
      auto operator() (const std::vector<std::string>&, const std::vector<double>&) { return _x; }
    private:
      bool _x;
    };
    struct evaluator {
    private:
        void *pLib = nullptr;
    public:
        using sigT = bool(const std::vector<std::string>&, const std::vector<double>&);
        using retFnT = std::function<sigT>;
        evaluator() {}
        evaluator(helper::positionTeller, const helper::Global &) {}
        typedef retFnT result_type;

        retFnT operator()(expr const& x)
        {
            pLib = ::dlopen(x.path.val.c_str(), RTLD_LAZY);
            if (!pLib) return whatever{true};
            auto fn = (sigT*)(::dlsym(pLib, x.fn.c_str()));
            if (!fn) return whatever{true};
            //::dlclose(pLib);
            return fn;//static_cast<sigT*>(fn);
        }

        ~evaluator() {
            if (!pLib or pLib == nullptr) return;
            ::dlclose(pLib);
        }
    };
}}}

BOOST_FUSION_ADAPT_STRUCT(
    client::logicalc::ast::quoted,
    (std::string, val)
)

BOOST_FUSION_ADAPT_STRUCT(
    client::logicalc::ast::expr,
    (client::logicalc::ast::quoted, path)
    (std::string, fn)
)
#endif

max_stars_repo_name: haptork/pawn

max_issues_repo_name: haptork/pawn

max_forks_repo_name: haptork/pawn


text:
//          Copyright Gavin Band 2008 - 2012.
// 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 <iomanip>
#include <boost/ptr_container/ptr_deque.hpp>
#include <boost/function.hpp>
#include <boost/timer/timer.hpp>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include "unistd.h"
#include "config/config.hpp"
#if HAVE_CBLAS
	#include "cblas.h"
#endif

#include "Eigen/Core"
#include "Eigen/Eigenvalues"
#include "genfile/VariantIdentifyingData.hpp"
#include "genfile/VariantDataReader.hpp"
#include "genfile/SNPDataSourceProcessor.hpp"
#include "genfile/SingleSNPGenotypeProbabilities.hpp"
#include "genfile/vcf/get_set_eigen.hpp"
#include "statfile/BuiltInTypeStatSink.hpp"
#include "statfile/BuiltInTypeStatSource.hpp"
#include "worker/Task.hpp"
#include "worker/FunctionTask.hpp"
#include "appcontext/FileUtil.hpp"
#include "appcontext/get_current_time_as_string.hpp"
#include "components/RelatednessComponent/KinshipCoefficientComputer.hpp"
#include "components/RelatednessComponent/PCAComputer.hpp"
#include "components/RelatednessComponent/mean_centre_genotypes.hpp"

#define USING_BOOST_THREADPOOL 0
#if USING_BOOST_THREADPOOL
#include "boost/threadpool.hpp"
#else
#include "metro/concurrency/threadpool.hpp"
#endif

// #define DEBUG_KINSHIP_COEFFICIENT_COMPUTER 2

namespace impl {
	std::ostream& operator<<( std::ostream& out, SampleBounds const& b ) {
		out << "[" << b.begin_sample_i << "-" << b.end_sample_i << ", " << b.begin_sample_j << "-" << b.end_sample_j << "]" ;
		return out ;
	}

	// Return a tiling of a dxd matrix into (roughly) B blocks.
	// Blocks should be roughly evenly sized.
	// This implementation makes off-diagonal blocks half the size of diagonal blocks.
	std::vector< SampleBounds > get_matrix_lower_diagonal_tiling( std::size_t d, std::size_t B ) {
		// Because off-diagonal blocks involve about twice as much computation,
		// we make them half the size vertically.
		// If there are (N ( N+1)/2 ) square blocks this makes
		// (N (N+1) ) - N = N^2 blocks in total.
		// So we want to choose N so that N^2 is about twice the number of threads.
		// Def
		std::size_t const N = B ;
		std::vector< SampleBounds > result ;
		double K = double( d ) / N ;
//#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
		std::cerr << "get_matrix_lower_diagonal_tiling: " << d << "x" << d << " matrix, "
			<< N << " blocks across diagonal, "
			<< N*(N-1) << " blocks in lower triangle.\n" ;
//#endif
		// Set up some initial tasks.
		// Do j (the column) as the outer loop
		// so that tasks go in column-major direction.
		for( std::size_t j = 0; j < N; ++j ) {
			for( std::size_t i = 0; i < N; ++i ) {
				if( i == j ) {
					SampleBounds bounds ;
					bounds.begin_sample_i = std::ceil(i*K) ;
					bounds.end_sample_i = std::min( std::size_t( std::ceil( (i+1)*K ) ), d ) ;
					bounds.begin_sample_j = bounds.begin_sample_i ;
					bounds.end_sample_j = bounds.end_sample_i ;
					result.push_back( bounds ) ;
				}
				else {
					// Do two vertical stripes
					SampleBounds bounds ;
					bounds.begin_sample_i = std::ceil(i*K) ;
					bounds.end_sample_i = std::min( std::size_t( std::ceil( (i+1)*K ) ), d ) ;
					bounds.begin_sample_j = std::ceil(j*K) ;
					bounds.end_sample_j = std::ceil((j+0.5)*K) ;
					result.push_back( bounds ) ;

					bounds.begin_sample_j = bounds.end_sample_j ;
					bounds.end_sample_j = std::min( std::size_t( std::ceil( (j+1)*K ) ), d ) ;
					result.push_back( bounds ) ;
				}
			}
		}
//#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
		std::cerr << "get_matrix_lower_diagonal_tiling: tiling has " << result.size() << " blocks in total.\n" ;
//#endif
		return result ;
	}

	std::vector< SampleBounds > get_matrix_lower_diagonal_vertical_strip_tiling( std::size_t d, std::size_t const strip_width ) {
		std::vector< SampleBounds > result ;
//#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
		std::cerr << "get_matrix_lower_diagonal_vertical_strip_tiling: " << d << "x" << d << " matrix" ;
//#endif
		// Set up some initial tasks.
		// Do j (the column) as the outer loop
		// so that tasks go in column-major direction.
		for( std::size_t i = 0; i < d; i += strip_width ) {
			SampleBounds bounds ;
			bounds.begin_sample_i = i ;
			bounds.end_sample_i = d ;
			bounds.begin_sample_j = i ;
			bounds.end_sample_j = std::min( i+strip_width, d ) ;
			result.push_back( bounds ) ;
		}
//#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
		std::cerr << "get_matrix_lower_diagonal_vertical_strip_tiling: tiling has " << result.size() << " blocks in total.\n" ;
//#endif
		return result ;
	}

	std::vector< SampleBounds > get_matrix_lower_diagonal_horizontal_strip_tiling( std::size_t d, std::size_t const strip_width ) {
		std::vector< SampleBounds > result ;
//#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
		std::cerr << "get_matrix_lower_diagonal_horizontal_strip_tiling: " << d << "x" << d << " matrix" ;
//#endif
		// Set up some initial tasks.
		// Do j (the column) as the outer loop
		// so that tasks go in column-major direction.
		for( std::size_t i = 0; i < d; i += strip_width ) {
			SampleBounds bounds ;
			bounds.begin_sample_i = i ;
			bounds.end_sample_i = i + strip_width ;
			bounds.begin_sample_j = 0 ;
			bounds.end_sample_j = std::min( i+strip_width, d ) ;
			result.push_back( bounds ) ;
		}
//#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
		std::cerr << "get_matrix_lower_diagonal_horizontal_strip_tiling: tiling has " << result.size() << " blocks in total.\n" ;
//#endif
		return result ;
	}

	NTaskDispatcher::NTaskDispatcher(
		worker::Worker* worker
	):
		m_worker( worker )
	{
	}

	void NTaskDispatcher::set_number_of_tasks( std::size_t number_of_tasks ) {
		wait_until_complete() ;
		// TODO: do this better using the constructor
		// I don't have the docs here so don't know the right call.
		m_tasks.clear() ;
		for( std::size_t i = 0; i < number_of_tasks; ++i ) {
			m_tasks.push_back( 0 ) ;
		}
	}

	std::size_t NTaskDispatcher::number_of_tasks() const { return m_tasks.size() ; }

	void NTaskDispatcher::submit_task( std::size_t task_i, boost::function< void() > task ) {
		assert( task_i < m_tasks.size() ) ;
		if( !m_tasks.is_null( task_i ) ) {
			throw genfile::BadArgumentError(
				"impl::NTaskDispatcher::submit_task()",
				( boost::format( "task_i=%d" ) % task_i ).str(),
				"Task is still running.  Call wait_until_complete() first."
			) ;
		}
		worker::Task::UniquePtr new_task( new worker::FunctionTask( task ) ) ;
		m_tasks.replace( task_i, new_task ) ;
		m_worker->tell_to_perform_task( m_tasks[ task_i ] ) ;
	}

	void NTaskDispatcher::wait_until_complete() {
		for( std::size_t i = 0; i < m_tasks.size(); ++i ) {
			if( !m_tasks.is_null( i ) ) {
				m_tasks[ i ].wait_until_complete() ;
				m_tasks.replace( i, 0 ) ;
			}
		}
	}

	NormaliseGenotypesAndComputeXXtFast::UniquePtr NormaliseGenotypesAndComputeXXtFast::create(
		worker::Worker* worker,
		std::size_t const number_of_snps_per_computation
	) {
		return NormaliseGenotypesAndComputeXXtFast::UniquePtr( new NormaliseGenotypesAndComputeXXtFast( worker, number_of_snps_per_computation ) ) ;
	}

	NormaliseGenotypesAndComputeXXtFast::NormaliseGenotypesAndComputeXXtFast(
		worker::Worker* worker,
		std::size_t const number_of_snps_per_chunk
	):
		m_worker( worker ),
		m_dispatcher( new NTaskDispatcher( worker ) ),
		m_call_threshhold( 0.9 ),
		m_allele_frequency_threshhold( 0.001 ),
		m_number_of_snps_per_chunk( number_of_snps_per_chunk ),
		m_number_of_snps_per_computation( 4 * number_of_snps_per_chunk )
	{
		// We allocate lookup tables exactly once, here.
		// We follow, roughly, the scheme in plink 1.9 of having four lookup tables.
		// Here we encode pairs of genotypes in 4 bits (though we could do 3 as in plink).
		// Each computation then involves 16 variants, four from each lookup table.
		// This multi-table version reduces the number of times the result matrices
		// have to be traversed, and seems to make most difference in speed when
		// multithreading.
		m_lookup_tables.resize( 4, std::vector< double >( 1 << ( m_number_of_snps_per_chunk * 4 ), 0.0 ) ) ;
		m_nonmissingness_lookup_tables.resize( 4, std::vector< int >( 1 << ( m_number_of_snps_per_chunk * 4 ), 0.0 ) ) ;
	}

	NormaliseGenotypesAndComputeXXtFast::Matrix const& NormaliseGenotypesAndComputeXXtFast::result() const {
		return m_result ;
	}

	NormaliseGenotypesAndComputeXXtFast::IntegerMatrix const& NormaliseGenotypesAndComputeXXtFast::nonmissingness() const {
		return m_nonmissingness ;
	}

	std::size_t NormaliseGenotypesAndComputeXXtFast::number_of_snps_included() const {
		return m_snp_count ;
	}

	std::string NormaliseGenotypesAndComputeXXtFast::get_summary() const {
		return (
			boost::format(
				"NormaliseGenotypesAndComputeXXtFast():\n"
				" - %d SNPs per chunk\n"
				" - %d chunks per array acces\n"
				" - four lookup tables of size: %d\n"
				" - minimum allele frequency: %.3f"
			)
				% m_number_of_snps_per_chunk
				% (m_number_of_snps_per_computation / m_number_of_snps_per_chunk)
				% m_lookup_tables[0].size()
				% m_allele_frequency_threshhold
		).str()
		;
	}
	void NormaliseGenotypesAndComputeXXtFast::begin_processing_snps(
		std::size_t number_of_samples,
		genfile::SNPDataSource::Metadata const&
	) {
		m_result.resize( number_of_samples, number_of_samples ) ;
		m_result.setZero() ;
		m_nonmissingness.resize( number_of_samples, number_of_samples ) ;
		m_nonmissingness.setZero() ;
		std::size_t numberOfTasks = m_worker->get_number_of_worker_threads() ;
#if 0
		m_matrix_tiling = get_matrix_lower_diagonal_vertical_strip_tiling( number_of_samples, 1 ) ;
#else
		m_matrix_tiling = get_matrix_lower_diagonal_tiling(
			number_of_samples,
			numberOfTasks
		) ;
#endif
		m_dispatcher->set_number_of_tasks( m_matrix_tiling.size() ) ;
		m_combined_genotypes.resize( number_of_samples, 0 ) ;
		m_per_snp_genotypes.resize( number_of_samples, 0 ) ;
		m_snp_count = 0 ;
	}

	namespace impl {
		template< typename T >
		double add( T a, T b ) {
			return a + b ;
		}
	}

#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
	namespace {
		template< typename T >
		void print_lookup_table( std::ostream& out, std::vector< T > const& lookup_table, std::size_t const max = 64 ) {
			out << "print_lookup_table(): lookup table of size " << lookup_table.size() << ":" ;
			for( std::size_t i = 0; i < std::min( max, lookup_table.size() ); ++i ) {
				if( i % 8 == 0 ) {
					out << "\n" ;
				} else {
					out << " " ;
				}
				out << ( boost::format( " - 0x%02x: %.2f" ) % i % lookup_table[i] ) ;
			}
			out << "\n" ;
		}
	}
#endif

	void NormaliseGenotypesAndComputeXXtFast::processed_snp(
		genfile::VariantIdentifyingData const& id_data,
		genfile::VariantDataReader::SharedPtr data_reader
	) {
		// std::vector< std::size_t > m_genotypes
		// std::vector< int >
		m_per_snp_genotypes.assign( m_result.rows(), 0 ) ;

		// I find it simplest here to encode genotypes as
		// 0 (missing), 1 (AA homozygote), 2 (heterozygote), 3 (BB homozygote).
		data_reader->get(
			":genotypes:",
			genfile::vcf::get_threshholded_calls( m_per_snp_genotypes, m_call_threshhold, 0, 1, 2, 3 )
		) ;

		// compute allele frequency
		double allele2_count = 0.0 ;
		double nonmissing_count = 0.0 ;
		for( std::size_t i = 0; i < m_combined_genotypes.size(); ++i ) {
			bool const missing = ( m_per_snp_genotypes[i] == 0 ) ;
			if( !missing ) {
				allele2_count += m_per_snp_genotypes[i] - 1.0 ;
				nonmissing_count += 1 ;
			}
		}
		// Data estimate:
		// double const allele_frequency = allele2_count / ( nonmissing_count * 2.0 ) ;
		// Regularised estimate based on adding one of each allele,
		// this matches Price et al Nature Genetics 2006
		double const posterior_allele_frequency = (1 + allele2_count) / ( 2 + ( 2 * nonmissing_count)) ;
		double const allele_frequency = allele2_count / ( 2 * nonmissing_count ) ;
		if( nonmissing_count > 0 && std::min( allele_frequency, 1.0 - allele_frequency ) > m_allele_frequency_threshhold ) {
			// Ok we will process this SNP.
			// We batch SNPs together to form a total of m_number_of_snps_per_computation SNPs.
			// This means we visit the result matrix (which for large samples won't fit in cache)
			// as few times as possible.
			// Here we are not quite as efficient as plink: I use four bits instead of three to
			// encode the two genotypes.
			std::size_t const lookup_snp_index = m_snp_count % m_number_of_snps_per_computation ;
			if( lookup_snp_index == 0 ) {
				m_dispatcher->wait_until_complete() ;
				std::copy( m_per_snp_genotypes.begin(), m_per_snp_genotypes.end(), m_combined_genotypes.begin() ) ;
				// Clear the lookup tables
				for( std::size_t i = 0; i < m_lookup_tables.size(); ++i ) {
					std::fill( m_lookup_tables[i].begin(), m_lookup_tables[i].end(), 0.0 ) ;
					std::fill( m_nonmissingness_lookup_tables[i].begin(), m_nonmissingness_lookup_tables[i].end(), 0.0 ) ;
				}
			} else {
				// We allow 4 bits per genotype, although each genotype takes up only the lower two bits.
				// This allows us to encode pairs of genotypes in consecutive pairs of bits
				// for simpler lookup of the lookup table.
				for( std::size_t i = 0; i < m_combined_genotypes.size(); ++i ) {
					m_combined_genotypes[i] |= m_per_snp_genotypes[i] << (4 * lookup_snp_index) ;
				}
			}

			std::size_t const lookup_table_index = ( m_snp_count % m_number_of_snps_per_computation ) / m_number_of_snps_per_chunk ;
			double const mean = 2.0 * allele_frequency ;
			double const sd = std::sqrt( ( 2.0 * posterior_allele_frequency * ( 1.0 - posterior_allele_frequency )) ) ;
#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
			std::cerr << "NormaliseGenotypesAndComputeXXtFast::processed_snp(): filling lookup table " << lookup_table_index << ".\n" ;
#endif

			add_snp_to_lookup_table(
				lookup_snp_index % m_number_of_snps_per_chunk,
				mean, sd,
				&m_lookup_tables[ lookup_table_index ],
				&m_nonmissingness_lookup_tables[ lookup_table_index ]
			) ;

			++m_snp_count ;
#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
			boost::format fmt( "%.2f" ) ;
			std::cerr << "NormaliseGenotypesAndComputeXXtFast::processed_snp(): m_snp_count: " << m_snp_count << ".\n" ;
			std::cerr << "NormaliseGenotypesAndComputeXXtFast::processed_snp(): allele_frequency: " << fmt % allele_frequency << ".\n" ;
			std::cerr << "NormaliseGenotypesAndComputeXXtFast::processed_snp(): mean: " << fmt % mean << ", sd = " << fmt % sd << ".\n" ;
			print_lookup_table( std::cerr, m_lookup_tables[0], 32 ) ;
			print_lookup_table( std::cerr, m_lookup_tables[1], 32 ) ;
			print_lookup_table( std::cerr, m_lookup_tables[2], 32 ) ;
			print_lookup_table( std::cerr, m_lookup_tables[3], 32 ) ;
			//print_lookup_table( std::cerr, m_nonmissingness_lookup_table, 256 ) ;
#endif
			if( m_snp_count % m_number_of_snps_per_computation == 0 ) {
#if DEBUG_KINSHIP_COEFFICIENT_COMPUTER
			std::cerr << "NormaliseGenotypesAndComputeXXtFast::processed_snp(): submitting tasks...\n" ;
#endif
				submit_tasks( m_combined_genotypes ) ;
			}
		}
	}

	void NormaliseGenotypesAndComputeXXtFast::add_snp_to_lookup_table(
		std::size_t const snp_lookup_index,
		double const mean,
		double const sd,
		std::vector< double >* lookup_table,
		std::vector< int >* nonmissingness_lookup_table
	) {
		// We lay out the lookup table as follows.
		// The two genotypes at the first SNP occupy the first 4 bits,
		// the two genotypes at the second SNP occupy the next 4 bits,
		// etc.
		// Thus after k SNPs the size of the useful part of the table is 16^k,
		// which is computed as (1 << 4k).
		// Note that because genotype value 0 corresponds to missing data,
		// The block as computed after SNP k-1 is equal to the block
		// for missing values for SNP k.
		if( snp_lookup_index == 0 ) {
			// bottom 2 bits correspond to top genotype = 0.
			for( std::size_t g = 0; g < 4; ++g ) {
				(*nonmissingness_lookup_table)[g] = 0 ;
				(*lookup_table)[ g ] = 0 ;
			}
			for( std::size_t g = 1; g < 4; ++g ) {
				(*nonmissingness_lookup_table)[ (g << 2) + 0 ] = 0 ;
				(*nonmissingness_lookup_table)[ (g << 2) + 1 ] = 1 ;
				(*nonmissingness_lookup_table)[ (g << 2) + 2 ] = 1 ;
				(*nonmissingness_lookup_table)[ (g << 2) + 3 ] = 1 ;
				(*lookup_table)[ (g << 2) + 0 ] = 0.0 ;
				(*lookup_table)[ (g << 2) + 1 ] = ( ( 0.0 - mean ) / sd ) * ( ( (g-1) - mean ) / sd ) ;
				(*lookup_table)[ (g << 2) + 2 ] = ( ( 1.0 - mean ) / sd ) * ( ( (g-1) - mean ) / sd ) ;
				(*lookup_table)[ (g << 2) + 3 ] = ( ( 2.0 - mean ) / sd ) * ( ( (g-1) - mean ) / sd ) ;
			}
		} else {
			// We have already computed the initial block of size 16^k.
			// Now we compute 15 additional blocks for 16 in total.
			// In the computation we break these up as 4 blocks of size
			// This means this SNP has no effect and we need only copy.
			std::size_t const inner_block_size = 1 << ( 4 * snp_lookup_index ) ;
			std::size_t const outer_block_size = 4 * inner_block_size ;
			for( std::size_t outer_g = 0; outer_g < 4; ++outer_g ) {
				for( std::size_t inner_g = (outer_g == 0) ? 1 : 0; inner_g < 4; ++inner_g ) {
					double const value = ( inner_g == 0 || outer_g == 0 )
						? 0.0
						: (((inner_g-1.0) - mean)/sd) * (((outer_g-1.0) - mean)/sd) ;
					int const nonmissingness = ( inner_g == 0 || outer_g == 0 )
						? 0
						: 1 ;
					std::transform(
						lookup_table->begin(),
						lookup_table->begin() + inner_block_size,
						lookup_table->begin() + outer_block_size * outer_g + inner_block_size * inner_g,
						boost::bind( &impl::add< double >, _1, value )
					) ;
					std::transform(
						nonmissingness_lookup_table->begin(),
						nonmissingness_lookup_table->begin() + inner_block_size,
						nonmissingness_lookup_table->begin() + outer_block_size * outer_g + inner_block_size * inner_g,
						boost::bind( &impl::add< int >, _1, nonmissingness )
					) ;
				}
			}
		}
	}

	void NormaliseGenotypesAndComputeXXtFast::submit_tasks(
		std::vector< uint64_t > const& genotypes
	) {
		for( std::size_t tile_i = 0; tile_i < m_matrix_tiling.size(); ++tile_i ) {
	#if 1
			m_dispatcher->submit_task(
				tile_i,
				boost::bind(
					&NormaliseGenotypesAndComputeXXtFast::compute_block,
					this,
					boost::cref( m_matrix_tiling[ tile_i ] ),
					boost::cref( genotypes )
				)
			) ;
	#else
			compute_block( m_matrix_tiling[tile_i], genotypes, lookup_table, nonmissingness_lookup_table ) ;
	#endif
		}
	}

	void NormaliseGenotypesAndComputeXXtFast::end_processing_snps() {
		if( m_snp_count % m_number_of_snps_per_computation > 0 ) {
			submit_tasks( m_combined_genotypes ) ;
		}
		m_dispatcher->wait_until_complete() ;
		std::cerr << "snp count is: " << m_snp_count << ".\n" ;
		std::cerr << "non-missingness array is:\n" << m_nonmissingness.block(0,0,10,10) << ".\n" ;
		m_result.array() /= m_nonmissingness.array().cast< double >() ;
	}

	void NormaliseGenotypesAndComputeXXtFast::compute_block(
		SampleBounds const& sample_bounds,
		std::vector< uint64_t > const& genotypes
	) {
		// only compute the lower diagonal.
		// We also want to make the function go down the rows of the result
		// in the inner loop, since it's stored column-major, so put row index in the inner loop.
		for( std::size_t j = sample_bounds.begin_sample_j; j < sample_bounds.end_sample_j; ++j ) {
			for( std::size_t i = std::max( j, std::size_t( sample_bounds.begin_sample_i ) ); i < sample_bounds.end_sample_i; ++i ) {
				uint64_t const combined_genotype = ( genotypes[i] << 2 ) + genotypes[j] ;
				std::size_t const lookup_index0 = combined_genotype & 0xFFFF ;
				std::size_t const lookup_index1 = ( combined_genotype >> 16 ) & 0xFFFF ;
				std::size_t const lookup_index2 = ( combined_genotype >> 32 ) & 0xFFFF ;
				std::size_t const lookup_index3 = ( combined_genotype >> 48 ) & 0xFFFF ;
				m_result(i,j) += m_lookup_tables[0][ lookup_index0 ] ;
				m_result(i,j) += m_lookup_tables[1][ lookup_index1 ] ;
				m_result(i,j) += m_lookup_tables[2][ lookup_index2 ] ;
				m_result(i,j) += m_lookup_tables[3][ lookup_index3 ] ;
				m_nonmissingness(i,j) += m_nonmissingness_lookup_tables[0][ lookup_index0 ] ;
				m_nonmissingness(i,j) += m_nonmissingness_lookup_tables[1][ lookup_index1 ] ;
				m_nonmissingness(i,j) += m_nonmissingness_lookup_tables[2][ lookup_index2 ] ;
				m_nonmissingness(i,j) += m_nonmissingness_lookup_tables[3][ lookup_index3 ] ;
			}
		}
	}
}

KinshipCoefficientComputer::KinshipCoefficientComputer(
	appcontext::OptionProcessor const& options,
	genfile::CohortIndividualSource const& samples,
	appcontext::UIContext& ui_context,
	Computation::UniquePtr computation
):
	m_options( options ),
	m_ui_context( ui_context ),
	m_samples( samples ),
	m_computation( computation )
{
	assert( m_computation.get() ) ;
}

void KinshipCoefficientComputer::begin_processing_snps( std::size_t number_of_samples, genfile::SNPDataSource::Metadata const& metadata ) {
	m_computation->begin_processing_snps( number_of_samples, metadata ) ;
}

void KinshipCoefficientComputer::processed_snp( genfile::VariantIdentifyingData const& id_data, genfile::VariantDataReader::SharedPtr data_reader ) {
	m_computation->processed_snp( id_data, data_reader ) ;
}

void KinshipCoefficientComputer::end_processing_snps() {
	m_computation->end_processing_snps() ;

	std::string description = "Number of SNPs: "
		+ genfile::string_utils::to_string( m_computation->number_of_snps_included() )
		+ "\nNumber of samples: "
		+ genfile::string_utils::to_string( m_samples.get_number_of_individuals() )
	;
#if 1
	send_results(
		m_computation->number_of_snps_included(),
		m_computation->nonmissingness().cast< double >(),
		m_computation->result().cast< double >(),
		"KinshipCoefficientComputer",
		description
	) ;
	#endif
}

max_stars_repo_name: gavinband/qctool

max_issues_repo_name: gavinband/qctool

max_forks_repo_name: gavinband/qctool


text:
// ---------------------------------------------------------------------------
//
//  This file is part of PermLib.
//
// Copyright (c) 2009-2011 Thomas Rehn <thomas@carmen76.de>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products
//    derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ---------------------------------------------------------------------------

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE symmetric group magic
#include <boost/test/unit_test.hpp>

#include <iostream>
#include <fstream>
#include <algorithm>
#include <set>

#include <permlib/permutation.h>

#include "test-common.h"
#include <permlib/symmetric_group.h>
#include <permlib/change/deterministic_base_transpose.h>
#include <permlib/change/conjugating_base_change.h>

using namespace permlib;

BOOST_AUTO_TEST_CASE( symmetric_group )
{
	typedef Permutation PERM;
	typedef SymmetricGroup<PERM>::TRANS TRANS;
	typedef DeterministicBaseTranspose<PERM,TRANS> BASETRANSPOSE;

	const unsigned long n = 19;

	SymmetricGroup<PERM> s_n(n);

	BOOST_REQUIRE( s_n.B.size() >= n-1 );

	for (unsigned int i=0; i<n; ++i) {
		PERM* p = s_n.U[0].at(i);
		BOOST_REQUIRE( p );
		BOOST_CHECK( *p / s_n.B[0] == i );
		BOOST_CHECK( *p / i == s_n.B[0] );
		delete p;
	}

	ConjugatingBaseChange<PERM, TRANS, BASETRANSPOSE> cbc(s_n);
	const unsigned long newBaseLength = 5;
	unsigned long newBase[newBaseLength] = { 3, 1, 0, 9, 17 };
	cbc.change(s_n, newBase, newBase+newBaseLength);

	BOOST_REQUIRE( s_n.B.size() >= n-1 );

	for (unsigned int i=0; i<newBaseLength; ++i) {
		BOOST_CHECK(s_n.B[i] == newBase[i]);
	}

	std::set<unsigned long> seenBaseElements;
	for (unsigned int i=0; i<n; ++i) {
		seenBaseElements.insert(s_n.B[i]);
	}

	BOOST_CHECK( s_n.B.size() == seenBaseElements.size() );
}

max_stars_repo_name: peterlietz/PermLib

max_issues_repo_name: peterlietz/PermLib

max_forks_repo_name: peterlietz/PermLib