text:
// (C) Copyright 2005 Matthias Troyer

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

//  Authors: Matthias Troyer

#include <boost/serialization/array.hpp>

#ifndef BOOST_MPI_DETAIL_FORWARD_IPRIMITIVE_HPP
#define BOOST_MPI_DETAIL_FORWARD_IPRIMITIVE_HPP

namespace boost {
namespace mpi {
namespace detail {

/// @brief a minimal input archive, which forwards reading to another archive
///
/// This class template is designed to use the loading facilities of another
/// input archive (the "implementation archive", whose type is specified by
/// the template argument, to handle serialization of primitive types,
/// while serialization for specific types can be overriden independently
/// of that archive.

template <class ImplementationArchive> class forward_iprimitive {
public:
  /// the type of the archive to which the loading of primitive types will be
  /// forwarded
  typedef ImplementationArchive implementation_archive_type;

  /// the constructor takes a reference to the implementation archive used for
  /// loading primitve types
  forward_iprimitive(implementation_archive_type &ar)
      : implementation_archive(ar) {}

  /// binary loading is forwarded to the implementation archive
  void load_binary(void *address, std::size_t count) {
    implementation_archive.load_binary(address, count);
  }

  /// loading of arrays is forwarded to the implementation archive
  template <class T>
  void load_array(serialization::array_wrapper<T> &x,
                  unsigned int file_version) {
    implementation_archive.load_array(x, file_version);
  }

  typedef typename ImplementationArchive::use_array_optimization
      use_array_optimization;

#ifndef BOOST_NO_MEMBER_TEMPLATE_FRIENDS
  friend class archive::load_access;

protected:
#else
public:
#endif

  ///  loading of primitives is forwarded to the implementation archive
  template <class T> void load(T &t) { implementation_archive >> t; }

private:
  implementation_archive_type &implementation_archive;
};

} // namespace detail
} // namespace mpi
} // namespace boost

#endif // BOOST_MPI_DETAIL_FORWARD_IPRIMITIVE_HPP

ext: hpp

max_stars_repo_name: henrywarhurst/matrix

max_issues_repo_name: henrywarhurst/matrix

max_forks_repo_name: henrywarhurst/matrix


text:
//  (C) Copyright Gennadiy Rozental 2001-2012.
//  Distributed under the Boost Software License, Version 1.0.
//  (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : ifstream_line_iterator unit test
// *****************************************************************************

// Boost.Test
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

#include <boost/test/utils/iterator/ifstream_line_iterator.hpp>

namespace ut = boost::unit_test;

static ut::ifstream_line_iterator eoi;

//____________________________________________________________________________//

BOOST_AUTO_TEST_CASE( test_default_delimeter )
{
    ut::ifstream_line_iterator it( ut::framework::master_test_suite().argc <= 1
                                        ? "./test_files/ifstream_line_iterator.tst1"
                                        : ut::framework::master_test_suite().argv[1] );

    BOOST_CHECK( it != eoi );

    BOOST_CHECK_EQUAL( *it, "acv ffg" );
    ++it;

    BOOST_CHECK_EQUAL( *it, "" );
    ++it;

    BOOST_CHECK_EQUAL( *it, " " );
    ++it;

    BOOST_CHECK_EQUAL( *it, "1" );
    ++it;

    BOOST_CHECK( it == eoi );
}

//____________________________________________________________________________//

BOOST_AUTO_TEST_CASE( test_custom_delimeter )
{
    ut::ifstream_line_iterator it( ut::framework::master_test_suite().argc <= 2
                                        ? "./test_files/ifstream_line_iterator.tst2"
                                        : ut::framework::master_test_suite().argv[2], '}' );

    BOOST_CHECK( it != eoi );

    BOOST_CHECK_EQUAL( *it, "{ abc d " );
    ++it;

    BOOST_CHECK_EQUAL( *it, "\n{ d \n dsfg\n" );
    ++it;

    BOOST_CHECK_EQUAL( *it, "\n" );
    ++it;

    BOOST_CHECK( it == eoi );
}

//____________________________________________________________________________//

// EOF

ext: cpp

max_stars_repo_name: juslee/boost-svn

max_issues_repo_name: datacratic/boost-svn

max_forks_repo_name: datacratic/boost-svn


text:
//
// Created by zhaobq on 2017-4-25.
//

#include <boost/python.hpp>
#include "MPI_Server.cpp"
#include "MPI_Base.cpp"
#include "Include/IRecv_buffer.h"
using namespace boost::python;

BOOST_PYTHON_MODULE(Server_Module)
{
        class_<MPI_Server>("MPI_Server", init<IRecv_buffer*, char*>())
                //.def("run", &MPI_Server::run)
                .def("initialize", &MPI_Server::initialize)
                .def("stop", &MPI_Server::stop)
                .def("finalize", &MPI_Server::finalize)
                //.def("recv_handle", &MPI_Server::recv_handle)
                //.def("send_int", &MPI_Server::send_int)
                .def("send_string", &MPI_Server::send_string)
                //.def("disconnect_client", &MPI_Server::disconnect_client)
                //.def("bcast", &MPI_Server::bcast)
                .def("get_Commlist_size", &MPI_Server::get_Commlist_size)
                .def("get_stop_permit",&MPI_Server::get_stop_permit)
                .def("print_Commlist", &MPI_Server::print_Commlist)
				.def("set_portfile", &MPI_Server::set_portfile)
                ;

}


text:
// Copyright 2017 Ralf Kohrt

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <hdf5.h>
#include <boost/filesystem/operations.hpp>
#include <string>
#include <iostream>

#include "rootData.hpp"
#include "storableWrapper.hpp"
#include "hdf5Helper.hpp"
#include "dataWriterHdf5.hpp"

using namespace RecHDF;

int main(int argc, const char* argv[] ) {

    if(argc < 2) {
        std::cout << "usage: " << argv[0] << " [output-filename] \n";
        return 1;
    }
    boost::filesystem::path p(argv[1]);
    if(boost::filesystem::exists(p)){
        std::cout << "file " << argv[1] << " does already exist" << std::endl;
    }
    hid_t fileId = Hdf5Helper::openFile(p);

    //generate data
    std::shared_ptr<rootData> root = std::make_shared<rootData>();

    if(!Hdf5Helper::doesGroupExist("recursiveOutput",fileId)) {
        dataWriterHdf5<double, int> d(fileId, "recursiveOutput");
        d.store(std::make_shared<storableWrapper >( root ));
    }
    H5Fclose(fileId);
}


text:
// Copyright (c) 2007-2008 Sean Kent
//
// 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 )
//
// $LastChangedBy$ - $LastChangedDate$
//
//     Notes:
// Ownership of intrusive_ptr<T> enabled classes is always shared despite descriptions bellow, except where copied.
// You will still need to use intrusive_ptr<T> or equivalent, of course, on the C++ side of things.
//
//     Missing:
// ruby_value doesn't handle shared_ptr<T> or scoped_ptr<T> and probably never will.  Sharing their ownership
// is a PITA or impossible, and .get() should be used to make explicit the lack of ownership transfer.
// Types lacking ruby_value<...>::from are unidirectional from C++ to Ruby
// ruby_value<...>::to is usually missing due to constness and Ruby not respecting it (yet).
//
//     See also:
// industry/languages/ruby/detail/builtins.hpp for the specializations of "value" (always copied) types

#ifndef IG_INDUSTRY_LANGAUGES_RUBY_DETAIL_RUBY_VALUE
#define IG_INDUSTRY_LANGAUGES_RUBY_DETAIL_RUBY_VALUE

#include <industry/languages/ruby/declarations.hpp>
#include <industry/languages/ruby/detail/builtins.hpp>
#include <industry/languages/ruby/detail/wrap_retarded_ruby.hpp>
#include <boost/intrusive_ptr.hpp>
#include <boost/preprocessor.hpp>
#include <boost/ref.hpp>
#include <boost/tuple/tuple.hpp>
#include <memory>
#include <stdexcept>
#include <string>

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable: 4127 ) // conditional expression is constant -- the do {...} while(0) idiom used by Data_Wrap_Struct
#endif

namespace industry { namespace languages { namespace ruby {
	namespace detail {
		template<class T> struct class_registry;
		template<class T> struct instance_registry;
		template<class T> struct ruby_value;

		//// OWNERSHIP:  Does not transfer ////////////////////////////////////////////////////////////////////////////
		template<class T> struct ruby_value<T*> {
			static VALUE to(T* ptr) { return ptr ? instance_registry<T>::get_ruby_value(ptr) : Qnil; }
			static T* from(VALUE v) { if (v==Qnil) return 0; T* ptr; Data_Get_Struct(v, T, ptr); return ptr; }
		};
		template<class T> struct ruby_value<const T*> {
			static const T* from(VALUE v) { if (v==Qnil) return 0; const T* ptr; Data_Get_Struct(v, const T, ptr); return ptr; }
		};

		template<class T> struct ruby_value< boost::reference_wrapper<T> > {
			static VALUE to( const boost::reference_wrapper<T>& ref ) { return instance_registry<T>::get_ruby_value(ref.get_pointer()); }
		};

		//// OWNERSHIP:  Transfers (to Ruby) //////////////////////////////////////////////////////////////////////////
		template<class T> struct ruby_value< std::auto_ptr<T> > {
			static VALUE to(std::auto_ptr<T> ptr) { return ptr.get() ? instance_registry<T>::register_ruby_owned(ptr.release()) : Qnil; }
		};

		//// OWNERSHIP:  Shared (always) //////////////////////////////////////////////////////////////////////////////
		// (must implement the intrusive_ptr interface, of course)
		template<class T> struct ruby_value< boost::intrusive_ptr<T> > {
			static VALUE to(const boost::intrusive_ptr<T>& ptr ) { return ptr.get() ? instance_registry<T>::get_ruby_value(ptr.get()) : Qnil; }
			static boost::intrusive_ptr<T> from(VALUE v) { if (v==Qnil) return boost::intrusive_ptr<T>(); T* ptr; Data_Get_Struct(v,T,ptr); return ptr; }
		};

		template<class T> struct ruby_value< boost::intrusive_ptr<const T> > {
			static boost::intrusive_ptr<const T> from(VALUE v) { if (v==Qnil) return boost::intrusive_ptr<const T>(); const T* ptr; Data_Get_Struct(v,T,ptr); return ptr; }
		};

		//// OWNERSHIP:  Gives a copy to Ruby, but does not copy or transfer ownership to C++ /////////////////////////
		template <class T> struct ruby_value< const T > : ruby_value<T> {};
		template <class T> struct ruby_value< const T&> : ruby_value<const T> {
			// Uses ruby_value<const T>::to if available -- use boost::ref to pass to ruby by reference!
			static const T& from( VALUE v ) { const T* ptr; Data_Get_Struct(v,const T,ptr); return *ptr; }
		};
		template <class T> struct ruby_value<       T&> : ruby_value<T> {
			// Uses ruby_value<T>::to -- use boost::ref to pass to ruby by reference!
			static T& from( VALUE v ) { T* ptr; Data_Get_Struct(v,T,ptr); return *ptr; }
		};
		template<class T> struct ruby_value {
			static VALUE to(const T& ref) { return class_<T>::clone_type(ref); }
			static T from(VALUE v) { T* ptr; Data_Get_Struct(v, T, ptr); return *ptr; }
		};

