text:
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>

#include <boost/assert.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/ref.hpp>
#include <boost/optional.hpp>
#include <boost/system/system_error.hpp>
#include <boost/thread.hpp>

#include <boost/fiber.hpp>

typedef boost::fibers::spin::unbounded_channel< std::string >	fifo_t;

inline
void ping(
		fifo_t & recv_buf,
		fifo_t & send_buf)
{
	std::stringstream tss;
	tss << boost::this_thread::get_id();
	std::stringstream fss;
	fss << boost::this_fiber::get_id();

	fprintf( stderr, "start ping fiber %s in thread %s\n", fss.str().c_str(), tss.str().c_str() );

	boost::optional< std::string > value;

	send_buf.put("ping");
	BOOST_ASSERT( recv_buf.take( value) );
	fprintf( stderr, "ping fiber %s in thread %s recevied %s\n", fss.str().c_str(), tss.str().c_str(), value->c_str());
	value.reset();

	send_buf.put("ping");
	BOOST_ASSERT( recv_buf.take( value) );
	fprintf( stderr, "ping fiber %s in thread %s recevied %s\n", fss.str().c_str(), tss.str().c_str(), value->c_str());
	value.reset();

	send_buf.put("ping");
	BOOST_ASSERT( recv_buf.take( value) );
	fprintf( stderr, "ping fiber %s in thread %s recevied %s\n", fss.str().c_str(), tss.str().c_str(), value->c_str());
	value.reset();

	send_buf.deactivate();

	fprintf( stderr, "end ping fiber %s in thread %s\n", fss.str().c_str(), tss.str().c_str() );
}

inline
void pong(
		fifo_t & recv_buf,
		fifo_t & send_buf)
{
	std::stringstream tss;
	tss << boost::this_thread::get_id();
	std::stringstream fss;
	fss << boost::this_fiber::get_id();

	fprintf( stderr, "start pong fiber %s in thread %s\n", fss.str().c_str(), tss.str().c_str() );

	boost::optional< std::string > value;

	BOOST_ASSERT( recv_buf.take( value) );
	fprintf( stderr, "pong fiber %s in thread %s recevied %s\n", fss.str().c_str(), tss.str().c_str(), value->c_str());
	value.reset();
	send_buf.put("pong");

	BOOST_ASSERT( recv_buf.take( value) );
	fprintf( stderr, "pong fiber %s in thread %s recevied %s\n", fss.str().c_str(), tss.str().c_str(), value->c_str());
	value.reset();
	send_buf.put("pong");

	BOOST_ASSERT( recv_buf.take( value) );
	fprintf( stderr, "pong fiber %s in thread %s recevied %s\n", fss.str().c_str(), tss.str().c_str(), value->c_str());
	value.reset();
	send_buf.put("pong");

	send_buf.deactivate();

	fprintf( stderr, "end pong fiber %s in thread %s\n", fss.str().c_str(), tss.str().c_str() );
}

void f(
		fifo_t & recv_buf,
		fifo_t & send_buf)
{
	std::stringstream tss;
	tss << boost::this_thread::get_id();

	fprintf( stderr, "start thread %s\n", tss.str().c_str() );

	boost::fibers::scheduler<> sched;

	sched.make_fiber( & ping, recv_buf, send_buf, boost::fiber::default_stacksize);

	for (;;)
	{
		while ( sched.run() );
		if ( sched.empty() ) break;
	}

	fprintf( stderr, "end thread %s\n", tss.str().c_str() );
}

void g(
		fifo_t & recv_buf,
		fifo_t & send_buf)
{
	std::stringstream tss;
	tss << boost::this_thread::get_id();

	fprintf( stderr, "start thread %s\n", tss.str().c_str() );

	boost::fibers::scheduler<> sched;

	sched.make_fiber( & pong, recv_buf, send_buf, boost::fiber::default_stacksize);

	for (;;)
	{
		while ( sched.run() );
		if ( sched.empty() ) break;
	}

	fprintf( stderr, "end thread %s\n", tss.str().c_str() );
}

int main()
{
	try
	{
		fifo_t buf1;
		fifo_t buf2;

		std::cout << "start" << std::endl;

		boost::thread th1( boost::bind( & f, buf1, buf2) );
		boost::thread th2( boost::bind( & g, buf2, buf1) );

		th1.join();
		th2.join();

		std::cout << "finish" << std::endl;

		return EXIT_SUCCESS;
	}
	catch ( boost::system::system_error const& e)
	{ std::cerr << "system_error: " << e.code().value() << std::endl; }
	catch ( boost::fibers::scheduler_error const& e)
	{ std::cerr << "scheduler_error: " << e.what() << std::endl; }
	catch ( std::exception const& e)
	{ std::cerr << "exception: " << e.what() << std::endl; }
	catch (...)
	{ std::cerr << "unhandled exception" << std::endl; }
	return EXIT_FAILURE;
}

ext: cpp

max_stars_repo_name: ghisguth/tasks

max_issues_repo_name: ghisguth/tasks

max_forks_repo_name: ghisguth/tasks


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

#ifdef HAVE_CONFIG_H
#	include "config.h"
#endif

#define _USE_MATH_DEFINES

#include <iostream>

#include <boost/math/special_functions/zeta.hpp>

#include "sample.h"
#include "sample_k2p.h"
#include "ccvector.h"
#include "series.h"
#include "invert_matrix.h"
#include "table.h"
#include "emdel.h"

using namespace std;

void sample_k2p_zeta::preallocate(size_t maxa, size_t maxd)
{
	p.resize(maxa+1,maxd+1,0.0);
}

void sample_k2p_zeta::presample_step(const params_type &params, const sequence &seq_a, const sequence &seq_d)
{
	size_t sz_max = std::max(sz_height, sz_width);
	size_t sz_anc = seq_a.size();
	size_t sz_dec = seq_d.size();
	sa = seq_a;
	sd = seq_d;

	const model_type &model = get_model();

	p(0,0) = prob_scale;

	for(size_t d = 1; d <= sz_dec; ++d) {
		p(0,d) = 0.0;
		for(size_t k = d; k > 0; --k)
			p(0,d) += p(0,d-k)*model.p_indel_size[k];
	}

	for(size_t a = 1; a <= sz_anc; ++a) {
		p(a,0) = 0.0;
		for(size_t k = a; k > 0; --k)
			p(a,0) += p(a-k,0)*model.p_indel_size[k];
	}

	for(size_t a=1;a<=sz_anc;++a) {
		for(size_t d=1;d<= sz_dec;++d) {
			double pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];

			for(size_t k = d; k > 0; --k)
				pt += p(a,d-k)*model.p_indel_size[k];
			for(size_t k = a; k > 0; --k)
				pt += p(a-k,d)*model.p_indel_size[k];
			p(a,d) = pt;
		}
	}
}

void sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)
{
	size_t a = sa.size();
	size_t d = sd.size();
	seq_a.clear();
	seq_d.clear();

	const model_type &model = get_model();

	while(a != 0 || d != 0) {
		double u = p(a,d)*myrand.uniform01();
		double t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;
		if(u < t) {
			// match
			a = a-1;
			d = d-1;
			seq_a.append(1, ccNuc[sa[a]]);
			seq_d.append(1, ccNuc[sd[d]]);
		} else {
			for(size_t k = 1; k <= a || k <= d; ++k) {
				if(k <= a) {
					t += p(a-k,d)*model.p_indel_size[k];
					if(u < t) {
						// gap in d
						seq_d.append(k, '-');
						while(k--) seq_a.append(1, ccNuc[sa[--a]]);
						break;
					}
				}
				if(k <= d)
				{
					t += p(a,d-k)*model.p_indel_size[k];
					if(u < t) {
						// gap in a
						seq_a.append(k, '-');
						while(k--) seq_d.append(1, ccNuc[sd[--d]]);
						break;
					}
				}
			}
		}
		//seq_a.append(1,',');
		//seq_d.append(1,',');
	}
	reverse(seq_a.begin(), seq_a.end());
	reverse(seq_d.begin(), seq_d.end());
}

void sample_k2p_geo::preallocate(size_t maxa, size_t maxd)
{
	p.resize(maxa+1,maxd+1,0.0);
}

void sample_k2p_geo::presample_step(const params_type &params, const sequence &seq_a, const sequence &seq_d)
{
	size_t sz_max = std::max(sz_height, sz_width);
	size_t sz_anc = seq_a.size();
	size_t sz_dec = seq_d.size();
	sa = seq_a;
	sd = seq_d;

	const model_type &model = get_model();

	double row_cache = 0.0;
	vector<double> col_cache(sz_dec+1, 0.0);

	p(0,0) = prob_scale;
	for(size_t d = 1; d <= sz_dec; ++d) {
		row_cache *= model.p_extend;
		row_cache += p(0,d-1)*model.p_open;
		p(0,d) = row_cache;
	}

	row_cache = 0.0;
	for(size_t a = 1; a <= sz_anc; ++a) {
		row_cache *= model.p_extend;
		row_cache += p(a-1,0)*model.p_open;
		p(a,0) = row_cache;
	}

	for(size_t a=1;a<=sz_anc;++a) {
		row_cache = 0.0;
		for(size_t d=1;d<= sz_dec;++d) {
			double pt = p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]];
			row_cache *= model.p_extend;
			row_cache += p(a,d-1)*model.p_open;
			pt += row_cache;
			col_cache[d] *= model.p_extend;
			col_cache[d] += p(a-1,d)*model.p_open;
			pt += col_cache[d];
			p(a,d) = pt;
		}
	}
}

void sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)
{
	size_t a = sa.size();
	size_t d = sd.size();
	seq_a.clear();
	seq_d.clear();

	const model_type &model = get_model();

	while(a != 0 || d != 0) {
		double u = p(a,d)*myrand.uniform01();
		double t = (a > 0 && d > 0) ? p(a-1,d-1)*model.p_substitution[sa[a-1]][sd[d-1]] : 0.0;
		if(u < t) {
			// match
			a = a-1;
			d = d-1;
			seq_a.append(1, ccNuc[sa[a]]);
			seq_d.append(1, ccNuc[sd[d]]);
		} else {
			for(size_t k = 1; k <= a || k <= d; ++k) {
				if(k <= a) {
					t += p(a-k,d)*model.p_indel_size[k];
					if(u < t) {
						// gap in d
						seq_d.append(k, '-');
						while(k--) seq_a.append(1, ccNuc[sa[--a]]);
						break;
					}
				}
				if(k <= d)
				{
					t += p(a,d-k)*model.p_indel_size[k];
					if(u < t) {
						// gap in a
						seq_a.append(k, '-');
						while(k--) seq_d.append(1, ccNuc[sd[--d]]);
						break;
					}
				}
			}
		}
		//seq_a.append(1,',');
		//seq_d.append(1,',');
	}
	reverse(seq_a.begin(), seq_a.end());
	reverse(seq_d.begin(), seq_d.end());
}

// Draw from Zipf distribution, with parameter a > 1.0
// Devroye Luc (1986) Non-uniform random variate generation.
//     Springer-Verlag: Berlin. p551
inline unsigned int rand_zipf(double a)
{
	double b = pow(2.0, a-1.0);
	double x,t;
	do {
	 x = floor(pow(myrand.uniform01(), -1.0/(a-1.0)));
	 t = pow(1.0+1.0/x, a-1.0);
	} while( myrand.uniform01()*x*(t-1.0)*b >= t*(b-1.0));
	return (unsigned int)x;
}

const char g_nuc[] = "ACGT";
const char g_nuc2[] = "ACGT" "GTAC" "TGCA" "CATG";

void gen_sample_k2p_zeta::sample_once(std::string &seq_a, std::string &seq_d)
{
	seq_a.clear();
	seq_d.clear();

	const model_type &model = get_model();
	const double z = get_params()[model_k2p_zeta::pZ];
	while(1) {
		double p = myrand.uniform01();
		if(p < model.p_2h) {
			// M
			unsigned int x = myrand.uniform(4);
			seq_a.append(1, g_nuc[x]);
			p = myrand.uniform01();
			if(p < model.p_match) {
				seq_d.append(1, g_nuc2[x]);
			} else if(p < model.p_match+model.p_ts) {
				seq_d.append(1, g_nuc2[x+4]);
			} else if(p < 1.0 - 0.5*model.p_ts) {
				seq_d.append(1, g_nuc2[x+8]);
			} else {
				seq_d.append(1, g_nuc2[x+12]);
			}
		} else if(p <  model.p_2h+model.p_2g) {
			// U
			unsigned int x;
			do {
				x = rand_zipf(z);
			} while(x > nmax);
			seq_d.append(x, '-');
			while(x--) {
				seq_a.append(1, g_nuc[myrand.uniform(4)]);
			}
		} else if(p <  1.0-model.p_end) {
			// V
			unsigned int x;
			do {
				x = rand_zipf(z);
			} while(x > nmax);
			seq_a.append(x, '-');
			while(x--) {
				seq_d.append(1, g_nuc[myrand.uniform(4)]);
			}
		} else {
			// E
			break;
		}
	}
}

void gen_sample_k2p_geo::sample_once(std::string &seq_a, std::string &seq_d)
{
	seq_a.clear();
	seq_d.clear();

	const model_type &model = get_model();
	const double q = 1.0/get_params()[model_k2p_geo::pQ];
	while(1) {
		double p = myrand.uniform01();
		if(p < model.p_2h) {
			// M
			unsigned int x = myrand.uniform(4);
			seq_a.append(1, g_nuc[x]);
			p = myrand.uniform01();
			if(p < model.p_match) {
				seq_d.append(1, g_nuc2[x]);
			} else if(p < model.p_match+model.p_ts) {
				seq_d.append(1, g_nuc2[x+4]);
			} else if(p < 1.0 - 0.5*model.p_ts) {
				seq_d.append(1, g_nuc2[x+8]);
			} else {
				seq_d.append(1, g_nuc2[x+12]);
			}
		} else if(p <  model.p_2h+model.p_2g) {
			// U
			unsigned int x = myrand.geometric(q);
			seq_d.append(x, '-');
			while(x--) {
				seq_a.append(1, g_nuc[myrand.uniform(4)]);
			}
		} else if(p <  1.0-model.p_end) {
			// V
			unsigned int x = myrand.geometric(q);
			seq_a.append(x, '-');
			while(x--) {
				seq_d.append(1, g_nuc[myrand.uniform(4)]);
			}
		} else {
			// E
			break;
		}
	}
}

max_stars_repo_name: reedacartwright/emdel

max_issues_repo_name: reedacartwright/emdel

max_forks_repo_name: reedacartwright/emdel


