text:
///////////////////////////////////////////////////////////////////////////////
// orientation_tests.cpp
//
//  Copyright 2021 Brandon Kohn. 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 <gtest/gtest.h>
#include <gmock/gmock.h>
#include "./2d_kernel_fixture.hpp"
#include "./3d_kernel_fixture.hpp"
#include "./3d_kernel_units_fixture.hpp"

#include <geometrix/algorithm/orientation.hpp>
#include <geometrix/algorithm/distance/point_line_distance.hpp>

#include <geometrix/utility/utilities.hpp>
#include <geometrix/utility/scope_timer.ipp>

#include <boost/range/adaptor/transformed.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/algorithm_ext/erase.hpp>

#include <exception>
#include <iostream>

//! Google tests
TEST_F(geometry_kernel_2d_fixture, point_line_orientation_point_is_right_and_far_returns_right)
{
    using namespace geometrix;

    auto p1 = point2 { 0., 0. };
    auto p2 = point2 { 4., 4. };
    auto l = make_line(p1, p2);
    auto seg = make_segment(p1, p2);
    auto p = point2 { 1.0, 0.0 };
    auto r = point_line_distance(p, l) - 0.1;
    auto c = circle2 { p, r };
    auto o = circle_line_orientation(c, l, cmp);

    EXPECT_EQ(o, oriented_right);
}

TEST_F(geometry_kernel_2d_fixture, point_line_orientation_point_is_left_and_far_returns_left)
{
    using namespace geometrix;

    auto p1 = point2 { 0., 0. };
    auto p2 = point2 { 4., 4. };
    auto l = make_line(p1, p2);
    auto seg = make_segment(p1, p2);
    auto p = point2 { 1.0, 1.5 };
    auto r = point_line_distance(p, l) - 0.1;
    auto c = circle2 { p, r };
    auto o = circle_line_orientation(c, l, cmp);

    EXPECT_EQ(o, oriented_left);
}

TEST_F(geometry_kernel_2d_fixture, point_line_orientation_point_is_right_and_near_returns_collinear)
{
    using namespace geometrix;

    auto p1 = point2 { 0., 0. };
    auto p2 = point2 { 4., 4. };
    auto l = make_line(p1, p2);
    auto seg = make_segment(p1, p2);
    auto p = point2 { 1.0, 0.0 };
    auto r = point_line_distance(p, l) + 0.1;
    auto c = circle2 { p, r };
    auto o = circle_line_orientation(c, l, cmp);

    EXPECT_EQ(o, oriented_collinear);
}

#include <geometrix/algorithm/orientation.hpp>

TEST_F(geometry_kernel_2d_fixture, circle_polyline_orientation_corner_test_point_right)
{
    using namespace geometrix;
    auto pline = polyline2 { { 0.0, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } };
    point2 p = pline[2] + 1.0 * normalize(vector2 { 1.0, 1.0 });
    auto r = 0.5;
    auto c = circle2 { p, r };
    auto result = circle_polyline_orientation(c, pline, cmp);
    EXPECT_EQ(result, oriented_right);
}

TEST_F(geometry_kernel_2d_fixture, circle_polyline_orientation_corner_test_point_overlaps_collinear)
{
    using namespace geometrix;
    auto pline = polyline2 { { 0.0, 0.0 }, { 1.0, 0.0 }, { 1.0, 1.0 }, { 0.0, 1.0 } };
    point2 p = pline[2] + 1.0 * normalize(vector2 { 1.0, 1.0 });
    auto r = 1.5;
    auto c = circle2 { p, r };
    auto result = circle_polyline_orientation(c, pline, cmp);
    EXPECT_EQ(result, oriented_collinear);
}

TEST_F(geometry_kernel_2d_fixture, point_segment_orientation_point_is_right)
{
    using namespace geometrix;
    auto seg = segment2{ { 0.0, 0.0 }, { 4.0, 4.0 } };
    auto p = point2{ 1.0, 0.0 };
    auto result = point_segment_orientation(p, seg, cmp);
    auto result2 = point_segment_orientation(p, seg.get_start(), seg.get_end(), cmp);
    EXPECT_EQ(result, oriented_right);
    EXPECT_EQ(result2, oriented_right);
}

TEST_F(geometry_kernel_2d_fixture, point_segment_orientation_point_is_left)
{
    using namespace geometrix;
    auto seg = segment2{ { 0.0, 0.0 }, { 4.0, 4.0 } };
    auto p = point2{ 1.0, 2.0 };
    auto result = point_segment_orientation(p, seg, cmp);
    auto result2 = point_segment_orientation(p, seg.get_start(), seg.get_end(), cmp);
    EXPECT_EQ(result, oriented_left);
    EXPECT_EQ(result2, oriented_left);
}

TEST_F(geometry_kernel_2d_fixture, point_segment_orientation_point_is_collinear)
{
    using namespace geometrix;
    auto seg = segment2{ { 0.0, 0.0 }, { 4.0, 4.0 } };
    auto p = point2{ 1.0, 1.0 };
    auto result = point_segment_orientation(p, seg, cmp);
    auto result2 = point_segment_orientation(p, seg.get_start(), seg.get_end(), cmp);
    EXPECT_EQ(result, oriented_collinear);
    EXPECT_EQ(result2, oriented_collinear);
}

TEST_F(geometry_kernel_3d_fixture, collinear_test_3d_points_true)
{
    using namespace geometrix;
	auto a = point3{ 0.0, 0.0, 0.0 };
	auto b = point3{ 1.0, 1.0, 1.0 };
	auto c = point3{ 2.0, 2.0, 2.0 };

    auto o = is_collinear( c, a, b, cmp );
	EXPECT_TRUE( o );
}

TEST_F(geometry_kernel_3d_fixture, collinear_test_3d_points_false)
{
    using namespace geometrix;
	auto a = point3{ 0.0, 0.0, 0.0 };
	auto b = point3{ 1.0, 1.0, 1.0 };
	auto c = point3{ 2.0, 2.0, 0.0 };

    auto o = is_collinear( c, a, b, cmp );
	EXPECT_FALSE( o );
}

TEST_F(geometry_kernel_3d_units_fixture, collinear_test_3d_points_false)
{
    using namespace geometrix;
	auto a = point3{ 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };
	auto b = point3{ 1.0 * boost::units::si::meters, 1.0 * boost::units::si::meters, 1.0 * boost::units::si::meters };
	auto c = point3{ 2.0 * boost::units::si::meters, 2.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };

    auto o = is_collinear( c, a, b, cmp );
	EXPECT_FALSE( o );
}

TEST_F(geometry_kernel_3d_units_fixture, collinear_test_3d_points_true_all_same)
{
    using namespace geometrix;
	auto a = point3{ 1.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };
	auto b = point3{ 1.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };
	auto c = point3{ 1.0 * boost::units::si::meters, 0.0 * boost::units::si::meters, 0.0 * boost::units::si::meters };

    auto o = is_collinear( c, a, b, cmp );
	EXPECT_TRUE( o );
}

max_stars_repo_name: brandon-kohn/Geometrix

max_issues_repo_name: brandon-kohn/Geometrix

max_forks_repo_name: brandon-kohn/Geometrix


text:
/* Copyright 2017 Joaquin M Lopez Munoz.
 * 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/poly_collection for library home page.
 */

#ifndef BOOST_POLY_COLLECTION_DETAIL_WORKAROUND_DR1467_HPP
#define BOOST_POLY_COLLECTION_DETAIL_WORKAROUND_DR1467_HPP

#if defined(_MSC_VER)
#pragma once
#endif

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

#if BOOST_WORKAROUND(BOOST_GCC_VERSION,<50000)||\
    defined(BOOST_CLANG)&&\
      (__clang_major__<3||(__clang_major__==3&&__clang_minor__<=6))
/* Defect report 1467 denounces that for aggregate types an intended {}-style
 * copy construction will be mistaken for aggregate initialization:
 *   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1467
 *
 * A solution is to define a default constructor for the offending class so
 * that it is no longer an aggregate.
 */

#define BOOST_POLY_COLLECTION_WORKAROUND_DR1467(name) name(){}
#else
#define BOOST_POLY_COLLECTION_WORKAROUND_DR1467(name)
#endif

#endif

ext: hpp

max_stars_repo_name: SnailTowardThesun/face-detect

max_issues_repo_name: SnailTowardThesun/face-detect

max_forks_repo_name: gradinkov/nheqminer-gradinkov


text:
/*
   Copyright (c) Marshall Clow 2008-2012.

   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)

 Revision history:
   27 June 2009 mtc First version
   23 Oct  2010 mtc Added predicate version

*/

/// \file clamp.hpp
/// \brief Clamp algorithm
/// \author Marshall Clow
///
/// Suggested by olafvdspek in https://svn.boost.org/trac/boost/ticket/3215

#ifndef BOOST_ALGORITHM_CLAMP_HPP
#define BOOST_ALGORITHM_CLAMP_HPP

#include <functional>       //  For std::less
#include <iterator>         //  For std::iterator_traits
#include <cassert>

#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/mpl/identity.hpp>      // for identity
#include <boost/utility/enable_if.hpp> // for boost::disable_if