		//// OWNERSHIP:  Gives a copy to the other language ///////////////////////////////////////////////////////////
		// (however, the ownership of inner types is dealt with with their own policies)
		template< typename L, typename R > struct ruby_value< std::pair<L,R> > {
			static VALUE to( const std::pair<L,R>& p ) {
				return rb_ary_new3( 2, ruby_value<L>::to(p.first), ruby_value<R>::to(p.second) );
			}
			static std::pair<L,R> from( VALUE v ) {
				if ( CLASS_OF(v) != rb_cArray || RARRAY(v)->len != 2 ) {
					throw std::runtime_error( "Expected an array of length 2" );
				}
				return std::pair<L,R>( ruby_value<L>::from(rb_ary_entry(v,0)), ruby_value<R>::from(rb_ary_entry(v,1)) );
			}
		};
		template< typename L, typename R > struct ruby_value< const std::pair<L,R> > : ruby_value< std::pair<L,R> > {};

#define TO_RUBY_VALUE(z,n,tuple) ruby_value<T##n>::to(tuple.template get<n>())
#define FROM_RUBY_VALUE(z,n,unused) ruby_value<T##n>::from(rb_ary_entry(v,n))
/*---------------------------------------------------------------------------------------------------------------------*/
#define BOOST_PP_LOCAL_MACRO(N)                                                                                \
		template < BOOST_PP_ENUM_PARAMS(N,typename T) > struct ruby_value< boost::tuple<BOOST_PP_ENUM_PARAMS(N,T)> > {  \
			typedef boost::tuple<BOOST_PP_ENUM_PARAMS(N,T)> tuple_type;                                                 \
			static VALUE to( const tuple_type& t ) { return rb_ary_new3(N,BOOST_PP_ENUM(N,TO_RUBY_VALUE,t)); }          \
			static tuple_type from( VALUE v ) {                                                                         \
				if ( CLASS_OF(v) != rb_cArray || RARRAY(v)->len != N ) {                                                \
					throw std::runtime_error( "Expected an array of length " #N );                                      \
				}                                                                                \
				return tuple_type(BOOST_PP_ENUM(N,FROM_RUBY_VALUE,~));                                                  \
			}                                                                                \
		};                                                                                \
		template < BOOST_PP_ENUM_PARAMS(N,typename T) >                                                                 \
		struct ruby_value< const boost::tuple<BOOST_PP_ENUM_PARAMS(N,T)>& >                                             \
			:  ruby_value< boost::tuple<BOOST_PP_ENUM_PARAMS(N,T)> > {};                                                \
/*---------------------------------------------------------------------------------------------------------------------*/
#define BOOST_PP_LOCAL_LIMITS (1,10)
#include BOOST_PP_LOCAL_ITERATE()
#undef TO_RUBY_VALUE
#undef FROM_RUBY_VALUE
#undef BOOST_PP_LOCAL_MACRO
	}
}}}

#ifdef _MSC_VER
#pragma warning( pop )
#endif

#endif//IG_INDUSTRY_LANGAUGES_RUBY_DETAIL_RUBY_VALUE

max_stars_repo_name: MaulingMonkey/libindustry

max_issues_repo_name: MaulingMonkey/libindustry

max_forks_repo_name: MaulingMonkey/libindustry


text:
/** \file gameengine/Expressions/InputParser.cpp
 *  \ingroup expressions
 */
// Parser.cpp: implementation of the CParser class.
/*
 * Copyright (c) 1996-2000 Erwin Coumans <coockie@acm.org>
 *
 * Permission to use, copy, modify, distribute and sell this software
 * and its documentation for any purpose is hereby granted without fee,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.  Erwin Coumans makes no
 * representations about the suitability of this software for any
 * purpose.  It is provided "as is" without express or implied warranty.
 *
 */

#include "EXP_InputParser.h"

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

#include "CM_Message.h"
#include "EXP_BoolValue.h"
#include "EXP_ConstExpr.h"
#include "EXP_EmptyValue.h"
#include "EXP_ErrorValue.h"
#include "EXP_FloatValue.h"
#include "EXP_IdentifierExpr.h"
#include "EXP_IntValue.h"
#include "EXP_Operator1Expr.h"
#include "EXP_Operator2Expr.h"
#include "EXP_StringValue.h"

// this is disable at the moment, I expected a memleak from it, but the error-cleanup was the
// reason well, looks we don't need it anyway, until maybe the Curved Surfaces are integrated into
// CSG cool things like (IF(LOD==1,CCurvedValue,IF(LOD==2,CCurvedValue2)) etc...
#include "EXP_IfExpr.h"

#if defined(WIN32) || defined(WIN64)
#  define strcasecmp _stricmp

#  ifndef strtoll
#    define strtoll _strtoi64
#  endif

#endif /* Def WIN32 or Def WIN64 */

#define NUM_PRIORITY 6

CParser::CParser() : m_identifierContext(nullptr)
{
}

CParser::~CParser()
{
  if (m_identifierContext) {
    m_identifierContext->Release();
  }
}

void CParser::ScanError(const std::string &str)
{
  /* Sets the global variable errmsg to an errormessage with
   * contents str, appending if it already exists.
   */
  if (errmsg) {
    errmsg = new COperator2Expr(VALUE_ADD_OPERATOR, errmsg, Error(str));
  }
  else {
    errmsg = Error(str);
  }

  sym = errorsym;
}

CExpression *CParser::Error(const std::string &str)
{
  // Makes and returns a new CConstExpr filled with an CErrorValue with string str.
  return new CConstExpr(new CErrorValue(str));
}

void CParser::NextCh()
{
  /* Sets the global variable ch to the next character, if it exists
   * and increases the global variable chcount
   */
  ++chcount;

  if (chcount < text.size()) {
    ch = text[chcount];
  }
  else {
    ch = 0x00;
  }
}

void CParser::TermChar(char c)
{
  /* Generates an error if the next char isn't the specified char c,
   * otherwise, skip the char.
   */
  if (ch == c) {
    NextCh();
  }
  else {
    CM_Warning(c << " expected. Continuing without it.");
  }
}

void CParser::DigRep()
{
  // Changes the current character to the first character that isn't a decimal.
  while ((ch >= '0') && (ch <= '9')) {
    NextCh();
  }
}

void CParser::CharRep()
{
  // Changes the current character to the first character that isn't an alphanumeric character.
  while (((ch >= '0') && (ch <= '9')) || ((ch >= 'a') && (ch <= 'z')) ||
         ((ch >= 'A') && (ch <= 'Z')) || (ch == '.') || (ch == '_')) {
    NextCh();
  }
}

void CParser::GrabString(int start)
{
  /* Puts part of the input string into the global variable
   * const_as_string, from position start, to position chchount.
   */
  const_as_string = text.substr(start, chcount - start);
}

void CParser::GrabRealString(int start)
{
  /* Works like GrabString but converting \\n to \n
   * puts part of the input string into the global variable
   * const_as_string, from position start, to position chchount.
   */

  const_as_string = std::string();
  for (int i = start; i < chcount; i++) {
    char tmpch = text[i];
    if ((tmpch == '\\') && (text[i + 1] == 'n')) {
      tmpch = '\n';
      i++;
    }
    const_as_string += tmpch;
  }
}

void CParser::NextSym()
{
  /* Sets the global variable sym to the next symbol, and
   * if it is an operator
   * sets the global variable opkind to the kind of operator
   * if it is a constant
   * sets the global variable constkind to the kind of operator
   * if it is a reference to a cell
   * sets the global variable cellcoord to the kind of operator
   */

  errmsg = nullptr;
  while (ch == ' ' || ch == 0x9) {
    NextCh();
  }

  switch (ch) {
    case '(': {
      sym = lbracksym;
      NextCh();
      break;
    }
    case ')': {
      sym = rbracksym;
      NextCh();
      break;
    }
    case ',': {
      sym = commasym;
      NextCh();
      break;
    }
    case '%': {
      sym = opsym;
      opkind = OPmodulus;
      NextCh();
      break;
    }
    case '+': {
      sym = opsym;
      opkind = OPplus;
      NextCh();
      break;
    }
    case '-': {
      sym = opsym;
      opkind = OPminus;
      NextCh();
      break;
    }
    case '*': {
      sym = opsym;
      opkind = OPtimes;
      NextCh();
      break;
    }
    case '/': {
      sym = opsym;
      opkind = OPdivide;
      NextCh();
      break;
    }
    case '&': {
      sym = opsym;
      opkind = OPand;
      NextCh();
      TermChar('&');
      break;
    }
    case '|': {
      sym = opsym;
      opkind = OPor;
      NextCh();
      TermChar('|');
      break;
    }
    case '=': {
      sym = opsym;
      opkind = OPequal;
      NextCh();
      TermChar('=');
      break;
    }
    case '!': {
      sym = opsym;
      NextCh();
      if (ch == '=') {
        opkind = OPunequal;
        NextCh();
      }
      else {
        opkind = OPnot;
      }
      break;
    }
    case '>': {
      sym = opsym;
      NextCh();
      if (ch == '=') {
        opkind = OPgreaterequal;
        NextCh();
      }
      else {
        opkind = OPgreater;
      }
      break;
    }
    case '<': {
      sym = opsym;
      NextCh();
      if (ch == '=') {
        opkind = OPlessequal;
        NextCh();
      }
      else {
        opkind = OPless;
      }
      break;
    }
    case '\"': {
      sym = constsym;
      constkind = stringtype;
      NextCh();
      int start = chcount;
      while ((ch != '\"') && (ch != 0x0)) {
        NextCh();
      }
      GrabRealString(start);
      TermChar('\"');  // check for eol before '\"'
      break;
    }
    case 0x0: {
      sym = eolsym;
      break;
    }
    default: {
      int start = chcount;
      DigRep();
      if ((start != chcount) || (ch == '.')) {  // number
        sym = constsym;
        if (ch == '.') {
          constkind = floattype;
          NextCh();
          DigRep();
        }
        else {
          constkind = inttype;
        }
        if ((ch == 'e') || (ch == 'E')) {
          constkind = floattype;
          NextCh();
          if ((ch == '+') || (ch == '-')) {
            NextCh();
          }
          int mark = chcount;
          DigRep();
          if (mark == chcount) {
            ScanError("Number expected after 'E'");
            return;
          }
        }
        GrabString(start);
      }
      else if (((ch >= 'a') && (ch <= 'z')) || ((ch >= 'A') && (ch <= 'Z'))) {
        start = chcount;
        CharRep();
        GrabString(start);
        if (boost::iequals(const_as_string, "SUM")) {
          sym = sumsym;
        }
        else if (boost::iequals(const_as_string, "NOT")) {
          sym = opsym;
          opkind = OPnot;
        }
        else if (boost::iequals(const_as_string, "AND")) {
          sym = opsym;
          opkind = OPand;
        }
        else if (boost::iequals(const_as_string, "OR")) {
          sym = opsym;
          opkind = OPor;
        }
        else if (boost::iequals(const_as_string, "IF")) {
          sym = ifsym;
        }
        else if (boost::iequals(const_as_string, "WHOMADE")) {
          sym = whocodedsym;
        }
        else if (boost::iequals(const_as_string, "FALSE")) {
          sym = constsym;
          constkind = booltype;
          boolvalue = false;
        }
        else if (boost::iequals(const_as_string, "TRUE")) {
          sym = constsym;
          constkind = booltype;
          boolvalue = true;
        }
        else {
          sym = idsym;
        }
      }
      else {
        std::string str = (boost::format("Unexpected character '%c'") % ch).str();
        NextCh();
        ScanError(str);
        return;
      }
    }
  }
}

const std::string CParser::Symbol2Str(int s)
{
  // Returns a string representation of of symbol s, for use in Term when generating an error.
  switch (s) {
    case errorsym: {
      return "error";
    }
    case lbracksym: {
      return "(";
    }
    case rbracksym: {
      return ")";
    }
    case commasym: {
      return ",";
    }
    case opsym: {
      return "operator";
    }
    case constsym: {
      return "constant";
    }
    case sumsym: {
      return "SUM";
    }
    case ifsym: {
      return "IF";
    }
    case whocodedsym: {
      return "WHOMADE";
    }
    case eolsym: {
      return "end of line";
    }
    case idsym: {
      return "identifier";
    }
  }
  return "unknown";  // should not happen
}

void CParser::Term(int s)
{
  /* Generates an error if the next symbol isn't the specified symbol s
   * otherwise, skip the symbol.
   */
  if (s == sym) {
    NextSym();
  }
  else {
    CM_Warning(Symbol2Str(s) << "expected. Continuing without it.");
  }
}

int CParser::Priority(int optorkind)
{
  // Returns the priority of an operator higher number means higher priority.
  switch (optorkind) {
    case OPor: {
      return 1;
    }
    case OPand: {
      return 2;
    }
    case OPgreater:
    case OPless:
    case OPgreaterequal:
    case OPlessequal:
    case OPequal:
    case OPunequal: {
      return 3;
    }
    case OPplus:
    case OPminus: {
      return 4;
    }
    case OPmodulus:
    case OPtimes:
    case OPdivide:
      return 5;
  }
  BLI_assert(false);
  return 0;  // should not happen
}

CExpression *CParser::Ex(int i)
{
  /* Parses an expression in the imput, starting at priority i, and
   * returns an CExpression, containing the parsed input.
   */
  CExpression *e1 = nullptr, *e2 = nullptr;

  if (i < NUM_PRIORITY) {
    e1 = Ex(i + 1);
    while ((sym == opsym) && (Priority(opkind) == i)) {
      int opkind2 = opkind;
      NextSym();
      e2 = Ex(i + 1);
      switch (opkind2) {
        case OPmodulus: {
          e1 = new COperator2Expr(VALUE_MOD_OPERATOR, e1, e2);
        } break;
        case OPplus: {
          e1 = new COperator2Expr(VALUE_ADD_OPERATOR, e1, e2);
        } break;
        case OPminus: {
          e1 = new COperator2Expr(VALUE_SUB_OPERATOR, e1, e2);
        } break;
        case OPtimes: {
          e1 = new COperator2Expr(VALUE_MUL_OPERATOR, e1, e2);
        } break;
        case OPdivide: {
          e1 = new COperator2Expr(VALUE_DIV_OPERATOR, e1, e2);
        } break;
        case OPand: {
          e1 = new COperator2Expr(VALUE_AND_OPERATOR, e1, e2);
        } break;
        case OPor: {
          e1 = new COperator2Expr(VALUE_OR_OPERATOR, e1, e2);
        } break;
        case OPequal: {
          e1 = new COperator2Expr(VALUE_EQL_OPERATOR, e1, e2);
        } break;
        case OPunequal: {
          e1 = new COperator2Expr(VALUE_NEQ_OPERATOR, e1, e2);
        } break;
        case OPgreater: {
          e1 = new COperator2Expr(VALUE_GRE_OPERATOR, e1, e2);
        } break;
        case OPless: {
          e1 = new COperator2Expr(VALUE_LES_OPERATOR, e1, e2);
        } break;
        case OPgreaterequal: {
          e1 = new COperator2Expr(VALUE_GEQ_OPERATOR, e1, e2);
        } break;
        case OPlessequal: {
          e1 = new COperator2Expr(VALUE_LEQ_OPERATOR, e1, e2);
        } break;
        default: {
          BLI_assert(false);
        } break;  // should not happen
      }
    }
  }
  else if (i == NUM_PRIORITY) {
    if ((sym == opsym) && ((opkind == OPminus) || (opkind == OPnot) || (opkind == OPplus))) {
      NextSym();
      switch (opkind) {
        /* +1 is also a valid number! */
        case OPplus: {
          e1 = new COperator1Expr(VALUE_POS_OPERATOR, Ex(NUM_PRIORITY));
        } break;
        case OPminus: {
          e1 = new COperator1Expr(VALUE_NEG_OPERATOR, Ex(NUM_PRIORITY));
        } break;
        case OPnot: {
          e1 = new COperator1Expr(VALUE_NOT_OPERATOR, Ex(NUM_PRIORITY));
        } break;
        default: {
          // should not happen
          e1 = Error("operator +, - or ! expected");
        }
      }
    }
    else {
      switch (sym) {
        case constsym: {
          switch (constkind) {
            case booltype: {
              e1 = new CConstExpr(new CBoolValue(boolvalue));
              break;
            }
            case inttype: {
              cInt temp;
              temp = std::stol(const_as_string, nullptr, 10); /* atoi is for int only */
              e1 = new CConstExpr(new CIntValue(temp));
              break;
            }
            case floattype: {
              double temp;
              temp = std::stof(const_as_string);
              e1 = new CConstExpr(new CFloatValue(temp));
              break;
            }
            case stringtype: {
              e1 = new CConstExpr(new CStringValue(const_as_string, ""));
              break;
            }
            default: {
              BLI_assert(false);
              break;
            }
          }
          NextSym();
          break;
        }
        case lbracksym: {
          NextSym();
          e1 = Ex(1);
          Term(rbracksym);
          break;
        }
        case ifsym: {
          CExpression *e3;
          NextSym();
          Term(lbracksym);
          e1 = Ex(1);
          Term(commasym);
          e2 = Ex(1);
          if (sym == commasym) {
            NextSym();
            e3 = Ex(1);
          }
          else {
            e3 = new CConstExpr(new CEmptyValue());
          }
          Term(rbracksym);
          e1 = new CIfExpr(e1, e2, e3);
          break;
        }
        case idsym: {
          e1 = new CIdentifierExpr(const_as_string, m_identifierContext);
          NextSym();

          break;
        }
        case errorsym: {
          BLI_assert(!e1);
          std::string errtext = "[no info]";
          if (errmsg) {
            CValue *errmsgval = errmsg->Calculate();
            errtext = errmsgval->GetText();
            errmsgval->Release();

            // e1 = Error(errmsg->Calculate()->GetText());//new CConstExpr(errmsg->Calculate());

            if (!(errmsg->Release())) {
              errmsg = nullptr;
            }
            else {
              // does this happen ?
              BLI_assert("does this happen");
            }
          }
          e1 = Error(errtext);

          break;
        }
        default:
          NextSym();
          // return Error("Expression expected");
          BLI_assert(!e1);
          e1 = Error("Expression expected");
      }
    }
  }
  return e1;
}

CExpression *CParser::Expr()
{
  // parses an expression in the imput, and
  // returns an CExpression, containing the parsed input
  return Ex(1);
}

CExpression *CParser::ProcessText(const std::string &intext)
{

  // and parses the string in intext and returns it.

  CExpression *expr;
  text = intext;

  chcount = 0;
  if (text.size() == 0) {
    return nullptr;
  }

  ch = text[0];
  /* if (ch != '=') {
   * expr = new CConstExpr(new CStringValue(text));
   * *dependent = deplist;
   * return expr;
   * } else
   */
  //	NextCh();
  NextSym();
  expr = Expr();
  if (sym != eolsym) {
    CExpression *oldexpr = expr;
    expr = new COperator2Expr(
        VALUE_ADD_OPERATOR,
        oldexpr,
        Error("Extra characters after expression"));  // new CConstExpr(new CErrorValue("Extra
                                                      // characters after expression")));
  }
  if (errmsg) {
    errmsg->Release();
  }

  return expr;
}

void CParser::SetContext(CValue *context)
{
  if (m_identifierContext) {
    m_identifierContext->Release();
  }
  m_identifierContext = context;
}

max_stars_repo_licenses: Naumen Condor-1.1 MS-PL

max_issues_repo_licenses: Naumen Condor-1.1 MS-PL

max_forks_repo_licenses: Naumen Condor-1.1 MS-PL


text:
//
//  Copyright Silvin Lubecki 2010
//
//  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 "Facade.h"
#include "depend/ModuleVisitor.h"
#include "depend/FileVisitor.h"
#include "depend/LineVisitor.h"
#include "depend/UncommentedLineVisitor.h"
#include "depend/IncludeVisitor.h"
#include "depend/ClassVisitor.h"
#include "depend/UnitDependency.h"
#include "depend/EdgeSerializer.h"
#include "depend/Log.h"
#include "depend/Finder.h"
#include "depend/ExternalModuleResolver.h"
#include "depend/InternalModuleResolver.h"
#include "depend/ProxyModuleResolver.h"
#include "depend/Filter_ABC.h"
#include "depend/UnitCache.h"
#include "depend/ClassSerializer.h"
#include "depend/GraphMLSerializer.h"
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <xeumeuleu/xml.hpp>
#include <iostream>

using namespace depend;

// -----------------------------------------------------------------------------
// Name: Facade constructor
// Created: SLI 2010-08-18
// -----------------------------------------------------------------------------
Facade::Facade( xml::xisubstream xis )
    : log_                   ( new Log( xis >> xml::start( "configuration" ) ) )
    , finder_                ( new Finder() )
    , externalResolver_      ( new ExternalModuleResolver( xis, *finder_, *log_ ) )
    , proxy_                 ( new ProxyModuleResolver( *externalResolver_ ) )
    , moduleVisitor_         ( new ModuleVisitor( *log_ ) )
    , unitCache_             ( new UnitCache( *moduleVisitor_ ) )
    , fileVisitor_           ( new FileVisitor( xis ) )
    , lineVisitor_           ( new LineVisitor() )
    , uncommentedLineVisitor_( new UncommentedLineVisitor( *lineVisitor_ ) )
    , includeVisitor_        ( new IncludeVisitor( *uncommentedLineVisitor_ ) )
    , classVisitor_          ( new ClassVisitor( *uncommentedLineVisitor_ ) )
    , internalResolver_      ( new InternalModuleResolver( xis, *finder_, *moduleVisitor_ ) )
    , dependencyMetric_      ( new UnitDependency( *moduleVisitor_, *fileVisitor_, *includeVisitor_, *proxy_, *internalResolver_, *log_ ) )
    , classSerializer_       ( new ClassSerializer( *moduleVisitor_, *classVisitor_ ) )
{
    // NOTHING
}

// -----------------------------------------------------------------------------
// Name: Facade::Process
// Created: SLI 2010-09-10
// -----------------------------------------------------------------------------
void Facade::Process( xml::xisubstream xis )
{
    xis >> xml::start( "configuration" )
            >> xml::start( "paths" )
                >> xml::list( "path", *this, &Facade::Visit )
            >> xml::end;
    Serialize( xis );
}

// -----------------------------------------------------------------------------
// Name: Facade destructor
// Created: SLI 2010-08-18
// -----------------------------------------------------------------------------
Facade::~Facade()
{
    // NOTHING
}

namespace
{
    class FileObserver : private Observer< FileObserver_ABC >
    {
    public:
        FileObserver( FileVisitor& fileVisitor, LineVisitor& lineVisitor )
            : Observer< FileObserver_ABC >( fileVisitor )
            , lineVisitor_( lineVisitor )
        {
            // NOTHING
        }
        virtual ~FileObserver()
        {
            // NOTHING
        }
    private:
        virtual void NotifyFile( const std::string& /*path*/, std::istream& stream, const std::string& context )
        {
            lineVisitor_.Visit( stream, context );
        }
    private:
        LineVisitor& lineVisitor_;
    };

