<commit_before>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	dbtransaction.cxx
 *
 *   DESCRIPTION
 *      implementation of the pqxx::dbtransaction class.
 *   pqxx::dbtransaction represents a real backend transaction
 *
 * Copyright (c) 2004-2005, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/compiler.h"

#include "pqxx/dbtransaction"

using namespace std;

pqxx::dbtransaction::dbtransaction(connection_base &C,
    const PGSTD::string &IsolationString,
    const PGSTD::string &NName,
    const PGSTD::string &CName) :
  transaction_base(C, NName, CName),
  m_StartCmd()
{
  if (IsolationString != isolation_traits<read_committed>::name())
    m_StartCmd = "SET TRANSACTION ISOLATION LEVEL " + IsolationString;
}

pqxx::dbtransaction::~dbtransaction()
{
}

void pqxx::dbtransaction::start_backend_transaction()
{
  DirectExec("BEGIN", 2);
  // TODO: Can't we pipeline this to eliminate roundtrip time?
  if (!m_StartCmd.empty()) DirectExec(m_StartCmd.c_str());
}

pqxx::result pqxx::dbtransaction::do_exec(const char Query[])
{
  try
  {
    return DirectExec(Query);
  }
  catch (const exception &)
  {
    try { abort(); } catch (const exception &) {}
    throw;
  }
}

<commit_msg>Use PGSTD, not std!<commit_after>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	dbtransaction.cxx
 *
 *   DESCRIPTION
 *      implementation of the pqxx::dbtransaction class.
 *   pqxx::dbtransaction represents a real backend transaction
 *
 * Copyright (c) 2004-2005, Jeroen T. Vermeulen <jtv@xs4all.nl>
 *
 * See COPYING for copyright license.  If you did not receive a file called
 * COPYING with this source code, please notify the distributor of this mistake,
 * or contact the author.
 *
 *-------------------------------------------------------------------------
 */
#include "pqxx/compiler.h"

#include "pqxx/dbtransaction"

using namespace PGSTD;

pqxx::dbtransaction::dbtransaction(connection_base &C,
    const PGSTD::string &IsolationString,
    const PGSTD::string &NName,
    const PGSTD::string &CName) :
  transaction_base(C, NName, CName),
  m_StartCmd()
{
  if (IsolationString != isolation_traits<read_committed>::name())
    m_StartCmd = "SET TRANSACTION ISOLATION LEVEL " + IsolationString;
}

pqxx::dbtransaction::~dbtransaction()
{
}

void pqxx::dbtransaction::start_backend_transaction()
{
  DirectExec("BEGIN", 2);
  // TODO: Can't we pipeline this to eliminate roundtrip time?
  if (!m_StartCmd.empty()) DirectExec(m_StartCmd.c_str());
}

pqxx::result pqxx::dbtransaction::do_exec(const char Query[])
{
  try
  {
    return DirectExec(Query);
  }
  catch (const exception &)
  {
    try { abort(); } catch (const exception &) {}
    throw;
  }
}

<|endoftext|>


<commit_before>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <iostream>
#include <qimessaging/object.hpp>
#include <boost/algorithm/string/predicate.hpp>

namespace qi {

  Object::Object()
    : _meta(new MetaObject())
  {
    advertiseMethod("__metaobject", this, &Object::metaObject);
  }

  Object::~Object() {
    delete _meta;
  }

  MetaObject &Object::metaObject() {
    return *_meta;
  }

  MetaMethod::MetaMethod()
    : _signature("")
    , _functor(0)
    , _idx(0)
  {
  }

  MetaMethod::MetaMethod(const std::string &sig, const qi::Functor *functor)
    : _signature(sig)
    , _functor(functor)
    , _idx(0)
  {
  }

  unsigned int Object::xAdvertiseMethod(const std::string& signature, const qi::Functor* functor) {
    MetaMethod mm(signature, functor);
    unsigned int idx = _meta->_methodsNumber++;
    mm._idx = idx;
    _meta->_methods.push_back(mm);
    _meta->_methodsNameToIdx[signature] = idx;
    qiLogVerbose("qi::Object") << "binding method:" << signature;
    return idx;
  }

  void Object::metaCall(unsigned int method, const FunctorParameters &in, qi::FunctorResult out)
  {
    if (method > _meta->_methods.size()) {
      std::stringstream ss;
      ss << "Can't find methodID: " << method;
      qi::Buffer     buf;
      qi::DataStream ds(buf);
      ds << ss.str();
      out.setError(buf);
      return;
    }
    MetaMethod *mm = &(_meta->_methods[method]);
    if (mm->_functor)
      mm->_functor->call(in, out);
  }

  bool Object::xMetaCall(const std::string &signature, const FunctorParameters &in, FunctorResult out)
  {
    int methodId = metaObject().methodId(signature);
    if (methodId < 0) {
      qiLogError("object") << "cant find method: " << signature;
      qi::Buffer     buf;
      qi::DataStream ds(buf);
      std::stringstream ss;
      ss << "Can't find method: " << signature << std::endl
         << "Canditate(s):" << std::endl;
      std::vector<qi::MetaMethod>           mml = metaObject().findMethod(qi::signatureSplit(signature)[1]);
      std::vector<qi::MetaMethod>::iterator it;

      for (it = mml.begin(); it != mml.end(); ++it) {
        qi::MetaMethod       &mm = *it;
        ss << "  " << mm.signature();
      }
      ds << ss.str();
      out.setError(buf);
      return false;
    }
    metaCall(methodId, in, out);
    return true;
  }

  qi::DataStream &operator<<(qi::DataStream &stream, const MetaMethod &meta) {
    stream << meta._signature;
    stream << meta._idx;
    return stream;
  }

  qi::DataStream &operator>>(qi::DataStream &stream, MetaMethod &meta) {
    stream >> meta._signature;
    stream >> meta._idx;
    return stream;
  }

  qi::DataStream &operator<<(qi::DataStream &stream, const MetaObject &meta) {
    stream << meta._methodsNameToIdx;
    stream << meta._methods;
    stream << meta._methodsNumber;
    return stream;
  }

  qi::DataStream &operator>>(qi::DataStream &stream, MetaObject &meta) {
    stream >> meta._methodsNameToIdx;
    stream >> meta._methods;
    stream >> meta._methodsNumber;
    return stream;
  }

  std::vector<qi::MetaMethod> MetaObject::findMethod(const std::string &name)
  {
    std::vector<qi::MetaMethod>           ret;
    std::vector<qi::MetaMethod>::iterator it;
    std::string cname(name);
    cname += "::";

    for (it = _methods.begin(); it != _methods.end(); ++it) {
      qi::MetaMethod &mm = *it;
      if (boost::starts_with(mm.signature(), cname))
        ret.push_back(mm);
    }
    return ret;
  }

};
<commit_msg>object: better log when a method is not found<commit_after>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <iostream>
#include <qimessaging/object.hpp>
#include <boost/algorithm/string/predicate.hpp>

namespace qi {

  Object::Object()
    : _meta(new MetaObject())
  {
    advertiseMethod("__metaobject", this, &Object::metaObject);
  }

  Object::~Object() {
    delete _meta;
  }

  MetaObject &Object::metaObject() {
    return *_meta;
  }

  MetaMethod::MetaMethod()
    : _signature("")
    , _functor(0)
    , _idx(0)
  {
  }

  MetaMethod::MetaMethod(const std::string &sig, const qi::Functor *functor)
    : _signature(sig)
    , _functor(functor)
    , _idx(0)
  {
  }

  unsigned int Object::xAdvertiseMethod(const std::string& signature, const qi::Functor* functor) {
    MetaMethod mm(signature, functor);
    unsigned int idx = _meta->_methodsNumber++;
    mm._idx = idx;
    _meta->_methods.push_back(mm);
    _meta->_methodsNameToIdx[signature] = idx;
    qiLogVerbose("qi::Object") << "binding method:" << signature;
    return idx;
  }

  void Object::metaCall(unsigned int method, const FunctorParameters &in, qi::FunctorResult out)
  {
    if (method > _meta->_methods.size()) {
      std::stringstream ss;
      ss << "Can't find methodID: " << method;
      qi::Buffer     buf;
      qi::DataStream ds(buf);
      ds << ss.str();
      out.setError(buf);
      return;
    }
    MetaMethod *mm = &(_meta->_methods[method]);
    if (mm->_functor)
      mm->_functor->call(in, out);
  }

  bool Object::xMetaCall(const std::string &signature, const FunctorParameters &in, FunctorResult out)
  {
    int methodId = metaObject().methodId(signature);
    if (methodId < 0) {
      qi::Buffer     buf;
      qi::DataStream ds(buf);
      std::stringstream ss;
      ss << "Can't find method: " << signature << std::endl
         << "  Candidate(s):" << std::endl;
      std::vector<qi::MetaMethod>           mml = metaObject().findMethod(qi::signatureSplit(signature)[1]);
      std::vector<qi::MetaMethod>::const_iterator it;

      for (it = mml.begin(); it != mml.end(); ++it) {
        const qi::MetaMethod       &mm = *it;
        ss << "  " << mm.signature();
      }
      qiLogError("object") << ss.str();
      ds << ss.str();
      out.setError(buf);
      return false;
    }
    metaCall(methodId, in, out);
    return true;
  }

  qi::DataStream &operator<<(qi::DataStream &stream, const MetaMethod &meta) {
    stream << meta._signature;
    stream << meta._idx;
    return stream;
  }

  qi::DataStream &operator>>(qi::DataStream &stream, MetaMethod &meta) {
    stream >> meta._signature;
    stream >> meta._idx;
    return stream;
  }

  qi::DataStream &operator<<(qi::DataStream &stream, const MetaObject &meta) {
    stream << meta._methodsNameToIdx;
    stream << meta._methods;
    stream << meta._methodsNumber;
    return stream;
  }

