text:
//此源码被清华学神尹成大魔王专业翻译分析并修改
//尹成QQ77025077
//尹成微信18510341407
//尹成所在QQ群721929980
//尹成邮箱 yinc13@mails.tsinghua.edu.cn
//尹成毕业于清华大学,微软区块链领域全球最有价值专家
//https://mvp.microsoft.com/zh-cn/PublicProfile/4033620
//————————————————————————————————————————————————————————————————————————————————————————————————————————————————
/*
    此文件是Rippled的一部分：https://github.com/ripple/rippled
    版权所有（c）2016 Ripple Labs Inc.

    使用、复制、修改和/或分发本软件的权限
    特此授予免费或不收费的目的，前提是
    版权声明和本许可声明出现在所有副本中。

    本软件按“原样”提供，作者不作任何保证。
    关于本软件，包括
    适销性和适用性。在任何情况下，作者都不对
    任何特殊、直接、间接或后果性损害或任何损害
    因使用、数据或利润损失而导致的任何情况，无论是在
    合同行为、疏忽或其他侵权行为
    或与本软件的使用或性能有关。
**/

//==============================================================

#include <ripple/basics/contract.h>
#include <ripple/conditions/Condition.h>
#include <ripple/conditions/Fulfillment.h>
#include <ripple/conditions/impl/PreimageSha256.h>
#include <ripple/conditions/impl/utils.h>
#include <boost/regex.hpp>
#include <boost/optional.hpp>
#include <vector>
#include <iostream>

namespace ripple {
namespace cryptoconditions {

namespace detail {
//条件的二进制编码根据其
//类型。所有类型至少定义一个指纹和成本
//子场。一些类型，例如复合条件
//类型，定义需要的其他子字段
//传递密码条件的基本属性（例如
//作为子条件在
//化合物类型）。
//
//条件编码如下：
//
//条件：：=选择
//预成像256[0]单工256条件，
//PrefixSha256[1]复合材料256条件，
//阈值256[2]复合256条件，
//RSASHA256[3]单工256条件，
//ED25519SHA256[4]单工256条件
//}
//
//单工256条件：：=顺序
//指纹八位字节字符串（大小（32）），
//成本整数（0..4294967295）
//}
//
//复合材料256条件：：=序列
//指纹八位字节字符串（大小（32）），
//成本整数（0..4294967295）
//子类型条件类型
//}
//
//条件类型：：=位字符串
//预成像256（0），
//前缀256（1）
//阈值256（2）
//RSASHA256（3）
//ED25519SHA256（4）
//}

constexpr std::size_t fingerprintSize = 32;

std::unique_ptr<Condition>
loadSimpleSha256(Type type, Slice s, std::error_code& ec)
{
    using namespace der;

    auto p = parsePreamble(s, ec);

    if (ec)
        return {};

    if (!isPrimitive(p) || !isContextSpecific(p))
    {
        ec = error::incorrect_encoding;
        return {};
    }

    if (p.tag != 0)
    {
        ec = error::unexpected_tag;
        return {};
    }

    if (p.length != fingerprintSize)
    {
        ec = error::fingerprint_size;
        return {};
    }

    Buffer b = parseOctetString(s, p.length, ec);

    if (ec)
        return {};

    p = parsePreamble(s, ec);

    if (ec)
        return {};

    if (!isPrimitive(p) || !isContextSpecific(p))
    {
        ec = error::malformed_encoding;
        return{};
    }

    if (p.tag != 1)
    {
        ec = error::unexpected_tag;
        return {};
    }

    auto cost = parseInteger<std::uint32_t>(s, p.length, ec);

    if (ec)
        return {};

    if (!s.empty())
    {
        ec = error::trailing_garbage;
        return {};
    }

    switch (type)
    {
    case Type::preimageSha256:
        if (cost > PreimageSha256::maxPreimageLength)
        {
            ec = error::preimage_too_long;
            return {};
        }
        break;

    default:
        break;
    }

    return std::make_unique<Condition>(type, cost, std::move(b));
}

}

std::unique_ptr<Condition>
Condition::deserialize(Slice s, std::error_code& ec)
{
//根据RFC，在某种情况下，我们选择基于类型的
//在项目的标签上，我们包含：
//
//条件：：=选择
//预成像256[0]单工256条件，
//PrefixSha256[1]复合材料256条件，
//阈值256[2]复合256条件，
//RSASHA256[3]单工256条件，
//ED25519SHA256[4]单工256条件
//}
    if (s.empty())
    {
        ec = error::buffer_empty;
        return {};
    }

    using namespace der;

    auto const p = parsePreamble(s, ec);
    if (ec)
        return {};

//所有实现都是上下文特定的、构造的
//类型
    if (!isConstructed(p) || !isContextSpecific(p))
    {
        ec = error::malformed_encoding;
        return {};
    }

    if (p.length > s.size())
    {
        ec = error::buffer_underfull;
        return {};
    }

    if (s.size() > maxSerializedCondition)
    {
        ec = error::large_size;
        return {};
    }

    std::unique_ptr<Condition> c;

    switch (p.tag)
    {
case 0: //预兆HA256
        c = detail::loadSimpleSha256(
            Type::preimageSha256,
            Slice(s.data(), p.length), ec);
        if (!ec)
            s += p.length;
        break;

case 1: //PrimSux256
        ec = error::unsupported_type;
        return {};

case 2: //阈下SAH256
        ec = error::unsupported_type;
        return {};

case 3: //RSASH256
        ec = error::unsupported_type;
        return {};

case 4: //ED25519SAH256
        ec = error::unsupported_type;
        return {};

    default:
        ec = error::unknown_type;
        return {};
    }

    if (!s.empty())
    {
        ec = error::trailing_garbage;
        return {};
    }

    return c;
}

}
}

max_stars_repo_name: yinchengtsinghua/RippleCPPChinese

max_issues_repo_name: yinchengtsinghua/RippleCPPChinese

max_forks_repo_name: yinchengtsinghua/RippleCPPChinese


