text:
/**
 * @file
 * @copyright This code is licensed under the 3-clause BSD license.\n
 *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
 *            See LICENSE.txt for details.
 */
#include "Utils/Geometry.h"
#include <Utils/IO/ChemicalFileFormats/ChemicalFileHandler.h>
#include <gmock/gmock.h>
#include <Eigen/Geometry>

using namespace testing;
namespace Scine {
namespace Utils {
using namespace Geometry;
namespace Tests {

/**
 * @class Scine::Utils::Tests::InternalCoordinatesTest InternalCoordinatesTest.cpp
 * @brief Comprises tests for the class Scine::Utils::InternalCoordinates.
 * @test
 */
TEST(InternalCoordinatesTest, Formaldehyde) {
  auto elements = ElementTypeCollection{ElementType::O, ElementType::C, ElementType::H, ElementType::H};
  PositionCollection positions(4, 3);
  // clang-format off
  positions(0,0) = 0.0; positions(0,1) =  0.000000; positions(0,2) = -0.537500;
  positions(1,0) = 0.0; positions(1,1) =  0.000000; positions(1,2) =  0.662500;
  positions(2,0) = 0.0; positions(2,1) =  0.866025; positions(2,2) = -1.037500;
  positions(3,0) = 0.0; positions(3,1) = -0.866025; positions(3,2) = -1.037500;
  // clang-format on
  AtomCollection atoms(elements, positions);
  InternalCoordinates ic(atoms);
  auto internal = ic.coordinatesToInternal(positions);
  auto backtransformed = ic.coordinatesToCartesian(internal);
  for (unsigned int i = 0; i < 4; i++) {
    for (unsigned int j = 0; j < 3; j++) {
      EXPECT_NEAR(positions(i, j), backtransformed(i, j), 1e-9);
    }
  }
}

TEST(InternalCoordinatesTest, Water) {
  auto elements = ElementTypeCollection{ElementType::O, ElementType::H, ElementType::H};
  Eigen::MatrixX3d positions = Eigen::MatrixX3d::Zero(3, 3);
  // clang-format off
  positions(0,0) = 0.0; positions(0,1) = 0.0; positions(0,2) = 0.0;
  positions(1,0) = 0.0; positions(1,1) = 0.0; positions(1,2) = 1.0;
  positions(2,0) = 0.0; positions(2,1) = 1.0; positions(2,2) = 0.0;
  // clang-format on
  AtomCollection atoms(elements, positions);
  InternalCoordinates ic(atoms);
  ASSERT_EQ(3, ic.coordinatesToInternal(positions).size());
}

TEST(InternalCoordinatesTest, HessianGuessForSmallMolecule) {
  auto elements = ElementTypeCollection{ElementType::O, ElementType::H, ElementType::H};
  Eigen::MatrixX3d positions = Eigen::MatrixX3d::Zero(3, 3);
  // clang-format off
  positions(0,0) = 0.0; positions(0,1) = 0.0; positions(0,2) = 0.0;
  positions(1,0) = 0.0; positions(1,1) = 0.0; positions(1,2) = 1.0;
  positions(2,0) = 0.0; positions(2,1) = 1.0; positions(2,2) = 0.0;
  // clang-format on
  AtomCollection atoms(elements, positions);
  InternalCoordinates ic(atoms);
  auto guess = ic.hessianGuess();
  auto invguess = ic.inverseHessianGuess();
  Eigen::MatrixXd ref = Eigen::MatrixXd::Identity(3, 3);
  ASSERT_EQ((guess - ref).sum(), 0.0);
  ASSERT_EQ((invguess - ref).sum(), 0.0);
}

} /* namespace Tests */
} /* namespace Utils */
} /* namespace Scine */

max_stars_repo_name: qcscine/utilities

max_issues_repo_name: qcscine/utilities

max_forks_repo_name: qcscine/utilities


text:
/*!
@file
Defines the @ref group-functional module.

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

#ifndef BOOST_HANA_FUNCTIONAL_HPP
#define BOOST_HANA_FUNCTIONAL_HPP

#include <boost/hana/functional/always.hpp>
#include <boost/hana/functional/apply.hpp>
#include <boost/hana/functional/arg.hpp>
#include <boost/hana/functional/capture.hpp>
#include <boost/hana/functional/compose.hpp>
#include <boost/hana/functional/curry.hpp>
#include <boost/hana/functional/demux.hpp>
#include <boost/hana/functional/fix.hpp>
#include <boost/hana/functional/flip.hpp>
#include <boost/hana/functional/id.hpp>
#include <boost/hana/functional/infix.hpp>
#include <boost/hana/functional/iterate.hpp>
#include <boost/hana/functional/lockstep.hpp>
#include <boost/hana/functional/on.hpp>
#include <boost/hana/functional/overload.hpp>
#include <boost/hana/functional/overload_linearly.hpp>
#include <boost/hana/functional/partial.hpp>
#include <boost/hana/functional/placeholder.hpp>
#include <boost/hana/functional/reverse_partial.hpp>

#endif // !BOOST_HANA_FUNCTIONAL_HPP

ext: hpp

max_stars_repo_name: kindlychung/mediasoup-sfu-cpp

max_issues_repo_name: kindlychung/mediasoup-sfu-cpp

max_forks_repo_name: kindlychung/mediasoup-sfu-cpp


text:
///////////////////////////////////////////////////////////////////////////////
// optimize.hpp
//
//  Copyright 2004 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_XPRESSIVE_DETAIL_CORE_OPTIMIZE_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_CORE_OPTIMIZE_HPP_EAN_10_04_2005

#include <string>
#include <utility>
#include <boost/mpl/bool.hpp>
#include <boost/iterator/iterator_traits.hpp>
#include <boost/xpressive/detail/core/finder.hpp>
#include <boost/xpressive/detail/core/peeker.hpp>
#include <boost/xpressive/detail/core/regex_impl.hpp>
#include <boost/xpressive/detail/utility/hash_peek_bitset.hpp>

namespace boost { namespace xpressive { namespace detail
{

///////////////////////////////////////////////////////////////////////////////
// optimize_regex
//
template<typename BidiIter, typename Traits>
inline void optimize_regex(regex_impl<BidiIter> &impl, Traits const &traits, mpl::true_)
{
    typedef typename iterator_value<BidiIter>::type char_type;

    // optimization: get the peek chars OR the boyer-moore search string
    hash_peek_bitset<char_type> bset;
    xpression_peeker<char_type> peeker(&bset, traits);
    impl.xpr_->peek(peeker);

    // if we have a leading string literal, initialize a boyer-moore struct with it
    std::pair<std::basic_string<char_type> const *, bool> str = peeker.get_string();
    if(0 != str.first)
    {
        impl.finder_.reset
        (
            new boyer_moore_finder<BidiIter, Traits>
            (
                str.first->data()
              , str.first->data() + str.first->size()
              , traits
              , str.second
            )
        );
    }
    else if(peeker.line_start())
    {
        impl.finder_.reset
        (
            new line_start_finder<BidiIter, Traits>(traits)
        );
    }
    else if(256 != bset.count())
    {
        impl.finder_.reset
        (
            new hash_peek_finder<BidiIter, Traits>(bset)
        );
    }
}

///////////////////////////////////////////////////////////////////////////////
// optimize_regex
//
template<typename BidiIter, typename Traits>
inline void optimize_regex(regex_impl<BidiIter> &impl, Traits const &traits, mpl::false_)
{
    typedef typename iterator_value<BidiIter>::type char_type;

    // optimization: get the peek chars OR the line start finder
    hash_peek_bitset<char_type> bset;
    xpression_peeker<char_type> peeker(&bset, traits);
    impl.xpr_->peek(peeker);

    if(peeker.line_start())
    {
        impl.finder_.reset
        (
            new line_start_finder<BidiIter, Traits>(traits)
        );
    }
    else if(256 != bset.count())
    {
        impl.finder_.reset
        (
            new hash_peek_finder<BidiIter, Traits>(bset)
        );
    }
}

}}} // namespace boost::xpressive

#endif


text:
/*
Copyright 2019 Glen Joseph Fernandes
(glenjofe@gmail.com)

Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_CORE_NOINIT_ADAPTOR_HPP
#define BOOST_CORE_NOINIT_ADAPTOR_HPP

#include <boost/config.hpp>
#if !defined(BOOST_NO_CXX11_ALLOCATOR)
#include <memory>
#endif
#include <new>
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
#include <utility>
#endif

namespace boost {

template <class A> struct noinit_adaptor : A {
  template <class U> struct rebind {
#if !defined(BOOST_NO_CXX11_ALLOCATOR)
    typedef noinit_adaptor<
        typename std::allocator_traits<A>::template rebind_alloc<U>>
        other;
#else
    typedef noinit_adaptor<typename A::template rebind<U>::other> other;
#endif
  };

  noinit_adaptor() : A() {}

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
  template <class U>
  noinit_adaptor(U &&u) BOOST_NOEXCEPT : A(std::forward<U>(u)) {}
#else
  template <class U> noinit_adaptor(const U &u) BOOST_NOEXCEPT : A(u) {}
#endif

  template <class U>
  noinit_adaptor(const noinit_adaptor<U> &u) BOOST_NOEXCEPT
      : A(static_cast<const U &>(u)) {}

  template <class U> void construct(U *p) { ::new ((void *)p) U; }

#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
  template <class U, class V, class... Args>
  void construct(U *p, V &&v, Args &&... args) {
    ::new ((void *)p) U(std::forward<V>(v), std::forward<Args>(args)...);
  }
#else
  template <class U, class V> void construct(U *p, V &&v) {
    ::new ((void *)p) U(std::forward<V>(v));
  }
#endif
#else
  template <class U, class V> void construct(U *p, const V &v) {
    ::new ((void *)p) U(v);
  }

  template <class U, class V> void construct(U *p, V &v) {
    ::new ((void *)p) U(v);
  }
#endif

  template <class U> void destroy(U *p) { p->~U(); }
};

template <class T, class U>
inline bool operator==(const noinit_adaptor<T> &lhs,
                       const noinit_adaptor<U> &rhs) BOOST_NOEXCEPT {
  return static_cast<const T &>(lhs) == static_cast<const U &>(rhs);
}

template <class T, class U>
inline bool operator!=(const noinit_adaptor<T> &lhs,
                       const noinit_adaptor<U> &rhs) BOOST_NOEXCEPT {
  return !(lhs == rhs);
}

template <class A>
inline noinit_adaptor<A> noinit_adapt(const A &a) BOOST_NOEXCEPT {
  return noinit_adaptor<A>(a);
}

} // namespace boost

#endif

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
//---------------------------------------------------------------------------//
// Copyright (c) 2014 Fabian Köhler <fabian2804@googlemail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://kylelutz.github.com/compute for more information.
//---------------------------------------------------------------------------//
#define BOOST_TEST_MODULE TestUnsupportedExtension
#include <boost/test/unit_test.hpp>
#include <boost/compute/exception/unsupported_extension_error.hpp>

BOOST_AUTO_TEST_CASE(unsupported_extension_error_what)
{
    boost::compute::unsupported_extension_error error("CL_DUMMY_EXTENSION");
    BOOST_CHECK_EQUAL(std::string(error.what()), std::string("OpenCL extension CL_DUMMY_EXTENSION not supported"));
}

ext: cpp

max_stars_repo_name: bastiankoe/compute

max_issues_repo_name: bastiankoe/compute

max_forks_repo_name: bastiankoe/compute


text:
/*==============================================================================
  Copyright (c) 2017, 2018 Matt Calabrese

  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 ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_HPP_
#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_HPP_

#include <argot/gen/concept_body/detail/expected.hpp>
#include <argot/gen/concept_body/detail/parenthesized_part.hpp>
#include <argot/gen/concept_body/detail/parse_template_parameter_list.hpp>
#include <argot/gen/concept_body/detail/part_in_parentheses.hpp>
#include <argot/gen/concept_body/detail/part_after_parentheses.hpp>
#include <argot/gen/concept_body/detail/result_of_parse.hpp>

#include <boost/preprocessor/control/iif.hpp>
#include <boost/preprocessor/punctuation/is_begin_parens.hpp>
#include <boost/vmd/is_empty.hpp>

// TODO(mattcalabrese) Better failure reporting (i.e. trailing text at end).
// TODO(mattcalabrese) Make version that disallows empty lists.

#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST( ... )    \
BOOST_PP_IIF                                                                   \
( BOOST_PP_IS_BEGIN_PARENS( __VA_ARGS__ )                                      \
, ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_IMPL            \
, ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_FAILURE         \
)( __VA_ARGS__ )

// TODO(mattcalabrese) split at parentheses
#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_IMPL(     \
                                                                           ... \
                                                                         )     \
ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_IMPL_             \
( ARGOT_GEN_DETAIL_PARSE_TEMPLATE_PARAMETER_LIST                               \
  ( ARGOT_GEN_DETAIL_PART_IN_PARENTHESES( __VA_ARGS__ ) )                      \
, ( ARGOT_GEN_DETAIL_PART_AFTER_PARENTHESES( __VA_ARGS__ ) )                   \
)

#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_IMPL_(    \
                                                                  params_parse \
                                                                , remaining    \
                                                                )              \
ARGOT_GEN_DETAIL_VISIT_EXPECTED                                                \
( ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_                \
, params_parse                                                                 \
)( params_parse, remaining )

#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_value(    \
                                                                  params_parse \
                                                                , remaining    \
                                                                )              \
BOOST_PP_IIF                                                                   \
( BOOST_VMD_IS_EMPTY( ARGOT_GEN_DETAIL_GET_REMAINING_TEXT( params_parse ) )    \
, ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_SUCCESS         \
, ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_TRAILING        \
)( params_parse, remaining )

#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_SUCCESS(  \
                                                                  params_parse \
                                                                , remaining    \
                                                                )              \
value( ()                                                                      \
     , parenthesized_template_parameter_list                                   \
       ( ARGOT_GEN_DETAIL_GET_NODE_DATA( params_parse ) )                      \
     , remaining                                                               \
     )

#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_FAILURE(  \
                                                                           ... \
                                                                         )     \
unexpected( soft(), parenthesized_template_parameter_list, ( __VA_ARGS__ ) )

// TODO(mattcalabrese) Make this a hard error
#define ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_TRAILING( \
                                                                  params_parse \
                                                                , remaining    \
                                                                )              \
unexpected                                                                     \
( soft(), parenthesized_template_parameter_list                                \
, ( ( ARGOT_GEN_DETAIL_GET_PARSED_INPUT( params_parse )                        \
      ARGOT_GEN_DETAIL_GET_REMAINING_TEXT( params_parse )                      \
    ) BOOST_PP_TUPLE_ENUM( remaining )                                         \
  )                                                                            \
)

#endif  // ARGOT_GEN_DETAIL_PARSE_PARENTHESIZED_TEMPLATE_PARAMETER_LIST_HPP_

max_stars_repo_name: mattcalabrese/argot

max_issues_repo_name: mattcalabrese/argot

max_forks_repo_name: mattcalabrese/argot


text:
/*******************************************************************************
 * Copyright 2013-2014 Sebastian Niemann <niemann@sra.uni-hannover.de>.
 *
 * Licensed under the MIT License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/MIT
 *
 * Developers:
 *   Sebastian Niemann - Lead developer
 *   Daniel Kiechle - Unit testing
 ******************************************************************************/