  qi::DataStream &operator>>(qi::DataStream &stream, MetaObject &meta) {
    stream >> meta._methodsNameToIdx;
    stream >> meta._methods;
    stream >> meta._methodsNumber;
    return stream;
  }

  std::vector<qi::MetaMethod> MetaObject::findMethod(const std::string &name)
  {
    std::vector<qi::MetaMethod>           ret;
    std::vector<qi::MetaMethod>::iterator it;
    std::string cname(name);
    cname += "::";

    for (it = _methods.begin(); it != _methods.end(); ++it) {
      qi::MetaMethod &mm = *it;
      if (boost::starts_with(mm.signature(), cname))
        ret.push_back(mm);
    }
    return ret;
  }

};
<|endoftext|>


<commit_before>/*
 PCA9539 GPIO Expander Library
 By: OpenROV
 Date: September 14, 2016
*/

#include <Arduino.h>
#include <CI2C.h>

#include "PCA9539.h"

using namespace pca9539;

PCA9539::PCA9539( CI2C* i2cInterfaceIn )
    : m_i2cAddress( pca9539::PCA9539_ADDRESS )
    , m_pI2C( i2cInterfaceIn )
    , m_gpioDirection( 0xFF ) //All inputs
    , m_gpioState( 0x00 ) //All low
{

}

ERetCode PCA9539::Initialize()
{
    Serial.println( "PCA9539.status: INIT" );

    m_gpioDirection = 0x00; //All outputs

    uint8_t value;
    //Read it
    auto ret = ReadByte( PCA9539_REGISTER::CONFIG, value );
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }
    Serial.println(value, HEX);

    //Write it
    ret = WriteByte( PCA9539_REGISTER::CONFIG, m_gpioDirection);
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }

    //Read it
    ret = ReadByte( PCA9539_REGISTER::CONFIG, value );
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }
    Serial.println(value, HEX);

    m_gpioState |= (1 << 5);

    //Write it
    ret = WriteByte( PCA9539_REGISTER::OUTPUT, m_gpioState);
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }

    return ERetCode::SUCCESS;
}
value == HIGH ? _gpioState |= (1 << pin) : _gpioState &= ~(1 << pin);

if(HIGH)
{
    value = _gpioState |= (1 << pin);
}
else
{
    _gpioState &= ~(1 << pin)
}

/***************************************************************************
    PRIVATE FUNCTIONS
 ***************************************************************************/
int32_t PCA9539::WriteByte( PCA9539_REGISTER addressIn, uint8_t dataIn )
{
	return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );
}

int32_t PCA9539::ReadByte( PCA9539_REGISTER addressIn, uint8_t &dataOut )
{
	return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );
}
int32_t PCA9539::ReadNBytes( PCA9539_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )
{
    return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );
}

<commit_msg>Huge typo<commit_after>/*
 PCA9539 GPIO Expander Library
 By: OpenROV
 Date: September 14, 2016
*/

#include <Arduino.h>
#include <CI2C.h>

#include "PCA9539.h"

using namespace pca9539;

PCA9539::PCA9539( CI2C* i2cInterfaceIn )
    : m_i2cAddress( pca9539::PCA9539_ADDRESS )
    , m_pI2C( i2cInterfaceIn )
    , m_gpioDirection( 0xFF ) //All inputs
    , m_gpioState( 0x00 ) //All low
{

}

ERetCode PCA9539::Initialize()
{
    Serial.println( "PCA9539.status: INIT" );

    m_gpioDirection = 0x00; //All outputs

    uint8_t value;
    //Read it
    auto ret = ReadByte( PCA9539_REGISTER::CONFIG, value );
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }
    Serial.println(value, HEX);

    //Write it
    ret = WriteByte( PCA9539_REGISTER::CONFIG, m_gpioDirection);
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }

    //Read it
    ret = ReadByte( PCA9539_REGISTER::CONFIG, value );
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }
    Serial.println(value, HEX);

    m_gpioState |= (1 << 5);

    //Write it
    ret = WriteByte( PCA9539_REGISTER::OUTPUT, m_gpioState);
    if( ret != I2C::ERetCode::SUCCESS )
    {
        return ERetCode::FAILED;
    }

    return ERetCode::SUCCESS;
}
// value == HIGH ? _gpioState |= (1 << pin) : _gpioState &= ~(1 << pin);

// if(HIGH)
// {
//     value = _gpioState |= (1 << pin);
// }
// else
// {
//     _gpioState &= ~(1 << pin)
// }

/***************************************************************************
    PRIVATE FUNCTIONS
 ***************************************************************************/
int32_t PCA9539::WriteByte( PCA9539_REGISTER addressIn, uint8_t dataIn )
{
	return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn );
}

int32_t PCA9539::ReadByte( PCA9539_REGISTER addressIn, uint8_t &dataOut )
{
	return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut );
}
int32_t PCA9539::ReadNBytes( PCA9539_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn )
{
    return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn );
}

<|endoftext|>


<commit_before>/**
 * ExperimentPackager.cpp
 *
 * History:
 * paul on 1/25/06 - Created.
 *
 * Copyright 2006 MIT. All rights reserved.
 */

#include "ExperimentPackager.h"
#include "Utilities.h"
#include "LoadingUtilities.h"
#include "SystemEventFactory.h"
#include <iostream>
#include <fstream>

#include "PlatformDependentServices.h"
#include "boost/filesystem/path.hpp"
#include "boost/algorithm/string/replace.hpp"
#include <boost/scope_exit.hpp>

BEGIN_NAMESPACE_MW

Datum ExperimentPackager::packageSingleFile(const Datum &contents, const std::string &filename) {
    Datum unit(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS_PER_UNIT);

    Datum name;
	name.setString(filename.c_str(), filename.length()+1);
	unit.addElement(M_PACKAGER_FILENAME_STRING, name);

	unit.addElement(M_PACKAGER_CONTENTS_STRING, contents);

	return unit;
}

Datum
ExperimentPackager::packageSingleFile(const boost::filesystem::path filepath, const std::string filename) {
	namespace bf = boost::filesystem;

	std::ifstream mediaFile;
	mediaFile.open(filepath.string().c_str(), std::ios::binary);

	// get length of file:
	mediaFile.seekg(0, std::ios::end);
	int length = mediaFile.tellg();
	// if the file was never opened
	if(length <= 0) {
		mediaFile.close();
        Datum undef;
		return undef;
	}

	char * buffer = new char[length];

	mediaFile.seekg(0, std::ios::beg);
	mediaFile.read(buffer, length);
	mediaFile.close();

    Datum bufferData;
	bufferData.setString(buffer, length);

	delete [] buffer;

	return packageSingleFile(bufferData, filename);
}

Datum ExperimentPackager::packageExperiment(const boost::filesystem::path filename) {
	namespace bf = boost::filesystem;
	IncludedFilesParser parser(filename.string());
	std::string working_path_string;
    Datum include_files;

	try{
		parser.parse(false);
		working_path_string = parser.getWorkingPathString();
		include_files = parser.getIncludedFilesManifest();
	} catch(std::exception& e){
		merror(M_PARSER_MESSAGE_DOMAIN, "Experiment packaging failed: %s",
										e.what());
		return Datum();
	}

    Datum eventPayload(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS);

    {
        // Use getDocumentData to get the experiment file with any preprocessing and/or
        // XInclude substitutions already applied
        std::vector<xmlChar> fileData;
        parser.getDocumentData(fileData);

        Datum contents(reinterpret_cast<char *>(&(fileData.front())), fileData.size());
        eventPayload.addElement(M_PACKAGER_EXPERIMENT_STRING,
                                packageSingleFile(contents, XMLParser::squashFileName(filename.string())));
    }

	if(include_files.getNElements() >= 1) {
        Datum mediaFilesPayload(M_LIST, include_files.getNElements());

		for(int i=0; i< include_files.getNElements();  ++i) {

			// DDC there seem to be a lot of unnecessary steps here
			// simplified hackily for the moment
			std::string mediaName(include_files.getElement(i).getString());

			bf::path mediaPath = expandPath(working_path_string, mediaName);

			//bf::path mediaPath(include_files.getElement(i).getElement(M_PACKAGER_FULL_NAME).getString());
			//std::string mediaName(include_files.getElement(i).getElement(M_PACKAGER_RELATIVE_NAME).getString());
            Datum mediaElement = packageSingleFile(mediaPath, mediaName);

			if(!mediaElement.isUndefined()) {
				mediaFilesPayload.addElement(mediaElement);
			} else {
				merror(M_FILE_MESSAGE_DOMAIN,
					   "Can't find file: %s", mediaPath.string().c_str());
                Datum undef;
				return undef;
			}
		}

		eventPayload.addElement(M_PACKAGER_MEDIA_BUFFERS_STRING,
								mediaFilesPayload);
    }

	return SystemEventFactory::systemEventPackage(M_SYSTEM_DATA_PACKAGE,
											 M_EXPERIMENT_PACKAGE,
											 eventPayload);
}

IncludedFilesParser::IncludedFilesParser(const std::string &_path) :
    XMLParser(_path, "MWMediaPackagerTransformation.xsl"),
    manifest(M_LIST, 1)
{ }

