<commit_before>#include <iostream>
#include <fstream>

#include "itkFileListVideoIO.h"
#include "itkImportImageFilter.h"
#include "itkRGBPixel.h"
#include "itkImageFileWriter.h"

// ITK typedefs
typedef itk::RGBPixel<char> PixelType;
typedef itk::ImportImageFilter<PixelType, 2> ImportFilterType;
typedef itk::Image<PixelType, 2> ImageType;
typedef itk::ImageFileWriter<ImageType> WriterType;

///////////////////////////////////////////////////////////////////////////////
// This tests all of the functionality of the FileListVideoIO
//
// Usage: [Video Input] [Non-Video Input] [Video Output] [Width] [Height]
//            [Num Frames] [FpS]

int test_FileListVideoIO ( char* input, char* nonVideoInput, char* output, char* cameraOutput,
                         unsigned int inWidth, unsigned int inHeight, unsigned long inNumFrames,
                         double inFpS )
{

  int ret = EXIT_SUCCESS;

  // Create the VideoIO
  itk::FileListVideoIO::Pointer fileListIO = itk::FileListVideoIO::New();

  //////
  // SetFileName
  //////

  fileListIO->SetFileName(input);

  //////
  // CanReadFile
  //////
  std::cout << "FileListVideoIO::CanReadFile..." << std::endl;

  // Test CanReadFile on good file
  if (!fileListIO->CanReadFile(input))
    {
    std::cerr << "Could not read " << input << std::endl;
    ret = EXIT_FAILURE;
    }

  // Test CanReadFile on non-existant file
  std::string nonExistantFile = "Bad/Path/To/Nothing";
  if (fileListIO->CanReadFile(nonExistantFile.c_str()))
    {
    std::cerr << "Should have failed to open \"" << nonExistantFile << "\"" << std::endl;
    ret = EXIT_FAILURE;
    }

  // Test CanReadFile on non-image file list
  if (fileListIO->CanReadFile(nonVideoInput))
    {
    std::cerr << "Should have failed to open \"" << nonVideoInput << "\"" << std::endl;
    ret = EXIT_FAILURE;
    }
/*

  //////
  // ReadImageInformation
  //////
  std::cout << "FileListVideoIO::ReadImageInformation..." << std::endl;

  fileListIO->SetFileName(input);
  fileListIO->ReadImageInformation();
  bool infoSet = true;
  std::stringstream paramMessage;
  if (fileListIO->GetDimensions(0) != inWidth)
    {
    infoSet = false;
    paramMessage << "Width mismatch: (expected) " << inWidth << " != (got) "
      << fileListIO->GetDimensions(0) << std::endl;
    }
  if (fileListIO->GetDimensions(1) != inHeight)
    {
    infoSet = false;
    paramMessage << "Height mismatch: (expected) " << inHeight << " != (got) "
      << fileListIO->GetDimensions(1) << std::endl;
    }
  double epsilon = 0.0001;
  if (fileListIO->GetFpS() < inFpS - epsilon || fileListIO->GetFpS() > inFpS + epsilon)
    {
    infoSet = false;
    paramMessage << "FpS mismatch: (expected) " << inFpS << " != (got) " << fileListIO->GetFpS()
      << std::endl;
    }
  if (fileListIO->GetFrameTotal() != inNumFrames)
    {
    infoSet = false;
    paramMessage << "FrameTotal mismatch: (expected) " << inNumFrames << " != (got) "
      << fileListIO->GetFrameTotal() << std::endl;
    }

  if (!infoSet)
    {
    std::cerr << paramMessage.str();
    ret = EXIT_FAILURE;
    }

  //////
  // Read
  //////
  std::cout << "FileListVideoIO::Read..." << std::endl;
  std::cout << "Comparing all " << fileListIO->GetFrameTotal() << " frames" << std::endl;

  // Set up FileList capture
  CvCapture* capture = cvCaptureFromFile( fileListIO->GetFileName() );

  // Loop through all frames
  for (unsigned long i = 0; i < fileListIO->GetFrameTotal(); ++i)
    {
    if (!readCorrectly(fileListIO, capture, i))
      {
      std::cerr << "Failed to read frame " << i << " correctly" << std::endl;
      ret = EXIT_FAILURE;
      break;
      }
    }

  // Release capture
  cvReleaseCapture(&capture);

  //////
  // SetNextFrameToRead
  //////
  std::cout << "FileListVideoIO::SetNextFrameToRead" << std::endl;

  // Set up the buffer for the frame data so Read can be called
  size_t bufferSize = fileListIO->GetImageSizeInBytes();
  PixelType buffer[bufferSize];

  // try seeking to an I-Frame
  unsigned long seekFrame = fileListIO->GetIFrameInterval();
  if (!fileListIO->SetNextFrameToRead(seekFrame))
    {
    std::cerr << "Failed to seek to second I-Frame..." << std::endl;
    ret = EXIT_FAILURE;
    }

  // Read the frame data which updates the current frame correctly
  fileListIO->Read(static_cast<void*>(buffer));

  if (fileListIO->GetCurrentFrame() != seekFrame)
    {
    std::cerr << "Seek to I-Frame didn't end up in the right place" << std::endl;
    ret = EXIT_FAILURE;
    }

  // If there are I-Frame intervals, check behavior
  if (fileListIO->GetIFrameInterval() > 1)
    {

    // try seeking in-between I-Frames
    seekFrame = fileListIO->GetIFrameInterval()/2;
    if (!fileListIO->SetNextFrameToRead(seekFrame))
      {
      std::cerr << "Failed to seek between I-Frames" << std::endl;
      ret = EXIT_FAILURE;
      }
    fileListIO->Read(static_cast<void*>(buffer));
    if (fileListIO->GetCurrentFrame() != fileListIO->GetIFrameInterval())
      {
      std::cerr << "Seek between I-Frames didn't end up in the right place" << std::endl;
      ret = EXIT_FAILURE;
      }

    // try seeking past last I-Frame
    seekFrame = fileListIO->GetLastIFrame() + 1;
    if (fileListIO->SetNextFrameToRead(seekFrame))
      {
      std::cerr << "Did no fail when seeking past the last I-Frame" << std::endl;
      ret = EXIT_FAILURE;
      }

    }

  // Save the current parameters
  double fps = fileListIO->GetFpS();
  unsigned int width = fileListIO->GetDimensions(0);
  unsigned int height = fileListIO->GetDimensions(1);
  const char* fourCC = "MP42";
  unsigned int nChannels = fileListIO->GetNumberOfComponents();

  // Reset the VideoIO
  fileListIO->FinishReadingOrWriting();

  //////
  // Test reading from camera -- If webcam 0 can be opened, it will, otherwise this will be skipped
  //////

  // Check to see if camera is available
  if (fileListIO->CanReadCamera( 0 ))
    {

    std::cout << "FileListVideoIO::Read (from camera)..." << std::endl;

    // Set the reader to use the camera
    fileListIO->SetReadFromCamera();

    // Get information from the camera
    try
      {
      fileListIO->ReadImageInformation();
      }
    catch (itk::ExceptionObject e)
      {
      std::cerr << "Could not read information from the camera" << std::endl;
      ret = EXIT_FAILURE;
      }

    // set up buffer for camera
    size_t camBufferSize = fileListIO->GetImageSizeInBytes();
    PixelType camBuffer[camBufferSize];

    // Read from the camera
    try
      {
      fileListIO->Read(reinterpret_cast<void*>(camBuffer));
      }
    catch (itk::ExceptionObject e)
      {
      std::cerr << "Could not read from the camera" << std::endl;
      ret = EXIT_FAILURE;
      }

    // Get an ITK image from the camera's frame
    ImageType::Pointer cameraFrame = itkImageFromBuffer(fileListIO, camBuffer, camBufferSize);

    // Write out the ITK image -- DEBUG
    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName(cameraOutput);
    writer->SetInput(cameraFrame);
    writer->Update();

    // Overwirte the file right away so we're not saving pictures of the tester!
    std::ofstream fs;
    fs.open(cameraOutput);
    fs << "EMPTY... deleted picture from webcam\n";
    fs.close();

    // Finish reading
    fileListIO->FinishReadingOrWriting();

    }

  /////////////////////////////////////////////////////////////////////////////
  // Test Writing
  //

  //////
  // SetWriterParameters
  //////
  std::cout << "FileListVIdeoIO::SetWriterParameters..." << std::endl;

  // Reset the saved parameters
  std::vector<unsigned int> size;
  size.push_back(width);
  size.push_back(height);
  fileListIO->SetWriterParameters(fps, size, fourCC, nChannels, itk::ImageIOBase::UCHAR);

  // Make sure they set correctly
  if (fileListIO->GetFpS() != fps || fileListIO->GetDimensions(0) != width ||
      fileListIO->GetDimensions(1) != height || fileListIO->GetNumberOfComponents() != nChannels)
    {
    std::cerr << "Didn't set writer parmeters correctly" << std::endl;
    ret = EXIT_FAILURE;
    }

  //////
  // CanWriteFile
  //////
  std::cout << "FileListVideoIO::CanWriteFile..." << std::endl;

  // Test CanWriteFile on good filename
  if (!fileListIO->CanWriteFile(output))
    {
    std::cerr << "CanWriteFile didn't return true correctly" << std::endl;
    ret = EXIT_FAILURE;
    }

  // Test CanWriteFile on bad filename
  if (fileListIO->CanWriteFile("asdfasdfasdf"))
    {
    std::cerr << "CanWriteFile should have failed for bad filename" << std::endl;
    ret = EXIT_FAILURE;
    }

  //////
  // Write
  //////
  std::cout << "FileListVIdeoIO::Write..." << std::endl;

  // Set output filename
  fileListIO->SetFileName( output );

  // Set up a second VideoIO to read while we're writing
  itk::FileListVideoIO::Pointer fileListIO2 = itk::FileListVideoIO::New();
  fileListIO2->SetFileName( input );
  fileListIO2->ReadImageInformation();

  // Loop through all frames to read with fileListIO2 and write with fileListIO
  for (unsigned int i = 0; i < inNumFrames; ++i)
    {

    // Set up a buffer to read to
    size_t bufferSize = fileListIO2->GetImageSizeInBytes();
    PixelType buffer[bufferSize];

    // Read into the buffer
    fileListIO2->Read(static_cast<void*>(buffer));

    // Write out the frame from the buffer
    fileListIO->Write(static_cast<void*>(buffer));

    }

  // Finish writing
  fileListIO2->FinishReadingOrWriting();
  fileListIO->FinishReadingOrWriting();

  //DEBUG -- Don't do this for now, need a better comparison method
  // Compare input and output videos to make sure they are identical
  //if (!videosMatch(input, output))
  //  {
  //  std::cerr << "Written video does not match input video" << std::endl;
  //  ret = EXIT_FAILURE;
  //  }

  //DEBUG
  //std::cout << "PIM1 = " << CV_FOURCC('P','I','M','1') << std::endl;
  //std::cout << "MJPG = " << CV_FOURCC('M','J','P','G') << std::endl;
  //std::cout << "MP42 = " << CV_FOURCC('M', 'P', '4', '2') << std::endl;
  //std::cout << "DIV3 = " << CV_FOURCC('D', 'I', 'V', '3') << std::endl;
  //std::cout << "DIVX = " << CV_FOURCC('D', 'I', 'V', 'X') << std::endl;
  //std::cout << "U263 = " << CV_FOURCC('U', '2', '6', '3') << std::endl;
  //std::cout << "I263 = " << CV_FOURCC('I', '2', '6', '3') << std::endl;
  //std::cout << "FLV1 = " << CV_FOURCC('F', 'L', 'V', '1') << std::endl;

*/

  std::cout<<"Done !"<<std::endl;
  return ret;
}

