text:
#include "dsa_common.h"

#include "module_with_loader.h"

#include "authorizer.h"
#include "client_manager.h"
#include "logger.h"
#include "storage.h"

#include <boost/dll/import.hpp>
#include <iostream>

namespace dsa {

ModuleWithLoader::ModuleWithLoader(bf::path lib_path,
                                   ref_<Module>&& default_module) {
  _default_module = std::move(default_module);

  auto module_suffix = boost::dll::shared_library::suffix();

  // There is no module directory returning default function
  if (!bf::is_directory(lib_path)) return;

  // Iterate directory files
  std::vector<bf::path> module_paths;
  bf::directory_iterator end_itr;

  for (bf::directory_iterator itr(lib_path); itr != end_itr; ++itr) {
    if (bf::is_regular_file(itr->path())) {
      auto file_name = itr->path().filename().string();
      auto file_suffix = itr->path().extension();

      // check extension
      if (file_suffix == module_suffix) {
        module_paths.push_back(itr->path());
      }
    }
  }

  for (auto module_path : module_paths) {
    try {
      auto module = boost::dll::import<Module>(module_path, "module");
      _modules.push_back(module);
    } catch (int e) {
      std::cout << "Exception while loading " << module_path << std::endl;
    }
  }
}

ref_<Storage> ModuleWithLoader::create_storage(App& app,
                                               const LinkStrandRef& strand) {
  ref_<Storage> service = nullptr;

  // Check in files
  for (auto module : _modules) {
    module->init_storage(app, strand);
    auto temp = module->get_storage();
    if (temp == nullptr) continue;

    if (service == nullptr) {
      service = temp;
    } else {
      LOG_FATAL(
          __FILENAME__,
          "There are more than one storage in libs directory, cannot select "
          "them!")
    }
  }

  if (service != nullptr) return service;

  _default_module->init_storage(app, strand);
  return _default_module->get_storage();
}

shared_ptr_<Logger> ModuleWithLoader::create_logger(
    App& app, const LinkStrandRef& strand) {
  shared_ptr_<Logger> service = nullptr;

  // Check in files
  for (auto module : _modules) {
    module->init_logger(app, strand);
    auto temp = module->get_logger();
    if (temp == nullptr) continue;

    if (service == nullptr) {
      service = temp;
    } else {
      LOG_FATAL(
          __FILENAME__,
          "There are more than one logger in libs directory, cannot select "
          "them!")
    }
  }

  if (service != nullptr) return service;

  _default_module->init_logger(app, strand);
  return _default_module->get_logger();
}

ref_<ClientManager> ModuleWithLoader::create_client_manager(
    App& app, const LinkStrandRef& strand) {
  ref_<ClientManager> service = nullptr;

  // Check in files
  for (auto module : _modules) {
    module->init_client_manager(app, strand);
    auto temp = module->get_client_manager();
    if (temp == nullptr) continue;

    if (service == nullptr) {
      service = temp;
    } else {
      LOG_FATAL(
          __FILENAME__,
          "There are more than one client manager in libs directory, cannot "
          "select them!")
    }
  }

  if (service != nullptr) return service;

  _default_module->init_client_manager(app, strand);
  return _default_module->get_client_manager();
}

ref_<Authorizer> ModuleWithLoader::create_authorizer(
    App& app, const LinkStrandRef& strand) {
  ref_<Authorizer> service = nullptr;

  // Check in files
  for (auto module : _modules) {
    module->init_authorizer(app, strand);
    auto temp = module->get_authorizer();
    if (temp == nullptr) continue;

    if (service == nullptr) {
      service = temp;
    } else {
      LOG_FATAL(__FILENAME__,
                LOG << "There are more than one authorizer in libs directory, "
                       "cannot select them!")
    }
  }

  if (service != nullptr) return service;

  _default_module->init_authorizer(app, strand);
  return _default_module->get_authorizer();
}

void ModuleWithLoader::add_module_node(NodeModel& module_node,
                                       BrokerPubRoot& pub_root) {
  _default_module->add_module_node(module_node, pub_root);
  for (auto module : _modules) {
    module->add_module_node(module_node, pub_root);
  }
}

void ModuleWithLoader::add_web_handler() {
  _default_module->add_web_handler();
  for (auto module : _modules) {
    module->add_web_handler();
  }
}
}  // namespace dsa

ext: cc


text: #include <boost/ratio/mpl/negate.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//          Copyright Camille Gillot 2012 - 2015.
// 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)

#ifndef RTTI_MIXIN_SINGLE_NODE_HPP
#define RTTI_MIXIN_SINGLE_NODE_HPP

#include "mmethod/config.hpp"
#include "mmethod/rttifwd.hpp"

#include "mmethod/rtti/mixin/mixin_node.hpp"

namespace rtti {

struct single_mixin_node {
public:
  template<bool Declare, typename Mixin, typename Derived>
  struct base
  {};
};

template<typename Mixin, typename Derived>
struct single_mixin_node::base<true, Mixin, Derived>
: private detail::mixin_node_holder
{
  friend detail::mixin_node_holder const&
  rtti_get_mixin(Derived const& d) {
    return static_cast<base const&>(d);
  }
};

} // namespace rtti

#include <boost/typeof/typeof.hpp>
#include BOOST_TYPEOF_INCREMENT_REGISTRATION_GROUP()

BOOST_TYPEOF_REGISTER_TYPE(rtti::single_mixin_node)

#endif

max_stars_repo_name: cjgillot/rtti

max_issues_repo_name: cjgillot/rtti

max_forks_repo_name: cjgillot/rtti


text:
//////////////////////////////////////////////////////////////////////////////////////////////
/// \file CommonMath.hpp
/// \brief Header file for some common math functions
/// \details defines some constants, angle-based functions, and comparison functions.
///
/// \author Sean Anderson, ASRL
//////////////////////////////////////////////////////////////////////////////////////////////

#ifndef LGM_COMMON_MATH_HPP
#define LGM_COMMON_MATH_HPP

#include <Eigen/Core>

namespace lgmath {

//////////////////////////////////////////////////////////////////////////////////////////////
/// Define various pi functions -- found from matlab w long precision
//////////////////////////////////////////////////////////////////////////////////////////////
namespace constants {
  const double TWO_PI         = 6.283185307179586;  // 2*pi
  const double PI             = 3.141592653589793;  // pi
  const double PI_DIV_TWO     = 1.570796326794897;  // pi/2
  const double PI_DIV_FOUR    = 0.785398163397448;  // pi/4
  const double ONE_DIV_PI     = 0.318309886183791;  // 1/pi
  const double ONE_DIV_TWO_PI = 0.159154943091895;  // 1/2*pi
  const double DEG2RAD	      = 0.017453292519943;  // pi/180
  const double RAD2DEG	      = 57.295779513082323;  // 180/pi
} // constants

//////////////////////////////////////////////////////////////////////////////////////////////
/// Common math functions
//////////////////////////////////////////////////////////////////////////////////////////////
namespace common {

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief moves a radian value to the range -pi, pi
//////////////////////////////////////////////////////////////////////////////////////////////
double angleMod(double radians);

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief converts from degrees to radians
//////////////////////////////////////////////////////////////////////////////////////////////
double deg2rad(double degrees);

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief converts from radians to degrees
//////////////////////////////////////////////////////////////////////////////////////////////
double rad2deg(double radians);

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief compares if doubles are near equal
//////////////////////////////////////////////////////////////////////////////////////////////
bool nearEqual(double a, double b, double tol = 1e-6);

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief compares if (double) Eigen matrices are near equal
//////////////////////////////////////////////////////////////////////////////////////////////
bool nearEqual(Eigen::MatrixXd A, Eigen::MatrixXd B, double tol = 1e-6);

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief compares if radian angles are near equal
//////////////////////////////////////////////////////////////////////////////////////////////
bool nearEqualAngle(double radA, double radB, double tol = 1e-6);

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief compares if axis angles are near equal
//////////////////////////////////////////////////////////////////////////////////////////////
bool nearEqualAxisAngle(Eigen::Matrix<double,3,1> aaxis1,
                        Eigen::Matrix<double,3,1> aaxis2, double tol = 1e-6);

//////////////////////////////////////////////////////////////////////////////////////////////
/// \brief compares if lie algebra is near equal
//////////////////////////////////////////////////////////////////////////////////////////////
bool nearEqualLieAlg(Eigen::Matrix<double,6,1> vec1,
                     Eigen::Matrix<double,6,1> vec2, double tol = 1e-6);

} // common
} // lgmath

#endif // LGM_COMMON_MATH_HPP

max_stars_repo_name: utiasASRL/lgmath

max_issues_repo_name: utiasASRL/lgmath

max_forks_repo_name: utiasASRL/lgmath


text:
/*
 * This file is part of MXE. See LICENSE.md for licensing information.
 *
 * This code was originally found on:
 *   https://eigen.tuxfamily.org/dox/GettingStarted.html
 */

#include <Eigen/Dense>

using Eigen::MatrixXd;

int main()
{
    MatrixXd m(2,2);
    m(0,0) = 3;
    m(1,0) = 2.5;
    m(0,1) = -1;
    m(1,1) = m(1,0) + m(0,1);
    return 0;
}

ext: cpp

max_stars_repo_name: swigger/mxe

max_issues_repo_name: swigger/mxe

max_forks_repo_name: swigger/mxe


text: #include <boost/spirit/home/classic/tree/parse_tree_utils.hpp>


text:
#include "asioclient.h"
#include <cstring>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

void asioclient::init(
	const std::string& host,
	const std::string& service,
	const std::size_t interval)
{
	// Resolve ip address
	tcp::resolver resolver(io_context_);
	endpoints_ = resolver.resolve(host, service);
	// Create the worker threads
	pwork_ = std::make_shared< boost::asio::io_context::work>(io_context_);
	for (size_t i = 0; i < prosessor_num_; i++) {
		io_threads_.push_back(std::make_shared< std::thread>(
			boost::bind(&boost::asio::io_service::run, &io_context_)
		));
	}
	// Set heart timer
	heart_interval_ = interval;
	start_timer();
}

void asioclient::deinit()
{
	// Cancel the timer
	heart_timer_.cancel();
	if (heart_thread_) {
		heart_thread_->join();
	}
	// Close sockets
	boost::asio::post(
		io_context_,
		[this]() { do_deinit(); }
	);
	// Wait for threads to exit
	for (size_t i = 0; i < prosessor_num_; i++) {
		io_threads_[i]->join();
	}
	io_threads_.clear();
	// Clean the context list
	{
		boost::unique_lock<boost::shared_mutex> m(rwmutex_);
		for (auto it = socket_list_.begin(); it != socket_list_.end(); it++) {
			delete it->second;
		}
		socket_list_.clear();
	}
}

void asioclient::connect(
	const std::string & host,
	const std::string & service,
	const unsigned id,
	const std::string & key)
{
	// Resolve ip address
	tcp::resolver resolver(io_context_);
	endpoints_ = resolver.resolve(host, service);
	// Connect
	connect(id, key);
}

void asioclient::connect(const unsigned id, const std::string &key)
{
	bool exist = false;
	context_info *pitem;
	{
		boost::unique_lock<boost::shared_mutex> m(rwmutex_);
		if (socket_list_.count(id)) {
			exist = true;
		}
		else {
			pitem = new context_info(io_context_, id, key);
			socket_list_[id] = pitem;
		}
	}
	if (exist) {
		return;
	}

	boost::asio::async_connect(
		pitem->socket_,
		endpoints_,
		boost::bind(
			&asioclient::on_connect,
			this,
			pitem,
			boost::asio::placeholders::error,
			boost::asio::placeholders::endpoint
		)
	);
}

int asioclient::disconnect(const unsigned id)
{
	int ret = -1;
	{
		boost::shared_lock<boost::shared_mutex> m(rwmutex_);
		if (socket_list_.count(id)) {
			socket_list_[id]->socket_.close();
			ret = 0;
		}
	}
	return ret;
}

void asioclient::post_write(context_info* context, const char *msg, const size_t len)
{
	if (context->stat_ != ioconst::IO_READY) {
		return;
	}
	context->stat_ = ioconst::IO_SENDING;
	context->len_send_ = len;
	memcpy(context->buff_send_, msg, len);
	boost::asio::post(
		io_context_,
		boost::bind(
			&asioclient::do_write,
			this,
			context
		)
	);
}

void asioclient::post_read(context_info* context)
{
	boost::asio::post(
		io_context_,
		boost::bind(
			&asioclient::do_read_header,
			this,
			context
		)
	);
}

