text:
//
// Boost.Pointer Container
//
//  Copyright Thorsten Ottosen 2008. Use, modification and
//  distribution is subject to the Boost Software License, Version
//  1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
// For more information, see http://www.boost.org/libs/ptr_container/
//

#ifndef BOOST_PTR_CONTAINER_PTR_UNORDERED_SET_HPP
#define BOOST_PTR_CONTAINER_PTR_UNORDERED_SET_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <boost/ptr_container/indirect_fun.hpp>
#include <boost/ptr_container/ptr_set_adapter.hpp>
#include <boost/unordered_set.hpp>

namespace boost
{

    template
    <
        class Key,
        class Hash           = boost::hash<Key>,
        class Pred           = std::equal_to<Key>,
        class CloneAllocator = heap_clone_allocator,
        class Allocator      = std::allocator<void*>
    >
    class ptr_unordered_set :
        public ptr_set_adapter< Key,
                                boost::unordered_set<void*,void_ptr_indirect_fun<Hash,Key>,
                                                     void_ptr_indirect_fun<Pred,Key>,Allocator>,
                                CloneAllocator, false >
    {
        typedef ptr_set_adapter< Key,
                                 boost::unordered_set<void*,void_ptr_indirect_fun<Hash,Key>,
                                 void_ptr_indirect_fun<Pred,Key>,Allocator>,
                                 CloneAllocator, false >
             base_type;

        typedef ptr_unordered_set<Key,Hash,Pred,CloneAllocator,Allocator> this_type;

    public:
        typedef typename base_type::size_type size_type;

    private:
        using base_type::lower_bound;
        using base_type::upper_bound;
        using base_type::rbegin;
        using base_type::rend;
        using base_type::crbegin;
        using base_type::crend;
        using base_type::key_comp;
        using base_type::value_comp;
        using base_type::front;
        using base_type::back;

    public:
        using base_type::begin;
        using base_type::end;
        using base_type::cbegin;
        using base_type::cend;
        using base_type::bucket_count;
        using base_type::max_bucket_count;
        using base_type::bucket_size;
        using base_type::bucket;
        using base_type::load_factor;
        using base_type::max_load_factor;
        using base_type::rehash;
        using base_type::key_eq;
        using base_type::hash_function;

    public:
        ptr_unordered_set()
        {}

        explicit ptr_unordered_set( size_type n )
        : base_type( n, ptr_container_detail::unordered_associative_container_tag() )
        { }

        ptr_unordered_set( size_type n,
                           const Hash& comp,
                           const Pred& pred   = Pred(),
                           const Allocator& a = Allocator() )
         : base_type( n, comp, pred, a )
        { }

        template< typename InputIterator >
        ptr_unordered_set( InputIterator first, InputIterator last )
         : base_type( first, last )
        { }

        template< typename InputIterator >
        ptr_unordered_set( InputIterator first, InputIterator last,
                           const Hash& comp,
                           const Pred& pred   = Pred(),
                           const Allocator& a = Allocator() )
         : base_type( first, last, comp, pred, a )
        { }

        BOOST_PTR_CONTAINER_DEFINE_RELEASE_AND_CLONE( ptr_unordered_set,
                                                      base_type,
                                                      this_type )

        BOOST_PTR_CONTAINER_DEFINE_COPY_CONSTRUCTORS( ptr_unordered_set,
                                                      base_type )

    };

    template
    <
        class Key,
        class Hash           = boost::hash<Key>,
        class Pred           = std::equal_to<Key>,
        class CloneAllocator = heap_clone_allocator,
        class Allocator      = std::allocator<void*>
    >
    class ptr_unordered_multiset :
          public ptr_multiset_adapter< Key,
                                boost::unordered_multiset<void*,void_ptr_indirect_fun<Hash,Key>,
                                                                void_ptr_indirect_fun<Pred,Key>,Allocator>,
                                            CloneAllocator, false >
    {
      typedef ptr_multiset_adapter< Key,
              boost::unordered_multiset<void*,void_ptr_indirect_fun<Hash,Key>,
                                        void_ptr_indirect_fun<Pred,Key>,Allocator>,
                                        CloneAllocator, false >
              base_type;
        typedef ptr_unordered_multiset<Key,Hash,Pred,CloneAllocator,Allocator> this_type;

    public:
        typedef typename base_type::size_type size_type;

    private:
        using base_type::lower_bound;
        using base_type::upper_bound;
        using base_type::rbegin;
        using base_type::rend;
        using base_type::crbegin;
        using base_type::crend;
        using base_type::key_comp;
        using base_type::value_comp;
        using base_type::front;
        using base_type::back;

    public:
        using base_type::begin;
        using base_type::end;
        using base_type::cbegin;
        using base_type::cend;
        using base_type::bucket_count;
        using base_type::max_bucket_count;
        using base_type::bucket_size;
        using base_type::bucket;
        using base_type::load_factor;
        using base_type::max_load_factor;
        using base_type::rehash;
        using base_type::key_eq;
        using base_type::hash_function;

    public:
        ptr_unordered_multiset()
        { }

        explicit ptr_unordered_multiset( size_type n )
         : base_type( n, ptr_container_detail::unordered_associative_container_tag() )
        { }

        ptr_unordered_multiset( size_type n,
                                const Hash& comp,
                                const Pred& pred   = Pred(),
                                const Allocator& a = Allocator() )
         : base_type( n, comp, pred, a )
        { }

        template< typename InputIterator >
        ptr_unordered_multiset( InputIterator first, InputIterator last )
         : base_type( first, last )
        { }

        template< typename InputIterator >
        ptr_unordered_multiset( InputIterator first, InputIterator last,
                                const Hash& comp,
                                const Pred& pred   = Pred(),
                                const Allocator& a = Allocator() )
         : base_type( first, last, comp, pred, a )
        { }

        BOOST_PTR_CONTAINER_DEFINE_RELEASE_AND_CLONE( ptr_unordered_multiset,
                                                      base_type,
                                                      this_type )

        BOOST_PTR_CONTAINER_DEFINE_COPY_CONSTRUCTORS( ptr_unordered_multiset,
                                                      base_type )

    };

    /////////////////////////////////////////////////////////////////////////
    // clonability

    template< typename K, typename H, typename P, typename CA, typename A >
    inline ptr_unordered_set<K,H,P,CA,A>*
    new_clone( const ptr_unordered_set<K,H,P,CA,A>& r )
    {
        return r.clone().release();
    }

    template< typename K, typename H, typename P, typename CA, typename A >
    inline ptr_unordered_multiset<K,H,P,CA,A>*
    new_clone( const ptr_unordered_multiset<K,H,P,CA,A>& r )
    {
        return r.clone().release();
    }

    /////////////////////////////////////////////////////////////////////////
    // swap

    template< typename K, typename H, typename P, typename CA, typename A >
    inline void swap( ptr_unordered_set<K,H,P,CA,A>& l,
                      ptr_unordered_set<K,H,P,CA,A>& r )
    {
        l.swap(r);
    }

    template< typename K, typename H, typename P, typename CA, typename A >
    inline void swap( ptr_unordered_multiset<K,H,P,CA,A>& l,
                      ptr_unordered_multiset<K,H,P,CA,A>& r )
    {
        l.swap(r);
    }

}

#endif


text:
/*!
  Copyright (c) 2012, Leon Mergen, all rights reserved.
 */

#ifndef LIBPAXOS_CPP_EXCEPTION_EXCEPTION_HPP
#define LIBPAXOS_CPP_EXCEPTION_EXCEPTION_HPP

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

namespace paxos { namespace exception {

/*!
  \brief Base class for all our exceptions
 */
class exception : virtual public std::exception,
                  virtual public boost::exception {};

/*!
  \brief Thrown when the callback function of multiple paxos::server instances
         do not reply with the same output for the same input

  As described in the documentation of paxos::server, it is a requirement of the
  callback function of a paxos::server to always return the exact same response for
  similar commands.

  In other words, consider this example:

  \li server 1 replies to paxos message 123 with response "foo"
  \li server 2 replies to paxos message 123 with response "bar"
  \li since the responses do not match, an exception will be thrown.

 */
class inconsistent_response : virtual public exception {};

/*!
  \brief Thrown when there is no known leader in the quorum

  Usually occurs right after launching a quorum and should recover upon next retry.
 */
class no_leader : virtual public exception {};

/*!
  \brief Thrown when there is no majority of servers reachable to the current leader

  There is a built-in protection in the library to ensure that at least a certain percentage
  of followers are reachable in order to make progress. This prevents the situation that multiple
  representations of the current truth exist within the same quorum of servers.

  There are two likely situations that this exception can be thrown:

  \li not enough servers are alive;
  \li enough servers are alive, but due to networking error (netsplits) they are not all reachable
      to each other.

  The second scenario is the situation this exception helps the most in: in case of one datacenter
  being cut off from the outside world, it prevents that datacenter of building up a different
  understanding of the truth compared to the other, alive, datacenters.
 */
class no_majority : virtual public exception {};

/*!
  \brief Thrown when a follower does not agree with the proposal id being sent by a leader

  Usually occurs in leader failover or at the end of a netsplit and should recover upon next retry.
 */
class incorrect_proposal : virtual public exception {};

/*!
  \brief Thrown when a follower/client connection has unexpectedly closed

  Usually occurs after a follower has disconnected from the quorum and should recover upon next retry.
 */
class connection_close : virtual public exception {};

/*!
  \brief Thrown when an error occured with a durable storage component
 */
class storage_error : virtual public exception {};

} };

#endif  //! LIBPAXOS_CPP_EXCEPTION_EXCEPTION_HPP

ext: hpp

max_stars_repo_name: armos-db/libpaxos-cpp

max_issues_repo_name: armos-db/libpaxos-cpp

max_forks_repo_name: armos-db/libpaxos-cpp


text:
/**
 * @author
 *
 * \section Description
 * This file was generated by Aldebaran Robotics ModuleGenerator
 */

#include <signal.h>
#include <boost/shared_ptr.hpp>
#include <alcommon/albroker.h>
#include <alcommon/almodule.h>
#include <alcommon/albrokermanager.h>
#include <alcommon/altoolsmain.h>

#include "onfacedetection.h"

#ifdef ONFACEDETECTION_IS_REMOTE
# define ALCALL
#else
# ifdef _WIN32
#  define ALCALL __declspec(dllexport)
# else
#  define ALCALL
# endif
#endif

extern "C"
{
  ALCALL int _createModule(boost::shared_ptr<AL::ALBroker> pBroker)
  {
    // init broker with the main broker instance
    // from the parent executable
    AL::ALBrokerManager::setInstance(pBroker->fBrokerManager.lock());
    AL::ALBrokerManager::getInstance()->addBroker(pBroker);
      AL::ALModule::createModule<OnFaceDetection>( pBroker, "OnFaceDetection" );

    return 0;
  }

  ALCALL int _closeModule()
  {
    return 0;
  }
}

#ifdef ONFACEDETECTION_IS_REMOTE
  int main(int argc, char *argv[])
  {
    // pointer to createModule
    TMainType sig;
    sig = &_createModule;
    // call main
    ALTools::mainFunction("onfacedetection", argc, argv, sig);
  }
#endif

ext: cpp


text:
#include "InputFileOperator.h"
#include "CommandLineHandlers/CommandLineHandler.h"
#include <boost/tokenizer.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/program_options.hpp>

USING_NAMESPACE(std);
USING_NAMESPACE(clu);
namespace po = boost::program_options;

class FilterOperator : public InputFileOperator
{
public:
	FilterOperator(size_t argument_number) : m_argumentNumber(argument_number - 1)
	{
		if (argument_number == 0)
			m_fullline = true;
		else
			m_fullline = false;
	}

