text:
#include <libcaercpp/devices/davis.hpp>

#include <atomic>
#include <csignal>
#include <fstream>
#include <iostream>

#include <opencv2/core/core.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

static std::atomic_bool globalShutdown(false);

static void globalShutdownSignalHandler(int signal) {
	// Simply set the running flag to false on SIGTERM and SIGINT (CTRL+C) for global shutdown.
	if (signal == SIGTERM || signal == SIGINT) {
		globalShutdown.store(true);
	}
}

static void usbShutdownHandler(void *ptr) {
	(void) (ptr); // UNUSED.

	globalShutdown.store(true);
}

int main(int argc, char * argv[]) {
	boost::program_options::options_description desc("Allowed options");
	desc.add_options()
		("help,h", "produce a help screen")
		("event,e", "display events")
		("frame,f", "display APS frames")
		("quiet,q", "run the exe in quiet mode")
		;

	boost::program_options::variables_map vm;
	boost::program_options::store(parse_command_line(argc, argv, desc), vm);

	if(vm.count("help"))
	{
		std::cout << "Usage: regex [options]\n";
		std::cout << desc;
		return (EXIT_SUCCESS);
	}

// Install signal handler for global shutdown.
#if defined(_WIN32)
	if (signal(SIGTERM, &globalShutdownSignalHandler) == SIG_ERR) {
		libcaer::log::log(libcaer::log::logLevel::CRITICAL, "ShutdownAction",
			"Failed to set signal handler for SIGTERM. Error: %d.", errno);
		return (EXIT_FAILURE);
	}

	if (signal(SIGINT, &globalShutdownSignalHandler) == SIG_ERR) {
		libcaer::log::log(libcaer::log::logLevel::CRITICAL, "ShutdownAction",
			"Failed to set signal handler for SIGINT. Error: %d.", errno);
		return (EXIT_FAILURE);
	}
#else
	struct sigaction shutdownAction;

	shutdownAction.sa_handler = &globalShutdownSignalHandler;
	shutdownAction.sa_flags   = 0;
	sigemptyset(&shutdownAction.sa_mask);
	sigaddset(&shutdownAction.sa_mask, SIGTERM);
	sigaddset(&shutdownAction.sa_mask, SIGINT);

	if (sigaction(SIGTERM, &shutdownAction, NULL) == -1) {
		libcaer::log::log(libcaer::log::logLevel::CRITICAL, "ShutdownAction",
			"Failed to set signal handler for SIGTERM. Error: %d.", errno);
		return (EXIT_FAILURE);
	}

	if (sigaction(SIGINT, &shutdownAction, NULL) == -1) {
		libcaer::log::log(libcaer::log::logLevel::CRITICAL, "ShutdownAction",
			"Failed to set signal handler for SIGINT. Error: %d.", errno);
		return (EXIT_FAILURE);
	}
#endif

	// Make folders for saving current image
	std::string folder_name_img = "log/images/";

	std::string folder_remove_command;
	folder_remove_command = "rm -rf " + folder_name_img;
	if( system(folder_remove_command.c_str()) ){
		return (EXIT_FAILURE);
	}

	std::string folder_create_command;
	folder_create_command = "mkdir -p " + folder_name_img;
	if( system(folder_create_command.c_str()) ){
		return (EXIT_FAILURE);
	}

	// Open file for writing.
	std::fstream fEventOutput, fIMUOutput, fImageOutput;;
	fEventOutput.open("log/events.txt", std::fstream::out);
	fImageOutput.open("log/images.txt", std::fstream::out);
	fIMUOutput.open("log/imu.txt", std::fstream::out);

	// Open a DAVIS, give it a device ID of 1, and don't care about USB bus or SN restrictions.
	libcaer::devices::davis davisHandle = libcaer::devices::davis(1);

	// Let's take a look at the information we have on the device.
	struct caer_davis_info davis_info = davisHandle.infoGet();
	std::cout << davis_info.deviceString
		<< " --- ID: " << davis_info.deviceID
		<< ", Master: " << davis_info.deviceIsMaster
		<< ", DVS X:" << davis_info.dvsSizeX
		<< ", DVS Y: " << davis_info.dvsSizeY
		<< ", Logic: " << davis_info.logicVersion << std::endl;

	// Send the default configuration before using the device.
	// No configuration is sent automatically!
	davisHandle.sendDefaultConfig();

	// Now let's get start getting some data from the device. We just loop in blocking mode,
	// no notification needed regarding new events. The shutdown notification, for example if
	// the device is disconnected, should be listened to.
	davisHandle.dataStart(nullptr, nullptr, nullptr, &usbShutdownHandler, nullptr);

	// Let's turn on blocking data-get mode to avoid wasting resources.
	davisHandle.configSet(CAER_HOST_CONFIG_DATAEXCHANGE, CAER_HOST_CONFIG_DATAEXCHANGE_BLOCKING, true);

	std::cout << "Started logging to file ..." << std::endl;

	char image_index_char[255];
	std::string image_file_name;
	unsigned int image_index = 0;

	while (!globalShutdown.load(std::memory_order_relaxed)) {
		std::unique_ptr<libcaer::events::EventPacketContainer> packetContainer = davisHandle.dataGet();
		if (packetContainer == nullptr) {
			continue; // Skip if nothing there.
		}

		for (auto &packet : *packetContainer) {
			if (packet == nullptr) {
				continue; // Skip if nothing there.
			}

			if (packet->getEventType() == POLARITY_EVENT) {
				std::shared_ptr<const libcaer::events::PolarityEventPacket> polarity
					= std::static_pointer_cast<libcaer::events::PolarityEventPacket>(packet);

				cv::Mat cvEvents(davis_info.dvsSizeY, davis_info.dvsSizeX, CV_8UC3, cv::Vec3b{127, 127, 127});

				// Print out timestamps and addresses.
				for (const auto &evt : *polarity) {
					int64_t ts = evt.getTimestamp64(*polarity);
					uint16_t x = evt.getX();
					uint16_t y = evt.getY();
					bool pol   = evt.getPolarity();

					if( vm.count("event") ){
						cvEvents.at<cv::Vec3b>(y, x) = pol? cv::Vec3b{0, 0, 255} : cv::Vec3b{0, 255, 0};
					}

					fEventOutput << std::fixed << std::setprecision(6) << (double)ts*1e-6 << " " << x << " " << y << " " << pol << std::endl;
				}

				if( vm.count("event") ){
					cv::imshow("DVS-EVS", cvEvents);
					cv::waitKey(1);
				}
			}
			else if (packet->getEventType() == IMU6_EVENT) {
				std::shared_ptr<const libcaer::events::IMU6EventPacket> imu
					= std::static_pointer_cast<libcaer::events::IMU6EventPacket>(packet);

				// Print out timestamps and data.
				for (const auto &evt : *imu) {
					int64_t ts   = evt.getTimestamp64(*imu);
					float accelX = evt.getAccelX();
					float accelY = evt.getAccelY();
					float accelZ = evt.getAccelZ();
					float gyroX  = evt.getGyroX();
					float gyroY  = evt.getGyroY();
					float gyroZ  = evt.getGyroZ();

					fIMUOutput << std::fixed << std::setprecision(6) << (double)ts*1e-6 << " " << accelX << " " << accelY << " " << accelZ << " " << gyroX
							   << " " << gyroY << " " << gyroZ << std::endl;
				}
			}
			else if (packet->getEventType() == FRAME_EVENT) {
				std::shared_ptr<const libcaer::events::FrameEventPacket> frame
					= std::static_pointer_cast<libcaer::events::FrameEventPacket>(packet);

				for (const auto &f : *frame) {
					if (f.getROIIdentifier() != 0) {
						continue;
					}

					cv::Mat cvFrame = f.getOpenCVMat(false);
					int32_t ts = f.getTimestamp();

					if( vm.count("frame") ){
							// Simple display, just use OpenCV GUI.
							cv::imshow("DVS-APS", cvFrame);
							cv::waitKey(1);
					}

					sprintf(image_index_char, "frame_%08d", image_index++);
					image_file_name = folder_name_img + image_index_char + ".png";
					cv::imwrite(image_file_name, cvFrame);

					if( !vm.count("quiet") ){
						std::cout << image_file_name << std::endl;
					}

					fImageOutput << std::fixed << std::setprecision(6) << (double)ts*1e-6 << " " << "images/" << image_index_char << ".png" << std::endl;
				}

			}
		}
	}

	davisHandle.dataStop();

	// Close automatically done by destructor.
	fEventOutput.close();
	fIMUOutput.close();
	fImageOutput.close();

	if( vm.count("frame") ) cv::destroyWindow("DVS-APS");
	if( vm.count("event") )	cv::destroyWindow("DVS-EVS");

	std::cout << "Stopped logging to file." << std::endl;

	return (EXIT_SUCCESS);
}


text:
// Copyright 2020 Anatoliy Petrov
// (apetrov.projects@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

#ifndef VARIADIC_DETAIL_ADD_PARENS_HPP
#define VARIADIC_DETAIL_ADD_PARENS_HPP

/* boost */
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/punctuation/is_begin_parens.hpp>

#define VDC_DETAIL_ADD_PARENS_COND(arg) \
    BOOST_PP_IF( \
        BOOST_PP_IS_BEGIN_PARENS(arg), \
        arg, \
        (arg) \
    )

#define VDC_DETAIL_ADD_PARENS(arg) (arg)

#endif /* VARIADIC_DETAIL_ADD_PARENS_HPP */

ext: hpp

max_stars_repo_name: AnatoliyProjects/variadic

max_issues_repo_name: AnatoliyProjects/variadic

max_forks_repo_name: AnatoliyProjects/variadic


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

  @copyright 2016 NumScale SAS

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

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

 /*!

    @ingroup group-trigonometric
    Function object implementing atan2pi capabilities

    atan2pi function : atan2 in pi multiples.

    @par Semantic:

    For every parameters of same floating type

    @code
    auto r = atan2pi(y, x);
    @endcode

    is similar  to:

    @code
    auto r =  atan2(y, x)/Pi;
    @endcode

    as it is quadrant aware.

    For any real arguments @c x and @c y not both equal to zero, <tt>atan2pi(y, x)</tt>
    is the angle in degrees between the positive x-axis of a plane and the point
    given by the coordinates  <tt>(x, y)</tt>.

    It is also the angle in \f$[-1, 1[\f$ for which
    \f$x/\sqrt{x^2+y^2}\f$ and \f$y/\sqrt{x^2+y^2}\f$
    are respectively the sine and the cosine.

    @see atand, atan2, atan2d, atan

  **/
  Value atan2pi(Value const& x, const Value &y);
} }
#endif

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