size_t asioclient::get_ionum() {
	size_t num = 0;
	{
		boost::shared_lock<boost::shared_mutex> m(rwmutex_);
		num = socket_list_.size();
	}
	return num;
}

void asioclient::start_timer()
{
	heart_timer_.expires_from_now(boost::posix_time::seconds(heart_interval_));
	heart_timer_.async_wait(
		boost::bind(
			&asioclient::on_timer,
			this,
			boost::asio::placeholders::error
		)
	);
}

void asioclient::thread_timer()
{
	if (!timer_handler_) {
		return;
	}
	{
		boost::shared_lock<boost::shared_mutex> m(rwmutex_);
		for (auto it = socket_list_.begin(); it != socket_list_.end(); it++) {
			timer_handler_(it->second);
		}
	}
}

void asioclient::on_error(context_info* context, const boost::system::error_code ec)
{
	unsigned id = context->label_;
	{
		boost::unique_lock<boost::shared_mutex> m(rwmutex_);
		for (auto it = socket_list_.begin(); it != socket_list_.end(); it++) {
			if (it->second == context) {
				delete it->second;
				socket_list_.erase(it);
				break;
			}
		}
	}
	if (error_handler_) {
		error_handler_(id, ec);
	}
}

void asioclient::do_deinit()
{
	{
		boost::shared_lock<boost::shared_mutex> m(rwmutex_);
		for (auto it = socket_list_.begin(); it != socket_list_.end(); it++) {
			it->second->socket_.close();
		}
	}
	pwork_ = nullptr;
}

void asioclient::on_connect(context_info* context, boost::system::error_code ec, tcp::endpoint)
{
	if (ec) {
		// 未连接成功时上层列表无记录 不需要更新列表
		// on_error(context, ec);
		return;
	}
	context->stat_ = ioconst::IO_READY;
	do_read_header(context);
	if (open_handler_) {
		open_handler_(context);
	}
}

void asioclient::on_timer(boost::system::error_code ec)
{
	if (ec) {
		return;
	}
	start_timer();
	if (heart_thread_) {
		heart_thread_->join();
	}
	heart_thread_.reset(new std::thread(
		&asioclient::thread_timer, this
	));
}

void asioclient::do_write(context_info* context, const char *msg, const size_t len)
{
	if (context->stat_ != ioconst::IO_READY) {
		return;
	}
	context->stat_ = ioconst::IO_SENDING;
	context->len_send_ = len;
	memcpy(context->buff_send_, msg, len);
	do_write(context);
}

void asioclient::do_write(context_info* context)
{
	boost::asio::async_write(
		context->socket_,
		boost::asio::buffer(
			context->buff_send_,
			context->len_send_
		),
		boost::bind(
			&asioclient::on_write,
			this,
			context,
			boost::asio::placeholders::error,
			boost::asio::placeholders::bytes_transferred
		)
	);
}

void asioclient::on_write(context_info* context, boost::system::error_code ec, std::size_t length)
{
	if (ec) {
		// 发送失败时 接收IO同样会产生错误 只需向上层通知一次
		// on_error(context, ec);
		return;
	}
	context->stat_ = ioconst::IO_READY;
}

void asioclient::do_read_header(context_info* context)
{
	boost::asio::async_read(
		context->socket_,
		boost::asio::buffer(
			context->buff_header_,
			header_len_
		),
		boost::bind(
			&asioclient::on_read_header,
			this,
			context,
			boost::asio::placeholders::error,
			boost::asio::placeholders::bytes_transferred
		)
	);
}

void asioclient::on_read_header(context_info* context, boost::system::error_code ec, std::size_t length)
{
	if (ec) {
		on_error(context, ec);
		return;
	}
	size_t ret = 0;
	if (header_handler_) {
		ret = header_handler_(context, length);
	}
	if (ret == header_len_) {
		do_read_header(context);
	}
	else if (ret == 0) {
		do_read_some(context);
	}
	else {
		do_read_payload(context, ret - header_len_);
	}
}

void asioclient::do_read_payload(context_info* context, std::size_t length)
{
	boost::asio::async_read(
		context->socket_,
		boost::asio::buffer(
			context->buff_payload_,
			length
		),
		boost::bind(
			&asioclient::on_read_payload,
			this,
			context,
			boost::asio::placeholders::error,
			boost::asio::placeholders::bytes_transferred
		)
	);
}

void asioclient::on_read_payload(context_info* context, boost::system::error_code ec, std::size_t length)
{
	if (ec) {
		on_error(context, ec);
		return;
	}
	if (payload_handler_) {
		payload_handler_(context, length);
	}
	do_read_header(context);
}

void asioclient::do_read_some(context_info* context)
{
	context->socket_.async_read_some(
		boost::asio::buffer(
			context->buff_payload_,
			ioconst::MAX_PAYLOAD_BUFF
		),
		boost::bind(
			&asioclient::on_read_some,
			this,
			context,
			boost::asio::placeholders::error,
			boost::asio::placeholders::bytes_transferred
		)
	);
}

void asioclient::on_read_some(context_info* context, boost::system::error_code ec, std::size_t length)
{
	if (ec) {
		on_error(context, ec);
		return;
	}
	do_read_header(context);
}

max_stars_repo_name: EricEcho/BilibiliTool

max_forks_repo_name: EricEcho/BilibiliTool


text:
/*-----------------------------------------------------------------------
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agceements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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 agceed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-----------------------------------------------------------------------*/
#include "MyOwnCoreProtocolHandlers.h"

#include <thread>

#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <fetpapi/etp/EtpHelpers.h>
#include <fetpapi/etp/PlainClientSession.h>

#include "MyOwnDiscoveryProtocolHandlers.h"
#include "MyOwnStoreProtocolHandlers.h"

void printHelp()
{
	std::cout << "List of available commands :" << std::endl;
	std::cout << "\tPing" << std::endl << "\t\tPing the server" << std::endl << std::endl;
	std::cout << "\tList" << std::endl << "\t\tList the objects which have been got from ETP to the in-memory epc" << std::endl << std::endl;
	std::cout << "\tPutXmldAndHdfAtOnce" << std::endl << "\t\tPut a dummy point set representation to the store sending XML and HDF5 points at once." << std::endl << std::endl;
	std::cout << "\tGetResources URI scope(default self) depth(default 1) countObjects(true or false, default is true) getObject(true or false, default is false) dataTypeFilter,dataTypeFilter,...(default noFilter)" << std::endl << std::endl;
	std::cout << "\tGetDataObjects dataObjectURI,dataObjectURI,..." << std::endl << "\t\tGet the objects from an ETP store and store them into the in memory epc (only create partial TARGET relationships, not any SOURCE relationships)" << std::endl << std::endl;
	std::cout << "\tGetXYZPoints URI" << std::endl << "\t\tGet the XYZ points of a rep from store and print some of them." << std::endl << std::endl;
	std::cout << "\tPutDataObject UUID" << std::endl << "\t\tPut the XML part of a dataobject which is on the client side (use \"Load\" command to laod some dataobjects on client side) to the store" << std::endl << std::endl;
	std::cout << "\tGetSourceObjects dataObjectURI" << std::endl << "\t\tGet the source objects of another object from an ETP store and put it into the in memory epc" << std::endl << std::endl;
	std::cout << "\tGetTargetObjects dataObjectURI" << std::endl << "\t\tGet the target objects of another object from an ETP store and put it into the in memory epc" << std::endl << std::endl;
	std::cout << "\tGetResourceObjects dataObjectURI" << std::endl << "\t\tGet the object, its source and its target objects from an ETP store and put it into the in memory epc" << std::endl << std::endl;
	std::cout << "\tGetDataArray epcExternalPartURI datasetPathInEpcExternalPart" << std::endl << "\t\tGet the numerical values from a dataset included in an EpcExternalPart over ETP." << std::endl << std::endl;
	std::cout << "\tPutDataArray epcExternalPartURI datasetPathInEpcExternalPart" << std::endl << "\t\tPut a dummy {0,1,2,3,4,5,6,7,8,9} integer array in a particular store epcExternalPartURI at a particular dataset path" << std::endl << std::endl;
	std::cout << "\tSubscribeNotif URI scope(default self) depth(default 1) receiveXML(true or false, default is true) dataTypeFilter,dataTypeFilter,...(default noFilter)" << std::endl << "\t\tSubscribe to notifications." << std::endl << std::endl;
	std::cout << "\tLoad epcDocument" << std::endl << "\t\tLoad an EPC document into the DataObjectRepository." << std::endl << std::endl;
	std::cout << "\tquit" << std::endl << "\t\tQuit the session." << std::endl << std::endl;
}