	virtual bool OnLineRead(string& input)
	{
		string argument;
		if (m_fullline)
			argument = input;
		else {
			vector<string> tokens;
			ExtractTokens(input, tokens, SpaceDelimiters);

			if (tokens.size() <= m_argumentNumber)
				return true;

			argument = tokens[m_argumentNumber];
		}

		if (shouldPrint(argument))
			m_OutputHandler->OutputLineFeed(input);
		return true;
	}

	virtual bool shouldPrint(string& data) = 0;
protected:
	size_t m_argumentNumber;
	bool m_fullline;
};

class NumericFilter : public FilterOperator
{
public:
	NumericFilter(size_t arg_num, double arg_value) : FilterOperator(arg_num), m_argValue(arg_value)
	{
	}

	virtual bool shouldPrint(string& data)
	{
		double cur_value = atof(data.c_str());
		return shouldPrint(cur_value);
	}

	virtual bool shouldPrint(double value) = 0;
protected:
	double m_argValue;
};

class GreaterThanFilter : public NumericFilter
{
public:
	GreaterThanFilter(int arg_num, double threshold) : NumericFilter(arg_num, threshold)
	{
	}
	virtual bool shouldPrint(double value)
	{
		return m_argValue < value;
	}
};

class LessThanFilter : public NumericFilter
{
public:
	LessThanFilter(int arg_num, double threshold) : NumericFilter(arg_num, threshold) {}
	virtual bool shouldPrint(double value)
	{
		return m_argValue > value;
	};
};

class ContainStringFilter : public FilterOperator
{
public:
	ContainStringFilter(size_t arg_num, string value, bool match) : FilterOperator(arg_num), m_match(match)
	{
		m_search_regex = boost::regex(value.c_str());
	}
	virtual bool shouldPrint(string& data)
	{
		bool ret_value = false;
		if (m_match)
			ret_value = boost::regex_match(data, m_search_regex);
		else
			ret_value = boost::regex_search(data, m_search_regex);

		return ret_value;
	}
protected:
	boost::regex m_search_regex;
	bool m_match;
};

class NotContainStringFilter : public ContainStringFilter
{
public:
	NotContainStringFilter(int arg_num, string value, bool match) : ContainStringFilter(arg_num, value, match)
	{
	}

	virtual bool shouldPrint(string& data)
	{
		return ContainStringFilter::shouldPrint(data);
	}
};

class Filter_CommandLine : public InputFileOperator_CommandLine
{
public:
	virtual bool AddProgramOptions(po::options_description& desc)
	{
		desc.add_options()
			("filter,f", po::value<int>(), "Filter Operator - Filter argument")
			("larger,l", po::value<double>(), "Filter Operator - Larger")
			("smaller,s", po::value<double>(), "Filter Operator - Smaller")
			("contains", po::value<string>(), "Filter Operator - Contains")
			("ncontains", po::value<string>(), "Filter Operator - Not Contains")
			("reg", po::bool_switch(), "Filter Operator - Contains / Not Contains regular expression, also in start stop operations");
		return true;
	}

	virtual InputFileOperator* GetOperator(const po::variables_map &vm)
	{
		InputFileOperator* listener = NULL;
		if (vm.count("filter")) {
			int filter_value = vm["filter"].as<int>();
			if (vm.count("larger")) {
				double larger_value = vm["larger"].as<double>();
				listener = new GreaterThanFilter(filter_value, larger_value);
			}
			if (vm.count("smaller")) {
				double smaller_value = vm["smaller"].as<double>();
				listener = new LessThanFilter(filter_value, smaller_value);
			}

			bool match = false;
			if (vm.count("reg") && vm["reg"].as<bool>())
				match = true;
			if (vm.count("contains")) {
				const string& contains_value = vm["contains"].as<string>();
				listener = new ContainStringFilter(filter_value, contains_value, match);
			}
			if (vm.count("ncontains")) {
				const string& ncontains_value = vm["ncontains"].as<string>();
				listener = new NotContainStringFilter(filter_value, ncontains_value, match);
			}
		}
		return listener;
	}
};

static auto nameRegisterVar = CommandLineHandler::GetInstance().AddCommandLineHandler(new Filter_CommandLine());

max_stars_repo_name: ShaiRoitman/clu

max_issues_repo_name: ShaiRoitman/clu

max_forks_repo_name: ShaiRoitman/clu


text:
//
// Created by akhil on 17.05.17.
//

#ifndef VISUALIZER_HPP
#define VISUALIZER_HPP

#include <Libs/Structures.hpp>
#include <pcl/visualization/pcl_visualizer.h>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/mersenne_twister.hpp>

class Visualizer {
public:

    Visualizer(){
    }

    void initializeViewer(){
        viewer = boost::shared_ptr<pcl::visualization::PCLVisualizer> (new pcl::visualization::PCLVisualizer ("Pole Detector"));
        viewer->setBackgroundColor (0, 0, 0);
        viewer->addCoordinateSystem (3.0, "coordinates", 0);
    }

    void viewCloud(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, string name){
        boost::random::uniform_int_distribution<> dist(0, 255);
        uint8_t r = dist(randomGen), g = dist(randomGen), b = dist(randomGen);
        pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> colourHandler(cloud, r, g, b);
        viewer->addPointCloud<pcl::PointXYZ> (cloud, colourHandler, name);
        viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, name);

    }

    void viewClusterList(list<Cluster> const &clusterList, string id){
        boost::random::uniform_int_distribution<> dist(0, 255);
        uint8_t r = dist(randomGen), g = dist(randomGen), b = dist(randomGen);
        int j = 0;
        pcl::PointXYZ center;
        for (list<Cluster>::const_iterator it = clusterList.begin(); it != clusterList.end(); ++it){
            Cluster cluster = *it;
            eigenV4f2PointXYZ(cluster.getCentroid(), center);
            viewer->addSphere(center, cluster.getRadius()/2, r, g, b, id+boost::lexical_cast<string>(j));
            j++;
        }
    }

    void viewCluster(Cluster &cluster, string id){
        boost::random::uniform_int_distribution<> dist(0, 255);
        uint8_t r = dist(randomGen), g = dist(randomGen), b = dist(randomGen);
        pcl::PointXYZ center;
        eigenV4f2PointXYZ(cluster.getCentroid(), center);
        viewer->addSphere(center, cluster.getRadius()/2, r, g, b, id);
    }

    void makeColouredCloud(list<Segment>& segmentList, pcl::PointCloud<pcl::PointXYZRGB>::Ptr debugCloud){
        boost::random::uniform_int_distribution<> dist(0, 255);
        for (list<Segment>::iterator it = segmentList.begin(); it != segmentList.end(); ++it) {
            Segment segment = *it;
            //** Making single color for each detected pole
            uint8_t r = dist(randomGen), g = dist(randomGen), b = dist(randomGen);
            uint32_t rgb = ((uint32_t) r << 16 | (uint32_t) g << 8 | (uint32_t) b);
            for (list<Cluster>::iterator it2 = segment.getSegmentParts().begin();
                 it2 != segment.getSegmentParts().end(); ++it2) {
                for (size_t i = 0; i < it2->getClusterCloud()->points.size(); ++i) {
                    pcl::PointXYZRGB PtColored;
                    makeColoredPoint(PtColored, it2->getClusterCloud()->points[i], rgb);
                    debugCloud->points.push_back(PtColored);
                }
            }
        }
    }

private:
    boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer;
    boost::random::mt19937 randomGen;

};

#endif //POLE_DETECTOR_VISUALIZER_HPP


text:
// Copyright (c) 2014, Alexey Ivanov

#include "stdafx.h"
#include "utils/util.h"
#include <boost/crc.hpp>
#include "plugin/logger.h"

namespace {
using namespace ControlPlugin::PluginLogger;
ModuleLoggerType& logger()
    { return getLogManager().getModuleLogger<ControlPlugin::AIMPControlPlugin>(); }
}

namespace Utilities
{

//! Returns crc32 of buffer[0, length);
crc32_t crc32(const void* buffer, unsigned int length)
{
    static boost::crc_32_type crc32_calculator;
    crc32_calculator.reset();
    crc32_calculator.process_bytes(buffer, length);
    return crc32_calculator.checksum();
}

Profiler::Profiler(const char * const msg)
    :
    msg_(msg)
{}

Profiler::~Profiler()
{
    BOOST_LOG_SEV(logger(), debug) << msg_ << " duration " << timer_.elapsed() << " sec.";
}

bool stringStartsWith(const std::string& string, const std::string& search_string)
{
    if ( string.length() >= search_string.length() ) {
        return search_string.find( string.c_str(), 0, search_string.length() ) == 0;
    }
    return false;
}

std::wstring getExecutableProductVersion(const TCHAR* pszFilePath) // throws std::runtime_error
{
    using namespace Utilities;

    // got from http://stackoverflow.com/a/940784/1992063

    // get the version info for the file requested
    const DWORD dwSize = GetFileVersionInfoSize( pszFilePath, NULL );
    if ( dwSize == 0 ) {
        throw std::runtime_error( MakeString() << "Error in GetFileVersionInfoSize: " << GetLastError() );
    }

    std::string versionInfoBuf(dwSize, '\0');
    BYTE* pbVersionInfo = reinterpret_cast<BYTE*>( const_cast<std::string::value_type*>(versionInfoBuf.c_str()) );

    if ( !GetFileVersionInfo( pszFilePath, 0, dwSize, pbVersionInfo ) ) {
        throw std::runtime_error( MakeString() << "Error in GetFileVersionInfo: " << GetLastError() );
    }

    struct LANGANDCODEPAGE {
      WORD wLanguage;
      WORD wCodePage;
    };

    // Read the list of languages and code pages.
    LANGANDCODEPAGE* lpTranslate = NULL;
    UINT cbTranslate = 0;
    if (!VerQueryValue(pbVersionInfo,
                       TEXT("\\VarFileInfo\\Translation"),
                       (LPVOID*)&lpTranslate,
                       &cbTranslate)
                       )
    {
        throw std::runtime_error( MakeString() << "Error in VerQueryValue: " << GetLastError() );
    }

    std::wstring result;
    // Read the file description for each language and code page.
    for (UINT i = 0; i < (cbTranslate/sizeof(LANGANDCODEPAGE)); ++i) {
        WCHAR subblock[50];
        wsprintf(subblock, L"\\StringFileInfo\\%04x%04x\\ProductVersion", lpTranslate[i].wLanguage, lpTranslate[i].wCodePage);
        WCHAR* product_version = NULL;
        UINT product_version_length = 0;
        if (!VerQueryValue( pbVersionInfo,
                            subblock,
                            (LPVOID*)&product_version,
                            &product_version_length)
            )
        {
            throw std::runtime_error( MakeString() << "Error in VerQueryValue: " << GetLastError() );
        }
        result = product_version;
    }
    return result;
}

std::wstring getCurrentExecutablePath() // throws std::runtime_error
{
    HMODULE hm = NULL;
    if (!GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
                           (LPCWSTR)&getCurrentExecutablePath,
                           &hm)
       )
    {
        using namespace Utilities;
        throw std::runtime_error( MakeString() << "Error in GetModuleHandleEx: " << GetLastError() );
    }

    WCHAR path[MAX_PATH + 1];
    GetModuleFileName(hm, path, MAX_PATH);
    return path;
}

std::wstring getPluginVersion()
{
    try {
        return getExecutableProductVersion( getCurrentExecutablePath().c_str() );
    } catch (...) {
        return L"unknown";
    }
}