namespace boost { namespace algorithm {

/// \fn clamp ( T const& val,
///               typename boost::mpl::identity<T>::type const & lo,
///               typename boost::mpl::identity<T>::type const & hi, Pred p )
/// \return the value "val" brought into the range [ lo, hi ]
///     using the comparison predicate p.
///     If p ( val, lo ) return lo.
///     If p ( hi, val ) return hi.
///     Otherwise, return the original value.
///
/// \param val   The value to be clamped
/// \param lo    The lower bound of the range to be clamped to
/// \param hi    The upper bound of the range to be clamped to
/// \param p     A predicate to use to compare the values.
///                 p ( a, b ) returns a boolean.
///
  template<typename T, typename Pred>
  BOOST_CXX14_CONSTEXPR T const & clamp ( T const& val,
    typename boost::mpl::identity<T>::type const & lo,
    typename boost::mpl::identity<T>::type const & hi, Pred p )
  {
//    assert ( !p ( hi, lo ));    // Can't assert p ( lo, hi ) b/c they might be equal
    return p ( val, lo ) ? lo : p ( hi, val ) ? hi : val;
  }

/// \fn clamp ( T const& val,
///               typename boost::mpl::identity<T>::type const & lo,
///               typename boost::mpl::identity<T>::type const & hi )
/// \return the value "val" brought into the range [ lo, hi ].
///     If the value is less than lo, return lo.
///     If the value is greater than "hi", return hi.
///     Otherwise, return the original value.
///
/// \param val   The value to be clamped
/// \param lo    The lower bound of the range to be clamped to
/// \param hi    The upper bound of the range to be clamped to
///
  template<typename T>
  BOOST_CXX14_CONSTEXPR T const& clamp ( const T& val,
    typename boost::mpl::identity<T>::type const & lo,
    typename boost::mpl::identity<T>::type const & hi )
  {
    return boost::algorithm::clamp ( val, lo, hi, std::less<T>());
  }

/// \fn clamp_range ( InputIterator first, InputIterator last, OutputIterator out,
///       std::iterator_traits<InputIterator>::value_type const & lo,
///       std::iterator_traits<InputIterator>::value_type const & hi )
/// \return clamp the sequence of values [first, last) into [ lo, hi ]
///
/// \param first The start of the range of values
/// \param last  One past the end of the range of input values
/// \param out   An output iterator to write the clamped values into
/// \param lo    The lower bound of the range to be clamped to
/// \param hi    The upper bound of the range to be clamped to
///
  template<typename InputIterator, typename OutputIterator>
  BOOST_CXX14_CONSTEXPR OutputIterator clamp_range ( InputIterator first, InputIterator last, OutputIterator out,
    typename std::iterator_traits<InputIterator>::value_type const & lo,
    typename std::iterator_traits<InputIterator>::value_type const & hi )
  {
  // this could also be written with bind and std::transform
    while ( first != last )
        *out++ = boost::algorithm::clamp ( *first++, lo, hi );
    return out;
  }

/// \fn clamp_range ( const Range &r, OutputIterator out,
///       typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & lo,
///       typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & hi )
/// \return clamp the sequence of values [first, last) into [ lo, hi ]
///
/// \param r     The range of values to be clamped
/// \param out   An output iterator to write the clamped values into
/// \param lo    The lower bound of the range to be clamped to
/// \param hi    The upper bound of the range to be clamped to
///
  template<typename Range, typename OutputIterator>
  BOOST_CXX14_CONSTEXPR typename boost::disable_if_c<boost::is_same<Range, OutputIterator>::value, OutputIterator>::type
  clamp_range ( const Range &r, OutputIterator out,
    typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & lo,
    typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & hi )
  {
    return boost::algorithm::clamp_range ( boost::begin ( r ), boost::end ( r ), out, lo, hi );
  }

/// \fn clamp_range ( InputIterator first, InputIterator last, OutputIterator out,
///       std::iterator_traits<InputIterator>::value_type const & lo,
///       std::iterator_traits<InputIterator>::value_type const & hi, Pred p )
/// \return clamp the sequence of values [first, last) into [ lo, hi ]
///     using the comparison predicate p.
///
/// \param first The start of the range of values
/// \param last  One past the end of the range of input values
/// \param out   An output iterator to write the clamped values into
/// \param lo    The lower bound of the range to be clamped to
/// \param hi    The upper bound of the range to be clamped to
/// \param p     A predicate to use to compare the values.
///                 p ( a, b ) returns a boolean.

///
  template<typename InputIterator, typename OutputIterator, typename Pred>
  BOOST_CXX14_CONSTEXPR OutputIterator clamp_range ( InputIterator first, InputIterator last, OutputIterator out,
    typename std::iterator_traits<InputIterator>::value_type const & lo,
    typename std::iterator_traits<InputIterator>::value_type const & hi, Pred p )
  {
  // this could also be written with bind and std::transform
    while ( first != last )
        *out++ = boost::algorithm::clamp ( *first++, lo, hi, p );
    return out;
  }

/// \fn clamp_range ( const Range &r, OutputIterator out,
///       typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & lo,
///       typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & hi,
///       Pred p )
/// \return clamp the sequence of values [first, last) into [ lo, hi ]
///     using the comparison predicate p.
///
/// \param r     The range of values to be clamped
/// \param out   An output iterator to write the clamped values into
/// \param lo    The lower bound of the range to be clamped to
/// \param hi    The upper bound of the range to be clamped to
/// \param p     A predicate to use to compare the values.
///                 p ( a, b ) returns a boolean.
//
//  Disable this template if the first two parameters are the same type;
//  In that case, the user will get the two iterator version.
  template<typename Range, typename OutputIterator, typename Pred>
  BOOST_CXX14_CONSTEXPR typename boost::disable_if_c<boost::is_same<Range, OutputIterator>::value, OutputIterator>::type
  clamp_range ( const Range &r, OutputIterator out,
    typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & lo,
    typename std::iterator_traits<typename boost::range_iterator<const Range>::type>::value_type const & hi,
    Pred p )
  {
    return boost::algorithm::clamp_range ( boost::begin ( r ), boost::end ( r ), out, lo, hi, p );
  }

}}

#endif // BOOST_ALGORITHM_CLAMP_HPP


text:
// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/ext/boost/mpl/integral_c.hpp>

#include <boost/hana/core/tag_of.hpp>

#include <boost/mpl/bool.hpp>
#include <boost/mpl/char.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/integral_c.hpp>
#include <boost/mpl/long.hpp>
#include <boost/mpl/size_t.hpp>

#include <cstddef>
#include <type_traits>
namespace hana = boost::hana;
namespace mpl = boost::mpl;

static_assert(std::is_same<
    hana::tag_of_t<mpl::bool_<true>>,
    hana::ext::boost::mpl::integral_c_tag<bool>
>::value, "");

static_assert(std::is_same<
    hana::tag_of_t<mpl::int_<0>>,
    hana::ext::boost::mpl::integral_c_tag<int>
>::value, "");

static_assert(std::is_same<
    hana::tag_of_t<mpl::long_<0>>,
    hana::ext::boost::mpl::integral_c_tag<long>
>::value, "");

static_assert(std::is_same<
    hana::tag_of_t<mpl::size_t<0>>,
    hana::ext::boost::mpl::integral_c_tag<std::size_t>
>::value, "");

static_assert(std::is_same<
    hana::tag_of_t<mpl::integral_c<int, 0>>,
    hana::ext::boost::mpl::integral_c_tag<int>
>::value, "");

static_assert(std::is_same<
    hana::tag_of_t<mpl::char_<0>>,
    hana::ext::boost::mpl::integral_c_tag<char>
>::value, "");

int main() { }

ext: cpp


text:
/*
 * Read and decode CANFRAME.
 * Benjamin
*/

#include <functional>
#include <iostream>
#include <iomanip>
#include <unistd.h>
#include <spdlog/spdlog.h>
#include <boost/program_options.hpp>
namespace po = boost::program_options;

#include "SimpleSocketCan.h"
#include "DBSparser.h"
// simple sec to usec convertor
using namespace tutil;

int main(int ac, char* av[]) {
	spdlog::info("Start CANread script\n");

	// Parse input
	std::string canbus;
	std::string dbs_path;
	po::options_description desc("Options");
	desc.add_options()
		("help", "run with CANread -canbus vcan0")
		("canbus,c", po::value<std::string>(&canbus), "path to socket")
		("dbs", po::value(&dbs_path), "path to dbs file");
	po::variables_map vm;
	po::store(po::parse_command_line(ac, av, desc), vm);
	po::notify(vm);

	if(vm.count("help")) {
		std::cout << desc << "\n";
		exit(0);
	}

	if(dbs_path.length() < 1) {
		spdlog::warn("No .dbs file specified.");
		std::cout << desc << "\n";
		exit(1);
	}

	if(canbus.length() < 1) {
		spdlog::warn("No canbus specified, using vcan0");
		canbus.clear();
		canbus = "vcan0";
	}
	spdlog::info("Opening CANBUS: {}", canbus);

	// Generate socket
	ssc::SimpleSocketCan vcan0;
	auto status = vcan0.open(canbus);
	if (status != ssc::SocketCanStatus::STATUS_OK) {
		spdlog::error("Error while opening the socket: {}", status);
	}

	// Load dbsfile:
	ssc::DBSParser dbsparser;
  dbsparser.load(dbs_path);

	// Generate and send message.
	ssc::sscan_frame read_frame;
	while(true) {
		auto status_read = vcan0.read(read_frame);
		if (status_read != ssc::SocketCanStatus::STATUS_OK) {
			spdlog::error("Error while reading socket.");
		}

		// Print out the frame content.
		std::cout << std::hex << std::setfill('0');
		spdlog::info("Received: frame {} | {}:",read_frame.can_id, read_frame.can_dlc);
		for(auto i=0; i<read_frame.can_dlc;i++) {
			std::cout << std::setw(2) << read_frame.data[i] << " ";
		}
		std::cout << std::endl;

		// Decode data:
		auto decode_status = dbsparser.decode(read_frame);
	}

}

max_stars_repo_name: BenbenIO/LearningAboutCan

max_issues_repo_name: BenbenIO/LearningAboutCan

max_forks_repo_name: BenbenIO/LearningAboutCan


text:
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <boost/format.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>
#include <boost/iostreams/copy.hpp>

int main(int argc, char *argv[]){
    if(argc!=3){
        std::cout << "Correct format is \"toASCII inputFile outputFile\"";
        return -1;
    }

    std::ifstream infile(argv[1], std::ios_base::binary);
    boost::iostreams::filtering_streambuf<boost::iostreams::input> inbuf;
    inbuf.push(boost::iostreams::zlib_decompressor());
    inbuf.push(infile);
    std::stringstream decompressed;

    boost::iostreams::copy(inbuf,decompressed);

    std::ofstream outFile (argv[2], std::ios::out);

    double bufferD;
    int bufferInt;

    decompressed.read((char*) &bufferInt, sizeof(int));
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<"env_min "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD<<"\n";

    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<"env_max "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD<<"\n";

    decompressed.read((char*) &bufferInt, sizeof(int));
    outFile<<"NumCells_XYZ "<<bufferInt;
    int cells_x=bufferInt;
    decompressed.read((char*) &bufferInt, sizeof(int));
    outFile<<" "<<bufferInt;
    int cells_y=bufferInt;
    decompressed.read((char*) &bufferInt, sizeof(int));
    outFile<<" "<<bufferInt<<"\n";
    int cells_z=bufferInt;

    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<"CellSizes_XYZ "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD<<"\n";

    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<"GasSourceLocation_XYZ "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD;
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<" "<<bufferD<<"\n";

    decompressed.read((char*) &bufferInt, sizeof(int));
    outFile<<"GasType "<<bufferInt<<"\n";

    outFile<<"Number of moles per filament ";
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<bufferD<<"\nMoles of all gases in cm3 ";
    decompressed.read((char*) &bufferD, sizeof(double));
    outFile<<bufferD<<"\n";

    decompressed.read((char*) &bufferInt, sizeof(int));
    outFile<<bufferInt<<"\n";

    while(decompressed.peek()!=EOF){

        decompressed.read((char*) &bufferInt, sizeof(int));
        outFile<<bufferInt<<" ";
        decompressed.read((char*) &bufferD, sizeof(double));
        outFile<<bufferD<<" ";
        decompressed.read((char*) &bufferD, sizeof(double));
        outFile<<bufferD<<" ";
        decompressed.read((char*) &bufferD, sizeof(double));
        outFile<<bufferD<<" ";
        decompressed.read((char*) &bufferD, sizeof(double));
        outFile<<bufferD<<"\n";

    }

    outFile.close();
    return 0;
}


