text:
#ifndef INCLUDED_STDDEFX
#include "stddefx.h"
#define INCLUDED_STDDEFX
#endif

#ifndef INCLUDED_CALC_ASTSCRIPT
#include "calc_astscript.h"
#define INCLUDED_CALC_ASTSCRIPT
#endif

// Library headers.
#ifndef INCLUDED_BOOST_NONCOPYABLE
#include <boost/noncopyable.hpp>
#define INCLUDED_BOOST_NONCOPYABLE
#endif

// PCRaster library headers.
#ifndef INCLUDED_COM_EXCEPTION
#include "com_exception.h"
#define INCLUDED_COM_EXCEPTION
#endif
#ifndef INCLUDED_APPARGS
#include "appargs.h"  // appClone
#define INCLUDED_APPARGS
#endif
// Module headers.
#ifndef INCLUDED_CALC_POSITIONNAME
#include "calc_positionname.h"  // appClone
#define INCLUDED_CALC_POSITIONNAME
#endif
#ifndef INCLUDED_CALC_CODE
#include "calc_code.h"
#define INCLUDED_CALC_CODE
#endif
#ifndef INCLUDED_CALC_SYMEXCEPTION
#include "calc_symexception.h"
#define INCLUDED_CALC_SYMEXCEPTION
#endif
#ifndef INCLUDED_CALC_USEDEFANALYZER
#include "calc_usedefanalyzer.h"
#define INCLUDED_CALC_USEDEFANALYZER
#endif
#ifndef INCLUDED_CALC_BUILDTYPESVISITOR
#include "calc_buildtypesvisitor.h"
#define INCLUDED_CALC_BUILDTYPESVISITOR
#endif
#ifndef INCLUDED_CALC_RUNSETTINGS
#include "calc_runsettings.h"
#define INCLUDED_CALC_RUNSETTINGS
#endif
#ifndef INCLUDED_CALC_ASTNODE
#include "calc_astnode.h"
#define INCLUDED_CALC_ASTNODE
#endif
#ifndef INCLUDED_CALC_ASTNODEVECTOR
#include "calc_astnodevector.h"
#define INCLUDED_CALC_ASTNODEVECTOR
#endif
#ifndef INCLUDED_CALC_REPORTVISITOR
#include "calc_reportvisitor.h"
#define INCLUDED_CALC_REPORTVISITOR
#endif
#ifndef INCLUDED_CALC_CFGCREATOR
#include "calc_cfgcreator.h"
#define INCLUDED_CALC_CFGCREATOR
#endif
#ifndef INCLUDED_CALC_CFGNODE
#include "calc_cfgnode.h"
#define INCLUDED_CALC_CFGNODE
#endif
#ifndef INCLUDED_CALC_POINTCODEBLOCKDLL
#include "calc_pointcodeblockdll.h"
#define INCLUDED_CALC_POINTCODEBLOCKDLL
#endif
#ifndef INCLUDED_CALC_INSERTPOINTCODEBLOCKS
#include "calc_insertpointcodeblocks.h"
#define INCLUDED_CALC_INSERTPOINTCODEBLOCKS
#endif
#ifndef INCLUDED_CALC_POINTCODEBLOCK
#include "calc_pointcodeblock.h"
#define INCLUDED_CALC_POINTCODEBLOCK
#endif
#ifndef INCLUDED_CALC_DATATYPECLASH
#include "calc_datatypeclash.h"
#define INCLUDED_CALC_DATATYPECLASH
#endif

#ifndef INCLUDED_CALC_ASTNUMBER
#include "calc_astnumber.h"
#define INCLUDED_CALC_ASTNUMBER
#endif

#ifndef INCLUDED_CALC_VS
#include "calc_vs.h"
#define INCLUDED_CALC_VS
#endif

#ifndef INCLUDED_CALC_TIMETABLE
#include "calc_timetable.h"
#define INCLUDED_CALC_TIMETABLE
#endif

/*!
  \file
  This file contains the implementation of the ASTScript class.
*/

//------------------------------------------------------------------------------

namespace calc {
  namespace Private {
    struct Check : public boost::noncopyable {
     const ASTSymbolTable& d_syms;
     Check(const ASTSymbolTable& syms):d_syms(syms) {}

     void notANumber(ASTId *id,
                     const std::string& name)
     {
         std::ostringstream os;
         os << id->qName() <<" is not a whole positive number (in "<<
               name << " definition)";
         id->posError(os);
     }

     // check id being a number of an id known as constant
     size_t operator()(
         ASTId *id,
         const std::string& name)
     {
       PRECOND(id);
       const ASTNumber *n=dynamic_cast<const ASTNumber *>(id);
       double value;
       if(n) {
         value=n->value();
       } else {
        PRECOND(d_syms.contains(id->name()));
        const ASTSymbolInfo&  a(d_syms[id->name()]);
        if(!a.isConstant()) // pcrcalc8b
          notANumber(id,name);
        value=a.constantValue();
       }
       if ( (!isIn(VS_N,id->returnDataType().vs())) || value < 0) {
          // pcrcalc7a
          notANumber(id,name);
       }
       return static_cast<size_t>(value);
     }
   };
  }
}

//------------------------------------------------------------------------------
// DEFINITION OF STATIC ASTSCRIPT MEMBERS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF ASTSCRIPT MEMBERS
//------------------------------------------------------------------------------

calc::ASTScript::ASTScript():
  d_code(0),
  d_cfgCode(0),
  d_cfgBody(0),
  d_areaMap(0),
  d_externalTimer(0),
  d_timerStartOrTss(0),
  d_timerEnd(0),
  d_timerStep(0),
  d_containsDynamicSection(false),
  d_hasStatementWithReportKeyword(false),
  d_pointCodeBlockDll(0),
  d_reportOnlyForXMLScriptOutput(false)
{
  if (appClone)
    setAreaMapFromString(appClone,"--clone");
}

void calc::ASTScript::setAreaMapFromString(
  std::string const& value,
  std::string const& positionText)
{
    delete d_areaMap;
    d_areaMap= new ASTPar(value);
    PositionName pn(positionText);
    d_areaMap->setPosition(&pn);
}

calc::ASTScript::~ASTScript()
{
  delete d_areaMap;
  delete d_externalTimer;
  delete d_timerStartOrTss;
  delete d_timerEnd;
  delete d_timerStep;
  delete d_code;

  delete d_cfgCode;
  delete d_cfgBody;

  delete d_pointCodeBlockDll;
}

/* NOT IMPLEMENTED
//! Assignment operator.
calc::ASTScript& calc::ASTScript::operator=(const ASTScript& rhs)
{
  if (this != &rhs) {
  }
  return *this;
}

//! Copy constructor. NOT IMPLEMENTED.
calc::ASTScript::ASTScript(const ASTScript& rhs):
  Base(rhs)
{
}
*/

/*! \brief transfer code, code may contain initial and dynamic section
 */
void calc::ASTScript::transferCode(ASTNode *code) {
  delete d_code;
  d_code=new Code(code);

  rebuildCFG();
}

void calc::ASTScript::rebuildCFG() {
  // TODO not very efficient doing it twice
  delete d_cfgCode;
  d_cfgCode = createCFG(d_code);
  delete d_cfgBody;

  std::vector<ASTNode *> body;
  body.push_back(d_areaMap);
  body.push_back(d_timerStartOrTss);
  body.push_back(d_timerEnd);
  body.push_back(d_timerStep);
  body.push_back(d_code);

  d_cfgBody = createCFG(body);

}

void calc::ASTScript::buildTypesFullClosure()
{
  BuildTypesVisitor btv(d_cfgBody);
  btv.init(d_symbols);

  size_t nrChanges=btv.nrChanges();
  do {
   nrChanges=btv.nrChanges();
   btv.visit();
   // Let's be reasonable about this
   PRECOND(btv.nrChanges() < 100000);
  } while(nrChanges != btv.nrChanges());

  // updated symbols
  d_symbols = btv.table();

  d_containsDynamicSection=btv.containsDynamicSection();
  d_hasStatementWithReportKeyword=btv.hasStatementWithReportKeyword();

}

/*
 * \brief attach info from interface and binding to d_symbols
 *        (as discovered in the BuildTypesVisitor).
 *
 * Note that applying the interface may restrict the DataType of d_symbols.
 */
void calc::ASTScript::applyInterface()
{
  EffectiveBindings bt(d_bindings);

  // 1) external binding -> bindings
  if (!d_rteSettings.externalBindingFile().isEmpty()) {
   RunSettings rs(d_rteSettings.externalBindingFile());
   bt.overwrite(rs);
  }

  // 2) apply bindings
  // make set of syms defined in interface
  std::set<std::string> interfaceSyms;
  for(size_t i=0; i<d_interface.size(); ++i)
    interfaceSyms.insert(d_interface[i].name());
  bt.applyToSymbols(d_symbols,interfaceSyms);

  // 3) apply interface
  for(size_t i=0; i<d_interface.size(); ++i) {
    ASTSymbolTable::iterator s= d_symbols.find(d_interface[i].name());
    if (s!=d_symbols.end())
      s->second.setInfo(d_interface[i]);
  }
}