boost::filesystem::wpath temp_directory_path()
{
    using namespace boost::filesystem;

    std::vector<wpath::value_type> buf(GetTempPathW(0, NULL));

    if (buf.empty() || GetTempPathW(buf.size(), &buf[0])==0) {
        return wpath();
    }

    buf.pop_back();

    wpath p(buf.begin(), buf.end());

    /*
    if ((ec&&!is_directory(p, *ec))||(!ec&&!is_directory(p))) {
        ::SetLastError(ENOTDIR);
        error(true, p, ec, "boost::filesystem::temp_directory_path");
        return path();
    }
    */

    return p;
}

} // namespace Utilities


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

#include "logs.h"
#include "route.h"
#include "track.h"

using namespace GPS;

/*
                                   Documentation

The following test cases are to test the validity of the netHeightGain function in order to make sure that
the values being returned are both valid and accurate. There are 9 test cases below, each providing a description
of the test case.

The test cases are as follows:

Single_Elevation_Value
No_Elevation
Negative_Net_Elevation
Positive_Net_Elevation
Negative_Elevation_Values
Positive_Elevation_Values
Positive_Negative_Values
Large_Dataset
Alternating_Elevations

*/

BOOST_AUTO_TEST_SUITE( Net_Height_Gain_Z )

const bool isFileName = true;

/*
Test: Single_Elevation_Value
Desc: This test checks if the the correct net elevation value is returned when there is only a single point in the
      GPX file. The net elevation returned should be 0 (as there are no other points).
*/
BOOST_AUTO_TEST_CASE(Single_Elevation_Value){
    Route route = Route(LogFiles::GPXRoutesDir + "Edge.gpx", isFileName);
    BOOST_CHECK_CLOSE(route.netHeightGain(), 0, 0.01);
}

/*
Test: No_Elevation
Desc: This test checks whether the correct net elevation value returned when there is no elevation (flat plane).
      The net elevation returned should be 0.
*/
BOOST_AUTO_TEST_CASE(No_Elevation){
    Route route = Route(LogFiles::GPXRoutesDir + "ABCD.gpx", isFileName);
    BOOST_CHECK_CLOSE(route.minElevation(), 0, 0.01);
}

/*
Test: Negative_Net_Elevation
Desc: This test checks whether the net elevation returned is 0 when the net elevation result is negative. i.e if the
      net elevation is -20 the value returned from the function should be 0.
*/
BOOST_AUTO_TEST_CASE(Negative_Net_Elevation){
    Route route = Route(LogFiles::GPXRoutesDir + "NorthYorkMoors.gpx", isFileName);
    BOOST_CHECK_CLOSE(route.netHeightGain(), 0, 0.01);
}

/*
Test: Positive_Net_Elevation
Desc: This test checks whether the the function returns the correct net elevation value when working with positive elevation values.
*/
BOOST_AUTO_TEST_CASE(Positive_Net_Elevation){
    Track track = Track(LogFiles::GPXTracksDir + "positiveNetElevation.gpx", isFileName);
    BOOST_CHECK_CLOSE(track.netHeightGain(), 60, 0.01);
}

/*
Test: Negative_Elevation_Values
Desc: This test checks whether the the function returns the correct net elevation value when working with negative elevation values.
*/
BOOST_AUTO_TEST_CASE(Negative_Elevation_Values){
    Track track = Track(LogFiles::GPXTracksDir + "negativeElevation.gpx", isFileName);
    BOOST_CHECK_CLOSE(track.netHeightGain(), 5, 0.01);
}

/*
Test: Positive_Elevation_Values
Desc: This test checks whether the the function returns the correct net elevation value when working with positive elevation values.
*/
BOOST_AUTO_TEST_CASE(Positive_Elevation_Values){
    Track track = Track(LogFiles::GPXTracksDir + "positiveElevation.gpx", isFileName);
    BOOST_CHECK_CLOSE(track.netHeightGain(), 202, 0.01);
}

/*
Test: Positive_Negative_Values
Desc: This test checks whether the the function returns the correct net elevation value when working with both positive and negative
      elevation values.
*/
BOOST_AUTO_TEST_CASE(Positive_Negative_Values){
    Track track = Track(LogFiles::GPXTracksDir + "negativePositiveElevation.gpx", isFileName);
    BOOST_CHECK_CLOSE(track.netHeightGain(), 25, 0.01);
}

/*
Test: Large_Dataset
Desc: This test checks whether the the function returns the correct net elevation value when working with a large dataset.
*/
BOOST_AUTO_TEST_CASE(Large_Dataset){
    Route route = Route(LogFiles::GPXRoutesDir + "NorthYorkMoors.gpx", isFileName);
    BOOST_CHECK_CLOSE(route.netHeightGain(), 0, 0.01);
}

/*
Test: Alternating_Elevations
Desc: This test checks whether the the function returns the correct net elevation value when with alternating positive and negative
      elevations are being read in
*/
BOOST_AUTO_TEST_CASE(Alternating_Elevations){
    Route route = Route(LogFiles::GPXRoutesDir + "ZigZag.gpx", isFileName);
    BOOST_CHECK_CLOSE(route.netHeightGain(), 50, 0.01);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: EdwinLangley/GPX-Route-and-Track

max_issues_repo_name: EdwinLangley/GPX-Route-and-Track

max_forks_repo_name: EdwinLangley/GPX-Route-and-Track


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

#ifndef CRYPTO3_ACCUMULATORS_PUBKEY_SCHEME_SIGS_HPP
#define CRYPTO3_ACCUMULATORS_PUBKEY_SCHEME_SIGS_HPP

#include <boost/container/static_vector.hpp>

#include <boost/parameter/value_type.hpp>

#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>

#include <nil/crypto3/detail/make_array.hpp>
#include <nil/crypto3/detail/digest.hpp>
#include <nil/crypto3/detail/inject.hpp>

#include <nil/crypto3/pubkey/accumulators/bits_count.hpp>

#include <nil/crypto3/pubkey/accumulators/parameters/scheme.hpp>
#include <nil/crypto3/pubkey/accumulators/parameters/bits.hpp>

#include <nil/crypto3/pubkey/scheme.hpp>

namespace nil {
    namespace crypto3 {
        namespace accumulators {
            namespace impl {
                template<typename Mode>
                struct scheme_sigs_impl : boost::accumulators::accumulator_base {
                protected:
                    typedef Mode mode_type;
                    typedef typename Mode::scheme_type scheme_type;
                    typedef typename Mode::padding_type padding_type;

                    typedef typename mode_type::endian_type endian_type;

                    constexpr static const std::size_t public_key_bits = scheme_type::public_key_type::key_bits;
                    typedef typename scheme_type::public_key_type::key_type public_key_type;

                    constexpr static const std::size_t private_key_bits = scheme_type::private_key_type::key_bits;
                    typedef typename scheme_type::private_key_type::key_type private_key_type;

                    constexpr static const std::size_t scheme_key_bits = mode_type::scheme_key_bits;
                    typedef typename mode_type::key_type scheme_key_type;

                public:
                    typedef std::pair<public_key_type, private_key_type> result_type;

                    template<typename Args>
                    scheme_sigs_impl(const Args &args) : mode(args[boost::accumulators::sample]) {
                    }

                    template<typename ArgumentPack>
                    inline void operator()(const ArgumentPack &args) {
                        resolve_type(args[boost::accumulators::sample]);
                    }

                    inline result_type result(boost::accumulators::dont_care) const {
                        using namespace ::nil::crypto3::detail;

                        result_type res = dgst;

                        return res;
                    }

                protected:
                    inline void resolve_type(const scheme_key_type &value) {
                    }
                    mode_type mode;

                    result_type dgst;
                };
            }    // namespace impl

            namespace tag {
                template<typename Mode>
                struct scheme_sigs : boost::accumulators::depends_on<bits_count> {
                    typedef Mode mode_type;

                    /// INTERNAL ONLY
                    ///

                    typedef boost::mpl::always<accumulators::impl::scheme_sigs_impl<mode_type>> impl;
                };
            }    // namespace tag

            namespace extract {
                template<typename Mode, typename AccumulatorSet>
                typename boost::mpl::apply<AccumulatorSet, tag::scheme_sigs<Mode>>::type::result_type
                    scheme_sigs(const AccumulatorSet &acc) {
                    return boost::accumulators::extract_result<tag::scheme_sigs<Mode>>(acc);
                }
            }    // namespace extract
        }        // namespace accumulators
    }            // namespace crypto3
}    // namespace nil

#endif    // CRYPTO3_ACCUMULATORS_PUBKEY_HPP


text:
#include "vrc_meta_tool.h"

#include <cstring>
#include <fstream>
#include <iostream>
#include <vector>

#include <boost/format.hpp>

namespace vrc_photo_album2::meta_tool {

chunk_util::chunk_util(filesystem::path path) : path_(path) {}

decltype(auto) chunk_util::parse_chunk(chunk_s& chunk) {
  // chunk.dataは終端文字が入っていないため部分文字列を取得する
  return std::make_tuple(std::string(reinterpret_cast<char*>(chunk.head_.type), 4),
                         std::string(reinterpret_cast<char*>(chunk.data_), chunk.size()));
}

decltype(auto) chunk_util::read() {
  constexpr int png_header_size                = 8;
  const unsigned char png_sig[png_header_size] = {0x89, 0x50, 0x4e, 0x47,
                                                  0x0d, 0x0a, 0x1a, 0x0a};
  auto meta_chunks = std::make_unique<std::vector<std::tuple<std::string, std::string>>>();

  char header[png_header_size];
  std::ifstream ifs(path_.string(), std::ios::binary);
  ifs.read(header, 8);

  if (std::strncmp((char*)header, (char*)png_sig, png_header_size) != 0) {
    throw std::invalid_argument("not png file.");
  }

  std::stringstream ss{
      std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>())};

  std::vector<const char*> vrc_meta_chunks;
  vrc_meta_chunks.push_back("vrCd");
  vrc_meta_chunks.push_back("vrCp");
  vrc_meta_chunks.push_back("vrCw");
  vrc_meta_chunks.push_back("vrCu");

  for (;;) {
    chunk_s ch;
    ss.read((char*)&ch.head_, sizeof(header));

    if (std::strncmp(ch.head_.type, "IEND", 4) == 0) {
      return meta_chunks;
    }

    bool skip = true;
    for (auto meta_chunk : vrc_meta_chunks) {
      if (std::strncmp(ch.head_.type, meta_chunk, 4) == 0) {
        skip = false;
        std::vector<char> dat(ch.size());
        ch.data_ = dat.data();
        ss.read((char*)ch.data_, ch.size());
        ss.seekg(4, std::iostream::cur);
        auto chunk = parse_chunk(ch);
        meta_chunks->push_back(chunk);
      }
    }

    if (skip) {
      ss.seekg(ch.size() + 4, std::iostream::cur);
    }
  }
}

// decltype(auto) chunk_util::write() {}

// decltype(auto) chunk_util::create_chunk() {}

std::string meta_tool::date() const {
  return data_.date.value_or("");
}

std::string meta_tool::readable_date() const {
  const std::string year   = data_.date.value().substr(0, 4);
  const std::string month  = data_.date.value().substr(4, 2);
  const std::string day    = data_.date.value().substr(6, 2);
  const std::string hour   = data_.date.value().substr(8, 2);
  const std::string minute = data_.date.value().substr(10, 2);
  const std::string second = data_.date.value().substr(12, 2);
  // const std::string milli  = data_.date.value().substr(14, 3);

  return (boost::format("%04d-%02d-%02d %02d:%02d:%02d") % year % month % day % hour % minute %
          second)
      .str();
}

std::string meta_tool::photographer() const {
  return data_.photographer.value_or("");
}

std::string meta_tool::world() const {
  return data_.world.value_or("");
}

std::map<std::string, std::optional<std::string>> meta_tool::users() const {
  return data_.users;
}

bool meta_tool::has_any() const {
  return has_date() || has_photographer() || has_world() || has_users();
}

bool meta_tool::has_date() const {
  return data_.date.has_value();
}

bool meta_tool::has_readable_date() const {
  return data_.date.has_value();
}

bool meta_tool::has_photographer() const {
  return data_.photographer.has_value();
}

bool meta_tool::has_world() const {
  return data_.world.has_value();
}

bool meta_tool::has_users() const {
  return !data_.users.empty();
}

void meta_tool::set_date(std::optional<std::string> date) {
  data_.date = date;
}

void meta_tool::set_photographer(std::optional<std::string> photographer) {
  data_.photographer = photographer;
}

void meta_tool::set_world(std::optional<std::string> world) {
  data_.world = world;
}

void meta_tool::add_user(std::string user) {
  // twitterのidがあれば分割
  const std::string_view delemiter = " : ";
  auto pos                         = user.rfind(delemiter);
  if (pos != std::string::npos) {
    data_.users.insert(
        std::make_pair(user.substr(0, pos), user.substr(pos + delemiter.length())));
  } else {
    data_.users.insert(std::make_pair(user, std::nullopt));
  }
}

void meta_tool::delete_user(std::string user_name) {
  data_.users.erase(user_name);
}

void meta_tool::clear_users() {
  std::map<std::string, std::optional<std::string>>().swap(data_.users);
}

void meta_tool::read(filesystem::path path) {
  // dateの初期化
  set_date(std::nullopt);
  set_photographer(std::nullopt);
  set_world(std::nullopt);
  clear_users();

  chunk_util util(path);
  try {
    auto chunks = util.read();
    // auto chunks = util.read();
    for (auto chunk : *chunks) {
      auto [type, data] = chunk;
      if (type == "vrCd") {
        set_date(data);
      } else if (type == "vrCp") {
        set_photographer(data);
      } else if (type == "vrCw") {
        set_world(data);
      } else if (type == "vrCu") {
        add_user(data);
      }
    }
  } catch (...) {
    std::cout << "read png exception: " << path.string() << std::endl;
  }
}
} // namespace vrc_photo_album2::meta_tool