text:
/**************************************************************************\
 *   This file is part of CaSPER.                                          *
 *                                                                         *
 *   Copyright:                                                            *
 *   2009-2009 - Marco Correia <marco.v.correia@gmail.com>           *
 *                                                                         *
 *   Licensed under the Apache License, Version 2.0 (the "License");       *
 *   you may not use this file except in compliance with the License.      *
 *   You may obtain a copy of the License at                               *
 *            http://www.apache.org/licenses/LICENSE-2.0                   *
 *   Unless required by applicable law or agreed to in writing, software   *
 *   distributed under the License is distributed on an                    *
 *   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,          *
 *   either express or implied.                                            *
 *   See the License for the specific language governing permissions and   *
 *   limitations under the License.                                        *
 \*************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <libxml++/libxml++.h>

#include <bindings/cpp/cpp.h>
#include <bindings/cpp/print.h> // tmp
#include <list>

#include <boost/algorithm/string.hpp>

#include <boost/xpressive/xpressive.hpp> // must be here
#include "exprparser.h"

// Parameterized predicates
struct ParPredicate
{
	std::string pars;
	std::string expr;
	ParPredicate(const std::string& pars, const std::string& expr) :
		pars(pars),expr(expr) {}
	casperbind::cpp::SharedSymbol generateConstraint(const casperbind::cpp::SymbolArray& pars);
};

casperbind::cpp::SharedSymbol ParPredicate::generateConstraint(const casperbind::cpp::SymbolArray& sympars)
{
	std::map<std::string,casperbind::cpp::SharedSymbol> mpars;
	// parse pars str to vector
	std::vector<std::string> strpars;
	boost::split(strpars, pars, boost::is_space());
	// create map from par name to current symbol instantiation
	if (sympars.getSize() != (int)strpars.size()/2)
		throw xmlpp::validity_error(std::string("predicate defined/called with diferent number of parameters: ")+expr);
	for (int i = 0; i < (int)strpars.size()/2; ++i)
		mpars.insert(make_pair(strpars[i*2+1],sympars[i]));
	// parse expression
	ExprParser e;
	casperbind::cpp::SharedSymbol s = e.parse(expr,mpars);
	if (s.getType(true) != casperbind::cpp::Symbol::sPredicate)
		throw xmlpp::parse_error(std::string("parsing expression: ")+expr);
	return s;
}

class XCSPParser : public xmlpp::SaxParser
{
public:
  XCSPParser();
  virtual ~XCSPParser();

  void presentationBegin(const AttributeList& atts);

  void domainBegin(const AttributeList& attributes);
  void domainContents(const Glib::ustring& text);

  void variableBegin(const AttributeList& attributes);

  void relationBegin(const AttributeList& attributes);
  void relationContents(const Glib::ustring& text);

  void predicateBegin(const AttributeList& attributes);
  void predicateEnd();
  void expressionParsContents(const Glib::ustring& text);
  void expressionContents(const Glib::ustring& text);

  void constraintBegin(const AttributeList& attributes);
  void constraintParsContents(const Glib::ustring& text);
  void constraintEnd();

  casperbind::cpp::Instance getInstance() const;

protected:
  //overrides:
  virtual void on_start_document();
  virtual void on_end_document();
  virtual void on_start_element(const Glib::ustring& name,
                                const AttributeList& properties);
  virtual void on_end_element(const Glib::ustring& name);
  virtual void on_characters(const Glib::ustring& characters);
  virtual void on_characters_buffered();
  virtual void on_comment(const Glib::ustring& text);
  virtual void on_warning(const Glib::ustring& text);
  virtual void on_error(const Glib::ustring& text);
  virtual void on_fatal_error(const Glib::ustring& text);

  void updatePathBegin(const Glib::ustring& text) { path.push_front(text);	}
  void updatePathEnd(const Glib::ustring& text);
  void assertParent(const Glib::ustring& text);
  const Glib::ustring& parent() const;
  const Glib::ustring& grandParent() const;

  casperbind::cpp::IntSet parseIntSet(const Glib::ustring& text);
  casperbind::cpp::IntRange parseIntRange(const Glib::ustring& text);
  casperbind::cpp::SharedSymbol parseIntDomain(const Glib::ustring& text);
  casperbind::cpp::IntArray parseIntTupleList(const Glib::ustring& text,
												int arity, int size);
  casperbind::cpp::SymbolArray parseParameters(const std::string& s) const;
  casperbind::cpp::SymbolArray parseScope(const std::string& s) const;

  std::list<Glib::ustring> path;

  casperbind::cpp::Index index;
  std::list<casperbind::cpp::SharedSymbol> variables;
  std::map<std::string,casperbind::cpp::SharedSymbol> posTables;
  std::map<std::string,casperbind::cpp::SharedSymbol> negTables;

  Glib::ustring curCharactersBuffer;

  std::string curDomainKey;

  std::string curRelationKey;
  int curRelationArity;
  int curRelationNbTuples;

  std::string curPredicateKey;
  std::string curExpressionPars;
  std::string curExpression;

  std::map<std::string,ParPredicate*> predicates;

  std::string curConstraintKey;
  std::string curConstraintScope;
  std::string curConstraintRef;
  std::string curConstraintPars;

  std::list<casperbind::cpp::SharedSymbol> constraints;

  enum { pos, neg } curRelationSemantics;
};

const Glib::ustring& XCSPParser::parent() const
{	return *path.begin();	}

const Glib::ustring& XCSPParser::grandParent() const
{	return *++path.begin();	}

void XCSPParser::updatePathEnd(const Glib::ustring& text)
{
	assertParent(text);
	path.pop_front();
}

void XCSPParser::assertParent(const Glib::ustring& text)
{
	if (parent() != text)
		throw xmlpp::parse_error(std::string("parsing element: ")+text);
}

struct StrToInt
{
	int operator()(const std::string& s) const
	{	return atoi(s.c_str());	}
};

casperbind::cpp::IntSet XCSPParser::parseIntSet(const Glib::ustring& text)
{
	std::vector<std::string> tokens;
	boost::split(tokens, text.raw(), boost::is_space());
	casperbind::cpp::IntSet r;
	std::transform(tokens.begin(),tokens.end(),
			casperbind::cpp::Detail::inserter(r),StrToInt());
	return r;
}

casperbind::cpp::IntRange XCSPParser::parseIntRange(const Glib::ustring& text)
{
	unsigned int pos = text.find("..");
	if (pos >= text.size())
		throw xmlpp::parse_error(std::string("parsing integer range: ")+text);
	int lb = atoi(text.substr(0,pos).c_str());
	int ub = atoi(text.substr(pos+2,text.size()).c_str());
	return casperbind::cpp::IntRange(lb,ub);
}

casperbind::cpp::SharedSymbol XCSPParser::parseIntDomain(const Glib::ustring& text)
{
	std::vector<Glib::ustring> tokens;
	boost::split(tokens, text.raw(), boost::is_any_of("\t \r\n"));

	// if we have only one range, store it and leave
	if (tokens.size()==1 and tokens[0].find("..") < tokens[0].size())
		return parseIntRange(text);

	casperbind::cpp::IntSet s;

	// else store list of values since there is no mixed sets (ranges+int) in casperbind
	for (std::vector<Glib::ustring>::iterator it = tokens.begin();
			it != tokens.end(); ++it)
		if (it->find("..") < tokens[0].size()) // is a range
		{
			casperbind::cpp::IntRange r(parseIntRange(*it));
			for (int i = r.getLower(); i <= r.getUpper(); ++i)
				s.add(i);
		}
		else	// is a set
		{
			casperbind::cpp::IntSet r(parseIntSet(*it));
			for (casperbind::cpp::IntSet::ConstIterator it2 = r.begin();
					it2 != r.end(); ++it2)
				s.add(*it2);
		}

	return s;
}

casperbind::cpp::IntArray XCSPParser::parseIntTupleList(const Glib::ustring& text,
				int arity, int size)
{
	int dims[2] = { size, arity };
	casperbind::cpp::IntArray r(2,dims);
	int c = 0;

	std::vector<std::string> tuples;
	boost::split(tuples, text.raw(), boost::is_any_of("|"));

	for (std::vector<std::string>::iterator it = tuples.begin();
			it != tuples.end(); ++it)
	{
		std::vector<std::string> elements;
		boost::split(elements, *it, boost::is_any_of(" \t\r\n"));
		std::transform(elements.begin(),elements.end(),&r[c],StrToInt());
		c += elements.size();
	}

	return r;
}

casperbind::cpp::SymbolArray XCSPParser::parseParameters(const std::string& s) const
{
	std::list<casperbind::cpp::SharedSymbol> l;
	std::vector<std::string> pars;
	boost::split(pars, s, boost::is_any_of("\t\r\n "));
	for (std::vector<std::string>::const_iterator it = pars.begin();
			it != pars.end(); ++it)
		if (index.hasKey(*it)) // parameter is a variable
			l.push_back(index.getSymbol(*it));
		else // parameter is an integral constant
			l.push_back(casperbind::cpp::int(atoi(it->c_str())));
	casperbind::cpp::SymbolArray r(l.size());
	std::copy(l.begin(),l.end(),r.getData());
	return r;
}

casperbind::cpp::SymbolArray XCSPParser::parseScope(const std::string& s) const
{
	std::list<casperbind::cpp::SharedSymbol> l;
	std::vector<std::string> pars;
	boost::split(pars, s, boost::is_any_of("\t\r\n "));
	for (std::vector<std::string>::const_iterator it = pars.begin();
			it != pars.end(); ++it)
		if (index.hasKey(*it)) // parameter is a variable
			l.push_back(index.getSymbol(*it));
		else // something is wrong
			throw xmlpp::parse_error(std::string("undeclared variable in constraint scope: ")+s);
	casperbind::cpp::SymbolArray r(l.size());
	std::copy(l.begin(),l.end(),r.getData());
	return r;
}

void XCSPParser::presentationBegin(const AttributeList& attributes)
{
	// test for valid XCSP format versions
	const int n = 2;
	Glib::ustring compatibleVersions[n] = { "XCSP 2.0","XCSP 2.1" };

	Glib::ustring name = "format";
	AttributeList::const_iterator versionIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName(name));

	if (versionIt == attributes.end() or
			std::find_if(compatibleVersions,
						 &compatibleVersions[n],
						 std::bind1st(std::equal_to<Glib::ustring>(),versionIt->value))==
							 &compatibleVersions[n])
	{
		std::ostringstream s;
		std::copy(compatibleVersions,&compatibleVersions[n],
					std::ostream_iterator<Glib::ustring>(s,", "));
		throw xmlpp::validity_error("incompatible XCSP version. Supported versions: "+s.str());
	}
}

void XCSPParser::domainBegin(const AttributeList& attributes)
{
	AttributeList::const_iterator nameIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("name"));
	if (nameIt == attributes.end())
		throw xmlpp::validity_error("unnamed domain found");

	curDomainKey = nameIt->value;
}

void XCSPParser::variableBegin(const AttributeList& attributes)
{
	AttributeList::const_iterator nameIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("name"));
	std::string curVariableKey = nameIt->value;
	if (nameIt == attributes.end())
		throw xmlpp::validity_error("unnamed variable");

	AttributeList::const_iterator domIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("domain"));
	if (domIt == attributes.end())
		throw xmlpp::validity_error("variable with unspecified domain");

	const casperbind::cpp::SharedSymbol& dom  = index.getSymbol(domIt->value);

	if (dom.getType()!=casperbind::cpp::Symbol::sSymbol)
		throw xmlpp::validity_error("assertion failure in XCSPParser::variableBegin");

	casperbind::cpp::SharedSymbol var = casperbind::cpp::Variable(dom);
	variables.push_back(var);
	index.add(var,curVariableKey);
}

void XCSPParser::relationBegin(const AttributeList& attributes)
{
	AttributeList::const_iterator nameIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("name"));
	if (nameIt == attributes.end())
		throw xmlpp::validity_error("unnamed relation");

	curRelationKey = nameIt->value;

	AttributeList::const_iterator arityIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("arity"));
	if (arityIt == attributes.end())
		throw xmlpp::validity_error("relation with unspecified arity");

	curRelationArity = atoi(arityIt->value.c_str());

	AttributeList::const_iterator nbIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("nbTuples"));
	if (nbIt == attributes.end())
		throw xmlpp::validity_error("relation with unspecified nbTuples");

	curRelationNbTuples = atoi(nbIt->value.c_str());

	AttributeList::const_iterator semIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("semantics"));
	if (semIt == attributes.end())
		throw xmlpp::validity_error("relation with unspecified semantics");

	if (semIt->value == "supports")
		curRelationSemantics = pos;
	else
		curRelationSemantics = neg;
}

void XCSPParser::predicateBegin(const AttributeList& attributes)
{
	AttributeList::const_iterator nameIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("name"));
	if (nameIt == attributes.end())
		throw xmlpp::validity_error("unnamed predicate found");

	curPredicateKey = nameIt->value;
}

void XCSPParser::domainContents(const Glib::ustring& text)
{
	index.add(parseIntDomain(text),curDomainKey);
}

void XCSPParser::relationContents(const Glib::ustring& text)
{
	casperbind::cpp::IntArray a = parseIntTupleList(text,curRelationArity,
														 curRelationNbTuples);
	index.add(a,curRelationKey);
	if (curRelationSemantics == pos)
		posTables.insert(make_pair(curRelationKey,index.getSymbol(curRelationKey)));
	else
		negTables.insert(make_pair(curRelationKey,index.getSymbol(curRelationKey)));
}

void XCSPParser::expressionParsContents(const Glib::ustring& text)
{
	curExpressionPars = text;
}

void XCSPParser::expressionContents(const Glib::ustring& text)
{
	curExpression = text;
}

void XCSPParser::predicateEnd()
{
	if (predicates.find(curPredicateKey) != predicates.end())
		throw xmlpp::validity_error("multiple definitions of predicate with same name");
	predicates.insert(std::make_pair(curPredicateKey,new ParPredicate(curExpressionPars,curExpression)));
}

void XCSPParser::constraintBegin(const AttributeList& attributes)
{
	AttributeList::const_iterator nameIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("name"));
	if (nameIt == attributes.end())
		throw xmlpp::validity_error("unnamed constraint");

	curConstraintKey = nameIt->value;

	AttributeList::const_iterator scopeIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("scope"));
	if (scopeIt == attributes.end())
		throw xmlpp::validity_error("constraint with unspecified scope");

	curConstraintScope = scopeIt->value;

	AttributeList::const_iterator refIt = std::find_if(attributes.begin(),
										attributes.end(), AttributeHasName("reference"));
	if (refIt == attributes.end())
		throw xmlpp::validity_error("constraint with unspecified reference");

	curConstraintRef = refIt->value;

}

void XCSPParser::constraintParsContents(const Glib::ustring& text)
{
	curConstraintPars = text;
}

void XCSPParser::constraintEnd()
{
	// if cur constraint is a predicate
	if (predicates.find(curConstraintRef)!=predicates.end())
	{
		casperbind::cpp::SymbolArray pars = parseParameters(curConstraintPars);
		index.add(predicates[curConstraintRef]->generateConstraint(pars),curConstraintKey);
		constraints.push_back(index.getSymbol(curConstraintKey));
	}
	else // if cur constraint is a positive table
	if (posTables.find(curConstraintRef) != posTables.end())
	{
		casperbind::cpp::SymbolArray vars = parseScope(curConstraintScope);
		casperbind::cpp::SymbolArray pars(2);
		pars[0] = vars;
		pars[1] = posTables[curConstraintRef];
		casperbind::cpp::SharedSymbol s =
				casperbind::cpp::Predicate(casperbind::cpp::Predicate::pInTable,pars);
		index.add(s,curConstraintKey);
		constraints.push_back(s);
	}
	else
	if (negTables.find(curConstraintRef) != negTables.end())
	{
		casperbind::cpp::SymbolArray vars = parseScope(curConstraintScope);
		casperbind::cpp::SymbolArray pars(2);
		pars[0] = vars;
		pars[1] = negTables[curConstraintRef];
		casperbind::cpp::SharedSymbol s =
				casperbind::cpp::Predicate(casperbind::cpp::Predicate::pNotInTable,pars);
		index.add(s,curConstraintKey);
		constraints.push_back(s);
	}
}

XCSPParser::XCSPParser()
  : xmlpp::SaxParser()
{
}

XCSPParser::~XCSPParser()
{
}

void XCSPParser::on_start_document()
{
  std::cout << "on_start_document()" << std::endl;
}

void XCSPParser::on_end_document()
{
  std::cout << "on_end_document()" << std::endl;
}

void XCSPParser::on_start_element(const Glib::ustring& name,
                                   const AttributeList& attributes)
{
	if (name == "presentation")
	{
		assertParent("instance");
		presentationBegin(attributes);
	}
	else
	if (name == "domains")
		assertParent("instance");
	else
	if (name == "domain")
	{
		assertParent("domains");
		domainBegin(attributes);
	}
	else
	if (name == "variables")
		assertParent("instance");
	else
	if (name == "variable")
	{
		assertParent("variables");
		variableBegin(attributes);
	}
	else
	if (name == "relations")
		assertParent("instance");
	else
	if (name == "relation")
	{
		assertParent("relations");
		relationBegin(attributes);
	}
	else
	if (name == "predicates")
		assertParent("instance");
	else
	if (name == "predicate")
	{
		assertParent("predicates");
		predicateBegin(attributes);
	}
	else
	if (name == "constraint")
	{
		assertParent("constraints");
		constraintBegin(attributes);
	}

	updatePathBegin(name);

	curCharactersBuffer = "";
}

void XCSPParser::on_end_element(const Glib::ustring& name)
{
	if (curCharactersBuffer.size()>0)
	{
		on_characters_buffered();
		curCharactersBuffer = "";
	}

	if (parent()=="predicate")
		predicateEnd();
	else
	if (parent()=="constraint")
		constraintEnd();

	updatePathEnd(name);

//  std::cout << "on_end_element()" << std::endl;
}

void XCSPParser::on_characters(const Glib::ustring& text)
{
	curCharactersBuffer += text;
}

void XCSPParser::on_characters_buffered()
{
	if (parent()=="domain")
		domainContents(curCharactersBuffer);
	else
	if (parent()=="relation")
		relationContents(curCharactersBuffer);
	else
	if (parent()=="parameters" and grandParent()=="predicate")
		expressionParsContents(curCharactersBuffer);
	else
	if (parent()=="functional" and grandParent()=="expression")
		expressionContents(curCharactersBuffer);
	else
	if (parent()=="parameters" and grandParent()=="constraint")
		constraintParsContents(curCharactersBuffer);

 // std::cout << "on_characters(): " << text << std::endl;
}

void XCSPParser::on_comment(const Glib::ustring& text)
{
  std::cout << "on_comment(): " << text << std::endl;
}

void XCSPParser::on_warning(const Glib::ustring& text)
{
  std::cout << "on_warning(): " << text << std::endl;
}

void XCSPParser::on_error(const Glib::ustring& text)
{
  std::cout << "on_error(): " << text << std::endl;
}

void XCSPParser::on_fatal_error(const Glib::ustring& text)
{
  std::cout << "on_fatal_error(): " << text << std::endl;
}

casperbind::cpp::Instance XCSPParser::getInstance() const
{
	casperbind::cpp::SymbolArray vars(variables.size());
	int c = 0;
	// FIXME this should be only labeling variables (the remaining are refd indirectly)
	for (std::list<casperbind::cpp::SharedSymbol>::const_iterator it = variables.begin();
			it != variables.end(); ++it)
		vars[c++] = *it;
	casperbind::cpp::SymbolArray cons(constraints.size());
	c = 0;
    for (std::list<casperbind::cpp::SharedSymbol>::const_iterator it = constraints.begin();
			it != constraints.end(); ++it)
    	cons[c++] = *it;
    return casperbind::cpp::Instance(index,vars,cons);
}

int
main(int argc, char* argv[])
{
  std::string filepath;
  if(argc > 1 )
    filepath = argv[1]; //Allow the user to specify a different XML file to parse.
  else
  {
	  std::cerr << "usage: " << argv[0] << " xcspfile" << std::endl;
	  return 1;
  }
  // Parse the entire document in one go:
  try
  {
    XCSPParser parser;
    parser.set_substitute_entities(true); //
    parser.parse_file(filepath);
    SymStream scout(std::cout,parser.getInstance().getIndex());
    scout << parser.getInstance() << std::endl;

  }
  catch(const xmlpp::exception& ex)
  {
    std::cout << "exception: " << ex.what() << std::endl;
  }

  return 0;
}

ext: cpp

max_stars_repo_name: marcovc/casper

max_issues_repo_name: marcovc/casper

max_forks_repo_name: marcovc/casper


text:
// Copyright (C) 2016 Gideon May (gideon@borges.xyz)
//
// Permission to copy, use, sell and distribute this software is granted
// provided this copyright notice appears in all copies.
// Permission to modify the code and to distribute modified code is granted
// provided this copyright notice appears in all copies, and a notice
// that the code was modified is included with the copyright notice.
//
// This software is provided "as is" without express or implied warranty,
// and with no claim as to its suitability for any purpose.

#ifndef PYOSG_HELD_PTR
#define PYOSG_HELD_PTR 1

#include <boost/python/detail/indirect_traits.hpp>
#include <boost/mpl/if.hpp>
#include <boost/python/to_python_indirect.hpp>
#include <boost/type_traits/composite_traits.hpp>

#include <boost/python/to_python_converter.hpp>
#include <boost/python/implicit.hpp>

#include <osg/Referenced>
#include <osg/ref_ptr>
#include <osg/Node>

#define TEST_REF 0

#if 0
namespace boost { namespace python {

template<class T> inline T * get_pointer(osg::ref_ptr<T> const & p)
{
    return const_cast<T *>(p.get());
}

#if 0
template<class T> inline T * get_pointer(Producer::ref_ptr<T> const & p)
{
    return const_cast<T *>(p.get());
}
#endif

}} // namespace boost:python
#endif

struct make_osg_holder
{
  template <class T>
  static PyObject* execute(T* p)
  {
      typedef osg::ref_ptr<T> smart_pointer;
      typedef boost::python::objects::pointer_holder<smart_pointer, T> holder_t;

      smart_pointer ptr(p);
      return boost::python::objects::make_ptr_instance<T, holder_t>::execute(ptr);
  }
};

template <class R>
struct manage_osg_object_requires_a_pointer_return_type
# if defined(__GNUC__) && __GNUC__ >= 3 || defined(__EDG__)
{}
# endif
;

template <class R>
struct manage_osg_object_requires_a_pointer_or_reference_return_type
# if defined(__GNUC__) && __GNUC__ >= 3 || defined(__EDG__)
  {}
# endif
;

struct manage_osg_object
{
    template <class T>
    struct apply
    {
#if TEST_REF
        BOOST_STATIC_CONSTANT(
            bool, ok = boost::is_pointer<T>::value || boost::is_reference<T>::value);
        typedef typename boost::mpl::if_c<
            ok
            , boost::python::to_python_indirect<T, make_osg_holder>
            , manage_osg_object_requires_a_pointer_or_reference_return_type<T>
        >::type type;
#else
        typedef typename boost::mpl::if_c<
            boost::is_pointer<T>::value
            , boost::python::to_python_indirect<T, make_osg_holder>
            , manage_osg_object_requires_a_pointer_return_type<T>
        >::type type;
#endif
    };
};

#if 0
struct make_producer_holder
{
  typedef PyObject* result_type;
  template <class T>
  static result_type execute(T* p)
  {
      typedef Producer::ref_ptr<T> smart_pointer;
      typedef boost::python::objects::pointer_holder<smart_pointer, T> holder_t;

      smart_pointer ptr(p);
      return boost::python::objects::make_ptr_instance<T, holder_t>::execute(ptr);
  }
};

template <class R>
struct manage_producer_object_requires_a_pointer_return_type
# if defined(__GNUC__) && __GNUC__ >= 3 || defined(__EDG__)
{}
# endif
;

struct manage_producer_object
{
    template <class T>
    struct apply
    {
        typedef typename boost::mpl::if_c<
            boost::is_pointer<T>::value
            , boost::python::to_python_indirect<T, make_producer_holder>
            , manage_producer_object_requires_a_pointer_return_type<T>
        >::type type;
    };
};
#endif

template <class T>
struct enum_to_int_converter
{
   static PyObject* convert(T const& x)
   {
          return PyInt_FromLong(x);
   }
};

template <class T>
void enum_as_int()
{
        boost::python::to_python_converter<T, enum_to_int_converter<T> >();
        boost::python::implicitly_convertible<int, T>();
};

#endif // PYOSG_HELD_PTR

ext: hpp

max_stars_repo_name: gideonmay/PyOSG

max_issues_repo_name: gideonmay/PyOSG

max_forks_repo_name: gideonmay/PyOSG


text:
// -----------------------------------------------------------------------
// RTToolbox - DKFZ radiotherapy quantitative evaluation library
//
// Copyright (c) German Cancer Research Center (DKFZ),
// Software development for Integrated Diagnostics and Therapy (SIDT).
// ALL RIGHTS RESERVED.
// See rttbCopyright.txt or
// http://www.dkfz.de/en/sidt/projects/rttb/copyright.html
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE.  See the above copyright notices for more information.
//
//------------------------------------------------------------------------

// this file defines the rttbCoreTests for the test driver
// and all it expects is that you have a function called RegisterTests

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

#include "litCheckMacros.h"

#include "rttbBaseType.h"
#include "rttbDVHCalculator.h"
#include "rttbGenericMaskedDoseIterator.h"
#include "rttbGeometricInfo.h"
#include "rttbGenericDoseIterator.h"
#include "rttbNullPointerException.h"
#include "rttbInvalidParameterException.h"
#include "DummyDoseAccessor.h"
#include "DummyMaskAccessor.h"

namespace rttb
{

	namespace testing
	{
		typedef core::GenericDoseIterator::DoseAccessorPointer DoseAccessorPointer;
		typedef core::GenericMaskedDoseIterator::MaskAccessorPointer MaskAccessorPointer;
		typedef core::DVHCalculator::DoseIteratorPointer DoseIteratorPointer;
		typedef core::DVHCalculator::MaskedDoseIteratorPointer MaskedDoseIteratorPointer;

		/*!@brief DVHTest - test the API of DVH
		 1) test constructors (values as expected?)
		*/

		int DVHCalculatorTest(int /*argc*/, char* /*argv*/[])
		{
			PREPARE_DEFAULT_TEST_REPORTING;

			//create null pointer to DoseIterator
			DoseIteratorPointer spDoseIteratorNull;

			const IDType structureID = "myStructure";
			const IDType doseIDNull = "myDose";

			//1) test constructors (values as expected?)
			CHECK_THROW_EXPLICIT(core::DVHCalculator myDVHCalc(spDoseIteratorNull, structureID, doseIDNull),
			                     core::NullPointerException);

			//create dummy DoseAccessor
			boost::shared_ptr<DummyDoseAccessor> spTestDoseAccessor = boost::make_shared<DummyDoseAccessor>();
			DoseAccessorPointer spDoseAccessor(spTestDoseAccessor);
			const std::vector<DoseTypeGy>* doseVals = spTestDoseAccessor->getDoseVector();
			//create corresponding DoseIterator
			boost::shared_ptr<core::GenericDoseIterator> spTestDoseIterator =
			    boost::make_shared<core::GenericDoseIterator>(spDoseAccessor);
			DoseIteratorPointer spDoseIterator(spTestDoseIterator);

			const IDType doseID = spDoseAccessor->getUID();

			CHECK_NO_THROW(core::DVHCalculator myDVHCalc(spDoseIterator, structureID, doseID));
			CHECK_THROW_EXPLICIT(core::DVHCalculator myDVHCalc(spDoseIterator, structureID, doseID, -1),
			                     core::InvalidParameterException);

			int numBins = 21;
			DoseTypeGy binSize = 0;
			DoseStatisticType maximum = 0;
			std::vector<DoseTypeGy>::const_iterator doseIt = doseVals->begin();

			while (doseIt != doseVals->end())
			{
				if (maximum < *doseIt)
				{
					maximum = *doseIt;
				}

				++doseIt;
			}

			binSize = maximum * 1.5 / numBins;

			CHECK_NO_THROW(core::DVHCalculator myDVHCalc(spDoseIterator, structureID, doseID, binSize,
			               numBins));
			CHECK_THROW_EXPLICIT(core::DVHCalculator myDVHCalc(spDoseIterator, structureID, doseID, 0, 0),
			                     core::InvalidParameterException);//aNumberOfBins must be >=0
			core::DVHCalculator myDVHCalc(spDoseIterator, structureID, doseID, binSize, 1);
			CHECK_THROW_EXPLICIT(myDVHCalc.generateDVH(),
			                     core::InvalidParameterException);//_numberOfBins must be > max(aDoseIterator)/aDeltaD!

      //generateDVH (only test basic functionality here and test it in RTTBDicomIOTests and RTTBITKIOTests)

       //create dummy DoseAccessor with values 0 to check if _deltaD is set to 0.1
      std::vector<DoseTypeGy> zeros(1000, 0);
      core::GeometricInfo geoInfo;
      geoInfo.setNumColumns(10);
      geoInfo.setNumRows(10);
      geoInfo.setNumSlices(10);
      geoInfo.setSpacing({1.0, 1.0, 1.0});

      boost::shared_ptr<DummyDoseAccessor> spTestDoseAccessorZeros = boost::make_shared<DummyDoseAccessor>(zeros, geoInfo);
      DoseAccessorPointer spDoseAccessorZeros(spTestDoseAccessorZeros);
      boost::shared_ptr<core::GenericDoseIterator> spTestDoseIteratorZeros =
        boost::make_shared<core::GenericDoseIterator>(spDoseAccessorZeros);
      DoseIteratorPointer spDoseIteratorZeros(spTestDoseIteratorZeros);
      CHECK_NO_THROW(core::DVHCalculator myDVHCalc2(spDoseIteratorZeros, structureID, doseID, 0,
        numBins));
      core::DVHCalculator myDVHCalc2(spDoseIteratorZeros, structureID, doseID, 0,
        numBins);
      core::DVH::Pointer dvh;
      CHECK_NO_THROW(dvh = myDVHCalc2.generateDVH());
      CHECK(dvh);
      CHECK_CLOSE(dvh->getDeltaD(), 0.1, errorConstant);

			//create dummy MaskAccessor
			boost::shared_ptr<DummyMaskAccessor> spTestMaskAccessor =
			    boost::make_shared<DummyMaskAccessor>(spDoseAccessor->getGeometricInfo());
			MaskAccessorPointer spMaskAccessor(spTestMaskAccessor);
			//create corresponding MaskedDoseIterator
			boost::shared_ptr<core::GenericMaskedDoseIterator> spTestMaskedDoseIterator =
			    boost::make_shared<core::GenericMaskedDoseIterator>(spMaskAccessor, spDoseAccessor);
			MaskedDoseIteratorPointer spMaskedDoseIterator(spTestMaskedDoseIterator);

			CHECK_NO_THROW(core::DVHCalculator myDVHCalc3(spMaskedDoseIterator, structureID, doseID));
      core::DVHCalculator myDVHCalc3(spMaskedDoseIterator, structureID, doseID);

      CHECK_NO_THROW(dvh = myDVHCalc3.generateDVH());
      CHECK(dvh);

			RETURN_AND_REPORT_TEST_SUCCESS;
		}

	}//end namespace testing
}//end namespace rttb

