text:
// BenchmarkFloatConv.cpp : Defines the entry point for the console application.
//

#include <vector>
#include <iostream>
#include <iomanip>
#include <string>
#include <cstring>
#include <cmath>
#include <cassert>
#include <sstream>
#include <cstdlib>
#include <chrono>
#include <boost/lexical_cast.hpp>
#include <boost/spirit/include/qi.hpp>
#include "google_double_conversion/double-conversion.h"
#include <charconv>

typedef std::pair<const std::string, const double> pair_type;
typedef std::vector< pair_type > vector_type;

#ifdef WIN32

#pragma optimize("", off)
template <class T>
void do_not_optimize_away(T&& datum) {
	datum = datum;
}
#pragma optimize("", on)

#else
static void do_not_optimize_away(void* p) {
    asm volatile("" : : "g"(p) : "memory");
}
#endif

void init(vector_type& vec);

#define MYASSERT(value, expected)

//#define MYASSERT(value, expected) if(value != expected) { std::cerr << value << " and expected:" << expected << " are different" << std::endl; }

class timer
{
public:
	timer() = default;
	void start(const std::string& text_)
	{
		text = text_;
		begin = std::chrono::high_resolution_clock::now();
	}
	void stop()
	{
		auto end = std::chrono::high_resolution_clock::now();
		auto dur = end - begin;
		auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
		std::cout << std::setw(19) << text << ":" << std::setw(5) << ms << "ms" << std::endl;
	}

private:
	std::string text;
	std::chrono::high_resolution_clock::time_point begin;
};

// Original crack_atof version is at http://crackprogramming.blogspot.sg/2012/10/implement-atof.html
// But it cannot convert floating point with high +/- exponent.
// The version below by Tian Bo fixes that problem and improves performance by 10%
// http://coliru.stacked-crooked.com/a/2e28f0d71f47ca5e
double pow10(int n)
{
	double ret = 1.0;
	double r = 10.0;
	if (n < 0) {
		n = -n;
		r = 0.1;
	}

	while (n) {
		if (n & 1) {
			ret *= r;
		}
		r *= r;
		n >>= 1;
	}
	return ret;
}

double crack_atof(const char* num)
{
	if (!num || !*num) {
		return 0;
	}

	int sign = 1;
	double integerPart = 0.0;
	double fractionPart = 0.0;
	bool hasFraction = false;
	bool hasExpo = false;

	// Take care of +/- sign
	if (*num == '-') {
		++num;
		sign = -1;
	}
	else if (*num == '+') {
		++num;
	}

	while (*num != '\0') {
		if (*num >= '0' && *num <= '9') {
			integerPart = integerPart * 10 + (*num - '0');
		}
		else if (*num == '.') {
			hasFraction = true;
			++num;
			break;
		}
		else if (*num == 'e') {
			hasExpo = true;
			++num;
			break;
		}
		else {
			return sign * integerPart;
		}
		++num;
	}

	if (hasFraction) {
		double fractionExpo = 0.1;

		while (*num != '\0') {
			if (*num >= '0' && *num <= '9') {
				fractionPart += fractionExpo * (*num - '0');
				fractionExpo *= 0.1;
			}
			else if (*num == 'e') {
				hasExpo = true;
				++num;
				break;
			}
			else {
				return sign * (integerPart + fractionPart);
			}
			++num;
		}
	}

	// parsing exponet part
	double expPart = 1.0;
	if (*num != '\0' && hasExpo) {
		int expSign = 1;
		if (*num == '-') {
			expSign = -1;
			++num;
		}
		else if (*num == '+') {
			++num;
		}

		int e = 0;
		while (*num != '\0' && *num >= '0' && *num <= '9') {
			e = e * 10 + *num - '0';
			++num;
		}

		expPart = pow10(expSign * e);
	}

	return sign * (integerPart + fractionPart) * expPart;
}

#define white_space(c) ((c) == ' ' || (c) == '\t')
#define valid_digit(c) ((c) >= '0' && (c) <= '9')
// http://www.leapsecond.com/tools/fast_atof.c
// Do not use this one because the converison is imprecise.
double fast_atof(const char *p)
{
	int frac;
	double sign, value, scale;

	// Skip leading white space, if any.

	while (white_space(*p)) {
		p += 1;
	}

	// Get sign, if any.

	sign = 1.0;
	if (*p == '-') {
		sign = -1.0;
		p += 1;

	}
	else if (*p == '+') {
		p += 1;
	}

	// Get digits before decimal point or exponent, if any.

	for (value = 0.0; valid_digit(*p); p += 1) {
		value = value * 10.0 + (*p - '0');
	}

	// Get digits after decimal point, if any.

	if (*p == '.') {
		double pow10 = 10.0;
		p += 1;
		while (valid_digit(*p)) {
			value += (*p - '0') / pow10;
			pow10 *= 10.0;
			p += 1;
		}
	}

	// Handle exponent, if any.

	frac = 0;
	scale = 1.0;
	if ((*p == 'e') || (*p == 'E')) {
		unsigned int expon;

		// Get sign of exponent, if any.

		p += 1;
		if (*p == '-') {
			frac = 1;
			p += 1;

		}
		else if (*p == '+') {
			p += 1;
		}

		// Get digits of exponent, if any.

		for (expon = 0; valid_digit(*p); p += 1) {
			expon = expon * 10 + (*p - '0');
		}
		if (expon > 308) expon = 308;

		// Calculate scaling factor.

		while (expon >= 50) { scale *= 1E50; expon -= 50; }
		while (expon >= 8) { scale *= 1E8;  expon -= 8; }
		while (expon > 0) { scale *= 10.0; expon -= 1; }
	}

	// Return signed and scaled floating point result.

	return sign * (frac ? (value / scale) : (value * scale));
}
int main(int argc, char *argv [])
{
	const size_t MAX_LOOP = (argc == 2) ? atoi(argv[1]) : 100000;

	vector_type vec;
	init(vec);
	timer stopwatch;
	double d = 0.0;

	stopwatch.start("atof");
	for (size_t k = 0; k<MAX_LOOP; ++k)
	{
		for (size_t j=0; j<vec.size(); ++j)
		{
			pair_type& pr = vec[j];
			d = std::atof(pr.first.c_str());
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("lexical_cast");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t j=0; j<vec.size(); ++j)
		{
			pair_type& pr = vec[j];
			d = boost::lexical_cast<double>(pr.first.c_str());
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("std::istringstream");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t i = 0; i<vec.size(); ++i)
		{
			pair_type& pr = vec[i];
			std::istringstream oss(pr.first);
			oss >> d;
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("std::stod");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t i = 0; i<vec.size(); ++i)
		{
			pair_type& pr = vec[i];
			d = std::stod(pr.first, nullptr);
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("std::strtod");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t i = 0; i < vec.size(); ++i)
		{
			pair_type& pr = vec[i];
			d = std::strtod(pr.first.c_str(), nullptr);
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("crack_atof");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t j=0; j<vec.size(); ++j)
		{
			pair_type& pr = vec[j];
			d = crack_atof(pr.first.c_str());
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("fast_atof");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t j=0; j<vec.size(); ++j)
		{
			pair_type& pr = vec[j];
			d = fast_atof(pr.first.c_str());
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	namespace qi = boost::spirit::qi;

	stopwatch.start("boost_spirit");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t j=0; j<vec.size(); ++j)
		{
			pair_type& pr = vec[j];
			bool success = qi::parse(pr.first.cbegin(), pr.first.cend(), qi::double_, d);
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("google_dconv");
	int processed_characters_count = 0;
	using namespace double_conversion;
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t j = 0; j < vec.size(); ++j)
		{
			pair_type& pr = vec[j];

			static StringToDoubleConverter conv(StringToDoubleConverter::NO_FLAGS, 0.0, NAN, "infinity", "nan");
			d = conv.StringToDouble(pr.first.c_str(), pr.first.size(), &processed_characters_count);

			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	stopwatch.start("std::from_chars");
	for (size_t k = 0; k < MAX_LOOP; ++k)
	{
		for (size_t j = 0; j < vec.size(); ++j)
		{
			pair_type& pr = vec[j];
			std::from_chars(pr.first.data(), pr.first.data() + pr.first.size(), d);
			do_not_optimize_away(&d);
			MYASSERT(d, pr.second);
		}
	}
	stopwatch.stop();

	std::cout << "Last float value: " << d << " <-- Ignore this" << std::endl;
	return 0;
}

void init(vector_type& vec)
{
	std::string float_str = "+12369";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "-25934";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "-47896.36";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "+532.102";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "4.5655";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "8.3658";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "-125.6900";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "-1236.2311";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "-5522.2389";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
	float_str = "-14.23";
	vec.push_back(std::make_pair(float_str, atof(float_str.c_str())));
}

max_stars_repo_name: shaovoon/floatbench

max_issues_repo_name: shaovoon/floatbench

max_forks_repo_name: shaovoon/floatbench


text:
#define BOOST_TEST_MODULE communicator_barrier

#include <boost/test/included/unit_test.hpp>
#include <mpl/mpl.hpp>

bool barrier_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  comm_world.barrier();
  return true;
}

bool ibarrier_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  auto r{comm_world.ibarrier()};
  r.wait();
  return true;
}

BOOST_AUTO_TEST_CASE(barrier) {
  BOOST_TEST(barrier_test());
  BOOST_TEST(ibarrier_test());
}

ext: cc

max_stars_repo_name: mlund/mpl

max_issues_repo_name: mlund/mpl

max_forks_repo_name: mlund/mpl


text:
///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                 polar v1.0 - August the 15th 2019                         //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  Copyright 2019 Matteo Tommasini                                          //
//                                                                           //
//  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.                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#ifndef ROBUST_H
#define ROBUST_H

#include <Eigen/Core>

class VCD;
class States;
class VibStates;

class Robust
{

private:
   // attributes
   Eigen::VectorXd electric_transition_moment,
                   magnetic_transition_moment,
                   wavenumber,
                   transition_energy;

   bool is_electronic  = false,
	      is_vibrational = false;

public:
   Robust();
   explicit Robust(const VibStates&);
   explicit Robust(const States&);
   void Print() const;

};

#endif // ROBUST_H

ext: hpp

max_stars_repo_name: matteo-maria-tommasini/polar

max_issues_repo_name: matteo-maria-tommasini/polar

max_forks_repo_name: matteo-maria-tommasini/polar


text:
/*
 * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     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.
 *
 */
#define BOOST_TEST_MAIN

#define BOOST_TEST_MODULE vxc_potential_test

// Standard includes
#include <fstream>

// Third party includes
#include <boost/test/unit_test.hpp>

// Local VOTCA includes
#include "votca/xtp/orbitals.h"
#include "votca/xtp/vxc_grid.h"
#include "votca/xtp/vxc_potential.h"
#include <libint2/initialize.h>
#include <votca/tools/eigenio_matrixmarket.h>
using namespace votca::xtp;
using namespace std;

BOOST_AUTO_TEST_SUITE(vxc_potential_test)

AOBasis CreateBasis(const QMMolecule& mol) {
  BasisSet basis;
  basis.Load(std::string(XTP_TEST_DATA_FOLDER) + "/vxc_potential/3-21G.xml");
  AOBasis aobasis;
  aobasis.Fill(basis, mol);
  return aobasis;
}

Eigen::MatrixXd DMat() {
  Eigen::MatrixXd dmat = votca::tools::EigenIO_MatrixMarket::ReadMatrix(
      std::string(XTP_TEST_DATA_FOLDER) + "/vxc_potential/dmat.mm");
  return dmat;
}