#include <Expected.hpp>
using armadilloJava::Expected;

#include <iostream>
using std::cout;
using std::endl;

#include <utility>
using std::pair;

#include <armadillo>
using arma::Mat;

#include <InputClass.hpp>
using armadilloJava::InputClass;

#include <Input.hpp>
using armadilloJava::Input;

namespace armadilloJava {
  class ExpectedInPlaceGenMatRowIndGenDouble : public Expected {
    public:
      ExpectedInPlaceGenMatRowIndGenDouble() {
        cout << "Compute ExpectedInPlaceGenMatRowIndGenDouble(): " << endl;

          vector<vector<pair<string, void*>>> inputs = Input::getTestParameters({
            InputClass::GenMat,
            InputClass::RowInd,
            InputClass::GenDouble
          });

          for (vector<pair<string, void*>> input : inputs) {
            _fileSuffix = "";

            int n = 0;
            for (pair<string, void*> value : input) {
              switch (n) {
                case 0:
                  _fileSuffix += value.first;
                  _genMat = *static_cast<Mat<double>*>(value.second);
                  break;
                case 1:
                  _fileSuffix += "," + value.first;
                  _rowInd = *static_cast<int*>(value.second);
                  break;
                case 2:
                  _fileSuffix += "," + value.first;
                  _genDouble = *static_cast<double*>(value.second);
                  break;
              }
              ++n;
            }

            cout << "Using input: " << _fileSuffix << endl;

            _copyOfGenMat = _genMat;
            _copyOfRowInd = _rowInd;
            _copyOfGenDouble = _genDouble;

            expectedMatDiagPlus();

            _genMat = _copyOfGenMat;
            _rowInd = _copyOfRowInd;
            _genDouble = _copyOfGenDouble;
            expectedMatDiagMinus();

            _genMat = _copyOfGenMat;
            _rowInd = _copyOfRowInd;
            _genDouble = _copyOfGenDouble;
            expectedMatDiagTimes();

            _genMat = _copyOfGenMat;
            _rowInd = _copyOfRowInd;
            _genDouble = _copyOfGenDouble;
            expectedMatDiagDivide();

            _genMat = _copyOfGenMat;
            _rowInd = _copyOfRowInd;
            _genDouble = _copyOfGenDouble;
            expectedMatColPlus();

            _genMat = _copyOfGenMat;
            _rowInd = _copyOfRowInd;
            _genDouble = _copyOfGenDouble;
            expectedMatColMinus();

            _genMat = _copyOfGenMat;
            _rowInd = _copyOfRowInd;
            _genDouble = _copyOfGenDouble;
            expectedMatColTimes();

            _genMat = _copyOfGenMat;
            _rowInd = _copyOfRowInd;
            _genDouble = _copyOfGenDouble;
            expectedMatColDivide();
          }

          cout << "done." << endl;
        }

    protected:
      Mat<double> _genMat;
      Mat<double> _copyOfGenMat;

      int _rowInd;
      int _copyOfRowInd;

      double _genDouble;
      double _copyOfGenDouble;

      void expectedMatDiagPlus() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatDiagPlus() ... ";

        _genMat.diag(-_rowInd) += _genDouble;
        save<double>("Mat.diagSubPlus", _genMat);

        cout << "done." << endl;
      }

      void expectedMatDiagMinus() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatDiagMinus() ... ";

        _genMat.diag(-_rowInd) -= _genDouble;
        save<double>("Mat.diagSubMinus", _genMat);

        cout << "done." << endl;
      }

      void expectedMatDiagTimes() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatDiagTimes() ... ";

        _genMat.diag(-_rowInd) *= _genDouble;
        save<double>("Mat.diagSubTimes", _genMat);

        cout << "done." << endl;
      }

      void expectedMatDiagDivide() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatDiagDivide() ... ";

        _genMat.diag(-_rowInd) /= _genDouble;
        save<double>("Mat.diagSubDivide", _genMat);

        cout << "done." << endl;
      }

      void expectedMatColPlus() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatColPlus() ... ";

        _genMat.row(_rowInd) += _genDouble;
        save<double>("Mat.rowPlus", _genMat);

        cout << "done." << endl;
      }

      void expectedMatColMinus() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatColMinus() ... ";

        _genMat.row(_rowInd) -= _genDouble;
        save<double>("Mat.rowMinus", _genMat);

        cout << "done." << endl;
      }

      void expectedMatColTimes() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatColTimes() ... ";

        _genMat.row(_rowInd) *= _genDouble;
        save<double>("Mat.rowTimes", _genMat);

        cout << "done." << endl;
      }

      void expectedMatColDivide() {
        if(_rowInd >= _genMat.n_rows) {
          return;
        }

        cout << "- Compute expectedMatColDivide() ... ";

        _genMat.row(_rowInd) /= _genDouble;
        save<double>("Mat.rowDivide", _genMat);

        cout << "done." << endl;
      }
  };
}

max_stars_repo_name: sebiniemann/ArmadilloJava

max_issues_repo_name: sebiniemann/ArmadilloJava

max_forks_repo_name: sebiniemann/ArmadilloJava


text:
#include "socks5/detail/sync/io.hpp"
#include "socks5/request.hpp"
#include "socks5/tests/fixtures/socket.hpp"
#include "socks5/tests/util/random.hpp"

#include <boost/asio/read.hpp>
#include <boost/asio/write.hpp>
#include <boost/system/error_code.hpp>
#include <gtest/gtest.h>

#include <algorithm>
#include <cstdint>
#include <vector>

#include <iostream>

namespace socks5::tests {

struct SyncIOTests : socks5::tests::fixtures::SocketTest<true> {
    inline auto random_buffer() const noexcept -> std::vector<std::uint8_t> {
        std::vector<std::uint8_t> ret(socks5::tests::util::random(0, 1024));

        for (auto &b : ret) {
            b = socks5::tests::util::random<std::uint8_t>();
        }

        return ret;
    }

    boost::system::error_code ec;
};

TEST_F(SyncIOTests, WriteTest) {
    std::vector<std::uint8_t> inbuf {random_buffer()};
    std::vector<std::uint8_t> outbuf(inbuf.size());
    std::size_t               tx;

    tx = socks5::detail::sync::write(socket, boost::asio::buffer(inbuf), ec);
    EXPECT_FALSE(ec);
    EXPECT_EQ(tx, inbuf.size());

    tx = boost::asio::read(socket.output_pipe(), boost::asio::buffer(outbuf),
                           ec);
    EXPECT_FALSE(ec);
    EXPECT_TRUE(
        std::equal(inbuf.begin(), inbuf.end(), outbuf.begin(), outbuf.end()));
    EXPECT_EQ(tx, outbuf.size());
}

TEST_F(SyncIOTests, ReadTest) {
    std::vector<std::uint8_t> inbuf {random_buffer()};
    std::vector<std::uint8_t> outbuf(inbuf.size());
    std::size_t               tx;

    tx =
        boost::asio::write(socket.input_pipe(), boost::asio::buffer(inbuf), ec);
    EXPECT_FALSE(ec);
    EXPECT_EQ(tx, inbuf.size());

    tx = socks5::detail::sync::read(socket, boost::asio::buffer(outbuf), ec);
    EXPECT_FALSE(ec);
    EXPECT_TRUE(
        std::equal(inbuf.begin(), inbuf.end(), outbuf.begin(), outbuf.end()));
    EXPECT_EQ(tx, outbuf.size());
}

TEST_F(SyncIOTests, ReadWriteTest) {
    auto buf1 = random_buffer();
    auto buf2 = random_buffer();

    std::vector<std::uint8_t> buf(buf2.size());
    std::size_t               tx;

    tx = boost::asio::write(socket.input_pipe(), boost::asio::buffer(buf2));
    EXPECT_EQ(tx, buf2.size());

    tx = socks5::detail::sync::write_read(socket, boost::asio::buffer(buf1),
                                          boost::asio::buffer(buf), ec);
    EXPECT_FALSE(ec);
    EXPECT_EQ(tx, buf1.size() + buf2.size());
    EXPECT_TRUE(std::equal(buf2.begin(), buf2.end(), buf.begin(), buf.end()));

    buf.resize(buf1.size());
    tx = boost::asio::read(socket.output_pipe(), boost::asio::buffer(buf));
    EXPECT_EQ(tx, buf1.size());
    EXPECT_TRUE(std::equal(buf1.begin(), buf1.end(), buf.begin(), buf.end()));
}

TEST_F(SyncIOTests, SendRequestTest) {
    auto buf = random_buffer();
    auto str = socks5::tests::util::random_string(0xFF);
    auto req = socks5::make_request<5>();

    req.put<std::uint8_t>(socks5::tests::util::random<std::uint8_t>());
    req.put<std::uint16_t>(socks5::tests::util::random<std::uint16_t>());
    req.put<std::uint32_t>(socks5::tests::util::random<std::uint32_t>());
    req.put<std::uint64_t>(socks5::tests::util::random<std::uint64_t>());
    req.put(buf.cbegin(), buf.cend());
    req.put(str);

    auto tx = socks5::detail::sync::send_request(socket, req, ec);
    EXPECT_FALSE(ec);
    EXPECT_EQ(tx, req.size());

    buf.resize(req.size());
    tx = boost::asio::read(socket.output_pipe(), boost::asio::buffer(buf));
    EXPECT_EQ(tx, buf.size());
    EXPECT_TRUE(std::equal(buf.begin(), buf.end(), req.begin(), req.end()));
}

TEST_F(SyncIOTests, ReadResponseTest) {
    auto req = socks5::make_request<5>();
    req.put<std::uint8_t>(socks5::tests::util::random<std::uint8_t>());
    req.put<std::uint16_t>(socks5::tests::util::random<std::uint16_t>());
    req.put<std::uint32_t>(socks5::tests::util::random<std::uint32_t>());
    req.put<std::uint64_t>(socks5::tests::util::random<std::uint64_t>());
    req.put(socks5::tests::util::random_string(0xFF));

    auto tx = boost::asio::write(socket.input_pipe(),
                                 boost::asio::buffer(req.buffer()));
    EXPECT_EQ(tx, req.size());

    socks5::response_fixed<272> resp {};
    socks5::detail::sync::read_response(socket, resp, ec);
    EXPECT_FALSE(ec);
    EXPECT_TRUE(std::equal(resp.begin(), resp.end(), req.begin(), req.end()));
}

TEST_F(SyncIOTests, ReadEndpointTest) {
    boost::asio::ip::tcp::endpoint ep1;

    auto ep2 = socks5::tests::util::random_endpoint();
    auto req = socks5::make_request<5>(ep2.address(), ep2.port());

    std::vector<std::uint8_t> buf {req.begin() + 1, req.end()};
    auto tx = boost::asio::write(socket.input_pipe(), boost::asio::buffer(buf));
    EXPECT_EQ(tx, buf.size());

    socks5::detail::sync::read_endpoint(socket, ep1, ec);
    EXPECT_FALSE(ec);
    EXPECT_EQ(ep1.address(), ep2.address());
    EXPECT_EQ(ep1.port(), ep2.port());
} // namespace socks5::tests

} // namespace socks5::tests


