text:
/***********************************************************************************************************************
* Copyright (c) Hands Free Team. All rights reserved.
* FileName: hf_link.cpp
* Contact:  QQ Exchange Group -- 521037187
* Version:  V2.0
*
* LICENSING TERMS:
* The Hands Free is licensed generally under a permissive 3-clause BSD license.
* Contributions are required to be made under the same license.
*
* History:
* <author>      <time>      <version>      <desc>
* luke liao       2015.10.1   V1.0           creat this file
*
* Description: send the robot speed and publish odom directly through specific hardware interface
***********************************************************************************************************************/

#include <base_simple_controller.h>

#include <boost/assign.hpp>

#include <tf/transform_datatypes.h>

namespace base_simple_controller {

BaseSimpleController::BaseSimpleController()
: cmd_()
, base_frame_id_("base_link")
, cmd_vel_timeout_(0.5)
, base_name_("mobile_base")
{}

bool BaseSimpleController::init(hardware_interface::BaseVelocityInterface* hw,
		ros::NodeHandle& root_nh,
		ros::NodeHandle &controller_nh)
{
	last_x_ = last_y_ = last_theta_ = 0.0;
	const std::string complete_ns = controller_nh.getNamespace();
	std::size_t id = complete_ns.find_last_of("/");
	name_ = complete_ns.substr(id + 1);

	double publish_rate = 20.0;
	controller_nh.getParam("publish_rate", publish_rate);
	publish_period_ = ros::Duration(1.0 / publish_rate);
	last_vel_get_ = ros::Time::now();

	controller_nh.getParam("cmd_vel_timeout", cmd_vel_timeout_);
	controller_nh.getParam("base_frame_id", base_frame_id_);
	controller_nh.getParam("base_name", base_name_);

	handle_ = hw->getHandle(base_name_);

	odom_pub_.reset(new realtime_tools::RealtimePublisher<nav_msgs::Odometry>(controller_nh, "odom", 100));
	odom_pub_->msg_.header.frame_id = "odom";
	odom_pub_->msg_.child_frame_id = base_frame_id_;
	odom_pub_->msg_.pose.pose.position.z = 0;
	// TODO: fulfill the true parameters add the experience parameters
	odom_pub_->msg_.pose.covariance = boost::assign::list_of
		(0.001) (0)  (0)  (0)  (0)  (0)
		(0)  (0.001) (0)  (0)  (0)  (0)
		(0)  (0)  (1000000.0) (0)  (0)  (0)
		(0)  (0)  (0)  (1000000.0) (0)  (0)
		(0)  (0)  (0)  (0)  (1000000.0) (0)
		(0)  (0)  (0)  (0)  (0)  (1000.0);
	odom_pub_->msg_.twist.twist.linear.z  = 0;
	odom_pub_->msg_.twist.twist.angular.x = 0;
	odom_pub_->msg_.twist.twist.angular.y = 0;
	odom_pub_->msg_.pose.covariance = boost::assign::list_of
			(0.001) (0)  (0)  (0)  (0)  (0)
			(0)  (0.001) (0)  (0)  (0)  (0)
			(0)  (0)  (1000000.0) (0)  (0)  (0)
			(0)  (0)  (0)  (1000000.0) (0)  (0)
			(0)  (0)  (0)  (0)  (1000000.0) (0)
			(0)  (0)  (0)  (0)  (0)  (1000.0);
	//TODO: add the convarience matrix to the omni base
	tf_odom_pub_.reset(new realtime_tools::RealtimePublisher<tf::tfMessage>(root_nh, "/tf", 100));
	tf_odom_pub_->msg_.transforms.resize(1);
	tf_odom_pub_->msg_.transforms[0].transform.translation.z = 0.0;
	tf_odom_pub_->msg_.transforms[0].child_frame_id = base_frame_id_;
	tf_odom_pub_->msg_.transforms[0].header.frame_id = "odom";

	cmd_vel_sub_ = controller_nh.subscribe("cmd_vel",1 ,&BaseSimpleController::cmdvelCallBack, this);
	return true;
}

void BaseSimpleController::cmdvelCallBack(const geometry_msgs::Twist::ConstPtr &msg)
{
	if (isRunning())
	{
		command_buffer_.writeFromNonRT(*msg);
		last_vel_get_ = ros::Time::now();
	} else
	{
		ROS_ERROR_NAMED(name_, "Can't accept new commands. Controller is not running.");
	}
}

void BaseSimpleController::update(const ros::Time& time, const ros::Duration& period)
{
	if (last_state_publish_time_ + publish_period_ < time)
	{
		last_state_publish_time_ += publish_period_;

		const geometry_msgs::Quaternion orientation(
				tf::createQuaternionMsgFromYaw(handle_.getTheta()));
		if(odom_pub_->trylock())
		{
			odom_pub_->msg_.header.stamp = time;
			odom_pub_->msg_.pose.pose.position.x = handle_.getX();
			odom_pub_->msg_.pose.pose.position.y = handle_.getY();
			odom_pub_->msg_.pose.pose.orientation = orientation;
			odom_pub_->msg_.twist.twist.linear.x  = handle_.getXvel();
			odom_pub_->msg_.twist.twist.linear.y  = handle_.getYvel();
			odom_pub_->msg_.twist.twist.angular.z = handle_.getThetavel();
			odom_pub_->unlockAndPublish();

		}

		// Publish tf /odom frame
		if (tf_odom_pub_->trylock())
		{
			geometry_msgs::TransformStamped& odom_frame = tf_odom_pub_->msg_.transforms[0];
			odom_frame.header.stamp = time;
			odom_frame.transform.translation.x = handle_.getX();
			odom_frame.transform.translation.y = handle_.getY();
			odom_frame.transform.rotation = orientation;
			tf_odom_pub_->unlockAndPublish();
		}
	}

	geometry_msgs::Twist temp;
	temp = *(command_buffer_.readFromRT());
	if ((time - last_vel_get_).toSec() > cmd_vel_timeout_)
	{
		// stop the robot first
		handle_.setXcmd(0.0);
		handle_.setYcmd(0.0);
		handle_.setThetacmd(0.0);
	} else
	{
		handle_.setXcmd(temp.linear.x);
		handle_.setYcmd(temp.linear.y);
		handle_.setThetacmd(temp.angular.z);
	}
}

void BaseSimpleController::starting(const ros::Time& time)
{
	// stop the robot first
	handle_.setXcmd(0.0);
	handle_.setYcmd(0.0);
	handle_.setThetacmd(0.0);

	last_state_publish_time_ = time;

#if ROS_VERSION_MINOR < 15
	state_ = RUNNING;
#else
    state_ = ControllerState::RUNNING;
#endif

}

void BaseSimpleController::stopping(const ros::Time& time)
{
	// stop the robot
	handle_.setXcmd(0.0);
	handle_.setYcmd(0.0);
	handle_.setThetacmd(0.0);
}

}

max_stars_repo_name: HANDS-FREE/handsfree

max_issues_repo_name: HANDS-FREE/handsfree

max_forks_repo_name: HANDS-FREE/handsfree


text:
/*
    Copyright (c) 2019 Xavier Leclercq

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
    IN THE SOFTWARE.
*/

#include "BeastSession.h"
#include "BeastServer.h"
#include <boost/asio/bind_executor.hpp>

