text:
/**
* Connected Vision - https://github.com/ConnectedVision
* MIT License
*/

// auto-generated header by CodeFromTemplate - Connected Vision - https://github.com/ConnectedVision
// CodeFromTemplate Version: 0.3 alpha
// stubs/Stub_generic_status.cpp
// NEVER TOUCH this file!

#include <utility>

#include <rapidjson/document.h>
#include <rapidjson/prettywriter.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/error/en.h>
#include <boost/make_shared.hpp>

#include "Stub_generic_status.h"
#include "../Class_generic_status.h"

// --> Do NOT EDIT <--
namespace ConnectedVision {

const boost::shared_ptr<std::string> Stub_generic_status::status_na = boost::make_shared<std::string>("n/a");
const boost::shared_ptr<std::string> Stub_generic_status::status_init = boost::make_shared<std::string>("init");
const boost::shared_ptr<std::string> Stub_generic_status::status_starting = boost::make_shared<std::string>("starting");
const boost::shared_ptr<std::string> Stub_generic_status::status_running = boost::make_shared<std::string>("running");
const boost::shared_ptr<std::string> Stub_generic_status::status_stopping = boost::make_shared<std::string>("stopping");
const boost::shared_ptr<std::string> Stub_generic_status::status_stopped = boost::make_shared<std::string>("stopped");
const boost::shared_ptr<std::string> Stub_generic_status::status_finished = boost::make_shared<std::string>("finished");
const boost::shared_ptr<std::string> Stub_generic_status::status_error = boost::make_shared<std::string>("error");
const boost::shared_ptr<std::string> Stub_generic_status::status_recovering = boost::make_shared<std::string>("recovering");
const boost::shared_ptr<std::string> Stub_generic_status::status_resetting = boost::make_shared<std::string>("resetting");

// --> Do NOT EDIT <--
/* copy constructors */
Stub_generic_status::Stub_generic_status(const Stub_generic_status& other)
{
	// TODO: other.readLock
	// id
	id = other.id;
	// timestamp
	timestamp = other.timestamp;
	// moduleID
	moduleID = other.moduleID;
	// moduleURI
	if ( other.moduleURI )
		moduleURI = boost::make_shared<std::string>(*other.moduleURI);
	// commandQueue
	{
		const auto& n0 = other.commandQueue;
		auto a0 = boost::make_shared<std::vector<boost::shared_ptr<std::string>>>( (n0->size()) );
		for (size_t i0 = 0; i0 < n0->size(); ++i0)
		{
			if ( n0->at(i0) )
				a0->at(i0) = boost::make_shared<std::string>( *n0->at(i0) );
		}
		commandQueue = a0;
	}
	// status
	if ( other.status )
		status = boost::make_shared<std::string>(*other.status);
	// message
	if ( other.message )
		message = boost::make_shared<std::string>(*other.message);
	// progress
	progress = other.progress;
	// startTime
	startTime = other.startTime;
	// systemTimeProcessing
	systemTimeProcessing = other.systemTimeProcessing;
	// estimatedFinishTime
	estimatedFinishTime = other.estimatedFinishTime;
	// qualityOfService
	if ( other.qualityOfService )
		qualityOfService = boost::make_shared<Class_generic_status_qualityOfService>(*other.qualityOfService);
	// stableResults
	{
		const auto& n0 = other.stableResults;
		auto a0 = boost::make_shared<std::vector<boost::shared_ptr<Class_generic_status_stableResults>>>( (n0->size()) );
		for (size_t i0 = 0; i0 < n0->size(); ++i0)
		{
			if ( n0->at(i0) )
				a0->at(i0) = boost::make_shared<Class_generic_status_stableResults>( *n0->at(i0) );
		}
		stableResults = a0;
	}
	// chain
	{
		const auto& n0 = other.chain;
		auto a0 = boost::make_shared<std::vector<boost::shared_ptr<std::string>>>( (n0->size()) );
		for (size_t i0 = 0; i0 < n0->size(); ++i0)
		{
			if ( n0->at(i0) )
				a0->at(i0) = boost::make_shared<std::string>( *n0->at(i0) );
		}
		chain = a0;
	}
	// configID
	configID = other.configID;
}

// --> Do NOT EDIT <--
/* copy assignment operator */
Stub_generic_status& Stub_generic_status::operator =(const Stub_generic_status& other)
{
	Stub_generic_status tmp(other); // re-use copy-constructor
	*this = std::move(tmp); // re-use move-assignment
	return *this;
}

// --> Do NOT EDIT <--
/* mopy assignment operator */
Stub_generic_status& Stub_generic_status::operator =(Stub_generic_status&& other) noexcept
{
	// id
    std::swap(id, other.id);
	// timestamp
    std::swap(timestamp, other.timestamp);
	// moduleID
    std::swap(moduleID, other.moduleID);
	// moduleURI
    std::swap(moduleURI, other.moduleURI);
	// commandQueue
    std::swap(commandQueue, other.commandQueue);
	// status
    std::swap(status, other.status);
	// message
    std::swap(message, other.message);
	// progress
    std::swap(progress, other.progress);
	// startTime
    std::swap(startTime, other.startTime);
	// systemTimeProcessing
    std::swap(systemTimeProcessing, other.systemTimeProcessing);
	// estimatedFinishTime
    std::swap(estimatedFinishTime, other.estimatedFinishTime);
	// qualityOfService
    std::swap(qualityOfService, other.qualityOfService);
	// stableResults
    std::swap(stableResults, other.stableResults);
	// chain
    std::swap(chain, other.chain);
	// configID
    std::swap(configID, other.configID);

	return *this;
}

// --> Do NOT EDIT <--
/* default constructors */
Stub_generic_status::Stub_generic_status()
{
	clear();
}

// --> Do NOT EDIT <--
Stub_generic_status::Stub_generic_status(const rapidjson::Value& value)
{
	clear();
	parseJson( value );
}

// --> Do NOT EDIT <--
Stub_generic_status::Stub_generic_status(const std::string& str)
{
	clear();
	parseJson( str );
}

// --> Do NOT EDIT <--
Stub_generic_status::~Stub_generic_status()
{
}

// --> Do NOT EDIT <--
void Stub_generic_status::clear()
{
	this->id = "";
	this->timestamp = 0;
	this->moduleID = "";
	this->moduleURI.reset( new std::string("") );
	this->commandQueue.reset( new std::vector<boost::shared_ptr<std::string>> );
	this->status.reset( new std::string("n/a") );
	this->message.reset( new std::string("") );
	this->progress = static_cast<double>(0);
	this->startTime = -1;
	this->systemTimeProcessing = -1;
	this->estimatedFinishTime = -1;
	this->qualityOfService.reset( new Class_generic_status_qualityOfService );
	this->stableResults.reset( new std::vector<boost::shared_ptr<Class_generic_status_stableResults>> );
	this->chain.reset( new std::vector<boost::shared_ptr<std::string>> );
	this->configID = "";
}

// --> Do NOT EDIT <--
void Stub_generic_status::parseJson(const char *str)
{
	// ignore empty data
	if ( str[0] == 0 )
		return;

	// parse data
	rapidjson::Document document;
	if (document.Parse<0>(str).HasParseError())
	{
		std::string context;
		size_t off = document.GetErrorOffset();
		size_t i, line_start = 0, context_start = 0;
		int num_line = 1;
		for ( i = 0; (i < off) && str[i]; i++ )
		{
			if ( str[i] == '\n' )
			{ line_start = i+1; context_start = i+1; num_line++; }
			if ( str[i] == '{' || str[i] == '[' )
			{ context_start = i; }
		}
		for ( i = context_start; str[i]; i++ )
		{
			if ( str[i] == '\n' || str[i] == '\r' ) break;
			context += str[i];
			if ( str[i] == '}' || str[i] == ']' ) break;
		}
		throw ConnectedVision::runtime_error( std::string("parse error of JSON Object: ") + rapidjson::GetParseError_En(document.GetParseError()) + std::string(" at line ") + ConnectedVision::intToStr( num_line ) + ": " + context);
	}

	parseJson(document);
}

// --> Do NOT EDIT <--
void Stub_generic_status::parseJson(const rapidjson::Value& value)
{
	clear();
	if ( !value.IsObject() )
		throw ConnectedVision::runtime_error( "no JSON Object");

	// id
	if ((value.HasMember("id")) && value["id"].IsString())
	{
		set_id( ConnectedVision::strToID( value["id"].GetString() ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'id'");

	// timestamp
	if ((value.HasMember("timestamp")) && value["timestamp"].IsInt64())
	{
		set_timestamp( value["timestamp"].GetInt64() );
	}
	// moduleID
	if ((value.HasMember("moduleID")) && value["moduleID"].IsString())
	{
		set_moduleID( ConnectedVision::strToID( value["moduleID"].GetString() ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'moduleID'");

	// moduleURI
	if ((value.HasMember("moduleURI")) && value["moduleURI"].IsString())
	{
		set_moduleURI( boost::shared_ptr<std::string>( new std::string( value["moduleURI"].GetString() ) ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'moduleURI'");

	// commandQueue
	if ((value.HasMember("commandQueue")) && value["commandQueue"].IsArray())
	{
		const rapidjson::Value& n0 = value["commandQueue"];
		boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>> a0( new std::vector<boost::shared_ptr<std::string>>(n0.Size()) );
		for (rapidjson::SizeType i0 = 0; i0 < n0.Size(); i0++)
		{
			a0->at(i0) = boost::shared_ptr<std::string>( new std::string( n0[i0].GetString() ) );
		}
		set_commandQueue( a0 );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'commandQueue'");

	// status
	if ((value.HasMember("status")) && value["status"].IsString())
	{
		set_status( boost::shared_ptr<std::string>( new std::string( value["status"].GetString() ) ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'status'");

	// message
	if ((value.HasMember("message")) && value["message"].IsString())
	{
		set_message( boost::shared_ptr<std::string>( new std::string( value["message"].GetString() ) ) );
	}
	// progress
	if ((value.HasMember("progress")) && value["progress"].IsNumber())
	{
		set_progress( value["progress"].GetDouble() );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'progress'");

	// startTime
	if ((value.HasMember("startTime")) && value["startTime"].IsInt64())
	{
		set_startTime( value["startTime"].GetInt64() );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'startTime'");

	// systemTimeProcessing
	if ((value.HasMember("systemTimeProcessing")) && value["systemTimeProcessing"].IsInt64())
	{
		set_systemTimeProcessing( value["systemTimeProcessing"].GetInt64() );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'systemTimeProcessing'");

	// estimatedFinishTime
	if ((value.HasMember("estimatedFinishTime")) && value["estimatedFinishTime"].IsInt64())
	{
		set_estimatedFinishTime( value["estimatedFinishTime"].GetInt64() );
	}
	// qualityOfService
	if ((value.HasMember("qualityOfService")) && value["qualityOfService"].IsObject())
	{
		set_qualityOfService( boost::shared_ptr<Class_generic_status_qualityOfService>( new Class_generic_status_qualityOfService( value["qualityOfService"] ) ) );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'qualityOfService'");

	// stableResults
	if ((value.HasMember("stableResults")) && value["stableResults"].IsArray())
	{
		const rapidjson::Value& n0 = value["stableResults"];
		boost::shared_ptr<std::vector<boost::shared_ptr<Class_generic_status_stableResults>>> a0( new std::vector<boost::shared_ptr<Class_generic_status_stableResults>>(n0.Size()) );
		for (rapidjson::SizeType i0 = 0; i0 < n0.Size(); i0++)
		{
			a0->at(i0) = boost::shared_ptr<Class_generic_status_stableResults>( new Class_generic_status_stableResults( n0[i0] ) );
		}
		set_stableResults( a0 );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'stableResults'");

	// chain
	if ((value.HasMember("chain")) && value["chain"].IsArray())
	{
		const rapidjson::Value& n0 = value["chain"];
		boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>> a0( new std::vector<boost::shared_ptr<std::string>>(n0.Size()) );
		for (rapidjson::SizeType i0 = 0; i0 < n0.Size(); i0++)
		{
			a0->at(i0) = boost::shared_ptr<std::string>( new std::string( ConnectedVision::jsonToStr(n0[i0]) ) );
		}
		set_chain( a0 );
	}
	else
		throw ConnectedVision::runtime_error( "required member is missing: 'chain'");

}

// --> Do NOT EDIT <--
std::string Stub_generic_status::toJsonStr() const
{
	rapidjson::StringBuffer s;
	rapidjson::Document doc; doc.SetObject();
	this->toJson(doc, doc.GetAllocator());
	rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(s);
	doc.Accept(writer);
	return std::string(s.GetString());
}

// --> Do NOT EDIT <--
std::string Stub_generic_status::toJson() const
{
	rapidjson::StringBuffer s;
	rapidjson::Document doc; doc.SetObject();
	this->toJson(doc, doc.GetAllocator());
	rapidjson::Writer<rapidjson::StringBuffer> writer(s);
	doc.Accept(writer);
	return std::string(s.GetString());
}

// --> Do NOT EDIT <--
rapidjson::Value& Stub_generic_status::toJson(rapidjson::Value& node, rapidjson::Value::AllocatorType& allocator) const
{
	{ // id
		node.AddMember("id", rapidjson::Value().SetString( ConnectedVision::IDToChar( get_id() ), allocator), allocator);
	}
	{ // timestamp
		node.AddMember("timestamp", rapidjson::Value().SetInt64( get_timestamp() ), allocator);
	}
	{ // moduleID
		node.AddMember("moduleID", rapidjson::Value().SetString( ConnectedVision::IDToChar( get_moduleID() ), allocator), allocator);
	}
	{ // moduleURI
		node.AddMember("moduleURI", rapidjson::Value().SetString( get_moduleURI()->c_str(), allocator), allocator);
	}
	{ // commandQueue
		rapidjson::Value n0; n0.SetArray();
		boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>>&& a0 = get_commandQueue(); // rvalue reference for const functions
		for (size_t i0 = 0; i0 < a0->size(); i0++)
		{
			// process array level 0
			// final level of array, add string
			n0.PushBack(rapidjson::Value().SetString( a0->at(i0)->c_str(), allocator), allocator);
		}
		node.AddMember("commandQueue", n0, allocator);
	}
	{ // status
		node.AddMember("status", rapidjson::Value().SetString( get_status()->c_str(), allocator), allocator);
	}
	{ // message
		node.AddMember("message", rapidjson::Value().SetString( get_message()->c_str(), allocator), allocator);
	}
	{ // progress
		node.AddMember("progress", rapidjson::Value().SetDouble( get_progress() ), allocator);
	}
	{ // startTime
		node.AddMember("startTime", rapidjson::Value().SetInt64( get_startTime() ), allocator);
	}
	{ // systemTimeProcessing
		node.AddMember("systemTimeProcessing", rapidjson::Value().SetInt64( get_systemTimeProcessing() ), allocator);
	}
	{ // estimatedFinishTime
		node.AddMember("estimatedFinishTime", rapidjson::Value().SetInt64( get_estimatedFinishTime() ), allocator);
	}
	{ // qualityOfService
		node.AddMember("qualityOfService", get_qualityOfService()->toJson( rapidjson::Value().SetObject(), allocator), allocator);
	}
	{ // stableResults
		rapidjson::Value n0; n0.SetArray();
		boost::shared_ptr<std::vector<boost::shared_ptr<Class_generic_status_stableResults>>>&& a0 = get_stableResults(); // rvalue reference for const functions
		for (size_t i0 = 0; i0 < a0->size(); i0++)
		{
			// process array level 0
			// final dimension of array, add actual value
			if ( a0->at(i0) )	// ensure that we have no NULL pointer
			{
				n0.PushBack(a0->at(i0)->toJson( rapidjson::Value().SetObject(), allocator), allocator);
			}
		}
		node.AddMember("stableResults", n0, allocator);
	}
	{ // chain
		rapidjson::Value n0; n0.SetArray();
		boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>>&& a0 = get_chain(); // rvalue reference for const functions
		for (size_t i0 = 0; i0 < a0->size(); i0++)
		{
			// process array level 0
			// final level of array, add raw data
			if ( a0->at(i0) )	// ensure that we have no NULL pointer
			{
				rapidjson::Document doc(&allocator);
				doc.Parse<0>( a0->at(i0)->c_str() );
				n0.PushBack(static_cast<rapidjson::Value&>(doc), allocator);
			}
		}
		node.AddMember("chain", n0, allocator);
	}
	return node;
}

// --> Do NOT EDIT <--
ConnectedVision::id_t Stub_generic_status::get_id() const
{
	return( this->id );
}

// --> Do NOT EDIT <--
const ConnectedVision::id_t Stub_generic_status::getconst_id() const
{
	return( this->id );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_id(ConnectedVision::id_t value)
{
	this->id = value;
}

// --> Do NOT EDIT <--
ConnectedVision::timestamp_t Stub_generic_status::get_timestamp() const
{
	return( this->timestamp );
}

// --> Do NOT EDIT <--
const ConnectedVision::timestamp_t Stub_generic_status::getconst_timestamp() const
{
	return( this->timestamp );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_timestamp(ConnectedVision::timestamp_t value)
{
	this->timestamp = value;
}

// --> Do NOT EDIT <--
ConnectedVision::id_t Stub_generic_status::get_moduleID() const
{
	return( this->moduleID );
}

// --> Do NOT EDIT <--
const ConnectedVision::id_t Stub_generic_status::getconst_moduleID() const
{
	return( this->moduleID );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_moduleID(ConnectedVision::id_t value)
{
	this->moduleID = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::string> Stub_generic_status::get_moduleURI() const
{
	return( this->moduleURI );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::string> Stub_generic_status::getconst_moduleURI() const
{
	return( boost::static_pointer_cast<const std::string>(this->moduleURI) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_moduleURI(boost::shared_ptr<std::string> value)
{
	this->moduleURI = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>> Stub_generic_status::get_commandQueue() const
{
	return( this->commandQueue );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::vector<boost::shared_ptr<std::string>>> Stub_generic_status::getconst_commandQueue() const
{
	return( boost::static_pointer_cast<const std::vector<boost::shared_ptr<std::string>>>(this->commandQueue) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_commandQueue(boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>> value)
{
	this->commandQueue = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::string> Stub_generic_status::get_commandQueue(int index) const
{
	return( this->commandQueue->at(index) );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<std::string>& Stub_generic_status::getconst_commandQueue(int index) const
{
	return( this->commandQueue->at(index) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::add_commandQueue(boost::shared_ptr<std::string> value)
{
	this->commandQueue->push_back(value);
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::string> Stub_generic_status::get_status() const
{
	return( this->status );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::string> Stub_generic_status::getconst_status() const
{
	return( boost::static_pointer_cast<const std::string>(this->status) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_status(boost::shared_ptr<std::string> value)
{
	this->status = value;
}

// --> Do NOT EDIT <--
bool Stub_generic_status::is_status(const boost::shared_ptr<std::string> &value) const
{
	return ( (*this->status) == (*value) );
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::string> Stub_generic_status::get_message() const
{
	return( this->message );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::string> Stub_generic_status::getconst_message() const
{
	return( boost::static_pointer_cast<const std::string>(this->message) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_message(boost::shared_ptr<std::string> value)
{
	this->message = value;
}

// --> Do NOT EDIT <--
double Stub_generic_status::get_progress() const
{
	return( this->progress );
}

// --> Do NOT EDIT <--
const double Stub_generic_status::getconst_progress() const
{
	return( this->progress );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_progress(double value)
{
	this->progress = value;
}

// --> Do NOT EDIT <--
ConnectedVision::timestamp_t Stub_generic_status::get_startTime() const
{
	return( this->startTime );
}

// --> Do NOT EDIT <--
const ConnectedVision::timestamp_t Stub_generic_status::getconst_startTime() const
{
	return( this->startTime );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_startTime(ConnectedVision::timestamp_t value)
{
	this->startTime = value;
}

// --> Do NOT EDIT <--
ConnectedVision::timestamp_t Stub_generic_status::get_systemTimeProcessing() const
{
	return( this->systemTimeProcessing );
}

// --> Do NOT EDIT <--
const ConnectedVision::timestamp_t Stub_generic_status::getconst_systemTimeProcessing() const
{
	return( this->systemTimeProcessing );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_systemTimeProcessing(ConnectedVision::timestamp_t value)
{
	this->systemTimeProcessing = value;
}

// --> Do NOT EDIT <--
ConnectedVision::timestamp_t Stub_generic_status::get_estimatedFinishTime() const
{
	return( this->estimatedFinishTime );
}

// --> Do NOT EDIT <--
const ConnectedVision::timestamp_t Stub_generic_status::getconst_estimatedFinishTime() const
{
	return( this->estimatedFinishTime );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_estimatedFinishTime(ConnectedVision::timestamp_t value)
{
	this->estimatedFinishTime = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<Class_generic_status_qualityOfService> Stub_generic_status::get_qualityOfService() const
{
	return( this->qualityOfService );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const Class_generic_status_qualityOfService> Stub_generic_status::getconst_qualityOfService() const
{
	return( boost::static_pointer_cast<const Class_generic_status_qualityOfService>(this->qualityOfService) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_qualityOfService(boost::shared_ptr<Class_generic_status_qualityOfService> value)
{
	this->qualityOfService = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::vector<boost::shared_ptr<Class_generic_status_stableResults>>> Stub_generic_status::get_stableResults() const
{
	return( this->stableResults );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::vector<boost::shared_ptr<Class_generic_status_stableResults>>> Stub_generic_status::getconst_stableResults() const
{
	return( boost::static_pointer_cast<const std::vector<boost::shared_ptr<Class_generic_status_stableResults>>>(this->stableResults) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_stableResults(boost::shared_ptr<std::vector<boost::shared_ptr<Class_generic_status_stableResults>>> value)
{
	this->stableResults = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<Class_generic_status_stableResults> Stub_generic_status::get_stableResults(int index) const
{
	return( this->stableResults->at(index) );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<Class_generic_status_stableResults>& Stub_generic_status::getconst_stableResults(int index) const
{
	return( this->stableResults->at(index) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::add_stableResults(boost::shared_ptr<Class_generic_status_stableResults> value)
{
	this->stableResults->push_back(value);
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>> Stub_generic_status::get_chain() const
{
	return( this->chain );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<const std::vector<boost::shared_ptr<std::string>>> Stub_generic_status::getconst_chain() const
{
	return( boost::static_pointer_cast<const std::vector<boost::shared_ptr<std::string>>>(this->chain) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_chain(boost::shared_ptr<std::vector<boost::shared_ptr<std::string>>> value)
{
	this->chain = value;
}

// --> Do NOT EDIT <--
boost::shared_ptr<std::string> Stub_generic_status::get_chain(int index) const
{
	return( this->chain->at(index) );
}

// --> Do NOT EDIT <--
const boost::shared_ptr<std::string>& Stub_generic_status::getconst_chain(int index) const
{
	return( this->chain->at(index) );
}

// --> Do NOT EDIT <--
void Stub_generic_status::add_chain(boost::shared_ptr<std::string> value)
{
	this->chain->push_back(value);
}

// --> Do NOT EDIT <--
ConnectedVision::id_t Stub_generic_status::get_configID() const
{
	return( this->configID );
}

// --> Do NOT EDIT <--
const ConnectedVision::id_t Stub_generic_status::getconst_configID() const
{
	return( this->configID );
}

// --> Do NOT EDIT <--
void Stub_generic_status::set_configID(ConnectedVision::id_t value)
{
	this->configID = value;
}

} // namespace ConnectedVision

max_stars_repo_name: ConnectedVision/ConnectedVision

max_issues_repo_name: ConnectedVision/ConnectedVision

max_forks_repo_name: ConnectedVision/ConnectedVision


text:
#include <string>
#include <iostream>
#include <cstdint>
#include <boost/bind.hpp>

#include "pandar_api/tcp_client.hpp"

namespace{
  const uint16_t API_PORT = 9347;
  const size_t HEADER_SIZE = 8;

  inline int64_t parse64(uint8_t* raw){
    return htobe64(*((int64_t*)raw));
  }

  inline uint32_t parse32(uint8_t* raw){
    return htobe32(*((uint32_t*)raw));
  }

  inline uint16_t parse16(uint8_t* raw){
    return htobe16(*((uint16_t*)raw));
  }
}

namespace pandar_api
{
TCPClient::TCPClient(const std::string& device_ip, int32_t timeout)
  : io_service_(),
    socket_(io_service_),
    timer_(io_service_),
    return_code_(ReturnCode::SUCCESS),
    timeout_(timeout)
{
  device_ip_ = boost::asio::ip::address::from_string(device_ip);
}

TCPClient::ReturnCode TCPClient::getInventoryInfo(InventoryInfo& info)
{
  header_ = MessageHeader();
  header_.cmd = PTC_COMMAND_GET_INVENTORY_INFO;
  payload_.clear();
  connect();
  if(return_code_ != ReturnCode::SUCCESS){
    return return_code_;
  }
  uint8_t* it = payload_.data();

  info.sn = std::string(it, it + 18);
  it += 18;

  info.date_of_manufacture = std::string(it, it + 16);
  it += 16;

  info.mac = std::string(it, it + 6);
  it += 6;

  info.sw_ver = std::string(it, it + 16);
  it += 16;

  info.hw_ver = std::string(it, it + 16);
  it += 16;

  info.control_fw_ver = std::string(it, it + 16);
  it += 16;

  info.sensor_fw_ver = std::string(it, it + 16);
  it += 16;

  info.angle_offset = parse16(it);
  it += 2;

  if(*it == 0){
    info.model = "Pandar40P";
  }else if(*it == 2){
    info.model = "Pandar64";
  }else if(*it == 3){
    info.model = "Pandar128";
  }else if(*it == 15){
    info.model = "PandarQT";
  }else if(*it == 17){
    info.model = "Pandar40M";
  }else{
    info.model = "unknown";
  }
  it += 1;

  if(*it == 0){
    info.motor_type = "single direction";
  }else{
    info.motor_type = "dual direction";
  }
  it += 1;

  info.num_of_lines = *it;
  it += 1;
  return return_code_;
}

TCPClient::ReturnCode TCPClient::getLidarCalibration(std::string& content)
{
  header_ = MessageHeader();
  payload_.clear();
  header_.cmd = PTC_COMMAND_GET_LIDAR_CALIBRATION;
  connect();
  if(return_code_ == ReturnCode::SUCCESS){
    content = std::string(payload_.data(), payload_.data() + payload_.size());
  }
  return return_code_;
}

TCPClient::ReturnCode TCPClient::getLidarRange(uint16_t* range)
{
  header_ = MessageHeader();
  header_.cmd = PTC_COMMAND_GET_LIDAR_RANGE;
  payload_.clear();
  connect();
  if(return_code_ == ReturnCode::SUCCESS){
    if(payload_[0] != 0){
      // not support each-channel / multi-section
      return ReturnCode::NO_SUPPORT;
    }else{
      range[0] = parse16(&payload_[1]) * 10;
      range[1] = parse16(&payload_[3]) * 10;
      return return_code_;
    }
  }else{
    return return_code_;
  }
}

TCPClient::ReturnCode TCPClient::getLidarStatus(LidarStatus& status)
{
  header_ = MessageHeader();
  header_.cmd = PTC_COMMAND_GET_LIDAR_STATUS;
  payload_.clear();
  connect();
  if(return_code_ == ReturnCode::SUCCESS){
    uint8_t* it = payload_.data();

    status.uptime = parse32(it);
    it += 4;
    status.motor_speed = parse16(it);
    it += 2;
    status.temp[8];
    for(int i = 0; i < 8; i++){
      status.temp[i] = parse32(it);
      it += 4;
    }
    status.gps_pps_lock = *it;
    it+=1;

    status.gps_gprmc_status = *it;
    it+=1;

    status.startup_times = parse32(it);
    it += 4;

    status.total_operation_time = parse32(it);
    it += 4;

    status.ptp_clock_status = *it;

    return return_code_;
  }else{
    return return_code_;
  }
}

TCPClient::ReturnCode TCPClient::getPTPDiagnostics(PTPDiag& diag)
{
  header_ = MessageHeader();
  header_.cmd = PTC_COMMAND_PTP_DIAGNOSTICS;
  header_.payload_length = 1;
  payload_.clear();
  payload_.push_back(0x01);

  connect();
  if(return_code_ == ReturnCode::SUCCESS){
    uint8_t* it = payload_.data();
    diag.master_offset = parse64(it);
    it += 8;
    uint32_t test = parse32(it);
    it += 4;
    diag.elapsed_millisec = parse32(it);
    it += 4;
    std::cout << diag.master_offset << std::endl;
    std::cout << test << std::endl;
    std::cout << diag.elapsed_millisec << std::endl;
  }
  return return_code_;
}

void TCPClient::connect()
{
  io_service_.reset();
  socket_.async_connect(
    boost::asio::ip::tcp::endpoint(device_ip_, API_PORT),
    boost::bind(&TCPClient::on_connect, this, boost::asio::placeholders::error));

  timer_.expires_from_now(std::chrono::milliseconds(timeout_));
  timer_.async_wait(boost::bind(&TCPClient::on_timer, this, boost::placeholders::_1));
  io_service_.run();
}

void TCPClient::on_connect(const boost::system::error_code& error)
{
  if (error) {
    return_code_ = ReturnCode::CONNECTION_FAILED;
    return;
  }

  // send header
  buffer_.clear();

  buffer_.resize(HEADER_SIZE + payload_.size());
  header_.write(buffer_.data());
  std::memcpy(buffer_.data() + HEADER_SIZE, payload_.data(), payload_.size());

  boost::asio::async_write(
      socket_,
      boost::asio::buffer(buffer_),
      boost::bind(&TCPClient::on_send, this, boost::asio::placeholders::error));
}

void TCPClient::on_send(const boost::system::error_code& error)
{
  if (error) {
    return_code_ = ReturnCode::CONNECTION_FAILED;
    return;
  }

  boost::asio::async_read(
  socket_,
  boost::asio::buffer(buffer_),
  boost::asio::transfer_exactly(HEADER_SIZE),
  boost::bind(&TCPClient::on_receive, this, boost::asio::placeholders::error));
}

void TCPClient::on_receive(const boost::system::error_code& error)
{
  if (error) {
    return_code_ = ReturnCode::CONNECTION_FAILED;
    return;
  }
  header_.read(buffer_.data());
  if(header_.protocol_identifier[0] != 0x47 || header_.protocol_identifier[1] != 0x74){
    return_code_ = ReturnCode::CONNECTION_FAILED;
    socket_.close();
    return;
  }else if((ReturnCode)header_.return_code != ReturnCode::SUCCESS) {
    return_code_ = (ReturnCode)header_.return_code;
    socket_.close();
    return;
  }

  // receive payload
  if (header_.payload_length > 0){
    payload_.resize(header_.payload_length);
    boost::asio::async_read(
        socket_,
        boost::asio::buffer(payload_),
        boost::asio::transfer_exactly(payload_.size()),
        [this](const boost::system::error_code& error, std::size_t)
        {
          if (error){
            return_code_ = ReturnCode::CONNECTION_FAILED;
          }
          else {
            socket_.close();
            timer_.cancel();
            return;
          }
        });
  }
}

void TCPClient::on_timer(const boost::system::error_code& error)
{
  if (!error) {
    return_code_ = ReturnCode::CONNECTION_FAILED;
    socket_.close();
  }
}

}  // namespace pandar_api

ext: cpp


text:
#include "XradiaReader.h"
#include "api.h"
#include <hxcore/HxData.h>
#include <hxfield/HxUniformScalarField3.h>
#include <amiramesh/HxParamBundle.h>
#include "CCPiAvizoUserInterface.h"
#if AVIZO_UNSUPPORTED_INTERNAL
#include <hxcore/internal/HxWorkArea.h>
#include <hxcore/internal/HxThread.h>
#else
#include <hxcore/HxWorkArea.h>
#include <hxcore/HxThread.h>
#endif
#include <QApplication>
#include <boost/filesystem.hpp>

void setParameters(HxUniformScalarField3 *field, CCPi::XradiaReader reader);

CCPI_API
int CCPiXradiaAvizoReader(const char* filename)
{
    theWorkArea->startWorking(
     QApplication::translate("CCPiXradiaAvizoReader", "Reading xradia data"));
    CCPiAvizoUserInterface *msg = new CCPiAvizoUserInterface();
	CCPi::XradiaReader reader(filename,msg);
	int newDims[3];
	newDims[0] = reader.getImageWidth();
	newDims[1] = reader.getImageHeight();
	newDims[2] = reader.getNumberOfImages();
#if AVIZO_UNSUPPORTED_INTERNAL
	HxUniformScalarField3 *field = new HxUniformScalarField3(newDims, McPrimType::MC_UINT16);
	uint16_t *data = (uint16_t*)reader.getImageDataInShort()->data();
	uint16_t *rawout=(uint16_t *)field->lattice().dataPtr();
	unsigned long long totalsize = 1;
	for(int i=0;i<3;i++)
		totalsize *= newDims[i];

	for(unsigned long long idx=0;idx<totalsize;idx++)
		rawout[idx]=data[idx];

	HxUniformCoord3 * coords = (HxUniformCoord3 *)field->lattice().coords();

	McBox3f bx;
	bx = coords->getBoundingBox();
#else
	HxUniformScalarField3 *field = new HxUniformScalarField3(newDims, McPrimType::mc_uint16);
	uint16_t *data = (uint16_t*)reader.getImageDataInShort()->data();
	uint16_t *rawout = (uint16_t *)field->lattice.dataPtr();
	unsigned long long totalsize = 1;
	for (int i = 0; i<3; i++)
		totalsize *= newDims[i];

	for (unsigned long long idx = 0; idx<totalsize; idx++)
		rawout[idx] = data[idx];

	HxUniformCoord3 * coords = (HxUniformCoord3 *)field->lattice.coords();

	float * bx;
	bx=coords->bbox();
#endif
	bx[0]=0;
	if(newDims[0]!=1)
		bx[1]=(float)newDims[0]-1;
	else
		bx[1]=1;
	bx[2]=0;
	if(newDims[1]!=1)
		bx[3]=(float)newDims[1]-1;
	else
		bx[3]=1;
	bx[4]=0;
	if(newDims[2]!=1)
		bx[5]=(float)newDims[2]-1;
	else
		bx[5] = 1;
#if AVIZO_UNSUPPORTED_INTERNAL
	coords->setBoundingBox(bx);
#endif
	HxData::registerData(field, "ImageData");
	setParameters(field, reader);
	theWorkArea->stopWorking();
	return 1;
}

void setParameters(HxUniformScalarField3 *field, CCPi::XradiaReader reader)
{
	//field->parameters.set("VoxelSize", 3, reader.getVoxelSize());
	//field->parameters.set("Offset", 3, reader.getOffset());
	field->parameters.set("SourceToObject", -1*reader.getSourceToObject());
	field->parameters.set("SourceToDetector", reader.getDetectorToObject()-reader.getSourceToObject());
	//Copy angles
	double *angles = new double[reader.getNumberOfImages()];
	std::vector<float> rangles = reader.getAngles();
	for(int i=0;i<reader.getNumberOfImages();i++)
		angles[i] = rangles[i];
	field->parameters.set("Angles", reader.getNumberOfImages(), angles);
	//field->parameters.set("DetectorPixelSize", 2, reader.getDetectorPixelSize());
	////field->parameters.set("InitialAngle", reader.getInitialAngle());
	//field->parameters.set("WhiteLevel", reader.getWhiteLevel());
	//field->parameters.set("Scattering", reader.getScattering());
	//field->parameters.set("CoefX", 5, reader.getCoefX());
	//field->parameters.set("Scale", reader.getScale());
	//field->parameters.set("MaskRadius", reader.getMaskRadius());
}

max_stars_repo_name: vais-ral/CCPi-Reconstruction

max_issues_repo_name: vais-ral/CCPi-Reconstruction

max_forks_repo_name: vais-ral/CCPi-Reconstruction


text:
// Copyright 2021, Autonomous Space Robotics Lab (ASRL)
//
// 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.

/**
 * \file cloud.hpp
 * \brief PointXYZ, PointXY, PointCloud class definition
 *
 * \author Hugues Thomas, Autonomous Space Robotics Lab (ASRL)
 */
#pragma once

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <unordered_map>
#include <vector>

#include <time.h>

#include <Eigen/Dense>

#include <vtr_lidar/npm_ply/ply_file_in.h>
#include <vtr_lidar/npm_ply/ply_file_out.h>
#include <vtr_lidar/npm_ply/ply_types.h>

namespace vtr {
namespace lidar {

//------------------------------------------------------------------------------------------------------------
// Point class
// ***********
//
//------------------------------------------------------------------------------------------------------------

class PointXYZ {
 public:
  using Vector3fMap = Eigen::Map<Eigen::Vector3f>;
  using Vector3fMapConst = const Eigen::Map<const Eigen::Vector3f>;
  // Elements
  // ********
  union {
    struct {
      float x;
      float y;
      float z;
    };
    float data[3];
  };

  // Methods
  // *******

  // Constructor
  PointXYZ(float x0 = 0, float y0 = 0, float z0 = 0) : x(x0), y(y0), z(z0) {}

  Vector3fMap getVector3fMap() { return (Vector3fMap(data)); }
  Vector3fMapConst getVector3fMap() const { return (Vector3fMapConst(data)); }

  // array type accessor
  float operator[](int i) const {
    if (i == 0)
      return x;
    else if (i == 1)
      return y;
    else
      return z;
  }

  // opperations
  float dot(const PointXYZ P) const { return x * P.x + y * P.y + z * P.z; }

  float sq_norm() const { return x * x + y * y + z * z; }

  PointXYZ cross(const PointXYZ P) const {
    return PointXYZ(y * P.z - z * P.y, z * P.x - x * P.z, x * P.y - y * P.x);
  }

  PointXYZ& operator+=(const PointXYZ& P) {
    x += P.x;
    y += P.y;
    z += P.z;
    return *this;
  }

  PointXYZ& operator-=(const PointXYZ& P) {
    x -= P.x;
    y -= P.y;
    z -= P.z;
    return *this;
  }

  PointXYZ& operator*=(const float& a) {
    x *= a;
    y *= a;
    z *= a;
    return *this;
  }
};

// Point Opperations
// *****************

inline PointXYZ operator+(const PointXYZ A, const PointXYZ B) {
  return PointXYZ(A.x + B.x, A.y + B.y, A.z + B.z);
}

inline PointXYZ operator-(const PointXYZ A, const PointXYZ B) {
  return PointXYZ(A.x - B.x, A.y - B.y, A.z - B.z);
}

inline PointXYZ operator*(const PointXYZ P, const float a) {
  return PointXYZ(P.x * a, P.y * a, P.z * a);
}

inline PointXYZ operator*(const float a, const PointXYZ P) {
  return PointXYZ(P.x * a, P.y * a, P.z * a);
}

inline PointXYZ operator/(const PointXYZ P, const float a) {
  return PointXYZ(P.x / a, P.y / a, P.z / a);
}

inline PointXYZ operator/(const float a, const PointXYZ P) {
  return PointXYZ(P.x / a, P.y / a, P.z / a);
}

inline std::ostream& operator<<(std::ostream& os, const PointXYZ P) {
  return os << "[" << P.x << ", " << P.y << ", " << P.z << "]";
}

inline bool operator==(const PointXYZ A, const PointXYZ B) {
  return A.x == B.x && A.y == B.y && A.z == B.z;
}

inline PointXYZ floor(const PointXYZ P) {
  return PointXYZ(std::floor(P.x), std::floor(P.y), std::floor(P.z));
}

PointXYZ max_point(const std::vector<PointXYZ>& points);
PointXYZ min_point(const std::vector<PointXYZ>& points);
PointXYZ max_point(const PointXYZ A, const PointXYZ B);
PointXYZ min_point(const PointXYZ A, const PointXYZ B);

//------------------------------------------------------------------------------------------------------------
// Point class 2D
// **************
//
//------------------------------------------------------------------------------------------------------------

class PointXY {
 public:
  // Elements
  // ********

  float x, y;

  // Methods
  // *******

  // Constructor
  PointXY() {
    x = 0;
    y = 0;
  }
  PointXY(float x0, float y0) {
    x = x0;
    y = y0;
  }
  PointXY(PointXYZ P) {
    x = P.x;
    y = P.y;
  }

  // array type accessor
  float operator[](int i) const {
    if (i == 0)
      return x;
    else
      return y;
  }

  // opperations
  float dot(const PointXY P) const { return x * P.x + y * P.y; }

  float sq_norm() const { return x * x + y * y; }

  float cross(const PointXY P) const { return x * P.y - y * P.x; }

  PointXY& operator+=(const PointXY& P) {
    x += P.x;
    y += P.y;
    return *this;
  }

  PointXY& operator-=(const PointXY& P) {
    x -= P.x;
    y -= P.y;
    return *this;
  }

  PointXY& operator*=(const float& a) {
    x *= a;
    y *= a;
    return *this;
  }
};

// Point Opperations
// *****************

inline PointXY operator+(const PointXY A, const PointXY B) {
  return PointXY(A.x + B.x, A.y + B.y);
}

inline PointXY operator-(const PointXY A, const PointXY B) {
  return PointXY(A.x - B.x, A.y - B.y);
}

inline PointXY operator*(const PointXY P, const float a) {
  return PointXY(P.x * a, P.y * a);
}

inline PointXY operator*(const float a, const PointXY P) {
  return PointXY(P.x * a, P.y * a);
}

inline PointXY operator/(const PointXY P, const float a) {
  return PointXY(P.x / a, P.y / a);
}

inline PointXY operator/(const float a, const PointXY P) {
  return PointXY(P.x / a, P.y / a);
}

inline std::ostream& operator<<(std::ostream& os, const PointXY P) {
  return os << "[" << P.x << ", " << P.y << "]";
}

inline bool operator==(const PointXY A, const PointXY B) {
  return A.x == B.x && A.y == B.y;
}

inline PointXY floor(const PointXY P) {
  return PointXY(std::floor(P.x), std::floor(P.y));
}

//------------------------------------------------------------------------------------------------------------
// Pointcloud class
// ****************
//
//------------------------------------------------------------------------------------------------------------

struct PointCloud {
  std::vector<PointXYZ> pts;

  // Must return the number of data points
  inline size_t kdtree_get_point_count() const { return pts.size(); }

  // Returns the dim'th component of the idx'th point in the class:
  // Since this is inlined and the "dim" argument is typically an immediate
  // value, the
  //  "if/else's" are actually solved at compile time.
  inline float kdtree_get_pt(const size_t idx, const size_t dim) const {
    if (dim == 0)
      return pts[idx].x;
    else if (dim == 1)
      return pts[idx].y;
    else
      return pts[idx].z;
  }

  // Optional bounding-box computation: return false to default to a standard
  // bbox computation loop.
  //   Return true if the BBOX was already computed by the class and returned in
  //   "bb" so it can be avoided to redo it again. Look at bb.size() to find out
  //   the expected dimensionality (e.g. 2 or 3 for point clouds)
  template <class BBOX>
  bool kdtree_get_bbox(BBOX& /* bb */) const {
    return false;
  }
};

// Utility function for pointclouds
template <typename T1, typename T2>
void filterVector(std::vector<T1>& vec, std::vector<T2>& scores,
                  T2 filter_value) {
  // Remove every element whose score is < filter_value
  auto vec_address = vec.data();
  vec.erase(std::remove_if(vec.begin(), vec.end(),
                           [&scores, vec_address, filter_value](const T1& f) {
                             return scores[(size_t)(&f - vec_address)] <
                                    filter_value;
                           }),
            vec.end());
}

template <typename T>
void filterVector(std::vector<T>& vec, T filter_value) {
  vec.erase(std::remove_if(
                vec.begin(), vec.end(),
                [filter_value](const float s) { return s < filter_value; }),
            vec.end());
}

template <typename T>
void filterFloatVector(std::vector<T>& vec, std::vector<float>& scores,
                       float filter_value) {
  // Remove every element whose score is < filter_value
  auto vec_address = vec.data();
  vec.erase(std::remove_if(vec.begin(), vec.end(),
                           [&scores, vec_address, filter_value](const T& f) {
                             return scores[(size_t)(&f - vec_address)] <
                                    filter_value;
                           }),
            vec.end());
}

void filterPointCloud(std::vector<PointXYZ>& pts, std::vector<float>& scores,
                      float filter_value);
void filterFloatVector(std::vector<float>& vec, float filter_value);

// PLY reading/saving functions
void save_cloud(std::string dataPath, std::vector<PointXYZ>& points,
                std::vector<PointXYZ>& normals, std::vector<float>& features);
void save_cloud(std::string dataPath, std::vector<PointXYZ>& points,
                std::vector<float>& features);
void save_cloud(std::string dataPath, std::vector<PointXYZ>& points,
                std::vector<PointXYZ>& normals);
void save_cloud(std::string dataPath, std::vector<PointXYZ>& points);

void load_cloud(std::string& dataPath, std::vector<PointXYZ>& points);

void load_cloud(std::string& dataPath, std::vector<PointXYZ>& points,
                std::vector<float>& float_scalar,
                std::string& float_scalar_name, std::vector<int>& int_scalar,
                std::string& int_scalar_name);

void load_cloud_normals(std::string& dataPath, std::vector<PointXYZ>& points,
                        std::vector<PointXYZ>& normals,
                        std::vector<float>& float_scalar,
                        std::string& float_scalar_name,
                        std::vector<int>& int_scalar,
                        std::string& int_scalar_name);

//------------------------------------------------------------------------------------------------------------
// Plane3D class
// *************
//
//------------------------------------------------------------------------------------------------------------

class Plane3D {
 public:
  // Elements
  // ********

  // The plane is define by the equation a*x + b*y + c*z = d. The values (a, b,
  // c) are stored in a PointXYZ called u.
  PointXYZ u;
  float d;

  // Methods
  // *******

  // Constructor
  Plane3D() {
    u.x = 1;
    u.y = 0;
    u.z = 0;
    d = 0;
  }
  Plane3D(const float a0, const float b0, const float c0, const float d0) {
    u.x = a0;
    u.y = b0;
    u.z = c0;
    d = d0;
  }
  Plane3D(const PointXYZ P0, const PointXYZ N0) {
    // Init with point and normal
    u = N0;
    d = N0.dot(P0);
  }
  Plane3D(const PointXYZ A, const PointXYZ B, const PointXYZ C) {
    // Init with three points
    u = (B - A).cross(C - A);
    d = u.dot(A);
  }

  // Method getting distance to one point
  float point_distance(const PointXYZ P) {
    return std::abs((u.dot(P) - d) / std::sqrt(u.sq_norm()));
  }

  // Method getting square distance to one point
  float point_sq_dist(const PointXYZ P) {
    float tmp = u.dot(P) - d;
    return tmp * tmp / u.sq_norm();
  }

  // Method getting distances to some points
  void point_distances(std::vector<PointXYZ>& points,
                       std::vector<float>& distances) {
    if (distances.size() != points.size())
      distances = std::vector<float>(points.size());
    size_t i = 0;
    float inv_norm_u = 1 / std::sqrt(u.sq_norm());
    for (auto& p : points) {
      distances[i] = std::abs((u.dot(p) - d) * inv_norm_u);
      i++;
    }
  }

  int in_range(std::vector<PointXYZ>& points, float threshold) {
    int count = 0;
    float inv_norm_u = 1 / std::sqrt(u.sq_norm());
    for (auto& p : points) {
      if (std::abs((u.dot(p) - d) * inv_norm_u) < threshold) count++;
    }
    return count;
  }
};

}  // namespace lidar
}  // namespace vtr

ext: hpp


text:
/*
 * BoxFactory.cpp
 *
 *  Created on: 24 feb 2018
 *      Author: lorenzo
 */

#include "BoxFactory.h"

#include "Cuboid.h"

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

namespace ashell {

BoxFactory::~BoxFactory() {

}

std::shared_ptr<Box> BoxFactory::make_box(std::string input_line) {
	std::shared_ptr<Box> new_box;

	std::vector<std::string> spl_input;
	boost::split(spl_input, input_line, boost::is_any_of("\t "), boost::token_compress_on);

	if(spl_input[0] == "cube") {
		if(spl_input.size() != 2) {
			std::string error = boost::str(boost::format("The cuboid box line '%s' should have 2 fields, not %d") % input_line % spl_input.size());
			throw std::runtime_error(error);
		}

		double L = boost::lexical_cast<double>(spl_input[1]);
		new_box = std::shared_ptr<Box>(new Cuboid(L));
	}
	else if(spl_input[0] == "cuboid") {
		if(spl_input.size() != 4) {
			std::string error = boost::str(boost::format("The cuboid box line '%s' should have 4 fields, not %d") % input_line % spl_input.size());
			throw std::runtime_error(error);
		}

		double Lx = boost::lexical_cast<double>(spl_input[1]);
		double Ly = boost::lexical_cast<double>(spl_input[2]);
		double Lz = boost::lexical_cast<double>(spl_input[3]);
		new_box = std::shared_ptr<Box>(new Cuboid(Lx, Ly, Lz));
	}
	else {
		std::string error = boost::str(boost::format("Invalid box line '%s'") % input_line);
		throw std::runtime_error(error);
	}

	return new_box;
}

} /* namespace ashell */

max_stars_repo_name: lorenzo-rovigatti/ashell

max_issues_repo_name: lorenzo-rovigatti/ashell

max_forks_repo_name: lorenzo-rovigatti/ashell


text:
//
// Created by Blum Thomas on 20.10.20.
//

#ifndef PROTODB_EXECUTIONCONTEXT_HPP
#define PROTODB_EXECUTIONCONTEXT_HPP

#include <vector>
#include "foundations/Database.hpp"
#include <boost/dynamic_bitset.hpp>

struct ExecutionResource {
    virtual ~ExecutionResource() { }
};

struct ExecutionContext {
    std::vector<std::unique_ptr<ExecutionResource>> resources;
    void acquireResource(std::unique_ptr<ExecutionResource> && resource);

    bool overflowFlag = false;
    branch_id_t branchId = 0;
    std::unordered_map<branch_id_t, branch_id_t> branch_lineage; // mapping: parent -> offspring
    std::unordered_map<branch_id_t,std::unordered_map<branch_id_t, branch_id_t>> branch_lineages;
    boost::dynamic_bitset<> branch_lineage_bitset;
};

#endif //PROTODB_EXECUTIONCONTEXT_HPP

max_stars_repo_name: josefschmeisser/TardisDB

max_issues_repo_name: josefschmeisser/TardisDB

max_forks_repo_name: josefschmeisser/TardisDB


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

//  See http://www.boost.org/libs/test for the library home page.
//
//  File        : $RCSfile$
//
//  Version     : $Revision$
//
//  Description : defines monomorphic dataset based on stl sequence
// ***************************************************************************

#ifndef BOOST_TEST_DATA_MONOMORPHIC_COLLECTION_HPP_102211GER
#define BOOST_TEST_DATA_MONOMORPHIC_COLLECTION_HPP_102211GER

// Boost.Test
#include <boost/test/data/config.hpp>
#include <boost/test/data/monomorphic/dataset.hpp>

#include <boost/test/detail/suppress_warnings.hpp>

//____________________________________________________________________________//

namespace boost {
namespace unit_test {
namespace data {
namespace monomorphic {

// ************************************************************************** //
// **************                  collection                  ************** //
// ************************************************************************** //

template<typename C>
class collection : public monomorphic::dataset<typename boost::decay<C>::type::value_type> {
    typedef typename boost::decay<C>::type col_type;
    typedef typename col_type::value_type T;
    typedef monomorphic::dataset<T> base;
    typedef typename base::iter_ptr iter_ptr;

    struct iterator : public base::iterator {
        // Constructor
        explicit    iterator( collection<C> const& owner )
        : m_iter( owner.col().begin() )
        , m_singleton( owner.col().size() == 1 )
        {}

        // forward iterator interface
        virtual T const&    operator*()     { return *m_iter; }
        virtual void        operator++()    { if( !m_singleton ) ++m_iter; }

    private:
        // Data members
        typename col_type::const_iterator m_iter;
        bool                m_singleton;
    };

public:
    enum { arity = 1 };

#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
    // Constructor
    explicit                collection( C&& col ) : m_col( std::forward<C>(col) ) {}

    // Move constructor
    collection( collection&& c ) : m_col( std::forward<C>( c.m_col ) ) {}
#else
    explicit                collection( C const& col ) : m_col( col ) {}
#endif

    // Access methods
    C const&                col() const             { return m_col; }

    // dataset interface
    virtual data::size_t    size() const            { return m_col.size(); }
    virtual iter_ptr        begin() const           { return boost::make_shared<iterator>( *this ); }

private:
    // Data members
    C               m_col;
};

//____________________________________________________________________________//

template<typename C>
struct is_dataset<collection<C> > : mpl::true_ {};

} // namespace monomorphic

template<typename C>
inline monomorphic::collection<typename BOOST_TEST_ENABLE_IF<is_forward_iterable<C>::value,C>::type>
#ifndef BOOST_NO_CXX11_RVALUE_REFERENCES
make( C&& c )
{
    return monomorphic::collection<C>( std::forward<C>(c) );
}
#else
make( C const& c )
{
    return monomorphic::collection<C>( c );
}
#endif

//____________________________________________________________________________//

} // namespace data
} // namespace unit_test
} // namespace boost

#include <boost/test/detail/enable_warnings.hpp>

#endif // BOOST_TEST_DATA_MONOMORPHIC_COLLECTION_HPP_102211GER

max_stars_repo_name: ballisticwhisper/boost

max_issues_repo_name: ballisticwhisper/boost

max_forks_repo_name: ballisticwhisper/boost


text: #include <boost/spirit/home/support/adapt_adt_attributes.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/*
 * Copyright (C) 2019, Xilinx Inc - All rights reserved
 * Xilinx Resource Manger U30 Encoder Plugin
 *
 * Licensed under the Apache License, Version 2.0 (the "License"). You may
 * not use this file except in compliance with the License. A copy of the
 * License is located at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
#ifndef _CODEC_ENCODER_XRM_PLG_U30_HPP_
#define _CODEC_ENCODER_XRM_PLG_U30_HPP_

//#include <string.h>
#include <stdio.h>
#include <syslog.h>
#include <vector>
#include <tuple>
#include <string>

#include <xrm.h>
#include <xrm_error.h>
#include <xrm_limits.h>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/map.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree_serialization.hpp>

#define XRM_PLUGIN_U30_ENC_ID 4
#define MAX_CH_SIZE 4096
#define MAX_OUT_ELEMENTS 64
#define U30_ENC_MAXCAPACITY (1920*1080*60*4)
#define U30_LA_MAXCAPACITY (1920*1080*60*2)

namespace pt = boost::property_tree;
using namespace std;

#ifdef __cplusplus
extern "C" {
#endif

struct FrameRate
{
   int32_t numerator;
   int32_t denominator;
};

struct Resolution
{
   int32_t width;
   int32_t height;
   FrameRate frame_rate;
};

struct ResourceData
{
   string               function;
   string               format;
   int32_t              channel_load;
   int32_t              lookahead_load;
   Resolution           in_res;
   vector<Resolution>   out_res;
};

struct ParamsData
{
   int32_t             job_count;
};

int32_t xrmU30EncPlugin_api_version(void);
int32_t xrmU30EncPlugin_get_plugin_id(void);
int32_t xrmU30EncPlugin_calcPercent(xrmPluginFuncParam* param);
uint32_t extData[4];

xrmPluginData xrmU30EncPlugin{xrmU30EncPlugin_get_plugin_id, xrmU30EncPlugin_api_version, xrmU30EncPlugin_calcPercent, NULL, NULL,NULL,NULL,NULL,NULL,NULL,extData[4] };

#ifdef __cplusplus
}
#endif

#endif //_CODEC_ENCODER_XRM_PLG_U30_HPP_


text:
/*
 * OSMDatabase.hpp
 *
 *  Created on: Jun 14, 2015
 *      Author: jcassidy
 */

#ifndef OSMDATABASE_HPP_
#define OSMDATABASE_HPP_

#include "OSMNode.hpp"
#include "OSMWay.hpp"
#include "OSMRelation.hpp"
#include "ValueTable.hpp"
#include "KeyValueTable.hpp"

#include <boost/container/flat_map.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/map.hpp>

#include <unordered_map>

class OSMDatabase {
public:

    OSMDatabase() {
    }

    OSMDatabase(const std::pair<LatLon, LatLon>& bounds,
            std::vector<OSMNode>&& nodes,
            KeyValueTable&& nodeTags,
            std::vector<OSMWay>&& ways,
            KeyValueTable&& wayTags,
            std::vector<OSMRelation>&& relations,
            KeyValueTable&& relationTags,
            ValueTable&& relationMemberRoles) :

    bounds_(bounds),
    nodes_(std::move(nodes)),
    nodeTags_(std::move(nodeTags)),
    ways_(std::move(ways)),
    wayTags_(std::move(wayTags)),
    relations_(std::move(relations)),
    relationTags_(std::move(relationTags)),
    relationMemberRoles_(std::move(relationMemberRoles)) {
        buildIDMap_();
    }

    // print summary information on the database
    void print() const;

    // print full information for node/relation/way
    void showNode(unsigned i) const;
    void showRelation(unsigned i) const;
    void showWay(unsigned i) const;

    const std::vector<OSMNode>& nodes() const {
        return nodes_;
    }

    const std::vector<OSMWay>& ways() const {
        return ways_;
    }

    const std::vector<OSMRelation>& relations() const {
        return relations_;
    }

    const KeyValueTable& nodeTags() const {
        return nodeTags_;
    }

    const KeyValueTable& wayTags() const {
        return wayTags_;
    }

    const KeyValueTable& relationTags() const {
        return relationTags_;
    }

    const ValueTable& relationRoles() const {
        return relationMemberRoles_;
    }

    std::vector<LatLon> extractPoly(const OSMWay& way) const;

    const OSMRelation& relationFromID(unsigned long long id) const {
        return *idToRelationMap_.at(id);
    }

    const OSMWay& wayFromID(unsigned long long id) const {
        return *idToWayMap_.at(id);
    }

    const OSMWay* wayPtrFromID(unsigned long long id) const {
        const auto it = idToWayMap_.find(id);
        if (it != idToWayMap_.end())
            return it->second;
        else
            return nullptr;
    }

    const OSMNode& nodeFromID(unsigned long long id) const {
        return *idToNodeMap_.at(id);
    }

    const OSMNode* nodePtrFromID(unsigned long long id) const {
        const auto it = idToNodeMap_.find(id);
        return it == idToNodeMap_.end() ? nullptr : it->second;
    }

    std::vector<LatLon> corners() const {
        return std::vector<LatLon>{
            bounds_.first,
            LatLon(bounds_.second.lat, bounds_.first.lon),
            bounds_.second,
            LatLon(bounds_.first.lat, bounds_.second.lon)
        };
    }

    // returns all key string values for a given entity type

    std::vector<std::pair<std::string, unsigned>> nodeTagKeys() const {
        return tagKeys(nodes_, nodeTags_);
    }

    std::vector<std::pair<std::string, unsigned>> wayTagKeys() const {
        return tagKeys(ways_, wayTags_);
    }

    std::vector<std::pair<std::string, unsigned>> relationTagKeys() const {
        return tagKeys(relations_, relationTags_);
    }

    // returns all string values for a given key over all of an entity type (nodes/ways/relations)

    std::vector<std::pair<std::string, unsigned>> nodeTagValuesForKey(const std::string k) const {
        return tagValuesForKey(k, nodes_, nodeTags_);
    }

    std::vector<std::pair<std::string, unsigned>> wayTagValuesForKey(const std::string k) const {
        return tagValuesForKey(k, ways_, wayTags_);
    }

    std::vector<std::pair<std::string, unsigned>> relationTagValuesForKey(const std::string k) const {
        return tagValuesForKey(k, relations_, relationTags_);
    }

    // map bounds reported by OSM file

    std::pair<LatLon, LatLon> bounds() const {
        return bounds_;
    }

private:

    template<typename OSMEntityRange>std::vector<std::pair<std::string, unsigned>> tagKeys(OSMEntityRange R, const KeyValueTable& tbl) const;
    template<typename OSMEntityRange>std::vector<std::pair<std::string, unsigned>> tagValuesForKey(const std::string, OSMEntityRange R, const KeyValueTable& tbl) const;

    std::unordered_map<unsigned long long, const OSMNode*> idToNodeMap_;
    std::unordered_map<unsigned long long, const OSMWay*> idToWayMap_;
    std::unordered_map<unsigned long long, const OSMRelation*> idToRelationMap_;

    std::pair<LatLon, LatLon> bounds_ = std::make_pair(LatLon{NAN, NAN}, LatLon{NAN, NAN});

    std::vector<OSMNode> nodes_;
    KeyValueTable nodeTags_;

    std::vector<OSMWay> ways_;
    KeyValueTable wayTags_;

    std::vector<OSMRelation> relations_;
    KeyValueTable relationTags_;

    ValueTable relationMemberRoles_;

    template<class Archive>void serialize(Archive& ar, const unsigned ver) {
        ar & bounds_ & nodes_ & nodeTags_ & ways_ & wayTags_ & relations_ & relationTags_ & relationMemberRoles_;
        buildIDMap_();
    }

    void buildIDMap_() {
        idToWayMap_.clear();
        idToNodeMap_.clear();
        idToRelationMap_.clear();

        idToNodeMap_.reserve(nodes_.size());
        idToRelationMap_.reserve(relations_.size());
        idToWayMap_.reserve(ways_.size());

        // build ID to entity (node/way/relation) map
        bool inserted;
        for (const auto& w : ways_) {
            tie(std::ignore, inserted) = idToWayMap_.insert(std::make_pair(w.id(), &w));
            assert(inserted);
        }
        for (const auto& r : relations_) {
            tie(std::ignore, inserted) = idToRelationMap_.insert(std::make_pair(r.id(), &r));
            assert(inserted);
        }
        for (const auto& n : nodes_) {
            tie(std::ignore, inserted) = idToNodeMap_.insert(std::make_pair(n.id(), &n));
            assert(inserted);
        }
    }

    friend class boost::serialization::access;
};

template<typename OSMEntityRange>std::vector<std::pair<std::string, unsigned>> OSMDatabase::tagKeys(OSMEntityRange r, const KeyValueTable& tbl) const {
    std::vector<std::pair < std::string, unsigned>> v(tbl.keys().size());

    for (unsigned ki = 0; ki < v.size(); ++ki)
        v[ki] = std::make_pair(tbl.keys()[ki], 0);

    for (const auto& entity : r)
        for (const auto ki : entity.tags() | boost::adaptors::map_keys)
            v[ki].second++;

    return v;
}

template<typename OSMEntityRange>std::vector<std::pair<std::string, unsigned>> OSMDatabase::tagValuesForKey(const std::string k, OSMEntityRange r, const KeyValueTable& tbl) const {
    // lookup integer ID corresponding to key name k
    auto p = std::find(tbl.keys().begin(), tbl.keys().end(), k);

    std::unordered_map<unsigned, unsigned> m;

    if (p != tbl.keys().end()) {
        unsigned ki = p - tbl.keys().begin();

        for (const auto& entity : r) {
            for (const auto p : entity.tags() | boost::adaptors::filtered([ki](std::pair<const unsigned, unsigned> p) {
                    return p.first == ki; }))
            m[p.second]++;
        }

    }

    std::vector<std::pair < std::string, unsigned>> v;

    for (const auto p : m)
        v.emplace_back(tbl.getValue(p.first), p.second);

    return v;
}

#endif /* OSMDATABASE_HPP_ */


text:
/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2011 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_MAPPED_MEMORY_CACHE_HPP
#define MAPNIK_MAPPED_MEMORY_CACHE_HPP

// mapnik
#include <mapnik/config.hpp>
#include <mapnik/utils.hpp>
#include <mapnik/noncopyable.hpp>

// boost
#include <boost/unordered_map.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/optional.hpp>

namespace mapnik
{

using namespace boost::interprocess;

typedef boost::shared_ptr<mapped_region> mapped_region_ptr;

class MAPNIK_DECL mapped_memory_cache :
        public singleton<mapped_memory_cache, CreateStatic>,
        private mapnik::noncopyable
{
    friend class CreateStatic<mapped_memory_cache>;
    boost::unordered_map<std::string,mapped_region_ptr> cache_;
public:
    bool insert(std::string const& key, mapped_region_ptr);
    boost::optional<mapped_region_ptr> find(std::string const& key, bool update_cache = false);
    void clear();
};

}

#endif // MAPNIK_MAPPED_MEMORY_CACHE_HPP

max_stars_repo_name: Wujingli/OpenWebGlobeDataProcessing

max_issues_repo_name: Wujingli/OpenWebGlobeDataProcessing

max_forks_repo_name: Wujingli/OpenWebGlobeDataProcessing


text:
//-------------------------------------------------------------------
//  MetaInfo Framework (MIF)
//  https://github.com/tdv/mif
//  Created:     07.2017
//  Copyright (C) 2016-2021 tdv
//-------------------------------------------------------------------

// STD
#include <stdexcept>

// BOOST
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

// MIF
#include <mif/common/log.h>
#include <mif/db/id/service.h>
#include <mif/db/transaction.h>
#include <mif/reflection/reflection.h>
#include <mif/service/create.h>

// THIS
#include "employee_service.h"
#include "data/meta/data.h"

namespace Service
{

    EmployeeService::EmployeeService(std::string const &pathPrefix, Mif::Application::IConfigPtr dbConfig)
    {
        // Handlers
        AddHandler(pathPrefix + "/create", this, &EmployeeService::Create);
        AddHandler(pathPrefix + "/read", this, &EmployeeService::Read);
        AddHandler(pathPrefix + "/update", this, &EmployeeService::Update);
        AddHandler(pathPrefix + "/delete", this, &EmployeeService::Delete);

        AddHandler(pathPrefix + "/list", this, &EmployeeService::List);

        m_connections = Mif::Service::Create
                <Mif::Db::Id::Service::PostgresConnectionPool, Mif::Db::IConnectionPool>
                (dbConfig);
    }

    Data::Response::Info EmployeeService::CreateMeta(std::uint32_t code, std::string const &message) const
    {
        Data::Response::Info meta;
        meta.timestamp = boost::posix_time::to_iso_string(boost::posix_time::second_clock::universal_time());
        meta.node = boost::asio::ip::host_name();
        meta.status.code = code;
        meta.status.message = message;
        return meta;
    }

    std::string EmployeeService::FormatExceptionMessage(std::string const &message) const
    {
        try
        {
            MIF_LOG(Warning) << "[EmployeeService] Failed to process request. Error: " << message;

            Data::Response::Void response;
            response.meta = CreateMeta(-1, message);
            return Mif::Serialization::Json::Serialize(response).data();
        }
        catch (std::exception const &e)
        {
            MIF_LOG(Error) << "[EmployeeService] Failed to format message. Error: " << e.what() << " Message: " << message;
        }
        return message;
    }

    EmployeeService::ResultSerializer
    EmployeeService::Create(InputContent<Data::Employee> const &employee)
    {
        if (!employee)
            throw std::invalid_argument{"No data."};

        auto const &data = employee.Get();

        auto connection = m_connections->GetConnection();
        Mif::Db::Transaction tr{connection};

        auto statement = connection->CreateStatement(
                "INSERT INTO employees (name, last_name, age, email, position, rate) "
                "VALUES ($1::text, $2::text, $3::integer, $4::text, $5::\"Position\", $6::numeric(10, 2))"
                "RETURNING employee_id ; "
            );

        auto result = statement->Execute({data.name, data.lastName, std::to_string(data.age),
                data.email, Mif::Reflection::ToString(data.position), std::to_string(data.rate)});

        if (!result->Read())
            throw std::runtime_error{"[Service::EmployeeService::Create] Failed to create employee."};

        Data::Response::Id response;

        response.meta = CreateMeta();
        response.data = result->GetAsString(0);

        tr.Commit();

        return response;
    }

    EmployeeService::ResultSerializer
    EmployeeService::Read(Prm<Data::ID, Name("id")> const &id)
    {
        if (!id || id.Get().empty())
            throw std::invalid_argument{"Id must not be empty."};

        auto connection = m_connections->GetConnection();
        Mif::Db::Transaction tr{connection};

        auto statement = connection->CreateStatement(
                "SELECT name, last_name, age, email, position, rate "
                "FROM employees "
                "WHERE employee_id = $1::bigint ;"
            );

        auto result = statement->Execute({id.Get()});

        if (!result->Read())
            throw std::invalid_argument{"[Service::EmployeeService::Read] Employee with id \"" + id.Get() + "\" not found."};

        Data::Response::Employee response;

        response.meta = CreateMeta();

        std::size_t index = 0;

        response.data.name = result->GetAsString(index++);
        response.data.lastName = result->GetAsString(index++);
        response.data.age = static_cast<std::uint32_t>(result->GetAsInt32(index++));
        response.data.email = result->GetAsString(index++);
        response.data.position = Mif::Reflection::FromString<Data::Position>(result->GetAsString(index++));
        response.data.rate = result->GetAsDouble(index++);

        return response;
    }

    EmployeeService::ResultSerializer
    EmployeeService::Update(Prm<Data::ID, Name("id")> const &id,
                            InputContent<Data::Employee> const &employee)
    {
        if (!id || id.Get().empty())
            throw std::invalid_argument{"Id must not be empty."};

        if (!employee)
            throw std::invalid_argument{"No data."};

        auto const &data = employee.Get();

        auto connection = m_connections->GetConnection();
        Mif::Db::Transaction tr{connection};

        auto statement = connection->CreateStatement(
                "UPDATE employees "
                "SET name=$1::text, last_name=$2::text, age=$3::integer, email=$4::text, "
                    "position=$5::\"Position\", rate=$6::numeric(10, 2)  "
                "WHERE employee_id = $7::bigint "
                "RETURNING employee_id ; "
            );

        auto result = statement->Execute({data.name, data.lastName, std::to_string(data.age),
                data.email, Mif::Reflection::ToString(data.position), std::to_string(data.rate), id.Get()});

        if (!result->Read())
            throw std::invalid_argument{"[Service::EmployeeService::Update] Employee with id \"" + id.Get() + "\" not found."};

        tr.Commit();

        Data::Response::Void response;

        response.meta = CreateMeta();

        return response;
    }

    EmployeeService::ResultSerializer
    EmployeeService::Delete(Prm<Data::ID, Name("id")> const &id)
    {
        if (!id || id.Get().empty())
            throw std::invalid_argument{"Id must not be empty."};

        auto connection = m_connections->GetConnection();
        Mif::Db::Transaction tr{connection};

        auto statement = connection->CreateStatement(
                "DELETE FROM employees "
                "WHERE employee_id = $1::bigint "
                "RETURNING employee_id ; "
            );

        auto result = statement->Execute({id.Get()});

        if (!result->Read())
            throw std::invalid_argument{"[Service::EmployeeService::Delete] Employee with id \"" + id.Get() + "\" not found."};

        tr.Commit();

        Data::Response::Void response;

        response.meta = CreateMeta();

        return response;
    }

    EmployeeService::ResultSerializer
    EmployeeService::List(Prm<std::size_t, Name("offset")> const &offset,
                          Prm<std::size_t, Name("limit")> const &limit)
    {
        auto connection = m_connections->GetConnection();
        Mif::Db::Transaction tr{connection};

        std::string sql = "SELECT name, last_name, age, email, position, rate, employee_id "
                "FROM employees ";

        Mif::Db::IStatement::Parameters params;

        if (offset)
        {
            sql += "OFFSET $1::integer ";
            params.push_back(std::to_string(offset.Get()));
        }

        if (limit)
        {
            auto const index = !offset ? 1 : 2;
            sql += "LIMIT $" + std::to_string(index) + "::integer ";
            params.push_back(std::to_string(limit.Get()));
        }

        sql += ";";

        auto statement = connection->CreateStatement(sql);
        auto result = statement->Execute(params);

        Data::Response::Employees response;

        response.meta = CreateMeta();

        while (result->Read())
        {
            std::size_t index = 0;

            Data::Employee employee;

            employee.name = result->GetAsString(index++);
            employee.lastName = result->GetAsString(index++);
            employee.age = static_cast<std::uint32_t>(result->GetAsInt32(index++));
            employee.email = result->GetAsString(index++);
            employee.position = Mif::Reflection::FromString<Data::Position>(result->GetAsString(index++));
            employee.rate = result->GetAsDouble(index++);

            response.data.emplace(result->GetAsString(index), std::move(employee));
        }

        return response;
    }

}   // namespace Service

max_stars_repo_name: tdv/mif

max_issues_repo_name: tdv/mif

max_forks_repo_name: tdv/mif


text:
/*
 * Copyright 2020 Ryan Levy, Xiongjie Yu, and Bryan K. Clark
 *
 * 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 "../util/types_and_headers.h"
#include "../linalg/lapack_wrapper.h"
#include "../dtensor/dtensor_all.h"
#include "../qtensor/qtensor_all.h"
#include "../mps/mps_all.h"

#include "../models/sites/spinhalf.h"
#include "../models/sites/electron.h"
#include "../models/hams/Heisenberg.h"

#include "../algos/dmrg/dmrg.h"

#include "../util/timer.h"

#include "../models/hams/AutoMPO.h"

#include "../models/lattice/square.h"
#include "../models/lattice/triangular.h"

#include <ctf.hpp>
#include <sys/stat.h>
using namespace std;
inline bool check_existence(const string& name);

//#include <Eigen/Dense>
#include "hdf5.h"

filebuf fbuf;
ostream perr(&fbuf);
filebuf fbufo;
ostream pout(&fbufo);

template <typename T, template <typename,unsigned> class TensorType>
void fixTensors(TensorType<T,1>& psi,TensorType<T,2>& H){
  uint_vec perm;
  string Link_name_pref = "ID"+to_string(psi._id)+"Link";
  string Site_name_pref = "Site";
  for(unsigned l=0;l<psi.length;l++){
    string left_link_name  = Link_name_pref+to_string(l);
    string right_link_name = Link_name_pref+to_string(l+1);
    string site_name       = Site_name_pref+to_string(l);
    vector<qtensor_index> inds(3);
    for(auto& ix : psi.A[l].idx_set){
      if(ix.name()==left_link_name) inds[0] = ix;
      else if(ix.name()==site_name) inds[1] = ix;
      else if(ix.name()==right_link_name) inds[2] = ix;
    }
    find_index_permutation(psi.A[l].idx_set,inds, perm);
    psi.A[l].permute(perm);
  }
  //check if we need to dagger H
  string site_name = Site_name_pref+to_string(0);
  auto& psiSet = psi.A[0].idx_set;
  auto& HSet   = H.A[0].idx_set;
  auto it  = find_if(psiSet.begin(), psiSet.end(), [&](qtensor_index& qi){ return qi.name()==site_name;});
  auto itH = find_if(HSet.begin(),   HSet.end(),   [&](qtensor_index& qi){ return (qi.name()==site_name) && (qi.level()==0);});
  assert(it!=psiSet.end() && itH != HSet.end());
  if( it->arrow() == itH->arrow()){
    for(auto& Ai: H.A) Ai.dag();
  }

}

int main(int argc, char **argv)
{
  MPI_Init(&argc, &argv);
  {
    CTF::World world(argc,argv);
    if (world.rank == 0){
      perr.rdbuf(cerr.rdbuf());
      pout.rdbuf(cout.rdbuf());
      perr.precision(12);
      pout.precision(12);
    }
    if(argc==1) {
      perr<<"Error: Need filename!"<<endl;
      assert(1==2);
    }
    string inputName = string(argv[1]);
    ifstream in;
    in.open(inputName);
    assert(in);
    string line; stringstream linest;

    /*
     *              input file format
     * type
     * Nx Ny
     * J1 J2
     * fname
     * prefix
     * nsweeps
     * maxm maxm maxm
     * cutoff cutoff cutoff
     * restart restart restart
     *
     */

    string type; getline(in,type);
    getline(in,line); linest.clear(); linest.str(line);
    int Nx,Ny;
    linest >> Nx >> Ny;
    auto N = Nx*Ny;
    double J1,J2;
    getline(in,line); linest.clear(); linest.str(line);
    perr << "J1 line=" << line << endl;
    linest >> J1 >> J2;
    string fname="";
    getline(in,line); if(!line.empty()) fname=line;
    string pref="";
    getline(in,line); if(!line.empty()) pref=line;
    int nsweeps = 0;
    getline(in,line); linest.clear(); linest.str(line);
    linest >> nsweeps;

    vector<int> maxm;
    vector<double> cutoff;
    vector<int> max_restart;
    getline(in,line); linest.clear(); linest.str(line);
    while(getline(linest,line,' ')){
      maxm.push_back(std::stoi(line));
    }
    getline(in,line); linest.clear(); linest.str(line);
    while(getline(linest,line,' ')){
      cutoff.push_back(std::stof(line));
    }
    getline(in,line); linest.clear(); linest.str(line);
    while(getline(linest,line,' ')){
      max_restart.push_back(std::stoi(line));
    }
    in.close();

    if(world.rank==0)
      printf("type=%s N=(%i,%i) J1=%f J2=%f\nfile=%s prefix=%s\nnsweeps=%i \n",
          type.c_str(),Nx,Ny,J1,J2,fname.c_str(),pref.c_str(),nsweeps);
    perr<<"maxm:";        for(auto m: maxm)        perr<<m<<" "; perr<<"\n";
    perr<<"cutoff:";      for(auto c: cutoff)      perr<<c<<" "; perr<<"\n";
    perr<<"max_restart:"; for(auto r: max_restart) perr<<r<<" "; perr<<"\n";
    //spinhalf sites(N);
    electron sites(N);
    str_vec ps;
    for (size_t i = 0; i < sites.N(); i++) {
      if(i%2==0)
        ps.push_back("Dn");
      else
        ps.push_back("Up");
    }

    AutoMPO ampo(sites);
    bool yperiodic = true;
    auto lattice = triangularLattice(Nx,Ny,yperiodic);
    auto t = 1.0;
    auto U = J2;

    for(auto bnd : lattice){
      //hopping terms in the 1DEG
      ampo+=-t,"Cdagup",bnd.s1-1,"Cup",bnd.s2-1;
      ampo+=-t,"Cdagdn",bnd.s1-1,"Cdn",bnd.s2-1;
      ampo+=-t,"Cdagup",bnd.s2-1,"Cup",bnd.s1-1;
      ampo+=-t,"Cdagdn",bnd.s2-1,"Cdn",bnd.s1-1;
    }
    //-------------------------
    for(int i=0;i<N;i++)
      ampo+=U,"Nupdn",i;

    if(type=="d"){
      pout << "\n" << "Dense MPS DMRG (Linear Heisenberg)" << '\n';

      MPS<double> psi(&sites,ps);
      //psi.load(fname); //TODO: fix pref
      psi.print();
      MPO< double > H;
      Heisenberg< double > HB(&sites);
      HB.buildHam(H);
      dmrg(psi, H, nsweeps, maxm, cutoff, max_restart);
      psi.print();

    }
    if(type=="q"){
      pout << "\n" << "qMPS Fermionic DMRG" << '\n';

      qMPS< double > psi(&sites,ps);
      bool yperiodic=true;
      auto lattice = triangularLattice(Nx,Ny,yperiodic);

      auto t = 1.0;
      auto U = J2;

      AutoMPO ampo(sites);
      for(auto bnd : lattice){
        //hopping terms in the 1DEG
        ampo+=-t,"Cdagup",bnd.s1-1,"Cup",bnd.s2-1;
        ampo+=-t,"Cdagdn",bnd.s1-1,"Cdn",bnd.s2-1;
        ampo+=-t,"Cdagup",bnd.s2-1,"Cup",bnd.s1-1;
        ampo+=-t,"Cdagdn",bnd.s2-1,"Cdn",bnd.s1-1;
      }
      //-------------------------
      for(int i=0;i<N;i++)
        ampo+=U,"Nupdn",i;

      string postfix = to_string(Nx)+"x"+to_string(Ny)+"_U"+to_string(U);
      auto sp = "psi_"+postfix;
      qMPO< double > H;
      Heisenberg< double > HB(&sites);
      perr<<"making H"<<endl;
      HB.buildHam(ampo,H);

      psi.load(fname,pref);
      psi.print();

      assert(H._id != psi._id);
      fixTensors(psi,H);

      dmrg(psi, H, nsweeps, maxm, cutoff, max_restart);

    }
    if(type=="qs"){
      pout << "\n" << "qsMPS Fermionic DMRG" << '\n';

      qsMPS<double> psi(&sites,ps);
      psi.load(fname,pref);
      psi.print();
      qMPO< double > H;
      Heisenberg< double > HB(&sites);
      HB.buildHam(ampo,H);
      qsMPO< double > Hq = H;

      assert(H._id != psi._id);
      fixTensors(psi,Hq);

      dmrg(psi, Hq, nsweeps, maxm, cutoff, max_restart);

      psi.print();
      for(int l=0;l<N;l++){
        auto& Al = psi.A[l];
        perr<<Al._T.nnz_tot<<","<<(double)Al._T.nnz_tot/(Al._T.get_tot_size(false))<<endl;
        for(size_t i=0;i<Al.block_index_qd.size();i++)
          perr<<"   ("<<Al.block_index_qd[i][0]<<","
              << Al.block_index_qd[i][1]<<","<<Al.block_index_qd[i][2]<<")\n";
      }
    }
    if(type=="qToqs"){
      pout << "\n" << "q to qsMPS Fermionic DMRG" << '\n';

      qMPO< double > H;
      Heisenberg< double > HB(&sites);
      HB.buildHam(ampo,H);
      H.load("H_36_1.h5");
      H.print();
      qsMPO< double > Hq = H;

      qMPS<double> psi(&sites);
      psi.load(fname,pref);
      psi.print();
      qsMPS<double> psiq = psi;
      psiq.print();

      assert(H._id != psi._id);
      fixTensors(psiq,Hq);

      dmrg(psiq, Hq, nsweeps, maxm, cutoff, max_restart);

      psiq.print();
      /*for(int l=0;l<N;l++){
        auto& Al = psiq.A[l];
        perr<<Al._T.nnz_tot<<","<<(double)Al._T.nnz_tot/(Al._T.get_tot_size(false))<<endl;
        perr<<"   ";
        for(size_t i=0;i<Al.block_index_qd.size();i++)
          perr<<"("<<Al.block_index_qd[i][0]<<","
              << Al.block_index_qd[i][1]<<","<<Al.block_index_qd[i][2]<<") ";
        perr<<'\n';
      }*/
    }
  }
  MPI_Finalize();
  return 0;
  exit(1);
  //------------------------------------
  return 0;
}

inline bool check_existence(const std::string& name){
  struct stat buffer;
  return (stat (name.c_str(),&buffer) == 0);
}

max_stars_repo_name: ClarkResearchGroup/tensor-tools

max_issues_repo_name: ClarkResearchGroup/tensor-tools

max_forks_repo_name: ClarkResearchGroup/tensor-tools


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

    @copyright 2016 NumScale SAS

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

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-trigonometric
    This function object converts degree to radian.

    @par Header <boost/simd/function/inrad.hpp>

    @par Example:

      @snippet inrad.cpp inrad

    @par Possible output:

      @snippet inrad.txt inrad

  **/
  IEEEValue inrad(IEEEValue const& x);
} }
#endif

#include <boost/simd/function/scalar/inrad.hpp>
#include <boost/simd/function/simd/inrad.hpp>

#endif

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
#include "torntpage.h"
#include "ui_torntpage.h"
#include "clientmodel.h"
#include "tornttablemodel.h"
#include "bitcoingui.h"
#include "guiutil.h"
#include "util.h"
#include "main.h"
#include "transactiondescdialog.h"
#include "bitcoinrpc.h"
#include <algorithm>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/foreach.hpp>

#include "ui_interface.h"
#include "json/json_spirit_reader_template.h"
#include "json/json_spirit_writer_template.h"
#include "json/json_spirit_utils.h"

#include <QSortFilterProxyModel>
#include <QClipboard>
#include <QMessageBox>
#include <QMenu>
#include <QPainter>

using namespace boost;
using namespace json_spirit;

int gettorntBlockCount()
{
    QSqlQuery query;
    query.exec(QString("select blockindex from blockindex"));
    if (query.next())
    {
        return query.value(0).toInt();
    }
    return 0;
}

void updatetornt(int index)
{
    try{
        QString s = QString::number(index, 10);
        std::vector<std::string> args;
        args.push_back("getblockhash");
        args.push_back(s.toStdString());
        Value result = tableRPC.execute(args[0],RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
        if (result.type() == str_type)
        {
            args.clear();
            args.push_back("getblock");
            args.push_back(result.get_str());
            result = tableRPC.execute(args[0],RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
            if (result.type() == obj_type)
            {
                Object reply = result.get_obj();
                Array  txid  = find_value(reply, "tx").get_array();
                BOOST_FOREACH(Value v, txid)
                {

                    args.clear();
                    args.push_back("gettornt");
                    args.push_back(v.get_str());
                    Value value = tableRPC.execute(args[0],RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
                    if (value.type() == obj_type)
                    {
                        Object reply = value.get_obj();
                        QSqlQuery query;
                        query.exec(QString("insert into tornt values('%1','%2',%3)").arg(QString::fromStdString(find_value(reply, "title").get_str())).arg(QString::fromStdString(v.get_str())).arg(index));
                    }
                }
            }
        }

        QSqlQuery query;
        query.exec(QString("UPDATE blockindex set blockindex = %1").arg(index));
    }catch (json_spirit::Object& objError)
    {
        throw std::runtime_error("updatetornt error");
    }
    catch(std::runtime_error& e)
    {
          throw std::runtime_error("updatetornt error");
    }
    catch (std::exception& e)
    {
        throw std::runtime_error("updatetornt error");
    }
}

class TDBExecutor: public QObject
{
    Q_OBJECT

    public slots:
        void start();

    signals:
    void refreshtorntTable();
};

#include "torntpage.moc"

void TDBExecutor::start()
{
    try{
        int torntblockcount = gettorntBlockCount();
        while((torntblockcount < nBestHeight))
        {
            updatetornt(torntblockcount);
            torntblockcount++;
        }
    }catch(std::runtime_error& e)
    {
          emit refreshtorntTable();
    }
    emit refreshtorntTable();
}

torntPage::torntPage(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::torntPage),
    model(0)
{
    ui->setupUi(this);
    startExecutor();

}

torntPage::~torntPage()
{
    emit stopExecutor();

    delete ui;
}

void torntPage::setModel(torntTableModel *model)
{
    this->model = model;
    if(!model)
        return;

    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(model);
    proxyModel->setDynamicSortFilter(true);
    proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
    proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);

    ui->tableView->setModel(model);
    ui->tableView->sortByColumn(0, Qt::AscendingOrder);

    // Set column widths
#if QT_VERSION < 0x050000
    ui->tableView->horizontalHeader()->setResizeMode(torntTableModel::Title, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setResizeMode(torntTableModel::Address, QHeaderView::ResizeToContents);
#else
    ui->tableView->horizontalHeader()->setSectionResizeMode(torntTableModel::Title, QHeaderView::Stretch);
    ui->tableView->horizontalHeader()->setSectionResizeMode(torntTableModel::Address, QHeaderView::ResizeToContents);
#endif

    connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
            this, SLOT(selectionChanged()));

    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SIGNAL(doubleClicked(QModelIndex)));
    connect(ui->searchButton, SIGNAL(clicked()), this, SLOT(searchButtonClicked()));
}

void torntPage::setClientModel(ClientModel *model)
{
    this->clientModel = model;
    if(model)
    {

    }
}

void torntPage::startExecutor()
{
    QThread* thread = new QThread;
    TDBExecutor *executor = new TDBExecutor();
    executor->moveToThread(thread);

    connect(executor, SIGNAL(refreshtorntTable()), this, SLOT(refreshtorntTable()));
    connect(thread, SIGNAL(started()), executor, SLOT(start()));
    connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
    connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

    thread->start();
}

void torntPage::refreshtorntTable()
{
    model->refreshtorntTable();
}

void torntPage::showDetails()
{
    if(!ui->tableView->selectionModel())
        return;
    QModelIndexList selection = ui->tableView->selectionModel()->selectedRows();
    if(!selection.isEmpty())
    {
        QString html = selection.at(0).data(torntTableModel::torntRole).toString();
        TransactionDescDialog dlg(html);
        dlg.exec();
    }
}

void torntPage::searchButtonClicked()
{

}