text:
//  Hannibal: partial C++ grammar to parse C++ type information
//  Copyright (c) 2005-2006 Danny Havenith
//
//  Boost.Wave: A Standard compliant C++ preprocessor
//  Copyright (c) 2001-2009 Hartmut Kaiser
//
//  http://www.boost.org/
//
//  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)

#define HANNIBAL_DUMP_PARSE_TREE 1
//#define HANNIBAL_TRACE_DECLARATIONS
//#define BOOST_SPIRIT_DEBUG

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include <boost/spirit/include/classic_ast.hpp>
#include <boost/spirit/include/classic_tree_to_xml.hpp>
#include <boost/program_options.hpp>

///////////////////////////////////////////////////////////////////////////////
//  Include Wave itself
#include <boost/wave.hpp>

///////////////////////////////////////////////////////////////////////////////
// Include the lexer stuff
#include <boost/wave/cpplexer/cpp_lex_token.hpp>    // token class
#include <boost/wave/cpplexer/cpp_lex_iterator.hpp> // lexer class

///////////////////////////////////////////////////////////////////////////////
//  Include the Hannibal grammar
#include "translation_unit_parser.h"
#include "translation_unit_skipper.h"

using std::vector;
using std::string;
namespace po = boost::program_options;

#if HANNIBAL_DUMP_PARSE_TREE != 0
///////////////////////////////////////////////////////////////////////////////
namespace {

    ///////////////////////////////////////////////////////////////////////////
    //  helper routines needed to generate the parse tree XML dump
    typedef boost::wave::cpplexer::lex_token<> token_type;

    token_type::string_type  get_token_id(token_type const &t)
    {
        using namespace boost::wave;
        return get_token_name(token_id(t)); // boost::wave::token_id(t);
    }

    token_type::string_type get_token_value(token_type const &t)
    {
        return t.get_value();
    }

///////////////////////////////////////////////////////////////////////////////
}   // unnamed namespace
#endif

///////////////////////////////////////////////////////////////////////////////
namespace {

    ///////////////////////////////////////////////////////////////////////////
    // Parse the command line for input files and  (system-) include paths
    // Prints usage info if needed.
    // returns true if program should continue, false if program must stop
    bool parse_command_line( int argc, char *argv[], po::variables_map &vm)
    {
        //
        // Setup command line structure
        po::options_description visible("Usage: hannibal [options] file");
        visible.add_options()
                ("help,h", "show this help message")
                ("include,I", po::value<vector<string> >(),
                    "specify additional include directory")
                ("sysinclude,S", po::value<vector<string> >(),
                    "specify additional system include directory")
                ("define,D", po::value<vector<string> >()->composing(),
                    "specify a macro to define (as macro[=[value]])")
                ("predefine,P", po::value<vector<string> >()->composing(),
                    "specify a macro to predefine (as macro[=[value]])")
                ("undefine,U", po::value<vector<string> >()->composing(),
                    "specify a macro to undefine")
            ;

        po::options_description hidden;
        hidden.add_options()
            ("input-file", "input file");

        po::options_description desc;
        desc.add( visible).add( hidden);

        po::positional_options_description p;
        p.add("input-file", 1);

        //
        // Parse
        po::store(po::command_line_parser(argc, argv).
                options(desc).positional(p).run(), vm);
        po::notify(vm);

        //
        // Print usage, if necessary
        if (!vm.count( "input-file") ||  vm.count( "help"))
        {
            std::cout << visible << std::endl;
            return false;
        }
        else
        {
            return true;
        }
    }

///////////////////////////////////////////////////////////////////////////////
}   // unnamed namespace

///////////////////////////////////////////////////////////////////////////////
// main entry point
int main(int argc, char *argv[])
{
    po::variables_map vm;

    if (!parse_command_line( argc, argv, vm))
    {
        return -1;
    }

   string inputfile = vm["input-file"].as< string>();

// current file position is saved for exception handling
boost::wave::util::file_position_type current_position;

    try {
    //  Open and read in the specified input file.
        std::ifstream instream( inputfile.c_str());
        std::string instring;

        if (!instream.is_open()) {
            std::cerr << "Hannibal: could not open input file: " << inputfile
                      << std::endl;
            return -2;
        }
        instream.unsetf(std::ios::skipws);
        instring = std::string(std::istreambuf_iterator<char>(instream.rdbuf()),
                               std::istreambuf_iterator<char>());

    //  The template boost::wave::cpplexer::lex_token<> is the token type to be
    //  used by the Wave library.
        typedef boost::wave::cpplexer::lex_token<> token_type;

    //  The template boost::wave::cpplexer::lex_iterator<> is the lexer type to
    //  be used by the Wave library.
        typedef boost::wave::cpplexer::lex_iterator<token_type> lex_iterator_type;

    //  This is the resulting context type to use. The first template parameter
    //  should match the iterator type to be used during construction of the
    //  corresponding context object (see below).
        typedef boost::wave::context<
                std::string::iterator,
                lex_iterator_type,
                boost::wave::iteration_context_policies::load_file_to_string
            > context_type;

    // The preprocessor iterator shouldn't be constructed directly. It is
    // to be generated through a wave::context<> object. This wave:context<>
    // object is to be used additionally to initialize and define different
    // parameters of the actual preprocessing (not done here).
    //
    // The preprocessing of the input stream is done on the fly behind the
    // scenes during iteration over the context_type::iterator_type stream.
    context_type ctx (instring.begin(), instring.end(), inputfile.c_str());

    // add include directories to the include path
        if (vm.count("include")) {
            vector<string> const &paths =
                vm["include"].as<vector<string> >();
            vector<string>::const_iterator end = paths.end();
            for (vector<string>::const_iterator cit = paths.begin();
                cit != end; ++cit)
            {
                ctx.add_include_path((*cit).c_str());
            }
        }

    // add system include directories to the include path
        if (vm.count("sysinclude")) {
            vector<string> const &syspaths =
                vm["sysinclude"].as<vector<string> >();
            vector<string>::const_iterator end = syspaths.end();
            for (vector<string>::const_iterator cit = syspaths.begin();
                cit != end; ++cit)
            {
                ctx.add_sysinclude_path((*cit).c_str());
            }
        }

    // add additional defined macros
        if (vm.count("define")) {
            vector<string> const &macros = vm["define"].as<vector<string> >();
            vector<string>::const_iterator end = macros.end();
            for (vector<string>::const_iterator cit = macros.begin();
                 cit != end; ++cit)
            {
                ctx.add_macro_definition(*cit);
            }
        }

    // add additional predefined macros
        if (vm.count("predefine")) {
            vector<string> const &predefmacros =
                vm["predefine"].as<vector<string> >();
            vector<string>::const_iterator end = predefmacros.end();
            for (vector<string>::const_iterator cit = predefmacros.begin();
                 cit != end; ++cit)
            {
                ctx.add_macro_definition(*cit, true);
            }
        }

    // undefine specified macros
        if (vm.count("undefine")) {
            vector<string> const &undefmacros =
                vm["undefine"].as<vector<string> >();
            vector<string>::const_iterator end = undefmacros.end();
            for (vector<string>::const_iterator cit = undefmacros.begin();
                 cit != end; ++cit)
            {
                ctx.remove_macro_definition((*cit).c_str(), true);
            }
        }

    // analyze the input file
    context_type::iterator_type first = ctx.begin();
    context_type::iterator_type last = ctx.end();

    translation_unit_skipper s;

#if HANNIBAL_DUMP_PARSE_TREE != 0
    typedef boost::spirit::classic::tree_parse_info<context_type::iterator_type>
        result_type;
    translation_unit_grammar::rule_map_type rule_map;
    translation_unit_grammar g(&rule_map);

    // parse the input file
    result_type pi = boost::spirit::classic::ast_parse(first, last, g, s);
#else
    typedef boost::spirit::classic::parse_info<context_type::iterator_type>
        result_type;
    translation_unit_grammar g;

    // parse the input file
    result_type pi = boost::spirit::classic::parse(first, last, g, s);
#endif

        if (pi.full) {
            std::cout
                << "Hannibal: parsed sucessfully: " << inputfile << std::endl;

#if HANNIBAL_DUMP_PARSE_TREE != 0
            // generate xml dump from parse tree, if requested
            boost::spirit::classic::tree_to_xml(std::cerr, pi.trees, "", rule_map,
                &get_token_id, &get_token_value);
#endif
        }
        else {
            std::cerr
                << "Hannibal: parsing failed: " << inputfile << std::endl;
            std::cerr
                << "Hannibal: last recognized token was: "
                << get_token_id(*pi.stop) << std::endl;

            using boost::wave::util::file_position_type;
            file_position_type const& pos(pi.stop->get_position());
            std::cerr
                << "Hannibal: at: " << pos.get_file() << "(" << pos.get_line()
                << "," << pos.get_column() << ")" << std::endl;
            return 1;
        }
    }
    catch (boost::wave::cpp_exception const& e) {
    // some preprocessing error
        std::cerr
            << e.file_name() << ":" << e.line_no() << ":" << e.column_no()
            << ": " << e.description() << std::endl;
        return 2;
    }
    catch (boost::wave::cpplexer::lexing_exception const& e) {
    // some lexing error
        std::cerr
            << e.file_name() << ":" << e.line_no() << ":" << e.column_no()
            << ": " << e.description() << std::endl;
        return 2;
    }
    catch (std::exception const& e) {
    // use last recognized token to retrieve the error position
        std::cerr
            << current_position.get_file()
            << "(" << current_position.get_line() << "): "
            << "exception caught: " << e.what()
            << std::endl;
        return 3;
    }
    catch (...) {
    // use last recognized token to retrieve the error position
        std::cerr
            << current_position.get_file()
            << "(" << current_position.get_line() << "): "
            << "unexpected exception caught." << std::endl;
        return 4;
    }
    return 0;
}

max_stars_repo_name: boost-cmake/vintage

max_issues_repo_name: boost-cmake/vintage