text:
// Copyright 2009-2010 Jeroen Habraken.
// Copyright 2009-2013 Dean Michael Berris, Glyn Matthews.
// Copyright 2012 Google, Inc.
// 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 NETWORK_URI_INC
#define NETWORK_URI_INC

/**
 * \file
 * \brief Contains the uri the class.
 */

#include <iterator>
#include <algorithm>
#include <functional>
#include <boost/lexical_cast.hpp>
#include <boost/utility/string_ref.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/optional.hpp>
#include <network/uri/config.hpp>
#include <network/uri/uri_errors.hpp>
#include <network/uri/detail/encode.hpp>
#include <network/uri/detail/decode.hpp>
#include <network/uri/detail/translate.hpp>

namespace network {
#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
  namespace detail {
    template <class FwdIter>
    struct hierarchical_part {
      boost::optional<boost::iterator_range<FwdIter> > user_info;
      boost::optional<boost::iterator_range<FwdIter> > host;
      boost::optional<boost::iterator_range<FwdIter> > port;
      boost::optional<boost::iterator_range<FwdIter> > path;
    };

    template <class FwdIter>
    struct uri_parts {
      boost::optional<boost::iterator_range<FwdIter> > scheme;
      hierarchical_part<FwdIter> hier_part;
      boost::optional<boost::iterator_range<FwdIter> > query;
      boost::optional<boost::iterator_range<FwdIter> > fragment;
    };
  }  // namespace detail
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)

  /**
   * \enum uri_comparison_level
   * \brief Defines the steps on the URI comparison ladder.
   */
  enum class uri_comparison_level {
    string_comparison,
    syntax_based,
    scheme_based,
  };

  /**
   * \ingroup uri
   * \class uri_builder network/uri/uri_builder.hpp network/uri.hpp
   * \brief A class that allows complex uri objects to be constructed.
   * \sa uri
   */
  class uri_builder;

  /**
   * \ingroup uri
   * \class uri network/uri/uri.hpp network/uri.hpp
   * \brief A class that parses a URI (Uniform Resource Identifier)
   *        into its component parts.
   *
   * This class conforms to a URI as defined by RFC 3986, RFC 3987 and
   * RFC 2732, including scoped IDs. It provides member functions for
   * normalizing, comparing and resolving URIs.
   *
   * A URI has the syntax:
   *
   * \code
   * [scheme:][user_info@][host][:port][path][?query][#fragment]
   * \endcode
   *
   * Example:
   *
   * \code
   * network::uri instance("http://cpp-netlib.org/");
   * assert(instance.is_absolute());
   * assert(!instance.is_opaque());
   * assert(instance.scheme());
   * assert("http" == *instance.scheme());
   * assert(instance.host());
   * assert("cpp-netlib.org" == *instance.host());
   * assert(instance.path());
   * assert("/" == *instance.path());
   * \endcode
   */
  class NETWORK_URI_DECL uri {

#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
    friend class uri_builder;
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)

   public:

    /**
     * \brief The URI string_type.
     */
    typedef std::string string_type;

    /**
     * \brief The URI iterator type.
     */
    typedef string_type::const_iterator iterator;
    /**
     * \brief The URI const_iterator type.
     */
    typedef string_type::const_iterator const_iterator;

    /**
     * \brief The URI value_type.
     */
    typedef std::iterator_traits<iterator>::value_type value_type;

    /**
     * \brief A reference to the underlying string_type parts.
     */
    typedef boost::string_ref string_view;

   private:

    void initialize(boost::optional<string_type> scheme,
                    boost::optional<string_type> user_info,
                    boost::optional<string_type> host,
                    boost::optional<string_type> port,
                    boost::optional<string_type> path,
                    boost::optional<string_type> query,
                    boost::optional<string_type> fragment);

   public:

    /**
     * \brief Constructor.
     */
    uri();

    /**
     * \brief Constructor.
     * \param first The first element in a string sequence.
     * \param last The end + 1th element in a string sequence.
     * \throws uri_syntax_error if the sequence is not a valid URI.
     * \throws std::bad_alloc If the underlying string cannot be allocated.
     */
    template <class InputIter>
    uri(InputIter first, InputIter last) {
      if (!initialize(string_type(first, last))) {
        throw uri_syntax_error();
      }
    }

#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
    template <class InputIter>
    explicit uri(InputIter first, InputIter last, std::error_code &ec) {
      if (!initialize(string_type(first, last))) {
        ec = make_error_code(uri_error::invalid_syntax);
      }
    }
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)

    /**
     * \brief Constructor.
     * \param source A source string that is to be parsed as a URI.
     * \throws uri_syntax_error if the source is not a valid URI.
     * \throws std::bad_alloc If the underlying string cannot be allocated.
     */
    template <class Source>
    explicit uri(const Source &source) {
      if (!initialize(detail::translate(source))) {
        throw uri_syntax_error();
      }
    }

#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
    template <class Source>
    explicit uri(const Source &source, std::error_code &ec) {
      if (!initialize(detail::translate(source))) {
        ec = make_error_code(uri_error::invalid_syntax);
      }
    }
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)

#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
    explicit uri(const uri_builder &builder);
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)

    /**
     * \brief Copy constructor.
     * \throws std::bad_alloc If the underlying string cannot be allocated.
     */
    uri(const uri &other);

    /**
     * \brief Move constructor.
     */
    uri(uri &&other) NETWORK_URI_NOEXCEPT;

    /**
     * \brief Destructor.
     */
    ~uri() NETWORK_URI_NOEXCEPT;

    /**
     * \brief Assignment operator.
     * \throws std::bad_alloc If the underlying string cannot be allocated.
     */
    uri &operator=(uri other);

    /**
     * \brief Swaps one uri object with another.
     * \param other The other uri object.
     */
    void swap(uri &other) NETWORK_URI_NOEXCEPT;

    /**
     * \brief Returns an iterator at the first element in the
     *        underlying sequence.
     * \return An iterator starting at the first element.
     */
    const_iterator begin() const;

    /**
     * \brief Returns an iterator at the end + 1th element in the
     *        underlying sequence.
     * \return An iterator starting at the end + 1th element.
     */
    const_iterator end() const;

    /**
     * \brief Returns the URI scheme.
     * \return The scheme, if it exists, or boost::none.
     */
    boost::optional<string_view> scheme() const;

    /**
     * \brief Returns the URI user info.
     * \return The user info, if it exists, or boost::none.
     */
    boost::optional<string_view> user_info() const;

    /**
     * \brief Returns the URI host.
     * \return The host, if it exists, or boost::none.
     */
    boost::optional<string_view> host() const;

    /**
     * \brief Returns the URI port.
     * \return The port, if it exists, or boost::none.
     */
    boost::optional<string_view> port() const;

    /**
     * \brief Returns the URI port as an integer.
     * \return The port, if it exists, or boost::none.
     */
    template <typename IntT>
    boost::optional<IntT> port(typename std::is_integral<IntT>::type * = 0) const {
      if (auto p = port()) {
        try {
          return boost::lexical_cast<IntT>(string_type(std::begin(*p), std::end(*p)));
        }
        catch (boost::bad_lexical_cast &) {
          return boost::optional<IntT>();
        }
      }
      return boost::optional<IntT>();
    }

    /**
     * \brief Returns the URI path.
     * \return The path, if it exists, or boost::none.
     */
    boost::optional<string_view> path() const;

    /**
     * \brief Returns the URI query.
     * \return The query, if it exists, or boost::none.
     */
    boost::optional<string_view> query() const;

    /**
     * \brief Returns the URI fragment.
     * \return The fragment, if it exists, or boost::none.
     */
    boost::optional<string_view> fragment() const;

    /**
     * \brief Returns the URI authority.
     * \return The authority, if it exists, or boost::none.
     */
    boost::optional<string_view> authority() const;

#if !defined(_MSC_VER)
    /**
     * \brief Returns the URI as a std::basic_string object.
     * \return A URI string.
     */
    template <typename CharT, class CharTraits = std::char_traits<CharT>,
              class Alloc = std::allocator<CharT> >
    std::basic_string<CharT, CharTraits, Alloc> to_string(const Alloc &alloc =
                                                              Alloc()) const {
      return std::basic_string<CharT, CharTraits, Alloc>(begin(), end());
    }