namespace Nemu
{

BeastSession::BeastSession(BeastServer& server, boost::asio::ip::tcp::socket&& socket)
    : m_server(server), m_socket(std::move(socket))/*, m_strand(m_socket.get_executor())*/, m_response(server.views())
{
    boost::asio::make_strand(m_socket.get_executor());
}

void BeastSession::run()
{
    read();
}

void BeastSession::handleRequest(BeastRequest&& request)
{
    m_response.initialize(request.request());

    const Route& route = m_server.routes().match(request.URI());
    route.runHandler(request, m_response);
    m_response.response().prepare_payload();

    std::string requestLine = request.request().method_string().to_string() + " "
        + request.request().target().to_string();
    if (request.request().version() == 11)
    {
        requestLine += " HTTP/1.1";
    }
    else
    {
        requestLine += " HTTP/1.0";
    }

    auto handler = boost::asio::bind_executor(m_strand,
        std::bind(&BeastSession::onWrite, shared_from_this(), std::placeholders::_1, std::placeholders::_2,
            m_response.response().need_eof()));

    m_server.accessLog().log(m_socket.remote_endpoint().address().to_string(), requestLine,
        m_response.response().result_int(), m_response.response().payload_size().value());

    boost::beast::http::async_write(m_socket, m_response.response(), handler);
}

void BeastSession::read()
{
    m_request = BeastRequest();

    auto handler = boost::asio::bind_executor(m_strand,
        std::bind(&BeastSession::onRead, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
    boost::beast::http::async_read(m_socket, m_buffer, m_request.request(), handler);
}

void BeastSession::onRead(boost::system::error_code ec, size_t bytesTransferred)
{
    if (!ec)
    {
        handleRequest(std::move(m_request));
    }
    else if (ec == boost::beast::http::error::end_of_stream)
    {
        return close();
    }
}

void BeastSession::onWrite(boost::system::error_code ec, size_t bytesTransferred, bool closed)
{
    if (closed)
    {
        close();
    }

    m_response.reset();

    read();
}

void BeastSession::close()
{
    boost::system::error_code ec;
    m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);

    const std::string& sourceAddress = m_socket.remote_endpoint().address().to_string() + ":" +
        std::to_string(m_socket.remote_endpoint().port());
    m_server.observers().notify(&Server::Observer::onConnectionClosed, m_server, sourceAddress);
}

}

ext: cpp

max_stars_repo_name: nemu-cpp/beast-networking-engine

max_issues_repo_name: nemu-cpp/beast-networking-engine

max_forks_repo_name: nemu-cpp/beast-networking-engine


text:
/**
 * @file
 * @brief Implementation of the make_QuadRuleNodal.
 * @author Raffael Casagrande
 * @date   2018-12-26 10:25:52
 * @copyright MIT License
 */

#include "make_quad_rule_nodal.h"
#include <boost/core/ref.hpp>

namespace lf::quad {
QuadRule make_QuadRuleNodal(base::RefEl ref_el) {
  double ref_el_vol = 1.0;
  if (ref_el == base::RefEl::kTria()) {
    ref_el_vol = 0.5;
  }
  return QuadRule(ref_el, ref_el.NodeCoords(),
                  Eigen::VectorXd::Constant(ref_el.NumNodes(),
                                            ref_el_vol / ref_el.NumNodes()),
                  1);
}
}  // namespace lf::quad

ext: cc

max_stars_repo_name: Pascal-So/lehrfempp

max_issues_repo_name: Pascal-So/lehrfempp

max_forks_repo_name: Pascal-So/lehrfempp


text:
#include "modules/mapred/resource_manager.h"
#include "modules/mapred/manifest.h"
#include "modules/mapred/name_generator.h"
#include "modules/io/config.h"
#include "modules/io/uuid.h"

#include <boost/filesystem.hpp>

#include <sys/file.h>
#include <sys/fcntl.h>
#include <sys/stat.h>

class mmap_readable : public reset_readable
{
public:
	mmap_readable(const char* buf, size_t size)
		: m_buf(buf)
		, m_size(size)
	{}

	void reset() override
	{
		m_offset = 0;
	}

	size_t read(char* buf, size_t len) override
	{
		len = std::min(len, m_size - m_offset);
		std::copy_n(m_buf + m_offset, len, buf);
		m_offset += len;
		return len;
	}

private:
	const char* m_buf;
	size_t m_size;
	size_t m_offset = 0;
};

resource_manager::resource_manager()
{
	path storage_root(CONF_S(storage_root));
	if (storage_root.type() == path::FILE) {
		m_direct = true;
	}
}

resource_manager::resource_manager(bool direct)
	: m_direct(direct)
{}

void resource_manager::create_resource(mmap_buffer& out, size_t size)
{
	path root(CONF_S(resources_root));
	root.mkdir();
	std::string dir = root.bare_path();
	auto id = make_uuid();
	std::string path = printstring("%s/%s", dir.c_str(), id.c_str());

	SPLOG_P(LOG_DEBUG, "resource_manager::create_resource> size = %lu, %s", size, path.c_str());

	if (!m_direct) {
		make_space(size);
	}

	out.open(path, size);
	out.set_uuid(id);
}

void resource_manager::write_resource(
	manifest& out,
	mmap_buffer& in,
	const path& root,
	const std::string& prefix,
	const progress_handler_t& progress)
{
	if (m_direct) {
		path root(CONF_S(path_bulkdata));
		root.mkdir();

		path src(in.path());
		path dest(root.append(in.get_uuid()));

		SPLOG_P(LOG_DEBUG, "resource_manager::write_resource> %s -> %s",
			src.bare_path().c_str(),
			dest.bare_path().c_str()
		);

		path::move(src, dest);

		file_info fi;
		fi.file = dest;
		fi.size = dest.size();
		fi.num_records = 0;
		out.add(fi, 0);
		progress(1.0);

		return;
	}

	SPLOG_P(LOG_DEBUG, "resource_manager::write_resource> %s", in.path().c_str());
	std::string pname = in.path();

	const size_t chunk_size = 64 * 1024 * 1024;
	int chunk_num = 0;
	for (size_t i = 0; i < in.size(); i += chunk_size) {
		progress(double(i) / double(in.size()));
		size_t cur_size = std::min(chunk_size, in.size() - i);
		mmap_readable mr(in.buffer() + i, cur_size);
		auto name = printstring("%s_%d", prefix.c_str(), chunk_num++);
		auto tmppath = root.append(printstring("%03ld_%s_%s",
			random() % 1000,
			make_uuid().c_str(),
			name.c_str())
		);
		tmppath.write_inverted(mr, cur_size)->wait();
		file_info fi;
		fi.file = tmppath;
		fi.size = cur_size;
		fi.num_records = 0;
		out.add(fi, 0);
	}
	out.metadata().set(meta::ns::internal, "resource_uuid", in.get_uuid());
	in.close();
	chmod(pname.c_str(), 0444);
	in.open(pname, mmap_buffer::mode::copy_on_write);
	progress(1.0);
}

static
void write_complete(int fd, const char* buf, size_t len)
{
	size_t offset = 0;
	while (offset < len) {
		ssize_t r = write(fd, buf + offset, len - offset);
		if (r < 0 && errno == EINTR) {
			continue;
		}
		if (r < 0) {
			throw io_exception("Error in write_complete");
		}
		offset += r;
	}
}

void resource_manager::read_resource(
	mmap_buffer& out,
	const manifest& in,
	const progress_handler_t& progress)
{
	if (m_direct) {
		auto first = in.begin();
		SPLOG_P(LOG_DEBUG, "resource_manager::read_resource> %s", first->file.bare_path().c_str());
		out.open(first->file.bare_path(), mmap_buffer::mode::copy_on_write);
		progress(1.0);
		return;
	}

	make_space(in.get_size());
	std::string uuid = in.metadata().get<std::string>(meta::ns::internal, "resource_uuid");
	auto dir = CONF_S(resources_root);
	std::string path = printstring("%s/%s", dir.c_str(), uuid.c_str());
	SPLOG_P(LOG_DEBUG, "resource_manager::read_resource> %s", path.c_str());
	// Make make/download resource
	while (true) {
		//SPLOG("Trying open");
		// TODO: Use a better file locking mechanism here. This scheme fails if the process
		// runs as root, since it can always open the file for writing.
		int fd = open(path.c_str(), O_RDWR | O_CREAT, 0664);
		if (fd < 0 && errno == EACCES) {
			SPLOG("resource_manager::read_resource> Open in write mode failed %s", path.c_str());
			break; // Probably alrady RO, give the mapping a try
		}
		if (fd < 0) {
			throw io_exception("resource_manager: Unable to create file"); // Otherwise, bad news
		}
		int r = flock(fd, LOCK_EX | LOCK_NB);
		if (r < 0 && errno == EWOULDBLOCK) {
			// Some else is downloading, try again
			SPLOG("resource_manager::read_resource> flock() failed %s", path.c_str());
			close(fd);
			progress(0.0);
			sleep(3);
			continue;
		}
		if (r < 0) {
			throw io_exception("resource_manager: Unable to lock file");
		}
		// I've got the lock, do the download
		SPLOG("resource_manager::read_resource> Loading data from manifest");
		manifest_reader mr(in);
		const size_t k_bufsize = 16*1024;
		char buf[k_bufsize];
		size_t tot_size = in.get_size();
		size_t cur_size = 0;
		while (true) {
			size_t r = mr.read(buf, k_bufsize);
			if (r == 0) {
				break;
			}
			write_complete(fd, buf, r);
			cur_size += r;
			progress(double(cur_size) / double(tot_size));
		}
		//SPLOG("Loaded the data, truncating\n");
		r = ftruncate(fd, tot_size);
		if (r < 0) {
			throw io_exception("resource_manager: Unable to truncate file");
		}
		// Mark read only (download done), and close
		//SPLOG("Changing mode");
		fchmod(fd, 0444);
		close(fd);
	}
	SPLOG_P(LOG_DEBUG, "resource_manager::read_resource> Doing RO open");
	out.open(path, mmap_buffer::mode::copy_on_write);
	progress(1.0);
}

size_t resource_manager::free_space()
{
	namespace fs = boost::filesystem;
	fs::path dir = CONF_S(resources_root);
	auto si = fs::space(dir);
	size_t slop = CONF_T(size_t, resource_quota_slop);
	if (si.available < slop) {
		return 0;
	}
	return si.available - slop;
}

void resource_manager::make_space(size_t space)
{
	namespace fs = boost::filesystem;
	try {
		fs::path dir = CONF_S(resources_root);
		fs::create_directory(dir);
		while (free_space() < space) {
			fs::path which;
			std::time_t oldest = std::numeric_limits<std::time_t>::max();
			for (auto it = fs::directory_iterator(dir); it != fs::directory_iterator(); ++it) {
				std::time_t last_write = fs::last_write_time(*it);
				if (last_write < oldest) {
					oldest = last_write;
					which = *it;
				}
			}
			if (which.empty()) {
				throw io_exception("No room for resource!");
			}
			fs::remove(which);
		}
	} catch (const fs::filesystem_error& err) {
		throw io_exception(std::string("Error during make_space: ") + err.what());
	}
}

max_stars_repo_name: spiralgenetics/biograph

max_issues_repo_name: spiralgenetics/biograph

max_forks_repo_name: spiralgenetics/biograph


text:
//
// Copyright Jason Rice 2017
// 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 <nbdl/entity.hpp>
#include <nbdl/match.hpp>
#include <nbdl/variant.hpp>

#include <boost/hana/equal.hpp>
#include <boost/hana/map.hpp>
#include <boost/hana/pair.hpp>
#include <boost/hana/string.hpp>
#include <boost/hana/tuple.hpp>
#include <catch.hpp>
#include <string>

namespace hana = boost::hana;
using namespace hana::literals;

namespace
{
  struct name_first_t { std::string value; };
  struct name_last_t { std::string value; };