max_forks_repo_name: boost-cmake/vintage


text:
#pragma once

#include "../../util/assert.hh"
#include "../../util/meta.hh"

#include <Eigen/Core>
#include <stdexcept>
#include <sstream>

namespace bold
{
  template<typename T,int dim>
  struct LineSegment : Eigen::Matrix<T,dim,2>
  {
  public:
    typedef Eigen::Matrix<T,dim,2> Base;
    typedef Eigen::Matrix<T,dim,1> PointType;

    template<typename OtherDerived>
    LineSegment(Eigen::MatrixBase<OtherDerived> const& other)
      :  Base(other)
    {}

    LineSegment(PointType const& p1,
                PointType const& p2)
    {
      static_assert(std::is_arithmetic<T>::value, "Must be an arithmetic type");

      this->col(0) = p1;
      this->col(1) = p2;

      ASSERT((p2 - p1).cwiseAbs().maxCoeff() != 0);
    }

    template<typename OtherDerived>
    LineSegment& operator=(Eigen::MatrixBase<OtherDerived> const& other)
    {
      this->Base::operator=(other);
      return *this;
    }

    PointType p1() const { return this->col(0); }
    PointType p2() const { return this->col(1); }

    /** Returns the vector formed by p2() - p1() */
    PointType delta() const { return p2() - p1(); }

    /** Returns the vector formed by (p2() + p1()) / 2.0 */
    PointType mid() const { return (p2() + p1()) / 2.0; }

    T length() const { return delta().norm(); }

    double normalisedDot(LineSegment<T,dim> other) const
    {
      return delta().normalized().dot( other.delta().normalized() );
    }

    /** Calculate the smallest angle between the two line segments.
     *
     * The output will be between 0 and PI/2, inclusive.
     */
    double smallestAngleBetween(LineSegment<T,dim> other)
    {
      auto a = fabs(acos(normalisedDot(other)));
      if (a >= M_PI/2)
        a = M_PI - a;
      return a;
    }

    template<int newDim>
    LineSegment<T,newDim> to() const
    {
      auto newLineSegment = LineSegment<T,newDim>{LineSegment<T,newDim>::Zero()};
      newLineSegment.col(0).template head< meta::min<dim,newDim>::value >() =
        this->col(0).template head< meta::min<dim,newDim>::value >();
      newLineSegment.col(1).template head< meta::min<dim,newDim>::value >() =
        this->col(1).template head< meta::min<dim,newDim>::value >();
      return newLineSegment;
    }

    bool operator==(LineSegment<T,dim> const& other) const
    {
      const double epsilon = 0.0000004;
      return (this->array() - other.array()).abs().sum() < epsilon;
    }

    LineSegment<T,dim> operator+(PointType const& delta) const
    {
      return LineSegment<T,dim>{this->colwise() + delta};
    }

    LineSegment<T,dim> operator-(PointType const& delta) const
    {
      return LineSegment<T,dim>{this->colwise() - delta};
    }

    friend std::ostream& operator<<(std::ostream& stream, LineSegment<T,dim> const& lineSegment)
    {
      return stream << "LineSegment (P1=" << lineSegment.p1().transpose() << " P2=" << lineSegment.p2().transpose() << ")";
    }

  };

  typedef LineSegment<double,3> LineSegment3d;
  typedef LineSegment<int,3> LineSegment3i;
}

ext: hh

max_stars_repo_name: drewnoakes/bold-humanoid

max_issues_repo_name: drewnoakes/bold-humanoid

max_forks_repo_name: drewnoakes/bold-humanoid


text:
// Copyright Abel Sinkovics (abel@sinkovics.hu) 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)

#define BOOST_TEST_MODULE string

#define BOOST_METAPARSE_LIMIT_STRING_SIZE 64

#include <boost/metaparse/string.hpp>

#include <boost/mpl/equal.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/char.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/back.hpp>
#include <boost/mpl/begin_end.hpp>
#include <boost/mpl/deref.hpp>
#include <boost/mpl/advance.hpp>
#include <boost/mpl/next.hpp>
#include <boost/mpl/prior.hpp>
#include <boost/mpl/distance.hpp>
#include <boost/mpl/clear.hpp>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/is_sequence.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/pop_back.hpp>
#include <boost/mpl/push_front.hpp>
#include <boost/mpl/push_back.hpp>
#include <boost/mpl/string.hpp>
#include <boost/mpl/assert.hpp>

#include <boost/test/unit_test.hpp>

#include <string>

BOOST_AUTO_TEST_CASE(test_string)
{
  using boost::mpl::equal;
  using boost::mpl::equal_to;
  using boost::mpl::char_;
  using boost::mpl::int_;
  using boost::mpl::at;
  using boost::mpl::at_c;
  using boost::mpl::size;
  using boost::mpl::back;
  using boost::mpl::deref;
  using boost::mpl::advance;
  using boost::mpl::next;
  using boost::mpl::prior;
  using boost::mpl::distance;
  using boost::mpl::clear;
  using boost::mpl::empty;
  using boost::mpl::front;
  using boost::mpl::is_sequence;
  using boost::mpl::pop_front;
  using boost::mpl::pop_back;
  using boost::mpl::begin;
  using boost::mpl::end;
  using boost::mpl::c_str;
  using boost::mpl::push_front;
  using boost::mpl::push_back;

  using namespace boost;

  // string type
  ///////////////////////

  typedef metaparse::string<'H','e','l','l','o'> hello;
  typedef metaparse::string<> empty_string;

  typedef begin<hello>::type begin_hello;
  typedef end<hello>::type end_hello;

  // test_value_of_empty_string
  BOOST_REQUIRE_EQUAL(std::string(), c_str<empty_string>::type::value);

  // test_value
  BOOST_REQUIRE_EQUAL(std::string("Hello"), c_str<hello>::type::value);

  // equal_to
  BOOST_MPL_ASSERT((equal_to<hello, hello>));
  BOOST_MPL_ASSERT_NOT((equal_to<hello, empty_string>));

  // at
  BOOST_MPL_ASSERT((equal_to<char_<'e'>, at<hello, int_<1> >::type>));
  BOOST_MPL_ASSERT((equal_to<char_<'e'>, at_c<hello, 1>::type>));

  // size
  BOOST_MPL_ASSERT((equal_to<int_<5>, size<hello>::type>));

  // is_sequence
  BOOST_MPL_ASSERT((is_sequence<hello>));

  // front
  BOOST_MPL_ASSERT((equal_to<char_<'H'>, front<hello>::type>));

  // push_front
  BOOST_MPL_ASSERT((
    equal_to<
      metaparse::string<'x','H','e','l','l','o'>,
      push_front<hello, char_<'x'> >::type
    >
  ));

  // back
  BOOST_MPL_ASSERT((equal_to<char_<'o'>, back<hello>::type>));

  // push_back
  BOOST_MPL_ASSERT((
    equal_to<
      metaparse::string<'H','e','l','l','o', 'x'>,
      push_back<hello, char_<'x'> >::type
    >
  ));

  // clear
  BOOST_MPL_ASSERT((equal_to<empty_string, clear<hello>::type>));

  // empty
  BOOST_MPL_ASSERT_NOT((empty<hello>::type));
  BOOST_MPL_ASSERT((empty<empty_string>::type));

  // string_iterator
  BOOST_MPL_ASSERT((equal_to<begin_hello, begin_hello>));
  BOOST_MPL_ASSERT_NOT((equal_to<begin_hello, end_hello>));
  BOOST_MPL_ASSERT((
    equal_to<begin<empty_string>::type, end<empty_string>::type>
  ));

  BOOST_MPL_ASSERT((equal_to<char_<'H'>, deref<begin_hello>::type>));
  BOOST_MPL_ASSERT((equal_to<end_hello, advance<begin_hello, int_<5> >::type>));
  BOOST_MPL_ASSERT((
    equal_to<char_<'e'>, deref<next<begin_hello>::type>::type>
  ));
  BOOST_MPL_ASSERT((equal_to<char_<'o'>, deref<prior<end_hello>::type>::type>));

  BOOST_MPL_ASSERT((equal_to<int_<5>, distance<begin_hello, end_hello>::type>));

  // pop_front
  BOOST_MPL_ASSERT((
    equal_to<metaparse::string<'e','l','l','o'>, pop_front<hello>::type>
  ));

  // pop_back
  BOOST_MPL_ASSERT((
    equal_to<metaparse::string<'H','e','l','l'>, pop_back<hello>::type>
  ));

#ifndef BOOST_NO_CONSTEXPR
  // BOOST_METAPARSE_STRING macro
  ///////////////////////

  // test_empty_string
  BOOST_MPL_ASSERT((equal<BOOST_METAPARSE_STRING(""), empty_string>));

  // test_string_creation
  BOOST_MPL_ASSERT((equal<BOOST_METAPARSE_STRING("Hello"), hello>));
#endif

}

max_stars_repo_name: lijgame/boost

max_issues_repo_name: nxplatform/nx-mobile

max_forks_repo_name: nxplatform/nx-mobile