void askUser(ETP_NS::AbstractSession* session)
{
	std::string buffer;

	std::cout << "What is your command (\"quit\" for closing connection)?" << std::endl;
	std::string command;
	while (command != "quit")
	{
		std::getline(std::cin, command);
		auto commandTokens = tokenize(command, ' ');

		if (commandTokens.empty()) {
			printHelp();
			continue;
		}
		if (commandTokens[0] == "quit") {
			continue;
		}

		else if (commandTokens[0] == "GetResources") {
			Energistics::Etp::v12::Protocol::Discovery::GetResources mb;
			mb.context.uri = commandTokens[1];
			mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::self;
			mb.context.depth = 1;
			mb.context.navigableEdges = Energistics::Etp::v12::Datatypes::Object::RelationshipKind::Primary;
			mb.countObjects = true;

			if (commandTokens.size() > 2) {
				if (commandTokens[2] == "self")
					mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::self;
				else if (commandTokens[2] == "sources")
					mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::sources;
				else if (commandTokens[2] == "sourcesOrSelf")
					mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::sourcesOrSelf;
				else if (commandTokens[2] == "targets")
					mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::targets;
				else if (commandTokens[2] == "targetsOrSelf")
					mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::targetsOrSelf;

				if (commandTokens.size() > 3) {
					mb.context.depth = std::stoi(commandTokens[3]);

					if (commandTokens.size() > 4) {
						if (commandTokens[4] == "false" || commandTokens[4] == "False" || commandTokens[4] == "FALSE") {
							mb.countObjects = false;
						}

						if (commandTokens.size() > 6) {
							mb.context.dataObjectTypes = tokenize(commandTokens[6], ',');
						}
					}
				}
			}

			if (commandTokens.size() > 5 && (commandTokens[5] == "true" || commandTokens[5] == "True" || commandTokens[5] == "TRUE")) {
				std::static_pointer_cast<MyOwnDiscoveryProtocolHandlers>(session->getDiscoveryProtocolHandlers())->getObjectWhenDiscovered.push_back(session->send(mb, 0, 0x02));
			}
			else {
				session->send(mb, 0, 0x02);
			}
			continue;
		}
		else if (commandTokens[0] == "GetDataObjects") {
			Energistics::Etp::v12::Protocol::Store::GetDataObjects getO;
			std::vector<std::string> tokens = tokenize(commandTokens[1], ',');
			std::map<std::string, std::string> tokenMaps;
			for (size_t i = 0; i < tokens.size(); ++i) {
				tokenMaps[std::to_string(i)] = tokens[i];
			}
			getO.uris = tokenMaps;
			session->send(getO, 0, 0x02);
		}
		else if (commandTokens[0] == "SubscribeNotif") {
			Energistics::Etp::v12::Protocol::StoreNotification::SubscribeNotifications mb;
			Energistics::Etp::v12::Datatypes::Object::SubscriptionInfo subscriptionInfo;
			subscriptionInfo.context.uri = commandTokens[1];
			subscriptionInfo.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::self;
			subscriptionInfo.context.depth = 1;
			boost::uuids::random_generator gen;
			boost::uuids::uuid uuid = gen();
			std::move(std::begin(uuid.data), std::end(uuid.data), subscriptionInfo.requestUuid.array.begin());

			if (commandTokens.size() > 2) {
				if (commandTokens[2] == "self")
					subscriptionInfo.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::self;
				else if (commandTokens[2] == "sources")
					subscriptionInfo.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::sources;
				else if (commandTokens[2] == "sourcesOrSelf")
					subscriptionInfo.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::sourcesOrSelf;
				else if (commandTokens[2] == "targets")
					subscriptionInfo.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::targets;
				else if (commandTokens[2] == "targetsOrSelf")
					subscriptionInfo.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::targetsOrSelf;

				if (commandTokens.size() > 3) {
					subscriptionInfo.context.depth = std::stoi(commandTokens[3]);

					if (commandTokens.size() > 4) {
						subscriptionInfo.includeObjectData = commandTokens[4] == "true";

						if (commandTokens.size() > 5) {
							subscriptionInfo.context.dataObjectTypes = tokenize(commandTokens[5], ',');
						}
					}
				}
			}

			mb.request["0"] = subscriptionInfo;

			session->send(mb, 0, 0x02);

			continue;
		}

		if (commandTokens.size() == 1) {
			if (commandTokens[0] == "Ping") {
				Energistics::Etp::v12::Protocol::Core::Ping ping;
				ping.currentDateTime = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
				session->send(ping, 0, 0x02); // 0x10 requires Acknowledge from the store
				std::cout << "PING at " << ping.currentDateTime << std::endl;
			}
		}
		else if (commandTokens.size() == 2) {
			if (commandTokens[0] == "GetSourceObjects") {
				Energistics::Etp::v12::Protocol::Discovery::GetResources mb;
				mb.context.uri = commandTokens[1];
				mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::sources;
				mb.context.depth = 1;
				mb.context.navigableEdges = Energistics::Etp::v12::Datatypes::Object::RelationshipKind::Primary;
				mb.countObjects = true;

				std::static_pointer_cast<MyOwnDiscoveryProtocolHandlers>(session->getDiscoveryProtocolHandlers())->getObjectWhenDiscovered.push_back(session->send(mb, 0, 0x02));
			}
			else if (commandTokens[0] == "GetTargetObjects") {
				Energistics::Etp::v12::Protocol::Discovery::GetResources mb;
				mb.context.uri = commandTokens[1];
				mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::targets;
				mb.context.depth = 1;
				mb.context.navigableEdges = Energistics::Etp::v12::Datatypes::Object::RelationshipKind::Primary;
				mb.countObjects = true;

				std::static_pointer_cast<MyOwnDiscoveryProtocolHandlers>(session->getDiscoveryProtocolHandlers())->getObjectWhenDiscovered.push_back(session->send(mb, 0, 0x02));
			}
			else if (commandTokens[0] == "GetResourceObjects") {
				Energistics::Etp::v12::Protocol::Discovery::GetResources mb;
				mb.context.uri = commandTokens[1];
				mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::targetsOrSelf;
				mb.context.depth = 1;
				mb.context.navigableEdges = Energistics::Etp::v12::Datatypes::Object::RelationshipKind::Primary;
				mb.countObjects = true;
				std::static_pointer_cast<MyOwnDiscoveryProtocolHandlers>(session->getDiscoveryProtocolHandlers())->getObjectWhenDiscovered.push_back(session->send(mb, 0, 0x02));

				mb.scope = Energistics::Etp::v12::Datatypes::Object::ContextScopeKind::sources;
				std::static_pointer_cast<MyOwnDiscoveryProtocolHandlers>(session->getDiscoveryProtocolHandlers())->getObjectWhenDiscovered.push_back(session->send(mb, 0, 0x02));
			}
		}
		else if (commandTokens.size() == 3) {
			if (commandTokens[0] == "GetDataArray") {
				Energistics::Etp::v12::Protocol::DataArray::GetDataArrays gda;
				gda.dataArrays["0"].uri = commandTokens[1];
				gda.dataArrays["0"].pathInResource = commandTokens[2];
				std::cout << gda.dataArrays["0"].pathInResource << std::endl;
				session->send(gda);
			}
			else if (commandTokens[0] == "PutDataArray") {
				Energistics::Etp::v12::Protocol::DataArray::PutDataArrays pda;
				pda.dataArrays["0"].uid.uri = commandTokens[1];
				pda.dataArrays["0"].uid.pathInResource = commandTokens[2];

				std::vector<int64_t> dimensions = { 10 };
				pda.dataArrays["0"].array.dimensions = dimensions;

				Energistics::Etp::v12::Datatypes::AnyArray data;
				Energistics::Etp::v12::Datatypes::ArrayOfInt arrayOfInt;
				arrayOfInt.values = { 0,1,2,3,4,5,6,7,8,9 };
				data.item.set_ArrayOfInt(arrayOfInt);
				pda.dataArrays["0"].array.data = data;

				session->send(pda, 0, 0x02);
			}
		}
	}

	session->close();
}

void MyOwnCoreProtocolHandlers::on_OpenSession(const Energistics::Etp::v12::Protocol::Core::OpenSession & os, int64_t correlationId)
{
	// Ask the user about what he wants to do on another thread
	// The main thread is on reading mode
	std::thread askUserThread(askUser, session);
	askUserThread.detach(); // Detach the thread since we don't want it to be a blocking one.
}


text:
/**
 * \file Supporting_Methods.cpp
 */

#include "Global.hpp"

#include <vector>
#include <string>
#include <iterator>

#include <fstream>
#include <iostream>

#include <getopt.h>

#include <boost/tokenizer.hpp>
#include <boost/assign/std/vector.hpp>

using namespace std;
using namespace boost;
using namespace boost::assign;

vector<string> tokenize(string token, string str) {
	vector<string> tokens;
	char_separator<char> sep(token.c_str()); //without c_str() not working, changes string into c-string
	tokenizer< char_separator<char> > tok(str, sep);

	for (tokenizer< char_separator<char> >::iterator i = tok.begin(); i != tok.end(); ++i) {
		tokens += *i;
	}
	return tokens;
}

void reset_getopt() {
	#ifdef __GLIBC__
		optind = 0;
	#else
		optind = 1;
	#endif
	#ifdef HAVE_OPTRESET
		optreset = 1;
	#endif
}

bool files_identical (string first_file, string second_file) {
	ifstream first_ifstream( first_file.c_str() );
	ifstream second_ifstream( second_file.c_str() );

	if (!first_ifstream) {
		ERR_STRM << "Error (in Test Mode): Could not open '" << first_file << "'!" << endl;
		cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl;
		abort();
	}

	if (!second_ifstream) {
		ERR_STRM << "Error (in Test Mode): Could not open '" << second_file << "'!" << endl;
		cout << __FILE__ << " " << __FUNCTION__ << " " << __LINE__ << endl;
		abort();
	}

	string str;
	vector <string> first;
	vector <string> second;

	while ( getline(first_ifstream, str) ) {
		first += str;
	}
	while ( getline(second_ifstream, str) ) {
		second += str;
	}

	if ( first.size() != second.size()) {
		return false;
	}
	for ( unsigned i = 0; i < first.size(); i++) {
		if ( first[i] != second[i] ) {
			return false;
		}
	}
	return true;
}

max_stars_repo_name: sestaton/Augustus

max_issues_repo_name: sestaton/Augustus

max_forks_repo_name: sestaton/Augustus


text:
/*
 * ============================================================================
 *       Filename:  RecoTauMVATransform.cc
 *
 *    Description:  Transform TaNC output according to decay mode.
 *        Created:  10/22/2010 15:36:12
 *         Author:  Evan K. Friis (UC Davis), evan.klose.friis@cern.ch
 * ============================================================================
 */

#include <boost/ptr_container/ptr_map.hpp>
#include <memory>

#include "RecoTauTag/RecoTau/interface/TauDiscriminationProducerBase.h"
#include "RecoTauTag/RecoTau/interface/PFTauDecayModeTools.h"

#include "DataFormats/TauReco/interface/PFTau.h"
#include "DataFormats/TauReco/interface/PFTauFwd.h"

#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"

#include <FWCore/ParameterSet/interface/ConfigurationDescriptions.h>
#include <FWCore/ParameterSet/interface/ParameterSetDescription.h>

#include "TGraph.h"

namespace {

// Build the transformation function from the PSet format
std::unique_ptr<TGraph> buildTransform(const edm::ParameterSet &pset) {
  double min = pset.getParameter<double>("min");
  double max = pset.getParameter<double>("max");
  const std::vector<double> &values =
      pset.getParameter<std::vector<double> >("transform");
  double stepSize = (max - min)/(values.size()-1);
  std::unique_ptr<TGraph> output(new TGraph(values.size()));
  for (size_t step = 0; step < values.size(); ++step) {
    double x = min + step*stepSize;
    output->SetPoint(step, x, values[step]);
  }
  return output;
}

}

class RecoTauMVATransform : public PFTauDiscriminationProducerBase {
  public:
    explicit RecoTauMVATransform(const edm::ParameterSet& pset);
    ~RecoTauMVATransform() override {}

    void beginEvent(const edm::Event&, const edm::EventSetup&) override;
    double discriminate(const reco::PFTauRef&) const override;

    static void fillDescriptions(edm::ConfigurationDescriptions & descriptions);
  private:
    // Map a decay mode to a transformation
    typedef boost::ptr_map<reco::PFTau::hadronicDecayMode, TGraph> TransformMap;
    TransformMap transforms_;
    // Points to raw TaNC output
    edm::InputTag input_;
    edm::Handle<reco::PFTauDiscriminator> disc_;
};

RecoTauMVATransform::RecoTauMVATransform(const edm::ParameterSet& pset)
  :PFTauDiscriminationProducerBase(pset) {
  input_ = pset.getParameter<edm::InputTag>("toTransform");
  typedef std::vector<edm::ParameterSet> VPSet;
  const VPSet& transforms = pset.getParameter<VPSet>("transforms");
  prediscriminantFailValue_ = -2.0;
  for(auto const& transform : transforms) {
    unsigned int nCharged = transform.getParameter<unsigned int>("nCharged");
    unsigned int nPiZeros = transform.getParameter<unsigned int>("nPiZeros");
    // Get the transform
    const edm::ParameterSet &transformImpl =
        transform.getParameter<edm::ParameterSet>("transform");
    // Get the acutal decay mode
    reco::PFTau::hadronicDecayMode decayMode =
        reco::tau::translateDecayMode(nCharged, nPiZeros);

    if (!transforms_.count(decayMode)) {
      // Add it
      transforms_.insert(decayMode, buildTransform(transformImpl).get());
    } else {
      edm::LogError("DecayModeNotUnique") << "The tau decay mode with "
        "nCharged/nPiZero = " << nCharged << "/" << nPiZeros <<
        " dm: " << decayMode <<
        " is associated to multiple MVA transforms, "
        "the second instantiation is being ignored!!!";
    }
  }
}

// Update our discriminator handle at the begninng of the event
void
RecoTauMVATransform::beginEvent(const edm::Event& evt, const edm::EventSetup&) {
  evt.getByLabel(input_, disc_);
}

double RecoTauMVATransform::discriminate(const reco::PFTauRef& tau) const {
  // Check if we support this decay mode:
  TransformMap::const_iterator transformIter =
      transforms_.find(tau->decayMode());
  // Unsupported DM
  if (transformIter == transforms_.end())
    return prediscriminantFailValue_;
  const TGraph *transform = transformIter->second;
  // Get the discriminator output to transform
  double value = (*disc_)[tau];
  double result = transform->Eval(value);
  return result;
}

void
RecoTauMVATransform::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
  // recoTauMVATransform
  edm::ParameterSetDescription desc;

  desc.add<edm::InputTag>("toTransform");

  edm::ParameterSetDescription vpsd_transforms;
  vpsd_transforms.add<uint32_t>("nCharged");
  vpsd_transforms.add<uint32_t>("nPiZeros");

  edm::ParameterSetDescription pset_transform;
  pset_transform.add<double>("min");
  pset_transform.add<double>("max");
  pset_transform.add<std::vector<double>>("transform");
  vpsd_transforms.add<edm::ParameterSetDescription>("transform", pset_transform);

  //            name          description       no defaults items
  desc.addVPSet("transforms", vpsd_transforms);

  fillProducerDescriptions(desc); // inherited from the base

  descriptions.add("recoTauMVATransform", desc);
}

#include "FWCore/Framework/interface/MakerMacros.h"
DEFINE_FWK_MODULE(RecoTauMVATransform);

max_stars_repo_name: bisnupriyasahu/cmssw

max_issues_repo_name: bisnupriyasahu/cmssw

max_forks_repo_name: bisnupriyasahu/cmssw


text:
///////////////////////////////////////////////////////////////////////////////
// dynamic.hpp
//
//  Copyright 2008 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_XPRESSIVE_DETAIL_DYNAMIC_DYNAMIC_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_DYNAMIC_DYNAMIC_HPP_EAN_10_04_2005

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <vector>
#include <utility>
#include <algorithm>
#include <boost/assert.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/throw_exception.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>
#include <boost/xpressive/detail/core/quant_style.hpp>
#include <boost/xpressive/detail/dynamic/matchable.hpp>
#include <boost/xpressive/detail/dynamic/sequence.hpp>
#include <boost/xpressive/detail/core/icase.hpp>

