text:
/** \file
 * Support for Eigen linear algebra library in Chaiscript.
 *
 * \author Truong X. Nghiem (xuan.nghiem@epfl.ch)
 */

#ifndef _CHAISCRIPT_EXTRAS_EIGEN_H
#define _CHAISCRIPT_EXTRAS_EIGEN_H

#include <vector>
#include <Eigen/Dense>
#include <chaiscript/chaiscript.hpp>

namespace chaiscript {
    namespace extras {
        namespace eigenlinalg {
            typedef std::vector<chaiscript::Boxed_Value> TChaiVector;   ///< The C++ type of a Chaiscript's vector object

            Eigen::IOFormat EigenMatlabFmt(Eigen::StreamPrecision, 0, ", ", ";\n", "", "", "[", "]");

            // Register with Chaiscript a new Eigen vector type
            template<typename CLS, typename Scalar>
            ModulePtr eigen_vector_type(const char* CLSNAME, ModulePtr m = std::make_shared<Module>()) {
                //// 1.1. Type and Construction
                m->add(user_type<CLS>(), CLSNAME);
                m->add(constructor<CLS ()>(), CLSNAME);
                m->add(constructor<CLS (typename CLS::Index)>(), CLSNAME);
                m->add(bootstrap::copy_constructor<CLS>(CLSNAME));
                m->add(fun(static_cast<CLS& (CLS::*)(const CLS&)>(&CLS::operator=)), "=");

                // Construct vector from a Chaiscript vector of elements of EXACTLY the type Scalar
                m->add(fun([](const TChaiVector& cv) {
                    auto n = cv.size();
                    CLS v(n);
                    if (n > 0) {
                        int k = 0;
                        for (auto& elem: cv) {
                            v(k++) = chaiscript::boxed_cast<Scalar>(elem);
                        }
                    }
                    return v;
                }), CLSNAME);

                //// 1.2. Accessors
                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index)>(&CLS::operator())), "[]");
                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index)>(&CLS::operator())), "coeff");

                //// 1.3. Size and resize
                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::size)), "size");
                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::rows)), "rows");
                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::cols)), "cols");
                m->add(fun(static_cast<void (CLS::*)(typename CLS::Index)>(&CLS::resize)), "resize"); // destructive resize

                //// 1.4. Misc

                // Convert to string to print
                m->add(fun([](const CLS& v) {
                    std::stringstream s;
                    s << v.format(EigenMatlabFmt);
                    return s.str();
                }), "to_string");

                return m;
            }

            // Register with Chaiscript a new Eigen matrix type
            template<typename CLS, typename Scalar>
            ModulePtr eigen_matrix_type(const char* CLSNAME, ModulePtr m = std::make_shared<Module>()) {
                //// 1.1. Type and Construction
                m->add(user_type<CLS>(), CLSNAME);
                m->add(constructor<CLS ()>(), CLSNAME);
                // Somehow Eigen does not work nicely with Chaiscript's constructor utility, so I must use a workaround
                m->add(fun([](typename CLS::Index r, typename CLS::Index c) {
                    return CLS(r, c);
                }), CLSNAME);
                bootstrap::copy_constructor<CLS>(CLSNAME, *m);
                m->add(fun(static_cast<CLS& (CLS::*)(const CLS&)>(&CLS::operator=)), "=");

                // Conversions from vector to matrix
                //m->add(fun([](const Eigen::Matrix<Scalar,Eigen::Dynamic,1>& v) { return CLS(v); }), CLSNAME);
                //m->add(fun([](const Eigen::Matrix<Scalar,1,Eigen::Dynamic>& v) { return CLS(v); }), CLSNAME);

                // Construct a matrix of given size from a Chaiscript vector of elements of EXACTLY the type Scalar.
                // This is done ROW-WISE.
                // Only r*c elements are copied from the vector to the matrix. If the vector contains fewer elements, only those will be copied, the remaining elements of the matrix are undefined.
                m->add(fun([](typename CLS::Index r, typename CLS::Index c, const TChaiVector& cv) {
                    auto n = cv.size();
                    CLS v(r, c);
                    if (n > 0 && r*c > 0) {
                        int k = 0;
                        for (auto ri = 0; ri < r; ++ri) {
                            for (auto ci = 0; ci < c; ++ci) {
                                v(ri, ci) = chaiscript::Boxed_Number(cv[k++]).get_as<Scalar>();
                                if (k == n) {
                                    break;
                                }
                            }
                            if (k == n) {
                                break;
                            }
                        }
                    }
                    return v;
                }), CLSNAME);

                //// 1.2. Accessors
                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index, typename CLS::Index)>(&CLS::operator())), "coeff");
                m->add(fun(static_cast<Scalar& (CLS::*)(typename CLS::Index)>(&CLS::operator())), "[]");

                //// 1.3. Size and resize
                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::size)), "size");
                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::rows)), "rows");
                m->add(fun(static_cast<typename CLS::Index (CLS::*)() const>(&CLS::cols)), "cols");
                m->add(fun(static_cast<void (CLS::*)(typename CLS::Index, typename CLS::Index)>(&CLS::resize)), "resize"); // destructive resize

                //// 1.4. Misc
                // Convert to string to print
                m->add(fun([](const CLS& v) {
                    std::stringstream s;
                    s << v.format(EigenMatlabFmt);
                    return s.str();
                }), "to_string");

                return m;
            }

            // Predefined matrices
            template<typename CLS>
            ModulePtr eigen_matrix_predefined(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](typename CLS::Index r, typename CLS::Index c) { return CLS(CLS::Zero(r,c)); }), "zeros");  // Zero matrix
                m->add(fun([](CLS &m) { m.setZero(); }), "setZero");  // set all coefficients to 0

                m->add(fun([](typename CLS::Index r, typename CLS::Index c) { return CLS(CLS::Ones(r,c)); }), "ones");  // matrix of 1's
                m->add(fun([](CLS &m) { m.setOnes(); }), "setOnes");  // set all coefficients to 1

                m->add(fun(&CLS::fill), "fill");  // set all coefficients to a given constant

                m->add(fun([](typename CLS::Index r, typename CLS::Index c) { return CLS(CLS::Identity(r,c));}), "eyes");  // Identity matrix
                m->add(fun([](CLS &m) { m.setIdentity(); }), "setIdentity");  // set the matrix to identity
                m->add(fun([](CLS &m, typename CLS::Index r, typename CLS::Index c) { m.setIdentity(r,c); }), "setIdentity");  // resize and set the matrix to identity

                return m;
            }

            // Binary Addition and subtraction
            // CLS1 and CLS2 should be different types, where CLS1 should be "larger" in the sense that CLS2 is a special case of CLS1 (e.g. Matrix and Vector)
            template<typename CLS1, typename CLS2>
            ModulePtr binary_addition_substraction(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS1& a, const CLS2& b) { return CLS1(a + b); }), "+");
                m->add(fun([](const CLS2& a, const CLS1& b) { return CLS1(a + b); }), "+");
                m->add(fun([](const CLS1& a, const CLS2& b) { return CLS1(a - b); }), "-");
                m->add(fun([](const CLS2& a, const CLS1& b) { return CLS1(a - b); }), "-");
                return m;
            }

            // Binary Addition and subtraction for objects of same class
            template<typename CLS1>
            ModulePtr binary_addition_substraction(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS1& a, const CLS1& b) { return (a + b).eval(); }), "+");
                m->add(fun([](const CLS1& a, const CLS1& b) { return (a - b).eval(); }), "-");
                m->add(fun([](CLS1& a, const CLS1& b) { return (a += b); }), "+=");

                // Between matrix and scalar
                m->add(fun([](const CLS1& a, const typename CLS1::Scalar b) { return CLS1(a.array() + b); }), "+");
                //m->add(fun([](const typename CLS1::Scalar b, const CLS1& a) { return CLS1(a.array() + b); }), "+");
                m->add(fun([](const CLS1& a, const typename CLS1::Scalar b) { return CLS1(a.array() - b); }), "-");
                //m->add(fun([](const typename CLS1::Scalar b, const CLS1& a) { return CLS1((-a).array() + b); }), "-");

                return m;
            }

            // Unary Addition and subtraction
            template<typename CLS>
            ModulePtr unary_addition_substraction(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS& a) { return a; }), "+");
                m->add(fun([](const CLS& a) { return (-a).eval(); }), "-");
                return m;
            }

            // Scalar multiplication and division
            template<typename CLS, typename Scalar>
            ModulePtr scalar_mult_div(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS& a, const Scalar b) { return (a * b).eval(); }), "*");
                m->add(fun([](const Scalar a, const CLS& b) { return (a * b).eval(); }), "*");
                m->add(fun([](const CLS& a, const Scalar b) { return (a / b).eval(); }), "/");
                m->add(fun([](CLS& a, const Scalar b) { return (a *= b); }), "*=");
                m->add(fun([](CLS& a, const Scalar b) { return (a /= b); }), "/=");
                return m;
            }

            // Transpose and conjugation
            template<typename CLS, const bool withConjugation>
            ModulePtr transpose_conjugation(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS& a) { return CLS(a.transpose()); }), "transpose");
                m->add(fun(static_cast<void (CLS::*)()>(&CLS::transposeInPlace)), "transposeInPlace");    // in-place transpose: void transposeInPlace()

                if (withConjugation) {
                    m->add(fun([](const CLS& a) { return CLS(a.conjugate()); }), "conjugate");
                    m->add(fun([](const CLS& a) { return CLS(a.adjoint()); }), "adjoint");
                    m->add(fun(static_cast<void (CLS::*)()>(&CLS::adjointInPlace)), "adjointInPlace");    // in-place adjoint: void adjointInPlace()
                }
                return m;
            }

            // Matrix multiplication
            template<typename CLS1, typename CLS2 = CLS1>
            ModulePtr matrix_mult(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS1& a, const CLS2& b) { return (a * b).eval(); }), "*");
                m->add(fun([](CLS1& a, const CLS2& b) { return a *= b; }), "*=");
                return m;
            }

            // Dot product (only for vector types)
            template<typename CLS1>
            ModulePtr dot_product(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS1& a, const CLS1& b) { return a.dot(b); }), "dot");
                return m;
            }

            // Basic arithmetic reduction operations
            template<typename CLS>
            ModulePtr arith_reduction(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::sum)), "sum");
                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::prod)), "prod");
                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::mean)), "mean");
                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::minCoeff)), "min");
                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::maxCoeff)), "max");
                m->add(fun(static_cast<typename CLS::Scalar (CLS::*)() const>(&CLS::trace)), "trace");
                return m;
            }

            // Coefficient-wise operations
            template<typename CLS>
            ModulePtr coefficient_wise_operations(ModulePtr m = std::make_shared<Module>()) {
                m->add(fun([](const CLS& a) { return a.cwiseAbs().eval(); }), "abs");
                m->add(fun([](const CLS& a) { return a.cwiseAbs2().eval(); }), "abs2");
                m->add(fun([](const CLS& a) { return a.cwiseSqrt().eval(); }), "sqrt");
                m->add(fun([](const CLS& a) { return a.array().log().matrix().eval(); }), "log");
                m->add(fun([](const CLS& a) { return a.array().exp().matrix().eval().eval(); }), "exp");
                m->add(fun([](const CLS& a, double e) { return a.array().pow(e).matrix().eval(); }), "pow");
                m->add(fun([](const CLS& a) { return a.array().square().matrix().eval(); }), "square");
                m->add(fun([](const CLS& a) { return a.array().sin().matrix().eval(); }), "sin");
                m->add(fun([](const CLS& a) { return a.array().cos().matrix().eval(); }), "cos");
                m->add(fun([](const CLS& a) { return a.array().tan().matrix().eval(); }), "tan");
                m->add(fun([](const CLS& a) { return a.array().asin().matrix().eval(); }), "asin");
                m->add(fun([](const CLS& a) { return a.array().acos().matrix().eval(); }), "acos");

                return m;
            }

        }
    }
}
#endif // _CHAISCRIPT_EXTRAS_EIGEN_H