/*! rewrite the AST for compiled code blocks if compile flag is set
 * \todo
 *   disabled and not working in tests at this moment
 */
void calc::ASTScript::compile()
{
  if (!d_rteSettings.compile())
    return;

 std::vector<PointCodeBlock *> l=
   insertPointCodeBlocks(d_symbols,d_code,d_cfgCode);
 d_pointCodeBlockDll= new PointCodeBlockDll(l);

 // AST is changed by insertPointCodeBlocks
 rebuildCFG();
 setLastUse(d_cfgCode);
}

/*
 * //! check and build up new symbol table using the xmlConfigure context
 * void calc::ASTScript::analyzeWithConfiguration(
 *     const std::string& xmlConfigure)
 * {
 *   XMLReflection xr(xmlConfigure);
 *
 *   // d_rteSettings.resetIOStrategy(xr.ioStrategy());
 *   // POSTCOND(xr.ioStrategy()==pcrxml::IOStrategyType::IOMemory);
 *
 *   // start with info from script itself
 *   analyzeNoContext();
 *
 *   //  restrict d_symbols in types from xmlConfigure
 *   d_rteSettings.configureSymbols(d_symbols, xr);
 * }
 */

void calc::ASTScript::setSettingsFromXML(pcrxml::Script const& script)
{
  std::string areaMapRef =
    d_rteSettings.setSettingsFromXML(script);
  if (! areaMapRef.empty()) {
    setAreaMapFromString(areaMapRef,"<xmlApi>");
  }
}

void calc::ASTScript::callWithClashRewrite(
    void (ASTScript::*f)() )
{
 try {
      try {
          (this->*f)();
      } catch( const DataTypeClash& ) {
       // transform DataTypeClash into SymException
       //  see for example pcrcalc372a
       buildTypesFullClosure();
       POSTCOND(FALSE); // never here
      }
 } catch (const SymException& s) {
     d_symbols.throwSym(s);
 }
}

//! check and build up new symbol table without any context
/*!
 * no context means:
 * - reset d_symbols to empty at start.
 * - no resolve() to look for input data.
 * .
 *
 * \todo (*) since IOMemory is not yet correct for mapstacks
 *        this is not completely true, only the default will do
 */
void calc::ASTScript::analyzeNoContextUnChecked()
{
  // BuildTypesVisitor with empty table
  d_symbols = ASTSymbolTable();
  buildTypesFullClosure();

  setLastUse(d_cfgCode);

  // compute ioTypes
  typedef std::map<std::string,IOType> CodeTypes;
  CodeTypes codeTypes=ioTypes(d_cfgCode);
  for (CodeTypes::const_iterator i=codeTypes.begin();
       i!=codeTypes.end(); ++i) {
    ASTSymbolTable::iterator s=d_symbols.find(i->first);
    PRECOND(s!=d_symbols.end());
    s->second.setIoType(i->second);
  }

  applyInterface();

  // redo with type information found in applyInterface
  buildTypesFullClosure();

  if (d_rteSettings.useDiskStorage())
   d_symbols.checkDifferentExternalNames();
}

void calc::ASTScript::resolve() {
  callWithClashRewrite(&ASTScript::resolveUnChecked);
}
void calc::ASTScript::analyzeNoContext() {
  callWithClashRewrite(&ASTScript::analyzeNoContextUnChecked);
}

/*! resolve inputs and recheck types of input with AST and symbol info
 */
void calc::ASTScript::resolveUnChecked() {

  std::string areaMap;
  if (d_areaMap)
    areaMap=d_areaMap->name();

  // possible first time to see if it IS reported
  // NOTE never call setReport for the first time
  //      before setDefinition() is done
  setReports();

  Timer t(timer());

  d_rteSettings.resolve(d_symbols, areaMap, t);

  buildTypesFullClosure();
  // possible second or later time, now we know the timer end
  // that might came up from a read timeseries in resolve()
  setReports();

  if (containsDynamicSection() && !t.dynamic())
    d_code->posError("There is a dynamic section but no timer section");
}

/* \brief analyzeNoContext() followed by resolve()
 * Full configuration and checking of AST and symbols
 */
void calc::ASTScript::analyzeAndResolve()
{
 analyzeNoContext();
 resolve();
}

/*! update symbols for report info, what is written and what not
 */
void calc::ASTScript::setReports()
{
 Timer t = timer();
 if (!t.lastInt())
     t.setLastInt(1);

 d_reports.update(t);

 bool reportLastAssOfEverySymbol =
    !d_containsDynamicSection &&
     d_interface.empty() &&
    !d_hasStatementWithReportKeyword;
 if (d_reportOnlyForXMLScriptOutput)
   reportLastAssOfEverySymbol=true;

 ReportVisitor rv(reportLastAssOfEverySymbol, d_reports,t);
 if (d_code)
    d_code->accept(rv);

 ReportPars rps(rv.reportPars());
 for(ReportPars::const_iterator rp=rps.begin();rp!=rps.end();++rp) {
   ASTSymbolTable::iterator s= d_symbols.find(rp->first);
   POSTCOND(s != d_symbols.end());
   ReportPar const& rpp(rp->second);
   s->second.setReport(rpp.d_par,rpp.d_report,rpp.d_inDynamic,
                       d_reportOnlyForXMLScriptOutput);
 }
}

//! set value of d_reportOnlyForXMLScriptOutput
void calc::ASTScript::setReportOnlyForXMLScriptOutput(bool reportOnlyForXMLScriptOutput)
{
  d_reportOnlyForXMLScriptOutput=reportOnlyForXMLScriptOutput;
}

//! get value of cfgCode
calc::CFGNode*  calc::ASTScript::cfgCode() const
{
  return d_cfgCode;
}

//! get value of cfgCode
calc::ASTNode*  calc::ASTScript::astCode() const
{
  return d_code;
}

void calc::ASTScript::transferAreaMap(ASTId *areaMap)
{
  delete d_areaMap;
  d_areaMap=areaMap;
}

void calc::ASTScript::transferTimerSection(ASTId* timerStartOrTss,
                                           ASTId* timerEnd,
                                           ASTId* timerStep)
{
  PRECOND(!d_timerStartOrTss); // only called once
  d_timerStartOrTss=timerStartOrTss;
  d_timerEnd       =timerEnd;
  d_timerStep      =timerStep;
}

//! get value of rteSettings
const calc::RunTimeEnvSettings& calc::ASTScript::rteSettings() const
{
  return d_rteSettings;
}

void  calc::ASTScript::setRteSettings(RunTimeEnvSettings const& rteSettings)
{
  d_rteSettings=rteSettings;
}

//! get value of bindings
const calc::BindingTable& calc::ASTScript::bindings() const
{
  return d_bindings;
}

//! get value of reports
const calc::ReportTable& calc::ASTScript::reports() const
{
  return d_reports;
}

//! get const symbols
const calc::ASTSymbolTable& calc::ASTScript::symbols() const
{
  return d_symbols;
}
//
//! get value of containsDynamicSection
bool calc::ASTScript::containsDynamicSection() const
{
  return d_containsDynamicSection;
}

//! get modifiable symbols
calc::ASTSymbolTable& calc::ASTScript::symbols()
{
  return d_symbols;
}

void calc::ASTScript::transferOneBinding(ASTNode* bindingDefinition)
{
    d_bindings.transferPushBack(bindingDefinition);
}

void calc::ASTScript::addReportDefinition(Report const& reportDef)
{
    d_reports.add(reportDef);
}
void calc::ASTScript::addInterfaceDefinition(ASTDefinition const& astDef)
{
    d_interface.push_back(astDef);
}

//! set value of externalTimer
void calc::ASTScript::setExternalTimer(Timer const& externalTimer)
{
  delete d_externalTimer;
  d_externalTimer= new Timer(externalTimer);
}