ext: cc


text:
///////////////////////////////////////////////////////////////////////////////
//
// http://protoc.sourceforge.net/
//
// Copyright (C) 2013 Bjorn Reese <breese@users.sourceforge.net>
//
// Permission to use, copy, modify, and distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHORS AND
// CONTRIBUTORS ACCEPT NO RESPONSIBILITY IN ANY CONCEIVABLE MANNER.
//
///////////////////////////////////////////////////////////////////////////////

#include <boost/test/unit_test.hpp>

#include <protoc/transenc/reader.hpp>
#include <protoc/transenc/detail/codes.hpp>

namespace format = protoc::transenc;
namespace detail = format::detail;

BOOST_AUTO_TEST_SUITE(transenc_reader_suite)

//-----------------------------------------------------------------------------
// Basic types
//-----------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_empty)
{
    format::reader::value_type input[] = {};
    format::reader reader(input, input + sizeof(input));
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_eof);
}

BOOST_AUTO_TEST_CASE(test_false)
{
    format::reader::value_type input[] = { detail::code_false };
    format::reader reader(input, input + sizeof(input));
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_boolean);
    BOOST_REQUIRE_EQUAL(reader.get_bool(), false);
    BOOST_REQUIRE_EQUAL(reader.next(), false);
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_eof);
}

BOOST_AUTO_TEST_CASE(test_true)
{
    format::reader::value_type input[] = { detail::code_true };
    format::reader reader(input, input + sizeof(input));
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_boolean);
    BOOST_REQUIRE_EQUAL(reader.get_bool(), true);
    BOOST_REQUIRE(!reader.next());
}

BOOST_AUTO_TEST_CASE(test_null)
{
    format::reader::value_type input[] = { detail::code_null };
    format::reader reader(input, input + sizeof(input));
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_null);
    BOOST_REQUIRE(!reader.next());
}

BOOST_AUTO_TEST_CASE(test_integer)
{
    format::reader::value_type input[] = { 0x01 };
    format::reader reader(input, input + sizeof(input));
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_integer);
    BOOST_REQUIRE_EQUAL(reader.get_int(), 1);
    BOOST_REQUIRE(!reader.next());
}

BOOST_AUTO_TEST_CASE(test_floating)
{
    format::reader::value_type input[] = { detail::code_float64, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xF0, 0x3F };
    format::reader reader(input, input + sizeof(input));
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_floating);
    BOOST_REQUIRE_EQUAL(reader.get_double(), 1.0);
    BOOST_REQUIRE(!reader.next());
}

//-----------------------------------------------------------------------------
// Containers
//-----------------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_record)
{
    format::reader::value_type input[] = { detail::code_record_begin, detail::code_record_end };
    format::reader reader(input, input + sizeof(input));
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_record_begin);
    BOOST_REQUIRE_EQUAL(reader.size(), 0);
    BOOST_REQUIRE(reader.next());
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_record_end);
    BOOST_REQUIRE_EQUAL(reader.size(), 1);
    BOOST_REQUIRE(!reader.next());
    BOOST_REQUIRE_EQUAL(reader.type(), protoc::token::token_eof);
    BOOST_REQUIRE_EQUAL(reader.size(), 0);
}

BOOST_AUTO_TEST_SUITE_END()


text:
/*
 * Data:                2019-03-18
 * Autor:               Marcin Kurdziel
 * Kompilacja:          clang++ -std=c++14 -o server2_async server2_async.cpp -lpthread
 *                      Zamiast clang++ można użyć g++, ale nie jest to zalecane
 *                      Do skompilowaniu programu potrzebna jest biblioteka Boost.Asio oraz Boost.Lexical_Cast
 * Uruchamianie:        ./server2_async <numer portu>
 */

#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/udp.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/asio/write.hpp>
#include <iostream>
#include <string>
#include <array>
#include <thread>

namespace asio = boost::asio;
namespace ip = asio::ip;

void print_error(const std::string msg, const boost::system::error_code& err)
{
    if(err == asio::error::operation_aborted) return;
    std::cerr << msg << "(): " << err.message() << std::endl;
}

int main(int argc, char** argv)
{
    if (argc != 2)
    {
        std::cout << "Invocation: " << argv[0] << " <PORT>" << std::endl;
        return 1;
    }

    // io_context jest niezbędnym elementem, który służy do komunikacji z systemem operacyjnym
    asio::io_context context;

    // utworzenie gniazda UDP i zbindowanie go
    ip::udp::socket socket(context,
            ip::udp::endpoint(ip::udp::v4(), boost::lexical_cast<unsigned short>(argv[1])));

    std::cout << "Server is listening for incoming connection..." << std::endl;

    // punkt końcowy dla komunikacji, zostanie uzupełniony po odebraniu danych za pomocą receive_from
    ip::udp::endpoint remote;

    // oczekiwanie na dane od klienta
    std::array<char, 256> buff;
    socket.async_receive_from(asio::buffer(buff), remote, [&](const boost::system::error_code& err, std::size_t bytes)
    {
        if(err)
        {
            print_error("receive_from", err);
            return;
        }

        // dzięki temu unikamy wypisywania "śmieci"
        buff[bytes] = '\0';

        std::cout << "UDP datagram received from " << remote.address() << ":" << remote.port()
             << ". Echoing message...\n" << buff.data() << std::endl;

        sleep(4);

        // wysłanie odpowiedzi
        socket.async_send_to(asio::buffer(buff), remote, [&](const boost::system::error_code& err, std::size_t bytes)
        {
            if(err)
            {
                print_error("send_to", err);
                return;
            }

            socket.close();
        });

    });

    // odpalenie obsługi handlerów na osobnym wątku
    std::thread thread([&](){ context.run(); });
    // jesli wolimy, by komunikacja działała w tle i nie chcemy czekać, możemy zrobić tu detach()

    // tutaj możemy robić co chcemy (równolegle do obsługi komunikacji)
    // ...

    // jeżeli nie użyliśmy detach()
    thread.join();

    return 0;
}


text:
//
// Created by fabian on 17.05.21.
//

#ifndef PICTURETOWOOD_PICTURE_HPP
#define PICTURETOWOOD_PICTURE_HPP

#include <iostream>
#include "opencv2/highgui.hpp"
#include <boost/filesystem.hpp>
#include <opencv2/imgproc.hpp>

struct image_set{
    cv::Mat img;
    cv::Mat img_gray;
    cv::Mat img_filter;
    cv::Mat mask;
};

class picture {
    public:
        std::string name;
        std::vector<struct image_set> images;
        unsigned int origDPI;
        struct image_set origImage;

        picture(const std::string &path, unsigned int dpi, int filter_type, double filter_ratio);
        void show() const;
        void addRotations(int n);
        void updateMasks();
        void scaleTo(unsigned int dpi);
        void transformHistTo(cv::Mat targetHist, int channel, double ratio);
        void addColorToMask(cv::Vec<uchar, 3> color);
        unsigned int currentDPI;
        unsigned int filterType;
        double filter_ratio;
        void updateImageSet();
};

cv::Mat cumulativeHist(std::vector<picture> &picList, int channel);

#endif //PICTURETOWOOD_PICTURE_HPP

max_stars_repo_name: OberKnirps/PictureToWood

max_issues_repo_name: OberKnirps/PictureToWood

max_forks_repo_name: OberKnirps/PictureToWood


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * File:   EventServiceModule.cpp
 * Author: ubuntu
 *
 * Created on January 19, 2018, 7:20 AM
 */

#include <iostream>

#include <condition_variable>
#include <boost/optional/optional.hpp>

#include "keto/event/EventServiceModule.hpp"
#include "keto/common/MetaInfo.hpp"

namespace keto {
namespace event {

EventServiceModule::EventServiceModule() {
}

EventServiceModule::~EventServiceModule() {
}

const std::string EventServiceModule::getName() const {
    return "EventService";
}

const std::string EventServiceModule::getDescription() const {
    return "Event Service Description";
}

const std::string EventServiceModule::getVersion() const {
    return keto::common::MetaInfo::VERSION;
}

void EventServiceModule::triggerEvent(const Event& event) {
    EventServiceModule::Signal signal =this->getEventHandler(event.getName());

    (*signal.get())(event);
}

Event EventServiceModule::processEvent(const Event& event) {
    EventServiceModule::Signal signal =this->getEventHandler(event.getName());
    boost::optional<Event> option = (*signal.get())(event);
    return option.get();
}

void EventServiceModule::registerEventHandler(const std::string& name, handler handlerMethod) {
    this->addEventHandler(name,handlerMethod);
}

void EventServiceModule::deregisterEventHandler(const std::string& name) {
    this->removeEventHandler(name);
}

void EventServiceModule::addEventHandler(const std::string& name, keto::event::handler handlerMethod) {
    Signal signal = std::make_shared<boost::signals2::signal<Event (const Event&)>>();
    signal->connect(handlerMethod);
    std::lock_guard<std::mutex> guard(this->classMutex);
    if (this->registeredSignals.count(name)) {
        BOOST_THROW_EXCEPTION(DuplicateEventHandlerException(
                "Pre-existing event handler by the name of : " +
                name));
    }
    this->registeredSignals[name] = signal;
}

EventServiceModule::Signal EventServiceModule::getEventHandler(const std::string& name) {
    std::lock_guard<std::mutex> guard(this->classMutex);
    if (!this->registeredSignals.count(name)) {
        BOOST_THROW_EXCEPTION(UnknownEventHandlerException("Unknown event handler : " +
                name));
    }
    return this->registeredSignals[name];
}

void EventServiceModule::removeEventHandler(const std::string& name) {
    std::lock_guard<std::mutex> guard(this->classMutex);
    this->registeredSignals[name].reset();
    this->registeredSignals.erase(name);
}

}
}