text:
/*
 * Copyright 2020 Ke Sun
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <string>
#include <chrono>
#include <unordered_set>
#include <boost/timer/timer.hpp>
#include <gperftools/profiler.h>

#include <ros/ros.h>
#include <ros/console.h>

#include <node/common/convert_to_visualization_msgs.h>
#include <node/planner/ego_idm_lattice_planning_node.h>

using namespace router;
using namespace planner;
using namespace planner::idm_lattice_planner;

namespace node {

bool EgoIDMLatticePlanningNode::initialize() {

  // Create the publishers.
  path_pub_ = nh_.advertise<visualization_msgs::Marker>(
      "ego_path", 1, true);
  conformal_lattice_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(
      "conformal_lattice", 1, true);
  waypoint_lattice_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(
      "waypoint_lattice", 1, true);

  bool all_param_exist = true;

  std::string host = "localhost";
  int port = 2000;
  all_param_exist &= nh_.param<std::string>("host", host, "localhost");
  all_param_exist &= nh_.param<int>("port", port, 2000);

  // Get the world.
  ROS_INFO_NAMED("ego_planner", "connect to the server.");
  client_ = boost::make_shared<CarlaClient>(host, port);
  client_->SetTimeout(std::chrono::seconds(10));
  world_ = boost::make_shared<CarlaWorld>(client_->GetWorld());
  ros::Duration(1.0).sleep();

  // Get the world and map.
  world_ = boost::make_shared<CarlaWorld>(client_->GetWorld());
  map_ = world_->GetMap();
  fast_map_ = boost::make_shared<utils::FastWaypointMap>(map_);

  // Initialize the path and speed planner.
  boost::shared_ptr<router::LoopRouter> router = boost::make_shared<router::LoopRouter>();
  path_planner_ = boost::make_shared<planner::IDMLatticePlanner>(0.1, 150.0, router, map_, fast_map_);
  speed_planner_ = boost::make_shared<planner::VehicleSpeedPlanner>();

  // Start the action server.
  ROS_INFO_NAMED("ego_planner", "start action server.");
  server_.start();

  ROS_INFO_NAMED("ego_planner", "initialization finishes.");
  return all_param_exist;
}

void EgoIDMLatticePlanningNode::executeCallback(
    const conformal_lattice_planner::EgoPlanGoalConstPtr& goal) {

  ROS_INFO_NAMED("ego_planner", "executeCallback()");

  // Update the carla world and map.
  world_ = boost::make_shared<CarlaWorld>(client_->GetWorld());
  //map_ = world_->GetMap();

  // Create the current snapshot.
  boost::shared_ptr<Snapshot> snapshot = createSnapshot(goal->snapshot);

  // Plan path.
  ros::Time start_time = ros::Time::now();
  const DiscretePath ego_path = path_planner_->planPath(snapshot->ego().id(), *snapshot);
  ros::Duration path_planning_time = ros::Time::now() - start_time;

  // Publish the station graph.
  //conformal_lattice_pub_.publish(createConformalLatticeMsg(
  //      path_planner_->nodes(), path_planner_->edges()));
  path_pub_.publish(createEgoPathMsg(ego_path));
  //waypoint_lattice_pub_.publish(createWaypointLatticeMsg(path_planner_->waypointLattice()));

  // Plan speed.
  const double ego_accel = speed_planner_->planSpeed(snapshot->ego().id(), *snapshot);

  // Update the ego vehicle in the simulator.
  double dt = 0.05;
  nh_.param<double>("fixed_delta_seconds", dt, 0.05);

  const double movement = snapshot->ego().speed()*dt + 0.5*ego_accel*dt*dt;
  const std::pair<CarlaTransform, double> updated_transform_curvature = ego_path.transformAt(movement);
  const CarlaTransform updated_transform = updated_transform_curvature.first;
  const double updated_curvature = updated_transform_curvature.second;
  const double updated_speed = snapshot->ego().speed() + ego_accel*dt;

  ROS_INFO_NAMED("ego_planner", "ego %lu", snapshot->ego().id());
  ROS_INFO_NAMED("ego_planner", "movement:%f", movement);
  ROS_INFO_NAMED("ego_planner", "acceleration:%f", ego_accel);
  ROS_INFO_NAMED("ego_planner", "speed:%f", updated_speed);
  ROS_INFO_NAMED("ego_planner", "transform: x:%f y:%f z:%f r:%f p:%f y:%f",
      updated_transform.location.x,
      updated_transform.location.y,
      updated_transform.location.z,
      updated_transform.rotation.roll,
      updated_transform.rotation.pitch,
      updated_transform.rotation.yaw);

  boost::shared_ptr<CarlaVehicle> ego_vehicle = carlaVehicle(snapshot->ego().id());
  ego_vehicle->SetTransform(updated_transform);
  //ego_vehicle->SetVelocity(updated_transform.GetForwardVector()*updated_speed);

  // Inform the client the result of plan.
  planner::Vehicle updated_ego(
      snapshot->ego().id(),
      snapshot->ego().boundingBox(),
      updated_transform,
      updated_speed,
      snapshot->ego().policySpeed(),
      ego_accel,
      updated_curvature);

  conformal_lattice_planner::EgoPlanResult result;
  result.header.stamp = ros::Time::now();
  result.success = true;
  result.path_type = ego_path.laneChangeType();
  result.planning_time = path_planning_time.toSec();
  populateVehicleMsg(updated_ego, result.ego);
  server_.setSucceeded(result);

  return;
}
} // End namespace node.

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

  if(ros::console::set_logger_level(
        ROSCONSOLE_DEFAULT_NAME,
        ros::console::levels::Info)) {
    ros::console::notifyLoggerLevelsChanged();
  }

  node::EgoIDMLatticePlanningNodePtr planner =
    boost::make_shared<node::EgoIDMLatticePlanningNode>(nh);
  if (!planner->initialize()) {
    ROS_ERROR("Cannot initialize the ego IDM lattice planner.");
  }

  //ProfilerStart("conformal_lattice_planner.stat");
  ros::spin();
  //ProfilerStop();
  return 0;
}


text:
// Copyright (C) 2001-2003
// William E. Kempf
//
//  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/thread/detail/config.hpp>

#include <boost/thread/mutex.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/exceptions.hpp>
#include <boost/limits.hpp>
#include <string>
#include <stdexcept>
#include <cassert>
#include "timeconv.inl"

#if defined(BOOST_HAS_WINTHREADS)
#   include <new>
#   include <boost/thread/once.hpp>
#   include <windows.h>
#   include <time.h>
#   include "mutex.inl"
#elif defined(BOOST_HAS_PTHREADS)
#   include <errno.h>
#elif defined(BOOST_HAS_MPTASKS)
#    include <MacErrors.h>
#    include "mac/init.hpp"
#    include "mac/safe.hpp"
#endif

namespace boost {

#if defined(BOOST_HAS_WINTHREADS)

mutex::mutex()
    : m_mutex(0)
    , m_critical_section(false)
{
    m_critical_section = true;
    if (m_critical_section)
        m_mutex = new_critical_section();
    else
        m_mutex = new_mutex(0);
}

mutex::~mutex()
{
    if (m_critical_section)
        delete_critical_section(m_mutex);
    else
        delete_mutex(m_mutex);
}

void mutex::do_lock()
{
    if (m_critical_section)
        wait_critical_section_infinite(m_mutex);
    else
        wait_mutex(m_mutex, INFINITE);
}

void mutex::do_unlock()
{
    if (m_critical_section)
        release_critical_section(m_mutex);
    else
        release_mutex(m_mutex);
}

void mutex::do_lock(cv_state&)
{
    do_lock();
}

void mutex::do_unlock(cv_state&)
{
    do_unlock();
}

try_mutex::try_mutex()
    : m_mutex(0)
    , m_critical_section(false)
{
    m_critical_section = has_TryEnterCriticalSection();
    if (m_critical_section)
        m_mutex = new_critical_section();
    else
        m_mutex = new_mutex(0);
}

try_mutex::~try_mutex()
{
    if (m_critical_section)
        delete_critical_section(m_mutex);
    else
        delete_mutex(m_mutex);
}

void try_mutex::do_lock()
{
    if (m_critical_section)
        wait_critical_section_infinite(m_mutex);
    else
        wait_mutex(m_mutex, INFINITE);
}

bool try_mutex::do_trylock()
{
    if (m_critical_section)
        return wait_critical_section_try(m_mutex);
    else
        return wait_mutex(m_mutex, 0) == WAIT_OBJECT_0;
}

void try_mutex::do_unlock()
{
    if (m_critical_section)
        release_critical_section(m_mutex);
    else
        release_mutex(m_mutex);
}

void try_mutex::do_lock(cv_state&)
{
    do_lock();
}

void try_mutex::do_unlock(cv_state&)
{
    do_unlock();
}

timed_mutex::timed_mutex()
    : m_mutex(0)
{
    m_mutex = new_mutex(0);
}

timed_mutex::~timed_mutex()
{
    delete_mutex(m_mutex);
}

void timed_mutex::do_lock()
{
    wait_mutex(m_mutex, INFINITE);
}

bool timed_mutex::do_trylock()
{
    return wait_mutex(m_mutex, 0) == WAIT_OBJECT_0;
}

bool timed_mutex::do_timedlock(const xtime& xt)
{
    for (;;)
    {
        int milliseconds;
        to_duration(xt, milliseconds);

        int res = wait_mutex(m_mutex, milliseconds);

        if (res == WAIT_TIMEOUT)
        {
            boost::xtime cur;
            boost::xtime_get(&cur, boost::TIME_UTC);
            if (boost::xtime_cmp(xt, cur) > 0)
                continue;
        }

        return res == WAIT_OBJECT_0;
    }
}

void timed_mutex::do_unlock()
{
    release_mutex(m_mutex);
}

void timed_mutex::do_lock(cv_state&)
{
    do_lock();
}

void timed_mutex::do_unlock(cv_state&)
{
    do_unlock();
}

#elif defined(BOOST_HAS_PTHREADS)

mutex::mutex()
{
    int res = 0;
    res = pthread_mutex_init(&m_mutex, 0);
    if (res != 0)
        throw thread_resource_error();
}

mutex::~mutex()
{
    int res = 0;
    res = pthread_mutex_destroy(&m_mutex);
    assert(res == 0);
}

void mutex::do_lock()
{
    int res = 0;
    res = pthread_mutex_lock(&m_mutex);
    if (res == EDEADLK) throw lock_error();
    assert(res == 0);
}

void mutex::do_unlock()
{
    int res = 0;
    res = pthread_mutex_unlock(&m_mutex);
    if (res == EPERM) throw lock_error();
    assert(res == 0);
}

void mutex::do_lock(cv_state&)
{
}

void mutex::do_unlock(cv_state& state)
{
    state.pmutex = &m_mutex;
}

try_mutex::try_mutex()
{
    int res = 0;
    res = pthread_mutex_init(&m_mutex, 0);
    if (res != 0)
        throw thread_resource_error();
}

try_mutex::~try_mutex()
{
    int res = 0;
    res = pthread_mutex_destroy(&m_mutex);
    assert(res == 0);
}

void try_mutex::do_lock()
{
    int res = 0;
    res = pthread_mutex_lock(&m_mutex);
    if (res == EDEADLK) throw lock_error();
    assert(res == 0);
}

bool try_mutex::do_trylock()
{
    int res = 0;
    res = pthread_mutex_trylock(&m_mutex);
    if (res == EDEADLK) throw lock_error();
    assert(res == 0 || res == EBUSY);
    return res == 0;
}

void try_mutex::do_unlock()
{
    int res = 0;
    res = pthread_mutex_unlock(&m_mutex);
    if (res == EPERM) throw lock_error();
    assert(res == 0);
}

void try_mutex::do_lock(cv_state&)
{
}

void try_mutex::do_unlock(cv_state& state)
{
    state.pmutex = &m_mutex;
}

timed_mutex::timed_mutex()
    : m_locked(false)
{
    int res = 0;
    res = pthread_mutex_init(&m_mutex, 0);
    if (res != 0)
        throw thread_resource_error();

    res = pthread_cond_init(&m_condition, 0);
    if (res != 0)
    {
        pthread_mutex_destroy(&m_mutex);
        throw thread_resource_error();
    }
}

timed_mutex::~timed_mutex()
{
    assert(!m_locked);
    int res = 0;
    res = pthread_mutex_destroy(&m_mutex);
    assert(res == 0);

    res = pthread_cond_destroy(&m_condition);
    assert(res == 0);
}

void timed_mutex::do_lock()
{
    int res = 0;
    res = pthread_mutex_lock(&m_mutex);
    assert(res == 0);

    while (m_locked)
    {
        res = pthread_cond_wait(&m_condition, &m_mutex);
        assert(res == 0);
    }

    assert(!m_locked);
    m_locked = true;

    res = pthread_mutex_unlock(&m_mutex);
    assert(res == 0);
}

bool timed_mutex::do_trylock()
{
    int res = 0;
    res = pthread_mutex_lock(&m_mutex);
    assert(res == 0);

    bool ret = false;
    if (!m_locked)
    {
        m_locked = true;
        ret = true;
    }

    res = pthread_mutex_unlock(&m_mutex);
    assert(res == 0);
    return ret;
}

bool timed_mutex::do_timedlock(const xtime& xt)
{
    int res = 0;
    res = pthread_mutex_lock(&m_mutex);
    assert(res == 0);

    timespec ts;
    to_timespec(xt, ts);

    while (m_locked)
    {
        res = pthread_cond_timedwait(&m_condition, &m_mutex, &ts);
        assert(res == 0 || res == ETIMEDOUT);

        if (res == ETIMEDOUT)
            break;
    }

    bool ret = false;
    if (!m_locked)
    {
        m_locked = true;
        ret = true;
    }

    res = pthread_mutex_unlock(&m_mutex);
    assert(res == 0);
    return ret;
}

void timed_mutex::do_unlock()
{
    int res = 0;
    res = pthread_mutex_lock(&m_mutex);
    assert(res == 0);

    assert(m_locked);
    m_locked = false;

    res = pthread_cond_signal(&m_condition);
    assert(res == 0);

    res = pthread_mutex_unlock(&m_mutex);
    assert(res == 0);
}

void timed_mutex::do_lock(cv_state&)
{
    int res = 0;
    while (m_locked)
    {
        res = pthread_cond_wait(&m_condition, &m_mutex);
        assert(res == 0);
    }

    assert(!m_locked);
    m_locked = true;

    res = pthread_mutex_unlock(&m_mutex);
    assert(res == 0);
}

void timed_mutex::do_unlock(cv_state& state)
{
    int res = 0;
    res = pthread_mutex_lock(&m_mutex);
    assert(res == 0);

    assert(m_locked);
    m_locked = false;

    res = pthread_cond_signal(&m_condition);
    assert(res == 0);

    state.pmutex = &m_mutex;
}

#elif defined(BOOST_HAS_MPTASKS)

using threads::mac::detail::safe_enter_critical_region;

mutex::mutex()
{
}

mutex::~mutex()
{
}

void mutex::do_lock()
{
    OSStatus lStatus = noErr;
    lStatus = safe_enter_critical_region(m_mutex, kDurationForever,
        m_mutex_mutex);
    assert(lStatus == noErr);
}

void mutex::do_unlock()
{
    OSStatus lStatus = noErr;
    lStatus = MPExitCriticalRegion(m_mutex);
    assert(lStatus == noErr);
}

void mutex::do_lock(cv_state& /*state*/)
{
    do_lock();
}