  struct person_t
  {
    std::string name_first;
    std::string name_last;
  };
}

namespace nbdl
{
  NBDL_ENTITY(
    person_t
    , name_first
    , name_last
  );
}

TEST_CASE("Match on values in a hana::map.", "[match][Store]")
{
  std::string result("FAIL!");

  auto store = hana::make_map(
    hana::make_pair("key_1"_s, std::string("Hello, World!"))
  , hana::make_pair("key_2"_s, 42)
  );

  nbdl::match(
    store
  , "key_1"_s
  , [&](std::string const& x) { result = x; }
  );

  // Hello, World!

  CHECK(result == std::string{"Hello, World!"});
}

TEST_CASE("Match on values in a nbdl::Entity.", "[match][Store]")
{
  std::string result("FAIL!");

  auto store = person_t{"John", "Smith"};

  nbdl::match(
    store
  , "name_first"_s
  , [&](std::string const& x) { result = x; }
  );

  // John

  CHECK(result == std::string{"John"});
}

TEST_CASE("Match on values in a hana::tuple.", "[core]")
{
  std::string result_1("FAIL!");
  std::string result_2("FAIL!");

  auto store = hana::make_tuple(name_first_t{"John"}, name_last_t{"Smith"});

  nbdl::match(
    store
  , hana::type<name_first_t>{}
  , [&](name_first_t const& x) { result_1 = x.value; }
  );

  nbdl::match(
    store
  , hana::type<name_last_t>{}
  , [&](name_last_t const& x) { result_2 = x.value; }
  );

  CHECK(result_1 == std::string{"John"});
  CHECK(result_2 == std::string{"Smith"});
}

TEST_CASE("Match on values in a hana::Product.", "[core]")
{
  std::string result_1("FAIL!");
  std::string result_2("FAIL!");

  auto store = hana::make_pair(name_first_t{"John"}, name_last_t{"Smith"});

  nbdl::match(
    store
  , hana::first
  , [&](name_first_t const& x) { result_1 = x.value; }
  );

  nbdl::match(
    store
  , hana::second
  , [&](name_last_t const& x) { result_2 = x.value; }
  );

  CHECK(result_1 == std::string{"John"});
  CHECK(result_2 == std::string{"Smith"});
}

TEST_CASE("Match on values in a variant.", "[match][Store]")
{
  std::string result("FAIL!");

  nbdl::optional<std::string> store = std::string("Hello, maybe!");

  nbdl::match(
    store
  , [&](auto const& x)
    {
      if constexpr(hana::is_a<std::string, decltype(x)>)
        result = x;
    }
  );

  // Hello, maybe!

  CHECK(result == std::string{"Hello, maybe!"});
}

TEST_CASE("Match on values nested in a variant.", "[match][Store]")
{
  std::string result("FAIL!");

  nbdl::optional<person_t> store = person_t{"John", "Smith"};

  nbdl::match(
    store
  , "name_first"_s
  , [&](auto const& x)
    {
      if constexpr(hana::is_a<std::string, decltype(x)>)
        result = x;
    }
  );

  // John

  CHECK(result == std::string{"John"});
}

TEST_CASE("Match with visitor match_when", "[match]")
{
  auto store = hana::make_map(
    hana::make_pair(hana::type_c<int>, 5)
  , hana::make_pair(hana::type_c<char>, 'x')
  );

  {
    bool result = false;
    nbdl::match_when<int>(
      store
    , hana::type_c<int>
    , [&](auto x)
      {
        CHECK(x == 5);
        result = true;
      }
    );

    CHECK(result);
  }

  {
    bool result = false;
    nbdl::match(
      std::move(store)
    , hana::type_c<int>
    , nbdl::match_when<void>([&](auto&&) { result = true; })
    );

    CHECK(not result);
  }
}

TEST_CASE("Match nbdl::variant with visitor match_when", "[match]")
{
  auto store = nbdl::variant<int, float, double, char>{int{42}};

  {
    bool result = false;

    nbdl::match(
      store
    , nbdl::match_when<int>([&](auto x)
      {
        CHECK(x == 42);
        result = true;
      })
    );

    CHECK(result);
  }

  {
    bool result = false;

    nbdl::match_when<float>(
      store
    , [&](auto) { result = true; }
    );

    CHECK(not result);
  }

  { // something not on the list
    bool result = false;

    nbdl::match(
      std::move(store)
    , nbdl::match_when<void>([&](auto&&) { result = true; })
    );

    CHECK(not result);
  }
}

TEST_CASE("Match with vistor mapped_overload", "[match]")
{
  auto store = hana::make_map(
    hana::make_pair(hana::type_c<int>, int{82})
  , hana::make_pair(hana::type_c<char>, 'x')
  );

  {
    std::string result = "FAIL";

    nbdl::match(
      store
    , hana::type_c<int>
    , nbdl::mapped_overload(
        hana::make_map(
          hana::make_pair(hana::type_c<int>, [&](auto x)
          {
            CHECK(x == 82);
            result = "int";
          })
        , hana::make_pair(hana::type_c<float>, [&](auto) { result = "float"; })
        , hana::make_pair(hana::type_c<double>, [&](auto) { result = "double"; })
        )
      , [&](auto) { result = "otherwise"; }
      )
    );

    CHECK(result == "int");
  }

  {
    std::string result = "FAIL";

    nbdl::match(
      store
    , nbdl::mapped_overload(
        hana::make_map(
          hana::make_pair(hana::type_c<float>, [&](auto) { result = "float"; })
        , hana::make_pair(hana::type_c<double>, [&](auto) { result = "double"; })
        )
      , [&](auto) { result = "otherwise"; }
      )
    );

    CHECK(result == "otherwise");
  }
}

TEST_CASE("Match variant with vistor mapped_overload", "[match]")
{
  auto store = nbdl::variant<int, float, double, char>{int{101}};

  {
    std::string result = "FAIL";

    nbdl::match(
      store
    , nbdl::mapped_overload(
        hana::make_map(
          hana::make_pair(hana::type_c<int>, [&](auto x)
          {
            CHECK(x == 101);
            result = "int";
          })
        , hana::make_pair(hana::type_c<float>, [&](auto) { result = "float"; })
        , hana::make_pair(hana::type_c<double>, [&](auto) { result = "double"; })
        )
      , [&](auto) { result = "otherwise"; }
      )
    );

    CHECK(result == "int");
  }

  {
    std::string result = "FAIL";

    nbdl::match(
      store
    , nbdl::mapped_overload(
        hana::make_map(
          hana::make_pair(hana::type_c<float>, [&](auto) { result = "float"; })
        , hana::make_pair(hana::type_c<double>, [&](auto) { result = "double"; })
        )
      , [&](auto) { result = "otherwise"; }
      )
    );

    CHECK(result == "otherwise");
  }
}

max_stars_repo_name: ricejasonf/nbdl

max_issues_repo_name: ricejasonf/nbdl

max_forks_repo_name: ricejasonf/nbdl


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

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_IF_ZERO_ELSE_HPP_INCLUDED
#define BOOST_SIMD_ARCH_COMMON_SIMD_FUNCTION_IF_ZERO_ELSE_HPP_INCLUDED
#include <boost/simd/detail/overload.hpp>

#include <boost/simd/meta/hierarchy/simd.hpp>
#include <boost/simd/meta/is_bitwise_logical.hpp>
#include <boost/simd/constant/zero.hpp>
#include <boost/simd/function/bitwise_andnot.hpp>
#include <boost/simd/function/genmask.hpp>

namespace boost { namespace simd { namespace ext
{
   namespace bd = boost::dispatch;
   namespace bs = boost::simd;
   BOOST_DISPATCH_OVERLOAD_IF(if_zero_else_
                             , (typename A0, typename A1, typename X)
                             , (detail::is_native<X>)
                             , bd::cpu_
                             , bs::pack_<bd::unspecified_<A0>, X>
                             , bs::pack_<bd::arithmetic_<A1>, X>
                             )
   {
      using result = A1;
      template<typename A0_>
      typename enable_if< bs::is_bitwise_logical<A0_>, result>::type
        BOOST_FORCEINLINE operator()(A0_ const& a0, A1 const& a1) const
      {
        return bitwise_andnot(a1, genmask(a0));
      }
      template<typename A0_>
      typename disable_if< bs::is_bitwise_logical<A0_>, result>::type
        BOOST_FORCEINLINE operator()(A0_ const& a0, A1 const& a1) const
      {
        return if_else(a0, Zero<A1>(), a1);
      }
   };

} } }

#endif

ext: hpp

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
/*
 * Tree node obbox file
 *
 * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns)
 * See "SoftPixelEngine.hpp" for license information.
 */

#include "Base/spTreeNodeOBB.hpp"
#include "Base/spMathCollisionLibrary.hpp"

#include <boost/foreach.hpp>

namespace sp
{
namespace scene
{

OBBTreeNode::OBBTreeNode(OBBTreeNode* Parent, const dim::obbox3df &Box) :
    TreeNode    (Parent, TREENODE_OBBTREE   ),
    Box_        (Box                        )
{
}
OBBTreeNode::~OBBTreeNode()
{
    MemoryManager::deleteList(Children_);
}

u32 OBBTreeNode::getNumChildren() const
{
    if (!Children_.empty())
    {
        u32 Num = Children_.size();

        foreach (TreeNode* Node, Children_)
            Num += Node->getNumChildren();

        return Num;
    }
    return 0;
}

bool OBBTreeNode::isLeaf() const
{
    return Children_.empty();
}

const TreeNode* OBBTreeNode::findLeaf(const dim::vector3df &Point) const
{
    if (Box_.isPointInside(Point))
    {
        foreach (TreeNode* Node, Children_)
        {
            const TreeNode* Leaf = Node->findLeaf(Point);
            if (Leaf)
                return Leaf;
        }
        return this;
    }
    return 0;
}

void OBBTreeNode::findLeafList(std::list<const TreeNode*> &TreeNodeList, const dim::vector3df &Point, f32 Radius) const
{
    if (math::CollisionLibrary::getPointBoxDistanceSq(Box_, Point) < math::pow2(Radius))
    {
        if (!Children_.empty())
        {
            foreach (TreeNode* Node, Children_)
                Node->findLeafList(TreeNodeList, Point, Radius);
        }
        else
            TreeNodeList.push_back(this);
    }
}

void OBBTreeNode::findLeafList(std::list<const TreeNode*> &TreeNodeList, const dim::line3df &Line) const
{
    if (math::CollisionLibrary::checkLineBoxOverlap(InvBoxTransformation_ * Line, dim::aabbox3df::IDENTITY))
    {
        if (!Children_.empty())
        {
            foreach (TreeNode* Node, Children_)
                Node->findLeafList(TreeNodeList, Line);
        }
        else
            TreeNodeList.push_back(this);
    }
}

void OBBTreeNode::findLeafList(std::list<const TreeNode*> &TreeNodeList, const dim::line3df &Line, f32 Radius) const
{
    if (math::CollisionLibrary::getLineBoxDistanceSq(dim::aabbox3df::IDENTITY, InvBoxTransformation_ * Line) < math::pow2(Radius))
    {
        if (!Children_.empty())
        {
            foreach (TreeNode* Node, Children_)
                Node->findLeafList(TreeNodeList, Line, Radius);
        }
        else
            TreeNodeList.push_back(this);
    }
}

OBBTreeNode* OBBTreeNode::insertBoundingBox(const dim::obbox3df &Box)
{
    /* Check if the box can be inserted into this box */
    if (Box_.isBoxInside(Box))
    {
        /* Check if the box can be inserted into a child */
        foreach (TreeNode* Child, Children_)
        {
            if (Child->getType() == TREENODE_OBBTREE)
            {
                OBBTreeNode* Node = static_cast<OBBTreeNode*>(Child)->insertBoundingBox(Box);
                if (Node)
                    return Node;
            }
        }

        /* Create a new child */
        return createChild(Box);
    }
    return 0;
}

bool OBBTreeNode::insertBoundingBox(OBBTreeNode* Node)
{
    /* Check if the box can be inserted into this box */
    if (Node && Box_.isBoxInside(Node->getBox()))
    {
        /* Check if the box can be inserted into a child */
        foreach (TreeNode* Child, Children_)
        {
            if (Child->getType() == TREENODE_OBBTREE && static_cast<OBBTreeNode*>(Child)->insertBoundingBox(Node))
                return true;
        }

        /* Add to this children list */
        addChild(Node);

        return true;
    }
    return false;
}

void OBBTreeNode::setBox(const dim::obbox3df &Box)
{
    Box_ = Box;
    InvBoxTransformation_ = dim::matrix4f(Box_).getInverse();
}

void OBBTreeNode::update(bool UpdateChildren)
{
    /* Root nodes must not be updated */
    if (!Parent_ || Parent_->getType() != TREENODE_OBBTREE)
        return;

    OBBTreeNode* Parent = static_cast<OBBTreeNode*>(Parent_);

    if (UpdateChildren)
    {
        /* Check for each child if it's no longer inside this box and must be updated */
        for (std::list<TreeNode*>::iterator it = Children_.begin(); it != Children_.end();)
        {
            if ((*it)->getType() == TREENODE_OBBTREE && !Box_.isBoxInside(static_cast<OBBTreeNode*>(*it)->getBox()))
            {
                /* Exchange the child to the upper parent */
                Parent->addChild(static_cast<OBBTreeNode*>(*it));
                it = Children_.erase(it);
            }
            else
                ++it;
        }
    }

    /* Check if this box is still inside it's parent box */
    insertThisUpper(Parent);
}

/*
 * ======= Private: =======
 */

OBBTreeNode* OBBTreeNode::createChild(const dim::obbox3df &Box)
{
    return addChild(new OBBTreeNode(this, Box));
}

void OBBTreeNode::removeFromParent()
{
    if (Parent_ && Parent_->getType() == TREENODE_OBBTREE)
    {
        TreeNode* Child = this;
        MemoryManager::removeElement(static_cast<OBBTreeNode*>(Parent_)->Children_, Child);
    }
}

void OBBTreeNode::insertThisUpper(OBBTreeNode* Parent)
{
    if (Parent->getBox().isBoxInside(Box_))
    {
        /* Check if the box can be inserted into a parent's child */
        foreach (TreeNode* Child, Parent->Children_)
        {
            if (Child && Child != this && Child->getType() == TREENODE_OBBTREE &&
                static_cast<OBBTreeNode*>(Child)->insertBoundingBox(this))
            {
                removeFromParent();
                return;
            }
        }
    }
    else if (Parent->getParent() && Parent->getParent()->getType() == TREENODE_OBBTREE)
    {
        insertThisUpper(static_cast<OBBTreeNode*>(Parent->getParent()));
        return;
    }

    /* Check if this box must be inserted into the current parent */
    if (Parent != Parent_)
    {
        removeFromParent();
        Parent->addChild(this);
    }
}

} // /namespace scene

} // /namespace sp

// ================================================================================

max_stars_repo_name: rontrek/softpixel

max_issues_repo_name: rontrek/softpixel

max_forks_repo_name: rontrek/softpixel


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