max_stars_repo_name: MIC-DKFZ/RTTB

max_issues_repo_name: MIC-DKFZ/RTTB

max_forks_repo_name: MIC-DKFZ/RTTB


text:
/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ --- Module
 *
 * This file defines Module, a wrapper for ib_module_t.
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#ifndef __IBPP__MODULE__
#define __IBPP__MODULE__

#include <ironbeepp/abi_compatibility.hpp>
#include <ironbeepp/common_semantics.hpp>
#include <ironbeepp/configuration_map.hpp>
#include <ironbeepp/context.hpp>
#include <ironbeepp/data.hpp>
#include <ironbeepp/engine.hpp>
#include <ironbeepp/exception.hpp>
#include <ironbeepp/memory_manager.hpp>
#include <ironbeepp/throw.hpp>

#include <ironbee/mm.h>
#include <ironbee/module.h>

#include <boost/function.hpp>

#include <ostream>
#include <cassert>

namespace IronBee {

class Module;

/**
 * Const Module; equivalent to a const pointer to ib_module_t
 *
 * Provides operators ==, !=, <, >, <=, >= and evaluation as a boolean for
 * singularity via CommonSemantics.
 *
 * See Module for discussion of modules
 *
 * @sa Module
 * @sa ironbeepp
 * @sa ib_module_t
 * @nosubgrouping
 **/
class ConstModule :
    public CommonSemantics<ConstModule>
{
public:
    //! C Type.
    typedef const ib_module_t* ib_type;

    //! Construct singular ConstModule.
    ConstModule();

    /**
     * @name Queries
     * Query aspects of the module.
     **/
    ///@{

    //! Associated Engine.
    Engine engine() const;

    //! Version number.
    uint32_t version_number() const;

    //! ABI number.
    uint32_t abi_number() const;

    //! Version string.
    const char* version() const;

    //! Filename.
    const char* filename() const;

    //! Index.
    size_t index() const;

    //! Name.
    const char* name() const;

    ///@}

    /**
     * @name C Interoperability
     * Methods to access underlying C types.
     **/
    ///@{

    //! Const ib_module_t accessor.
    // Intentionally inlined.
    const ib_module_t* ib() const
    {
        return m_ib;
    }

    explicit
    ConstModule(const ib_module_t* ib_module);

    ///@}

private:
    const ib_module_t* m_ib;
};

/**
 * Module information; equivalent to a pointer to ib_module_t.
 *
 * Modules can be treated as ConstModules.  See @ref ironbeepp for details on
 * IronBee++ object semantics.
 *
 * An IronBee Module adds functionality to IronBee.  This class represents
 * the information each module provides to the engine.
 *
 * This class behaves similar to @c ib_module_t*.  In particular, it can
 * be singular (equivalent to NULL).  See object semantics in @ref ironbeepp.
 *
 * If you are interested in writing a module in C++, see module_bootstrap.hpp.
 *
 * @sa ironbeepp
 * @sa module_bootstrap.hpp
 * @sa ib_module_t
 * @sa ConstModule
 * @nosubgrouping
 **/
class Module :
    public ConstModule // Slicing is intentional; see apidoc.hpp
{
public:
    //! C Type.
    typedef ib_module_t* ib_type;

   /**
    * Remove the constness of a ConstModule
    *
    * @warning This is as dangerous as a @c const_cast, use carefully.
    *
    * @param[in] const_module ConstModule to remove const from.
    * @returns Module pointing to same underlying module as @a const_module.
    **/
    static Module remove_const(const ConstModule& const_module);

    //! Construct singular module.
    Module();

    /**
     * Get existing module by name.
     *
     * @param[in] engine Engine to get module from.
     * @param[in] name   Name of module.
     * @returns Module with name @a name.
     **/
    static Module with_name(Engine engine, const char* name);

    /**
     * @name Callbacks
     * Types and methods associated with callbacks.
     *
     * Callbacks can be chained.  Usually all callbacks in the chain are
     * called, but if any throws an exception it will abort the chain.  When
     * possible, prefer the @c chain_* methods.  Other IronBee++ components
     * will prechain callbacks to handle their own callbacks.
     *
     * All @c set_* callbacks can be passed an empty functional, e.g.,
     * @c module_callback_t(), to remove the callback (and any chained)
     * callbacks.
     *
     * @warning The @c set_* callbacks will clear all other chained callbacks.
     *          Only do this if you are sure of what you are doing.
     *
     * - An Engine parameter is not provided.  Instead, use Module::engine().
     * - Parameters are passed by copy as they are references to underlying
     *   C objects.  See Module.
     * - Any exceptions thrown will be translated to log messages and
     *   appropriate status returns.  See exception.hpp.
     * - As boost::function's, these are compatible with any function pointer
     *   or function object that matches the signature.
     **/
    ///@{

    //! Module callback.
    typedef boost::function<void (Module)> module_callback_t;
    //! Called on module initialization.
    typedef module_callback_t initialize_t;
     //! Called on module finalization.
    typedef module_callback_t finalize_t;

    //! Chain initialization function.
    void chain_initialize(initialize_t f) const;
    //! Chain finalize function.
    void chain_finalize(finalize_t f) const;

    //! Prechain initialization function.  Prefer chain_initialize().
    void prechain_initialize(initialize_t f) const;
    //! Prechain finalize function.  Prefer chain_finalize().
    void prechain_finalize(finalize_t f) const;

    //! Set initialization function.  Prefer chain_initialize().
    void set_initialize(initialize_t f) const;
    //! Set finalize function.  Prefer chain_finalize().
    void set_finalize(finalize_t f) const;

    ///@}

    /**
     * @name Configuration Data
     * Types and methods associated with configuration data.
     *
     * A module can have configuration data.  This data is set as the
     * "global" configuration data.  Each context then copies the
     * configuration data of the parent context or the global configuration
     * data if there is no parent context.
     *
     * There are two levels that Module can handle configuration data:
     *
     * At the lowest level is set_configuration_data_pod() which fairly
     * directly matches the C interface.  It requires that configuration data
     * by POD (plain old data; essentially any C type).  POD data is copied
     * either via direct memory copy (default) or a user provided copy
     * functional.
     *
     * At the higher level is set_configuration_data() which uses C++
     * semantics, i.e., copy constructors, destructors, etc.  To accommodate
     * the C interface, it stores a pointer to the type rather than the type
     * in the C interface.
     *
     * It is highly recommended to use set_configuration_data() unless you
     * need to closely interoperate with the C code.
     *
     * Both methods returns a ConfigurationMapInit object to facilitate
     * creation of configuration maps.  See configuration_map.hpp for details.
     * E.g.,
     *
     * @code
     * module.set_configuration_data_pod(my_global_data)
     *       .number("num_foos", &my_global_data_t::num_foos)
     *       .byte_string_s("best_foo_name", &my_global_data_t::best_foo_name)
     *       ;
     * @endcode
     *
     * If the configuration data is not a class/struct, the return value
     * is a valid type (ConfigurationMapInit<DataType>) but has no
     * methods.
     **/
    ///@{

    /**
     * Metafunction providing type of configuration data copier.
     *
     * Will define @c type to be the the appropriate functional type.
     *
     * @warning @a DataType must be POD.  At present, issues with clang and
     * __is_pod() make it impossible to statically assert podness in a
     * compatible way.  And such, behavior is undefined if @a DataType is not
     * POD.
     *
     * @sa set_configuration_data()
     *
     * @tparam DataType Type of configuration data.
     * @tparam Enable   Internal use only.
     **/
    template <typename DataType>
    struct configuration_copier_t
    {
        //! Type of copier for set_configuration_data().
        typedef boost::function<
            void(Module, DataType&, const DataType&)
        > type;
    };

    /**
     * Set configuration data for POD
     *
     * See group member group documentation for details.
     *
     * For C++ object semantics with configuration data, see
     * set_configuration_data().
     *
     * For type safety, the type of configuration data (@a DataType), global
     * data (@a global_data), and any copier function (@a copier) must be
     * provided simultaneously.
     *
     * This is a low level routine and, as such, requires that @a DataType
     * be POD.  Behavior is undefined if @a DataType is not POD (see
     * configuration_copier_t for discussion).
     *
     * You should strongly consider using set_configuration_data() instead
     * of using this directly.
     *
     * The copier functional must take a Module, a reference to @a DataType
     * specifying the destination and a const reference to @a DataType
     * specifying the source.  No assumptions should be made about the
     * contents of the destination.
     *
     * @warning Only call one of set_configuration_data() and
     * set_configuration_data_pod().  They will overwrite each other.
     *
     * @tparam DataType Type of configuration data.  Must be POD.
     * @param[in] global_data The global configuration data copied to every
     *                        top level context.
     * @param[in] copier      Optional copier functional.  Defaults to
     *                        memory copy (IB engine default).
     * @returns ConfigurationMapInit
     **/
    template <typename DataType>
    ConfigurationMapInit<DataType> set_configuration_data_pod(
        const DataType& global_data,
        typename configuration_copier_t<DataType>::type copier =
            typename configuration_copier_t<DataType>::type()
    ) const;

    /**
     * Set configuration for C++ objects.
     *
     * See group member group documentation for details.
     *
     * Under the hood, this calls set_configuration_data_pod() with a pointer
     * to DataType (pointers are POD).  That is, @c gcdata is a pointer to
     * a pointer to a @a DataType.
     *
     * @warning Only call one of set_configuration_data() and
     * set_configuration_data_pod().  They will overwrite each other.
     *
     * @tparam DataType Type of configuration data.  Must be copyable.
     * @param[in] global_data The global configuration data copied to
     *                        every toplevel context.
     * @returns ConfigurationMapInit
    **/
    template <typename DataType>
    ConfigurationMapInit<DataType> set_configuration_data(
        const DataType& global_data = DataType()
    ) const;

    /**
     * Fetch POD configuration data for @a context.
     *
     * This method fetches configuration data for @a context assuming
     * set_configuration_data_pod() was used during module setup.
     *
     * @warning Do not use this method if set_configuration_data() was used;
     *          instead, use configuration_data().
     *
     * @a DataType must match the data type used in
     * set_configuration_data_pod().
     *
     * @tparam DataType Type of configuration data.
     * @param[in] context Context to fetch configuration for.
     * @returns Configuration data.
     **/
    template <typename DataType>
    DataType& configuration_data_pod(ConstContext context) const;

    /**
     * Fetch configuration data for @a context.
     *
     * This method fetches configuration data for @a context assuming
     * set_configuration_data() was used during module setup.
     *
     * @warning Do not use this method if set_configuration_data_pod() was
     *          used; instead, use configuration_data_pod().
     *
     * @a DataType must match the data type used in
     * set_configuration_data().
     *
     * @tparam DataType Type of configuration data.
     * @param[in] context Context to fetch configuration for.
     * @returns Configuration data.
     **/
    template <typename DataType>
    DataType& configuration_data(ConstContext context) const;
    ///@}

    /**
     * @name C Interoperability
     * Methods to access underlying C types.
     **/
    ///@{

    //! Non-const ib_module_t accessor.
    // Intentionally inlined.
    ib_module_t* ib() const
    {
        return m_ib;
    }

    //! Construct Module from ib_module_t.
    explicit
    Module(ib_module_t* ib_module);

    ///@}

private:
    ib_module_t* m_ib;

    // Translator for configuration copier.
    typedef boost::function<
        void(ib_module_t*, void*, const void*, size_t)
    > configuration_copier_translator_t;

    void set_configuration_copier_translator(
        configuration_copier_translator_t f
    ) const;
};

namespace Internal {
/// @cond Internal

/**
 * Helper functional to translated untyped interface to typed.
 *
 * Used by set_configuration_data_pod().
 *
 * @tparam DataType DataType of configuration data.
 **/
template <typename DataType>
class configuration_copier_translator
{
public:
    /**
     * Default constructor.
     **/
    configuration_copier_translator()
    {
        // nop
    }