void mutex::do_unlock(cv_state& /*state*/)
{
    do_unlock();
}

try_mutex::try_mutex()
{
}

try_mutex::~try_mutex()
{
}

void try_mutex::do_lock()
{
    OSStatus lStatus = noErr;
    lStatus = safe_enter_critical_region(m_mutex, kDurationForever,
        m_mutex_mutex);
    assert(lStatus == noErr);
}

bool try_mutex::do_trylock()
{
    OSStatus lStatus = noErr;
    lStatus = MPEnterCriticalRegion(m_mutex, kDurationImmediate);
    assert(lStatus == noErr || lStatus == kMPTimeoutErr);
    return lStatus == noErr;
}

void try_mutex::do_unlock()
{
    OSStatus lStatus = noErr;
    lStatus = MPExitCriticalRegion(m_mutex);
    assert(lStatus == noErr);
}

void try_mutex::do_lock(cv_state& /*state*/)
{
    do_lock();
}

void try_mutex::do_unlock(cv_state& /*state*/)
{
    do_unlock();
}

timed_mutex::timed_mutex()
{
}

timed_mutex::~timed_mutex()
{
}

void timed_mutex::do_lock()
{
    OSStatus lStatus = noErr;
    lStatus = safe_enter_critical_region(m_mutex, kDurationForever,
        m_mutex_mutex);
    assert(lStatus == noErr);
}

bool timed_mutex::do_trylock()
{
    OSStatus lStatus = noErr;
    lStatus = MPEnterCriticalRegion(m_mutex, kDurationImmediate);
    assert(lStatus == noErr || lStatus == kMPTimeoutErr);
    return(lStatus == noErr);
}

bool timed_mutex::do_timedlock(const xtime& xt)
{
    int microseconds;
    to_microduration(xt, microseconds);
    Duration lDuration = kDurationMicrosecond * microseconds;

    OSStatus lStatus = noErr;
    lStatus = safe_enter_critical_region(m_mutex, lDuration, m_mutex_mutex);
    assert(lStatus == noErr || lStatus == kMPTimeoutErr);

    return(lStatus == noErr);
}

void timed_mutex::do_unlock()
{
    OSStatus lStatus = noErr;
    lStatus = MPExitCriticalRegion(m_mutex);
    assert(lStatus == noErr);
}

void timed_mutex::do_lock(cv_state& /*state*/)
{
    do_lock();
}

void timed_mutex::do_unlock(cv_state& /*state*/)
{
    do_unlock();
}

#endif

} // namespace boost

// Change Log:
//   8 Feb 01  WEKEMPF Initial version.

max_stars_repo_name: dbremner/framewave

max_issues_repo_name: dbremner/framewave

max_forks_repo_name: dbremner/framewave


text:
// Simple Music Player
// coding by S.H. (GAMELINKS)
// This source code license is MIT, see the license

// include DxLib
#include "DxLib.h"

// include Boost library
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>

namespace fs = boost::filesystem;

// include openCV
#include <opencv2/opencv.hpp>

// include standard library
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <thread>
#include <chrono>

// One (and only one) of your C++ files must define CVUI_IMPLEMENTATION
// before the inclusion of cvui.h to ensure its implementaiton is compiled.
#define CVUI_IMPLEMENTATION
#include "cvui.h"

// Hide Console Window
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")

// Set Software Title
constexpr const char* WindowName = "Simple Music Player";

// Set Wait Time
constexpr int WaitTime = 20;

//Read All MP3 File Path
std::vector<std::string> AllFilePath() {

	std::vector<std::string> Container;

	std::string Path = "mp3";

	const fs::path path(Path);

	BOOST_FOREACH(const fs::path& p, std::make_pair(fs::directory_iterator(path),
		fs::directory_iterator())) {
		if (!fs::is_directory(p))
			Container.emplace_back(std::move(p.filename().string()));
	}

	return Container;
}

// Loading music
std::vector<int> LoadMusic(const std::vector<std::string> Container) {

	// Loading Sound Data Type Set
	DxLib::SetCreateSoundDataType(DX_SOUNDDATATYPE_MEMPRESS);

	std::string Path = "mp3/";

	std::vector<int> MusicContainer;

	for (auto&& c : Container)
		MusicContainer.emplace_back(std::move(DxLib::LoadSoundMem((Path + c).c_str())));

	return MusicContainer;
}

// Draw button
int DrawButton(cv::Mat frame, std::int32_t Num, std::vector<int> MusicContainer) {

	if (cvui::button(frame, 20, 40, "Prev") || DxLib::CheckHitKey(KEY_INPUT_LEFT)){
		Num = (Num == 0) ? 0 : Num - 1;

		DxLib::StopSoundMem(MusicContainer[Num + 1]);
		DxLib::PlaySoundMem(MusicContainer[Num], DX_PLAYTYPE_LOOP);
	}

	if (cvui::button(frame, 80, 40, "Play") || DxLib::CheckHitKey(KEY_INPUT_SPACE))
		DxLib::PlaySoundMem(MusicContainer[Num], DX_PLAYTYPE_LOOP);

	if (cvui::button(frame, 140, 40, "Stop") || DxLib::CheckHitKey(KEY_INPUT_BACK))
		DxLib::StopSoundMem(MusicContainer[Num]);

	if (cvui::button(frame, 200, 40, "Next") || DxLib::CheckHitKey(KEY_INPUT_RIGHT)) {

		Num = (static_cast<unsigned int>(Num) + 1 == MusicContainer.size()) ? MusicContainer.size() - 1 : Num + 1;

		DxLib::StopSoundMem(MusicContainer[Num - 1]);
		DxLib::PlaySoundMem(MusicContainer[Num], DX_PLAYTYPE_LOOP);
	}

	std::this_thread::sleep_for(std::chrono::milliseconds(WaitTime));

	return Num;
}