#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
    template <typename CharT, class CharTraits = std::char_traits<CharT>,
              class Alloc = std::allocator<CharT> >
    std::basic_string<CharT, CharTraits, Alloc> string(const Alloc &alloc =
                                                           Alloc()) const {
      return to_string<CharT, CharTraits, Alloc>(alloc);
    }
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)
#else
#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
    template <typename CharT, class CharTraits, class Alloc>
    std::basic_string<CharT, CharTraits, Alloc> to_string(const Alloc &alloc =
                                                              Alloc()) const {
      return std::basic_string<CharT, CharTraits, Alloc>(begin(), end());
    }

    template <typename CharT, class CharTraits = std::char_traits<CharT>,
              class Alloc = std::allocator<CharT> >
    std::basic_string<CharT, CharTraits, Alloc> string(const Alloc &alloc =
                                                           Alloc()) const {
      return to_string<CharT, CharTraits, Alloc>(alloc);
    }
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)
#endif // !/defined(_MSC_VER)

    /**
     * \brief Returns the URI as a std::string object.
     * \returns A URI string.
     */
    std::string string() const;

    /**
     * \brief Returns the URI as a std::wstring object.
     * \returns A URI string.
     */
    std::wstring wstring() const;

    /**
     * \brief Returns the URI as a std::u16string object.
     * \returns A URI string.
     */
    std::u16string u16string() const;

    /**
     * \brief Returns the URI as a std::u32string object.
     * \returns A URI string.
     */
    std::u32string u32string() const;

    /**
     * \brief Checks if the uri object is empty, i.e. it has no parts.
     * \returns \c true if there are no parts, \c false otherwise.
     */
    bool empty() const NETWORK_URI_NOEXCEPT;

    /**
     * \brief Checks if the uri is absolute, i.e. it has a scheme.
     * \returns \c true if it is absolute, \c false if it is relative.
     */
    bool is_absolute() const;

    /**
     * \brief Checks if the uri is opaque, i.e. if it doesn't have an
     *        authority.
     * \returns \c true if it is opaque, \c false if it is hierarchical.
     */
    bool is_opaque() const;

    /**
     * \brief Normalizes a uri object at a given level in the
     *        comparison ladder.
     * \param level The comparison level.
     * \returns A normalized uri.
     * \post compare(normalize(uri, level), level) == 0
     * \throws std::bad_alloc
     */
    uri normalize(uri_comparison_level level) const;

    /**
     * \brief Returns a relative reference against the base URI.
     * \param base The base URI.
     * \returns A relative reference of this URI against the base.
     * \throws std::bad_alloc
     */
    uri make_relative(const uri &base) const;

#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
    uri make_reference(const uri &base) const { return make_relative(base); }
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)

    /**
     * \brief Resolves a relative reference against the given URI.
     * \param base The base URI to resolve against.
     * \returns An absolute URI.
     * \throws std::bad_alloc
     */
    uri resolve(const uri &base) const;

    /**
     * \brief Compares this URI against another, corresponding to the
     *        level in the comparison ladder.
     * \param other The other URI.
     * \param level The level in the comparison ladder.
     * \returns \c 0 if the URIs are considered equal, \c -1 if this is
     *         less than other and and 1 if this is greater than
     *         other.
     */
    int compare(const uri &other, uri_comparison_level level) const NETWORK_URI_NOEXCEPT;

    /**
     * \brief Encodes a sequence according to the rules for encoding a
     *        user info part.
     * \param first The iterator at first element in the input
     *        sequence.
     * \param last The iterator at end + 1th element in the input
     *        sequence.
     * \param out The iterator at the first element in the output
     *        sequence.
     * \returns The iterator at the end + 1th in the output sequence.
     */
    template <typename InputIter, typename OutputIter>
    static OutputIter encode_user_info(InputIter first, InputIter last,
                                       OutputIter out) {
      return detail::encode_user_info(first, last, out);
    }

    /**
     * \brief Encodes a sequence according to the rules for encoding a
     *        host part.
     * \param first The iterator at first element in the input
     *        sequence.
     * \param last The iterator at end + 1th element in the input
     *        sequence.
     * \param out The iterator at the first element in the output
     *        sequence.
     * \returns The iterator at the end + 1th in the output sequence.
     */
    template <typename InputIter, typename OutputIter>
    static OutputIter encode_host(InputIter first, InputIter last,
                                  OutputIter out) {
      return detail::encode_host(first, last, out);
    }

    /**
     * \brief Encodes a sequence according to the rules for encoding a
     *        port part.
     * \param first The iterator at first element in the input
     *        sequence.
     * \param last The iterator at end + 1th element in the input
     *        sequence.
     * \param out The iterator at the first element in the output
     *        sequence.
     * \returns The iterator at the end + 1th in the output sequence.
     */
    template <typename InputIter, typename OutputIter>
    static OutputIter encode_port(InputIter first, InputIter last,
                                  OutputIter out) {
      return detail::encode_port(first, last, out);
    }

    /**
     * \brief Encodes a sequence according to the rules for encoding a
     *        path part.
     * \param first The iterator at first element in the input
     *        sequence.
     * \param last The iterator at end + 1th element in the input
     *        sequence.
     * \param out The iterator at the first element in the output
     *        sequence.
     * \returns The iterator at the end + 1th in the output sequence.
     */
    template <typename InputIter, typename OutputIter>
    static OutputIter encode_path(InputIter first, InputIter last,
                                  OutputIter out) {
      return detail::encode_path(first, last, out);
    }

    /**
     * \brief Encodes a sequence according to the rules for encoding a
     *        query part.
     * \param first The iterator at first element in the input
     *        sequence.
     * \param last The iterator at end + 1th element in the input
     *        sequence.
     * \param out The iterator at the first element in the output
     *        sequence.
     * \returns The iterator at the end + 1th in the output sequence.
     */
    template <typename InputIter, typename OutputIter>
    static OutputIter encode_query(InputIter first, InputIter last,
                                   OutputIter out) {
      return detail::encode_query(first, last, out);
    }

    /**
     * \brief Encodes a sequence according to the rules for encoding a
     *        fragment part.
     * \param first The iterator at first element in the input
     *        sequence.
     * \param last The iterator at end + 1th element in the input
     *        sequence.
     * \param out The iterator at the first element in the output
     *        sequence.
     * \returns The iterator at the end + 1th in the output sequence.
     */
    template <typename InputIter, typename OutputIter>
    static OutputIter encode_fragment(InputIter first, InputIter last,
                                      OutputIter out) {
      return detail::encode_fragment(first, last, out);
    }

    /**
     * \brief Decodes a sequence according to the percent decoding
     *        rules.
     * \param first The iterator at first element in the input
     *        sequence.
     * \param last The iterator at end + 1th element in the input
     *        sequence.
     * \param out The iterator at the first element in the output
     *        sequence.
     * \returns The iterator at the end + 1th in the output sequence.
     */
    template <typename InputIter, typename OutputIter>
    static OutputIter decode(InputIter first, InputIter last, OutputIter out) {
      return detail::decode(first, last, out);
    }

   private:

    bool initialize(const string_type &uri);

    string_type uri_;
    detail::uri_parts<string_type::iterator> uri_parts_;
  };

  /**
   * \brief \c uri factory function.
   * \param first The first element in a string sequence.
   * \param last The end + 1th element in a string sequence.
   * \param ec Error code set if the sequence is not a valid URI.
   */
  template <class InputIter>
  inline uri make_uri(InputIter first, InputIter last,
                      std::error_code &ec) {
    return uri(first, last, ec);
  }

  /**
   * \brief \c uri factory function.
   * \param source A source string that is to be parsed as a URI.
   * \param ec Error code set if the source is not a valid URI.
   */
  template <class Source>
  inline uri make_uri(const Source &source,
                      std::error_code &ec) {
    return uri(source, ec);
  }

  /**
   * \brief Swaps one uri object with another.
   */
   void swap(uri &lhs, uri &rhs) NETWORK_URI_NOEXCEPT;

   /**
   * \brief Equality operator for the \c uri.
   */
  bool operator==(const uri &lhs, const uri &rhs) NETWORK_URI_NOEXCEPT;

  /**
   * \brief Equality operator for the \c uri.
   */
  bool operator==(const uri &lhs, const char *rhs) NETWORK_URI_NOEXCEPT;

  /**
   * \brief Equality operator for the \c uri.
   */
  inline bool operator==(const char *lhs, const uri &rhs) NETWORK_URI_NOEXCEPT {
    return rhs == lhs;
  }

  /**
   * \brief Inequality operator for the \c uri.
   */
  inline bool operator!=(const uri &lhs, const uri &rhs) NETWORK_URI_NOEXCEPT {
    return !(lhs == rhs);
  }

  /**
   * \brief Less-than operator for the \c uri.
   */
  bool operator<(const uri &lhs, const uri &rhs) NETWORK_URI_NOEXCEPT ;

  /**
   * \brief Greater-than operator for the \c uri.
   */
  inline bool operator>(const uri &lhs, const uri &rhs) NETWORK_URI_NOEXCEPT {
    return rhs < lhs;
  }

  /**
   * \brief Less-than-or-equal-to operator for the \c uri.
   */
  inline bool operator<=(const uri &lhs, const uri &rhs) NETWORK_URI_NOEXCEPT {
    return !(rhs < lhs);
  }

  /**
   * \brief Greater-than-or-equal-to operator for the \c uri.
   */
  inline bool operator>=(const uri &lhs, const uri &rhs) NETWORK_URI_NOEXCEPT {
    return !(lhs < rhs);
  }
}  // namespace network

#if !defined(DOXYGEN_SHOULD_SKIP_THIS)
namespace std {
  template <>
  struct is_error_code_enum<network::uri_error> : public true_type {};
}  // namespace std

namespace std {
  template <>
  struct hash<network::uri> {

    std::size_t operator()(const network::uri &uri_) const {
      std::size_t seed = 0;
      std::for_each(std::begin(uri_), std::end(uri_),
                    [&seed](network::uri::value_type v) {
        std::hash<network::uri::value_type> hasher;
        seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
      });
      return seed;
    }
  };
}  // namespace std
#endif // !defined(DOXYGEN_SHOULD_SKIP_THIS)

#include <network/uri/uri_builder.hpp>

#endif  // NETWORK_URI_INC

max_stars_repo_name: FollowTheDarkside/openFrameworks

max_issues_repo_name: SpecularStudio/ofQt

max_forks_repo_name: hunter-packages/uri


text:
#pragma once

// `krbn::grabbable_state_manager` can be used safely in a multi-threaded environment.

#include "boost_defs.hpp"

#include "device_detail.hpp"
#include "dispatcher.hpp"
#include "event_queue.hpp"
#include "keyboard_repeat_detector.hpp"
#include <boost/signals2.hpp>

namespace krbn {
class grabbable_state_manager final : public pqrs::dispatcher::extra::dispatcher_client {
public:
#include "grabbable_state_manager/entry.hpp"

  // Signals (invoked from the shared dispatcher thread)

  boost::signals2::signal<void(const grabbable_state&)> grabbable_state_changed;

  // Methods

  grabbable_state_manager(const grabbable_state_manager&) = delete;

  grabbable_state_manager(void) : dispatcher_client() {
  }

  virtual ~grabbable_state_manager(void) {
    detach_from_dispatcher([] {
    });
  }