void IncludedFilesParser::parse(bool announce_progress) {
    // Load the experiment file, applying any preprocessing and/or XInclude substitutions
    loadFile();

    // Look for resource declarations
    auto xpathObject = evaluateXPathExpression("//resource/@path[string-length() != 0]");
    if (xpathObject) {
        BOOST_SCOPE_EXIT( xpathObject ) {
            xmlXPathFreeObject(xpathObject);
        } BOOST_SCOPE_EXIT_END

        if (xpathObject->type == XPATH_NODESET && xpathObject->nodesetval && xpathObject->nodesetval->nodeNr > 0) {
            // Found one or more resource declarations, so add the identified files and directories to
            // the manifest
            for (int nodeIndex = 0; nodeIndex < xpathObject->nodesetval->nodeNr; nodeIndex++) {
                auto path = _getContent(xpathObject->nodesetval->nodeTab[nodeIndex]);
                if (boost::filesystem::is_directory(expandPath(getWorkingPathString(), path))) {
                    addDirectory(path, true);  // Recursive
                } else {
                    manifest.addElement(path);
                }
            }
            // Return without parsing the file.  This allows experiments that declare resources to use
            // run-time expressions in "path" and other attributes that would otherwise need to be
            // evaluated at parse time.
            return;
        }
    }

    // No resource declarations found, so parse the experiment (expanding any replicators), and
    // infer the included files from component attributes
    XMLParser::parse(announce_progress);
}

void IncludedFilesParser::addDirectory(const std::string &directoryPath, bool recursive) {
    std::vector<std::string> filePaths;
    mw::getFilePaths(getWorkingPathString(), directoryPath, filePaths, recursive);
    for (const auto &path : filePaths) {
        manifest.addElement(path);
    }
}

void IncludedFilesParser::_processCreateDirective(xmlNode *node) {
    xmlNode *child = node->children;

    while (child != NULL) {
        string name((const char *)(child->name));

        if (name == "path") {

            string filePath = _getContent(child);
            manifest.addElement(filePath);

        } else if (name == "directory_path") {

            string directoryPath = _getContent(child);
            addDirectory(directoryPath, false);  // Not recursive

        }

        child = child->next;
    }
}

void IncludedFilesParser::_processAnonymousCreateDirective(xmlNode *node) {
    _processCreateDirective(node);
}

END_NAMESPACE_MW

<commit_msg>In ExperimentPackager::packageSingleFile, don't reject empty files<commit_after>/**
 * ExperimentPackager.cpp
 *
 * History:
 * paul on 1/25/06 - Created.
 *
 * Copyright 2006 MIT. All rights reserved.
 */

#include "ExperimentPackager.h"
#include "Utilities.h"
#include "LoadingUtilities.h"
#include "SystemEventFactory.h"
#include <iostream>
#include <fstream>

#include "PlatformDependentServices.h"
#include "boost/filesystem/path.hpp"
#include "boost/algorithm/string/replace.hpp"
#include <boost/scope_exit.hpp>

BEGIN_NAMESPACE_MW

Datum ExperimentPackager::packageSingleFile(const Datum &contents, const std::string &filename) {
    Datum unit(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS_PER_UNIT);

    Datum name;
	name.setString(filename.c_str(), filename.length()+1);
	unit.addElement(M_PACKAGER_FILENAME_STRING, name);

	unit.addElement(M_PACKAGER_CONTENTS_STRING, contents);

	return unit;
}

Datum
ExperimentPackager::packageSingleFile(const boost::filesystem::path filepath, const std::string filename) {
	namespace bf = boost::filesystem;

	std::ifstream mediaFile;
	mediaFile.open(filepath.string().c_str(), std::ios::binary);

	// get length of file:
	mediaFile.seekg(0, std::ios::end);
	int length = mediaFile.tellg();
	// if the file was never opened
	if (length < 0) {
		mediaFile.close();
        Datum undef;
		return undef;
	}

	char * buffer = new char[length];

	mediaFile.seekg(0, std::ios::beg);
	mediaFile.read(buffer, length);
	mediaFile.close();

    Datum bufferData;
	bufferData.setString(buffer, length);

	delete [] buffer;

	return packageSingleFile(bufferData, filename);
}

Datum ExperimentPackager::packageExperiment(const boost::filesystem::path filename) {
	namespace bf = boost::filesystem;
	IncludedFilesParser parser(filename.string());
	std::string working_path_string;
    Datum include_files;

	try{
		parser.parse(false);
		working_path_string = parser.getWorkingPathString();
		include_files = parser.getIncludedFilesManifest();
	} catch(std::exception& e){
		merror(M_PARSER_MESSAGE_DOMAIN, "Experiment packaging failed: %s",
										e.what());
		return Datum();
	}

    Datum eventPayload(M_DICTIONARY, M_EXPERIMENT_PACKAGE_NUMBER_ELEMENTS);

    {
        // Use getDocumentData to get the experiment file with any preprocessing and/or
        // XInclude substitutions already applied
        std::vector<xmlChar> fileData;
        parser.getDocumentData(fileData);

        Datum contents(reinterpret_cast<char *>(&(fileData.front())), fileData.size());
        eventPayload.addElement(M_PACKAGER_EXPERIMENT_STRING,
                                packageSingleFile(contents, XMLParser::squashFileName(filename.string())));
    }

	if(include_files.getNElements() >= 1) {
        Datum mediaFilesPayload(M_LIST, include_files.getNElements());

		for(int i=0; i< include_files.getNElements();  ++i) {

			// DDC there seem to be a lot of unnecessary steps here
			// simplified hackily for the moment
			std::string mediaName(include_files.getElement(i).getString());

			bf::path mediaPath = expandPath(working_path_string, mediaName);

			//bf::path mediaPath(include_files.getElement(i).getElement(M_PACKAGER_FULL_NAME).getString());
			//std::string mediaName(include_files.getElement(i).getElement(M_PACKAGER_RELATIVE_NAME).getString());
            Datum mediaElement = packageSingleFile(mediaPath, mediaName);

			if(!mediaElement.isUndefined()) {
				mediaFilesPayload.addElement(mediaElement);
			} else {
				merror(M_FILE_MESSAGE_DOMAIN,
					   "Can't find file: %s", mediaPath.string().c_str());
                Datum undef;
				return undef;
			}
		}

		eventPayload.addElement(M_PACKAGER_MEDIA_BUFFERS_STRING,
								mediaFilesPayload);
    }

	return SystemEventFactory::systemEventPackage(M_SYSTEM_DATA_PACKAGE,
											 M_EXPERIMENT_PACKAGE,
											 eventPayload);
}

IncludedFilesParser::IncludedFilesParser(const std::string &_path) :
    XMLParser(_path, "MWMediaPackagerTransformation.xsl"),
    manifest(M_LIST, 1)
{ }

void IncludedFilesParser::parse(bool announce_progress) {
    // Load the experiment file, applying any preprocessing and/or XInclude substitutions
    loadFile();

    // Look for resource declarations
    auto xpathObject = evaluateXPathExpression("//resource/@path[string-length() != 0]");
    if (xpathObject) {
        BOOST_SCOPE_EXIT( xpathObject ) {
            xmlXPathFreeObject(xpathObject);
        } BOOST_SCOPE_EXIT_END

        if (xpathObject->type == XPATH_NODESET && xpathObject->nodesetval && xpathObject->nodesetval->nodeNr > 0) {
            // Found one or more resource declarations, so add the identified files and directories to
            // the manifest
            for (int nodeIndex = 0; nodeIndex < xpathObject->nodesetval->nodeNr; nodeIndex++) {
                auto path = _getContent(xpathObject->nodesetval->nodeTab[nodeIndex]);
                if (boost::filesystem::is_directory(expandPath(getWorkingPathString(), path))) {
                    addDirectory(path, true);  // Recursive
                } else {
                    manifest.addElement(path);
                }
            }
            // Return without parsing the file.  This allows experiments that declare resources to use
            // run-time expressions in "path" and other attributes that would otherwise need to be
            // evaluated at parse time.
            return;
        }
    }

    // No resource declarations found, so parse the experiment (expanding any replicators), and
    // infer the included files from component attributes
    XMLParser::parse(announce_progress);
}

void IncludedFilesParser::addDirectory(const std::string &directoryPath, bool recursive) {
    std::vector<std::string> filePaths;
    mw::getFilePaths(getWorkingPathString(), directoryPath, filePaths, recursive);
    for (const auto &path : filePaths) {
        manifest.addElement(path);
    }
}

void IncludedFilesParser::_processCreateDirective(xmlNode *node) {
    xmlNode *child = node->children;

    while (child != NULL) {
        string name((const char *)(child->name));

        if (name == "path") {

            string filePath = _getContent(child);
            manifest.addElement(filePath);

        } else if (name == "directory_path") {

            string directoryPath = _getContent(child);
            addDirectory(directoryPath, false);  // Not recursive

        }

        child = child->next;
    }
}

void IncludedFilesParser::_processAnonymousCreateDirective(xmlNode *node) {
    _processCreateDirective(node);
}

END_NAMESPACE_MW

<|endoftext|>


<commit_before>/*
 * By: ulises-jeremias
 * From: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3146
 * Name: I Can Guess the Data Structure!
 * Date: 08/09/2017
 */

#include <iostream>
#include <queue>
#include <stack>

using namespace std;

int main(int argc, char const *argv[]) {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);

        int n, i, op, v;
        stack<int> stk;
        queue<int> q;
        priority_queue<int> pq;
        bool is_stack, is_queue, is_priority_queue;

        while (cin >> n) {
                while (stk.size()) stk.pop();
                while (q.size()) q.pop();
                while (pq.size()) pq.pop();
                is_stack = is_queue = is_priority_queue = true;

                for (i = 0; i < n; i++) {
                        cin >> op >> v;

                        if (op == 1) {
                                stk.push(v);
                                q.push(v);
                                pq.push(v);
                        } else {
                                if (stk.size() == 0) {
                                        is_stack = is_queue = is_priority_queue = false;
                                } else {
                                        if (stk.top() != v) is_stack = false;
                                        stk.pop();
                                        if (q.front() != v) is_queue = false;
                                        q.pop();
                                        if (pq.top() != v) is_priority_queue = false;
                                        pq.pop();
                                }
                        }
                }
        }

        return 0;
}
<commit_msg>ICanGuesstheDataStructure! solved<commit_after>/*
 * By: ulises-jeremias
 * From: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3146
 * Name: I Can Guess the Data Structure!
 * Date: 08/09/2017
 */