text:
// This file is part of the pyMOR project (http://www.pymor.org).
// Copyright 2013-2018 pyMOR developers and contributors. All rights reserved.
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef EXAMPLE_HH
#define EXAMPLE_HH

#include <deal.II/base/function.h>
#include <deal.II/base/logstream.h>
#include <deal.II/base/quadrature_lib.h>
#include <deal.II/dofs/dof_accessor.h>
#include <deal.II/dofs/dof_handler.h>
#include <deal.II/dofs/dof_tools.h>
#include <deal.II/fe/fe_q.h>
#include <deal.II/fe/fe_system.h>
#include <deal.II/fe/fe_values.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_refinement.h>
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/lac/constraint_matrix.h>
#include <deal.II/lac/full_matrix.h>
#include <deal.II/lac/precondition.h>
#include <deal.II/lac/solver_bicgstab.h>
#include <deal.II/lac/solver_cg.h>
#include <deal.II/lac/sparse_matrix.h>
#include <deal.II/lac/vector.h>
#include <deal.II/numerics/data_out.h>
#include <deal.II/numerics/error_estimator.h>
#include <deal.II/numerics/matrix_tools.h>
#include <deal.II/numerics/solution_transfer.h>
#include <deal.II/numerics/vector_tools.h>

#include <functional>

#include "rhs.hh"

using namespace dealii;

class ElasticityExample {

public:
  static constexpr size_t dim{2};

  ElasticityExample(int refine_steps);
  ~ElasticityExample();

  typedef double Number;
  typedef std::map<std::string, std::vector<Number>> Parameter;
  typedef Vector<Number> VectorType;

  void visualize(const VectorType& solution, std::string filename) const;
  VectorType solve(const Parameter& param);

  const SparseMatrix<Number>& lambda_mat() const;
  const SparseMatrix<Number>& mu_mat() const;
  const SparseMatrix<Number>& h1_mat() const;
  const Vector<Number>& rhs() const;

  Number h1_0_semi_norm(const Vector<Number>& v) const;
  Number energy_norm(const Vector<Number>& v) const;

  VectorType transfer_to(int refine_steps, const VectorType& v);

private:
  void setup_system();
  void assemble_h1();
  void assemble_system();
  void _solve(Parameter param, VectorType& solution);

protected:
  void refine_global(int refine_steps = 1);

  Triangulation<dim> triangulation_;
  DoFHandler<dim> dof_handler_;

  FESystem<dim> fe_;

  SparsityPattern sparsity_pattern_;
  SparseMatrix<Number> lambda_system_matrix_, mu_system_matrix_, h1_matrix_;
  Vector<Number> system_rhs_, tmp_data_;
};

#endif // EXAMPLE_HH

ext: hh


text:
#include "StdAfx.h"
#include "SearchResult.h"
#include "query.h"

#include <boost/test/unit_test.hpp>
#ifdef UNIT_TEST
BOOST_AUTO_TEST_SUITE( TestSearchResult )

	using namespace mem_engine;
	typedef CComObject< CSearchResult > result_obj ;
	typedef CComPtr< result_obj > result_ptr ;

	BOOST_AUTO_TEST_CASE( Instantiate )
	{
		result_ptr result ;
		HRESULT hr = result_obj::CreateInstance( &result ) ;
		BOOST_CHECK( SUCCEEDED( hr ) ) ;
		BOOST_CHECK( result ) ;
	}
	BOOST_AUTO_TEST_CASE( get_record )
	{
		result_ptr result ;
		result_obj::CreateInstance( &result ) ;
		CComPtr<IRecord> rec ;
		HRESULT hr = result->get_Record(&rec) ;
		BOOST_CHECK( SUCCEEDED( hr ) ) ;
		BOOST_CHECK( rec ) ;
	}
	BOOST_AUTO_TEST_CASE( get_score )
	{
		result_ptr result ;
		result_obj::CreateInstance( &result ) ;
		double score = 5.0 ;
		result->get_Score(&score) ;
		BOOST_CHECK_CLOSE(0.0, score, 0.00001);
	}
	BOOST_AUTO_TEST_CASE( set_match )
	{
		result_ptr result ;
		result_obj::CreateInstance( &result ) ;
		search_match_ptr match(new search_match) ;
		match->set_base_score(0.5) ;
		result->set_match(match) ;
		double score = 1.0 ;
		result->get_Score(&score) ;
		BOOST_CHECK_CLOSE(0.5, score, 0.00001);
	}
	BOOST_AUTO_TEST_CASE( get_name )
	{
		result_ptr result ;
		result_obj::CreateInstance( &result ) ;
		search_match_ptr match(new search_match) ;
		CComBSTR name ;
		match->set_base_score(0.5) ;
		const wstring loc = L"foo.ftm" ;
		match->set_memory_location(loc) ;
		result->set_match(match) ;
		result->get_MemoryName(&name) ;
		string expected = "foo.ftm" ;
		string actual = CW2A(name) ;
		BOOST_CHECK_EQUAL(expected, actual);
	}
BOOST_AUTO_TEST_SUITE_END()

#endif

ext: cpp

max_stars_repo_name: ultimatezen/felix

max_issues_repo_name: ultimatezen/felix

max_forks_repo_name: ultimatezen/felix


text:
#include <iostream>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/include/vector.hpp>

int main() {
    boost::fusion::vector<int, int, int> vec;

    for(auto &x: vec)
	std::cout << x << std::endl;
}

ext: cc

max_stars_repo_name: NobodyXu/snippet

max_issues_repo_name: NobodyXu/snippet

max_forks_repo_name: NobodyXu/snippet


text:
#ifndef __pinocchio_python_pybind11_hpp__
#define __pinocchio_python_pybind11_hpp__

/// \mainpage Pinocchio PyBind11 helpers
///
/// This package provides utilities to ease the use of Pinocchio objects when
/// using PyBind11.
/// There are two methods:
/// 1. The developer-friendly but likely less user-friendly method: \ref
/// PINOCCHIO_PYBIND11_TYPE_CASTER
/// 2. The user-friendly but less developer-friendly method: \ref
/// pinocchio::python::make_pybind11_function
///
/// Both methods can be mixed. For both cases, you may
/// \code
/// // with necessary #define. See below
/// #include <pinocchio/bindings/python/pybind11-all.hpp>
/// \endcode
/// to get some \subpage default_type_caster.
///
/// \section example Example
/// \code
/// #define SCALAR double
/// #define OPTIONS 0
/// #define JOINT_MODEL_COLLECTION ::pinocchio::JointCollectionDefaultTpl
/// #include <pinocchio/bindings/python/pybind11-all.hpp>
///
/// ...
/// // method 1
/// m.def("function", my_function);
/// // method 2
/// m.def("function", pinocchio::python::make_pybind11_function(my_function));
/// \endcode
///

#include <iostream>
#include <pinocchio/fwd.hpp>

// This lines forces clang-format to keep the include split here
#include <pybind11/pybind11.h>

#include <boost/python.hpp>

namespace pinocchio {
namespace python {
namespace bp = boost::python;
namespace py = pybind11;

template <typename T>
inline py::object to(T& t) {
  // Create PyObject using boost Python
  bp::object obj = bp::api::object(t);
  PyObject* pyobj = obj.ptr();
  return pybind11::reinterpret_borrow<py::object>(pyobj);
}
template <typename T>
inline py::object to(T* t) {
  // Create PyObject using boost Python
  typename bp::manage_new_object::apply<T*>::type converter;
  PyObject* pyobj = converter(t);
  // Create the Pybind11 object
  return py::reinterpret_borrow<py::object>(pyobj);
}

template <typename ReturnType>
inline ReturnType& from(py::handle model) {
  return bp::extract<ReturnType&>(model.ptr());
}

template <typename T>
struct convert_type {
  typedef T type;
  static inline T _to(T t) { return t; }
  static inline type _from(type t) { return t; }
};
template <>
struct convert_type<void> {
  // typedef void type;
  // static inline void _to() {}
};

template <typename T>
struct convert_boost_python_object {
  typedef py::object type;
  static inline type _to(T t) {
    return to<typename std::remove_pointer<typename std::remove_reference<
        typename std::remove_cv<T>::type>::type>::type>(t);
  }
  static inline T _from(type t) {
    return from<
        typename std::remove_cv<typename std::remove_reference<T>::type>::type>(
        t);
  }
};

/// \brief Defines a conversion used by \ref make_pybind11_function
#define PINOCCHIO_PYBIND11_ADD_CONVERT_TYPE(CLASS)                    \
  namespace pinocchio {                                               \
  namespace python {                                                  \
  template <>                                                         \
  struct convert_type<CLASS> : convert_boost_python_object<CLASS> {}; \
  }                                                                   \
  }

/// \brief Defines a set of conversion used by \ref make_pybind11_function
#define _SINGLE_ARG(...) __VA_ARGS__
#define PINOCCHIO_PYBIND11_ADD_ALL_CONVERT_TYPE(CLASS)           \
  PINOCCHIO_PYBIND11_ADD_CONVERT_TYPE(_SINGLE_ARG(CLASS))        \
  PINOCCHIO_PYBIND11_ADD_CONVERT_TYPE(_SINGLE_ARG(CLASS const))  \
  PINOCCHIO_PYBIND11_ADD_CONVERT_TYPE(_SINGLE_ARG(CLASS&))       \
  PINOCCHIO_PYBIND11_ADD_CONVERT_TYPE(_SINGLE_ARG(CLASS const&)) \
  PINOCCHIO_PYBIND11_ADD_CONVERT_TYPE(_SINGLE_ARG(CLASS*))       \
  PINOCCHIO_PYBIND11_ADD_CONVERT_TYPE(_SINGLE_ARG(CLASS const*))

namespace internal {

template <typename R, typename... Args>
auto call(R (*f)(Args...), typename convert_type<Args>::type... args) {
  return convert_type<R>::_to(f(convert_type<Args>::_from(args)...));
}
template <typename... Args>
void call(void (*f)(Args...), typename convert_type<Args>::type... args) {
  f(convert_type<Args>::_from(args)...);
}

template <typename T>
struct function_wrapper;

template <typename R, typename... Args>
struct function_wrapper<R (*)(Args...)> {
  static const size_t nargs = sizeof...(Args);

  typedef R result_type;

  template <size_t i>
  struct arg {
    typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
  };

  typedef R (*func_type)(Args...);

  func_type f;

  // typename convert_type<result_type>::type
  auto operator()(typename convert_type<Args>::type... args) {
    return call(f, args...);
  }
};
}  // namespace internal

/// \brief Creates a function wrapper.
///
/// Using function wrapper has the advantage of being copy-less when possible
/// but the disadvantage of requiring to wrap the exposed function.
///
/// The wrapper does:
/// - converts the argument if a conversion has been previously declared,
/// - call the wrapped function
/// - converts the result if a conversion has been previously declared.
template <typename R, typename... Args>
internal::function_wrapper<R (*)(Args...)> make_pybind11_function(
    R (*func)(Args...)) {
  internal::function_wrapper<R (*)(Args...)> wrapper;
  wrapper.f = func;
  return wrapper;
}

template <typename T>
py::object default_arg(T t) {
  py::object obj = to<T>(t);
  //obj.inc_ref();
  return obj;
}

/// \brief Add a PyBind11 type caster.
///
/// Using type caster has the advantage of not requiring to wrap the exposed
/// functions but the disadvantage of systematically requiring a copy.
///
/// See \ref https://pybind11.readthedocs.io/en/stable/advanced/cast/custom.html
/// "PyBind11 documentation"
#define PINOCCHIO_PYBIND11_TYPE_CASTER(native_type, boost_python_name)     \
  namespace pybind11 {                                                     \
  namespace detail {                                                       \
  template <>                                                              \
  struct type_caster<native_type> {                                        \
    PYBIND11_TYPE_CASTER(_SINGLE_ARG(native_type), boost_python_name);     \
                                                                           \
    /* Python -> C++ */                                                    \
    bool load(pybind11::handle src, bool) {                                \
      PyObject* source = src.ptr();                                        \
      value = boost::python::extract<native_type>(source);                 \
      return !PyErr_Occurred();                                            \
    }                                                                      \
    /* C++ -> Python */                                                    \
    static pybind11::handle cast(native_type src,                          \
                                 pybind11::return_value_policy /*policy*/, \
                                 pybind11::handle /*parent*/) {            \
      return boost::python::api::object(src).ptr();                        \
    }                                                                      \
  };                                                                       \
  } /* namespace detail */                                                 \
  } /* namespace pybind11 */

}  // namespace python
}  // namespace pinocchio