  void update(const grabbable_state& state) {
    std::lock_guard<std::mutex> lock(entries_mutex_);

    auto registry_entry_id = state.get_registry_entry_id();

    auto it = entries_.find(registry_entry_id);
    if (it == std::end(entries_)) {
      entries_.emplace(registry_entry_id,
                       entry(registry_entry_id));
      it = entries_.find(registry_entry_id);
    }

    if (it != std::end(entries_)) {
      auto old_state = it->second.get_grabbable_state();

      it->second.set_grabbable_state(state);

      auto new_state = it->second.get_grabbable_state();

      if (!old_state.equals_except_time_stamp(new_state)) {
        enqueue_to_dispatcher([this, new_state] {
          grabbable_state_changed(new_state);
        });
      }
    }
  }

  void update(const event_queue::queue& event_queue) {
    std::lock_guard<std::mutex> lock(entries_mutex_);

    for (const auto& event_queue_entry : event_queue.get_entries()) {
      if (auto device_detail = types::find_device_detail(event_queue_entry.get_device_id())) {
        if (auto registry_entry_id = device_detail->get_registry_entry_id()) {
          auto time_stamp = event_queue_entry.get_event_time_stamp().get_time_stamp();

          auto it = entries_.find(*registry_entry_id);
          if (it == std::end(entries_)) {
            entries_.emplace(*registry_entry_id,
                             entry(*registry_entry_id));
            it = entries_.find(*registry_entry_id);
          }

          if (it != std::end(entries_)) {
            auto old_state = it->second.get_grabbable_state();

            it->second.update(*registry_entry_id,
                              time_stamp,
                              event_queue_entry);

            auto new_state = it->second.get_grabbable_state();

            if (!old_state.equals_except_time_stamp(new_state)) {
              enqueue_to_dispatcher([this, new_state] {
                grabbable_state_changed(new_state);
              });
            }
          }
        }
      }
    }
  }

  void erase(registry_entry_id registry_entry_id) {
    std::lock_guard<std::mutex> lock(entries_mutex_);

    entries_.erase(registry_entry_id);
  }

  boost::optional<grabbable_state> get_grabbable_state(registry_entry_id registry_entry_id) const {
    std::lock_guard<std::mutex> lock(entries_mutex_);

    auto it = entries_.find(registry_entry_id);
    if (it != std::end(entries_)) {
      return it->second.get_grabbable_state();
    }
    return boost::none;
  }

private:
  std::unordered_map<registry_entry_id, entry> entries_;
  mutable std::mutex entries_mutex_;
};
} // namespace krbn

max_stars_repo_name: cyrusccy/Karabiner-Elements

max_issues_repo_name: cyrusccy/Karabiner-Elements

max_forks_repo_name: cyrusccy/Karabiner-Elements


text:
/*
Phobos 3d
January 2010
Copyright (c) 2005-2011 Bruno Sanches  http://code.google.com/p/phobos3d

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

#include "Phobos/String.h"

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

namespace Phobos
{
	using namespace std;

	size_t StringReplaceAll(String_t &str, char search, char replace)
	{
		size_t count = 0;
		for(string::iterator it = str.begin(), end = str.end(); it != end; ++it)
		{
			if(*it == search)
			{
				++count;
				*it = replace;
			}
		}

		return count;
	}

	void StringReplaceAll(String_t &out, const String_t &src, char search, char replace)
	{
		out.clear();
		for(string::const_iterator it = src.begin(), end = src.end(); it != end; ++it)
		{
			out += *it == search ? replace : *it;
		}
	}

	void StringTrim(String_t &str, int mode)
	{
		using namespace boost;

		if(mode & STRING_TRIM_LEFT)
		{
			trim_left(str);
		}
		if(mode & STRING_TRIM_RIGHT)
		{
			trim_right(str);
		}
	}

	bool StringIsBlank(const String_t &src)
	{
		const std::locale& loc=std::locale();
		for(string::const_iterator it = src.begin(), end = src.end(); it != end; ++it)
		{
			if(!std::isspace(*it, loc))
				return false;
		}

		return true;
	}

	bool StringSplitBy(String_t &out, const String_t &src, char ch, size_t pos, size_t *outPos)
	{
		const size_t sz = src.length();
		size_t startPos = pos;

		size_t len = 0;

		out.clear();
		for(;pos < sz; ++pos)
		{
			if(src[pos] == ch)
			{
				len = pos - startPos;
				if(len == 0)
				{
					startPos = pos + 1;
					continue;
				}

				++pos;
				goto COPY_SUB;
			}
		}

		//When the loop ends normally, we need to compute len
		len = pos - startPos;

		//end of the string?
		if((pos >= sz) && (len == 0))
			return(false);

		//no split char found, check if we can return he full string
		if(startPos == 0)
		{
			out = src;
		}
		else
		{
	COPY_SUB:
			//out.SetSub(this, startPos, len);
			out.assign(src, startPos, len);
		}

		if(outPos)
			*outPos = pos;

		return(true);
	}

	bool StringToBoolean(const String_t &a)
	{
		if(a.compare("true") == 0)
			return true;
		else if(a.compare("false") == 0)
			return false;
		else
		{
			return std::stoi	(a) ? true : false;
		}
	}
}


text:
#include <NTL/FacVec.h>
#include <NTL/ZZ.h>

#include <NTL/new.h>

NTL_START_IMPL

NTL_vector_impl(IntFactor,vec_IntFactor)

static
void swap(IntFactor& x, IntFactor& y)
{
   IntFactor t;

   t = x;  x = y;  y = t;
}

static
void FindMin(FacVec& v, long lo, long hi)
{
   long minv = 0;
   long minp = -1;
   long i;

   for (i = lo; i <= hi; i++) {
      if (minv == 0 || v[i].val < minv) {
         minv = v[i].val;
         minp = i;
      }
   }

   swap(v[lo], v[minp]);
}

void FactorInt(FacVec& fvec, long n)
{
   if (n <= 1) Error("internal error: FactorInt(FacVec,long n) with n<=1");

   if (NTL_OVERFLOW(n, 1, 0))
      Error("internal error: FactorInt(FacVec,long n) with n too large");

   long NumFactors;
   long q;

   fvec.SetLength(2*NextPowerOfTwo(n));

   NumFactors = 0;
   q = 2;

   while (n != 1) {
      if (n%q == 0) {
         fvec[NumFactors].q = q;
         n = n/q;
         fvec[NumFactors].a = 1;
         fvec[NumFactors].val = q;
         while (n%q == 0) {
            n = n/q;
            (fvec[NumFactors].a)++;
            fvec[NumFactors].val *= q;
         }
         fvec[NumFactors].link = -1;
         NumFactors++;
      }

      q++;
   }

   fvec.SetLength(2*NumFactors-1);

   long lo = 0;
   long hi = NumFactors - 1;

   while (lo < hi) {
      FindMin(fvec, lo, hi);
      FindMin(fvec, lo+1, hi);
      hi++;
      fvec[hi].link = lo;
      fvec[hi].val = fvec[lo].val * fvec[lo+1].val;
      lo += 2;
   }
}

NTL_END_IMPL

max_stars_repo_name: vshesh/RUNEtag

max_issues_repo_name: vshesh/RUNEtag

max_forks_repo_name: vshesh/RUNEtag


text:
// Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/functional/partial.hpp>

#include <laws/base.hpp>
namespace hana = boost::hana;
using hana::test::ct_eq;

int main() {
    hana::test::_injection<0> f{};

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f)(),
        f()
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f)(ct_eq<1>{}),
        f(ct_eq<1>{})
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f)(ct_eq<1>{}, ct_eq<2>{}),
        f(ct_eq<1>{}, ct_eq<2>{})
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f)(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{}),
        f(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{})
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f, ct_eq<1>{})(),
        f(ct_eq<1>{})
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f, ct_eq<1>{})(ct_eq<2>{}),
        f(ct_eq<1>{}, ct_eq<2>{})
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f, ct_eq<1>{})(ct_eq<2>{}, ct_eq<3>{}),
        f(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{})
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f, ct_eq<1>{}, ct_eq<2>{})(),
        f(ct_eq<1>{}, ct_eq<2>{})
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f, ct_eq<1>{}, ct_eq<2>{})(ct_eq<3>{}),
        f(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{})
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f, ct_eq<1>{}, ct_eq<2>{})(ct_eq<3>{}, ct_eq<4>{}),
        f(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{}, ct_eq<4>{})
    ));

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::partial(f, ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{})(),
        f(ct_eq<1>{}, ct_eq<2>{}, ct_eq<3>{})
    ));
}

max_stars_repo_name: nxplatform/nx-mobile

max_issues_repo_name: nxplatform/nx-mobile

max_forks_repo_name: nxplatform/nx-mobile


text:
/*
Copyright (C) 2019 Quaternion Risk Management Ltd
All rights reserved.

This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org

ORE is free software: you can redistribute it and/or modify it
under the terms of the Modified BSD License.  You should have received a
copy of the license along with this program.
The license is also available online at <http://opensourcerisk.org>

This program is distributed on the basis that it will form a useful
contribution to risk analytics and model standardisation, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

/*! \file qle/termstructures/dynamicyoyoptionletvolatilitystructure.hpp
\brief dynamic yoy inflation optionlet volatility structure
\ingroup termstructures
*/

#pragma once

#include <boost/make_shared.hpp>
#include <ql/termstructures/volatility/inflation/yoyinflationoptionletvolatilitystructure.hpp>
#include <ql/termstructures/volatility/smilesection.hpp>
#include <qle/termstructures/dynamicstype.hpp>

namespace QuantExt {
using namespace QuantLib;

//! Converts YoYOptionletVolatilitySurface with fixed reference date into a floating reference date term structure.
/*! Different ways of reacting to time decay can be specified.

\warning No checks are performed that the supplied YoYOptionletVolatilitySurface has a fixed reference date

\ingroup termstructures
*/

class DynamicYoYOptionletVolatilitySurface : public YoYOptionletVolatilitySurface {
public:
    DynamicYoYOptionletVolatilitySurface(const boost::shared_ptr<YoYOptionletVolatilitySurface>& source,
                                         ReactionToTimeDecay decayMode = ConstantVariance);

protected:
    Volatility volatilityImpl(Time optionTime, Rate strike) const override;
    Rate minStrike() const override;
    Rate maxStrike() const override;
    Date maxDate() const override;

private:
    const boost::shared_ptr<YoYOptionletVolatilitySurface> source_;
    ReactionToTimeDecay decayMode_;
    const Date originalReferenceDate_;
};

} // namespace QuantExt

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
#include <NTL/vec_GF2E.h>
#include <rank/knowledge_of_valid_opening/knowledge_of_valid_opening.h>
#include <rank/rank_commitment/rank_commitment.h>
#include <utils/utils.h>
#include "linear_relations.h"