    /**
     * Constructor.
     *
     * @param[in] copier Typed copier to forward to.
     **/
    explicit
    configuration_copier_translator(
        typename Module::configuration_copier_t<DataType>::type copier
    ) :
        m_copier( copier )
    {
        // nop
    }

    /**
     * Call operator.
     *
     * Converts arguments to appropriate C++ types and calls copier.
     **/
    void operator()(
        ib_module_t* ib_module,
        void*        dst,
        const void*  src,
        size_t       length
    ) const
    {
        assert(length == sizeof(DataType));
        m_copier(
            Module(ib_module),
            *reinterpret_cast<DataType*>(dst),
            *reinterpret_cast<const DataType*>(src)
        );
    }

private:
    typename Module::configuration_copier_t<DataType>::type m_copier;
};

/**
 * Functional to delete a given object.
 *
 * Used by set_configuration_data().
 *
 * @tparam DataType Type of configuration data.
 **/
template <typename DataType>
class configuration_data_destroy
{
public:
    /**
     * Default constructor.
     **/
    configuration_data_destroy() :
        m_p(NULL)
    {
        // nop
    }

    /**
     * Constructor.
     *
     * @param[in] p Pointer to object to destroy.
     **/
    explicit
    configuration_data_destroy(DataType* p) :
        m_p(p)
    {
        // nop
    }