text:
////////////////////////////////////////////////////////////////////////////
// lazy_list2_tests.cpp
//
// more tests on list<T>
//
////////////////////////////////////////////////////////////////////////////
/*=============================================================================
    Copyright (c) 2000-2003 Brian McNamara and Yannis Smaragdakis
    Copyright (c) 2001-2007 Joel de Guzman
    Copyright (c) 2015 John Fletcher

    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/phoenix/core/limits.hpp>

#include <boost/detail/lightweight_test.hpp>
#include <boost/phoenix/core.hpp>
#include <boost/phoenix/function/lazy_prelude.hpp>

int main()
{
    namespace phx = boost::phoenix;
    using boost::phoenix::arg_names::arg1;
    using boost::phoenix::arg_names::arg2;
    using namespace phx;

    list<int> l0;
    list<int> l1 = list_with<>()(1,2,3,4,5);
    list<int> l2 = all_but_last(l1)();

    BOOST_TEST(null(l0)());
    BOOST_TEST(head(l1)()       == 1);
    BOOST_TEST(head(tail(l1))() == 2);
    BOOST_TEST(last(l1)()       == 5);
    BOOST_TEST(last(l2)()       == 4);
    BOOST_TEST(head(drop(2,l2))() == 3);

    return boost::report_errors();
}


text: #include <boost/type_traits/has_modulus_assign.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
// Copyright (c) 2012-2018 Dano Pernis
// See LICENSE for details

#include "hcc/assembler/asm.h"
#include "hcc/jack/ast.h"
#include "hcc/jack/parser.h"
#include "hcc/jack/tokenizer.h"
#include "hcc/ssa/ssa.h"
#include "hcc/vm/parser.h"
#include "hcc/vm/optimize.h"
#include "hcc/vm/writer.h"
#include <boost/algorithm/string/join.hpp>
#include <fstream>
#include <iostream>
#include <sstream>
#include <stdexcept>

bool ends_with(const std::string& value, const std::string& suffix)
{
    if (suffix.size() > value.size()) {
        return false;
    }
    return std::equal(suffix.rbegin(), suffix.rend(), value.rbegin());
}

struct command_line_options {
    command_line_options(int argc, char* argv[])
    {
        opterr = 0;
        int opt = -1;
        while ((opt = getopt(argc, argv, ":ho:S")) != -1) {
            switch (opt) {
            case 'h':
                help = true;
                break;
            case 'o':
                output = optarg;
                break;
            case 'S':
                assemble = false;
                break;
            case '?':
                throw std::runtime_error(std::string("Unknown command line option: ")
                                         + static_cast<char>(optopt));
            case ':':
                throw std::runtime_error(std::string("Missing argument for command line option: ")
                                         + static_cast<char>(optopt));
            }
        }
        while (optind < argc) {
            std::string input_file = argv[optind++];
            if (ends_with(input_file, ".jack")) {
                jack_input_files.emplace_back(input_file);
            } else if (ends_with(input_file, ".asm")) {
                asm_input_files.emplace_back(input_file);
            } else if (ends_with(input_file, ".vm")) {
                vm_input_files.emplace_back(input_file);
            } else {
                throw std::runtime_error("Input file has unknown suffix: " + input_file);
            }
        }

        const auto all_empty = jack_input_files.empty() && asm_input_files.empty()
                               && vm_input_files.empty();
        if (all_empty && !help) {
            throw std::runtime_error("Missing input file(s)");
        }

        // Until we get linker working, we have to impose some constraints
        if (asm_input_files.size() > 1) {
            throw std::runtime_error("More than one asm input file");
        }
        if (!asm_input_files.empty() && !jack_input_files.empty()) {
            throw std::runtime_error("Mixing jack and asm input files");
        }
        if (!jack_input_files.empty() && !vm_input_files.empty()) {
            throw std::runtime_error("Mixing jack and vm input files");
        }
        if (!vm_input_files.empty() && !asm_input_files.empty()) {
            throw std::runtime_error("Mixing vm and asm input files");
        }

        if (output.empty()) {
            if (assemble) {
                output = "output.hack";
            } else {
                output = "output.asm";
            }
        }
    }

    void print_help() const
    {
        std::cout << "Usage: hcc [options] file...\n"
                     "Options:\n"
                     "  -h                   Display this information\n"
                     "  -o <file>            Place the output into <file>\n"
                     "  -S                   Compile only; do not assemble\n";
    }

    bool help{false};
    bool assemble{true};
    std::string output;
    std::vector<std::string> jack_input_files;
    std::vector<std::string> asm_input_files;
    std::vector<std::string> vm_input_files;
};

void jack_to_asm(const std::vector<std::string>& jack_input_files, hcc::assembler::program& out)
{
    if (jack_input_files.empty()) {
        return;
    }

    // parse input
    std::vector<hcc::jack::Class> classes;
    try {
        for (const auto& input_file : jack_input_files) {
            std::ifstream input{input_file};
            hcc::jack::tokenizer t{std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
            classes.push_back(parse(t));
        }
    }
    catch (const hcc::jack::parse_error& e) {
        std::stringstream ss;
        ss << "Parse error: " << e.what() << " at " << e.line << ":" << e.column;
        throw std::runtime_error(ss.str());
    }

    // produce intermediate code
    hcc::ssa::unit u;
    for (const auto& class_ : classes) {
        u.translate_from_jack(class_);
    }

    // optimize
    for (auto& subroutine_entry : u.subroutines) {
        auto& subroutine = subroutine_entry.second;
        subroutine.dead_code_elimination();
        subroutine.copy_propagation();
        subroutine.dead_code_elimination();
        subroutine.ssa_deconstruct();
        subroutine.allocate_registers();
    }

    u.translate_to_asm(out);
}

void vm_to_asm(const std::vector<std::string>& vm_input_files, hcc::assembler::program& out)
{
    if (vm_input_files.empty()) {
        return;
    }

    hcc::vm::writer writer(out);
    writer.writeBootstrap();
    for (const auto& input_file : vm_input_files) {
        std::ifstream input{input_file.c_str()};
        hcc::vm::parser parser{input};
        auto cmds = parser.parse();
        hcc::vm::optimize(cmds);
        writer.writeFile(input_file, cmds);
    }
}

void asm_to_asm(const std::vector<std::string>& asm_input_files, hcc::assembler::program& out)
{
    if (asm_input_files.empty()) {
        return;
    }

    for (const auto& input_file : asm_input_files) {
        std::ifstream input_stream{input_file};
        hcc::assembler::program prog{input_stream};
        out = prog;
    }
}

int main(int argc, char* argv[]) try {
    const command_line_options options{argc, argv};
    if (options.help) {
        options.print_help();
        return 0;
    }

    hcc::assembler::program out;
    jack_to_asm(options.jack_input_files, out);
    asm_to_asm(options.asm_input_files, out);
    vm_to_asm(options.vm_input_files, out);
    out.local_optimization();

    // output
    if (options.assemble) {
        hcc::assembler::saveHACK(options.output, out.assemble());
    } else {
        out.save(options.output);
    }

    return 0;
}
catch (const std::runtime_error& e) {
    std::cerr << "When executing "
              << boost::algorithm::join(std::vector<std::string>(argv, argv + argc), " ")
              << " ...\n" << e.what() << "\n";
    return 1;
}

ext: cc

max_stars_repo_name: danopernis/hcc

max_issues_repo_name: danopernis/hcc

max_forks_repo_name: danopernis/hcc


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

  @copyright 2015 NumScale SAS
  @copyright 2015 J.T. Lapreste

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

#ifndef BOOST_SIMD_NO_INVALIDS
#include <boost/simd/constant/nan.hpp>
#include <boost/simd/function/scalar/is_nan.hpp>
#endif
#include <boost/simd/arch/common/detail/generic/expm1_kernel.hpp>
#include <boost/simd/constant/inf.hpp>
#include <boost/simd/constant/logeps.hpp>
#include <boost/simd/constant/maxlog.hpp>
#include <boost/simd/constant/mone.hpp>
#include <boost/simd/function/scalar/is_greater.hpp>
#include <boost/simd/function/scalar/is_less.hpp>
#include <boost/dispatch/function/overload.hpp>
#include <boost/config.hpp>
#include <cmath>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  namespace bs = boost::simd;
  BOOST_DISPATCH_OVERLOAD ( expm1_
                          , (typename A0)
                          , bd::cpu_
                          , bd::generic_< bd::floating_<A0> >
                          )
  {
    BOOST_FORCEINLINE A0 operator() (A0 a0) const BOOST_NOEXCEPT
    {
    #ifndef BOOST_SIMD_NO_INVALIDS
      if(is_nan(a0)) return Nan<A0>();
    #endif
      if((a0 < Logeps<A0>())) return Mone<A0>();
      if((a0 > Maxlog<A0>())) return  Inf<A0>();
      return detail::expm1_kernel<A0>::expm1(a0);
    }
  };

  BOOST_DISPATCH_OVERLOAD ( expm1_
                          , (typename A0)
                          , bd::cpu_
                          , bd::scalar_< bd::floating_<A0> >
                          , bs::std_tag
                          )
  {
    BOOST_FORCEINLINE A0 operator() (A0 a0, std_tag const&) const BOOST_NOEXCEPT
    {
      return std::expm1(a0);
    }
  };
} } }

#endif


text:
//
// keyvi - A key value store.
//
// Copyright 2015 Hendrik Muhs<hendrik.muhs@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

/*
 * dictionary_compiler_test.cpp
 *
 *  Created on: Jul 23, 2014
 *      Author: hendrik
 */

#include <boost/test/unit_test.hpp>

#include "dictionary/dictionary_compiler.h"
#include "dictionary/dictionary.h"
#include "dictionary/fsa/automata.h"
#include "dictionary/fsa/internal/sparse_array_persistence.h"
#include "dictionary/fsa/internal/int_value_store.h"
#include "dictionary/fsa/internal/json_value_store.h"
#include "dictionary/fsa/entry_iterator.h"