int itkFileListVideoIOTest ( int argc, char *argv[] )
{
  if (argc != 9)
    {
    std::cerr << "Usage: [Video Input] [Non-Video Input] [Video Output] [Webcam Output] "
      "[Width] [Height] [Num Frames] [FpS]" << std::endl;
    return EXIT_FAILURE;
    }

  return test_FileListVideoIO(argv[1], argv[2], argv[3], argv[4], atoi(argv[5]), atoi(argv[6]),
                            atoi(argv[7]), atof(argv[8]));
}

<commit_msg>ENH: Uncomment parts of FileListVideoIOTest<commit_after>#include <iostream>
#include <fstream>

#include "itkFileListVideoIO.h"
#include "itkImportImageFilter.h"
#include "itkRGBPixel.h"
#include "itkImageFileWriter.h"

// ITK typedefs
typedef itk::RGBPixel<char> PixelType;
typedef itk::ImportImageFilter<PixelType, 2> ImportFilterType;
typedef itk::Image<PixelType, 2> ImageType;
typedef itk::ImageFileWriter<ImageType> WriterType;

///////////////////////////////////////////////////////////////////////////////
// This tests all of the functionality of the FileListVideoIO
//
// Usage: [Video Input] [Non-Video Input] [Video Output] [Width] [Height]
//            [Num Frames] [FpS]

int test_FileListVideoIO ( char* input, char* nonVideoInput, char* output, char* cameraOutput,
                         unsigned int inWidth, unsigned int inHeight, unsigned long inNumFrames,
                         double inFpS )
{

  int ret = EXIT_SUCCESS;

  // Create the VideoIO
  itk::FileListVideoIO::Pointer fileListIO = itk::FileListVideoIO::New();

  //////
  // SetFileName
  //////

  fileListIO->SetFileName(input);

  //////
  // CanReadFile
  //////
  std::cout << "FileListVideoIO::CanReadFile..." << std::endl;

  // Test CanReadFile on good file
  if (!fileListIO->CanReadFile(input))
    {
    std::cerr << "Could not read " << input << std::endl;
    ret = EXIT_FAILURE;
    }

  // Test CanReadFile on non-existant file
  std::string nonExistantFile = "Bad/Path/To/Nothing";
  if (fileListIO->CanReadFile(nonExistantFile.c_str()))
    {
    std::cerr << "Should have failed to open \"" << nonExistantFile << "\"" << std::endl;
    ret = EXIT_FAILURE;
    }

  // Test CanReadFile on non-image file list
  if (fileListIO->CanReadFile(nonVideoInput))
    {
    std::cerr << "Should have failed to open \"" << nonVideoInput << "\"" << std::endl;
    ret = EXIT_FAILURE;
    }

  //////
  // ReadImageInformation
  //////
  std::cout << "FileListVideoIO::ReadImageInformation..." << std::endl;

  fileListIO->SetFileName(input);
  fileListIO->ReadImageInformation();
  bool infoSet = true;
  std::stringstream paramMessage;
  if (fileListIO->GetDimensions(0) != inWidth)
    {
    infoSet = false;
    paramMessage << "Width mismatch: (expected) " << inWidth << " != (got) "
      << fileListIO->GetDimensions(0) << std::endl;
    }
  if (fileListIO->GetDimensions(1) != inHeight)
    {
    infoSet = false;
    paramMessage << "Height mismatch: (expected) " << inHeight << " != (got) "
      << fileListIO->GetDimensions(1) << std::endl;
    }
  double epsilon = 0.0001;
  if (fileListIO->GetFpS() < inFpS - epsilon || fileListIO->GetFpS() > inFpS + epsilon)
    {
    infoSet = false;
    paramMessage << "FpS mismatch: (expected) " << inFpS << " != (got) " << fileListIO->GetFpS()
      << std::endl;
    }
  if (fileListIO->GetFrameTotal() != inNumFrames)
    {
    infoSet = false;
    paramMessage << "FrameTotal mismatch: (expected) " << inNumFrames << " != (got) "
      << fileListIO->GetFrameTotal() << std::endl;
    }

  if (!infoSet)
    {
    std::cerr << paramMessage.str();
    ret = EXIT_FAILURE;
    }

  //////
  // Read
  //////
  std::cout << "FileListVideoIO::Read..." << std::endl;
  std::cout << "Comparing all " << fileListIO->GetFrameTotal() << " frames" << std::endl;

  // Set up FileList capture
  CvCapture* capture = cvCaptureFromFile( fileListIO->GetFileName() );

  // Loop through all frames
  for (unsigned long i = 0; i < fileListIO->GetFrameTotal(); ++i)
    {
    if (!readCorrectly(fileListIO, capture, i))
      {
      std::cerr << "Failed to read frame " << i << " correctly" << std::endl;
      ret = EXIT_FAILURE;
      break;
      }
    }

  // Release capture
  cvReleaseCapture(&capture);

  //////
  // SetNextFrameToRead
  //////
  std::cout << "FileListVideoIO::SetNextFrameToRead" << std::endl;

  // Set up the buffer for the frame data so Read can be called
  size_t bufferSize = fileListIO->GetImageSizeInBytes();
  PixelType buffer[bufferSize];

  // try seeking to an I-Frame
  unsigned long seekFrame = fileListIO->GetIFrameInterval();
  if (!fileListIO->SetNextFrameToRead(seekFrame))
    {
    std::cerr << "Failed to seek to second I-Frame..." << std::endl;
    ret = EXIT_FAILURE;
    }

  // Read the frame data which updates the current frame correctly
  fileListIO->Read(static_cast<void*>(buffer));

  if (fileListIO->GetCurrentFrame() != seekFrame)
    {
    std::cerr << "Seek to I-Frame didn't end up in the right place" << std::endl;
    ret = EXIT_FAILURE;
    }

  // If there are I-Frame intervals, check behavior
  if (fileListIO->GetIFrameInterval() > 1)
    {

    // try seeking in-between I-Frames
    seekFrame = fileListIO->GetIFrameInterval()/2;
    if (!fileListIO->SetNextFrameToRead(seekFrame))
      {
      std::cerr << "Failed to seek between I-Frames" << std::endl;
      ret = EXIT_FAILURE;
      }
    fileListIO->Read(static_cast<void*>(buffer));
    if (fileListIO->GetCurrentFrame() != fileListIO->GetIFrameInterval())
      {
      std::cerr << "Seek between I-Frames didn't end up in the right place" << std::endl;
      ret = EXIT_FAILURE;
      }

    // try seeking past last I-Frame
    seekFrame = fileListIO->GetLastIFrame() + 1;
    if (fileListIO->SetNextFrameToRead(seekFrame))
      {
      std::cerr << "Did no fail when seeking past the last I-Frame" << std::endl;
      ret = EXIT_FAILURE;
      }

    }

  // Save the current parameters
  double fps = fileListIO->GetFpS();
  unsigned int width = fileListIO->GetDimensions(0);
  unsigned int height = fileListIO->GetDimensions(1);
  const char* fourCC = "MP42";
  unsigned int nChannels = fileListIO->GetNumberOfComponents();

  // Reset the VideoIO
  fileListIO->FinishReadingOrWriting();

  //////
  // Test reading from camera -- If webcam 0 can be opened, it will, otherwise this will be skipped
  //////

  // Check to see if camera is available
  if (fileListIO->CanReadCamera( 0 ))
    {

    std::cout << "FileListVideoIO::Read (from camera)..." << std::endl;

    // Set the reader to use the camera
    fileListIO->SetReadFromCamera();

    // Get information from the camera
    try
      {
      fileListIO->ReadImageInformation();
      }
    catch (itk::ExceptionObject e)
      {
      std::cerr << "Could not read information from the camera" << std::endl;
      ret = EXIT_FAILURE;
      }

    // set up buffer for camera
    size_t camBufferSize = fileListIO->GetImageSizeInBytes();
    PixelType camBuffer[camBufferSize];

    // Read from the camera
    try
      {
      fileListIO->Read(reinterpret_cast<void*>(camBuffer));
      }
    catch (itk::ExceptionObject e)
      {
      std::cerr << "Could not read from the camera" << std::endl;
      ret = EXIT_FAILURE;
      }

    // Get an ITK image from the camera's frame
    ImageType::Pointer cameraFrame = itkImageFromBuffer(fileListIO, camBuffer, camBufferSize);

    // Write out the ITK image -- DEBUG
    WriterType::Pointer writer = WriterType::New();
    writer->SetFileName(cameraOutput);
    writer->SetInput(cameraFrame);
    writer->Update();

    // Overwirte the file right away so we're not saving pictures of the tester!
    std::ofstream fs;
    fs.open(cameraOutput);
    fs << "EMPTY... deleted picture from webcam\n";
    fs.close();

    // Finish reading
    fileListIO->FinishReadingOrWriting();

    }

  /////////////////////////////////////////////////////////////////////////////
  // Test Writing
  //

  //////
  // SetWriterParameters
  //////
  std::cout << "FileListVIdeoIO::SetWriterParameters..." << std::endl;

  // Reset the saved parameters
  std::vector<unsigned int> size;
  size.push_back(width);
  size.push_back(height);
  fileListIO->SetWriterParameters(fps, size, fourCC, nChannels, itk::ImageIOBase::UCHAR);

  // Make sure they set correctly
  if (fileListIO->GetFpS() != fps || fileListIO->GetDimensions(0) != width ||
      fileListIO->GetDimensions(1) != height || fileListIO->GetNumberOfComponents() != nChannels)
    {
    std::cerr << "Didn't set writer parmeters correctly" << std::endl;
    ret = EXIT_FAILURE;
    }

  //////
  // CanWriteFile
  //////
  std::cout << "FileListVideoIO::CanWriteFile..." << std::endl;

  // Test CanWriteFile on good filename
  if (!fileListIO->CanWriteFile(output))
    {
    std::cerr << "CanWriteFile didn't return true correctly" << std::endl;
    ret = EXIT_FAILURE;
    }

  // Test CanWriteFile on bad filename
  if (fileListIO->CanWriteFile("asdfasdfasdf"))
    {
    std::cerr << "CanWriteFile should have failed for bad filename" << std::endl;
    ret = EXIT_FAILURE;
    }

  //////
  // Write
  //////
  std::cout << "FileListVIdeoIO::Write..." << std::endl;

  // Set output filename
  fileListIO->SetFileName( output );

  // Set up a second VideoIO to read while we're writing
  itk::FileListVideoIO::Pointer fileListIO2 = itk::FileListVideoIO::New();
  fileListIO2->SetFileName( input );
  fileListIO2->ReadImageInformation();

  // Loop through all frames to read with fileListIO2 and write with fileListIO
  for (unsigned int i = 0; i < inNumFrames; ++i)
    {

    // Set up a buffer to read to
    size_t bufferSize = fileListIO2->GetImageSizeInBytes();
    PixelType buffer[bufferSize];

    // Read into the buffer
    fileListIO2->Read(static_cast<void*>(buffer));

    // Write out the frame from the buffer
    fileListIO->Write(static_cast<void*>(buffer));

    }

  // Finish writing
  fileListIO2->FinishReadingOrWriting();
  fileListIO->FinishReadingOrWriting();

  //DEBUG -- Don't do this for now, need a better comparison method
  // Compare input and output videos to make sure they are identical
  //if (!videosMatch(input, output))
  //  {
  //  std::cerr << "Written video does not match input video" << std::endl;
  //  ret = EXIT_FAILURE;
  //  }

  //DEBUG
  //std::cout << "PIM1 = " << CV_FOURCC('P','I','M','1') << std::endl;
  //std::cout << "MJPG = " << CV_FOURCC('M','J','P','G') << std::endl;
  //std::cout << "MP42 = " << CV_FOURCC('M', 'P', '4', '2') << std::endl;
  //std::cout << "DIV3 = " << CV_FOURCC('D', 'I', 'V', '3') << std::endl;
  //std::cout << "DIVX = " << CV_FOURCC('D', 'I', 'V', 'X') << std::endl;
  //std::cout << "U263 = " << CV_FOURCC('U', '2', '6', '3') << std::endl;
  //std::cout << "I263 = " << CV_FOURCC('I', '2', '6', '3') << std::endl;
  //std::cout << "FLV1 = " << CV_FOURCC('F', 'L', 'V', '1') << std::endl;

  std::cout<<"Done !"<<std::endl;
  return ret;
}