    /**
     * Destroy object.
     *
     * Does nothing if default constructed.
     **/
    void operator()()
    {
        if (m_p) {
            delete m_p;
        }
    }

private:
    DataType* m_p;
};

/**
 * Functional to copy configuration data when C++.
 *
 * Used by set_configuration_data().
 *
 * Used copy constructor of @a DataType.
 *
 * @tparam DataType Type of configuration data.  Note: C++ type, not POD
 *         type.  The POD type is @c DataType*.
 **/
template <typename DataType>
class configuration_data_copy
{
public:
    /**
     * Create copy of @c *src and store in @c *dst.
     *
     * Also ensures that copy is properly destroyed.
     *
     * @param[in]  module Module involved.
     * @param[out] dst    Where to store pointer to copy.
     * @param[in]  src    Pointer to source.
     **/
    void operator()(
        Module           module,
        DataType*&       dst,
        DataType* const& src
    ) const
    {
        dst = new DataType(*src);
        MemoryManager(
            ib_engine_mm_main_get(module.engine().ib())
        ).register_cleanup(
            configuration_data_destroy<DataType>(dst)
        );
    }
};

/// @endcond
} // Internal

template <typename DataType>
ConfigurationMapInit<DataType> Module::set_configuration_data_pod(
    const DataType& global_data,
    typename configuration_copier_t<DataType>::type copier
) const
{
    MemoryManager mm(ib_engine_mm_main_get(ib()->ib));
    throw_if_error(
        ib_module_config_initialize(
          ib(),
          mm.alloc(sizeof(global_data)),
          sizeof(global_data)
      )
    );

    if (ib()->gcdata == NULL) {
        BOOST_THROW_EXCEPTION(
          ealloc() << errinfo_what(
            "Could not allocate memory for configuration data."
          )
        );
    }
    *reinterpret_cast<DataType*>(ib()->gcdata) = global_data;

    if (copier.empty()) {
        ib()->fn_cfg_copy     = NULL;
        ib()->cbdata_cfg_copy = NULL;
    }
    else {
        set_configuration_copier_translator(
            Internal::configuration_copier_translator<DataType>(copier)
        );
    }

    return ConfigurationMapInit<DataType>(ib()->cm_init, mm);
}

template <typename DataType>
ConfigurationMapInit<DataType> Module::set_configuration_data(
    const DataType& global_data
) const
{
    MemoryManager mm(ib_engine_mm_main_get(ib()->ib));
    DataType* global_data_ptr = new DataType(global_data);

    // This will make gcdata a pointer to a pointer.
    set_configuration_data_pod(
        global_data_ptr,
        Internal::configuration_data_copy<DataType>()
    );

    MemoryManager(
        ib_engine_mm_main_get(engine().ib())
    ).register_cleanup(
        Internal::configuration_data_destroy<DataType>(global_data_ptr)
    );

    return ConfigurationMapInit<DataType>(ib()->cm_init, mm, true);
}

template <typename DataType>
DataType& Module::configuration_data_pod(ConstContext context) const
{
    DataType* config;
    throw_if_error(
        ib_context_module_config(context.ib(), ib(), &config)
    );
    return *config;
}

template <typename DataType>
DataType& Module::configuration_data(ConstContext context) const
{
    DataType* config_ptr = configuration_data_pod<DataType*>(context);
    return *config_ptr;
}

/**
 * Output operator for Module.
 *
 * Outputs Module[@e name] to @a o where @e name is replaced with
 * @a module.@c name().
 *
 * @param[in] o      Ostream to output to.
 * @param[in] module Module to output.
 * @return @a o
 **/
std::ostream& operator<<(std::ostream& o, const ConstModule& module);

} // IronBee

#endif

max_issues_repo_name: ErikHendriks/ironbee

max_forks_repo_name: ErikHendriks/ironbee