namespace boost { namespace xpressive { namespace detail
{

///////////////////////////////////////////////////////////////////////////////
// invalid_xpression
template<typename BidiIter>
struct invalid_xpression
  : matchable_ex<BidiIter>
{
    invalid_xpression()
      : matchable_ex<BidiIter>()
    {
        intrusive_ptr_add_ref(this); // keep alive forever
    }

    bool match(match_state<BidiIter> &) const
    {
        BOOST_ASSERT(false);
        return false;
    }
};

///////////////////////////////////////////////////////////////////////////////
// get_invalid_xpression
template<typename BidiIter>
inline shared_matchable<BidiIter> const &get_invalid_xpression()
{
    static invalid_xpression<BidiIter> const invalid_xpr;
    static intrusive_ptr<matchable_ex<BidiIter> const> const invalid_ptr(&invalid_xpr);
    static shared_matchable<BidiIter> const invalid_matchable(invalid_ptr);
    return invalid_matchable;
}

///////////////////////////////////////////////////////////////////////////////
// dynamic_xpression
template<typename Matcher, typename BidiIter>
struct dynamic_xpression
  : Matcher
  , matchable_ex<BidiIter>
{
    typedef typename iterator_value<BidiIter>::type char_type;

    dynamic_xpression(Matcher const &matcher = Matcher())
      : Matcher(matcher)
      , next_(get_invalid_xpression<BidiIter>())
    {
    }

    virtual bool match(match_state<BidiIter> &state) const
    {
        return this->Matcher::match(state, *this->next_.matchable());
    }

    virtual void link(xpression_linker<char_type> &linker) const
    {
        linker.accept(*static_cast<Matcher const *>(this), this->next_.matchable().get());
        this->next_.link(linker);
    }

    virtual void peek(xpression_peeker<char_type> &peeker) const
    {
        this->peek_next_(peeker.accept(*static_cast<Matcher const *>(this)), peeker);
    }

    virtual void repeat(quant_spec const &spec, sequence<BidiIter> &seq) const
    {
        this->repeat_(spec, seq, quant_type<Matcher>(), is_same<Matcher, mark_begin_matcher>());
    }

private:
    friend struct sequence<BidiIter>;

    void peek_next_(mpl::true_, xpression_peeker<char_type> &peeker) const
    {
        this->next_.peek(peeker);
    }

    void peek_next_(mpl::false_, xpression_peeker<char_type> &) const
    {
        // no-op
    }

    void repeat_(quant_spec const &spec, sequence<BidiIter> &seq, mpl::int_<quant_none>, mpl::false_) const
    {
        if(quant_none == seq.quant())
        {
            boost::throw_exception(
                regex_error(regex_constants::error_badrepeat, "expression cannot be quantified")
            );
        }
        else
        {
            this->repeat_(spec, seq, mpl::int_<quant_variable_width>(), mpl::false_());
        }
    }

    void repeat_(quant_spec const &spec, sequence<BidiIter> &seq, mpl::int_<quant_fixed_width>, mpl::false_) const
    {
        if(this->next_ == get_invalid_xpression<BidiIter>())
        {
            make_simple_repeat(spec, seq, matcher_wrapper<Matcher>(*this));
        }
        else
        {
            this->repeat_(spec, seq, mpl::int_<quant_variable_width>(), mpl::false_());
        }
    }

    void repeat_(quant_spec const &spec, sequence<BidiIter> &seq, mpl::int_<quant_variable_width>, mpl::false_) const
    {
        if(!is_unknown(seq.width()) && seq.pure())
        {
            make_simple_repeat(spec, seq);
        }
        else
        {
            make_repeat(spec, seq);
        }
    }

    void repeat_(quant_spec const &spec, sequence<BidiIter> &seq, mpl::int_<quant_fixed_width>, mpl::true_) const
    {
        make_repeat(spec, seq, this->mark_number_);
    }

    shared_matchable<BidiIter> next_;
};

///////////////////////////////////////////////////////////////////////////////
// make_dynamic
template<typename BidiIter, typename Matcher>
inline sequence<BidiIter> make_dynamic(Matcher const &matcher)
{
    typedef dynamic_xpression<Matcher, BidiIter> xpression_type;
    intrusive_ptr<xpression_type> xpr(new xpression_type(matcher));
    return sequence<BidiIter>(xpr);
}

///////////////////////////////////////////////////////////////////////////////
// alternates_vector
template<typename BidiIter>
struct alternates_vector
  : std::vector<shared_matchable<BidiIter> >
{
    BOOST_STATIC_CONSTANT(std::size_t, width = unknown_width::value);
    BOOST_STATIC_CONSTANT(bool, pure = false);
};

///////////////////////////////////////////////////////////////////////////////
// matcher_wrapper
template<typename Matcher>
struct matcher_wrapper
  : Matcher
{
    matcher_wrapper(Matcher const &matcher = Matcher())
      : Matcher(matcher)
    {
    }

    template<typename BidiIter>
    bool match(match_state<BidiIter> &state) const
    {
        return this->Matcher::match(state, matcher_wrapper<true_matcher>());
    }

    template<typename Char>
    void link(xpression_linker<Char> &linker) const
    {
        linker.accept(*static_cast<Matcher const *>(this), 0);
    }

    template<typename Char>
    void peek(xpression_peeker<Char> &peeker) const
    {
        peeker.accept(*static_cast<Matcher const *>(this));
    }
};

//////////////////////////////////////////////////////////////////////////
// make_simple_repeat
template<typename BidiIter, typename Xpr>
inline void
make_simple_repeat(quant_spec const &spec, sequence<BidiIter> &seq, Xpr const &xpr)
{
    if(spec.greedy_)
    {
        simple_repeat_matcher<Xpr, mpl::true_> quant(xpr, spec.min_, spec.max_, seq.width().value());
        seq = make_dynamic<BidiIter>(quant);
    }
    else
    {
        simple_repeat_matcher<Xpr, mpl::false_> quant(xpr, spec.min_, spec.max_, seq.width().value());
        seq = make_dynamic<BidiIter>(quant);
    }
}

//////////////////////////////////////////////////////////////////////////
// make_simple_repeat
template<typename BidiIter>
inline void
make_simple_repeat(quant_spec const &spec, sequence<BidiIter> &seq)
{
    seq += make_dynamic<BidiIter>(true_matcher());
    make_simple_repeat(spec, seq, seq.xpr());
}

//////////////////////////////////////////////////////////////////////////
// make_optional
template<typename BidiIter>
inline void
make_optional(quant_spec const &spec, sequence<BidiIter> &seq)
{
    typedef shared_matchable<BidiIter> xpr_type;
    seq += make_dynamic<BidiIter>(alternate_end_matcher());
    if(spec.greedy_)
    {
        optional_matcher<xpr_type, mpl::true_> opt(seq.xpr());
        seq = make_dynamic<BidiIter>(opt);
    }
    else
    {
        optional_matcher<xpr_type, mpl::false_> opt(seq.xpr());
        seq = make_dynamic<BidiIter>(opt);
    }
}

//////////////////////////////////////////////////////////////////////////
// make_optional
template<typename BidiIter>
inline void
make_optional(quant_spec const &spec, sequence<BidiIter> &seq, int mark_nbr)
{
    typedef shared_matchable<BidiIter> xpr_type;
    seq += make_dynamic<BidiIter>(alternate_end_matcher());
    if(spec.greedy_)
    {
        optional_mark_matcher<xpr_type, mpl::true_> opt(seq.xpr(), mark_nbr);
        seq = make_dynamic<BidiIter>(opt);
    }
    else
    {
        optional_mark_matcher<xpr_type, mpl::false_> opt(seq.xpr(), mark_nbr);
        seq = make_dynamic<BidiIter>(opt);
    }
}

//////////////////////////////////////////////////////////////////////////
// make_repeat
template<typename BidiIter>
inline void
make_repeat(quant_spec const &spec, sequence<BidiIter> &seq)
{
    // only bother creating a repeater if max is greater than one
    if(1 < spec.max_)
    {
        // create a hidden mark so this expression can be quantified
        int mark_nbr = -static_cast<int>(++*spec.hidden_mark_count_);
        seq = make_dynamic<BidiIter>(mark_begin_matcher(mark_nbr)) + seq
            + make_dynamic<BidiIter>(mark_end_matcher(mark_nbr));
        make_repeat(spec, seq, mark_nbr);
        return;
    }

    // if min is 0, the repeat must be made optional
    if(0 == spec.min_)
    {
        make_optional(spec, seq);
    }
}

//////////////////////////////////////////////////////////////////////////
// make_repeat
template<typename BidiIter>
inline void
make_repeat(quant_spec const &spec, sequence<BidiIter> &seq, int mark_nbr)
{
    BOOST_ASSERT(spec.max_); // we should never get here if max is 0

    // only bother creating a repeater if max is greater than one
    if(1 < spec.max_)
    {
        // TODO: statically bind the repeat matchers to the mark matchers for better perf
        unsigned int min = spec.min_ ? spec.min_ : 1U;
        repeat_begin_matcher repeat_begin(mark_nbr);
        if(spec.greedy_)
        {
            repeat_end_matcher<mpl::true_> repeat_end(mark_nbr, min, spec.max_);
            seq = make_dynamic<BidiIter>(repeat_begin) + seq
                + make_dynamic<BidiIter>(repeat_end);
        }
        else
        {
            repeat_end_matcher<mpl::false_> repeat_end(mark_nbr, min, spec.max_);
            seq = make_dynamic<BidiIter>(repeat_begin) + seq
                + make_dynamic<BidiIter>(repeat_end);
        }
    }

    // if min is 0, the repeat must be made optional
    if(0 == spec.min_)
    {
        make_optional(spec, seq, mark_nbr);
    }
}

}}} // namespace boost::xpressive::detail

#endif

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham


text:
////////////////////////////////////////////////////////////////////
//
// $Id: QEM.hxx 2021/06/05 14:25:18 kanai Exp $
//
// Copyright (c) 2021 Takashi Kanai
// Released under the MIT license
//
////////////////////////////////////////////////////////////////////

#ifndef _QEM_HXX
#define _QEM_HXX 1

#include <vector>
#include <cmath>
#include <cstring>
using namespace std;

#include "VertexL.hxx"
#include "FaceL.hxx"

#if 1
#include <Eigen/Dense>
#include <Eigen/Cholesky>
//using namespace Eigen;
#endif

#define DEFAULT_QEM_SIZE 10

class QEM {

  std::vector<double> mat_;

 public:

  QEM(){
    resize( DEFAULT_QEM_SIZE );
    init();
  };
  QEM(int size) { resize( size ); init(); };
  QEM( VertexL* vt ) {
    resize( DEFAULT_QEM_SIZE );
    init();
    QEM q;
    q.construct(vt);
    add(q);
  };
  QEM( HalfedgeL* he ) {
    resize( DEFAULT_QEM_SIZE );
    init();
    QEM q;
    q.construct(he);
    add(q);
  };
  QEM( HalfedgeL* he, double penalty ) {
    resize( DEFAULT_QEM_SIZE );
    init();
    QEM q; q.construct_boundary( he, penalty );
    add(q);
  };
  // copy constructor
  QEM( const QEM& q ) {
    resize( q.size() );
    set(q);
  };

  ~QEM(){};

  int size() const { return mat_.size(); };
  void resize( int n ) { mat_.resize( n ); };
  void init() { for ( unsigned int i = 0; i < mat_.size(); ++i ) mat_[i]=0.0; };
  void clear() { for ( unsigned int i = 0; i < mat_.size(); ++i ) mat_[i]=0.0; };

  void optimizePoint( VertexL* vt ) {
    optimizePoint( vt->point() );
  };
  bool optimizePoint( Point3d& );
  // matrix inverse
  bool inverse( QEM& );

  double error( Point3d& );

  // vertex QEM
  void construct( VertexL* vt ) {
    QEM q;
    construct( vt, q );
    add(q);
  };
  void construct( VertexL*, QEM& );

  // face QEM
  void construct( HalfedgeL* he ) {
    QEM q;
    construct( he, q );
    add(q);
  };
  void construct( HalfedgeL*, QEM& );
  void construct( FaceL*, QEM& );

  void construct_boundary( HalfedgeL* he, double penalty ) {
    QEM q;
    construct_boundary( he, penalty, q );
    add(q);
  };
  void construct_boundary( HalfedgeL*, double, QEM& );

  void setMat( int i, double val ) {
//     if ( val < .0 ) cout << i << " " << val << endl;
    mat_[i] = val;
  };
  //void set( VertexL* );