// Change Volumes
double VolumeTrackBar(cv::Mat frame, double value) {
	cvui::trackbar(frame, 40, 70, 220, &value, (double)0.0, (double)100.0);

	if (DxLib::CheckHitKey(KEY_INPUT_UP)) {
		if (value >= 100.0)
			value = 100.0;
		else
			value++;
	}

	if (DxLib::CheckHitKey(KEY_INPUT_DOWN)) {
		if (value <= 0.0)
			value = 0.0;
		else
			value--;
	}

	std::this_thread::sleep_for(std::chrono::milliseconds(WaitTime));

	return value;
}

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

	DxLib::SetNotWinFlag(TRUE);	// Do not draw Window for DxLib

	if (DxLib::DxLib_Init() == -1)    // DxLib Init!
	{
		return -1;    // Error!
	}

	std::vector<std::string> Container = AllFilePath();

	// Create a frame where components will be rendered to.
	cv::Mat frame = cv::Mat(180, 280, CV_8UC3);

	// Init cvui and tell it to create a OpenCV window, i.e. cv::namedWindow(WINDOW_NAME).
	cvui::init(WindowName);

	// Set Volumnes
	double value = 100.0;

	const std::vector<int> MusicContainer = LoadMusic(Container);

	std::int32_t Num = 0;

	while (true) {
		// Fill the frame with a nice color
		frame = cv::Scalar(49, 52, 49);

		Num = DrawButton(frame, Num, MusicContainer);

		value = VolumeTrackBar(frame, value);

		ChangeVolumeSoundMem(255 * static_cast<int>(value) / 100, MusicContainer[Num]);

		if (DxLib::CheckSoundMem(MusicContainer[Num]) == 1)
			cvui::text(frame, 40, 150, "Now Playing " + Container[Num]);

		// Update cvui stuff and show everything on the screen
		cvui::imshow(WindowName, frame);

		// Exit to ESC Key!
		if (cv::waitKey(20) == 27) {
			break;
		}
	}

	DxLib::DxLib_End();        // DxLib End!

	return 0;
}

max_stars_repo_name: S-H-GAMELINKS/SimpleMusicPlayer

max_issues_repo_name: S-H-GAMELINKS/SimpleMusicPlayer

max_forks_repo_name: S-H-GAMELINKS/SimpleMusicPlayer


text:
//  Copyright (c) 2019 AUTHORS
//
//  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 "octotiger/defs.hpp"
#include "octotiger/options.hpp"

#include <boost/program_options.hpp>

#include <vector>

options& opts() {
	static options opts_;
	return opts_;
}
std::vector<hpx::id_type> options::all_localities = { };


text:
//  (C) Copyright John Maddock 2021.
//  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)

//
// As detailed in https://github.com/boostorg/math/issues/544
// our original non-central T test data wasn't accurate past about
// 20 decimal places.  This data generator takes the original input
// values and generates new CDF and CDF-complement values via
// tanh_sinh integration - an option that wasn't available when
// the original values were generated back in 2008.
//
// Note that this code will take SEVERAL DAYS to run on typical
// 2021 hardware.
//

#include <boost/math/special_functions/gamma.hpp>
#include <boost/math/special_functions/beta.hpp>
#include <boost/math/special_functions/hypergeometric_1F1.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/quadrature/exp_sinh.hpp>
#include <boost/multiprecision/cpp_bin_float.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <fstream>

#include <libs/math/test/table_type.hpp>

using namespace boost::math::tools;
using namespace boost::math;
using namespace std;
using namespace boost::multiprecision;

//using big_t = number<cpp_bin_float<200, digit_base_10, void, long long>>;
using big_t = number<mpfr_float_backend<200>>;

big_t nct_A(big_t v, big_t x, big_t nu)
{
   big_t result = boost::math::hypergeometric_1F1(v / 2 + 1, big_t(3) / 2, nu * nu * x * x / (2 * (v + x * x)));
   result *= boost::math::constants::root_two<big_t>() * nu * x;
   result /= (v + x * x) * boost::math::tgamma((v + 1) / 2);
   return result;
}
big_t nct_B(big_t v, big_t x, big_t nu)
{
   big_t result = boost::math::hypergeometric_1F1((v + 1) / 2, big_t(1) / 2, nu * nu * x * x / (2 * (x * x + v)));
   result /= sqrt(v + x * x) * boost::math::tgamma(v / 2 + 1);
   return result;
}
big_t nct_PDF(big_t v, big_t nu, big_t x)
{
   big_t result = nct_A(v, x, nu) + nct_B(v, x, nu);
   result *= pow(v, v / 2) * boost::math::tgamma(v + 1);
   result /= pow(big_t(2), v) * exp(nu * nu / 2) * pow(v + x * x, v / 2) * boost::math::tgamma(v / 2);
   return result;
}

big_t nc_t_F(big_t v, big_t nc, big_t t)
{
   unsigned j = 0;
   big_t sum = 0;
   big_t tol = std::numeric_limits<big_t>::epsilon();
   do
   {
      big_t x = t * t / (t * t + v);
      big_t p = exp(-nc * nc / 2) * pow(nc * nc / 2, j) / (2 * boost::math::factorial<big_t>(j));
      big_t q = (nc / 2) * exp(-nc * nc / 2) * pow(nc * nc / 2, j) / (boost::math::constants::root_two<big_t>() * boost::math::tgamma(j + big_t(3) / 2));
      big_t term = p * boost::math::ibeta(big_t(j) + 0.5, v / 2, x) + q * boost::math::ibeta(big_t(j + 1), v / 2, x);
      ++j;

      sum += term;

      if (fabs(sum * tol) > fabs(term))
         break;
   } while (true);

   return sum + boost::math::constants::half<big_t>() * (1 + boost::math::erf(-nc / boost::math::constants::root_two<big_t>()));
}
big_t nc_t(big_t v, big_t nc, big_t t)
{
   return t < 0 ? 1 - nc_t_F(v, -nc, t) : nc_t_F(v, nc, t);
}

#define SC_(x) BOOST_JOIN(x, f)

int main(int, char* [])
{
   mpfr_set_emax(mpfr_get_emax_max());
   mpfr_set_emin(mpfr_get_emin_min());

   boost::math::quadrature::exp_sinh<big_t> integrator(10);
   using T = float;

#include <libs/math/test/nct.ipp>

   for (unsigned i = 0; i < nct.size(); ++i)
   {
      big_t error1, error2;
      big_t v(nct[i][0]), nc(nct[i][1]), x(nct[i][2]);
      big_t cdf, ccdf;
      try{
         cdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, -std::numeric_limits<big_t>::infinity(), x, big_t(1e-36), &error1);
         ccdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, x, std::numeric_limits<big_t>::infinity(), big_t(1e-36), &error2);
      }
      catch(const std::exception& e)
      {
         std::cout << "// " << e.what() << " reverting to ibeta method" << std::endl;
         error1 = error2 = 0;
         cdf = nc_t(v, nc, x);
         ccdf = 1 - cdf;
      }

      if (error1 > 1e-35)
      {
         std::cout << "// Accuracy for cdf was " << error1 << " reverting to ibeta method" << std::endl;
         cdf = nc_t(v, nc, x);
      }
      if (error2 > 1e-35)
      {
         std::cout << "// Accuracy for complement cdf was " << error2 << " reverting to ibeta method" << std::endl;
         ccdf = 1 - nc_t(v, nc, x);
      }

      std::cout << std::setprecision(40);
      std::cout << "{{ SC_(" << nct[i][0] << "), SC_(" << nct[i][1] << "), SC_(" << nct[i][2] << "), SC_(";
      std::cout << cdf << "), SC_(" << ccdf << ") }}," << std::endl;
   }

#include <libs/math/test/nct_small_delta.ipp>
   for (unsigned i = 0; i < nct_small_delta.size(); ++i)
   {
      big_t error1, error2;
      big_t v(nct_small_delta[i][0]), nc(nct_small_delta[i][1]), x(nct_small_delta[i][2]);
      big_t cdf, ccdf;
      try {
         cdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, -std::numeric_limits<big_t>::infinity(), x, big_t(1e-36), &error1);
         ccdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, x, std::numeric_limits<big_t>::infinity(), big_t(1e-36), &error2);
      }
      catch (const std::exception& e)
      {
         std::cout << "// " << e.what() << " reverting to ibeta method" << std::endl;
         error1 = error2 = 0;
         cdf = nc_t(v, nc, x);
         ccdf = 1 - cdf;
      }

      if (error1 > 1e-35)
      {
         std::cout << "// Accuracy for cdf was " << error1 << " reverting to ibeta method" << std::endl;
         cdf = nc_t(v, nc, x);
      }
      if (error2 > 1e-35)
      {
         std::cout << "// Accuracy for complement cdf was " << error2 << " reverting to ibeta method" << std::endl;
         ccdf = 1 - nc_t(v, nc, x);
      }

      std::cout << std::setprecision(40);
      std::cout << "{{ SC_(" << v << "), SC_(" << nc << "), SC_(" << x << "), SC_(";
      std::cout << cdf << "), SC_(" << ccdf << ") }}," << std::endl;
   }

#include "../test/nct_asym.ipp"
   for (unsigned i = 0; i < nct_asym.size(); ++i)
   {
      big_t error1, error2;
      big_t v(nct_asym[i][0]), nc(nct_asym[i][1]), x(nct_asym[i][2]);
      big_t cdf, ccdf;
      try {
         cdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, -std::numeric_limits<big_t>::infinity(), x, big_t(1e-36), &error1);
         ccdf = integrator.integrate([&](big_t y) { return nct_PDF(v, nc, y); }, x, std::numeric_limits<big_t>::infinity(), big_t(1e-36), &error2);
      }
      catch (const std::exception& e)
      {
         std::cout << "// " << e.what() << " reverting to ibeta method" << std::endl;
         error1 = error2 = 0;
         cdf = nc_t(v, nc, x);
         ccdf = 1 - cdf;
      }

      if (error1 > 1e-35)
      {
         std::cout << "// Accuracy for cdf was " << error1 << " reverting to ibeta method" << std::endl;
         cdf = nc_t(v, nc, x);
      }
      if (error2 > 1e-35)
      {
         std::cout << "// Accuracy for complement cdf was " << error2 << " reverting to ibeta method" << std::endl;
         ccdf = 1 - nc_t(v, nc, x);
      }

      std::cout << std::setprecision(40);
      std::cout << "{{ SC_(" << v << "), SC_(" << nc << "), SC_(" << x << "), SC_(";
      std::cout << cdf << "), SC_(" << ccdf << ") }}," << std::endl;
   }

   return 0;
}