text:
/*=============================================================================
  Copyright (c) 2010-2016 Bolero MURAKAMI
  https://github.com/bolero-MURAKAMI/Sprig

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

#include <sprig/config/config.hpp>

#ifdef SPRIG_USING_PRAGMA_ONCE
#	pragma once
#endif	// #ifdef SPRIG_USING_PRAGMA_ONCE

#include <boost/mpl/and.hpp>
#include <boost/mpl/or.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_array.hpp>
#include <boost/type_traits/remove_pointer.hpp>
#include <boost/type_traits/remove_bounds.hpp>
#include <sprig/type_traits/is_char_type.hpp>
#include <sprig/type_traits/is_wchar_type.hpp>

namespace sprig {
	//
	// is_c_str_pointer
	//
	template<typename T>
	struct is_c_str_pointer
		: public boost::mpl::and_<
			boost::is_pointer<T>,
			boost::mpl::or_<
				sprig::is_char_type<typename boost::remove_pointer<T>::type>,
				sprig::is_wchar_type<typename boost::remove_pointer<T>::type>
			>
		>
	{};
	//
	// is_c_str_array
	//
	template<typename T>
	struct is_c_str_array
		: public boost::mpl::and_<
			boost::is_array<T>,
			boost::mpl::or_<
				sprig::is_char_type<typename boost::remove_bounds<T>::type>,
				sprig::is_wchar_type<typename boost::remove_bounds<T>::type>
			>
		>
	{};
	//
	// is_c_str
	//
	template<typename T>
	struct is_c_str
		: public boost::mpl::or_<
			is_c_str_pointer<T>,
			is_c_str_array<T>
		>
	{};
}	// namespace sprig

#endif	// #ifndef SPRIG_TYPE_TRAITS_IS_C_STR_HPP

max_stars_repo_name: bolero-MURAKAMI/Sprig

max_issues_repo_name: bolero-MURAKAMI/Sprig

max_forks_repo_name: bolero-MURAKAMI/Sprig


text:
// Copyright Louis Dionne 2013-2016
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/assert.hpp>
#include <boost/hana/equal.hpp>
#include <boost/hana/optional.hpp>
#include <boost/hana/ap.hpp>

#include <laws/base.hpp>
namespace hana = boost::hana;
using hana::test::ct_eq;

int main() {
    hana::test::_injection<0> f{};

    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::ap(hana::nothing, hana::nothing),
        hana::nothing
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::ap(hana::just(f), hana::nothing),
        hana::nothing
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::ap(hana::nothing, hana::just(ct_eq<3>{})),
        hana::nothing
    ));
    BOOST_HANA_CONSTANT_CHECK(hana::equal(
        hana::ap(hana::just(f), hana::just(ct_eq<3>{})),
        hana::just(f(ct_eq<3>{}))
    ));
}

max_issues_repo_name: lipper/arangodb

max_forks_repo_name: lipper/arangodb


text:
/*******************************************************************************
procmon, Copyright (c) 2014, The Regents of the University of California,
through Lawrence Berkeley National Laboratory (subject to receipt of any
required approvals from the U.S. Dept. of Energy).  All rights reserved.

If you have questions about your rights to use or distribute this software,
please contact Berkeley Lab's Technology Transfer Department at  TTD@lbl.gov.

The LICENSE file in the root directory of the source code archive describes the
licensing and distribution rights and restrictions on this software.

Author:   Douglas Jacobsen <dmj@nersc.gov>
*******************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <ncurses.h>
#include <math.h>
#include <sys/types.h>
#include <pwd.h>

#include <boost/program_options.hpp>
#include <boost/bind.hpp>

#include <vector>
#include <deque>
#include <unordered_map>
#include <string>
#include <iostream>
#include <algorithm>

#include "ProcData.hh"
#include "ProcIO.hh"

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

class TopCurses;

class JobtopConfig {
    public:
    JobtopConfig(int argc, char **argv) {
        system = DEFAULT_SYSTEM;
        host = "*";
        identifier = "*";
        subidentifier = "*";
        setupProgramOptions();
        parseProgramOptions(argc, argv);
    }
    inline const string getSystem() const { return system; }
    inline const string getHost() const { return host; }
    inline const string getIdentifier() const { return identifier; }
    inline const string getSubidentifier() const { return subidentifier; }

    private:
    string system;
    string host;
    string identifier;
    string subidentifier;
    po::options_description options;

    void setJob(const string &input) {
        size_t dotpos = input.find('.');
        if (dotpos != string::npos) {
            identifier = input.substr(0, dotpos);
            subidentifier = input.substr(dotpos + 1);
            dotpos = subidentifier.find('.');
            if (dotpos != string::npos) {
                subidentifier = subidentifier.substr(0, dotpos);
            }
        } else {
            identifier = input;
            subidentifier = "*";
        }
    }

    void setupProgramOptions() {
        po::options_description basic("JobTop Options");
        basic.add_options()
            ("version", "Print version information")
            ("help,h", "Print help message")
            ("system", po::value<string>(&system)->default_value(system), "Name of computational platform")
            ("host", po::value<string>(&host)->default_value("*"), "Hosts to listen to")
            ("job",  po::value<string>()->notifier(
                    boost::bind(&JobtopConfig::setJob, this, _1)
                ), "Job descriptor to listen for")
        ;
        options.add(basic);
    }

    void parseProgramOptions(int argc, char **argv) {
        po::positional_options_description p;
        p.add("job", -1);

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

        if (vm.count("help")) {
            cout << options << endl;
            exit(0);
        }
        if (host == "*" && identifier == "*" && subidentifier == "*") {
            cerr << "ERROR:  must specify job or host" << endl;
            cerr << options << endl;
            exit(1);
        }
    }
};

pthread_mutex_t data_lock = PTHREAD_MUTEX_INITIALIZER;
time_t last_update = 0;
int cleanup = 0;
int age_timeout = 60;
unordered_map<int,string> usernames;
void fatal_error(const char *error, int err);
static void screen_exit(TopCurses *screen, int exit_code);

int cmp_procstat_pid(const void *t_a, const void *t_b) {
    const procstat *a = (const procstat *) t_a;
    const procstat *b = (const procstat *) t_b;
    return a->pid - b->pid;
}

int cmp_procdata_pid(const void *t_a, const void *t_b) {
    const procdata *a = (const procdata *) t_a;
    const procdata *b = (const procdata *) t_b;
    return a->pid - b->pid;
}

class JobDataDelta;

class JobData {
  friend class JobDataDelta;
  public:
    JobData() {
        ps = NULL;
        pd = NULL;
        n_ps = 0;
        n_pd = 0;
    }
    ~JobData() {
        if (ps != NULL) delete ps;
        if (pd != NULL) delete pd;
        ps = NULL;
        pd = NULL;
        n_ps = 0;
        n_pd = 0;
    }
    void setProcStat(procstat *data, int n) {
        ps = new procstat[n];
        if (ps == NULL) {
            fatal_error("Couldn't allocate memory, failing.", 0);
        }
        memcpy(ps, data, sizeof(procstat) * n);
        n_ps = n;
        qsort(ps, n_ps, sizeof(procstat), cmp_procstat_pid);
    }
    void setProcData(procdata *data, int n) {
        pd = new procdata[n];
        if (pd == NULL) {
            fatal_error("Couldn't allocate memory, failing.", 0);
        }
        memcpy(pd, data, sizeof(procdata) * n);
        n_pd = n;
        qsort(pd, n_pd, sizeof(procdata), cmp_procdata_pid);
    }

    procstat *ps;
    procdata *pd;
    int n_ps;
    int n_pd;
};

class JobDataDelta {
  public:
    JobDataDelta(JobData *current, JobData *old) {
        n_items = current->n_ps;
        d_stime = new double[n_items];
        d_utime = new double[n_items];
        d_ioread = new double[n_items];
        d_iowrite = new double[n_items];
        for (int i = 0; i < n_items; i++) {
            procstat *ps = &(current->ps[i]);
            bool found = false;
            for (int j = 0; j < old->n_ps || old->ps[j].pid > ps->pid; j++) {
                if (ps->pid == old->ps[j].pid) {
                    d_stime[i] = ps->stime - old->ps[j].stime;
                    d_utime[i] = ps->utime - old->ps[j].utime;
                    d_ioread[i] = ps->io_rchar - old->ps[j].io_rchar;
                    d_iowrite[i] = ps->io_wchar - old->ps[j].io_wchar;
                    found = true;
                    dt = (ps->recTime + ps->recTimeUSec*1e-6) - (old->ps[j].recTime + old->ps[j].recTimeUSec*1e-6);
                }
            }
            if (!found) {
                dt = NAN;
            }
        }
    }
    ~JobDataDelta() {
        delete d_stime;
        delete d_utime;
        delete d_ioread;
        delete d_iowrite;
    }
    int n_items;
    double *d_stime;
    double *d_utime;
    double *d_ioread;
    double *d_iowrite;
    double dt;
};

struct JobIdent {
    string hostname;
    string jobid;
    string taskid;

    JobIdent(const string &_hostname, const string &_jobid, const string &_taskid):
        hostname(_hostname), jobid(_jobid), taskid(_taskid) {
    }
    bool operator==(const JobIdent &other) const {
        return hostname == other.hostname && jobid == other.jobid && taskid == other.taskid;
    }
};

namespace std {
    template <>
    struct hash<JobIdent> {
        std::size_t operator()(const JobIdent &k) const {
            using std::size_t;
            using std::hash;
            using std::string;
            return ((hash<string>()(k.hostname) ^ (hash<string>()(k.jobid) << 1)) >> 1) ^ (hash<string>()(k.taskid) << 1);
        }
    };
}

struct PrintData {
    string hostname;
    string command;
    string username;
    int pid;
    int ppid;
    time_t recTime;
    double total_cpu;
    double rate_cpu;
    double wallTime;
    double rss;
    double vmem;
    int threads;
    char state;
    int mpiRank;
    double total_ioRead;
    double total_ioWrite;
    double rate_ioRead;
    double rate_ioWrite;
};

struct CurrentJobData {
    JobData *data;
    JobDataDelta *delta;
    //vector<PrintData *> records;

    CurrentJobData(JobData *data, JobDataDelta *delta) {
        this->data = data;
        this->delta = delta;
    }

    ~CurrentJobData() {
        if (data != NULL) delete data;
        if (delta != NULL) delete delta;
        /*
        for (auto it = records.begin(); it != records.end(); it++) {
            delete *it;
        }
        */
        data = NULL;
        delta = NULL;
    }
};

struct cmpJobIdent {
    bool operator()(const JobIdent& a, const JobIdent& b) const {
        return a.hostname == b.hostname && a.jobid == b.jobid && a.taskid == b.taskid;
    }
};

enum DisplayType {
    STRING,
    TIME,
    MEMORY,
    INTEGER,
    DOUBLE,
};

class DisplayData {
    friend class TopCurses;
    public:
    DisplayData(string _label, int _width, bool _widthFixed,
        double _widthCoefficient):
        label(_label), baseWidth(_width),
        widthFixed(_widthFixed), widthCoefficient(_widthCoefficient)
    {
        width = baseWidth;
    }
    virtual void display(int y, int x, PrintData *data) = 0;
    void displayLabel(int y, int x) {
        bool boldNext = false;
        for (int i = 0; i < label.size(); i++) {
            if (label[i] == '&') {
                boldNext = true;
                continue;
            }
            if (boldNext) {
                attr_on(A_BOLD, NULL);
            }
            mvaddch(y,x,label[i]);
            if (boldNext) {
                attr_off(A_BOLD, NULL);
                boldNext = false;
            }
            x++;
        }
    }

    protected:
    string label;
    int baseWidth;
    int width;
    bool widthFixed;
    double widthCoefficient;

    static char *format_time(double value, char *buffer, int buflen, int maxwidth) {
        int hours = 0;
        int minutes = 0;
        int seconds = 0;
        int millis = 0;
        int s = floor(value);
        millis = (value - s) * 1000;
        seconds = s % 60;
        s /= 60;
        minutes = s % 60;
        s /= 60;
        hours = s;
        int count = snprintf(buffer, buflen, "%02d:%02d:%02d.%04d", hours, minutes, seconds, millis);
        if (count > maxwidth) {
            memset( buffer, '*', min(buflen, maxwidth));
            buffer[min(buflen,maxwidth)] = 0;
        }
        return buffer;
    }

    static char *format_memory(double value, char *buffer, int buflen, int maxwidth) {
        const char *suffix = "BKMGTPE";
        int count = 0;
        while (value > 1024) {
            value /= 1024;
            count++;
        }
        count = snprintf(buffer, buflen, "%0.1f%c", value, suffix[count]);
        if (count > maxwidth) {
            memset(buffer, '*', min(buflen, maxwidth));
            buffer[min(buflen,maxwidth)] = 0;
        }
        return buffer;
    }
};

class DisplayAge: public DisplayData {
    public:
    DisplayAge(): DisplayData("&AGE", 3, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%*d", width, (time(NULL) - data->recTime));
    }
};
class DisplayMpiRank: public DisplayData {
    public:
    DisplayMpiRank(): DisplayData("&MPI", 4, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%*d", width, data->mpiRank);
    }
};
class DisplayUser: public DisplayData {
    public:
    DisplayUser() : DisplayData("&USER", 8, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%-.*s", width, data->username.c_str());
    }
};
class DisplayHost: public DisplayData {
    public:
    DisplayHost() : DisplayData("&HOST", 10, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%-.*s", width, data->hostname.c_str());
    }
};
class DisplayPid: public DisplayData {
    public:
    DisplayPid() : DisplayData("&PID", 6, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%*d", width, data->pid);
    }
};
class DisplayPPid: public DisplayData {
    public:
    DisplayPPid() : DisplayData("PP&ID", 6, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%*d", width, data->ppid);
    }
};
class DisplayCommand: public DisplayData {
    public:
    DisplayCommand() : DisplayData("&COMMAND", 6, false, 1.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%-.*s", width, data->command.c_str());
    }
};
class DisplayCpuRate: public DisplayData {
    public:
    DisplayCpuRate() : DisplayData("CPU&%", 5, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%0.1f", width, data->rate_cpu);
    }
};
class DisplayCpuTotal: public DisplayData {
    public:
    DisplayCpuTotal() : DisplayData("CPU", 15, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_time(data->total_cpu, buffer, 1024, width));
    }
};
class DisplayState: public DisplayData {
    public:
    DisplayState() : DisplayData("&S", 1, true, 0.0) {
    }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%c", data->state);
    }
};
class DisplayDuration: public DisplayData {
    public:
    DisplayDuration() : DisplayData("&DURATION", 15, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_time(data->wallTime, buffer, 1024, width));
    }
};
class DisplayRSS: public DisplayData {
    public:
    DisplayRSS() : DisplayData("&RSS", 7, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_memory(data->rss, buffer, 1024, width));
    }
};
class DisplayVMem: public DisplayData {
    public:
    DisplayVMem() : DisplayData("&VMEM", 7, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_memory(data->vmem, buffer, 1024, width));
    }
};
class DisplayIORTotal: public DisplayData {
    public:
    DisplayIORTotal() : DisplayData("I&O_R", 7, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_memory(data->total_ioRead, buffer, 1024, width));
    }
};
class DisplayIOWTotal: public DisplayData {
    public:
    DisplayIOWTotal() : DisplayData("IO_&W", 7, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_memory(data->total_ioWrite, buffer, 1024, width));
    }
};
class DisplayIORRate: public DisplayData {
    public:
    DisplayIORRate() : DisplayData("IO_R/s", 7, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_memory(data->rate_ioRead, buffer, 1024, width));
    }
};
class DisplayIOWRate: public DisplayData {
    public:
    DisplayIOWRate() : DisplayData("IO_W/s", 7, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        char buffer[1024];
        mvprintw(y, x, "%s", format_memory(data->rate_ioWrite, buffer, 1024, width));
    }
};
class DisplayThreads: public DisplayData {
    public:
    DisplayThreads() : DisplayData("&TH", 3, true, 0.0) { }
    virtual void display(int y, int x, PrintData *data) {
        mvprintw(y, x, "%*d", width, data->threads);
    }
};

bool sortHostname(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->hostname < b->hostname;
}
bool sortHostnameRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortHostname(a, b);
}
bool sortUsername(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->username < b->username;
}
bool sortUsernameRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->username > b->username;
}
bool sortRSS(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->rss < b->rss;
}

bool sortRSSRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->rss > b->rss;
}

bool sortVMem(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->vmem < b->vmem;
}