#endif

max_stars_repo_name: xmar/pythran

max_issues_repo_name: xmar/pythran

max_forks_repo_name: xmar/pythran


text:
//
// Copyright 2013 Christian Henning
//
// 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/gil.hpp>
#include <boost/gil/extension/io/jpeg/old.hpp>

#include <boost/mp11.hpp>
#include <boost/core/lightweight_test.hpp>

#include "mandel_view.hpp"
#include "paths.hpp"

namespace gil = boost::gil;
namespace mp11 = boost::mp11;

#ifdef BOOST_GIL_IO_TEST_ALLOW_READING_IMAGES

void test_old_read_dimensions()
{
    gil::point_t dim = gil::jpeg_read_dimensions(jpeg_filename);
    BOOST_TEST_EQ(dim.x, 1000);
    BOOST_TEST_EQ(dim.y, 600);
}

void test_old_read_image()
{
    gil::rgb8_image_t img;
    gil::jpeg_read_image(jpeg_filename, img);

    BOOST_TEST_EQ(img.width(), 1000);
    BOOST_TEST_EQ(img.height(), 600);
}

void test_old_read_and_convert_image()
{
    gil::rgb8_image_t img;
    gil::jpeg_read_and_convert_image(jpeg_filename, img);

    BOOST_TEST_EQ(img.width(), 1000);
    BOOST_TEST_EQ(img.height(), 600);
}

void test_old_read_view()
{
    gil::rgb8_image_t img(1000, 600);
    gil::jpeg_read_view(jpeg_filename, gil::view(img));
}

void test_old_read_and_convert_view()
{
    gil::rgb8_image_t img(1000, 600);
    gil::jpeg_read_and_convert_view(jpeg_filename, gil::view(img));
}

void test_old_write_view()
{
#ifdef BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
    auto b = gil::rgb8_pixel_t(0, 0, 255);
    auto g = gil::rgb8_pixel_t(0, 255, 0);
    gil::jpeg_write_view(jpeg_out + "old_write_test.jpg", create_mandel_view(320, 240, b, g));
#endif // BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
}

void test_old_dynamic_image()
{
    using my_img_types = mp11::mp_list
        <
            gil::gray8_image_t,
            gil::gray16_image_t,
            gil::rgb8_image_t,
            gil::rgba8_image_t
        >;

    gil::any_image<my_img_types> image;
    gil::jpeg_read_image(jpeg_filename.c_str(), image);

#ifdef BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
    gil::jpeg_write_view(jpeg_out + "old_dynamic_image_test.jpg", gil::view(image));
#endif // BOOST_GIL_IO_TEST_ALLOW_WRITING_IMAGES
}

int main()
{
    test_old_read_dimensions();
    test_old_read_image();
    test_old_read_and_convert_image();
    test_old_read_view();
    test_old_read_and_convert_view();
    test_old_write_view();
    test_old_dynamic_image();

    return boost::report_errors();
}

#else
int main() {}
#endif // BOOST_GIL_IO_TEST_ALLOW_READING_IMAGES

ext: cpp

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
/*
 * vi:ts=4:shiftwidth=4:expandtab
 * vim600:fdm=marker
 *
 * ngramstat.hpp  -  Implements Nagao 1994 N-gram extraction algorithm (unicode
 * version)
 *
 * This class implements Nagao 1994's N-gram extraction algorithm (with minor
 * improvements). All the Characters are encoded in unicode (uchar_t)
 * internally so we can handle oriental languages like Chinese and Japanese
 * gracefully.
 *
 * Copyright (C) 2002 by Zhang Le <ejoy@users.sourceforge.net>
 * Begin       : 30-Oct-2002
 * Last Change : 22-Apr-2004.
 *
 * 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 NGRAMSTAT_H
#define NGRAMSTAT_H

#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <cwchar>
#include <boost/utility.hpp>
#include <boost/function.hpp>

#include "unicode.hpp"

using std::basic_string;
using std::char_traits;
using std::string;
using std::ustring;
using std::vector;

template <typename CharT, typename Traits = std::char_traits<CharT> >
/**
 * This class implements Nagao 1994 N-gram extraction algorithm.
 *
 * All characters are represented with unicode (uchar_t) internally for better
 * handling of oriental languages.
 */
class NGramStat : boost::noncopyable {
    public:
        typedef basic_string<CharT, Traits> string_type;
        typedef boost::function<void(const string_type& ngram,
                unsigned count)> OutputFunc;

        NGramStat(unsigned memory, const string& file_name_base = "",
                bool use_mmap = false);
        ~NGramStat();

        void clear();
//        void parse(const vector<string>& files, const string& encoding = "UTF-8");
//        void parse(const string& str, const string& encoding = "UTF-8");
        void parse_begin();
        void parse_end();
        void parse_buf(const string_type& buf);
//        void parse(const string_type& str);
        void extract_ngram(unsigned N,
                unsigned M,
                unsigned freq,
                OutputFunc& output) ;
//        void extract_ngram(unsigned N,
//                unsigned M,
//                unsigned freq,
//                std::ostream& os = std::cout,
//                const string& encoding = "UTF-8");
        void set_temp_dir(const string& dir){};

    private: //{{{

        struct NGram{
            string_type  m_text;
            unsigned m_count;
        };

        /**
         * compare two wide string pointed by ptable index
         * if the first 255 chars of the two string are equal
         * we define the string with lower index is smaller
         */
        struct cmp_ptable {
            cmp_ptable(const CharT* buf):m_buf(buf){}
            bool operator()(const unsigned& lhs,const unsigned& rhs) const {
                int rc = Traits::compare((const CharT*)&m_buf[lhs],
                        (const CharT*)&m_buf[rhs],255);
                return (rc < 0 || (rc == 0 && lhs < rhs));
            }
            private:
            const CharT* m_buf;
        };

        void alloc_mem();
//        void preprocess_w(ustring& buf) const;
//        string_type preprocess(ustring& buf)
//            const {return string_type();}
        void calc_ltable();
        void save_temp_buffer();
        void write_ltable() const;
        void write_ltable(const CharT* ngram_table,const string ptable_filename) const;
        void write_ptable(const string& name,unsigned start_offset) const;
        void merge_ptables();
        void add_ptable_node(unsigned start,unsigned end);
        unsigned char calc_common_words(const CharT* s1,const CharT* s2) const;
        string next_temp_ptable_filename() const;
        void fetch_ngram(unsigned N,CharT* s,string_type& ngram) const;
        void fetch_ngrams(unsigned N,unsigned M,CharT* s,vector<NGram>& ngrams) const;
        unsigned ptable_entry(unsigned* ptable,FILE* fp,unsigned pos) const;
        unsigned char ltable_entry(unsigned char* ltable,FILE* fp,unsigned pos) const;
        unsigned ptable_entry(unsigned pos);
        unsigned char ltable_entry(unsigned pos);
//        bool is_punct_w(uchar_t ch) const;
//        bool has_punct(const string_type& s) const;
//        void utf8Output(const ustring& ws,unsigned count) const;

        //extra buffer to hold enough room for at most 255 words/chars
        //(assume wordlen == 20)
        //beyond m_buffersize,these words will be copy to
        //the beginning of m_buffer after flushing out m_buffer
        //to ngram file and writing temp ptable
        static const unsigned m_extra_buffersize = 20 * 255; //about 20k

        unsigned       m_start_offset;    //in-memory buffer's offset in the whole nmram file in terms of uchar_t
        unsigned       m_buffer_offset;   //current offset in in-memory buffer,in terms of uchar_t where next char is written to
        unsigned       m_last_word_end;   //last valid word's end(word boundary + 1)

        bool           m_is_use_mmap;
        string         m_filename_base;
        std::ofstream  m_ngramfile;
        unsigned       m_mem_size;        //in kb
        unsigned       m_buffersize;      //in-memory buffer size in terms of uchar_t
        CharT*         m_buffer;
        string_type        m_buf_remain;
        vector<unsigned>      *m_ptable;
        vector<unsigned char> *m_ltable;
        vector<string>         m_tempfiles;
        static const CharT s_terminal;
//}}}
};

#include "ngramstat.tcc"
#endif /* ifndef NGRAMSTAT_H */

max_stars_repo_name: jimregan/ngramtool

max_issues_repo_name: jimregan/ngramtool

max_forks_repo_name: jimregan/ngramtool


text:
// cpp-flexargs
//
// Copyright iorate 2018.
// 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)

// Reference: http://www.kmonos.net/alang/boost/classes/program_options.html

#include <iostream>
#include <stdexcept>
#include <string_view>
#include <utility>
#include <boost/timer/timer.hpp>
#include "../flexargs.hpp"
using namespace flexargs;

int calc_v0(std::string_view op, int lhs = 100, int rhs = 200) {
    if (op == "add") {
        return lhs + rhs;
    } else if (op == "sub") {
        return lhs - rhs;
    } else if (op == "mul") {
        return lhs * rhs;
    } else if (op == "div") {
        if (rhs == 0) {
            throw std::invalid_argument("division by zero");
        } else {
            return lhs / rhs;
        }
    } else {
        throw std::invalid_argument("bad operator");
    }
}

namespace keywords {
    inline constexpr keyword<struct op_> op;
    inline constexpr keyword<struct lhs_> lhs;
    inline constexpr keyword<struct rhs_> rhs;
}

template <class ...Args>
int calc_v1(Args &&...args) {
    auto [op, lhs, rhs] = match(
        parameter<std::string_view>(keywords::op),
        parameter<int>(keywords::lhs) = 100,
        parameter<int>(keywords::rhs) = 200,
        std::forward<Args>(args)...
    );
    if (op == "add") {
        return lhs + rhs;
    } else if (op == "sub") {
        return lhs - rhs;
    } else if (op == "mul") {
        return lhs * rhs;
    } else if (op == "div") {
        if (rhs == 0) {
            throw std::invalid_argument("division by zero");
        } else {
            return lhs / rhs;
        }
    } else {
        throw std::invalid_argument("bad operator");
    }
}