namespace keyvi {
namespace dictionary {

BOOST_AUTO_TEST_SUITE( DictionaryCompilerTests )

class DCTTestHelper final{
 public:
  static uint32_t GetStateIdForPrefix(const fsa::automata_t& fsa, std::string& query)
{

  uint32_t state = fsa->GetStartState();
  size_t depth = 0;
  size_t query_length = query.size();

  while (state != 0 && depth != query_length) {
          state = fsa->TryWalkTransition(state, query[depth]);
          ++depth;
        }

  return state;
}
};

typedef boost::mpl::list<sort::InMemorySorter<key_value_t>, sort::TpieSorter<key_value_t>> sorter_types;

BOOST_AUTO_TEST_CASE_TEMPLATE( minimizationIntInnerWeights, SorterT, sorter_types )
{
  // simulating  permutation
  std::vector<std::pair<std::string, uint32_t>> test_data = {
    { "fb#fb msg downl de", 22 },
    { "msg#fb msg downl de", 22 },
    { "downl#fb msg downl de", 22 },
    { "de#fb msg downl de", 22 },

    { "fb msg#fb msg downl de", 22 },
    { "fb downl#fb msg downl de", 22 },
    { "fb de#fb msg downl de", 22 },

    { "msg fb#fb msg downl de", 22 },
    { "msg downl#fb msg downl de", 22 },
    { "msg de#fb msg downl de", 22 },

    { "downl fb#fb msg downl de", 22 },
    { "downl msg#fb msg downl de", 22 },
    { "downl de#fb msg downl de", 22 },

    { "de fb#fb msg downl de", 22 },
    { "de msg#fb msg downl de", 22 },
    { "de downl#fb msg downl de", 22 },
  };

  keyvi::dictionary::DictionaryCompiler<
      fsa::internal::SparseArrayPersistence<>,
      fsa::internal::IntValueStoreWithInnerWeights,
      SorterT> compiler;

  for (auto p: test_data){
    compiler.Add(p.first, p.second);
  }
  compiler.Compile();

  boost::filesystem::path temp_path =
      boost::filesystem::temp_directory_path();

  temp_path /= boost::filesystem::unique_path(
      "dictionary-unit-test-dictionarycompiler-%%%%-%%%%-%%%%-%%%%");
  std::string file_name = temp_path.native();

  compiler.WriteToFile(file_name);

  Dictionary d(file_name.c_str());
  fsa::automata_t a = d.GetFsa();

  std::string reference_value ("de#");
  uint32_t reference_weight = DCTTestHelper::GetStateIdForPrefix(a,reference_value);

  std::vector<std::string> query_data = {
      "fb#", "msg#", "downl#",
      "fb msg#", "fb downl#",
      "downl fb#", "downl de#"
  };
  std::cout << "test "<< std::endl;

  int tested_values = 0;
  for (auto q: query_data){
    std::cout << "test "<<q<<std::endl;
    BOOST_CHECK(reference_weight == DCTTestHelper::GetStateIdForPrefix(a, q));
    ++tested_values;
  }

  BOOST_CHECK(tested_values == query_data.size());
  std::remove(file_name.c_str());
}

BOOST_AUTO_TEST_CASE_TEMPLATE( sortOrder, SorterT, sorter_types )
{
  // simulating  permutation
  std::vector<std::pair<std::string, uint32_t>> test_data = {
    { "uboot", 22 },
    { "überfall", 33 },
    { "vielleicht", 43 },
    { "arbeit", 3 },
    { "zoo", 5 },
    { "ändern", 6 },
  };

  keyvi::dictionary::DictionaryCompiler<
      fsa::internal::SparseArrayPersistence<>,
      fsa::internal::IntValueStoreWithInnerWeights,
      SorterT> compiler;

  for (auto p: test_data){
    compiler.Add(p.first, p.second);
  }
  compiler.Compile();

  boost::filesystem::path temp_path =
      boost::filesystem::temp_directory_path();

  temp_path /= boost::filesystem::unique_path(
      "dictionary-unit-test-dictionarycompiler-%%%%-%%%%-%%%%-%%%%");
  std::string file_name = temp_path.native();

  compiler.WriteToFile(file_name);

  Dictionary d(file_name.c_str());

  fsa::automata_t f(d.GetFsa());

  fsa::EntryIterator it(f);
  fsa::EntryIterator end_it;

  std::stringstream ss;

  BOOST_CHECK_EQUAL("arbeit", it.GetKey());
  it.WriteKey(ss);
  BOOST_CHECK_EQUAL("arbeit", ss.str());
  ss.str("");
  ss.clear();
  ++it;
  BOOST_CHECK_EQUAL("uboot", it.GetKey());
  it.WriteKey(ss);
  BOOST_CHECK_EQUAL("uboot", ss.str());
  ss.str("");
  ss.clear();

  ++it;
  BOOST_CHECK_EQUAL("vielleicht", it.GetKey());
  it.WriteKey(ss);
  BOOST_CHECK_EQUAL("vielleicht", ss.str());
  ss.str("");
  ss.clear();

  ++it;
  BOOST_CHECK_EQUAL("zoo", it.GetKey());
  it.WriteKey(ss);
  BOOST_CHECK_EQUAL("zoo", ss.str());
  ss.str("");
  ss.clear();

  ++it;
  BOOST_CHECK_EQUAL("ändern", it.GetKey());
  it.WriteKey(ss);
  BOOST_CHECK_EQUAL("ändern", ss.str());
  ss.str("");
  ss.clear();

  ++it;
  BOOST_CHECK_EQUAL("überfall", it.GetKey());
  it.WriteKey(ss);
  BOOST_CHECK_EQUAL("überfall", ss.str());
  ss.str("");
  ss.clear();

  ++it;
  BOOST_CHECK(it == end_it);

  std::remove(file_name.c_str());
}

BOOST_AUTO_TEST_CASE_TEMPLATE( compactSize, SorterT, sorter_types )
{
  // simulating  permutation
  std::vector<std::pair<std::string, uint32_t>> test_data = {
    { "uboot", 22 },
    { "überfall", 33 },
    { "vielleicht", 43 },
    { "arbeit", 3 },
    { "zoo", 5 },
    { "ändern", 6 },
  };

  keyvi::dictionary::DictionaryCompiler<
      fsa::internal::SparseArrayPersistence<uint16_t>,
      fsa::internal::IntValueStoreWithInnerWeights,
      SorterT> compiler;

  for (auto p: test_data){
    compiler.Add(p.first, p.second);
  }
  compiler.Compile();

  boost::filesystem::path temp_path =
      boost::filesystem::temp_directory_path();

  temp_path /= boost::filesystem::unique_path(
      "dictionary-unit-test-dictionarycompiler-%%%%-%%%%-%%%%-%%%%");
  std::string file_name = temp_path.native();

  compiler.WriteToFile(file_name);

  Dictionary d(file_name.c_str());

  fsa::automata_t f(d.GetFsa());

  fsa::EntryIterator it(f);
  fsa::EntryIterator end_it;

  BOOST_CHECK_EQUAL("arbeit", it.GetKey());
  ++it;
  BOOST_CHECK_EQUAL("uboot", it.GetKey());
  ++it;
  BOOST_CHECK_EQUAL("vielleicht", it.GetKey());
  ++it;
  BOOST_CHECK_EQUAL("zoo", it.GetKey());
  ++it;
  BOOST_CHECK_EQUAL("ändern", it.GetKey());
  ++it;
  BOOST_CHECK_EQUAL("überfall", it.GetKey());
  ++it;
  BOOST_CHECK(it == end_it);
}

BOOST_AUTO_TEST_CASE_TEMPLATE( stableInsert, SorterT, sorter_types )
{
  // simulating  permutation
  std::vector<std::pair<std::string, std::string>> test_data = {
    { "aa", "\"{1:2}\"" },
    { "ab", "\"{2:44}\""},
    { "bb", "\"{33:23}\"" },
    { "cc", "\"{3:24}\"" },
    { "aa", "\"{2:27}\"" },
    { "zz", "\"{3:21}\"" },
    { "zz", "\"{5:22}\"" },
    { "aa", "\"{3:24}\"" },
  };

  keyvi::dictionary::compiler_param_t params = {{STABLE_INSERTS, "true"}};

  keyvi::dictionary::DictionaryCompiler<
      fsa::internal::SparseArrayPersistence<uint16_t>,
      fsa::internal::JsonValueStore,
      SorterT> compiler(10485760, params);

  for (auto p: test_data){
    compiler.Add(p.first, p.second);
  }

  // test delete
  compiler.Delete("ab");

  compiler.Compile();

  boost::filesystem::path temp_path =
      boost::filesystem::temp_directory_path();

  temp_path /= boost::filesystem::unique_path(
      "dictionary-unit-test-dictionarycompiler-%%%%-%%%%-%%%%-%%%%");
  std::string file_name = temp_path.native();

  compiler.WriteToFile(file_name);

  Dictionary d(file_name.c_str());

  fsa::automata_t f(d.GetFsa());

  fsa::EntryIterator it(f);
  fsa::EntryIterator end_it;

  BOOST_CHECK_EQUAL("aa", it.GetKey());
  BOOST_CHECK_EQUAL("\"{3:24}\"", it.GetValueAsString());
  ++it;
  BOOST_CHECK_EQUAL("bb", it.GetKey());
  BOOST_CHECK_EQUAL("\"{33:23}\"", it.GetValueAsString());
  ++it;
  BOOST_CHECK_EQUAL("cc", it.GetKey());
  BOOST_CHECK_EQUAL("\"{3:24}\"", it.GetValueAsString());
  ++it;
  BOOST_CHECK_EQUAL("zz", it.GetKey());
  BOOST_CHECK_EQUAL("\"{5:22}\"", it.GetValueAsString());
  ++it;
  BOOST_CHECK(it == end_it);
}

BOOST_AUTO_TEST_CASE_TEMPLATE( addAndDeletes, SorterT, sorter_types )
{
  keyvi::dictionary::compiler_param_t params = {{STABLE_INSERTS, "true"}};

  keyvi::dictionary::DictionaryCompiler<
          fsa::internal::SparseArrayPersistence<uint16_t>,
          fsa::internal::JsonValueStore,
          SorterT> compiler(10485760, params);

  // add, delete, add again
  compiler.Add("aa", "1");
  compiler.Delete("aa");
  compiler.Delete("aa");
  compiler.Add("aa", "2");

  // delete, add
  compiler.Delete("bb");
  compiler.Add("bb", "1");

  // add, delete, last item
  compiler.Add("zz", "1");
  compiler.Delete("zz");

  compiler.Compile();

  boost::filesystem::path temp_path =
      boost::filesystem::temp_directory_path();

  temp_path /= boost::filesystem::unique_path(
        "dictionary-unit-test-dictionarycompiler-%%%%-%%%%-%%%%-%%%%");
  std::string file_name = temp_path.native();

  compiler.WriteToFile(file_name);

  Dictionary d(file_name.c_str());

  fsa::automata_t f(d.GetFsa());

  fsa::EntryIterator it(f);
  fsa::EntryIterator end_it;

  BOOST_CHECK_EQUAL("aa", it.GetKey());
  BOOST_CHECK_EQUAL("2", it.GetValueAsString());
  ++it;

  BOOST_CHECK_EQUAL("bb", it.GetKey());
  BOOST_CHECK_EQUAL("1", it.GetValueAsString());
  ++it;

  BOOST_CHECK(it == end_it);

  std::remove(file_name.c_str());
}

BOOST_AUTO_TEST_CASE_TEMPLATE( DeleteUnsupported, SorterT, sorter_types )
{
  keyvi::dictionary::compiler_param_t params = {};

  keyvi::dictionary::DictionaryCompiler<
            fsa::internal::SparseArrayPersistence<uint16_t>,
            fsa::internal::JsonValueStore,
            SorterT> compiler(10485760, params);

  // add, delete, add again
  compiler.Add("aa", "1");
  BOOST_CHECK_THROW( compiler.Delete("aa"), compiler_exception);
}

BOOST_AUTO_TEST_SUITE_END()

} /* namespace dictionary */
} /* namespace keyvi */

max_stars_repo_name: ssherko/keyvi

max_issues_repo_name: ssherko/keyvi

max_forks_repo_name: ssherko/keyvi


text:
/**
 * Copyright (c) 2018, University Osnabrück
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the University Osnabrück nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL University Osnabrück BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Debug.hpp
 *
 * Collection of functions to debug mesh generation.
 *
 * @date 18.07.2017
 * @author Johan M. von Behren <johan@vonbehren.eu>
 */

#ifndef LVR2_UTIL_DEBUG_H_
#define LVR2_UTIL_DEBUG_H_

#include <boost/iostreams/device/null.hpp>
#include <array>
#include <fstream>
#include <vector>

using std::array;
using std::string;
using std::vector;

#include "lvr2/geometry/Handles.hpp"
#include "lvr2/geometry/BaseMesh.hpp"
#include "lvr2/algorithm/ClusterPainter.hpp"
#include "lvr2/algorithm/ColorAlgorithms.hpp"

namespace lvr2
{

inline std::ostream& dout()
{
    // To have a "null" ostream, it's apparently a good idea to use an
    // unopened file, as no one ever checks the error state or sth. Source:
    //
    // https://stackoverflow.com/a/8244052/2408867
    static bool isDebug = getenv("LVR2_MESH_DEBUG") != nullptr;
    static std::ofstream unopenedFile;

    return isDebug ? cout : unopenedFile;
}

/**
 * @brief Write a mesh to the given filename and color it with the given color
 */
template<typename BaseVecT>
void writeDebugMesh(
    const BaseMesh<BaseVecT>& mesh,
    string filename = "debug.ply",
    Rgb8Color color = {255, 0, 0}
);

/**
 * @brief Returns all handles of duplicate vertices from the given mesh
 *
 * The equality of two points is check via Point::operator==().
 *
 * @return duplicate vertex handles. The vertex handles for each duplicate point are stored in a seperate vector. The
 *         return value is a vector which consists of these vectors. In other words: each vector in the result vector
 *         is a set of vertex handles, which points to points with the same coordinates.
 */
template<typename BaseVecT>
vector<vector<VertexHandle>> getDuplicateVertices(const BaseMesh<BaseVecT>& mesh);

/**
 * @brief Writes a mesh to the given filename and colors it with the following meaning:
 *  - conntectedColor: connected mesh (vertices of edges with 2 connected faces)
 *  - contourColor: contour edges (vertices of edges with 1 connected face)
 *  - bugColor: edges with neither 1 or 2 conntected faces
 */
template<typename BaseVecT>
void writeDebugContourMesh(
    const BaseMesh<BaseVecT>& mesh,
    string filename = "debug-contours.ply",
    Rgb8Color connectedColor = {0, 255, 0},
    Rgb8Color contourColor = {0, 0, 255},
    Rgb8Color bugColor = {255, 0, 0}
);

#ifdef NDEBUG
#define DOINDEBUG(...) ;
#else
#define DOINDEBUG(...) __VA_ARGS__
#endif

} // namespace lvr2

#include "lvr2/util/Debug.tcc"

#endif /* LVR2_UTIL_DEBUG_H_ */

max_stars_repo_name: uos/lvr

max_issues_repo_name: uos/lvr

max_forks_repo_name: uos/lvr


text:
/*
 * File: fast_hankel_transform.cc
 * Created Date: 2019-09-11
 * Author: Lei Pan
 * Contact: <panlei7@gmail.com>
 *
 * Last Modified: Wednesday September 25th 2019 11:37:38 am
 *
 * MIT License
 *
 * Copyright (c) 2019 Lei Pan
 *
 * 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.
 * -----
 * HISTORY:
 * Date      	 By	Comments
 * ----------	---
 * ----------------------------------------------------------
 */

#include "fast_hankel_transform.hpp"

#include <Eigen/Dense>
#include <boost/math/special_functions/bessel.hpp>
#include <cmath>
#include <complex>
#include <fftw3.h>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <iostream>

using namespace Eigen;
using std::abs;
using std::exp;
using std::log;
using std::pow;

FastHankelTransform::FastHankelTransform(int num_sample, double ux, double uy)
    : num_sample_(num_sample), ux_(ux), uy_(uy),
      x_(VectorXd::Zero(num_sample_)), f_(VectorXd::Zero(num_sample_ + 1)),
      phi_(new std::complex<double>[num_sample_ * 2]),
      j1_(new std::complex<double>[num_sample_ * 2]) {
  alpha_ = evaluate_alpha();
  k0_ = evaluate_k0(alpha_);
}

FastHankelTransform::~FastHankelTransform() {
  delete[] phi_;
  delete[] j1_;
}

double FastHankelTransform::evaluate_alpha() {
  auto func = [&](auto a) { return -log(1.0 - exp(-a)) / (num_sample_ - 1); };

  const int maxiter = 100;
  double alpha = 1.0;
  for (auto i = 0; i < maxiter; ++i) {
    alpha = func(alpha);
  }
  return alpha;
}

double FastHankelTransform::evaluate_k0(double alpha) {
  double k0 = (2.0 * exp(alpha) + exp(2.0 * alpha)) /
              (pow(1 + exp(alpha), 2) * (1 - exp(-2.0 * alpha)));
  return k0;
}

VectorXd FastHankelTransform::sampling() {
  x_updated_ = true;
  x_(0) = (1.0 + exp(alpha_)) * exp(-alpha_ * num_sample_) / 2.0;
  for (auto i = 1; i < num_sample_; ++i) {
    x_(i) = x_(0) * exp(alpha_ * i);
  }
  return x_;
}