bool sortCpuRate(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->rate_cpu < b->rate_cpu;
}
bool sortCpuRateRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortCpuRate(a, b);
}
bool sortMpiRank(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->mpiRank < b->mpiRank;
}
bool sortMpiRankRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortMpiRank(a, b);
}

bool sortThreads(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->threads < b->threads;
}
bool sortThreadsRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortThreads(a,b);
}

bool sortTotalIORead(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->total_ioRead < b->total_ioRead;
}
bool sortTotalIOReadRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortTotalIORead(a,b);
}
bool sortTotalIOWrite(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->total_ioWrite < b->total_ioWrite;
}
bool sortTotalIOWriteRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortTotalIOWrite(a,b);
}
bool sortPid(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->pid < b->pid;
}
bool sortPidRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortPid(a,b);
}
bool sortAge(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->recTime < b->recTime;
}
bool sortAgeRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortAge(a,b);
}
bool sortPPid(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->ppid < b->ppid;
}
bool sortPPidRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return !sortPPid(a,b);
}

bool sortVMemRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->vmem > b->vmem;
}

bool sortDuration(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->wallTime < b->wallTime;
}
bool sortDurationRev(PrintData *a, PrintData *b) {
    if (a == NULL || b == NULL) return false;
    return a->wallTime > b->wallTime;
}

class TopCurses {
  public:
    unordered_map<JobIdent, CurrentJobData*> jobData;
    unordered_map<JobIdent, JobData*> newJobData;
    deque<PrintData *> printData;
    string system;
    string jobid;
    string taskid;
    vector<DisplayData *> columns;
    int highlight_row;
    size_t item_start;
    int xlim, ylim;
    bool (*sortFunction)(PrintData *,PrintData *);

    TopCurses(const string &system, const string &jobid, const string &taskid) {
        this->system = system;
        this->jobid = jobid;
        this->taskid = taskid;
        initscr();
        cbreak(); // let os handle ctrl-c, ctrl-z
        keypad(stdscr, TRUE);
        noecho();
        halfdelay(5);
        highlight_row = 0;
        item_start = 0;
        xlim = 0;
        ylim = 0;
        sortFunction = NULL;

        columns.push_back(new DisplayAge());
        columns.push_back(new DisplayUser());
        columns.push_back(new DisplayHost());
        columns.push_back(new DisplayPid());
        columns.push_back(new DisplayPPid());
        columns.push_back(new DisplayCommand());
        columns.push_back(new DisplayCpuRate());
        columns.push_back(new DisplayState());
        columns.push_back(new DisplayDuration());
        columns.push_back(new DisplayRSS());
        columns.push_back(new DisplayVMem());
        columns.push_back(new DisplayIORTotal());
        columns.push_back(new DisplayIORRate());
        columns.push_back(new DisplayIOWTotal());
        columns.push_back(new DisplayIOWRate());
        columns.push_back(new DisplayThreads());
        columns.push_back(new DisplayMpiRank());
        columns.push_back(new DisplayCpuTotal());
    }

    void printScreen() {
        getmaxyx(stdscr, ylim, xlim);
        erase();

        /* trim the data if any has aged out */
        time_t curr_time = time(NULL);
        int err = 0;
        class AgePrintObj {
            time_t cutoff;
            public:
            AgePrintObj(time_t _cutoff) {
                cutoff = _cutoff;
            }
            bool operator()(PrintData *tgt) {
                return tgt->recTime < cutoff;
            }
        };
        if ((err = pthread_mutex_lock(&data_lock)) != 0) fatal_error("printScreen failed to lock token.", err);
        remove_if(printData.begin(), printData.end(), AgePrintObj(curr_time - age_timeout));

        if (sortFunction != NULL) {
            sort(printData.begin(), printData.end(), sortFunction);
        }
        /* determine window position */
        if (highlight_row < 0) {
            if (item_start - highlight_row < 0) {
                item_start = 0;
            } else {
                item_start -= highlight_row;
            }
            highlight_row = 0;
        } else if (highlight_row >= ylim) {
            item_start += (highlight_row - ylim)+1;
            if (item_start > printData.size()) {
                if (printData.size() - ylim > 0) {
                    item_start = printData.size() - ylim;
                } else {
                    item_start = 0;
                }
            }
            highlight_row = ylim - 1;
        }

        int extra = xlim;
        for (auto it = columns.begin(), end = columns.end(); it != end; it++) {
             extra -= (*it)->baseWidth;
             extra--; // for the space padding
        }
        for (auto it = columns.begin(), end = columns.end(); it != end; it++) {
            if (!(*it)->widthFixed && extra > 0) {
                (*it)->width = (*it)->baseWidth + (*it)->widthCoefficient * extra;
            } else {
                (*it)->width = (*it)->baseWidth;
            }
        }

        mvprintw(0, 0, "System: %s, Job: %s, Task: %s", system.c_str(), jobid.c_str(), taskid.c_str());
        int ypos = 1;
        int xpos = 0;
        int idx = 0;
        int item_idx = item_start;
        for (auto it = columns.begin(), end = columns.end(); it != end && xpos + (*it)->width <= xlim; it++) {
            (*it)->displayLabel(ypos, xpos);
            xpos += (*it)->width + 1;
        }
        ypos = 2;
        while (ypos <= ylim && item_idx < printData.size()) {
            PrintData *item = printData[item_idx];
            xpos = 0;
            idx = 0;
            char buffer[1024];
            if (highlight_row == ypos) {
                attr_on(A_REVERSE, NULL);
            }
            for (auto it = columns.begin(), end = columns.end(); it != end && xpos + (*it)->width <= xlim; it++) {
                (*it)->display(ypos, xpos, item);
                xpos += (*it)->width + 1;
            }
            if (highlight_row == ypos) {
                attr_off(A_REVERSE, NULL);
            }

            item_idx++;
            ypos++;
        }
        if (ypos == 2) {
            mvprintw(3, 0, "Awaiting data.");
        }
        if ((err = pthread_mutex_unlock(&data_lock)) != 0) fatal_error("printScreen failed to unlock token.", err);
        refresh();
    }

    void eventLoop() {
        printScreen();
        while (cleanup == 0) {
            int ch = getch();
            switch (ch) {
                case 'q': screen_exit(this, 0); break;
                case 'd': sortFunction = sortDuration; break;
                case 'D': sortFunction = sortDurationRev; break;
                case 'v': sortFunction = sortVMem; break;
                case 'V': sortFunction = sortVMemRev; break;
                case 'r': sortFunction = sortRSS; break;
                case 'R': sortFunction = sortRSSRev; break;
                case 'h': sortFunction = sortHostname; break;
                case 'H': sortFunction = sortHostnameRev; break;
                case 'u': sortFunction = sortUsername; break;
                case 'U': sortFunction = sortUsernameRev; break;
                case '5': sortFunction = sortCpuRate; break;
                case '%': sortFunction = sortCpuRateRev; break;
                case 'm': sortFunction = sortMpiRank; break;
                case 'M': sortFunction = sortMpiRankRev; break;
                case 'p': sortFunction = sortPid; break;
                case 'P': sortFunction = sortPidRev; break;
                case 'i': sortFunction = sortPPid; break;
                case 'I': sortFunction = sortPPidRev; break;
                case 't': sortFunction = sortThreads; break;
                case 'T': sortFunction = sortThreadsRev; break;
                case 'o': sortFunction = sortTotalIORead; break;
                case 'O': sortFunction = sortTotalIOReadRev; break;
                case 'w': sortFunction = sortTotalIOWrite; break;
                case 'W': sortFunction = sortTotalIOWriteRev; break;
                case 'a': sortFunction = sortAge; break;
                case 'A': sortFunction = sortAgeRev; break;
                case KEY_UP: highlight_row--; break;
                case KEY_DOWN: highlight_row++; break;
                case KEY_PPAGE: highlight_row -= 2*ylim; break;
                case KEY_NPAGE: highlight_row += ylim; break;
            };
            printScreen();
        }
    }

    void setProcData(const string &hostname, const string &jobid, const string &taskid, procdata *data, int n) {
        JobIdent ident(hostname, jobid, taskid);
        JobData *newData = NULL;
        int err;
        if ((err = pthread_mutex_lock(&data_lock)) != 0) fatal_error("setProcData failed to lock token.", err);
        auto it = newJobData.find(ident);
        if (it != newJobData.end()) {
            newData = (*it).second;
        } else {
            newData = new JobData();
        }
        newData->setProcData(data, n);
        if (checkAndMaybeSet(ident, newData)) {
            if (it != newJobData.end()) {
                newJobData.erase(it);
            }
        } else {
            newJobData[ident] = newData;
        }
        if ((err = pthread_mutex_unlock(&data_lock)) != 0) fatal_error("setProcData failed to unlock token.", err);
    }

    void setProcStat(const string &hostname, const string &jobid, const string &taskid, procstat *data, int n) {
        JobIdent ident(hostname, jobid, taskid);
        JobData *newData = NULL;
        int err;
        if ((err = pthread_mutex_lock(&data_lock)) != 0) fatal_error("setProcStat failed to lock token.", err);
        auto it = newJobData.find(ident);
        if (it != newJobData.end()) {
            newData = (*it).second;
        } else {
            newData = new JobData();
        }
        newData->setProcStat(data, n);
        if (checkAndMaybeSet(ident, newData)) {
            if (it != newJobData.end()) {
                newJobData.erase(it);
            }
        } else {
            newJobData[ident] = newData;
        }
        if ((err = pthread_mutex_unlock(&data_lock)) != 0) fatal_error("setProcStat failed to unlock token.", err);
    }

    bool checkAndMaybeSet(JobIdent &ident, JobData *newData) {
        class TrimPrintObj {
            CurrentJobData *jobData;
            public:
            TrimPrintObj(CurrentJobData *_jobData) {
                jobData = _jobData;
            }
            bool operator()(PrintData *tgt) {
                //return find(jobData->records.begin(), jobData->records.end(), tgt) != jobData->records.end();
                return false;
            }
        };

        if (newData->ps == NULL || newData->pd == NULL) {
            return false;
        }
        JobDataDelta *delta = NULL;
        auto it = jobData.find(ident);
        if (it != jobData.end()) {
            CurrentJobData *curr = it->second;
            JobData *oldData = (*it).second->data;
            delta = new JobDataDelta(newData, oldData);
//printData.erase(remove_if(printData.begin(), printData.end(), TrimPrintObj(curr)), printData.end());
            //remove_if(printData.begin(), printData.end(), TrimPrintObj(curr));
            delete it->second;
            it->second = NULL;
        }
        CurrentJobData *currData = new CurrentJobData(newData, delta);
        jobData[ident] = currData;

        for (int i = 0; i < newData->n_pd; i++) {
            procdata *pd = &(newData->pd[i]);
            procstat *ps = NULL;
            int ps_idx = 0;
            for (int j = 0; j < newData->n_ps && newData->ps[j].pid <= pd->pid; j++) {
                if (newData->ps[j].pid == pd->pid) {
                    ps = &(newData->ps[j]);
                    ps_idx = j;
                }
            }
            if (ps == NULL) {
                continue;
            }
            PrintData *d = new PrintData();
            d->hostname = ident.hostname;
            d->command =  string(pd->cmdArgs);
            auto user_it = usernames.find(ps->realUid);
            if (user_it != usernames.end()) {
                d->username = user_it->second;
            } else {
                struct passwd *user = getpwuid(ps->realUid);
                string username = "unknown";
                if (user != NULL) {
                    username = string(user->pw_name);
                }
                usernames[ps->realUid] = username;
                d->username = username;
            }

            replace(d->command.begin(), d->command.end(), '|', ' ');
            d->wallTime = (pd->recTime + pd->recTimeUSec*1e-6) - (pd->startTime + pd->startTimeUSec*1e-6);
            d->rate_cpu = NAN;
            d->rate_ioRead = NAN;
            d->rate_ioWrite = NAN;
            d->recTime = ps->recTime;
            d->pid = ps->pid;
            d->ppid = ps->ppid;
            if (delta != NULL && delta->dt > 0) {
                if (delta->d_utime[ps_idx] != NAN && delta->d_stime[ps_idx] != NAN)
                    d->rate_cpu = (delta->d_utime[ps_idx] + delta->d_stime[ps_idx]) / delta->dt;
                if (delta->d_ioread[ps_idx] != NAN) d->rate_ioRead = delta->d_ioread[ps_idx] / delta->dt;
                if (delta->d_iowrite[ps_idx] != NAN) d->rate_ioWrite = delta->d_iowrite[ps_idx] / delta->dt;
            }
            d->total_cpu = (ps->stime + ps->utime) / 100.;
            d->rss = ps->rss;
            d->vmem = ps->vsize;
            d->threads = ps->numThreads;
            d->state = ps->state;
            d->total_ioRead = ps->io_rchar;
            d->total_ioWrite = ps->io_wchar;
            d->mpiRank = ps->rtPriority;
            //currData->records.push_back(d);
            printData.push_back(d);
        }

        return true;
    }