max_stars_repo_name: oleg-alexandrov/math

max_issues_repo_name: oleg-alexandrov/math

max_forks_repo_name: oleg-alexandrov/math


text:
/*
 *
 * Crypto.BI Toolbox
 * https://Crypto.BI/
 *
 * Author: José Fonseca (https://zefonseca.com/)
 *
 * Distributed under the MIT software license, see the accompanying
 * file COPYING or http://www.opensource.org/licenses/mit-license.php.
 *
 */

#include <cstdlib>
#include <boost/filesystem.hpp>
#include <iostream>

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

	return EXIT_SUCCESS;
}

max_stars_repo_name: nwtechguy/toolbox

max_issues_repo_name: nwtechguy/toolbox

max_forks_repo_name: nwtechguy/toolbox


text:
/*=============================================================================
    Copyright (c) 2001-2003 Daniel Nuffer
    http://spirit.sourceforge.net/

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

///////////////////////////////////////////////////////////////////////////////
#include <boost/spirit/home/classic/core.hpp>
#include <boost/spirit/home/classic/iterator/multi_pass.hpp>
#include <boost/spirit/home/classic/namespace.hpp>

///////////////////////////////////////////////////////////////////////////////
namespace boost {
namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

namespace impl {

template <typename T> void flush_iterator(T &) {}

template <typename T1, typename T2, typename T3, typename T4>
void flush_iterator(
    BOOST_SPIRIT_CLASSIC_NS::multi_pass<
        T1, T2, T3, T4, BOOST_SPIRIT_CLASSIC_NS::multi_pass_policies::std_deque>
        &i) {
  i.clear_queue();
}

} // namespace impl

///////////////////////////////////////////////////////////////////////////
//
//  flush_multi_pass_parser
//
//      The flush_multi_pass_parser flushes an underlying
//      multi_pass_iterator during the normal parsing process. This may
//      be used at certain points during the parsing process, when it is
//      clear, that no backtracking is needed anymore and the input
//      gathered so far may be discarded.
//
///////////////////////////////////////////////////////////////////////////
class flush_multi_pass_parser : public parser<flush_multi_pass_parser> {
public:
  typedef flush_multi_pass_parser this_t;

  template <typename ScannerT>
  typename parser_result<this_t, ScannerT>::type
  parse(ScannerT const &scan) const {
    impl::flush_iterator(scan.first);
    return scan.empty_match();
  }
};

///////////////////////////////////////////////////////////////////////////
//
//  predefined flush_multi_pass_p object
//
//      This object should may used to flush a multi_pass_iterator along
//      the way during the normal parsing process.
//
///////////////////////////////////////////////////////////////////////////

flush_multi_pass_parser const flush_multi_pass_p = flush_multi_pass_parser();

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

} // namespace spirit
} // namespace boost

#endif // BOOST_SPIRIT_FLUSH_MULTI_PASS_HPP

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


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

#include <boost/hana/sandbox/lambda_tuple.hpp>

#include <boost/hana/tuple.hpp>
#include <boost/hana/type.hpp>

#include <test/auto/base.hpp>
#include <test/auto/sequence.hpp>
#include <test/cnumeric.hpp>
using namespace boost::hana;

template <int i>
constexpr auto ord = test::cnumeric<int, i>;

namespace boost { namespace hana { namespace test {
    template <>
    auto objects<sandbox::LambdaTuple> = make<Tuple>(
            sandbox::lambda_tuple()
          , sandbox::lambda_tuple(ord<0>)
          , sandbox::lambda_tuple(ord<0>, ord<1>)
          , sandbox::lambda_tuple(ord<0>, ord<1>, ord<2>)
          , sandbox::lambda_tuple(ord<0>, ord<1>, ord<2>, ord<3>)
          , sandbox::lambda_tuple(ord<0>, ord<1>, ord<2>, ord<3>, ord<4>)
          , sandbox::lambda_tuple(ord<0>, ord<1>, ord<2>, ord<3>, ord<4>, ord<5>)
    );

    template <>
    auto instances<sandbox::LambdaTuple> = make<Tuple>(
        // type<Sequence>
          type<Iterable>
        , type<Searchable>
        , type<Foldable>
        , type<Comparable>
        , type<Orderable>
    );
}}}

int main() {
    test::check_datatype<sandbox::LambdaTuple>();
}

max_stars_repo_name: josephwinston/hana

max_issues_repo_name: josephwinston/hana

max_forks_repo_name: josephwinston/hana


text:
#include "stdafx.h"
#include "ConstructorDeclarationPattern.h"
#include <JCDT_Lib/internal/ast/AstConstructorDeclaration.h>
#include <JCDT_Lib/internal/lookup/MethodSymbol.h>
#include <JCDT_Lib/internal/lookup/VariableSymbol.h>
#include <JCDT_Lib/internal/classfmt/class.h>
#include <JCDT_Lib/internal/util/CharOperation.h>
#include <boost/algorithm/string.hpp>
#include  <JCDT_Lib/internal/codegen/Signature.h>
namespace Jikes { // Open namespace Jikes block

namespace Search{
	ConstructorDeclarationPattern::ConstructorDeclarationPattern(
		std::wstring declaringSimpleName,
		int _matchMode, bool _isCaseSensitive,
		std::wstring declaringQualification,
		std::vector<std::wstring>* parameterQualifications,
		std::vector<std::wstring> *parameterSimpleNames)
		:MethodDeclarationPattern(
			L"",
			_matchMode,
			_isCaseSensitive,
			declaringQualification,
			declaringSimpleName,
			L"",
			L"",
			nullptr,
			nullptr)
	{
	}

	bool ConstructorDeclarationPattern::matchesBinary(std::pair<void*, BinaryInfoType>&  binaryInfo,
		std::pair<const ConstantPool*, CPClassInfo*>& class_data)
	{
		if (!(binaryInfo.second == BinaryInfoType::METHOD_INFO )
			|| !class_data.first
			|| !binaryInfo.first)
			return false;

		auto method = (MethodInfo*)binaryInfo.first;

		// must be a constructor
		const ConstantPool& pool = *(class_data.first);
		auto str = method->Name(pool);

		string selector;
		if(str)
			selector.assign(str, str + method->NameLength(pool));

		if(selector != "<init>")
			return false;

		// declaring type
		CPClassInfo* class_info = class_data.second;

		if (class_info != nullptr) {

			wstring declaringTypeName = CharOperation::ConvertUtf8ToUnicode(class_info->TypeName(pool));;
			boost::replace_all(declaringTypeName, L"/", L".");
			if (!matchesType(declaringSimpleName, declaringQualification, declaringTypeName)) {
				return false;
			}
		}

		// parameter types
		int parameterCount = parameterSimpleNames == nullptr ? -1 : parameterSimpleNames->size();
		if (parameterCount > -1) {
			str = method->Signature(pool, nullptr);
			if (!str)
				return false;

			string sig(str,
				str + method->SignatureLength(pool, nullptr));
			auto  _ret = Signature::parseSignature(sig);
			auto & formal_parameters = _ret.first;
			int argumentCount = formal_parameters.size();
			if (parameterCount != argumentCount)
				return false;

			for (int i = 0; i < parameterCount; i++) {

				auto& qualification = parameterQualifications->operator[](i);
				auto& type = parameterSimpleNames->operator[](i);
				if (!matchesType(type, qualification, formal_parameters[i]))
					return false;
			}
		}

		return true;
	}

	int ConstructorDeclarationPattern::matchLevel(Ast* node, bool resolve)
	{
		if (!node ||  node->kind != CONSTRUCTOR) {
			return IMPOSSIBLE_MATCH;
		}

		ConstructorDeclaration* constructor = (ConstructorDeclaration*)node;

		if (resolve) {
			return matchLevel(constructor->method_symbol);
		}
		else {
			// constructor name is stored in selector field
			auto  declarator  =constructor->method_declarator;

			if (!declarator || !declarator->identifier_token)
				return IMPOSSIBLE_MATCH;

			if (	declaringSimpleName.empty() != true
				&& ! matchesName(declaringSimpleName, declarator->identifier_token->getName())
				)
				return IMPOSSIBLE_MATCH;

			// parameter types
			int parameterCount = parameterSimpleNames==nullptr ? -1: parameterSimpleNames->size();
			if (parameterCount > -1) {
				int argumentCount = declarator->NumFormalParameters();
				if (parameterCount != argumentCount)
					return IMPOSSIBLE_MATCH;
			}

			return _needsResolve ? POSSIBLE_MATCH : ACCURATE_MATCH;
		}
	}

	int ConstructorDeclarationPattern::matchLevel(Symbol* binding)
	{
		if (!binding)
			return INACCURATE_MATCH;

		if (binding->_kind != Symbol::METHOD)
			return IMPOSSIBLE_MATCH;

		int level;

		MethodSymbol* constructor = reinterpret_cast<MethodSymbol*>(binding);

		// must be a constructor
		if (!constructor->IsConstructor())
			return IMPOSSIBLE_MATCH;

		// declaring type
		auto declaringType = constructor->containing_type;

		if(!declaringType)
			return IMPOSSIBLE_MATCH;

		if (!constructor->ACC_STATIC() && !constructor->ACC_PRIVATE()) {
			level = matchLevelAsSubtype(declaringType, declaringSimpleName, declaringQualification);
		}
		else {
			level = matchLevelForType(declaringSimpleName, declaringQualification, declaringType);
		}
		if (level == IMPOSSIBLE_MATCH) {
			return IMPOSSIBLE_MATCH;
		}

		// parameter types
		int parameterCount = parameterSimpleNames== nullptr? -1 : parameterSimpleNames->size();
		if (parameterCount >= -1) {
			int argumentCount = constructor->NumFormalParameters();
			if (parameterCount != argumentCount)
				return IMPOSSIBLE_MATCH;

			for (int i = 0; i < parameterCount; i++) {
				auto& qualification = parameterQualifications->operator[](i);
				auto& type = parameterSimpleNames->operator[](i);
				auto parameter = constructor->FormalParameter(i);
				if (!parameter)
					continue;

				int newLevel = matchLevelForType(type, qualification, parameter->Type());
				switch (newLevel)
				{
				case IMPOSSIBLE_MATCH:
					return IMPOSSIBLE_MATCH;
				case ACCURATE_MATCH: // keep previous level
					break;
				default: // ie. INACCURATE_MATCH
					level = newLevel;
					break;
				}
			}
		}

		return level;
	}
}

} // Close namespace Jikes block

max_stars_repo_name: kuafuwang/JCDT

max_issues_repo_name: kuafuwang/JCDT

max_forks_repo_name: kuafuwang/JCDT


text:
/**
 *  @file
 *  @author     2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de)
 *  @copyright  Simplified BSD
 *
 *  @cond
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the FreeBSD license as published by the FreeBSD
 *  project.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 *  You should have received a copy of the FreeBSD license along with this
 *  program. If not, see <http://www.opensource.org/licenses/bsd-license>.
 *  @endcond
 */