void FastHankelTransform::set_feval(const Ref<const VectorXd> &feval) {
  assert(x_updated_ == true);
  f_updated_ = true;
  f_.head(num_sample_) = feval;
}

void FastHankelTransform::evaluate_phi() {
  phi_[0] = k0_ * (f_(0) - f_(1)) * exp(alpha_ * (1 - num_sample_));
  for (auto i = 1; i < num_sample_; ++i) {
    phi_[i] = (f_(i) - f_(i + 1)) * exp(alpha_ * (i + 1 - num_sample_));
  }
  for (auto i = num_sample_; i < num_sample_ * 2; ++i) {
    phi_[i] = 0.0;
  }
}

void FastHankelTransform::evaluate_j1() {
  for (auto i = 0; i < num_sample_ * 2; ++i) {
    double x = ux_ * uy_ * x_(0) * exp(alpha_ * (i + 1 - num_sample_));
    j1_[i] = boost::math::cyl_bessel_j(1, x);
  }
}

VectorXd FastHankelTransform::calculate() {
  assert(f_updated_ == true);
  evaluate_phi();
  evaluate_j1();

  int nsample = num_sample_ * 2;
  fftw_complex *fft_phi =
      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);
  fftw_complex *phi = reinterpret_cast<fftw_complex *>(phi_);
  fftw_plan p1 =
      fftw_plan_dft_1d(nsample, phi, fft_phi, FFTW_FORWARD, FFTW_ESTIMATE);
  fftw_execute(p1);

  fftw_complex *fft_j1 =
      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);
  fftw_complex *j1 = reinterpret_cast<fftw_complex *>(j1_);
  fftw_plan p2 =
      fftw_plan_dft_1d(nsample, j1, fft_j1, FFTW_BACKWARD, FFTW_ESTIMATE);
  fftw_execute(p2);

  fftw_complex *in =
      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);

  for (auto i = 0; i < nsample; ++i) {
    in[i][0] = fft_phi[i][0] * fft_j1[i][0] - fft_phi[i][1] * fft_j1[i][1];
    in[i][1] = fft_phi[i][0] * fft_j1[i][1] + fft_phi[i][1] * fft_j1[i][0];
  }

  fftw_complex *out =
      (fftw_complex *)fftw_malloc(sizeof(fftw_complex) * nsample);

  fftw_plan p3 =
      fftw_plan_dft_1d(nsample, in, out, FFTW_FORWARD, FFTW_ESTIMATE);
  fftw_execute(p3);

  VectorXd ret(num_sample_);
  for (auto i = 0; i < num_sample_; ++i) {
    ret(i) = 2.0 / (x_(i) * pow(ux_, 2) * uy_) * out[i][0] / nsample;
  }

  fftw_destroy_plan(p1);
  fftw_destroy_plan(p2);
  fftw_destroy_plan(p3);
  fftw_free(fft_phi);
  fftw_free(fft_j1);
  fftw_free(in);
  fftw_free(out);

  return ret;
}


text:
#include <pbcopper/data/Interval.h>

#include <istream>
#include <ostream>
#include <sstream>
#include <vector>

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

namespace PacBio {
namespace Data {

Interval::Interval(const Position val) : data_{val, val + 1} {}

Interval::Interval(const Position start, const Position end) : data_{start, end} {}

void Interval::Reset(const Position start, const Position end)
{
    assert(start <= end);
    *this = Interval{start, end};
}

void Interval::Reset(const Interval& other)
{
    assert(other.Start() <= other.End());
    *this = other;
}

bool Interval::operator==(const Interval& other) const noexcept { return data_ == other.data_; }

bool Interval::operator!=(const Interval& other) const noexcept { return !(data_ == other.data_); }

bool Interval::operator<(const Interval& other) const noexcept { return data_ < other.data_; }

bool Interval::IsEmpty() const { return Length() == 0; }

bool Interval::ContainedBy(const Interval& other) const
{
    return boost::icl::within(data_, other.data_);
}

bool Interval::Contains(const Interval& other) const
{
    return boost::icl::contains(data_, other.data_);
}

Position Interval::End() const { return data_.upper(); }

Interval& Interval::End(const Position& end)
{
    data_ = interval_type{data_.lower(), end};
    return *this;
}

bool Interval::Intersects(const Interval& other) const
{
    return boost::icl::intersects(data_, other.data_);
}

bool Interval::Overlaps(const Interval& other) const
{
    // if the left of one is in the range of the other
    return (other.Start() <= Start() && Start() <= other.End()) ||
           (Start() <= other.End() && other.Start() <= End());
}

bool Interval::IsValid() const { return !boost::icl::is_empty(data_); }

Data::Position Interval::Length() const { return boost::icl::length(data_); }

Position Interval::Start() const { return data_.lower(); }

Interval& Interval::Start(const Position& start)
{
    data_ = interval_type{start, data_.upper()};
    return *this;
}

Interval Interval::Union(const Interval& other) const
{
    if (Overlaps(other)) {
        return {std::min(Start(), other.Start()), std::max(End(), other.End())};
    } else {
        std::ostringstream msg;
        msg << "[pbcopper] interval ERROR: cannot merge intervals " << *this << " and " << other
            << ", because they do not overlap.";
        throw std::invalid_argument{msg.str()};
    }
}

Interval Interval::Intersect(const Interval& other) const
{
    if (Overlaps(other)) {
        return {std::max(Start(), other.Start()), std::min(End(), other.End())};
    } else {
        std::ostringstream msg;
        msg << "[pbcopper] interval ERROR: cannot create the intersection of intervals " << *this
            << " and " << other << ", because they do not overlap.";
        throw std::invalid_argument{msg.str()};
    }
}

Interval Interval::FromString(const std::string& str)
{
    try {
        std::vector<std::string> components;
        boost::split(components, str, boost::is_any_of("-"));
        if (components.size() == 1) {
            Position left = boost::lexical_cast<Position>(components[0]);
            return Interval(left, left + 1);
        } else if (components.size() == 2) {
            Position left = boost::lexical_cast<Position>(components[0]);
            Position right = boost::lexical_cast<Position>(components[1]);
            // if right < left, we have an invalid interval, fall through
            if (left <= right) {
                return Interval(left, right + 1);
            }
        }
    } catch (...) {
    }

    throw std::invalid_argument("[pbcopper] interval ERROR: cannot create an interval from '" +
                                str + "'");
}

Interval Interval::begin() const { return Interval(Start(), End()); }

Interval Interval::end() const { return Interval(End(), End()); }

Interval& Interval::operator++()
{
    Position newStart = Start();
    ++newStart;
    return Start(newStart);
}

Interval Interval::operator++(int)
{
    Position newStart = Start();
    return Interval{newStart++, End()};
}

Position Interval::operator*() const { return Start(); }

std::ostream& operator<<(std::ostream& os, const Interval& interval)
{
    return os << '[' << interval.Start() << ", " << interval.End() << ')';
}

std::istream& operator>>(std::istream& is, Interval& interval)
{
    char delim;
    Position start{}, end{};
    is >> std::ws >> delim >> start >> delim >> std::ws >> end >> delim;
    assert(is.good() && (start <= end));

    interval.Start(start);
    interval.End(end);

    return is;
}

}  // namespace Data
}  // namespace PacBio

max_stars_repo_name: PacificBiosciences/pbcopper

max_issues_repo_name: PacificBiosciences/pbcopper

max_forks_repo_name: PacificBiosciences/pbcopper


text:
/*
 Copyright (C) 2017 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/equityvolconstantspread.hpp
    \brief equity surface that combines an ATM curve and vol spreads from a surface
    \ingroup termstructures
*/

#ifndef quantext_equityvolatilityconstantspread_hpp
#define quantext_equityvolatilityconstantspread_hpp

#include <boost/shared_ptr.hpp>
#include <ql/termstructures/volatility/equityfx/blackvariancecurve.hpp>
#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>
#include <ql/termstructures/volatility/equityfx/blackvoltermstructure.hpp>

namespace QuantExt {
using namespace QuantLib;

//! Equity cube that combines an ATM matrix and vol spreads from a cube
/*! Notice that the TS has a floating reference date and accesses the source TS only via
 their time-based volatility methods.

 \warning the given atm vol structure should be strike independent, this is not checked
*/
class EquityVolatilityConstantSpread : public BlackVolTermStructure {
public:
    EquityVolatilityConstantSpread(const Handle<BlackVolTermStructure>& atm,
                                   const Handle<BlackVolTermStructure>& surface)
        : BlackVolTermStructure(0, atm->calendar(), atm->businessDayConvention(), atm->dayCounter()), atm_(atm),
          surface_(surface) {
        enableExtrapolation(atm->allowsExtrapolation());
        registerWith(atm);
        registerWith(surface);
    }

    //! \name TermStructure interface
    //@{
    DayCounter dayCounter() const { return atm_->dayCounter(); }
    Date maxDate() const { return atm_->maxDate(); }
    Time maxTime() const { return atm_->maxTime(); }
    const Date& referenceDate() const { return atm_->referenceDate(); }
    Calendar calendar() const { return atm_->calendar(); }
    Natural settlementDays() const { return atm_->settlementDays(); }
    //@}
    //! \name VolatilityTermStructure interface
    //@{
    Rate minStrike() const { return surface_->minStrike(); }
    Rate maxStrike() const { return surface_->maxStrike(); }
    //@}

protected:
    Volatility blackVolImpl(Time t, Rate strike) const {
        Real s = surface_->blackVol(t, strike, true) - surface_->blackVol(t, Null<Real>(), true);
        Real v = atm_->blackVol(t, Null<Real>(), true);
        return v + s;
    }

    Real blackVarianceImpl(Time t, Real strike) const {
        Real vol = blackVolImpl(t, strike);
        return vol * vol * t;
    }

private:
    Handle<BlackVolTermStructure> atm_, surface_;
};

} // namespace QuantExt

#endif

max_stars_repo_name: PiotrSiejda/Engine

max_issues_repo_name: zhangjiayin/Engine

max_forks_repo_name: zhangjiayin/Engine


text:
#pragma once

#include <pty.h>
#include <pwd.h>
#include <termios.h>

#include <app.hpp>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/process/io.hpp>
#include <websocket.hpp>

#include <map>

namespace crow
{

namespace obmc_shell
{

class Handler : public std::enable_shared_from_this<Handler>
{
  public:
    Handler(crow::websocket::Connection* conn) :
        session(conn), streamFileDescriptor(conn->getIoContext()),
        doingWrite(false)
    {}

    ~Handler() = default;

    void doClose()
    {
        streamFileDescriptor.close();

        // boost::process::child::terminate uses SIGKILL, need to send SIGTERM
        int rc = kill(pid, SIGKILL);
        session = nullptr;
        if (rc)
        {
            return;
        }
        waitpid(pid, nullptr, 0);
    }

    void connect()
    {
        pid = forkpty(&ttyFileDescriptor, nullptr, nullptr, nullptr);

        if (pid == -1)
        {
            // ERROR
            if (session)
            {
                session->close("Error creating child process for login shell.");
            }
            return;
        }
        if (pid == 0)
        {
            // CHILD

            if (auto userName = session->getUserName(); !userName.empty())
            {
                execl("/bin/login", "/bin/login", "-f", userName.c_str(), NULL);
                // execl only returns on fail
                BMCWEB_LOG_ERROR << "execl() for /bin/login failed: " << errno;
                session->close("Internal Error Login failed");
            }
            else
            {
                session->close("Error session user name not found");
            }
            return;
        }
        if (pid > 0)
        {
            // PARENT

            // for io operation assing file discriptor
            // to boost stream_descriptor
            streamFileDescriptor.assign(ttyFileDescriptor);
            doWrite();
            doRead();
        }
    }