    @copyright 2016 NumScale SAS

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

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!

    @ingroup group-operator
    This function object returns the elementwise unary minus of the parameter

    Infix notation can be used with operator '-'

    @par Header <boost/simd/function/unary_minus.hpp>

    @par Note:

    - `r = unary_minus(x)` is equivalent to  `r = -x` for SIMD types.

    @warningbox{Take care that the infix notation in scalar integral mode encurs
    a possible promotion of the type as C++ rules state.}

    @par Decorators
    - `saturated_` ensures that `saturated_(unary_minus)(Valmin<T>())` is `Valmin<T>()`

    @see  minus, unary_plus

    @par Example:

      @snippet unary_minus.cpp unary_minus

    @par Possible output:

      @snippet unary_minus.txt unary_minus

  **/
  Value unary_minus(Value const& x);
} }
#endif

#include <boost/simd/function/scalar/unary_minus.hpp>
#include <boost/simd/function/simd/unary_minus.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include <pxp-agent/module_cache_dir.hpp>
#include <pxp-agent/module.hpp>
#include <pxp-agent/util/purgeable.hpp>
#include <pxp-agent/util/bolt_helpers.hpp>
#include <pxp-agent/configuration.hpp>
#include <pxp-agent/time.hpp>

#include <leatherman/locale/locale.hpp>
#include <leatherman/file_util/file.hpp>
#include <leatherman/file_util/directory.hpp>
#include <boost/system/error_code.hpp>