  void set( const QEM& q ) {
    for ( unsigned int i = 0; i < mat_.size(); ++i )
      mat_[i] = q.mat(i);
  };
  void mul( Point3d& p ) {
    Point3d q;
    mul(p, q);
    p.set(q);
  };

  void mul( Point3d& p, Point3d& q ) {
    q.x = mat_[0]*p.x + mat_[3]*p.y + mat_[4]*p.z;
    q.y = mat_[3]*p.x + mat_[1]*p.y + mat_[5]*p.z;
    q.z = mat_[4]*p.x + mat_[5]*p.y + mat_[2]*p.z;
  };

  void add( const QEM& q1, const QEM& q2 ) {
    for (unsigned int i = 0; i < mat_.size(); ++i )
      mat_[i] += (q1.mat(i) + q2.mat(i));
  };

  void add( const QEM& q ) {
    for (unsigned int i = 0; i < mat_.size(); ++i )
      mat_[i] += q.mat(i);
  };

  bool equals( const QEM& q ) {
    return ( (mat_[0] == q.mat(0)) && (mat_[1] == q.mat(1)) &&
	     (mat_[2] == q.mat(2)) && (mat_[3] == q.mat(3)) &&
	     (mat_[4] == q.mat(4)) && (mat_[5] == q.mat(5)) &&
	     (mat_[6] == q.mat(6)) && (mat_[7] == q.mat(7)) &&
	     (mat_[8] == q.mat(8)) && (mat_[9] == q.mat(9)) );
  };

  void scale( double t ) {
    for (unsigned int i = 0; i < mat_.size(); ++i )
      mat_[i] *= t;
  };

  double sum() {
    double t = .0;
    for ( unsigned int i = 0; i < mat_.size(); ++i ) t += mat_[i];
    return t;
  };

  void copy( QEM& q ) {
    for ( unsigned int i = 0; i < mat_.size(); ++i )
      q.setMat(i, mat_[i]);
  };

  //
  // operators
  //
  QEM& operator=( const QEM& q ) {
    set(q);
    return *this;
  };

  QEM& operator+=( const QEM& q ) {
    add( q );
    return *this;
  };

  bool operator==(const QEM& q ) {
    return equals(q);
  };

  friend std::ostream& operator <<( std::ostream& o, const QEM& q ) {
    return o << "( " << q.mat(0) << ", " << q.mat(1) << ", " << q.mat(2) << ", " << q.mat(3) << ", " << q.mat(4) << " " << q.mat(5) << " " << q.mat(6) << " " << q.mat(7) << " " << q.mat(8) << " " << q.mat(9) << " )\n";
  };

  double mat(int i) const { return mat_[i]; };
  //std::vector<double>* mat() { return &mat_; };

  bool invert( double* m, double* invOut ) {

    double inv[16];
    inv[0] = m[5]  * m[10] * m[15] -
             m[5]  * m[11] * m[14] -
             m[9]  * m[6]  * m[15] +
             m[9]  * m[7]  * m[14] +
             m[13] * m[6]  * m[11] -
             m[13] * m[7]  * m[10];

    inv[4] = -m[4]  * m[10] * m[15] +
              m[4]  * m[11] * m[14] +
              m[8]  * m[6]  * m[15] -
              m[8]  * m[7]  * m[14] -
              m[12] * m[6]  * m[11] +
              m[12] * m[7]  * m[10];

    inv[8] = m[4]  * m[9] * m[15] -
             m[4]  * m[11] * m[13] -
             m[8]  * m[5] * m[15] +
             m[8]  * m[7] * m[13] +
             m[12] * m[5] * m[11] -
             m[12] * m[7] * m[9];

    inv[12] = -m[4]  * m[9] * m[14] +
               m[4]  * m[10] * m[13] +
               m[8]  * m[5] * m[14] -
               m[8]  * m[6] * m[13] -
               m[12] * m[5] * m[10] +
               m[12] * m[6] * m[9];

    inv[1] = -m[1]  * m[10] * m[15] +
              m[1]  * m[11] * m[14] +
              m[9]  * m[2] * m[15] -
              m[9]  * m[3] * m[14] -
              m[13] * m[2] * m[11] +
              m[13] * m[3] * m[10];

    inv[5] = m[0]  * m[10] * m[15] -
             m[0]  * m[11] * m[14] -
             m[8]  * m[2] * m[15] +
             m[8]  * m[3] * m[14] +
             m[12] * m[2] * m[11] -
             m[12] * m[3] * m[10];

    inv[9] = -m[0]  * m[9] * m[15] +
              m[0]  * m[11] * m[13] +
              m[8]  * m[1] * m[15] -
              m[8]  * m[3] * m[13] -
              m[12] * m[1] * m[11] +
              m[12] * m[3] * m[9];

    inv[13] = m[0]  * m[9] * m[14] -
              m[0]  * m[10] * m[13] -
              m[8]  * m[1] * m[14] +
              m[8]  * m[2] * m[13] +
              m[12] * m[1] * m[10] -
              m[12] * m[2] * m[9];

    inv[2] = m[1]  * m[6] * m[15] -
             m[1]  * m[7] * m[14] -
             m[5]  * m[2] * m[15] +
             m[5]  * m[3] * m[14] +
             m[13] * m[2] * m[7] -
             m[13] * m[3] * m[6];

    inv[6] = -m[0]  * m[6] * m[15] +
              m[0]  * m[7] * m[14] +
              m[4]  * m[2] * m[15] -
              m[4]  * m[3] * m[14] -
              m[12] * m[2] * m[7] +
              m[12] * m[3] * m[6];

    inv[10] = m[0]  * m[5] * m[15] -
              m[0]  * m[7] * m[13] -
              m[4]  * m[1] * m[15] +
              m[4]  * m[3] * m[13] +
              m[12] * m[1] * m[7] -
              m[12] * m[3] * m[5];

    inv[14] = -m[0]  * m[5] * m[14] +
               m[0]  * m[6] * m[13] +
               m[4]  * m[1] * m[14] -
               m[4]  * m[2] * m[13] -
               m[12] * m[1] * m[6] +
               m[12] * m[2] * m[5];

    inv[3] = -m[1] * m[6] * m[11] +
              m[1] * m[7] * m[10] +
              m[5] * m[2] * m[11] -
              m[5] * m[3] * m[10] -
              m[9] * m[2] * m[7] +
              m[9] * m[3] * m[6];

    inv[7] = m[0] * m[6] * m[11] -
             m[0] * m[7] * m[10] -
             m[4] * m[2] * m[11] +
             m[4] * m[3] * m[10] +
             m[8] * m[2] * m[7] -
             m[8] * m[3] * m[6];

    inv[11] = -m[0] * m[5] * m[11] +
               m[0] * m[7] * m[9] +
               m[4] * m[1] * m[11] -
               m[4] * m[3] * m[9] -
               m[8] * m[1] * m[7] +
               m[8] * m[3] * m[5];

    inv[15] = m[0] * m[5] * m[10] -
              m[0] * m[6] * m[9] -
              m[4] * m[1] * m[10] +
              m[4] * m[2] * m[9] +
              m[8] * m[1] * m[6] -
              m[8] * m[2] * m[5];

    double det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];

    // cout << "det " << det << endl;
    if (det == 0) return false;

    det = 1.0 / det;
    for (int i = 0; i < 16; i++)
      {
        invOut[i] = inv[i] * det;
      }

    return true;
  };

  void cholesky4( double* A, double* L ) {

    //double *L = (double*)calloc(n * n, sizeof(double));
    //if (L == NULL)
    //exit(EXIT_FAILURE);
    for ( int i = 0; i < 16; ++i ) L[i] = .0;

    int n = 4;
    for (int i = 0; i < n; i++)
      for (int j = 0; j < (i+1); j++) {
        double s = 0;
        for (int k = 0; k < j; k++)
          s += L[i * n + k] * L[j * n + k];
        L[i * n + j] = (i == j) ?
          std::sqrt(A[i * n + i] - s) :
          (1.0 / L[j * n + j] * (A[i * n + j] - s));
      }
    // cout << "cholesky ";
    // for ( int m = 0; m < 16; ++m )
    //   cout << L[m] << " ";
    // cout << endl;
  };

  void toInvR( double* Rinv ) {

    Eigen::MatrixXd A(4,4);
    A << mat_[0], mat_[3], mat_[4], mat_[6],
      mat_[3], mat_[1], mat_[5], mat_[7],
      mat_[4], mat_[5], mat_[2], mat_[8],
      mat_[6], mat_[7], mat_[8], mat_[9];

    // Cholesky decomposition
    Eigen::LLT<Eigen::MatrixXd> lltOfA(A);
    Eigen::MatrixXd L = lltOfA.matrixL();
    // Inverse
    Eigen::MatrixXd Linv = L.inverse();

    // OpenGL is column-major
    Eigen::MatrixXd Linvtrans = Linv.transpose();
    memcpy( Rinv, Linvtrans.data(), sizeof(double) * 16 );

#if 0
    // OpenGL is column-major
    for ( int i = 0; i < 4; ++i )
      for ( int j = 0; j < 4; ++j )
        Rinv[ 4 * i + j ] = Linv(i,j);
#endif

#if 0
    double a[16];
    Eigen::MatrixXd Linvtrans = Linv.transpose();
    memcpy( a, Linvtrans.data(), sizeof(double) * 16 );

    cout << "Rinv ";
    for ( int i = 0; i < 4; ++i )
      for ( int j = 0; j < 4; ++j )
        cout << Rinv[ 4 * i + j ] << " ";
    cout << endl;

    cout << "a ";
    for ( int i = 0; i < 4; ++i )
      for ( int j = 0; j < 4; ++j )
        cout << a[ 4 * i + j ] << " ";
    cout << endl;
#endif

#if 0
    double p[16];
    p[0]  = mat_[0]; p[1]  = mat_[3]; p[2]  = mat_[4]; p[3]  = mat_[6];
    p[4]  = mat_[3]; p[5]  = mat_[1]; p[6]  = mat_[5]; p[7]  = mat_[7];
    p[8]  = mat_[4]; p[9]  = mat_[5]; p[10] = mat_[2]; p[11] = mat_[8];
    p[12] = mat_[6]; p[13] = mat_[7]; p[14] = mat_[8]; p[15] = mat_[9];

    // cout << "p ";
    // for ( int m = 0; m < 16; ++m )
    //   cout << p[m] << " ";
    // cout << endl;

    // Cholesky decomposition
    double R[16];
    cholesky4( p, R );

    // inverse R
    if ( invert( R, Rinv ) == false )
      {
        cerr << "error in matrix inverse." << endl;
      }
#endif

  };

protected:

  double operator[](size_t index) {
    return mat_[index];
  };

};

#if 0
#ifdef __cplusplus
extern "C" {
#endif

// functions
extern void optimize_vector(Sped *, double *);
extern BOOL InvertSymMatrix3(double *, double *);
extern double calc_error(double *, Vec *);
extern void optimize_2subvector(Sped *, double *);
extern void make_qeminfmatrix(Sped *, double *, double *);
extern void optimize_infvector(Sped *, double *);
extern double calc_inferror(double *, Vec *);
extern void make_vqem2submatrix(Sped *, double *, double, double *);
extern void make_eqem2submatrix(Sped *, double, double *);
extern void loop_odd_vertex(Spvt *, Spvt *, Spvt *, Spvt *, int, double *, Vec *);
extern void loop_even_vertex(Sped *, int *, double *, double *, Vec *, BOOL);
extern void loop_even_vertex_vj(Spvt *, Sped *, int *, double *, double *, Vec *);
extern Sped *ppdedge_first_ring_edge(Sped *);
extern Sped *ppdedge_next_ring_edge(Sped *, Sped *);
extern Sped *ppdedge_prev_ring_edge(Sped *, Sped *);
extern Spvt *ppdedge_ring_another_vt(Sped *, Sped *);
extern Spvt *ppdedge_first_ring_vertex(Sped *, Sped **);
extern Spvt *ppdedge_last_ring_vertex( Sped *, Sped ** );
extern Spvt *ppdedge_next_ring_vertex(Spvt *, Sped *, Sped *, Sped **);
extern Spvt *ppdedge_prev_ring_vertex(Spvt *, Sped *, Sped *, Sped **);
extern Spvt *ppdedge_opposite_vertex(Sped *, Spvt *, Spvt *);
extern void qem_matrix4(double, Vec *, double *, double *);
extern void edge_ring_test(Sppd *);
extern void edge_ring_vertex_test(Sppd *);

// parameters for QEM evaluation
#define EVAL_VERTEX 0
#define EVAL_SLP    1
#define EVAL_2SUB   2

#ifdef __cplusplus
}
#endif
#endif