    class ModuleObserver : private Observer< UnitObserver_ABC >
    {
    public:
        ModuleObserver( ModuleVisitor& unitVisitor, FileVisitor& fileVisitor, LineVisitor& lineVisitor, const std::string& path )
            : Observer< UnitObserver_ABC >( unitVisitor )
            , fileVisitor_( fileVisitor )
            , lineVisitor_( lineVisitor )
            , path_       ( path )
        {
             // NOTHING
        }
        virtual ~ModuleObserver()
        {
            // NOTHING
        }
    private:
        virtual void NotifyUnit( const std::string& unit, const std::string& context )
        {
            FileObserver observer( fileVisitor_, lineVisitor_ );
            fileVisitor_.Visit( path_ + "/" + unit, context );
        }
    private:
        FileVisitor& fileVisitor_;
        LineVisitor& lineVisitor_;
        const std::string path_;
    };
}

// -----------------------------------------------------------------------------
// Name: Facade::Visit
// Created: SLI 2010-08-18
// -----------------------------------------------------------------------------
void Facade::Visit( xml::xistream& xis )
{
    const std::string path = xis.value< std::string >();
    ModuleObserver observer( *moduleVisitor_, *fileVisitor_, *lineVisitor_, path );
    moduleVisitor_->Visit( path, path );
}

namespace
{
    void Noop() {}
    class SimpleFilter : public Filter_ABC
    {
    public:
        virtual bool Check( const std::string& /*module*/ ) const
        {
            return true;
        }
        virtual bool CheckCore( const std::string& /*module*/ ) const
        {
            return true;
        }
    };
}

// -----------------------------------------------------------------------------
// Name: Facade::Serialize
// Created: SLI 2010-09-03
// -----------------------------------------------------------------------------
void Facade::Serialize( xml::xistream& xis )
{
    const std::string output = xis.content< std::string >( "output" );
    boost::shared_ptr< std::ostream > out( &std::cout, boost::bind( &Noop ) );
    if( !output.empty() )
        out.reset( new std::ofstream( output.c_str() ) );
    xml::xostringstream xos;
    if( xis.content< bool >( "graphml" ) )
        GraphMLSerializer( *dependencyMetric_, *unitCache_ ).Serialize( xos );
    else
    {
        xos << xml::start( "graph" );
        EdgeSerializer( *dependencyMetric_, *unitCache_ ).Serialize( xos, SimpleFilter() );
        classSerializer_->Serialize( xos );
        xos << xml::end;
    }
    *out << xos.str();
}

max_stars_repo_name: vinsle/dependency-analysis

max_issues_repo_name: vinsle/dependency-analysis

max_forks_repo_name: vinsle/dependency-analysis


text:
#pragma once

#define MAX_QUAD_POINTS -1

#include <Eigen/Dense>
#include <Eigen/Sparse>

namespace polyfem
{
	// Stack-allocated vectors of size either 2 or 3
	typedef Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> VectorNd;
	typedef Eigen::Matrix<double, 1, Eigen::Dynamic, Eigen::RowMajor, 1, 3> RowVectorNd;
	typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor, 3, 3> MatrixNd;