int itkFileListVideoIOTest ( int argc, char *argv[] )
{
  if (argc != 9)
    {
    std::cerr << "Usage: [Video Input] [Non-Video Input] [Video Output] [Webcam Output] "
      "[Width] [Height] [Num Frames] [FpS]" << std::endl;
    return EXIT_FAILURE;
    }

  return test_FileListVideoIO(argv[1], argv[2], argv[3], argv[4], atoi(argv[5]), atoi(argv[6]),
                            atoi(argv[7]), atof(argv[8]));
}

<|endoftext|>


<commit_before>/*
 * Websocket Broadcaster
 */

#include <iostream>
#include <sstream>
#include <memory>
#include <map>

#include "include/server_ws.hpp"

using namespace std;

typedef SimpleWeb::SocketServer<SimpleWeb::WS> WsServer;

int main(int argc, char* argv[])
{
	if(argc!=2) {
		cout << "Usage : broadcaster <port>" << endl;
		return 0;
	}

	istringstream ss(argv[1]);
	int port;
	if(!(ss>>port))
		cerr << "Invalid Port number " << argv[1] << endl;

	WsServer server(port, 4);
	cout << "Waiting for connection on port " << port << endl;

	auto& sensor_epmap = server.endpoint["^/sensor/?$"];
	auto& command_epmap = server.endpoint["^/command/?$"];

	sensor_epmap.onmessage=[&server](shared_ptr<WsServer::Connection> connection, shared_ptr<WsServer::Message> message) {
		auto message_str = message->string();
		cout << "[" << connection.get() << "]" << "\tMessage received : " << message_str << endl;

		for(auto a_connection: server.get_connections()) {
			auto send_stream = make_shared<WsServer::SendStream>();
			if(a_connection.get()->path==connection.get()->path){
				*send_stream << message_str;
				//server.send is an asynchronous function
				server.send(a_connection, send_stream);
				cout << "---Broadcast data to " << connection.get() << endl;
			}
		}
	};

	sensor_epmap.onopen=[](shared_ptr<WsServer::Connection> connection) { cout << "* New connection : " << connection.get() << endl; };
	sensor_epmap.onclose=[](shared_ptr<WsServer::Connection> connection, int status, const string& reason) { cout << "* Close connection : " << connection.get() << " with status code " << status << endl; };
	sensor_epmap.onerror=[](shared_ptr<WsServer::Connection> connection, const boost::system::error_code& ec) { cout << "Server: Error in connection " << connection.get() << ". " << "Error: " << ec << ", error message: " << ec.message() << endl; };

	command_epmap.onopen=[](shared_ptr<WsServer::Connection> connection) { cout << "* New connection : " << connection.get() << endl; };
	command_epmap.onclose=[](shared_ptr<WsServer::Connection> connection, int status, const string& reason) { cout << "* Close connection : " << connection.get() << " with status code " << status << endl; };
	command_epmap.onerror=[](shared_ptr<WsServer::Connection> connection, const boost::system::error_code& ec) { cout << "Server: Error in connection " << connection.get() << ". " << "Error: " << ec << ", error message: " << ec.message() << endl; };

	command_epmap.onmessage=[&server](shared_ptr<WsServer::Connection> connection, shared_ptr<WsServer::Message> message) {
			auto message_str = message->string();
			cout << "[" << connection.get() << "]" << "\tMessage received : " << message_str << endl;

			for(auto a_connection: server.get_connections()) {
				auto send_stream = make_shared<WsServer::SendStream>();
				if(a_connection.get()->path==connection.get()->path){
					*send_stream << message_str;
					//server.send is an asynchronous function
					server.send(a_connection, send_stream);
					cout << "Broadcast data to " << connection.get() << endl;
				}
			}
		};
	thread server_thread([&server](){
		//Start WS-server
		server.start();
	});

	//Wait for server to start so that the client can connect
	this_thread::sleep_for(chrono::seconds(1));

	server_thread.join();

	return 0;
}
<commit_msg>bug fixed. message broadcasts to the other connections (no echo)<commit_after>/*
 * Websocket Broadcaster
 */

#include <iostream>
#include <sstream>
#include <memory>
#include <map>

#include "include/server_ws.hpp"

using namespace std;

typedef SimpleWeb::SocketServer<SimpleWeb::WS> WsServer;