int main() {
    using namespace keywords;
    constexpr int N = 100'000'000;
    {
        std::cout << "call calc_v0() " << N << " times:\n";
        boost::timer::auto_cpu_timer timer;
        for (int i = 0; i < N; ++i) {
            calc_v0("sub", 999);
        }
    }
    {
        std::cout << "call calc_v1() " << N << " times:\n";
        boost::timer::auto_cpu_timer timer;
        for (int i = 0; i < N; ++i) {
            calc_v1(op = "sub", lhs = 999);
        }
    }
}

/*
$ g++ -std=c++17 -O2 performance.cpp -lboost_timer -o performance

$ ./performance
call calc_v0() 100000000 times:
 0.284747s wall, 0.296875s user + 0.000000s system = 0.296875s CPU (104.3%)
call calc_v1() 100000000 times:
 0.729618s wall, 0.718750s user + 0.000000s system = 0.718750s CPU (98.5%)
*/

max_stars_repo_name: iorate/cpp-flexargs

max_issues_repo_name: iorate/cpp-flexargs

max_forks_repo_name: iorate/cpp-flexargs


text:
// links_page.hpp
//
// Copyright (c) 2010 Steven Watanabe
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanyiong file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef LINKS_PAGE_HPP_INCLUDED
#define LINKS_PAGE_HPP_INCLUDED

#include "xml.hpp"
#include <boost/filesystem/path.hpp>

namespace boost {
namespace regression {

void links_page(
    const failures_markup_t& explicit_markup,
    const test_structure_t::run_t& test_run);

}
}

#endif

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
/*
    IO.hpp
    ======
        I/O functions implementation.
*/

#ifndef __YSASA_IO_HPP
#define __YSASA_IO_HPP

#include <cstdio>
#include <string>
#include <vector>
#include <stdexcept>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <Eigen/Dense>
#include <PDBToolsCpp/PDBTools>
#include "AtomBall.h"

namespace YSASA
{

////////////////////////////////////////////////////////////////////////////////
// Using
////////////////////////////////////////////////////////////////////////////////

using std::string;
using std::vector;
using std::invalid_argument;
using boost::filesystem::path;
using boost::filesystem::exists;
using Eigen::RowVector3d;
using PDBTools::Atom;

////////////////////////////////////////////////////////////////////////////////
// Get .xyz File Path
////////////////////////////////////////////////////////////////////////////////

string __getXYZFilePath(const string &dotCountStr)
{
    string xyzFilePath = (path(__FILE__).parent_path().parent_path() /
        "data" / (dotCountStr + ".xyz")).string();

    if (!exists(xyzFilePath))
    {
        throw invalid_argument((boost::format("Invalid argument: -c %s. File: %s not exists") %
            dotCountStr % xyzFilePath).str());
    }

    return xyzFilePath;
}

////////////////////////////////////////////////////////////////////////////////
// Parse .xyz File
////////////////////////////////////////////////////////////////////////////////

void ParseXYZFile(const string &dotCountStr, vector<RowVector3d> &unitBallCoord)
{
    FILE *f = fopen(__getXYZFilePath(dotCountStr).c_str(), "r");
    double x, y, z;

    while (fscanf(f, "%lf %lf %lf", &x, &y, &z) != EOF)
    {
        unitBallCoord.emplace_back(x, y, z);
    }

    fclose(f);
}

////////////////////////////////////////////////////////////////////////////////
// Output Result
////////////////////////////////////////////////////////////////////////////////

void OutputResult(const string &outputFilePath, double SASA)
{
    FILE *fo = fopen(outputFilePath.c_str(), "w");
    fprintf(fo, "SASA: %.6f (A^2)\n", SASA);
    fclose(fo);
}

////////////////////////////////////////////////////////////////////////////////
// Dump Dot PDB
////////////////////////////////////////////////////////////////////////////////

void DumpDotPDB(const string &outputFilePath, const vector<AtomBall> &atomBallObjList)
{
    FILE *fo = fopen(outputFilePath.c_str(), "w");

    for (auto &atomBallObj: atomBallObjList)
    {
        for (auto &atomCoord: atomBallObj.ballCoord())
        {
            fprintf(fo, "%s", Atom("", 0, atomCoord).Dumps().c_str());
        }
    }

    fclose(fo);
}

}  // End namespace YSASA

#endif  // __YSASA_IO_HPP

max_stars_repo_name: yingyulou/YSASA

max_issues_repo_name: yingyulou/YSASA

max_forks_repo_name: yingyulou/YSASA


text:
#pragma once

#include "types.hxx"

#include <boost/functional/hash.hpp>

struct Material
{
  Shader* shader = {nullptr};
  Medium* medium = {nullptr};
  RadianceOrImportance::AreaEmitter *emitter = {nullptr};

  struct Hash
  {
    inline std::size_t operator()(const Material &key) const
    {
      std::size_t h = boost::hash_value((key.shader));
      boost::hash_combine(h, boost::hash_value((key.medium)));
      boost::hash_combine(h, boost::hash_value((void*)key.emitter));
      return h;
    }
  };

  friend inline bool operator==(const Material &a, const Material &b)
  {
    return (a.shader == b.shader) &&
          (a.medium == b.medium) &&
          (a.emitter == b.emitter);
  }
};

ext: hxx

max_stars_repo_name: DaWelter/NaiveTrace

max_issues_repo_name: DaWelter/NaiveTrace

max_forks_repo_name: DaWelter/NaiveTrace


text:
/*
 * Copyright (C) 2014, Computing Systems Laboratory (CSLab), NTUA
 * Copyright (C) 2014, Vasileios Karakasis
 * All rights reserved.
 *
 * This file is distributed under the BSD License. See LICENSE.txt for details.
 */

/**
 * \file Types.hpp
 * \brief Wrap API's types.h and promote user supplied types to our internals
 *
 * \author Computing Systems Laboratory (CSLab), NTUA
 * \date 2011–2014
 * \copyright This file is distributed under the BSD License. See LICENSE.txt
 * for details.
 */

#ifndef SPARSEX_INTERNALS_TYPES_HPP
#define SPARSEX_INTERNALS_TYPES_HPP

#include <sparsex/types.h>
#include <boost/type_traits.hpp>

// Index type should be promoted to unsigned internally
typedef boost::make_unsigned<spx_index_t>::type spx_uindex_t;

#endif  // SPARSEX_INTERNALS_TYPES_HPP

max_stars_repo_name: Baltoli/sparsex

max_issues_repo_name: Baltoli/sparsex

max_forks_repo_name: Baltoli/sparsex


text:
/* =========================================================================
   Copyright (c) 2010-2014, Institute for Microelectronics,
                            Institute for Analysis and Scientific Computing,
                            TU Wien.
   Portions of this software are copyright by UChicago Argonne, LLC.

                            -----------------
                  ViennaCL - The Vienna Computing Library
                            -----------------

   Project Head:    Karl Rupp                   rupp@iue.tuwien.ac.at

   (A list of authors and contributors can be found in the PDF manual)

   License:         MIT (X11), see file LICENSE in the base directory
============================================================================= */

/*
*
*   Tutorial: Least Squares problem for matrices from ViennaCL or Boost.uBLAS (least-squares.cpp and least-squares.cu are identical, the latter being required for compilation using CUDA nvcc)
*
*   See Example 2 at http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx for a reference solution.
*
*/

// activate ublas support in ViennaCL
#define VIENNACL_WITH_UBLAS

//
// include necessary system headers
//
#include <iostream>

//
// Boost includes
//
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/lu.hpp>
#include <boost/numeric/ublas/io.hpp>

//
// ViennaCL includes
//
#include "viennacl/vector.hpp"
#include "viennacl/matrix.hpp"
#include "viennacl/matrix_proxy.hpp"
#include "viennacl/linalg/qr.hpp"
#include "viennacl/linalg/lu.hpp"

/*
*   Tutorial: Least Squares problem for matrices from ViennaCL or Boost.uBLAS
*
*   See Example 2 at http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx for a reference solution.
*/

int main (int, const char **)
{
  typedef float               ScalarType;     //feel free to change this to 'double' if supported by your hardware
  typedef boost::numeric::ublas::matrix<ScalarType>              MatrixType;
  typedef boost::numeric::ublas::vector<ScalarType>              VectorType;
  typedef viennacl::matrix<ScalarType, viennacl::column_major>   VCLMatrixType;
  typedef viennacl::vector<ScalarType>                           VCLVectorType;

  //
  // Create vectors and matrices with data, cf. http://tutorial.math.lamar.edu/Classes/LinAlg/QRDecomposition.aspx
  //
  VectorType ublas_b(4);
  ublas_b(0) = -4;
  ublas_b(1) =  2;
  ublas_b(2) =  5;
  ublas_b(3) = -1;

  MatrixType ublas_A(4, 3);
  MatrixType Q = boost::numeric::ublas::zero_matrix<ScalarType>(4, 4);
  MatrixType R = boost::numeric::ublas::zero_matrix<ScalarType>(4, 3);

  ublas_A(0, 0) =  2; ublas_A(0, 1) = -1; ublas_A(0, 2) =  1;
  ublas_A(1, 0) =  1; ublas_A(1, 1) = -5; ublas_A(1, 2) =  2;
  ublas_A(2, 0) = -3; ublas_A(2, 1) =  1; ublas_A(2, 2) = -4;
  ublas_A(3, 0) =  1; ublas_A(3, 1) = -1; ublas_A(3, 2) =  1;

  //
  // Setup the matrix in ViennaCL:
  //
  VCLVectorType vcl_b(ublas_b.size());
  VCLMatrixType vcl_A(ublas_A.size1(), ublas_A.size2());

  viennacl::copy(ublas_b, vcl_b);
  viennacl::copy(ublas_A, vcl_A);

  //////////// Part 1: Use Boost.uBLAS for all computations ////////////////

  std::cout << "--- Boost.uBLAS ---" << std::endl;
  std::vector<ScalarType> ublas_betas = viennacl::linalg::inplace_qr(ublas_A);  //computes the QR factorization

  // compute modified RHS of the minimization problem:
  // b' := Q^T b
  viennacl::linalg::inplace_qr_apply_trans_Q(ublas_A, ublas_betas, ublas_b);

  // Final step: triangular solve: Rx = b'', where b'' are the first three entries in b'
  // We only need the upper left square part of A, which defines the upper triangular matrix R
  boost::numeric::ublas::range ublas_range(0, 3);
  boost::numeric::ublas::matrix_range<MatrixType> ublas_R(ublas_A, ublas_range, ublas_range);
  boost::numeric::ublas::vector_range<VectorType> ublas_b2(ublas_b, ublas_range);
  boost::numeric::ublas::inplace_solve(ublas_R, ublas_b2, boost::numeric::ublas::upper_tag());

  std::cout << "Result: " << ublas_b2 << std::endl;

  //////////// Part 2: Use ViennaCL types for BLAS 3 computations, but use Boost.uBLAS for the panel factorization ////////////////

  std::cout << "--- ViennaCL (hybrid implementation)  ---" << std::endl;
  std::vector<ScalarType> hybrid_betas = viennacl::linalg::inplace_qr(vcl_A);

  // compute modified RHS of the minimization problem:
  // b := Q^T b
  viennacl::linalg::inplace_qr_apply_trans_Q(vcl_A, hybrid_betas, vcl_b);

  // Final step: triangular solve: Rx = b'.
  // We only need the upper part of A such that R is a square matrix
  viennacl::range vcl_range(0, 3);
  viennacl::matrix_range<VCLMatrixType> vcl_R(vcl_A, vcl_range, vcl_range);
  viennacl::vector_range<VCLVectorType> vcl_b2(vcl_b, vcl_range);
  viennacl::linalg::inplace_solve(vcl_R, vcl_b2, viennacl::linalg::upper_tag());

  std::cout << "Result: " << vcl_b2 << std::endl;

  //
  //  That's it.
  //
  std::cout << "!!!! TUTORIAL COMPLETED SUCCESSFULLY !!!!" << std::endl;

  return EXIT_SUCCESS;
}