	typedef Eigen::Matrix<double, Eigen::Dynamic, 1, 0, MAX_QUAD_POINTS, 1> QuadratureVector;

#ifdef POLYSOLVE_LARGE_INDEX
	typedef Eigen::SparseMatrix<double, Eigen::ColMajor, std::ptrdiff_t> StiffnessMatrix;
#else
	typedef Eigen::SparseMatrix<double, Eigen::ColMajor> StiffnessMatrix;
#endif
} // namespace polyfem

max_stars_repo_name: danielepanozzo/polyfem

max_issues_repo_name: danielepanozzo/polyfem

max_forks_repo_name: danielepanozzo/polyfem


text:
//
//  Created by Robert Binna
//

#include <boost/test/unit_test.hpp>
#include <idx/contenthelpers/ContentEquals.hpp>

namespace idx { namespace contenthelpers {

BOOST_AUTO_TEST_SUITE(ContentEqualsTest)

BOOST_AUTO_TEST_CASE(testEqualityCheckString) {
	BOOST_REQUIRE(contenthelpers::contentEquals("A", "B") == false);
	BOOST_REQUIRE(contenthelpers::contentEquals("B", "A") == false);
	BOOST_REQUIRE(contenthelpers::contentEquals("A", "A") == true);
}

BOOST_AUTO_TEST_CASE(testEqualityCheckPointer) {
	void* pointer1 = reinterpret_cast<void*>(1ul);
	void* sameAddressAsPointer1 = reinterpret_cast<void*>(1ul);
	void* pointer2 = reinterpret_cast<void*>(2ul);

	BOOST_REQUIRE(contenthelpers::contentEquals(pointer1, sameAddressAsPointer1) == true);
	BOOST_REQUIRE(contenthelpers::contentEquals(pointer1, pointer2) == false);
	BOOST_REQUIRE(contenthelpers::contentEquals(sameAddressAsPointer1, pointer2) == false);
}

BOOST_AUTO_TEST_SUITE_END()

}}

max_stars_repo_name: yishayahu/hot

max_issues_repo_name: SheldonZhong/hot

max_forks_repo_name: SheldonZhong/hot


text:
#include "svg_document.h"

#include <boost/format.hpp>
#include <boost/log/trivial.hpp>
#include <boost/property_tree/xml_parser.hpp>

SvgDocument::SvgDocument() {
    tree_.put("svg.<xmlattr>.xmlns", "http://www.w3.org/2000/svg");
    tree_.put("svg.<xmlattr>.xmlns:xlink", "http://www.w3.org/1999/xlink");
    tree_.put("svg.<xmlattr>.stroke", "black");
}

void SvgDocument::SetSize(long double width, long double height) {
    tree_.put("svg.<xmlattr>.width", width);
    tree_.put("svg.<xmlattr>.height", height);
}

void SvgDocument::AddLine(long double x1, long double y1, long double x2, long double y2) {
    boost::property_tree::ptree node;
    node.put("<xmlattr>.x1", FormatValue(x1));
    node.put("<xmlattr>.y1", FormatValue(y1));
    node.put("<xmlattr>.x2", FormatValue(x2));
    node.put("<xmlattr>.y2", FormatValue(y2));
    tree_.add_child("svg.line", node);
}

void SvgDocument::BuildAndWriteToDisk(const std::string& filename) {
    try {
        boost::property_tree::write_xml(filename, tree_);
    } catch (std::exception& e) {
        BOOST_LOG_TRIVIAL(error) << "Caught exception when building SVG document " << filename
                                 << ": " << e.what();
        throw;
    }
}

std::string SvgDocument::FormatValue(long double v) { return std::to_string(v); }


text:
#include <boost/program_options.hpp>
#include <boost/process.hpp>

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

namespace po = boost::program_options;
namespace bp = boost::process;

struct Parameters
{
    bool PrintHelp = false;
    int Timeout = -1; // unlimited
    int Count = 1;
    bool SkipFirst = true;
    std::string StdOut; // empty redirect to null
    std::string Executable;
    std::vector<std::string> Params;
};

class ArgumentParser
{
public:
    ArgumentParser()
        : desc_("Allowed options")
    {
        desc_.add_options()
            ("help,H", "produce help message")
            ("timeout", po::value<int>()->default_value(-1), "set process timeout")
            ("count,C", po::value<int>()->default_value(1), "number of samples (process runs)")
            ("drop-first", po::value<bool>()->default_value(true), "if multiples samples are collected, skip first run")
            ("stdout", po::value<std::string>()->default_value(""), "redirect stdout to specified file");

        p_.add("executable", 1);
        p_.add("parameters", -1);
    }

    Parameters Parse(int argc, char** argv) const
    {
        po::variables_map vm;

        std::vector<std::string> params;

        po::options_description hidden;
        hidden.add_options()
            ("executable", po::value<std::string>())
            ("parameters", po::value(&params));

        po::options_description cmdline_options;
        cmdline_options.add(desc_).add(hidden);

        po::store(po::command_line_parser(argc, argv).
            options(cmdline_options).positional(p_).run(), vm);
        po::notify(vm);

        if (vm.count("help") != 0)
            return Parameters{ true };

        if (vm.count("executable") == 0)
            throw std::runtime_error("Path to executable is required.");

        return Parameters{
            false, // help
            vm["timeout"].as<int>(),
            vm["count"].as<int>(),
            vm["drop-first"].as<bool>(),
            vm["stdout"].as<std::string>(),
            vm["executable"].as<std::string>(),
            params,
        };
    }

private:
    po::options_description desc_;
    po::positional_options_description p_;

    friend std::ostream& operator<<(std::ostream& lhs, const ArgumentParser& rhs);
};

std::ostream& operator<<(std::ostream& lhs, const ArgumentParser& rhs)
{
    lhs << "Usage: TimeThis [options] executable param1 ... paramN\n";
    lhs << rhs.desc_;
    return lhs;
}

int main(int argc, char** argv)
{
    ArgumentParser ap;
    try
    {
        Parameters params = ap.Parse(argc, argv);

        if (params.PrintHelp)
        {
            std::cout << ap;
            return 0;
        }

        std::chrono::milliseconds total(0);
        int runs = 0;

        for (int i = 0; i < params.Count; ++i)
        {
            auto start = std::chrono::high_resolution_clock::now();

            bp::child process = [&]() {
                if (params.StdOut.empty())
                    return bp::child(params.Executable, bp::args(params.Params), bp::std_out > bp::null, bp::std_err > bp::null);
                else
                    return bp::child(params.Executable, bp::args(params.Params), bp::std_out > params.StdOut, bp::std_err > bp::null);
            }();

            if (params.Timeout < 0)
            {
                process.wait(); // infinite wait
            }
            else
            {
                auto timeout = std::chrono::seconds(params.Timeout);
                if (!process.wait_for(timeout))
                {
                    process.terminate();
                    std::cout << "Run #" << i + 1 << " timeout!\n";
                    return 0;

                }
            }

            auto duration = std::chrono::high_resolution_clock::now() - start;
            auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
            std::cout << "Run #" << i + 1 << " took " << ms.count() << "ms\n";

            if (params.Count > 1 && i == 0 && params.SkipFirst)
                continue; // skip first run

            ++runs;
            total += ms;
        }

        std::cout << "\nTotal (" << runs << " runs) " << total.count() / static_cast<double>(runs) << "ms\n";
    }
    catch (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
        std::cout << ap;
        return 1;
    }
}

max_stars_repo_name: koscelansky/TimeThis

max_issues_repo_name: koscelansky/TimeThis

max_forks_repo_name: koscelansky/TimeThis


text:
#include "tags.h"
#include "clock.h"

#include <0mq/message.h>
#include <0mq/context.h>
#include <0mq/socket.h>
#include <0mq/poller.h>

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>

#include <chrono>
#include <cstddef>
#include <list>
#include <memory>
#include <unordered_map>
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <sstream>
#include <thread>

namespace zmqmap {

typedef std::chrono::time_point<steadyclock_type> timepoint_type;

typedef zmq::Message identity_type;
typedef zmq::Message jobid_type;
typedef zmq::Message call_type;

class IdentityHash {
public:
    size_t operator() (const identity_type& identity) const;
};

size_t IdentityHash::operator() (const identity_type& identity) const {
  std::size_t h = 0;
  const char* d = identity.data();
  for (std::size_t i = 0; i < identity.size(); ++i) {
    h = (h << 1) ^ (std::hash<char>()(d[i]));
  }

  return h;
}

class Worker {
  public:
    Worker(const identity_type& identity)
      : heartbeatInterval_(1000 * 3), identity_(identity)
    {
    }

    void update(const timepoint_type& timePoint) {
      latestHeartBeat_ = timePoint +
        std::chrono::milliseconds(heartbeatInterval_);
    }

    bool isVanished(const timepoint_type& timePoint) const {
      return timePoint > latestHeartBeat_;
    }

    const identity_type& getIdentity() const {
      return identity_;
    }

  private:
    const std::size_t heartbeatInterval_;

    const identity_type identity_;
    timepoint_type latestHeartBeat_;
};

class Signal {
  public:
    Signal()
      : doWork_(true), thread_()
    {
    }

    ~Signal() {
      doWork_ = false;

      thread_->join();
    }

    void init(const std::string& bindStr, zmq::Context& context);

  private:
    void go(const std::string& bindStr, zmq::Context& context);

    // do not copy
    Signal(const Signal&);

    bool doWork_;
    std::unique_ptr<std::thread> thread_;
};

void Signal::init(const std::string& bindStr, zmq::Context& context) {
  // create a thread that waits on the job socket for work
  thread_ = std::unique_ptr<std::thread>(new
      std::thread(std::bind(&Signal::go, this, bindStr, context)));
}

void Signal::go(const std::string& bindStr, zmq::Context& context) {
  zmq::Socket signalSocket = context.createSocket(ZMQ_PAIR);
  signalSocket.connect(bindStr.c_str());

  zmq::Socket::messages_type signal {zmq::Message()};
  while (doWork_ && std::cin.good()) {
    std::cin.get();

    signalSocket.send(signal);
  }
}

class BrokerApplication {
  private:
    typedef std::unordered_map<identity_type, Worker, IdentityHash> workermap_type;

  public:
    BrokerApplication(const std::size_t cacheQueueLength)
    : heartbeatInterval_(1000), cacheQueueLength_(cacheQueueLength),
      context_(), frontendSocket_(), backendSocket_(),
      cacheQueue_(), idleWorkers_(), busyWorkers_()
    {
    }

    void init(const std::string& frontend, const std::string& backend);

    void go();

  private:
    void printStats() const {
      std::cout << "idle: " << std::setw(3) << idleWorkers_.size()
        << ", busy: " << std::setw(3) << busyWorkers_.size() << ", cache: "
        << std::setw(3) << cacheQueue_.size() << std::endl;
    }

    void handleBackend();

    void sendJobQueued();

    void handleFrontend();

    void sendJobTag(const identity_type& client, const int tag, const
        jobid_type& jobID, const call_type& call);

    void assignJobs();

    void sendKill(const workermap_type& workers) {
      broadcastTag(workers, QUEUE_KILL_TAG);
    }

    void sendHeartBeat(const workermap_type& workers) {
      broadcastTag(workers, QUEUE_HEARTBEAT_TAG);
    }

    void checkWorkers(workermap_type& workers) const;

    void broadcastTag(const workermap_type& workers, const int tag);

    void updateWorkers(workermap_type& workers, const identity_type& identity)
      const;

    void connect(const std::string& frontend, const std::string& backend);

    // do not copy
    BrokerApplication(const BrokerApplication&);

    const std::size_t heartbeatInterval_;
    const std::size_t cacheQueueLength_;

    zmq::Context context_;
    zmq::Socket frontendSocket_;
    zmq::Socket backendSocket_;
    zmq::Socket signalSocket_;

    std::list<zmq::Socket::messages_type> cacheQueue_;
    workermap_type idleWorkers_;
    workermap_type busyWorkers_;

