text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 *************************************************************/

#ifndef SDEXT_PRESENTER_CONFIGURATION_ACCESS_HXX
#define SDEXT_PRESENTER_CONFIGURATION_ACCESS_HXX

#include <rtl/ustring.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XHierarchicalNameAccess.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <vector>
#include <boost/function.hpp>

namespace css = ::com::sun::star;

namespace sdext { namespace presenter {

/** This class gives access to the configuration.  Create an object of this
    class for one node of the configuration.  This will be the root node.
    From this one you can use this class in two ways.

In a stateless mode (with exception of the root node) you can use static
    methods for obtaining child nodes, get values from properties at leaf
    nodes and iterate over children of inner nodes.

In a stateful mode use non-static methods like GoToChild() to
    navigate to children.

Note to call CommitChanges() after making changes to
    PresenterConfigurationAccess object that was opened in READ_WRITE mode.

*/
class PresenterConfigurationAccess
{
public:
    enum WriteMode { READ_WRITE, READ_ONLY };
    typedef ::boost::function<bool(
        const ::rtl::OUString&,
        const css::uno::Reference<css::beans::XPropertySet>&)> Predicate;
    static const ::rtl::OUString msPresenterScreenRootName;

    /** Create a new object to access the configuration entries below the
        given root.
        @param rsRootName
            Name of the root.  You can use msPresenterScreenRootName to
            access the configuration of the presenter screen.
        @param eMode
            This flag specifies whether to give read-write or read-only
            access.
    */
    PresenterConfigurationAccess(
        const css::uno::Reference<css::uno::XComponentContext>& rxContext,
        const ::rtl::OUString& rsRootName,
        WriteMode eMode);

    ~PresenterConfigurationAccess (void);

    /** Return a configuration node below the root of the called object.
        @param rsPathToNode
            The relative path from the root (as given the constructor) to the node.
    */
    css::uno::Any GetConfigurationNode (
        const ::rtl::OUString& rsPathToNode);
    css::uno::Reference<css::beans::XPropertySet> GetNodeProperties (
        const ::rtl::OUString& rsPathToNode);

    /** Return <TRUE/> when opening the configuration (via creating a new
        PresenterConfigurationAccess object) or previous calls to
        GoToChild() left the called PresenterConfigurationAccess object in a
        valid state.
    */
    bool IsValid (void) const;

    /** Move the focused node to the (possibly indirect) child specified by the given path.
    */
    bool GoToChild (const ::rtl::OUString& rsPathToNode);

    /** Move the focused node to the first direct child that fulfills the given predicate.
    */
    bool GoToChild (const Predicate& rPredicate);

    /** Modify the property child of the currently focused node.  Keep in
        mind to call CommitChanges() to write the change back to the
        configuration.
    */
    bool SetProperty (const ::rtl::OUString& rsPropertyName, const css::uno::Any& rValue);

    /** Return a configuration node below the given node.
        @param rxNode
            The node that acts as root to the given relative path.
        @param rsPathToNode
            The relative path from the given node to the requested node.
            When this string is empty then rxNode is returned.
        @return
            The type of the returned node varies with the requested node.
            It is empty when the node was not found.
    */
    static css::uno::Any GetConfigurationNode (
        const css::uno::Reference<css::container::XHierarchicalNameAccess>& rxNode,
        const ::rtl::OUString& rsPathToNode);

    static css::uno::Reference<css::beans::XPropertySet> GetNodeProperties (
        const css::uno::Reference<css::container::XHierarchicalNameAccess>& rxNode,
        const ::rtl::OUString& rsPathToNode);

    /** Write any changes that have been made back to the configuration.
        This call is ignored when the called ConfigurationAccess object was
        not create with read-write mode.
    */
    void CommitChanges (void);

    css::uno::Any GetValue (const rtl::OUString& sKey);

    typedef ::boost::function<void(
        const ::rtl::OUString&,
        const ::std::vector<css::uno::Any>&) > ItemProcessor;
    typedef ::boost::function<void(
        const ::rtl::OUString&,
        const ::css::uno::Reference<css::beans::XPropertySet>&) > PropertySetProcessor;

    /** Execute a functor for all elements of the given container.
        @param rxContainer
            The container is a XNameAccess to a list of the configuration.
            This can be a node returned by GetConfigurationNode().
        @param rArguments
            The functor is called with arguments that are children of each
            element of the container.  The set of children is specified  this
            list.
        @param rFunctor
            The functor to be executed for some or all of the elements in
            the given container.
    */
    static void ForAll (
        const css::uno::Reference<css::container::XNameAccess>& rxContainer,
        const ::std::vector<rtl::OUString>& rArguments,
        const ItemProcessor& rProcessor);
    static void ForAll (
        const css::uno::Reference<css::container::XNameAccess>& rxContainer,
        const PropertySetProcessor& rProcessor);

    /** Fill a list with the string contents of all sub-elements in the given container.
        @param rxContainer
            The container is a XNameAccess to a list of the configuration.
            This can be a node returned by GetConfigurationNode().
        @param rsArgument
            This specifies which string children of the elements in the
            container are to be inserted into the list.  The specified child
            has to be of type string.
        @param rList
            The list to be filled.
    */
    static void FillList(
        const css::uno::Reference<css::container::XNameAccess>& rxContainer,
        const ::rtl::OUString& rsArgument,
        ::std::vector<rtl::OUString>& rList);

    static css::uno::Any Find (
        const css::uno::Reference<css::container::XNameAccess>& rxContainer,
        const Predicate& rPredicate);

    static bool IsStringPropertyEqual (
        const ::rtl::OUString& rsValue,
        const ::rtl::OUString& rsPropertyName,
        const css::uno::Reference<css::beans::XPropertySet>& rxNode);

    /** This method wraps a call to getPropertyValue() and returns an empty
        Any instead of throwing an exception when the property does not
        exist.
    */
    static css::uno::Any GetProperty (
        const css::uno::Reference<css::beans::XPropertySet>& rxProperties,
        const ::rtl::OUString& rsKey);

private:
    css::uno::Reference<css::uno::XInterface> mxRoot;
    css::uno::Any maNode;
};

} } // end of namespace sdext::tools

#endif

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice


text:
/**
 * Authors:
 *      Andre Potes (andre.potes@tecnico.ulisboa.pt)
 *      Marcelo Jacinto (marcelo.jacinto@tecnico.ulisboa.pt)
 * Maintained by: Andre Potes (andre.potes@tecnico.ulisboa.pt)
 * Last Update: 14/12/2021
 * License: MIT
 * File: ThrusterManager.hpp
 * Brief: Defines a thruster manager ROS plugin that translates the desired forces for the vehicle thrusters, from the
 *        DSOR stack to the UUV simulator
 */

#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

#include <limits>

#include <gazebo/gazebo.hh>
#include <gazebo/msgs/msgs.hh>
#include <gazebo/physics/Link.hh>
#include <gazebo/physics/Model.hh>
#include <gazebo/physics/PhysicsEngine.hh>
#include <gazebo/physics/World.hh>
#include <gazebo/transport/TransportTypes.hh>
#include <sdf/sdf.hh>
#include <dsor_msgs/Thruster.h>

#include <math.h>

#include <uuv_gazebo_ros_plugins/ThrusterManagerROSPlugin.hh>

namespace gazebo {

    ThrusterManagerROSPlugin::ThrusterManagerROSPlugin() : thrustersNumber(0)  {}

    ThrusterManagerROSPlugin::~ThrusterManagerROSPlugin() {
        if (this->updateConnection) {
            this->updateConnection.reset();
        }
        this->rosNode->shutdown();
    }

    void ThrusterManagerROSPlugin::Load(physics::ModelPtr _model, sdf::ElementPtr _sdf) {

        GZ_ASSERT(_model != NULL, "Invalid model pointer");

        if (!ros::isInitialized()) {
            gzerr << "Not loading plugin since ROS has not been "
                << "properly initialized.  Try starting gazebo with ros plugin:\n"
                << "  gazebo -s libgazebo_ros_api_plugin.so\n";
            return;
        }

        this->rosNode.reset(new ros::NodeHandle(""));

        // Initializing the transport node
        this->node = transport::NodePtr(new transport::Node());
        this->node->Init(_model->GetWorld()->Name());

        // Reading number of thrusters
        GZ_ASSERT(_sdf->HasElement("thrustersNumber"), "Number of thrusters was not provided");
        this->thrustersNumber = _sdf->Get<int>("thrustersNumber");
        GZ_ASSERT(this->thrustersNumber > 0, "Number of thrusters must be greater than zero.");

        // Reading thrusters topic from DSOR stack
        GZ_ASSERT(_sdf->HasElement("dsorTopicThrusters"), "Topic of thrusters was not provided");
        this->dsorTopicThrusters = _sdf->Get<std::string>("dsorTopicThrusters");

        this->thrusterStackSubscriber = this->rosNode->subscribe(this->dsorTopicThrusters, 10, &ThrusterManagerROSPlugin::SetThrustReference, this);

        // Root string for topics
        std::string topicPrefix;

        for (int i = 0; i < this->thrustersNumber; i++) {

            // Get the topic prefix for each thruster topic to publish
            topicPrefix =  "/" + _model->GetName() + "/thrusters/" + std::to_string(i) + "/input";

            // Advertise the thrust topic
            this->thrustInputPublisher.push_back(this->rosNode->advertise<uuv_gazebo_ros_plugins_msgs::FloatStamped>(topicPrefix, 1));
        }
    }

    void ThrusterManagerROSPlugin::SetThrustReference(const dsor_msgs::Thruster &msg) {

        // Safety check the number of thrusters in the control message
        if (msg.value.size() > this->thrustersNumber) {
            ROS_WARN("Number of thruster from DSOR stack is not equal to the predefined number of thruster in vehicle (gazebo).");
            return;
        }

        // Get the current time from ros
        ros::Time curTime = ros::Time().now();

        // Publish individual thrust in msg (DSOR stack) to each respective topic (gazebo)
        for (int i = 0; i < this->thrustersNumber; i++) {

            // Create the FloatStamped ros msg
            uuv_gazebo_ros_plugins_msgs::FloatStamped thrust_msg;
            thrust_msg.header.stamp.sec = curTime.sec;
            thrust_msg.header.stamp.nsec = curTime.nsec;
            thrust_msg.data = msg.value[i];

            // Publish the desired thrust to each individual thruster
            this->thrustInputPublisher[i].publish(thrust_msg);
        }
    }

    void ThrusterManagerROSPlugin::Update(const common::UpdateInfo &_info) {}

GZ_REGISTER_MODEL_PLUGIN(ThrusterManagerROSPlugin)
}