text:
#include "TopNClusteringDB.h"
#include <am/range/AmIterator.h>
#include <boost/filesystem.hpp>

using namespace izenelib::am;
namespace sf1r { namespace laser {

TopNClusteringDB::TopNClusteringDB(const std::string& topNClusteringPath,
    const std::size_t& maxClustering)
    : topNClusteringPath_(topNClusteringPath)
    , maxClustering_(maxClustering)
{
    if (!boost::filesystem::exists(topNClusteringPath_))
    {
        boost::filesystem::create_directory(topNClusteringPath_);
    }
    load_();
}

TopNClusteringDB::~TopNClusteringDB()
{
    if (NULL != topNclusterLeveldb_)
    {
        topNclusterLeveldb_->close();
        delete topNclusterLeveldb_;
        topNclusterLeveldb_ = NULL;
    }
}

bool TopNClusteringDB::load_()
{
    topNclusterLeveldb_ = new TopNclusterLeveldbType(topNClusteringPath_);
    if(topNclusterLeveldb_->open())
    {
        return true;
    }
    else
    {
        topNclusterLeveldb_->close();
        delete topNclusterLeveldb_;
        topNclusterLeveldb_ = NULL;
        return false;
    }
}

bool TopNClusteringDB::update(const std::string& user, const std::map<int, float>& clustering)
{
    return topNclusterLeveldb_->insert(user, clustering);
}

bool TopNClusteringDB::get(const std::string& user, std::map<int, float>& clustering) const
{
    if (!topNclusterLeveldb_->get(user, clustering))
    {
        for (std::size_t i = 0; i < TOP_N; i++)
        {
            clustering[rand() % maxClustering_] = 1.0;
        }
    }
    return true;
}
} }


text:
#include <vector>

#include <NTL/ZZ.h>

#include "../src/elements/element.hpp"
#include "../src/algorithms/utils.hpp"

/* Example: using the remainder tree algorithm to search for Wilson primes.
 * This was the first application for the remainder tree algorithm and also is
 * one of the simplest. Wilson's theorem says that for all primes p, the following is true:
 *(p-1)! = -1 (mod p). A Wilson prime satisfies the same identity modulo p^2.
 *
 * Let A_0 = A_1 = 1, and A_n = n-1. Also set m_n to be n if n is prime, and 1 otherwise.
 * Then, if A_0 * A_1 * ... A_p = -1 (mod m_n), then m_n is a Wilson prime.
 */

using std::vector;

/* The first decision to make is what kind of datatype to use. In this case it is clear that we only
 * need to use integers. However, for many applications such as those in polynomial rings or if the
 * recurrence relation of the dividends is of order higher than 1, other datatypes may be desired.
 * Most of the code was written with using NTL in mind. However, we wrap every value in the type Elt.
 * Elt is a templated class object which will forward constructors, operators, etc. to its underlying type.
 * To specialize it for a new type (for example, to optimize its .mulmod() method), create a new file in
 * src/elements and then include it in elt_custom.tpp
 * I recommend specialized the methods rather than the class itself. Take a look at elt_NTL.tpp for an example.
 */
using NTL::ZZ;

//The convention here is to generate from lower bound---inclusive to upper---exclusive
vector<Elt<ZZ>> gen_n(long lower, long upper) {
    vector<Elt<ZZ>> output(upper-lower);

    for(long i = lower; i < upper; ++i) {
        if(i <= 1){
            output[i] = Elt<ZZ>(1);
        }
        else {
            output[i-lower] = Elt<ZZ> (i-1);
        }
    }
    return output;
}

vector<Elt<ZZ>> gen_second_prime_power(long lower, long upper) {
    vector<Elt<ZZ>> output(upper-lower);

    for(long i = lower; i < upper; i++){
        ZZ n(i);
        if(ProbPrime(n)) { //Technically a sieve is faster & more correct, but shouldn't make a big difference.
                            //This is just an example anyway.
            power(n, n, 2);
            output[i-lower] = Elt<ZZ>(n);
        }
        else{
            output[i-lower] = Elt<ZZ>(1);
        }
    }
    return output;
}

//TODO: explain how to modify calculate_factorial and compute V

max_stars_repo_name: adienes/remainder-tree

max_issues_repo_name: adienes/remainder-tree

max_forks_repo_name: adienes/remainder-tree


text:
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2015 Daniele Panozzo <daniele.panozzo@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "angles.h"
#include <Eigen/Geometry>
#include <cassert>

template <
  typename DerivedV,
  typename DerivedF,
  typename Derivedtheta>