void rank::linear_relations::initalized_commitments_and_responses(
        commitments_t *commitments,
        responses_t *responses) {

    commitments->s0.SetLength(I);
    commitments->s1.SetLength(I);
    commitments->s2.SetLength(I);

    commitments->c0.SetLength(I);
    commitments->c1.SetLength(I);
    commitments->c2.SetLength(I);

    responses->r1.SetLength(I);
    responses->r2.SetLength(I);
    responses->r3.SetLength(I);
}

void rank::linear_relations::generate_revealed_values(
        revealed_values_t *revealed_values) {

    revealed_values->P.SetLength(I);
    revealed_values->Q.SetLength(I);

    ::utils::generate_random_binary_matrix(
            revealed_values->matrices.x_0,
            MI,
            MI);
    ::utils::generate_random_binary_matrix(
            revealed_values->matrices.x_1,
            MI,
            MI);

    for(int i = 0; i < I; i++) {
        utils::generate_random_square_invertible_matrix(
                revealed_values->P[i],
                EN);
        utils::generate_random_square_invertible_matrix(
                revealed_values->Q[i],
                EM);
    }
}

void rank::linear_relations::generate_private_key(
        private_key_t *private_key,
        const linear_relation_matrices_t *matrices) {

    private_key->m.kill();

    private_key->e.kill();
    private_key->e.SetLength(I);

    for(int i = 0; i < I; i++) {
        private_key->e[i].kill();
        private_key->e[i].SetLength(EN);
        ::utils::generate_vector_of_specific_rank(
                private_key->e[i],
                EN,
                RHO);
    }

    for(int i = 0; i < 2; i++) {
        private_key->m.append(NTL::vec_GF2());
        private_key->m[i] = NTL::random_vec_GF2(MI);
    }
    private_key->m.append((private_key->m[0] * matrices->x_0) + (private_key->m[1] * matrices->x_1));
}

void rank::linear_relations::generate_public_key(
        public_key_t *public_key,
        const private_key_t *private_key) {

    public_key->commitments.SetLength(I);

    utils::generate_random_matrix_gf2e(
            public_key->G,
            K,
            EN);

    for(int i = 0; i < I; i++) {
        NTL::vec_GF2 s;
        utils::generate_random_binary_vector(
                s,
                PI);

        rank::rank_commitment::generate_commitment(
                public_key->commitments[i],
                s,
                private_key->m[i],
                public_key->G,
                private_key->e[i]);
    }
}

void rank::linear_relations::generate_random_values(
        random_values_t *random_values,
        const linear_relation_matrices_t *matrices) {

    for (int i = 0; i < I; i++) {
        random_values->u.append(NTL::random_vec_GF2(PI));
        random_values->f.append(NTL::random_vec_GF2E(EN));
    }

    for (int i = 0; i < I - 1; i++) {
        random_values->v.append(NTL::random_vec_GF2(MI));
    }

    auto v_2 = (random_values->v[0] * matrices->x_0) + (random_values->v[1] * matrices->x_1);
    random_values->v.append(v_2);

    random_values->u_v = random_values->u;

    for(int i = 0; i < I; i++) {
        NTL::append(random_values->u_v[i], random_values->v[i]);
    }
}

void rank::linear_relations::generate_commitments_and_responses(
        commitments_t *commitments,
        responses_t *responses,
        const random_values_t *random_values,
        const revealed_values_t *revealed_values,
        const private_key_t *private_key,
        const public_key_t *public_key) {

    for (int i = 0; i < I; i++) {
        rank::knowledge_of_valid_opening::generate_commitment_0_and_response_0(
                commitments->c0[i],
                commitments->s0[i],
                responses->r1[i],
                utils::gf2e_from_vec_gf2(random_values->u_v[i]),
                random_values->f[i],
                revealed_values->P[i],
                revealed_values->Q[i],
                public_key->G);

        rank::knowledge_of_valid_opening::generate_commitment_1_and_response_1(
                commitments->c1[i],
                commitments->s1[i],
                responses->r2[i],
                random_values->f[i],
                revealed_values->P[i],
                revealed_values->Q[i],
                public_key->G);

        rank::knowledge_of_valid_opening::generate_commitment_2_and_response_2(
                commitments->c2[i],
                commitments->s2[i],
                responses->r3[i],
                private_key->e[i],
                random_values->f[i],
                revealed_values->P[i],
                revealed_values->Q[i],
                public_key->G);
    }
}

int rank::linear_relations::verify_0(
        const NTL::Vec<NTL::vec_GF2> &s0,
        const NTL::Vec<NTL::vec_GF2> &s1,
        const NTL::Vec<NTL::vec_GF2E> &c0,
        const NTL::Vec<NTL::vec_GF2E> &c1,
        const NTL::Vec<NTL::vec_GF2E> &r1,
        const NTL::Vec<NTL::vec_GF2E> &r2,
        const NTL::Vec<NTL::mat_GF2> &P,
        const NTL::Vec<NTL::mat_GF2> &Q,
        const NTL::mat_GF2 &x_0,
        const NTL::mat_GF2 &x_1,
        const public_key_t *public_key) {

    for (int i = 0; i < I; i++) {
        auto _r1 = utils::encode(P[i], Q[i], r1[i], MI);
        if (rank::rank_commitment::verify_proof(
                c0[i],
                s0[i],
                _r1,
                public_key->G) != 0) {
            std::cout << "Verification 2 for ch = 0 failed" << std::endl;
            return 1;
        }
    }

    for (int i = 0; i < I; i++) {
        auto _r2 = utils::encode_2(r2[i], MI);
        if (rank::rank_commitment::verify_proof(
                c1[i],
                s1[i],
                _r2,
                public_key->G) != 0) {
            std::cout << "Verification 2 for ch = 0 failed" << std::endl;
            return 1;
        }
    }

    NTL::Vec<NTL::vec_GF2E> results;
    for (int i = 0; i < I; i++) {
        NTL::vec_GF2E pi_inv_r2;
        rank::knowledge_of_valid_opening::calculate_pi_inv(
                pi_inv_r2,
                P[i],
                Q[i],
                r2[i]);

        NTL::vec_GF2E result;
        if (utils::solve_equation(
                result,
                public_key->G,
                r1[i] + pi_inv_r2) != 0) {
            std::cout << "No Solutions" << std::endl;
            return 1;
        }
        results.append(result);
    }

    NTL::Vec<NTL::vec_GF2E> b;
    b.SetLength(I);
    for (int i = 0; i < I; i++) {
        NTL::VectorCopy(b[i], results[i], K);
    }

    auto b0_gf2 = utils::gf2_from_gf2e(b[0]);
    auto b1_gf2 = utils::gf2_from_gf2e(b[1]);
    auto b2_gf2 = utils::gf2_from_gf2e(b[2]);

    NTL::vec_GF2 b0_gf2_s, b1_gf2_s, b2_gf2_s;
    for (int j = PI; j < PI + MI; j++) {
        b0_gf2_s.append(b0_gf2[j]);
        b1_gf2_s.append(b1_gf2[j]);
        b2_gf2_s.append(b2_gf2[j]);
    }

    if (NTL::IsZero(b2_gf2_s + ((b0_gf2_s * x_0) + (b1_gf2_s * x_1)))) {
        return 0;
    } else {
        std::cout << "Verify 0 failed" << std::endl;
        std::cout << b2_gf2_s << std::endl;
        std::cout << (b0_gf2_s * x_0) + (b1_gf2_s * x_1) << std::endl;
        return 1;
    }
}

int rank::linear_relations::verify_1(
        const NTL::Vec<NTL::vec_GF2> &s0,
        const NTL::Vec<NTL::vec_GF2> &s2,
        const NTL::Vec<NTL::vec_GF2E> &c0,
        const NTL::Vec<NTL::vec_GF2E> &c2,
        const NTL::Vec<NTL::vec_GF2E> &r1,
        const NTL::Vec<NTL::vec_GF2E> &r3,
        const NTL::Vec<NTL::mat_GF2> &P,
        const NTL::Vec<NTL::mat_GF2> &Q,
        const NTL::mat_GF2 &x_0,
        const NTL::mat_GF2 &x_1,
        const public_key_t *public_key) {

    for (int i = 0; i < I; i++) {
        auto _r1 = utils::encode(P[i], Q[i], r1[i], MI);
        if (rank::rank_commitment::verify_proof(
                c0[i],
                s0[i],
                _r1,
                public_key->G) != 0) {
            std::cout << "Verification 2 for ch = 0 failed" << std::endl;
            return 1;
        }
    }

    for (int i = 0; i < I; i++) {
        auto _r3 = utils::encode_2(r3[i], MI);
        if (rank::rank_commitment::verify_proof(
                c2[i],
                s2[i],
                _r3,
                public_key->G) != 0) {
            std::cout << "Verification 2 for ch = 0 failed" << std::endl;
            return 1;
        }
    }

    NTL::Vec<NTL::vec_GF2E> results;
    for (int i = 0; i < I; i++) {
        NTL::vec_GF2E pi_inv_r3;
        rank::knowledge_of_valid_opening::calculate_pi_inv(
                pi_inv_r3,
                P[i],
                Q[i],
                r3[i]);

        NTL::vec_GF2E result;
        if (utils::solve_equation(
                result,
                public_key->G,
                r1[i] + pi_inv_r3 + public_key->commitments[i]) != 0) {
            std::cout << "No Solutions" << std::endl;
            return 1;
        }
        results.append(result);
    }

    NTL::Vec<NTL::vec_GF2E> d;
    d.SetLength(I);
    for (int i = 0; i < I; i++) {
        NTL::VectorCopy(d[i], results[i], K);
    }

    auto d0_gf2 = utils::gf2_from_gf2e(d[0]);
    auto d1_gf2 = utils::gf2_from_gf2e(d[1]);
    auto d2_gf2 = utils::gf2_from_gf2e(d[2]);

    NTL::vec_GF2 d0_gf2_s, d1_gf2_s, d2_gf2_s;
    for (int j = 0; j < MI; j++) {
        d0_gf2_s.append(d0_gf2[j + PI]);
        d1_gf2_s.append(d1_gf2[j + PI]);
        d2_gf2_s.append(d2_gf2[j + PI]);
    }

    if (NTL::IsZero(d2_gf2_s + ((d0_gf2_s * x_0) + (d1_gf2_s * x_1)))) {
        return 0;
    } else {
        std::cout << "Verify 1 failed" << std::endl;
        std::cout << d2_gf2_s << std::endl;
        std::cout << (d0_gf2_s * x_0) + (d1_gf2_s * x_1) << std::endl;
        return 1;
    }
}