ext: cc


text:
/*
  * Generated by cppsrc.sh
  * On 2015-12-12  9:44:59,49
  * by Paweu
*/
/*--END OF HEADER BLOCK--*/
#define _WIN32_WINNT 0x0501

#include "../StarVFSInternal.h"
#include "RemoteModule.h"

#include <thread>
#include <chrono>
#include <iostream>
#include <boost/asio.hpp>

#include "RemoteHeaders.h"

using boost::asio::ip::tcp;
using boost::asio::deadline_timer;

namespace StarVFS {
namespace Modules {

RemoteModule::RemoteModule(StarVFS *svfs, const String &port): iModule(svfs), m_Port(port) {
	m_ThreadRunning = false;
	m_CanRun = false;

	m_Port = "";
}

RemoteModule::~RemoteModule() {
	Disable();
}

//-------------------------------------------------------------------------------------------------

bool RemoteModule::Enable() {
	if (m_ThreadRunning)
		return true;

	m_CanRun = true;
	std::thread([this]() {
		m_ThreadRunning = true;
		try {
			ThreadMain();
		}
		catch (std::exception &e) {
			std::cout << "EXCEPTION: " << e.what();
		}
		catch (...) {
		}
		m_ThreadRunning = false;
	}).detach();

	return true;
}

bool RemoteModule::Disable() {
	m_CanRun = false;
	while (m_ThreadRunning)
		std::this_thread::sleep_for(std::chrono::milliseconds(10));
	return true;
}

//-------------------------------------------------------------------------------------------------

using BaseConnectionClass = RemoteHeaders::BaseConnection<boost::asio::io_service, tcp::socket>;
struct RemoteModule::Connection : public BaseConnectionClass {
	RemoteModule *m_Owner;
	using MessageBuffer = RemoteHeaders::MessageBuffer;

	Connection(RemoteModule *Owner): BaseConnectionClass() {
		m_Owner = Owner;
	}

	virtual bool CanRun() const override { return m_Owner->m_CanRun; }

	bool ProcessPingPong(MessageBuffer &message) {
		message.Clear();
		auto hdr = message.GetHeader();
		if (hdr->CommandID == RemoteHeaders::Command::Ping)
			hdr->CommandID = RemoteHeaders::Command::Pong;
		else
			hdr->CommandID = RemoteHeaders::Command::Ping;

		return WriteMessage(message);
	}

	bool SendFileTable(MessageBuffer &message) {
		message.Clear();
		auto hdr = message.GetHeader();
		auto vfs = m_Owner->GetVFS();
		auto ft = vfs->GetFileTable();

		auto c = ft->GetAllocatedFileCount();
		message.PushString((char*)ft->GetTable(), c * sizeof(File));
		hdr->ElementCount = c;

		return WriteMessage(message);
	}
	bool SendStringTable(MessageBuffer &message) {
		message.Clear();
		auto hdr = message.GetHeader();
		auto vfs = m_Owner->GetVFS();
		auto ft = vfs->GetFileTable();
		auto st = ft->GetStringTable();

		auto c = st->GetAllocatedCount();
		message.PushString((char*)st->GetMemory(), c * sizeof(Char));
		hdr->ElementCount = c;

		return WriteMessage(message);
	}
	bool SendFile(MessageBuffer &message) {
		message.Clear();
//		auto hdr = message.GetHeader();
		auto vfs = m_Owner->GetVFS();

		auto request = message.GetAndPull<RemoteHeaders::GetFileRequest>();
		FileHandle h;

		using Mode = RemoteHeaders::GetFileRequest::FindMode;
		switch (request->Mode) {
		case Mode::Hash:
			break;
		case Mode::ID:
			h = vfs->OpenFile(request->ID, request->AccessMode);
			break;
		case Mode::Path:
			h = vfs->OpenFile((CString)request->Path, request->AccessMode, request->FileOpenMode);
			break;
		default:
			break;
		}

		message.Clear();
		auto response = message.AllocAndZero<RemoteHeaders::GetFileResponse>();

		ByteTable ct;
		if (!h || !h.GetFileData(ct)) {
			response->Result = 1;
		} else {
			response->DataSize = h.GetSize();
			message.PushString((char*)ct.get(), h.GetSize());
		}

		return WriteMessage(message);
	}
	virtual bool ProcessCommand(MessageBuffer &message) override {
		auto hdr = message.GetHeader();

		STARVFSDebugInfoLog("Recived command:%u payload:%u", (unsigned)hdr->CommandID, (unsigned)hdr->PayLoadSize);

		switch (hdr->CommandID) {
		case RemoteHeaders::Command::GetFileTable:
			return SendFileTable(message);
		case RemoteHeaders::Command::GetStringTable:
			return SendStringTable(message);
		case RemoteHeaders::Command::GetFile:
			return SendFile(message);
		case RemoteHeaders::Command::Ping:
		case RemoteHeaders::Command::Pong:
			return ProcessPingPong(message);

		case RemoteHeaders::Command::NOP:
		default:
			return true;
		}
	}

	void HandleClient() {
		STARVFSDebugLog("Accepted connection");
		auto Buffer = std::make_unique<MessageBuffer>();
		while (m_Owner->m_CanRun && ReadMessage(*Buffer.get()) && ProcessCommand(*Buffer.get())) {
			//NOP
		}
		STARVFSDebugLog("Client disconnected");
	}
};

//-------------------------------------------------------------------------------------------------

void RemoteModule::ThreadMain() {
	Connection c(this);

	while (m_CanRun) {
		std::this_thread::sleep_for(std::chrono::milliseconds(500));

		int id = 0;
		uint16_t port = (uint16_t)strtol(m_Port.c_str(), nullptr, 10);
		if (port == 0) {
			port = static_cast<uint16_t>(RemoteHeaders::Settings::BasePort);
			m_Port = std::to_string(port);
		}
		tcp::acceptor a(c.m_io_service, tcp::endpoint(tcp::v4(), port));

		STARVFSDebugLog("Waiting for connection %d", id++);
		boost::system::error_code error;
		c.m_Socket = tcp::socket(c.m_io_service);
		a.accept(c.m_Socket, error);
		c.HandleClient();
		//c.m_io_service.run();

	//	deadline.expires_from_now(boost::posix_time::seconds(1));
	//	io_service.run();
	}
}

} //namespace Modules
} //namespace StarVFS

ext: cpp

max_stars_repo_name: pgrabas/starVFS

max_issues_repo_name: pgrabas/starVFS

max_forks_repo_name: pgrabas/starVFS


text:
#include <iostream>

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>

#include <onmt/Tokenizer.h>

namespace po = boost::program_options;

int main(int argc, char* argv[])
{
  po::options_description desc("Tokenization");
  desc.add_options()
    ("help,h", "display available options")
    ("mode,m", po::value<std::string>()->default_value("conservative"), "Define how aggressive should the tokenization be: 'aggressive' only keeps sequences of letters/numbers, 'conservative' allows mix of alphanumeric as in: '2,000', 'E65', 'soft-landing'")
    ("joiner_annotate,j", po::bool_switch()->default_value(false), "mark joints with joiner tokens (mutually exclusive with spacer_annotate)")
    ("joiner", po::value<std::string>()->default_value(onmt::Tokenizer::joiner_marker), "joiner token")
    ("joiner_new", po::bool_switch()->default_value(false), "make joiners independent tokens")
    ("spacer_annotate", po::bool_switch()->default_value(false), "mark spaces with spacer tokens (mutually exclusive with joiner_annotate)")
    ("spacer_new", po::bool_switch()->default_value(false), "make spacers independent tokens")
    ("preserve_placeholders", po::bool_switch()->default_value(false), "do not mark placeholders with joiners or spacers")
    ("preserve_segmented_tokens", po::bool_switch()->default_value(false), "do not mark segmented tokens (segment_* options) with joiners or spacers")
    ("case_feature,c", po::bool_switch()->default_value(false), "lowercase corpus and generate case feature")
    ("segment_case", po::bool_switch()->default_value(false), "Segment case feature, splits AbC to Ab C to be able to restore case")
    ("segment_numbers", po::bool_switch()->default_value(false), "Segment numbers into single digits")
    ("segment_alphabet", po::value<std::string>()->default_value(""), "comma-separated list of alphabets on which to segment all letters.")
    ("segment_alphabet_change", po::bool_switch()->default_value(false), "Segment if the alphabet changes between 2 letters.")
    ("bpe_model,bpe", po::value<std::string>()->default_value(""), "path to the BPE model")
    ("bpe_vocab", po::value<std::string>()->default_value(""), "Vocabulary file (built with get_vocab.py). If provided, this script reverts any merge operations that produce an OOV.")
    ("bpe_vocab_threshold", po::value<int>()->default_value(50), "Vocabulary threshold. If vocabulary is provided, any word with frequency < threshold will be treated as OOV.")
#ifdef WITH_SP
    ("sp_model,sp", po::value<std::string>()->default_value(""), "path to the SentencePiece model")
    ("sp_nbest_size", po::value<int>()->default_value(0), "number of candidates for the SentencePiece sampling API")
    ("sp_alpha", po::value<float>()->default_value(0.1), "smoothing parameter for the SentencePiece sampling API")
#endif
    ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);

  if (vm.count("help"))
  {
    std::cerr << desc << std::endl;
    return 1;
  }

  int flags = 0;
  if (vm["case_feature"].as<bool>())
    flags |= onmt::Tokenizer::Flags::CaseFeature;
  if (vm["joiner_annotate"].as<bool>())
    flags |= onmt::Tokenizer::Flags::JoinerAnnotate;
  if (vm["joiner_new"].as<bool>())
    flags |= onmt::Tokenizer::Flags::JoinerNew;
  if (vm["spacer_annotate"].as<bool>())
    flags |= onmt::Tokenizer::Flags::SpacerAnnotate;
  if (vm["spacer_new"].as<bool>())
    flags |= onmt::Tokenizer::Flags::SpacerNew;
  if (vm["preserve_placeholders"].as<bool>())
    flags |= onmt::Tokenizer::Flags::PreservePlaceholders;
  if (vm["preserve_segmented_tokens"].as<bool>())
    flags |= onmt::Tokenizer::Flags::PreserveSegmentedTokens;
  if (vm["segment_case"].as<bool>())
    flags |= onmt::Tokenizer::Flags::SegmentCase;
  if (vm["segment_numbers"].as<bool>())
    flags |= onmt::Tokenizer::Flags::SegmentNumbers;
  if (vm["segment_alphabet_change"].as<bool>())
    flags |= onmt::Tokenizer::Flags::SegmentAlphabetChange;

  std::vector<std::string> alphabets_to_segment;
  boost::split(alphabets_to_segment,
               vm["segment_alphabet"].as<std::string>(),
               boost::is_any_of(","));

  std::unique_ptr<onmt::Tokenizer> tokenizer;