#define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.pxp_agent.util.module_cache_dir"
#include <leatherman/logging/logging.hpp>

namespace fs          = boost::filesystem;
namespace pcp_util    = PCPClient::Util;
namespace lth_loc     = leatherman::locale;
namespace lth_file    = leatherman::file_util;
namespace boost_error = boost::system::errc;

namespace PXPAgent {
  ModuleCacheDir::ModuleCacheDir(const std::string& cache_dir,
                                 const std::string& cache_dir_purge_ttl) :
    cache_dir_ { cache_dir },
    purge_ttl_ { cache_dir_purge_ttl }
  {}

  // Creates the <cache_dir>/<sha256> directory (and parent dirs), ensuring that its permissions are readable by
  // the PXP agent owner/group (for unix OSes), writable for the PXP agent owner,
  // and executable by both PXP agent owner and group. Returns the path to this directory.
  // Note that the last modified time of the directory is updated, and that this routine
  // will not fail if the directory already exists.
  fs::path ModuleCacheDir::createCacheDir(const std::string& sha256) {
    pcp_util::lock_guard<pcp_util::mutex> the_lock { cache_dir_mutex_ };
    auto file_cache_dir = static_cast<fs::path>(cache_dir_) / sha256;
    try {
      Util::createDir(file_cache_dir);
      fs::last_write_time(file_cache_dir, time(nullptr));
    } catch (fs::filesystem_error& e) {
      auto err_code = e.code();
      if (err_code == boost_error::no_such_file_or_directory) {
          throw Module::ProcessingError(lth_loc::format("No such file or directory: {1}", e.path1()));
      } else {
          throw Module::ProcessingError(lth_loc::format("Failed to create cache dir {1} to download file to: {2}", file_cache_dir, e.what()));
      }
    }
    return file_cache_dir;
  }

  unsigned int ModuleCacheDir::purgeCache(const std::string& ttl,
                                          std::vector<std::string> ongoing_transactions,
                                          std::function<void(const std::string& dir_path)> purge_callback)
  {
    unsigned int num_purged_dirs { 0 };
    Timestamp ts { ttl };

    LOG_INFO("About to purge cached files from '{1}'; TTL = {2}",
        cache_dir_, ttl);

    lth_file::each_subdirectory(
      cache_dir_,
      // Lambda function
      [&](std::string const& sub_dir) -> bool {
        fs::path dir_path { sub_dir };
        LOG_TRACE("Inspecting '{1}' for purging", sub_dir);

        boost::system::error_code ec;
        pcp_util::lock_guard<pcp_util::mutex> the_lock { cache_dir_mutex_ };
        auto last_update = fs::last_write_time(dir_path, ec);
        if (ec) {
          LOG_ERROR("Failed to remove '{1}': {2}", sub_dir, ec.message());
        } else if (ts.isNewerThan(last_update)) {
          LOG_TRACE("Removing '{1}'", sub_dir);

          try {
            purge_callback(dir_path.string());
            num_purged_dirs++;
          } catch (const std::exception& e) {
            LOG_ERROR("Failed to remove '{1}': {2}", sub_dir, e.what());
          }
        }
        return true;  // Return from Lamda function passed to lth_file::each_subdirectory
      });

    LOG_INFO(lth_loc::format_n(
      // LOCALE: info
      "Removed {1} directory from '{2}'",
      "Removed {1} directories from '{2}'",
      num_purged_dirs, num_purged_dirs, cache_dir_));
    return num_purged_dirs;
  }
}  // PXPAgent

max_stars_repo_name: Dorin-Pleava/pxp-agent

max_issues_repo_name: Dorin-Pleava/pxp-agent

max_forks_repo_name: Dorin-Pleava/pxp-agent


text: #include <boost/geometry/arithmetic/normalize.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