#undef _SINGLE_ARG

#endif  // #ifndef __pinocchio_python_pybind11_hpp__

ext: hpp

max_stars_repo_name: vishalbelsare/pinocchio

max_issues_repo_name: mulittleyun/pinocchio

max_forks_repo_name: mulittleyun/pinocchio


text:
#ifndef GAUGE_SPAN_AGGREGATOR_HPP
#define GAUGE_SPAN_AGGREGATOR_HPP
#include <chrono>
#include <list>
#include <map>
#include <memory>
#include <mutex>
#include <random>
#include <string>
#include <unordered_map>

#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <pybind11/pybind11.h>
#include <spdlog/logger.h>

#include "gauge/base.hpp"
#include "gauge/collector.hpp"
#include "gauge/utils/chrono.hpp"

namespace gauge {
namespace span_aggregator_impl {

namespace py = pybind11;
using namespace std::literals::chrono_literals;
using namespace boost::multi_index;

/**
 * Aggregates raw traces and turns them into spans.
 *
 *
 */
class SpanAggregator {
public:
    explicit SpanAggregator(
        std::chrono::steady_clock::duration span_ttl = 100ms);
    void subscribe(
        std::function<void(
            std::shared_ptr<std::vector<std::shared_ptr<Span>>>)> callback);
    void subscribe(py::object callback);
    void finish_open_spans();

    /**
     * Process raw trace-samples.
     *
     * This is the entry-point of the class, that activates it's main
     * functionality - aggregation of traces.
     *
     * @param traces Raw traces that has to be processed and aggregated.
     */
    void
    operator()(const std::shared_ptr<std::vector<std::shared_ptr<TraceSample>>>
                   &traces);

private:
    using TimePointConversionUtil = detail::TimePointConversionUtil<
        std::chrono::steady_clock,
        std::chrono::system_clock>;
    std::mutex                                mutex;
    std::shared_ptr<spdlog::logger>           logger;
    TimePointConversionUtil::BaseMeasurements clocks_base_measurements;
    std::forward_list<std::function<void(
        std::shared_ptr<std::vector<std::shared_ptr<Span>>>)>>
                                  callbacks;
    std::forward_list<py::object> py_callbacks;

    boost::uuids::random_generator random_generator;

    std::chrono::steady_clock::duration   span_ttl;
    std::chrono::steady_clock::time_point offset;
    std::chrono::steady_clock::time_point finish_offsets;

    /* --- Spans indexing --- */
    // TODO: Need to evaluate idea of having spans indexed as stacks.
    struct OpenSpan {
        decltype(Frame::cookie) cookie;
        std::shared_ptr<Span>   span;

        inline OpenSpan(
            decltype(Frame::cookie) cookie,
            std::shared_ptr<Span>   span)
            : cookie{cookie}, span{std::move(span)} {}
    };

    struct by_cookie {};
    struct by_id {};
    struct by_parent_id {};

    struct span_id_extractor {
        using result_type = decltype(Span::id);

        inline result_type operator()(const OpenSpan &open_span) const {
            return open_span.span->id;
        };
    };
    struct span_parent_id_extractor {
        using result_type = decltype(Span::parent_id);

        inline result_type operator()(const OpenSpan &open_span) const {
            return open_span.span->parent_id;
        };
    };

    multi_index_container<
        OpenSpan,
        indexed_by<
            hashed_unique<
                tag<by_cookie>,
                member<
                    OpenSpan,
                    decltype(OpenSpan::cookie),
                    &OpenSpan::cookie>>,
            hashed_unique<tag<by_id>, span_id_extractor>,
            hashed_non_unique<tag<by_parent_id>, span_parent_id_extractor>>>
        open_spans;
    /**
     * Index new open span
     *
     * Does not mutate the span in any way.
     */
    void add_span(
        const std::shared_ptr<Span> &       span,
        const decltype(Frame::cookie) &     cookie,
        std::vector<std::shared_ptr<Span>> &spans);
    /**
     * Remove indexed span.
     */
    void remove_span(
        const std::shared_ptr<Span> &       span,
        const decltype(Frame::cookie) &     cookie,
        std::vector<std::shared_ptr<Span>> &spans);
    /**
     * @overload void remove_span(
     *               const std::shared_ptr<Span>& span,
     *               const decltype(Frame::cookie) &cookie,
     *               std::vector<std::shared_ptr<Span>> &spans
     *           )
     */
    void remove_span(
        const std::shared_ptr<Span> &             span,
        const decltype(Frame::cookie) &           cookie,
        std::vector<std::shared_ptr<Span>> &      spans,
        decltype(Span::monotonic_clock_timestamp) monotonic_clock_timestamp,
        decltype(Span::timestamp)                 timestamp);

    void process_open_spans(
        std::shared_ptr<std::vector<std::shared_ptr<Span>>> &spans,
        bool force_finish = false);
    std::unique_ptr<Span> to_end_span(const std::shared_ptr<Span> &span);
    py::object            py_context;
    void                  sort_spans(
                         const std::shared_ptr<std::vector<std::shared_ptr<Span>>> &spans);
    void execute_callbacks(
        std::shared_ptr<std::vector<std::shared_ptr<Span>>> &spans);
};
} // namespace span_aggregator_impl

using span_aggregator_impl::SpanAggregator;

} // namespace gauge
#endif // GAUGE_SPAN_AGGREGATOR_HPP

max_stars_repo_name: AndreiPashkin/gauge

max_issues_repo_name: AndreiPashkin/gauge

max_forks_repo_name: AndreiPashkin/gauge


text:
#include "../DynAutoDiff/DynAutoDiff.hpp"
#include <algorithm>
#include <boost/test/tools/old/interface.hpp>
#include <eigen3/Eigen/Core>
#include <iostream>
#include <vector>

#define BOOST_TEST_MODULE ArithMetic_Test
#include <boost/test/included/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#define TL 1e-10

using namespace Eigen;
using namespace std;
using namespace DynAutoDiff;

BOOST_AUTO_TEST_SUITE(test)
BOOST_AUTO_TEST_CASE(multi_branch_test) {
    auto x1=psca(2.0),x2=psca(3.0),x3=psca(4.0),x4=psca(5.0);
	auto y1=x1*x2+x3;
	auto y2=y1*x4+y1;

	GraphManager<> m1(y2);
	m1.run();
	BOOST_CHECK_CLOSE(y2->v(), 60.0, 1e-5);
	BOOST_CHECK_CLOSE(x1->g(), 18.0, 1e-5);
}
BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: kilasuelika/DynAutoDiff

max_issues_repo_name: kilasuelika/DynAutoDiff

max_forks_repo_name: kilasuelika/DynAutoDiff


text:
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//版权所有（c）2012-2018比特币核心开发者
//根据MIT软件许可证分发，请参见随附的
//文件复制或http://www.opensource.org/licenses/mit-license.php。
#include <boost/test/unit_test.hpp>
#include <cuckoocache.h>
#include <script/sigcache.h>
#include <test/test_bitcoin.h>
#include <random.h>
#include <thread>

/*布谷缓存测试套件
 *
 *1）所有测试都应具有确定性结果（使用不安全的RAND）
 *具有确定性种子）
 *2）为便于测试，模板化了一些测试方法。
 *与新版本/比较
 *3）结果应视为回归测试，即行为
 *与预期相比有显著变化。这可以是正常的，取决于
 *更改的性质，但需要更新测试以反映新的
 *预期行为。例如，提高命中率可能会导致一些测试
 *使用Boost_检查关闭失败。
 *
 **/

BOOST_AUTO_TEST_SUITE(cuckoocache_tests);

/*测试是否没有从缓存中读取未插入的值。
 *
 *前200000个不安全的\getrandhash调用中没有重复
 **/

BOOST_AUTO_TEST_CASE(test_cuckoocache_no_fakes)
{
    SeedInsecureRand(true);
    CuckooCache::cache<uint256, SignatureCacheHasher> cc{};
    size_t megabytes = 4;
    cc.setup_bytes(megabytes << 20);
    for (int x = 0; x < 100000; ++x) {
        cc.insert(InsecureRand256());
    }
    for (int x = 0; x < 100000; ++x) {
        BOOST_CHECK(!cc.contains(InsecureRand256(), false));
    }
};

/*此帮助程序返回当条目数为兆字节*时的命中率。
 *插入到兆字节大小的缓存中
 **/

template <typename Cache>
static double test_cache(size_t megabytes, double load)
{
    SeedInsecureRand(true);
    std::vector<uint256> hashes;
    Cache set{};
    size_t bytes = megabytes * (1 << 20);
    set.setup_bytes(bytes);
    uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));
    hashes.resize(n_insert);
    for (uint32_t i = 0; i < n_insert; ++i) {
        uint32_t* ptr = (uint32_t*)hashes[i].begin();
        for (uint8_t j = 0; j < 8; ++j)
            *(ptr++) = InsecureRand32();
    }
    /*我们复制散列，因为
     *布谷缓存可能会覆盖插入的元素，因此测试是
     *“未来证明”。
     **/

    std::vector<uint256> hashes_insert_copy = hashes;
    /*做插入*/
    for (const uint256& h : hashes_insert_copy)
        set.insert(h);
    /*统计命中率*/
    uint32_t count = 0;
    for (const uint256& h : hashes)
        count += set.contains(h, false);
    double hit_rate = ((double)count) / ((double)n_insert);
    return hit_rate;
}

/*给定负载的标准化命中率。
 *
 *语义有点混乱，请看下面
 ＊解释。
 *
 *实例：
 *
 *1）在加载0.5时，我们期望有一个完美的命中率，因此我们乘以
 * 1
 *2）在加载2.0时，我们希望看到一半的条目，所以命中率非常理想。
 *为0.5。因此，如果我们看到0.4的命中率，0.4*2.0=0.8是
 *标准化命中率。
 *
 *这基本上是正确的语义，但根据
 *如何测量负载1.0左右，正如负载1.0之后您的标准化命中率一样。
 *变得非常完美，忽略新鲜感。
 **/

static double normalize_hit_rate(double hits, double load)
{
    return hits * std::max(load, 1.0);
}

/*检查从0.1到1.6的负载的命中率*/
BOOST_AUTO_TEST_CASE(cuckoocache_hit_rate_ok)
{
    /*为该测试选择的任意命中率阈值
     *作为性能的下限。
     **/

    double HitRateThresh = 0.98;
    size_t megabytes = 4;
    for (double load = 0.1; load < 2; load *= 2) {
        double hits = test_cache<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes, load);
        BOOST_CHECK(normalize_hit_rate(hits, load) > HitRateThresh);
    }
}

/*此帮助程序检查删除的元素是否优先插入和
 *刷新键的命中率是合理的。*/