    void doWrite()
    {
        if (!session)
        {
            BMCWEB_LOG_DEBUG << "session is closed";
            return;
        }
        if (doingWrite)
        {
            BMCWEB_LOG_DEBUG << "Already writing.  Bailing out";
            return;
        }

        if (inputBuffer.empty())
        {
            BMCWEB_LOG_DEBUG << "inputBuffer empty.  Bailing out";
            return;
        }

        doingWrite = true;
        streamFileDescriptor.async_write_some(
            boost::asio::buffer(inputBuffer.data(), inputBuffer.size()),
            [this, self(shared_from_this())](boost::beast::error_code ec,
                                             std::size_t bytesWritten) {
                BMCWEB_LOG_DEBUG << "Wrote " << bytesWritten << "bytes";
                doingWrite = false;
                inputBuffer.erase(0, bytesWritten);
                if (ec == boost::asio::error::eof)
                {
                    session->close("ssh socket port closed");
                    return;
                }
                if (ec)
                {
                    session->close("Error in writing to processSSH port");
                    BMCWEB_LOG_ERROR << "Error in ssh socket write " << ec;
                    return;
                }
                doWrite();
            });
    }

    void doRead()
    {
        if (!session)
        {
            BMCWEB_LOG_DEBUG << "session is closed";
            return;
        }
        streamFileDescriptor.async_read_some(
            boost::asio::buffer(outputBuffer.data(), outputBuffer.size()),
            [this, self(shared_from_this())](
                const boost::system::error_code& ec, std::size_t bytesRead) {
                BMCWEB_LOG_DEBUG << "Read done.  Read " << bytesRead
                                 << " bytes";
                if (!session)
                {
                    BMCWEB_LOG_DEBUG << "session is closed";
                    return;
                }
                if (ec)
                {
                    BMCWEB_LOG_ERROR << "Couldn't read from ssh port: " << ec;
                    session->close("Error in connecting to ssh port");
                    return;
                }
                std::string_view payload(outputBuffer.data(), bytesRead);
                session->sendBinary(payload);
                doRead();
            });
    }

    // this has to public
    std::string inputBuffer;

  private:
    crow::websocket::Connection* session;
    boost::asio::posix::stream_descriptor streamFileDescriptor;
    bool doingWrite;
    int ttyFileDescriptor;
    pid_t pid;

    std::array<char, 4096> outputBuffer;
};

static std::map<crow::websocket::Connection*, std::shared_ptr<Handler>>
    mapHandler;

inline void requestRoutes(App& app)
{
    BMCWEB_ROUTE(app, "/bmc-console")
        .privileges({{"OemIBMPerformService"}})
        .websocket()
        .onopen([](crow::websocket::Connection& conn,
                   const std::shared_ptr<bmcweb::AsyncResp>&) {
            BMCWEB_LOG_DEBUG << "Connection " << &conn << " opened";
            if (auto it = mapHandler.find(&conn); it == mapHandler.end())
            {
                auto insertData =
                    mapHandler.emplace(&conn, std::make_shared<Handler>(&conn));
                if (std::get<bool>(insertData))
                {
                    std::get<0>(insertData)->second->connect();
                }
            }
        })
        .onclose(
            [](crow::websocket::Connection& conn, const std::string& reason) {
                BMCWEB_LOG_DEBUG << "bmc-shell console.onclose(reason = '"
                                 << reason << "')";
                if (auto it = mapHandler.find(&conn); it != mapHandler.end())
                {
                    it->second->doClose();
                    mapHandler.erase(it);
                }
            })
        .onmessage([]([[maybe_unused]] crow::websocket::Connection& conn,
                      const std::string& data, [[maybe_unused]] bool isBinary) {
            if (auto it = mapHandler.find(&conn); it != mapHandler.end())
            {
                it->second->inputBuffer += data;
                it->second->doWrite();
            }
            else
            {
                BMCWEB_LOG_ERROR << "connection to webScoket not found";
            }
        });
}

} // namespace obmc_shell
} // namespace crow

max_stars_repo_name: raviteja-b/bmcweb

max_issues_repo_name: raviteja-b/bmcweb

max_forks_repo_name: raviteja-b/bmcweb


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

#include <algorithm>
#include <thread>

#include <boost/scope_exit.hpp>

#include <gtest/gtest.h>

#include "yb/util/priority_thread_pool.h"
#include "yb/util/random_util.h"
#include "yb/util/test_macros.h"
#include "yb/util/test_util.h"

using namespace std::literals;

namespace yb {

const auto kStepTime = 25ms;
const auto kWaitTime = kStepTime * 3;

class Share {
 public:
  bool Step(int index) {
    running_.fetch_or(1ULL << index, std::memory_order_acq_rel);
    return (stop_.load(std::memory_order_acquire) & (1ULL << index)) == 0;
  }

  void Stop(int index) {
    stop_.fetch_or(1ULL << index, std::memory_order_acq_rel);
  }

  void ResetRunning() {
    running_.store(0, std::memory_order_release);
  }

  uint64_t running() {
    return running_.load(std::memory_order_acquire);
  }

 private:
  std::atomic<uint64_t> running_{0};
  std::atomic<uint64_t> stop_{0};
};

class Task : public PriorityThreadPoolTask {
 public:
  explicit Task(int index, int priority, Share* share)
      : index_(index), priority_(priority), share_(share) {}

  void Run(const Status& status, PriorityThreadPoolSuspender* suspender) override {
    if (!status.ok()) {
      return;
    }
    while (share_->Step(index_)) {
      suspender->PauseIfNecessary();
      std::this_thread::sleep_for(kStepTime);
    }
  }

  bool BelongsTo(void* key) override {
    return false;
  }

  int Index() const {
    return index_;
  }

  // Priority of this task.
  int Priority() const override {
    return priority_;
  }

  void AddToStringFields(std::string* out) const override {
    *out += Format("index: $0 ", index_);
  }

 private:
  const int index_;
  const int priority_;
  Share* const share_;
};

// Test randomly submits and stops task to priority thread pool.
// Checking that only expected tasks are running.
// Task priority is calculated as index/divisor.
// So with divisor == 1 we get unique priorities, and with divisor > 1 multiple tasks could have
// the same priority.
void TestRandom(int divisor) {
  const int kTasks = 20;
  const int kMaxRunningTasks = 3;
  PriorityThreadPool thread_pool(kMaxRunningTasks);
  std::vector<std::unique_ptr<Task>> tasks;
  tasks.reserve(kTasks);
  Share share;
  for (int i = 0; i != kTasks; ++i) {
    tasks.emplace_back(std::make_unique<Task>(i, i / divisor, &share));
  }
  std::shuffle(tasks.begin(), tasks.end(), ThreadLocalRandom());
  std::set<int> scheduled;
  size_t schedule_idx = 0;
  std::set<int> stopped;
  std::vector<int> running_vector;
  std::vector<int> expected_running;

  BOOST_SCOPE_EXIT(&share, scheduled, &thread_pool) {
    thread_pool.StartShutdown();
    for (int idx = 0; idx != kTasks; ++idx) {
      share.Stop(idx);
    }
    thread_pool.CompleteShutdown();
  } BOOST_SCOPE_EXIT_END;

  while (stopped.size() != kTasks) {
    if (schedule_idx < kTasks && RandomUniformInt<int>(0, 2 + scheduled.size()) == 0) {
      auto& task = tasks[schedule_idx];
      auto index = task->Index();
      scheduled.insert(index);
      ++schedule_idx;
      auto submit_result = thread_pool.Submit(std::move(task));
      ASSERT_TRUE(submit_result == nullptr);
      LOG(INFO) << "Submitted: " << index << ", scheduled: " << yb::ToString(scheduled);
    } else if (!scheduled.empty() &&
               RandomUniformInt<int>(0, std::max<int>(0, 13 - scheduled.size())) == 0) {
      auto it = scheduled.end();
      std::advance(
          it, -RandomUniformInt<int>(1, std::min<int>(scheduled.size(), kMaxRunningTasks)));
      auto idx = *it;
      stopped.insert(idx);
      share.Stop(idx);
      scheduled.erase(it);
      LOG(INFO) << "Stopped: " << idx << ", scheduled: " << yb::ToString(scheduled);
    }
    std::this_thread::sleep_for(kWaitTime);
    share.ResetRunning();
    std::this_thread::sleep_for(kWaitTime);
    auto running = share.running();
    running_vector.clear();
    for (int i = 0; i != kTasks; ++i) {
      if (running & (1 << i)) {
        running_vector.push_back(i / divisor);
      }
    }
    expected_running.clear();
    auto it = scheduled.end();
    auto left = kMaxRunningTasks;
    while (it != scheduled.begin() && left > 0) {
      --it;
      expected_running.push_back(*it / divisor);
      --left;
    }
    std::reverse(expected_running.begin(), expected_running.end());
    ASSERT_EQ(expected_running, running_vector) << "Scheduled: " << yb::ToString(scheduled)
                                                << ", running: " << yb::ToString(running_vector)
                                                << ", state: " << thread_pool.StateToString();
  }
}

TEST(PriorityThreadPoolTest, RandomUnique) {
  TestRandom(1 /* divisor */);
}

TEST(PriorityThreadPoolTest, RandomNonUnique) {
  TestRandom(3 /* divisor */);
}

constexpr int kMaxRandomTaskTimeMs = 40;

class RandomTask : public PriorityThreadPoolTask {
 public:
  RandomTask() : priority_(RandomUniformInt(0, 4)) {}

  void Run(const Status& status, PriorityThreadPoolSuspender* suspender) override {
    if (!status.ok()) {
      return;
    }
    std::this_thread::sleep_for(1ms * RandomUniformInt(1, kMaxRandomTaskTimeMs));
  }

  // Returns true if the task belongs to specified key, which was passed to
  // PriorityThreadPool::Remove.
  bool BelongsTo(void* key) override {
    return false;
  }

  // Priority of this task.
  int Priority() const override {
    return priority_;
  }

  void AddToStringFields(std::string* out) const override {
  }

 private:
  int priority_;
};

TEST(PriorityThreadPoolTest, RandomTasks) {
  constexpr int kMaxRunningTasks = 10;
  PriorityThreadPool thread_pool(kMaxRunningTasks);
  TestThreadHolder holder;
  for (int i = 0; i != kMaxRunningTasks; ++i) {
    holder.AddThread([&stop = holder.stop_flag(), &thread_pool] {
      while (!stop.load()) {
        auto task = thread_pool.Submit(std::make_unique<RandomTask>());
        ASSERT_TRUE(task == nullptr);
        // Submit tasks slightly slower than they complete.
        // To frequently get case of empty thread pool.
        std::this_thread::sleep_for(1ms * RandomUniformInt(1, kMaxRandomTaskTimeMs * 5 / 4));
      }
    });
  }
  holder.WaitAndStop(60s);
  thread_pool.Shutdown();
}

} // namespace yb

max_stars_repo_name: JackDavidson/yugabyte-db

max_issues_repo_name: JackDavidson/yugabyte-db

max_forks_repo_name: JackDavidson/yugabyte-db


text:
#include "ApiKeyFileFormatter.h"

#include "gtest/gtest.h"
#include <boost/optional/optional_io.hpp>

using namespace ::testing;
using namespace glossary::wordDescriptionService;

namespace
{
const std::string fileContentWithWhiteSpaces{" \n\n       apiKey\n\n\n "};
const std::string fileContentWithoutWhiteSpaces{"apiKey"};
const std::string expectedApiKey{"apiKey"};
}

class ApiKeyFromFileContentRetrieverTest : public Test
{
public:
    ApiKeyFileFormatter formatter;
};

TEST_F(ApiKeyFromFileContentRetrieverTest, givenFileContentWithWhiteSpaces_shouldIgnoreThemAndReturnApiKey)
{
    const auto actualApiKey = formatter.getFormattedApiKey(fileContentWithWhiteSpaces);

    ASSERT_EQ(actualApiKey, expectedApiKey);
}

TEST_F(ApiKeyFromFileContentRetrieverTest, givenFileContentWithotWhiteSpaces_shouldReturnApiKey)
{
    const auto actualApiKey = formatter.getFormattedApiKey(fileContentWithoutWhiteSpaces);

    ASSERT_EQ(actualApiKey, expectedApiKey);
}

max_stars_repo_name: michalovsky/Glossary

max_issues_repo_name: michalovsky/Glossary

max_forks_repo_name: michalovsky/Glossary