#endif // _QEM_HXX

ext: hxx

max_stars_repo_name: kanait/hsphparam

max_issues_repo_name: kanait/hsphparam

max_forks_repo_name: kanait/hsphparam


text:
//
// Copyright (c) 2015-2020 CNRS INRIA
// Copyright (c) 2016 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//

#ifndef __pinocchio_python_motion_hpp__
#define __pinocchio_python_motion_hpp__

#include <eigenpy/memory.hpp>
#include <boost/python/tuple.hpp>

#include "pinocchio/spatial/se3.hpp"
#include "pinocchio/spatial/motion.hpp"
#include "pinocchio/spatial/force.hpp"
#include "pinocchio/bindings/python/utils/copyable.hpp"
#include "pinocchio/bindings/python/utils/printable.hpp"

EIGENPY_DEFINE_STRUCT_ALLOCATOR_SPECIALIZATION(pinocchio::Motion)

namespace pinocchio
{
  namespace python
  {
    namespace bp = boost::python;

    template<typename T> struct call;

    template<typename Scalar, int Options>
    struct call< MotionTpl<Scalar,Options> >
    {
      typedef MotionTpl<Scalar,Options> Motion;

      static bool isApprox(const Motion & self, const Motion & other,
                           const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision())
      {
        return self.isApprox(other,prec);
      }

      static bool isZero(const Motion & self,
                         const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision())
      {
        return self.isZero(prec);
      }
    };

    BOOST_PYTHON_FUNCTION_OVERLOADS(isApproxMotion_overload,call<Motion>::isApprox,2,3)
    BOOST_PYTHON_FUNCTION_OVERLOADS(isZero_overload,call<Motion>::isZero,1,2)

    template<typename Motion>
    struct MotionPythonVisitor
      : public boost::python::def_visitor< MotionPythonVisitor<Motion> >
    {
      enum { Options = traits<Motion>::Options };

      typedef typename Motion::Scalar Scalar;
      typedef ForceTpl<Scalar,traits<Motion>::Options> Force;
      typedef typename Motion::Vector6 Vector6;
      typedef typename Motion::Vector3 Vector3;

    public:

      template<class PyClass>
      void visit(PyClass& cl) const
      {
        cl
        .def(bp::init<>("Default constructor"))
        .def(bp::init<Vector3,Vector3>
             ((bp::arg("linear"),bp::arg("angular")),
              "Initialize from linear and angular components of a Motion vector (don(t mix the order)."))
        .def(bp::init<Vector6>((bp::arg("vec")),"Init from a vector 6 [linear velocity, angular velocity]"))
        .def(bp::init<Motion>((bp::arg("other")),"Copy constructor."))

        .add_property("linear",
                      &MotionPythonVisitor::getLinear,
                      &MotionPythonVisitor::setLinear,
                      "Linear part of a *this, corresponding to the linear velocity in case of a Spatial velocity.")
        .add_property("angular",
                      &MotionPythonVisitor::getAngular,
                      &MotionPythonVisitor::setAngular,
                      "Angular part of a *this, corresponding to the angular velocity in case of a Spatial velocity.")
        .add_property("vector",
                      &MotionPythonVisitor::getVector,
                      &MotionPythonVisitor::setVector,
                      "Returns the components of *this as a 6d vector.")
        .add_property("np",&MotionPythonVisitor::getVector)

        .def("se3Action",&Motion::template se3Action<Scalar,Options>,
             bp::args("M"),"Returns the result of the action of M on *this.")
        .def("se3ActionInverse",&Motion::template se3ActionInverse<Scalar,Options>,
             bp::args("M"),"Returns the result of the action of the inverse of M on *this.")

        .add_property("action",&Motion::toActionMatrix,"Returns the action matrix of *this (acting on Motion).")
        .add_property("dualAction",&Motion::toDualActionMatrix,"Returns the dual action matrix of *this (acting on Force).")

        .def("setZero",&MotionPythonVisitor::setZero,
             "Set the linear and angular components of *this to zero.")
        .def("setRandom",&MotionPythonVisitor::setRandom,
             "Set the linear and angular components of *this to random values.")

        .def("cross",(Motion (Motion::*)(const Motion &) const) &Motion::cross,
             bp::args("m"),"Action of *this onto another Motion m. Returns ¨*this x m.")
        .def("cross",(Force (Motion::*)(const Force &) const) &Motion::cross,
             bp::args("f"),"Dual action of *this onto a Force f. Returns *this x* f.")

        .def(bp::self + bp::self)
        .def(bp::self += bp::self)
        .def(bp::self - bp::self)
        .def(bp::self -= bp::self)
        .def(-bp::self)
        .def(bp::self ^ bp::self)
        .def(bp::self ^ Force())

        .def(bp::self == bp::self)
        .def(bp::self != bp::self)

        .def(bp::self * Scalar())
        .def(Scalar() * bp::self)
        .def(bp::self / Scalar())

        .def("isApprox",
             call<Motion>::isApprox,
             isApproxMotion_overload(bp::args("other","prec"),
                                     "Returns true if *this is approximately equal to other, within the precision given by prec."))

        .def("isZero",
             call<Motion>::isZero,
             isZero_overload(bp::args("prec"),
                             "Returns true if *this is approximately equal to the zero Motion, within the precision given by prec."))

        .def("Random",&Motion::Random,"Returns a random Motion.")
        .staticmethod("Random")
        .def("Zero",&Motion::Zero,"Returns a zero Motion.")
        .staticmethod("Zero")

        .def("__array__",&MotionPythonVisitor::getVector)

        .def_pickle(Pickle())
        ;
      }

      static void expose()
      {
        bp::class_<Motion>("Motion",
                           "Motion vectors, in se3 == M^6.\n\n"
                           "Supported operations ...",
                           bp::init<>())
        .def(MotionPythonVisitor<Motion>())
        .def(CopyableVisitor<Motion>())
        .def(PrintableVisitor<Motion>())
        ;
      }

    private:

      struct Pickle : bp::pickle_suite
      {
        static
        boost::python::tuple
        getinitargs(const Motion & m)
        { return bp::make_tuple((Vector3)m.linear(),(Vector3)m.angular()); }
      };

      static Vector3 getLinear(const Motion & self) { return self.linear(); }
      static void setLinear (Motion & self, const Vector3 & v) { self.linear(v); }
      static Vector3 getAngular(const Motion & self) { return self.angular(); }
      static void setAngular(Motion & self, const Vector3 & w) { self.angular(w); }

      static Vector6 getVector(const Motion & self) { return self.toVector(); }
      static void setVector(Motion & self, const Vector6 & v) { self = v; }

      static void setZero(Motion & self) { self.setZero(); }
      static void setRandom(Motion & self) { self.setRandom(); }

    };

  }} // namespace pinocchio::python

#endif // ifndef __pinocchio_python_se3_hpp__

max_stars_repo_name: yDMhaven/pinocchio

max_issues_repo_name: longwoo/pinocchio

max_forks_repo_name: longwoo/pinocchio


text:
/*
 * LYHoldemAction.cpp
 *
 *  Created on: 2013-7-4
 *      Author: caiqingfeng
 */

#include "LYHoldemAction.h"
#include "poker/src/LYCardHelpers.h"
#include <boost/algorithm/string.hpp>
#include <iostream>

void cleanQuote(std::string& s)
{
    if (s.size() < 1) return;
    if (s[0] == '\"') s = s.substr(1, s.size()-1);
    if (s[s.size()-1] == '\"') s = s.substr(0, s.size()-1);
}

LYHoldemAction::LYHoldemAction(const std::string& tid) {
	// TODO Auto-generated constructor stub
    reset();

	table_id = tid;
}

void LYHoldemAction::reset() {
	// TODO Auto-generated constructor stub
	table_id = "";
	bet = 0;
	applicant = LYHouse;
	verb = LYHousePollingDecision;
	desc = "";
	cards.clear();
}

LYHoldemAction::LYHoldemAction(std::vector<std::pair<std::string, std::string> >& kvps)
{
    std::vector<std::pair<std::string, std::string> >::iterator it = kvps.begin();
    for (; it!=kvps.end(); it++) {
        std::pair<std::string, std::string> kvp = *it;
		if (kvp.first == "table_id" || kvp.first == "\"table_id\"") {
			this->table_id = kvp.second;
			cleanQuote(this->table_id);
		} else if (kvp.first == "applicant" || kvp.first == "\"applicant\"") {
			this->applicant = (LYApplicant)std::stoi(
					kvp.second);
		} else if (kvp.first == "verb" || kvp.first == "\"verb\"") {
			this->verb = (LYVerb)std::stoi(
					kvp.second);
		} else if (kvp.first == "bet" || kvp.first == "\"bet\"") {
			this->bet = std::stoi(
					kvp.second);
		} else if (kvp.first == "desc" || kvp.first == "\"desc\"") {
			this->desc = kvp.second;
			cleanQuote(this->desc);
		} else if (kvp.first == "cards" || kvp.first == "\"cards\"") {
//		std::cout << "cards:" << kvp.second << std::endl;
			cleanQuote(kvp.second);
		    LYCardHelpers::stringToCards(kvp.second, this->cards);
		}
    }
}

LYHoldemAction::~LYHoldemAction() {
	// TODO Auto-generated destructor stub
}

LYHoldemAction& LYHoldemAction::operator = (const LYHoldemAction& right)
{
    this->table_id = right.table_id;
    this->applicant = right.applicant;
    this->verb = right.verb;
    this->bet = right.bet;
    this->desc = right.desc;
    this->cards = right.cards;
    return *this;
}

bool LYHoldemAction::operator == (LYHoldemAction& right)
{
    return (this->table_id == right.table_id &&
        this->applicant == right.applicant &&
        this->verb == right.verb &&
        this->bet == right.bet &&
        this->desc == right.desc &&
        this->cards.size() == right.cards.size());
}

std::string LYHoldemAction::toString()
{
    std::string cardsStr;
    LYCardHelpers::cardsToString(cards, cardsStr);
	std::string str = "";
	cleanQuote(this->table_id);
	cleanQuote(this->desc);
	cleanQuote(cardsStr);
	str = "\"table_id\":\"" + table_id + "\"," +
	        "\"applicant\":" + std::to_string(applicant) + "," +
	        "\"verb\":" + std::to_string(verb) + "," +
	        "\"bet\":" + std::to_string(bet) + "," +
	        "\"desc\":\"" + desc + "\"," +
	        "\"cards\":\"" + cardsStr + "\"";
	return str;
}

LYHoldemAction LYHoldemAction::build_from_action_string(std::string& action_str)
{
    std::vector<std::pair<std::string, std::string>> actions_vector;

    std::vector<std::string> actions;
        // 对cards要特殊处理
    int i = action_str.find("cards");
    std::string s = action_str.substr(0, i);
        // boost::is_any_of这里相当于分割规则了
    boost::split(actions, s, boost::is_any_of(","));
    std::vector<std::string>::iterator it = actions.begin();
    for (; it!=actions.end(); it++) {
        std::vector<std::string> v;
        std::string s = *it;
        boost::split(v, s, boost::is_any_of(":"));
        if (v.size() != 2) continue;
        std::pair<std::string, std::string> kvp;
        kvp.first = v[0];
        cleanQuote(kvp.first);
//        std::cout << kvp.first << std::endl;
        kvp.second = v[1];
        cleanQuote(kvp.second);
//        std::cout << kvp.second << std::endl;
        actions_vector.push_back(kvp);
    }

    s = action_str.substr(i, action_str.size() - i);
//        std::cout << s << std::endl;
    std::vector<std::string> v;
    boost::split(v, s, boost::is_any_of(":"));
    if (v.size() == 2) {
        std::pair<std::string, std::string> kvp;
        kvp.first = v[0];
        cleanQuote(kvp.first);
//        std::cout << kvp.first << std::endl;
        kvp.second = v[1];
        cleanQuote(kvp.second);
//        std::cout << kvp.second << std::endl;
        actions_vector.push_back(kvp);
    }

    LYHoldemAction action(actions_vector);
    return action;
}

void LYHoldemAction::issueFlopCards(const std::vector<LYCard> &cds)
{
    verb = LYHouseIssueFlop;
    cards = cds;
    bet = 0;
    applicant = LYHouse;
    desc = "";
}

void LYHoldemAction::issueTurnCard(const LYCard &cd)
{
    cards.clear();
    verb = LYHouseIssueTurn;
    cards.push_back(cd);
    bet = 0;
    applicant = LYHouse;
    desc = "";
}