#include "SMTPInvoker.h"
#include <glog/logging.h>

#ifdef BUILD_AS_PLUGINS
#include <Pluma/Connector.hpp>
#endif

#include <boost/algorithm/string.hpp>
#include "uscxml/UUID.h"
#include "uscxml/messages/Blob.h"

namespace uscxml {

#ifdef BUILD_AS_PLUGINS
PLUMA_CONNECTOR
bool pluginConnect(pluma::Host& host) {
	host.add( new SMTPInvokerProvider() );
	return true;
}
#endif

SMTPInvoker::SMTPInvoker() {
}

SMTPInvoker::~SMTPInvoker() {
};

boost::shared_ptr<InvokerImpl> SMTPInvoker::create(InterpreterImpl* interpreter) {
	boost::shared_ptr<SMTPInvoker> invoker = boost::shared_ptr<SMTPInvoker>(new SMTPInvoker());
	return invoker;
}

Data SMTPInvoker::getDataModelVariables() {
	Data data;
	return data;
}

size_t SMTPInvoker::writeCurlData(void *ptr, size_t size, size_t nmemb, void *userdata) {
	if (!userdata)
		return 0;

	SMTPContext* ctx = (SMTPContext*)userdata;

	size_t toWrite = (std::min)(ctx->content.length() - ctx->readPtr, size * nmemb);
	if (toWrite > 0) {
		memcpy (ptr, ctx->content.c_str() + ctx->readPtr, toWrite);
		ctx->readPtr += toWrite;
	}

	return toWrite;
}

std::list<std::string> SMTPInvoker::getAtoms(std::list<Data> list) {
	std::list<std::string> atoms;

	std::list<Data>::const_iterator iter = list.begin();
	while(iter != list.end()) {
		const Data& data = *iter;
		if (data.atom.size() > 0) {
			atoms.push_back(data.atom);
		} else if (data.array.size() > 0) {
			std::list<Data>::const_iterator arrIter = data.array.begin();
			while(arrIter != data.array.end()) {
				if (arrIter->atom.size() > 0) {
					atoms.push_back(arrIter->atom);
					arrIter++;
				}
			}
		}
		iter++;
	}
	return atoms;
}

void SMTPInvoker::getAttachments(std::list<Data> list, std::list<Data>& attachments) {
	// accumulate attachments with filename, mimetype and data
	std::list<Data>::const_iterator iter = list.begin();
	while(iter != list.end()) {
		const Data& data = *iter;
		if (data.hasKey("data")) {
			// compound structure with all information
			Data att = data;

			if (!att.hasKey("mimetype")) {
				if (att["data"].binary && att["data"].binary.getMimeType().size() > 0) {
					att.compound["mimetype"] = Data(att["data"].binary.getMimeType(), Data::VERBATIM);
				} else {
					att.compound["mimetype"] = Data("text/plain", Data::VERBATIM);
				}
			}

			if (!att.hasKey("filename")) {
				std::stringstream filenameSS;
				filenameSS << "attachment" << attachments.size() + 1;
				if (boost::starts_with(att.compound["mimetype"].atom, "text")) {
					filenameSS << ".txt";
				} else {
					filenameSS << ".bin";
				}
				att.compound["filename"] = Data(filenameSS.str(), Data::VERBATIM);
			}

			attachments.push_back(att);

		} else if (data.binary) {
			// a single binary blob
			Data att;

			att.compound["data"].binary = data.binary;

			if (data.binary.getMimeType().size() > 0) {
				att.compound["mimetype"] = Data(attachments.back()["data"].binary.getMimeType(), Data::VERBATIM);
			} else {
				att.compound["mimetype"] = Data("application/octet-stream", Data::VERBATIM);
			}

			std::stringstream filenameSS;
			filenameSS << "attachment" << attachments.size() + 1;
			if (boost::starts_with(att.compound["mimetype"].atom, "text")) {
				filenameSS << ".txt";
			} else {
				filenameSS << ".bin";
			}
			att.compound["filename"] = Data(filenameSS.str(), Data::VERBATIM);

			attachments.push_back(att);

		} else if (data.compound.size() > 0) {
			// data is some compound, descent to find attachment structures or binaries
			std::map<std::string, Data>::const_iterator compIter = data.compound.begin();
			while(compIter != data.compound.end()) {
				std::list<Data> tmp;
				tmp.push_back(compIter->second);
				getAttachments(tmp, attachments);
				compIter++;
			}
		} else if (data.array.size() > 0) {
			// descent into array
			getAttachments(data.array, attachments);
		}
		iter++;
	}
}

void SMTPInvoker::send(const SendRequest& req) {
	if (iequals(req.name, "mail.send")) {

		struct curl_slist* recipients = NULL;
		CURLcode curlError;
		std::string multipartSep;

		bool verbose;
		std::string from;
		std::string subject;
		std::string contentType;
		std::list<Data> headerParams;
		std::list<Data> toParams;
		std::list<Data> ccParams;
		std::list<Data> bccParams;
		std::list<Data> attachmentParams;

		Event::getParam(req.params, "verbose", verbose);
		Event::getParam(req.params, "Content-Type", contentType);
		Event::getParam(req.params, "attachment", attachmentParams);
		Event::getParam(req.params, "from", from);
		Event::getParam(req.params, "subject", subject);
		Event::getParam(req.params, "header", headerParams);
		Event::getParam(req.params, "to", toParams);
		Event::getParam(req.params, "cc", ccParams);
		Event::getParam(req.params, "bcc", bccParams);

		if (contentType.size() == 0)
			contentType = "text/plain; charset=\"UTF-8\"";

		SMTPContext* ctx = new SMTPContext();
		std::stringstream contentSS;

		std::list<std::string>::const_iterator recIter;
		std::list<std::string> to = getAtoms(toParams);
		std::list<std::string> cc = getAtoms(ccParams);
		std::list<std::string> bcc = getAtoms(bccParams);
		std::list<std::string> headers = getAtoms(headerParams);
		std::list<Data> attachments;
		getAttachments(attachmentParams, attachments);

		if (to.size() == 0)
			return;

		recIter = to.begin();
		recIter++; // skip first as we need it in CURLOPT_MAIL_RCPT
		while(recIter != to.end()) {
			contentSS << "TO: " << *recIter << std::endl;
			recIter++;
		}
		recIter = cc.begin();
		while(recIter != cc.end()) {
			contentSS << "CC: " << *recIter << std::endl;
			recIter++;
		}
		recIter = bcc.begin();
		while(recIter != bcc.end()) {
			contentSS << "BCC: " << *recIter << std::endl;
			recIter++;
		}

		recIter = headers.begin();
		while(recIter != headers.end()) {
			contentSS << *recIter << std::endl;
			recIter++;
		}

		if (subject.length() > 0) {
			boost::replace_all(subject, "\n\r", " ");
			boost::replace_all(subject, "\r\n", " ");
			boost::replace_all(subject, "\n", " ");
			boost::replace_all(subject, "\r", " ");
			contentSS << "Subject: " << subject << "\n";
		}

		// content type is different when we have attachments
		if (attachments.size() > 0) {
			multipartSep = UUID::getUUID();
			boost::replace_all(multipartSep, "-", "");
			contentSS << "Content-Type: multipart/mixed; boundary=\"" << multipartSep << "\"\n";
			contentSS << "MIME-Version: 1.0\n";
			contentSS << "\n";
			contentSS << "--" << multipartSep << "\n";
			contentSS << "Content-Type: " << contentType << "\n";
		} else {
			// when we have no attachment, respect user-defined or use text/plain
			contentSS << "Content-Type: " << contentType << "\n";
		}

		contentSS << "\n";
		contentSS << req.content;

		std::list<Data>::iterator attIter = attachments.begin();
		while(attIter != attachments.end()) {
			// only send valid attachments
			if(!attIter->hasKey("filename") || !attIter->hasKey("mimetype") || !attIter->hasKey("data")) {
				LOG(ERROR) << "Not sending attachment as filename, mimetype or data is missing: " << *attIter;
			} else {
				contentSS << "\n\n";
				contentSS << "--" << multipartSep << "\n";
				contentSS << "Content-Disposition: attachment; filename=\"" << attIter->compound["filename"].atom << "\"";
				contentSS << "\n";

				contentSS << "Content-Type: " << attIter->compound["mimetype"].atom << "; ";
				contentSS << "name=\"" << attIter->compound["filename"].atom << "\"";
				contentSS << "\n";

				if (attIter->compound["data"].binary) {
					contentSS << "Content-Transfer-Encoding: base64";
					contentSS << "\n\n";
					contentSS << attIter->compound["data"].binary.base64();
				} else {
					contentSS << "Content-Transfer-Encoding: 7Bit";
					contentSS << "\n\n";
					contentSS << attIter->compound["data"].atom;
				}
			}
			attIter++;
		}

		ctx->content = contentSS.str();
		ctx->invoker = this;

		// see http://curl.haxx.se/libcurl/c/smtp-tls.html
		_curl = curl_easy_init();
		if(_curl) {
			(curlError = curl_easy_setopt(_curl, CURLOPT_USERNAME, _username.c_str())) == CURLE_OK ||
			LOG(ERROR) << "Cannot set username: " << curl_easy_strerror(curlError);
			(curlError = curl_easy_setopt(_curl, CURLOPT_PASSWORD, _password.c_str())) == CURLE_OK ||
			LOG(ERROR) << "Cannot set password: " << curl_easy_strerror(curlError);
			(curlError = curl_easy_setopt(_curl, CURLOPT_URL, _server.c_str())) == CURLE_OK ||
			LOG(ERROR) << "Cannot set server string: " << curl_easy_strerror(curlError);
			(curlError = curl_easy_setopt(_curl, CURLOPT_USE_SSL, (long)CURLUSESSL_ALL)) == CURLE_OK ||
			LOG(ERROR) << "Cannot use SSL: " << curl_easy_strerror(curlError);

			// this is needed, even if we have a callback function
			recipients = curl_slist_append(recipients, to.begin()->c_str());
			(curlError = curl_easy_setopt(_curl, CURLOPT_MAIL_RCPT, recipients)) == CURLE_OK ||
			LOG(ERROR) << "Cannot set mail recipient: " << curl_easy_strerror(curlError);

			(curlError = curl_easy_setopt(_curl, CURLOPT_READFUNCTION, SMTPInvoker::writeCurlData)) == CURLE_OK ||
			LOG(ERROR) << "Cannot register read function: " << curl_easy_strerror(curlError);
			(curlError = curl_easy_setopt(_curl, CURLOPT_READDATA, ctx)) == CURLE_OK ||
			LOG(ERROR) << "Cannot register userdata for read function: " << curl_easy_strerror(curlError);
			(curlError = curl_easy_setopt(_curl, CURLOPT_UPLOAD, 1L)) == CURLE_OK ||
			LOG(ERROR) << "Cannot set upload parameter: " << curl_easy_strerror(curlError);

#if 1
			(curlError = curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, 0L)) == CURLE_OK ||
			LOG(ERROR) << "Cannot unset verify peer with SSL: " << curl_easy_strerror(curlError);
			(curlError = curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYHOST, 0L)) == CURLE_OK ||
			LOG(ERROR) << "Cannot unset verify host with SSL: " << curl_easy_strerror(curlError);
#else
			(curlError = curl_easy_setopt(_curl, CURLOPT_CAINFO, "/path/to/certificate.pem")) == CURLE_OK ||
			LOG(ERROR) << "Cannot set CA info path: " << curl_easy_strerror(curlError);
#endif

			if (from.length() > 0) {
				(curlError = curl_easy_setopt(_curl, CURLOPT_MAIL_FROM, from.c_str())) == CURLE_OK ||
				LOG(ERROR) << "Cannot set from parameter: " << curl_easy_strerror(curlError);
			}

			if (verbose) {
				(curlError = curl_easy_setopt(_curl, CURLOPT_VERBOSE, 1L)) == CURLE_OK ||
				LOG(ERROR) << "Cannot set curl to verbose: " << curl_easy_strerror(curlError);
			}

			CURLcode res = curl_easy_perform(_curl);

			/* Check for errors */
			if(res != CURLE_OK) {
				LOG(ERROR) << "curl_easy_perform() failed: " << curl_easy_strerror(res);
				returnErrorExecution("error.mail.send");
			} else {
				returnErrorExecution("success.mail.send");
			}
			/* Free the list of recipients */
			if (recipients)
				curl_slist_free_all(recipients);

			/* Always cleanup */
			curl_easy_cleanup(_curl);

		}

	}
}