#ifdef WITH_SP
  if (!vm["sp_model"].as<std::string>().empty())
  {
    tokenizer.reset(new onmt::Tokenizer(vm["sp_model"].as<std::string>(),
                                        vm["sp_nbest_size"].as<int>(),
                                        vm["sp_alpha"].as<float>(),
                                        onmt::Tokenizer::mapMode.at(vm["mode"].as<std::string>()),
                                        flags,
                                        vm["joiner"].as<std::string>()));
  }
  else
#endif
  {
    tokenizer.reset(new onmt::Tokenizer(onmt::Tokenizer::mapMode.at(vm["mode"].as<std::string>()),
                                        flags,
                                        vm["bpe_model"].as<std::string>(),
                                        vm["joiner"].as<std::string>(),
                                        vm["bpe_vocab"].as<std::string>(),
                                        vm["bpe_vocab_threshold"].as<int>()));
  }

  for (const auto& alphabet : alphabets_to_segment)
  {
    if (!alphabet.empty() && !tokenizer->add_alphabet_to_segment(alphabet))
      std::cerr << "WARNING: " << alphabet << " alphabet is not supported" << std::endl;
  }

  std::string line;

  while (std::getline(std::cin, line))
  {
    if (!line.empty())
      std::cout << reinterpret_cast<onmt::ITokenizer*>(tokenizer.get())->tokenize(line);

    std::cout << std::endl;
  }

  return 0;
}

max_stars_repo_name: koenvw/Tokenizer

max_issues_repo_name: koenvw/Tokenizer

max_forks_repo_name: koenvw/Tokenizer


text:
#ifndef GAME_STATE_HPP
#define GAME_STATE_HPP

#include <armadillo>

/*
Install Armadillo:
	If not present already, install LAPACK, Boost and BLAS  with
		sudo apt-get install liblapack-dev
		sudo apt-get install libblas-dev
		sudo apt-get install libboost-dev
	Install Armadillo using
		sudo apt-get install libarmadillo-dev
*/

struct Robot
{
	arma::vec2 pos; // (x, y) robot position in centimeters.
	arma::vec2 dir; // Unit vector indicating robot direction.
	bool missing;   // True if robot is not being seen.

	Robot()
	{
		pos = {0.0, 0.0};
		dir = {1.0, 0.0};
		missing = true;
	}
};

struct Ball
{
	arma::vec2 pos; // Ball position
	bool missing;   // True if ball is not being seen.

	Ball()
	{
		pos = {0.0, 0.0};
		missing = true;
	}
};

struct GameState
{
	Ball ball;					// Ball Position (x, y) in centimeters.
	std::vector<Robot> robots;  // Friendly robots.
	std::vector<Robot> enemies; // Enemy robots.

	GameState() : ball()
	{
		this->robots = std::vector<Robot>(3, Robot());
		this->enemies = std::vector<Robot>(3, Robot());
	}
};

#endif

ext: hpp

max_stars_repo_name: ger-unicamp/VSSS

max_issues_repo_name: ger-unicamp/VSSS

max_forks_repo_name: ger-unicamp/VSSS


text:
#include "util/thread_pool.h"

#include <boost/thread.hpp>
#include <glog/logging.h>
#include <queue>
#include <vector>

using boost::condition_variable;
using boost::function;
using boost::lock_guard;
using boost::mutex;
using boost::thread;
using boost::unique_lock;
using std::queue;
using std::vector;

namespace cert_trans {

class ThreadPool::Impl {
 public:
  ~Impl();

  void Worker();

  // TODO(pphaneuf): Would have used vector<thread>, but this requires
  // emplace_back, which is not available to us yet (C++11). I'd also
  // like it to be const, but it required to jump a few more hoops,
  // keeping it simple for now.
  vector<thread*> threads_;

  mutex queue_lock_;
  condition_variable queue_cond_var_;
  queue<function<void()> > queue_;
};

ThreadPool::Impl::~Impl() {
  // Start by sending an empty closure to every thread (and notify
  // them), to have them exit cleanly.
  {
    lock_guard<mutex> lock(queue_lock_);
    for (int i = threads_.size(); i > 0; --i)
      queue_.push(function<void()>());
  }
  // Notify all the threads *after* adding all the empty closures, to
  // avoid any races.
  queue_cond_var_.notify_all();

  // Wait for the threads to exit.
  for (vector<thread*>::const_iterator it = threads_.begin();
       it != threads_.end(); ++it) {
    (*it)->join();
    delete *it;
  }
}

void ThreadPool::Impl::Worker() {
  function<void()> closure;
  while (true) {
    closure.clear();

    {
      unique_lock<mutex> lock(queue_lock_);

      // If there's nothing to do, wait until there is.
      if (queue_.empty()) {
        queue_cond_var_.wait(lock);

        // condition_variable::wait can return spuriously.
        if (queue_.empty())
          continue;
      }

      // If we received an empty closure, exit cleanly.
      if (queue_.front().empty())
        break;

      closure = queue_.front();
      queue_.pop();
    }

    // Make sure not to hold the lock while calling the closure.
    closure();
  }
}

ThreadPool::ThreadPool() : impl_(new Impl) {
  const int num_threads(
      thread::hardware_concurrency() > 0 ? thread::hardware_concurrency() : 1);

  LOG(INFO) << "ThreadPool starting with " << num_threads << " threads";
  for (int i = 0; i < num_threads; ++i)
    impl_->threads_.push_back(new thread(&Impl::Worker, impl_.get()));
}

ThreadPool::~ThreadPool() {
  // Need to have this method defined where the definition of
  // ThreadPool::Impl is visible.
}

void ThreadPool::Add(const function<void()>& closure) {
  // Empty closures signal a thread to exit, don't allow that (also,
  // it doesn't make sense).
  CHECK(!closure.empty());

  {
    lock_guard<mutex> lock(impl_->queue_lock_);
    impl_->queue_.push(closure);
  }
  impl_->queue_cond_var_.notify_one();
}

}  // namespace cert_trans

max_stars_repo_name: laiqu/certificate-transparency

max_issues_repo_name: laiqu/certificate-transparency

max_forks_repo_name: laiqu/certificate-transparency