void igl::angles(
  const Eigen::PlainObjectBase<DerivedV>& V,
  const Eigen::PlainObjectBase<DerivedF>& F,
  Eigen::PlainObjectBase<Derivedtheta>& theta)
{
  theta.resize(F.rows(),F.cols());

  auto corner = [](const Eigen::PlainObjectBase<DerivedV>& x, const Eigen::PlainObjectBase<DerivedV>& y, const Eigen::PlainObjectBase<DerivedV>& z)
  {
    Eigen::RowVector3d v1 = (x-y).normalized();
    Eigen::RowVector3d v2 = (z-y).normalized();

    // http://stackoverflow.com/questions/10133957/signed-angle-between-two-vectors-without-a-reference-plane
    double s = v1.cross(v2).norm();
    double c = v1.dot(v2);

    return atan2(s, c);
  };

  for(unsigned i=0; i<F.rows(); ++i)
  {
    for(unsigned j=0; j<F.cols(); ++j)
    {
      theta(i,j) = corner(
        V.row(F(i,int(j-1+F.cols())%F.cols())),
        V.row(F(i,j)),
        V.row(F(i,(j+1+F.cols())%F.cols()))
        );
    }
  }
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template specialization
template void igl::angles<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
#endif

max_stars_repo_name: Pentacode-IAFA/Quad-Remeshing

max_issues_repo_name: Pentacode-IAFA/Quad-Remeshing

max_forks_repo_name: Pentacode-IAFA/Quad-Remeshing


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

#include <pvkernel/rush/PVInputDescription.h> // for PVInputDescription_p, etc
#include <pvkernel/rush/PVInputType.h>        // for PVInputType::list_inputs
#include <pvkernel/rush/PVSourceDescription.h>

#include <boost/iterator/indirect_iterator.hpp> // for indirect_iterator, etc
#include <boost/iterator/iterator_facade.hpp>   // for operator!=

#include <QFile>
#include <QList>
#include <QString>

#include <algorithm> // for equal
#include <memory>    // for __shared_ptr

bool PVRush::PVSourceDescription::operator==(const PVSourceDescription& other) const
{
	// FIXME: PVSourceCreator and PVFormat should have their own operator==

	return _inputs.size() == other._inputs.size() && //!\\ compare lists size before applying
	                                                 // std::equal to avoid segfault !
	       std::equal(boost::make_indirect_iterator(_inputs.begin()),
	                  boost::make_indirect_iterator(_inputs.end()),
	                  boost::make_indirect_iterator(other._inputs.begin())) &&
	       _source_creator_p->registered_name() == other._source_creator_p->registered_name() &&
	       _format.get_full_path() == other._format.get_full_path();
}

max_stars_repo_name: inendi-inspector/inspector

max_issues_repo_name: inendi-inspector/inspector

max_forks_repo_name: inendi-inspector/inspector


text:
#define BOOST_TEST_DYN_LINK
#include <canard/net/ofp/v13/queue_property/min_rate.hpp>
#include <boost/test/unit_test.hpp>

#include <cstdint>
#include <vector>
#include <canard/net/ofp/v13/io/openflow.hpp>

namespace of = canard::net::ofp;
namespace v13 = of::v13;
namespace queue_props = v13::queue_properties;
namespace protocol = v13::protocol;

namespace {

auto operator ""_bin(char const* const str, std::size_t const size)
    -> std::vector<std::uint8_t>
{
    return std::vector<std::uint8_t>(str, str + size);
}

struct min_rate_fixture
{
    queue_props::min_rate sut{0x1234};
    std::vector<std::uint8_t> binary
        = "\x00\x01\x00\x10\x00\x00\x00\x00""\x12\x34\x00\x00\x00\x00\x00\x00"
          ""_bin
        ;
};

}

BOOST_AUTO_TEST_SUITE(queue_property_test)

BOOST_AUTO_TEST_SUITE(min_rate_test)

    BOOST_AUTO_TEST_CASE(construct_test)
    {
        auto const rate = std::uint16_t{34};

        auto const sut = queue_props::min_rate{rate};

        BOOST_TEST(sut.property() == protocol::OFPQT_MIN_RATE);
        BOOST_TEST(sut.length() == sizeof(protocol::ofp_queue_prop_min_rate));
        BOOST_TEST(sut.rate() == rate);
    }

    BOOST_AUTO_TEST_SUITE(equality)
      BOOST_AUTO_TEST_CASE(true_if_same_object)
      {
        auto const sut = queue_props::min_rate{1};

        BOOST_TEST((sut == sut));
      }
      BOOST_AUTO_TEST_CASE(true_if_rate_is_equal)
      {
        BOOST_TEST((queue_props::min_rate{2} == queue_props::min_rate{2}));
      }
      BOOST_AUTO_TEST_CASE(is_true_if_both_rate_are_not_configurable)
      {
        BOOST_TEST(
            (queue_props::min_rate{protocol::OFPQ_MIN_RATE_UNCFG}
          == queue_props::min_rate{protocol::OFPQ_MIN_RATE_UNCFG}));
      }
      BOOST_AUTO_TEST_CASE(false_if_rate_is_not_equal)
      {
        BOOST_TEST((queue_props::min_rate{3} != queue_props::min_rate{4}));
      }
      BOOST_AUTO_TEST_CASE(is_false_if_rate_is_not_equal_and_both_are_over_1000)
      {
        BOOST_TEST(
            (queue_props::min_rate{1001} != queue_props::min_rate{1002}));
      }
      BOOST_AUTO_TEST_CASE(is_false_if_both_rates_are_over_1000_but_one_is_uncfg)
      {
        BOOST_TEST(
            (queue_props::min_rate{1001}
          != queue_props::min_rate{protocol::OFPQ_MIN_RATE_UNCFG}));
      }
      BOOST_AUTO_TEST_CASE(is_false_if_lhs_rate_is_over_1000)
      {
        BOOST_TEST(
            (queue_props::min_rate{1000} != queue_props::min_rate{1001}));
      }
      BOOST_AUTO_TEST_CASE(is_false_if_rhs_rate_is_over_1000)
      {
        BOOST_TEST(
            (queue_props::min_rate{1001} != queue_props::min_rate{1000}));
      }
      BOOST_AUTO_TEST_CASE(false_if_pad_is_not_equal)
      {
        auto const binary
          = "\x00\x01\x00\x10\x00\x00\x00\x00""\x02\x34\x00\x00\x00\x00\x00\x01"
            ""_bin;
        auto it = binary.begin();
        auto const nonzero_pad
          = queue_props::min_rate::decode(it, binary.end());

        BOOST_TEST((queue_props::min_rate{0x234} != nonzero_pad));
      }
    BOOST_AUTO_TEST_SUITE_END() // equality

    BOOST_AUTO_TEST_SUITE(function_equivalent)
      BOOST_AUTO_TEST_CASE(true_if_same_object)
      {
        auto const sut = queue_props::min_rate{1};

        BOOST_TEST(equivalent(sut, sut));
      }
      BOOST_AUTO_TEST_CASE(true_if_rate_is_equal)
      {
        BOOST_TEST(
            equivalent(queue_props::min_rate{2}, queue_props::min_rate{2}));
      }
      BOOST_AUTO_TEST_CASE(is_true_if_both_rate_are_not_configurable)
      {
        BOOST_TEST(
            equivalent(
                queue_props::min_rate{protocol::OFPQ_MIN_RATE_UNCFG}
              , queue_props::min_rate{protocol::OFPQ_MIN_RATE_UNCFG}));
      }
      BOOST_AUTO_TEST_CASE(false_if_rate_is_not_equal)
      {
        BOOST_TEST(
            !equivalent(queue_props::min_rate{3}, queue_props::min_rate{4}));
      }
      BOOST_AUTO_TEST_CASE(is_true_if_rate_is_not_equal_but_both_are_over_1000)
      {
        BOOST_TEST(
            equivalent(
              queue_props::min_rate{1001}, queue_props::min_rate{1002}));
      }
      BOOST_AUTO_TEST_CASE(is_false_if_both_rates_are_over_1000_but_one_is_uncfg)
      {
        BOOST_TEST(
            !equivalent(
                queue_props::min_rate{1001}
              , queue_props::min_rate{protocol::OFPQ_MIN_RATE_UNCFG}));
      }
      BOOST_AUTO_TEST_CASE(is_false_if_lhs_rate_is_over_1000)
      {
        BOOST_TEST(
            !equivalent(
              queue_props::min_rate{1000}, queue_props::min_rate{1001}));
      }
      BOOST_AUTO_TEST_CASE(is_false_if_rhs_rate_is_over_1000)
      {
        BOOST_TEST(
            !equivalent(
              queue_props::min_rate{1001}, queue_props::min_rate{1000}));
      }
      BOOST_AUTO_TEST_CASE(true_if_pad_is_not_equal)
      {
        auto const binary
          = "\x00\x01\x00\x10\x00\x00\x00\x00""\x02\x34\x00\x00\x00\x00\x00\x01"
            ""_bin;
        auto it = binary.begin();
        auto const nonzero_pad
          = queue_props::min_rate::decode(it, binary.end());

        BOOST_TEST(equivalent(queue_props::min_rate{0x234}, nonzero_pad));
      }
    BOOST_AUTO_TEST_SUITE_END() // function_equivalent

    BOOST_FIXTURE_TEST_CASE(encode_test, min_rate_fixture)
    {
        auto buffer = std::vector<std::uint8_t>{};

        sut.encode(buffer);

        BOOST_TEST(buffer.size() == sut.length());
        BOOST_TEST(buffer == binary, boost::test_tools::per_element{});
    }

    BOOST_FIXTURE_TEST_CASE(decode_test, min_rate_fixture)
    {
        auto it = binary.begin();
        auto const it_end = binary.end();

        auto const min_rate = queue_props::min_rate::decode(it, it_end);

        BOOST_TEST((it == it_end));
        BOOST_TEST((min_rate == sut));
    }

BOOST_AUTO_TEST_SUITE_END() // min_rate_test

BOOST_AUTO_TEST_SUITE_END() // queue_property_test


text:
// Copyright (C) 2005, 2006 The Trustees of Indiana University.

// 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)

//  Authors: Douglas Gregor
//           Andrew Lumsdaine
#define PBGL_ACCOUNTING

#include <boost/graph/use_mpi.hpp>
#include <boost/config.hpp>
#include <boost/throw_exception.hpp>
#include <boost/graph/distributed/delta_stepping_shortest_paths.hpp>
#include <boost/graph/distributed/mpi_process_group.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/graph/parallel/distribution.hpp>
#include <boost/graph/erdos_renyi_generator.hpp>
#include <boost/graph/distributed/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/random.hpp>
#include <boost/test/minimal.hpp>
#include <boost/graph/iteration_macros.hpp>

#include <iostream>
#include <iomanip>

#ifdef BOOST_NO_EXCEPTIONS
void
boost::throw_exception(std::exception const& ex)
{
    std::cout << ex.what() << std::endl;
    abort();
}
#endif

/****************************************************************************
 * Timing                                                                   *
 ****************************************************************************/
typedef double time_type;

inline time_type get_time()
{
  return MPI_Wtime();
}

std::string print_time(time_type t)
{
  std::ostringstream out;
  out << std::setiosflags(std::ios::fixed) << std::setprecision(2) << t;
  return out.str();
}

/****************************************************************************
 * Edge weight generator iterator                                           *
 ****************************************************************************/
template<typename F, typename RandomGenerator>
class generator_iterator
{
public:
  typedef std::input_iterator_tag iterator_category;
  typedef typename F::result_type value_type;
  typedef const value_type&       reference;
  typedef const value_type*       pointer;
  typedef void                    difference_type;

  explicit
  generator_iterator(RandomGenerator& gen, const F& f = F())
    : f(f), gen(&gen)
  {
    value = this->f(gen);
  }

  reference operator*() const  { return value; }
  pointer   operator->() const { return &value; }

  generator_iterator& operator++()
  {
    value = f(*gen);
    return *this;
  }

  generator_iterator operator++(int)
  {
    generator_iterator temp(*this);
    ++(*this);
    return temp;
  }

  bool operator==(const generator_iterator& other) const
  { return f == other.f; }

  bool operator!=(const generator_iterator& other) const
  { return !(*this == other); }

private:
  F f;
  RandomGenerator* gen;
  value_type value;
};

template<typename F, typename RandomGenerator>
inline generator_iterator<F, RandomGenerator>
make_generator_iterator( RandomGenerator& gen, const F& f)
{ return generator_iterator<F, RandomGenerator>(gen, f); }

/****************************************************************************
 * Verification                                                             *
 ****************************************************************************/
template <typename Graph, typename DistanceMap, typename WeightMap>
void
verify_shortest_paths(const Graph& g, DistanceMap distance,
                      const WeightMap& weight) {

  distance.set_max_ghost_cells(0);

  BGL_FORALL_VERTICES_T(v, g, Graph) {
    BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
      get(distance, target(e, g));
    }
  }

  synchronize(process_group(g));

  BGL_FORALL_VERTICES_T(v, g, Graph) {
    BGL_FORALL_OUTEDGES_T(v, e, g, Graph) {
      assert(get(distance, target(e, g)) <=
             get(distance, source(e, g)) + get(weight, e));
    }
  }
}

using namespace boost;
using boost::graph::distributed::mpi_process_group;

typedef int weight_type;

struct WeightedEdge {
  WeightedEdge(weight_type weight = 0) : weight(weight) { }

  weight_type weight;

  template<typename Archiver>
  void serialize(Archiver& ar, const unsigned int /*version*/)
  {
    ar & weight;
  }
};

struct VertexProperties {
  VertexProperties(int d = 0)
    : distance(d) { }

  int distance;

  template<typename Archiver>
  void serialize(Archiver& ar, const unsigned int /*version*/)
  {
    ar & distance;
  }
};