calc::Timer calc::ASTScript::timer() const
{
 Timer timer;

 if (d_externalTimer)
    return *d_externalTimer;

 if (!d_timerStartOrTss)
   return timer; // no timer section, static model

 // else analyze d_timerStartOrTss

 PRECOND(!timer.lastInt());
 if (!d_timerStartOrTss->isNumber()) {
   const ASTSymbolInfo&  a(d_symbols[d_timerStartOrTss->name()]);
   if (!a.isConstant()) { // it is a (file)-symbol
     try {
       TimeTable tss(a.externalName(),VS_S,1);
       timer.setStartInt(1);
       timer.setLastInt(tss.nrTimeSteps());
      } catch(const com::Exception& e) {
        // pcrcalc364
        a.throwAtFirst(e); // happens to be first ?
      }
  }
 }

 // if not set by tss
 if (!timer.startInt()) {

   Private::Check c(d_symbols);
   timer.setStartInt(c(d_timerStartOrTss,"start time"));
   timer.setLastInt(c(d_timerEnd,"end time"));
   size_t step  = c(d_timerStep,"time step");

   if ( timer.startInt() == 0) { // pcrcalc6
     d_timerStartOrTss->posError("start time must be > 0 ");
   }
   if (step != 1) { // pcrcalc7
    std::ostringstream os;
    os<<"current limitation: time step must be 1 (not "<<step<<")";
    d_timerStep->posError(os);
   }
   if (timer.startInt() > timer.lastInt()) { // pcrcalc8
    std::ostringstream os;
    os<<"Start time ("<<timer.startInt()<<") is greater than end time ("
      << timer.lastInt() <<")";
    d_timerStartOrTss->posError(os);
   }
 }
 return timer;
}

//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF FREE OPERATORS
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
// DEFINITION OF FREE FUNCTIONS
//------------------------------------------------------------------------------

ext: cc

max_stars_repo_name: quanpands/wflow

max_issues_repo_name: quanpands/wflow

max_forks_repo_name: quanpands/wflow


text:
#ifndef SUPERGENIUS_SRC_API_RPC_THREAD_POOL_HPP
#define SUPERGENIUS_SRC_API_RPC_THREAD_POOL_HPP

#include <boost/asio/io_service.hpp>
#include <boost/asio/signal_set.hpp>
#include <set>
#include <thread>

#include "api/transport/rpc_io_context.hpp"
#include "application/app_state_manager.hpp"
#include "base/logger.hpp"

using sgns::application::AppStateManager;

namespace sgns::api {

  /**
   * @brief thread pool for serve RPC calls
   */
  class RpcThreadPool : public std::enable_shared_from_this<RpcThreadPool> {
   public:
    using Context = RpcContext;

    struct Configuration {
      size_t min_thread_number = 1;
      size_t max_thread_number = 10;
    };

    RpcThreadPool(std::shared_ptr<Context> context,
                  const Configuration &configuration);

    ~RpcThreadPool() = default;

    /**
     * @brief starts pool
     */
    void start();

    /**
     * @brief stops pool
     */
    void stop();

   private:
    std::shared_ptr<Context> context_;
    const Configuration config_;

    std::vector<std::shared_ptr<std::thread>> threads_;

    base::Logger logger_ = base::createLogger("RPC thread pool");
  };

}  // namespace sgns::api

#endif  // SUPERGENIUS_SRC_API_RPC_THREAD_POOL_HPP

ext: hpp

max_stars_repo_name: GeniusVentures/SuperGenius

max_issues_repo_name: GeniusVentures/SuperGenius

max_forks_repo_name: GeniusVentures/SuperGenius


text:
/**
 * Opens the file specified, maps it into memory, and attempts to parse it as
 * a chunk.
 */
#ifndef CHUNKFILEPARSER_H
#define CHUNKFILEPARSER_H

#include <boost/filesystem.hpp>

#include <cstdio>

#include "TapeStructs.h"

class ChunkFileParser {
	public:
		ChunkFileParser(boost::filesystem::path);
		~ChunkFileParser();

		void listFiles();

		void extractAtIndex(off_t);

	private:
		FILE *fd;
		void *mappedFile;
		size_t size;

		void _parseHeader();

		void _printFileInfo(size_t, chunk_file_entry_t *);
		const char *_nameForUid(int);
		const char *_nameForGid(int);
};

#endif

max_stars_repo_name: backuperator/daemon

max_issues_repo_name: backuperator/daemon

max_forks_repo_name: backuperator/daemon


text:
/**
 * Utility class for tracking relation/individual
 * counts throughout.
 *
 * @file PredFinderCounts.h
 * @author gkratkiew@bbn.com
 **/

#include "Generic/common/leak_detection.h"

#include "Generic/common/ParamReader.h"
#include "Generic/common/SessionLogger.h"

#include "PredFinderCounts.h"

#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>

#include <iostream>
#include <cassert>

using namespace std;

PredFinderCounts* PredFinderCounts::getPredFinderCounts(bool sort_output) {
	PredFinderCounts* pi;
	if (sort_output) {
		pi = new PredFinderCountsSort;
	} else {
		pi = new PredFinderCountsNonsort;
	}
	pi->start();
	return pi;
}

void PredFinderCounts::doc_start_message(const DocTheory* doc_theory) {
	wostringstream local_ostr;
	local_ostr << "Processing " << doc_theory->getDocument()->getName() << "...\n";
	SessionLogger::info("doc_info_start") << local_ostr.str();

	_ostr.str(L"");
}

void PredFinderCounts::add_total(const ElfDocument_ptr elf_info, int type) {
	_totals_cr.Add(type, elf_info->get_n_relations(), elf_info->get_n_individuals());
}

void PredFinderCounts::titles() {
	_ostr.str(L"");
	write_doc_id(L"DOCUMENT_ID");
	write_rel_and_indiv_count<const char*>("PELF_RL", "PELF_IN");
	write_rel_and_indiv_count<const char*>("SELF_RL", "SELF_IN");
	write_rel_and_indiv_count<const char*>("MSELF_RL", "MSELF_IN");
	write_rel_and_indiv_count<const char*>("RELF_RL", "RELF_IN");
	write_rel_and_indiv_count<const char*>("MRELF_RL", "MRELF_IN");
	SessionLogger::info("doc_title_0") << _ostr.str();
}

void PredFinderCounts::totals() {
	//titles();
	totals(L"TOTAL PELF", "PELF", CountRecord::PELF);
	totals(L"TOTAL SELF", "SELF", CountRecord::SELF);
	totals(L"TOTAL MERGED-SELF", "MERGED-SELF", CountRecord::MERGED_SELF);
	totals(L"TOTAL RELF", "RELF", CountRecord::RELF);
	totals(L"TOTAL MERGED-RELF", "MERGED-RELF", CountRecord::MERGED_RELF);
}

void PredFinderCounts::totals(const wstring & title, const string & tag, const int type) {
	_ostr.str(L"");
	write_doc_id(title);
	write_rel_and_indiv_count<int>(_totals_cr.GetRelationCount(type), _totals_cr.GetIndividualCount(type));
	_ostr << right << std::endl << std::endl;
	SessionLogger::info("total_0") << _ostr.str();
	if (_totals_cr.GetRelationCount(type) == 0) {
		SessionLogger::warn("no_rel_0") << "No " << tag << " relations found!\n";
	}
	if (type != CountRecord::RELF && type != CountRecord::MERGED_RELF && _totals_cr.GetIndividualCount(type) == 0) {
		SessionLogger::warn("no_ind_0") << "No " << tag << " individuals found!\n";
	}
}

void PredFinderCounts::write_doc_id(const wstring & doc_id) {
	const int ID_WIDTH(35);
	_ostr.width(ID_WIDTH);
	_ostr << left << doc_id;
}

template <class T>
void PredFinderCounts::write_rel_and_indiv_count(T relation_count, T individual_count) {
	const int NUM_WIDTH(8);
	_ostr << " ";
	_ostr.width(NUM_WIDTH);
	_ostr << right << relation_count;
	_ostr << " ";
	_ostr.width(NUM_WIDTH);
	_ostr << right << individual_count;
}

void PredFinderCountsSort::doc_start(const DocTheory* doc_theory) {
	doc_start_message(doc_theory);

	_current_cr.Reset();
	_current_cr.SetDocId(doc_theory->getDocument()->getName().to_string());
}

void PredFinderCountsSort::add(const ElfDocument_ptr elf_info, int type) {
	add_total(elf_info, type);
	_current_cr.Set(type, elf_info->get_n_relations(), elf_info->get_n_individuals());
}

void PredFinderCountsSort::doc_end() {
	_count_record_set.insert(_current_cr);
}

void PredFinderCountsSort::finish() {
	titles();
	BOOST_FOREACH(CountRecord cr, _count_record_set) {
		_ostr.str(L"");
		write_doc_id(cr.GetDocId());
		write_rel_and_indiv_count<int>(cr.GetRelationCount(CountRecord::PELF), cr.GetIndividualCount(CountRecord::PELF));
		write_rel_and_indiv_count<int>(cr.GetRelationCount(CountRecord::SELF), cr.GetIndividualCount(CountRecord::SELF));
		write_rel_and_indiv_count<int>(cr.GetRelationCount(CountRecord::MERGED_SELF), cr.GetIndividualCount(CountRecord::MERGED_SELF));
		write_rel_and_indiv_count<int>(cr.GetRelationCount(CountRecord::RELF), cr.GetIndividualCount(CountRecord::RELF));
		write_rel_and_indiv_count<int>(cr.GetRelationCount(CountRecord::MERGED_RELF), cr.GetIndividualCount(CountRecord::MERGED_RELF));
		SessionLogger::info("doc_id_1") << _ostr.str();
	}
	SessionLogger::info("doc_id_2") << "\n\n";
	totals();
}