#include <iostream>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <list>
#include <vector>
#include <map>
#include <exception>
#include <stdexcept>

#include <unistd.h>
#include <errno.h>
#include <getopt.h>
#include <stdlib.h>
#include <stdint.h>
#include <memory.h>
#include <pthread.h>
#include <sys/types.h>
#include <netinet/in.h>

#include <boost/shared_ptr.hpp>

#include "shared.h"

#include "onlvmbased_userdata.h"
#include "onlvmbased_session.h"
#include "onlvmbased_session_manager.h"
#include "onlvmbased_globals.h"
#include "onlvmbased_requests.h"
#include "onlvmbased_responses.h"

namespace onlvmbased
{
  dispatcher *the_dispatcher;
  nccp_listener *rli_conn;
  nccp_connection *spec_conn;
  session_manager *the_session_manager;

  bool using_spec_daemon;
  std::string user;
  bool testing;
  bool root_only;//set to true if specialty daemons are only run as root
};

using namespace onlvmbased;

int main(int argc, char** argv)
{
  the_dispatcher = dispatcher::get_dispatcher();
  the_session_manager = new session_manager();
  rli_conn = NULL;
  spec_conn = NULL;
  using_spec_daemon = false;
  user = "nobody";
  testing = false;

  static struct option longopts[] =
  {{"help",       0, NULL, 'h'},
   {"testing",    0, NULL, 't'},
   {"root_only",    0, NULL, 'r'},
   {NULL,         0, NULL,  0}
  };

  int c;
  while ((c = getopt_long(argc, argv, "htr", longopts, NULL)) != -1) {
    switch (c) {
      case 't':
        testing = true;
        break;
      case 'r':
	root_only = true;
	break;
      case 'h':
        std::cout << "usage: onlvmbased [-h] [-t] [-r]" << std::endl;
        std::cout << "       -h:       print this message" << std::endl;
        std::cout << "       -t:       run in testing mode, i.e., don't reboot on refresh" << std::endl;
        std::cout << "       -r:       only launch subtype daemons as root" << std::endl;
        exit(0);
    }
  }
  try
  {
    std::string tmp_addr("10.");
    rli_conn = new nccp_listener(tmp_addr, Default_ND_Port);
  }
  catch(std::exception& e)
  {
    write_log(e.what());
    exit(1);
  }

  register_req<start_experiment_req>(NCCP_Operation_StartExperiment);
  register_req<refresh_req>(NCCP_Operation_Refresh);

  register_req<user_data_req>(NCCP_Operation_UserData);
  register_req<user_data_ts_req>(NCCP_Operation_UserDataTS);

  register_req<configure_node_req>(NCCP_Operation_CfgNode);
  register_req<end_configure_node_req>(NCCP_Operation_EndCfgNode);
  //register_resp<crd_response>(NCCP_Operation_CfgNode);

  for(uint8_t op=64; op<=254; ++op)
  {
    register_req<rli_relay_req>(op);
    register_resp<rli_response>(op);
  }

  rli_conn->receive_messages(true);

  nccp_connection* crd_conn = NULL;
  i_am_up* upmsg = NULL;
  try
  {
    // cgw, read file to get crd host/port?
    //crd_conn = new nccp_connection("10.0.1.2", Default_CRD_Port);
    crd_conn = new nccp_connection("onlsrv", Default_CRD_Port);
    i_am_up* upmsg = new i_am_up();
    upmsg->set_connection(crd_conn);
    upmsg->send();
  }
  catch(std::exception& e)
  {
    write_log("main: warning: could not connect CRD");
  }
  if(upmsg) delete upmsg;
  if(crd_conn) delete crd_conn;

  while (true) { sleep(2); }
  pthread_exit(NULL);
}

max_stars_repo_name: WU-ARL/ONLdaemons

max_issues_repo_name: WU-ARL/ONLdaemons

max_forks_repo_name: WU-ARL/ONLdaemons


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

#ifndef ING_TEST_SOURCE_LOCATION
#define ING_TEST_SOURCE_LOCATION no_std
#define ING_NO_STD_SOURCE_LOCATION
#endif
#include <ing/source_location.hpp>

BOOST_AUTO_TEST_SUITE(ING_TEST_SOURCE_LOCATION)

BOOST_AUTO_TEST_CASE(current_source_location)
{
    ing::source_location macro = ING_CURRENT_LOCATION(); std::uint_least32_t line = __LINE__;
    const char* file = __FILE__;
    const char* function =
#ifdef ING_NO_STD_SOURCE_LOCATION
        BOOST_CURRENT_FUNCTION;
#else
        __func__;
#endif

    BOOST_TEST(macro.file_name() == file);
    BOOST_TEST(macro.line() == line);
    BOOST_TEST(macro.function_name() == function);
}