int main(int argc, char* argv[])
{
	if(argc!=2) {
		cout << "Usage : broadcaster <port>" << endl;
		return 0;
	}

	istringstream ss(argv[1]);
	int port;
	if(!(ss>>port))
		cerr << "Invalid Port number " << argv[1] << endl;

	WsServer server(port, 4);
	cout << "Waiting for connection on port " << port << endl;

	auto& sensor_epmap = server.endpoint["^/sensor/?$"];
	auto& command_epmap = server.endpoint["^/command/?$"];

	sensor_epmap.onmessage=[&server](shared_ptr<WsServer::Connection> connection, shared_ptr<WsServer::Message> message) {
		auto message_str = message->string();
		cout << "[" << connection.get() << "]" << "\tMessage received : " << message_str << endl;

		for(auto a_connection: server.get_connections()) {
			auto send_stream = make_shared<WsServer::SendStream>();
			if(a_connection.get()->path==connection.get()->path && a_connection!=connection){
				*send_stream << message_str;
				//server.send is an asynchronous function
				server.send(a_connection, send_stream);
				cout << "---Broadcast data to " << connection.get() << endl;
			}
		}
	};

	sensor_epmap.onopen=[](shared_ptr<WsServer::Connection> connection) { cout << "* New connection : " << connection.get() << endl; };
	sensor_epmap.onclose=[](shared_ptr<WsServer::Connection> connection, int status, const string& reason) { cout << "* Close connection : " << connection.get() << " with status code " << status << endl; };
	sensor_epmap.onerror=[](shared_ptr<WsServer::Connection> connection, const boost::system::error_code& ec) { cout << "Server: Error in connection " << connection.get() << ". " << "Error: " << ec << ", error message: " << ec.message() << endl; };

	command_epmap.onopen=[](shared_ptr<WsServer::Connection> connection) { cout << "* New connection : " << connection.get() << endl; };
	command_epmap.onclose=[](shared_ptr<WsServer::Connection> connection, int status, const string& reason) { cout << "* Close connection : " << connection.get() << " with status code " << status << endl; };
	command_epmap.onerror=[](shared_ptr<WsServer::Connection> connection, const boost::system::error_code& ec) { cout << "Server: Error in connection " << connection.get() << ". " << "Error: " << ec << ", error message: " << ec.message() << endl; };

	command_epmap.onmessage=[&server](shared_ptr<WsServer::Connection> connection, shared_ptr<WsServer::Message> message) {
			auto message_str = message->string();
			cout << "[" << connection.get() << "]" << "\tMessage received : " << message_str << endl;

			for(auto a_connection: server.get_connections()) {
				auto send_stream = make_shared<WsServer::SendStream>();
				if(a_connection.get()->path==connection.get()->path && a_connection!=connection){
					*send_stream << message_str;
					//server.send is an asynchronous function
					server.send(a_connection, send_stream);
					cout << "Broadcast data to " << connection.get() << endl;
				}
			}
		};
	thread server_thread([&server](){
		//Start WS-server
		server.start();
	});

	//Wait for server to start so that the client can connect
	this_thread::sleep_for(chrono::seconds(1));

	server_thread.join();

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>param was using user length for strncpy, causing overflows<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: DllMain.cpp,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hro $ $Date: 2002-08-26 13:43:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <malloc.h>

HMODULE     UWINAPI_BaseAddress = NULL;
const CHAR  szUnicowsModuleName[] = "UNICOWS.DLL";

static HMODULE WINAPI _LoadUnicowsLibrary(VOID)
{
    CHAR        szModulePath[MAX_PATH];
    HMODULE     hModuleUnicows = NULL;

    // First search in the same directory as UWINAPI.DLL was loaded from. This is because
    // UWINAPI.DLL not always resides in the same directory as the actual application.

    if ( UWINAPI_BaseAddress && GetModuleFileNameA( UWINAPI_BaseAddress, szModulePath, MAX_PATH ) )
    {
        char    *lpLastBkSlash = strrchr( szModulePath, '\\' );

        if ( lpLastBkSlash )
        {
            size_t  nParentDirSize = lpLastBkSlash - szModulePath + 1;
            LPSTR   lpUnicowsModulePath = (LPTSTR)_alloca( nParentDirSize + sizeof(szUnicowsModuleName) );

            if ( lpUnicowsModulePath )
            {
                strncpy( lpUnicowsModulePath, szModulePath, nParentDirSize );
                strcat( lpUnicowsModulePath, szUnicowsModuleName );

                hModuleUnicows = LoadLibraryA( lpUnicowsModulePath );
            }
        }
    }

    // Search at the common places

    if ( !hModuleUnicows )
        hModuleUnicows = LoadLibraryA(szUnicowsModuleName);

    return hModuleUnicows;
}

static HMODULE WINAPI LoadUnicowsLibrary(VOID)
{
    HMODULE hModuleUnicows;
    int     idMsg = IDOK;

    do
    {
        hModuleUnicows = _LoadUnicowsLibrary();

        if ( !hModuleUnicows )
        {
            LPVOID lpMsgBuf;

            FormatMessageA(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,
                ERROR_DLL_NOT_FOUND /* GetLastError() */,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                (LPSTR)&lpMsgBuf,
                0,
                NULL
            );
            // Process any inserts in lpMsgBuf.
            CHAR szModuleFileName[MAX_PATH];

            GetModuleFileNameA( NULL, szModuleFileName, sizeof(szModuleFileName) );
            LPSTR   lpMessage = (LPSTR)_alloca( strlen( (LPCSTR)lpMsgBuf ) + sizeof(szUnicowsModuleName) + 1 );
            strcpy( lpMessage, (LPCSTR)lpMsgBuf );
            strcat( lpMessage, "\n" );
            strcat( lpMessage, szUnicowsModuleName );
            // Free the buffer.
            LocalFree( lpMsgBuf );
            // Display the string.
            idMsg = MessageBoxA( NULL, lpMessage,
                szModuleFileName, MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_TASKMODAL );

            if ( IDABORT == idMsg )
                TerminateProcess( GetCurrentProcess(), 255 );
        }
    } while ( !hModuleUnicows && IDRETRY == idMsg );

    return hModuleUnicows;
}

extern "C" FARPROC _PfnLoadUnicows = (FARPROC)LoadUnicowsLibrary;

extern "C" BOOL WINAPI DllMain( HMODULE hModule, DWORD dwReason, LPVOID lpReserved )
{
    switch ( dwReason )
    {
    case DLL_PROCESS_ATTACH:
        UWINAPI_BaseAddress = hModule;
        return DisableThreadLibraryCalls( hModule );
    default:
        return TRUE;
    }

}

<commit_msg>INTEGRATION: CWS sal01 (1.2.50); FILE MERGED 2003/04/04 13:28:13 hro 1.2.50.1: #107706# Fix library search mechanism<commit_after>/*************************************************************************
 *
 *  $RCSfile: DllMain.cpp,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-11 14:24:35 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <malloc.h>
#define _MBCS
#include <tchar.h>

HMODULE     UWINAPI_BaseAddress = NULL;
const CHAR  szUnicowsModuleName[] = "UNICOWS.DLL";

static HMODULE WINAPI _LoadUnicowsLibrary(VOID)
{
    CHAR        szModulePath[MAX_PATH];
    HMODULE     hModuleUnicows = NULL;

    // First search in the same directory as UWINAPI.DLL was loaded from. This is because
    // UWINAPI.DLL not always resides in the same directory as the actual application.

    if ( UWINAPI_BaseAddress && GetModuleFileNameA( UWINAPI_BaseAddress, szModulePath, MAX_PATH ) )
    {
        char    *lpLastBkSlash = _tcsrchr( szModulePath, '\\' );

        if ( lpLastBkSlash )
        {
            size_t  nParentDirSize = _tcsinc( lpLastBkSlash ) - szModulePath;
            LPSTR   lpUnicowsModulePath = (LPTSTR)_alloca( nParentDirSize + sizeof(szUnicowsModuleName) );

            if ( lpUnicowsModulePath )
            {
                _tcsncpy( lpUnicowsModulePath, szModulePath, nParentDirSize );
                _tcscpy( lpUnicowsModulePath + nParentDirSize, szUnicowsModuleName );

                hModuleUnicows = LoadLibraryA( lpUnicowsModulePath );
            }
        }
    }

    // Search at the common places

    if ( !hModuleUnicows )
        hModuleUnicows = LoadLibraryA(szUnicowsModuleName);

    return hModuleUnicows;
}

static HMODULE WINAPI LoadUnicowsLibrary(VOID)
{
    HMODULE hModuleUnicows;
    int     idMsg = IDOK;

    do
    {
        hModuleUnicows = _LoadUnicowsLibrary();

        if ( !hModuleUnicows )
        {
            LPVOID lpMsgBuf;

            FormatMessageA(
                FORMAT_MESSAGE_ALLOCATE_BUFFER |
                FORMAT_MESSAGE_FROM_SYSTEM |
                FORMAT_MESSAGE_IGNORE_INSERTS,
                NULL,
                ERROR_DLL_NOT_FOUND /* GetLastError() */,
                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
                (LPSTR)&lpMsgBuf,
                0,
                NULL
            );
            // Process any inserts in lpMsgBuf.
            CHAR szModuleFileName[MAX_PATH];

            GetModuleFileNameA( NULL, szModuleFileName, sizeof(szModuleFileName) );
            LPSTR   lpMessage = (LPSTR)_alloca( strlen( (LPCSTR)lpMsgBuf ) + sizeof(szUnicowsModuleName) + 1 );
            strcpy( lpMessage, (LPCSTR)lpMsgBuf );
            strcat( lpMessage, "\n" );
            strcat( lpMessage, szUnicowsModuleName );
            // Free the buffer.
            LocalFree( lpMsgBuf );
            // Display the string.
            idMsg = MessageBoxA( NULL, lpMessage,
                szModuleFileName, MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_TASKMODAL );

            if ( IDABORT == idMsg )
                TerminateProcess( GetCurrentProcess(), 255 );
        }
    } while ( !hModuleUnicows && IDRETRY == idMsg );

    return hModuleUnicows;
}

extern "C" FARPROC _PfnLoadUnicows = (FARPROC)LoadUnicowsLibrary;

extern "C" BOOL WINAPI DllMain( HMODULE hModule, DWORD dwReason, LPVOID lpReserved )
{
    switch ( dwReason )
    {
    case DLL_PROCESS_ATTACH:
        UWINAPI_BaseAddress = hModule;
        return DisableThreadLibraryCalls( hModule );
    default:
        return TRUE;
    }

}

<|endoftext|>


<commit_before>// Bindings
#include "PyROOT.h"
#include "Adapters.h"
#include "Utility.h"

// ROOT
#include "TInterpreter.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TDataType.h"
#include "TDataMember.h"
#include "TMethod.h"
#include "TFunction.h"
#include "TMethodArg.h"
#include "TList.h"
#include "TError.h"

//- helper -------------------------------------------------------------------
namespace PyROOT {
   inline std::string UnqualifiedTypeName( const std::string name ) {
      return TClassEdit::ShortType(
         TClassEdit::CleanType( name.c_str(), 1 ).c_str(), 5 );
   }
} // namespace PyROOT

//= TReturnTypeAdapter =======================================================
std::string PyROOT::TReturnTypeAdapter::Name( unsigned int mod ) const
{
// get the name of the return type that is being adapted
   std::string name = fName;

   if ( mod & Rflx::FINAL )
      name = Utility::ResolveTypedef( name );

   if ( ! ( mod & Rflx::QUALIFIED ) )
      name = UnqualifiedTypeName( fName );

   return name;
}

//= TMemberAdapter ===========================================================
PyROOT::TMemberAdapter::TMemberAdapter( TMethod* meth ) : fMember( meth )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethod*() const
{
// cast the adapter to a TMethod* being adapted, returns 0 on failure
   return dynamic_cast< TMethod* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TFunction* func ) : fMember( func )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TFunction*() const
{
// cast the adapter to a TFunction* being adapted, returns 0 on failure
   return dynamic_cast< TFunction* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TDataMember* mb ) : fMember( mb )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TDataMember*() const
{
// cast the adapter to a TDataMember* being adapted, returns 0 on failure
   return dynamic_cast< TDataMember* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TMethodArg* ma ) : fMember( ma )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethodArg*() const
{
// cast the adapter to a TMethodArg* being adapted, returns 0 on failure
   return dynamic_cast< TMethodArg* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::Name( unsigned int mod ) const
{
// Return name of the type described by fMember
   TMethodArg* arg = (TMethodArg*)*this;

   if ( arg ) {

      std::string name = arg->GetTypeNormalizedName();
      if ( mod & Rflx::FINAL )
         name = Utility::ResolveTypedef( name );

      if ( ! ( mod & Rflx::QUALIFIED ) )
         name = UnqualifiedTypeName( name );

      return name;

   } else if ( mod & Rflx::FINAL )
      return Utility::ResolveTypedef( fMember->GetName() );

   return fMember->GetName();
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstant() const
{
// test if the adapted member is a const method
   return fMember->Property() & kIsConstMethod;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstructor() const
{
// test if the adapted member is a const method
   return ((TFunction*)fMember) ? (((TFunction*)fMember)->ExtraProperty() & kIsConstructor) : kFALSE;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsEnum() const
{
// test if the adapted member is of an enum type
   return fMember->Property() & kIsEnum;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsPublic() const
{
// test if the adapted member represents an public (data) member
   return fMember->Property() & kIsPublic;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsStatic() const
{
// test if the adapted member represents a class (data) member
   return fMember->Property() & kIsStatic;
}

//____________________________________________________________________________
size_t PyROOT::TMemberAdapter::FunctionParameterSize( Bool_t required ) const
{
// get the total number of parameters that the adapted function/method takes
   TFunction* func = (TFunction*)fMember;
   if ( ! func )
      return 0;

   if ( required == true )
      return func->GetNargs() - func->GetNargsOpt();

   return func->GetNargs();
}

//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TMemberAdapter::FunctionParameterAt( size_t nth ) const
{
// get the type info of the function parameter at position nth
   return (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
}

//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterNameAt( size_t nth ) const
{
// get the formal name, if available, of the function parameter at position nth
   const char* name =
      ((TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth ))->GetName();

   if ( name )
      return name;
   return "";
}

//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterDefaultAt( size_t nth ) const
{
// get the default value, if available, of the function parameter at position nth
   TMethodArg* arg = (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
   const char* def = arg->GetDefault();

   if ( ! def )
      return "";

// special case for strings: "some value" -> ""some value"
   if ( strstr( Utility::ResolveTypedef( arg->GetTypeNormalizedName() ).c_str(), "char*" ) ) {
      std::string sdef = "\"";
      sdef += def;
      sdef += "\"";
      return sdef;
   }

   return def;
}

//____________________________________________________________________________
PyROOT::TReturnTypeAdapter PyROOT::TMemberAdapter::ReturnType() const
{
// get the return type of the wrapped function/method
   return TReturnTypeAdapter( ((TFunction*)fMember)->GetReturnTypeNormalizedName() );
}

//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TMemberAdapter::DeclaringScope() const
{
// get the declaring scope (class) of the wrapped function/method
   TMethod* method = (TMethod*)*this;
   if ( method )
      return method->GetClass();

// happens for free-standing functions (i.e. global scope)
   return std::string( "" );
}

//= TBaseAdapter =============================================================
std::string PyROOT::TBaseAdapter::Name() const
{
// get the name of the base class that is being adapted
   return fBase->GetName();
}

//= TScopeAdapter ============================================================
PyROOT::TScopeAdapter::TScopeAdapter( TClass* klass ) : fClass( klass )
{
// wrap a class (scope)
   if ( fClass.GetClass() != 0 )
      fName = fClass->GetName();
}

//____________________________________________________________________________
PyROOT::TScopeAdapter::TScopeAdapter( const std::string& name ) :
   fClass( name.c_str() ), fName( name )
{
   /* empty */
}

PyROOT::TScopeAdapter::TScopeAdapter( const TMemberAdapter& mb ) :
      fClass( mb.Name( Rflx::SCOPED ).c_str() ),
      fName( mb.Name( Rflx::QUALIFIED | Rflx::SCOPED ) )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TScopeAdapter::ByName( const std::string& name, Bool_t quiet )
{
// lookup a scope (class) by name
   Int_t oldEIL = gErrorIgnoreLevel;
   if ( quiet )
      gErrorIgnoreLevel = 3000;

   TClassRef klass( name.c_str() );
   if (klass.GetClass() && klass->GetListOfAllPublicMethods()->GetSize() == 0) {
   // sometimes I/O interferes, leading to zero methods: reload from CINT
      ClassInfo_t* cl = gInterpreter->ClassInfo_Factory( name.c_str() );
      if ( cl ) {
         gInterpreter->SetClassInfo( klass, kTRUE );
         gInterpreter->ClassInfo_Delete(cl);
      }
   }

   gErrorIgnoreLevel = oldEIL;

   return klass.GetClass();
}

//____________________________________________________________________________
std::string PyROOT::TScopeAdapter::Name( unsigned int mod ) const
{
// Return name of type described by fClass
   if ( ! fClass.GetClass() || ! fClass->Property() ) {
   // fundamental types have no class, and unknown classes have no property
      std::string name = fName;

      if ( mod & Rflx::FINAL )
         name = Utility::ResolveTypedef( name );

      if ( ! ( mod & Rflx::QUALIFIED ) )
         name = UnqualifiedTypeName( fName );

      return name;
   }

   std::string name = fClass->GetName();
   if ( mod & Rflx::FINAL )
      name = Utility::ResolveTypedef( name );

   if ( ! (mod & Rflx::SCOPED) ) {
   // remove scope from the name
      Int_t tpl_open = 0;
      for ( std::string::size_type pos = name.size() - 1; 0 < pos; --pos ) {
         std::string::value_type c = name[ pos ];

      // count '<' and '>' to be able to skip template contents
         if ( c == '>' )
            ++tpl_open;
         else if ( c == '<' )
            --tpl_open;
         else if ( tpl_open == 0 && c == ':' && 0 < pos && name[ pos-1 ] == ':' ) {
         // found scope, strip name from it
            name = name.substr( pos+1, std::string::npos );
            break;
         }
      }
   }

   return name;
}

//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::BaseSize() const
{
// get the total number of base classes that this class has
   if ( fClass.GetClass() && fClass->GetListOfBases() != 0 ) {
// CLING WORKAROUND (ROOT-5761)
      if ( Name().find( "shared_ptr" ) == 0 ) return 0;
// -- CLING WORKAROUND
      return fClass->GetListOfBases()->GetSize();
   }

   return 0;
}

//____________________________________________________________________________
PyROOT::TBaseAdapter PyROOT::TScopeAdapter::BaseAt( size_t nth ) const
{
// get the nth base of this class
   return (TBaseClass*)fClass->GetListOfBases()->At( nth );
}

//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::FunctionMemberSize() const
{
// get the total number of methods that this class has
   if ( fClass.GetClass() )
      return fClass->GetListOfMethods()->GetSize();

   return 0;
}

//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::FunctionMemberAt( size_t nth ) const
{
// get the nth method of this class
   return (TMethod*)fClass->GetListOfMethods()->At( nth );
}

//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::DataMemberSize() const
{
// get the total number of data members that this class has
   if ( fClass.GetClass() )
      return fClass->GetListOfDataMembers()->GetSize();

   return 0;
}

//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::DataMemberAt( size_t nth ) const
{
// get the nth data member of this class
   return (TDataMember*)fClass->GetListOfDataMembers()->At( nth );
}

//____________________________________________________________________________
PyROOT::TScopeAdapter::operator Bool_t() const
{
// check the validity of this scope (class)
   if ( fName.empty() )
      return false;

   Bool_t b = kFALSE;

   Int_t oldEIL = gErrorIgnoreLevel;
   gErrorIgnoreLevel = 3000;
   std::string scname = Name( Rflx::SCOPED );
   TClass* klass = TClass::GetClass( scname.c_str() );
   if ( klass && klass->GetClassInfo() )     // works for normal case w/ dict
      b = gInterpreter->ClassInfo_IsValid( klass->GetClassInfo() );
   else {      // special case for forward declared classes
      ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
      if ( ci ) {
         b = gInterpreter->ClassInfo_IsValid( ci );
         gInterpreter->ClassInfo_Delete( ci );    // we own the fresh class info
      }
   }
   gErrorIgnoreLevel = oldEIL;
   return b;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsComplete() const
{
// verify whether the dictionary of this class is fully available
   Bool_t b = kFALSE;

   std::string scname = Name( Rflx::SCOPED );
   TClass* klass = TClass::GetClass( scname.c_str() );
   if ( klass && klass->GetClassInfo() )     // works for normal case w/ dict
      b = gInterpreter->ClassInfo_IsLoaded( klass->GetClassInfo() );
   else {      // special case for forward declared classes
      ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
      if ( ci ) {
         b = gInterpreter->ClassInfo_IsLoaded( ci );
         gInterpreter->ClassInfo_Delete( ci );    // we own the fresh class info
      }
   }
   return b;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsClass() const
{
// test if this scope represents a class
   if ( fClass.GetClass() ) {
   // some inverted logic: we don't have a TClass, but a builtin will be recognized, so
   // if it is NOT a builtin, it is a class or struct (but may be missing dictionary)
      return (fClass->Property() & kIsClass) || ! (fClass->Property() & kIsFundamental);
   }

// no class can mean either is no class (i.e. builtin), or no dict but coming in
// through PyCintex/Reflex ... as a workaround, use TDataTypes that has a full
// enumeration of builtin types
   return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsStruct() const
{
// test if this scope represents a struct
   if ( fClass.GetClass() ) {
   // same logic as for IsClass() above ...
      return (fClass->Property() & kIsStruct) || ! (fClass->Property() & kIsFundamental);
   }

// same logic as for IsClass() above ...
   return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsNamespace() const
{
// test if this scope represents a namespace
   if ( fClass.GetClass() )
      return fClass->Property() & kIsNamespace;

   return kFALSE;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsAbstract() const
{
// test if this scope represents an abstract class
   if ( fClass.GetClass() )
      return fClass->Property() & kIsAbstract;   // assume set only for classes

   return kFALSE;
}
<commit_msg>make sure that we get an error report and not a crash<commit_after>// Bindings
#include "PyROOT.h"
#include "Adapters.h"
#include "Utility.h"

// ROOT
#include "TInterpreter.h"
#include "TBaseClass.h"
#include "TClass.h"
#include "TClassEdit.h"
#include "TDataType.h"
#include "TDataMember.h"
#include "TMethod.h"
#include "TFunction.h"
#include "TMethodArg.h"
#include "TList.h"
#include "TError.h"

//- helper -------------------------------------------------------------------
namespace PyROOT {
   inline std::string UnqualifiedTypeName( const std::string name ) {
      return TClassEdit::ShortType(
         TClassEdit::CleanType( name.c_str(), 1 ).c_str(), 5 );
   }
} // namespace PyROOT

//= TReturnTypeAdapter =======================================================
std::string PyROOT::TReturnTypeAdapter::Name( unsigned int mod ) const
{
// get the name of the return type that is being adapted
   std::string name = fName;

   if ( mod & Rflx::FINAL )
      name = Utility::ResolveTypedef( name );

   if ( ! ( mod & Rflx::QUALIFIED ) )
      name = UnqualifiedTypeName( fName );

   return name;
}

//= TMemberAdapter ===========================================================
PyROOT::TMemberAdapter::TMemberAdapter( TMethod* meth ) : fMember( meth )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethod*() const
{
// cast the adapter to a TMethod* being adapted, returns 0 on failure
   return dynamic_cast< TMethod* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TFunction* func ) : fMember( func )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TFunction*() const
{
// cast the adapter to a TFunction* being adapted, returns 0 on failure
   return dynamic_cast< TFunction* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TDataMember* mb ) : fMember( mb )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TDataMember*() const
{
// cast the adapter to a TDataMember* being adapted, returns 0 on failure
   return dynamic_cast< TDataMember* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::TMemberAdapter( TMethodArg* ma ) : fMember( ma )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TMemberAdapter::operator TMethodArg*() const
{
// cast the adapter to a TMethodArg* being adapted, returns 0 on failure
   return dynamic_cast< TMethodArg* >( const_cast< TDictionary* >( fMember ) );
}

//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::Name( unsigned int mod ) const
{
// Return name of the type described by fMember
   TMethodArg* arg = (TMethodArg*)*this;

   if ( arg ) {

      std::string name = arg->GetTypeNormalizedName();
      if ( mod & Rflx::FINAL )
         name = Utility::ResolveTypedef( name );

      if ( ! ( mod & Rflx::QUALIFIED ) )
         name = UnqualifiedTypeName( name );

      return name;

   } else if ( mod & Rflx::FINAL )
      return Utility::ResolveTypedef( fMember->GetName() );

   if ( fMember )
      return fMember->GetName();
   return "<unknown>";   // happens for classes w/o dictionary
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstant() const
{
// test if the adapted member is a const method
   return fMember->Property() & kIsConstMethod;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsConstructor() const
{
// test if the adapted member is a const method
   return ((TFunction*)fMember) ? (((TFunction*)fMember)->ExtraProperty() & kIsConstructor) : kFALSE;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsEnum() const
{
// test if the adapted member is of an enum type
   return fMember->Property() & kIsEnum;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsPublic() const
{
// test if the adapted member represents an public (data) member
   return fMember->Property() & kIsPublic;
}

//____________________________________________________________________________
Bool_t PyROOT::TMemberAdapter::IsStatic() const
{
// test if the adapted member represents a class (data) member
   return fMember->Property() & kIsStatic;
}

//____________________________________________________________________________
size_t PyROOT::TMemberAdapter::FunctionParameterSize( Bool_t required ) const
{
// get the total number of parameters that the adapted function/method takes
   TFunction* func = (TFunction*)fMember;
   if ( ! func )
      return 0;

   if ( required == true )
      return func->GetNargs() - func->GetNargsOpt();

   return func->GetNargs();
}

//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TMemberAdapter::FunctionParameterAt( size_t nth ) const
{
// get the type info of the function parameter at position nth
   return (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
}

//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterNameAt( size_t nth ) const
{
// get the formal name, if available, of the function parameter at position nth
   const char* name =
      ((TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth ))->GetName();

   if ( name )
      return name;
   return "";
}

//____________________________________________________________________________
std::string PyROOT::TMemberAdapter::FunctionParameterDefaultAt( size_t nth ) const
{
// get the default value, if available, of the function parameter at position nth
   TMethodArg* arg = (TMethodArg*)((TFunction*)fMember)->GetListOfMethodArgs()->At( nth );
   const char* def = arg->GetDefault();

   if ( ! def )
      return "";

// special case for strings: "some value" -> ""some value"
   if ( strstr( Utility::ResolveTypedef( arg->GetTypeNormalizedName() ).c_str(), "char*" ) ) {
      std::string sdef = "\"";
      sdef += def;
      sdef += "\"";
      return sdef;
   }

   return def;
}

//____________________________________________________________________________
PyROOT::TReturnTypeAdapter PyROOT::TMemberAdapter::ReturnType() const
{
// get the return type of the wrapped function/method
   return TReturnTypeAdapter( ((TFunction*)fMember)->GetReturnTypeNormalizedName() );
}

//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TMemberAdapter::DeclaringScope() const
{
// get the declaring scope (class) of the wrapped function/method
   TMethod* method = (TMethod*)*this;
   if ( method )
      return method->GetClass();

// happens for free-standing functions (i.e. global scope)
   return std::string( "" );
}

//= TBaseAdapter =============================================================
std::string PyROOT::TBaseAdapter::Name() const
{
// get the name of the base class that is being adapted
   return fBase->GetName();
}

//= TScopeAdapter ============================================================
PyROOT::TScopeAdapter::TScopeAdapter( TClass* klass ) : fClass( klass )
{
// wrap a class (scope)
   if ( fClass.GetClass() != 0 )
      fName = fClass->GetName();
}

//____________________________________________________________________________
PyROOT::TScopeAdapter::TScopeAdapter( const std::string& name ) :
   fClass( name.c_str() ), fName( name )
{
   /* empty */
}

PyROOT::TScopeAdapter::TScopeAdapter( const TMemberAdapter& mb ) :
      fClass( mb.Name( Rflx::SCOPED ).c_str() ),
      fName( mb.Name( Rflx::QUALIFIED | Rflx::SCOPED ) )
{
   /* empty */
}

//____________________________________________________________________________
PyROOT::TScopeAdapter PyROOT::TScopeAdapter::ByName( const std::string& name, Bool_t quiet )
{
// lookup a scope (class) by name
   Int_t oldEIL = gErrorIgnoreLevel;
   if ( quiet )
      gErrorIgnoreLevel = 3000;

   TClassRef klass( name.c_str() );
   if (klass.GetClass() && klass->GetListOfAllPublicMethods()->GetSize() == 0) {
   // sometimes I/O interferes, leading to zero methods: reload from CINT
      ClassInfo_t* cl = gInterpreter->ClassInfo_Factory( name.c_str() );
      if ( cl ) {
         gInterpreter->SetClassInfo( klass, kTRUE );
         gInterpreter->ClassInfo_Delete(cl);
      }
   }

   gErrorIgnoreLevel = oldEIL;

   return klass.GetClass();
}

//____________________________________________________________________________
std::string PyROOT::TScopeAdapter::Name( unsigned int mod ) const
{
// Return name of type described by fClass
   if ( ! fClass.GetClass() || ! fClass->Property() ) {
   // fundamental types have no class, and unknown classes have no property
      std::string name = fName;

      if ( mod & Rflx::FINAL )
         name = Utility::ResolveTypedef( name );

      if ( ! ( mod & Rflx::QUALIFIED ) )
         name = UnqualifiedTypeName( fName );

      return name;
   }

   std::string name = fClass->GetName();
   if ( mod & Rflx::FINAL )
      name = Utility::ResolveTypedef( name );

   if ( ! (mod & Rflx::SCOPED) ) {
   // remove scope from the name
      Int_t tpl_open = 0;
      for ( std::string::size_type pos = name.size() - 1; 0 < pos; --pos ) {
         std::string::value_type c = name[ pos ];

      // count '<' and '>' to be able to skip template contents
         if ( c == '>' )
            ++tpl_open;
         else if ( c == '<' )
            --tpl_open;
         else if ( tpl_open == 0 && c == ':' && 0 < pos && name[ pos-1 ] == ':' ) {
         // found scope, strip name from it
            name = name.substr( pos+1, std::string::npos );
            break;
         }
      }
   }

   return name;
}

//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::BaseSize() const
{
// get the total number of base classes that this class has
   if ( fClass.GetClass() && fClass->GetListOfBases() != 0 ) {
// CLING WORKAROUND (ROOT-5761)
      if ( Name().find( "shared_ptr" ) == 0 ) return 0;
// -- CLING WORKAROUND
      return fClass->GetListOfBases()->GetSize();
   }

   return 0;
}

//____________________________________________________________________________
PyROOT::TBaseAdapter PyROOT::TScopeAdapter::BaseAt( size_t nth ) const
{
// get the nth base of this class
   return (TBaseClass*)fClass->GetListOfBases()->At( nth );
}

//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::FunctionMemberSize() const
{
// get the total number of methods that this class has
   if ( fClass.GetClass() )
      return fClass->GetListOfMethods()->GetSize();

   return 0;
}

//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::FunctionMemberAt( size_t nth ) const
{
// get the nth method of this class
   return (TMethod*)fClass->GetListOfMethods()->At( nth );
}

//____________________________________________________________________________
size_t PyROOT::TScopeAdapter::DataMemberSize() const
{
// get the total number of data members that this class has
   if ( fClass.GetClass() )
      return fClass->GetListOfDataMembers()->GetSize();

   return 0;
}

//____________________________________________________________________________
PyROOT::TMemberAdapter PyROOT::TScopeAdapter::DataMemberAt( size_t nth ) const
{
// get the nth data member of this class
   return (TDataMember*)fClass->GetListOfDataMembers()->At( nth );
}

//____________________________________________________________________________
PyROOT::TScopeAdapter::operator Bool_t() const
{
// check the validity of this scope (class)
   if ( fName.empty() )
      return false;

   Bool_t b = kFALSE;

   Int_t oldEIL = gErrorIgnoreLevel;
   gErrorIgnoreLevel = 3000;
   std::string scname = Name( Rflx::SCOPED );
   TClass* klass = TClass::GetClass( scname.c_str() );
   if ( klass && klass->GetClassInfo() )     // works for normal case w/ dict
      b = gInterpreter->ClassInfo_IsValid( klass->GetClassInfo() );
   else {      // special case for forward declared classes
      ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
      if ( ci ) {
         b = gInterpreter->ClassInfo_IsValid( ci );
         gInterpreter->ClassInfo_Delete( ci );    // we own the fresh class info
      }
   }
   gErrorIgnoreLevel = oldEIL;
   return b;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsComplete() const
{
// verify whether the dictionary of this class is fully available
   Bool_t b = kFALSE;

   std::string scname = Name( Rflx::SCOPED );
   TClass* klass = TClass::GetClass( scname.c_str() );
   if ( klass && klass->GetClassInfo() )     // works for normal case w/ dict
      b = gInterpreter->ClassInfo_IsLoaded( klass->GetClassInfo() );
   else {      // special case for forward declared classes
      ClassInfo_t* ci = gInterpreter->ClassInfo_Factory( scname.c_str() );
      if ( ci ) {
         b = gInterpreter->ClassInfo_IsLoaded( ci );
         gInterpreter->ClassInfo_Delete( ci );    // we own the fresh class info
      }
   }
   return b;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsClass() const
{
// test if this scope represents a class
   if ( fClass.GetClass() ) {
   // some inverted logic: we don't have a TClass, but a builtin will be recognized, so
   // if it is NOT a builtin, it is a class or struct (but may be missing dictionary)
      return (fClass->Property() & kIsClass) || ! (fClass->Property() & kIsFundamental);
   }

// no class can mean either is no class (i.e. builtin), or no dict but coming in
// through PyCintex/Reflex ... as a workaround, use TDataTypes that has a full
// enumeration of builtin types
   return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsStruct() const
{
// test if this scope represents a struct
   if ( fClass.GetClass() ) {
   // same logic as for IsClass() above ...
      return (fClass->Property() & kIsStruct) || ! (fClass->Property() & kIsFundamental);
   }

// same logic as for IsClass() above ...
   return TDataType( Name( Rflx::FINAL | Rflx::SCOPED ).c_str() ).GetType() == kOther_t;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsNamespace() const
{
// test if this scope represents a namespace
   if ( fClass.GetClass() )
      return fClass->Property() & kIsNamespace;

   return kFALSE;
}

//____________________________________________________________________________
Bool_t PyROOT::TScopeAdapter::IsAbstract() const
{
// test if this scope represents an abstract class
   if ( fClass.GetClass() )
      return fClass->Property() & kIsAbstract;   // assume set only for classes

   return kFALSE;
}
<|endoftext|>


<commit_before>#include <controller_manager/controller_manager.hpp>
#include <bitbots_ros_control/wolfgang_hardware_interface.h>
#include <signal.h>
#include <thread>
#include <rclcpp/rclcpp.hpp>

sig_atomic_t volatile request_shutdown = 0;

void sigintHandler(int sig) {
  // gives other nodes some time to perform shutdown procedures with robot
  request_shutdown = 1;
}

int main(int argc, char *argv[]) {
  // register signal handler for ctrl-c that we use to request shutdown but give extra time for other nodes to finish
  signal(SIGINT, sigintHandler);

  // initialize ros
  rclcpp::init(argc, argv);
  rclcpp::NodeOptions options = rclcpp::NodeOptions().automatically_declare_parameters_from_overrides(true).allow_undeclared_parameters(true);
  rclcpp::Node::SharedPtr nh = rclcpp::Node::make_shared("wolfgang_hardware_interface", options);

  // create hardware interfaces
  bitbots_ros_control::WolfgangHardwareInterface hw(nh);
  if (!hw.init()) {
    RCLCPP_ERROR(nh->get_logger(), "Failed to initialize hardware interface.");
    return 1;
  }

  // diagnostics
  int diag_counter = 0;
  rclcpp::Publisher<diagnostic_msgs::msg::DiagnosticArray>::SharedPtr diagnostic_pub = nh->create_publisher<diagnostic_msgs::msg::DiagnosticArray>("/diagnostics", 10);
  diagnostic_msgs::msg::DiagnosticArray array_msg = diagnostic_msgs::msg::DiagnosticArray();
  std::vector<diagnostic_msgs::msg::DiagnosticStatus> array = std::vector<diagnostic_msgs::msg::DiagnosticStatus>();
  diagnostic_msgs::msg::DiagnosticStatus status = diagnostic_msgs::msg::DiagnosticStatus();
  // add prefix PS for pressure sensor to sort in diagnostic analyser
  status.name = "BUSBus";
  status.hardware_id = "Bus";

  // Start control loop
  rclcpp::Time current_time = nh->get_clock()->now();
  rclcpp::Duration period = nh->get_clock()->now() - current_time;
  bool first_update = true;
  float control_loop_hz = 500.0;
  nh->get_parameter("control_loop_hz", control_loop_hz);
  rclcpp::Rate rate(control_loop_hz);
  rclcpp::Time stop_time;
  bool shut_down_started = false;

  while (!request_shutdown || nh->get_clock()->now().seconds() - stop_time.seconds() < 5) {
    //
    // read
    //
    hw.read(current_time, period);
    period = nh->get_clock()->now() - current_time;
    current_time = nh->get_clock()->now();

    // period only makes sense after the first update
    // therefore, the controller manager is only updated starting with the second iteration
    if (first_update) {
      first_update = false;
    } else {
      //todo replaced controller part, if necessary
    }

    //
    // Write
    //
    hw.write(current_time, period);
    rclcpp::spin_some(nh->get_node_base_interface());
    rate.sleep();

    //
    // Diagnostics
    //
    // publish diagnostic messages each 100 frames
    if (diag_counter % 100 == 0) {
      // check if we are staying the correct cycle time. warning if we only get half
      array_msg.header.stamp = nh->get_clock()->now();
      if (rate.period() < std::chrono::nanoseconds (int(1e9 * (1 / control_loop_hz) * 2))) {
        status.level = diagnostic_msgs::msg::DiagnosticStatus::OK;
        status.message = "";
      } else {
        status.level = diagnostic_msgs::msg::DiagnosticStatus::WARN;
        status.message = "Bus runs not at specified frequency";
      }
      array = std::vector<diagnostic_msgs::msg::DiagnosticStatus>();
      array.push_back(status);
      array_msg.status = array;
      diagnostic_pub->publish(array_msg);
    }
    diag_counter++;

    if (request_shutdown && !shut_down_started) {
      stop_time = nh->get_clock()->now();
      shut_down_started = true;
      RCLCPP_INFO(nh->get_logger(), "Shutting down in 5 seconds");
    }
  }
  return 0;
}
<commit_msg>use event executor<commit_after>#include <controller_manager/controller_manager.hpp>
#include <bitbots_ros_control/wolfgang_hardware_interface.h>
#include <signal.h>
#include <thread>
#include <rclcpp/rclcpp.hpp>

sig_atomic_t volatile request_shutdown = 0;

void sigintHandler(int sig) {
  // gives other nodes some time to perform shutdown procedures with robot
  request_shutdown = 1;
}

int main(int argc, char *argv[]) {
  // register signal handler for ctrl-c that we use to request shutdown but give extra time for other nodes to finish
  signal(SIGINT, sigintHandler);

  // initialize ros
  rclcpp::init(argc, argv);
  rclcpp::NodeOptions options = rclcpp::NodeOptions().automatically_declare_parameters_from_overrides(true).allow_undeclared_parameters(true);
  rclcpp::Node::SharedPtr nh = rclcpp::Node::make_shared("wolfgang_hardware_interface", options);

  // create hardware interfaces
  bitbots_ros_control::WolfgangHardwareInterface hw(nh);
  if (!hw.init()) {
    RCLCPP_ERROR(nh->get_logger(), "Failed to initialize hardware interface.");
    return 1;
  }

  // diagnostics
  int diag_counter = 0;
  rclcpp::Publisher<diagnostic_msgs::msg::DiagnosticArray>::SharedPtr diagnostic_pub = nh->create_publisher<diagnostic_msgs::msg::DiagnosticArray>("/diagnostics", 10);
  diagnostic_msgs::msg::DiagnosticArray array_msg = diagnostic_msgs::msg::DiagnosticArray();
  std::vector<diagnostic_msgs::msg::DiagnosticStatus> array = std::vector<diagnostic_msgs::msg::DiagnosticStatus>();
  diagnostic_msgs::msg::DiagnosticStatus status = diagnostic_msgs::msg::DiagnosticStatus();
  // add prefix PS for pressure sensor to sort in diagnostic analyser
  status.name = "BUSBus";
  status.hardware_id = "Bus";

  // Start control loop
  rclcpp::Time current_time = nh->get_clock()->now();
  rclcpp::Duration period = nh->get_clock()->now() - current_time;
  bool first_update = true;
  float control_loop_hz = 500.0;
  nh->get_parameter("control_loop_hz", control_loop_hz);
  rclcpp::Rate rate(control_loop_hz);
  rclcpp::Time stop_time;
  bool shut_down_started = false;
  rclcpp::executors::EventsExecutor exec;
  exec.add_node(nh);

  while (!request_shutdown || nh->get_clock()->now().seconds() - stop_time.seconds() < 5) {
    //
    // read
    //
    hw.read(current_time, period);
    period = nh->get_clock()->now() - current_time;
    current_time = nh->get_clock()->now();

    // period only makes sense after the first update
    // therefore, the controller manager is only updated starting with the second iteration
    if (first_update) {
      first_update = false;
    } else {
      //todo replaced controller part, if necessary
    }

    //
    // Write
    //
    hw.write(current_time, period);
    exec.spin_some();
    rate.sleep();

    //
    // Diagnostics
    //
    // publish diagnostic messages each 100 frames
    if (diag_counter % 100 == 0) {
      // check if we are staying the correct cycle time. warning if we only get half
      array_msg.header.stamp = nh->get_clock()->now();
      if (rate.period() < std::chrono::nanoseconds (int(1e9 * (1 / control_loop_hz) * 2))) {
        status.level = diagnostic_msgs::msg::DiagnosticStatus::OK;
        status.message = "";
      } else {
        status.level = diagnostic_msgs::msg::DiagnosticStatus::WARN;
        status.message = "Bus runs not at specified frequency";
      }
      array = std::vector<diagnostic_msgs::msg::DiagnosticStatus>();
      array.push_back(status);
      array_msg.status = array;
      diagnostic_pub->publish(array_msg);
    }
    diag_counter++;

    if (request_shutdown && !shut_down_started) {
      stop_time = nh->get_clock()->now();
      shut_down_started = true;
      RCLCPP_INFO(nh->get_logger(), "Shutting down in 5 seconds");
    }
  }
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: introwin.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:31:20 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALFRAME_HXX
#include <vcl/salframe.hxx>
#endif

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _SV_SVDATA_HXX
#include <vcl/svdata.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif

#include <vcl/bitmap.hxx>
#include <impbmp.hxx>
#include <vcl/introwin.hxx>

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

void IntroWindow::ImplInitIntroWindowData()
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->mpIntroWindow = this;
}

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

IntroWindow::IntroWindow( ) :
    WorkWindow( WINDOW_INTROWINDOW )
{
    ImplInitIntroWindowData();
    WorkWindow::ImplInit( 0, WB_INTROWIN, NULL );
}

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

IntroWindow::~IntroWindow()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( pSVData->mpIntroWindow == this )
        pSVData->mpIntroWindow = NULL;
}

void IntroWindow::SetBackgroundBitmap( const Bitmap& rBitmap )
{
    if( ! rBitmap.IsEmpty() )
    {
        SalBitmap* pBmp = rBitmap.ImplGetImpBitmap()->ImplGetSalBitmap();
        ImplGetFrame()->SetBackgroundBitmap( pBmp );
    }
}
<commit_msg>INTEGRATION: CWS mergesvp (1.9.2); FILE MERGED 2007/07/04 15:32:40 pl 1.9.2.1: #i79023# header moving<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: introwin.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-24 10:20:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALFRAME_HXX
#include <vcl/salframe.hxx>
#endif

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _SV_SVDATA_HXX
#include <vcl/svdata.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <vcl/wrkwin.hxx>
#endif

#include <vcl/bitmap.hxx>
#include <vcl/impbmp.hxx>
#include <vcl/introwin.hxx>

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

void IntroWindow::ImplInitIntroWindowData()
{
    ImplSVData* pSVData = ImplGetSVData();
    pSVData->mpIntroWindow = this;
}

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

IntroWindow::IntroWindow( ) :
    WorkWindow( WINDOW_INTROWINDOW )
{
    ImplInitIntroWindowData();
    WorkWindow::ImplInit( 0, WB_INTROWIN, NULL );
}

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

IntroWindow::~IntroWindow()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( pSVData->mpIntroWindow == this )
        pSVData->mpIntroWindow = NULL;
}

void IntroWindow::SetBackgroundBitmap( const Bitmap& rBitmap )
{
    if( ! rBitmap.IsEmpty() )
    {
        SalBitmap* pBmp = rBitmap.ImplGetImpBitmap()->ImplGetSalBitmap();
        ImplGetFrame()->SetBackgroundBitmap( pBmp );
    }
}
<|endoftext|>


<commit_before><commit_msg>added exact distances for strafing and moving backwards.<commit_after><|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id: $ */

//_________________________________________________________________________
// Analysis task that executes the analysis classes
// that depend on the PartCorr frame, frame for Particle identification and correlations.
// Specially designed for calorimeters but also can be used for charged tracks
// Input of this task is a configuration file that contains all the settings of the analyis
//
// -- Author: Gustavo Conesa (INFN-LNF)

#include <cstdlib>

// --- Root ---
#include <TROOT.h>
#include <TInterpreter.h>
//#include <Riostream.h>

// --- Analysis ---
#include "AliAnalysisTaskParticleCorrelation.h"
#include "AliAnaPartCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
#include "AliAnalysisManager.h"

ClassImp(AliAnalysisTaskParticleCorrelation)

////////////////////////////////////////////////////////////////////////
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation():
  AliAnalysisTaskSE(),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName(0)
{
  // Default constructor
}

//_____________________________________________________
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name):
  AliAnalysisTaskSE(name),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName("")
{
  // Default constructor

  DefineOutput(1, TList::Class());

}

//_____________________________________________________
AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation()
{
  // Remove all pointers

  if(fOutputContainer){
    fOutputContainer->Clear() ;
    delete fOutputContainer ;
  }

}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects()
{
  // Create the output container
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - Begin\n");

  //Get list of aod arrays, add each aod array to analysis frame
  TClonesArray * array = 0;
  TList * list = fAna->GetAODBranchList();
  TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName();
  for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++){
    array = (TClonesArray*) list->At(iaod);
	if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file
	else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file
  }

  //Histograms container
  OpenFile(1);
  fOutputContainer = fAna->GetOutputContainer();
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - End\n");
}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Init()
{
  // Initialization

  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - Begin\n");

  // Call configuration file if specified

  if (fConfigName.Length()) {
    printf("AliAnalysisTaskParticleCorrelation::Init() - ### Configuration file is %s.C ###\n", fConfigName.Data());
	gROOT->LoadMacro(fConfigName+".C");
	fAna = (AliAnaPartCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
  }

  if(!fAna) {
	printf("AliAnalysisTaskParticleCorrelation::Init() - Analysis maker pointer not initialized, no analysis specified, STOP!\n");
	abort();
  }

  // Add different generator particles to PDG Data Base
  // to avoid problems when reading MC generator particles
  AliPDG::AddParticlesToPdgDataBase();

  // Initialise analysis
  fAna->Init();

  //Delta AOD
  if((fAna->GetReader())->GetDeltaAODFileName()!="")
	  AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName());

  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - End\n");

}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/)
{
  // Execute analysis for current event
  //
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - Begin\n");

   //Get the type of data, check if type is correct
  Int_t  datatype = fAna->GetReader()->GetDataType();
  if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
     datatype != AliCaloTrackReader::kMC){
    printf("AliAnalysisTaskParticleCorrelation::UserExec() - Wrong type of data\n");
    return ;
  }

  fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());

  //Process event
  fAna->ProcessEvent((Int_t) Entry(), CurrentFileName());
  //printf("AliAnalysisTaskParticleCorrelation::Current Event %d; Current File Name : %s\n",(Int_t) Entry(), CurrentFileName());
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - End\n");

  PostData(1, fOutputContainer);

}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/)
{
  // Terminate analysis
  // Do some plots

  // Get merged histograms from the output container
  TList *outputList = (TList*)GetOutputData(1);
  // Propagate histagrams to maker
  fAna->Terminate(outputList);

}

<commit_msg>Problem with overwriting memory corrected.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/
/* $Id: $ */

//_________________________________________________________________________
// Analysis task that executes the analysis classes
// that depend on the PartCorr frame, frame for Particle identification and correlations.
// Specially designed for calorimeters but also can be used for charged tracks
// Input of this task is a configuration file that contains all the settings of the analyis
//
// -- Author: Gustavo Conesa (INFN-LNF)

#include <cstdlib>

// --- Root ---
#include <TROOT.h>
#include <TInterpreter.h>
//#include <Riostream.h>

// --- Analysis ---
#include "AliAnalysisTaskParticleCorrelation.h"
#include "AliAnaPartCorrMaker.h"
#include "AliCaloTrackReader.h"
#include "AliPDG.h"
#include "AliAnalysisManager.h"

ClassImp(AliAnalysisTaskParticleCorrelation)

////////////////////////////////////////////////////////////////////////
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation():
  AliAnalysisTaskSE(),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName("")
{
  // Default constructor
}

//_____________________________________________________
AliAnalysisTaskParticleCorrelation::AliAnalysisTaskParticleCorrelation(const char* name):
  AliAnalysisTaskSE(name),
  fAna(0x0),
  fOutputContainer(0x0),
  fConfigName("")
{
  // Default constructor

  DefineOutput(1, TList::Class());

}

//_____________________________________________________
AliAnalysisTaskParticleCorrelation::~AliAnalysisTaskParticleCorrelation()
{
  // Remove all pointers

  if(fOutputContainer){
    fOutputContainer->Clear() ;
    delete fOutputContainer ;
  }

}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects()
{
  // Create the output container
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - Begin\n");

  //Get list of aod arrays, add each aod array to analysis frame
  TClonesArray * array = 0;
  TList * list = fAna->GetAODBranchList();
  TString deltaAODName = (fAna->GetReader())->GetDeltaAODFileName();
  for(Int_t iaod = 0; iaod < list->GetEntries(); iaod++){
    array = (TClonesArray*) list->At(iaod);
	if(deltaAODName!="") AddAODBranch("TClonesArray", &array, deltaAODName);//Put it in DeltaAOD file
	else AddAODBranch("TClonesArray", &array);//Put it in standard AOD file
  }

  //Histograms container
  OpenFile(1);
  fOutputContainer = fAna->GetOutputContainer();
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserCreateOutputObjects() - End\n");
}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Init()
{
  // Initialization

  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - Begin\n");

  // Call configuration file if specified

  if (fConfigName.Length()) {
    printf("AliAnalysisTaskParticleCorrelation::Init() - ### Configuration file is %s.C ###\n", fConfigName.Data());
	gROOT->LoadMacro(fConfigName+".C");
	fAna = (AliAnaPartCorrMaker*) gInterpreter->ProcessLine("ConfigAnalysis()");
  }

  if(!fAna) {
	printf("AliAnalysisTaskParticleCorrelation::Init() - Analysis maker pointer not initialized, no analysis specified, STOP !\n");
	abort();
  }

  // Add different generator particles to PDG Data Base
  // to avoid problems when reading MC generator particles
  AliPDG::AddParticlesToPdgDataBase();

  // Initialise analysis
  fAna->Init();

  //Delta AOD
  if((fAna->GetReader())->GetDeltaAODFileName()!="")
	  AliAnalysisManager::GetAnalysisManager()->RegisterExtraFile((fAna->GetReader())->GetDeltaAODFileName());

  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::Init() - End\n");

}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::UserExec(Option_t */*option*/)
{
  // Execute analysis for current event
  //
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - Begin\n");

   //Get the type of data, check if type is correct
  Int_t  datatype = fAna->GetReader()->GetDataType();
  if(datatype != AliCaloTrackReader::kESD && datatype != AliCaloTrackReader::kAOD &&
     datatype != AliCaloTrackReader::kMC){
    printf("AliAnalysisTaskParticleCorrelation::UserExec() - Wrong type of data\n");
    return ;
  }

  fAna->GetReader()->SetInputOutputMCEvent(InputEvent(), AODEvent(), MCEvent());

  //Process event
  fAna->ProcessEvent((Int_t) Entry(), CurrentFileName());
  //printf("AliAnalysisTaskParticleCorrelation::Current Event %d; Current File Name : %s\n",(Int_t) Entry(), CurrentFileName());
  if (DebugLevel() > 1) printf("AliAnalysisTaskParticleCorrelation::UserExec() - End\n");

  PostData(1, fOutputContainer);

}

//_____________________________________________________
void AliAnalysisTaskParticleCorrelation::Terminate(Option_t */*option*/)
{
  // Terminate analysis
  // Do some plots

  // Get merged histograms from the output container
  TList *outputList = (TList*)GetOutputData(1);
  // Propagate histagrams to maker
  fAna->Terminate(outputList);

}

<|endoftext|>