void LYHoldemAction::issueRiverCard(const LYCard &cd)
{
    cards.clear();
    verb = LYHouseIssueRiver;
    cards.push_back(cd);
    bet = 0;
    applicant = LYHouse;
    desc = "";
}

void LYHoldemAction::pollingDecision(enum LYApplicant st, unsigned int chips)
{
    verb = LYHousePollingDecision;
    applicant = st;
    bet = chips;
    desc = "";
    cards.clear();
}

void LYHoldemAction::fold(enum LYApplicant st, const std::string &reason )
{
    verb = LYFold;
    applicant = st;
    bet = 0;
    desc = reason;
    cards.clear();
}

void LYHoldemAction::check(enum LYApplicant st)
{
    verb = LYCheck;
    applicant = st;
    bet = 0;
    desc = "";
    cards.clear();
}

void LYHoldemAction::allin(enum LYApplicant st, unsigned int chips)
{
    verb = LYAllin;
    applicant = st;
    bet = chips;
    desc = "";
    cards.clear();
}

void LYHoldemAction::call(enum LYApplicant st, unsigned int chips)
{
    verb = LYCall;
    applicant = st;
    bet = chips;
    desc = "";
    cards.clear();
}

void LYHoldemAction::doBet(enum LYApplicant st, unsigned int chips)
{
    verb = LYBet;
    applicant = st;
    bet = chips;
    desc = "";
    cards.clear();
}

void LYHoldemAction::betSmallBlind(enum LYApplicant st, unsigned int chips)
{
    verb = LYBetSmallBlind;
    applicant = st;
    bet = chips;
    desc = "";
    cards.clear();
}

void LYHoldemAction::betBigBlind(enum LYApplicant st, unsigned int chips)
{
    verb = LYBetBigBlind;
    applicant = st;
    bet = chips;
    desc = "";
    cards.clear();
}

void LYHoldemAction::raise(enum LYApplicant st, unsigned int chips)
{
    verb = LYRaise;
    applicant = st;
    bet = chips;
    desc = "";
    cards.clear();
}

void LYHoldemAction::assure(enum LYApplicant st, unsigned int chips, const std::string pot)
{
    verb = LYBuyAssurance;
    applicant = st;
    bet = chips;
    desc = pot;
    cards.clear();
}

void LYHoldemAction::askAssure(enum LYApplicant st, unsigned int chips,
    const std::vector<LYCard>& outs, const std::string pot)
{
    verb = LYAskAssurance;
    applicant = st;
    bet = chips;
    desc = pot;
    cards = outs;
}

void LYHoldemAction::payAssure(enum LYApplicant st, unsigned int chips, const std::string pot)
{
    verb = LYPayAssurance;
    applicant = st;
    bet = chips;
    desc = pot;
}

void LYHoldemAction::summarizeAssure(int chips, int total_income)
{
    verb = LYSummarizeAssurance;
    applicant = LYHouse;
    bet = chips;
    desc = std::to_string(total_income);
}

bool LYHoldemAction::isAssuranceRelevant()
{
    switch (verb)
    {
    case LYSummarizeAssurance:
    case LYBuyAssurance:
    case LYAskAssurance:
    case LYPayAssurance:
        return true;
    default:
        return false;
    }

    return false;
}

/*
 * discarded 20160701
 */
std::vector<std::pair<std::string, std::string> > LYHoldemAction::to_kvps()
{
	std::vector<std::pair<std::string, std::string> > kvps;
	std::pair < std::string, std::string > kvp;

	kvp.first = "table_id";
	kvp.second = this->table_id;
	kvps.push_back(kvp);

	kvp.first = "applicant";
	kvp.second = std::to_string(this->applicant);
	kvps.push_back(kvp);

	kvp.first = "verb";
	kvp.second = std::to_string(this->verb);
	kvps.push_back(kvp);

	kvp.first = "bet";
	kvp.second = std::to_string(this->bet);
	kvps.push_back(kvp);

	kvp.first = "desc";
	kvp.second = this->desc;
	kvps.push_back(kvp);

    std::string cardsStr;
    LYCardHelpers::cardsToString(cards, cardsStr);
	kvp.first = "cards";
	kvp.second = cardsStr;
	kvps.push_back(kvp);

	return kvps;
}

bool LYHoldemAction::isPolling()
{
    return (verb == LYHousePollingDecision || verb == LYAskAssurance);
}

max_stars_repo_name: caiqingfeng/libpoker

max_issues_repo_name: caiqingfeng/libpoker

max_forks_repo_name: caiqingfeng/libpoker


text:
#include <SFML\Graphics.hpp>
#include <Box2D\Box2D.h>
#include <array>
#include <memory>
#include <iostream>
#include <boost/math/special_functions/round.hpp>
#include "Marvin.h"
#include "SceneNode.h"
#include "SpriteNode.h"
#include "TextNode.h"
#include "TilemapNode.h"
#include "SoundNode.h"
#include "ResourceManager.h"
#include "TiledJSONLoader.h"
#include "Box2DTiledLoader.h"
#include "MapData.h"
#include "GameObjectFactory.h"
#include "EntityFactory.h"
#include "CollisionHandler.h"
#include "World.h"
#include "SaveManager.h"
#include "Bee.h"

World::World(State::Context context, const std::string &map) :
        mContext(context),
        mWorldView(mContext.window->getDefaultView()),
        mMapLoader(TiledJSONLoader("Resources/Maps/", "Resources/Textures/Tileset/")),
        mWorldLoader(Box2DTiledLoader()),
        mCollisionHandler(CollisionHandler(*this)),
        mSceneGraph(SceneNode()),
        mPlayerCharacter(nullptr),
        numDeaths(0),
        mGemCollected(false),
        mResetRequested(false),
        mCompletionRequested(false),
        mCompleted(false),
        mMapLoaded(false),
        mObjectsLoaded(false),
        mTexturesLoaded(false),
        mMap(map){}

void World::initialize(){
    mMapLoader.load(mMap);
    mMapLoaded = mMapLoader.isMapLoaded();
    assert(mMapLoader.isMapLoaded());
    mMapData.tileWidth = mMapLoader.getTileSize().x;
    mMapData.tileHeight = mMapLoader.getTileSize().y;
    mMapData.mapWidth = mMapLoader.getMapSize().x;
    mMapData.mapHeight = mMapLoader.getMapSize().y;
    mMapData.tileLayers = mMapLoader.getTileLayers();
    mMapData.objectGroups = mMapLoader.getObjectGroups();

    mWorldLoader.load(mMapLoader.getTileLayers().back().tiles);
    mObjectsLoaded = mWorldLoader.isWorldLoaded();
    assert(mWorldLoader.isWorldLoaded());
    mBox2DWorld = std::unique_ptr<b2World>(mWorldLoader.getWorld());
    mBox2DWorld->SetContactListener(&mCollisionHandler);
    mGameObjectFactory = GameObjectFactory(mMapData, mBox2DWorld.get());
    buildScene();
    mTexturesLoaded = true;

    centerPlayerView();
    mContext.window->setView(mWorldView);
}

void World::reset(){
    mBox2DWorld.release();
    mLevelTimeElapsed = sf::Time::Zero;
    mCompletionTime = 0.0f;
    mPlayerCharacter = nullptr;
    mPlayerBody = nullptr;
    mWorldLoader.load(mMapData.tileLayers.back().tiles);
    assert(mWorldLoader.isWorldLoaded());
    mBox2DWorld = std::unique_ptr<b2World>(mWorldLoader.getWorld());
    mBox2DWorld->SetContactListener(&mCollisionHandler);
    mGameObjectFactory = GameObjectFactory(mMapData, mBox2DWorld.get());
    for (std::size_t i = 0; i < LayerCount; ++i){
        mSceneGraph.detachChild(*mSceneLayers[i]);
    }
    mSceneLayers.empty();
    buildScene();
    centerPlayerView();
    mResetRequested = false;
    mGemCollected = false;
    ++numDeaths;
}

void World::requestReset(){
    mResetRequested = true;
    Command resetSoundCommand;
    resetSoundCommand.category = Category::SoundEffect;
    resetSoundCommand.action = [](SceneNode &node, sf::Time deltaTime){
        SoundNode &sound = static_cast<SoundNode&>(node);
        sound.play(SoundEffectID::PlayerDie);
    };
    mCommandQueue.push(resetSoundCommand);
}

CommandQueue& World::getCommandQueue(){
    return mCommandQueue;
}

void World::update(sf::Time deltaTime){

    if (!mCompletionRequested){
        mLevelTimeElapsed += deltaTime;

        //It's important we advance our physics engine before updating
        mBox2DWorld->Step(deltaTime.asSeconds(), 6, 2);

        updateSeekers();
        while (!mCommandQueue.empty()){
            mSceneGraph.onCommand(mCommandQueue.front(), deltaTime);
            mCommandQueue.pop();
        }

        mSceneGraph.removeChildren();
        mSceneGraph.update(deltaTime);
        centerPlayerView();

        //Reposition and update our time
        std::ostringstream timeStream;
        timeStream << boost::math::round(
            mLevelTimeElapsed.asSeconds() * 100.f) / 100.f;
        mTimeText->setText(timeStream.str());
        mTimeText->setPosition(
            mWorldView.getCenter().x + mWorldView.getSize().x / 2.f - 125.f,
            mWorldView.getCenter().y - mWorldView.getSize().y / 2.f + 25.f);

        if (mResetRequested)
            reset();
    }

    else if (!mPlayerCharacter->isFaded()){
        mPlayerCharacter->update(deltaTime);
    }

    else{
        mCompleted = true;
    }

    mContext.soundPlayer->removeStoppedSounds();
}

void World::updateSeekers(){
    Command seekCommand;
    seekCommand.category = Category::Seeker;
    sf::Vector2f playerPos = mPlayerCharacter->getRenderPosition();
    seekCommand.action = [playerPos](SceneNode &node, sf::Time deltaTime){
        Bee &bee = static_cast<Bee&>(node);
        bee.seek(playerPos);
    };
    mCommandQueue.push(seekCommand);
}

void World::requestCompletion(){
    mCompletionRequested = true;
    std::ostringstream timeStream;
    mCompletionTime = boost::math::round(mLevelTimeElapsed.asSeconds() * 100.f) / 100.f;
    mPlayerCharacter->fade();
    Command fadeSoundCommand;
    fadeSoundCommand.category = Category::SoundEffect;
    fadeSoundCommand.action = [](SceneNode &node, sf::Time deltaTime){
        SoundNode &sound = static_cast<SoundNode&>(node);
        sound.play(SoundEffectID::PlayerFade);
    };
    mCommandQueue.push(fadeSoundCommand);
}

bool World::isComplete(){
    return mCompleted;
}

float World::getAttemptTime(){
    return mCompletionTime;
}

int World::getNumDeaths(){
    return numDeaths;
}

bool World::isGemCollected(){
    return mGemCollected;
}

void World::collectGem(){
    Command gemSoundCommand;
    gemSoundCommand.category = Category::SoundEffect;
    gemSoundCommand.action = [](SceneNode &node, sf::Time deltaTime){
        SoundNode &sound = static_cast<SoundNode&>(node);
        sound.play(SoundEffectID::GemPickup);
    };
    mCommandQueue.push(gemSoundCommand);
    mGemCollected = true;
}

void World::centerPlayerView(){

    //Make sure our view is inside map bounds
    float viewWidth =  mWorldView.getSize().x;
    float viewHeight = mWorldView.getSize().y;
    sf::Vector2f viewCenter = mWorldView.getCenter();
    sf::Vector2f playerPos = mPlayerCharacter->getRenderPosition();
    float mMapWidthPixels = mMapData.mapWidth * PX_PER_M;
    float mMapHeightPixels = mMapData.mapHeight * PX_PER_M;

    float xOffset = 0;
    float yOffset = 0;

    if (playerPos.y - viewHeight/2 < 0)
        yOffset = fabs(playerPos.y - viewHeight/2);
    else if (playerPos.y + viewHeight/2 > mMapHeightPixels)
        yOffset = -1 * (viewHeight/2 - (mMapHeightPixels - playerPos.y));
    if (playerPos.x - viewWidth/2 < 0)
        xOffset = fabs(playerPos.x - viewWidth/2);
    else if (playerPos.x + viewWidth/2 > mMapWidthPixels)
        xOffset = -1 * (viewWidth/2 - (mMapWidthPixels - playerPos.x));

    sf::Vector2f newCenter(playerPos.x + xOffset, playerPos.y + yOffset);
    mWorldView.setCenter(newCenter);
}