#include <iostream>
#include <queue>
#include <stack>

using namespace std;

int main(int argc, char const *argv[]) {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);

        int n, i, op, v;
        stack<int> stk;
        queue<int> q;
        priority_queue<int> pq;
        bool is_stack, is_queue, is_priority_queue;

        while (cin >> n) {
                while (stk.size()) stk.pop();
                while (q.size()) q.pop();
                while (pq.size()) pq.pop();
                is_stack = is_queue = is_priority_queue = true;

                for (i = 0; i < n; i++) {
                        cin >> op >> v;

                        if (op == 1) {
                                stk.push(v);
                                q.push(v);
                                pq.push(v);
                        } else {
                                if (stk.size() == 0) {
                                        is_stack = is_queue = is_priority_queue = false;
                                } else {
                                        if (stk.top() != v) is_stack = false;
                                        stk.pop();
                                        if (q.front() != v) is_queue = false;
                                        q.pop();
                                        if (pq.top() != v) is_priority_queue = false;
                                        pq.pop();
                                }
                        }
                }

                if (!is_stack && !is_queue && !is_priority_queue) {
                        cout<<"impossible\n";
                } else if ((is_stack && is_queue) || (is_stack && is_priority_queue) || (is_queue && is_priority_queue)) {
                        cout<<"not sure\n";
                } else if (is_stack) {
                        cout<<"stack\n";
                } else if (is_queue) {
                        cout<<"queue\n";
                } else {
                        cout<<"priority queue\n";
                }
        }

        return 0;
}
<|endoftext|>


<commit_before><commit_msg>[DF][Doc][NFC] Small fixes to DF docs<commit_after><|endoftext|>


<commit_before>/*
 * tut_xml_reporter.hpp
 *
 * ECOS Library. IPT CS R&D CET ECOS Copyright 2008 Nokia
 * Siemens Networks. All right
 *
 *
 */

#ifndef TUT_XML_REPORTER
#define TUT_XML_REPORTER

#include <tut/tut.hpp>
#include <string>
#include <fstream>
#include <vector>
#include <stdexcept>

namespace tut
{

/**
 * \brief JUnit XML TUT reporter
 * @author Lukasz Maszczynski, NSN
 * @date 11/07/2008
 */
class xml_reporter : public tut::callback
{
protected:
    typedef std::vector<tut::test_result> TestResults;
    typedef std::map<std::string, TestResults> TestGroups;

    TestGroups all_tests; /// holds all test results
    std::string filename; /// filename base

    /**
     * \brief Initializes object
     * Resets counters and clears all stored test results.
     */
    virtual void init()
    {
        ok_count = 0;
        exceptions_count = 0;
        failures_count = 0;
        terminations_count = 0;
        warnings_count = 0;
        all_tests.clear();
    }

    /**
     * \brief Encodes text to XML
     * XML-reserved characters (e.g. "<") are encoded according to specification
     * @param text text to be encoded
     * @return encoded string
     */
    virtual std::string encode(const std::string & text)
    {
        std::string out;

        for (unsigned int i=0; i<text.length(); ++i) {
            char c = text[i];
            switch (c) {
                case '<':
                    out += "<";
                    break;
                case '>':
                    out += ">";
                    break;
                case '&':
                    out += "&";
                    break;
                case '\'':
                    out += "'";
                    break;
                case '"':
                    out += """;
                    break;
                default:
                    out += c;
            }
        }

        return out;
    }

    /**
     * \brief Builds "testcase" XML entity with given parameters
     * Builds \<testcase\> entity according to given parameters. \<testcase\>-s are part of \<testsuite\>.
     * @param tr test result to be used as source data
     * @param failure_type type of failure to be reported ("Assertion" or "Error", empty if test passed)
     * @param failure_msg failure message to be reported (empty, if test passed)
     * @return string with \<testcase\> entity
     */
    virtual std::string xml_build_testcase(const tut::test_result & tr, const std::string & failure_type,
                                           const std::string & failure_msg, int pid = 0)
    {
        using std::endl;
        using std::string;

        std::ostringstream out;

        if (tr.result == test_result::ok)
        {
            out << "  <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\" />";
        }
        else
        {
            string err_msg = encode(failure_msg + tr.message);

            string tag; // determines tag name: "failure" or "error"
            if ( tr.result == test_result::fail || tr.result == test_result::warn ||
                 tr.result == test_result::ex || tr.result == test_result::ex_ctor )
            {
                tag = "failure";
            }
            else
            {
                tag = "error";
            }

            out << "  <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\">" << endl;
            out << "    <" << tag << " message=\"" << err_msg << "\"" << " type=\"" << failure_type << "\"";
#if defined(TUT_USE_POSIX)
            if(pid != getpid())
            {
                out << " child=\"" << pid << "\"";
            }
#endif
            out << ">" << err_msg << "</" << tag << ">" << endl;
            out << "  </testcase>";
        }

        return out.str();
    }

    /**
     * \brief Builds "testsuite" XML entity
     * Builds \<testsuite\> XML entity according to given parameters.
     * @param errors number of errors to be reported
     * @param failures number of failures to be reported
     * @param total total number of tests to be reported
     * @param name test suite name
     * @param testcases encoded XML string containing testcases
     * @return string with \<testsuite\> entity
     */
    virtual std::string xml_build_testsuite(int errors, int failures, int total,
                                            const std::string & name, const std::string & testcases)
    {
        std::ostringstream out;

        out << "<testsuite errors=\"" << errors << "\" failures=\"" << failures << "\" tests=\"" << total << "\" name=\"" << encode(name) << "\">" << std::endl;
        out << testcases;
        out << "</testsuite>";

        return out.str();
    }

public:
    int ok_count;           /// number of passed tests
    int exceptions_count;   /// number of tests that threw exceptions
    int failures_count;     /// number of tests that failed
    int terminations_count; /// number of tests that would terminate
    int warnings_count;     /// number of tests where destructors threw an exception

    /**
     * \brief Default constructor
     * @param filename base filename
     * @see setFilenameBase
     */
    xml_reporter(const std::string & _filename = "")
    {
        init();
        setFilenameBase(_filename);
    }

    /**
     * \brief Sets filename base for output
     * @param _filename filename base
     * Example usage:
     * @code
     * xml_reporter reporter;
     * reporter.setFilenameBase("my_xml");
     * @endcode
     * The above code will instruct reporter to create my_xml_1.xml file for the first test group,
     * my_xml_2.xml file for the second, and so on.
     */
    virtual void setFilenameBase(const std::string & _filename)
    {
        if (_filename == "")
        {
            filename = "testResult";
        }
        else
        {
            if (_filename.length() > 200)
            {
                throw(std::runtime_error("Filename too long!"));
            }

            filename = _filename;
        }
    }

    /**
     * \brief Callback function
     * This function is called before the first test is executed. It initializes counters.
     */
    virtual void run_started()
    {
        init();
    }

    /**
     * \brief Callback function
     * This function is called when test completes. Counters are updated here, and test results stored.
     */
    virtual void test_completed(const tut::test_result& tr)
    {
        // update global statistics
        switch (tr.result) {
            case test_result::ok:
                ok_count++;
                break;
            case test_result::fail:
            case test_result::rethrown:
                failures_count++;
                break;
            case test_result::ex:
            case test_result::ex_ctor:
                exceptions_count++;
                break;
            case test_result::warn:
                warnings_count++;
                break;
            case test_result::term:
                terminations_count++;
                break;
        } // switch

        // add test result to results table
        (all_tests[tr.group]).push_back(tr);
    }

    /**
     * \brief Callback function
     * This function is called when all tests are completed. It generates XML output
     * to file(s). File name base can be set with \ref setFilenameBase.
     */
    virtual void run_completed()
    {
        using std::endl;
        using std::string;

        static int number = 1;  // results file sequence number (testResult_<number>.xml)

        // iterate over all test groups
        TestGroups::const_iterator tgi;
        for (tgi = all_tests.begin(); tgi != all_tests.end(); ++tgi) {
            /* per-group statistics */
            int passed = 0;         // passed in single group
            int exceptions = 0;     // exceptions in single group
            int failures = 0;       // failures in single group
            int terminations = 0;   // terminations in single group
            int warnings = 0;       // warnings in single group
            int errors = 0;     // errors in single group

            /* generate output filename */
            char fn[256];
            sprintf(fn, "%s_%d.xml", filename.c_str(), number++);

            std::ofstream xmlfile;
            xmlfile.open(fn, std::ios::in | std::ios::trunc);
            if (!xmlfile.is_open()) {
                throw (std::runtime_error("Cannot open file for output"));
            }

            /* *********************** header ***************************** */
            xmlfile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;

            // output is written to string stream buffer, because JUnit format <testsuite> tag
            // contains statistics, which aren't known yet
            std::ostringstream out;

            // iterate over all test cases in the current test group
            TestResults::const_iterator tri;
            for (tri = (*tgi).second.begin(); tri != (*tgi).second.end(); ++tri) {
                string failure_type;    // string describing the failure type
                string failure_msg;     // a string with failure message

                switch ((*tri).result) {
                    case test_result::ok:
                        passed++;
                        break;
                    case test_result::fail:
                        failure_type = "Assertion";
                        failure_msg  = "";
                        failures++;
                        break;
                    case test_result::ex:
                        failure_type = "Assertion";
                        failure_msg  = "Thrown exception: " + (*tri).exception_typeid + '\n';
                        exceptions++;
                        break;
                    case test_result::warn:
                        failure_type = "Assertion";
                        failure_msg  = "Destructor failed.\n";
                        warnings++;
                        break;
                    case test_result::term:
                        failure_type = "Error";
                        failure_msg  = "Test application terminated abnormally.\n";
                        terminations++;
                        break;
                    case test_result::ex_ctor:
                        failure_type = "Assertion";
                        failure_msg  = "Constructor has thrown an exception: " + (*tri).exception_typeid + '\n';
                        exceptions++;
                        break;
                    case test_result::rethrown:
                        failure_type = "Assertion";
                        failure_msg  = "Child failed";
                        failures++;
                        break;
                    default:
                        failure_type = "Error";
                        failure_msg  = "Unknown test status, this should have never happened. "
                                "You may just have found a BUG in TUT XML reporter, please report it immediately.\n";
                        errors++;
                        break;
                } // switch

#if defined(TUT_USE_POSIX)
                out << xml_build_testcase(*tri, failure_type, failure_msg, (*tri).pid) << endl;
#else
                out << xml_build_testcase(*tri, failure_type, failure_msg) << endl;
#endif

            } // iterate over all test cases

            // calculate per-group statistics
            int stat_errors = terminations + errors;
            int stat_failures = failures + warnings + exceptions;
            int stat_all = stat_errors + stat_failures + passed;

            xmlfile << xml_build_testsuite(stat_errors, stat_failures, stat_all, (*tgi).first/* name */, out.str()/* testcases */) << endl;
            xmlfile.close();
        } // iterate over all test groups
    }

    /**
     * \brief Returns true, if all tests passed
     */
    virtual bool all_ok() const
    {
        return ( (terminations_count + failures_count + warnings_count + exceptions_count) == 0);
    };
};

}

#endif
<commit_msg>Added tr::dummy to xml_reporter (thanks ninh@phusion.nl)<commit_after>/*
 * tut_xml_reporter.hpp
 *
 * ECOS Library. IPT CS R&D CET ECOS Copyright 2008 Nokia
 * Siemens Networks. All right
 *
 *
 */

#ifndef TUT_XML_REPORTER
#define TUT_XML_REPORTER

#include <tut/tut.hpp>
#include <string>
#include <fstream>
#include <vector>
#include <stdexcept>

namespace tut
{

/**
 * \brief JUnit XML TUT reporter
 * @author Lukasz Maszczynski, NSN
 * @date 11/07/2008
 */
class xml_reporter : public tut::callback
{
protected:
    typedef std::vector<tut::test_result> TestResults;
    typedef std::map<std::string, TestResults> TestGroups;

    TestGroups all_tests; /// holds all test results
    std::string filename; /// filename base

    /**
     * \brief Initializes object
     * Resets counters and clears all stored test results.
     */
    virtual void init()
    {
        ok_count = 0;
        exceptions_count = 0;
        failures_count = 0;
        terminations_count = 0;
        warnings_count = 0;
        all_tests.clear();
    }

    /**
     * \brief Encodes text to XML
     * XML-reserved characters (e.g. "<") are encoded according to specification
     * @param text text to be encoded
     * @return encoded string
     */
    virtual std::string encode(const std::string & text)
    {
        std::string out;

        for (unsigned int i=0; i<text.length(); ++i) {
            char c = text[i];
            switch (c) {
                case '<':
                    out += "<";
                    break;
                case '>':
                    out += ">";
                    break;
                case '&':
                    out += "&";
                    break;
                case '\'':
                    out += "'";
                    break;
                case '"':
                    out += """;
                    break;
                default:
                    out += c;
            }
        }

        return out;
    }