void
test_distributed_shortest_paths(int n, double p, int c, int seed)
{
  typedef adjacency_list<listS,
                         distributedS<mpi_process_group, vecS>,
                         undirectedS,
                         VertexProperties,
                         WeightedEdge> Graph;

  typedef graph_traits<Graph>::vertex_descriptor vertex_descriptor;
  typedef graph_traits<Graph>::vertex_iterator vertex_iterator;
  typedef graph_traits<Graph>::vertices_size_type vertices_size_type;
  typedef property_map<Graph, vertex_index_t>::type vertex_index_map;

  // Build a random number generator
  minstd_rand gen;
  gen.seed(seed);

  // Build a random graph
  Graph g(erdos_renyi_iterator<minstd_rand, Graph>(gen, n, p),
          erdos_renyi_iterator<minstd_rand, Graph>(),
          make_generator_iterator(gen, uniform_int<int>(0, c)),
          n);

  uniform_int<vertices_size_type> rand_vertex(0, n);

  graph::distributed::delta_stepping_shortest_paths(g,
                                                    vertex(rand_vertex(gen), g),
                                                    dummy_property_map(),
                                                    get(&VertexProperties::distance, g),
                                                    get(&WeightedEdge::weight, g));

  verify_shortest_paths(g,
                        get(&VertexProperties::distance, g),
                        get(&WeightedEdge::weight, g));
}

int test_main(int argc, char* argv[])
{
  mpi::environment env(argc, argv);

  int n = 1000;
  double p = 0.01;
  int c = 100;
  int seed = 1;

  if (argc > 1) n             = lexical_cast<int>(argv[1]);
  if (argc > 2) p             = lexical_cast<double>(argv[2]);
  if (argc > 3) c             = lexical_cast<int>(argv[3]);
  if (argc > 4) seed          = lexical_cast<int>(argv[4]);

  test_distributed_shortest_paths(n, p, c, seed);

  return 0;
}

max_stars_repo_name: zyiacas/boost-doc-zh

max_issues_repo_name: sdfict/boost-doc-zh

max_forks_repo_name: sdfict/boost-doc-zh


text:
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2015-2015. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////

#include <boost/container/flat_map.hpp>
#include <boost/container/allocator.hpp>
#include "movable_int.hpp"
#include "dummy_test_allocator.hpp"
#include <boost/container/stable_vector.hpp>
#include <boost/container/small_vector.hpp>
#include <boost/container/deque.hpp>
#include <boost/container/static_vector.hpp>

struct empty
{
   friend bool operator == (const empty &, const empty &){ return true; }
   friend bool operator <  (const empty &, const empty &){ return true; }
};

template class ::boost::container::flat_map<empty, empty>;
template class ::boost::container::flat_multimap<empty, empty>;

volatile ::boost::container::flat_map<empty, empty> dummy;
volatile ::boost::container::flat_multimap<empty, empty> dummy2;

namespace boost {
namespace container {

//Explicit instantiation to detect compilation errors

//flat_map
typedef std::pair<test::movable_and_copyable_int, test::movable_and_copyable_int> test_pair_t;

template class flat_map
   < test::movable_and_copyable_int
   , test::movable_and_copyable_int
   , std::less<test::movable_and_copyable_int>
   , small_vector< test_pair_t, 10, std::allocator< test_pair_t > >
   >;

//flat_multimap
template class flat_multimap
   < test::movable_and_copyable_int
   , test::movable_and_copyable_int
   , std::less<test::movable_and_copyable_int>
   , stable_vector< test_pair_t, allocator< test_pair_t > >
   >;

template class flat_multimap
   < test::movable_and_copyable_int
   , test::movable_and_copyable_int
   , std::less<test::movable_and_copyable_int>
   , deque<test_pair_t, test::simple_allocator< test_pair_t > >
   >;

template class flat_multimap
   < test::movable_and_copyable_int
   , test::movable_and_copyable_int
   , std::less<test::movable_and_copyable_int>
   , static_vector<test_pair_t, 10 >
   >;

//As flat container iterators are typedefs for vector::[const_]iterator,
//no need to explicit instantiate them

}} //boost::container

#if (__cplusplus > 201103L)
#include <vector>

namespace boost{
namespace container{

template class flat_map
   < test::movable_and_copyable_int
   , test::movable_and_copyable_int
   , std::less<test::movable_and_copyable_int>
   , std::vector<test_pair_t>
>;

}} //boost::container

#endif

int main()
{
   return 0;
}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2012 Peter Caspers

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

/*! \file swaptionvolmatrix.hpp
    \brief Swaption matrix whith hull white smiles
*/

#ifndef quantlib_swaption_volatility_hullwhite_hpp
#define quantlib_swaption_volatility_hullwhite_hpp

#include <ql/termstructures/yieldtermstructure.hpp>
#include <ql/indexes/SwapIndex.hpp>
#include <ql/time/daycounters/actual360.hpp>
#include <ql/termstructures/volatility/swaption/swaptionvoldiscrete.hpp>
#include <ql/termstructures/volatility/swaption/swaptionvolstructure.hpp>
#include <ql/models/shortrate/calibrationhelpers/swaptionhelper.hpp>
#include <ql/models/shortrate/onefactormodels/hullwhite.hpp>
#include <ql/math/interpolations/interpolation2d.hpp>
#include <ql/math/matrix.hpp>
#include <ql/math/solvers1D/brent.hpp>
#include <ql/math/optimization/levenbergmarquardt.hpp>
#include <ql/math/optimization/simplex.hpp>
#include <ql/math/optimization/costfunction.hpp>
#include <ql/math/optimization/endcriteria.hpp>
#include <ql/math/optimization/problem.hpp>
#include <ql/termstructures/volatility/smilesection.hpp>
#include <ql/pricingengines/swaption/jamshidianswaptionengine.hpp>
#include <boost/noncopyable.hpp>
#include <vector>

#include <iostream>

#include <hullwhitesmilesection.hpp>

namespace QuantLib {

    class Quote;

    class SwaptionVolatilityHullWhite : public SwaptionVolatilityDiscrete,
                                     private boost::noncopyable {
      public:
        //! floating reference date, floating market data
        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,
                    const Calendar& calendar,
                    BusinessDayConvention bdc,
                    const std::vector<Period>& optionTenors,
                    const std::vector<Period>& swapTenors,
                    const std::vector<std::vector<Handle<Quote> > >& vols,
                    const DayCounter& dayCounter);
        //! fixed reference date, floating market data
        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,
                    const Date& referenceDate,
                    const Calendar& calendar,
                    BusinessDayConvention bdc,
                    const std::vector<Period>& optionTenors,
                    const std::vector<Period>& swapTenors,
                    const std::vector<std::vector<Handle<Quote> > >& vols,
                    const DayCounter& dayCounter);
        //! floating reference date, fixed market data
        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,
                    const Calendar& calendar,
                    BusinessDayConvention bdc,
                    const std::vector<Period>& optionTenors,
                    const std::vector<Period>& swapTenors,
                    const Matrix& volatilities,
                    const DayCounter& dayCounter);
        //! fixed reference date, fixed market data
        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,
                    const Date& referenceDate,
                    const Calendar& calendar,
                    BusinessDayConvention bdc,
                    const std::vector<Period>& optionTenors,
                    const std::vector<Period>& swapTenors,
                    const Matrix& volatilities,
                    const DayCounter& dayCounter);
        // fixed reference date and fixed market data, option dates
        SwaptionVolatilityHullWhite(const Real reversion, const Handle<YieldTermStructure>& yts, const boost::shared_ptr<SwapIndex> indexBase,
								 const Date& referenceDate,
                                 const std::vector<Date>& optionDates,
                                 const std::vector<Period>& swapTenors,
                                 const Matrix& volatilities,
                                 const DayCounter& dayCounter);
        //! \name LazyObject interface
        //@{
        void performCalculations() const;
        //@}
        //! \name TermStructure interface
        //@{
        Date maxDate() const;
        //@}
        //! \name VolatilityTermStructure interface
        //@{
        Rate minStrike() const;
        Rate maxStrike() const;
        //@}
        //! \name SwaptionVolatilityStructure interface
        //@{
        const Period& maxSwapTenor() const;
        //@}
        //! \name Other inspectors
        //@{
        //! returns the lower indexes of surrounding volatility matrix corners
        std::pair<Size,Size> locate(const Date& optionDate,
                                    const Period& swapTenor) const {
            return locate(timeFromReference(optionDate),
                          swapLength(swapTenor));
        }
        //! returns the lower indexes of surrounding volatility matrix corners
        std::pair<Size,Size> locate(Time optionTime,
                                    Time swapLength) const {
            return std::make_pair(interpolation_.locateY(optionTime),
                                  interpolation_.locateX(swapLength));
        }
        //@}
      protected:
        boost::shared_ptr<SmileSection> smileSectionImpl(const Date&,
                                                         const Period&) const;
        boost::shared_ptr<SmileSection> smileSectionImpl(Time,
                                                         Time) const;
        Volatility volatilityImpl(Time optionTime,
                                  Time swapLength,
                                  Rate strike) const;
		Volatility volatilityImpl(const Date& optionDate, const Period& swapTenor, Rate strike) const;

      private:
        void checkInputs(Size volRows,
                         Size volsColumns) const;
        void registerWithMarketData();
        std::vector<std::vector<Handle<Quote> > > volHandles_;
        mutable Matrix volatilities_;
        mutable Interpolation2D interpolation_;
		mutable Matrix hwsigmas_;
		mutable Interpolation2D interpolationSigma_;
		Real reversion_;
		Handle<YieldTermStructure> yts_;
		boost::shared_ptr<SwapIndex> indexBase_;

		struct calibrationFunction : CostFunction {

			calibrationFunction(boost::shared_ptr<CalibratedModel> model, boost::shared_ptr<SwaptionHelper> helper) : model_(model), helper_(helper) {}

			Real value(const Array& params0) const {
				Array params(2);
				params[0]=model_->params()[0];
				params[1]=params0[0]*params0[0];
				model_->setParams(params);
				Real error=helper_->calibrationError();
				return error;
			}

			Disposable<Array> values(const Array& params) const {
			   Array result(1);
			   result[0] = value(params);
			   return result;
			}

			boost::shared_ptr<CalibratedModel> model_;
			boost::shared_ptr<SwaptionHelper> helper_;
		};
	};

    // inline definitions

    inline Date SwaptionVolatilityHullWhite::maxDate() const {
        return optionDates_.back();
    }

    inline Rate SwaptionVolatilityHullWhite::minStrike() const {
        return QL_MIN_REAL;
    }

    inline Rate SwaptionVolatilityHullWhite::maxStrike() const {
        return QL_MAX_REAL;
    }

    inline const Period& SwaptionVolatilityHullWhite::maxSwapTenor() const {
        return swapTenors_.back();
    }

    inline Volatility SwaptionVolatilityHullWhite::volatilityImpl(Time optionTime,
                                                               Time swapLength,
                                                               Rate strike) const {
        calculate();
		return smileSection(optionTime,swapLength,true)->volatility(strike);
    }

	inline Volatility SwaptionVolatilityHullWhite::volatilityImpl(const Date& optionDate,
                                                const Period& swapTenor, Rate strike) const {
        calculate();
		return smileSection(optionDate,swapTenor,true)->volatility(strike);
    }

}