    Signal signal_;
};

void BrokerApplication::checkWorkers(workermap_type& workers) const {
  timepoint_type now = steadyclock_type::now();

  workermap_type::iterator workerIt = workers.begin();
  while (workerIt != workers.end()) {
    if (workerIt->second.isVanished(now)) {
      std::cout << "delete" << std::endl;
      workerIt = workers.erase(workerIt);
    } else {
      ++workerIt;
    }
  }
}

void BrokerApplication::broadcastTag(const workermap_type& workers, const int
    tag) {
  zmq::Message tagMsg(1);
  tagMsg.data()[0] = tag;

  for (const auto& worker : workers) {
    zmq::Socket::messages_type msgs;
    msgs.push_back(worker.second.getIdentity());
    msgs.push_back(tagMsg);

    backendSocket_.send(msgs);
  }
}

void BrokerApplication::updateWorkers(workermap_type& workers, const
    identity_type& identity) const {
  workermap_type::iterator it = workers.find(identity);

  if (it == workers.end()) {
    it = workers.insert(std::make_pair(identity, Worker(identity))).first;
  }

  timepoint_type now = steadyclock_type::now();
  it->second.update(now);
}

void BrokerApplication::connect(const std::string& frontend, const std::string&
    backend) {
  frontendSocket_ = context_.createSocket(ZMQ_ROUTER);
  backendSocket_ = context_.createSocket(ZMQ_ROUTER);
  frontendSocket_.bind(frontend);
  backendSocket_.bind(backend);
}

void BrokerApplication::sendJobQueued() {
  for (const auto& job : cacheQueue_) {
    zmq::Socket::messages_type::const_iterator messagePtr =
      job.begin();
    const zmq::Message& client = *messagePtr++;
    const zmq::Message& jobID = *messagePtr++;
    const zmq::Message& call = *messagePtr++;

    sendJobTag(client, JOB_QUEUED, jobID, call);
  }
}

void BrokerApplication::handleFrontend() {
  zmq::Socket::messages_type messages = frontendSocket_.receive();

  // check if we got Interrupted
  if (messages.empty()) {
    throw std::runtime_error("BrokerApplication::go: got interrupted");
  }

  if (cacheQueue_.size() < cacheQueueLength_) {
    cacheQueue_.push_back(messages);
  } else {
    // send wait and drop job
    zmq::Socket::messages_type::iterator messagePtr =
      messages.begin();
    const zmq::Message& client = *messagePtr++;
    const zmq::Message& jobID = *messagePtr++;
    const zmq::Message& call = *messagePtr++;

    sendJobTag(client, JOB_WAIT, jobID, call);
  }
}

void BrokerApplication::sendJobTag(const identity_type& client, const int tag,
    const jobid_type& jobID, const call_type& call) {
  zmq::Socket::messages_type reply;
  reply.push_back(client);

  zmq::Message jobReplyTag(1);
  jobReplyTag.data()[0] = tag;
  reply.push_back(std::move(jobReplyTag));
  reply.push_back(jobID);
  reply.push_back(call);

  frontendSocket_.send(reply);
}

void BrokerApplication::assignJobs() {
  auto jobIt = cacheQueue_.begin();
  auto workerIt = idleWorkers_.begin();

  while (workerIt != idleWorkers_.end() && jobIt != cacheQueue_.end()) {
    zmq::Socket::messages_type assigment;
    assigment.push_back(workerIt->second.getIdentity());

    zmq::Message queueTag(1);
    queueTag.data()[0] = QUEUE_JOB_TAG;
    assigment.push_back(std::move(queueTag));

    assigment.splice(assigment.end(), *jobIt);

    backendSocket_.send(assigment);

    // remove worker
    updateWorkers(busyWorkers_, workerIt->first);
    workerIt = idleWorkers_.erase(workerIt);
    jobIt = cacheQueue_.erase(jobIt);
  }
}

void BrokerApplication::handleBackend() {
  zmq::Socket::messages_type messages = backendSocket_.receive();
  // check if we got Interrupted
  const std::size_t messageCount = messages.size();

  if (messageCount < 2) {
    throw std::runtime_error("BrokerApplication::go: receive invalid "
        "message");
  }

  zmq::Socket::messages_type::iterator messagePtr =
    messages.begin();
  const zmq::Message& identity = *messagePtr++;
  const zmq::Message& tag = *messagePtr++;

  if (tag.size() != 1) {
    throw std::runtime_error("BrokerApplication::go: invalid tag size");
  }

  zmq::Socket::messages_type messagesTail;
  messagesTail.splice(messagesTail.begin(), messages, messagePtr,
      messages.end());

  switch (tag.data()[0]) {
    case WORKER_HEARTBEAT_TAG:
      // this worker is idle again; in case it was busy, remove it from
      // the busy queue
      busyWorkers_.erase(identity);

      updateWorkers(idleWorkers_, identity);
      break;
    case WORKER_UPDATE_TAG:
      // worker busy messages are directly forwarded to the clients,
      // they have to take care if a worker dies
      updateWorkers(busyWorkers_, identity);
      frontendSocket_.send(messagesTail);
      break;
    default:
      throw std::runtime_error("BrokerApplication::go: invalid tag:");
      break;
  }
}

void BrokerApplication::go() {
  //  Send out heartbeats at regular intervals
  timepoint_type nextHeartBeat;
  nextHeartBeat = steadyclock_type::now() +
    std::chrono::milliseconds(heartbeatInterval_);

  while (true) {
    std::vector<zmq::Socket> items = { backendSocket_, frontendSocket_,
      signalSocket_ };

    std::vector<short> state = zmq::poll(items, heartbeatInterval_);

    // handle backend
    if (state[0] & ZMQ_POLLIN) {
      handleBackend();
    }

    // handle frontend
    if (state[1] & ZMQ_POLLIN) {
      handleFrontend();
    }

    if (state[2] & ZMQ_POLLIN) {
      sendKill(idleWorkers_);
      sendKill(busyWorkers_);

      signalSocket_.receive();
      //zmq::Socket::messages_type signal { zmq::Message() };
      //signalSocket_.send(signal);
    }

    checkWorkers(idleWorkers_);
    checkWorkers(busyWorkers_);

    assignJobs();

    timepoint_type now = steadyclock_type::now();
    if (now > nextHeartBeat) {
      sendHeartBeat(idleWorkers_);
      sendHeartBeat(busyWorkers_);

      sendJobQueued();

      nextHeartBeat = now +
        std::chrono::milliseconds(heartbeatInterval_);

      printStats();
    }
  }
}

void BrokerApplication::init(const std::string& frontend, const std::string&
    backend) {
  boost::uuids::uuid uuid;

  std::ostringstream bindStr;
  bindStr << "inproc://signal_" << uuid;

  signalSocket_ = context_.createSocket(ZMQ_PAIR);
  signalSocket_.bind(bindStr.str().c_str());
  signal_.init(bindStr.str(), context_);

  connect(frontend, backend);
}

}

int main(int argc, const char** argv) {
  if (argc < 4) {
    std::cerr << "Usage: " << argv[0] << " <queue-length> <frontend> <backend>" << std::endl
      << "e.g. " << argv[0] << " 100 'tcp://*:5555' 'tcp://*:5556'" << std::endl;

    return 1;
  }

  std::size_t queueLength;
  std::istringstream(argv[1]) >> queueLength;

  zmqmap::BrokerApplication app(queueLength);
  app.init(argv[2], argv[3]);

  app.go();

  return 0;
}

ext: cc


text:
// __BEGIN_LICENSE__
//  Copyright (c) 2006-2012, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NASA Vision Workbench is 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.
// __END_LICENSE__

#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif

#include <cstdlib>
#include <iostream>
#include <cmath>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;

#include <vw/Core/Functors.h>
#include <vw/Image/Algorithms.h>
#include <vw/Image/ImageMath.h>
#include <vw/Image/ImageViewRef.h>
#include <vw/Image/PerPixelViews.h>
#include <vw/Image/PixelMask.h>
#include <vw/Image/MaskViews.h>
#include <vw/Image/PixelTypes.h>
#include <vw/Image/Statistics.h>
#include <vw/FileIO/DiskImageView.h>
#include <vw/Cartography/GeoReference.h>
#include <vw/tools/Common.h>
#include <vw/FileIO/DiskImageResourceGDAL.h>
#include <vw/Image/Interpolation.h>
#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>

using namespace vw;
using namespace vw::cartography;
using namespace std;

struct Options : asp::BaseOptions {};

/// Find the mean and std dev DEM of the given input sets of DEMs.
/// Also output count.tif, showing for each pixel how many times
/// it was encountered in the stack of DEMs.

int main( int argc, char *argv[] ){

  try {
    ImageView<double> mean_dem, std_dev_dem, count_dem;
    GeoReference georef;
    double nodata_val = numeric_limits<double>::quiet_NaN();

    if (argc <= 1){
      vw_throw(ArgumentErr() << "Missing input files.\n"
               << "Usage: " << argv[0] << " <dems>\n");
    }

    int start = 1;
    for (int i = start; i < argc; i++){
      std::string curr_file = argv[i];
      std::cout << "Reading: " << curr_file << std::endl;

      DiskImageResourceGDAL in_rsrc(curr_file);
      double curr_nodata_val = numeric_limits<double>::quiet_NaN();
      if ( in_rsrc.has_nodata_read() ) {
        curr_nodata_val = in_rsrc.nodata_read();
        vw_out() << "\tFound input nodata value: " << curr_nodata_val << std::endl;
      }else{
        vw_out() << "Nodata value not found in: " << curr_file << std::endl;
      }

      GeoReference curr_georef;
      read_georeference(curr_georef, in_rsrc);

      DiskImageView<float> curr_dem(in_rsrc);
      ImageViewRef< PixelMask<float> > masked_dem = create_mask(curr_dem, curr_nodata_val);

      InterpolationView<EdgeExtensionView< ImageViewRef < PixelMask<float> >, ConstantEdgeExtension>, BilinearInterpolation> masked_dem_interp = interpolate(masked_dem);

      if (i == start){
        mean_dem.set_size    ( curr_dem.cols(), curr_dem.rows() );
        std_dev_dem.set_size ( curr_dem.cols(), curr_dem.rows() );
        count_dem.set_size   ( curr_dem.cols(), curr_dem.rows() );
        georef = curr_georef;
        nodata_val = curr_nodata_val;
      }

      for (int col = 0; col < mean_dem.cols(); col++){
        for (int row = 0; row < mean_dem.rows(); row++){
          Vector2 pix(col, row);

          if (i != start){
            pix = curr_georef.lonlat_to_pixel(georef.pixel_to_lonlat(pix));
          }

          double x = pix[0], y = pix[1];
          double interp_val;
          bool is_in_box = ( 0 <= x && x <= masked_dem_interp.cols() - 1 &&
                             0 <= y && y <= masked_dem_interp.rows() - 1 );
          if (!is_in_box) continue;

          // The "if" statement below is to work around a bug in
          // interpolation with PixelMask.
          PixelMask<float> val;
          if (x == col && y == row)
            val = masked_dem(col, row);
          else
            val = masked_dem_interp(x, y);
          if (!is_valid(val)) continue;
          interp_val = val.child();

          mean_dem    (col, row) += interp_val;
          std_dev_dem (col, row) += interp_val*interp_val;
          count_dem   (col, row) += 1;
        }

      }
    }

    for (int col = 0; col < mean_dem.cols(); col++){
      for (int row = 0; row < mean_dem.rows(); row++){

        if (count_dem (col, row) == 0){
          mean_dem    (col, row) = nodata_val;
          std_dev_dem (col, row) = nodata_val;
          count_dem   (col, row) = nodata_val;
          continue;
        }

        double mean    = mean_dem(col, row)/count_dem(col, row);
        double std_dev = sqrt( std_dev_dem(col, row)/count_dem(col, row) - mean*mean );

        mean_dem    (col, row) = mean;
        std_dev_dem (col, row) = std_dev;
      }
    }

    Options opt;
    std::string mean_file = "mean.tif";
    std::cout << "Writing: " << mean_file << std::endl;
    asp::block_write_gdal_image(mean_file, pixel_cast<float>(mean_dem),
                                georef, nodata_val, opt);

    std::string std_dev_file = "std_dev.tif";
    std::cout << "Writing: " << std_dev_file << std::endl;
    asp::block_write_gdal_image(std_dev_file, pixel_cast<float>(std_dev_dem),
                                georef, nodata_val, opt);

    std::string count_file = "count.tif";
    std::cout << "Writing: " << count_file << std::endl;
    asp::block_write_gdal_image(count_file, pixel_cast<float>(count_dem),
                                georef, nodata_val, opt);

  } ASP_STANDARD_CATCHES;

  return 0;
}

max_stars_repo_name: NeoGeographyToolkit/Tools

max_issues_repo_name: NeoGeographyToolkit/Tools

max_forks_repo_name: NeoGeographyToolkit/Tools


text: #include <boost/mpl/begin_end_fwd.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


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

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

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

#include <boost/dispatch/function/overload.hpp>
#include <boost/config.hpp>
#include <boost/simd/constant/one.hpp>
#include <boost/simd/constant/pio2_1.hpp>
#include <boost/simd/constant/pio2_2.hpp>
#include <boost/simd/constant/pio2_3.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/simd/function/simd/multiplies.hpp>
#include <boost/simd/function/simd/minus.hpp>

namespace boost { namespace simd { namespace ext
{
  namespace bd = boost::dispatch;
  namespace bs = boost::simd;
  BOOST_DISPATCH_OVERLOAD (rem_pio2_straight_
                          , (typename A0, typename A1)
                          , bd::cpu_
                          , bd::generic_ < bd::floating_<A0> >
                          , bd::generic_ < bd::integer_<A1>  >
                          , bd::generic_ < bd::floating_<A0> >
                          )
  {
    BOOST_FORCEINLINE void operator() ( A0 const& x, A1 & n, A0 & xr) BOOST_NOEXCEPT
    {
      n = bs::rem_pio2_straight(x, xr);
    }
  };