    /**
     * \brief Builds "testcase" XML entity with given parameters
     * Builds \<testcase\> entity according to given parameters. \<testcase\>-s are part of \<testsuite\>.
     * @param tr test result to be used as source data
     * @param failure_type type of failure to be reported ("Assertion" or "Error", empty if test passed)
     * @param failure_msg failure message to be reported (empty, if test passed)
     * @return string with \<testcase\> entity
     */
    virtual std::string xml_build_testcase(const tut::test_result & tr, const std::string & failure_type,
                                           const std::string & failure_msg, int pid = 0)
    {
        using std::endl;
        using std::string;

        std::ostringstream out;

        if (tr.result == test_result::ok)
        {
            out << "  <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\" />";
        }
        else
        {
            string err_msg = encode(failure_msg + tr.message);

            string tag; // determines tag name: "failure" or "error"
            if ( tr.result == test_result::fail || tr.result == test_result::warn ||
                 tr.result == test_result::ex || tr.result == test_result::ex_ctor )
            {
                tag = "failure";
            }
            else
            {
                tag = "error";
            }

            out << "  <testcase classname=\"" << encode(tr.group) << "\" name=\"" << encode(tr.name) << "\">" << endl;
            out << "    <" << tag << " message=\"" << err_msg << "\"" << " type=\"" << failure_type << "\"";
#if defined(TUT_USE_POSIX)
            if(pid != getpid())
            {
                out << " child=\"" << pid << "\"";
            }
#endif
            out << ">" << err_msg << "</" << tag << ">" << endl;
            out << "  </testcase>";
        }

        return out.str();
    }

    /**
     * \brief Builds "testsuite" XML entity
     * Builds \<testsuite\> XML entity according to given parameters.
     * @param errors number of errors to be reported
     * @param failures number of failures to be reported
     * @param total total number of tests to be reported
     * @param name test suite name
     * @param testcases encoded XML string containing testcases
     * @return string with \<testsuite\> entity
     */
    virtual std::string xml_build_testsuite(int errors, int failures, int total,
                                            const std::string & name, const std::string & testcases)
    {
        std::ostringstream out;

        out << "<testsuite errors=\"" << errors << "\" failures=\"" << failures << "\" tests=\"" << total << "\" name=\"" << encode(name) << "\">" << std::endl;
        out << testcases;
        out << "</testsuite>";

        return out.str();
    }

public:
    int ok_count;           /// number of passed tests
    int exceptions_count;   /// number of tests that threw exceptions
    int failures_count;     /// number of tests that failed
    int terminations_count; /// number of tests that would terminate
    int warnings_count;     /// number of tests where destructors threw an exception

    /**
     * \brief Default constructor
     * @param filename base filename
     * @see setFilenameBase
     */
    xml_reporter(const std::string & _filename = "")
    {
        init();
        setFilenameBase(_filename);
    }

    /**
     * \brief Sets filename base for output
     * @param _filename filename base
     * Example usage:
     * @code
     * xml_reporter reporter;
     * reporter.setFilenameBase("my_xml");
     * @endcode
     * The above code will instruct reporter to create my_xml_1.xml file for the first test group,
     * my_xml_2.xml file for the second, and so on.
     */
    virtual void setFilenameBase(const std::string & _filename)
    {
        if (_filename == "")
        {
            filename = "testResult";
        }
        else
        {
            if (_filename.length() > 200)
            {
                throw(std::runtime_error("Filename too long!"));
            }

            filename = _filename;
        }
    }

    /**
     * \brief Callback function
     * This function is called before the first test is executed. It initializes counters.
     */
    virtual void run_started()
    {
        init();
    }

    /**
     * \brief Callback function
     * This function is called when test completes. Counters are updated here, and test results stored.
     */
    virtual void test_completed(const tut::test_result& tr)
    {
        // update global statistics
        switch (tr.result) {
            case test_result::ok:
                ok_count++;
                break;
            case test_result::fail:
            case test_result::rethrown:
                failures_count++;
                break;
            case test_result::ex:
            case test_result::ex_ctor:
                exceptions_count++;
                break;
            case test_result::warn:
                warnings_count++;
                break;
            case test_result::term:
                terminations_count++;
                break;
            case tut::test_result::dummy:
                assert(!"Should never be called");
        } // switch

        // add test result to results table
        (all_tests[tr.group]).push_back(tr);
    }

    /**
     * \brief Callback function
     * This function is called when all tests are completed. It generates XML output
     * to file(s). File name base can be set with \ref setFilenameBase.
     */
    virtual void run_completed()
    {
        using std::endl;
        using std::string;

        static int number = 1;  // results file sequence number (testResult_<number>.xml)

        // iterate over all test groups
        TestGroups::const_iterator tgi;
        for (tgi = all_tests.begin(); tgi != all_tests.end(); ++tgi) {
            /* per-group statistics */
            int passed = 0;         // passed in single group
            int exceptions = 0;     // exceptions in single group
            int failures = 0;       // failures in single group
            int terminations = 0;   // terminations in single group
            int warnings = 0;       // warnings in single group
            int errors = 0;     // errors in single group

            /* generate output filename */
            char fn[256];
            sprintf(fn, "%s_%d.xml", filename.c_str(), number++);

            std::ofstream xmlfile;
            xmlfile.open(fn, std::ios::in | std::ios::trunc);
            if (!xmlfile.is_open()) {
                throw (std::runtime_error("Cannot open file for output"));
            }

            /* *********************** header ***************************** */
            xmlfile << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;

            // output is written to string stream buffer, because JUnit format <testsuite> tag
            // contains statistics, which aren't known yet
            std::ostringstream out;

            // iterate over all test cases in the current test group
            TestResults::const_iterator tri;
            for (tri = (*tgi).second.begin(); tri != (*tgi).second.end(); ++tri) {
                string failure_type;    // string describing the failure type
                string failure_msg;     // a string with failure message

                switch ((*tri).result) {
                    case test_result::ok:
                        passed++;
                        break;
                    case test_result::fail:
                        failure_type = "Assertion";
                        failure_msg  = "";
                        failures++;
                        break;
                    case test_result::ex:
                        failure_type = "Assertion";
                        failure_msg  = "Thrown exception: " + (*tri).exception_typeid + '\n';
                        exceptions++;
                        break;
                    case test_result::warn:
                        failure_type = "Assertion";
                        failure_msg  = "Destructor failed.\n";
                        warnings++;
                        break;
                    case test_result::term:
                        failure_type = "Error";
                        failure_msg  = "Test application terminated abnormally.\n";
                        terminations++;
                        break;
                    case test_result::ex_ctor:
                        failure_type = "Assertion";
                        failure_msg  = "Constructor has thrown an exception: " + (*tri).exception_typeid + '\n';
                        exceptions++;
                        break;
                    case test_result::rethrown:
                        failure_type = "Assertion";
                        failure_msg  = "Child failed";
                        failures++;
                        break;
                    default:
                        failure_type = "Error";
                        failure_msg  = "Unknown test status, this should have never happened. "
                                "You may just have found a BUG in TUT XML reporter, please report it immediately.\n";
                        errors++;
                        break;
                } // switch

#if defined(TUT_USE_POSIX)
                out << xml_build_testcase(*tri, failure_type, failure_msg, (*tri).pid) << endl;
#else
                out << xml_build_testcase(*tri, failure_type, failure_msg) << endl;
#endif

            } // iterate over all test cases

            // calculate per-group statistics
            int stat_errors = terminations + errors;
            int stat_failures = failures + warnings + exceptions;
            int stat_all = stat_errors + stat_failures + passed;

            xmlfile << xml_build_testsuite(stat_errors, stat_failures, stat_all, (*tgi).first/* name */, out.str()/* testcases */) << endl;
            xmlfile.close();
        } // iterate over all test groups
    }