template <typename Cache>
static void test_cache_erase(size_t megabytes)
{
    double load = 1;
    SeedInsecureRand(true);
    std::vector<uint256> hashes;
    Cache set{};
    size_t bytes = megabytes * (1 << 20);
    set.setup_bytes(bytes);
    uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));
    hashes.resize(n_insert);
    for (uint32_t i = 0; i < n_insert; ++i) {
        uint32_t* ptr = (uint32_t*)hashes[i].begin();
        for (uint8_t j = 0; j < 8; ++j)
            *(ptr++) = InsecureRand32();
    }
    /*我们复制散列，因为
     *布谷缓存可能会覆盖插入的元素，因此测试是
     *“未来证明”。
     **/

    std::vector<uint256> hashes_insert_copy = hashes;

    /*插入上半部分*/
    for (uint32_t i = 0; i < (n_insert / 2); ++i)
        set.insert(hashes_insert_copy[i]);
    /*删除第一个季度*/
    for (uint32_t i = 0; i < (n_insert / 4); ++i)
        BOOST_CHECK(set.contains(hashes[i], true));
    /*插入下半部分*/
    for (uint32_t i = (n_insert / 2); i < n_insert; ++i)
        set.insert(hashes_insert_copy[i]);

    /*我们标记为已删除但仍存在的元素*/
    size_t count_erased_but_contained = 0;
    /*我们没有删除但较旧的元素*/
    size_t count_stale = 0;
    /*最近插入的元素*/
    size_t count_fresh = 0;

    for (uint32_t i = 0; i < (n_insert / 4); ++i)
        count_erased_but_contained += set.contains(hashes[i], false);
    for (uint32_t i = (n_insert / 4); i < (n_insert / 2); ++i)
        count_stale += set.contains(hashes[i], false);
    for (uint32_t i = (n_insert / 2); i < n_insert; ++i)
        count_fresh += set.contains(hashes[i], false);

    double hit_rate_erased_but_contained = double(count_erased_but_contained) / (double(n_insert) / 4.0);
    double hit_rate_stale = double(count_stale) / (double(n_insert) / 4.0);
    double hit_rate_fresh = double(count_fresh) / (double(n_insert) / 2.0);

//检查我们的命中率是完美的
    BOOST_CHECK_EQUAL(hit_rate_fresh, 1.0);
//检查陈旧元素的命中率是否比
//删除的元素。
    BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained);
}

BOOST_AUTO_TEST_CASE(cuckoocache_erase_ok)
{
    size_t megabytes = 4;
    test_cache_erase<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes);
}

template <typename Cache>
static void test_cache_erase_parallel(size_t megabytes)
{
    double load = 1;
    SeedInsecureRand(true);
    std::vector<uint256> hashes;
    Cache set{};
    size_t bytes = megabytes * (1 << 20);
    set.setup_bytes(bytes);
    uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));
    hashes.resize(n_insert);
    for (uint32_t i = 0; i < n_insert; ++i) {
        uint32_t* ptr = (uint32_t*)hashes[i].begin();
        for (uint8_t j = 0; j < 8; ++j)
            *(ptr++) = InsecureRand32();
    }
    /*我们复制散列，因为
     *布谷缓存可能会覆盖插入的元素，因此测试是
     *“未来证明”。
     **/

    std::vector<uint256> hashes_insert_copy = hashes;
    boost::shared_mutex mtx;

    {
        /*抓住锁确保我们释放插入件*/
        boost::unique_lock<boost::shared_mutex> l(mtx);
        /*插入上半部分*/
        for (uint32_t i = 0; i < (n_insert / 2); ++i)
            set.insert(hashes_insert_copy[i]);
    }

    /*旋转3个线程运行包含擦除。
     **/

    std::vector<std::thread> threads;
    /*删除第一个季度*/
    for (uint32_t x = 0; x < 3; ++x)
        /*每个线程用x copy by value放置
        **/

        threads.emplace_back([&, x] {
            boost::shared_lock<boost::shared_mutex> l(mtx);
            size_t ntodo = (n_insert/4)/3;
            size_t start = ntodo*x;
            size_t end = ntodo*(x+1);
            for (uint32_t i = start; i < end; ++i) {
                bool contains = set.contains(hashes[i], true);
                assert(contains);
            }
        });

    /*等待所有线程完成
     **/

    for (std::thread& t : threads)
        t.join();
    /*抓紧锁，确保我们观察到擦除*/
    boost::unique_lock<boost::shared_mutex> l(mtx);
    /*插入下半部分*/
    for (uint32_t i = (n_insert / 2); i < n_insert; ++i)
        set.insert(hashes_insert_copy[i]);

    /*我们标记为已删除但仍存在的元素*/
    size_t count_erased_but_contained = 0;
    /*我们没有删除但较旧的元素*/
    size_t count_stale = 0;
    /*最近插入的元素*/
    size_t count_fresh = 0;

    for (uint32_t i = 0; i < (n_insert / 4); ++i)
        count_erased_but_contained += set.contains(hashes[i], false);
    for (uint32_t i = (n_insert / 4); i < (n_insert / 2); ++i)
        count_stale += set.contains(hashes[i], false);
    for (uint32_t i = (n_insert / 2); i < n_insert; ++i)
        count_fresh += set.contains(hashes[i], false);

    double hit_rate_erased_but_contained = double(count_erased_but_contained) / (double(n_insert) / 4.0);
    double hit_rate_stale = double(count_stale) / (double(n_insert) / 4.0);
    double hit_rate_fresh = double(count_fresh) / (double(n_insert) / 2.0);

//检查我们的命中率是完美的
    BOOST_CHECK_EQUAL(hit_rate_fresh, 1.0);
//检查陈旧元素的命中率是否比
//删除的元素。
    BOOST_CHECK(hit_rate_stale > 2 * hit_rate_erased_but_contained);
}
BOOST_AUTO_TEST_CASE(cuckoocache_erase_parallel_ok)
{
    size_t megabytes = 4;
    test_cache_erase_parallel<CuckooCache::cache<uint256, SignatureCacheHasher>>(megabytes);
}