max_stars_repo_name: burntjam/keto

max_issues_repo_name: burntjam/keto

max_forks_repo_name: burntjam/keto


text:
#include "experiments/util/bitmap_db.hpp"
#include "experiments/util/gen.hpp"
#include "experiments/util/threading.hpp"
#include "thirdparty/perfevent/PerfEvent.hpp"

#include <dtl/bitmap/teb_legacy.hpp>
#include <dtl/bitmap/teb_wrapper.hpp>
#include <dtl/bitmap/util/convert.hpp>
#include <dtl/dtl.hpp>
#include <dtl/env.hpp>

#include <boost/algorithm/string.hpp>

#include <chrono>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
//===----------------------------------------------------------------------===//
// Micro-Experiment: Determine the costs of downward navigational steps.
//===----------------------------------------------------------------------===//
/// The database file where the bitmaps are stored.
static const std::string DB_FILE =
    dtl::env<std::string>::get("DB_FILE", "./random_bitmaps.sqlite3");
/// The database instance where the bitmaps are stored.
bitmap_db db(DB_FILE);
/// The clustering factor needs to be 1, to ensure that we navigate downwards
/// the tree until the very last level.
f64 F = 1.0;
/// The bit densities we test. Note that with higher density, the number of
/// perfect levels increases and therefore the number of downward steps
/// decreases. If the number of downward steps is less than 5, the results
/// are (significantly) distorted due to the overhead in the
/// 'nav_from_root_to(pos)' function.
std::vector<$f64> bit_densities = { 0.0001, 0.001, 0.01, 0.1 };
/// The bitmap length.
u64 N = 1ull << 20;
/// Each measurement is repeated until the time below is elapsed.
static $u64 RUN_DURATION_NANOS = 1000e6; // 1s
//===----------------------------------------------------------------------===//
// Helper
auto now_nanos = []() {
  return std::chrono::duration_cast<std::chrono::nanoseconds>(
      std::chrono::steady_clock::now().time_since_epoch())
      .count();
};
//===----------------------------------------------------------------------===//
void run(u64 n, f64 f, f64 d, i64 bitmap_id) {
  const auto bid = bitmap_id;
  const auto plain_bitmap = db.load_bitmap(bid);

  using T = dtl::teb_wrapper;
  //  using T = dtl::teb<3>;

  T enc_bitmap(plain_bitmap);

  std::vector<std::size_t> probe_positions;
  std::size_t down_step_sum = 0;
  {
    auto it = enc_bitmap.it();
    while (!it.end()) {
      if (probe_positions.size() > 1024) break;
      probe_positions.push_back(it.pos());
      auto down_steps = dtl::teb<>::determine_tree_height(n) - (it.perfect_levels() - 1);
      down_step_sum += down_steps;
      it.next();
    }
  }
  if (down_step_sum == 0) return;

  const auto nanos_end = now_nanos() + RUN_DURATION_NANOS;

  auto it = enc_bitmap.it();
  std::size_t repeat_cnt = 0;
  PerfEvent e;
  e.startCounters();
  std::size_t chksum = 0;
  while (now_nanos() < nanos_end) {
    ++repeat_cnt;
    for (std::size_t i = 0; i < probe_positions.size(); ++i) {
      std::size_t to_pos = probe_positions[i];
      it.nav_from_root_to(to_pos);
      chksum += it.pos();
    }
  }
  e.stopCounters();
  down_step_sum *= repeat_cnt;

  std::string type_info = enc_bitmap.info();
  boost::replace_all(type_info, "\"", "\"\""); // Escape JSON for CSV output.

  std::cout << n << "," << f << "," << d
            << "," << (e.getCounter("cycles") / down_step_sum)
            << "," << (e.getCounter("instructions") / down_step_sum)
            << "," << (e.getCounter("branch-misses") / down_step_sum)
            << "," << e.getIPC()
            << "," << type_info
            << "," << chksum
            << std::endl;
}
//===----------------------------------------------------------------------===//
$i32 main() {
  std::vector<$i64> bitmap_ids;

  for (auto d : bit_densities) {
    const auto ids = db.find_bitmaps(N, F, d);
    if (ids.empty()) {
      const auto bitmap = gen_random_bitmap_markov(N, F, d);
      const auto id = db.store_bitmap(N, F, d, bitmap);
      bitmap_ids.push_back(id);
    }
  }

  // CSV header
  std::cerr << "n,f,d,cycles,instructions,branch-misses,ipc,info,dontcare" << std::endl;
  for (auto d : bit_densities) {
    const auto ids = db.find_bitmaps(N, F, d);
    if (!ids.empty()) {
      run(N, F, d, ids[0]);
    }
  }
}
//===----------------------------------------------------------------------===//

max_stars_repo_name: harald-lang/tree-encoded-bitmaps

max_issues_repo_name: marcellus-saputra/Thuja

max_forks_repo_name: marcellus-saputra/Thuja


text: #include <boost/function/function9.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#ifndef _MESSAGE_BUS_HPP_
#define _MESSAGE_BUS_HPP_

#include "FunctionTraits.hpp"
#include <iostream>
#include <string>
#include <map>
#include <boost/any.hpp>

using namespace func_traits;

class MessageBus {
private:
    std::multimap<std::string, boost::any> container;
    using Iter = std::multimap<std::string, boost::any>::iterator;

public:
    // use the synthesized default constructor
    MessageBus() = default;

    // no copy
    MessageBus(const MessageBus&) = delete;
    MessageBus(MessageBus&&) = delete;

    // no assignment
    MessageBus& operator= (const MessageBus&) = delete;
    MessageBus& operator= (MessageBus&&) = delete;

    // use the synthesized destructor
    ~MessageBus() = default;

    // create a node with a topic and a callback function
    template <typename F>
    void create(const std::string& topic, F&& func) {
        using FunctionWrapperType = typename FunctionTraits<F>::FunctionWrapperType;
        FunctionWrapperType func_wrapper = func;
        const std::string tag = topic + typeid(func_wrapper).name();
        container.emplace(std::move(tag), std::forward<FunctionWrapperType>(func_wrapper));
    }

    // remove nodes that are listening to the given topic and have the given call signature
    template <typename RetType, typename... Args>
    void remove(const std::string& topic) {
        using FunctionWrapperType = std::function<RetType(Args...)>;
        const std::string remove_tag = topic + typeid(FunctionWrapperType).name();
        auto remove_range = container.equal_range(remove_tag);
        if (remove_range.first == remove_range.second) {
            std::cout << "Node not found." << std::endl;
        }
        else {
            container.erase(remove_range.first, remove_range.second);
        }
    }

    // send messages to nodes without argument
    template <typename RetType>
    void push(const std::string& topic) {
        using FunctionWrapperType = std::function<RetType()>;
        const std::string push_tag = topic + typeid(FunctionWrapperType).name();
        auto send_range = container.equal_range(push_tag);
        if (send_range.first == send_range.second) {
            std::cout << "Node not found." << std::endl;
            return;
        }
        for (Iter it = send_range.first; it != send_range.second; ++it) {
            FunctionWrapperType func_wrapper = boost::any_cast<FunctionWrapperType>(it->second);
            func_wrapper();
        }
    }

    // send messages to nodes with arguments
    template <typename RetType, typename... Args>
    void push(const std::string& topic, Args&&... args) {
        using FunctionWrapperType = std::function<RetType(Args...)>;
        const std::string push_tag = topic + typeid(FunctionWrapperType).name();
        auto send_range = container.equal_range(push_tag);
        if (send_range.first == send_range.second) {
            std::cout << "Node not found." << std::endl;
            return;
        }
        for (Iter it = send_range.first; it != send_range.second; ++it) {
            FunctionWrapperType func_wrapper = boost::any_cast<FunctionWrapperType>(it->second);
            func_wrapper(std::forward<Args>(args)...);
        }
    }
};

#endif

max_stars_repo_name: whichxjy/MessageBus

max_issues_repo_name: whichxjy/MessageBus

max_forks_repo_name: whichxjy/MessageBus


text:
///////////////////////////////////////////////////////////////////////////////
// xml_message.hpp
//
// unicomm - Unified Communication protocol C++ library.
//
// Unified Communication protocol complex xml message.
//
// 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)
//
// 2008, (c) Dmitry Timoshenko.

#ifdef _MSC_VER
# pragma once
#endif // _MSC_VER

#ifndef UNI_XML_MESSAGE_HPP_
#define UNI_XML_MESSAGE_HPP_

/** @file xml_message.hpp Xml message definition based on
 *    @e smart::data::complex.
 */

#include <unicomm/config/auto_link.hpp>

#ifdef UNICOMM_USE_COMPLEX_XML

#include <unicomm/message_base.hpp>
#include <unicomm/basic.hpp>

#include <smart/data/complex.hpp>

#include <boost/shared_ptr.hpp>

#include <string>

/** @namespace unicomm Unicomm library root namespace. */
namespace unicomm
{

/** Message which is serialized into complex xml.
 *
 *  This stuff is optional. If you are not satisfied with
 *  xml_message implement your own derived from unicomm::message_base.
 */
class UNICOMM_DECL xml_message : public message_base
{
//////////////////////////////////////////////////////////////////////////
// interface
public:
  /** Format identifier used by the message.
   *
   *  @return Message format name this class is regarded to.
   *  @see message_base::message_format(), setup_message_format(),
   *    config::message_decoder(), config::message_encoder().
   */
  static const std::string& message_format(void) { return xml_message_format(); }

public:
  /** Constructs a message object with given priority.
   *
   *  @param p Message priority. This value is used when message is popped out
   *    from the message outgoing queue. Undefined priority value causes that when
   *    the message is pushed into the queue it will be assigned default priority
   *    value specified by the @ref config_section "configuration".
   *    If you want this instance of the message to have distinct priority,
   *    pass it to the constructor.
   *
   *  @see undefined_priority(), min_priority(),
   *    max_priority(), config::message_priority().
   */
  explicit xml_message(size_t p = undefined_priority());

public:
  /** Returns message instance identifier.
   *
   *  @return Message instance identifier.
   */
  messageid_type id(void) const;

  /** Sets message instance identifier.
   *
   *  @param mid Message instance identifier. If message identifiers are used,
   *    unicomm takes care about identifiers. If identifiers are not used
   *    by the engine you are able to specify the identifier in order to
   *    distinct the message on sent event.
   *
   *  @note You are also able to set this identifier manually for the message
   *    when identifiers are enabled and used by the engine, but in this case
   *    the uniqueness of assigned identifier is on you.
   */
  xml_message& id(messageid_type mid);

  /** Returns message instance reply id.
   *
   *  @return Message reply id. If message is reply and identifiers are
   *    used by the engine this value is an id of the request message that
   *    this message is reply to.
   */
  messageid_type rid(void) const;

  /** Sets message instance reply id.
   *
   *  @param mid Reply message instance identifier.
   */
  void rid(messageid_type mid);

  /** Serializes message to a std::string.
   *
   *  @return Serialized string.
   */
  std::string serialize(void) const;

  /** Restores message from a std::string.
   *
   *  @param message Serialized message string.
   */
  void unserialize(const std::string &message);

public:
  /** Sets message priority.
   *
   *  @param p Message priority.
   *  @see unicomm::min_priority(), unicomm::max_priority().
   */
  xml_message& priority(size_t p);