void SMTPInvoker::cancel(const std::string sendId) {
}

void SMTPInvoker::invoke(const InvokeRequest& req) {
	Event::getParam(req.params, "username", _username);
	Event::getParam(req.params, "password", _password);
	Event::getParam(req.params, "server", _server);
}

}

max_stars_repo_name: sradomski/uscxml

max_issues_repo_name: sradomski/uscxml

max_forks_repo_name: sradomski/uscxml


text:
#include <stan/math/fwd/scal.hpp>
#include <gtest/gtest.h>
#include <boost/math/special_functions/digamma.hpp>
#include <math/fwd/scal/fun/nan_util.hpp>

TEST(AgradFwdLogFallingFactorial, Fvar) {
  using boost::math::digamma;
  using stan::math::fvar;
  using stan::math::log_falling_factorial;

  fvar<double> a(4.0, 1.0);
  fvar<double> x = log_falling_factorial(a, 2);
  EXPECT_FLOAT_EQ(std::log(12.0), x.val_);
  EXPECT_FLOAT_EQ((boost::math::digamma(5) - boost::math::digamma(3)), x.d_);

  // finite diff
  double eps = 1e-6;
  EXPECT_FLOAT_EQ((stan::math::log_falling_factorial(4.0 + eps, 2.0)
                   - stan::math::log_falling_factorial(4.0 - eps, 2.0))
                      / (2 * eps),
                  x.d_);

  fvar<double> c(-3.0, 2.0);

  EXPECT_THROW(log_falling_factorial(c, 2), std::domain_error);
  EXPECT_THROW(log_falling_factorial(c, c), std::domain_error);

  x = log_falling_factorial(a, a);
  EXPECT_FLOAT_EQ(std::log(24.0), x.val_);
  EXPECT_FLOAT_EQ(boost::math::digamma(5), x.d_);

  x = log_falling_factorial(5, a);
  EXPECT_FLOAT_EQ(std::log(120.0), x.val_);
  EXPECT_FLOAT_EQ(digamma(2.0), x.d_);

  // finite diff
  EXPECT_FLOAT_EQ((stan::math::log_falling_factorial(5.0, 4.0 + eps)
                   - stan::math::log_falling_factorial(5.0, 4.0 - eps))
                      / (2 * eps),
                  x.d_);
}

TEST(AgradFwdLogFallingFactorial, FvarFvarDouble) {
  using stan::math::fvar;
  using stan::math::log_falling_factorial;

  fvar<fvar<double> > x;
  x.val_.val_ = 4.0;
  x.val_.d_ = 1.0;

  fvar<fvar<double> > y;
  y.val_.val_ = 3.0;
  y.d_.val_ = 1.0;

  fvar<fvar<double> > a = log_falling_factorial(x, y);

  EXPECT_FLOAT_EQ(3.1780539, a.val_.val_);
  EXPECT_FLOAT_EQ(1.0833334, a.val_.d_);
  EXPECT_FLOAT_EQ(0.42278433, a.d_.val_);
  EXPECT_FLOAT_EQ(0.64493406, a.d_.d_);
}

struct log_falling_factorial_fun {
  template <typename T0, typename T1>
  inline typename boost::math::tools::promote_args<T0, T1>::type operator()(
      const T0 arg1, const T1 arg2) const {
    return log_falling_factorial(arg1, arg2);
  }
};

TEST(AgradFwdLogFallingFactorial, nan_0) {
  log_falling_factorial_fun log_falling_factorial_;
  test_nan_fwd(log_falling_factorial_, 3.0, 5.0, false);
}

max_stars_repo_name: alashworth/stan-monorepo

max_issues_repo_name: alashworth/stan-monorepo

max_forks_repo_name: alashworth/stan-monorepo