BOOST_AUTO_TEST_CASE(vxc_test) {
  libint2::initialize();
  QMMolecule mol("none", 0);

  mol.LoadFromFile(std::string(XTP_TEST_DATA_FOLDER) +
                   "/vxc_potential/molecule.xyz");
  AOBasis aobasis = CreateBasis(mol);

  Eigen::MatrixXd dmat = DMat();
  Vxc_Grid grid;
  grid.GridSetup("medium", mol, aobasis);
  Vxc_Potential<Vxc_Grid> num(grid);
  num.setXCfunctional("XC_GGA_X_PBE XC_GGA_C_PBE");

  BOOST_CHECK_EQUAL(grid.getGridSize(), grid.getGridpoints().size());
  BOOST_CHECK_EQUAL(grid.getGridSize(), 53404);
  BOOST_CHECK_EQUAL(grid.getBoxesSize(), 51);

  BOOST_CHECK_CLOSE(num.getExactExchange("XC_GGA_X_PBE XC_GGA_C_PBE"), 0.0,
                    1e-5);
  BOOST_CHECK_CLOSE(num.getExactExchange("XC_HYB_GGA_XC_PBEH"), 0.25, 1e-5);
  Mat_p_Energy e_vxc = num.IntegrateVXC(dmat);

  Eigen::MatrixXd vxc_ref = votca::tools::EigenIO_MatrixMarket::ReadMatrix(
      std::string(XTP_TEST_DATA_FOLDER) + "/vxc_potential/vxc_ref.mm");

  bool check_vxc = e_vxc.matrix().isApprox(vxc_ref, 0.0001);

  BOOST_CHECK_CLOSE(e_vxc.energy(), -4.6303432151572643, 1e-5);
  if (!check_vxc) {
    std::cout << "ref" << std::endl;
    std::cout << vxc_ref << std::endl;
    std::cout << "calc" << std::endl;
    std::cout << e_vxc.matrix() << std::endl;
  }
  BOOST_CHECK_EQUAL(check_vxc, 1);

  libint2::finalize();
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: rubengerritsen/xtp

max_issues_repo_name: rubengerritsen/xtp

max_forks_repo_name: rubengerritsen/xtp


text:
// Copyright John Maddock 2007.

// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/math/policies/policy.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/test/test_exec_monitor.hpp> // for test_main
#include <iostream>

template <class P1, class P2>
bool check_same(const P1&, const P2&)
{
   if(!boost::is_same<P1, P2>::value)
   {
      std::cout << "P1 = " << typeid(P1).name() << std::endl;
      std::cout << "P2 = " << typeid(P2).name() << std::endl;
   }
   return boost::is_same<P1, P2>::value;
}

int test_main(int, char* [])
{
   using namespace boost::math::policies;
   using namespace boost;

   BOOST_CHECK(check_same(make_policy(), policy<>()));
   BOOST_CHECK(check_same(make_policy(denorm_error<ignore_error>()), normalise<policy<denorm_error<ignore_error> > >::type()));
   BOOST_CHECK(check_same(make_policy(digits2<20>()), normalise<policy<digits2<20> > >::type()));
   BOOST_CHECK(check_same(make_policy(promote_float<false>()), normalise<policy<promote_float<false> > >::type()));
   BOOST_CHECK(check_same(make_policy(domain_error<ignore_error>()), normalise<policy<domain_error<ignore_error> > >::type()));
   BOOST_CHECK(check_same(make_policy(pole_error<ignore_error>()), normalise<policy<pole_error<ignore_error> > >::type()));
   BOOST_CHECK(check_same(make_policy(indeterminate_result_error<ignore_error>()), normalise<policy<indeterminate_result_error<ignore_error> > >::type()));

   return 0;
} // int test_main(int, char* [])

ext: cpp

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
/*!
 * @file
 * This file defines `boost::mpl::matches`.
 */

#ifndef BOOST_MPL_MATCHES_HPP
#define BOOST_MPL_MATCHES_HPP

#include <boost/mpl/any_of.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/mpl/equal.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/type_traits/is_same.hpp>

namespace boost { namespace mpl {
namespace match {
    //! Matches anything.
    struct any;

    // Matches iff any of the patterns match.
    template <typename ...Patterns>
    struct any_of;

    //! Matches iff the pattern does not match.
    template <typename Pattern>
    struct not_;

    //! Matches iff the `LambdaExpression` returns true.
    template <typename LambdaExpression>
    struct if_;

    //! Matches iff the `LambdaExpression` returns false.
    template <typename LambdaExpression>
    struct unless;
} // end namespace match

/*!
 * Metafunction returning whether a type matches a given pattern.
 *
 * By default, a type matches a pattern if they are the same. Two template
 * types match if their template parameters match side by side.
 *
 *
 * @internal
 * We use `is_same` because specializing `matches<T, T>` makes it an ambiguous
 * specialization with the `Node<...>` specialization when `Children1` is the
 * same as `Children2`.
 */
template <typename T, typename Pattern>
struct matches
    : is_same<T, Pattern>
{ };

template <template <typename ...> class Node,
          typename ...Children1,
          typename ...Children2>
struct matches<Node<Children1...>, Node<Children2...>>
    : equal<
        typename vector<Children1...>::type,
        typename vector<Children2...>::type,
        matches<_1, _2>
    >
{ };

template <typename T>
struct matches<T, match::any>
    : true_
{ };

template <typename T, typename ...Patterns>
struct matches<T, match::any_of<Patterns...>>
    : any_of<
        typename vector<Patterns...>::type,
        matches<T, _1>
    >
{ };

template <typename T, typename Pattern>
struct matches<T, match::not_<Pattern>>
    : not_<matches<T, Pattern>>
{ };

template <typename T, typename LambdaExpression>
struct matches<T, match::if_<LambdaExpression>>
    : bool_<apply<LambdaExpression, T>::type::value>
{ };

template <typename T, typename LambdaExpression>
struct matches<T, match::unless<LambdaExpression>>
    : not_<apply<LambdaExpression, T>>
{ };

namespace matches_detail {
    template <typename FuncDecl>
    struct assert_matches_impl;

    template <typename Ret, typename T, typename Pattern>
    struct assert_matches_impl<Ret (T, Pattern)>
        : matches<T, Pattern>
    { };
} // end namespace matches_detail

#define BOOST_MPL_ASSERT_MATCHES(FuncParams)                                \
    static_assert(                                                          \
        ::boost::mpl::matches_detail::assert_matches_impl<                  \
            void FuncParams                                                 \
        >::value,                                                           \
        #FuncParams                                                         \
    )                                                                       \
/**/

#define BOOST_MPL_ASSERT_MATCHES_NOT(FuncParams)                            \
    static_assert(                                                          \
      ! ::boost::mpl::matches_detail::assert_matches_impl<                  \
            void FuncParams                                                 \
        >::value,                                                           \
        #FuncParams                                                         \
    )                                                                       \
/**/
}} // end namespace boost::mpl

#endif // !BOOST_MPL_MATCHES_HPP


text:
#include <inttypes.h>
#include <iostream>
#include <memory>

#include <boost/timer/timer.hpp>

#include "sparta/sparta.hpp"
#include "sparta/simulation/TreeNode.hpp"
#include "sparta/statistics/Counter.hpp"
#include "sparta/statistics/StatisticSet.hpp"
#include "sparta/statistics/StatisticDef.hpp"
#include "sparta/statistics/StatisticInstance.hpp"
#include "sparta/utils/Utils.hpp"
#include "sparta/utils/SpartaTester.hpp"

/*!
 * \file main.cpp
 * \brief Test for StatisticSet, StatisticDef, and StatisticInstance
 *
 * Under the right circumstances, this test will ensure that there are no
 * segfaults during static destruction caused by SPARTA static members being
 * destructed before other objects that depend on them (e.g. TreeNode
 * instances). Note that this may not always be a valid test, because static
 * initialization order is not defined and some compilers will
 * for gcc-4.7.0, this test originally caused a segfault in TreeNode::~TreeNode
 * which was fixed.
 */

TEST_INIT;

using sparta::StatisticDef;
using sparta::StatisticInstance;
using sparta::StatisticSet;
using sparta::RootTreeNode;
using sparta::TreeNode;
using sparta::Counter;

class StaticStuff {
public:
    RootTreeNode root;
    TreeNode dummy;

    StaticStuff() :
        dummy(&root, "dummy", "A dummy node")
    {;}
};

/*!
 * \brief Instantiate this in main, and allow the static destruction to destroy
 * it.
 */
std::unique_ptr<StaticStuff> sstuff;

/*!
 * \brief Instantiate this globally and allow the static destructor to destroy
 * it
 *
 * \warning NOT YET SUPPORTED because of StringManager's statics.
 * \verbatim
 *   what():  _GBL_string_manager.is_constructed == IS_CONSTRUCTED_CONST: Attempted to access StringManager singleton before it was statically constructed.: in file: '/sarc/spa/users/nhaw/proj/sparta/test/StaticInit/../../sparta/StringManager.h', on line: 121
 * \endverbatim
 */
StaticStuff ss2;

int main()
{
    // Place into a tree
    sstuff.reset(new StaticStuff());

    StatisticSet sset(&sstuff->root);
    StatisticSet cset(&sstuff->dummy);
    Counter ctr(&cset, "a", "Counter A", Counter::COUNT_NORMAL);
    EXPECT_TRUE(sset.isAttached()); // Ensure that node constructed with parent arg is properly attached

    // Done

    // Report errors before drawing trees in case any nodes were attached which
    // should not have been.
    REPORT_ERROR;

    // Render Tree for information purposes

    std::cout << "The tree from the top with builtins: " << std::endl << sstuff->root.renderSubtree(-1, true) << std::endl;
    std::cout << "The tree from the top without builtins: " << std::endl << sstuff->root.renderSubtree() << std::endl;
    std::cout << "The tree from sset: " << std::endl << sset.renderSubtree(-1, true);

    sstuff->root.enterTeardown();
    ss2.root.enterTeardown();

    return ERROR_CODE;
}


text:
/* Copyright (c) 2012, Julian Straub <jstraub@csail.mit.edu>
 * Licensed under the MIT license. See LICENSE.txt or
 * http://www.opensource.org/licenses/mit-license.php */

#pragma once

#include "probabilityHelpers.hpp"

#include <stddef.h>
#include <stdint.h>
#include <typeinfo>

#include <armadillo>

using namespace std;
using namespace arma;

class HDP_var_base
{
  public:

    HDP_var_base(uint32_t K=0, uint32_t T=0, uint32_t Nw=0)
      : mK(K), mT(T), mNw(Nw)
    {};

    void getA(Mat<double>& a)
    {
      a=mA;
    };

    void getPerplexity(Mat<double>& perp)
    {
      perp=mPerp;
    };

    bool getDocTopics(Mat<double>& pi, Mat<double>& sigPi, Mat<uint32_t>& c) const
    {
      uint32_t D=mZeta.size();

      pi.set_size(D,mT);
      sigPi.set_size(D,mT+1);
      c.set_size(D,mT);
      for (uint32_t d=0; d<D; ++d){
        Row<double> cpi(mT);
        Row<double> csigPi(mT+1);
        Row<uint32_t> cc(mT);

        betaMode(cpi,mGamma[d].col(0),mGamma[d].col(1));
        stickBreaking(csigPi,cpi);
        if ( sum(csigPi>1.0)>0)
        {
          cout<<"d="<<d<<endl;
          cout<<"gamma: "<<mGamma[d]<<endl;
          cout<<"cpi="<<cpi<<endl;
          cout<<"csigPi="<<csigPi<<endl;
          cout<<"|csigPi|="<<sum(csigPi)<<endl;
          assert(0);
        }
        for (uint32_t i=0; i<mT; ++i){
          cc[i] = multinomialMode(mZeta[d].row(i));
        }

        //getDocTopics(cpi,csigPi,cc,mGamma[d],mZeta[d]);
        pi.row(d) = cpi;
        sigPi.row(d) = csigPi;
        c.row(d) = cc;
//        cout<<csigPi.t()<<" = "<<sum(csigPi)<<endl;
//        cout<<sigPi.row(d)<<" = "<<sum(sigPi.row(d))<<endl;
      }
      return true;
    };

  /*
   * Gets the indicators for each word pointing to a doc level topic.
   * Need to give it the doc of interest, because all documents have
   * different numbers of words and hence z is different for all docs
   *
   * @param d points to the document of interest.
   */
    bool getWordTopics(Col<uint32_t>& z, uint32_t d) const {
//      cout<<"mPhi -> D="<<mPhi.size()<<endl;
      if (z.n_rows != mPhi[d].n_rows)
      {
//        cout<<"z.rows="<<z.n_rows<<" vs phi_d.rows="<<mPhi[d].n_rows<<endl;
        return false;
      }else{
      return getWordTopics(z,mPhi[d]);
      }
    };

    bool getCorpTopicProportions(Col<double>& v, Col<double>& sigV) const
    {
      return getCorpTopicProportions(v,sigV,mA);
    };

    virtual Row<double> logP_w(uint32_t d) const
    {
      cerr<<"has to be implemented in the child classes!!"<<endl;
      exit(0);
      return Row<double>(1);
    };

//    bool getWordDistr(Mat<double>& p){
//      uint32_t D=mZeta.size();
//      p.set_size(D,mNw);
////      assert(p.n_rows == D);
////      assert(p.n_cols == mNw);
////      cout<<"D="<<D<<endl;
//      for (uint32_t d=0; d<D; ++d){
//        p.row(d) = logP_w(d);
//      }
//      return true;
//    };

protected:
    Mat<double> mA; // corpus level Beta process alpha parameter for stickbreaking
    vector<Mat<double> > mZeta; // document level topic indices/pointers to corpus level topics (Multinomial)
    vector<Mat<double> > mPhi; // document level word to doc level topic assignment (Multinomial)
    vector<Mat<double> > mGamma; // document level Beta distribution alpha parameter for stickbreaking

    Col<double> mPerp; // perplexity for each document

    uint32_t mK; // Corp level truncation
    uint32_t mT; // Doc level truncation
    uint32_t mNw; // size of dictionary

    /*
     * @param a are the parameters of the beta distribution from which v is drawn
     */
    bool getCorpTopicProportions(Col<double>& v, Col<double>& sigV, const Mat<double>& a) const
    {
      uint32_t K = a.n_rows; // corp level topics

      sigV.set_size(K+1);
      v.set_size(K);

      betaMode(v, a.col(0), a.col(1));
      stickBreaking(sigV,v);
      return true;
    };

    bool getDocTopics(Col<double>& pi, Col<double>& sigPi, Col<uint32_t>& c, const Mat<double>& gamma, const Mat<double>& zeta) const
    {
      uint32_t T = gamma.n_rows; // doc level topics

      sigPi.set_size(T+1);
      pi.set_size(T);
      c.set_size(T);

      //cout<<"K="<<K<<" T="<<T<<endl;
      betaMode(pi,gamma.col(0),gamma.col(1));
      stickBreaking(sigPi,pi);
      //cout<<"pi="<<pi<<endl;
      //cout<<"sigPi="<<sigPi<<endl;
      //cout<<"mGamma="<<mGamma[d]<<endl;
      for (uint32_t i=0; i<T; ++i){
        c[i] = multinomialMode(zeta.row(i));
      }
      return true;
    };

    bool getWordTopics(Col<uint32_t>& z, const Mat<double>& phi) const {
//      cout<<phi.n_rows<<" x "<<phi.n_cols<<endl;
      z.set_size(phi.n_rows);
      for (uint32_t i=0; i<z.n_elem; ++i){
        z[i] = multinomialMode(phi.row(i));
      }
      return true;
    };
};

max_stars_repo_name: jstraub/bnp

max_issues_repo_name: jstraub/bnp

max_forks_repo_name: jstraub/bnp


text:
//
// Created by along on 17-11-12.
//
#include "HttpServer.h"

// 用于字符串处理
#include <iostream>
#include <cstring>

// 用于套接字
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

// 用于接收用户的终止命令
#include <csignal>

// 多线程处理
#include <thread>

// 日志处理
#include <boost/log/trivial.hpp>

// 对接收的数据进行处理
#include <vector>
#include <sstream>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <fstream>
#include <wait.h>

using namespace std;

// 宏定义，用于控制缓冲区大小
#define BUF_SIZE     (4096)

// 宏定义，HTTP服务器版本信息
#define SERVER_STRING "Server: miniHttpServer/0.1.0\r\n"

/** 用于接收退出信号 */
void signalHandle(int signum);

HttpServer::HttpServer(const unsigned short &u_port) : port(u_port), serverSock(0) {
    sockaddr_in name{};
    // 初始化
    // 流式 Socket（SOCK_STREAM）是一种面向连接的 Socket，针对于面向连接的 TCP 服务应用
    serverSock = socket(PF_INET, SOCK_STREAM, 0);
    if (-1 == serverSock) {
        BOOST_LOG_TRIVIAL(error) << "Socket Init Failed!";
        exit(EXIT_FAILURE);
    } else
        BOOST_LOG_TRIVIAL(info) << "Socket Init Successfully!";
    memset(&name, 0, sizeof(name));

    // AF_INET 决定了要用 ipv4 地址（32位的）与端口号（16位的）的组合
    name.sin_family = AF_INET;
    // 使用htons进行转序，本机的字节序转换成网路字节序
    name.sin_port = htons(port);
    // 接受任何信息
    name.sin_addr.s_addr = htonl(INADDR_ANY);

    // 地址族中的特定地址赋给socket。
    // 例如对应 AF_INET、AF_INET6就是把一个 ipv4 或 ipv6 地址和端口号组合赋给socket
    if (bind(serverSock, (sockaddr *) &name, sizeof(name)) < 0) {
        BOOST_LOG_TRIVIAL(error) << "Bind Failed!";
        exit(EXIT_FAILURE);
    } else
        BOOST_LOG_TRIVIAL(info) << "Socket Bind Successfully!";

    // port = 0时进行动态分配地址
    if (port == 0) {
        socklen_t nameLen = sizeof(name);
        if (getsockname(serverSock, (sockaddr *) &name, &nameLen) == -1) {
            BOOST_LOG_TRIVIAL(error) << "Get Sock Name Failed!";
            exit(EXIT_FAILURE);
        } else {
            port = ntohs(name.sin_port);
            BOOST_LOG_TRIVIAL(info) << "Dynamically allocating a port!";
        }
    }
    // 对套接字进行监听
    if (listen(serverSock, 5) < 0) {
        BOOST_LOG_TRIVIAL(error) << "Listen Failed!";
        exit(EXIT_FAILURE);
    } else
        BOOST_LOG_TRIVIAL(info) << "Start Listening(port:" << port << ")!";

    // 注册退出程序
    signal(SIGINT, signalHandle);
}

HttpServer::~HttpServer() {
    close(serverSock);
}

void HttpServer::run() {
    sockaddr_in clientName{};
    socklen_t clientNameLen = sizeof(clientName);
    // 建立连接进行处理
    int clientSock = -1;
    while (true) {
        clientSock = accept(serverSock, (sockaddr *) &clientName, &clientNameLen);
        if (-1 == clientSock)
            BOOST_LOG_TRIVIAL(error) << "Accept failed";
        // 开启新进程进行数据处理
        thread requestHandle(acceptRequestWrapper, this, clientSock);
        requestHandle.join();
    }

}

void HttpServer::acceptRequest(int client) {
    /** 缓冲区 */
    char buf[BUF_SIZE];
    memset(buf, 0, sizeof(buf));
    ssize_t msgSize;
    BOOST_LOG_TRIVIAL(info) << "Link(" << client << ") connect";
    msgSize = read(client, buf, sizeof(buf));

    if (msgSize == -1 && errno == EINTR) {
        BOOST_LOG_TRIVIAL(error) << "Read message error";
        exit(EXIT_FAILURE);
    }
    if (msgSize > 0) {
#ifndef NDEBUG
        cout << buf << endl;
#endif
        // 解析报文数据
        HttpParser parser(string(buf, static_cast<unsigned long>(msgSize)));
        HttpExecute execute(parser);
        execute.execute(client);
    }
    close(client);

#ifndef NDEBUG
    BOOST_LOG_TRIVIAL(info) << "Link(" << client << ") closed";
#endif
}

void HttpServer::acceptRequestWrapper(HttpServer *server, int client) {
    server->acceptRequest(client);
}

void signalHandle(int signum) {
    BOOST_LOG_TRIVIAL(info) << "Interrupt signal (" << signum << ") received.";
    exit(signum);
}

HttpParser::HttpParser(std::string msg)
    : method(UNKNOWN), version(ONE), url("./webDocs"), content(""),
      cookie(""), contentType(HTML), cgi(false), contentLen(0) {
    initRequest(getLine(msg));
    for (string line = getLine(msg); !line.empty(); line = getLine(msg)) {
        vector<string> tokens;
        boost::split_regex(tokens, line, boost::regex(": "));
        if (tokens.size() > 1) {
            if (tokens[0] == "Cookie")
                cookie = tokens[1];
            else if (tokens[0] == "Content-Length")
                contentLen = stoul(tokens[1]);
        } else {
            cgi = true;
            content = line;
        }
    }
    if (string::npos != url.find('?')) {
        cgi = true;
        auto pos = url.find('?');
        queryString = url.substr(pos + 1, string::npos);
        url.resize(pos);
    }
    content = msg;
    if (content.size() > 0)
        cgi = true;
    BOOST_LOG_TRIVIAL(info) << "HTML头解析完毕";
}

void HttpParser::initRequest(const string &line) {
    vector<string> tokens;
    boost::algorithm::split(tokens, line, boost::is_any_of(" "));

    // 处理请求方法
    if (tokens[0] == "GET")
        method = GET;
    else if (tokens[0] == "POST")
        method = POST;

    url += tokens[1];
    if (url.at(url.size() - 1) == '/')
        url.append("index.html");
    version = tokens[2] == "1.1" ? ONE : ZERO;
}

/** 从消息中读取一行并把这一行删除掉 */
std::string HttpParser::getLine(std::string &msg) {
    size_t pos = msg.find("\r\n");
    string res = msg.substr(0, pos);
    msg.erase(0, pos + 2);
    return res;
}

HttpExecute::HttpExecute(HttpParser &httpParser) : parser(httpParser) {}

void HttpExecute::execute(int &client) {
    string message;
    ifstream file;
    CONTENT_TYPE contentType;
    if (parser.url.find(".html") != string::npos || parser.url.find(".cgi") != string::npos)
        contentType = HTML;
    else if (parser.url.find(".js") != string::npos)
        contentType = JS;
    else if (parser.url.find(".css") != string::npos)
        contentType = CSS;
    else if (parser.url.find(".svg") != string::npos)
        contentType = SVG;
    else if (parser.url.find(".png") != string::npos)
        contentType = PNG;
    else if (parser.url.find(".jpeg") != string::npos)
        contentType = JPG;
    else if (parser.url.find(".less") != string::npos)
        contentType = LESS;
    else
        contentType = ANY;

    cout << parser.url << endl;

    // 处理各种方法
    switch (parser.method) {
    case GET:
        if (!parser.cgi) {
            file.open(parser.url, ios::binary);
            if (!file) {
                message = notFound();
                message = headers(404, message.size()) + message;
                break;
            }
            message = serveFile(file);
        } else {
            message = executeCgi();
        }
        message = headers(200, message.size(), contentType) + message;
        break;
    case POST:
        if (!parser.cgi) {
            message = notFound();
        } else {
            message = executeCgi();
        }
        message = headers(200, message.size()) + message;
        break;
    default: message = unImplemented();
        message = headers(501, message.size()) + message;
        break;
    }

#ifndef NDEBUG
    cout << message << endl;
#endif
    send(client, message.c_str(), message.size(), 0);
}

string HttpExecute::unImplemented() {
    string msg("<TITLE>Method Not Implemented\r\n");
    msg += "</TITLE>\r\n";
    msg += "
HTTP request method not supported.\r\n";
    msg += "\r\n";
    return msg;
}

string HttpExecute::notFound() {
    string msg("<TITLE>Not Found</TITLE>\r\n");
    msg += "
The server could not fulfill\r\n";
    msg += "your request because the resource specified\r\n";
    msg += "is unavailable or nonexistent.\r\n";
    msg += "\r\n";
    return msg;
}

std::string HttpExecute::headers(unsigned int state, unsigned long contentLen, CONTENT_TYPE type) {
    string header("HTTP/1.1 ");
    switch (state) {
    case 200:header += "200 OK\r\n";
        break;
    case 404:header += "404 NOT FOUND\r\n";
        break;
    case 400:header += "400 BAD REQUEST\r\n";
        break;
    case 501:header += "500 Internal Server Error\r\n";
        break;
    default:header += "501 Method Not Implemented\r\n";
    }
    switch (type) {
    default:
    case HTML:header += "Content-Type: text/html\r\n";
        break;
    case JS:header += "Content-Type: text/javascript\r\n";
        break;
    case CSS:header += "Content-Type: text/css\r\n";
        break;
    case SVG:header += "Content-Type: image/svg\r\n";
        break;
    case PNG:header += "Content-Type: image/png\r\n";
        break;
    case JPG:header += "Content-Type: image/jpeg\r\n";
        break;
    case LESS:header += "Content-Type: text/less\r\n";
        break;
    case ANY:header += "Content-Type: */*\r\n";
        break;
    }
    header += "Content-Length: " + to_string(contentLen) + "\r\nConnection: close\r\n\r\n";
    return header;
}

std::string HttpExecute::serveFile(std::istream &file) {
    string msg;
    char aByte;
    while (!file.eof()) {
        file.read(&aByte, sizeof(char));
        msg += aByte;
    }
    return msg;
}

std::string HttpExecute::cannotExecute() {
    return "
Error prohibited CGI execution.\r\n";
}

std::string HttpExecute::executeCgi() {
    pid_t pid;
    // cgi管道重定向
    int cgiInput[2];
    int cgiOutput[2];

    int status;

    string msg;

    if ((pipe(cgiInput) < 0) || (pipe(cgiOutput) < 0) || ((pid = fork()) < 0))
        return cannotExecute();

    if (0 == pid) { /** 子进程 */
        dup2(cgiOutput[1], 1);
        dup2(cgiInput[0], 0);
        close(cgiOutput[0]);
        close(cgiInput[1]);
        execl(parser.url.c_str(), parser.queryString.c_str(), nullptr);

        BOOST_LOG_TRIVIAL(info) << "CGI执行完毕";

        exit(EXIT_SUCCESS);
    } else { /** 父进程 */
        close(cgiOutput[1]);
        close(cgiInput[0]);

        if (parser.method == POST) {
            write(cgiInput[1], parser.content.c_str(), parser.content.size());
        }
        char ch;
        while (read(cgiOutput[0], &ch, 1) > 0)
            msg += ch;
        close(cgiOutput[0]);
        close(cgiInput[1]);
        waitpid(pid, &status, 0);
    }

    return msg;
}

max_stars_repo_name: AlongWY/HIT-WorkShop

max_issues_repo_name: AlongWY/HIT-WorkShop

max_forks_repo_name: AlongWY/HIT-WorkShop


text:
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 Sylko Olzscher
 *
 */

#include <smf/http/srv/server.h>
#include <smf/http/srv/session.h>
#include <smf/cluster/generator.h>

#include <cyng/vm/controller.h>

#include <boost/uuid/uuid_io.hpp>

namespace node
{
	namespace http
	{

		server::server(cyng::logging::log_ptr logger
			, boost::asio::io_context& ioc
			, boost::asio::ip::tcp::endpoint endpoint
			, std::string const& doc_root
			, std::string const& blog_root
#ifdef NODE_SSL_INSTALLED
			, auth_dirs const& ad
#endif
			, std::set<boost::asio::ip::address> const& blacklist
			, cyng::controller& vm
			, bool https_rewrite)
		: logger_(logger)
			, acceptor_(ioc)
			, socket_(ioc)
			, blacklist_(blacklist)
			, connection_manager_(logger
				, vm
				, doc_root
#ifdef NODE_SSL_INSTALLED
				, ad
#endif
				, https_rewrite)
			, is_listening_(false)
			, shutdown_complete_()
			, mutex_()
			, uidgen_()
		{
			boost::system::error_code ec;

			// Open the acceptor
			acceptor_.open(endpoint.protocol(), ec);
			if (ec)
			{
				CYNG_LOG_FATAL(logger_, "open: " << ec.message());
				return;
			}
			CYNG_LOG_TRACE(logger_, "open: " << endpoint.address().to_string() << ':' << endpoint.port());

			// Allow address reuse
			acceptor_.set_option(boost::asio::socket_base::reuse_address(true));
			if (ec)
			{
				CYNG_LOG_FATAL(logger_, "allow address reuse: " << ec.message());
				//BOOST_ASSERT_MSG(!ec, "SET_OPTION");
				return;
			}

			// Bind to the server address
			if (!bind(endpoint, 16))	return;
			CYNG_LOG_TRACE(logger_, "bind: " << endpoint.address().to_string() << ':' << endpoint.port());

			// Start listening for connections
			acceptor_.listen(boost::asio::socket_base::max_listen_connections, ec);
			if (ec)
			{
				CYNG_LOG_FATAL(logger_, "listen: " << ec.message());
				return;
			}
		}

		connection_manager_interface& server::get_cm()
		{
			return connection_manager_;
		}

        bool server::bind(boost::asio::ip::tcp::endpoint ep, std::size_t retries)
		{
			boost::system::error_code ec;

			do
            {
                acceptor_.bind(ep, ec);
                if (ec)
                {
                    CYNG_LOG_FATAL(logger_, "bind: " << ec.message());
                    std::this_thread::sleep_for(std::chrono::seconds(10));
                }
            } while(ec && (retries-- > 0u));

            return !ec;
		}

		// Start accepting incoming connections
		bool server::run()
		{
			//
			//	set listener flag immediately to prevent
			//	a concurrent call of this same
			//	method
			//
			if (acceptor_.is_open() && !is_listening_.exchange(true))
			{
				do_accept();
			}
			else
			{
				CYNG_LOG_WARNING(logger_, "acceptor closed");
			}
			return is_listening_;
		}

		void server::do_accept()
		{
			acceptor_.async_accept(
				socket_,
				std::bind(
					&server::on_accept,
					this,
					std::placeholders::_1));
		}

		void server::on_accept(boost::system::error_code ec)
		{
			if (ec)
			{
				CYNG_LOG_ERROR(logger_, "accept: " << ec.message());

				//
				//	remove listener flag
				//
				is_listening_.exchange(false);

				//
				//	notify
				//
				cyng::async::lock_guard<cyng::async::mutex> lk(mutex_);
				shutdown_complete_.notify_all();

				return;
			}
			else
			{
				//	since C++20 use contains()
				auto pos = blacklist_.find(socket_.remote_endpoint().address());
				if (pos != blacklist_.end()) {

					CYNG_LOG_WARNING(logger_, "address "
						<< socket_.remote_endpoint()
						<< " is blacklisted");
					socket_.close();

					std::stringstream ss;
					ss
						<< "access from blacklisted address: "
						<< *pos
						;
					connection_manager_.vm().async_run(cyng::generate_invoke("log.msg.warning", ss.str()));
				}
				else {

					const auto tag = uidgen_();

					CYNG_LOG_TRACE(logger_, "accept "
						<< socket_.remote_endpoint()
						<< " - "
						<< tag);

					// Create the http_session and run it
					connection_manager_.create_session(std::move(socket_));
				}

				// Accept another connection
				do_accept();

			}
		}

		void server::close()
		{
			if (is_listening_)
			{
				acceptor_.cancel();
				acceptor_.close();

				cyng::async::unique_lock<cyng::async::mutex> lock(mutex_);

				CYNG_LOG_TRACE(logger_, "listener is waiting for cancellation");
				//	wait for cancellation of accept operation
				shutdown_complete_.wait(lock, [this] {
					return !is_listening_.load();
				});
				CYNG_LOG_TRACE(logger_, "listener cancellation complete");

				//
				//	stop all connections
				//
				CYNG_LOG_INFO(logger_, "stop all connections");
				connection_manager_.stop_all();

			}
		}
	}
}

max_stars_repo_name: solosTec/node

max_issues_repo_name: solosTec/node

max_forks_repo_name: solosTec/node


text:
/*
 *
 * Copyright (c) 2004
 * John Maddock
 *
 * Use, modification and distribution are subject to the
 * Boost Software License, Version 1.0. (See accompanying file
 * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 *
 */

 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         main.cpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: entry point for test program.
  */

#include "test.hpp"
#include "test_locale.hpp"
#include <stdarg.h>

#ifdef BOOST_HAS_ICU
#include <unicode/uloc.h>
#endif

#ifdef TEST_THREADS
#include <list>
#include <boost/thread.hpp>
#include <boost/thread/tss.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/array.hpp>

int* get_array_data();

#endif

int error_count = 0;

#ifndef TEST_THREADS
#define RUN_TESTS(name) \
   std::cout << "Running test case \"" #name "\".\n";\
   name();
#else
#define RUN_TESTS(name) \
   name();
#endif

void run_tests()
{
   RUN_TESTS(basic_tests);
   RUN_TESTS(test_simple_repeats);
   RUN_TESTS(test_alt);
   RUN_TESTS(test_sets);
   RUN_TESTS(test_sets2);
   RUN_TESTS(test_anchors);
   RUN_TESTS(test_backrefs);
   RUN_TESTS(test_character_escapes);
   RUN_TESTS(test_assertion_escapes);
   RUN_TESTS(test_tricky_cases);
   RUN_TESTS(test_grep);
   RUN_TESTS(test_replace);
   RUN_TESTS(test_non_greedy_repeats);
   RUN_TESTS(test_non_marking_paren);
   RUN_TESTS(test_partial_match);
   RUN_TESTS(test_forward_lookahead_asserts);
   RUN_TESTS(test_fast_repeats);
   RUN_TESTS(test_fast_repeats2);
   RUN_TESTS(test_independent_subs);
   RUN_TESTS(test_nosubs);
   RUN_TESTS(test_conditionals);
   RUN_TESTS(test_options);
   RUN_TESTS(test_options2);
#ifndef TEST_THREADS
   RUN_TESTS(test_en_locale);
#endif
   RUN_TESTS(test_emacs);
   RUN_TESTS(test_operators);
   RUN_TESTS(test_overloads);
   RUN_TESTS(test_unicode);
   RUN_TESTS(test_pocessive_repeats);
   RUN_TESTS(test_mark_resets);
   RUN_TESTS(test_recursion);
}

int cpp_main(int /*argc*/, char * /*argv*/[])
{
#ifdef BOOST_HAS_ICU
   //
   // We need to set the default locale used by ICU,
   // otherwise some of our tests using equivalence classes fail.
   //
   UErrorCode err = U_ZERO_ERROR;
   uloc_setDefault("en", &err);
   if(err != U_ZERO_ERROR)
   {
      std::cerr << "Unable to set the default ICU locale to \"en\"." << std::endl;
      return -1;
   }
#endif
#ifdef TEST_THREADS
   try{
      get_array_data();  // initialises data.
   }
   catch(const std::exception& e)
   {
      std::cerr << "TSS Initialisation failed with message: " << e.what() << std::endl;
      return -1;
   }

   std::list<boost::shared_ptr<boost::thread> > threads;
   for(int i = 0; i < 5; ++i)
   {
      try{
         threads.push_back(boost::shared_ptr<boost::thread>(new boost::thread(&run_tests)));
      }
      catch(const std::exception& e)
      {
         std::cerr << "<note>Thread creation failed with message: " << e.what() << "</note>" << std::endl;
      }
   }
   std::list<boost::shared_ptr<boost::thread> >::const_iterator a(threads.begin()), b(threads.end());
   while(a != b)
   {
      (*a)->join();
      ++a;
   }
#else
   run_tests();
#endif
   return error_count;
}

#ifdef TEST_THREADS

int* get_array_data()
{
   static boost::thread_specific_ptr<boost::array<int, 200> > tp;

   if(tp.get() == 0)
      tp.reset(new boost::array<int, 200>);

   return tp.get()->data();
}

#endif

const int* make_array(int first, ...)
{
   //
   // this function takes a variable number of arguments
   // and packs them into an array that we can pass through
   // our testing macros (ideally we would use an array literal
   // but these can't apparently be used as macro arguments).
   //
#ifdef TEST_THREADS
   int* data = get_array_data();
#else
   static int data[200];
#endif
   va_list ap;
   va_start(ap, first);
   //
   // keep packing args, until we get two successive -2 values:
   //
   int terminator_count;
   int next_position = 1;
   data[0] = first;
   if(first == -2)
      terminator_count = 1;
   else
      terminator_count = 0;
   while(terminator_count < 2)
   {
      data[next_position] = va_arg(ap, int);
      if(data[next_position] == -2)
         ++terminator_count;
      else
         terminator_count = 0;
      ++next_position;
   }
   va_end(ap);
   return data;
}

#ifdef BOOST_NO_EXCEPTIONS

namespace boost{

void throw_exception(std::exception const & e)
{
   std::abort();
}

}

#endif

void test(const char& c, const test_regex_replace_tag& tag)
{
   do_test(c, tag);
}
void test(const char& c, const test_regex_search_tag& tag)
{
   do_test(c, tag);
}
void test(const char& c, const test_invalid_regex_tag& tag)
{
   do_test(c, tag);
}

#ifndef BOOST_NO_WREGEX
void test(const wchar_t& c, const test_regex_replace_tag& tag)
{
   do_test(c, tag);
}
void test(const wchar_t& c, const test_regex_search_tag& tag)
{
   do_test(c, tag);
}
void test(const wchar_t& c, const test_invalid_regex_tag& tag)
{
   do_test(c, tag);
}
#endif

#ifdef BOOST_NO_EXCETIONS
namespace boost{

void throw_exception( std::exception const & e )
{
   std::cerr << e.what() << std::endl;
   std::exit(1);
}

}
#endif

#include <boost/test/included/prg_exec_monitor.hpp>


text:
#include <dlib/string.h>
#include <dlib/string/string.h>
#include <iostream>
#include <istream>
#include <map>
#include <queue>
#include <set>
#include <string>

std::map<std::string, std::vector<std::string>> graph;
std::map<std::string, std::vector<std::string>> reverse_graph;

int max_depth;
std::string conflict;
std::string conflict_parent;

std::vector<std::string> list;

void DFS(const std::string &current) {
  for (auto i = list.cbegin(); i != list.cend(); ++i) {
    if (*i == current) {
      conflict_parent = current;
      conflict = list.back();
      return;
    }
  }

  list.push_back(current);

  if (list.size() > max_depth) {
    max_depth = list.size();
  }

  if (list.size() == 18) {
    for (const auto &s : list) {
      std::cout << s << "->";
    }
    std::cout << "The End!!!" << std::endl;
  }

  for (const auto &s : graph[current]) {
    DFS(s);
  }

  list.pop_back();
}

void DFS() {
  for (const auto &[k, v] : reverse_graph) {
    if (v.empty()) {
      list.clear();
      DFS(k);
    }
  }
}

std::vector<std::string> SplitBySpace(const std::string &s) {
  std::vector<std::string> result;
  int current_pos = 0;

  while (true) {
    auto p = s.find_first_of(" ", current_pos);
    if (p == std::string::npos) {
      result.push_back(std::string(s.cbegin() + current_pos, s.cend()));
      break;
    } else {
      result.push_back(std::string(s.cbegin() + current_pos, s.cbegin() + p));
      current_pos = p + 1;
    }
  }

  return result;
}

int main() {
  std::string s;
  while (std::getline(std::cin, s)) {
    auto result = SplitBySpace(s);

    std::string parent = result.front();

    graph[parent];
    reverse_graph[parent];

    for (auto i = result.cbegin() + 1; i != result.cend(); i++) {
      graph[parent].push_back(*i);
      reverse_graph[*i].push_back(parent);
    }
  }

  std::cout << "We have " << graph.size() << " items.\n";
  std::cout << "We have " << reverse_graph.size() << " parent items.\n";

  DFS();

  std::cout << conflict << "->" << conflict_parent << '\n';
  std::cout << "Max depth: " << max_depth << '\n';

  return 0;
}

max_stars_repo_name: crupest/what-can-a-programmer-do

max_issues_repo_name: crupest/what-can-a-programmer-do

max_forks_repo_name: crupest/what-can-a-programmer-do


text:
/**
 * Copyright (C) 2015 MongoDB Inc.
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * As a special exception, the copyright holders give permission to link the
 * code of portions of this program with the OpenSSL library under certain
 * conditions as described in each individual source file and distribute
 * linked combinations including the program with the OpenSSL library. You
 * must comply with the GNU Affero General Public License in all respects
 * for all of the code used other than as permitted herein. If you modify
 * file(s) with this exception, you may extend this exception to your
 * version of the file(s), but you are not obligated to do so. If you do not
 * wish to do so, delete this exception statement from your version. If you
 * delete this exception statement from all source files in the program,
 * then also delete it in the license file.
 */

#include "mongo/platform/basic.h"

#include "mongo/scripting/mozjs/numberlong.h"

#include <boost/optional.hpp>
#include <js/Conversions.h>

#include "mongo/scripting/mozjs/implscope.h"
#include "mongo/scripting/mozjs/objectwrapper.h"
#include "mongo/scripting/mozjs/valuereader.h"
#include "mongo/scripting/mozjs/valuewriter.h"
#include "mongo/scripting/mozjs/wrapconstrainedmethod.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/represent_as.h"
#include "mongo/util/text.h"

namespace mongo {
namespace mozjs {

const JSFunctionSpec NumberLongInfo::methods[6] = {
    MONGO_ATTACH_JS_CONSTRAINED_METHOD(toNumber, NumberLongInfo),
    MONGO_ATTACH_JS_CONSTRAINED_METHOD(toString, NumberLongInfo),
    MONGO_ATTACH_JS_CONSTRAINED_METHOD(toJSON, NumberLongInfo),
    MONGO_ATTACH_JS_CONSTRAINED_METHOD(valueOf, NumberLongInfo),
    MONGO_ATTACH_JS_CONSTRAINED_METHOD(compare, NumberLongInfo),
    JS_FS_END};

const char* const NumberLongInfo::className = "NumberLong";

void NumberLongInfo::finalize(JSFreeOp* fop, JSObject* obj) {
    auto numLong = static_cast<int64_t*>(JS_GetPrivate(obj));

    if (numLong)
        getScope(fop)->trackedDelete(numLong);
}

int64_t NumberLongInfo::ToNumberLong(JSContext* cx, JS::HandleValue thisv) {
    auto numLong = static_cast<int64_t*>(JS_GetPrivate(thisv.toObjectOrNull()));
    return numLong ? *numLong : 0;
}

int64_t NumberLongInfo::ToNumberLong(JSContext* cx, JS::HandleObject thisv) {
    auto numLong = static_cast<int64_t*>(JS_GetPrivate(thisv));
    return numLong ? *numLong : 0;
}

void NumberLongInfo::Functions::valueOf::call(JSContext* cx, JS::CallArgs args) {
    int64_t out = NumberLongInfo::ToNumberLong(cx, args.thisv());
    ValueReader(cx, args.rval()).fromDouble(out);
}

void NumberLongInfo::Functions::toNumber::call(JSContext* cx, JS::CallArgs args) {
    valueOf::call(cx, args);
}

void NumberLongInfo::Functions::toString::call(JSContext* cx, JS::CallArgs args) {
    str::stream ss;

    int64_t val = NumberLongInfo::ToNumberLong(cx, args.thisv());

    const int64_t limit = 2LL << 30;

    if (val <= -limit || limit <= val)
        ss << "NumberLong(\"" << val << "\")";
    else
        ss << "NumberLong(" << val << ")";

    ValueReader(cx, args.rval()).fromStringData(ss.operator std::string());
}

void NumberLongInfo::Functions::toJSON::call(JSContext* cx, JS::CallArgs args) {
    int64_t val = NumberLongInfo::ToNumberLong(cx, args.thisv());

    ValueReader(cx, args.rval())
        .fromBSON(BSON("$numberLong" << std::to_string(val)), nullptr, false);
}

void NumberLongInfo::Functions::compare::call(JSContext* cx, JS::CallArgs args) {
    uassert(ErrorCodes::BadValue, "NumberLong.compare() needs 1 argument", args.length() == 1);
    uassert(ErrorCodes::BadValue,
            "NumberLong.compare() argument must be a NumberLong",
            getScope(cx)->getProto<NumberLongInfo>().instanceOf(args.get(0)));

    int64_t thisVal = NumberLongInfo::ToNumberLong(cx, args.thisv());
    int64_t otherVal = NumberLongInfo::ToNumberLong(cx, args.get(0));

    int comparison = 0;
    if (thisVal < otherVal) {
        comparison = -1;
    } else if (thisVal > otherVal) {
        comparison = 1;
    }

    ValueReader(cx, args.rval()).fromDouble(comparison);
}

void NumberLongInfo::Functions::floatApprox::call(JSContext* cx, JS::CallArgs args) {
    int64_t numLong = NumberLongInfo::ToNumberLong(cx, args.thisv());
    ValueReader(cx, args.rval()).fromDouble(numLong);
}

void NumberLongInfo::Functions::top::call(JSContext* cx, JS::CallArgs args) {
    auto numULong = static_cast<uint64_t>(NumberLongInfo::ToNumberLong(cx, args.thisv()));
    ValueReader(cx, args.rval()).fromDouble(numULong >> 32);
}

void NumberLongInfo::Functions::bottom::call(JSContext* cx, JS::CallArgs args) {
    auto numULong = static_cast<uint64_t>(NumberLongInfo::ToNumberLong(cx, args.thisv()));
    ValueReader(cx, args.rval()).fromDouble(numULong & 0x00000000FFFFFFFF);
}

void NumberLongInfo::construct(JSContext* cx, JS::CallArgs args) {
    uassert(ErrorCodes::BadValue,
            "NumberLong needs 0, 1 or 3 arguments",
            args.length() == 0 || args.length() == 1 || args.length() == 3);

    auto scope = getScope(cx);

    JS::RootedObject thisv(cx);

    scope->getProto<NumberLongInfo>().newObject(&thisv);

    int64_t numLong;

    ObjectWrapper o(cx, thisv);

    if (args.length() == 0) {
        numLong = 0;
    } else if (args.length() == 1) {
        auto arg = args.get(0);

        if (arg.isInt32()) {
            numLong = arg.toInt32();
        } else if (arg.isDouble()) {
            auto opt = representAs<int64_t>(arg.toDouble());
            uassert(ErrorCodes::BadValue,
                    "number passed to NumberLong must be representable as an int64_t",
                    opt);
            numLong = *opt;
        } else if (arg.isString()) {
            // For string values we call strtoll because we expect non-number string
            // values to fail rather than return 0 (which is the behavior of ToInt64).
            std::string str = ValueWriter(cx, arg).toString();
            numLong = parseLL(str.c_str());
        } else {
            numLong = ValueWriter(cx, arg).toInt64();
        }
    } else {
        uassert(ErrorCodes::BadValue, "floatApprox must be a number", args.get(0).isNumber());
        uassert(ErrorCodes::BadValue, "top must be a number", args.get(1).isNumber());
        uassert(ErrorCodes::BadValue, "bottom must be a number", args.get(2).isNumber());

        auto topOpt = representAs<uint32_t>(args.get(1).toNumber());
        uassert(ErrorCodes::BadValue, "top must be a 32 bit unsigned number", topOpt);
        uint64_t top = *topOpt;

        auto botOpt = representAs<uint32_t>(args.get(2).toNumber());
        uassert(ErrorCodes::BadValue, "bottom must be a 32 bit unsigned number", botOpt);
        uint64_t bot = *botOpt;

        numLong = (top << 32) + bot;
    }

    JS_SetPrivate(thisv, scope->trackedNew<int64_t>(numLong));

    args.rval().setObjectOrNull(thisv);
}

void NumberLongInfo::postInstall(JSContext* cx, JS::HandleObject global, JS::HandleObject proto) {
    JS::RootedValue undef(cx);
    undef.setUndefined();

    // floatapprox
    if (!JS_DefinePropertyById(
            cx,
            proto,
            getScope(cx)->getInternedStringId(InternedString::floatApprox),
            undef,
            JSPROP_ENUMERATE | JSPROP_SHARED,
            smUtils::wrapConstrainedMethod<Functions::floatApprox, false, NumberLongInfo>,
            nullptr)) {
        uasserted(ErrorCodes::JSInterpreterFailure, "Failed to JS_DefinePropertyById");
    }

    // top
    if (!JS_DefinePropertyById(
            cx,
            proto,
            getScope(cx)->getInternedStringId(InternedString::top),
            undef,
            JSPROP_ENUMERATE | JSPROP_SHARED,
            smUtils::wrapConstrainedMethod<Functions::top, false, NumberLongInfo>,
            nullptr)) {
        uasserted(ErrorCodes::JSInterpreterFailure, "Failed to JS_DefinePropertyById");
    }

    // bottom
    if (!JS_DefinePropertyById(
            cx,
            proto,
            getScope(cx)->getInternedStringId(InternedString::bottom),
            undef,
            JSPROP_ENUMERATE | JSPROP_SHARED,
            smUtils::wrapConstrainedMethod<Functions::bottom, false, NumberLongInfo>,
            nullptr)) {
        uasserted(ErrorCodes::JSInterpreterFailure, "Failed to JS_DefinePropertyById");
    }
}

}  // namespace mozjs
}  // namespace mongo

max_stars_repo_name: sgweon/mongo

max_issues_repo_name: bjori/mongo

max_forks_repo_name: bjori/mongo


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

#ifndef MOOST_SERIALIZATION_HASH_MAP_SERIALISER_HPP__
#define MOOST_SERIALIZATION_HASH_MAP_SERIALISER_HPP__

/*!
 * Serialization of moost (Google) sparse and dense hashmap types
 */

#include "../container/sparse_hash_map.hpp"
#include "../container/dense_hash_map.hpp"

#include <boost/mpl/if.hpp>

namespace moost { namespace serialization {
   struct hash_map_save__
   {
      template<typename archiveT, typename mapT>
         static void serialize(archiveT & ar, mapT const & map, const unsigned int /*version*/)
      {
         // force 64 bit for portability
         boost::int64_t size = map.size();
         ar.save_binary(&size , sizeof(size));

         for(typename mapT::const_iterator itr = map.begin() ; itr != map.end() ; ++itr)
         {
            ar << itr->first;
            ar << itr->second;
         }
      }
   };

   struct hash_map_load__
   {
      template<typename archiveT, typename mapT>
         static void serialize(archiveT & ar, mapT & map, const unsigned int /*version*/)
      {
         // force 64 bit for portability
         boost::int64_t size = 0;
         ar.load_binary(&size , sizeof(size));
         map.resize(boost::numeric_cast<size_t>(size)); // make sure the cast back to size_t is safe

         typename mapT::key_type k;

         while(size-- > 0)
         {
            ar >> k;
            ar >> map[k];
         }
      }
   };
}}

namespace boost { // this really does have to be in the boost namespace for ADL to work properly :(
   namespace serialization {

      template<typename archiveT, typename Key, typename Data, typename HashFcn, typename EqualKey, typename Alloc>
      void serialize(archiveT & ar, moost::container::sparse_hash_map<Key, Data, HashFcn, EqualKey, Alloc> & map, const unsigned int version)
      {
         boost::mpl::if_<
            typename archiveT::is_saving,
            moost::serialization::hash_map_save__,
            moost::serialization::hash_map_load__
         >::type::serialize(ar, map, version);
      }

      template<typename archiveT, typename Key, typename Data, typename HashFcn, typename EqualKey, typename Alloc>
      void serialize(archiveT & ar, moost::container::dense_hash_map<Key, Data, HashFcn, EqualKey, Alloc> & map, const unsigned int version)
      {
         boost::mpl::if_<
            typename archiveT::is_saving,
            moost::serialization::hash_map_save__,
            moost::serialization::hash_map_load__
         >::type::serialize(ar, map, version);
      }
   }
}

#endif /// MOOST_SERIALIZATION_HASH_MAP_SERIALISER_HPP__

max_stars_repo_name: lastfm/libmoost

max_issues_repo_name: lastfm/libmoost

max_forks_repo_name: lastfm/libmoost


text:
//  Copyright 2018 Stephan Menzel. 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)

#pragma once
#include "MRedisConfig.hpp"
#include "MRedisResult.hpp"
#include "MRedisTypes.hpp"

#include <boost/variant.hpp>
#include <boost/cstdint.hpp>
#include <boost/asio/streambuf.hpp>

#include <iostream>
#include <string>
#include <chrono>

namespace moose {
namespace mredis {

/*! Raw protocol implementation
 */

// debug
MREDIS_API bool parse(const std::string &n_input, RedisMessage &n_response);

MREDIS_API RedisMessage parse_one(std::istream &n_is);

/*! Parse one message from the stream.
	@return false on cannot parse any
 */
MREDIS_API bool parse_from_stream(std::istream &n_is, RedisMessage &n_response) noexcept;

/*! Parse one message from the streambuf and consume if successful.
	@return false on cannot parse any
 */
MREDIS_API bool parse_from_streambuf(boost::asio::streambuf &n_streambuf, RedisMessage &n_response) noexcept;

/*! Generate to stream
	Mostly for testing
 */
MREDIS_API void generate_to_stream(std::ostream &n_os, const RedisMessage &n_message);

}
}

max_stars_repo_name: MrMoose/mredis

max_issues_repo_name: MrMoose/mredis

max_forks_repo_name: MrMoose/mredis


text:
#include <complex>
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <boost/circular_buffer.hpp>
#include <range/v3/all.hpp>
#include <cstdint>
#include <initializer_list>
#include <iterator>
namespace views = ranges::views;
using Buffer = boost::circular_buffer<int>;
class Knothash
{
  Buffer ring_;
  std::vector<int> sequencelen_;
  int skiplen_ = 0;
  int curpos_ = 0;
  void reverse(int start, int len)
  {
    for (auto i = 0; i < len / 2; ++i) {
      int b = (start + i) % ring_.size();
      int r = (start + len - 1 - i) % ring_.size();
      std::swap(ring_[b], ring_[r]);
    }
  }

public:
  Knothash(int n, std::initializer_list<int> l) : ring_(n), sequencelen_(l)
  {
    for (int i = 0; i < n; ++i) {
      ring_.push_back(i);
    }
  }
  void hash()
  {
    for (auto l : sequencelen_) {
      reverse(curpos_, l);
      curpos_ += l + skiplen_;
      ++skiplen_;
    }
  }
  int final() const
  {
    return ring_[0] * ring_[1];
  }
};
int main()
{
  //Knothash h(5, { 3, 4, 1, 5 });
  Knothash h(256, { 187, 254, 0, 81, 169, 219, 1, 190, 19, 102, 255, 56, 46, 32, 2, 216 });
  h.hash();
  int n = h.final();
  std::cout << n << std::endl;
}

max_stars_repo_name: jiayuehua/adventOfCode

max_issues_repo_name: jiayuehua/adventOfCode

max_forks_repo_name: jiayuehua/adventOfCode


text:
//  (C) Copyright John Maddock 2018.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/math/tools/series.hpp>
#include <iostream>
#include <complex>
#include <cassert>

//[series_log1p
template <class T>
struct log1p_series
{
   // we must define a result_type typedef:
   typedef T result_type;

   log1p_series(T x)
      : k(0), m_mult(-x), m_prod(-1) {}

   T operator()()
   {
      // This is the function operator invoked by the summation
      // algorithm, the first call to this operator should return
      // the first term of the series, the second call the second
      // term and so on.
      m_prod *= m_mult;
      return m_prod / ++k;
   }

private:
   int k;
   const T m_mult;
   T m_prod;
};
//]

//[series_log1p_func
template <class T>
T log1p(T x)
{
   // We really should add some error checking on x here!
   assert(std::fabs(x) < 1);

   // Construct the series functor:
   log1p_series<T> s(x);
   // Set a limit on how many iterations we permit:
   boost::uintmax_t max_iter = 1000;
   // Add it up, with enough precision for full machine precision:
   return boost::math::tools::sum_series(s, std::numeric_limits<T>::epsilon(), max_iter);
}
//]

//[series_clog1p_func
template <class T>
struct log1p_series<std::complex<T> >
{
   // we must define a result_type typedef:
   typedef std::complex<T> result_type;

   log1p_series(std::complex<T> x)
      : k(0), m_mult(-x), m_prod(-1) {}

   std::complex<T> operator()()
   {
      // This is the function operator invoked by the summation
      // algorithm, the first call to this operator should return
      // the first term of the series, the second call the second
      // term and so on.
      m_prod *= m_mult;
      return m_prod / T(++k);
   }

private:
   int k;
   const std::complex<T> m_mult;
   std::complex<T> m_prod;
};

template <class T>
std::complex<T> log1p(std::complex<T> x)
{
   // We really should add some error checking on x here!
   assert(abs(x) < 1);

   // Construct the series functor:
   log1p_series<std::complex<T> > s(x);
   // Set a limit on how many iterations we permit:
   boost::uintmax_t max_iter = 1000;
   // Add it up, with enough precision for full machine precision:
   return boost::math::tools::sum_series(s, std::complex<T>(std::numeric_limits<T>::epsilon()), max_iter);
}
//]

int main()
{
   using namespace boost::math::tools;

   std::cout << log1p(0.25) << std::endl;

   std::cout << log1p(std::complex<double>(0.25, 0.25)) << std::endl;

   return 0;
}


text:
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <thread>
#include <functional>
#include <iostream>

void reset(boost::shared_ptr<int> &sh)
{
  sh.reset();
}

void print(boost::weak_ptr<int> &w)
{
  boost::shared_ptr<int> sh = w.lock();
  if (sh)
    std::cout << *sh << '\n';
}

int main()
{
  boost::shared_ptr<int> sh{new int{99}};
  boost::weak_ptr<int> w{sh};
  std::thread t1{reset, std::ref(sh)};
  std::thread t2{print, std::ref(w)};
  t1.join();
  t2.join();
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
/*
 * Copyright (C) 2012-2016 Open Source Robotics Foundation
 *
 * 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 <boost/filesystem.hpp>
#include "gazebo/test/ServerFixture.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/test/helper_physics_generator.hh"

using namespace gazebo;
class PR2Test : public ServerFixture,
                public testing::WithParamInterface<const char*>
{
  public: void LoadPR2(std::string _physicsEngine);
  public: void ScrewJoint(std::string _physicsEngine);
  public: void StaticPR2(std::string _physicsEngine);
};

////////////////////////////////////////////////////////////////////////
void PR2Test::LoadPR2(std::string _physicsEngine)
{
  if (_physicsEngine == "dart")
  {
    gzerr << "Abort test since dart does not support ray sensor in PR2, "
          << "Please see issue #911.\n";
    return;
  }

  // Cleanup test directory.
  common::SystemPaths *paths = common::SystemPaths::Instance();
  boost::filesystem::remove_all(paths->GetDefaultTestPath());
  boost::filesystem::create_directories(paths->GetDefaultTestPath());

  ServerFixture::Load("worlds/empty.world", false, _physicsEngine);
  SpawnModel("model://pr2");

  int i;
  for (i = 0; i < 1000 && !this->HasEntity("pr2"); ++i)
    common::Time::MSleep(1000);
  EXPECT_LT(i, 1000);

  if (rendering::RenderEngine::Instance()->GetRenderPathType() ==
      rendering::RenderEngine::NONE)
    return;

  sensors::SensorPtr sensor =
    sensors::get_sensor("narrow_stereo_gazebo_l_stereo_camera_sensor");
  EXPECT_TRUE(sensor != NULL);

  sensors::CameraSensorPtr camSensor =
    std::dynamic_pointer_cast<sensors::CameraSensor>(sensor);
  EXPECT_TRUE(camSensor != NULL);

  while (!camSensor->SaveFrame(paths->GetDefaultTestPath() + "/frame_10.jpg"))
    common::Time::MSleep(100);

  physics::get_world("default")->GetPhysicsEngine()->SetGravity(
      math::Vector3(-0.5, 0, -0.1));
  for (int i = 11; i < 200; i++)
  {
    std::ostringstream filename;
    filename << paths->GetDefaultTestPath() << "/frame_" << i << ".jpg";
    camSensor->SaveFrame(filename.str());
    common::Time::MSleep(100);
  }

  // Cleanup test directory.
  boost::filesystem::remove_all(paths->GetDefaultTestPath());
}

TEST_P(PR2Test, LoadPR2)
{
  LoadPR2(GetParam());
}

////////////////////////////////////////////////////////////////////////
void PR2Test::ScrewJoint(std::string _physicsEngine)
{
  if (_physicsEngine == "bullet")
  {
    gzerr << "Abort test since bullet screw joints don't work yet\n";
    return;
  }
  if (_physicsEngine == "dart")
  {
    gzerr << "Abort test since dart does not support ray sensor in PR2, "
          << "Please see issue #911.\n";
    return;
  }

  ServerFixture::Load("worlds/pr2.world", true, _physicsEngine);
  physics::WorldPtr world = physics::get_world("default");
  ASSERT_TRUE(world != NULL);

  // check the physics engine type
  physics::PhysicsEnginePtr physics = world->GetPhysicsEngine();
  ASSERT_TRUE(physics != NULL);
  EXPECT_EQ(physics->GetType(), _physicsEngine);

  physics::ModelPtr model = world->GetModel("pr2");
  ASSERT_TRUE(model != NULL);

  physics::LinkPtr link = model->GetLink("torso_lift_link");
  ASSERT_TRUE(link != NULL);

  physics::JointPtr motor = model->GetJoint("torso_lift_motor_screw_joint");
  ASSERT_TRUE(motor != NULL);
  motor->SetEffortLimit(0, 1000);

  physics::JointPtr screw =
    model->GetJoint("torso_lift_screw_torso_lift_joint");
  ASSERT_TRUE(screw != NULL);

  // Let it settle a bit
  world->Step(300);

  // Set a fixed velocity on revolute joint that connects to the screw joint
  unsigned int steps = 1000;
  for (unsigned int i = 0; i < steps; ++i)
  {
    motor->SetForce(0, 10);
    world->Step(1);
  }

  // Expect torso to lift at least 1 mm/s
  gzdbg << "motor " << motor->GetVelocity(0) << std::endl;
  gzdbg << "screw " << screw->GetVelocity(0) << std::endl;
  gzdbg << "link  " << link->GetWorldLinearVel() << std::endl;
  EXPECT_GT(link->GetWorldLinearVel().z, 1e-3);
}

////////////////////////////////////////////////////////////////////////
// StaticPR2:
// Issue #586 noted a segfault when loading a pr2 as static and stepping
// physics forward. This test loads a world with several objects and
// steps time forward.
////////////////////////////////////////////////////////////////////////
void PR2Test::StaticPR2(std::string _physicsEngine)
{
  if (_physicsEngine == "simbody")
  {
    gzerr << "Abort test since simbody does not support static models "
          << "with pose offsets, "
          << "please see issue #860."
          << std::endl;
    return;
  }
  if (_physicsEngine == "dart")
  {
    gzerr << "Abort test since dart does not support ray sensor in PR2, "
          << "Please see issue #911.\n";
    return;
  }

  ServerFixture::Load("worlds/static_pr2.world", true, _physicsEngine);

  // The body of this is copied from PhysicsTest::EmptyWorld
  physics::WorldPtr world = physics::get_world("default");
  ASSERT_TRUE(world != NULL);

  // Verify physics engine type
  physics::PhysicsEnginePtr physics = world->GetPhysicsEngine();
  ASSERT_TRUE(physics != NULL);
  EXPECT_EQ(physics->GetType(), _physicsEngine);

  // simulate 1 step
  world->Step(1);
  double t = world->GetSimTime().Double();
  // verify that time moves forward
  EXPECT_GT(t, 0);

  // simulate a few steps
  int steps = 20;
  world->Step(steps);
  double dt = world->GetPhysicsEngine()->GetMaxStepSize();
  EXPECT_GT(dt, 0);
  t = world->GetSimTime().Double();
  EXPECT_GT(t, 0.99*dt*static_cast<double>(steps+1));
}

TEST_P(PR2Test, ScrewJoint)
{
  ScrewJoint(GetParam());
}

TEST_P(PR2Test, StaticPR2)
{
  StaticPR2(GetParam());
}

INSTANTIATE_TEST_CASE_P(PhysicsEngines, PR2Test, PHYSICS_ENGINE_VALUES);

int main(int argc, char **argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text: #include <boost/parameter/aux_/parenthesized_type.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/** \file
 * ucontext-based coroutine library designed to emulate a normal control flow around callbacks. */

// http://en.wikipedia.org/wiki/Setcontext; man 3 makecontext; man 2 getcontext
// http://www.boost.org/doc/libs/1_53_0/libs/context/doc/html/index.html
// g++ -std=c++11 -O1 -Wall -g test_cbcoro.cc -pthread && ./a.out

// NB: There is now a coroutine support in Boost ASIO which can be used to make asynchronous APIs look synchronous in a similar way:
//     https://svn.boost.org/trac/boost/changeset/84311

#include <ucontext.h>
#include <sys/mman.h>  // mmap
#include <string.h>  // strerror
#include <mutex>
#include <atomic>
#include <valgrind/valgrind.h>
#include <glim/exception.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/slist.hpp>

namespace glim {

/// Simplifies turning callback control flows into normal imperative control flows.
class CBCoro {
 public:
  /// "Holds" the CBCoro and will delete it when it is no longer used.
  struct CBCoroPtr {
    CBCoro* _coro;
    CBCoroPtr (CBCoro* coro): _coro (coro) {
      _coro->_users++;
    }
    ~CBCoroPtr() {
      if (--_coro->_users <= 0 && _coro->_delete) delete _coro;
    }
    CBCoro* operator ->() const {return _coro;}
  };

  static constexpr size_t defaultStackSize() {return 512 * 1024;}
  static constexpr uint8_t defaultCacheSize() {return 2;}
 protected:
  typedef boost::container::flat_map<size_t, boost::container::slist<void*> > cache_t;
  /// The cached stacks; stackSize -> free list.
  static cache_t& cache() {static cache_t CACHE; return CACHE;}
  static std::mutex& cacheMutex() {static std::mutex CACHE_MUTEX; return CACHE_MUTEX;}

  ucontext_t _context;
  ucontext_t* _returnTo;
  std::recursive_mutex _mutex;  ///< This one is locked most of the time.
  std::atomic_int_fast32_t _users;  ///< Counter used by `CBCoroPtr`.
  bool _delete;  ///< Whether the `CBCoroPtr` should `delete` this instance when it is no longer used (default is `true`).
  bool _invokeFromYield;  ///< True if `invokeFromCallback()` was called directly from `yieldForCallback()`.
  bool _yieldFromInvoke;  ///< True if `yieldForCallback()` now runs from `invokeFromCallback()`.
  uint8_t const _cacheStack;  ///< Tells `freeStack()` to cache the stack if the number of cached `#_stackSize` stacks is less than it.
  void* _stack;
  size_t const _stackSize;  ///< Keeps the size of the stack.

  /// Peek a stack from the cache or allocate one with `mmap` (and register with Valgrind).
  virtual void allocateStack() {
    if (_cacheStack) {
      std::lock_guard<std::mutex> lock (cacheMutex());
      auto& freeList = cache()[_stackSize];
      if (!freeList.empty()) {_stack = freeList.front(); freeList.pop_front(); return;}
    }
    _stack = mmap (nullptr, _stackSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_STACK | MAP_NORESERVE, -1, 0);
    if (_stack == MAP_FAILED) GTHROW (std::string ("mmap allocation failed: ") + ::strerror (errno));
    #pragma GCC diagnostic ignored "-Wunused-value"
    VALGRIND_STACK_REGISTER (_stack, (char*) _stack + _stackSize);
  }
  /// Release a stack into the cache or free it with `munmap` (and deregister with Valgrind).
  virtual void freeStack() {
    if (_cacheStack) {
      std::lock_guard<std::mutex> lock (cacheMutex());
      auto& freeList = cache()[_stackSize];
      if (freeList.size() < _cacheStack) {freeList.push_front (_stack); _stack = nullptr; return;}
    }
    VALGRIND_STACK_DEREGISTER (_stack);
    if (munmap (_stack, _stackSize)) GTHROW (std::string ("!munmap: ") + ::strerror (errno));;
    _stack = nullptr;
  }

  /// Prepare the coroutine (initialize context, allocate stack and register it with Valgrind).
  CBCoro (uint8_t cacheStack = defaultCacheSize(), size_t stackSize = defaultStackSize()):
      _returnTo (nullptr), _users (0), _delete (true), _invokeFromYield (false), _yieldFromInvoke (false),
      _cacheStack (cacheStack), _stack (nullptr), _stackSize (stackSize) {
    if (getcontext (&_context)) GTHROW ("!getcontext");
    allocateStack();
    _context.uc_stack.ss_sp = _stack;
    _context.uc_stack.ss_size = stackSize;
  }
  virtual ~CBCoro() {
    freeStack();
  }
 public:
  /// Starts the coroutine on the `_stack` (makecontext, swapcontext), calling the `CBCoro::run`.
  CBCoroPtr start() {
    CBCoroPtr ptr (this);
    ucontext_t back; _context.uc_link = &back;
    makecontext (&_context, (void(*)()) cbcRun, 1, (intptr_t) this);
    // Since we have to "return" from inside the `yieldForCallback`,
    // we're not actually using the `_context.uc_link` and `return`, we use `setcontext (_returnTo)` instead.
    _returnTo = &back;
    _mutex.lock();
    swapcontext (&back, &_context); // Now our stack lives and the caller stack is no longer in control.
    _mutex.unlock();
    return ptr;
  }
 protected:
  /// Logs exception thrown from `CBCoro::run`.
  virtual void log (const std::exception& ex) {
    std::cerr << "glim::CBCoro, exception: " << ex.what() << std::endl;
  }
  static void cbcRun (CBCoro* cbCoro) {
    try {
      cbCoro->run();
    } catch (const std::exception& ex) {
      cbCoro->log (ex);
    }
    cbCoro->cbcReturn();  // Return the control to the rightful owner, e.g. to a last callback who ran `invokeFromCallback`, or otherwise to `cbcStart`.
  }
  /// Relinquish the control to the original owner of the thread, restoring its stack.
  void cbcReturn() {
    ucontext_t* returnTo = _returnTo;
    if (returnTo != nullptr) {_returnTo = nullptr; setcontext (returnTo);}
  }
  /// This method is performed on the CBCoro stack, allowing it to be suspended and then reanimated from callbacks.
  virtual void run() = 0;
 public:
  /** Use this method to wrap a return-via-callback code.
   * For example, the callback code \code
   *   startSomeWork ([=]() {
   *     continueWhenWorkIsFinished();
   *   });
   * \endcode should be turned into \code
   *   yieldForCallback ([&]() {
   *     startSomeWork ([&]() {
   *       invokeFromCallback();
   *     });
   *   });
   *   continueWhenWorkIsFinished();
   * \endcode
   *
   * Captures the stack, runs the `fun` and relinquish the control to `_returnTo`.\n
   * This method will never "return" by itself, in order for it to "return" the
   * `fun` MUST call `invokeFromCallback`, maybe later and from a different stack. */
  template <typename F> CBCoroPtr yieldForCallback (F fun) {
    CBCoroPtr ptr (this);
    _yieldFromInvoke = false;
    if (getcontext (&_context)) GTHROW ("!getcontext");  // Capture.
    if (_yieldFromInvoke) {
      // We're now in the future, revived by the `invokeFromCallback`.
      // All we do now is "return" to the caller whose stack we captured earlier.
    } else {
      // We're still in the present, still have some work to do.
      fun();  // The `fun` is supposed to do something resulting in the `invokeFromCallback` being called later.
      if (_invokeFromYield) {
        // The `fun` used the `invokeFromCallback` directly, not resorting to callbacks, meaning we don't have to do our magick.
        _invokeFromYield = false;
      } else {
        // So, the `fun` took measures to revive us later, it's time for us to go into torpor and return the control to whoever we've borrowed it from.
        cbcReturn();
      }
    }
    return ptr;
  }

  /// To be called from a callback in order to lend the control to CBCoro, continuing it from where it called `yieldForCallback`.
  CBCoroPtr invokeFromCallback() {
    CBCoroPtr ptr (this);
    _mutex.lock();  // Wait for an other-thready `yieldForCallback` to finish.
    if (_returnTo != nullptr) {
      // We have not yet "returned" from the `yieldForCallback`,
      // meaning that the `invokeFromCallback` was executed immediately from inside the `yieldForCallback`.
      // In that case we must DO NOTHING, we must simply continue running on the current stack.
      _invokeFromYield = true;  // Tells `yieldForCallback` to do nothing.
    } else {
      // Revive the CBCoro, letting it continue from where it was suspended in `yieldForCallback`.
      ucontext_t cbContext; _returnTo = &cbContext; _yieldFromInvoke = true;
      if (swapcontext (&cbContext, &_context)) GTHROW ("!swapcontext");
      // NB: When the CBCoro is suspended or exits, the control returns back there and then back to the callback from which we borrowed it.
      if (_returnTo == &cbContext) _returnTo = nullptr;
    }
    _mutex.unlock();  // Other-thready `yieldForCallback` has finished and `cbcReturn`ed here.
    return ptr;
  }
};

/** CBCoro running a given functor.
 * The functor's first argument must be a CBCoro pointer, like this: \code (new CBCoroForFunctor ([](CBCoro* cbcoro) {}))->start(); \endcode */
template <typename FUN> struct CBCoroForFunctor: public CBCoro {
  FUN _fun;
  template <typename CFUN> CBCoroForFunctor (CFUN&& fun, uint8_t cacheStack, size_t stackSize): CBCoro (cacheStack, stackSize), _fun (std::forward<CFUN> (fun)) {}
  virtual void run() {_fun (this);}
  virtual ~CBCoroForFunctor() {}
};

/** Syntactic sugar: Runs a given functor in a CBCoro instance.
 * Example: \code glim::cbCoro ([](glim::CBCoro* cbcoro) {}); \endcode
 * Returns a `CBCoroPtr` to the CBCoro instance holding the `fun` which might be held somewhere in order to delay the deletion of `fun`. */
template <typename FUN> inline CBCoro::CBCoroPtr cbCoro (FUN&& fun, uint8_t cacheStack = CBCoro::defaultCacheSize(), size_t stackSize = CBCoro::defaultStackSize()) {
  return (new CBCoroForFunctor<FUN> (std::forward<FUN> (fun), cacheStack, stackSize))->start();
}

}

max_stars_repo_name: ViteFalcon/libglim

max_issues_repo_name: ViteFalcon/libglim

max_forks_repo_name: ViteFalcon/libglim


text:
// Copyright (c) 2014-2015 DiMS dev-team
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "base58.h"

#include <boost/foreach.hpp>

#include "common/actionHandler.h"
#include "common/authenticationProvider.h"

#include "tracker/clientRequestsManager.h"
#include "tracker/getBalanceAction.h"
#include "tracker/trackerNodesManager.h"
#include "tracker/controller.h"
#include "tracker/transactionRecordManager.h"

using namespace common;

namespace tracker
{

class CHandleClientRequestVisitor : public common::CClientRequestVisitorHandlerBase
{
public:
	using CClientRequestVisitorHandlerBase::operator ();

	CHandleClientRequestVisitor(uint256 const & _hash):m_hash( _hash ){};

	void operator()( CTransactionStatusReq const & _transactionStatus ) const
	{
		// shoudn't be handled this way
		CTransaction transaction;
		if ( CTransactionRecordManager::getInstance()->getTransaction( _transactionStatus.m_hash, transaction ) )
		{
			std::vector<unsigned char> signedHash;
			common::CAuthenticationProvider::getInstance()->sign( transaction.GetHash(), signedHash );
			CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTransactionStatusResponse( common::TransactionsStatus::Confirmed, transaction.GetHash(), signedHash ) );
		}
		else
			CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTransactionStatusResponse( common::TransactionsStatus::Unconfirmed, _transactionStatus.m_hash ) );
	}

	void operator()( CTrackerStatsReq const & _trackerStatsReq ) const
	{
		CController * controller = CController::getInstance();
		CClientRequestsManager::getInstance()->setClientResponse( m_hash, CTrackerSpecificStats( controller->getPrice() ) );
	}

	void operator()( CTransactionMessage const & _transactionMessage ) const
	{
		CTransactionRecordManager::getInstance()->addClientTransaction( _transactionMessage.m_transaction );
	}

	void operator()( CAddressBalanceReq const & _addressBalanceReq ) const
	{
		CKeyID keyId;
		CMnemonicAddress( _addressBalanceReq.m_address ).GetKeyID( keyId );
		common::CActionHandler::getInstance()->executeAction( (common::CAction*)new CGetBalanceAction( keyId, m_hash ) );
	}

	void operator()( CNetworkInfoReq const & _networkInfoReq ) const
	{
		// handle  it through  action  handler??
		std::vector< common::CValidNodeInfo > validNodesInfo;

		BOOST_FOREACH( common::CValidNodeInfo const & validNodeInfo, CTrackerNodesManager::getInstance()->getNodesInfo( common::CRole::Tracker ) )
		{
			validNodesInfo.push_back( validNodeInfo );
		}

		BOOST_FOREACH( common::CValidNodeInfo const & validNodeInfo, CTrackerNodesManager::getInstance()->getNodesInfo( common::CRole::Monitor ) )
		{
			validNodesInfo.push_back( validNodeInfo );
		}
		CClientRequestsManager::getInstance()->setClientResponse( m_hash, CClientNetworkInfoResult( validNodesInfo, common::CAuthenticationProvider::getInstance()->getMyKey(), common::CRole::Tracker ) );
	}
private:
	uint256 const m_hash;
};

CClientRequestsManager * CClientRequestsManager::ms_instance = NULL;

CClientRequestsManager::CClientRequestsManager()
{

}

CClientRequestsManager*
CClientRequestsManager::getInstance( )
{
	if ( !ms_instance )
	{
		ms_instance = new CClientRequestsManager();
	};
	return ms_instance;
}

CClientRequestsManager::~CClientRequestsManager()
{}

void
CClientRequestsManager::addRequest( NodeRequests const & _nodeRequest, uint256 const & _hash )
{
	boost::lock_guard<boost::mutex> lock( m_requestLock );
	m_getInfoRequest.insert( std::make_pair( _hash, _nodeRequest ) );
}

bool
CClientRequestsManager::getResponse( uint256 const & _token, ClientResponse & _clientResponse )
{
	boost::lock_guard<boost::mutex> lock( m_lock );

	InfoResponseRecord::iterator iterator = m_infoResponseRecord.find( _token );

	if ( iterator != m_infoResponseRecord.end() )
	{
		_clientResponse = iterator->second;
		m_infoResponseRecord.erase( iterator );

		return true;
	}

	return false;
}

void
CClientRequestsManager::setClientResponse( uint256 const & _hash, ClientResponse const & _clientResponse )
{
	boost::lock_guard<boost::mutex> lock( m_lock );
	if ( m_infoResponseRecord.find( _hash ) != m_infoResponseRecord.end() )
		m_infoResponseRecord.erase(_hash);
	m_infoResponseRecord.insert( std::make_pair( _hash, _clientResponse ) );
}

void
CClientRequestsManager::processRequestLoop()
{
	while(1)
	{
		MilliSleep(1000);
		{
			boost::lock_guard<boost::mutex> lock( m_requestLock );

			BOOST_FOREACH( InfoRequestRecord::value_type request, m_getInfoRequest )
			{
				boost::apply_visitor( CHandleClientRequestVisitor( request.first ), request.second );
			}

			m_getInfoRequest.clear();
		}

		boost::this_thread::interruption_point();

	}
}

}