    /**
     * \brief Returns true, if all tests passed
     */
    virtual bool all_ok() const
    {
        return ( (terminations_count + failures_count + warnings_count + exceptions_count) == 0);
    };
};

}

#endif
<|endoftext|>


<commit_before>
// Simple macro showing capabilities of TGSpeedo widget.
//Author: Bertrand Bellenot

#include "TSystem.h"
#include "TGFrame.h"
#include "TGWindow.h"
#include "TGSpeedo.h"

class TGShapedMain : public TGMainFrame {

protected:
   const TGPicture   *fBgnd;           // picture used as mask
   TGSpeedo          *fSpeedo;          // analog meter
   TTimer            *fTimer;           // update timer
   Int_t              fActInfo;         // actual information value

public:
   TGShapedMain(const TGWindow *p, int w, int h);
   virtual ~TGShapedMain();

   void              CloseWindow();
   TGSpeedo         *GetSpeedo() const { return fSpeedo; }
   Int_t             GetActInfo() const { return fActInfo; }
   void              ToggleInfos();

   ClassDef(TGShapedMain, 0)
};

// globals
TGShapedMain *gMainWindow;
TGSpeedo *gSpeedo;
Float_t prev_load;
Int_t old_memUsage;

//______________________________________________________________________________
TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) :
   TGMainFrame(p, w, h)
{
   // Constructor.

   fActInfo = 1;

   fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]");
   fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()");
   fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()");
   Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()");
   AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0));
   fSpeedo->SetDisplayText("Used RAM", "[MB]");
   fTimer = new TTimer(100);
   fTimer->SetCommand("Update()");

   fBgnd = fSpeedo->GetPicture();
   gVirtualX->ShapeCombineMask(GetId(), 0, 0, fBgnd->GetMask());
   SetBackgroundPixmap(fBgnd->GetPicture());
   SetWMSizeHints(fBgnd->GetWidth(), fBgnd->GetHeight(), fBgnd->GetWidth(),
                  fBgnd->GetHeight(), 1, 1);

   MapSubwindows();
   MapWindow();
   // To avoid closing the window while TGSpeedo is drawing
   DontCallClose();
   // To avoid closing the window while TGSpeedo is drawing
   Resize(GetDefaultSize());
   // Set fixed size
   SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1);
   SetWindowName("ROOT CPU Load Meter");
   fTimer->TurnOn();
}

//______________________________________________________________________________
void TGShapedMain::ToggleInfos()
{
   // Toggle information displayed in Analog Meter

   if (fActInfo < 2)
      fActInfo++;
   else
      fActInfo = 0;
   if (fActInfo == 0)
      fSpeedo->SetDisplayText("Total RAM", "[MB]");
   else if (fActInfo == 1)
      fSpeedo->SetDisplayText("Used RAM", "[MB]");
   else if (fActInfo == 2)
      fSpeedo->SetDisplayText("Free RAM", "[MB]");
}

//______________________________________________________________________________
TGShapedMain::~TGShapedMain()
{
   // Destructor.

}

//______________________________________________________________________________
void TGShapedMain::CloseWindow()
{
   // Close Window.

   if (fTimer)
      fTimer->TurnOff();
   delete fTimer;
   delete fSpeedo;
   delete this;
}

void Update()
{
   MemInfo_t memInfo;
   CpuInfo_t cpuInfo;
   Float_t act_load = 0.0;
   Int_t memUsage = 0;
   prev_load = act_load;
   old_memUsage = memUsage;

   // Get CPU informations
   gSystem->GetCpuInfo(&cpuInfo, 100);
   // actual CPU load
   act_load = cpuInfo.fTotal;
   // Get Memory informations
   gSystem->GetMemInfo(&memInfo);
   // choose which value to display
   if (gMainWindow->GetActInfo() == 0)
      memUsage = memInfo.fMemTotal;
   else if (gMainWindow->GetActInfo() == 1)
      memUsage = memInfo.fMemUsed;
   else if (gMainWindow->GetActInfo() == 2)
      memUsage = memInfo.fMemFree;
   // small threshold to avoid "trembling" needle
   if (fabs(act_load-prev_load) > 0.9) {
      gSpeedo->SetScaleValue(act_load, 10);
      prev_load = act_load;
   }
   // update only if value has changed
   if (memUsage != old_memUsage) {
      gSpeedo->SetOdoValue(memUsage);
      old_memUsage = memUsage;
   }
}

//______________________________________________________________________________
void CPUMeter()
{
   // Main application.

   gMainWindow = new TGShapedMain(0, 500, 200);
   gSpeedo = gMainWindow->GetSpeedo();

   // set threshold values
   gSpeedo->SetThresholds(12.5, 50.0, 87.5);
   // set threshold colors
   gSpeedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed);
   // enable threshold
   gSpeedo->EnableThreshold();
   gSpeedo->SetScaleValue(0.0, 5);
   // enable peak marker
   gSpeedo->EnablePeakMark();

}

<commit_msg>From Bertrand: Fixed errors reported by valgrind (slc4/ia32) and purify (win32).<commit_after>
// Simple macro showing capabilities of TGSpeedo widget.
//Author: Bertrand Bellenot

#include "TSystem.h"
#include "TGFrame.h"
#include "TGWindow.h"
#include "TGSpeedo.h"

class TGShapedMain : public TGMainFrame {

protected:
   const TGPicture   *fBgnd;           // picture used as mask
   TGSpeedo          *fSpeedo;          // analog meter
   TTimer            *fTimer;           // update timer
   Int_t              fActInfo;         // actual information value

public:
   TGShapedMain(const TGWindow *p, int w, int h);
   virtual ~TGShapedMain();

   void              CloseWindow();
   TGSpeedo         *GetSpeedo() const { return fSpeedo; }
   Int_t             GetActInfo() const { return fActInfo; }
   void              ToggleInfos();

   ClassDef(TGShapedMain, 0)
};

// globals
TGShapedMain *gMainWindow;
TGSpeedo *gSpeedo;
Float_t prev_load;
Int_t old_memUsage;

//______________________________________________________________________________
TGShapedMain::TGShapedMain(const TGWindow *p, int w, int h) :
   TGMainFrame(p, w, h)
{
   // Constructor.

   fActInfo = 1;

   fSpeedo = new TGSpeedo(this, 0.0, 100.0, "CPU", "[%]");
   fSpeedo->Connect("OdoClicked()", "TGShapedMain", this, "ToggleInfos()");
   fSpeedo->Connect("LedClicked()", "TGShapedMain", this, "CloseWindow()");
   Connect("CloseWindow()", "TGShapedMain", this, "CloseWindow()");
   AddFrame(fSpeedo, new TGLayoutHints(kLHintsCenterX | kLHintsCenterX, 0, 0, 0, 0));
   fSpeedo->SetDisplayText("Used RAM", "[MB]");
   fTimer = new TTimer(100);
   fTimer->SetCommand("Update()");

   fBgnd = fSpeedo->GetPicture();
   gVirtualX->ShapeCombineMask(GetId(), 0, 0, fBgnd->GetMask());
   SetBackgroundPixmap(fBgnd->GetPicture());
   SetWMSizeHints(fBgnd->GetWidth(), fBgnd->GetHeight(), fBgnd->GetWidth(),
                  fBgnd->GetHeight(), 1, 1);

   MapSubwindows();
   MapWindow();
   // To avoid closing the window while TGSpeedo is drawing
   DontCallClose();
   // To avoid closing the window while TGSpeedo is drawing
   Resize(GetDefaultSize());
   // Set fixed size
   SetWMSizeHints(GetDefaultWidth(), GetDefaultHeight(), GetDefaultWidth(), GetDefaultHeight(), 1, 1);
   SetWindowName("ROOT CPU Load Meter");
   fTimer->TurnOn();
}

//______________________________________________________________________________
void TGShapedMain::ToggleInfos()
{
   // Toggle information displayed in Analog Meter

   if (fActInfo < 2)
      fActInfo++;
   else
      fActInfo = 0;
   if (fActInfo == 0)
      fSpeedo->SetDisplayText("Total RAM", "[MB]");
   else if (fActInfo == 1)
      fSpeedo->SetDisplayText("Used RAM", "[MB]");
   else if (fActInfo == 2)
      fSpeedo->SetDisplayText("Free RAM", "[MB]");
}

//______________________________________________________________________________
TGShapedMain::~TGShapedMain()
{
   // Destructor.

   delete fTimer;
   delete fSpeedo;
}

//______________________________________________________________________________
void TGShapedMain::CloseWindow()
{
   // Close Window.

   if (fTimer)
      fTimer->TurnOff();
   DestroyWindow();
}