text:
/*=============================================================================
    Copyright (c) 2017 Paul Fultz II
    always.cpp
    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/hof/always.hpp>
#include <memory>

int main() {
    auto f = boost::hof::always(std::unique_ptr<int>{new int(1)});
    auto i = f(1, 2, 3);
    (void)i;
}


text:
#pragma once

#include <boost/utility.hpp>
#include <vector>
#include <utility>

#include <petuum_ps_common/include/abstract_row.hpp>
#include <petuum_ps_common/client/client_row.hpp>

namespace petuum {

class ProcessStorage;

// RowAccessor is a "smart pointer" for ROW: row_accessor.Get() gives a const
// reference.  We disallow copying of RowAccessor to avoid unnecessary
// manipulation of reference count.
class RowAccessor : boost::noncopyable {
public:
  RowAccessor() : client_row_ptr_(0) { }
  ~RowAccessor() {
    Clear();
  }

  // The returned reference is guaranteed to be valid only during the
  // lifetime of this RowAccessor.
  template<typename ROW>
  inline const ROW& Get() {
    return *(dynamic_cast<ROW*>(client_row_ptr_->GetRowDataPtr()));
  }

private:
  friend class BoundedDenseProcessStorage;
  friend class BoundedSparseProcessStorage;
  friend class AbstractBgWorker;
  friend class SSPBgWorker;
  friend class SSPPushBgWorker;
  friend class SSPAggrBgWorker;
  friend class SSPConsistencyController;
  friend class SSPPushConsistencyController;
  friend class SSPAggrConsistencyController;
  friend class SSPAggrValueConsistencyController;
  friend class LocalConsistencyController;
  friend class LocalOOCConsistencyController;
  friend class ThreadTable;
  friend class ThreadTableSN;

  void Clear() {
    if (client_row_ptr_ != 0) {
      client_row_ptr_->DecRef();
      client_row_ptr_ = 0;
    }
  }

  // Does not take ownership of client_row_ptr.
  inline void SetClientRow(ClientRow* client_row_ptr) {
    //Clear();
    client_row_ptr_ = client_row_ptr;
    client_row_ptr_->IncRef();
  }

  // Return client row which will stay alive throughout the lifetime of
  // RowAccessor.
  inline const ClientRow* GetClientRow() {
    return client_row_ptr_;
  }

  AbstractRow *GetRowData() {
    return client_row_ptr_->GetRowDataPtr();
  }

  ClientRow* client_row_ptr_;
};

class ThreadRowAccessor : boost::noncopyable {
public:
  ThreadRowAccessor() : row_data_ptr_(0) { }
  ~ThreadRowAccessor() { }

  // The returned reference is guaranteed to be valid only during the
  // lifetime of this RowAccessor.
  template<typename ROW>
  inline const ROW& Get() {
    return *(dynamic_cast<ROW*>(row_data_ptr_));
  }

private:
  friend class SSPConsistencyController;
  friend class SSPPushConsistencyController;
  friend class LocalConsistencyController;
  friend class LocalOOCConsistencyController;
  friend class ThreadTable;
  friend class ThreadTableSN;

  AbstractRow *row_data_ptr_;
};

}  // namespace petuum


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)

#ifndef BOOST_RECURSIVE_MUTEX_WEK070601_HPP
#define BOOST_RECURSIVE_MUTEX_WEK070601_HPP

#include <boost/thread/detail/config.hpp>

#include <boost/utility.hpp>
#include <boost/thread/detail/lock.hpp>

#if defined(BOOST_HAS_PTHREADS)
#   include <pthread.h>
#endif

#if defined(BOOST_HAS_MPTASKS)
#   include "scoped_critical_region.hpp"
#endif

namespace boost {

struct xtime;
// disable warnings about non dll import
// see: http://www.boost.org/more/separate_compilation.html#dlls
#ifdef BOOST_MSVC
#   pragma warning(push)
#   pragma warning(disable: 4251 4231 4660 4275)
#endif
class BOOST_THREAD_DECL recursive_mutex
    : private noncopyable
{
public:
    friend class detail::thread::lock_ops<recursive_mutex>;

    typedef detail::thread::scoped_lock<recursive_mutex> scoped_lock;

    recursive_mutex();
    ~recursive_mutex();

private:
#if (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
    typedef std::size_t cv_state;
#elif defined(BOOST_HAS_PTHREADS)
    struct cv_state
    {
        long count;
        pthread_mutex_t* pmutex;
    };
#endif
    void do_lock();
    void do_unlock();
    void do_lock(cv_state& state);
    void do_unlock(cv_state& state);

#if defined(BOOST_HAS_WINTHREADS)
    void* m_mutex;
    bool m_critical_section;
    unsigned long m_count;
#elif defined(BOOST_HAS_PTHREADS)
    pthread_mutex_t m_mutex;
    unsigned m_count;
#   if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE)
    pthread_cond_t m_unlocked;
    pthread_t m_thread_id;
    bool m_valid_id;
#   endif
#elif defined(BOOST_HAS_MPTASKS)
    threads::mac::detail::scoped_critical_region m_mutex;
    threads::mac::detail::scoped_critical_region m_mutex_mutex;
    std::size_t m_count;
#endif
};

class BOOST_THREAD_DECL recursive_try_mutex
    : private noncopyable
{
public:
    friend class detail::thread::lock_ops<recursive_try_mutex>;

    typedef detail::thread::scoped_lock<recursive_try_mutex> scoped_lock;
    typedef detail::thread::scoped_try_lock<
        recursive_try_mutex> scoped_try_lock;

    recursive_try_mutex();
    ~recursive_try_mutex();

private:
#if (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
    typedef std::size_t cv_state;
#elif defined(BOOST_HAS_PTHREADS)
    struct cv_state
    {
        long count;
        pthread_mutex_t* pmutex;
    };
#endif
    void do_lock();
    bool do_trylock();
    void do_unlock();
    void do_lock(cv_state& state);
    void do_unlock(cv_state& state);

#if defined(BOOST_HAS_WINTHREADS)
    void* m_mutex;
    bool m_critical_section;
    unsigned long m_count;
#elif defined(BOOST_HAS_PTHREADS)
    pthread_mutex_t m_mutex;
    unsigned m_count;
#   if !defined(BOOST_HAS_PTHREAD_MUTEXATTR_SETTYPE)
    pthread_cond_t m_unlocked;
    pthread_t m_thread_id;
    bool m_valid_id;
#   endif
#elif defined(BOOST_HAS_MPTASKS)
    threads::mac::detail::scoped_critical_region m_mutex;
    threads::mac::detail::scoped_critical_region m_mutex_mutex;
    std::size_t m_count;
#endif
};

class BOOST_THREAD_DECL recursive_timed_mutex
    : private noncopyable
{
public:
    friend class detail::thread::lock_ops<recursive_timed_mutex>;

    typedef detail::thread::scoped_lock<recursive_timed_mutex> scoped_lock;
    typedef detail::thread::scoped_try_lock<
        recursive_timed_mutex> scoped_try_lock;
    typedef detail::thread::scoped_timed_lock<
        recursive_timed_mutex> scoped_timed_lock;

    recursive_timed_mutex();
    ~recursive_timed_mutex();

private:
#if (defined(BOOST_HAS_WINTHREADS) || defined(BOOST_HAS_MPTASKS))
    typedef std::size_t cv_state;
#elif defined(BOOST_HAS_PTHREADS)
    struct cv_state
    {
        long count;
        pthread_mutex_t* pmutex;
    };
#endif
    void do_lock();
    bool do_trylock();
    bool do_timedlock(const xtime& xt);
    void do_unlock();
    void do_lock(cv_state& state);
    void do_unlock(cv_state& state);

#if defined(BOOST_HAS_WINTHREADS)
    void* m_mutex;
    unsigned long m_count;
#elif defined(BOOST_HAS_PTHREADS)
    pthread_mutex_t m_mutex;
    pthread_cond_t m_unlocked;
    pthread_t m_thread_id;
    bool m_valid_id;
    unsigned m_count;
#elif defined(BOOST_HAS_MPTASKS)
    threads::mac::detail::scoped_critical_region m_mutex;
    threads::mac::detail::scoped_critical_region m_mutex_mutex;
    std::size_t m_count;
#endif
};
#ifdef BOOST_MSVC
#   pragma warning(pop)
#endif
} // namespace boost

#endif // BOOST_RECURSIVE_MUTEX_WEK070601_HPP

// Change Log:
//    8 Feb 01  WEKEMPF Initial version.
//    1 Jun 01  WEKEMPF Modified to use xtime for time outs.  Factored out
//                      to three classes, mutex, try_mutex and timed_mutex.
//   11 Jun 01  WEKEMPF Modified to use PTHREAD_MUTEX_RECURSIVE if available.
//    3 Jan 03  WEKEMPF Modified for DLL implementation.


text:
#pragma once

#include <tuple>
#include <array>
#include <iostream>
#include <utility>
#include "sparta/log/MessageSource.hpp"
#include <type_traits>
#include <boost/format.hpp>
namespace sparta{
namespace pevents{

    //!A typedef for defining formatters for custom attributes.
    typedef std::ios_base::fmtflags FormatFlags;

//we'll want a way to force that certain keys are not used else where.
namespace PEventProtection
{
    enum ProtectAttrs{
        EV,
        CYCLE
    };
    extern std::array<std::string, 2> PEventProtectedAttrs;

    /**
     * \brief A helper method used when asserting that quotes do not
     * already exist in String type pevent attributes, since we will
     * be appending the quotes automatically.
     */
    template<typename T>
     bool CheckNoQuotes(const T&, const std::string&, const std::string&)
    {
        return true;
    }

    /**
     * \brief a helper method for appending quotes only when called by a
     * string type attribute.
     */
    template<typename T>
     void AppendQuote(std::stringstream&)
    {/*do nothing*/}

    template<>
    inline bool CheckNoQuotes(const std::string& obj, const std::string& pre, const std::string& post)
    {
        if(SPARTA_EXPECT_FALSE(std::strcmp(&obj.front(), "\"") == 0))
        {
            return false;
        }
        if(SPARTA_EXPECT_FALSE(std::strcmp(&obj.back(), "\"") == 0))
        {
            return false;
        }
        if(SPARTA_EXPECT_FALSE(std::strcmp(&pre.front(), "\"") == 0))
        {
            return false;
        }
        if(SPARTA_EXPECT_FALSE(std::strcmp(&post.back(), "\"") == 0))
        {
            return false;
        }
        //There were no problems with quotes.
        return true;
    }

    template<>
    inline void AppendQuote<const std::string&>(std::stringstream& ss)
    {
        ss << "\"";
    }

}

template<typename ...CustomAttrs>
class PEvent
{

    typedef PEvent<CustomAttrs...> ThisType;
    //!Some attributes that are required by each pevent.
    struct RequiredAttrs{
        RequiredAttrs(const std::string& name) :
            event_name(name)
        {}
        uint64_t cycle_time = 0; //!Where are we getting time, is the PEvent passed a clock, or are we asking the scheduler singleton
        uint64_t unique_id = 0;
        std::string event_name = "";
    };

    //!A struct used for cacheing output format information about each custom paramater.
    struct PrePostTags{
        PrePostTags() :
            pre_format(),
            post_format()
        {}
        std::string prefix = "";
        std::string postfix = "";
        FormatFlags pre_format;
        FormatFlags post_format;
        int swidth = 0;
        char fill_char = ' ';

    };

    //!We need to map the attributes to some text names
    //!Is there some need to ensure that custom attribute names follow a convention?
    std::array<std::string, sizeof...(CustomAttrs)> custom_attrs_names_;

    //!We need to capture some formatting information for each attribute
    std::array<PrePostTags, sizeof...(CustomAttrs)> custom_attrs_formats_;
    //!We need to cache attributes.
    std::tuple<CustomAttrs...> custom_attrs_;

    //!A struct with some required attributes.
    RequiredAttrs required_attrs_;

    //!We will need a logger to use
    log::MessageSource& logger_;
    //!The clock tied to this PEvent, yes the log is going to manage time also...
    const Clock* clk_;

    void writeRequiredData_(std::stringstream& s)
    {
        //Write event name
        std::stringstream name_str;
        name_str << "\"" << required_attrs_.event_name << "\"";
        s.flags(FormatFlags(std::ios::left));
        s << std::get<PEventProtection::EV>(PEventProtection::PEventProtectedAttrs) << "=" << std::setw(12) << name_str.str() << " ";
    }

    void appendCycle_(std::stringstream& s)
    {
        //Write cycle
        s << std::get<PEventProtection::CYCLE>(PEventProtection::PEventProtectedAttrs) << "=" << clk_->currentCycle();
    }

    //!Some crazyness to unroll our tuples/array at compile time.
    template <class Tuple, class Array, class Formats, std::size_t N>
    struct TupleUnroller {
        static void unroller_(const Tuple& t, const Array& a, const Formats& f, std::stringstream& s){
            TupleUnroller<Tuple, Array, Formats, N-1>::unroller_(t, a, f, s);
            s << std::get<N-1>(a) << "=";
            //Assert that the first and last character are not quotes on a string, since we are going to insert
            //our own quotes on strings.
            sparta_assert(PEventProtection::CheckNoQuotes(std::get<N-1>(t), std::get<N-1>(f).prefix, std::get<N-1>(f).postfix), "Quotes are appended to string types for PEvent logging automatically and should not be done by the modeller in the prefix, postfix, or the string itself.");
            //Automatically insert quotes to the beginning of the string types.
            PEventProtection::AppendQuote<decltype(std::get<N-1>(t))>(s);
            s.flags(std::get<N-1>(f).pre_format);
            s << std::get<N-1>(f).prefix;
            s << std::setfill(std::get<N-1>(f).fill_char);
            s << std::setw(std::get<N-1>(f).swidth);
            /*!     Writing the data  */
            s << std::get<N-1>(t);
            s << std::get<N-1>(f).postfix;
            //Automatically insert quotes to the end of the string types.
            PEventProtection::AppendQuote<decltype(std::get<N-1>(t))>(s);
            s << " ";
            s.flags(std::get<N-1>(f).post_format);
        }
    };
    template <class Tuple, class Array, class Formats>
    struct TupleUnroller<Tuple, Array, Formats, 1> {
        static void unroller_(const Tuple& t, const Array& a, const Formats& f, std::stringstream& s){
            s << std::get<0>(a) << "=";
            s.flags(std::get<0>(f).pre_format);
            s << std::get<0>(f).prefix;
            //Assert that the first and last character are not quotes on a string, since we are going to insert
            //our own quotes on strings, also do the assertions on pre and post fixes.
            sparta_assert(PEventProtection::CheckNoQuotes(std::get<0>(t), std::get<0>(f).prefix, std::get<0>(f).postfix), "Quotes are appended to string types for PEvent logging automatically and should not be done by the modeller in the prefix, postfix, or the string itself.");
            //Automatically insert quotes to the beginning of the string types.
            PEventProtection::AppendQuote<decltype(std::get<0>(t))>(s);
            s << std::get<0>(f).postfix;
            s << std::setfill(std::get<0>(f).fill_char);
            s << std::setw(std::get<0>(f).swidth);
            /*!     Writing the data  */
            s << std::get<0>(t);
            s.flags(std::get<0>(f).post_format);
            //Automatically insert quotes to the end of the string types.
            PEventProtection::AppendQuote<decltype(std::get<0>(t))>(s);
            s << " ";
        }
    };
public:

    //!Would set the event_type, as well as initial values for custom attrs
    //!Set the custom attribute names.
    //!We can probably create our own logger? But maybe they want to use the
    ///same logger for all these events?
    template<typename ...ArgNames>
    PEvent(const std::string& name, log::MessageSource& logger, const Clock* clk, ArgNames&&... names) :
        custom_attrs_names_{{names...}}, //some crazyness with array initializer lists, and stuff.
        required_attrs_(name),
        logger_(logger),
        clk_(clk)
    {
        //run time assert that checks to makes sure none of that custom attributes
        //are using a restricted name, such as names for required attributes.
        for(auto n : custom_attrs_names_)
        {
            sparta_assert(n != PEventProtection::PEventProtectedAttrs[0], "custom attribute name cannot be one of the protected attribute names");
            sparta_assert(n != PEventProtection::PEventProtectedAttrs[1], "custom attribute name cannot be one of the protected attribute names");
        }
    }

    void setName(const std::string& name)
    {
        required_attrs_.event_name = name;
    }
    /**
     * \brief add formatting options to each custom attribute.
     * \param n the position of the custom attribute in the parameters, with 0 being the
     * first custom parameter.
     * \param pre_flag the number format such as std::hex
     * \param post_flag the number format after leaving this, most always std::dec i assume.
     * \param pre a string to be appended to the front of the data, such as "0x"
     * \param post the string to be appended to the end of the data, such as ","
     *
     * \example
     * setFormatFlags(1, pevents::FormatFlags(std::ios::hex),
     *                   pevents::FormatFlags(std::ios::dec),
     *                   "0x", "");
     * would output as
     * EV="SOMETYPE", ... other attributes..., custom_param2=0x40
     */
    void setFormatFlags(const uint32_t n, const FormatFlags& pre_flag,
                        const FormatFlags& post_flag,
                        const std::string& pre, const std::string& post)
    {
        sparta_assert(n < sizeof...(CustomAttrs), "Cannot set the format flags for an attribute where n >= the number of custom attributes.");

        custom_attrs_formats_[n].prefix = pre;
        custom_attrs_formats_[n].postfix = post;
        custom_attrs_formats_[n].pre_format = pre_flag;
        custom_attrs_formats_[n].post_format = post_flag;
    }
    void setFormatFlags(const uint32_t n, const std::string& pre, const std::string& post)
    {
        setFormatFlags(n, FormatFlags(), FormatFlags(), pre, post);
    }

    /**
     * \brief set the setw size, and the alignment format.
     *
     * \example
     * //to set a number as hex that displays 8 leading zero's
     * setFormatLength(0, 8, FormatFlags(std::ios::left), '0');
     */
    void setFormatLength(const uint32_t n, const int length, const FormatFlags& align, const char fill)
    {
        sparta_assert(n < sizeof...(CustomAttrs), "Cannot set the format flags for an attribute where n >= the number of custom attributes.");
        custom_attrs_formats_.at(n).swidth = length;
        custom_attrs_formats_.at(n).pre_format = custom_attrs_formats_.at(n).pre_format | align;
        custom_attrs_formats_.at(n).fill_char = fill;
    }

    /**
     * \brief set many attributes as strings,
     * \usage
     * setAsString({1,3,5}); //where 1, 3, and 5 are attributes to be set as a string.
     */
    void setAsStrings(const std::initializer_list<uint32_t> list)
    {
        for(uint32_t i : list){
            setFormatFlags(i, "\"", "\"");
        }
    }

    /**
     * \brief a helper to set a custom attribute to be outputted in hex format.
     * \usage
     * setAsHex({1, 2, 3}); //will set custom attributes 1, 2, 3 as hex displayed outputs
     */
    void setAsHex(const std::initializer_list<uint32_t>& list)
    {
        static const int hex_length = 8;
        for(uint32_t i : list){
            setFormatFlags(i, pevents::FormatFlags(std::ios::hex), pevents::FormatFlags(std::ios::dec), "0x", "");
            setFormatLength(i, hex_length, pevents::FormatFlags(std::ios::right), '0');
        }
    }

    //!We probably need a way to set the attributes dynamically?
    //!Or would we rather set them every fireEvent?
    //!Or would the attributes not change?
    //!Is something like this sufficient?
    void setAttrs(CustomAttrs... attrs) { custom_attrs_ = std::make_tuple<CustomAttrs...>(std::forward<CustomAttrs>(attrs)...); }

    //!Set individual attributes?
    //!Would be cool if we could so some weirdness to set attribute by name... maybe some macro magic.
    template<typename AttrType, uint32_t N>
    void setAttr(const AttrType& attr) { std::get<N>(custom_attrs_) = attr; }

    //!Maybe it would be worth allowing some ability to have this PEvent instance query objects for attribute data...
    ///I don't know where the PEvent data is actually coming from?

    //!I guess we will need some way to alert the PEvent that it has occured?
    //!This is where the event would be dumped?
    void fireEvent()
    {
        if(logger_.observed())
        {
            std::stringstream s;
            writeRequiredData_(s);
            TupleUnroller<decltype(custom_attrs_), decltype(custom_attrs_names_), decltype(custom_attrs_formats_), sizeof...(CustomAttrs)>::unroller_(custom_attrs_, custom_attrs_names_, custom_attrs_formats_, s);
            appendCycle_(s);
            s << ";";
            logger_ << s.str();
        }
        //if(Pevent logging).... ? We need this if?
        //1)build a string with the required attrs.

        //2)append custom attrs to the string

        //3)dump the string, this may call a singleton head or something which passes information to the sparta logger?
        /// do what ever else the Pevent needs to do such as notifying observers?

        //We are dumping in a string format for sure?

        //Would I pass this to a logger now?
        //std::cout << //required_attrs_.cycle_time << " id: " << required_attrs_.unique_id << " EventType: "  << " ";
        //std::cout << std::get<PEventProtection::EV>(PEventProtection::PEventProtectedAttrs) << "="<< required_attrs_.event_name << " ";
        //This is gonna burn compile time, but oh well.
        //TupleUnroller<decltype(custom_attrs_), decltype(custom_attrs_names_), sizeof...(CustomAttrs)>::unroller_(custom_attrs_, custom_attrs_names_);
        //std::cout << std::endl;
    }

    //!Maybe overload fireEvent to allow setting the attributes when firing.
    void fireEvent(CustomAttrs... attrs)
    {
        setAttrs(attrs...);
        fireEvent();
    }

    bool observed()
    {
        return logger_.observed();
    }

};

}//namespace pevents
}//namespace sparta


text:
// Copyright (C) 2014 Vicente J. Botet Escriba
//
//  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)

// <boost/thread/sync_queue.hpp>

// class sync_queue<T>

//    sync_queue();

#define BOOST_THREAD_VERSION 4
//#define BOOST_THREAD_QUEUE_DEPRECATE_OLD

#include <boost/thread/sync_queue.hpp>
#include <boost/thread/concurrent_queues/queue_adaptor.hpp>
#include <boost/thread/concurrent_queues/queue_views.hpp>

#include <boost/detail/lightweight_test.hpp>
#include <boost/static_assert.hpp>

class non_copyable
{
  BOOST_THREAD_MOVABLE_ONLY(non_copyable)
  int val;
public:
  non_copyable(int v) : val(v){}
  non_copyable(BOOST_RV_REF(non_copyable) x): val(x.val) {}
  non_copyable& operator=(BOOST_RV_REF(non_copyable) x) { val=x.val; return *this; }
  bool operator==(non_copyable const& x) const {return val==x.val;}
  template <typename OSTREAM>
  friend OSTREAM& operator <<(OSTREAM& os, non_copyable const&x )
  {
    os << x.val;
    return os;
  }

};

#if defined  BOOST_NO_CXX11_RVALUE_REFERENCES
BOOST_STATIC_ASSERT( ! boost::is_copy_constructible<non_copyable>::value );
BOOST_STATIC_ASSERT( boost::has_move_emulation_enabled<non_copyable>::value );
#endif