  BOOST_DISPATCH_OVERLOAD (rem_pio2_straight_
                          , (typename A0)
                          , bd::cpu_
                          , bd::generic_ < bd::floating_<A0> >
                          )
  {
    using int_t = bd::as_integer_t<A0>;
    using result_t = std::pair<int_t, A0>;
    BOOST_FORCEINLINE result_t operator() ( A0 const& a0) const BOOST_NOEXCEPT
    {
      A0 second;
      int_t const first = rem_pio2_straight(a0,second);
      return {first, second};
    }
  };

  BOOST_DISPATCH_OVERLOAD (rem_pio2_straight_
                          , (typename A0)
                          , bd::cpu_
                          , bd::generic_< bd::floating_<A0> >
                          , bd::generic_< bd::floating_<A0> >
                          )
  {
    using int_t = bd::as_integer_t<A0>;
    BOOST_FORCEINLINE int_t operator() ( A0 const& x, A0 & xr) const BOOST_NOEXCEPT
    {
      xr = x-Pio2_1<A0>();
      xr = xr-Pio2_2<A0>();
      xr = xr-Pio2_3<A0>();
//       xr -= Pio2_2<A0>(); TODO
//       xr -= Pio2_3<A0>();
      return One<int_t>();
    }
  };
} } }

#endif


text:
/** $Id: Track.cxx 177772 2019-12-09 09:36:06Z jvansanten $
 * @file
 * @author Jakob van Santen <vansanten@wisc.edu>
 *
 * $Revision: 177772 $
 * $Date: 2019-12-09 02:36:06 -0700 (Mon, 09 Dec 2019) $
 */

#include <MuonGun/Track.h>
#include <simclasses/I3MMCTrack.h>

#include <boost/foreach.hpp>

namespace I3MuonGun {

Track::Track(const I3MMCTrack &mmctrack,
    const I3MCTree::sibling_const_iterator &sbegin,
    const I3MCTree::sibling_const_iterator &send) : I3Particle(mmctrack.GetI3Particle())
{
	// In the beginning, the particle is at its vertex with the given energy
	checkpoints_.push_back(Checkpoint(0., I3Particle::GetEnergy(), 0u));
	losses_.push_back(LossSum(checkpoints_.back().length, 0.));
	if (mmctrack.GetEi() > 0) {
		// Track started outside the MMC volume; we get an extra
		// measurement point (but no stochastics)
		double d = (I3Position(mmctrack.GetXi(), mmctrack.GetYi(),
		    mmctrack.GetZi())-I3Particle::GetPos()).Magnitude();
		checkpoints_.push_back(Checkpoint(d, mmctrack.GetEi(), losses_.size()));
	}

	// Sum energy losses between entry and exit
	double elost = 0;
	BOOST_FOREACH(const I3Particle &p, std::make_pair(sbegin, send)) {
		if (p.GetType() == mmctrack.GetI3Particle().GetType()) {
			continue;
		}
		elost += p.GetEnergy();
		double d = (p.GetPos()-I3Particle::GetPos()).Magnitude();
		losses_.push_back(LossSum(d, elost));
	}

	if (mmctrack.GetEf() > 0) {
		// Track made it to the edge of the MMC volume
		double d = (I3Position(mmctrack.GetXf(), mmctrack.GetYf(),
		    mmctrack.GetZf())-I3Particle::GetPos()).Magnitude();
		checkpoints_.push_back(Checkpoint(d, mmctrack.GetEf(), losses_.size()));
		losses_.push_back(LossSum(checkpoints_.back().length, 0.));
	}

	checkpoints_.push_back(Checkpoint(I3Particle::GetLength(), 0., losses_.size()));
	losses_.push_back(LossSum(I3Particle::GetLength(), 0.));
}

namespace {

template <typename T>
inline bool Sort(const T &a, const T &b)
{
	return a.length < b.length;
}

}

double
Track::GetEnergy(double length) const
{
	if (!std::isfinite(length) || length >= GetLength())
		return 0.;
	else if (length <= 0)
		return GetEnergy();
	// Find an energy checkpoint. The above if() guarantees that
	// that both cp and cp+1 are valid.
	std::vector<Checkpoint>::const_iterator cp =
	    std::max(std::lower_bound(checkpoints_.begin(), checkpoints_.end(),
	    Checkpoint(length), Sort<Checkpoint>)-1, checkpoints_.begin());
	// Store iterators the mark the records of stochastic losses
	// between the checkpoints
	std::vector<LossSum>::const_iterator l1(losses_.begin()+(cp->offset > 0 ? cp->offset-1 : 0)),
	    l2(losses_.begin()+(cp+1)->offset);
	// Find the cumulative energy loss since the last checkpoint
	std::vector<LossSum>::const_iterator ls = std::max(std::lower_bound(l1, l2,
	    LossSum(length), Sort<LossSum>)-1, l1);

	// Estimate continuous loss rate
	double conti_rate = (cp->energy - (cp+1)->energy - (l2-1)->energy)
	    /((cp+1)->length - cp->length);

	i3_assert(ls->energy <= cp->energy && "sum of losses is smaller than energy at last checkpoint");
	return cp->energy - ls->energy - conti_rate*(length-cp->length);
}

I3Position
Track::GetPos(double length) const
{
	if (!std::isfinite(length) || length < 0 || length >= GetLength())
		return I3Position(NAN, NAN, NAN);
	const I3Position &pos = I3Particle::GetPos();
	const I3Direction &dir = I3Particle::GetDir();
	return I3Position(pos.GetX() + length*dir.GetX(),
	                  pos.GetY() + length*dir.GetY(),
	                  pos.GetZ() + length*dir.GetZ());
}

double
Track::GetTime(double length) const
{
	if (!std::isfinite(length) || length < 0 || length >= GetLength())
		return NAN;
	else
		return I3Particle::GetTime() + length/I3Particle::GetSpeed();
}

namespace {

/**
 * Ensure that the MMCTrack has the same time reference as
 * the associated I3MCTree, and also the same ID.
 */
inline I3MMCTrack
TimeShift(const I3Particle &p, const I3MMCTrack mmctrack)
{
	I3MMCTrack shifted(mmctrack);
	double d = (p.GetPos()-I3Position(mmctrack.GetXi(), mmctrack.GetYi(),
	    mmctrack.GetZi())).Magnitude();
	double dt = p.GetTime() + d/p.GetSpeed() - mmctrack.GetTi();
	shifted.SetEnter( mmctrack.GetXi(), mmctrack.GetYi(), mmctrack.GetZi(), mmctrack.GetTi() + dt, mmctrack.GetEi());
	shifted.SetCenter(mmctrack.GetXc(), mmctrack.GetYc(), mmctrack.GetZc(), mmctrack.GetTc() + dt, mmctrack.GetEc());
	shifted.SetExit(  mmctrack.GetXf(), mmctrack.GetYf(), mmctrack.GetZf(), mmctrack.GetTf() + dt, mmctrack.GetEf());
	shifted.SetParticle(p);

	return shifted;
}

inline bool
equivalent(const I3Particle &p1, const I3Particle &p2)
{
    return (p1.GetType() == p2.GetType()) && (p1.GetEnergy() == p2.GetEnergy())
        && (p1.GetPos() == p2.GetPos()) && (p1.GetDir() == p2.GetDir());
}

}

std::list<Track>
Track::Harvest(const I3MCTree &mctree, const I3MMCTrackList &mmctracks)
{
    std::list<Track> tracks;
    I3MCTree::const_iterator p = mctree.end();
    I3MCTree::sibling_const_iterator daughters = mctree.end_sibling();
    BOOST_FOREACH(const I3MMCTrack &mmctrack, mmctracks) {
        // For each track, find the particle it corresponds to
        p = mctree.find(mmctrack.GetI3Particle());
        // The above search will fail if particle IDs were not originally
        // unique. Fall back to linear search.
        if (p == mctree.end() || !equivalent(*p, mmctrack.GetI3Particle())) {
            for (p = mctree.begin(); p != mctree.end(); p++) {
                if (equivalent(*p, mmctrack.GetI3Particle()))
                    break;
            }
        }
        if (p != mctree.end()) {
            i3_assert(equivalent(*p, mmctrack.GetI3Particle()));
            // Get energy checkpoints from the MMCTrack and stochastic losses
            // from the direct daughters of the corresponding MCTree node
            daughters = mctree.children(p);
            // Make sure we have daughters first
            if (daughters != mctree.end_sibling())
                // Timeshift the particle the track corresponds to, then make a track with that
                // timeshifted particle and its daughters
                tracks.push_back(Track(TimeShift(*p, mmctrack), daughters, mctree.end_sibling() ) );
        }
    }

	return tracks;
}

};

ext: cxx


text:
// (C) 2014 Arek Olek

#pragma once

#include <vector>

#include <boost/graph/adjacency_list.hpp>

template <class Graph, class Tree>
class Ilst {
  std::vector<bool> discovered;
  unsigned conflicted, leaves;

  void visit(Graph const & G, Tree & tree, unsigned v) {
    discovered[v] = true;
    for(auto w : range(adjacent_vertices(v, G))) {
      if(!discovered[w]) {
        add_edge(v, w, tree);
        visit(G, tree, w);
      }
    }
    if(out_degree(v, tree) == 1) {
      ++leaves;
      if(edge(0, v, G).second) {
        conflicted = v;
      }
    }
  }
  std::pair<unsigned, unsigned> branch_edge(unsigned l, Tree const & tree) const {
    unsigned a = l, b = l, tmp;
    do {
      auto it = adjacent_vertices(b, tree).first;
      tmp = a;
      a = b;
      b = tmp == *it ? *(++it) : *it;
    } while(out_degree(b, tree) == 2);
    return std::make_pair(a, b);
  }
public:
  Ilst() : conflicted(0), leaves(0) {}