  /** Returns message priority.
   *
   *  @return Message priority.
   *  @see unicomm::min_priority(), unicomm::max_priority().
   */
  size_t priority(void) const;

//////////////////////////////////////////////////////////////////////////
// protected stuff
protected:
  /** Returns a reference to a data holder.
   *
   *  @return Reference to internal @e smart::data::complex
   *    object that holds data.
   */
  smart::data::complex& complex(void) const;

//////////////////////////////////////////////////////////////////////////
// private stuff
private:
  struct impl;

  typedef boost::shared_ptr<impl> impl_ptr;

private:
  impl_ptr _impl;
};

} // namespace unicomm

#endif // UNICOMM_USE_COMPLEX_XML

#endif // UNI_XML_MESSAGE_HPP_

max_stars_repo_name: Chrizzly/libunicomm

max_issues_repo_name: Chrizzly/libunicomm

max_forks_repo_name: Chrizzly/libunicomm


text:
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"

#include "Generic/common/ParamReader.h"
#include "Generic/common/FileSessionLogger.h"
#include "Generic/common/UTF8InputStream.h"
#include "Generic/common/UTF8Token.h"
#include "Generic/tokens/Tokenizer.h"
#include "Generic/tokens/Untokenizer.h"
#include "Generic/morphAnalysis/MorphologicalAnalyzer.h"
#include "Generic/morphAnalysis/SessionLexicon.h"
#include "Generic/morphSelection/MorphSelector.h"
#include "MorphAnalyzer/Processor.h"
#include <time.h>
#include <boost/scoped_ptr.hpp>

#if defined(WIN32) || defined(WIN64)
#define snprintf _snprintf
#endif

#define MAX_NAMES_PER_SENTENCE 100
#define MAX_NAMES_PER_SPACE_SEP_TOK 5

Processor::Processor(char* param_file): _tokenizer(0), _morphAnalyzer(0), _morphSelector(0),
										_n_tokens(0), _n_tokens_adjusted(0)
{
	ParamReader::readParamFile(param_file);

	std::string log_file = ParamReader::getRequiredParam("quicklearn_log");
	std::wstring log_file_as_wstring(log_file.begin(), log_file.end());
	SessionLogger::logger = _new FileSessionLogger(log_file_as_wstring.c_str(), 0 ,0);

	//intialize tokenization components
	_tokenizer = Tokenizer::build();

	_morphAnalyzer = MorphologicalAnalyzer::build();
	_morphSelector = _new MorphSelector();

}

Processor::~Processor (){
	delete _tokenizer;
	delete _morphAnalyzer;
	delete _morphSelector;
}

wstring Processor::createAnalyzedCorpus(char* corpus_file, char* analyzed_corpus_file){
	// Get start time
	time_t start_time;
	time(&start_time);

	char errmsg[600];
	try {
		UTF8OutputStream outstream;
		outstream.open(analyzed_corpus_file);

		boost::scoped_ptr<UTF8InputStream> corpusstream_scoped_ptr(UTF8InputStream::build());
		UTF8InputStream& corpusstream(*corpusstream_scoped_ptr);
		corpusstream.open(corpus_file);
		if(corpusstream.fail()){
			snprintf(errmsg, 599, "Processor::ReadCorpus(), Can't read corpus file: %s", corpus_file);
			return getRetVal(false, errmsg);
		}
		//get the root
		UTF8Token tok;
		NameOffset nameInfo[MAX_NAMES_PER_SENTENCE];
		LocatedString* sentenceString;

		int n_cache_docs = 0;
		int n_total_sent = 0;
		while(!corpusstream.eof()){
			Symbol sentId;
			corpusstream >> tok;	//<doc
			int nsent = 0;
			if(wcsncmp(tok.chars(), L"<DOC", 4) ==0){
					corpusstream >> tok; // docid="ID"
					Document* doc = _new Document(tok.symValue());
					int nname = readSavedSentence(corpusstream, sentenceString, sentId, nameInfo);
					while(nname != -1){
						//tokenizer has to be reset fore every new sentence
						_tokenizer->resetForNewSentence(doc, nsent);
						addAnalyzedSentence(outstream, sentId, sentenceString, nameInfo, nname);
						nsent++;
						n_total_sent++;
						delete sentenceString;
						nname = readSavedSentence(corpusstream, sentenceString, sentId, nameInfo);
					}
					delete doc;
					n_cache_docs++;
					if (n_cache_docs > 50) {
						SessionLexicon::getInstance().getLexicon()->clearDynamicEntries();
						n_cache_docs = 1;
					}
			}
		}
		//cout << "\nNumber of tokens adjusted to match name boundaries: " << _n_tokens_adjusted;
		//cout << "\nNumber of total tokens: " << _n_tokens << "\n";

		// Report time
		time_t end_time;
		time(&end_time);
		double total_time = difftime(end_time, start_time);
		std::cout << "Elapsed time " << total_time << " seconds.\n";

		return getRetVal(true);
	}
	catch(UnrecoverableException &e) {
		cerr << "\n" << e.getMessage() << "\n";
		return getRetVal(false, e.getMessage());
	}

}

void Processor::addAnalyzedSentence(UTF8OutputStream &out, Symbol id, LocatedString* sentenceString,
											const NameOffset* nameInfo, int nname) {
	TokenSequence* fixedTokenSequence;
	TokenSequence* tempTheory;

	_tokenizer->getTokenTheories(&tempTheory, 1, sentenceString);
	_morphAnalyzer->getMorphTheories(tempTheory);
	_morphSelector->selectTokenization(sentenceString, tempTheory);
	fixedTokenSequence = adjustTokenizationToNames(tempTheory, nameInfo, nname, sentenceString);

	out << L"<SENTENCE ID=\"" << id.to_string() << L"\">\n";
	for (int i = 0; i < fixedTokenSequence->getNTokens(); i++) {
		const Token * token = fixedTokenSequence->getToken(i);
		out << L"<TOKEN START=\"" << token->getStartEDTOffset() << L"\" END=\"" << token->getEndEDTOffset() << L"\">";
		out << token->getSymbol().to_string();
		out << L"</TOKEN>\n";
	}
	out << L"</SENTENCE>\n";

	/*
	// Output in PIdF training format instead
	out << L"( ";
	int cur_name = 0;
	Symbol tag = Symbol(L"NONE");
	Symbol status = Symbol(L"-ST");
	int starttok = -1;
	int endtok = -1;
	if (nname > 0) {
		starttok = getStartTokenFromOffset(fixedTokenSequence, nameInfo[cur_name].startoffset);
		endtok = getEndTokenFromOffset(fixedTokenSequence, nameInfo[cur_name].endoffset);
	}

	for (int i = 0; i < fixedTokenSequence->getNTokens(); i++) {
		const Token * token = fixedTokenSequence->getToken(i);
		if (i == starttok) {
			tag = nameInfo[cur_name].type;
			status = Symbol(L"-ST");
		}

		// Added for spacified...
		//Symbol pToken = token->getSymbol();
		//wchar_t str[MAX_TOKEN_SIZE];
		//Untokenizer::untokenize(pToken.to_string(), str, MAX_TOKEN_SIZE);
		//size_t len = wcslen(str);
		//wchar_t buffer[2];
		//buffer[1] = L'\0';
		//for (int k = 0; k < len; k++) {
		//	buffer[0] = str[k];
		//	Symbol sub = Tokenizer::getSubstitutionSymbol(Symbol(buffer));
		//	out << L"(" << sub.to_string() << L" " << tag << status << L") ";
		//	status = Symbol(L"-CO");
		//}

		out << L"(" << token->getSymbol().to_string() << L" " << tag << status << L") ";
		status = Symbol(L"-CO");
		if (i == endtok) {
			tag = Symbol(L"NONE");
			status = Symbol(L"-ST");
			cur_name++;
			if (cur_name < nname) {
				starttok = getStartTokenFromOffset(fixedTokenSequence, nameInfo[cur_name].startoffset);
				endtok = getEndTokenFromOffset(fixedTokenSequence, nameInfo[cur_name].endoffset);
			}
			else {
				starttok = -1;
				endtok = -1;
			}
		}
	}
	out << L")\n";
	*/

	delete tempTheory;
	delete fixedTokenSequence;
}

TokenSequence* Processor::adjustTokenizationToNames(const TokenSequence* toks,
													 const NameOffset nameInfo[], int nann,
													 const LocatedString* sentenceString)
{
	int starttok;
	int endtok;

	int inName[MAX_SENTENCE_TOKENS][MAX_NAMES_PER_SPACE_SEP_TOK+1];
	Token* newTokens[MAX_SENTENCE_TOKENS];

	for(int i=0; i<toks->getNTokens(); i++){
		inName[i][0] =0;
	}
	for(int i=0; i<nann; i++){
		starttok= getStartTokenFromOffset(toks, nameInfo[i].startoffset);
		endtok = getEndTokenFromOffset(toks, nameInfo[i].endoffset);
		if(starttok!=-1) {
			inName[starttok][inName[starttok][0]+1] = i;
			inName[starttok][0]++;

			// when the sentence is too long the token might not be found and -1 is returned
			if(starttok != endtok && endtok!=-1) {
				inName[endtok][inName[endtok][0]+1] = i;
				inName[endtok][0]++;
			}
		}
	}
	int currTok =0;
	for(int i=0; i< toks->getNTokens(); i++){
		//this token isnt in a name, just add it to the newTokens
		if(inName[i][0] == 0){
			newTokens[currTok++] = _new Token(*toks->getToken(i));
		}
		//simple case only one name assigned to this token
		else if(inName[i][0] == 1){
			Token* nameParts[3];
			int nnewtoks = splitNameTokens(toks->getToken(i),
				nameInfo[inName[i][1]].startoffset, nameInfo[(inName[i][1])].endoffset,
				sentenceString, nameParts);
			if (nnewtoks > 1)
				_n_tokens_adjusted++;
			for(int j=0; j<nnewtoks; j++){
				newTokens[currTok++] = nameParts[j];
			}
		}
		//hardest case multiple names assigned to a single token
		else{
			Token* nameParts[2*MAX_NAMES_PER_SPACE_SEP_TOK + 1];
			int nnewtoks = splitNameTokens(toks->getToken(i), inName[i], nameInfo, sentenceString, nameParts);
			for(int j=0; j<nnewtoks; j++){
				newTokens[currTok++] = nameParts[j];
			}
			if (nnewtoks > 1)
				_n_tokens_adjusted++;
			/*
			std::cout<<"problem name: starttoken"<<i
				<<" nnames: "<<inName[i][0]<<std::endl;

			throw UnexpectedInputException("Processor::AdjustTokenizationToNames()",
				"More than one annotation per Token");
			*/

		}
		_n_tokens++;
	}
	return _new TokenSequence(0, currTok, newTokens);
}

void Processor::wcsubstr(const wchar_t* str, int start, int end, wchar_t* substr){
	int j =0;
	for(int i=start ; i< end; i++, j++){
		substr[j] = str[i];
	}
	substr[j] = L'\0';
}