max_stars_repo_name: salarii/dims

max_issues_repo_name: salivan-ratcoin-dev-team/dims

max_forks_repo_name: salivan-ratcoin-dev-team/dims


text:
// Licensed under the Apache License, Version 2.0.
// Author: Jin Qing (http://blog.csdn.net/jq0123)
// Rpc controller to call the response handler.

#ifndef RPCZ_RPC_CONTEXT_HPP
#define RPCZ_RPC_CONTEXT_HPP

#include <string>
#include <boost/noncopyable.hpp>

#include <rpcz/response_message_handler.hpp>
#include <rpcz/common.hpp>  // for uint64

namespace rpcz {

class message_iterator;

class rpc_controller : boost::noncopyable {
 public:
  inline rpc_controller(uint64 event_id,
      const response_message_handler& handler,
      long timeout_ms)
      : event_id_(event_id),
        handler_(handler),
        timeout_ms_(timeout_ms) {}
  inline ~rpc_controller() {}

 public:
  inline uint64 get_event_id() const { return event_id_; }
  inline long get_timeout_ms() const { return timeout_ms_; }

 public:
  inline void handle_response(const void* data, size_t size);

  // Error handlers are not inlined.
  void handle_timeout();
  void handle_error(int error_code,
      const std::string& error_str);