void Update()
{
   MemInfo_t memInfo;
   CpuInfo_t cpuInfo;
   Float_t act_load = 0.0;
   Int_t memUsage = 0;
   prev_load = act_load;
   old_memUsage = memUsage;

   // Get CPU informations
   gSystem->GetCpuInfo(&cpuInfo, 100);
   // actual CPU load
   act_load = cpuInfo.fTotal;
   // Get Memory informations
   gSystem->GetMemInfo(&memInfo);
   // choose which value to display
   if (gMainWindow->GetActInfo() == 0)
      memUsage = memInfo.fMemTotal;
   else if (gMainWindow->GetActInfo() == 1)
      memUsage = memInfo.fMemUsed;
   else if (gMainWindow->GetActInfo() == 2)
      memUsage = memInfo.fMemFree;
   // small threshold to avoid "trembling" needle
   if (fabs(act_load-prev_load) > 0.9) {
      gSpeedo->SetScaleValue(act_load, 10);
      prev_load = act_load;
   }
   // update only if value has changed
   if (memUsage != old_memUsage) {
      gSpeedo->SetOdoValue(memUsage);
      old_memUsage = memUsage;
   }
}

//______________________________________________________________________________
void CPUMeter()
{
   // Main application.

   gMainWindow = new TGShapedMain(0, 500, 200);
   gSpeedo = gMainWindow->GetSpeedo();

   // set threshold values
   gSpeedo->SetThresholds(12.5, 50.0, 87.5);
   // set threshold colors
   gSpeedo->SetThresholdColors(TGSpeedo::kGreen, TGSpeedo::kOrange, TGSpeedo::kRed);
   // enable threshold
   gSpeedo->EnableThreshold();
   gSpeedo->SetScaleValue(0.0, 5);
   // enable peak marker
   gSpeedo->EnablePeakMark();

}

<|endoftext|>


<commit_before>/*
 * http://github.com/dusty-nv/jetson-inference
 */

// #include "gstCamera.h"
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <chrono>
#include <jetson-inference/cudaMappedMemory.h>
#include <jetson-inference/cudaNormalize.h>
#include <jetson-inference/cudaFont.h>

#include <jetson-inference/imageNet.h>

#define DEFAULT_CAMERA -1	// -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0)

using namespace std;

bool signal_recieved = false;

//void sig_handler(int signo)
//{
	//if( signo == SIGINT )
	//{
		//printf("received SIGINT\n");
		//signal_recieved = true;
	//}
//}

static const std::string OPENCV_WINDOW = "Image post bridge conversion";
static const std::string OPENCV_WINDOW2 = "Image post bit depth conversion";
static const std::string OPENCV_WINDOW3 = "Image post color conversion";
static const std::string OPENCV_WINDOW4 = "Image window";

class ObjectClassifier
{
	ros::NodeHandle nh_;
	image_transport::ImageTransport it_;
	image_transport::Subscriber image_sub_;
    cv::Mat cv_im;
    cv_bridge::CvImagePtr cv_ptr;
    std::chrono::steady_clock::time_point prev;

	float confidence = 0.0f;

	//float* bbCPU    = NULL;
	//float* bbCUDA   = NULL;
	//float* confCPU  = NULL;
	//float* confCUDA = NULL;

    imageNet* net = NULL;
	//detectNet* net = NULL;
	//uint32_t maxBoxes = 0;
	//uint32_t classes = 0;

	float4* gpu_data = NULL;

	uint32_t imgWidth;
	uint32_t imgHeight;
	size_t imgSize;

public:
	ObjectClassifier(int argc, char** argv ) : it_(nh_)
	{
		cout << "start constructor" << endl;
		// Subscrive to input video feed and publish output video feed
		image_sub_ = it_.subscribe("/left/image_rect_color", 2,
		  &ObjectClassifier::imageCb, this);

		cv::namedWindow(OPENCV_WINDOW);

		cout << "Named a window" << endl;

        prev = std::chrono::steady_clock::now();

         // create imageNet
        // net = imageNet::Create(prototxt_path.c_str(),model_path.c_str(),NULL,class_labels_path.c_str());
        net = imageNet::Create(argc, argv );
		/*
		 * create detectNet
		 */
		//net = detectNet::Create(argc, argv);
		//cout << "Created DetectNet" << endl;

		if( !net )
		{
			printf("obj_detect:   failed to initialize imageNet\n");

		}

        //maxBoxes = net->GetMaxBoundingBoxes();
		//printf("maximum bounding boxes:  %u\n", maxBoxes);
		//classes  = net->GetNumClasses();

		///*
		 //* allocate memory for output bounding boxes and class confidence
		 //*/

		//if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) ||
			//!cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) )
		//{
			//printf("detectnet-console:  failed to alloc output memory\n");

		//}
		//cout << "Allocated CUDA mem" << endl;

		//maxBoxes = net->GetMaxBoundingBoxes();
		//printf("maximum bounding boxes:  %u\n", maxBoxes);
		//classes  = net->GetNumClasses();
		//cout << "Constructor operations complete" << endl;

	}

	~ObjectClassifier()
	{
		cv::destroyWindow(OPENCV_WINDOW);
	}

	void imageCb(const sensor_msgs::ImageConstPtr& msg)
	{

		try
		{
			cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
			cv_im = cv_ptr->image;
			cv_im.convertTo(cv_im,CV_32FC3);

			// convert color
			cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA);

		}
		catch (cv_bridge::Exception& e)
		{
		  ROS_ERROR("cv_bridge exception: %s", e.what());
		  return;
		}

        // allocate GPU data if necessary
        if(!gpu_data){
            ROS_INFO("first allocation");
            CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4)));
        }else if(imgHeight != cv_im.rows || imgWidth != cv_im.cols){
            ROS_INFO("re allocation");
            // reallocate for a new image size if necessary
            CUDA(cudaFree(gpu_data));
            CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4)));
        }

		imgHeight = cv_im.rows;
		imgWidth = cv_im.cols;
		imgSize = cv_im.rows*cv_im.cols * sizeof(float4);
		float4* cpu_data = (float4*)(cv_im.data);

		// copy to device
		CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice));

		void* imgCUDA = NULL;

        // classify image
        const int img_class = net->Classify((float*)gpu_data, imgWidth, imgHeight, &confidence);

        // find class string
        std::string class_name;
        class_name = net->GetClassDesc(img_class);

        std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
        float fps = 1000.0 / std::chrono::duration_cast<std::chrono::milliseconds>(now - prev).count() ;

        prev = now;

        char str[256];
        sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", fps);
        cv::setWindowTitle(OPENCV_WINDOW, str);

		// update image back to original

        cv_im.convertTo(cv_im,CV_8UC3);
        cv::cvtColor(cv_im,cv_im,CV_RGBA2BGR);

        // draw class string
        cv::putText(cv_im, class_name, cv::Point(60,60), cv::FONT_HERSHEY_PLAIN, 3.0, cv::Scalar(0,0,255),3);

		// Update GUI Window
        cv::imshow(OPENCV_WINDOW, cv_im);
		cv::waitKey(1);

	}
};

int main( int argc, char** argv ) {
	cout << "starting node" << endl;
	printf("obj_classifier\n  args (%i):  ", argc);

	ros::init(argc, argv, "obj_detector");
    ros::NodeHandle nh;

	for( int i=0; i < argc; i++ )
		printf("%i [%s]  ", i, argv[i]);

	printf("\n\n");

	ObjectClassifier ic(argc, argv);

	ros::spin();

	return 0;
}

<commit_msg>change classifier to subscribe to topic coming through on obj_detector<commit_after>/*
 * http://github.com/dusty-nv/jetson-inference
 */

// #include "gstCamera.h"
#include <ros/ros.h>
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <chrono>
#include <jetson-inference/cudaMappedMemory.h>
#include <jetson-inference/cudaNormalize.h>
#include <jetson-inference/cudaFont.h>

#include <jetson-inference/imageNet.h>

#define DEFAULT_CAMERA -1	// -1 for onboard camera, or change to index of /dev/video V4L2 camera (>=0)

using namespace std;

bool signal_recieved = false;

//void sig_handler(int signo)
//{
	//if( signo == SIGINT )
	//{
		//printf("received SIGINT\n");
		//signal_recieved = true;
	//}
//}

static const std::string OPENCV_WINDOW = "Image post bridge conversion";
static const std::string OPENCV_WINDOW2 = "Image post bit depth conversion";
static const std::string OPENCV_WINDOW3 = "Image post color conversion";
static const std::string OPENCV_WINDOW4 = "Image window";

class ObjectClassifier
{
	ros::NodeHandle nh_;
	image_transport::ImageTransport it_;
	image_transport::Subscriber image_sub_;
    cv::Mat cv_im;
    cv_bridge::CvImagePtr cv_ptr;
    std::chrono::steady_clock::time_point prev;

	float confidence = 0.0f;

	//float* bbCPU    = NULL;
	//float* bbCUDA   = NULL;
	//float* confCPU  = NULL;
	//float* confCUDA = NULL;

    imageNet* net = NULL;
	//detectNet* net = NULL;
	//uint32_t maxBoxes = 0;
	//uint32_t classes = 0;

	float4* gpu_data = NULL;