BOOST_AUTO_TEST_CASE(modified_source_location)
{
    ing::source_location modified = ING_CURRENT_LOCATION().function_name("custom").column(12u); std::uint_least32_t line = __LINE__;
    const char* file = __FILE__;

    BOOST_TEST(modified.file_name() == file);
    BOOST_TEST(modified.line() == line);
    BOOST_TEST(modified.function_name() == "custom");
    BOOST_TEST(modified.column() == 12u);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: huangqinjin/ing

max_issues_repo_name: huangqinjin/ing

max_forks_repo_name: huangqinjin/ing


text:
#ifndef FDM_HH
#define FDM_HH

#include <vector>
#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <Eigen/SparseLU>

#include "PDE.hh"

typedef std::vector<Eigen::VectorXd> matrix;

class FDMBase {
 protected:
  std::shared_ptr<BlackScholesPDE> pde;

  //Space domain [Nminus*dx,Nplus*dx]
  int long Nminus;
  int long Nplus;
  int long N;
  double dx;
  std::vector<double> x_values;

  //Time domain [0, 1/2*simga^2*T]
  unsigned long M;
  double dt;
  std::vector<double> tau_values;

  //coefficients
  double alpha;

  //initial vector;
  Eigen::VectorXd u0;

  //matrices
  Eigen::SparseMatrix<double, Eigen::RowMajor> A, I;

  // Constructor
  FDMBase(int _N , double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde);

  void calculate_step_sizes();
  void set_initial_conditions();
  void calculate_boundary_conditions(Eigen::VectorXd&, double);

 public:

  double get_dt()const{ return dt; }
  double get_dx()const{ return dx; }
  double get_alpha()const{ return alpha; }
  std::vector<double> get_x() const{ return x_values; }
  std::vector<double> get_tau() const{ return tau_values; }

  void BuildMatrix();
  void change_var(matrix&);
  virtual matrix solve() = 0;
};

class FDMEulerExplicit : public FDMBase {
 public:
  FDMEulerExplicit(int _N, double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde):
    FDMBase(_N, dx, _M, _pde){}

  matrix solve();
};

class FDMEulerImplicit : public FDMBase{
  public:
    FDMEulerImplicit(int _N, double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde):
      FDMBase(_N, dx, _M, _pde){}

    matrix solve();
};

class FDMCranckNicholson : public FDMBase{
public:
  FDMCranckNicholson(int _N, double dx, unsigned long _M, std::shared_ptr<BlackScholesPDE> _pde):
    FDMBase(_N, dx, _M, _pde){}

  matrix solve();
};

#endif

ext: hh

max_stars_repo_name: lorenzovitali/Progetto

max_issues_repo_name: lorenzovitali/Progetto

max_forks_repo_name: lorenzovitali/Progetto


text: #include <boost/range/algorithm/mismatch.hpp>


text:
#include "main.h"
#include "dot-editor-widget.h"
#include "wave-generator.h"
#include "wave-io.h"
#include "wave-io-dialog.h"
#include "new-wave-editor.h"
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QToolBar>
#include <QDoubleSpinBox>
#include <QLabel>
#include <QStatusBar>
#include <QAudioOutput>
#include <QFile>
#include <QDebug>
#include <boost/scope_exit.hpp>
#include <iostream>
#include <fstream>
#include <cmath>

int dotsize = 1;
int gridwidth = 1024;
int gridheight = 512;

int main(int argc, char *argv[]) {
  QApplication app(argc, argv);
  app.setApplicationName("Dessiner un son");

  prepare_audio();
  prepare_gui();

  return app.exec();
}

void prepare_gui() {
  QMainWindow *win = new QMainWindow;

  QMenuBar *mb = win->menuBar();
  QMenu *fileMenu = mb->addMenu("File");
  QAction *actGenerate = fileMenu->addAction(QIcon::fromTheme("document-new"), "Generate &new...");
  actGenerate->setShortcut(QKeySequence("Ctrl+N"));
  QAction *actOpen = fileMenu->addAction(QIcon::fromTheme("document-open"), "&Open");
  actOpen->setShortcut(QKeySequence("Ctrl+O"));
  QAction *actSave = fileMenu->addAction(QIcon::fromTheme("document-save"), "&Save");
  actSave->setShortcut(QKeySequence("Ctrl+S"));

  QToolBar *tb = new QToolBar;
  win->addToolBar(tb);

  QAction *actSmooth = tb->addAction("Smooth");
  QDoubleSpinBox *valSmooth = new QDoubleSpinBox;
  valSmooth->setRange(0.05, 1);
  valSmooth->setSingleStep(0.05);
  valSmooth->setValue(0.8);
  tb->addWidget(valSmooth);
  tb->addSeparator();

  QAction *actWindow = tb->addAction("Window");
  QDoubleSpinBox *valWindow = new QDoubleSpinBox;
  valWindow->setRange(0.05, 1);
  valWindow->setSingleStep(0.05);
  valWindow->setValue(0.5);
  tb->addWidget(valWindow);
  tb->addSeparator();

  tb->addWidget(new QLabel("Shift"));
  QAction *actShiftL2 = tb->addAction("↞");
  QAction *actShiftL1 = tb->addAction("←");
  QAction *actShiftR1 = tb->addAction("→");
  QAction *actShiftR2 = tb->addAction("↠");
  tb->addSeparator();

  tb->addWidget(new QLabel("Mirror"));
  QAction *actMirrorRToL = tb->addAction("⥒");
  QAction *actMirrorLToR = tb->addAction("⥓");
  tb->addSeparator();

  tb->addWidget(new QLabel("Invert"));
  QAction *actInvertL = tb->addAction("Left");
  QAction *actInvertR = tb->addAction("Right");
  tb->addSeparator();

  tb->addWidget(new QLabel("Sound"));
  QAction *actSoundPlay = tb->addAction("Play");
  QAction *actSoundStop = tb->addAction("Stop");
  QDoubleSpinBox *valSoundFreq = new QDoubleSpinBox;
  valSoundFreq->setRange(10.0, 8000.0);
  valSoundFreq->setSingleStep(10.0);
  valSoundFreq->setValue(220.0);
  tb->addWidget(valSoundFreq);
  tb->addSeparator();

  BasicDotEditorWidget *editor;
  if (dotsize > 1)
    editor = new DotEditorWidget(gridwidth, gridheight, dotsize);
  else
    editor = new CompactDotEditorWidget(gridwidth, gridheight);
  editor->initialize();
  win->setCentralWidget(editor);

  QStatusBar *statusBar = new QStatusBar;
  win->setStatusBar(statusBar);

  QObject::connect(actSave, &QAction::triggered,
                   editor, [editor]() { save_wavedata(editor->dotData()); });
  QObject::connect(actOpen, &QAction::triggered,
                   editor, [editor]() {
                     std::vector<double> &dotdata = editor->dotData();
                     if (load_wavedata(dotdata))
                       editor->update();
                   });
  QObject::connect(actGenerate, &QAction::triggered,
                   editor, [editor]() {
                               std::vector<double> &dotdata = editor->dotData();
                               if (gen_wavedata(dotdata))
                                   editor->update();
                           });

  QObject::connect(actSmooth, &QAction::triggered,
                   editor, [editor, valSmooth]() { editor->smooth(valSmooth->value()); });

  QObject::connect(actWindow, &QAction::triggered,
                   editor, [editor, valWindow]() { editor->window(valWindow->value()); });

  QObject::connect(actShiftL2, &QAction::triggered,
                   editor, [editor]() { editor->shiftData(-5); });
  QObject::connect(actShiftL1, &QAction::triggered,
                   editor, [editor]() { editor->shiftData(-1); });
  QObject::connect(actShiftR1, &QAction::triggered,
                   editor, [editor]() { editor->shiftData(+1); });
  QObject::connect(actShiftR2, &QAction::triggered,
                   editor, [editor]() { editor->shiftData(+5); });

  QObject::connect(actMirrorRToL, &QAction::triggered,
                   editor, [editor]() { editor->mirror(DotEditorWidget::MirRightToLeft); });
  QObject::connect(actMirrorLToR, &QAction::triggered,
                   editor, [editor]() { editor->mirror(DotEditorWidget::MirLeftToRight); });

  QObject::connect(actInvertL, &QAction::triggered,
                   editor, [editor]() { editor->invert(DotEditorWidget::LeftSide); });
  QObject::connect(actInvertR, &QAction::triggered,
                   editor, [editor]() { editor->invert(DotEditorWidget::RightSide); });

  QObject::connect(editor, &DotEditorWidget::hoveredGridCoord,
                   statusBar, [statusBar](QPoint gridpoint) {
                     QString status = QString("X %0 Y %1")
                       .arg(gridpoint.x(), -8).arg(gridpoint.y(), -8);
                     statusBar->showMessage(status);
                   });

  QObject::connect(actSoundPlay, &QAction::triggered,
                   ::audio_out, [editor, valSoundFreq]() {
                     ::audio_out->stop();
                     ::wave_generator->setWavetable(editor->dotData());
                     ::wave_generator->setFrequency(valSoundFreq->value());
                     ::audio_out->start(::wave_generator);
                   });
  QObject::connect(actSoundStop, &QAction::triggered,
                   ::audio_out, []() { ::audio_out->stop(); });
  QObject::connect(valSoundFreq, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged),
                   ::audio_out, [](double value) { ::wave_generator->setFrequency(value); });

  win->show();
}

QAudioFormat audio_format;
QAudioOutput *audio_out;
WaveGenerator *wave_generator;

void prepare_audio() {
  QAudioDeviceInfo info = QAudioDeviceInfo::defaultOutputDevice();
  audio_format = info.preferredFormat();
  audio_format.setChannelCount(1);
  audio_format.setSampleSize(8 * sizeof(float));
  audio_format.setCodec("audio/pcm");
  audio_format.setSampleType(QAudioFormat::Float);

  audio_out = new QAudioOutput(info, audio_format);
  std::cerr << "audio sampling rate is " << audio_format.sampleRate() << "\n";
  std::cerr << "audio buffer size is " << ::audio_out->bufferSize() << "\n";

  double attenuation = -20.0;
  audio_out->setVolume(std::pow(10.0, attenuation * 0.05));

  ::wave_generator = new WaveGenerator(audio_out);
  ::wave_generator->start(::audio_out->bufferSize(), ::audio_format.sampleRate());
}

bool save_wavedata(const std::vector<double> &wavedata) {
  WaveSaveDialog *dlg = new WaveSaveDialog;
  BOOST_SCOPE_EXIT(dlg) { delete dlg; } BOOST_SCOPE_EXIT_END;

  if (dlg->exec() != WaveSaveDialog::Accepted)
    return true;

  QString outfilename = dlg->waveFilename();
  if (outfilename.isEmpty())
    return true;

  int outsize = dlg->waveOutputSize();
  WaveFormat outfmt = WaveFormat(dlg->waveOutputFormat());
  WaveDataType outtype = WaveDataType(dlg->waveOutputDataType());

  std::vector<float> fdata(wavedata.begin(), wavedata.end());
  std::ofstream out(outfilename.toStdString(), std::ios::binary);
  write_wave(fdata.data(), fdata.size(), outsize, outfmt, outtype, out);
  out.flush();

  if (!out) {
    QFile::remove(outfilename);
    return false;
  }

  return true;
}