void PredFinderCountsNonsort::doc_start(const DocTheory* doc_theory) {
	doc_start_message(doc_theory);
	write_doc_id(doc_theory->getDocument()->getName().to_string());
}

void PredFinderCountsNonsort::add(const ElfDocument_ptr elf_info, int type) {
	add_total(elf_info, type);
	write_rel_and_indiv_count<int>(elf_info->get_n_relations(), elf_info->get_n_individuals());
}

void PredFinderCountsNonsort::doc_end() {
	_ostr << std::endl;
	SessionLogger::info("doc_info_0") << _ostr.str();
}

ext: cpp

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text: #include <boost/spirit/home/karma/stream/format_manip_attr.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */

///
/// This file was automatically generated from the AMQP specification.
/// Do not edit.
///

#include "qpid/client/Session_0_10.h"
#include "qpid/framing/all_method_bodies.h"
#include "qpid/client/SessionImpl.h"
#include "qpid/client/MessageImpl.h"
#include "qpid/client/PrivateImplRef.h"
#include "qpid/client/CompletionImpl.h"
#include <boost/intrusive_ptr.hpp>

namespace qpid {
namespace client {
namespace no_keyword {

using namespace framing;

void Session_0_10::executionSync(bool sync) {
    ExecutionSyncBody body(ProtocolVersion(0,10));
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::executionResult(const SequenceNumber& commandId, const std::string& value, bool sync) {
    ExecutionResultBody body(ProtocolVersion(0,10), commandId, value);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::executionException(uint16_t errorCode, const SequenceNumber& commandId, uint8_t classCode, uint8_t commandCode, uint8_t fieldIndex, const std::string& description, const FieldTable& errorInfo, bool sync) {
    ExecutionExceptionBody body(ProtocolVersion(0,10), errorCode, commandId, classCode, commandCode, fieldIndex, description, errorInfo);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageTransfer(const std::string& destination, uint8_t acceptMode, uint8_t acquireMode, const Message& content, bool sync) {
    MessageTransferBody body(ProtocolVersion(0,10), destination, acceptMode, acquireMode);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body, *MessageImpl::get(content)), impl)).wait();
}

void Session_0_10::messageAccept(const SequenceSet& transfers, bool sync) {
    MessageAcceptBody body(ProtocolVersion(0,10), transfers);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageReject(const SequenceSet& transfers, uint16_t code, const std::string& text, bool sync) {
    MessageRejectBody body(ProtocolVersion(0,10), transfers, code, text);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageRelease(const SequenceSet& transfers, bool setRedelivered, bool sync) {
    MessageReleaseBody body(ProtocolVersion(0,10), transfers, setRedelivered);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

qpid::framing::MessageAcquireResult Session_0_10::messageAcquire(const SequenceSet& transfers, bool sync) {
    MessageAcquireBody body(ProtocolVersion(0,10), transfers);
    body.setSync(sync);
    return TypedResult<qpid::framing::MessageAcquireResult>(new CompletionImpl(impl->send(body), impl)).get();
}

qpid::framing::MessageResumeResult Session_0_10::messageResume(const std::string& destination, const std::string& resumeId, bool sync) {
    MessageResumeBody body(ProtocolVersion(0,10), destination, resumeId);
    body.setSync(sync);
    return TypedResult<qpid::framing::MessageResumeResult>(new CompletionImpl(impl->send(body), impl)).get();
}

void Session_0_10::messageSubscribe(const std::string& queue, const std::string& destination, uint8_t acceptMode, uint8_t acquireMode, bool exclusive, const std::string& resumeId, uint64_t resumeTtl, const FieldTable& arguments, bool sync) {
    MessageSubscribeBody body(ProtocolVersion(0,10), queue, destination, acceptMode, acquireMode, exclusive, resumeId, resumeTtl, arguments);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageCancel(const std::string& destination, bool sync) {
    MessageCancelBody body(ProtocolVersion(0,10), destination);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageSetFlowMode(const std::string& destination, uint8_t flowMode, bool sync) {
    MessageSetFlowModeBody body(ProtocolVersion(0,10), destination, flowMode);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageFlow(const std::string& destination, uint8_t unit, uint32_t value, bool sync) {
    MessageFlowBody body(ProtocolVersion(0,10), destination, unit, value);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageFlush(const std::string& destination, bool sync) {
    MessageFlushBody body(ProtocolVersion(0,10), destination);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::messageStop(const std::string& destination, bool sync) {
    MessageStopBody body(ProtocolVersion(0,10), destination);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::txSelect(bool sync) {
    TxSelectBody body(ProtocolVersion(0,10));
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::txCommit(bool sync) {
    TxCommitBody body(ProtocolVersion(0,10));
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::txRollback(bool sync) {
    TxRollbackBody body(ProtocolVersion(0,10));
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::dtxSelect(bool sync) {
    DtxSelectBody body(ProtocolVersion(0,10));
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

qpid::framing::XaResult Session_0_10::dtxStart(const Xid& xid, bool join, bool resume, bool sync) {
    DtxStartBody body(ProtocolVersion(0,10), xid, join, resume);
    body.setSync(sync);
    return TypedResult<qpid::framing::XaResult>(new CompletionImpl(impl->send(body), impl)).get();
}

qpid::framing::XaResult Session_0_10::dtxEnd(const Xid& xid, bool fail, bool suspend, bool sync) {
    DtxEndBody body(ProtocolVersion(0,10), xid, fail, suspend);
    body.setSync(sync);
    return TypedResult<qpid::framing::XaResult>(new CompletionImpl(impl->send(body), impl)).get();
}

qpid::framing::XaResult Session_0_10::dtxCommit(const Xid& xid, bool onePhase, bool sync) {
    DtxCommitBody body(ProtocolVersion(0,10), xid, onePhase);
    body.setSync(sync);
    return TypedResult<qpid::framing::XaResult>(new CompletionImpl(impl->send(body), impl)).get();
}

void Session_0_10::dtxForget(const Xid& xid, bool sync) {
    DtxForgetBody body(ProtocolVersion(0,10), xid);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

qpid::framing::DtxGetTimeoutResult Session_0_10::dtxGetTimeout(const Xid& xid, bool sync) {
    DtxGetTimeoutBody body(ProtocolVersion(0,10), xid);
    body.setSync(sync);
    return TypedResult<qpid::framing::DtxGetTimeoutResult>(new CompletionImpl(impl->send(body), impl)).get();
}

qpid::framing::XaResult Session_0_10::dtxPrepare(const Xid& xid, bool sync) {
    DtxPrepareBody body(ProtocolVersion(0,10), xid);
    body.setSync(sync);
    return TypedResult<qpid::framing::XaResult>(new CompletionImpl(impl->send(body), impl)).get();
}

qpid::framing::DtxRecoverResult Session_0_10::dtxRecover(bool sync) {
    DtxRecoverBody body(ProtocolVersion(0,10));
    body.setSync(sync);
    return TypedResult<qpid::framing::DtxRecoverResult>(new CompletionImpl(impl->send(body), impl)).get();
}

qpid::framing::XaResult Session_0_10::dtxRollback(const Xid& xid, bool sync) {
    DtxRollbackBody body(ProtocolVersion(0,10), xid);
    body.setSync(sync);
    return TypedResult<qpid::framing::XaResult>(new CompletionImpl(impl->send(body), impl)).get();
}

void Session_0_10::dtxSetTimeout(const Xid& xid, uint32_t timeout, bool sync) {
    DtxSetTimeoutBody body(ProtocolVersion(0,10), xid, timeout);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::exchangeDeclare(const std::string& exchange, const std::string& type, const std::string& alternateExchange, bool passive, bool durable, bool autoDelete, const FieldTable& arguments, bool sync) {
    ExchangeDeclareBody body(ProtocolVersion(0,10), exchange, type, alternateExchange, passive, durable, autoDelete, arguments);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::exchangeDelete(const std::string& exchange, bool ifUnused, bool sync) {
    ExchangeDeleteBody body(ProtocolVersion(0,10), exchange, ifUnused);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

qpid::framing::ExchangeQueryResult Session_0_10::exchangeQuery(const std::string& name, bool sync) {
    ExchangeQueryBody body(ProtocolVersion(0,10), name);
    body.setSync(sync);
    return TypedResult<qpid::framing::ExchangeQueryResult>(new CompletionImpl(impl->send(body), impl)).get();
}

void Session_0_10::exchangeBind(const std::string& queue, const std::string& exchange, const std::string& bindingKey, const FieldTable& arguments, bool sync) {
    ExchangeBindBody body(ProtocolVersion(0,10), queue, exchange, bindingKey, arguments);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::exchangeUnbind(const std::string& queue, const std::string& exchange, const std::string& bindingKey, bool sync) {
    ExchangeUnbindBody body(ProtocolVersion(0,10), queue, exchange, bindingKey);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

qpid::framing::ExchangeBoundResult Session_0_10::exchangeBound(const std::string& exchange, const std::string& queue, const std::string& bindingKey, const FieldTable& arguments, bool sync) {
    ExchangeBoundBody body(ProtocolVersion(0,10), exchange, queue, bindingKey, arguments);
    body.setSync(sync);
    return TypedResult<qpid::framing::ExchangeBoundResult>(new CompletionImpl(impl->send(body), impl)).get();
}

void Session_0_10::queueDeclare(const std::string& queue, const std::string& alternateExchange, bool passive, bool durable, bool exclusive, bool autoDelete, const FieldTable& arguments, bool sync) {
    QueueDeclareBody body(ProtocolVersion(0,10), queue, alternateExchange, passive, durable, exclusive, autoDelete, arguments);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::queueDelete(const std::string& queue, bool ifUnused, bool ifEmpty, bool sync) {
    QueueDeleteBody body(ProtocolVersion(0,10), queue, ifUnused, ifEmpty);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

void Session_0_10::queuePurge(const std::string& queue, bool sync) {
    QueuePurgeBody body(ProtocolVersion(0,10), queue);
    body.setSync(sync);
    Completion(new CompletionImpl(impl->send(body), impl)).wait();
}

qpid::framing::QueueQueryResult Session_0_10::queueQuery(const std::string& queue, bool sync) {
    QueueQueryBody body(ProtocolVersion(0,10), queue);
    body.setSync(sync);
    return TypedResult<qpid::framing::QueueQueryResult>(new CompletionImpl(impl->send(body), impl)).get();
}

 Session_0_10::Session_0_10() {}
 Session_0_10::Session_0_10(const SessionBase_0_10& other) {
    *this = other;
}
 Session_0_10& Session_0_10::operator=(const SessionBase_0_10& other) {
    impl = static_cast<const Session_0_10&>(other).impl;
    return *this;
}

}}} // namespace qpid::client::no_keyword

max_stars_repo_name: gcsideal/debian-qpid-cpp

max_issues_repo_name: gcsideal/debian-qpid-cpp

max_forks_repo_name: gcsideal/debian-qpid-cpp


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

/// \brief Unit test for indexed_image type.

#include <boost/test/unit_test.hpp>

#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/toolbox/image_types/indexed_image.hpp>

using namespace std;
using namespace boost;
using namespace gil;

BOOST_AUTO_TEST_SUITE( toolbox_tests )

BOOST_AUTO_TEST_CASE( index_image_test )
{
    {
        indexed_image< uint8_t, rgb8_pixel_t > img( 640, 480 );
        fill_pixels( view( img ), rgb8_pixel_t( 255, 0, 0 ));

        rgb8_pixel_t p = *view( img ).xy_at( 10, 10 );
    }

    {
        typedef indexed_image< gray8_pixel_t, rgb8_pixel_t > image_t;

        image_t img( 640, 480, 256 );

#if __cplusplus >= 201103L
        generate_pixels( img.get_indices_view()
                       , [] () -> uint8_t
                        {
                            static uint8_t i = 0;
                            i = ( i == 256 ) ? 0 : ++i;

                            return gray8_pixel_t( i );
                        }
                       );

        generate_pixels( img.get_palette_view()
                       , [] () ->rgb8_pixel_t
                        {
                            static uint8_t i = 0;
                            i = ( i == 256 ) ? 0 : ++i;

                            return rgb8_pixel_t( i, i, i );
                        }
                       );
#else

        image_t::indices_view_t indices = img.get_indices_view();

        for( image_t::indices_view_t::iterator it = indices.begin(); it != indices.end(); ++it )
        {
            static uint8_t i = 0;
            i = ( i == 256 ) ? 0 : ++i;

            *it = gray8_pixel_t( i );
        }

        image_t::palette_view_t colors = img.get_palette_view();
        for( image_t::palette_view_t::iterator it = colors.begin(); it != colors.end(); ++it )
        {
            static uint8_t i = 0;
            i = ( i == 256 ) ? 0 : ++i;

            *it = rgb8_pixel_t( i, i, i );
        }
#endif

        gray8_pixel_t index = *img.get_indices_view().xy_at( 10   , 1 );
        rgb8_pixel_t  color = *img.get_palette_view().xy_at( index, 0 );

        rgb8_pixel_t p = *view( img ).xy_at( 10, 1 );
    }

    {
        typedef indexed_image< gray8_pixel_t, rgb8_pixel_t > image_t;
        image_t img( 640, 480, 256 );

#if __cplusplus >= 201103L
        generate_pixels( img.get_indices_view()
                       , [] () -> uint8_t
                       {
                            static uint8_t i = 0;
                            i = ( i == 256 ) ? 0 : ++i;

                            return i;
                       }
                       );

        generate_pixels( img.get_palette_view()
                       , [] () ->rgb8_pixel_t
                       {
                          static uint8_t i = 0;
                          i = ( i == 256 ) ? 0 : ++i;

                          return rgb8_pixel_t( i, i, i );
                       }
                       );
#else
        image_t::indices_view_t indices = img.get_indices_view();
        for( image_t::indices_view_t::iterator it = indices.begin(); it != indices.end(); ++it )
        {
            static uint8_t i = 0;
            i = ( i == 256 ) ? 0 : ++i;

            *it = gray8_pixel_t( i );
        }

        image_t::palette_view_t colors = img.get_palette_view();
        for( image_t::palette_view_t::iterator it = colors.begin(); it != colors.end(); ++it )
        {
            static uint8_t i = 0;
            i = ( i == 256 ) ? 0 : ++i;

            *it = rgb8_pixel_t( i, i, i );
        }
#endif

        uint8_t      index = *img.get_indices_view().xy_at( 10   , 1 );
        rgb8_pixel_t color = *img.get_palette_view().xy_at( index, 0 );

        rgb8_pixel_t p = *view( img ).xy_at( 10, 1 );
    }

    {
        typedef indexed_image< uint8_t, rgb8_pixel_t > image_t;
        image_t img( 640, 480, 256 );

        for( image_t::y_coord_t y = 0; y < view( img ).height(); ++y )
        {
            image_t::view_t::x_iterator it = view( img ).row_begin( y );

            for( image_t::x_coord_t x = 0; x < view( img ).width(); ++x )
            {
                rgb8_pixel_t p = *it;
                it++;
            }
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text:
/****************************************************************************
 * Copyright (c) 2012-2019 by the ArborX authors                            *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the ArborX library. ArborX is                       *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/

#include "ArborX_EnableDeviceTypes.hpp" // ARBORX_DEVICE_TYPES
#include "ArborX_EnableViewComparison.hpp"
#include <ArborX_DetailsDistributedSearchTreeImpl.hpp>

#include <boost/test/unit_test.hpp>

#define BOOST_TEST_MODULE DetailsDistributedSearchTreeImpl

#include <algorithm> // fill
#include <set>
#include <vector>

namespace tt = boost::test_tools;

BOOST_AUTO_TEST_CASE_TEMPLATE(sort_results, DeviceType, ARBORX_DEVICE_TYPES)
{
  std::vector<int> ids_ = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};
  std::vector<int> sorted_ids = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4};
  std::vector<int> offset = {0, 1, 3, 6, 10};
  int const n = 10;
  int const m = 4;
  BOOST_TEST(ids_.size() == n);
  BOOST_TEST(sorted_ids.size() == n);
  BOOST_TEST(offset.size() == m + 1);
  std::vector<int> results_ = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
  std::vector<std::set<int>> sorted_results = {
      {3},
      {6, 2},
      {8, 5, 1},
      {9, 7, 4, 0},
  };
  std::vector<int> ranks_ = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19};
  std::vector<std::set<int>> sorted_ranks = {
      {13},
      {16, 12},
      {18, 15, 11},
      {19, 17, 14, 10},
  };
  BOOST_TEST(results_.size() == n);
  BOOST_TEST(ranks_.size() == n);

  Kokkos::View<int *, DeviceType> ids("query_ids", n);
  auto ids_host = Kokkos::create_mirror_view(ids);
  for (int i = 0; i < n; ++i)
    ids_host(i) = ids_[i];
  Kokkos::deep_copy(ids, ids_host);

  Kokkos::View<int *, DeviceType> results("results", n);
  auto results_host = Kokkos::create_mirror_view(results);
  for (int i = 0; i < n; ++i)
    results_host(i) = results_[i];
  Kokkos::deep_copy(results, results_host);

  Kokkos::View<int *, DeviceType> ranks("ranks", n);
  auto ranks_host = Kokkos::create_mirror_view(ranks);
  for (int i = 0; i < n; ++i)
    ranks_host(i) = ranks_[i];
  Kokkos::deep_copy(ranks, ranks_host);

  ArborX::Details::DistributedSearchTreeImpl<DeviceType>::sortResults(
      ids, results, ranks);

  // COMMENT: ids are untouched
  Kokkos::deep_copy(ids_host, ids);
  BOOST_TEST(ids_host == ids_, tt::per_element());

  Kokkos::deep_copy(results_host, results);
  Kokkos::deep_copy(ranks_host, ranks);
  for (int q = 0; q < m; ++q)
    for (int i = offset[q]; i < offset[q + 1]; ++i)
    {
      BOOST_TEST(sorted_results[q].count(results_host[i]) == 1);
      BOOST_TEST(sorted_ranks[q].count(ranks_host[i]) == 1);
    }

  Kokkos::View<int *, DeviceType> not_sized_properly("", m);
  BOOST_CHECK_THROW(
      ArborX::Details::DistributedSearchTreeImpl<DeviceType>::sortResults(
          ids, not_sized_properly),
      ArborX::SearchException);
}

BOOST_AUTO_TEST_CASE_TEMPLATE(count_results, DeviceType, ARBORX_DEVICE_TYPES)
{
  std::vector<int> ids_ref = {4, 3, 2, 1, 4, 3, 2, 4, 3, 4};
  std::vector<int> offset_ref = {
      0, 0, 1, 3, 6, 10,
  };
  int const m = 5;
  int const nnz = 10;
  BOOST_TEST(ids_ref.size() == nnz);
  BOOST_TEST(offset_ref.size() == m + 1);

  Kokkos::View<int *, DeviceType> ids("query_ids", nnz);
  auto ids_host = Kokkos::create_mirror_view(ids);
  for (int i = 0; i < nnz; ++i)
    ids_host(i) = ids_ref[i];
  Kokkos::deep_copy(ids, ids_host);

  Kokkos::View<int *, DeviceType> offset("offset", m);

  ArborX::Details::DistributedSearchTreeImpl<DeviceType>::countResults(m, ids,
                                                                       offset);

  auto offset_host = Kokkos::create_mirror_view(offset);
  Kokkos::deep_copy(offset_host, offset);
  BOOST_TEST(offset_host == offset_ref, tt::per_element());
}

template <typename View1, typename View2>
inline void checkViewWasNotAllocated(View1 const &v1, View2 const &v2)
{
  // NOTE: cannot use operator== here because array layout may "change" for
  // rank-1 views
  BOOST_TEST(v1.data() == v2.data());
  BOOST_TEST(v1.span() == v2.span());

  BOOST_TEST((int)View1::rank == (int)View2::rank);
  BOOST_TEST((std::is_same<typename View1::const_value_type,
                           typename View2::const_value_type>::value));
  BOOST_TEST((std::is_same<typename View1::memory_space,
                           typename View2::memory_space>::value));

  BOOST_TEST(v1.extent(0) == v2.extent(0));
  BOOST_TEST(v1.extent(1) == v2.extent(1));
  BOOST_TEST(v1.extent(2) == v2.extent(2));
  BOOST_TEST(v1.extent(3) == v2.extent(3));
  BOOST_TEST(v1.extent(4) == v2.extent(4));
  BOOST_TEST(v1.extent(5) == v2.extent(5));
  BOOST_TEST(v1.extent(6) == v2.extent(6));
  BOOST_TEST(v1.extent(7) == v2.extent(7));
}

template <typename View1, typename View2>
inline void checkNewViewWasAllocated(View1 const &v1, View2 const &v2)
{
  BOOST_TEST(v1.data() != v2.data());

  BOOST_TEST((int)View1::rank == (int)View2::rank);
  BOOST_TEST((std::is_same<typename View1::const_value_type,
                           typename View2::const_value_type>::value));

  BOOST_TEST(v1.extent(0) == v2.extent(0));
  BOOST_TEST(v1.extent(1) == v2.extent(1));
  BOOST_TEST(v1.extent(2) == v2.extent(2));
  BOOST_TEST(v1.extent(3) == v2.extent(3));
  BOOST_TEST(v1.extent(4) == v2.extent(4));
  BOOST_TEST(v1.extent(5) == v2.extent(5));
  BOOST_TEST(v1.extent(6) == v2.extent(6));
  BOOST_TEST(v1.extent(7) == v2.extent(7));
}

BOOST_AUTO_TEST_CASE_TEMPLATE(create_layout_right_mirror_view, DeviceType,
                              ARBORX_DEVICE_TYPES)
{
  using ArborX::Details::create_layout_right_mirror_view;
  using Kokkos::ALL;
  using Kokkos::LayoutLeft;
  using Kokkos::LayoutRight;
  using Kokkos::make_pair;
  using Kokkos::subview;
  using Kokkos::View;

  if (!Kokkos::Impl::SpaceAccessibility<
          Kokkos::HostSpace, typename DeviceType::memory_space>::accessible)
    return;

  // rank-1 and not strided -> do not allocate
  View<int *, LayoutLeft, DeviceType> u("u", 255);
  auto u_h = create_layout_right_mirror_view(u);
  checkViewWasNotAllocated(u, u_h);

  // right layout -> do not allocate
  View<int **, LayoutRight, DeviceType> v("v", 2, 3);
  auto v_h = create_layout_right_mirror_view(v);
  checkViewWasNotAllocated(v, v_h);

  // the same with compile time size
  View<int[2][3], LayoutRight, DeviceType> v_c("v");
  auto v_c_h = create_layout_right_mirror_view(v_c);
  checkViewWasNotAllocated(v_c, v_c_h);

  // left layout and rank > 1 -> allocate
  View<int **, LayoutLeft, DeviceType> w("w", 4, 5);
  auto w_h = create_layout_right_mirror_view(w);
  checkNewViewWasAllocated(w, w_h);

  // the same with compile time size
  View<int * [5], LayoutLeft, DeviceType> w_c("v", 4);
  auto w_c_h = create_layout_right_mirror_view(w_c);
  checkNewViewWasAllocated(w_c, w_c_h);

  // strided layout -> allocate
  auto x = subview(v, ALL, 0);
  auto x_h = create_layout_right_mirror_view(x);
  checkNewViewWasAllocated(x, x_h);

  // subview is rank-1 and not strided -> do not allocate
  auto y = subview(u, make_pair(8, 16));
  auto y_h = create_layout_right_mirror_view(y);
  checkViewWasNotAllocated(y, y_h);
}

void checkBufferLayout(std::vector<int> const &ranks,
                       std::vector<int> const &permute_ref,
                       std::vector<int> const &unique_ref,
                       std::vector<int> const &counts_ref,
                       std::vector<int> const &offsets_ref)
{
  std::vector<int> permute(ranks.size());
  std::vector<int> unique;
  std::vector<int> counts;
  std::vector<int> offsets;
  ArborX::Details::sortAndDetermineBufferLayout(
      Kokkos::View<int const *, Kokkos::HostSpace,
                   Kokkos::MemoryTraits<Kokkos::Unmanaged>>(ranks.data(),
                                                            ranks.size()),
      Kokkos::View<int *, Kokkos::HostSpace,
                   Kokkos::MemoryTraits<Kokkos::Unmanaged>>(permute.data(),
                                                            permute.size()),
      unique, counts, offsets);
  BOOST_TEST(permute_ref == permute, tt::per_element());
  BOOST_TEST(unique_ref == unique, tt::per_element());
  BOOST_TEST(counts_ref == counts, tt::per_element());
  BOOST_TEST(offsets_ref == offsets, tt::per_element());
}

BOOST_AUTO_TEST_CASE(sort_and_determine_buffer_layout)
{
  checkBufferLayout({}, {}, {}, {}, {0});
  checkBufferLayout({2, 2}, {0, 1}, {2}, {2}, {0, 2});
  checkBufferLayout({3, 3, 2, 3, 2, 1}, {0, 1, 3, 2, 4, 5}, {3, 2, 1},
                    {3, 2, 1}, {0, 3, 5, 6});
  checkBufferLayout({1, 2, 3, 2, 3, 3}, {5, 3, 0, 4, 1, 2}, {3, 2, 1},
                    {3, 2, 1}, {0, 3, 5, 6});
  checkBufferLayout({0, 1, 2, 3}, {3, 2, 1, 0}, {3, 2, 1, 0}, {1, 1, 1, 1},
                    {0, 1, 2, 3, 4});
}

BOOST_AUTO_TEST_CASE(pointer_depth)
{
  static_assert(ArborX::Details::internal::PointerDepth<double>::value == 0,
                "Failing for double");
  static_assert(ArborX::Details::internal::PointerDepth<double *>::value == 1,
                "Failing for double*");
  static_assert(ArborX::Details::internal::PointerDepth<double[2]>::value == 0,
                "Failing for double[2]");
  static_assert(ArborX::Details::internal::PointerDepth<double **>::value == 2,
                "Failing for double**");
  static_assert(ArborX::Details::internal::PointerDepth<double * [2]>::value ==
                    1,
                "Failing for double*[2]");
  static_assert(ArborX::Details::internal::PointerDepth<double[2][3]>::value ==
                    0,
                "Failing for double[2][3]");
  static_assert(ArborX::Details::internal::PointerDepth<double ***>::value == 3,
                "Failing for double***");
  static_assert(
      ArborX::Details::internal::PointerDepth<double * * [2]>::value == 2,
      "Failing for double[2]");
  static_assert(
      ArborX::Details::internal::PointerDepth<double * [2][3]>::value == 1,
      "Failing for double*[2][3]");
  static_assert(
      ArborX::Details::internal::PointerDepth<double[2][3][4]>::value == 0,
      "Failing for double[2][3][4]");
}

max_stars_repo_name: anagainaru/ArborX

max_issues_repo_name: anagainaru/ArborX

max_forks_repo_name: anagainaru/ArborX


text:
//
// io_service.hpp
// ~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_ASIO_IO_SERVICE_HPP
#define BOOST_ASIO_IO_SERVICE_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/push_options.hpp>

#include <boost/asio/detail/push_options.hpp>
#include <cstddef>
#include <stdexcept>
#include <typeinfo>
#include <boost/config.hpp>
#include <boost/throw_exception.hpp>
#include <boost/system/error_code.hpp>
#include <boost/asio/detail/pop_options.hpp>

#include <boost/asio/detail/dev_poll_reactor_fwd.hpp>
#include <boost/asio/detail/epoll_reactor_fwd.hpp>
#include <boost/asio/detail/kqueue_reactor_fwd.hpp>
#include <boost/asio/detail/noncopyable.hpp>
#include <boost/asio/detail/select_reactor_fwd.hpp>
#include <boost/asio/detail/service_registry_fwd.hpp>
#include <boost/asio/detail/signal_init.hpp>
#include <boost/asio/detail/task_io_service_fwd.hpp>
#include <boost/asio/detail/win_iocp_io_service_fwd.hpp>
#include <boost/asio/detail/winsock_init.hpp>
#include <boost/asio/detail/wrapped_handler.hpp>

namespace boost {
namespace asio {

class io_service;
template <typename Service> Service& use_service(io_service& ios);
template <typename Service> void add_service(io_service& ios, Service* svc);
template <typename Service> bool has_service(io_service& ios);

/// Provides core I/O functionality.
/**
 * The io_service class provides the core I/O functionality for users of the
 * asynchronous I/O objects, including:
 *
 * @li boost::asio::ip::tcp::socket
 * @li boost::asio::ip::tcp::acceptor
 * @li boost::asio::ip::udp::socket
 * @li boost::asio::deadline_timer.
 *
 * The io_service class also includes facilities intended for developers of
 * custom asynchronous services.
 *
 * @par Thread Safety
 * @e Distinct @e objects: Safe.@n
 * @e Shared @e objects: Safe, with the exception that calling reset()
 * while there are unfinished run() calls results in undefined behaviour.
 *
 * @par Concepts:
 * Dispatcher.
 *
 * @par Effect of exceptions thrown from handlers
 *
 * If an exception is thrown from a handler, the exception is allowed to
 * propagate through the throwing thread's invocation of
 * boost::asio::io_service::run(), boost::asio::io_service::run_one(),
 * boost::asio::io_service::poll() or boost::asio::io_service::poll_one().
 * No other threads that are calling any of these functions are affected. It is
 * then the responsibility of the application to catch the exception.
 *
 * After the exception has been caught, the
 * boost::asio::io_service::run(), boost::asio::io_service::run_one(),
 * boost::asio::io_service::poll() or boost::asio::io_service::poll_one()
 * call may be restarted @em without the need for an intervening call to
 * boost::asio::io_service::reset(). This allows the thread to rejoin the
 * io_service's thread pool without impacting any other threads in the pool.
 *
 * For example:
 *
 * @code
 * boost::asio::io_service io_service;
 * ...
 * for (;;)
 * {
 *   try
 *   {
 *     io_service.run();
 *     break; // run() exited normally
 *   }
 *   catch (my_exception& e)
 *   {
 *     // Deal with exception as appropriate.
 *   }
 * }
 * @endcode
 *
 * @par Stopping the io_service from running out of work
 *
 * Some applications may need to prevent an io_service's run() call from
 * returning when there is no more work to do. For example, the io_service may
 * be being run in a background thread that is launched prior to the
 * application's asynchronous operations. The run() call may be kept running by
 * creating an object of type boost::asio::io_service::work:
 *
 * @code boost::asio::io_service io_service;
 * boost::asio::io_service::work work(io_service);
 * ... @endcode
 *
 * To effect a shutdown, the application will then need to call the io_service's
 * stop() member function. This will cause the io_service run() call to return
 * as soon as possible, abandoning unfinished operations and without permitting
 * ready handlers to be dispatched.
 *
 * Alternatively, if the application requires that all operations and handlers
 * be allowed to finish normally, the work object may be explicitly destroyed.
 *
 * @code boost::asio::io_service io_service;
 * auto_ptr<boost::asio::io_service::work> work(
 *     new boost::asio::io_service::work(io_service));
 * ...
 * work.reset(); // Allow run() to exit. @endcode
 */
class io_service
  : private noncopyable
{
private:
  // The type of the platform-specific implementation.
#if defined(BOOST_ASIO_HAS_IOCP)
  typedef detail::win_iocp_io_service impl_type;
#elif defined(BOOST_ASIO_HAS_EPOLL)
  typedef detail::task_io_service<detail::epoll_reactor<false> > impl_type;
#elif defined(BOOST_ASIO_HAS_KQUEUE)
  typedef detail::task_io_service<detail::kqueue_reactor<false> > impl_type;
#elif defined(BOOST_ASIO_HAS_DEV_POLL)
  typedef detail::task_io_service<detail::dev_poll_reactor<false> > impl_type;
#else
  typedef detail::task_io_service<detail::select_reactor<false> > impl_type;
#endif

public:
  class work;
  friend class work;

  class id;

  class service;

  class strand;

  /// Constructor.
  io_service();

  /// Constructor.
  /**
   * Construct with a hint about the required level of concurrency.
   *
   * @param concurrency_hint A suggestion to the implementation on how many
   * threads it should allow to run simultaneously.
   */
  explicit io_service(std::size_t concurrency_hint);

  /// Destructor.
  ~io_service();

  /// Run the io_service's event processing loop.
  /**
   * The run() function blocks until all work has finished and there are no
   * more handlers to be dispatched, or until the io_service has been stopped.
   *
   * Multiple threads may call the run() function to set up a pool of threads
   * from which the io_service may execute handlers. All threads that are
   * waiting in the pool are equivalent and the io_service may choose any one
   * of them to invoke a handler.
   *
   * The run() function may be safely called again once it has completed only
   * after a call to reset().
   *
   * @return The number of handlers that were executed.
   *
   * @throws boost::system::system_error Thrown on failure.
   *
   * @note The poll() function may also be used to dispatch ready handlers,
   * but without blocking.
   */
  std::size_t run();

  /// Run the io_service's event processing loop.
  /**
   * The run() function blocks until all work has finished and there are no
   * more handlers to be dispatched, or until the io_service has been stopped.
   *
   * Multiple threads may call the run() function to set up a pool of threads
   * from which the io_service may execute handlers. All threads that are
   * waiting in the pool are equivalent and the io_service may choose any one
   * of them to invoke a handler.
   *
   * The run() function may be safely called again once it has completed only
   * after a call to reset().
   *
   * @param ec Set to indicate what error occurred, if any.
   *
   * @return The number of handlers that were executed.
   *
   * @note The poll() function may also be used to dispatch ready handlers,
   * but without blocking.
   */
  std::size_t run(boost::system::error_code& ec);

  /// Run the io_service's event processing loop to execute at most one handler.
  /**
   * The run_one() function blocks until one handler has been dispatched, or
   * until the io_service has been stopped.
   *
   * @return The number of handlers that were executed.
   *
   * @throws boost::system::system_error Thrown on failure.
   */
  std::size_t run_one();

  /// Run the io_service's event processing loop to execute at most one handler.
  /**
   * The run_one() function blocks until one handler has been dispatched, or
   * until the io_service has been stopped.
   *
   * @param ec Set to indicate what error occurred, if any.
   *
   * @return The number of handlers that were executed.
   */
  std::size_t run_one(boost::system::error_code& ec);

  /// Run the io_service's event processing loop to execute ready handlers.
  /**
   * The poll() function runs handlers that are ready to run, without blocking,
   * until the io_service has been stopped or there are no more ready handlers.
   *
   * @return The number of handlers that were executed.
   *
   * @throws boost::system::system_error Thrown on failure.
   */
  std::size_t poll();

  /// Run the io_service's event processing loop to execute ready handlers.
  /**
   * The poll() function runs handlers that are ready to run, without blocking,
   * until the io_service has been stopped or there are no more ready handlers.
   *
   * @param ec Set to indicate what error occurred, if any.
   *
   * @return The number of handlers that were executed.
   */
  std::size_t poll(boost::system::error_code& ec);

  /// Run the io_service's event processing loop to execute one ready handler.
  /**
   * The poll_one() function runs at most one handler that is ready to run,
   * without blocking.
   *
   * @return The number of handlers that were executed.
   *
   * @throws boost::system::system_error Thrown on failure.
   */
  std::size_t poll_one();

  /// Run the io_service's event processing loop to execute one ready handler.
  /**
   * The poll_one() function runs at most one handler that is ready to run,
   * without blocking.
   *
   * @param ec Set to indicate what error occurred, if any.
   *
   * @return The number of handlers that were executed.
   */
  std::size_t poll_one(boost::system::error_code& ec);

  /// Stop the io_service's event processing loop.
  /**
   * This function does not block, but instead simply signals the io_service to
   * stop. All invocations of its run() or run_one() member functions should
   * return as soon as possible. Subsequent calls to run(), run_one(), poll()
   * or poll_one() will return immediately until reset() is called.
   */
  void stop();

  /// Reset the io_service in preparation for a subsequent run() invocation.
  /**
   * This function must be called prior to any second or later set of
   * invocations of the run(), run_one(), poll() or poll_one() functions when a
   * previous invocation of these functions returned due to the io_service
   * being stopped or running out of work. This function allows the io_service
   * to reset any internal state, such as a "stopped" flag.
   *
   * This function must not be called while there are any unfinished calls to
   * the run(), run_one(), poll() or poll_one() functions.
   */
  void reset();

  /// Request the io_service to invoke the given handler.
  /**
   * This function is used to ask the io_service to execute the given handler.
   *
   * The io_service guarantees that the handler will only be called in a thread
   * in which the run(), run_one(), poll() or poll_one() member functions is
   * currently being invoked. The handler may be executed inside this function
   * if the guarantee can be met.
   *
   * @param handler The handler to be called. The io_service will make
   * a copy of the handler object as required. The function signature of the
   * handler must be: @code void handler(); @endcode
   */
  template <typename CompletionHandler>
  void dispatch(CompletionHandler handler);

  /// Request the io_service to invoke the given handler and return immediately.
  /**
   * This function is used to ask the io_service to execute the given handler,
   * but without allowing the io_service to call the handler from inside this
   * function.
   *
   * The io_service guarantees that the handler will only be called in a thread
   * in which the run(), run_one(), poll() or poll_one() member functions is
   * currently being invoked.
   *
   * @param handler The handler to be called. The io_service will make
   * a copy of the handler object as required. The function signature of the
   * handler must be: @code void handler(); @endcode
   */
  template <typename CompletionHandler>
  void post(CompletionHandler handler);

  /// Create a new handler that automatically dispatches the wrapped handler
  /// on the io_service.
  /**
   * This function is used to create a new handler function object that, when
   * invoked, will automatically pass the wrapped handler to the io_service's
   * dispatch function.
   *
   * @param handler The handler to be wrapped. The io_service will make a copy
   * of the handler object as required. The function signature of the handler
   * must be: @code void handler(A1 a1, ... An an); @endcode
   *
   * @return A function object that, when invoked, passes the wrapped handler to
   * the io_service's dispatch function. Given a function object with the
   * signature:
   * @code R f(A1 a1, ... An an); @endcode
   * If this function object is passed to the wrap function like so:
   * @code io_service.wrap(f); @endcode
   * then the return value is a function object with the signature
   * @code void g(A1 a1, ... An an); @endcode
   * that, when invoked, executes code equivalent to:
   * @code io_service.dispatch(boost::bind(f, a1, ... an)); @endcode
   */
  template <typename Handler>
#if defined(GENERATING_DOCUMENTATION)
  unspecified
#else
  detail::wrapped_handler<io_service&, Handler>
#endif
  wrap(Handler handler);

  /// Obtain the service object corresponding to the given type.
  /**
   * This function is used to locate a service object that corresponds to
   * the given service type. If there is no existing implementation of the
   * service, then the io_service will create a new instance of the service.
   *
   * @param ios The io_service object that owns the service.
   *
   * @return The service interface implementing the specified service type.
   * Ownership of the service interface is not transferred to the caller.
   */
  template <typename Service>
  friend Service& use_service(io_service& ios);

  /// Add a service object to the io_service.
  /**
   * This function is used to add a service to the io_service.
   *
   * @param ios The io_service object that owns the service.
   *
   * @param svc The service object. On success, ownership of the service object
   * is transferred to the io_service. When the io_service object is destroyed,
   * it will destroy the service object by performing:
   * @code delete static_cast<io_service::service*>(svc) @endcode
   *
   * @throws boost::asio::service_already_exists Thrown if a service of the
   * given type is already present in the io_service.
   *
   * @throws boost::asio::invalid_service_owner Thrown if the service's owning
   * io_service is not the io_service object specified by the ios parameter.
   */
  template <typename Service>
  friend void add_service(io_service& ios, Service* svc);

  /// Determine if an io_service contains a specified service type.
  /**
   * This function is used to determine whether the io_service contains a
   * service object corresponding to the given service type.
   *
   * @param ios The io_service object that owns the service.
   *
   * @return A boolean indicating whether the io_service contains the service.
   */
  template <typename Service>
  friend bool has_service(io_service& ios);

private:
#if defined(BOOST_WINDOWS) || defined(__CYGWIN__)
  detail::winsock_init<> init_;
#elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \
  || defined(__osf__)
  detail::signal_init<> init_;
#endif

  // The service registry.
  boost::asio::detail::service_registry* service_registry_;

  // The implementation.
  impl_type& impl_;
};

/// Class to inform the io_service when it has work to do.
/**
 * The work class is used to inform the io_service when work starts and
 * finishes. This ensures that the io_service's run() function will not exit
 * while work is underway, and that it does exit when there is no unfinished
 * work remaining.
 *
 * The work class is copy-constructible so that it may be used as a data member
 * in a handler class. It is not assignable.
 */
class io_service::work
{
public:
  /// Constructor notifies the io_service that work is starting.
  /**
   * The constructor is used to inform the io_service that some work has begun.
   * This ensures that the io_service's run() function will not exit while the
   * work is underway.
   */
  explicit work(boost::asio::io_service& io_service);

  /// Copy constructor notifies the io_service that work is starting.
  /**
   * The constructor is used to inform the io_service that some work has begun.
   * This ensures that the io_service's run() function will not exit while the
   * work is underway.
   */
  work(const work& other);

  /// Destructor notifies the io_service that the work is complete.
  /**
   * The destructor is used to inform the io_service that some work has
   * finished. Once the count of unfinished work reaches zero, the io_service's
   * run() function is permitted to exit.
   */
  ~work();

  /// (Deprecated: use get_io_service().) Get the io_service associated with the
  /// work.
  boost::asio::io_service& io_service();

  /// Get the io_service associated with the work.
  boost::asio::io_service& get_io_service();

private:
  // Prevent assignment.
  void operator=(const work& other);

  // The io_service.
  boost::asio::io_service& io_service_;
};

/// Class used to uniquely identify a service.
class io_service::id
  : private noncopyable
{
public:
  /// Constructor.
  id() {}
};

/// Base class for all io_service services.
class io_service::service
  : private noncopyable
{
public:
  /// (Deprecated: use get_io_service().) Get the io_service object that owns
  /// the service.
  boost::asio::io_service& io_service();

  /// Get the io_service object that owns the service.
  boost::asio::io_service& get_io_service();

protected:
  /// Constructor.
  /**
   * @param owner The io_service object that owns the service.
   */
  service(boost::asio::io_service& owner);

  /// Destructor.
  virtual ~service();

private:
  /// Destroy all user-defined handler objects owned by the service.
  virtual void shutdown_service() = 0;

  friend class boost::asio::detail::service_registry;
  boost::asio::io_service& owner_;
  const std::type_info* type_info_;
  const boost::asio::io_service::id* id_;
  service* next_;
};

/// Exception thrown when trying to add a duplicate service to an io_service.
class service_already_exists
  : public std::logic_error
{
public:
  service_already_exists()
    : std::logic_error("Service already exists.")
  {
  }
};

/// Exception thrown when trying to add a service object to an io_service where
/// the service has a different owner.
class invalid_service_owner
  : public std::logic_error
{
public:
  invalid_service_owner()
    : std::logic_error("Invalid service owner.")
  {
  }
};

} // namespace asio
} // namespace boost

#include <boost/asio/impl/io_service.ipp>

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_IO_SERVICE_HPP

max_stars_repo_name: jaredhoberock/gotham

max_issues_repo_name: jaredhoberock/gotham

max_forks_repo_name: jaredhoberock/gotham