int rank::linear_relations::verify_2(
        const NTL::Vec<NTL::vec_GF2> &s1,
        const NTL::Vec<NTL::vec_GF2> &s2,
        const NTL::Vec<NTL::vec_GF2E> &c1,
        const NTL::Vec<NTL::vec_GF2E> &c2,
        const NTL::Vec<NTL::vec_GF2E> &r2,
        const NTL::Vec<NTL::vec_GF2E> &r3,
        const public_key_t *public_key) {

    for (int i = 0; i < I; i++) {
        auto _r2 = utils::encode_2(r2[i], MI);
        if (rank::rank_commitment::verify_proof(
                c1[i],
                s1[i],
                _r2,
                public_key->G)) {
            std::cout << "Verification 1 for ch = 2 failed" << std::endl;
            return 1;
        }
    }

    for (int i = 0; i < I; i++) {
        auto _r3 = utils::encode_2(r3[i], MI);
        if (rank::rank_commitment::verify_proof(
                c2[i],
                s2[i],
                _r3,
                public_key->G)) {
            std::cout << "Verification 2 for ch = 2 failed" << std::endl;
            return 1;
        }
    }

    for(int i = 0; i < I; i++) {
        auto r2_plus_r3 = r2[i] + r3[i];

        NTL::mat_GF2 M;
        M.SetDims(EN, EM);

        for (int j = 0; j < EN; j++) {
            for (int z = 0; z < EM; z++) {
                if (NTL::IsZero(r2_plus_r3[j]._GF2E__rep[z])) {
                    M[j][z] = NTL::GF2(0);
                } else {
                    M[j][z] = NTL::GF2(1);
                }
            }
        }

        auto _M = M;

        auto res = NTL::gauss(_M);
        if (res != RHO) {
            std::cout << "Matrix weight not equal to RHO" << std::endl;
            return 1;
        }
    }

    return 0;
}


text:
/*=============================================================================
    Copyright (c) 2001-2011 Hartmut Kaiser
    Copyright (c) 2001-2011 Joel de Guzman

    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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_STANDARD_APRIL_26_2006_1106PM)
#define BOOST_SPIRIT_STANDARD_APRIL_26_2006_1106PM

#if defined(_MSC_VER)
#pragma once
#endif

#include <cctype>
#include <boost/assert.hpp>
#include <boost/cstdint.hpp>

namespace boost { namespace spirit { namespace char_encoding
{
    ///////////////////////////////////////////////////////////////////////////
    //  Test characters for specified conditions (using std functions)
    ///////////////////////////////////////////////////////////////////////////
    struct standard
    {
        typedef char char_type;
        typedef unsigned char classify_type;

        static bool
        isascii_(int ch)
        {
            return 0 == (ch & ~0x7f);
        }

        static bool
        ischar(int ch)
        {
            // uses all 8 bits
            // we have to watch out for sign extensions
            return (0 == (ch & ~0xff) || ~0 == (ch | 0xff)) != 0;
        }

        // *** Note on assertions: The precondition is that the calls to
        // these functions do not violate the required range of ch (int)
        // which is that strict_ischar(ch) should be true. It is the
        // responsibility of the caller to make sure this precondition is not
        // violated.

        static bool
        strict_ischar(int ch)
        {
            // ch should be representable as an unsigned char
            return ch >= 0 && ch <= UCHAR_MAX;
        }

        static bool
        isalnum(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isalnum(ch) != 0;
        }

        static bool
        isalpha(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isalpha(ch) != 0;
        }

        static bool
        isdigit(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isdigit(ch) != 0;
        }

        static bool
        isxdigit(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isxdigit(ch) != 0;
        }

        static bool
        iscntrl(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::iscntrl(ch) != 0;
        }

        static bool
        isgraph(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isgraph(ch) != 0;
        }

        static bool
        islower(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::islower(ch) != 0;
        }

        static bool
        isprint(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isprint(ch) != 0;
        }

        static bool
        ispunct(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::ispunct(ch) != 0;
        }

        static bool
        isspace(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isspace(ch) != 0;
        }

        static bool
        isblank BOOST_PREVENT_MACRO_SUBSTITUTION (int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return (ch == ' ' || ch == '\t');
        }

        static bool
        isupper(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::isupper(ch) != 0;
        }

    ///////////////////////////////////////////////////////////////////////////////
    //  Simple character conversions
    ///////////////////////////////////////////////////////////////////////////////

        static int
        tolower(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::tolower(ch);
        }

        static int
        toupper(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return std::toupper(ch);
        }

        static ::boost::uint32_t
        toucs4(int ch)
        {
            BOOST_ASSERT(strict_ischar(ch));
            return ch;
        }
    };
}}}

#endif

max_stars_repo_name: cpp-pm/boost

max_issues_repo_name: cpp-pm/boost

max_forks_repo_name: cpp-pm/boost


text:
/**
 * @file utils.cpp
 * @brief This is a utility class for stomp
 *
 * @author Jorge Nicho
 * @date March 7, 2016
 * @version TODO
 * @bug No known bugs
 *
 * @copyright Copyright (c) 2016, Southwest Research Institute
 *
 * @par License
 * Software License Agreement (Apache License)
 * @par
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * @par
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stomp_core/utils.h>
#include <cmath>
#include <iostream>
#include <Eigen/Dense>

namespace stomp_core
{

void generateFiniteDifferenceMatrix(int num_time_steps,
                                             DerivativeOrders::DerivativeOrder order,
                                             double dt, Eigen::MatrixXd& diff_matrix)
{

  diff_matrix = Eigen::MatrixXd::Zero(num_time_steps, num_time_steps);
  double multiplier = 1.0/pow(dt,(int)order);
  for (int i=0; i<num_time_steps; ++i)
  {
    for (int j=-FINITE_DIFF_RULE_LENGTH/2; j<=FINITE_DIFF_RULE_LENGTH/2; ++j)
    {
      int index = i+j;
      if (index < 0)
      {
        index = 0;
        continue;
      }
      if (index >= num_time_steps)
      {
        index = num_time_steps-1;
        continue;
      }

      diff_matrix(i,index) = multiplier * FINITE_CENTRAL_DIFF_COEFFS[order][j+FINITE_DIFF_RULE_LENGTH/2];
    }
  }
}

void generateSmoothingMatrix(int num_timesteps,double dt, Eigen::MatrixXd& projection_matrix_M)
{
  using namespace Eigen;

  // generate augmented finite differencing matrix
  int start_index_padded = FINITE_DIFF_RULE_LENGTH-1;
  int num_timesteps_padded = num_timesteps + 2*(FINITE_DIFF_RULE_LENGTH-1);
  MatrixXd finite_diff_matrix_A_padded;
  generateFiniteDifferenceMatrix(num_timesteps_padded,DerivativeOrders::STOMP_ACCELERATION,
                                 dt,finite_diff_matrix_A_padded);

  /* computing control cost matrix (R = A_transpose * A):
   * Note: Original code multiplies the A product by the time interval.  However this is not
   * what was described in the literature
   */
  MatrixXd control_cost_matrix_R_padded = dt*finite_diff_matrix_A_padded.transpose() * finite_diff_matrix_A_padded;
  MatrixXd control_cost_matrix_R = control_cost_matrix_R_padded.block(
      start_index_padded,start_index_padded,num_timesteps,num_timesteps);
  MatrixXd inv_control_cost_matrix_R = control_cost_matrix_R.fullPivLu().inverse();

  // computing projection matrix M
  projection_matrix_M = inv_control_cost_matrix_R;
  double max = 0;
  for(auto t = 0u; t < num_timesteps; t++)
  {
    max = projection_matrix_M(t,t);
    projection_matrix_M.col(t)*= (1.0/(num_timesteps*max)); // scaling such that the maximum value is 1/num_timesteps
  }
}

void differentiate(const Eigen::VectorXd& parameters, DerivativeOrders::DerivativeOrder order,
                          double dt, Eigen::VectorXd& derivatives )
{

  using namespace Eigen;

  derivatives = Eigen::VectorXd::Zero(parameters.size());

  // coefficient arrays
  VectorXd central_coeffs = VectorXd::Map(&FINITE_CENTRAL_DIFF_COEFFS[order][0],FINITE_DIFF_RULE_LENGTH);
  VectorXd forward_coeffs = VectorXd::Map(&FINITE_FORWARD_DIFF_COEFFS[order][0],FINITE_DIFF_RULE_LENGTH);
  VectorXd backward_coeffs = forward_coeffs.reverse();

  // check order eveness
  if(order %2 != 0)
  {
    backward_coeffs*= -1.0;
  }

  // creating difference matrix
  int rule_length = FINITE_DIFF_RULE_LENGTH;
  int size = parameters.size();
  int skip = FINITE_DIFF_RULE_LENGTH/2;
  Eigen::MatrixXd A = Eigen::MatrixXd::Zero(size,size);
  int start_ind, end_ind;
  for(auto i = 0; i < size; i++)
  {
    if(i < skip)
    {
      start_ind = i;
      A.row(i).segment(start_ind,rule_length) = forward_coeffs;
    }
    else if(i >= skip && i < size - skip)
    {
      start_ind = i - skip;
      A.row(i).segment(start_ind,rule_length) = central_coeffs;
    }
    else
    {
      start_ind = i - rule_length+1;
      A.row(i).segment(start_ind,rule_length) = backward_coeffs;
    }
  }

  derivatives = A*parameters/std::pow(dt,2);
}

void toVector(const Eigen::MatrixXd& m,std::vector<Eigen::VectorXd>& v)
{
  v.resize(m.rows(),Eigen::VectorXd::Zero(m.cols()));
  for(auto d = 0u; d < m.rows();d++)
  {
    v[d] = m.row(d);
  }
}