void World::draw(){
    mContext.window->setView(mWorldView);
    mContext.window->draw(mSceneGraph);
}

void World::buildScene(){

    //Setup our layers
    for (std::size_t i = 0; i < LayerCount; ++i){
        SceneNode::Ptr layer(new SceneNode());
        mSceneLayers[i] = layer.get();
        mSceneGraph.attachChild(std::move(layer));
    }

    //Background layer
    sf::Texture &texture = mContext.textureManager->get(TextureID::Background);
    texture.setRepeated(true);
    std::unique_ptr<SpriteNode> backgroundSprite(new SpriteNode(texture, sf::IntRect(0, 0, mMapData.mapWidth * 70, mMapData.mapHeight * 70)));
    mSceneLayers[Background]->attachChild(std::move(backgroundSprite));

    //Tilemap layer
    std::unique_ptr<TilemapNode> tileMap(
        new TilemapNode(mMapData, mWorldLoader.getContours()));
    mSceneLayers[Tilemap]->attachChild(std::move(tileMap));

    //Object layer (players, enemies, etc)
    EntityFactory entityFactory = EntityFactory(*mContext.textureManager, mMapData, mBox2DWorld.get());
    for(auto &objectGroup : mMapData.objectGroups){
        if (objectGroup.name == "Objects"){
            for (auto &object : objectGroup.objects){
              if (object.type == "Gem" && SaveManager::getInstance().getLevelData(mMap).collectedGem)
                  continue;
                mSceneLayers[Object]->attachChild(
                    GameObject::Ptr(mGameObjectFactory.createGameObject(object)));
            }
        }
        else if (objectGroup.name == "Spawns"){
            for (auto &object : objectGroup.objects){
                if (object.type == "Player")
                    spawnPlayer(object.position);
                else{
                    mSceneLayers[Object]->attachChild(
                        Entity::Ptr(entityFactory.createEntity(object)));
                }
            }
        }
    }
    mSceneLayers[Object]->attachChild(std::move(std::unique_ptr<Marvin>(mPlayerCharacter)));

    //HUD Layer
    sf::Font &timeFont = mContext.fontManager->get(FontID::Thin);
    std::unique_ptr<TextNode> timeText(new TextNode(timeFont));
    mTimeText = timeText.get();
    mTimeText->setColor(sf::Color::Black);
    mSceneLayers[HUD]->attachChild(std::move(timeText));

    //Sound Effects
    std::unique_ptr<SoundNode> soundEffects(new SoundNode(*mContext.soundPlayer));
    mSceneLayers[Sounds]->attachChild(std::move(soundEffects));
}

void World::spawnPlayer(sf::Vector2f position){

    sf::Sprite playerSprite(mContext.textureManager->get(TextureID::PlayerStanding));
    sf::FloatRect bounds = playerSprite.getGlobalBounds();
    sf::Vector2f renderPos = position + sf::Vector2f(0.f, bounds.height/2);
    sf::Vector2f centerPlayerPos = sf::Vector2f(
        renderPos.x,
        mMapData.mapHeight*PX_PER_M - renderPos.y);

    //Create our box2D body
    b2BodyDef playerDef;
    playerDef.fixedRotation = true;
    playerDef.type = b2_dynamicBody;
    playerDef.position.Set(centerPlayerPos.x / PX_PER_M, centerPlayerPos.y / PX_PER_M);
    mPlayerBody = mBox2DWorld->CreateBody(&playerDef);

    //Bounding box with no friction to prevent sticking to static body walls
    b2PolygonShape boundingBox;
    boundingBox.SetAsBox(bounds.width / PX_PER_M / 2 - 0.1f, bounds.height / PX_PER_M / 2);
    b2FixtureDef playerFixture;
    playerFixture.friction = 0.f;
    playerFixture.shape = &boundingBox;
    mPlayerBody->CreateFixture(&playerFixture);

    //Special foot sensor to manage jumping/movement
    b2PolygonShape footShape;
    b2Vec2 footVertices[4];
    footVertices[0] = b2Vec2(-bounds.width / PX_PER_M / 2 + 0.15f, -bounds.height / PX_PER_M / 2 - 0.04f);
    footVertices[1] = b2Vec2(-bounds.width / PX_PER_M / 2 + 0.15f, -bounds.height / PX_PER_M / 2 + 0.05f);
    footVertices[2] = b2Vec2(bounds.width / PX_PER_M / 2 - 0.15f, -bounds.height / PX_PER_M / 2 + 0.05f);
    footVertices[3] = b2Vec2(bounds.width / PX_PER_M / 2 - 0.15f, -bounds.height / PX_PER_M / 2 - 0.04f);
    footShape.Set(footVertices,4);
    b2FixtureDef footFixture;
    footFixture.isSensor = true;
    footFixture.friction = 0.25f;
    footFixture.shape = &footShape;
    mPlayerBody->CreateFixture(&footFixture);

    mPlayerCharacter = new Marvin(*mContext.textureManager, mPlayerBody);
    mPlayerCharacter->setRenderPosition(renderPos);
    mPlayerBody->SetUserData(mPlayerCharacter);
}

void World::renderStaticBodyFixtures(){

    for (b2Body *b = mBox2DWorld->GetBodyList(); b; b = b->GetNext()){

        if (static_cast<SceneNode*>(b->GetUserData())->getCategory() & Category::Type::Walkable){
            for (b2Fixture *fixture = b->GetFixtureList(); fixture; fixture = fixture->GetNext()){

                //We know it's a chain shape
                b2ChainShape *chain = static_cast<b2ChainShape*>(fixture->GetShape());
                sf::VertexArray lines(sf::PrimitiveType::Lines);

                for (int i = 0; i < chain->GetChildCount(); ++i){

                    b2EdgeShape edge;
                    chain->GetChildEdge(&edge, i);
                    b2Vec2 v1 = edge.m_vertex1;
                    b2Vec2 v2 = edge.m_vertex2;
                    lines.append(sf::Vertex(sf::Vector2f(v1.x * PX_PER_M, (mMapData.mapHeight * 70) - v1.y * PX_PER_M), sf::Color::Blue));
                    lines.append(sf::Vertex(sf::Vector2f(v2.x * PX_PER_M, (mMapData.mapHeight * 70) - v2.y * PX_PER_M), sf::Color::Blue));
                }
                mContext.window->draw(lines);
            }
        }
    }
}

void World::onResolutionChange(){

    mWorldView.setSize(sf::Vector2f(
        mContext.window->getSize().x,
        mContext.window->getSize().y));
    centerPlayerView();
    mTimeText->setPosition(
        mWorldView.getCenter().x + mWorldView.getSize().x / 2.f - 125.f,
        mWorldView.getCenter().y - mWorldView.getSize().y / 2.f + 25.f);
}

bool World::mapLoaded(){ return mMapLoaded; }

bool World::objectsLoaded(){ return mObjectsLoaded; }

bool World::texturesLoaded(){ return mTexturesLoaded; }

max_stars_repo_name: TylerSandman/marvin

max_issues_repo_name: TylerSandman/marvin

max_forks_repo_name: TylerSandman/marvin


text:
// Copyright 2020, Madhur Chauhan

// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_MATH_SPECIAL_FIBO_HPP
#define BOOST_MATH_SPECIAL_FIBO_HPP

#include <boost/math/constants/constants.hpp>
#include <boost/math/policies/error_handling.hpp>
#include <cmath>
#include <limits>

#ifdef _MSC_VER
#pragma once
#endif

namespace boost {
namespace math {

namespace detail {
   constexpr double fib_bits_phi = 0.69424191363061730173879026;
   constexpr double fib_bits_deno = 1.1609640474436811739351597;
} // namespace detail

template <typename T>
inline BOOST_CXX14_CONSTEXPR T unchecked_fibonacci(unsigned long long n) noexcept(std::is_fundamental<T>::value) {
    // This function is called by the rest and computes the actual nth fibonacci number
    // First few fibonacci numbers: 0 (0th), 1 (1st), 1 (2nd), 2 (3rd), ...
    if (n <= 2) return n == 0 ? 0 : 1;
    /*
     * This is based on the following identities by Dijkstra:
     *   F(2*n)   = F(n)^2 + F(n+1)^2
     *   F(2*n+1) = (2 * F(n) + F(n+1)) * F(n+1)
     * The implementation is iterative and is unrolled version of trivial recursive implementation.
     */
    unsigned long long mask = 1;
    for (int ct = 1; ct != std::numeric_limits<unsigned long long>::digits && (mask << 1) <= n; ++ct, mask <<= 1)
        ;
    T a{1}, b{1};
    for (mask >>= 1; mask; mask >>= 1) {
        T t1 = a * a;
        a = 2 * a * b - t1, b = b * b + t1;
        if (mask & n)
            t1 = b, b = b + a, a = t1; // equivalent to: swap(a,b), b += a;
    }
    return a;
}

template <typename T, class Policy>
T inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n, const Policy &pol) {
    // check for overflow using approximation to binet's formula: F_n ~ phi^n / sqrt(5)
    if (n > 20 && n * detail::fib_bits_phi - detail::fib_bits_deno > std::numeric_limits<T>::digits)
        return policies::raise_overflow_error<T>("boost::math::fibonacci<%1%>(unsigned long long)", "Possible overflow detected.", pol);
    return unchecked_fibonacci<T>(n);
}

template <typename T>
T inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n) {
    return fibonacci<T>(n, policies::policy<>());
}

// generator for next fibonacci number (see examples/reciprocal_fibonacci_constant.hpp)
template <typename T>
class fibonacci_generator {
  public:
    // return next fibonacci number
    T operator()() noexcept(std::is_fundamental<T>::value) {
        T ret = a;
        a = b, b = b + ret; // could've simply: swap(a, b), b += a;
        return ret;
    }

    // after set(nth), subsequent calls to the generator returns consecutive
    // fibonacci numbers starting with the nth fibonacci number
    void set(unsigned long long nth) noexcept(std::is_fundamental<T>::value) {
        n = nth;
        a = unchecked_fibonacci<T>(n);
        b = unchecked_fibonacci<T>(n + 1);
    }

  private:
    unsigned long long n = 0;
    T a = 0, b = 1;
};

} // namespace math
} // namespace boost

#endif

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math

max_forks_repo_name: oleg-alexandrov/math


text:
//
//  Copyright (c) 2005 João Abecasis
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//

#include <boost/spirit/core.hpp>
#include <boost/spirit/attribute.hpp>
#include <boost/spirit/utility/grammar_def.hpp>

struct my_grammar1
    : boost::spirit::grammar<my_grammar1>
{
    template <typename Scanner>
    struct definition
        : boost::spirit::grammar_def<
            boost::spirit::rule<Scanner>,
            boost::spirit::same
        >
    {
        definition(my_grammar1 const &)
        {
            BOOST_SPIRIT_DEBUG_NODE(start_rule1);
            BOOST_SPIRIT_DEBUG_NODE(start_rule2);

            start_rule1 = boost::spirit::str_p("int");
            start_rule2 = boost::spirit::int_p;

            this->start_parsers(start_rule1, start_rule2);
        }

        boost::spirit::rule<Scanner>
            start_rule1,
            start_rule2;
    };
};

struct my_closure : boost::spirit::closure<my_closure, int>
{
    member1 value;
};

struct my_grammar2
    : boost::spirit::grammar<my_grammar2, my_closure::context_t>
{
    template <typename Scanner>
    struct definition
        : boost::spirit::grammar_def<
            boost::spirit::rule<Scanner>,
            boost::spirit::same
        >
    {
        definition(my_grammar2 const &)
        {
            BOOST_SPIRIT_DEBUG_NODE(start_rule1);
            BOOST_SPIRIT_DEBUG_NODE(start_rule2);

            start_rule1 = boost::spirit::str_p("int");
            start_rule2 = boost::spirit::int_p;

            this->start_parsers(start_rule1, start_rule2);
        }

        boost::spirit::rule<Scanner>
            start_rule1,
            start_rule2;
    };
};

int main()
{
    my_grammar1 g1;
    my_grammar2 g2;

    BOOST_SPIRIT_DEBUG_NODE(g1);
    BOOST_SPIRIT_DEBUG_NODE(g2);

    parse(
        "int 5",
        g1.use_parser<0>() >> g2.use_parser<1>(),
        boost::spirit::space_p
    );
}

max_stars_repo_name: spxuw/RFIM

max_issues_repo_name: spxuw/RFIM

max_forks_repo_name: spxuw/RFIM