int Processor::readSavedSentence(UTF8InputStream &in,
											 LocatedString*& sentString, Symbol& sentId,
											 NameOffset nameInfo[]){
	UTF8Token tok;
/*
  <SENTENCE ID=sentence_id>
    012345678901234
	<DISPLAY_TEXT>This is the sentence text.</DISPLAY_TEXT>
    <ANNOTATION TYPE=PER START_OFFSET=5 END_OFFSET=8 SOURCE=Example1/>
    <ANNOTATION TYPE=GPE START_OFFSET=21 END_OFFSET=27 SOURCE=Example1/>
  </SENTENCE>
*/
	in >> tok;	//<SENTENCE, ignore this
	if(wcscmp(tok.chars(), L"<SENTENCE") !=0){
		if((wcslen(tok.chars()) < 1) || iswspace(tok.chars()[0])){
			return -2;
		}
		return -1;
	}
	in >> tok;	//id="ID">
	wchar_t idstring[500];
	//static_cast<int>
	int len = static_cast<int>( wcslen(tok.chars()));
	wcsubstr(tok.chars(), 4, len-2, idstring);

	sentId = Symbol(idstring);

	const std::wstring &sent_txt = getSentenceTextFromStream(in);
	sentString = _new LocatedString(sent_txt.c_str());
	std::wstring line;
	in.getLine(line);
	Symbol type;

	int nann = 0;
	while(wcsncmp(line.c_str(), L"</SENTENCE>", 11) != 0){
		if(nann >= MAX_NAMES_PER_SENTENCE){
			return -1;
		}
		if(!parseAnnotationLine(line.c_str(), nameInfo[nann].type, nameInfo[nann].startoffset, nameInfo[nann].endoffset)){
			return -1;
		}
		nann++;
		in.getLine(line);
	}
	return nann;

}
bool Processor::parseAnnotationLine(const wchar_t* line, Symbol& type, EDTOffset& start_offset, EDTOffset& end_offset){
	size_t len = wcslen(line);
//    <ANNOTATION TYPE=PER START_OFFSET=5 END_OFFSET=8 SOURCE=Example1/>
	try{
		int start, end, curr_char = 0;
		wchar_t str_buffer[500];
		int len = static_cast<int>(wcslen(line));
		while((curr_char < len) && iswspace(line[curr_char])){
			curr_char++;
		}
		wcsubstr(line, curr_char+1, curr_char+11, str_buffer);
		if(wcsncmp(str_buffer, L"ANNOTATION",10) !=0){
			return false;
		}
		//TYPE="..."
		curr_char = findNextMatchingCharRequired(line, curr_char, L'\"');
		curr_char++;
		start = curr_char;
		curr_char = findNextMatchingCharRequired(line, curr_char, L'\"');
		end = curr_char;
		curr_char++;
		wcsubstr(line, start, end, str_buffer);
		type = Symbol(str_buffer);

		//START_OFFSET=..
		curr_char = findNextMatchingCharRequired(line, curr_char, L'\"');
		curr_char++;
		start = curr_char;
		curr_char = findNextMatchingCharRequired(line, curr_char, L'\"');
		end = curr_char;
		curr_char++;
		wcsubstr(line, start, end, str_buffer);
		start_offset = EDTOffset(_wtoi(str_buffer));

		//END_OFFSET=..
		curr_char = findNextMatchingCharRequired(line, curr_char, L'\"');
		curr_char++;
		start = curr_char;
		curr_char = findNextMatchingCharRequired(line, curr_char, L'\"');
		end = curr_char;
		curr_char++;
		wcsubstr(line, start, end, str_buffer);
		end_offset = EDTOffset(_wtoi(str_buffer));
		return true;

	}

	catch(UnexpectedInputException& e){
		e.prependToMessage("Processor::parseAnnotationLine() ");
		throw;
	}
}

wstring Processor::getRetVal(bool ok, const wchar_t* txt){
	wstring retval(L"<RETURN>\n");
	if(ok){
		retval +=L"\t<RETURN_CODE>OK</RETURN_CODE>\n";
	}
	else{
		retval += L"\t<RETURN_CODE>ERROR</RETURN_CODE>\n";
	}
	retval +=L"\t<RETURN_VALUE>";
	retval += txt;
	retval += L"</RETURN_VALUE>\n";
	retval += L"</RETURN>";

	return retval;
}
wstring Processor::getRetVal(bool ok, const char* txt){
	wstring retval(L"<RETURN>\n");
	if(strlen(txt) >999){
		char errbuffer[1000];
		strcpy(errbuffer, "Invalid Conversion, String too long\nFirst 900 characters: ");
		strncat(errbuffer, txt, 900);
		return getRetVal(false, errbuffer);
	}
	wchar_t conversionbuffer[1000];
	mbstowcs(conversionbuffer, txt, 1000);

	if(ok){
		retval +=L"\t<RETURN_CODE>OK</RETURN_CODE>\n";
	}
	else{
		retval += L"\t<RETURN_CODE>ERROR</RETURN_CODE>\n";
	}
	retval +=L"\t<RETURN_VALUE>";

	retval += conversionbuffer;
	retval += L"</RETURN_VALUE>\n";
	retval += L"</RETURN>";

	return retval;
}

int Processor::getTokenFromOffset(const TokenSequence* tok, EDTOffset offset){
	int midtoken = tok->getNTokens()/2;
	EDTOffset midoffset = tok->getToken(midtoken)->getStartEDTOffset();
	if(offset == midoffset){
		return midtoken;
	}
	if(offset < midoffset){
		for(int i=0; i< midtoken; i++){
			if((tok->getToken(i)->getStartEDTOffset()<= offset) &&
				(tok->getToken(i)->getEndEDTOffset()>= offset)){
					return i;
				}
		}
	}
	if(offset > midoffset){
		for(int i = midtoken; i< tok->getNTokens(); i++){
			if((tok->getToken(i)->getStartEDTOffset()<= offset) &&
				(tok->getToken(i)->getEndEDTOffset()>= offset)){
					return i;
				}
		}
	}
	return -1;
}

int Processor::getStartTokenFromOffset(const TokenSequence* tok, EDTOffset offset){
	int midtoken = tok->getNTokens()/2;
	EDTOffset midoffset = tok->getToken(midtoken)->getStartEDTOffset();

	if(offset == midoffset){
		while (midtoken > 0 && tok->getToken(midtoken-1)->getEndEDTOffset() == offset)
			midtoken--;
		return midtoken;
	}
	if(offset < midoffset){
		for(int i=0; i< midtoken; i++){
			if((tok->getToken(i)->getStartEDTOffset()<= offset) &&
				(tok->getToken(i)->getEndEDTOffset()>= offset)){
					return i;
				}
		}
	}
	if(offset > midoffset){
		for(int i = midtoken; i< tok->getNTokens(); i++){
			if((tok->getToken(i)->getStartEDTOffset()<= offset) &&
				(tok->getToken(i)->getEndEDTOffset()>= offset)){
					return i;
				}
		}
	}
	return -1;
}

int Processor::getEndTokenFromOffset(const TokenSequence* tok, EDTOffset offset){
	int midtoken = tok->getNTokens()/2;
	EDTOffset midoffset = tok->getToken(midtoken)->getStartEDTOffset();

	if(offset == midoffset){
		while (midtoken < tok->getNTokens() && tok->getToken(midtoken+1)->getStartEDTOffset() == offset)
			midtoken++;
		return midtoken;
	}
	if(offset < midoffset){
		for(int i = midtoken - 1; i >= 0; i--){
			if((tok->getToken(i)->getStartEDTOffset()<= offset) &&
				(tok->getToken(i)->getEndEDTOffset()>= offset)){
					return i;
				}
		}
	}
	if(offset > midoffset){
		for(int i = tok->getNTokens() - 1; i >= midtoken; i--){
			if((tok->getToken(i)->getStartEDTOffset()<= offset) &&
				(tok->getToken(i)->getEndEDTOffset()>= offset)){
					return i;
				}
		}
	}
	return -1;
}

int Processor::findNextMatchingChar(const wchar_t* txt, int start, wchar_t c){
	int length = static_cast<int>(wcslen(txt));
	int curr_char = start;
	while((curr_char < length) && txt[curr_char] != c){
		curr_char++;
	}
	if(txt[curr_char] == c){
		return curr_char;
	}
	else{
		return -1;
	}
}
int Processor::findNextMatchingCharRequired(const wchar_t* txt, int start, wchar_t c){
	int retval = findNextMatchingChar(txt, start, c);
	if(retval >= 0){
		return retval;
	}
	else{
		char buffer[500];
		snprintf(buffer, 500, "Couldn't find character: %c after char # %d ", c, start);
		throw UnexpectedInputException("PIdFActiveLearning:findNextMatchingCharRequired()",
					buffer);
		return -1;
	}
}

int Processor::splitNameTokens(const Token* origTok, int inName[], const NameOffset nameInfo[], const LocatedString *sentenceString, Token** newTokens) {
	int nnames = inName[0];
	int sorted_names[MAX_NAMES_PER_SPACE_SEP_TOK + 1];
	sorted_names[0] = nnames;
	EDTOffset min_offset(9999);
	EDTOffset prev_offset;
	int token_number = -1;
	// sort the names by their start offsets
	for (int j = 1; j <= nnames; j++) {
		for (int i = 1; i <= nnames; i++) {
			EDTOffset offset = nameInfo[inName[i]].startoffset;
			if ((offset < min_offset) && (offset > prev_offset)) {
				min_offset = offset;
				token_number = i;
			}
		}
		sorted_names[j] = inName[token_number];
		prev_offset = min_offset;
		min_offset = EDTOffset(9999);
	}

	Token * token_to_split = _new Token(*origTok);
	int currTok = 0;
	for (int i = 1; i <= nnames; i++) {
		Token* nameParts[3];
		int nnewtoks = splitNameTokens(token_to_split,
			nameInfo[sorted_names[i]].startoffset, nameInfo[(sorted_names[i])].endoffset,
			sentenceString, nameParts);
		for(int j = 0; j < nnewtoks-1; j++){
			newTokens[currTok] = nameParts[j];
			currTok++;
		}
		token_to_split = nameParts[nnewtoks - 1];
	}
	newTokens[currTok] = token_to_split;

	return currTok+1;
}

int Processor::splitNameTokens(const Token* origTok, EDTOffset namestart,
										EDTOffset nameend, const LocatedString *sentenceString, Token** newTokens)
{
	if((namestart <= origTok->getStartEDTOffset()) && (nameend >= origTok->getEndEDTOffset())){
		newTokens[0] = _new Token(*origTok);
		return 1;
	}
	const wchar_t* toktxt = origTok->getSymbol().to_string();

	if((namestart <= origTok->getStartEDTOffset()) && (nameend <= origTok->getEndEDTOffset())){
		int start_pos = sentenceString->positionOfStartOffset(origTok->getStartEDTOffset());
		int split_pos = sentenceString->positionOfEndOffset(nameend);
		int end_pos = sentenceString->positionOfEndOffset(origTok->getEndEDTOffset());
		newTokens[0] = _new Token(sentenceString, start_pos, split_pos);
		newTokens[1] = _new Token(sentenceString, split_pos+1, end_pos);
		return 2;
	}
	if((namestart >= origTok->getStartEDTOffset()) && (nameend >= origTok->getEndEDTOffset())){
		int start_pos = sentenceString->positionOfStartOffset(origTok->getStartEDTOffset());
		int split_pos = sentenceString->positionOfEndOffset(namestart)-1;
		int end_pos = sentenceString->positionOfEndOffset(origTok->getEndEDTOffset());
		newTokens[0] = _new Token(sentenceString, start_pos, split_pos);
		newTokens[1] = _new Token(sentenceString, split_pos+1, end_pos);
		return 2;
	}
	if((namestart >= origTok->getStartEDTOffset()) && (nameend <= origTok->getEndEDTOffset())){
		int start_pos = sentenceString->positionOfStartOffset(origTok->getStartEDTOffset());
		int split1_pos = sentenceString->positionOfEndOffset(namestart)-1;
		int split2_pos = sentenceString->positionOfEndOffset(nameend);
		int end_pos = sentenceString->positionOfEndOffset(origTok->getEndEDTOffset());
		newTokens[0] = _new Token(sentenceString, start_pos, split1_pos);
		newTokens[1] = _new Token(sentenceString, split1_pos+1, split2_pos);
		newTokens[2] = _new Token(sentenceString, split2_pos+1, end_pos);
		return 3;
	}
	return 0;
}