#endif

max_forks_repo_name: pcaspers/quantlib


text:
//==============================================================================
//         Copyright 2003 - 2012   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2012   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "nt2 arithmetic toolbox - touint/simd Mode"

//////////////////////////////////////////////////////////////////////////////
// unit test behavior of arithmetic components in simd mode
//////////////////////////////////////////////////////////////////////////////
/// created by jt the 04/12/2010
///
#include <nt2/arithmetic/include/functions/touint.hpp>
#include <boost/simd/sdk/simd/native.hpp>
#include <nt2/sdk/functor/meta/call.hpp>
#include <nt2/sdk/meta/as_integer.hpp>
#include <nt2/sdk/unit/tests.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/sdk/simd/io.hpp>
#include <nt2/include/constants/inf.hpp>
#include <nt2/include/constants/minf.hpp>
#include <nt2/include/constants/nan.hpp>
#include <nt2/include/constants/zero.hpp>
#include <nt2/include/constants/one.hpp>
#include <nt2/include/constants/mone.hpp>

NT2_TEST_CASE_TPL ( touint_real,  NT2_SIMD_REAL_TYPES)
{
  using nt2::touint;
  using nt2::tag::touint_;
  using boost::simd::native;
  typedef NT2_SIMD_DEFAULT_EXTENSION  ext_t;
  typedef native<T,ext_t>           vT;
  typedef typename nt2::meta::call<touint_(vT)>::type r_t;

  // specific values tests
  NT2_TEST_EQUAL(touint(nt2::One<vT>()), nt2::One<r_t>());
  NT2_TEST_EQUAL(touint(nt2::Zero<vT>()), nt2::Zero<r_t>());
} // end of test for floating_


text:
/**
  \file Hokuyo.hpp
  \brief Interface for connecting to the Hokuyo UTM-30LX Lidar.
  \author Jonathan Ulrich (jongulrich@gmail.com)
  \author Andrew Watson (watsontandrew@gmail.com)
  \date 2014
*/
#pragma once
#include "Point3D.hpp"
#include "Global.hpp"
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <urg_utils.h>
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <ctime>
#include <stdio.h>

namespace Pidar
{
    namespace Laser
    {
        /**
         * @brief The Callback class generates callbacks for subscribers of
         * laser data. Overload this class and corresponding functions to
         * receive appropriate laser data.
         */
        class Callback
        {
        public:
            typedef std::set<Callback*> Set;
            /**
             * @brief ProcessLaserData Invoked when new data becomes available
             * from the laser.
             * @param polarScan The captured scan in polar coordinates.
             * @param timestamp The time the scan was captured.
             */
            virtual void ProcessLaserData(const Point3D::List& polarScan,
                                          const long timeStamp) = 0;
        };
        /**
          \class Hokuyo
          \brief Hokuyo is an interface class used to wrap the urg helper
                 library available on sourceforge. It can connect to
                 Hokuyo LIDARS and generate callbacks for each scan.
        */
        /**
         * @brief The Hokuyo class is used to interface with Hokuyo LIDARs via
         * a USB nterface.
         */
        class Hokuyo
        {
        public:
            Hokuyo();
            ~Hokuyo();
            /**
             * @brief Initialize Starts a serial connection to a Hokuyo.
             * @returns True on success, false otherwise.
             */
            virtual bool Initialize();
            /**
             * @brief Shutdown Releases serial connection with the Hokuyo.
             */
            virtual void Shutdown();
            /**
             * @brief IsConnected
             * @returns True if connected, false otherwise.
             */
            virtual bool IsConnected() const { return mConnectedFlag; }
            /**
             * @brief StartCaptureThread
             * @returns True on start of Hokuyo IO thread, false otherwise.
             */
            virtual bool StartCaptureThread();
            /**
             * @brief StopCaptureThread Stops the serial IO thread.
             */
            virtual void StopCaptureThread();
            /**
             * @brief RegisterCallback
             * @param callback Callback to be registered.
             * @returns True on success, false otherwise.
             */
            virtual bool RegisterCallback(Callback* callback)
            {
                if(callback)
                {
                    mCallbacks.insert(callback);
                    return true;
                }
                return false;
            }
            /**
             * @brief RemoveCallback
             * @param callback Callback to be removed.
             * @returns True on success, false otherwise.
             */
            virtual bool RemoveCallback(Callback* callback)
            {
                if(callback)
                {
                    Callback::Set::iterator iter;
                    iter = mCallbacks.find(callback);
                    if(iter != mCallbacks.end())
                    {
                        mCallbacks.erase(callback);
                        return true;
                    }
                }
                return false;
            }
            /**
             * @brief ClearCallbacks
             */
            void ClearCallbacks() { mCallbacks.clear(); }
            /**
             * @brief GetErrorCount
             * @returns Number of read errors of serial data.
             */
            int GetErrorCount() { return mErrorCount; }

        protected:
            /**
             * @brief ProcessingThread Serial IO tread function.
             */
            virtual void ProcessingThread();

            bool mConnectedFlag;
            bool mProcessingThreadFlag;
            int mBaudRate;
            void* mpDevice;
            long* mpHokuyoScan;
            unsigned short* mpHokuyoScanIntensity;
            int mHokuyoMinStep;
            int mHokuyoMaxStep;
            volatile int mErrorCount;
            long mTimeStamp;
            long mTimeStampOffset;
            std::string mSerialPort;
            boost::mutex mMutex;
            boost::thread mProcessingThread;
            Point3D::List mLaserScan;
            Callback::Set mCallbacks;
        };
    }
}
/* End of File */


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

#include "main.h"
#include "base58.h"

using namespace std;

BOOST_AUTO_TEST_SUITE(SendFee_tests)