template <typename Cache>
static void test_cache_generations()
{
//此测试检查网络活动模拟的新点击
//利率永远不会低于99%，而且比
//99.9%小于1%。
    double min_hit_rate = 0.99;
    double tight_hit_rate = 0.999;
    double max_rate_less_than_tight_hit_rate = 0.01;
//因此，满足此规范的缓存显示为命中
//至少紧密命中率*（1-最大命中率比紧密命中率低）
//最小命中率*最大命中率小于紧命中率=0.999*99%+0.99*1%==99.89%
//低方差命中率。

//我们使用确定性值，但是这个测试也传递了许多
//具有非确定性值的迭代，因此它不“过适合”于
//FastRandomContext中的特定熵（true）和
//隐藏物。
    SeedInsecureRand(true);

//block_activity为一块网络活动建模。插入元素为
//添加到缓存。第一个N/4和最后一个N/4将被存储以供以后删除。
//中间的n/2不存储。这模拟了一个使用半
//最近（自上一个块以来）添加的事务的签名
//立即使用另一半。
    struct block_activity {
        std::vector<uint256> reads;
        block_activity(uint32_t n_insert, Cache& c) : reads()
        {
            std::vector<uint256> inserts;
            inserts.resize(n_insert);
            reads.reserve(n_insert / 2);
            for (uint32_t i = 0; i < n_insert; ++i) {
                uint32_t* ptr = (uint32_t*)inserts[i].begin();
                for (uint8_t j = 0; j < 8; ++j)
                    *(ptr++) = InsecureRand32();
            }
            for (uint32_t i = 0; i < n_insert / 4; ++i)
                reads.push_back(inserts[i]);
            for (uint32_t i = n_insert - (n_insert / 4); i < n_insert; ++i)
                reads.push_back(inserts[i]);
            for (const auto& h : inserts)
                c.insert(h);
        }
    };

    const uint32_t BLOCK_SIZE = 1000;
//我们期望窗口大小60在每个时代都能合理地运行。
//存储缓存大小的45%（约472K）。
    const uint32_t WINDOW_SIZE = 60;
    const uint32_t POP_AMOUNT = (BLOCK_SIZE / WINDOW_SIZE) / 2;
    const double load = 10;
    const size_t megabytes = 4;
    const size_t bytes = megabytes * (1 << 20);
    const uint32_t n_insert = static_cast<uint32_t>(load * (bytes / sizeof(uint256)));

    std::vector<block_activity> hashes;
    Cache set{};
    set.setup_bytes(bytes);
    hashes.reserve(n_insert / BLOCK_SIZE);
    std::deque<block_activity> last_few;
    uint32_t out_of_tight_tolerance = 0;
    uint32_t total = n_insert / BLOCK_SIZE;
//我们用最后一个模型来模拟一个滑窗。在每个
//步骤，每个最后一个窗口的“大小块”活动检查缓存
//弹出他们插入的哈希数，并标记这些已删除。
    for (uint32_t i = 0; i < total; ++i) {
        if (last_few.size() == WINDOW_SIZE)
            last_few.pop_front();
        last_few.emplace_back(BLOCK_SIZE, set);
        uint32_t count = 0;
        for (auto& act : last_few)
            for (uint32_t k = 0; k < POP_AMOUNT; ++k) {
                count += set.contains(act.reads.back(), true);
                act.reads.pop_back();
            }
//我们使用最后的.size（）而不是窗口大小
//第一个窗口大小迭代的行为，其中deque不是
//满了。
        double hit = (double(count)) / (last_few.size() * POP_AMOUNT);
//检查命中率是否高于最小命中率
        BOOST_CHECK(hit > min_hit_rate);
//更严格的检查，计算我们低于严格命中率的次数
//（隐含地，大于最小命中率）
        out_of_tight_tolerance += hit < tight_hit_rate;
    }
//检查超差发生的时间是否小于
//最大命中率
    BOOST_CHECK(double(out_of_tight_tolerance) / double(total) < max_rate_less_than_tight_hit_rate);
}
BOOST_AUTO_TEST_CASE(cuckoocache_generations)
{
    test_cache_generations<CuckooCache::cache<uint256, SignatureCacheHasher>>();
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: yinchengtsinghua/BitCoinCppChinese

max_issues_repo_name: yinchengtsinghua/BitCoinCppChinese

max_forks_repo_name: yinchengtsinghua/BitCoinCppChinese


text:
//=======================================================================
// Copyright 1997, 1998, 1999, 2000 University of Notre Dame.
// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/config.hpp>
#include <iostream>
#include <iterator>
#include <vector>
#include <list>
// Use boost::queue instead of std::queue because std::queue doesn't
// model Buffer; it has to top() function. -Jeremy
#include <boost/pending/queue.hpp>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/visitors.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/graph_utility.hpp>

using namespace std;
using namespace boost;
/*
  This example does a best-first-search (using dijkstra's) and
  simultaneously makes a copy of the graph (assuming the graph is
  connected).

  Example Graph: (p. 90 "Data Structures and Network Algorithms", Tarjan)

              g
            3+ +2
            / 1 \
           e+----f
           |+0 5++
           | \ / |
         10|  d  |12
           |8++\7|
           +/ | +|
           b 4|  c
            \ | +
            6+|/3
              a

  Sample Output:
a --> c d
b --> a d
c --> f
d --> c e f
e --> b g
f --> e g
g -->
Starting graph:
a(32767); c d
c(32767); f
d(32767); c e f
f(32767); e g
e(32767); b g
g(32767);
b(32767); a d
Result:
a(0); d c
d(4); f e c
c(3); f
f(9); g e
e(4); g b
g(7);
b(14); d a

*/

typedef property< vertex_color_t, default_color_type,
    property< vertex_distance_t, int > >
    VProperty;
typedef int weight_t;
typedef property< edge_weight_t, weight_t > EProperty;

typedef adjacency_list< vecS, vecS, directedS, VProperty, EProperty > Graph;

template < class Tag >
struct endl_printer : public boost::base_visitor< endl_printer< Tag > >
{
    typedef Tag event_filter;
    endl_printer(std::ostream& os) : m_os(os) {}
    template < class T, class Graph > void operator()(T, Graph&)
    {
        m_os << std::endl;
    }
    std::ostream& m_os;
};
template < class Tag > endl_printer< Tag > print_endl(std::ostream& os, Tag)
{
    return endl_printer< Tag >(os);
}

template < class PA, class Tag >
struct edge_printer : public boost::base_visitor< edge_printer< PA, Tag > >
{
    typedef Tag event_filter;

    edge_printer(PA pa, std::ostream& os) : m_pa(pa), m_os(os) {}

    template < class T, class Graph > void operator()(T x, Graph& g)
    {
        m_os << "(" << get(m_pa, source(x, g)) << "," << get(m_pa, target(x, g))
             << ") ";
    }
    PA m_pa;
    std::ostream& m_os;
};
template < class PA, class Tag >
edge_printer< PA, Tag > print_edge(PA pa, std::ostream& os, Tag)
{
    return edge_printer< PA, Tag >(pa, os);
}

template < class NewGraph, class Tag >
struct graph_copier
: public boost::base_visitor< graph_copier< NewGraph, Tag > >
{
    typedef Tag event_filter;

    graph_copier(NewGraph& graph) : new_g(graph) {}

    template < class Edge, class Graph > void operator()(Edge e, Graph& g)
    {
        add_edge(source(e, g), target(e, g), new_g);
    }

private:
    NewGraph& new_g;
};
template < class NewGraph, class Tag >
inline graph_copier< NewGraph, Tag > copy_graph(NewGraph& g, Tag)
{
    return graph_copier< NewGraph, Tag >(g);
}

template < class Graph, class Name > void print(Graph& G, Name name)
{
    typename boost::graph_traits< Graph >::vertex_iterator ui, uiend;
    for (boost::tie(ui, uiend) = vertices(G); ui != uiend; ++ui)
    {
        cout << name[*ui] << " --> ";
        typename boost::graph_traits< Graph >::adjacency_iterator vi, viend;
        for (boost::tie(vi, viend) = adjacent_vertices(*ui, G); vi != viend;
             ++vi)
            cout << name[*vi] << " ";
        cout << endl;
    }
}

int main(int, char*[])
{
    // Name and ID numbers for the vertices
    char name[] = "abcdefg";
    enum
    {
        a,
        b,
        c,
        d,
        e,
        f,
        g,
        N
    };

    Graph G(N);
    boost::property_map< Graph, vertex_index_t >::type vertex_id
        = get(vertex_index, G);

    std::vector< weight_t > distance(N, (numeric_limits< weight_t >::max)());
    typedef boost::graph_traits< Graph >::vertex_descriptor Vertex;
    std::vector< Vertex > parent(N);

    typedef std::pair< int, int > E;

    E edges[] = { E(a, c), E(a, d), E(b, a), E(b, d), E(c, f), E(d, c), E(d, e),
        E(d, f), E(e, b), E(e, g), E(f, e), E(f, g) };

    int weight[] = { 3, 4, 6, 8, 12, 7, 0, 5, 10, 3, 1, 2 };

    for (int i = 0; i < 12; ++i)
        add_edge(edges[i].first, edges[i].second, weight[i], G);

    print(G, name);

    adjacency_list< listS, vecS, directedS,
        property< vertex_color_t, default_color_type > >
        G_copy(N);

    cout << "Starting graph:" << endl;

    std::ostream_iterator< int > cout_int(std::cout, " ");
    std::ostream_iterator< char > cout_char(std::cout, " ");

    boost::queue< Vertex > Q;
    boost::breadth_first_search(G, vertex(a, G), Q,
        make_bfs_visitor(boost::make_list(
            write_property(make_iterator_property_map(name, vertex_id, name[0]),
                cout_char, on_examine_vertex()),
            write_property(make_iterator_property_map(
                               distance.begin(), vertex_id, distance[0]),
                cout_int, on_examine_vertex()),
            print_edge(make_iterator_property_map(name, vertex_id, name[0]),
                std::cout, on_examine_edge()),
            print_endl(std::cout, on_finish_vertex()))),
        get(vertex_color, G));

    std::cout << "about to call dijkstra's" << std::endl;

    parent[vertex(a, G)] = vertex(a, G);
    boost::dijkstra_shortest_paths(G, vertex(a, G),
        distance_map(make_iterator_property_map(
                         distance.begin(), vertex_id, distance[0]))
            .predecessor_map(make_iterator_property_map(
                parent.begin(), vertex_id, parent[0]))
            .visitor(
                make_dijkstra_visitor(copy_graph(G_copy, on_examine_edge()))));

    cout << endl;
    cout << "Result:" << endl;
    boost::breadth_first_search(G, vertex(a, G),
        visitor(make_bfs_visitor(boost::make_list(
            write_property(make_iterator_property_map(name, vertex_id, name[0]),
                cout_char, on_examine_vertex()),
            write_property(make_iterator_property_map(
                               distance.begin(), vertex_id, distance[0]),
                cout_int, on_examine_vertex()),
            print_edge(make_iterator_property_map(name, vertex_id, name[0]),
                std::cout, on_examine_edge()),
            print_endl(std::cout, on_finish_vertex())))));

    return 0;
}

max_issues_repo_name: qingkouwei/mediaones

max_forks_repo_name: qingkouwei/mediaones


text:
#ifndef IOT_COMMON_HPP
#define IOT_COMMON_HPP

#include <iconv.h>
#include <sstream>
#include <ndn-cxx/face.hpp>
#include <ndn-cxx/interest.hpp>
#include <ndn-cxx/name.hpp>
#include <ndn-cxx/data.hpp>
#include <ndn-cxx/selectors.hpp>
#include <ndn-cxx/key-locator.hpp>
#include <ndn-cxx/security/key-chain.hpp>
#include <ndn-cxx/security/validator-config.hpp>
#include <ndn-cxx/util/time.hpp>
#include <ndn-cxx/util/scheduler.hpp>
#include <ndn-cxx/encoding/block-helpers.hpp>

#include <boost/utility.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/random/geometric_distribution.hpp>

#include <map>
#include <string>
#include <vector>
#include <queue>
#include <list>
#include <algorithm>
#include <iostream>
#include <functional>
#include <memory>

namespace iot {

using ndn::Face;
using ndn::Block;
using ndn::Name;
namespace name = ndn::name;
using ndn::Interest;
using ndn::InterestFilter;
using ndn::RegisterPrefixSuccessCallback;
using ndn::Selectors;
using ndn::Exclude;
using ndn::Data;
using ndn::KeyLocator;
using ndn::KeyChain;
using ndn::Scheduler;
using ndn::ValidatorConfig;
using ndn::tlv::Content;

using std::shared_ptr;
using std::make_shared;
using std::bind;
using std::placeholders::_1;
using std::placeholders::_2;

using boost::noncopyable;

//using iot::IotNodeCallBack;
//using iot::IotNode;

typedef uint64_t ProcessId;
typedef uint64_t SegmentNo;

const int  INTEREST_LIFE_TIME = 5000;

} // namespace iot

#endif // IOT_COMMON_HPP

max_stars_repo_name: usnistgov/NamedIoT

max_issues_repo_name: usnistgov/NamedIoT

max_forks_repo_name: usnistgov/NamedIoT


text:
#ifndef NT2_TOOLBOX_MATLAB_FUNCTION_FEVAL_HPP_INCLUDED
#define NT2_TOOLBOX_MATLAB_FUNCTION_FEVAL_HPP_INCLUDED

#include <nt2/toolbox/matlab/details/array.hpp>
#include <nt2/toolbox/matlab/details/mcr.hpp>

#include <nt2/extension/parameters.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/preprocessor/repetition/enum.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>

namespace nt2
{
    namespace matlab
    {
        // not exception-safe, hard to fix in C++03

        #define M1(z, n, text) traits::to_matlab(a##n)

        #define M0(z, n, text)                                                 \
        template<typename R BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_PARAMS(n, typename T)>\
        R feval(const char* s BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM_BINARY_PARAMS(n, const T, & a))\
        {                                                                      \
            details::mcr::instance();                                          \
                                                                               \
            mxArray* in[] = { mxCreateString(s) BOOST_PP_COMMA_IF(n) BOOST_PP_ENUM(n, M1, ~) };\
            mxArray* out[1];                                                   \
                                                                               \
            mlxFeval(sizeof out / sizeof *out, out, sizeof in / sizeof *in, in);\
                                                                               \
            for(int i=0; i<sizeof in / sizeof *in; ++i)                        \
                mxDestroyArray(in[i]);                                         \
                                                                               \
            R r = traits::from_matlab<R>(out[0]);                              \
                                                                               \
            for(int i=0; i<sizeof out / sizeof *out; ++i)                      \
                mxDestroyArray(out[i]);                                        \
                                                                               \
            return r;                                                          \
        }

        BOOST_PP_REPEAT(NT2_MAX_ARITY, M0, ~)
        #undef M0
        #undef M1
    }
}

#endif


text:
#pragma once

#define EIGEN_SPARSEMATRIX_PLUGIN "numeric/thread_safe_plugin.hpp"

#include <Eigen/Sparse>

#include "numeric/doublet.hpp"

namespace neon
{
/// Type alias for the row major sparse matrix type
using sparse_matrix = Eigen::SparseMatrix<double, Eigen::RowMajor>;
}

max_stars_repo_name: annierhea/neon

max_issues_repo_name: annierhea/neon

max_forks_repo_name: annierhea/neon


text:
#ifndef MATHTOOLBOX_L_BFGS_HPP
#define MATHTOOLBOX_L_BFGS_HPP

#include <Eigen/Core>
#include <functional>

namespace mathtoolbox
{
    namespace optimization
    {
        void RunLBfgs(const Eigen::VectorXd&                                        x_init,
                      const std::function<double(const Eigen::VectorXd&)>&          f,
                      const std::function<Eigen::VectorXd(const Eigen::VectorXd&)>& g,
                      const double                                                  epsilon,
                      const unsigned int                                            max_num_iterations,
                      Eigen::VectorXd&                                              x_star,
                      unsigned int&                                                 num_iterations);
    }
} // namespace mathtoolbox

#endif // MATHTOOLBOX_L_BFGS_HPP

max_stars_repo_name: yuki-koyama/mathtoolbox


text:
/*
 * Copyright 2013 Matthew Harvey
 *
 * 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 GUARD_sqlite_dbconn_hpp_8577399267152603
#define GUARD_sqlite_dbconn_hpp_8577399267152603

// Hide from Doxygen
/// @cond

/** @file
 *
 * @brief Header file pertaining to SQLiteDBConn class.
 */

#include "../sqloxx_exceptions.hpp"
#include "sql_statement_impl.hpp"
#include <jewel/checked_arithmetic.hpp>
#include "sqlite3.h"  // Compiling directly into build
#include <boost/filesystem/path.hpp>
#include <limits>
#include <string>
#include <vector>

namespace sqloxx
{
namespace detail
{

/**
 * @class SQLiteDBConn
 *
 * This class is designed to be used only by other classes within
 * the Sqloxx module, and should not be accessed by external client
 * code.
 *
 * This class is intended to encapsulate calls to the C API
 * provided by SQLite, in relation to managing a database connection
 * represented by a sqlite3* struct.
 *
 * SQLiteDBConn is in designed to be contained
 * within an instance of DatabaseConnection; and it is DatabaseConnection
 * that provides the higher-level interface with clients outside of
 * Sqloxx, as well as a range of convenience functions that are not
 * provided by this lower-level class.
 *
 * @todo MEDIUM PRIORITY Supply public member function to close database
 * connection. Currently this is done in the destructor, but destructors should
 * not throw, so the destructor calls std::terminate() if close or shut-down
 * fails.
 */
class SQLiteDBConn
{
    friend class SQLStatementImpl;

public:

    /**
     * Initializes SQLite3, if not already initialized, and creates a database
     * connection initially set to null.
     *
     * @throws SQLiteInitializationError if initialization fails
     * for any reason.
     */
    SQLiteDBConn();

    SQLiteDBConn(SQLiteDBConn const&) = delete;
    SQLiteDBConn(SQLiteDBConn&&) = delete;
    SQLiteDBConn& operator=(SQLiteDBConn const&) = delete;
    SQLiteDBConn& operator=(SQLiteDBConn&&) = delete;

    /**
     * Closes any open SQLite3 database connection.
     *
     * Does not throw. If SQLite3 connection closure fails, the application is
     * aborted with a diagnostic message written to std::clog.
     */
    ~SQLiteDBConn();

    /**
     * Returns \e true iff the SQLiteDBConn is currently connected to a
     * database file. Does not throw.
     */
    bool is_valid() const;

    /**
     * Implements DatabaseConnection::open.
     */
    void open(boost::filesystem::path const& filepath);

    /**
     * Implements DatabaseConnection::execute_sql
     */
    void execute_sql(std::string const& str);

    /**
     * At this point this function does not fully support SQLite extended
     * error codes; only the basic error codes. If errcode is an extended
     * error code that is not also a basic error code, and is not
     * SQLITE_OK, SQLITE_DONE or SQLITE_ROW, then the function will
     * throw SQLiteUnknownErrorCode. If errcode is a basic error code that
     * is not SQLITE_OK, SQLITE_DONE or SQLITE_ROW, then it will throw an
     * exception derived from
     * SQLiteException, with the exception thrown corresponding to the
     * error code (see sqloxx_exceptions.hpp) and the error message returned
     * by called what() on the exception corresponding to the error message
     * produced by SQLite.
     *
     * If the database connection is invalid (in particular, if the connection
     * is not open), then InvalidConnection will always be thrown, regardless
     * of the value of errcode.
     *
     * errcode should be the return value of an operation just executed on
     * the SQLite API on this database connection. The function assumes that
     * no other operation has been executed on the API since the operation
     * that produced errcode.
     *
     * @throws InvalidConnection if the database connection is invalid. This
     * takes precedence over other exceptions that might be thrown.
     *
     * @throws an exception derived from SQLiteException if and only if
     * errcode is something other than SQLITE_OK, BUT
     *
     * @throws std::logic_error if errcode is not the latest error code
     * produced by a call to the SQLite API on this database connection.
     *
     * @param a SQLite error code.
     *
     * Exception safety: strong guarantee.
     */
    void throw_on_failure(int errcode);

private:

    /**
     * A connection to a SQLite3 database file.
     *
     * (Note this is a raw pointer not a smart pointer
     * to facilitate more straightforward interaction with the SQLite
     * C API.)
     */
    sqlite3* m_connection;

};

}  // namespace detail
}  // namespace sqloxx

/// @endcond
// End hiding from Doxygen

#endif  // GUARD_sqlite_dbconn_hpp_8577399267152603

max_stars_repo_name: matt-harvey/sqloxx

max_issues_repo_name: matt-harvey/sqloxx

max_forks_repo_name: matt-harvey/sqloxx


text:
#ifndef crocofix_libcrocofix_reader_hpp
#define crocofix_libcrocofix_reader_hpp

#include "message.hpp"
#include <functional>
#include <boost/signals2.hpp>

namespace crocofix
{

class reader
{
public:

    boost::signals2::signal<void()> closed;

    using message_callback = std::function<void(message&)>;

    virtual void read_async(message_callback callback) = 0;

    virtual void close() = 0;

};

}

#endif

max_stars_repo_name: GaryHughes/crocofix

max_issues_repo_name: GaryHughes/crocofix

max_forks_repo_name: GaryHughes/crocofix


text:
/// @author Владимир Керимов

#include <data/value>
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(test_dozen)
    BOOST_AUTO_TEST_SUITE(test_value)

        BOOST_AUTO_TEST_CASE(test_value_create)
        {
            data::value first;
            BOOST_CHECK(first.is_null());

            data::value second(data::null);
            BOOST_CHECK(second.is_null());

            data::value third(true);
            BOOST_REQUIRE(third.is_not_null());
            BOOST_REQUIRE(!third.is_null());
            BOOST_CHECK(third.get_value<bool>());
            BOOST_CHECK(third.is_true());
            BOOST_CHECK(!third.is_false());

            static const int INT_VALUE = 123;

            data::value fourth(INT_VALUE);
            BOOST_REQUIRE(fourth.is_not_null());
            BOOST_REQUIRE(!fourth.is_null());
            BOOST_CHECK_EQUAL(fourth.get_value<long long>(), INT_VALUE);
            BOOST_CHECK_EQUAL(fourth.get_value<int>(), INT_VALUE);

            static const double FLOAT_VALUE = -1.024;

            data::value fifth(FLOAT_VALUE);
            BOOST_REQUIRE(!fifth.is_null());
            BOOST_REQUIRE(fifth.is_not_null());
            BOOST_CHECK_EQUAL(fifth.get_value<double>(), FLOAT_VALUE);
        }

    BOOST_AUTO_TEST_SUITE_END() // test_value
BOOST_AUTO_TEST_SUITE_END() // test_dozen

max_stars_repo_name: qualab/dozen

max_issues_repo_name: qualab/dozen

max_forks_repo_name: qualab/dozen


text:
#include <boost/filesystem.hpp>

#include <framework/model_manager.h>
#include <framework/model.h>
#include <framework/model_reader.h>
#include <framework/model_node.h>
#include <framework/texture.h>
#include <framework/paths.h>

namespace fs = boost::filesystem;

namespace fw {

std::shared_ptr<model> model_manager::get_model(std::string const &name) {
  FW_ENSURE_RENDER_THREAD();
  fs::path path = fw::resolve("meshes/" + name + ".mesh");
  debug << boost::format("loading mesh: %1%") % path << std::endl;

  auto it = _models.find(name);
  if (it == _models.end()) {
    model_reader reader;
    std::shared_ptr<model> model = reader.read(path);
    model->texture = std::shared_ptr<texture>(new texture());
    model->texture->create(fw::resolve("meshes/" + name + ".png"));
    model->root_node->initialize(model.get());
    _models[name] = model;
    return model;
  } else {
    return it->second;
  }
}

}

max_stars_repo_name: codeka/ravaged-planets

max_issues_repo_name: codeka/ravaged-planets

max_forks_repo_name: codeka/ravaged-planets


text:
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 "qpid/sys/windows/AsynchIoResult.h"
#include "qpid/sys/windows/IoHandlePrivate.h"
#include "qpid/sys/AsynchIO.h"
#include "qpid/sys/Mutex.h"
#include "qpid/sys/Socket.h"
#include "qpid/sys/Poller.h"
#include "qpid/sys/Thread.h"
#include "qpid/sys/Time.h"
#include "qpid/log/Statement.h"

#include "qpid/sys/windows/check.h"
#include "qpid/sys/windows/mingw32_compat.h"

#include <boost/thread/once.hpp>

#include <queue>
#include <winsock2.h>
#include <mswsock.h>
#include <windows.h>

#include <boost/bind.hpp>

namespace {

    typedef qpid::sys::ScopedLock<qpid::sys::Mutex>  QLock;

/*
 * The function pointers for AcceptEx and ConnectEx need to be looked up
 * at run time.
 */
const LPFN_ACCEPTEX lookUpAcceptEx(const qpid::sys::Socket& s) {
    SOCKET h = toSocketHandle(s);
    GUID guidAcceptEx = WSAID_ACCEPTEX;
    DWORD dwBytes = 0;
    LPFN_ACCEPTEX fnAcceptEx;
    WSAIoctl(h,
             SIO_GET_EXTENSION_FUNCTION_POINTER,
             &guidAcceptEx,
             sizeof(guidAcceptEx),
             &fnAcceptEx,
             sizeof(fnAcceptEx),
             &dwBytes,
             NULL,
             NULL);
    if (fnAcceptEx == 0)
        throw qpid::Exception(QPID_MSG("Failed to look up AcceptEx"));
    return fnAcceptEx;
}

}

namespace qpid {
namespace sys {
namespace windows {

/*
 * Asynch Acceptor
 *
 */
class AsynchAcceptor : public qpid::sys::AsynchAcceptor {

    friend class AsynchAcceptResult;

public:
    AsynchAcceptor(const Socket& s, AsynchAcceptor::Callback callback);
    ~AsynchAcceptor();
    void start(Poller::shared_ptr poller);

private:
    void restart(void);

    AsynchAcceptor::Callback acceptedCallback;
    const Socket& socket;
    const LPFN_ACCEPTEX fnAcceptEx;
};

AsynchAcceptor::AsynchAcceptor(const Socket& s, Callback callback)
  : acceptedCallback(callback),
    socket(s),
    fnAcceptEx(lookUpAcceptEx(s)) {

    s.setNonblocking();
}

AsynchAcceptor::~AsynchAcceptor()
{
    socket.close();
}

void AsynchAcceptor::start(Poller::shared_ptr poller) {
    PollerHandle ph = PollerHandle(socket);
    poller->monitorHandle(ph, Poller::INPUT);
    restart ();
}

void AsynchAcceptor::restart(void) {
    DWORD bytesReceived = 0;  // Not used, needed for AcceptEx API
    AsynchAcceptResult *result = new AsynchAcceptResult(acceptedCallback,
                                                        this,
                                                        socket);
    BOOL status;
    status = fnAcceptEx(toSocketHandle(socket),
                        toSocketHandle(*result->newSocket),
                        result->addressBuffer,
                        0,
                        AsynchAcceptResult::SOCKADDRMAXLEN,
                        AsynchAcceptResult::SOCKADDRMAXLEN,
                        &bytesReceived,
                        result->overlapped());
    QPID_WINDOWS_CHECK_ASYNC_START(status);
}

AsynchAcceptResult::AsynchAcceptResult(AsynchAcceptor::Callback cb,
                                       AsynchAcceptor *acceptor,
                                       const Socket& listener)
  : callback(cb), acceptor(acceptor),
    listener(toSocketHandle(listener)),
    newSocket(listener.createSameTypeSocket()) {
}

void AsynchAcceptResult::success(size_t /*bytesTransferred*/) {
    ::setsockopt (toSocketHandle(*newSocket),
                  SOL_SOCKET,
                  SO_UPDATE_ACCEPT_CONTEXT,
                  (char*)&listener,
                  sizeof (listener));
    callback(*(newSocket.release()));
    acceptor->restart ();
    delete this;
}

void AsynchAcceptResult::failure(int /*status*/) {
    //if (status != WSA_OPERATION_ABORTED)
    // Can there be anything else?  ;
    delete this;
}

/*
 * AsynchConnector does synchronous connects for now... to do asynch the
 * IocpPoller will need some extension to register an event handle as a
 * CONNECT-type "direction", the connect completion/result will need an
 * event handle to associate with the connecting handle. But there's no
 * time for that right now...
 */
class AsynchConnector : public qpid::sys::AsynchConnector {
private:
    ConnectedCallback connCallback;
    FailedCallback failCallback;
    const Socket& socket;
    const std::string hostname;
    const std::string port;

public:
    AsynchConnector(const Socket& socket,
                    const std::string& hostname,
                    const std::string& port,
                    ConnectedCallback connCb,
                    FailedCallback failCb = 0);
    void start(Poller::shared_ptr poller);
};

AsynchConnector::AsynchConnector(const Socket& sock,
                                 const std::string& hname,
                                 const std::string& p,
                                 ConnectedCallback connCb,
                                 FailedCallback failCb) :
    connCallback(connCb), failCallback(failCb), socket(sock),
    hostname(hname), port(p)
{
}

void AsynchConnector::start(Poller::shared_ptr)
{
    try {
        socket.connect(hostname, port);
        socket.setNonblocking();
        connCallback(socket);
    } catch(std::exception& e) {
        if (failCallback)
            failCallback(socket, -1, std::string(e.what()));
        socket.close();
    }
}

} // namespace windows

AsynchAcceptor* AsynchAcceptor::create(const Socket& s,
                                       Callback callback)
{
    return new windows::AsynchAcceptor(s, callback);
}

AsynchConnector* qpid::sys::AsynchConnector::create(const Socket& s,
                                                    const std::string& hostname,
                                                    const std::string& port,
                                                    ConnectedCallback connCb,
                                                    FailedCallback failCb)
{
    return new windows::AsynchConnector(s,
                                        hostname,
                                        port,
                                        connCb,
                                        failCb);
}

/*
 * Asynch reader/writer
 */

namespace windows {

class AsynchIO : public qpid::sys::AsynchIO {
public:
    AsynchIO(const Socket& s,
             ReadCallback rCb,
             EofCallback eofCb,
             DisconnectCallback disCb,
             ClosedCallback cCb = 0,
             BuffersEmptyCallback eCb = 0,
             IdleCallback iCb = 0);
    ~AsynchIO();

    // Methods inherited from qpid::sys::AsynchIO

    /**
     * Notify the object is should delete itself as soon as possible.
     */
    virtual void queueForDeletion();

    /// Take any actions needed to prepare for working with the poller.
    virtual void start(Poller::shared_ptr poller);
    virtual void queueReadBuffer(BufferBase* buff);
    virtual void unread(BufferBase* buff);
    virtual void queueWrite(BufferBase* buff);
    virtual void notifyPendingWrite();
    virtual void queueWriteClose();
    virtual bool writeQueueEmpty();
    virtual void startReading();
    virtual void stopReading();
    virtual void requestCallback(RequestCallback);

    /**
     * getQueuedBuffer returns a buffer from the buffer queue, if one is
     * available.
     *
     * @retval Pointer to BufferBase buffer; 0 if none is available.
     */
    virtual BufferBase* getQueuedBuffer();

private:
    ReadCallback readCallback;
    EofCallback eofCallback;
    DisconnectCallback disCallback;
    ClosedCallback closedCallback;
    BuffersEmptyCallback emptyCallback;
    IdleCallback idleCallback;
    const Socket& socket;
    Poller::shared_ptr poller;

    std::deque<BufferBase*> bufferQueue;
    std::deque<BufferBase*> writeQueue;
    /* The MSVC-supplied deque is not thread-safe; keep locks to serialize
     * access to the buffer queue and write queue.
     */
    Mutex bufferQueueLock;

    // Number of outstanding I/O operations.
    volatile LONG opsInProgress;
    // Is there a write in progress?
    volatile bool writeInProgress;
    // Or a read?
    volatile bool readInProgress;
    // Deletion requested, but there are callbacks in progress.
    volatile bool queuedDelete;
    // Socket close requested, but there are operations in progress.
    volatile bool queuedClose;

private:
    // Dispatch events that have completed.
    void notifyEof(void);
    void notifyDisconnect(void);
    void notifyClosed(void);
    void notifyBuffersEmpty(void);
    void notifyIdle(void);

    /**
     * Initiate a write of the specified buffer. There's no callback for
     * write completion to the AsynchIO object.
     */
    void startWrite(AsynchIO::BufferBase* buff);

    void close(void);

    /**
     * readComplete is called when a read request is complete.
     *
     * @param result Results of the operation.
     */
    void readComplete(AsynchReadResult *result);

    /**
     * writeComplete is called when a write request is complete.
     *
     * @param result Results of the operation.
     */
    void writeComplete(AsynchWriteResult *result);

    /**
     * Queue of completions to run. This queue enforces the requirement
     * from upper layers that only one thread at a time is allowed to act
     * on any given connection. Once a thread is busy processing a completion
     * on this object, other threads that dispatch completions queue the
     * completions here for the in-progress thread to handle when done.
     * Thus, any threads can dispatch a completion from the IocpPoller, but
     * this class ensures that actual processing at the connection level is
     * only on one thread at a time.
     */
    std::queue<AsynchIoResult *> completionQueue;
    volatile bool working;
    Mutex completionLock;

    /**
     * Called when there's a completion to process.
     */
    void completion(AsynchIoResult *result);

    /**
     * Helper function to facilitate the close operation
     */
    void cancelRead();
};

// This is used to encapsulate pure callbacks into a handle
class CallbackHandle : public IOHandle {
public:
    CallbackHandle(AsynchIoResult::Completer completeCb,
                   AsynchIO::RequestCallback reqCb = 0) :
    IOHandle(new IOHandlePrivate (INVALID_SOCKET, completeCb, reqCb))
    {}
};

AsynchIO::AsynchIO(const Socket& s,
                   ReadCallback rCb,
                   EofCallback eofCb,
                   DisconnectCallback disCb,
                   ClosedCallback cCb,
                   BuffersEmptyCallback eCb,
                   IdleCallback iCb) :

    readCallback(rCb),
    eofCallback(eofCb),
    disCallback(disCb),
    closedCallback(cCb),
    emptyCallback(eCb),
    idleCallback(iCb),
    socket(s),
    opsInProgress(0),
    writeInProgress(false),
    readInProgress(false),
    queuedDelete(false),
    queuedClose(false),
    working(false) {
}

struct deleter
{
    template <typename T>
    void operator()(T *ptr){ delete ptr;}
};

AsynchIO::~AsynchIO() {
    std::for_each( bufferQueue.begin(), bufferQueue.end(), deleter());
    std::for_each( writeQueue.begin(), writeQueue.end(), deleter());
}

void AsynchIO::queueForDeletion() {
    {
        ScopedLock<Mutex> l(completionLock);
        assert(!queuedDelete);
        queuedDelete = true;
        if (working || opsInProgress > 0) {
            QPID_LOG(info, "Delete AsynchIO queued; ops in progress");
            // AsynchIOHandler calls this then deletes itself; don't do any more
            // callbacks.
            readCallback = 0;
            eofCallback = 0;
            disCallback = 0;
            closedCallback = 0;
            emptyCallback = 0;
            idleCallback = 0;
            return;
        }
    }
    delete this;
}

void AsynchIO::start(Poller::shared_ptr poller0) {
    PollerHandle ph = PollerHandle(socket);
    poller = poller0;
    poller->monitorHandle(ph, Poller::INPUT);
    if (writeQueue.size() > 0)  // Already have data queued for write
        notifyPendingWrite();
    startReading();
}

void AsynchIO::queueReadBuffer(AsynchIO::BufferBase* buff) {
    assert(buff);
    buff->dataStart = 0;
    buff->dataCount = 0;
    QLock l(bufferQueueLock);
    bufferQueue.push_back(buff);
}

void AsynchIO::unread(AsynchIO::BufferBase* buff) {
    assert(buff);
    buff->squish();
    QLock l(bufferQueueLock);
    bufferQueue.push_front(buff);
}

void AsynchIO::queueWrite(AsynchIO::BufferBase* buff) {
    assert(buff);
    QLock l(bufferQueueLock);
    writeQueue.push_back(buff);
    if (!writeInProgress)
        notifyPendingWrite();
}

void AsynchIO::notifyPendingWrite() {
    // This method is generally called from a processing thread; transfer
    // work on this to an I/O thread. Much of the upper layer code assumes
    // that all I/O-related things happen in an I/O thread.
    if (poller == 0)    // Not really going yet...
        return;

    InterlockedIncrement(&opsInProgress);
    PollerHandle ph(CallbackHandle(boost::bind(&AsynchIO::completion, this, _1)));
    poller->monitorHandle(ph, Poller::OUTPUT);
}

void AsynchIO::queueWriteClose() {
    {
        ScopedLock<Mutex> l(completionLock);
        queuedClose = true;
        if (working || writeInProgress)
            // no need to summon an IO thread
            return;
    }
    notifyPendingWrite();
}

bool AsynchIO::writeQueueEmpty() {
    QLock l(bufferQueueLock);
    return writeQueue.size() == 0;
}

/*
 * Initiate a read operation. AsynchIO::readComplete() will be
 * called when the read is complete and data is available.
 */
void AsynchIO::startReading() {
    if (queuedDelete || queuedClose)
        return;

    // (Try to) get a buffer; look on the front since there may be an
    // "unread" one there with data remaining from last time.
    AsynchIO::BufferBase *buff = 0;
    {
        QLock l(bufferQueueLock);

        if (!bufferQueue.empty()) {
            buff = bufferQueue.front();
            assert(buff);
            bufferQueue.pop_front();
        }
    }
    if (buff != 0) {
        int readCount = buff->byteCount - buff->dataCount;
        AsynchReadResult *result =
            new AsynchReadResult(boost::bind(&AsynchIO::completion, this, _1),
                                 buff,
                                 readCount);
        DWORD bytesReceived = 0, flags = 0;
        InterlockedIncrement(&opsInProgress);
        readInProgress = true;
        int status = WSARecv(toSocketHandle(socket),
                             const_cast<LPWSABUF>(result->getWSABUF()), 1,
                             &bytesReceived,
                             &flags,
                             result->overlapped(),
                             0);
        if (status != 0) {
            int error = WSAGetLastError();
            if (error != WSA_IO_PENDING) {
                result->failure(error);
                result = 0;   // result is invalid here
                return;
            }
        }
        // On status 0 or WSA_IO_PENDING, completion will handle the rest.
    }
    else {
        notifyBuffersEmpty();
    }
    return;
}

// stopReading was added to prevent a race condition with read-credit on Linux.
// It may or may not be required on windows.
//
// AsynchIOHandler::readbuff() calls stopReading() inside the same
// critical section that protects startReading() in
// AsynchIOHandler::giveReadCredit().
//
void AsynchIO::stopReading() {}

// Queue the specified callback for invocation from an I/O thread.
void AsynchIO::requestCallback(RequestCallback callback) {
    // This method is generally called from a processing thread; transfer
    // work on this to an I/O thread. Much of the upper layer code assumes
    // that all I/O-related things happen in an I/O thread.
    if (poller == 0)    // Not really going yet...
        return;

    InterlockedIncrement(&opsInProgress);
    PollerHandle ph(CallbackHandle(
        boost::bind(&AsynchIO::completion, this, _1),
        callback));
    poller->monitorHandle(ph, Poller::INPUT);
}

/**
 * Return a queued buffer if there are enough to spare.
 */
AsynchIO::BufferBase* AsynchIO::getQueuedBuffer() {
    QLock l(bufferQueueLock);
    // Always keep at least one buffer (it might have data that was
    // "unread" in it).
    if (bufferQueue.size() <= 1)
        return 0;
    BufferBase* buff = bufferQueue.back();
    assert(buff);
    bufferQueue.pop_back();
    return buff;
}

void AsynchIO::notifyEof(void) {
    if (eofCallback)
        eofCallback(*this);
}

void AsynchIO::notifyDisconnect(void) {
    if (disCallback)
        disCallback(*this);
}

void AsynchIO::notifyClosed(void) {
    if (closedCallback)
        closedCallback(*this, socket);
}

void AsynchIO::notifyBuffersEmpty(void) {
    if (emptyCallback)
        emptyCallback(*this);
}

void AsynchIO::notifyIdle(void) {
    if (idleCallback)
        idleCallback(*this);
}

/*
 * Asynch reader/writer using overlapped I/O
 */

void AsynchIO::startWrite(AsynchIO::BufferBase* buff) {
    writeInProgress = true;
    InterlockedIncrement(&opsInProgress);
    AsynchWriteResult *result =
        new AsynchWriteResult(boost::bind(&AsynchIO::completion, this, _1),
                              buff,
                              buff->dataCount);
    DWORD bytesSent = 0;
    int status = WSASend(toSocketHandle(socket),
                         const_cast<LPWSABUF>(result->getWSABUF()), 1,
                         &bytesSent,
                         0,
                         result->overlapped(),
                         0);
    if (status != 0) {
        int error = WSAGetLastError();
        if (error != WSA_IO_PENDING) {
            result->failure(error);   // Also decrements in-progress count
            result = 0;   // result is invalid here
            return;
        }
    }
    // On status 0 or WSA_IO_PENDING, completion will handle the rest.
    return;
}

/*
 * Close the socket and callback to say we've done it
 */
void AsynchIO::close(void) {
    socket.close();
    notifyClosed();
}

void AsynchIO::readComplete(AsynchReadResult *result) {
    int status = result->getStatus();
    size_t bytes = result->getTransferred();
    readInProgress = false;
    if (status == 0 && bytes > 0) {
        if (readCallback)
            readCallback(*this, result->getBuff());
        startReading();
    }
    else {
        // No data read, so put the buffer back. It may be partially filled,
        // so "unread" it back to the front of the queue.
        unread(result->getBuff());
        if (queuedClose) {
            return; // Expected from cancelRead()
        }
        notifyEof();
        if (status != 0)
        {
            notifyDisconnect();
        }
    }
}

/*
 * NOTE - this completion is called for completed writes and also when
 * a write is desired. The difference is in the buff - if a write is desired
 * the buff is 0.
 */
void AsynchIO::writeComplete(AsynchWriteResult *result) {
    int status = result->getStatus();
    size_t bytes = result->getTransferred();
    AsynchIO::BufferBase *buff = result->getBuff();
    if (buff != 0) {
        writeInProgress = false;
        if (status == 0 && bytes > 0) {
            if (bytes < result->getRequested()) // Still more to go; resubmit
                startWrite(buff);
            else
                queueReadBuffer(buff);     // All done; back to the pool
        }
        else {
            // An error... if it's a connection close, ignore it - it will be
            // noticed and handled on a read completion any moment now.
            // What to do with real error??? Save the Buffer?
        }
    }

    // If there are no writes outstanding, check for more writes to initiate
    // (either queued or via idle). The opsInProgress count is handled in
    // completion()
    if (!writeInProgress) {
        bool writing = false;
        {
            QLock l(bufferQueueLock);
            if (writeQueue.size() > 0) {
                buff = writeQueue.front();
                assert(buff);
                writeQueue.pop_front();
                startWrite(buff);
                writing = true;
            }
        }
        if (!writing && !queuedClose) {
            notifyIdle();
        }
    }
    return;
}

void AsynchIO::completion(AsynchIoResult *result) {
    bool closing = false;
    bool deleting = false;
    {
        ScopedLock<Mutex> l(completionLock);
        if (working) {
            completionQueue.push(result);
            return;
        }

        // First thread in with something to do; note we're working then keep
        // handling completions.
        working = true;
        while (result != 0) {
            // New scope to unlock temporarily.
            {
                ScopedUnlock<Mutex> ul(completionLock);
                AsynchReadResult *r = dynamic_cast<AsynchReadResult*>(result);
                if (r != 0)
                    readComplete(r);
                else {
                    AsynchWriteResult *w =
                        dynamic_cast<AsynchWriteResult*>(result);
                    if (w != 0)
                        writeComplete(w);
                    else {
                        AsynchCallbackRequest *req =
                          dynamic_cast<AsynchCallbackRequest*>(result);
                        req->reqCallback(*this);
                    }
                }
                delete result;
                result = 0;
                InterlockedDecrement(&opsInProgress);
                if (queuedClose && opsInProgress == 1 && readInProgress)
                    cancelRead();
            }
            // Lock is held again.
            if (completionQueue.empty())
                continue;
            result = completionQueue.front();
            completionQueue.pop();
        }
        working = false;
        if (opsInProgress == 0) {
            closing = queuedClose;
            deleting = queuedDelete;
        }
    }
    // Lock released; ok to close if ops are done and close requested.
    // Layer above will call back to queueForDeletion() if it hasn't
    // already been done. If it already has, go ahead and delete.
    if (deleting)
        delete this;
    else if (closing)
        // close() may cause a delete; don't trust 'this' on return
        close();
}

/*
 * NOTE - this method must be called in the same context as other completions,
 * so that the resulting readComplete, and final AsynchIO::close() is serialized
 * after this method returns.
 */
void AsynchIO::cancelRead() {
    if (queuedDelete)
        return;                 // socket already deleted
    else {
        ScopedLock<Mutex> l(completionLock);;
        if (!completionQueue.empty())
            return;             // process it; come back later if necessary
    }
    // Cancel outstanding read and force to completion.  Otherwise, on a faulty
    // physical link, the pending read can remain uncompleted indefinitely.
    // Draining the pending read will result in the official close (and
    // notifyClosed).  CancelIoEX() is the natural choice, but not available in
    // XP, so we make do with closesocket().
    socket.close();
}

} // namespace windows

AsynchIO* qpid::sys::AsynchIO::create(const Socket& s,
                                      AsynchIO::ReadCallback rCb,
                                      AsynchIO::EofCallback eofCb,
                                      AsynchIO::DisconnectCallback disCb,
                                      AsynchIO::ClosedCallback cCb,
                                      AsynchIO::BuffersEmptyCallback eCb,
                                      AsynchIO::IdleCallback iCb)
{
    return new qpid::sys::windows::AsynchIO(s, rCb, eofCb, disCb, cCb, eCb, iCb);
}

}}  // namespace qpid::sys

max_stars_repo_name: gcsideal/debian-qpid-cpp

max_issues_repo_name: gcsideal/debian-qpid-cpp

max_forks_repo_name: gcsideal/debian-qpid-cpp


text: #include <boost/units/base_units/astronomical/light_year.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**************************************************************
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 INCLUDED_WW8_STRUCT_BASE_HXX
#define INCLUDED_WW8_STRUCT_BASE_HXX

#include <boost/shared_ptr.hpp>
#include <doctok/WW8Document.hxx>
#include <resourcemodel/OutputWithDepth.hxx>

namespace writerfilter {
namespace doctok {

class WW8DocumentImpl;

/**
   Part of a stream.

   A part can have a parent, meaning its sequence of data is a
   subsequence of its parent's sequence of data.
 */
class WW8StructBase
{
public:
    typedef SubSequence<sal_uInt8> Sequence;
    typedef boost::shared_ptr<WW8StructBase> Pointer_t;

protected:
    /**
       Stream this part was created from.
    */
    ::com::sun::star::uno::Reference<com::sun::star::io::
    XInputStream> mrStream;

    /**
       The data.
     */
    mutable Sequence mSequence;

    /**
       This part's parent.
     */
    WW8StructBase * mpParent;

    /**
       This part's offset in parent.
    */
    sal_uInt32 mnOffsetInParent;

    /**
       The document of this struct.
     */
    WW8DocumentImpl * mpDocument;

public:
    WW8StructBase(sal_Int32 nLength)
    : mSequence(nLength)
    {
    }

    /**
       Creates a part from a steam.

       @param rStream    the stream
       @param nOffset    offset in @a rStream to start at
       @param nCount     count of bytes in the new part
     */
    WW8StructBase(WW8Stream & rStream,
                  sal_Int32 nOffset, sal_Int32 nCount)
    : mSequence(rStream.get(nOffset, nCount)), mpParent(0), mpDocument(0)
    {
    }

    /**
       Creates a part from a sequence.

       @param rSequence    the sequence
       @param nOffset    offset in @a rSequence to start at
       @param nCount     count of bytes in the new part
     */
    WW8StructBase(const Sequence & rSequence, sal_uInt32 nOffset = 0,
                  sal_uInt32 nCount = 0)
    : mSequence(rSequence, nOffset, nCount), mpParent(0), mpDocument(0)
    {
    }

    /**
       Creates a part from a parent part.

       @param pParent    the parent
       @param nOffset    offset in @a pParent to start at
       @param nCount     count of bytes in the new part
     */
    WW8StructBase(const WW8StructBase & rParent,
                  sal_uInt32 nOffset, sal_uInt32 nCount);

    /**
       Creates a part from a parent part.

       @param pParent    the parent
       @param nOffset    offset in @a pParent to start at
       @param nCount     count of bytes in the new part
     */
    WW8StructBase(WW8StructBase * pParent,
                  sal_uInt32 nOffset, sal_uInt32 nCount)
    : mSequence(pParent->mSequence, nOffset, nCount), mpParent(pParent),
      mnOffsetInParent(nOffset), mpDocument(pParent->getDocument())
    {
        if (nOffset + nCount > pParent->mSequence.getCount())
            throw ExceptionOutOfBounds("WW8StructBase");
    }

    virtual ~WW8StructBase()
    {
    }

    /**
       Assign a part to this part.

       After assignment this part has the same content as the assigned
       part.

       @param rSrc     part to assign

       @return this part after assignment
     */
    virtual WW8StructBase & Assign(const WW8StructBase & rSrc);

    /**
       Set the document of this struct.
     */
    void setDocument(WW8DocumentImpl * pDocument);

    /**
       Return the document of this struct.
    */
    WW8DocumentImpl * getDocument() const;

    /**
       Return count of bytes in this part.
     */
    sal_uInt32 getCount() const { return mSequence.getCount(); }

    /**
       Return unsigned byte value at an offset.

       @param offset     offset to get value from
     */
    sal_uInt8 getU8(sal_uInt32 nOffset) const;

    /**
       Return unsigned 16-bit value at an offset.

       @param offset     offset to get value from
     */
    sal_uInt16 getU16(sal_uInt32 nOffset) const;

    /**
       Return unsigned 32-bit value at an offset.

       @param offset     offset to get value from
     */
    sal_uInt32 getU32(sal_uInt32 nOffset) const;

    /**
       Return signed 8-bit value at an offset.

       @param offset     offset to get value from
     */
    sal_Int8 getS8(sal_uInt32 nOffset) const
    { return (sal_Int8) getU8(nOffset); }

    /**
       Return signed 16-bit value at an offset.

       @param offset     offset to get value from
     */
    sal_Int16 getS16(sal_uInt32 nOffset) const
    {return (sal_Int16) getU16(nOffset); }

    /**
       Return signed 32-bit value at an offset.

       @param offset     offset to get value from
     */
    sal_Int32 getS32(sal_uInt32 nOffset) const
    { return (sal_Int32) getU32(nOffset); }

    /**
       Return bit value from a 32-bit unsigned value.

       @param nValue     value to retrieve bit from
       @param nBit       number of bit to retrieve (0 = least significant)
     */
    sal_Bool getBit(sal_uInt32 nValue, sal_uInt16 nBit) const;

    /**
        Return nibble from a 32-bit unsigned value.

        @param nValue   value to retrieve nibble from (most significant bit left)
        @param nShift   amount of bits to shift right before returning least significant nibble
    */
    sal_uInt8 getNibble(sal_uInt32 nValue, sal_uInt16 nShift) const;

    /**
       Returns byte at an index.

       @param nIndex  index in this part of the byte to return
     */
    const sal_uInt8 * get(sal_uInt32 nIndex) const
    { return &((mSequence.getSequence())[nIndex + mSequence.getOffset()]); }

    /**
       Returns two byte character string starting at an offset.

       The string has to be Pascal like, e.g. the first word contains
       the lengthof the string in characters and is followed by the
       string's characters.

       @param nOffset    offset the string starts at

       @return  the string
     */
    rtl::OUString getString(sal_uInt32 nOffset) const;

    /**
       Returns binary object for remainder of this WW8StructBase

       @param nOffset     offset where remainder starts
     */
    WW8StructBase * getRemainder(sal_uInt32 nOffset) const;

    /**
       Returns two byte character string starting at an offset with a
       given length.

       @param nOffset     offset the string starts at
       @param nLength     number of characters in the string
     */
    rtl::OUString getString(sal_uInt32 nOffset, sal_uInt32) const;

    /**
       Dump the part.

       @param o       stream to dump to
     */
    virtual void dump(OutputWithDepth<string> & o) const { mSequence.dump(o); }
};

class WW8StructBaseTmpOffset
{
    sal_uInt32 mnOffset;
    WW8StructBase * mpStructBase;

public:
    WW8StructBaseTmpOffset(WW8StructBase * pStructBase);

    sal_uInt32 set(sal_uInt32 nOffset);
    sal_uInt32 get() const;
    sal_uInt32 inc(sal_uInt32 nOffset);

    operator sal_uInt32 () const;
};

/**
   Return unsigned byte from a sequence.

   @param rSeq        sequence to get value from
   @param nOffset     offset in sequence to get value from
 */
sal_uInt8 getU8(const WW8StructBase::Sequence & rSeq,  sal_uInt32 nOffset);

/**
   Return unsigned 16-bit value from a sequence.

   @param rSeq        sequence to get value from
   @param nOffset     offset in sequence to get value from
 */
sal_uInt16 getU16(const WW8StructBase::Sequence & rSeq, sal_uInt32 nOffset);

/**
   Return unsigned 32-bit value from a sequence.

   @param rSeq        sequence to get value from
   @param nOffset     offset in sequence to get value from
 */
sal_uInt32 getU32(const WW8StructBase::Sequence & rSeq, sal_uInt32 nOffset);

}}

#endif // INCLUDED_WW8_STRUCT_BASE_HXX

ext: hxx

max_stars_repo_name: Grosskopf/openoffice

max_issues_repo_name: Grosskopf/openoffice

max_forks_repo_name: Grosskopf/openoffice