std::wstring Processor::getSentenceTextFromStream(UTF8InputStream &in) {
	std::wstring sent_txt, line;
	bool add_new_line = false;

	in.getLine(line);
	const wchar_t* linestr = line.c_str();
	int start = findNextMatchingCharRequired(linestr, 0, L'>');
	start++;
	int end = findNextMatchingChar(line.c_str(),start, L'<');
	if(end!=-1) { // in case of <DISPLAY_TEXT>text...</DISPLAY_TEXT>
		sent_txt += line.substr(start, end-start);
	}else { // in case of <DISPLAY_TEXT>\n text...\n </DISPLAY_TEXT>
		while(end==-1) {
			in.getLine(line);
			end = findNextMatchingChar(line.c_str(),0, L'<');
			if(end==-1) {
				if(add_new_line)
					sent_txt += L'\n';
				sent_txt += line;
				add_new_line = true;
			}
		}
	}
	return sent_txt;
}

/*
int Processor::splitNameTokens(const Token* origTok, int namestart,
										int nameend, Token** newTokens)
{
	if((namestart <= origTok->getStartEDTOffset()) && (nameend >= origTok->getEndEDTOffset())){
		newTokens[0] = _new Token(*origTok);
		return 1;
	}
	const wchar_t* toktxt = origTok->getSymbol().to_string();
	wchar_t tokbuff[500];

	if((namestart <= origTok->getStartEDTOffset()) && (nameend <= origTok->getEndEDTOffset())){
		wcsubstr(toktxt, origTok->getStartEDTOffset(), nameend, tokbuff);
		Symbol part1sym = Symbol(tokbuff);
		wcsubstr(toktxt, nameend+1, origTok->getEndEDTOffset(), tokbuff);
		Symbol part2sym = Symbol(tokbuff);

		Token* part1 = _new Token(origTok->getStartEDTOffset(), nameend, part1sym);
		Token* part2 = _new Token(nameend+1, origTok->getEndEDTOffset(),  part2sym);
		newTokens[0] = part1;
		newTokens[1] = part2;
		return 2;
	}
	if((namestart >= origTok->getStartEDTOffset()) && (nameend >= origTok->getEndEDTOffset())){
		wcsubstr(toktxt, origTok->getStartEDTOffset(), namestart-1, tokbuff);
		Symbol part1sym = Symbol(tokbuff);
		wcsubstr(toktxt, namestart, origTok->getEndEDTOffset(), tokbuff);
		Symbol part2sym = Symbol(tokbuff);
		Token* part1 = _new Token(origTok->getStartEDTOffset(), namestart-1, part1sym);
		Token* part2 = _new Token(namestart, origTok->getEndEDTOffset(),  part2sym);
		newTokens[0] = part1;
		newTokens[1] = part2;
		return 2;
	}
	if((namestart >= origTok->getStartEDTOffset()) && (nameend <= origTok->getEndEDTOffset())){
		wcsubstr(toktxt, origTok->getStartEDTOffset(), namestart-1, tokbuff);
		Symbol part1sym = Symbol(tokbuff);
		wcsubstr(toktxt, namestart, nameend, tokbuff);
		Symbol part2sym = Symbol(tokbuff);
		wcsubstr(toktxt, nameend+1, origTok->getEndEDTOffset(), tokbuff);
		Symbol part3sym = Symbol(tokbuff);

		Token* part1 = _new Token(origTok->getStartEDTOffset(), namestart-1, part1sym);
		Token* part2 = _new Token(namestart, nameend, part2sym);
		Token* part3 = _new Token(nameend+2, origTok->getEndEDTOffset(),  part3sym);
		newTokens[0] = part1;
		newTokens[1] = part2;
		newTokens[2] = part3;
		return 3;
	}
	return 0;
}

*/

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
//
//  strassen.cpp
//  Jacobian
//
//  Created by David Freifeld
//  Copyright © 2020 David Freifeld. All rights reserved.
//
//  Description:
//  Experimental benchmarking of Strassen's Algorithm vs plain Eigen matrix multiply.
//  While naive multiplication is O(n^3), Strassen's Algorithm for matrix multiply is O(n^2.8074)
//  which means significant differences will begin to manifest for large matrices. All faster algorithms are galactic.
//

#include <Eigen/Dense>
#include <ctime>
#include <iostream>

// Not remotely extensible, just initial test.
Eigen::MatrixXf strassen_mul(Eigen::MatrixXf x, Eigen::MatrixXf y)
{
  int power = 0;
  int largest;
  if (x.rows() >= x.cols() || x.rows() >= y.cols() || x.rows() >= y.rows()) largest = x.rows();
  else if (x.cols() >= x.rows() || x.cols() >= y.cols() || x.cols() >= y.rows()) largest = x.cols();
  else if (y.cols() >= x.rows() || y.cols() >= x.cols() || y.cols() >= y.rows()) largest = y.cols();
  else if (y.rows() >= x.rows() || y.rows() >= x.cols() || y.rows() >= y.cols()) largest = y.rows();
  for (; pow(2, power) < largest; power++) {
    std::cout << pow(2, power) << " " << power <<"\n";
  }
  std::cout << "POWER: " << power << " LARGEST: " << largest << "\n";
  Eigen::MatrixXf a ((int)pow(2,power), (int)pow(2,power));
  Eigen::MatrixXf b ((int)pow(2,power), (int)pow(2,power));
  a.block(0,0,x.rows(), x.cols()) = x;
  b.block(0,0,y.rows(), y.cols()) = y;
  std::cout << "\nINIT\n" << a << "\n\n" << b << "\n\n\n";
  std::cout << "\nEIGEN_VER\n" << a*b << "\n\n\n";
  //Eigen::MatrixXf a ()
  int block_len = largest/2;
  Eigen::MatrixXf result ((int)pow(2,power), (int)pow(2,power));

  Eigen::MatrixXf m1 = ((a.block(0,0, block_len, block_len)) + a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len)) * (b.block(0,0, block_len, block_len) + b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));
  Eigen::MatrixXf m2 = (a.block(a.rows()-block_len, 0, block_len, block_len) + a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len)) * (b.block(0,0, block_len, block_len));
  Eigen::MatrixXf m3 = a.block(0,0, block_len, block_len) * (b.block(0,b.cols()-block_len, block_len, block_len) - b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));
  Eigen::MatrixXf m4 = a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len) * (b.block(b.rows()-block_len,0, block_len, block_len) - b.block(0,0, block_len, block_len));
  Eigen::MatrixXf m5 = (a.block(0, 0, block_len, block_len) + a.block(0,a.cols()-block_len, block_len, block_len)) * (b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));
  Eigen::MatrixXf m6 = (a.block(a.rows()-block_len,0, block_len, block_len) - a.block(0,0, block_len, block_len)) * (b.block(0,0, block_len, block_len) + b.block(0,b.cols()-block_len, block_len, block_len));
  Eigen::MatrixXf m7 = (a.block(0,a.cols()-block_len, block_len, block_len) - a.block(a.rows()-block_len,a.cols()-block_len, block_len, block_len)) * (b.block(a.rows()-block_len,0, block_len, block_len) + b.block(b.rows()-block_len,b.cols()-block_len, block_len, block_len));

  //  std::cout << m1 + m4 - m5 + m7 << "\n\n" << m3+m5 << "\n\n" << m2+m4 << "\n\n" << m1-m2+m3+m6;

  result.block(0,0, block_len, block_len) =  m1 + m4 - m5 + m7;
  result.block(0,result.cols()-block_len, block_len, block_len) =  m3 + m5;
  result.block(result.rows()-block_len,0, block_len, block_len) =  m2 + m4;
  result.block(result.rows()-block_len,result.cols()-block_len, block_len, block_len) =  m1 -m2 + m3 + m6;
  std::cout << "\nSTRASSEN_VER\n" << result << "\n\n\n";
  return result;
}

int main()
{
  srand((unsigned int) time(0));
  int sz;
  std::cin >> sz;
  Eigen::MatrixXf a = Eigen::MatrixXf::Random(sz, 3);
  Eigen::MatrixXf b = Eigen::MatrixXf::Random(3, sz);

  auto eigen_begin = std::chrono::high_resolution_clock::now();
  Eigen::MatrixXf product = a * b;
  auto eigen_end = std::chrono::high_resolution_clock::now();

  auto strassen_begin = std::chrono::high_resolution_clock::now();
  Eigen::MatrixXf sproduct = strassen_mul(a, b);
  auto strassen_end = std::chrono::high_resolution_clock::now();

  /* std::cout << "EIGEN: " << std::chrono::duration_cast<std::chrono::nanoseconds>(eigen_end - eigen_begin).count() / pow(10,9) << " STRASSEN: " << std::chrono::duration_cast<std::chrono::nanoseconds>(strassen_end - strassen_begin).count() / pow(10,9) << "\n"; */
  /* std::cout << "A:\n" << a << "\nB:\n" << b << "\nEigen:\n" << product << "\nStrassen:\n" << sproduct << "\n"; */
}

max_stars_repo_name: richardfeynmanrocks/ml-in-parallel

max_issues_repo_name: quantumish/Jacobian

max_forks_repo_name: quantumish/Jacobian


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// 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
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//

#ifndef BOOST_COMPUTE_ALGORITHM_MISMATCH_HPP
#define BOOST_COMPUTE_ALGORITHM_MISMATCH_HPP

#include <iterator>
#include <utility>

#include <boost/compute/system.hpp>
#include <boost/compute/functional.hpp>
#include <boost/compute/command_queue.hpp>
#include <boost/compute/algorithm/find.hpp>
#include <boost/compute/iterator/transform_iterator.hpp>
#include <boost/compute/iterator/zip_iterator.hpp>
#include <boost/compute/functional/detail/unpack.hpp>

namespace boost {
namespace compute {

/// Returns a pair of iterators pointing to the first position where the
/// range [\p first1, \p last1) and the range starting at \p first2
/// differ.
template<class InputIterator1, class InputIterator2>
inline std::pair<InputIterator1, InputIterator2>
mismatch(InputIterator1 first1,
         InputIterator1 last1,
         InputIterator2 first2,
         command_queue &queue = system::default_queue())
{
    typedef typename std::iterator_traits<InputIterator1>::value_type value_type;

    ::boost::compute::equal_to<value_type> op;

    InputIterator2 last2 = first2 + std::distance(first1, last1);

    InputIterator1 iter =
        boost::get<0>(
            ::boost::compute::find(
                ::boost::compute::make_transform_iterator(
                    ::boost::compute::make_zip_iterator(
                        boost::make_tuple(first1, first2)
                    ),
                    detail::unpack(op)
                ),
                ::boost::compute::make_transform_iterator(
                    ::boost::compute::make_zip_iterator(
                        boost::make_tuple(last1, last2)
                    ),
                    detail::unpack(op)
                ),
                false,
                queue
            ).base().get_iterator_tuple()
        );

    return std::make_pair(iter, first2 + std::distance(first1, iter));
}

/// \overload
template<class InputIterator1, class InputIterator2>
inline std::pair<InputIterator1, InputIterator2>
mismatch(InputIterator1 first1,
         InputIterator1 last1,
         InputIterator2 first2,
         InputIterator2 last2,
         command_queue &queue = system::default_queue())
{
    if(std::distance(first1, last1) < std::distance(first2, last2)){
        return ::boost::compute::mismatch(first1, last1, first2, queue);
    }
    else {
        return ::boost::compute::mismatch(
            first1, first1 + std::distance(first2, last2), first2, queue
        );
    }
}

} // end compute namespace
} // end boost namespace

#endif // BOOST_COMPUTE_ALGORITHM_MISMATCH_HPP

max_stars_repo_name: skozilla/compute

max_issues_repo_name: junmuz/compute

max_forks_repo_name: junmuz/compute