BOOST_AUTO_TEST_CASE(ThirdFee)
{
    const int nHeightCorrect = pindexBest->nHeight;
    pindexBest->nHeight = HEIGHT_PROTOCOL_V2 + 1;

    const CBitcoinAddress addressCorrect("CVBy4fjyzT2jHzqGaXDXiZSB8dfKa5dobx");
    const CTxDestination destinationAddressCorrect = addressCorrect.Get();
    CTxOut thirdFeeOutCorrect;
    thirdFeeOutCorrect.scriptPubKey.SetDestination(destinationAddressCorrect);
    thirdFeeOutCorrect.nValue = 833;

    const CBitcoinAddress addressIncorrect("CdbbsQGSVfjwz1kNXVWa5Peo6UQQbM2Fsq");
    const CTxDestination destinationAddressIncorrect = addressIncorrect.Get();
    CTxOut thirdFeeOutIncorrect;
    thirdFeeOutIncorrect.scriptPubKey.SetDestination(destinationAddressIncorrect);
    thirdFeeOutIncorrect.nValue = 834;

    int64_t fee = 2501;

    CTxOut thirdFeeOut = CTxOutForThirdFee(fee);

    //check CTxOutForThirdFee(const int64_t)
    BOOST_CHECK(thirdFeeOut.nValue == 833);
    BOOST_CHECK(thirdFeeOut.nValue != 834);

    BOOST_CHECK(thirdFeeOut.scriptPubKey == thirdFeeOutCorrect.scriptPubKey);
    BOOST_CHECK(thirdFeeOut.scriptPubKey != thirdFeeOutIncorrect.scriptPubKey);

    BOOST_CHECK(thirdFeeOut == thirdFeeOutCorrect);
    BOOST_CHECK(thirdFeeOut != thirdFeeOutIncorrect);

    CTransaction tx;
    tx.vout.push_back(thirdFeeOutIncorrect);
    tx.vout.push_back(thirdFeeOutIncorrect);

    //check ThirdFeeToOurAddress(CTransaction &, int64_t &)
    BOOST_CHECK(ThirdFeeToOurAddress(tx, fee));

    BOOST_CHECK(tx.vout.size() == 3);
    BOOST_CHECK(tx.vout.size() != 4);

    BOOST_CHECK(tx.vout.back() == thirdFeeOutCorrect);
    BOOST_CHECK(tx.vout.back() != thirdFeeOutIncorrect);

    BOOST_CHECK(fee == 1668);
    BOOST_CHECK(fee != 1669);

    //check ThirdFeeToOurAddressCheck(const CTransaction, const int64_t)
    BOOST_CHECK(!ThirdFeeToOurAddressCheck(tx, fee));

    fee = 2501;
    BOOST_CHECK(ThirdFeeToOurAddressCheck(tx, fee));

    tx.vout.pop_back();
    BOOST_CHECK(!ThirdFeeToOurAddressCheck(tx, fee));

    pindexBest->nHeight = nHeightCorrect;
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: cannonballdex/Centurion-Future

max_issues_repo_name: cannonballdex/Centurion-Future

max_forks_repo_name: cannonballdex/Centurion-Future


text:
//
// Created by Alex Chi on 2019-07-08.
//

#include <iostream>
#include <memory>
#include <ctime>
#include <cstdlib>
#include <queue>
#include <boost/log/trivial.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "Instance.h"

#include "raft.pb.h"
#include "raft.grpc.pb.h"

using boost::none;
using boost::property_tree::ptree;
using boost::property_tree::ptree_error;
using boost::property_tree::read_json;
using boost::property_tree::write_json;
using std::string;
using std::make_shared;
using std::dynamic_pointer_cast;
using std::priority_queue;

Instance::Instance(const string &id, shared_ptr<RPCClient> rpc) :
        role(FOLLOWER), voted_for(none), id(id), rpc(rpc),
        current_term(0), commit_index(-1), last_applied(-1),
        __debug_offline(false), membership_change_in_progress(false) {
    std::srand(std::time(nullptr));
}

void Instance::update() {
    if (role == FOLLOWER) {
        if (get_tick() - follower_begin > follower_timeout) {
            as_candidate();
        }
    } else if (role == CANDIDATE) {
        if (get_tick() - election_begin > election_timeout) {
            BOOST_LOG_TRIVIAL(info) << id << " election timeout";
            begin_election();
        }
    } else if (role == LEADER) {
        sync_log();
    }
}

TICK Instance::generate_timeout() {
    return std::rand() % 150 + 150;
}

void Instance::as_follower() {
    BOOST_LOG_TRIVIAL(info) << id << " become follower (term " << current_term << ")";
    role = FOLLOWER;
    follower_timeout = generate_timeout();
    follower_begin = get_tick();
    // TODO: not sure
    voted_for = none;
}

void Instance::start() {
    as_follower();
}

void Instance::as_candidate() {
    BOOST_LOG_TRIVIAL(info) << id << " become candidate (term " << current_term + 1 << ")";
    role = CANDIDATE;
    begin_election();
}

void Instance::begin_election() {
    election_begin = get_tick();
    election_timeout = generate_timeout();
    current_term++;
    voted_for.emplace(id);
    voted_for_self.clear();
    voted_for_self[id] = true;
    election_vote_cnt = 1;

    for (auto &&cluster : clusters) {
        auto req_vote = make_shared<RequestVoteRequest>();
        req_vote->set_term(current_term);
        req_vote->set_candidateid(id);
        req_vote->set_lastlogterm(logs.last_log_term());
        req_vote->set_lastlogindex(logs.last_log_index());
        rpc->send(cluster, req_vote);
    }
}

void Instance::set_clusters(const vector<Cluster> &clusters) {
    this->clusters = clusters;
    auto iter = std::find(this->clusters.begin(), this->clusters.end(), id);
    if (iter != this->clusters.end()) {
        this->clusters.erase(iter);
    }
    this->clusters_including_self = this->clusters;
    this->clusters_including_self.push_back(id);
}

unsigned Instance::cluster_size() {
    return clusters_including_self.size();
}

void Instance::on_rpc(const string &, shared_ptr<Message> message) {
    if (__debug_offline) return;
    auto message_term = get_term(message);
    auto message_from = get_from(message);
    if (!check_in_cluster(message_from)) return;
    if (message_term > current_term) {
        current_term = message_term;
        as_follower();
    }
    if (role == FOLLOWER) {
        follower_begin = get_tick();
        if (auto req_vote = dynamic_pointer_cast<RequestVoteRequest>(message)) {
            bool grant_vote = true;
            if (req_vote->term() < this->current_term) grant_vote = false;
                // not voted, or same candidate?
            else if (voted_for != none && *voted_for != req_vote->candidateid()) grant_vote = false;
                // at least as up-to-date?
            else if (req_vote->lastlogindex() < this->logs.last_log_index()) grant_vote = false;
            auto res_vote = make_shared<RequestVoteReply>();
            res_vote->set_term(current_term);
            res_vote->set_votegranted(grant_vote);
            res_vote->set_from(id);
            if (grant_vote) voted_for.emplace(req_vote->candidateid());
            rpc->send(req_vote->candidateid(), res_vote);
        } else if (auto req_app = dynamic_pointer_cast<AppendEntriesRequest>(message)) {
            bool succeed = true;
            Index lst_index = req_app->prevlogindex();
            if (req_app->term() < this->current_term) succeed = false;
                // log doesn't match
            else if (!logs.probe_log(req_app->prevlogindex(), req_app->prevlogterm())) succeed = false;
            else {
                for (Index next_idx = req_app->prevlogindex() + 1, cnt = 0;
                     cnt < req_app->entries_size(); cnt++, next_idx++) {
                    if (logs.exists(next_idx)) {
                        if (logs.logs[next_idx].first != req_app->term()) logs.purge(next_idx);
                    }
                    if (!logs.exists(next_idx)) {
                        auto entry = req_app->entries(cnt);
                        logs.append_log(make_pair(req_app->entries_term(cnt), entry));
                        try_membership_change(entry);
                    }
                }
                lst_index = logs.last_log_index();
                if (req_app->leadercommit() > commit_index) {
                    commit_index = req_app->leadercommit();
                    // TODO: apply to state machine
                }
            }
            auto res_app = make_shared<AppendEntriesReply>();
            res_app->set_term(current_term);
            res_app->set_success(succeed);
            res_app->set_lastagreedindex(std::min(lst_index, logs.last_log_index()));
            res_app->set_from(id);
            rpc->send(req_app->leaderid(), res_app);
        }
    } else if (role == CANDIDATE) {
        if (auto res_vote = dynamic_pointer_cast<RequestVoteReply>(message)) {
            if (res_vote->term() < current_term) return;
            if (res_vote->votegranted()) {
                auto from = res_vote->from();
                if (!voted_for_self[from]) {
                    voted_for_self[from] = true;
                    ++election_vote_cnt;
                    if (election_vote_cnt > cluster_size() / 2) {
                        as_leader();
                    }
                }
            }
        } else if (auto req_app = dynamic_pointer_cast<AppendEntriesRequest>(message)) {
            if (req_app->term() == current_term) {
                as_follower();
                // TODO: reply when fallback to follower
            } else {
                auto res_app = make_shared<AppendEntriesReply>();
                res_app->set_term(current_term);
                res_app->set_lastagreedindex(logs.last_log_index());
                res_app->set_success(false);
                res_app->set_from(id);
                rpc->send(req_app->leaderid(), res_app);
            }
        }
    } else if (role == LEADER) {
        if (auto res_app = dynamic_pointer_cast<AppendEntriesReply>(message)) {
            if (res_app->success()) {
                match_index[res_app->from()] = res_app->lastagreedindex();
                next_index[res_app->from()] = res_app->lastagreedindex() + 1;
            } else {
                next_index[res_app->from()] = std::max((Index) res_app->lastagreedindex(), (Index) 0);
            }
            priority_queue<Index> match_index_heap;
            for (auto &&kv : match_index) {
                auto idx = kv.second;
                if (logs.exists(idx) && logs.logs[idx].first == current_term) match_index_heap.push(idx);
            }
            for (int i = 0; i < cluster_size() / 2; i++) {
                if (!match_index_heap.empty()) match_index_heap.pop(); else break;
            }
            if (!match_index_heap.empty()) commit_index = std::max(match_index_heap.top(), commit_index);
        }
    }
}

Term Instance::get_term(shared_ptr<Message> message) {
    if (auto req_vote = dynamic_pointer_cast<RequestVoteRequest>(message)) return req_vote->term();
    else if (auto res_vote = dynamic_pointer_cast<RequestVoteReply>(message)) return res_vote->term();
    else if (auto req_app = dynamic_pointer_cast<AppendEntriesRequest>(message)) return req_app->term();
    else if (auto res_app = dynamic_pointer_cast<AppendEntriesReply>(message)) return res_app->term();
    assert(false);
    return -1;
}

void Instance::as_leader() {
    BOOST_LOG_TRIVIAL(info) << id << " become leader in clusters (term " << current_term << ") of " << clusters_including_self.size();
    role = LEADER;
    next_index.clear();
    match_index.clear();
    for (auto &&cluster : clusters) {
        next_index[cluster] = logs.last_log_index() + 1;
        match_index[cluster] = -1;
    }
    sync_log();
}

void Instance::sync_log() {
    for (auto &&cluster : clusters) {
        auto req_app = make_shared<AppendEntriesRequest>();
        req_app->set_term(current_term);
        req_app->set_leaderid(id);
        auto log_idx = next_index[cluster] - 1;
        auto next_idx = next_index[cluster];
        req_app->set_prevlogindex(log_idx);
        req_app->set_prevlogterm(log_idx == -1 ? 0 : logs.logs[log_idx].first);

        for (int cnt = 0; cnt < MAX_LOG_TRANSFER && next_idx < logs.logs.size(); cnt++, next_idx++) {
            req_app->add_entries_term(logs.logs[next_idx].first);
            req_app->add_entries(logs.logs[next_idx].second);
        }

        req_app->set_leadercommit(commit_index);
        rpc->send(cluster, req_app);
    }
}

void Instance::append_entry(const string &entry) {
    logs.append_log(make_pair(current_term, entry));
    try_membership_change(entry);
}

string Instance::get_role_string() {
    if (role == LEADER) return "leader";
    if (role == CANDIDATE) return "candidate";
    if (role == FOLLOWER) return "follower";
    return "";
}

void Instance::try_membership_change(const string &entry) {
    if (entry.length() <= 1) return;
    if (entry[0] != '{') return;
    try {
        ptree pt;
        std::stringstream ss(entry);
        read_json(ss, pt);
        if (pt.get<string>("type") == "membership_change") {
            auto clusters = pt.get_child("clusters");
            std::map<string, string> rpc_clusters;
            std::vector<Cluster> known_nodes;
            for (auto &v : clusters) {
                rpc_clusters[v.first] = v.second.get_value<string>();
                known_nodes.push_back(v.first);
            }
            rpc->update_clusters(rpc_clusters);
            set_clusters(known_nodes);
            membership_change_in_progress = true;
        }
    } catch (...) { return; }
}

void Instance::resolve_membership_change() {
    membership_change_in_progress = false;
}

bool Instance::check_in_cluster(const Cluster &c) {
    return std::find(clusters.begin(), clusters.end(), c) != clusters.end();
}

string Instance::get_from(shared_ptr<Message> message) {
    if (auto req_vote = dynamic_pointer_cast<RequestVoteRequest>(message)) return req_vote->candidateid();
    else if (auto res_vote = dynamic_pointer_cast<RequestVoteReply>(message)) return res_vote->from();
    else if (auto req_app = dynamic_pointer_cast<AppendEntriesRequest>(message)) return req_app->leaderid();
    else if (auto res_app = dynamic_pointer_cast<AppendEntriesReply>(message)) return res_app->from();
    assert(false);
    return "";
}

max_stars_repo_name: iskyzh/raft

max_issues_repo_name: skyzh/raft

max_forks_repo_name: skyzh/raft