std::string toString(const std::vector<Eigen::VectorXd>& data)
{
  Eigen::IOFormat clean_format(4, 0, ", ", "\n", "[", "]");
  Eigen::MatrixXd m = Eigen::MatrixXd::Zero(data.size(),data.front().size());
  std::stringstream ss;
  for(auto d = 0u; d < data.size(); d++)
  {
    m.row(d) = data[d].transpose();
  }

  ss<<m.format(clean_format);
  return ss.str();
}

std::string toString(const Eigen::MatrixXd& data)
{
  Eigen::IOFormat clean_format(4, 0, ", ", "\n", "[", "]");
  std::stringstream ss;
  ss<<data.format(clean_format);
  return ss.str();
}

std::string toString(const Eigen::VectorXd& data)
{
  Eigen::IOFormat clean_format(4, 0, ", ", "\n", "[", "]");
  std::stringstream ss;
  ss<<data.transpose().format(clean_format);
  return ss.str();
}

}


text:
#pragma once

#include <Eigen/Dense>
#include <zmq.hpp>

#include "messages/draco.pb.h"

class DracoData;

class DracoDataManager {
public:
  static DracoDataManager *GetDracoDataManager();
  virtual ~DracoDataManager();

  void InitializeSockets(const std::string &_addr);

  void Send();

  std::unique_ptr<DracoData> data;

private:
  /* data */
  DracoDataManager();

  std::unique_ptr<zmq::context_t> context_;
  std::unique_ptr<zmq::socket_t> socket_;

  bool b_socket_initialized_;
};

class DracoData {
public:
  DracoData(){};
  ~DracoData(){};

  // should be matching with protobuf msg
  double time = 0.;
  int phase = 0;

  Eigen::VectorXd task_com_pos = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_com_vel = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_com_pos_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_com_vel_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_com_acc_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_com_local_pos_err = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_com_local_vel_err = Eigen::VectorXd::Zero(3);

  Eigen::VectorXd task_cam_vel = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_cam_vel_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_cam_acc_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_cam_local_vel_err = Eigen::VectorXd::Zero(3);

  Eigen::VectorXd task_torso_ori_pos_des = Eigen::VectorXd::Zero(4);
  Eigen::VectorXd task_torso_ori_vel_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_torso_ori_acc_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_torso_ori_pos = Eigen::VectorXd::Zero(4);
  Eigen::VectorXd task_torso_ori_vel = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_torso_ori_local_pos_err = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_torso_ori_local_vel_err = Eigen::VectorXd::Zero(3);

  Eigen::VectorXd task_rfoot_lin_pos = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_lin_vel = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_lin_pos_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_lin_vel_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_lin_acc_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_lin_local_pos_err = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_lin_local_vel_err = Eigen::VectorXd::Zero(3);

  Eigen::VectorXd task_rfoot_ori_pos_des = Eigen::VectorXd::Zero(4);
  Eigen::VectorXd task_rfoot_ori_vel_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_ori_acc_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_ori_pos = Eigen::VectorXd::Zero(4);
  Eigen::VectorXd task_rfoot_ori_vel = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_ori_local_pos_err = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_rfoot_ori_local_vel_err = Eigen::VectorXd::Zero(3);

  Eigen::VectorXd task_lfoot_lin_pos = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_lin_vel = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_lin_pos_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_lin_vel_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_lin_acc_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_lin_local_pos_err = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_lin_local_vel_err = Eigen::VectorXd::Zero(3);

  Eigen::VectorXd task_lfoot_ori_pos_des = Eigen::VectorXd::Zero(4);
  Eigen::VectorXd task_lfoot_ori_vel_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_ori_acc_des = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_ori_pos = Eigen::VectorXd::Zero(4);
  Eigen::VectorXd task_lfoot_ori_vel = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_ori_local_pos_err = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd task_lfoot_ori_local_vel_err = Eigen::VectorXd::Zero(3);

  Eigen::VectorXd task_upper_body_pos_des = Eigen::VectorXd::Zero(13);
  Eigen::VectorXd task_upper_body_vel_des = Eigen::VectorXd::Zero(13);
  Eigen::VectorXd task_upper_body_acc_des = Eigen::VectorXd::Zero(13);
  Eigen::VectorXd task_upper_body_pos = Eigen::VectorXd::Zero(13);
  Eigen::VectorXd task_upper_body_vel = Eigen::VectorXd::Zero(13);

  // wbc cmd
  Eigen::VectorXd cmd_rfoot_rf = Eigen::VectorXd::Zero(6);
  Eigen::VectorXd cmd_lfoot_rf = Eigen::VectorXd::Zero(6);

  Eigen::VectorXd cmd_joint_positions = Eigen::VectorXd::Zero(27);
  Eigen::VectorXd cmd_joint_velocities = Eigen::VectorXd::Zero(27);
  Eigen::VectorXd cmd_joint_torques = Eigen::VectorXd::Zero(27);
  Eigen::VectorXd joint_velocities = Eigen::VectorXd::Zero(27);

  // for meshcat visualization
  Eigen::VectorXd joint_positions = Eigen::VectorXd::Zero(27);
  Eigen::VectorXd base_joint_pos = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd base_joint_quat = Eigen::VectorXd::Zero(4);

  // filtered data
  Eigen::VectorXd com_vel_est = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd com_vel_raw = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd imu_ang_vel_est = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd imu_ang_vel_raw = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd cam_est = Eigen::VectorXd::Zero(3);
  Eigen::VectorXd cam_raw = Eigen::VectorXd::Zero(3);

  // icp
  Eigen::VectorXd icp = Eigen::VectorXd::Zero(2);
  Eigen::VectorXd icp_des = Eigen::VectorXd::Zero(2);
  Eigen::VectorXd icp_dot = Eigen::VectorXd::Zero(2);
  Eigen::VectorXd icp_dot_des = Eigen::VectorXd::Zero(2);
};

max_stars_repo_name: junhyeokahn/PnC

max_issues_repo_name: junhyeokahn/PnC

max_forks_repo_name: junhyeokahn/PnC


text:
//***************************************************************************
//* Copyright (c) 2016 Saint Petersburg State University
//* All Rights Reserved
//* See file LICENSE for details.
//***************************************************************************

#ifndef __KMER_MAP_HPP__
#define __KMER_MAP_HPP__

#include "sequence/rtseq.hpp"

#include <tsl/htrie_map.h>
#include <boost/iterator/iterator_facade.hpp>

#define XXH_INLINE_ALL
#include "xxh/xxhash.h"

namespace debruijn_graph {
class KMerMap {
    struct str_hash {
        std::size_t operator()(const char* key, std::size_t key_size) const {
            return XXH3_64bits(key, key_size);
        }
    };

    typedef RtSeq Kmer;
    typedef RtSeq Seq;
    typedef typename Seq::DataType RawSeqData;
    typedef typename tsl::htrie_map<char, RawSeqData*, str_hash> HTMap;

    class iterator : public boost::iterator_facade<iterator,
                                                   const std::pair<Kmer, Seq>,
                                                   std::forward_iterator_tag,
                                                   const std::pair<Kmer, Seq>> {
      public:
        iterator(unsigned k, HTMap::const_iterator iter)
                : k_(k), iter_(iter) {}

      private:
        friend class boost::iterator_core_access;

        void increment() {
            ++iter_;
        }

        bool equal(const iterator &other) const {
            return iter_ == other.iter_;
        }

        const std::pair<Kmer, Seq> dereference() const {
            iter_.key(key_out_);
            Kmer k(k_, (const RawSeqData*)key_out_.data());
            Seq s(k_, (const RawSeqData*)iter_.value());
            return std::make_pair(k, s);
        }

        unsigned k_;
        HTMap::const_iterator iter_;
        mutable std::string key_out_;
    };

  public:
    KMerMap(unsigned k)
            : k_(k) {
        rawcnt_ = (unsigned)Seq::GetDataSize(k_);
    }

    ~KMerMap() {
        clear();
    }

    void erase(const Kmer &key) {
        auto res = mapping_.find_ks((const char*)key.data(), rawcnt_ * sizeof(RawSeqData));
        if (res == mapping_.end())
            return;

        delete[] res.value();
        mapping_.erase(res);
    }

    void set(const Kmer &key, const Seq &value) {
        RawSeqData *rawvalue = nullptr;
        auto res = mapping_.find_ks((const char*)key.data(), rawcnt_ * sizeof(RawSeqData));
        if (res == mapping_.end()) {
            rawvalue = new RawSeqData[rawcnt_];
            mapping_.insert_ks((const char*)key.data(), rawcnt_ * sizeof(RawSeqData), rawvalue);
        } else {
            rawvalue = res.value();
        }
        memcpy(rawvalue, value.data(), rawcnt_ * sizeof(RawSeqData));
    }

    bool count(const Kmer &key) const {
        return mapping_.count_ks((const char*)key.data(), rawcnt_ * sizeof(RawSeqData));
    }

    const RawSeqData *find(const Kmer &key) const {
        auto res = mapping_.find_ks((const char*)key.data(), rawcnt_ * sizeof(RawSeqData));
        if (res == mapping_.end())
            return nullptr;

        return res.value();
    }

    const RawSeqData *find(const RawSeqData *key) const {
        auto res = mapping_.find_ks((const char*)key, rawcnt_ * sizeof(RawSeqData));
        if (res == mapping_.end())
            return nullptr;

        return res.value();
    }

    void clear() {
        // Delete all the values
        for (auto it = mapping_.begin(); it != mapping_.end(); ++it) {
            VERIFY(it.value() != nullptr);
            delete[] it.value();
            it.value() = nullptr;
        }

        // Delete the mapping and all the keys
        mapping_.clear();
    }

    size_t size() const {
        return mapping_.size();
    }

    iterator begin() const {
        return iterator(k_, mapping_.begin());
    }

    iterator end() const {
        return iterator(k_, mapping_.end());
    }

  private:
    unsigned k_;
    unsigned rawcnt_;
    HTMap mapping_;
};

}

#endif // __KMER_MAP_HPP__

max_stars_repo_name: STRIDES-Codes/Exploring-the-Microbiome-

max_issues_repo_name: STRIDES-Codes/Exploring-the-Microbiome-

max_forks_repo_name: STRIDES-Codes/Exploring-the-Microbiome-