  Tree traverse(Graph const & G) {
    discovered.resize(num_vertices(G));
    Tree tree(num_vertices(G));
    visit(G, tree, 0);
    if(leaves > 2 && out_degree(0, tree) == 1 && conflicted != 0) {
      auto e = branch_edge(conflicted, tree);
      add_edge(0, conflicted, tree);
      remove_edge(e.first, e.second, tree);
    }
    return tree;
  }
};

template <class Graph, class Tree>
Tree ilst(Graph const & G) {
  return Ilst<Graph, Tree>().traverse(G);
}

max_stars_repo_name: arekolek/MaxIST

max_issues_repo_name: arekolek/MaxIST

max_forks_repo_name: arekolek/MaxIST


text:
/*
 * debugStubInfoAccess.hpp
 *
 *
 * @date 14-07-2020
 * @author Teddy DIDE
 * @version 1.00
 * cppBase generated by gensources.
 */

#ifndef _DEBUGSTUBINFO_ACCESS_HPP_
#define _DEBUGSTUBINFO_ACCESS_HPP_

#include <boost/scoped_ptr.hpp>
#include <memory>
#include <boost/signals2.hpp>
#include <boost/any.hpp>
#include "cppBaseExport.hpp"
#include "debugStubInfo.hpp"

#define A(str) encode<EncodingT,ansi>(str)
#define C(str) encode<ansi,EncodingT>(str)

NAMESPACE_BEGIN(data_access)

using namespace entity;

/// Represents an access class for DebugStubInfo object.
/// This class is used to manage DebugStubInfo entity in database.
template <class EncodingT>
class CPPBASE_API  _DebugStubInfoAccess {
private :
	std::list< boost::shared_ptr< _DebugStubInfo<EncodingT> > > m_backup;
	// Is a transaction in progress before queries ?
	bool m_transactionOwner;
	static _DebugStubInfoAccess<EncodingT>* m_instance;

public:
	typedef boost::signals2::signal<void (operation_access_t, typename EncodingT::string_t const&, boost::any const&)>  signal_t;
	typedef boost::signals2::signal<void (operation_access_t)>  signal_transaction_t;
	typedef boost::signals2::connection  connection_t;

private:
	signal_t m_insertSignal;
	signal_t m_updateSignal;
	signal_t m_deleteSignal;
	signal_transaction_t m_transactionSignal;

private:
	/** Creates a new element DebugStubInfoAccess.
	*/
	_DebugStubInfoAccess();
	/** Releases the DebugStubInfoAccess object.
	*/
	~_DebugStubInfoAccess();
	Category*	m_logger;

protected :
public :
	/** Returns DebugStubInfoAccess object.
	@return Instance of DebugStubInfoAccess.
	*/
	 static _DebugStubInfoAccess<EncodingT>* getInstance();
	/** Returns DebugStubInfo objects from database.
	@param filter Condition allowing to filter data.
	@return List of DebugStubInfo objects.
	*/
	 std::vector< boost::shared_ptr< _DebugStubInfo<EncodingT> > > getManyDebugStubInfos(typename EncodingT::string_t const&  filter) const;
	/** Returns all DebugStubInfo objects from database.
	@return List of DebugStubInfo objects.
	*/
	 std::vector< boost::shared_ptr< _DebugStubInfo<EncodingT> > > getAllDebugStubInfos() const;
	/** Returns DebugStubInfo object from database.
	@param identifier
	@return The DebugStubInfo object.
	*/
	 boost::shared_ptr< _DebugStubInfo<EncodingT> > getOneDebugStubInfo(long long identifier) const;
	/** Returns DebugStubInfo objects from database. Data are locked for update.
	@param filter Condition allowing to filter data.
	@param nowait Asynchonous call.
	@return List of DebugStubInfo objects.
	*/
	 std::vector< boost::shared_ptr< _DebugStubInfo<EncodingT> > > selectManyDebugStubInfos(typename EncodingT::string_t const&  filter, bool nowait = false, bool addition = false);
	/** Returns DebugStubInfo object from database. Data are locked for update.
	@param identifier
	@param nowait Asynchonous call.
	@return The DebugStubInfo object.
	*/
	 boost::shared_ptr< _DebugStubInfo<EncodingT> > selectOneDebugStubInfo(long long identifier, bool nowait = false, bool addition = false);
	/** Returns whether the data DebugStubInfo are selected.
	@param o The DebugStubInfo object.
	@return True if the data DebugStubInfo are selected.
	*/
	 bool isSelectedDebugStubInfo(boost::shared_ptr< _DebugStubInfo<EncodingT> > o) const;
	/** Cancel the selection. The DebugStubInfo object cannot be updated or deleted from database.
	*/
	 void cancelSelection();
	/** Fills debugFileInfo data from database.
	@param o The DebugStubInfo object.
	*/
	 void fillDebugFileInfo(boost::shared_ptr< _DebugStubInfo<EncodingT> > o);
	/** Fills debugValueInfo data from database.
	@param o The DebugStubInfo object.
	@param nowait Asynchronous call.
	*/
	 void fillAllDebugValueInfos(boost::shared_ptr< _DebugStubInfo<EncodingT> > o, bool nowait = false);
	/** Fills debugValueInfo data from database.
	@param o The DebugStubInfo object.
	@param identifier
	@param nowait Asynchronous call.
	*/
	 void fillOneDebugValueInfo(boost::shared_ptr< _DebugStubInfo<EncodingT> > o, long long identifier, bool nowait = false);
	/** Fills debugValueInfo data from database.
	@param o The DebugStubInfo object.
	@param filter Condition allowing to filter data.
	@param nowait Asynchonous call.
	*/
	 void fillManyDebugValueInfos(boost::shared_ptr< _DebugStubInfo<EncodingT> > o, typename EncodingT::string_t const&  filter, bool nowait = false);
	/** Returns whether DebugStubInfo data are altered from database.
	@param o The DebugStubInfo object.
	@return True if data DebugStubInfo have been altered.
	*/
	 bool isModifiedDebugStubInfo(boost::shared_ptr< _DebugStubInfo<EncodingT> > o) const;
	/** Updates DebugStubInfo data to database.
	@param o The DebugStubInfo object.
	*/
	 void updateDebugStubInfo(boost::shared_ptr< _DebugStubInfo<EncodingT> > o);
	/** Inserts DebugStubInfo data to database.
	@param o The DebugStubInfo object.
	*/
	 void insertDebugStubInfo(boost::shared_ptr< _DebugStubInfo<EncodingT> > o);
	/** Deletes DebugStubInfo data to database.
	@param o The DebugStubInfo object.
	*/
	 void deleteDebugStubInfo(boost::shared_ptr< _DebugStubInfo<EncodingT> > o);
	/** Add signal for DebugStubInfo insertion.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addInsertSignal(typename signal_t::slot_function_type subscriber);
	/** Add signal for DebugStubInfo update.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addUpdateSignal(typename signal_t::slot_function_type subscriber);
	/** Add signal for DebugStubInfo deletion.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addDeleteSignal(typename signal_t::slot_function_type subscriber);
	/** Add signal for DebugStubInfo transaction result.
	@param subscriber The observer
	@return The connection
	*/
	 connection_t addTransactionSignal(typename signal_transaction_t::slot_function_type subscriber);
	/** Remove signal for DebugStubInfo insertion.
	@param connection The connection
	*/
	 void removeInsertSignal(connection_t connection);
	/** Remove signal for DebugStubInfo update.
	@param connection The connection
	*/
	 void removeUpdateSignal(connection_t connection);
	/** Remove signal for DebugStubInfo deletion.
	@param connection The connection
	*/
	 void removeDeleteSignal(connection_t connection);
	/** Remove signal for DebugStubInfo transaction result.
	@param connection The connection
	*/
	 void removeTransactionSignal(connection_t connection);
};

typedef _DebugStubInfoAccess<ucs> UniDebugStubInfoAccess;
typedef _DebugStubInfoAccess<ansi> DebugStubInfoAccess;

NAMESPACE_END

#undef C
#undef A

#if !defined(HAS_CPPBASE_DLL) || defined(BUILD_CPPBASE_DLL)
#include "debugStubInfoAccess_impl.hpp"
#endif // !defined(HAS_CPPBASE_DLL) || defined(BUILD_CPPBASE_DLL)

#endif


text:
// ====================================================================================
// Copyright (c) 2012, ioriiod0@gmail.com All rights reserved.
// File         : scheduler.hpp
// Author       : ioriiod0@gmail.com
// Last Change  : 11/08/2012 12:35 AM
// Description  :
// ====================================================================================
#ifndef __ORCHID_SCHEDULER_H__
#define __ORCHID_SCHEDULER_H__

#include <set>
#include <algorithm>
#include <iostream>

#include <boost/assert.hpp>
#include <boost/function.hpp>
#include <boost/context/all.hpp>
#include <boost/utility.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/atomic.hpp>

#include "stack_allocator.hpp"
#include "../utility/debug.hpp"

namespace orchid { namespace detail {

template <template <class,class> class Coroutine,typename IOservice,typename Alloc = stack_allocator>
class scheduler_basic:boost::noncopyable {
public:
    typedef scheduler_basic<Coroutine,IOservice,Alloc> self_type;
    typedef IOservice io_service_type;
    typedef Alloc allocator_type;
    typedef Coroutine<self_type,allocator_type> coroutine_type;
    typedef boost::shared_ptr<coroutine_type> coroutine_pointer;
    typedef boost::context::fcontext_t context_type;
public:
    static boost::atomic<unsigned long> scheduler_id_gen_;

public:
	scheduler_basic() :id_(scheduler_id_gen_.fetch_add(1)), coroutine_id_gen_(0) {
        ORCHID_DEBUG("sche %lu: scheduler_basic()",id());
    }
    ~scheduler_basic() {
        ORCHID_DEBUG("sche %lu: ~scheduler_basic()",id());
        typename std::set<coroutine_pointer>::iterator it;
        for(it = all_.begin();it != all_.end();++it) {
            (*it) -> stop();
            ORCHID_DEBUG("sche %lu: clear coroutine %lu",id(),(*it)->id());
            boost::context::jump_fcontext(&ctx_,(*it)->ctx(),(intptr_t)((*it).get()));
            BOOST_ASSERT((*it) -> is_dead());
        }
        all_.clear();
    }

public:

    void run() {
        ORCHID_DEBUG("sche %lu run",id_);
        io_service_.run();
    }

    void stop() {
        io_service_.stop();
        // typename std::set<coroutine_pointer>::iterator it;
        // for(it = all_.begin();it != all_.end();++it) {
        //     (*it) -> stop();
        // }
    }

    template <typename F>
    void spawn(const F& f,std::size_t stack_size = coroutine_type::default_stack_size()) {
        coroutine_pointer co(new coroutine_type(*this,coroutine_id_gen_.fetch_add(1),f,stack_size));
        io_service_.post(boost::bind(&self_type::do_spawn,this,co));
        ORCHID_DEBUG("sche %lu spawn done",id_);
    }

    void resume(coroutine_pointer co) {
        BOOST_ASSERT(co != NULL);
        do_schedule(co);
    }

    template <typename F>
    void post(const F& f) {
        io_service_.post(f);
    }

    io_service_type& get_io_service() {
        return io_service_;
    }

    const io_service_type& get_io_service() const {
        return io_service_;
    }
    /////////////////////////////////////////////////

    context_type& ctx() {
        return ctx_;
    }

    const context_type& ctx() const {
        return ctx_;
    }

    unsigned long id() const {
        return id_;
    }

private:

    void do_schedule(coroutine_pointer co) {
        //jump to coroutine
        ORCHID_DEBUG("sche:%lu,coroutine:%lu,resume",id(),co->id());
        boost::context::jump_fcontext(&ctx_,co->ctx(),(intptr_t)(co.get()));
        if(co -> is_dead()) {
            all_.erase(co);
        }
    }

    void do_spawn(coroutine_pointer co) {
        ORCHID_DEBUG("sche %lu do spawn",id_);
        all_.insert(co);
        do_schedule(co);
    }

private:
    const unsigned long id_;
    boost::atomic<unsigned long> coroutine_id_gen_;
    context_type ctx_;
    std::set<coroutine_pointer> all_;
    io_service_type io_service_;
};

template <template <class,class> class Coroutine,typename IOservice,typename Alloc>
boost::atomic<unsigned long> scheduler_basic<Coroutine,IOservice,Alloc>::scheduler_id_gen_(0);

} }

#endif


text:
// Copyright 2019 Hans Dembinski
//
// 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/histogram/make_histogram.hpp>

using namespace boost::histogram;

int main() {
  // argument is not an axis
  (void)make_histogram(std::vector<int>{});
}


text:
#include "tgbot/net/HttpParser.h"

#include "tgbot/tools/StringTools.h"

#include <boost/algorithm/string.hpp>
#include <boost/utility/string_view.hpp>

#include <cstddef>
#include <string>
#include <vector>
#include <unordered_map>

using namespace std;
using namespace boost;

namespace TgBot {