    ~TopCurses() {
        endwin();

        for (auto it = columns.begin(); it != columns.end(); it++) {
            delete *it;
        }
    }

protected:

};

TopCurses *screen = NULL;
ProcAMQPIO *conn = NULL;

static void *screen_start(void *t_curses) {
    TopCurses *curses = (TopCurses *) t_curses;
    curses->eventLoop();
    delete curses;
}

static void *monitor_start(void *t_timeout) {
    int *timeout = (int *) t_timeout;
    last_update = time(NULL); //pretend we've seen an update recently
    int delta = 0;
    while (cleanup == 0) {
        sleep(2);
        delta = time(NULL) - last_update;
        if (delta > *timeout) {
            char buffer[1024];
            snprintf(buffer, 1024, "No data received for %d seconds", delta);
            fatal_error(buffer, 0);
        }
    }
}

static void screen_exit(TopCurses *screen, int exit_code) {
    cleanup = 1;
}

void fatal_error(const char *error, int err) {
    if (err != 0) {
        char buffer[1024];
        snprintf(buffer, 1024, "Failed: %s; bailing out.\n");
        errno = err;
        perror(buffer);
    } else {
        fprintf(stderr, "Failed: %s; %d; bailing out.\n", error, err);
    }
    screen_exit(screen, 1);
}

void sig_handler(int signum) {
    screen_exit(screen, 128 + signum);
}

int main(int argc, char **argv) {
    const char *mqServer = DEFAULT_AMQP_HOST;
    const char *mqVHost = DEFAULT_AMQP_VHOST;
    int mqPort = DEFAULT_AMQP_PORT;
    const char *mqUser = DEFAULT_AMQP_USER;
    const char *mqPassword = DEFAULT_AMQP_PASSWORD;
    const char *mqExchangeName = DEFAULT_AMQP_EXCHANGE_NAME;
    int mqFrameSize = DEFAULT_AMQP_FRAMESIZE;

    JobtopConfig config(argc, argv);

    screen = new TopCurses(config.getSystem(), config.getIdentifier(), config.getSubidentifier());
    signal(SIGTERM, sig_handler);
    signal(SIGINT, sig_handler);
    pthread_t screen_thread, monitor_thread;
    int retCode = pthread_create(&screen_thread, NULL, screen_start, screen);
    if (retCode != 0) {
        fatal_error("failed to start screen/interface thread", retCode);
    }
    retCode = pthread_create(&monitor_thread, NULL, monitor_start, &age_timeout);
    if (retCode != 0) {
        fatal_error("failed to start monitor thread", retCode);
    }

    conn = new ProcAMQPIO(mqServer, mqPort, mqVHost, mqUser, mqPassword, mqExchangeName, mqFrameSize, FILE_MODE_READ);
    conn->set_context(config.getHost(), config.getIdentifier(), config.getSubidentifier());

    void *data = NULL;
    size_t data_size = 0;
    int nRecords = 0;
    string hostname;
    string identifier;
    string subidentifier;

    /* TODO: add timer thread to look for idle-ness and kill the whole thing */

    while (cleanup == 0) {
        ProcRecordType recordType = conn->read_stream_record(&data, &data_size, &nRecords, 10000);
        conn->get_frame_context(hostname, identifier, subidentifier);

        if (data == NULL) {
            continue;
        }
        last_update = time(NULL);

        if (recordType == TYPE_PROCDATA) {
            procdata *ptr = (procdata *) data;
            screen->setProcData(hostname, identifier, subidentifier, ptr, nRecords);
        } else if (recordType == TYPE_PROCSTAT) {
            procstat *ptr = (procstat *) data;
            screen->setProcStat(hostname, identifier, subidentifier, ptr, nRecords);
        }
    }
    screen_exit(screen, 0);
    delete conn;
}

max_stars_repo_name: glennklockwood/procmon

max_issues_repo_name: glennklockwood/procmon

max_forks_repo_name: glennklockwood/procmon


text:
#pragma once

#include <string>
#include <unordered_set>

#include <boost/property_tree/ptree.hpp>

#include <msw/throw_runtime_error.hpp>

#include <rubetek/controller/specific_settings.hpp>

namespace rubetek    {
namespace controller {

    inline specific_settings read_global_settings(boost::property_tree::ptree const& pt, std::unordered_set<std::string> const& except_list = {"module_settings"})
    {
        std::unordered_set<std::string> names_of_added_settings;
        specific_settings global_settings;
        for (boost::property_tree::ptree::const_iterator i = pt.begin(); i != pt.end(); ++i)
        {
            std::string const name = i->first;
            std::string const value = i->second.get_value<std::string>();
            if (!value.empty() && !except_list.count(i->first))
            {
                if (names_of_added_settings.find(name) != names_of_added_settings.end()) msw::throw_runtime_error("setting '", name, "' already exists");
                names_of_added_settings.insert(name);
                global_settings.push_back(std::make_pair(name, value));
            }
        }
        return global_settings;
    }

}}

max_stars_repo_name: yklishevich/RubetekIOS-CPP-releases

max_issues_repo_name: yklishevich/RubetekIOS-CPP-releases

max_forks_repo_name: yklishevich/RubetekIOS-CPP-releases


text:
/*
Copyright (c) 2010-2018 Timur M. Khanipov <khanipov@gmail.com>.
Copyright (c) 2018, Visillect Service LLC. All rights reserved.
Developed for Kharkevich Institute for Information Transmission Problems of the
              Russian Academy of Sciences (IITP RAS).

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

   1. Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of copyright holders.
*/

#include <remseg/vertex.h>
#include <remseg/edge_heap.h>

#include <minbase/crossplat.h>
THIRDPARTY_INCLUDES_BEGIN
#include <Eigen/Dense>
THIRDPARTY_INCLUDES_END

#include <cassert>

namespace vi { namespace remseg {

Vertex::Vertex(const Vertex * v)
: channelsNum(v->channelsNum)
, channelsSum(0)
, area(v->area)
, needsSort(v->needsSort)
, existence_flag(v->existence_flag)
, absorbent(v->absorbent)
{
  Initialize(channelsNum);
  for (int i = 0; i < channelsNum; i++)
    channelsSum[i] = v->channelsSum[i];
}

void Vertex::Initialize(int _channelsNum)
{
  assert(_channelsNum > 0);
  channelsNum = _channelsNum;
  channelsSum = new long double[channelsNum];
  for (int i = 0; i < channelsNum; i++)
    channelsSum[i] = 0;
}

Vertex::~Vertex()
{
  if (channelsSum != NULL)
    delete[] channelsSum;
}

bool Vertex::isConnectedTo(const Vertex *v) const
{
  assert(v);
  for (ConstJoint it = begin(); it != end(); it++)
    if (it->vertex == v)
      return true;
  return false;
}

Vertex *Vertex::nearestNeighbour() const
{
  if (empty())
    return 0;
  EdgeValue minDist = begin()->edge->value;
  Vertex *nn = begin()->vertex;
  for (ConstJoint it = begin(); it != end(); it++)
    if (it->edge->value < minDist)
    {
      minDist = it->edge->value;
      nn = it->vertex;
    }
  return nn;
}

bool Vertex::isSorted() const
{
  if (empty())
    return true;
  ConstJoint next = begin();
  next++;
  for (ConstJoint current = begin(); next != end(); current++, next++)
    if (*next < *current)
      return false;
  return true;
}

void Vertex::update(const double * pix)
{
  const int n = channelsNum;
  for (int i = 0; i < n; ++i)
    channelsSum[i] += pix[i];
  area += 1;
}

void Vertex::update(const uint8_t * pix)
{
  const int n = channelsNum;
  for (int i = 0; i < n; ++i)
    channelsSum[i] += (long double)pix[i];
  area += 1;
}

void Vertex::absorb(Vertex *v)
{
  assert(v and v->exists());
  v->existence_flag = false;
  v->absorbent = this;

  for (int i = 0; i < channelsNum; i++)
    channelsSum[i] += v->channelsSum[i];

  area += v->area;
}

Vertex *Vertex::getFinalAbsorbent() const
{
  Vertex *v;
  for (v = absorbent; v and v->absorbent; v = v->absorbent)
    ;
  return v;
}

Joint Vertex::orderedInsert(Vertex *v)
{
  assert(v  and  v != this);

  Joint it = begin();
  while (it != end() and it->vertex < v)
    it++;
  assert(it == end()  or  it->vertex != v);	// попытка повтыорного добавления вершины

  return insert(it, Link(v));
}

Json::Value Vertex::jsonLog() const
{
  Json::Value root;

  root["area"] = (int)area;
  root["mean"] = Json::arrayValue;
  for (int i = 0; i < channelsNum; ++i)
    root["mean"].append(double(channelsSum[i]) / area);
  return root;
}

}}	// ns vi::remseg

max_stars_repo_name: dketterer/colorsegmentation

max_issues_repo_name: Visillect/segmentation

max_forks_repo_name: Visillect/segmentation


text:
//
// Copyright (c) 2021 Richard Hodges (hodges.r@gmail.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)
//
// Official repository: https://github.com/madmongo1/boost_channels
//

#ifndef BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_CONCEPTS_EQUALITY_COMPARABLE_HPP
#define BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_CONCEPTS_EQUALITY_COMPARABLE_HPP

#include <type_traits>
#include <boost/channels/concepts/boolean_testable.hpp>

namespace boost::channels::concepts
{
// clang-format off
template <class T, class U>
concept equality_comparable_with = requires(T const& l, U const& r)
{
    { l == r } -> boolean_testable;
};

template < class T >
concept equality_comparable = equality_comparable_with<T, T>;

// clang-format on
}
#endif   // BOOST_CHANNELS_INCLUDE_BOOST_CHANNELS_CONCEPTS_EQUALITY_COMPARABLE_HPP


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

 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         pattern_except.hpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: Declares pattern-matching exception classes.
  */

#ifndef BOOST_RE_PAT_EXCEPT_HPP
#define BOOST_RE_PAT_EXCEPT_HPP

#ifndef BOOST_REGEX_CONFIG_HPP
#include <boost/regex/config.hpp>
#endif

namespace boost{

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4275)
#endif
class BOOST_REGEX_DECL bad_pattern : public std::runtime_error
{
public:
   explicit bad_pattern(const std::string& s) : std::runtime_error(s){};
   ~bad_pattern() throw();
};
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif

class BOOST_REGEX_DECL bad_expression : public bad_pattern
{
public:
   explicit bad_expression(const std::string& s) : bad_pattern(s) {}
   ~bad_expression() throw();
};

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

} // namespace boost

#endif

max_stars_repo_name: macaurther/DOCUSA

max_issues_repo_name: macaurther/DOCUSA

max_forks_repo_name: dguenms/Dawn-of-Civilization