bool load_wavedata(std::vector<double> &wavedata) {
  WaveOpenDialog *dlg = new WaveOpenDialog;
  BOOST_SCOPE_EXIT(dlg) { delete dlg; } BOOST_SCOPE_EXIT_END;

  if (dlg->exec() != WaveOpenDialog::Accepted)
    return true;

  QString infilename = dlg->waveFilename();
  if (infilename.isEmpty())
    return true;

  WaveFormat infmt = WaveFormat(dlg->waveInputFormat());
  unsigned inchannel = dlg->waveInputChannel();

  std::ifstream in(infilename.toStdString(), std::ios::binary);
  std::vector<float> fdata(wavedata.begin(), wavedata.end());
  if (!read_wave_from_stream(fdata.data(), fdata.size(), in, infmt, inchannel))
    return false;

  wavedata.assign(fdata.begin(), fdata.end());
  return true;
}

bool gen_wavedata(std::vector<double> &wavedata)
{
    NewWaveEditor waveEd;
    bool update = false;

    auto update_dotdata =
        [&] {
            std::vector<float> in_samples(waveEd.waveData(), waveEd.waveData() + waveEd.waveSize());
            std::unique_ptr<float[]> out_samples(new float[wavedata.size()]);

            resample(in_samples.data(), in_samples.size(),
                     out_samples.get(), wavedata.size());

            wavedata.assign(&out_samples[0], &out_samples[wavedata.size()]);

            update = true;
        };

    QObject::connect(&waveEd, &NewWaveEditor::editingFinished, &waveEd, update_dotdata);

    if (waveEd.exec() == QDialog::Accepted)
        update_dotdata();

    return update;
}

max_stars_repo_name: jpcima/dessiner-un-son

max_issues_repo_name: jpcima/dessiner-un-son

max_forks_repo_name: jpcima/dessiner-un-son


text:
#include <exception>
#include <unordered_set>
#include <yaml-cpp/yaml.h>
#include <boost/uuid/uuid.hpp>
#include "third-party/cxxopts.hpp"
#include "third-party/aixlog.hpp"
#include "server.h"

using namespace boost;
using namespace boost::asio;

int main(int argc, char **argv) {
    cxxopts::Options options("4over6_server", "Server side of 4over6 tunnel");
    options.add_options()
            ("d,debug", "Enable debugging", cxxopts::value<bool>()->default_value("false"))
            ("c,conf", "File name", cxxopts::value<std::string>())
            ("v,verbose", "Verbose output", cxxopts::value<bool>()->default_value("false"))
            ("h,help", "Print usage");
    auto default_log_sink = AixLog::Log::init<AixLog::SinkCout>(AixLog::Severity::trace, AixLog::Type::all);
    try {
        auto result = options.parse(argc, argv);
        bool help = result.count("help");
        if(result.count("conf") == 0) {
            help = true;
            LOG_WARN("Please provide configuration file.");
        }
        if (help) {
            std::cout << options.help() << std::endl;
            exit(0);
        }
        if (!result["debug"].as<bool>()) default_log_sink->severity = AixLog::Severity::info;
        if (!result["verbose"].as<bool>()) default_log_sink->set_type(AixLog::Type::normal);
        // parse config
        YAML::Node config = YAML::LoadFile(result["conf"].as<std::string>());

        // pool range
        std::string address_range = config["address_range"].as<std::string>();
        auto pos = address_range.find('-');
        std::string start_addr = address_range.substr(0, pos);
        std::string end_addr = address_range.substr(pos + 1);
        // gateway, dns, ...
        ip::address_v4 gateway = ip::address_v4::from_string(config["gateway"].as<std::string>());
        ip::address_v4 dns_0 = ip::address_v4::from_string(config["dns0"].as<std::string>());
        ip::address_v4 dns_1 = ip::address_v4::from_string(config["dns1"].as<std::string>());
        ip::address_v4 dns_2 = ip::address_v4::from_string(config["dns2"].as<std::string>());
        ip::address_v4 netmask = ip::address_v4::from_string(config["netmask"].as<std::string>());

        ConfigPayload server_conf{"", gateway.to_string(), netmask.to_string(),
                                  {dns_0.to_string(), dns_1.to_string(), dns_2.to_string()}, {0}, false};

#ifdef SUPPORT_ENCRYPTION
        if (config["pk"].IsDefined()) {
            LOG(INFO) << "Starting server with encryption support" << std::endl;
            std::string pk = config["pk"].as<std::string>();
            boost::uuids::uuid uuid;
            if(utils::is_valid_uuid(pk, uuid)) {
                for(int i = 0; i < 16; ++i) server_conf.key[i] = uuid.data[i];
                server_conf.encrypt = true;
            } else {
                LOG_FATAL("Invalid pre-shared key. Expected a valid UUID");
            }
        } else {
            LOG(INFO) << "No pre-shared key in config file, disabling encryption support" << std::endl;
        }
#endif

        auto pool = std::make_shared<utils::AddressPool>(ip::address_v4::from_string(start_addr),
                                                         ip::address_v4::from_string(end_addr));
        io_service io_serv;
        Server server{pool, server_conf, io_serv,
                             ip::address_v6::from_string(config["listen_address"].as<std::string>()),
                             config["port"].as<uint16_t>()};
        server.start();
    }
    catch (const cxxopts::OptionException &ex) {
        LOG_WARN(ex.what());
        LOG(INFO) << options.help();
        exit(EXIT_FAILURE);
    }
    catch (const std::exception &ex) {
        LOG_FATAL(ex.what());
    }
    catch (...) {
        LOG_FATAL("An exception has occurred");
    }
    return 0;
}


text:
//          Copyright Oliver Kowalke 2009.
// 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_FIBERS_DETAIL_INFO_H
#define BOOST_FIBERS_DETAIL_INFO_H

#include <cstddef>

#include <boost/assert.hpp>
#include <boost/config.hpp>
#include <boost/move/move.hpp>
#include <boost/type_traits/remove_reference.hpp>

#include <boost/fiber/detail/config.hpp>
#include <boost/fiber/detail/info_base.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace fibers {
namespace detail {

class BOOST_FIBER_DECL info_default : public info_base
{
private:
	info_default( info_default &);
	info_default & operator=( info_default const&);

public:
	info_default() :
		info_base()
	{}

	void run()
	{ BOOST_ASSERT( ! "run() of master-fiber should never be executed"); }
};

template< typename Fn >
class info : public info_base
{
private:
	Fn	fn_;

	info( info &);
	info & operator=( info const&);

public:
	info( Fn fn, std::size_t stack_size) :
		info_base( stack_size),
		fn_( fn)
	{}

	info( BOOST_RV_REF( Fn) fn, std::size_t stack_size) :
		info_base( stack_size),
		fn_( fn)
	{}

	void run()
	{ fn_(); }
};

template< typename Fn >
class info< reference_wrapper< Fn > > : public info_base
{
private:
	Fn	&	fn_;

	info( info &);
	info & operator=( info const&);

public:
	info( reference_wrapper< Fn > fn, std::size_t stack_size) :
		info_base( stack_size),
		fn_( fn)
	{}

	void run()
	{ fn_(); }
};

template< typename Fn >
class info< const reference_wrapper< Fn > > : public info_base
{
private:
	Fn	&	fn_;

	info( info &);
	info & operator=( info const&);

public:
	info( const reference_wrapper< Fn > fn, std::size_t stack_size) :
		info_base( stack_size),
		fn_( fn)
	{}

	void run()
	{ fn_(); }
};

}}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_FIBERS_DETAIL_INFO_H

max_stars_repo_name: ghisguth/tasks

max_issues_repo_name: ghisguth/tasks

max_forks_repo_name: ghisguth/tasks