    namespace
    {
        const std::string GET = "GET ";
        const std::string POST = "POST ";
        const std::string HTTP1_1 = " HTTP/1.1\r\n";
        const std::string HOST = "Host: ";
        const std::string CONNECTION = "\r\nConnection: ";
        const std::string KEEP_ALIVE = "keep-alive";
        const std::string CLOSE = "close";
        const std::string NEW_LINE = "\r\n";
        const std::string ENCODED_URL_CONTENT = "Content-Type: application/x-www-form-urlencoded\r\n";
        const std::string MULTIPART_CONTENT = "Content-Type: multipart/form-data; boundary=";
        const std::string CONTENT_LENGTH = "Content-Length: ";
        const std::string CONTENT_DISPOSITION = "\r\nContent-Disposition: form-data; name=\"";
        const std::string FILE_NAME = "\"; filename=\"";
        const std::string CONTENT_TYPE = "Content-Type: ";
    }

    size_t HttpParser::calculate_approximate_buffer_size(const Url& url,
        const std::vector<HttpReqArg>& args) const
    {
        size_t result = 0;
        if (args.empty()) {
            result += GET.size();
        }
        else {
            result += POST.size();
        }
        result += url.path.size();
        result += url.query.empty() ? 0 : 1 + url.query.size();
        result += HTTP1_1.size();
        result += HOST.size();
        result += url.host.size();
        result += CONNECTION.size();

        result += KEEP_ALIVE.size();

        result += NEW_LINE.size();
        if (args.empty()) {
            result += NEW_LINE.size();
        }
        else {

            result += MULTIPART_CONTENT.size() + 100;
            result += NEW_LINE.size();
            result += calculate_approximate_multipart_size(args);

            result += CONTENT_LENGTH.size();
            result += 8;
            result += NEW_LINE.size() * 2;
        }
        if (result < 1024 * 10)
        {
            return result * 2;
        }
        return result + 1024 * 10; //+ 10КБ;
    }

    size_t HttpParser::calculate_approximate_multipart_size(const std::vector<HttpReqArg>& args) const
    {
        size_t result = 0;
        for (const HttpReqArg& item : args) {
            result += 102;
            result += CONTENT_DISPOSITION.size();
            result += item.name.size();
            if (item.isFile) {
                result += FILE_NAME.size() + item.fileName.size();
            }
            result += 1 + NEW_LINE.size();
            if (item.isFile) {
                result += CONTENT_TYPE.size();
                result += item.mimeType.size();
                result += NEW_LINE.size();
            }
            result += NEW_LINE.size();
            if (item.value.which() == 0)
            {
                auto& value = boost::get<std::shared_ptr<std::vector<std::uint8_t>>>(item.value);

                result += value->size();

            }
            else
            {
                result += boost::get<std::string>(item.value).size();
            }

            result += NEW_LINE.size();
        }
        result += 24 + NEW_LINE.size();
        return result;
    }

    size_t HttpParser::calculate_exactly_multipart_size(const std::vector<HttpReqArg>& args,
        const std::string& bondary) const
    {
        size_t result = 0;
        for (const HttpReqArg& item : args) {
            result += 2;
            result += bondary.size();
            result += CONTENT_DISPOSITION.size();
            result += item.name.size();
            if (item.isFile) {
                result += FILE_NAME.size() + item.fileName.size();
            }
            result += 1 + NEW_LINE.size();
            if (item.isFile) {
                result += CONTENT_TYPE.size();
                result += item.mimeType.size();
                result += NEW_LINE.size();
            }
            result += NEW_LINE.size();
            if (item.value.which() == 0)
            {
                auto& value = boost::get<std::shared_ptr<std::vector<std::uint8_t>>>(item.value);

                result += value->size();
            }
            else
            {
                result += boost::get<std::string>(item.value).size();
            }

            result += NEW_LINE.size();
        }
        result += 2 + bondary.size() + 2 + NEW_LINE.size();
        return result;
    }

string HttpParser::generateRequest(const Url& url, const vector<HttpReqArg>& args, bool isKeepAlive) const {

    size_t approx_buffer =  calculate_approximate_buffer_size(url, args);
    string result;
    result.reserve(approx_buffer);
    if (args.empty()) {
        result += "GET ";
    } else {
        result += "POST ";
    }
    result += url.path;
    result += url.query.empty() ? "" : "?" + url.query;
    result += " HTTP/1.1\r\n";
    result += "Host: ";
    result += url.host;
    result += "\r\nConnection: ";
    if (isKeepAlive) {
        result += "keep-alive";
    } else {
        result += "close";
    }
    result += "\r\n";
    if (args.empty()) {
        result += "\r\n";
    } else {

        string bondary = generateMultipartBoundary(args);
        if (bondary.empty()) {
            result += "Content-Type: application/x-www-form-urlencoded\r\n";
            string requestData = generateWwwFormUrlencoded(args);
            result += "Content-Length: ";
            result += std::to_string(requestData.length());
            result += "\r\n\r\n";
            result += requestData;
        } else {

            result += "Content-Type: multipart/form-data; boundary=";
            result += bondary;
            result += "\r\n";
            auto requestSize = calculate_exactly_multipart_size(args, bondary);
            result += "Content-Length: ";
            result += std::to_string(requestSize);
            result += "\r\n\r\n";
            auto resultSize = generateMultipartFormData(args, bondary, result);
            if (requestSize != resultSize)
                throw std::logic_error("requestSize != resultSize");
        }

    }
    return result;
}

size_t HttpParser::generateMultipartFormData(const vector<HttpReqArg>& args, const string& bondary, std::string& result) const {

    size_t old_size = result.size();

    for (const HttpReqArg& item : args) {
        result += "--";
        result += bondary;
        result += "\r\nContent-Disposition: form-data; name=\"";
        result += item.name;
        if (item.isFile) {
            result += "\"; filename=\"" + item.fileName;
        }
        result += "\"\r\n";
        if (item.isFile) {
            result += "Content-Type: ";
            result += item.mimeType;
            result += "\r\n";
        }
        result += "\r\n";
        if (item.value.which() == 0)
        {
            auto& value = boost::get<std::shared_ptr<std::vector<unsigned char>>>(item.value);
            //result += reinterpret_cast<char*>(
            //    boost::get<std::shared_ptr<std::vector<unsigned char>>>(item.value)->data());
            result.append(reinterpret_cast<char*>(value->data()),
                value->size());
        }
        else
        {
            result += boost::get<std::string>(item.value);
        }

        result += "\r\n";
    }
    result += "--" + bondary + "--\r\n";
    return result.size() - old_size;
}

string HttpParser::generateMultipartBoundary(const vector<HttpReqArg>& args) const {
    string result;
    for (const HttpReqArg& item : args) {
        if (item.isFile) {
            auto& file_data = boost::get<std::shared_ptr<std::vector<unsigned char>>>(item.value);
            boost::string_view value(reinterpret_cast<char*>(file_data->data()), file_data->size());

            //while (result.empty() || item.value.find(result) != string::npos) {
            //    result += StringTools::generateRandomString(4);
            //}
            while (result.empty() || value.find(result) != string::npos) {
                result += StringTools::generateRandomString(4);
            }
        }
    }
    return result;
}

string HttpParser::generateWwwFormUrlencoded(const vector<HttpReqArg>& args) const {
    string result;

    bool firstRun = true;
    for (const HttpReqArg& item : args) {
        if (firstRun) {
            firstRun = false;
        } else {
            result += '&';
        }
        result += StringTools::urlEncode(item.name);
        result += '=';
        if (item.value.which() == 0)
        {
            throw std::logic_error("generateWwwFormUrlencoded but has file");
            //auto& value = boost::get<std::shared_ptr<std::vector<unsigned char>>>(item.value);
            //result += StringTools::urlEncode(std::string(reinterpret_cast<char*>(
            //    value->data()), value->size()));
        }
        else
        {
            result += StringTools::urlEncode(boost::get<std::string>(item.value));
        }

    }

    return result;
}

string HttpParser::generateResponse(const string& data, const string& mimeType, unsigned short statusCode, const string& statusStr, bool isKeepAlive) const {
    string result;
    result += "HTTP/1.1 ";
    result += std::to_string(statusCode);
    result += ' ';
    result += statusStr;
    result += "\r\nContent-Type: ";
    result += mimeType;
    result += "\r\nContent-Length: ";
    result += std::to_string(data.length());
    result += "\r\nConnection: ";
    if (isKeepAlive) {
        result += "keep-alive";
    } else {
        result += "close";
    }
    result += "\r\n\r\n";
    result += data;
    return result;
}

unordered_map<string, string> HttpParser::parseHeader(const string& data, bool isRequest) const {
    unordered_map<string, string> headers;

    std::size_t lineStart = 0;
    std::size_t lineEnd = 0;
    std::size_t lineSepPos = 0;
    std::size_t lastLineEnd = string::npos;
    while (lastLineEnd != lineEnd) {
        lastLineEnd = lineEnd;
        bool isFirstLine = lineEnd == 0;
        if (isFirstLine) {
            if (isRequest) {
                lineSepPos = data.find(' ');
                lineEnd = data.find("\r\n");
                headers["_method"] = data.substr(0, lineSepPos);
                headers["_path"] = data.substr(lineSepPos + 1, data.find(' ', lineSepPos + 1) - lineSepPos - 1);
            } else {
                lineSepPos = data.find(' ');
                lineEnd = data.find("\r\n");
                headers["_status"] = data.substr(lineSepPos + 1, data.find(' ', lineSepPos + 1) - lineSepPos - 1);
            }
        } else {
            lineStart = lineEnd;
            lineStart += 2;
            lineEnd = data.find("\r\n", lineStart);
            lineSepPos = data.find(':', lineStart);
            if (lastLineEnd == lineEnd || lineEnd == string::npos) {
                break;
            }
            headers[data.substr(lineStart, lineSepPos - lineStart)] = trim_copy(data.substr(lineSepPos + 1, lineEnd - lineSepPos - 1));
        }
    }

    return headers;
}

string HttpParser::extractBody(const string& data) const {
    std::size_t headerEnd = data.find("\r\n\r\n");
    if (headerEnd == string::npos) {
        return data;
    }
    headerEnd += 4;
    return data.substr(headerEnd);
}

}


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

#include "rpplugins/ar_render/plugin.hpp"

#include <boost/dll/alias.hpp>

#include <fmt/ostream.h>

#include <render_pipeline/rpcore/loader.hpp>

#include "rpplugins/ar_render/ar_composite_stage.hpp"

#include "depthmap_render_stage.hpp"

RENDER_PIPELINE_PLUGIN_CREATOR(rpplugins::ARRenderPlugin)

namespace rpplugins {

rpcore::BasePlugin::RequrieType ARRenderPlugin::require_plugins_;

ARRenderPlugin::ARRenderPlugin(rpcore::RenderPipeline& pipeline): BasePlugin(pipeline, RPPLUGINS_ID_STRING)
{
}

rpcore::BasePlugin::RequrieType& ARRenderPlugin::get_required_plugins(void) const
{
    return require_plugins_;
}

void ARRenderPlugin::on_stage_setup(void)
{
    auto depthmap_render_stage = std::make_unique<DepthmapRenderStage>(pipeline_);
    depthmap_render_stage_ = depthmap_render_stage.get();
    add_stage(std::move(depthmap_render_stage));

    auto ar_composite_stage = std::make_unique<ARCompositeStage>(pipeline_);
    ar_composite_stage_ = ar_composite_stage.get();
    add_stage(std::move(ar_composite_stage));
}

NodePath ARRenderPlugin::get_real_depth_camera(void) const
{
    return depthmap_render_stage_->get_camera();
}

void ARRenderPlugin::set_ar_camera_color_texture(Texture* tex, bool is_bgr, bool flip_vertical)
{
    ar_composite_stage_->set_ar_camera_color_texture(tex, is_bgr, flip_vertical);
}

void ARRenderPlugin::set_ar_camera(const NodePath& cam)
{
    if (!cam.node()->is_of_type(Camera::get_class_type()))
    {
        error(fmt::format("The NodePath is not type of Camera: {}", cam));
        return;
    }

    depthmap_render_stage_->set_ar_camera(cam);
    ar_composite_stage_->set_ar_camera(cam);
}

void ARRenderPlugin::set_ar_camera(const NodePath& left_cam, const NodePath& right_cam)
{
    if (!left_cam.node()->is_of_type(Camera::get_class_type()))
    {
        error(fmt::format("The NodePath is not type of Camera: {}", left_cam));
        return;
    }

    if (!right_cam.node()->is_of_type(Camera::get_class_type()))
    {
        error(fmt::format("The NodePath is not type of Camera: {}", right_cam));
        return;
    }

    depthmap_render_stage_->set_ar_camera(left_cam);
    ar_composite_stage_->set_ar_camera(left_cam, right_cam);
}

}