<commit_before>/**************************************************************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: bulkDataNTConfiguration.cpp,v 1.29 2012/10/12 13:57:22 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2011-04-19  created
*/

#include "bulkDataNTConfiguration.h"
#include <ndds_config_cpp.h>
#include <logging.h>

using namespace AcsBulkdata;

const char* const DDSConfiguration::DEFAULT_LIBRARY = "BulkDataQoSLibrary";
const char* const DDSConfiguration::DEFAULT_SENDER_STREAM_PROFILE = "SenderStreamDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_SENDER_FLOW_PROFILE= "SenderFlowDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_RECEIVER_STREAM_PROFILE = "ReceiverStreamDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE = "ReceiverFlowDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_API_CREATE_PROFILE = "APICreateProfile";

short DDSConfiguration::debugLevel = -1;
unsigned int DDSConfiguration::DDSLogVerbosity = (unsigned int)(NDDS_CONFIG_LOG_VERBOSITY_WARNING);

bool StreamConfiguration::DEFAULT_PARTICIPANT_PER_STREAM=false;

double SenderFlowConfiguration::DEFAULT_SENDFRAME_TIMEOUT=5.0;  //secs
double SenderFlowConfiguration::DEFAULT_ACKs_TIMEOUT=2.0; //secs

unsigned short ReceiverStreamConfiguration::DEFAULT_BASE_UNICAST_PORT=48000;
bool ReceiverStreamConfiguration::DEFAULT_USE_INCREMENT_UNICAST_PORT=true;

const char* const ReceiverFlowConfiguration::DEFAULT_MULTICAST_ADDRESS="225.3.2.1";
double ReceiverFlowConfiguration::DEFAULT_CBRECEIVE_PROCESS_TIMEOUT=0.01; //sec => 6.4 MB/sec
double ReceiverFlowConfiguration::DEFAULT_CBRECEIVE_AVG_PROCESS_TIMEOUT=0.005; //sec => ~ 12MB/sec
bool ReceiverFlowConfiguration::DEFAULT_ENABLE_MULTICAST=true;
unsigned short ReceiverFlowConfiguration::DEFAULT_UNICAST_PORT=0; ///0 means that DDS will choose the port

bool DDSConfiguration::ignoreUserProfileQoS = true;
bool DDSConfiguration::ignoreEnvironmentProfileQoS = true;

std::string DDSConfiguration::urlProfileQoS="";
const char* const DDSConfiguration::DEFAULT_QoS_FILE="/config/bulkDataNTDefaultQosProfiles.xml";

bool AcsBulkdata::isBulkDataNTEnabled()
{
	const char *enableBulkDataNT = getenv("ENABLE_BULKDATA_NT");

	return ( enableBulkDataNT != 0 &&
			(strcmp(enableBulkDataNT, "1")==0 ||
			 strcasecmp(enableBulkDataNT, "true")==0 ||
			 strcasecmp(enableBulkDataNT, "y")==0
			)
		);
}
/**************************************************************************************
 * 			StreamConfiguration
 **************************************************************************************/
DDSConfiguration::DDSConfiguration()
{
	libraryQos=DDSConfiguration::DEFAULT_LIBRARY;
	DDSConfiguration::setDebugLevelFromEnvVar();

	if (urlProfileQoS.empty())
	{
		urlProfileQoS = "[";
		fillUrlProfileQoS("ACSDATA");
		urlProfileQoS+="]";
		// here we are sure that this is executed just once
		char *envVar = getenv("NDDS_DISCOVERY_PEERS");
		if (envVar && *envVar)
		{
			ACS_SHORT_LOG((LM_WARNING, "Env. variable NDDS_DISCOVERY_PEERS has been set to: %s, what could cause a problem to connect sender and receivers if it is not proprly used.", envVar));
		}//if
	}//if
}//DDSConfiguration

void DDSConfiguration::setDebugLevelFromEnvVar()
{
	if (debugLevel<0) //we read and set debug level jsut once
	{
		char *bulkDataNtDebug = getenv("BULKDATA_NT_DEBUG");
		if (bulkDataNtDebug && *bulkDataNtDebug)
		{
			debugLevel = atoi(bulkDataNtDebug);
			DDSConfiguration::setDDSLogVerbosity();
			ACS_SHORT_LOG((LM_INFO, "BulkDataNT debug level read from env. var. BULKDATA_NT_DEBUG and set to %d", debugLevel));
		}
		else
		{
			debugLevel=0;
		}
	}
}//setDebugLevelFromEnvVar

void DDSConfiguration::fillUrlProfileQoS(const char* envVar, const char *dilim)
{
	char *envVarValue = getenv(envVar);
	if (envVarValue != NULL)
	{
		urlProfileQoS += "file://";
		urlProfileQoS += envVarValue;
		urlProfileQoS += DEFAULT_QoS_FILE;
		urlProfileQoS += dilim;
	}
}//fillUrlProfileQoS

void DDSConfiguration::setDDSLogVerbosity()
{
	//RTI logging
	switch (DDSConfiguration::debugLevel)
	{
	case 2:
		DDSConfiguration::DDSLogVerbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_LOCAL;
		break;
	case 3:
		DDSConfiguration::DDSLogVerbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_REMOTE;
		break;
	case 4:
		DDSConfiguration::DDSLogVerbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
		break;
	}
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
			NDDS_CONFIG_LOG_CATEGORY_API,  (NDDS_Config_LogVerbosity)(DDSConfiguration::DDSLogVerbosity));
	/*
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
				NDDS_CONFIG_LOG_CATEGORY_COMMUNICATION,  (NDDS_Config_LogVerbosity)(DDSConfiguration::DDSLogVerbosity));
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
					NDDS_CONFIG_LOG_CATEGORY_ENTITIES,  (NDDS_Config_LogVerbosity)(DDSConfiguration::DDSLogVerbosity));
*/
}//setDDSLogVerbosity

void DDSConfiguration::setStringProfileQoS(char *cfg, const char *defaultProfile)
{
	profileQos=DEFAULT_API_CREATE_PROFILE;

	stringProfileQoS="<qos_profile name=\"";
	stringProfileQoS+=profileQos;
	stringProfileQoS+="\" base_name=\"";
	stringProfileQoS+=DDSConfiguration::DEFAULT_LIBRARY;
	stringProfileQoS+="::";
	stringProfileQoS+=defaultProfile;
	stringProfileQoS+="\">";
	stringProfileQoS+=cfg;
	stringProfileQoS+="</qos_profile>";
}//setStringProfileQoS

void DDSConfiguration::setStringProfileQoS(char*  profileName, char* cfg, const char *defaultProfile)
{
	profileQos=profileName;
	stringProfileQoS="<qos_profile name=\"";
	stringProfileQoS+=profileQos;
	stringProfileQoS+="\" base_name=\"";
	stringProfileQoS+=DDSConfiguration::DEFAULT_LIBRARY;
	stringProfileQoS+="::";
	stringProfileQoS+=defaultProfile;
	stringProfileQoS+="\">";
	stringProfileQoS+=cfg;
	stringProfileQoS+="</qos_profile>";
}//setStringProfileQoS

/**************************************************************************************
 * 			StreamConfiguration
 **************************************************************************************/
StreamConfiguration::StreamConfiguration()
{

	participantPerStream = DEFAULT_PARTICIPANT_PER_STREAM;
}//StreamConfiguration

/**************************************************************************************
 * 			SenderStreamConfiguration
 **************************************************************************************/
SenderStreamConfiguration::SenderStreamConfiguration()
{
	profileQos=DEFAULT_SENDER_STREAM_PROFILE;
}//StreamConfiguration

/**************************************************************************************
 * 			ReceiverStreamConfiguration
 **************************************************************************************/
ReceiverStreamConfiguration::ReceiverStreamConfiguration()
{
	profileQos=DEFAULT_RECEIVER_STREAM_PROFILE;
}//ReceiverStreamConfiguration