 private:
  uint64 event_id_;
  response_message_handler handler_;
  long timeout_ms_;
};  // class rpc_controller

// Run in worker thread.
inline void rpc_controller::handle_response(
    const void* data, size_t size) {
  BOOST_ASSERT(data);
  if (handler_) {
    handler_(NULL, data, size);
  }
}  // handle_response_message

}  // namespace rpcz
#endif  // RPCZ_RPC_CONTEXT_HPP


text:
/*
 * Copyright (C) 2012-2016 Open Source Robotics Foundation
 *
 * 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 <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include "gazebo/test/ServerFixture.hh"
#include "gazebo/physics/physics.hh"
#include "gazebo/sensors/sensors.hh"
#include "gazebo/common/common.hh"

using namespace gazebo;

class SpawnModels : public ServerFixture,
                    public testing::WithParamInterface<const char*>
{
};

/////////////////////////////////////////////////
TEST_P(SpawnModels, WirelessTransmitters)
{
  double gain = 2.6;
  double power = 14.5;

  Load("worlds/empty.world", true, GetParam());

  for (int i = 0; i < 10; ++i)
  {
    for (int j = 0; j < 10; ++j)
    {
      std::string modelName = "tx" +
         boost::lexical_cast<std::string>(i) +
         boost::lexical_cast<std::string>(j);
      std::string sensorName = "WirelessTransmitter" +
         boost::lexical_cast<std::string>(i) +
         boost::lexical_cast<std::string>(j);

      SpawnWirelessTransmitterSensor(modelName, sensorName,
          math::Vector3(i, j, 0.25), math::Vector3(0, 0, 0),
          "osrf", 2450.0, power, gain);

      sensors::WirelessTransmitterPtr tx =
        std::static_pointer_cast<sensors::WirelessTransmitter>(
          sensors::SensorManager::Instance()->GetSensor(sensorName));

      EXPECT_TRUE(this->HasEntity(modelName));
      EXPECT_TRUE(tx != NULL);
    }
  }
}

/////////////////////////////////////////////////
INSTANTIATE_TEST_CASE_P(TestTransceiverODE, SpawnModels,
    ::testing::Values("ode"));

/////////////////////////////////////////////////
#ifdef HAVE_BULLET
INSTANTIATE_TEST_CASE_P(TestTransceiverBullet, SpawnModels,
    ::testing::Values("bullet"));
#endif  // HAVE_BULLET

/////////////////////////////////////////////////
int main(int argc, char **argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}


text:
#define BOOST_TEST_DYN_LINK
#define BOOST_AUTO_TEST_MAIN
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/unit_test_suite.hpp>
#include <boost/test/unit_test.hpp>

#include <toolsbox/apply.hpp>

#include <string>

namespace
{
  int counter = 0;

  void fct1()
  {
    ++counter;
  }

  void fct2(int i)
  {
    counter += i;
  }

  int fct3(int i)
  {
    return i;
  }

  void fct4(const std::string& y, std::string& r)
  {
    r = y;
  }
}

BOOST_AUTO_TEST_CASE( apply_01 )
{
  counter = 0;
  toolsbox::apply(fct1, std::make_tuple());
  BOOST_CHECK_EQUAL(counter, 1);
}

BOOST_AUTO_TEST_CASE( apply_02 )
{
  counter = 0;
  toolsbox::apply(fct2, std::make_tuple(5));
  BOOST_CHECK_EQUAL(counter, 5);
}

BOOST_AUTO_TEST_CASE( apply_03 )
{
  int ret = toolsbox::apply(fct3, std::make_tuple(5));
  BOOST_CHECK_EQUAL(ret, 5);
}

BOOST_AUTO_TEST_CASE( apply_04 )
{
  auto tuple = std::make_tuple(5);
  int ret = toolsbox::apply(fct3, tuple);
  BOOST_CHECK_EQUAL(ret, 5);
}

BOOST_AUTO_TEST_CASE( apply_05 )
{
  const auto tuple = std::make_tuple(5);
  int ret = toolsbox::apply(fct3, tuple);
  BOOST_CHECK_EQUAL(ret, 5);
}

BOOST_AUTO_TEST_CASE( apply_06 )
{
  std::string ret;
  toolsbox::apply(fct4, std::make_tuple("e", std::ref(ret)));
  BOOST_CHECK_EQUAL(ret, "e");
}

BOOST_AUTO_TEST_CASE( apply_07 )
{
  std::string oo = "rr";
  std::string ret;
  toolsbox::apply(fct4, std::make_tuple(std::cref(oo), std::ref(ret)));
  BOOST_CHECK_EQUAL(ret, oo);
  BOOST_CHECK_EQUAL(oo,"rr");
}

BOOST_AUTO_TEST_CASE( apply_08 )
{
  std::string oo = "rr";
  std::string ret;
  std::function<void (const std::string&, std::string&)> fct = [](const std::string&y, std::string&r) { r = y; };
  toolsbox::apply(fct, std::make_tuple(std::cref(oo), std::ref(ret)));
  BOOST_CHECK_EQUAL(ret, oo);
  BOOST_CHECK_EQUAL(oo,"rr");
}

max_stars_repo_name: EVaillant/toolsbox

max_issues_repo_name: EVaillant/toolsbox

max_forks_repo_name: EVaillant/toolsbox