	uint32_t imgWidth;
	uint32_t imgHeight;
	size_t imgSize;

public:
	ObjectClassifier(int argc, char** argv ) : it_(nh_)
	{
		cout << "start constructor" << endl;
		// Subscrive to input video feed and publish output video feed
		//image_sub_ = it_.subscribe("/left/image_rect_color", 2,
		  //&ObjectClassifier::imageCb, this);
        image_sub_ = it_.subscribe("/detected_image", 2,
		  &ObjectClassifier::imageCb, this);

		cv::namedWindow(OPENCV_WINDOW);

		cout << "Named a window" << endl;

        prev = std::chrono::steady_clock::now();

         // create imageNet
        // net = imageNet::Create(prototxt_path.c_str(),model_path.c_str(),NULL,class_labels_path.c_str());
        net = imageNet::Create(argc, argv );
		/*
		 * create detectNet
		 */
		//net = detectNet::Create(argc, argv);
		//cout << "Created DetectNet" << endl;

		if( !net )
		{
			printf("obj_detect:   failed to initialize imageNet\n");

		}

        //maxBoxes = net->GetMaxBoundingBoxes();
		//printf("maximum bounding boxes:  %u\n", maxBoxes);
		//classes  = net->GetNumClasses();

		///*
		 //* allocate memory for output bounding boxes and class confidence
		 //*/

		//if( !cudaAllocMapped((void**)&bbCPU, (void**)&bbCUDA, maxBoxes * sizeof(float4)) ||
			//!cudaAllocMapped((void**)&confCPU, (void**)&confCUDA, maxBoxes * classes * sizeof(float)) )
		//{
			//printf("detectnet-console:  failed to alloc output memory\n");

		//}
		//cout << "Allocated CUDA mem" << endl;

		//maxBoxes = net->GetMaxBoundingBoxes();
		//printf("maximum bounding boxes:  %u\n", maxBoxes);
		//classes  = net->GetNumClasses();
		//cout << "Constructor operations complete" << endl;

	}

	~ObjectClassifier()
	{
		cv::destroyWindow(OPENCV_WINDOW);
	}

	void imageCb(const sensor_msgs::ImageConstPtr& msg)
	{

		try
		{
			cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8);
			cv_im = cv_ptr->image;
			cv_im.convertTo(cv_im,CV_32FC3);

			// convert color
			cv::cvtColor(cv_im,cv_im,CV_BGR2RGBA);

		}
		catch (cv_bridge::Exception& e)
		{
		  ROS_ERROR("cv_bridge exception: %s", e.what());
		  return;
		}

        // allocate GPU data if necessary
        if(!gpu_data){
            ROS_INFO("first allocation");
            CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4)));
        }else if(imgHeight != cv_im.rows || imgWidth != cv_im.cols){
            ROS_INFO("re allocation");
            // reallocate for a new image size if necessary
            CUDA(cudaFree(gpu_data));
            CUDA(cudaMalloc(&gpu_data, cv_im.rows*cv_im.cols * sizeof(float4)));
        }

		imgHeight = cv_im.rows;
		imgWidth = cv_im.cols;
		imgSize = cv_im.rows*cv_im.cols * sizeof(float4);
		float4* cpu_data = (float4*)(cv_im.data);

		// copy to device
		CUDA(cudaMemcpy(gpu_data, cpu_data, imgSize, cudaMemcpyHostToDevice));

		void* imgCUDA = NULL;

        // classify image
        const int img_class = net->Classify((float*)gpu_data, imgWidth, imgHeight, &confidence);

        // find class string
        std::string class_name;
        class_name = net->GetClassDesc(img_class);

        std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
        float fps = 1000.0 / std::chrono::duration_cast<std::chrono::milliseconds>(now - prev).count() ;

        prev = now;

        char str[256];
        sprintf(str, "TensorRT build %x | %s | %04.1f FPS", NV_GIE_VERSION, net->HasFP16() ? "FP16" : "FP32", fps);
        cv::setWindowTitle(OPENCV_WINDOW, str);

		// update image back to original

        cv_im.convertTo(cv_im,CV_8UC3);
        cv::cvtColor(cv_im,cv_im,CV_RGBA2BGR);

        // draw class string
        cv::putText(cv_im, class_name, cv::Point(60,60), cv::FONT_HERSHEY_PLAIN, 3.0, cv::Scalar(0,0,255),3);

		// Update GUI Window
        cv::imshow(OPENCV_WINDOW, cv_im);
		cv::waitKey(1);

	}
};

int main( int argc, char** argv ) {
	cout << "starting node" << endl;
	printf("obj_classifier\n  args (%i):  ", argc);

	ros::init(argc, argv, "obj_detector");
    ros::NodeHandle nh;

	for( int i=0; i < argc; i++ )
		printf("%i [%s]  ", i, argv[i]);

	printf("\n\n");

	ObjectClassifier ic(argc, argv);

	ros::spin();

	return 0;
}

<|endoftext|>


<commit_before>#pragma once

#include <af/defines.h>
#include <kernel_headers/tile.hpp>
#include <cl.hpp>
#include <ctx.hpp>
#include <traits.hpp>
#include <helper.hpp>
#include <sstream>
#include <string>
#include <dispatch.hpp>

typedef struct
{
    dim_type dims[4];
} dims_t;

using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::make_kernel;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;

namespace opencl
{
    namespace kernel
    {
        // Kernel Launch Config Values
        static const dim_type TX = 32;
        static const dim_type TY = 8;
        static const dim_type TILEX = 512;
        static const dim_type TILEY = 32;

        template<typename T>
        void tile(Buffer out, const Buffer in,
                  const dim_type *odims, const dim_type *idims,
                  const dim_type *ostrides, const dim_type *istrides, const dim_type offset)
        {

            static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
            static Program            tileProgs[DeviceManager::MAX_DEVICES];
            static Kernel           tileKernels[DeviceManager::MAX_DEVICES];

            int device = getActiveDeviceId();

            std::call_once( compileFlags[device], [device] () {
                    Program::Sources setSrc;
                    setSrc.emplace_back(transpose_cl, transpose_cl_len);

                    tileProgs[device] = Program(getContext(), setSrc);

                    std::ostringstream options;
                    options << " -D T=" << dtype_traits<T>::getName()
                            << " -D dim_type=" << dtype_traits<dim_type>::getName()
                            << " -D TILE_DIM=" << TILE_DIM;
                    tileProgs[device].build(options.str().c_str());

                    tileKernels[device] = Kernel(tileProgs[device], "transpose");
                });

            auto tileOp = make_kernel<Buffer, const Buffer, const dims_t, const dims_t,
                                      const dims_t, const dims_t, const dim_type,
                                      const unsigned, const unsigned>
                                      (tileKernels[device]);

            NDRange local(TX, TY, 1);

            unsigned blocksPerMatX = divup(odims[0], TILEX);
            unsigned blocksPerMatY = divup(odims[1], TILEY);
            NDRange global(local[0] * blocksPerMatX * odims[2],
                           local[1] * blocksPerMatY * odims[3],
                           1);

            dims_t _odims = {{odims[0], odims[1], odims[2], odims[3]}};
            dims_t _idims = {{idims[0], idims[1], idims[2], idims[3]}};
            dims_t _ostrides = {{ostrides[0], ostrides[1], ostrides[2], ostrides[3]}};
            dims_t _istrides = {{istrides[0], istrides[1], istrides[2], istrides[3]}};

            tileOp(EnqueueArgs(getQueue(0), global, local),
                   out, in, _odims, _idims, _ostrides, _istrides, offset, blocksPerMatX, blocksPerMatY);

        }
    }
}
<commit_msg>Fixing copy paste error<commit_after>#pragma once

#include <af/defines.h>
#include <kernel_headers/tile.hpp>
#include <cl.hpp>
#include <platform.hpp>
#include <traits.hpp>
#include <helper.hpp>
#include <sstream>
#include <string>
#include <dispatch.hpp>

typedef struct
{
    dim_type dims[4];
} dims_t;

using cl::Buffer;
using cl::Program;
using cl::Kernel;
using cl::make_kernel;
using cl::EnqueueArgs;
using cl::NDRange;
using std::string;

namespace opencl
{
    namespace kernel
    {
        // Kernel Launch Config Values
        static const dim_type TX = 32;
        static const dim_type TY = 8;
        static const dim_type TILEX = 512;
        static const dim_type TILEY = 32;

        template<typename T>
        void tile(Buffer out, const Buffer in,
                  const dim_type *odims, const dim_type *idims,
                  const dim_type *ostrides, const dim_type *istrides, const dim_type offset)
        {
            static std::once_flag compileFlags[DeviceManager::MAX_DEVICES];
            static Program            tileProgs[DeviceManager::MAX_DEVICES];
            static Kernel           tileKernels[DeviceManager::MAX_DEVICES];

            int device = getActiveDeviceId();

            std::call_once( compileFlags[device], [device] () {
                    Program::Sources setSrc;
                    setSrc.emplace_back(tile_cl, tile_cl_len);

                    tileProgs[device] = Program(getContext(), setSrc);

                    std::ostringstream options;
                    options << " -D T=" << dtype_traits<T>::getName()
                            << " -D dim_type=" << dtype_traits<dim_type>::getName();

                    tileProgs[device].build(options.str().c_str());
                    tileKernels[device] = Kernel(tileProgs[device], "tile_kernel");
                });

            auto tileOp = make_kernel<Buffer, const Buffer, const dims_t, const dims_t,
                                      const dims_t, const dims_t, const dim_type,
                                      const unsigned, const unsigned>
                (tileKernels[device]);

            NDRange local(TX, TY, 1);

            unsigned blocksPerMatX = divup(odims[0], TILEX);
            unsigned blocksPerMatY = divup(odims[1], TILEY);
            NDRange global(local[0] * blocksPerMatX * odims[2],
                           local[1] * blocksPerMatY * odims[3],
                           1);

            dims_t _odims = {{odims[0], odims[1], odims[2], odims[3]}};
            dims_t _idims = {{idims[0], idims[1], idims[2], idims[3]}};
            dims_t _ostrides = {{ostrides[0], ostrides[1], ostrides[2], ostrides[3]}};
            dims_t _istrides = {{istrides[0], istrides[1], istrides[2], istrides[3]}};

            tileOp(EnqueueArgs(getQueue(), global, local),
                   out, in, _odims, _idims, _ostrides, _istrides, offset, blocksPerMatX, blocksPerMatY);
        }
    }
}
<|endoftext|>