void ReceiverStreamConfiguration::setDDSReceiverStreamQoS(char *cfg)
{
	setStringProfileQoS(cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverStreamQoS

void ReceiverStreamConfiguration::setDDSReceiverStreamQoS(char *profileName, char* cfg)
{
	setStringProfileQoS(profileName, cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverStreamQoS

/**************************************************************************************
 * 			ReceiverFlowConfiguration
 **************************************************************************************/
ReceiverFlowConfiguration::ReceiverFlowConfiguration()
{
	profileQos=DEFAULT_RECEIVER_FLOW_PROFILE;
	cbReceiveProcessTimeout =DEFAULT_CBRECEIVE_PROCESS_TIMEOUT;
	cbReceiveAvgProcessTimeout =DEFAULT_CBRECEIVE_AVG_PROCESS_TIMEOUT;
	enableMulticast = DEFAULT_ENABLE_MULTICAST;
	multicastAddress = DEFAULT_MULTICAST_ADDRESS;
}//ReceiverFlowConfiguration

double ReceiverFlowConfiguration::getCbReceiveProcessTimeout() const
{
    return cbReceiveProcessTimeout;
}

void ReceiverFlowConfiguration::setCbReceiveProcessTimeout(double cbReceiveProcessTimeout)
{
    this->cbReceiveProcessTimeout = cbReceiveProcessTimeout;
}

double ReceiverFlowConfiguration::getCbReceiveAvgProcessTimeout() const
{
    return cbReceiveAvgProcessTimeout;
}

void ReceiverFlowConfiguration::setCbReceiveAvgProcessTimeout(double cbReceiveAvgProcessTimeout)
{
    this->cbReceiveAvgProcessTimeout = cbReceiveAvgProcessTimeout;
}

std::string ReceiverFlowConfiguration::getMulticastAddress() const
{
    return multicastAddress;
}

bool ReceiverFlowConfiguration::isEnableMulticast() const
{
    return enableMulticast;
}

void ReceiverFlowConfiguration::setEnableMulticast(bool enableMulticast)
{
    this->enableMulticast = enableMulticast;
}

void ReceiverFlowConfiguration::setMulticastAddress(std::string multicastAddress)
{
    this->multicastAddress = multicastAddress;
}

unsigned short ReceiverFlowConfiguration::getUnicastPort() const
{
	return this->unicastPort;
}

void ReceiverFlowConfiguration::setUnicastPort(	unsigned short port)
{
	this->unicastPort = port;
}

void ReceiverFlowConfiguration::setDDSReceiverFlowQoS(char* cfg)
{
	setStringProfileQoS(cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverFlowQoS

void ReceiverFlowConfiguration::setDDSReceiverFlowQoS(char* profileName, char* cfg)
{
	setStringProfileQoS(profileName, cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverFlowQoS

/**************************************************************************************
 * 			SenderFlowConfiguration
 **************************************************************************************/
SenderFlowConfiguration::SenderFlowConfiguration()
{
	profileQos=DEFAULT_SENDER_FLOW_PROFILE;
	sendFrameTimeout = DEFAULT_SENDFRAME_TIMEOUT;
	ACKsTimeout = DEFAULT_ACKs_TIMEOUT;
}

double SenderFlowConfiguration::getACKsTimeout() const
{
    return ACKsTimeout;
}

double SenderFlowConfiguration::getSendFrameTimeout() const
{
    return sendFrameTimeout;
}

void SenderFlowConfiguration::setACKsTimeout(double acKsTimeout)
{
    ACKsTimeout = acKsTimeout;
}

void SenderFlowConfiguration::setSendFrameTimeout(double frameTimeout)
{
    this->sendFrameTimeout = frameTimeout;
}

void SenderFlowConfiguration::setDDSSenderFlowQoS(char* cfg)
{
	setStringProfileQoS(cfg, DDSConfiguration::DEFAULT_SENDER_FLOW_PROFILE);
}//setDDSReceiverFlowQoS

void SenderFlowConfiguration::setDDSSenderFlowQoS(char* profileName, char* cfg)
{
	setStringProfileQoS(profileName, cfg, DDSConfiguration::DEFAULT_SENDER_FLOW_PROFILE);
}

<commit_msg>- in ReceiverFlowConfiguration set unicastPort tod efautl value - in SenderFlowConfiguration set baseUnicastPort and useIncrementUnicastPort to default vlaues<commit_after>/**************************************************************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2011
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
*
* "@(#) $Id: bulkDataNTConfiguration.cpp,v 1.30 2012/10/15 09:37:32 bjeram Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bjeram  2011-04-19  created
*/

#include "bulkDataNTConfiguration.h"
#include <ndds_config_cpp.h>
#include <logging.h>

using namespace AcsBulkdata;

const char* const DDSConfiguration::DEFAULT_LIBRARY = "BulkDataQoSLibrary";
const char* const DDSConfiguration::DEFAULT_SENDER_STREAM_PROFILE = "SenderStreamDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_SENDER_FLOW_PROFILE= "SenderFlowDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_RECEIVER_STREAM_PROFILE = "ReceiverStreamDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE = "ReceiverFlowDefaultQosProfile";
const char* const DDSConfiguration::DEFAULT_API_CREATE_PROFILE = "APICreateProfile";

short DDSConfiguration::debugLevel = -1;
unsigned int DDSConfiguration::DDSLogVerbosity = (unsigned int)(NDDS_CONFIG_LOG_VERBOSITY_WARNING);

bool StreamConfiguration::DEFAULT_PARTICIPANT_PER_STREAM=false;

double SenderFlowConfiguration::DEFAULT_SENDFRAME_TIMEOUT=5.0;  //secs
double SenderFlowConfiguration::DEFAULT_ACKs_TIMEOUT=2.0; //secs

unsigned short ReceiverStreamConfiguration::DEFAULT_BASE_UNICAST_PORT=48000;
bool ReceiverStreamConfiguration::DEFAULT_USE_INCREMENT_UNICAST_PORT=true;

const char* const ReceiverFlowConfiguration::DEFAULT_MULTICAST_ADDRESS="225.3.2.1";
double ReceiverFlowConfiguration::DEFAULT_CBRECEIVE_PROCESS_TIMEOUT=0.01; //sec => 6.4 MB/sec
double ReceiverFlowConfiguration::DEFAULT_CBRECEIVE_AVG_PROCESS_TIMEOUT=0.005; //sec => ~ 12MB/sec
bool ReceiverFlowConfiguration::DEFAULT_ENABLE_MULTICAST=true;
unsigned short ReceiverFlowConfiguration::DEFAULT_UNICAST_PORT=0; ///0 means that DDS will choose the port

bool DDSConfiguration::ignoreUserProfileQoS = true;
bool DDSConfiguration::ignoreEnvironmentProfileQoS = true;

std::string DDSConfiguration::urlProfileQoS="";
const char* const DDSConfiguration::DEFAULT_QoS_FILE="/config/bulkDataNTDefaultQosProfiles.xml";

bool AcsBulkdata::isBulkDataNTEnabled()
{
	const char *enableBulkDataNT = getenv("ENABLE_BULKDATA_NT");

	return ( enableBulkDataNT != 0 &&
			(strcmp(enableBulkDataNT, "1")==0 ||
			 strcasecmp(enableBulkDataNT, "true")==0 ||
			 strcasecmp(enableBulkDataNT, "y")==0
			)
		);
}
/**************************************************************************************
 * 			StreamConfiguration
 **************************************************************************************/
DDSConfiguration::DDSConfiguration()
{
	libraryQos=DDSConfiguration::DEFAULT_LIBRARY;
	DDSConfiguration::setDebugLevelFromEnvVar();

	if (urlProfileQoS.empty())
	{
		urlProfileQoS = "[";
		fillUrlProfileQoS("ACSDATA");
		urlProfileQoS+="]";
		// here we are sure that this is executed just once
		char *envVar = getenv("NDDS_DISCOVERY_PEERS");
		if (envVar && *envVar)
		{
			ACS_SHORT_LOG((LM_WARNING, "Env. variable NDDS_DISCOVERY_PEERS has been set to: %s, what could cause a problem to connect sender and receivers if it is not proprly used.", envVar));
		}//if
	}//if
}//DDSConfiguration

void DDSConfiguration::setDebugLevelFromEnvVar()
{
	if (debugLevel<0) //we read and set debug level jsut once
	{
		char *bulkDataNtDebug = getenv("BULKDATA_NT_DEBUG");
		if (bulkDataNtDebug && *bulkDataNtDebug)
		{
			debugLevel = atoi(bulkDataNtDebug);
			DDSConfiguration::setDDSLogVerbosity();
			ACS_SHORT_LOG((LM_INFO, "BulkDataNT debug level read from env. var. BULKDATA_NT_DEBUG and set to %d", debugLevel));
		}
		else
		{
			debugLevel=0;
		}
	}
}//setDebugLevelFromEnvVar

void DDSConfiguration::fillUrlProfileQoS(const char* envVar, const char *dilim)
{
	char *envVarValue = getenv(envVar);
	if (envVarValue != NULL)
	{
		urlProfileQoS += "file://";
		urlProfileQoS += envVarValue;
		urlProfileQoS += DEFAULT_QoS_FILE;
		urlProfileQoS += dilim;
	}
}//fillUrlProfileQoS

void DDSConfiguration::setDDSLogVerbosity()
{
	//RTI logging
	switch (DDSConfiguration::debugLevel)
	{
	case 2:
		DDSConfiguration::DDSLogVerbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_LOCAL;
		break;
	case 3:
		DDSConfiguration::DDSLogVerbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_REMOTE;
		break;
	case 4:
		DDSConfiguration::DDSLogVerbosity = NDDS_CONFIG_LOG_VERBOSITY_STATUS_ALL;
		break;
	}
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
			NDDS_CONFIG_LOG_CATEGORY_API,  (NDDS_Config_LogVerbosity)(DDSConfiguration::DDSLogVerbosity));
	/*
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
				NDDS_CONFIG_LOG_CATEGORY_COMMUNICATION,  (NDDS_Config_LogVerbosity)(DDSConfiguration::DDSLogVerbosity));
	NDDSConfigLogger::get_instance()->set_verbosity_by_category(
					NDDS_CONFIG_LOG_CATEGORY_ENTITIES,  (NDDS_Config_LogVerbosity)(DDSConfiguration::DDSLogVerbosity));
*/
}//setDDSLogVerbosity

void DDSConfiguration::setStringProfileQoS(char *cfg, const char *defaultProfile)
{
	profileQos=DEFAULT_API_CREATE_PROFILE;

	stringProfileQoS="<qos_profile name=\"";
	stringProfileQoS+=profileQos;
	stringProfileQoS+="\" base_name=\"";
	stringProfileQoS+=DDSConfiguration::DEFAULT_LIBRARY;
	stringProfileQoS+="::";
	stringProfileQoS+=defaultProfile;
	stringProfileQoS+="\">";
	stringProfileQoS+=cfg;
	stringProfileQoS+="</qos_profile>";
}//setStringProfileQoS

void DDSConfiguration::setStringProfileQoS(char*  profileName, char* cfg, const char *defaultProfile)
{
	profileQos=profileName;
	stringProfileQoS="<qos_profile name=\"";
	stringProfileQoS+=profileQos;
	stringProfileQoS+="\" base_name=\"";
	stringProfileQoS+=DDSConfiguration::DEFAULT_LIBRARY;
	stringProfileQoS+="::";
	stringProfileQoS+=defaultProfile;
	stringProfileQoS+="\">";
	stringProfileQoS+=cfg;
	stringProfileQoS+="</qos_profile>";
}//setStringProfileQoS

/**************************************************************************************
 * 			StreamConfiguration
 **************************************************************************************/
StreamConfiguration::StreamConfiguration()
{

	participantPerStream = DEFAULT_PARTICIPANT_PER_STREAM;
}//StreamConfiguration

/**************************************************************************************
 * 			SenderStreamConfiguration
 **************************************************************************************/
SenderStreamConfiguration::SenderStreamConfiguration()
{
	profileQos=DEFAULT_SENDER_STREAM_PROFILE;
}//StreamConfiguration

/**************************************************************************************
 * 			ReceiverStreamConfiguration
 **************************************************************************************/
ReceiverStreamConfiguration::ReceiverStreamConfiguration()
{
	profileQos=DEFAULT_RECEIVER_STREAM_PROFILE;
	useIncrementUnicastPort = DEFAULT_USE_INCREMENT_UNICAST_PORT;
	baseUnicastPort = DEFAULT_BASE_UNICAST_PORT;
}//ReceiverStreamConfiguration

void ReceiverStreamConfiguration::setDDSReceiverStreamQoS(char *cfg)
{
	setStringProfileQoS(cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverStreamQoS

void ReceiverStreamConfiguration::setDDSReceiverStreamQoS(char *profileName, char* cfg)
{
	setStringProfileQoS(profileName, cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverStreamQoS

/**************************************************************************************
 * 			ReceiverFlowConfiguration
 **************************************************************************************/
ReceiverFlowConfiguration::ReceiverFlowConfiguration()
{
	profileQos=DEFAULT_RECEIVER_FLOW_PROFILE;
	cbReceiveProcessTimeout =DEFAULT_CBRECEIVE_PROCESS_TIMEOUT;
	cbReceiveAvgProcessTimeout =DEFAULT_CBRECEIVE_AVG_PROCESS_TIMEOUT;
	enableMulticast = DEFAULT_ENABLE_MULTICAST;
	multicastAddress = DEFAULT_MULTICAST_ADDRESS;
	unicastPort = DEFAULT_UNICAST_PORT;
}//ReceiverFlowConfiguration

double ReceiverFlowConfiguration::getCbReceiveProcessTimeout() const
{
    return cbReceiveProcessTimeout;
}

void ReceiverFlowConfiguration::setCbReceiveProcessTimeout(double cbReceiveProcessTimeout)
{
    this->cbReceiveProcessTimeout = cbReceiveProcessTimeout;
}

double ReceiverFlowConfiguration::getCbReceiveAvgProcessTimeout() const
{
    return cbReceiveAvgProcessTimeout;
}

void ReceiverFlowConfiguration::setCbReceiveAvgProcessTimeout(double cbReceiveAvgProcessTimeout)
{
    this->cbReceiveAvgProcessTimeout = cbReceiveAvgProcessTimeout;
}

std::string ReceiverFlowConfiguration::getMulticastAddress() const
{
    return multicastAddress;
}

bool ReceiverFlowConfiguration::isEnableMulticast() const
{
    return enableMulticast;
}

void ReceiverFlowConfiguration::setEnableMulticast(bool enableMulticast)
{
    this->enableMulticast = enableMulticast;
}

void ReceiverFlowConfiguration::setMulticastAddress(std::string multicastAddress)
{
    this->multicastAddress = multicastAddress;
}

unsigned short ReceiverFlowConfiguration::getUnicastPort() const
{
	return this->unicastPort;
}

void ReceiverFlowConfiguration::setUnicastPort(	unsigned short port)
{
	this->unicastPort = port;
}

void ReceiverFlowConfiguration::setDDSReceiverFlowQoS(char* cfg)
{
	setStringProfileQoS(cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverFlowQoS

void ReceiverFlowConfiguration::setDDSReceiverFlowQoS(char* profileName, char* cfg)
{
	setStringProfileQoS(profileName, cfg, DDSConfiguration::DEFAULT_RECEIVER_FLOW_PROFILE);
}//setDDSReceiverFlowQoS

/**************************************************************************************
 * 			SenderFlowConfiguration
 **************************************************************************************/
SenderFlowConfiguration::SenderFlowConfiguration()
{
	profileQos=DEFAULT_SENDER_FLOW_PROFILE;
	sendFrameTimeout = DEFAULT_SENDFRAME_TIMEOUT;
	ACKsTimeout = DEFAULT_ACKs_TIMEOUT;
}

double SenderFlowConfiguration::getACKsTimeout() const
{
    return ACKsTimeout;
}

double SenderFlowConfiguration::getSendFrameTimeout() const
{
    return sendFrameTimeout;
}

void SenderFlowConfiguration::setACKsTimeout(double acKsTimeout)
{
    ACKsTimeout = acKsTimeout;
}

void SenderFlowConfiguration::setSendFrameTimeout(double frameTimeout)
{
    this->sendFrameTimeout = frameTimeout;
}

void SenderFlowConfiguration::setDDSSenderFlowQoS(char* cfg)
{
	setStringProfileQoS(cfg, DDSConfiguration::DEFAULT_SENDER_FLOW_PROFILE);
}//setDDSReceiverFlowQoS

void SenderFlowConfiguration::setDDSSenderFlowQoS(char* profileName, char* cfg)
{
	setStringProfileQoS(profileName, cfg, DDSConfiguration::DEFAULT_SENDER_FLOW_PROFILE);
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <class T>
struct Node
{
	T data;
	Node<T>* left;
	Node<T>* right;
};

template <class T>
class BinaryTree
{
private:
	Node<T> *root;
	uint16_t CountElements = 0;
public:
	BinaryTree();
	~BinaryTree();
	void deleteNode(Node<T>* temp);
	void insert_node(const T&);
	void print()const;
	Node<T>*root_();
	Node<T> *find_node(const T&, Node<T>*)const;
	void output(ostream&, Node<T>*)const;
	void reading(const std::string&);
	void writing(const std::string&)const;
	bool search_result(const T& value)const;
	Node<T>* get_pointer(const T& value, Node<T>* temp)const;
	ostream& show(std::ostream&, const Node<T>*, unsigned int);
	friend std::ostream& operator<< <> (std::ostream&, BinaryTree<T>&);

};

template<typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return get_pointer(value, temp->right);
	else return get_pointer(value, temp->left);
}

template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
	return get_pointer(value, root);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
		return;
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
	++CountElements;
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
	ifstream fin(filename);
	if (root != nullptr)
		deleteNode(root);

	int k;
	fin >> k;
	T temp;
	for (int i = 0; i < k; ++i)
	{
		fin >> temp;
		insert_node(temp);
	}
	fin.close();
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream file_1(filename);
	file_1 << CountElements << "\t";
	output(file_1, root);
	file_1.close();
}

template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp, unsigned int level)
{
	show(ost, temp->right, level + 1);
	for (unsigned int i = 0; i < level; i++)
		ost << "\t";
	ost << temp->data << std::endl;
	show(ost, temp->left, level + 1);
	return ost;
}

template <typename T>
ostream& operator<<(std::ostream& ost, BinaryTree<T>& temp)
{
	show(ost, temp.root, 0);
	return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <class T>
struct Node
{
	T data;
	Node<T>* left;
	Node<T>* right;
};

template <class T>
class BinaryTree
{
private:
	Node<T> *root;
	uint16_t CountElements = 0;
public:
	BinaryTree();
	~BinaryTree();
	void deleteNode(Node<T>* temp);
	void insert_node(const T&);
	void print()const;
	Node<T>*root_();
	Node<T> *find_node(const T&, Node<T>*)const;
	void output(ostream&, Node<T>*)const;
	void reading(const std::string&);
	void writing(const std::string&)const;
	bool search_result(const T& value)const;
	Node<T>* get_pointer(const T& value, Node<T>* temp)const;
	std::ostream& show(std::ostream&, const Node<T>*, unsigned int);
	friend std::ostream& operator<< <> (std::ostream&, BinaryTree<T>&);

};

template<typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return get_pointer(value, temp->right);
	else return get_pointer(value, temp->left);
}

template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
	return get_pointer(value, root);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
		return;
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
	++CountElements;
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
	ifstream fin(filename);
	if (root != nullptr)
		deleteNode(root);

	int k;
	fin >> k;
	T temp;
	for (int i = 0; i < k; ++i)
	{
		fin >> temp;
		insert_node(temp);
	}
	fin.close();
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream file_1(filename);
	file_1 << CountElements << "\t";
	output(file_1, root);
	file_1.close();
}

template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp, unsigned int level)
{
	show(ost, temp->right, level + 1);
	for (unsigned int i = 0; i < level; i++)
		ost << "\t";
	ost << temp->data << std::endl;
	show(ost, temp->left, level + 1);
	return ost;
}

template <typename T>
std::ostream& operator<<(std::ostream& ost, BinaryTree<T>& temp)
{
	show(ost, temp.root, 0);
	return ost;
}
<|endoftext|>


<commit_before>GenerateDocumentation01() {
    //This macro auto-generates documentation (twiki-style)
    //based on all OADBs currently deployed in the AliPhysics
    //directory specified here:

    TString lPathToOADBs = "$ALICE_PHYSICS/../src/OADB/COMMON/MULTIPLICITY/data/";
    cout<<"Expanding path name..."<<endl;
    gSystem->ExpandPathName( lPathToOADBs );
    cout<< "Expanded to: "<<lPathToOADBs.Data()<<endl;

    //Start: determine list of available OADBs
    TSystemDirectory dir(lPathToOADBs.Data(), lPathToOADBs.Data());
    TList *files = dir.GetListOfFiles();

    //sorting...
    files->Sort();

    //Number of automatically found OADB files
    Long_t lNOADBs = 0;

    //Output text file
    TString lOutputDoc = "doc.txt";
    ofstream lDocs;
    lDocs.open ( lOutputDoc.Data() );

    if (files) {
        TSystemFile *file;
        TString fname;
        TIter next(files);
        while ((file=(TSystemFile*)next())) {
            fname = file->GetName();
            TString lProdName = fname;
            TString lCalibRuns = "";
            TString lTime = "";
            TString lEvSels = "";
            TString lEstims = "";
	    TString lEstimPerRun = "";
            lProdName.ReplaceAll("OADB-","");
            lProdName.ReplaceAll(".root","");
            if (!file->IsDirectory() && fname.EndsWith(".root")) {
                cout<<"======================================================"<<endl;
                cout<<" OADB entry for period ["<<lProdName.Data() <<"] found!"<<endl;
                cout<<" -> Opening OADB and checking for information ... "<<endl;

                //Mod time
                Long_t id,size,flags,mt;
                gSystem->GetPathInfo(Form("%s%s",lPathToOADBs.Data(),fname.Data()),&id,&size,&flags,&mt);
                TTimeStamp st(mt);
                cout<<"Date : "<<st.GetDate()<<endl;
                lTime.Append(Form("%i",st.GetDate()));

                TFile * f = new TFile (Form("%s%s",lPathToOADBs.Data(),fname.Data()));
                AliOADBContainer * oadbContMS = (AliOADBContainer*) f->Get("MultSel");
                cout<<" ---> contains this many runs: "<<oadbContMS->GetNumberOfEntries()<<endl;
                AliOADBMultSelection * oadbMultSelection = 0x0;
                for(Long_t ir=0; ir<oadbContMS->GetNumberOfEntries(); ir++) {

                    //Acquire the MultSelection Object for this run and get the specific
                    //calibration information (Anchor point and anchor percentile) for each estimator
                    oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(ir);

                    //Get estimator info
                    lCalibRuns.Append("<element title=\"");
                    for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
                        TString def     = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName();
                        Float_t lAP     = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPoint();
                        Float_t lAPPerc = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPercentile();

                        lCalibRuns.Append(Form("%s",def.Data())); //Name
			if(oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetUseAnchor()) {
                        lCalibRuns.Append(Form(": Raw Val %.3f, Percentile: %.3f",lAP,lAPPerc)); //Characteristics
			} else {
			  lCalibRuns.Append(": Unanchored"); //Characteristics
			}
                        if ( iEst != oadbMultSelection->GetMultSelection()->GetNEstimators()-1 )
                            lCalibRuns.Append("
"); //Name
                    }
                    lCalibRuns.Append(Form("\"> %i</element>",oadbContMS->LowerLimit(ir)));
                    if( ir != oadbContMS->GetNumberOfEntries()-1 ) lCalibRuns.Append(", ");
                }
                cout<<" ---> Detected calibrated runs: "<<endl;
                cout<<lCalibRuns.Data()<<endl;
                cout<<" ---> Acquiring example object by index... "<<endl;
                oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(0);
                cout<<" -> Adding: Event selection information ..."<<endl;
                if( oadbMultSelection ) {
                    lEvSels.Append(Form("Vertex position |z| < %.1f cm",oadbMultSelection->GetEventCuts()->GetVzCut() ) );
                    if( oadbMultSelection->GetEventCuts()->GetTriggerCut() ) lEvSels.Append(" + Physics selected (Minimum Bias: kMB/kINT7)");
                    if( oadbMultSelection->GetEventCuts()->GetINELgtZEROCut() ) lEvSels.Append(" + INEL>0 with SPD tracklets");
                    if( oadbMultSelection->GetEventCuts()->GetTrackletsVsClustersCut() ) lEvSels.Append(" + tracklets versus clusters cut");
                    if( oadbMultSelection->GetEventCuts()->GetRejectPileupInMultBinsCut() ) lEvSels.Append(" + Pileup in Mult bins rejection");
                    if( oadbMultSelection->GetEventCuts()->GetVertexConsistencyCut() ) lEvSels.Append(" + SPD and Track Vertex Consistency OK");
                    if( oadbMultSelection->GetEventCuts()->GetNonZeroNContribs() ) lEvSels.Append(" + At least 1 contributor to PV");
                    oadbMultSelection->GetMultSelection()->PrintInfo();
                    for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
                        //syntax = <element title="test test test mom mom mom"> %ICONURL{help}% </div>
                        TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetDefinition();
                        cout<<"Def = "<<def.Data()<<endl;
			//Replace > and <s for html code
			def.ReplaceAll("<","<");
			def.ReplaceAll(">",">");
                        lEstims.Append("<element title=\"");
                        lEstims.Append(Form("%s",def.Data()));
                        lEstims.Append(Form("\"> !%s</element>",oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName()));
                        if(iEst!=oadbMultSelection->GetMultSelection()->GetNEstimators()-1) lEstims.Append(", ");
                    }
                }
                cout<<" ---> Event Selection: "<<lEvSels.Data()<<endl;
                //Appending event selection as a tooltip next to the dataset name
                lProdName.Prepend("*");
                lProdName.Append("*");
                lProdName.Append(Form(" <element title=\"Event Selection: %s\"",lEvSels.Data() ));
                lProdName.Append("> %ICONURL{help}% </element>");

                cout<<" ---> Estimator string: "<<lEstims.Data()<<endl;
                cout<<" -> Adding: estimator definition information ..."<<endl;
                cout<<"======================================================"<<endl;
                //Print this in this format:
                //| LHCxxx   |   RUNLIST   |   xx/xx/xxx   |   ESTIMATORS   |
                lDocs<<"| "<<lProdName.Data()<<" | "<<lCalibRuns.Data()<<" |   "<<lTime.Data()<<"   | "<<lEstims.Data()<<" |"<<endl;

            }
        }
    }

}
<commit_msg>Updating script to generate AliMultSelectionCalibStatus Twiki page (for bookkeeping purposes)<commit_after>GenerateDocumentation01() {
    //This macro auto-generates documentation (twiki-style)
    //based on all OADBs currently deployed in the AliPhysics
    //directory specified here:

    TString lPathToOADBs = "$HOME/alice/ali-master/AliPhysics/OADB/COMMON/MULTIPLICITY/data/";
    cout<<"Expanding path name..."<<endl;
    gSystem->ExpandPathName( lPathToOADBs );
    cout<< "Expanded to: "<<lPathToOADBs.Data()<<endl;

    //Start: determine list of available OADBs
    TSystemDirectory dir(lPathToOADBs.Data(), lPathToOADBs.Data());
    TList *files = dir.GetListOfFiles();

    //sorting...
    files->Sort();

    //Number of automatically found OADB files
    Long_t lNOADBs = 0;

    //Output text file
    TString lOutputDoc = "doc.txt";
    ofstream lDocs;
    lDocs.open ( lOutputDoc.Data() );

    if (files) {
        TSystemFile *file;
        TString fname;
        TIter next(files);
        while ((file=(TSystemFile*)next())) {
            fname = file->GetName();
            TString lProdName = fname;
            TString lCalibRuns = "";
            TString lTime = "";
            TString lEvSels = "";
            TString lEstims = "";
	    TString lEstimPerRun = "";
            lProdName.ReplaceAll("OADB-","");
            lProdName.ReplaceAll(".root","");
            if (!file->IsDirectory() && fname.EndsWith(".root")) {
                cout<<"======================================================"<<endl;
                cout<<" OADB entry for period ["<<lProdName.Data() <<"] found!"<<endl;
                cout<<" -> Opening OADB and checking for information ... "<<endl;

                //Mod time
                //Long_t id,size,flags,mt;
                //gSystem->GetPathInfo(Form("%s%s",lPathToOADBs.Data(),fname.Data()),&id,&size,&flags,&mt);
                //TTimeStamp st(mt);
                //cout<<"Date : "<<st.GetDate()<<endl;
                //lTime.Append(Form("%i",st.GetDate()));

                //Modification time, as per git command:
                // git log -1 --format="%ai" -- OADB-blablabla.root
                lTime = gSystem->GetFromPipe(Form("cd %s; git log -1 --format=\"%%ai\" -- OADB-%s.root", lPathToOADBs.Data(), lProdName.Data()));

                cout<<"======================================================"<<endl;
                cout<<lTime.Data()<<endl;
                cout<<"======================================================"<<endl;

                TFile * f = new TFile (Form("%s%s",lPathToOADBs.Data(),fname.Data()));
                AliOADBContainer * oadbContMS = (AliOADBContainer*) f->Get("MultSel");
                cout<<" ---> contains this many runs: "<<oadbContMS->GetNumberOfEntries()<<endl;
                AliOADBMultSelection * oadbMultSelection = 0x0;
                for(Long_t ir=0; ir<oadbContMS->GetNumberOfEntries(); ir++) {

                    //Acquire the MultSelection Object for this run and get the specific
                    //calibration information (Anchor point and anchor percentile) for each estimator
                    oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(ir);

                    //Get estimator info
                    lCalibRuns.Append("<element title=\"");
                    for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
                        TString def     = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName();
                        Float_t lAP     = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPoint();
                        Float_t lAPPerc = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetAnchorPercentile();

                        lCalibRuns.Append(Form("%s",def.Data())); //Name
			if(oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetUseAnchor()) {
                        lCalibRuns.Append(Form(": Raw Val %.3f, Percentile: %.3f",lAP,lAPPerc)); //Characteristics
			} else {
			  lCalibRuns.Append(": Unanchored"); //Characteristics
			}
                        if ( iEst != oadbMultSelection->GetMultSelection()->GetNEstimators()-1 )
                            lCalibRuns.Append("
"); //Name
                    }
                    lCalibRuns.Append(Form("\"> %i</element>",oadbContMS->LowerLimit(ir)));
                    if( ir != oadbContMS->GetNumberOfEntries()-1 ) lCalibRuns.Append(", ");
                }
                cout<<" ---> Detected calibrated runs: "<<endl;
                cout<<lCalibRuns.Data()<<endl;
                cout<<" ---> Acquiring example object by index... "<<endl;
                oadbMultSelection = (AliOADBMultSelection* )oadbContMS->GetObjectByIndex(0);
                cout<<" -> Adding: Event selection information ..."<<endl;
                if( oadbMultSelection ) {
                    lEvSels.Append(Form("Vertex position |z| < %.1f cm",oadbMultSelection->GetEventCuts()->GetVzCut() ) );
                    if( oadbMultSelection->GetEventCuts()->GetTriggerCut() ) lEvSels.Append(" + Physics selected (Minimum Bias: kMB/kINT7)");
                    if( oadbMultSelection->GetEventCuts()->GetINELgtZEROCut() ) lEvSels.Append(" + INEL>0 with SPD tracklets");
                    if( oadbMultSelection->GetEventCuts()->GetTrackletsVsClustersCut() ) lEvSels.Append(" + tracklets versus clusters cut");
                    if( oadbMultSelection->GetEventCuts()->GetRejectPileupInMultBinsCut() ) lEvSels.Append(" + Pileup in Mult bins rejection");
                    if( oadbMultSelection->GetEventCuts()->GetVertexConsistencyCut() ) lEvSels.Append(" + SPD and Track Vertex Consistency OK");
                    if( oadbMultSelection->GetEventCuts()->GetNonZeroNContribs() ) lEvSels.Append(" + At least 1 contributor to PV");
                    oadbMultSelection->GetMultSelection()->PrintInfo();
                    for(Int_t iEst = 0; iEst<oadbMultSelection->GetMultSelection()->GetNEstimators(); iEst++) {
                        //syntax = <element title="test test test mom mom mom"> %ICONURL{help}% </div>
                        TString def = oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetDefinition();
                        cout<<"Def = "<<def.Data()<<endl;
			//Replace > and <s for html code
			def.ReplaceAll("<","<");
			def.ReplaceAll(">",">");
                        lEstims.Append("<element title=\"");
                        lEstims.Append(Form("%s",def.Data()));
                        lEstims.Append(Form("\"> !%s</element>",oadbMultSelection->GetMultSelection()->GetEstimator(iEst)->GetName()));
                        if(iEst!=oadbMultSelection->GetMultSelection()->GetNEstimators()-1) lEstims.Append(", ");
                    }
                }
                cout<<" ---> Event Selection: "<<lEvSels.Data()<<endl;
                //Appending event selection as a tooltip next to the dataset name
                lProdName.Prepend("*");
                lProdName.Append("*");
                lProdName.Append(Form(" <element title=\"Event Selection: %s\"",lEvSels.Data() ));
                lProdName.Append("> %ICONURL{help}% </element>");

                cout<<" ---> Estimator string: "<<lEstims.Data()<<endl;
                cout<<" -> Adding: estimator definition information ..."<<endl;
                cout<<"======================================================"<<endl;
                //Print this in this format:
                //| LHCxxx   |   RUNLIST   |   xx/xx/xxx   |   ESTIMATORS   |
                lDocs<<"| "<<lProdName.Data()<<" | "<<lCalibRuns.Data()<<" |   "<<lTime.Data()<<"   | "<<lEstims.Data()<<" |"<<endl;

            }
        }
    }

}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <typename T>
std::ostream& operator<<(std::ostream&, const BinaryTree<T>&);

template <class T>
struct Node
{
	T data;
	Node<T>* left;
	Node<T>* right;
};

template <class T>
class BinaryTree
{
private:
	Node<T> *root;
	uint16_t CountElements = 0;
public:
	BinaryTree();
	~BinaryTree();
	void deleteNode(Node<T>* temp);
	void insert_node(const T&);
	void print()const;
	Node<T>*root_();
	Node<T> *find_node(const T&, Node<T>*)const;
	void output(ostream&, Node<T>*)const;
	void reading(const std::string&);
	void writing(const std::string&)const;
	bool search_result(const T& value)const;
	Node<T>* get_pointer(const T& value, Node<T>* temp)const;
	ostream& show(std::ostream&, const Node<T>*, unsigned int);
	friend std::ostream& operator<< <> (std::ostream&, BinaryTree<T>*);

};

template<typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return get_pointer(value, temp->right);
	else return get_pointer(value, temp->left);
}

template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
	return get_pointer(value, root);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
		return;
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
	++CountElements;
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
	ifstream fin(filename);
	if (root != nullptr)
		deleteNode(root);

	int k;
	fin >> k;
	T temp;
	for (int i = 0; i < k; ++i)
	{
		fin >> temp;
		insert_node(temp);
	}
	fin.close();
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream file_1(filename);
	file_1 << CountElements << "\t";
	output(file_1, root);
	file_1.close();
}

template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp, unsigned int level)
{
	show(ost, temp->right, level + 1);
	for (unsigned int i = 0; i < level; i++)
		ost << "\t";
	ost << temp->data << std::endl;
	show(ost, temp->left, level + 1);
	return ost;
}

template <typename T>
ostream& operator<<(std::ostream& ost, BinaryTree<T>& temp)
{
	show(ost, temp.root, 0);
	return ost;
}
<commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream>
#include <string>
#include <fstream>
#include <cstdint>

using namespace std;

template <typename T>
std::ostream& operator<< <> (std::ostream&, BinaryTree<T>&);

template <class T>
struct Node
{
	T data;
	Node<T>* left;
	Node<T>* right;
};

template <class T>
class BinaryTree
{
private:
	Node<T> *root;
	uint16_t CountElements = 0;
public:
	BinaryTree();
	~BinaryTree();
	void deleteNode(Node<T>* temp);
	void insert_node(const T&);
	void print()const;
	Node<T>*root_();
	Node<T> *find_node(const T&, Node<T>*)const;
	void output(ostream&, Node<T>*)const;
	void reading(const std::string&);
	void writing(const std::string&)const;
	bool search_result(const T& value)const;
	Node<T>* get_pointer(const T& value, Node<T>* temp)const;
	ostream& show(std::ostream&, const Node<T>*, unsigned int);
	friend std::ostream& operator<< <> (std::ostream&, BinaryTree<T>*);

};

template<typename T>
BinaryTree<T>::BinaryTree()
{
	root = nullptr;
}

template<typename T>
BinaryTree<T>::~BinaryTree()
{
	deleteNode(root);
}

template<typename T>
Node<T> *BinaryTree<T>::get_pointer(const T& value, Node<T>* temp)const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return get_pointer(value, temp->right);
	else return get_pointer(value, temp->left);
}

template<typename T>
bool BinaryTree<T>::search_result(const T& value)const
{
	return get_pointer(value, root);
}

template<typename T>
void BinaryTree<T>::deleteNode(Node<T>* temp)
{
	if (!temp)
		return;
	if (temp->left)
	{
		deleteNode(temp->left);
		temp->left = nullptr;
	}

	if (temp->right)
	{
		deleteNode(temp->right);
		temp->right = nullptr;
	}
	delete temp;
}

template<typename T>
void BinaryTree<T>::insert_node(const T&x)
{
	if (find_node(x, root_())) return;
	Node<T>* MyTree = new Node<T>;
	MyTree->data = x;
	MyTree->left = MyTree->right = 0;
	Node<T>* buff = root;
	Node<T>* temp = root;
	while (temp)
	{
		buff = temp;
		if (x < temp->data)
			temp = temp->left;
		else
			temp = temp->right;
	}
	if (!buff)
		root = MyTree;
	else
	{
		if (x < buff->data)
			buff->left = MyTree;
		else
			buff->right = MyTree;
	}
	++CountElements;
}

template<typename T>
Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const
{
	if (temp == 0 || value == temp->data)
		return temp;
	if (value > temp->data)
		return find_node(value, temp->right);
	else
		return find_node(value, temp->left);
}

template<typename T>
void BinaryTree<T>::reading(const std::string& filename)
{
	ifstream fin(filename);
	if (root != nullptr)
		deleteNode(root);

	int k;
	fin >> k;
	T temp;
	for (int i = 0; i < k; ++i)
	{
		fin >> temp;
		insert_node(temp);
	}
	fin.close();
}

template<typename T>
void BinaryTree<T>::writing(const std::string& filename)const
{
	ofstream file_1(filename);
	file_1 << CountElements << "\t";
	output(file_1, root);
	file_1.close();
}

template <typename T>
std::ostream& show(std::ostream& ost, const Node<T>* temp, unsigned int level)
{
	show(ost, temp->right, level + 1);
	for (unsigned int i = 0; i < level; i++)
		ost << "\t";
	ost << temp->data << std::endl;
	show(ost, temp->left, level + 1);
	return ost;
}

template <typename T>
ostream& operator<<(std::ostream& ost, BinaryTree<T>& temp)
{
	show(ost, temp.root, 0);
	return ost;
}
<|endoftext|>


<commit_before>#ifndef slic3r_SupportMaterial_hpp_
#define slic3r_SupportMaterial_hpp_

#include "Flow.hpp"

namespace Slic3r {

class PrintObject;
class PrintConfig;
class PrintObjectConfig;

// how much we extend support around the actual contact area
#define SUPPORT_MATERIAL_MARGIN 1.5

// Instantiated by Slic3r::Print::Object->_support_material()
class PrintSupportMaterial
{
public:
	enum SupporLayerType {
		sltUnknown = 0,
		sltRaft,
		stlFirstLayer,
		sltBottomContact,
		sltBottomInterface,
		sltBase,
		sltTopInterface,
		sltTopContact,
		// Some undecided type yet. It will turn into stlBase first, then it may turn into stlBottomInterface or stlTopInterface.
		stlIntermediate,
	};

	class MyLayer
	{
	public:
		MyLayer() :
			layer_type(sltUnknown),
			print_z(0.),
			bottom_z(0.),
			height(0.),
			idx_object_layer_above(size_t(-1)),
			idx_object_layer_below(size_t(-1)),
			bridging(false)
			{}

		~MyLayer()
		{
			delete aux_polygons;
			aux_polygons = NULL;
		}

		bool operator==(const MyLayer &layer2) const {
			return print_z == layer2.print_z && height == layer2.height && bridging == layer2.bridging;
		}

		bool operator<(const MyLayer &layer2) const {
			if (print_z < layer2.print_z) {
				return true;
			} else if (print_z == layer2.print_z) {
			 	if (height > layer2.height)
			 		return true;
			 	else if (height == layer2.height) {
			 	 	return bridging < layer2.bridging;
			 	} else
			 		return false;
			} else
				return false;
		}

		SupporLayerType layer_type;
		// Z used for printing in unscaled coordinates
		coordf_t print_z;
		// Bottom height of this layer. For soluble layers, bottom_z + height = print_z,
		// otherwise bottom_z + gap + height = print_z.
		coordf_t bottom_z;
		// layer height in unscaled coordinates
    	coordf_t height;
    	// Index of a PrintObject layer_id supported by this layer. This will be set for top contact layers.
    	// If this is not a contact layer, it will be set to size_t(-1).
    	size_t 	 idx_object_layer_above;
    	// Index of a PrintObject layer_id, which supports this layer. This will be set for bottom contact layers.
    	// If this is not a contact layer, it will be set to size_t(-1).
    	size_t 	 idx_object_layer_below;
    	// Use a bridging flow when printing this support layer.
    	bool 	 bridging;

    	// Polygons to be filled by the support pattern.
    	Polygons polygons;
    	// Currently for the contact layers only: Overhangs are stored here.
    	Polygons *aux_polygons;
	};

	struct LayerExtreme
	{
		LayerExtreme(MyLayer *alayer, bool ais_top) : layer(alayer), is_top(ais_top) {}
		MyLayer 	*layer;
		// top or bottom extreme
		bool   		 is_top;

		coordf_t	z() const { return is_top ? layer->print_z : layer->print_z - layer->height; }

		bool operator<(const LayerExtreme &other) const { return z() < other.z(); }
	};

	struct LayerPrintZ_Hash {
		size_t operator()(const MyLayer &layer) const {
			return std::hash<double>()(layer.print_z)^std::hash<double>()(layer.height)^size_t(layer.bridging);
		}
	};

	typedef std::vector<MyLayer*> 				MyLayersPtr;
	typedef std::deque<MyLayer> 				MyLayerStorage;

public:
	PrintSupportMaterial(
		const PrintConfig 		*print_config,
		const PrintObjectConfig	*object_config,
		const Flow 			 	&flow,
		const Flow 			 	&first_layer_flow,
		const Flow 			 	&interface_flow,
		bool 			 	 	 soluble_interface) :
		m_print_config(print_config),
		m_object_config(object_config),
		m_flow(flow),
		m_first_layer_flow(first_layer_flow),
		m_interface_flow(interface_flow),
		m_soluble_interface(soluble_interface),
		m_support_layer_height_max(0.),
		m_support_interface_layer_height_max(0.)
	{}

	PrintSupportMaterial(
		PrintConfig 		*print_config,
		PrintObjectConfig	*object_config,
		Flow 			 	*flow,
		Flow 			 	*first_layer_flow,
		Flow 			 	*interface_flow,
		bool 			 	 soluble_interface) :
		m_print_config(print_config),
		m_object_config(object_config),
		m_flow(*flow),
		m_first_layer_flow(*first_layer_flow),
		m_interface_flow(*interface_flow),
		m_soluble_interface(soluble_interface),
		m_support_layer_height_max(0.),
		m_support_interface_layer_height_max(0.)
	{}

	// Generate support material for the object.
	// New support layers will be added to the object,
	// with extrusion paths and islands filled in for each support layer.
	void generate(PrintObject &object);

private:
	// Generate top contact layers supporting overhangs.
	// For a soluble interface material synchronize the layer heights with the object, otherwise leave the layer height undefined.
	// If supports over bed surface only are requested, don't generate contact layers over an object.
	MyLayersPtr top_contact_layers(const PrintObject &object, MyLayerStorage &layer_storage) const;

	// Generate bottom contact layers supporting the top contact layers.
	// For a soluble interface material synchronize the layer heights with the object,
	// otherwise set the layer height to a bridging flow of a support interface nozzle.
	MyLayersPtr bottom_contact_layers(const PrintObject &object, const MyLayersPtr &top_contacts, MyLayerStorage &layer_storage) const;

	// Trim the top_contacts layers with the bottom_contacts layers if they overlap, so there would not be enough vertical space for both of them.
	void trim_top_contacts_by_bottom_contacts(const PrintObject &object, const MyLayersPtr &bottom_contacts, MyLayersPtr &top_contacts) const;

	// Generate raft layers and the intermediate support layers between the bottom contact and top contact surfaces.
	MyLayersPtr raft_and_intermediate_support_layers(
	    const PrintObject   &object,
	    const MyLayersPtr   &bottom_contacts,
	    const MyLayersPtr   &top_contacts,
	    MyLayerStorage	 	&layer_storage,
	    const coordf_t       max_object_layer_height) const;

	void generate_base_layers(
	    const PrintObject   &object,
	    const MyLayersPtr   &bottom_contacts,
	    const MyLayersPtr   &top_contacts,
	    MyLayersPtr         &intermediate_layers) const;

	MyLayersPtr generate_interface_layers(
	    const PrintObject   &object,
	    const MyLayersPtr   &bottom_contacts,
	    const MyLayersPtr   &top_contacts,
	    MyLayersPtr         &intermediate_layers,
	    MyLayerStorage      &layer_storage) const;

/*
	void generate_pillars_shape();
	void clip_with_shape();
*/

	// Produce the actual G-code.
	void generate_toolpaths(
        const PrintObject   &object,
        const MyLayersPtr   &bottom_contacts,
        const MyLayersPtr   &top_contacts,
        const MyLayersPtr   &intermediate_layers,
        const MyLayersPtr   &interface_layers) const;

	const PrintConfig 		*m_print_config;
	const PrintObjectConfig *m_object_config;
	Flow 			 	 m_flow;
	Flow 			 	 m_first_layer_flow;
	Flow 			 	 m_interface_flow;
	bool 			 	 m_soluble_interface;

	coordf_t		 	 m_support_layer_height_max;
	coordf_t		 	 m_support_interface_layer_height_max;
	bool 				 m_synchronize_support_layers_with_object;
};

} // namespace Slic3r

#endif /* slic3r_SupportMaterial_hpp_ */
<commit_msg>Disable C++11 hash feature in C++ Supports to compile on Strawberry.<commit_after>#ifndef slic3r_SupportMaterial_hpp_
#define slic3r_SupportMaterial_hpp_

#include "Flow.hpp"

namespace Slic3r {

class PrintObject;
class PrintConfig;
class PrintObjectConfig;

// how much we extend support around the actual contact area
#define SUPPORT_MATERIAL_MARGIN 1.5

// Instantiated by Slic3r::Print::Object->_support_material()
class PrintSupportMaterial
{
public:
	enum SupporLayerType {
		sltUnknown = 0,
		sltRaft,
		stlFirstLayer,
		sltBottomContact,
		sltBottomInterface,
		sltBase,
		sltTopInterface,
		sltTopContact,
		// Some undecided type yet. It will turn into stlBase first, then it may turn into stlBottomInterface or stlTopInterface.
		stlIntermediate,
	};

	class MyLayer
	{
	public:
		MyLayer() :
			layer_type(sltUnknown),
			print_z(0.),
			bottom_z(0.),
			height(0.),
			idx_object_layer_above(size_t(-1)),
			idx_object_layer_below(size_t(-1)),
			bridging(false)
			{}

		~MyLayer()
		{
			delete aux_polygons;
			aux_polygons = NULL;
		}

		bool operator==(const MyLayer &layer2) const {
			return print_z == layer2.print_z && height == layer2.height && bridging == layer2.bridging;
		}

		bool operator<(const MyLayer &layer2) const {
			if (print_z < layer2.print_z) {
				return true;
			} else if (print_z == layer2.print_z) {
			 	if (height > layer2.height)
			 		return true;
			 	else if (height == layer2.height) {
			 	 	return bridging < layer2.bridging;
			 	} else
			 		return false;
			} else
				return false;
		}

		SupporLayerType layer_type;
		// Z used for printing in unscaled coordinates
		coordf_t print_z;
		// Bottom height of this layer. For soluble layers, bottom_z + height = print_z,
		// otherwise bottom_z + gap + height = print_z.
		coordf_t bottom_z;
		// layer height in unscaled coordinates
    	coordf_t height;
    	// Index of a PrintObject layer_id supported by this layer. This will be set for top contact layers.
    	// If this is not a contact layer, it will be set to size_t(-1).
    	size_t 	 idx_object_layer_above;
    	// Index of a PrintObject layer_id, which supports this layer. This will be set for bottom contact layers.
    	// If this is not a contact layer, it will be set to size_t(-1).
    	size_t 	 idx_object_layer_below;
    	// Use a bridging flow when printing this support layer.
    	bool 	 bridging;

    	// Polygons to be filled by the support pattern.
    	Polygons polygons;
    	// Currently for the contact layers only: Overhangs are stored here.
    	Polygons *aux_polygons;
	};

	struct LayerExtreme
	{
		LayerExtreme(MyLayer *alayer, bool ais_top) : layer(alayer), is_top(ais_top) {}
		MyLayer 	*layer;
		// top or bottom extreme
		bool   		 is_top;

		coordf_t	z() const { return is_top ? layer->print_z : layer->print_z - layer->height; }

		bool operator<(const LayerExtreme &other) const { return z() < other.z(); }
	};

/*
	struct LayerPrintZ_Hash {
		size_t operator()(const MyLayer &layer) const {
			return std::hash<double>()(layer.print_z)^std::hash<double>()(layer.height)^size_t(layer.bridging);
		}
	};
*/

	typedef std::vector<MyLayer*> 				MyLayersPtr;
	typedef std::deque<MyLayer> 				MyLayerStorage;

public:
	PrintSupportMaterial(
		const PrintConfig 		*print_config,
		const PrintObjectConfig	*object_config,
		const Flow 			 	&flow,
		const Flow 			 	&first_layer_flow,
		const Flow 			 	&interface_flow,
		bool 			 	 	 soluble_interface) :
		m_print_config(print_config),
		m_object_config(object_config),
		m_flow(flow),
		m_first_layer_flow(first_layer_flow),
		m_interface_flow(interface_flow),
		m_soluble_interface(soluble_interface),
		m_support_layer_height_max(0.),
		m_support_interface_layer_height_max(0.)
	{}

	PrintSupportMaterial(
		PrintConfig 		*print_config,
		PrintObjectConfig	*object_config,
		Flow 			 	*flow,
		Flow 			 	*first_layer_flow,
		Flow 			 	*interface_flow,
		bool 			 	 soluble_interface) :
		m_print_config(print_config),
		m_object_config(object_config),
		m_flow(*flow),
		m_first_layer_flow(*first_layer_flow),
		m_interface_flow(*interface_flow),
		m_soluble_interface(soluble_interface),
		m_support_layer_height_max(0.),
		m_support_interface_layer_height_max(0.)
	{}

	// Generate support material for the object.
	// New support layers will be added to the object,
	// with extrusion paths and islands filled in for each support layer.
	void generate(PrintObject &object);

private:
	// Generate top contact layers supporting overhangs.
	// For a soluble interface material synchronize the layer heights with the object, otherwise leave the layer height undefined.
	// If supports over bed surface only are requested, don't generate contact layers over an object.
	MyLayersPtr top_contact_layers(const PrintObject &object, MyLayerStorage &layer_storage) const;

	// Generate bottom contact layers supporting the top contact layers.
	// For a soluble interface material synchronize the layer heights with the object,
	// otherwise set the layer height to a bridging flow of a support interface nozzle.
	MyLayersPtr bottom_contact_layers(const PrintObject &object, const MyLayersPtr &top_contacts, MyLayerStorage &layer_storage) const;

	// Trim the top_contacts layers with the bottom_contacts layers if they overlap, so there would not be enough vertical space for both of them.
	void trim_top_contacts_by_bottom_contacts(const PrintObject &object, const MyLayersPtr &bottom_contacts, MyLayersPtr &top_contacts) const;

	// Generate raft layers and the intermediate support layers between the bottom contact and top contact surfaces.
	MyLayersPtr raft_and_intermediate_support_layers(
	    const PrintObject   &object,
	    const MyLayersPtr   &bottom_contacts,
	    const MyLayersPtr   &top_contacts,
	    MyLayerStorage	 	&layer_storage,
	    const coordf_t       max_object_layer_height) const;

	void generate_base_layers(
	    const PrintObject   &object,
	    const MyLayersPtr   &bottom_contacts,
	    const MyLayersPtr   &top_contacts,
	    MyLayersPtr         &intermediate_layers) const;

	MyLayersPtr generate_interface_layers(
	    const PrintObject   &object,
	    const MyLayersPtr   &bottom_contacts,
	    const MyLayersPtr   &top_contacts,
	    MyLayersPtr         &intermediate_layers,
	    MyLayerStorage      &layer_storage) const;

/*
	void generate_pillars_shape();
	void clip_with_shape();
*/

	// Produce the actual G-code.
	void generate_toolpaths(
        const PrintObject   &object,
        const MyLayersPtr   &bottom_contacts,
        const MyLayersPtr   &top_contacts,
        const MyLayersPtr   &intermediate_layers,
        const MyLayersPtr   &interface_layers) const;

	const PrintConfig 		*m_print_config;
	const PrintObjectConfig *m_object_config;
	Flow 			 	 m_flow;
	Flow 			 	 m_first_layer_flow;
	Flow 			 	 m_interface_flow;
	bool 			 	 m_soluble_interface;

	coordf_t		 	 m_support_layer_height_max;
	coordf_t		 	 m_support_interface_layer_height_max;
	bool 				 m_synchronize_support_layers_with_object;
};

} // namespace Slic3r

#endif /* slic3r_SupportMaterial_hpp_ */
<|endoftext|>


<commit_before>#include "control.h"

int main()
{
	Control C;
	C.inicializador();
	return 0;
}<commit_msg>un pause en el main<commit_after>#include "control.h"

int main()
{
	Control C;
	C.inicializador();
	system("pause");
	return 0;
}<|endoftext|>


<commit_before>//#####################################################################
// Class Nested
//#####################################################################
#include <geode/array/Nested.h>
#include <geode/array/convert.h>
#include <geode/python/Class.h>
namespace geode {

Array<int> nested_array_offsets(RawArray<const int> lengths) {
  Array<int> offsets(lengths.size()+1,false);
  offsets[0] = 0;
  for (int i=0;i<lengths.size();i++) {
    GEODE_ASSERT(lengths[i]>=0);
    offsets[i+1] = offsets[i]+lengths[i];
  }
  return offsets;
}

#ifdef GEODE_PYTHON

static PyTypeObject* nested_array_type;
static PyObject* offsets_string;
static PyObject* flat_string;
static PyObject* empty_tuple;

static void _set_nested_array(PyObject* nested_array) {
  GEODE_ASSERT(PyObject_IsInstance(nested_array,(PyObject*)&PyType_Type));
  nested_array_type = (PyTypeObject*)nested_array;
}

PyObject* nested_array_to_python_helper(PyObject* offsets, PyObject* flat) {
  PyObject* object = 0;
  if (!nested_array_type) {
    PyErr_SetString(PyExc_RuntimeError,"_set_nested_array must be called before calling to_python");
    goto fail;
  }
  object = nested_array_type->tp_new(nested_array_type,empty_tuple,0);
  if (!object)
    goto fail;
  if (PyObject_GenericSetAttr(object,&*offsets_string,offsets))
    goto fail;
  Py_DECREF(offsets);
  offsets = 0;
  if (PyObject_GenericSetAttr(object,&*flat_string,flat))
    goto fail;
  Py_DECREF(flat);
  flat = 0;
  return object;
fail:
  Py_XDECREF(offsets);
  Py_XDECREF(flat);
  Py_XDECREF(object);
  return 0;
}

bool is_nested_array(PyObject* object) {
  GEODE_ASSERT(nested_array_type);
  return PyObject_IsInstance(object,(PyObject*)nested_array_type)!=0;
}

Vector<Ref<>,2> nested_array_from_python_helper(PyObject* object) {
  return vec(steal_ref_check(PyObject_GetAttr(object,&*offsets_string)),
             steal_ref_check(PyObject_GetAttr(object,&*flat_string)));
}

NESTED_CONVERSIONS(int)
NESTED_CONVERSIONS(float)
NESTED_CONVERSIONS(double)
NESTED_CONVERSIONS(Vector<float,2>)
NESTED_CONVERSIONS(Vector<double,2>)

#endif
}

void wrap_nested_array() {
  using namespace geode;

#ifdef GEODE_PYTHON
  GEODE_FUNCTION(_set_nested_array)

  offsets_string = PyString_FromString("offsets");
  if (!offsets_string) throw_python_error();
  flat_string = PyString_FromString("flat");
  if (!flat_string) throw_python_error();
  empty_tuple = PyTuple_New(0);
  if (!empty_tuple) throw_python_error();
#endif
}
<commit_msg>Add python conversion for Nested<Vec3><commit_after>//#####################################################################
// Class Nested
//#####################################################################
#include <geode/array/Nested.h>
#include <geode/array/convert.h>
#include <geode/python/Class.h>
namespace geode {

Array<int> nested_array_offsets(RawArray<const int> lengths) {
  Array<int> offsets(lengths.size()+1,false);
  offsets[0] = 0;
  for (int i=0;i<lengths.size();i++) {
    GEODE_ASSERT(lengths[i]>=0);
    offsets[i+1] = offsets[i]+lengths[i];
  }
  return offsets;
}

#ifdef GEODE_PYTHON

static PyTypeObject* nested_array_type;
static PyObject* offsets_string;
static PyObject* flat_string;
static PyObject* empty_tuple;

static void _set_nested_array(PyObject* nested_array) {
  GEODE_ASSERT(PyObject_IsInstance(nested_array,(PyObject*)&PyType_Type));
  nested_array_type = (PyTypeObject*)nested_array;
}

PyObject* nested_array_to_python_helper(PyObject* offsets, PyObject* flat) {
  PyObject* object = 0;
  if (!nested_array_type) {
    PyErr_SetString(PyExc_RuntimeError,"_set_nested_array must be called before calling to_python");
    goto fail;
  }
  object = nested_array_type->tp_new(nested_array_type,empty_tuple,0);
  if (!object)
    goto fail;
  if (PyObject_GenericSetAttr(object,&*offsets_string,offsets))
    goto fail;
  Py_DECREF(offsets);
  offsets = 0;
  if (PyObject_GenericSetAttr(object,&*flat_string,flat))
    goto fail;
  Py_DECREF(flat);
  flat = 0;
  return object;
fail:
  Py_XDECREF(offsets);
  Py_XDECREF(flat);
  Py_XDECREF(object);
  return 0;
}

bool is_nested_array(PyObject* object) {
  GEODE_ASSERT(nested_array_type);
  return PyObject_IsInstance(object,(PyObject*)nested_array_type)!=0;
}

Vector<Ref<>,2> nested_array_from_python_helper(PyObject* object) {
  return vec(steal_ref_check(PyObject_GetAttr(object,&*offsets_string)),
             steal_ref_check(PyObject_GetAttr(object,&*flat_string)));
}

NESTED_CONVERSIONS(int)
NESTED_CONVERSIONS(float)
NESTED_CONVERSIONS(double)
NESTED_CONVERSIONS(Vector<float,2>)
NESTED_CONVERSIONS(Vector<float,3>)
NESTED_CONVERSIONS(Vector<double,2>)
NESTED_CONVERSIONS(Vector<double,3>)

#endif
}

void wrap_nested_array() {
  using namespace geode;

#ifdef GEODE_PYTHON
  GEODE_FUNCTION(_set_nested_array)

  offsets_string = PyString_FromString("offsets");
  if (!offsets_string) throw_python_error();
  flat_string = PyString_FromString("flat");
  if (!flat_string) throw_python_error();
  empty_tuple = PyTuple_New(0);
  if (!empty_tuple) throw_python_error();
#endif
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// 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 MTAC_UTILS_H
#define MTAC_UTILS_H

#include <memory>
#include <utility>
#include <unordered_set>
#include <unordered_map>

#include "variant.hpp"
#include "Type.hpp"
#include "VisitorUtils.hpp"

#include "mtac/Program.hpp"
#include "mtac/Operator.hpp"
#include "mtac/forward.hpp"

namespace eddic {

class Variable;
struct GlobalContext;

namespace mtac {

template<typename V, typename T>
inline bool equals(T& variant, V value){
    return boost::get<V>(&variant) && value == boost::get<V>(variant);
}

template<typename V, typename T>
inline bool is(T& variant){
    return boost::get<V>(&variant);
}

template<typename V, typename T>
inline bool optional_is(T& variant){
    return variant && boost::get<V>(&*variant);
}

template<typename T>
inline bool isInt(T variant){
    return boost::get<int>(&variant);
}

template<typename T>
inline bool isFloat(T& variant){
    return boost::get<double>(&variant);
}

template<typename T>
inline bool isVariable(T& variant){
    return boost::get<std::shared_ptr<Variable>>(&variant);
}

template<typename T>
inline void assertIntOrVariable(T& variant){
    assert(isInt(variant) || isVariable(variant));
}

template<typename Visitor>
void visit_all_statements(Visitor& visitor, mtac::Function& function){
    for(auto& block : function){
        visit_each(visitor, block->statements);
    }
}

template<typename T, typename OptVariant, typename Functor>
void if_init(OptVariant& opt_variant, Functor functor){
    if(opt_variant){
        if(auto* ptr = boost::get<T>(&*opt_variant)){
            functor(*ptr);
        }
    }
}

template<typename T, typename OptVariant, typename Functor>
void if_init_equals(OptVariant& opt_variant, T& cmp, Functor functor){
    if(opt_variant){
        if(auto* ptr = boost::get<T>(&*opt_variant)){
            if(*ptr == cmp){
                functor();
            }
        }
    }
}

template<typename T, typename OptVariant, typename Functor>
void if_init_not_equals(OptVariant& opt_variant, T& cmp, Functor functor){
    if(opt_variant){
        if(auto* ptr = boost::get<T>(&*opt_variant)){
            if(*ptr != cmp){
                functor(*ptr);
            }
        }
    }
}

bool is_single_int_register(std::shared_ptr<const Type> type);
bool is_single_float_register(std::shared_ptr<const Type> type);

unsigned int compute_member_offset(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> typer, const std::string& member);
std::pair<unsigned int, std::shared_ptr<const Type>> compute_member(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> type, const std::string& member);

void computeBlockUsage(mtac::Function& function, std::unordered_set<mtac::basic_block_p>& usage);

bool is_recursive(mtac::Function& function);

bool safe(const std::string& call);
bool erase_result(mtac::Operator op);

mtac::Quadruple copy(const mtac::Quadruple& statement);

} //end of mtac

} //end of eddic

#endif
<commit_msg>Document utility<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2013.
// 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 MTAC_UTILS_H
#define MTAC_UTILS_H

#include <memory>
#include <utility>
#include <unordered_set>
#include <unordered_map>

#include "variant.hpp"
#include "Type.hpp"
#include "VisitorUtils.hpp"

#include "mtac/Program.hpp"
#include "mtac/Operator.hpp"
#include "mtac/forward.hpp"

namespace eddic {

class Variable;
struct GlobalContext;

namespace mtac {

template<typename V, typename T>
inline bool equals(T& variant, V value){
    return boost::get<V>(&variant) && value == boost::get<V>(variant);
}

template<typename V, typename T>
inline bool is(T& variant){
    return boost::get<V>(&variant);
}

template<typename V, typename T>
inline bool optional_is(T& variant){
    return variant && boost::get<V>(&*variant);
}

template<typename T>
inline bool isInt(T variant){
    return boost::get<int>(&variant);
}

template<typename T>
inline bool isFloat(T& variant){
    return boost::get<double>(&variant);
}

template<typename T>
inline bool isVariable(T& variant){
    return boost::get<std::shared_ptr<Variable>>(&variant);
}

template<typename T>
inline void assertIntOrVariable(T& variant){
    assert(isInt(variant) || isVariable(variant));
}

template<typename Visitor>
void visit_all_statements(Visitor& visitor, mtac::Function& function){
    for(auto& block : function){
        visit_each(visitor, block->statements);
    }
}

/*!
 * \brief Execute the given functor if the given optional variant is initialized and of the given template type.
 * \param opt_variant The optional variant.
 * \param functor The functor to execute. Must have an operator()(T).
 * \tparam T The type that must be contained in the variant.
 * \tparam OptVariant The optional variant type.
 * \tparam Functor the type of the functor.
 */
template<typename T, typename OptVariant, typename Functor>
void if_init(OptVariant& opt_variant, Functor functor){
    if(opt_variant){
        if(auto* ptr = boost::get<T>(&*opt_variant)){
            functor(*ptr);
        }
    }
}

/*!
 * \brief Execute the given functor if the given optional variant is initialized and is equals to the given value.
 * \param opt_variant The optional variant.
 * \param cmp The object the variant must be equals to.
 * \param functor The functor to execute. Must have an operator()().
 * \tparam T The type that must be contained in the variant.
 * \tparam OptVariant The optional variant type.
 * \tparam Functor the type of the functor.
 */
template<typename T, typename OptVariant, typename Functor>
void if_init_equals(OptVariant& opt_variant, T& cmp, Functor functor){
    if(opt_variant){
        if(auto* ptr = boost::get<T>(&*opt_variant)){
            if(*ptr == cmp){
                functor();
            }
        }
    }
}

/*!
 * \brief Execute the given functor if the given optional variant is initialized and is not equals to the given value.
 * \param opt_variant The optional variant.
 * \param cmp The object the variant must be not equals to.
 * \param functor The functor to execute. Must have an operator()(T).
 * \tparam T The type that must be contained in the variant.
 * \tparam OptVariant The optional variant type.
 * \tparam Functor the type of the functor.
 */
template<typename T, typename OptVariant, typename Functor>
void if_init_not_equals(OptVariant& opt_variant, T& cmp, Functor functor){
    if(opt_variant){
        if(auto* ptr = boost::get<T>(&*opt_variant)){
            if(*ptr != cmp){
                functor(*ptr);
            }
        }
    }
}

bool is_single_int_register(std::shared_ptr<const Type> type);
bool is_single_float_register(std::shared_ptr<const Type> type);

unsigned int compute_member_offset(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> typer, const std::string& member);
std::pair<unsigned int, std::shared_ptr<const Type>> compute_member(std::shared_ptr<const GlobalContext> context, std::shared_ptr<const Type> type, const std::string& member);

void computeBlockUsage(mtac::Function& function, std::unordered_set<mtac::basic_block_p>& usage);

bool is_recursive(mtac::Function& function);

bool safe(const std::string& call);
bool erase_result(mtac::Operator op);

mtac::Quadruple copy(const mtac::Quadruple& statement);

} //end of mtac

} //end of eddic

#endif
<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * 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.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE
* COPYRIGHT OWNER 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.
****************************************************************************/

#ifndef INCLUDED_UTILS_HPP
#define INCLUDED_UTILS_HPP

#include <pdal/pdal_internal.hpp>

#include <string>
#include <cassert>
#include <stdexcept>
#include <cmath>
#include <ostream>
#include <istream>
#include <limits>
#include <cstring>
#include <sstream>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/numeric/conversion/cast.hpp>

namespace pdal
{

class PDAL_DLL Utils
{
public:
    static void random_seed(unsigned int seed);
    static double random(double minimum, double maximum);

    // compares two values to within the datatype's epsilon
    template<class T>
    static bool compare_distance(const T& actual, const T& expected)
    {
        const T epsilon = std::numeric_limits<T>::epsilon();
        return compare_approx<T>(actual, expected, epsilon);
    }

    // compares two values to within a given tolerance
    // the value |tolerance| is compared to |actual - expected|
    template<class T>
    static bool compare_approx(const T& actual, const T& expected, const T& tolerance)
    {
        const double diff = std::abs((double)actual - (double)expected);
        const double delta = std::abs((double)tolerance);

        if (diff > delta)
        {
            return false;
        }
        return true;
    }

    template<class T>
    static inline void write_field(boost::uint8_t*& dest, T v)
    {
        *(T*)(void*)dest = v;
        dest += sizeof(T);
        return;
    }

    template<class T>
    static inline T read_field(boost::uint8_t*& src)
    {
        T tmp = *(T*)(void*)src;
        src += sizeof(T);
        return tmp;
    }

    template<class T>
    static inline void read_array_field(boost::uint8_t*& src, T* dest, std::size_t count)
    {
        memcpy((boost::uint8_t*)dest, (boost::uint8_t*)(T*)src, sizeof(T)*count);
        src += sizeof(T) * count;
        return;
    }

    template <typename T>
    static inline void read_n(T& dest, std::istream& src, std::streamsize const& num)
    {
        if (!src.good())
            throw std::runtime_error("pdal::Utils::read_n<T> input stream is not readable");

        char* p = as_buffer(dest);
        src.read(p, num);

        assert(check_stream_state(src));
    }

    template <typename T>
    static inline void write_n(std::ostream& dest, T const& src, std::streamsize const& num)
    {
        if (!dest.good())
            throw std::runtime_error("pdal::Utils::write_n<T>: output stream is not writable");

        T& tmp = const_cast<T&>(src);

        char const* p = as_bytes(tmp);
        dest.rdbuf()->sputn(p, num);

        assert(check_stream_state(dest));
    }

    // From http://stackoverflow.com/questions/485525/round-for-float-in-c
    static inline double sround(double r)
    {
        return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
    }

    static inline std::vector<boost::uint8_t> hex_string_to_binary(std::string const& source)
    {
        // Stolen from http://stackoverflow.com/questions/7363774/c-converting-binary-data-to-a-hex-string-and-back
        static int nibbles[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15 };
        std::vector<unsigned char> retval;
        for (std::string::const_iterator it = source.begin(); it < source.end(); it += 2) {
            unsigned char v = 0;
            if (::isxdigit(*it))
                v = nibbles[::toupper(*it) - '0'] << 4;
            if (it + 1 < source.end() && ::isxdigit(*(it + 1)))
                v += nibbles[::toupper(*(it + 1)) - '0'];
            retval.push_back(v);
        }
        return retval;
    }

    static inline std::string binary_to_hex_string(const std::vector<unsigned char>& source)
    {
        static char syms[] = "0123456789ABCDEF";
        std::stringstream ss;
        for (std::vector<unsigned char>::const_iterator it = source.begin(); it != source.end(); it++)
            ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];

        return ss.str();
    }

    template<typename Target, typename Source>
    static inline Target saturation_cast(Source const& src)
    {

        try
        {
            return boost::numeric_cast<Target>(src);
        }
        catch (boost::numeric::negative_overflow const&)
        {
            return std::numeric_limits<Target>::min();
        }
        catch (boost::numeric::positive_overflow const&)
        {
            return std::numeric_limits<Target>::max();
        }

    }

    static void registerPlugin(void* stageFactoryPtr, std::string const& filename, std::string const& method);

    static char* getenv(const char* env);
    static std::string getenv(std::string const& name);
    static int putenv(const char* env);

    // aid to operator>> parsers
    static void eatwhitespace(std::istream& s);

    // aid to operator>> parsers
    // if char found, eats it and returns true; otherwise, don't eat it and then return false
    static bool eatcharacter(std::istream& s, char x);

    static boost::uint32_t getStreamPrecision(double scale);

    static boost::uint32_t safeconvert64to32(boost::uint64_t x64);

    // Generates a random temporary filename
    static std::string generate_filename();
    static std::string generate_tempfile();

    static void* getDLLSymbol(std::string const& library, std::string const& name);
    static std::string base64_encode(std::vector<boost::uint8_t> const& bytes);
    static std::vector<boost::uint8_t> base64_decode(std::string const& input);

    static FILE* portable_popen(const std::string& command, const std::string& mode);
    static int portable_pclose(FILE* fp);
    static int run_shell_command(const std::string& cmd, std::string& output);

    static std::string replaceAll(std::string result,
                                  const std::string& replaceWhat,
                                  const std::string& replaceWithWhat);

private:
    template<typename T>
    static inline char* as_buffer(T& data)
    {
        return static_cast<char*>(static_cast<void*>(&data));
    }

    template<typename T>
    static inline char* as_buffer(T* data)
    {
        return static_cast<char*>(static_cast<void*>(data));
    }

    template<typename T>
    static inline char const* as_bytes(T const& data)
    {
        return static_cast<char const*>(static_cast<void const*>(&data));
    }

    template<typename T>
    static inline char const* as_bytes(T const* data)
    {
        return static_cast<char const*>(static_cast<void const*>(data));
    }

    template <typename C, typename T>
    static inline bool check_stream_state(std::basic_ios<C, T>& srtm)
    {
        // Test stream state bits
        if (srtm.eof())
            throw std::out_of_range("end of file encountered");
        else if (srtm.fail())
            throw std::runtime_error("non-fatal I/O error occured");
        else if (srtm.bad())
            throw std::runtime_error("fatal I/O error occured");
        return true;
    }

};

} // namespace pdal

#endif
<commit_msg>add a binary_to_hex_stream method<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * 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.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "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 THE
* COPYRIGHT OWNER 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.
****************************************************************************/

#ifndef INCLUDED_UTILS_HPP
#define INCLUDED_UTILS_HPP

#include <pdal/pdal_internal.hpp>

#include <string>
#include <cassert>
#include <stdexcept>
#include <cmath>
#include <ostream>
#include <istream>
#include <limits>
#include <cstring>
#include <sstream>
#include <vector>

#include <boost/filesystem.hpp>
#include <boost/algorithm/string/erase.hpp>
#include <boost/numeric/conversion/cast.hpp>

namespace pdal
{

class PDAL_DLL Utils
{
public:
    static void random_seed(unsigned int seed);
    static double random(double minimum, double maximum);

    // compares two values to within the datatype's epsilon
    template<class T>
    static bool compare_distance(const T& actual, const T& expected)
    {
        const T epsilon = std::numeric_limits<T>::epsilon();
        return compare_approx<T>(actual, expected, epsilon);
    }

    // compares two values to within a given tolerance
    // the value |tolerance| is compared to |actual - expected|
    template<class T>
    static bool compare_approx(const T& actual, const T& expected, const T& tolerance)
    {
        const double diff = std::abs((double)actual - (double)expected);
        const double delta = std::abs((double)tolerance);

        if (diff > delta)
        {
            return false;
        }
        return true;
    }

    template<class T>
    static inline void write_field(boost::uint8_t*& dest, T v)
    {
        *(T*)(void*)dest = v;
        dest += sizeof(T);
        return;
    }

    template<class T>
    static inline T read_field(boost::uint8_t*& src)
    {
        T tmp = *(T*)(void*)src;
        src += sizeof(T);
        return tmp;
    }

    template<class T>
    static inline void read_array_field(boost::uint8_t*& src, T* dest, std::size_t count)
    {
        memcpy((boost::uint8_t*)dest, (boost::uint8_t*)(T*)src, sizeof(T)*count);
        src += sizeof(T) * count;
        return;
    }

    template <typename T>
    static inline void read_n(T& dest, std::istream& src, std::streamsize const& num)
    {
        if (!src.good())
            throw std::runtime_error("pdal::Utils::read_n<T> input stream is not readable");

        char* p = as_buffer(dest);
        src.read(p, num);

        assert(check_stream_state(src));
    }

    template <typename T>
    static inline void write_n(std::ostream& dest, T const& src, std::streamsize const& num)
    {
        if (!dest.good())
            throw std::runtime_error("pdal::Utils::write_n<T>: output stream is not writable");

        T& tmp = const_cast<T&>(src);

        char const* p = as_bytes(tmp);
        dest.rdbuf()->sputn(p, num);

        assert(check_stream_state(dest));
    }

    // From http://stackoverflow.com/questions/485525/round-for-float-in-c
    static inline double sround(double r)
    {
        return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);
    }

    static inline std::vector<boost::uint8_t> hex_string_to_binary(std::string const& source)
    {
        // Stolen from http://stackoverflow.com/questions/7363774/c-converting-binary-data-to-a-hex-string-and-back
        static int nibbles[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15 };
        std::vector<unsigned char> retval;
        for (std::string::const_iterator it = source.begin(); it < source.end(); it += 2) {
            unsigned char v = 0;
            if (::isxdigit(*it))
                v = nibbles[::toupper(*it) - '0'] << 4;
            if (it + 1 < source.end() && ::isxdigit(*(it + 1)))
                v += nibbles[::toupper(*(it + 1)) - '0'];
            retval.push_back(v);
        }
        return retval;
    }

    static inline void binary_to_hex_stream(unsigned char* source, std::ostream& destination, int start, int end )
    {
        static char syms[] = "0123456789ABCDEF";
        for (int i = start; i != end; i++)
            destination << syms[((source[i] >> 4) & 0xf)] << syms[source[i] & 0xf];

    }

    static inline std::string binary_to_hex_string(const std::vector<unsigned char>& source)
    {
        static char syms[] = "0123456789ABCDEF";
        std::stringstream ss;
        for (std::vector<unsigned char>::const_iterator it = source.begin(); it != source.end(); it++)
            ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];

        return ss.str();
    }

    template<typename Target, typename Source>
    static inline Target saturation_cast(Source const& src)
    {

        try
        {
            return boost::numeric_cast<Target>(src);
        }
        catch (boost::numeric::negative_overflow const&)
        {
            return std::numeric_limits<Target>::min();
        }
        catch (boost::numeric::positive_overflow const&)
        {
            return std::numeric_limits<Target>::max();
        }

    }

    static void registerPlugin(void* stageFactoryPtr, std::string const& filename, std::string const& method);

    static char* getenv(const char* env);
    static std::string getenv(std::string const& name);
    static int putenv(const char* env);

    // aid to operator>> parsers
    static void eatwhitespace(std::istream& s);

    // aid to operator>> parsers
    // if char found, eats it and returns true; otherwise, don't eat it and then return false
    static bool eatcharacter(std::istream& s, char x);

    static boost::uint32_t getStreamPrecision(double scale);

    static boost::uint32_t safeconvert64to32(boost::uint64_t x64);

    // Generates a random temporary filename
    static std::string generate_filename();
    static std::string generate_tempfile();

    static void* getDLLSymbol(std::string const& library, std::string const& name);
    static std::string base64_encode(std::vector<boost::uint8_t> const& bytes);
    static std::vector<boost::uint8_t> base64_decode(std::string const& input);

    static FILE* portable_popen(const std::string& command, const std::string& mode);
    static int portable_pclose(FILE* fp);
    static int run_shell_command(const std::string& cmd, std::string& output);

    static std::string replaceAll(std::string result,
                                  const std::string& replaceWhat,
                                  const std::string& replaceWithWhat);

private:
    template<typename T>
    static inline char* as_buffer(T& data)
    {
        return static_cast<char*>(static_cast<void*>(&data));
    }

    template<typename T>
    static inline char* as_buffer(T* data)
    {
        return static_cast<char*>(static_cast<void*>(data));
    }

    template<typename T>
    static inline char const* as_bytes(T const& data)
    {
        return static_cast<char const*>(static_cast<void const*>(&data));
    }

    template<typename T>
    static inline char const* as_bytes(T const* data)
    {
        return static_cast<char const*>(static_cast<void const*>(data));
    }

    template <typename C, typename T>
    static inline bool check_stream_state(std::basic_ios<C, T>& srtm)
    {
        // Test stream state bits
        if (srtm.eof())
            throw std::out_of_range("end of file encountered");
        else if (srtm.fail())
            throw std::runtime_error("non-fatal I/O error occured");
        else if (srtm.bad())
            throw std::runtime_error("fatal I/O error occured");
        return true;
    }

};

} // namespace pdal

#endif
<|endoftext|>