int main()
{

  {
    // default queue invariants
      boost::queue_adaptor<boost::sync_queue<int> > sq;
      boost::queue_back<int> q(sq);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // default queue invariants
      boost::queue_adaptor<boost::sync_queue<int> > sq;
      boost::queue_front<int> q(sq);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }

  {
    // empty queue try_pull fails
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      int i;
      BOOST_TEST( boost::queue_op_status::empty == q.try_pull(i));
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // empty queue push rvalue/copyable succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      q.push(1);
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
  {
    // empty queue push lvalue/copyable succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      int i;
      q.push(i);
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }

#if 0
  {
    // empty queue push rvalue/non_copyable succeeds
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_back<non_copyable> q(sq);
      q.push(non_copyable(1));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
#endif
  {
    // empty queue push rvalue/non_copyable succeeds
    boost::queue_adaptor<boost::sync_queue<non_copyable> > q;
    //boost::sync_queue<non_copyable> q;
    //boost::queue_back<non_copyable> q(sq);
      non_copyable nc(1);
      q.push_back(boost::move(nc));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }

  {
    // empty queue push rvalue succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      q.push(1);
      q.push(2);
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 2u);
      BOOST_TEST(! q.closed());
  }
  {
    // empty queue push lvalue succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      int i;
      q.push(i);
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
  {
    // empty queue try_push rvalue/copyable succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      BOOST_TEST(boost::queue_op_status::success == q.try_push(1));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
  {
    // empty queue try_push rvalue/copyable succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      BOOST_TEST(boost::queue_op_status::success == q.try_push(1));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }

#if 0
  {
    // empty queue try_push rvalue/non-copyable succeeds
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_back<non_copyable> q(sq);
      non_copyable nc(1);
      BOOST_TEST(boost::queue_op_status::success == q.try_push(boost::move(nc)));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
#endif

  {
    // empty queue try_push lvalue succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      int i;
      BOOST_TEST(boost::queue_op_status::success == q.try_push(i));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
  {
    // empty queue try_push rvalue succeeds
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push(1));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }

#if 0
  {
    // empty queue nonblocking_push_back rvalue/non-copyable succeeds
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_back<non_copyable> q(sq);
      BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push(non_copyable(1)));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
#endif
  {
    // empty queue nonblocking_push_back rvalue/non-copyable succeeds
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_back<non_copyable> q(sq);
      non_copyable nc(1);
      BOOST_TEST(boost::queue_op_status::success == q.nonblocking_push(boost::move(nc)));
      BOOST_TEST(! q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 1u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue pull_front succeed
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      sq.push_back(1);
      int i;
      q.pull(i);
      BOOST_TEST_EQ(i, 1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue pull_front succeed
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_front<non_copyable> q(sq);
      non_copyable nc1(1);
      sq.push_back(boost::move(nc1));
      non_copyable nc2(2);
      q.pull(nc2);
      BOOST_TEST_EQ(nc1, nc2);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue pull_front succeed
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      sq.push_back(1);
      int i = q.pull();
      BOOST_TEST_EQ(i, 1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue pull_front succeed
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_front<non_copyable> q(sq);
      non_copyable nc1(1);
      sq.push_back(boost::move(nc1));
      non_copyable nc = q.pull();
      BOOST_TEST_EQ(nc, nc1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue try_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      sq.push_back(1);
      int i;
      BOOST_TEST(boost::queue_op_status::success == q.try_pull(i));
      BOOST_TEST_EQ(i, 1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue try_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_front<non_copyable> q(sq);
      non_copyable nc1(1);
      sq.push_back(boost::move(nc1));
      non_copyable nc(2);
      BOOST_TEST(boost::queue_op_status::success == q.try_pull(nc));
      BOOST_TEST_EQ(nc, nc1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue nonblocking_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      sq.push_back(1);
      int i;
      BOOST_TEST(boost::queue_op_status::success == q.nonblocking_pull(i));
      BOOST_TEST_EQ(i, 1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue nonblocking_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_front<non_copyable> q(sq);
      non_copyable nc1(1);
      sq.push_back(boost::move(nc1));
      non_copyable nc(2);
      BOOST_TEST(boost::queue_op_status::success == q.nonblocking_pull(nc));
      BOOST_TEST_EQ(nc, nc1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue wait_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_front<non_copyable> q(sq);
      non_copyable nc1(1);
      sq.push_back(boost::move(nc1));
      non_copyable nc(2);
      BOOST_TEST(boost::queue_op_status::success == q.wait_pull(nc));
      BOOST_TEST_EQ(nc, nc1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue wait_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      sq.push_back(1);
      int i;
      BOOST_TEST(boost::queue_op_status::success == q.wait_pull(i));
      BOOST_TEST_EQ(i, 1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }
  {
    // 1-element queue wait_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<non_copyable> > sq;
    boost::queue_front<non_copyable> q(sq);
      non_copyable nc1(1);
      sq.push_back(boost::move(nc1));
      non_copyable nc(2);
      BOOST_TEST(boost::queue_op_status::success == q.wait_pull(nc));
      BOOST_TEST_EQ(nc, nc1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(! q.closed());
  }

  {
    // closed invariants
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      q.close();
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(q.closed());
  }
  {
    // closed invariants
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      q.close();
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(q.closed());
  }
  {
    // closed queue push fails
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_back<int> q(sq);
      q.close();
      try {
        q.push(1);
        BOOST_TEST(false);
      } catch (...) {
        BOOST_TEST(q.empty());
        BOOST_TEST(! q.full());
        BOOST_TEST_EQ(q.size(), 0u);
        BOOST_TEST(q.closed());
      }
  }
  {
    // 1-element closed queue pull succeed
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      sq.push_back(1);
      q.close();
      int i;
      q.pull(i);
      BOOST_TEST_EQ(i, 1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(q.closed());
  }
  {
    // 1-element closed queue wait_pull_front succeed
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      sq.push_back(1);
      q.close();
      int i;
      BOOST_TEST(boost::queue_op_status::success == q.wait_pull(i));
      BOOST_TEST_EQ(i, 1);
      BOOST_TEST(q.empty());
      BOOST_TEST(! q.full());
      BOOST_TEST_EQ(q.size(), 0u);
      BOOST_TEST(q.closed());
  }
  {
    // closed empty queue wait_pull_front fails
    boost::queue_adaptor<boost::sync_queue<int> > sq;
    boost::queue_front<int> q(sq);
      q.close();
      BOOST_TEST(q.empty());
      BOOST_TEST(q.closed());
      int i;
      BOOST_TEST(boost::queue_op_status::closed == q.wait_pull(i));
      BOOST_TEST(q.empty());
      BOOST_TEST(q.closed());
  }
  return boost::report_errors();
}

max_stars_repo_name: tempoz/thread

max_issues_repo_name: tempoz/thread

max_forks_repo_name: tempoz/thread


text:
/*
 *
 * Copyright (c) 2002, 2003 Kresimir Fresl, Toon Knapen and Karl Meerbergen
 *
 * 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)
 *
 * KF acknowledges the support of the Faculty of Civil Engineering,
 * University of Zagreb, Croatia.
 *
 */

#ifndef BOOST_NUMERIC_BINDINGS_TRAITS_UBLAS_VECTOR_H
#define BOOST_NUMERIC_BINDINGS_TRAITS_UBLAS_VECTOR_H

#include <boost/numeric/bindings/traits/vector_traits.hpp>

#ifndef BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS

#ifndef BOOST_UBLAS_HAVE_BINDINGS
#  include <boost/numeric/ublas/vector.hpp>
#endif

namespace boost { namespace numeric { namespace bindings { namespace traits {

  // ublas::vector<>
  template <typename T, typename ArrT, typename V>
  struct vector_detail_traits< boost::numeric::ublas::vector<T, ArrT>, V >
  : default_vector_traits< V, T >
  {
#ifndef BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK
    BOOST_STATIC_ASSERT( (boost::is_same< boost::numeric::ublas::vector<T, ArrT>, typename boost::remove_const<V>::type >::value) );
#endif

    typedef boost::numeric::ublas::vector<T, ArrT>          identifier_type;
    typedef V                                               vector_type;
    typedef typename default_vector_traits< V, T >::pointer pointer;

    static pointer storage (vector_type& v) {
      typedef typename detail::generate_const<V,ArrT>::type array_type ;
      return vector_traits<array_type>::storage (v.data());
    }
  };

  // ublas::vector_reference<>
  template <typename V, typename VR>
  struct vector_detail_traits< boost::numeric::ublas::vector_reference<V>, VR >
  : default_vector_traits< VR, typename V::value_type >
  {
#ifndef BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK
    BOOST_STATIC_ASSERT( (boost::is_same< boost::numeric::ublas::vector_reference<V>, typename boost::remove_const<VR>::type >::value) );
#endif

    typedef boost::numeric::ublas::vector_reference<V>             identifier_type;
    typedef VR                                                     vector_type;
    typedef typename V::value_type                                 value_type ;
    typedef typename default_vector_traits<VR,value_type>::pointer pointer;

  private:
    typedef typename detail::generate_const<VR,V>::type vct_t;

  public:
    static pointer storage (vector_type& v) {
      return vector_traits<vct_t>::storage (v.expression());
    }
    static std::ptrdiff_t stride (vector_type& v) {
      return vector_traits<vct_t>::stride (v.expression());
    }
  };

  // ublas::vector_range<>
  template <typename V, typename VR>
  struct vector_detail_traits< boost::numeric::ublas::vector_range<V>, VR >
  : default_vector_traits< VR, typename V::value_type >
  {
#ifndef BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK
    BOOST_STATIC_ASSERT( (boost::is_same< boost::numeric::ublas::vector_range<V>, typename boost::remove_const<VR>::type >::value) );
#endif

    typedef boost::numeric::ublas::vector_range<V>                 identifier_type;
    typedef VR                                                     vector_type;
    typedef typename V::value_type                                 value_type ;
    typedef typename default_vector_traits<VR,value_type>::pointer pointer;

  private:
    typedef typename detail::generate_const<VR, typename VR::vector_closure_type>::type v_type;

  public:
    static pointer storage (vector_type& vr) {
      pointer ptr = vector_traits<v_type>::storage (vr.data());
      ptr += vr.start() * vector_traits<v_type>::stride (vr.data());
      return ptr;
    }
    static std::ptrdiff_t stride (vector_type& vr) {
      return vector_traits<v_type>::stride (vr.data());
    }
  };

  // ublas::vector_slice<>
  template <typename V, typename VS>
  struct vector_detail_traits<boost::numeric::ublas::vector_slice<V>, VS >
  : default_vector_traits< VS, typename V::value_type >
  {
#ifndef BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK
    BOOST_STATIC_ASSERT( (boost::is_same< boost::numeric::ublas::vector_slice<V>, typename boost::remove_const<VS>::type >::value) );
#endif

    typedef boost::numeric::ublas::vector_slice<V>                 identifier_type;
    typedef VS                                                     vector_type;
    typedef typename V::value_type                                 value_type ;
    typedef typename default_vector_traits<VS,value_type>::pointer pointer;

  private:
    typedef typename detail::generate_const<VS, typename VS::vector_closure_type>::type v_type;

  public:
    static pointer storage (vector_type& vs) {
      pointer ptr = vector_traits<v_type>::storage (vs.data());
      ptr += vs.start() * vector_traits<v_type>::stride (vs.data());
      return ptr;
    }
    static std::ptrdiff_t stride (vector_type& vs) {
      return vs.stride() * vector_traits<v_type>::stride (vs.data());
    }
  };

#ifndef BOOST_NUMERIC_BINDINGS_FORTRAN

  // (undocumented) ublas::c_vector<>
  template <typename T, std::size_t N, typename V>
  struct vector_detail_traits< boost::numeric::ublas::c_vector<T, N>, V >
  : default_vector_traits< V, T >
  {
#ifndef BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK
    BOOST_STATIC_ASSERT( (boost::is_same< boost::numeric::ublas::c_vector<T,N>, typename boost::remove_const<V>::type >::value) );
#endif

    typedef boost::numeric::ublas::c_vector<T,N>         identifier_type;
    typedef V                                            vector_type;
    typedef typename default_vector_traits<V,T>::pointer pointer;

    static pointer storage (vector_type& v) { return v.data(); }
  };

#endif // BOOST_NUMERIC_BINDINGS_FORTRAN

  // ublas::bounded_vector<>
  template <typename T, std::size_t N, typename V>
  struct vector_detail_traits< boost::numeric::ublas::bounded_vector<T, N>, V >
  : default_vector_traits< V, T >
  {
#ifndef BOOST_NUMERIC_BINDINGS_NO_SANITY_CHECK
    BOOST_STATIC_ASSERT( (boost::is_same< boost::numeric::ublas::bounded_vector<T, N>, typename boost::remove_const<V>::type >::value) );
#endif

    typedef boost::numeric::ublas::bounded_vector<T, N>     identifier_type;
    typedef V                                               vector_type;
    typedef typename default_vector_traits< V, T >::pointer pointer;

    static pointer storage (vector_type& v) {
      typedef typename detail::generate_const<V,typename identifier_type::array_type>::type array_type ;
      return vector_traits<array_type>::storage (v.data());
    }
  };

}}}}

#endif // BOOST_NUMERIC_BINDINGS_POOR_MANS_TRAITS

#endif // BOOST_NUMERIC_BINDINGS_TRAITS_UBLAS_VECTOR_H

max_stars_repo_name: diku-dk/PROX

max_issues_repo_name: jdsika/holy

max_forks_repo_name: jdsika/holy


text: #include <boost/heap/heap_merge.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_ParticleLeavingCellEventObserver.hpp
//! \author Alex Robinson
//! \brief  Particle leaving cell event observer base class declaration.
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_PARTICLE_LEAVING_CELL_EVENT_OBSERVER_HPP
#define MONTE_CARLO_PARTICLE_LEAVING_CELL_EVENT_OBSERVER_HPP

// Boost Includes
#include <boost/serialization/split_member.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/shared_ptr.hpp>

// FRENSIE Includes
#include "MonteCarlo_ParticleEventTags.hpp"
#include "MonteCarlo_ParticleState.hpp"
#include "Geometry_Model.hpp"
#include "Utility_Vector.hpp"
#include "Utility_ExplicitSerializationTemplateInstantiationMacros.hpp"
#include "Utility_SerializationHelpers.hpp"

namespace MonteCarlo{

/*! The particle leaving cell event observer base class
 * \ingroup particle_leaving_cell_event
 */
class ParticleLeavingCellEventObserver{

public:

  //! Typedef for the observer event
  typedef ParticleLeavingCellEvent EventTag;

  //! Constructor
  ParticleLeavingCellEventObserver()
  { /* ... */ }

  //! Destructor
  virtual ~ParticleLeavingCellEventObserver()
  { /* ... */ }

  //! Update the observer
  virtual void updateFromParticleLeavingCellEvent(
	   const ParticleState& particle,
	   const Geometry::Model::EntityId cell_leaving ) = 0;

private:

  // Serialize the observer
  template<typename Archive>
  void serialize( Archive& ar, const unsigned version )
  { /* ... */ }

  // Declare the boost serialization access object as a friend
  friend class boost::serialization::access;
};

} // end MonteCarlo namespace

BOOST_CLASS_VERSION( MonteCarlo::ParticleLeavingCellEventObserver, 0 );
BOOST_SERIALIZATION_ASSUME_ABSTRACT( MonteCarlo::ParticleLeavingCellEventObserver );
EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( MonteCarlo, ParticleLeavingCellEventObserver );

#endif // end MONTE_CARLO_PARTICLE_LEAVING_CELL_EVENT_OBSERVER_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_ParticleLeavingCellEventObserver.hpp
//---------------------------------------------------------------------------//


text:
#pragma once

#include <ros/ros.h>
#include <cav_msgs/MobilityOperation.h>
#include <cav_msgs/MobilityRequest.h>
#include <cav_msgs/MobilityResponse.h>
#include <cav_msgs/PlanType.h>
#include "pid_controller.hpp"
#include "pure_pursuit.hpp"
#include <boost/optional.hpp>

namespace platoon_control
{

	struct PlatoonLeaderInfo{
            // Static ID is permanent ID for each vehicle
            std::string staticId;
            // Current BSM Id for each CAV
            std::string bsmId;
            // Vehicle real time command speed in m/s
            double commandSpeed;
            // Actual vehicle speed in m/s
            double vehicleSpeed;
            // Vehicle current down track distance on the current route in m
            double vehiclePosition;
            // The local time stamp when the host vehicle update any informations of this member
            long   timestamp;
            // leader index in the platoon
            int leaderIndex;
            // Number of vehicles in front
            int NumberOfVehicleInFront;

            // PlatoonMember(std::string staticId, std::string bsmId, double commandSpeed, double vehicleSpeed, double vehiclePosition, long timestamp): staticId(staticId),
            // bsmId(bsmId), commandSpeed(commandSpeed), vehicleSpeed(vehicleSpeed), timestamp(timestamp) {}
        };

        // Leader info: platoonmember + leader index + number of vehicles in front

    class PlatoonControlWorker
    {
    public:

        PlatoonControlWorker();

        double getLastSpeedCommand() const;

        // Update speed commands based on the list of platoon members
        void generateSpeed(const cav_msgs::TrajectoryPlanPoint& point);
        void generateSteer(const cav_msgs::TrajectoryPlanPoint& point);

        // set platoon leader
        void setLeader(const PlatoonLeaderInfo& leader);
        void setCurrentSpeed(double speed);

        double speedCmd;
        double currentSpeed;
        double adjustmentCap = 10.0;
        double lastCmdSpeed = 0.0;

        double speedCmd_ = 0;
        double steerCmd_ = 0;

        PlatoonLeaderInfo platoon_leader;

        // platooning_desired_time_headway"
        double timeHeadway = 2.0;
        // platooning standstillheadway"
        double standStillHeadway = 12.0;

        void setCurrentPose(const geometry_msgs::PoseStampedConstPtr& msg)
		{
			current_pose = msg->pose;
		}

		// geometry pose
		geometry_msgs::Pose current_pose;

    private:

        // pid controller object
        PIDController pid_ctrl_;

        // pure pursuit controller object
        PurePursuit pp_;

    	double maxAccel = 2.5; // m/s/s

    	double desiredTimeGap = 1.0; // s

        double desiredGap_ = 0.0;

        long CMD_TIMESTEP = 100;

        double getCurrentDowntrackDistance(const cav_msgs::TrajectoryPlanPoint& point);

        double dist_to_front_vehicle;

        bool enableMaxAdjustmentFilter = leaderSpeedCapEnabled;
        bool leaderSpeedCapEnabled = true;

        bool enableLocalSpeedLimitFilter = speedLimitCapEnabled;
        bool speedLimitCapEnabled = true;

        bool enableMaxAccelFilter = maxAccelCapEnabled;
        bool maxAccelCapEnabled = true;

    };
}

max_stars_repo_name: harderthan/carma-platform

max_issues_repo_name: harderthan/carma-platform

max_forks_repo_name: harderthan/carma-platform


text:
//
//  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
//  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)
//
#ifdef BOOST_LOCALE_NO_POSIX_BACKEND
#include <iostream>
int main()
{
        std::cout << "POSIX Backend is not build... Skipping" << std::endl;
}
#else
#include <boost/locale/config.hpp>
#include <boost/locale/conversion.hpp>
#include <boost/locale/localization_backend.hpp>
#include <boost/locale/generator.hpp>
#include <boost/locale/info.hpp>
#include <iomanip>
#include "test_locale.hpp"
#include "test_locale_tools.hpp"
#include "test_posix_tools.hpp"
#include <iostream>

int get_sign(int x)
{
    if(x<0)
        return -1;
    else if(x==0)
        return 0;
    return 1;
}

template<typename CharType>
void test_one(std::locale const &l,std::string ia,std::string ib,int diff)
{
    std::basic_string<CharType> a=to_correct_string<CharType>(ia,l);
    std::basic_string<CharType> b=to_correct_string<CharType>(ib,l);
    if(diff < 0) {
        TEST(l(a,b));
        TEST(!l(b,a));
    }
    else if(diff == 0) {
        TEST(!l(a,b));
        TEST(!l(b,a));
    }
    else {
        TEST(!l(a,b));
        TEST(l(b,a));
    }

    std::collate<CharType> const &col = std::use_facet<std::collate<CharType> >(l);

    TEST(diff == col.compare(a.c_str(),a.c_str()+a.size(),b.c_str(),b.c_str()+b.size()));
    TEST(diff == get_sign(col.transform(a.c_str(),a.c_str()+a.size()).compare(col.transform(b.c_str(),b.c_str()+b.size()))));
    if(diff == 0) {
        TEST(col.hash(a.c_str(),a.c_str()+a.size()) == col.hash(b.c_str(),b.c_str()+b.size()));
    }
}

template<typename CharType>
void test_char()
{
    boost::locale::generator gen;

    std::cout << "- Testing at least C" << std::endl;

    std::locale l = gen("en_US.UTF-8");

    test_one<CharType>(l,"a","b",-1);
    test_one<CharType>(l,"a","a",0);

    std::string name;

    #ifndef __APPLE__
    std::string names[] = { "en_US.UTF-8", "en_US.ISO8859-1" };
    for(unsigned i=0;i<sizeof(names)/sizeof(names[0]);i++) {
        if(have_locale(names[i])) {
            name = names[i];
            std::cout << "- Testing " << name << std::endl;
            std::locale l=gen(name);
            test_one<CharType>(l,"a","ç",-1);
            test_one<CharType>(l,"ç","d",-1);
        }
        else {
            std::cout << "- " << names[i] << " not supported, skipping" << std::endl;
        }
    }
    #else
    std::cout << "- Collation is broken in Mac OS X's C standard library, skipping" << std::endl;
    #endif
}

int main()
{
    try {
        boost::locale::localization_backend_manager mgr = boost::locale::localization_backend_manager::global();
        mgr.select("posix");
        boost::locale::localization_backend_manager::global(mgr);

        std::cout << "Testing char" << std::endl;
        test_char<char>();
        std::cout << "Testing wchar_t" << std::endl;
        test_char<wchar_t>();
    }
    catch(std::exception const &e) {
        std::cerr << "Failed " << e.what() << std::endl;
        return EXIT_FAILURE;
    }
    FINALIZE();

}
#endif  // NO POSIX
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

// boostinspect:noascii


text:
//---------------------------------------------------------------------------//
//!
//! \file   Utility_Measurement.hpp
//! \author Alex Robinson
//! \brief  The measurement class declaration. This object is based of of the
//!         measurement class in the boost::units examples
//!
//---------------------------------------------------------------------------//

#ifndef UTILITY_MEASUREMENT_HPP
#define UTILITY_MEASUREMENT_HPP

// Boost Includes
#include <boost/units/config.hpp>
#include <boost/units/operators.hpp>
#include <boost/typeof/typeof.hpp>

// Trilinos Includes
#include <Teuchos_ScalarTraits.hpp>

// FRENSIE Includes
#include "Utility_PrintableObject.hpp"
#include "Utility_ContractException.hpp"

namespace Utility{

/*! The measurement class
 *
 * This class wraps is meant to be used as any typical scalar type
 * (e.g. double). It is designed to keep track of and propagate the
 * uncertainty of a value (like one would with a measured quantity).
 */
template<typename T>
class Measurement : public PrintableObject
{

private:

  // The scalar traits typedef
  typedef Teuchos::ScalarTraits<T> ST;

public:

  //! The typedef for this type
  typedef Measurement<T> ThisType;

  //! The typedef for the value type
  typedef T ValueType;

  //! Constructor
  Measurement( const ValueType& value = ValueType(),
	       const ValueType& uncertainty = ValueType() );

  //! Copy constructor
  Measurement( const ThisType& other_measurement );

  //! Destructor
  ~Measurement()
  { /* ... */ }

  //! Print method
  void print( std::ostream& os ) const;

  //! Return the value of the measurement
  const ValueType& getValue() const;

  //! Return the uncertainty of the measurement
  const ValueType& getUncertainty() const;

  //! Return the relative uncertainty of the measurement
  const ValueType getRelativeUncertainty() const;

  //! Return the lower bound of the measurement
  const ValueType getLowerBound() const;

  //! Return the upper bound of the measurement
  const ValueType getUpperBound() const;

  //! Implicit conversion to value type
  operator ValueType() const;

  //! In-place addition operator
  ThisType& operator+=( const ValueType& value );

  //! In-place addition operator
  ThisType& operator+=( const ThisType& other_measurement );

  //! In-place subtraction operator
  ThisType& operator-=( const ValueType& value );

  //! In-place subtraction operator
  ThisType& operator-=( const ThisType& other_measurement );

  //! In-place multiplication operator
  ThisType& operator*=( const ValueType& value );

  //! In-place multiplication operator
  ThisType& operator*=( const ThisType& other_measurement );

  //! In-place division operator
  ThisType& operator/=( const ValueType& value );

  //! In-place division operator
  ThisType& operator/=( const ThisType& other_measurement );

private:

  // The measurement value
  ValueType d_value;

  // The measurement uncertainty
  ValueType d_uncertainty;
};

//! Addition operator
template<typename T>
inline Measurement<T> operator+( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs, T(0) ) += rhs);

  testNestedConditionsEnd(1);
}

//! Addition operator
template<typename T>
inline Measurement<T> operator+( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) += Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Addition operator
template<typename T>
inline Measurement<T> operator+( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) += rhs );

  testNestedConditionsEnd(1);
}

//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs, T(0) ) -= rhs);

  testNestedConditionsEnd(1);
}

//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) -= Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Subtraction operator
template<typename T>
inline Measurement<T> operator-( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) -= rhs );

  testNestedConditionsEnd(1);
}

//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs, T(0) ) *= rhs);

  testNestedConditionsEnd(1);
}

//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) *= Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Multiplication operator
template<typename T>
inline Measurement<T> operator*( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) *= rhs );

  testNestedConditionsEnd(1);
}

//! Division operator
template<typename T>
inline Measurement<T> operator/( T lhs, const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  // Make sure nested conditions are met
  return (Measurement<T>( lhs, T(0) ) /= rhs);

  testNestedConditionsEnd(1);
}

//! Division operator
template<typename T>
inline Measurement<T> operator/( const Measurement<T>& lhs, T rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) /= Measurement<T>( rhs, T(0) ));

  testNestedConditionsEnd(1);
}

//! Division operator
template<typename T>
inline Measurement<T> operator/( const Measurement<T>& lhs,
				 const Measurement<T>& rhs )
{
  // Make sure nested conditions are met
  testNestedConditionsBegin(1);

  return (Measurement<T>( lhs ) /= rhs );

  testNestedConditionsEnd(1);
}

//! Overload of sqrt for a measurement
template<typename T>
inline Measurement<T> sqrt( const Measurement<T>& x )
{
  // Make sure the measurement is valid
  testPrecondition( x.getValue() >= 0.0 );

  const T new_value = std::sqrt( x.getValue() );

  const T propagated_uncertainty = 0.5*(new_value/x.getValue())*
    x.getUncertainty();

  // Make sure reasonable values have been calculated
  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) );
  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf(
						    propagated_uncertainty ) );

  return Measurement<T>( new_value, propagated_uncertainty );
}

//! Overload of pow for a measurement
template<typename T, typename ExponentType>
inline Measurement<T> pow( const Measurement<T>& x,
			   const ExponentType exponent )
{
  const T new_value = std::pow( x.getValue(), exponent );

  const T propagated_uncertainty = fabs(exponent*(new_value/x.getValue()))*
    x.getUncertainty();

  // Make sure reasonable values have been calculated
  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf( new_value ) );
  testPostcondition( !Teuchos::ScalarTraits<T>::isnaninf(
						    propagated_uncertainty ) );
  testPostcondition( propagated_uncertainty >= 0.0 );

  return Measurement<T>( new_value, propagated_uncertainty );
}

} // end Utility namespace

namespace boost{

namespace units{

//! Specialization of the boost::units::power_typeof_helper
template<typename Y, long N, long D>
struct power_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> >
{
  typedef Utility::Measurement<typename power_typeof_helper<Y,static_rational<N,D> >::type> type;

  static type value( const Utility::Measurement<Y>& x)
  {
    const static_rational<N,D> rational;

    const Y rational_power = Y(rational.numerator())/Y(rational.denominator());

    return Utility::pow( x, rational_power );
  }
};

//! Specialization of the boost::units::root_typeof_helper
template<typename Y, long N, long D>
struct root_typeof_helper<Utility::Measurement<Y>,static_rational<N,D> >
{
  typedef Utility::Measurement<typename root_typeof_helper<Y,static_rational<N,D> >::type> type;

  static type value( const Utility::Measurement<Y>& x )
  {
    const static_rational<N,D> rational;

    // Compute D/N instead of N/D since we're interested in the root
    const Y rational_power = Y(rational.denominator())/Y(rational.numerator());

    return Utility::pow( x, rational_power );
  }
};

} // end units namespace

} // end boost namespace

namespace Teuchos{

//! Partial specialization of Teuchos::ScalarTraits for the Measurement class
template<typename T>
struct ScalarTraits<Utility::Measurement<T> >
{
  typedef Utility::Measurement<T> Measurement;
  typedef T magnitudeType;
  typedef typename Teuchos::ScalarTraits<T>::halfPrecision halfPrecision;
  typedef typename Teuchos::ScalarTraits<T>::doublePrecision doublePrecision;

  static const bool isComplex = Teuchos::ScalarTraits<T>::isComplex;
  static const bool isOrdinal = Teuchos::ScalarTraits<T>::isOrdinal;
  static const bool isComparable = Teuchos::ScalarTraits<T>::isComparable;
  static const bool hasMachineParameters = Teuchos::ScalarTraits<T>::hasMachineParameters;

  static inline magnitudeType eps() { return ScalarTraits<magnitudeType>::eps(); }
  static inline magnitudeType sfmin() { return ScalarTraits<magnitudeType>::sfmin(); }
  static inline magnitudeType base() { return ScalarTraits<magnitudeType>::base(); }
  static inline magnitudeType prec() { return ScalarTraits<magnitudeType>::prec(); }
  static inline magnitudeType t() { return ScalarTraits<magnitudeType>::t(); }
  static inline magnitudeType rnd() { return ScalarTraits<magnitudeType>::rnd(); }
  static inline magnitudeType emin() { return ScalarTraits<magnitudeType>::emin(); }
  static inline magnitudeType rmin() { return ScalarTraits<magnitudeType>::rmin(); }
  static inline magnitudeType emax() { return ScalarTraits<magnitudeType>::emax(); }
  static inline magnitudeType rmax() { return ScalarTraits<magnitudeType>::rmax(); }
  static inline magnitudeType magnitude(Measurement a) { return ScalarTraits<magnitudeType>::magnitude( a.getValue() ); }
  static inline Measurement zero() { return Measurement( ScalarTraits<magnitudeType>::zero(), 0.0 ); }
  static inline Measurement one() { return Measurement( ScalarTraits<magnitudeType>::zero(), 1.0 ); }
  static inline Measurement conjugate(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::conjugate(a.getValue()), ScalarTraits<magnitudeType>::conjugate(a.getUncertainty()) ); }
  static inline Measurement real(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::real(a.getValue()), ScalarTraits<magnitudeType>::real(a.getUncertainty()) ); }
  static inline Measurement imag(Measurement a){ return Measurement( ScalarTraits<magnitudeType>::imag(a.getValue()), ScalarTraits<magnitudeType>::imag(a.getUncertainty()) ); }
  static inline Measurement nan() { return Measurement( ScalarTraits<magnitudeType>::nan(), ScalarTraits<magnitudeType>::nan() ); }
  static inline bool isnaninf(Measurement a){ return ScalarTraits<magnitudeType>::isnaninf(a.getValue()) || ScalarTraits<magnitudeType>::isnaninf(a.getUncertainty()); }
  static inline void seedrandom(unsigned int s) { ScalarTraits<magnitudeType>::seedrandom(s); }
  static inline Measurement random() { return Measurement( ScalarTraits<magnitudeType>::random(), 0.0 ); }
  static inline std::string name() { return std::string("Measurement<")+std::string(ScalarTraits<magnitudeType>::name())+std::string(">"); }
  static inline Measurement squareroot(Measurement a) { return Utility::sqrt(a); }
  static inline Measurement pow(Measurement a, Measurement b) { return Utility::pow( a, b.getValue() ); }

};

} // end Teuchos namespace

// Register the Measurement class with boost typeof for auto-like type
// deduction when used with the boost::units library
#if BOOST_UNITS_HAS_BOOST_TYPEOF

BOOST_TYPEOF_REGISTER_TEMPLATE(Utility::Measurement, 1)

#endif // end BOOST_UNITS_HAS_BOOST_TYPEOF

//---------------------------------------------------------------------------//
// Template Includes
//---------------------------------------------------------------------------//

#include "Utility_Measurement_def.hpp"

//---------------------------------------------------------------------------//

#endif // end UTILITY_MEASUREMENT_HPP

//---------------------------------------------------------------------------//
// end Utility_Measurement.hpp
//---------------------------------------------------------------------------//