<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProgrammableSource.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkProgrammableSource.h"
#include "vtkPolyData.h"
#include "vtkStructuredGrid.h"
#include "vtkStructuredPoints.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"

// Construct programmable filter with empty execute method.
vtkProgrammableSource::vtkProgrammableSource()
{
  this->ExecuteMethod = NULL;
  this->ExecuteMethodArg = NULL;

  this->PolyData = vtkPolyData::New();
  this->PolyData->SetSource(this);

  this->StructuredPoints = vtkStructuredPoints::New();
  this->StructuredPoints->SetSource(this);

  this->StructuredGrid = vtkStructuredGrid::New();
  this->StructuredGrid->SetSource(this);

  this->UnstructuredGrid = vtkUnstructuredGrid::New();
  this->UnstructuredGrid->SetSource(this);

  this->RectilinearGrid = vtkRectilinearGrid::New();
  this->RectilinearGrid->SetSource(this);

  //This is done because filter superclass assumes output is defined.
  this->Output = this->PolyData;
}

vtkProgrammableSource::~vtkProgrammableSource()
{
  this->StructuredPoints->Delete();
  this->StructuredGrid->Delete();
  this->UnstructuredGrid->Delete();
  this->RectilinearGrid->Delete();
  this->PolyData->Delete();
  // Output should only be one of the above. We set it to NULL
  // so that we don't free it twice
  this->Output = NULL;

  // delete the current arg if there is one and a delete meth
  if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete))
    {
    (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg);
    }
}

// Specify the function to use to generate the source data. Note
// that the function takes a single (void *) argument.
void vtkProgrammableSource::SetExecuteMethod(void (*f)(void *), void *arg)
{
  if ( f != this->ExecuteMethod || arg != this->ExecuteMethodArg )
    {
    // delete the current arg if there is one and a delete meth
    if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete))
      {
      (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg);
      }
    this->ExecuteMethod = f;
    this->ExecuteMethodArg = arg;
    this->Modified();
    }
}

// Set the arg delete method. This is used to free user memory.
void vtkProgrammableSource::SetExecuteMethodArgDelete(void (*f)(void *))
{
  if ( f != this->ExecuteMethodArgDelete)
    {
    this->ExecuteMethodArgDelete = f;
    this->Modified();
    }
}

// Get the output as a concrete type. This method is typically used by the
// writer of the source function to get the output as a particular type (i.e.,
// it essentially does type casting). It is the users responsibility to know
// the correct type of the output data.
vtkPolyData *vtkProgrammableSource::GetPolyDataOutput()
{
  return this->PolyData;
}

// Get the output as a concrete type.
vtkStructuredPoints *vtkProgrammableSource::GetStructuredPointsOutput()
{
  return this->StructuredPoints;
}

// Get the output as a concrete type.
vtkStructuredGrid *vtkProgrammableSource::GetStructuredGridOutput()
{
  return this->StructuredGrid;
}

// Get the output as a concrete type.
vtkUnstructuredGrid *vtkProgrammableSource::GetUnstructuredGridOutput()
{
  return this->UnstructuredGrid;
}

// Get the output as a concrete type.
vtkRectilinearGrid *vtkProgrammableSource::GetRectilinearGridOutput()
{
  return this->RectilinearGrid;
}

void vtkProgrammableSource::Execute()
{
  vtkDebugMacro(<<"Executing programmable filter");

  // Now invoke the procedure, if specified.
  if ( this->ExecuteMethod != NULL )
    {
    (*this->ExecuteMethod)(this->ExecuteMethodArg);
    }
}

void vtkProgrammableSource::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkSource::PrintSelf(os,indent);

  os << indent << "Execute Time: " <<this->ExecuteTime.GetMTime() << "\n";

}

<commit_msg>ENH: uninitialized ivar.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProgrammableSource.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1998 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

=========================================================================*/
#include "vtkProgrammableSource.h"
#include "vtkPolyData.h"
#include "vtkStructuredGrid.h"
#include "vtkStructuredPoints.h"
#include "vtkUnstructuredGrid.h"
#include "vtkRectilinearGrid.h"

// Construct programmable filter with empty execute method.
vtkProgrammableSource::vtkProgrammableSource()
{
  this->ExecuteMethod = NULL;
  this->ExecuteMethodArg = NULL;
  this->ExecuteMethodArgDelete = NULL;

  this->PolyData = vtkPolyData::New();
  this->PolyData->SetSource(this);

  this->StructuredPoints = vtkStructuredPoints::New();
  this->StructuredPoints->SetSource(this);

  this->StructuredGrid = vtkStructuredGrid::New();
  this->StructuredGrid->SetSource(this);

  this->UnstructuredGrid = vtkUnstructuredGrid::New();
  this->UnstructuredGrid->SetSource(this);

  this->RectilinearGrid = vtkRectilinearGrid::New();
  this->RectilinearGrid->SetSource(this);

  //This is done because filter superclass assumes output is defined.
  this->Output = this->PolyData;
}

vtkProgrammableSource::~vtkProgrammableSource()
{
  this->StructuredPoints->Delete();
  this->StructuredGrid->Delete();
  this->UnstructuredGrid->Delete();
  this->RectilinearGrid->Delete();
  this->PolyData->Delete();
  // Output should only be one of the above. We set it to NULL
  // so that we don't free it twice
  this->Output = NULL;

  // delete the current arg if there is one and a delete meth
  if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete))
    {
    (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg);
    }
}

// Specify the function to use to generate the source data. Note
// that the function takes a single (void *) argument.
void vtkProgrammableSource::SetExecuteMethod(void (*f)(void *), void *arg)
{
  if ( f != this->ExecuteMethod || arg != this->ExecuteMethodArg )
    {
    // delete the current arg if there is one and a delete meth
    if ((this->ExecuteMethodArg)&&(this->ExecuteMethodArgDelete))
      {
      (*this->ExecuteMethodArgDelete)(this->ExecuteMethodArg);
      }
    this->ExecuteMethod = f;
    this->ExecuteMethodArg = arg;
    this->Modified();
    }
}

// Set the arg delete method. This is used to free user memory.
void vtkProgrammableSource::SetExecuteMethodArgDelete(void (*f)(void *))
{
  if ( f != this->ExecuteMethodArgDelete)
    {
    this->ExecuteMethodArgDelete = f;
    this->Modified();
    }
}

// Get the output as a concrete type. This method is typically used by the
// writer of the source function to get the output as a particular type (i.e.,
// it essentially does type casting). It is the users responsibility to know
// the correct type of the output data.
vtkPolyData *vtkProgrammableSource::GetPolyDataOutput()
{
  return this->PolyData;
}

// Get the output as a concrete type.
vtkStructuredPoints *vtkProgrammableSource::GetStructuredPointsOutput()
{
  return this->StructuredPoints;
}

// Get the output as a concrete type.
vtkStructuredGrid *vtkProgrammableSource::GetStructuredGridOutput()
{
  return this->StructuredGrid;
}

// Get the output as a concrete type.
vtkUnstructuredGrid *vtkProgrammableSource::GetUnstructuredGridOutput()
{
  return this->UnstructuredGrid;
}

// Get the output as a concrete type.
vtkRectilinearGrid *vtkProgrammableSource::GetRectilinearGridOutput()
{
  return this->RectilinearGrid;
}

void vtkProgrammableSource::Execute()
{
  vtkDebugMacro(<<"Executing programmable filter");

  // Now invoke the procedure, if specified.
  if ( this->ExecuteMethod != NULL )
    {
    (*this->ExecuteMethod)(this->ExecuteMethodArg);
    }
}

void vtkProgrammableSource::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkSource::PrintSelf(os,indent);

  os << indent << "Execute Time: " <<this->ExecuteTime.GetMTime() << "\n";

}

<|endoftext|>


<commit_before>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TORRENT_DEBUG_HPP_INCLUDED
#define TORRENT_DEBUG_HPP_INCLUDED

#include <string>
#include <fstream>
#include <iostream>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/lexical_cast.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

namespace libtorrent
{
	// DEBUG API

	namespace fs = boost::filesystem;

	struct logger
	{
		logger(fs::path const& filename, int instance, bool append = true)
		{
			fs::path dir(fs::complete("libtorrent_logs" + boost::lexical_cast<std::string>(instance)));
			if (!fs::exists(dir)) fs::create_directories(dir);
			m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out));
			*this << "\n\n\n*** starting log ***\n";
		}

		template <class T>
		logger& operator<<(T const& v)
		{
			m_file << v;
			m_file.flush();
			return *this;
		}

		std::ofstream m_file;
	};

}

#endif // TORRENT_DEBUG_HPP_INCLUDED

<commit_msg>fixes issue whith failure to create logs causes libtorrent to quit, fixes ticket #168<commit_after>/*

Copyright (c) 2003, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#ifndef TORRENT_DEBUG_HPP_INCLUDED
#define TORRENT_DEBUG_HPP_INCLUDED

#include <string>
#include <fstream>
#include <iostream>

#ifdef _MSC_VER
#pragma warning(push, 1)
#endif

#include <boost/lexical_cast.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>

#ifdef _MSC_VER
#pragma warning(pop)
#endif

namespace libtorrent
{
	// DEBUG API

	namespace fs = boost::filesystem;

	struct logger
	{
		logger(fs::path const& filename, int instance, bool append = true)
		{
			try
			{
				fs::path dir(fs::complete("libtorrent_logs" + boost::lexical_cast<std::string>(instance)));
				if (!fs::exists(dir)) fs::create_directories(dir);
				m_file.open((dir / filename).string().c_str(), std::ios_base::out | (append ? std::ios_base::app : std::ios_base::out));
				*this << "\n\n\n*** starting log ***\n";
			}
			catch (std::exception& e)
			{
				std::cerr << "failed to create log '" << filename << "': " << e.what() << std::endl;
			}
		}

		template <class T>
		logger& operator<<(T const& v)
		{
			m_file << v;
			m_file.flush();
			return *this;
		}

		std::ofstream m_file;
	};

}

#endif // TORRENT_DEBUG_HPP_INCLUDED

<|endoftext|>


<commit_before>#ifndef LIB_MART_COMMON_GUARD_NW_UNIX_H
#define LIB_MART_COMMON_GUARD_NW_UNIX_H

/**
 * unix.h (mart-netlib)
 *
 * Copyright (C) 2019: Michael Balszun <michael.balszun@mytum.de>
 *
 * This software may be modified and distributed under the terms
 * of the MIT license. See either the LICENSE file in the library's root
 * directory or http://opensource.org/licenses/MIT for details.
 *
 * @author: Michael Balszun <michael.balszun@mytum.de>
 * @brief:	This file provides a simple unix doamin socket implementation
 *
 */

#include "port_layer.hpp"

#include <im_str/im_str.hpp>

#include <mart-common/utils.h>

#include <filesystem>
#include <string_view>

#include "detail/socket_base.hpp"

namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {

class endpoint {
public:
	using abi_endpoint_type = mart::nw::socks::port_layer::SockaddrUn;
	static constexpr socks::Domain domain = socks::Domain::Local;

	constexpr endpoint() noexcept = default;
	endpoint( mba::im_zstr path ) noexcept
		: _addr( std::move( path ) )
	{
	}
	explicit endpoint( std::string_view path ) noexcept
		: _addr( mba::im_zstr(path) )
	{
	}
	explicit endpoint( const std::filesystem::path& path ) noexcept
		// TODO use "native()" on platforms that use u8 encoding natively
		: _addr( std::string_view( path.string() ) )
	{
	}

	explicit endpoint( const abi_endpoint_type& path ) noexcept
		: endpoint( std::string_view( path.path() ) )
	{
	}

	mba::im_str asString() const noexcept { return _addr; }
	mba::im_str toString() const noexcept { return _addr; }
	mba::im_str toStringEx() const noexcept { return _addr; }

	bool valid() const noexcept { return _addr.data() != nullptr; }

	abi_endpoint_type toSockAddrUn() const noexcept { return abi_endpoint_type( _addr.data(), _addr.size() ); }

	// for use in generic contexts
	abi_endpoint_type toSockAddr() const noexcept { return toSockAddrUn(); }

	friend bool operator==( const endpoint& l, const endpoint& r ) noexcept { return l._addr == r._addr; }
	friend bool operator!=( const endpoint& l, const endpoint& r ) noexcept { return l._addr != r._addr; }
	friend bool operator<( const endpoint& l, const endpoint& r ) noexcept { return l._addr < r._addr; }

private:
	mba::im_str _addr{};
};
} // namespace un
} // namespace mart::nw

namespace mart::nw::socks::detail {
extern template class DgramSocket<mart::nw::un::endpoint>;
}

namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {
using Socket = mart::nw::socks::detail::DgramSocket<endpoint>;
}
} // namespace mart::nw

#endif<commit_msg>[netlib] Make use of std::filesystem optional<commit_after>#ifndef LIB_MART_COMMON_GUARD_NW_UNIX_H
#define LIB_MART_COMMON_GUARD_NW_UNIX_H

/**
 * unix.h (mart-netlib)
 *
 * Copyright (C) 2019: Michael Balszun <michael.balszun@mytum.de>
 *
 * This software may be modified and distributed under the terms
 * of the MIT license. See either the LICENSE file in the library's root
 * directory or http://opensource.org/licenses/MIT for details.
 *
 * @author: Michael Balszun <michael.balszun@mytum.de>
 * @brief:	This file provides a simple unix doamin socket implementation
 *
 */

#include "port_layer.hpp"

#include <im_str/im_str.hpp>

#include <mart-common/utils.h>

#if __has_include(<filesystem>)
#include <filesystem>
#endif

#include <string_view>

#include "detail/socket_base.hpp"

namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {

class endpoint {
public:
	using abi_endpoint_type = mart::nw::socks::port_layer::SockaddrUn;
	static constexpr socks::Domain domain = socks::Domain::Local;

	constexpr endpoint() noexcept = default;
	endpoint( mba::im_zstr path ) noexcept
		: _addr( std::move( path ) )
	{
	}
	explicit endpoint( std::string_view path ) noexcept
		: _addr( mba::im_zstr(path) )
	{
	}

#ifdef __cpp_lib_filesystem
	explicit endpoint( const std::filesystem::path& path ) noexcept
		// TODO use "native()" on platforms that use u8 encoding natively
		: _addr( std::string_view( path.string() ) )
	{
	}
#endif

	explicit endpoint( const abi_endpoint_type& path ) noexcept
		: endpoint( std::string_view( path.path() ) )
	{
	}

	mba::im_str asString() const noexcept { return _addr; }
	mba::im_str toString() const noexcept { return _addr; }
	mba::im_str toStringEx() const noexcept { return _addr; }

	bool valid() const noexcept { return _addr.data() != nullptr; }

	abi_endpoint_type toSockAddrUn() const noexcept { return abi_endpoint_type( _addr.data(), _addr.size() ); }

	// for use in generic contexts
	abi_endpoint_type toSockAddr() const noexcept { return toSockAddrUn(); }

	friend bool operator==( const endpoint& l, const endpoint& r ) noexcept { return l._addr == r._addr; }
	friend bool operator!=( const endpoint& l, const endpoint& r ) noexcept { return l._addr != r._addr; }
	friend bool operator<( const endpoint& l, const endpoint& r ) noexcept { return l._addr < r._addr; }

private:
	mba::im_str _addr{};
};
} // namespace un
} // namespace mart::nw

namespace mart::nw::socks::detail {
extern template class DgramSocket<mart::nw::un::endpoint>;
}

namespace mart::nw {
// classes related to the unix sockets protocol in general
namespace un {
using Socket = mart::nw::socks::detail::DgramSocket<endpoint>;
}
} // namespace mart::nw

#endif<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/MetaProcessor/MetaProcessor.h"

#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"

#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/Support/Path.h"

#include <cstdio>

using namespace clang;

namespace cling {

  MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
    m_InputValidator.reset(new InputValidator());
  }

  MetaProcessor::~MetaProcessor() {}

  int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
    if (!input_text) { // null pointer, nothing to do.
      return 0;
    }
    if (!input_text[0]) { // empty string, nothing to do.
      return m_InputValidator->getExpectedIndent();
    }
    std::string input_line(input_text);
    if (input_line == "\n") { // just a blank line, nothing to do.
      return 0;
    }
    //  Check for and handle any '.' commands.
    bool was_meta = false;
    if ((input_line[0] == '.') && (input_line.size() > 1)) {
      was_meta = ProcessMeta(input_line, result);
    }
    if (was_meta) {
      return 0;
    }

    // Check if the current statement is now complete. If not, return to
    // prompt for more.
    if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
        == InputValidator::kIncomplete) {
      return m_InputValidator->getExpectedIndent();
    }

    //  We have a complete statement, compile and execute it.
    std::string input = m_InputValidator->TakeInput();
    m_InputValidator->Reset();
    m_Interp.processLine(input, m_Options.RawInput, result);

    return 0;
  }

  MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
    // Take interpreter's state
    m_Options.PrintingAST = m_Interp.isPrintingAST();
    return m_Options;
  }

  bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){

   llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
   const LangOptions& LO = m_Interp.getCI()->getLangOpts();
   Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
                  MB->getBufferStart(), MB->getBufferEnd());
   Token Tok;

   RawLexer.LexFromRawLexer(Tok);
   if (Tok.isNot(tok::period))
     return false;

   // Read the command
   RawLexer.LexFromRawLexer(Tok);
   if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
     return false;

   const std::string Command = GetRawTokenName(Tok);
   std::string Param;

   //  .q //Quits
   if (Command == "q") {
      m_Options.Quitting = true;
      return true;
   }
   //  .L <filename>   //  Load code fragment.
   else if (Command == "L") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (!Tok.isAnyIdentifier())
       return false;

     Param = GetRawTokenName(Tok);
     bool success = m_Interp.loadFile(Param);
     if (!success) {
       llvm::errs() << "Load file failed.\n";
     }
     return true;
   }
   //  .(x|X) <filename> //  Execute function from file, function name is
   //                    //  filename without extension.
   else if ((Command == "x") || (Command == "X")) {
     // TODO: add extensive checks the folder paths and filenames
     //RawLexer->LexFromRawLexer(Tok);
     //if (!Tok.isAnyIdentifier())
     //  return false;

     const char* CurPtr = RawLexer.getBufferLocation();;
     Token TmpTok;
     RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
     llvm::StringRef Param(CurPtr,
                           MB->getBufferSize() - (CurPtr - MB->getBufferStart()));
     llvm::sys::Path path(Param);

     if (!path.isValid())
       return false;

     bool success = executeFile(path.c_str(), result);
      if (!success) {
        llvm::errs()<< "Execute file failed.\n";
      }
      return true;
   }
   //  .printAST [0|1]  // Toggle the printing of the AST or if 1 or 0 is given
   //                   // enable or disable it.
   else if (Command == "printAST") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
       return false;

     if (Tok.is(tok::eof)) {
       // toggle:
       bool print = !m_Interp.isPrintingAST();
       m_Interp.enablePrintAST(print);
       llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
     } else {
       Param = GetRawTokenName(Tok);

       if (Param == "0")
         m_Interp.enablePrintAST(false);
       else
         m_Interp.enablePrintAST(true);
     }

     m_Options.PrintingAST = m_Interp.isPrintingAST();
     return true;
   }
   //  .rawInput [0|1]  // Toggle the raw input or if 1 or 0 is given enable
   //                   // or disable it.
   else if (Command == "rawInput") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
       return false;

     if (Tok.is(tok::eof)) {
       // toggle:
       m_Options.RawInput = !m_Options.RawInput;
       llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
     } else {
       Param = GetRawTokenName(Tok);

       if (Param == "0")
         m_Options.RawInput = false;
       else
         m_Options.RawInput = true;
     }
     return true;
   }
   //
   //  .U <filename>
   //
   //  Unload code fragment.
   //
   //if (cmd_char == 'U') {
   //   llvm::sys::Path path(param);
   //   if (path.isDynamicLibrary()) {
   //      std::cerr << "[i] Failure: cannot unload shared libraries yet!"
   //                << std::endl;
   //   }
   //   bool success = m_Interp.unloadFile(param);
   //   if (!success) {
   //      //fprintf(stderr, "Unload file failed.\n");
   //   }
   //   return true;
   //}
   //
   //  Unrecognized command.
   //
   //fprintf(stderr, "Unrecognized command.\n");
   else if (Command == "I") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);

     if (Tok.is(tok::eof))
       m_Interp.DumpIncludePath();
     else {
       // TODO: add extensive checks the folder paths and filenames
       const char* CurPtr = RawLexer.getBufferLocation();;
       Token TmpTok;
       RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
       llvm::StringRef Param(CurPtr,
                             MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
       llvm::sys::Path path(Param);

       if (path.isValid())
         m_Interp.AddIncludePath(path.c_str());
       else
         return false;
     }
     return true;
   }
  // Cancel the multiline input that has been requested
   else if (Command == "@") {
     m_InputValidator->Reset();
     return true;
   }
   // Enable/Disable DynamicExprTransformer
   else if (Command == "dynamicExtensions") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
       return false;

     if (Tok.is(tok::eof)) {
       // toggle:
       bool dynlookup = !m_Interp.isDynamicLookupEnabled();
       m_Interp.enableDynamicLookup(dynlookup);
       llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
     } else {
       Param = GetRawTokenName(Tok);

       if (Param == "0")
         m_Interp.enableDynamicLookup(false);
       else
         m_Interp.enableDynamicLookup(true);
     }

     return true;
   }
   // Print Help
   else if (Command == "help") {
     PrintCommandHelp();
     return true;
   }

   return false;
  }

  std::string MetaProcessor::GetRawTokenName(const Token& Tok) {

    assert(!Tok.needsCleaning() && "Not implemented yet");

    switch (Tok.getKind()) {
    default:
      return "";
    case tok::numeric_constant:
      return Tok.getLiteralData();
    case tok::raw_identifier:
      return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
    case tok::slash:
      return "/";
    }

  }

  void MetaProcessor::PrintCommandHelp() {
    llvm::outs() << "Cling meta commands usage\n";
    llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
    llvm::outs() << "\n";
    llvm::outs() << ".q\t\t\t\t - Exit the program\n";
    llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
    llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
    llvm::outs() << "function with signature ret_type filename(args)\n";
    llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
    llvm::outs() << "given - adds the path to the list with the include paths\n";
    llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
    llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
    llvm::outs() << "the execution results of the input\n";
    llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
    llvm::outs() << "dynamic scopes and the late binding\n";
    llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
    llvm::outs() << "corresponding AST nodes\n";
    llvm::outs() << ".help\t\t\t\t - Shows this information\n";
  }

  // Run a file: .x file[(args)]
  bool MetaProcessor::executeFile(const std::string& fileWithArgs,
                                  Value* result) {
    // Look for start of parameters:

    typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;

    StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
    if (pairFileArgs.second.empty()) {
      pairFileArgs.second = ")";
    }
    StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
    if (pairPathFile.second.empty()) {
       pairPathFile.second = pairPathFile.first;
    }
    StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');

    //fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());

    Interpreter::CompilationResult interpRes
       = m_Interp.processLine(std::string("#include \"")
                              + pairFileArgs.first.str()
                              + std::string("\""), true /*raw*/);

    if (interpRes != Interpreter::kFailure) {
       std::string expression = pairFuncExt.first.str()
          + "(" + pairFileArgs.second.str();
       interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
    }

    return (interpRes != Interpreter::kFailure);
  }
} // end namespace cling

<commit_msg>No need of cstio anymore<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/MetaProcessor/MetaProcessor.h"

#include "InputValidator.h"
#include "cling/Interpreter/Interpreter.h"

#include "clang/Basic/TargetInfo.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/Preprocessor.h"

#include "llvm/Support/Path.h"

using namespace clang;

namespace cling {

  MetaProcessor::MetaProcessor(Interpreter& interp) : m_Interp(interp) {
    m_InputValidator.reset(new InputValidator());
  }

  MetaProcessor::~MetaProcessor() {}

  int MetaProcessor::process(const char* input_text, Value* result /*=0*/) {
    if (!input_text) { // null pointer, nothing to do.
      return 0;
    }
    if (!input_text[0]) { // empty string, nothing to do.
      return m_InputValidator->getExpectedIndent();
    }
    std::string input_line(input_text);
    if (input_line == "\n") { // just a blank line, nothing to do.
      return 0;
    }
    //  Check for and handle any '.' commands.
    bool was_meta = false;
    if ((input_line[0] == '.') && (input_line.size() > 1)) {
      was_meta = ProcessMeta(input_line, result);
    }
    if (was_meta) {
      return 0;
    }

    // Check if the current statement is now complete. If not, return to
    // prompt for more.
    if (m_InputValidator->Validate(input_line, m_Interp.getCI()->getLangOpts())
        == InputValidator::kIncomplete) {
      return m_InputValidator->getExpectedIndent();
    }

    //  We have a complete statement, compile and execute it.
    std::string input = m_InputValidator->TakeInput();
    m_InputValidator->Reset();
    m_Interp.processLine(input, m_Options.RawInput, result);

    return 0;
  }

  MetaProcessorOpts& MetaProcessor::getMetaProcessorOpts() {
    // Take interpreter's state
    m_Options.PrintingAST = m_Interp.isPrintingAST();
    return m_Options;
  }

  bool MetaProcessor::ProcessMeta(const std::string& input_line, Value* result){

   llvm::MemoryBuffer* MB = llvm::MemoryBuffer::getMemBuffer(input_line);
   const LangOptions& LO = m_Interp.getCI()->getLangOpts();
   Lexer RawLexer(SourceLocation(), LO, MB->getBufferStart(),
                  MB->getBufferStart(), MB->getBufferEnd());
   Token Tok;

   RawLexer.LexFromRawLexer(Tok);
   if (Tok.isNot(tok::period))
     return false;

   // Read the command
   RawLexer.LexFromRawLexer(Tok);
   if (!Tok.isAnyIdentifier() && Tok.isNot(tok::at))
     return false;

   const std::string Command = GetRawTokenName(Tok);
   std::string Param;

   //  .q //Quits
   if (Command == "q") {
      m_Options.Quitting = true;
      return true;
   }
   //  .L <filename>   //  Load code fragment.
   else if (Command == "L") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (!Tok.isAnyIdentifier())
       return false;

     Param = GetRawTokenName(Tok);
     bool success = m_Interp.loadFile(Param);
     if (!success) {
       llvm::errs() << "Load file failed.\n";
     }
     return true;
   }
   //  .(x|X) <filename> //  Execute function from file, function name is
   //                    //  filename without extension.
   else if ((Command == "x") || (Command == "X")) {
     // TODO: add extensive checks the folder paths and filenames
     //RawLexer->LexFromRawLexer(Tok);
     //if (!Tok.isAnyIdentifier())
     //  return false;

     const char* CurPtr = RawLexer.getBufferLocation();;
     Token TmpTok;
     RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
     llvm::StringRef Param(CurPtr,
                           MB->getBufferSize() - (CurPtr - MB->getBufferStart()));
     llvm::sys::Path path(Param);

     if (!path.isValid())
       return false;

     bool success = executeFile(path.c_str(), result);
      if (!success) {
        llvm::errs()<< "Execute file failed.\n";
      }
      return true;
   }
   //  .printAST [0|1]  // Toggle the printing of the AST or if 1 or 0 is given
   //                   // enable or disable it.
   else if (Command == "printAST") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
       return false;

     if (Tok.is(tok::eof)) {
       // toggle:
       bool print = !m_Interp.isPrintingAST();
       m_Interp.enablePrintAST(print);
       llvm::errs()<< (print?"P":"Not p") << "rinting AST\n";
     } else {
       Param = GetRawTokenName(Tok);

       if (Param == "0")
         m_Interp.enablePrintAST(false);
       else
         m_Interp.enablePrintAST(true);
     }

     m_Options.PrintingAST = m_Interp.isPrintingAST();
     return true;
   }
   //  .rawInput [0|1]  // Toggle the raw input or if 1 or 0 is given enable
   //                   // or disable it.
   else if (Command == "rawInput") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
       return false;

     if (Tok.is(tok::eof)) {
       // toggle:
       m_Options.RawInput = !m_Options.RawInput;
       llvm::errs() << (m_Options.RawInput?"U":"Not u") << "sing raw input\n";
     } else {
       Param = GetRawTokenName(Tok);

       if (Param == "0")
         m_Options.RawInput = false;
       else
         m_Options.RawInput = true;
     }
     return true;
   }
   //
   //  .U <filename>
   //
   //  Unload code fragment.
   //
   //if (cmd_char == 'U') {
   //   llvm::sys::Path path(param);
   //   if (path.isDynamicLibrary()) {
   //      std::cerr << "[i] Failure: cannot unload shared libraries yet!"
   //                << std::endl;
   //   }
   //   bool success = m_Interp.unloadFile(param);
   //   if (!success) {
   //      //fprintf(stderr, "Unload file failed.\n");
   //   }
   //   return true;
   //}
   //
   //  Unrecognized command.
   //
   //fprintf(stderr, "Unrecognized command.\n");
   else if (Command == "I") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);

     if (Tok.is(tok::eof))
       m_Interp.DumpIncludePath();
     else {
       // TODO: add extensive checks the folder paths and filenames
       const char* CurPtr = RawLexer.getBufferLocation();;
       Token TmpTok;
       RawLexer.getAndAdvanceChar(CurPtr, TmpTok);
       llvm::StringRef Param(CurPtr,
                             MB->getBufferSize()-(CurPtr-MB->getBufferStart()));
       llvm::sys::Path path(Param);

       if (path.isValid())
         m_Interp.AddIncludePath(path.c_str());
       else
         return false;
     }
     return true;
   }
  // Cancel the multiline input that has been requested
   else if (Command == "@") {
     m_InputValidator->Reset();
     return true;
   }
   // Enable/Disable DynamicExprTransformer
   else if (Command == "dynamicExtensions") {
     // Check for params
     RawLexer.LexFromRawLexer(Tok);
     if (Tok.isNot(tok::numeric_constant) && Tok.isNot(tok::eof))
       return false;

     if (Tok.is(tok::eof)) {
       // toggle:
       bool dynlookup = !m_Interp.isDynamicLookupEnabled();
       m_Interp.enableDynamicLookup(dynlookup);
       llvm::errs() << (dynlookup?"U":"Not u") <<"sing dynamic extensions\n";
     } else {
       Param = GetRawTokenName(Tok);

       if (Param == "0")
         m_Interp.enableDynamicLookup(false);
       else
         m_Interp.enableDynamicLookup(true);
     }

     return true;
   }
   // Print Help
   else if (Command == "help") {
     PrintCommandHelp();
     return true;
   }

   return false;
  }

  std::string MetaProcessor::GetRawTokenName(const Token& Tok) {

    assert(!Tok.needsCleaning() && "Not implemented yet");

    switch (Tok.getKind()) {
    default:
      return "";
    case tok::numeric_constant:
      return Tok.getLiteralData();
    case tok::raw_identifier:
      return StringRef(Tok.getRawIdentifierData(), Tok.getLength()).str();
    case tok::slash:
      return "/";
    }

  }

  void MetaProcessor::PrintCommandHelp() {
    llvm::outs() << "Cling meta commands usage\n";
    llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
    llvm::outs() << "\n";
    llvm::outs() << ".q\t\t\t\t - Exit the program\n";
    llvm::outs() << ".L <filename>\t\t\t - Load file or library\n";
    llvm::outs() << ".(x|X) <filename>[args]\t\t - Same as .L and runs a ";
    llvm::outs() << "function with signature ret_type filename(args)\n";
    llvm::outs() << ".I [path]\t\t\t - Shows the include path. If a path is ";
    llvm::outs() << "given - adds the path to the list with the include paths\n";
    llvm::outs() << ".@ \t\t\t\t - Cancels and ignores the multiline input\n";
    llvm::outs() << ".rawInput [0|1]\t\t\t - Toggles the wrapping and printing ";
    llvm::outs() << "the execution results of the input\n";
    llvm::outs() << ".dynamicExtensions [0|1]\t - Toggles the use of the ";
    llvm::outs() << "dynamic scopes and the late binding\n";
    llvm::outs() << ".printAST [0|1]\t\t\t - Toggles the printing of input's ";
    llvm::outs() << "corresponding AST nodes\n";
    llvm::outs() << ".help\t\t\t\t - Shows this information\n";
  }

  // Run a file: .x file[(args)]
  bool MetaProcessor::executeFile(const std::string& fileWithArgs,
                                  Value* result) {
    // Look for start of parameters:

    typedef std::pair<llvm::StringRef,llvm::StringRef> StringRefPair;

    StringRefPair pairFileArgs = llvm::StringRef(fileWithArgs).split('(');
    if (pairFileArgs.second.empty()) {
      pairFileArgs.second = ")";
    }
    StringRefPair pairPathFile = pairFileArgs.first.rsplit('/');
    if (pairPathFile.second.empty()) {
       pairPathFile.second = pairPathFile.first;
    }
    StringRefPair pairFuncExt = pairPathFile.second.rsplit('.');

    //fprintf(stderr, "funcname: %s\n", pairFuncExt.first.data());

    Interpreter::CompilationResult interpRes
       = m_Interp.processLine(std::string("#include \"")
                              + pairFileArgs.first.str()
                              + std::string("\""), true /*raw*/);

    if (interpRes != Interpreter::kFailure) {
       std::string expression = pairFuncExt.first.str()
          + "(" + pairFileArgs.second.str();
       interpRes = m_Interp.processLine(expression, false /*not raw*/, result);
    }

    return (interpRes != Interpreter::kFailure);
  }
} // end namespace cling

<|endoftext|>


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

#ifndef POINT_SYMBOLIZER_HPP
#define POINT_SYMBOLIZER_HPP

#include <boost/shared_ptr.hpp>
#include "graphics.hpp"

namespace mapnik
{
    struct MAPNIK_DECL point_symbolizer
    {
	point_symbolizer(std::string const& file,
			 std::string const& type,
			 unsigned width,unsigned height);
	point_symbolizer(point_symbolizer const& rhs);
	ImageData32 const& get_data() const;
    private:
	boost::shared_ptr<ImageData32> symbol_;
    };
}

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

#ifndef POINT_SYMBOLIZER_HPP
#define POINT_SYMBOLIZER_HPP

#include <boost/shared_ptr.hpp>
#include "graphics.hpp"

namespace mapnik
{
    struct MAPNIK_DECL point_symbolizer
    {
        point_symbolizer(std::string const& file,
                         std::string const& type,
                         unsigned width,unsigned height);
        point_symbolizer(point_symbolizer const& rhs);
        ImageData32 const& get_data() const;
    private:
        boost::shared_ptr<ImageData32> symbol_;
    };
}

#endif // POINT_SYMBOLIZER_HPP
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
//  This class provides storage for event and track information which
//  are used for same-event as well as mixed-event analyses in AliAnalysisTaskKPFemto
//  Author: ramona.lea@cern.ch
//  was: maria.nicassio@cern.ch (derived and adapted from D. Gangadharan PWGCF/FEMTOSCOPY/Chaoticity/AliChaoticityEventCollection
//                                  and J. Salzwedel PWGCF/FEMTOSCOPY/V0LamAnalysis/AliAnalysisV0LamEventCollection)
//
////////////////////////////////////////////////////////////////////////////////

#include "AliAnalysisKPEventCollection.h"

//_____________________________________________________________________________
// Default constructor
AliReconstructedFirst::AliReconstructedFirst() :
  fPt(0),
  fEta(0),
  fTheta(0),
  fPhi(0),
  fRap(0),
  fCharge(0),
  fDCAxy(0),
  fDCAz(0),
  isTOFmismatch(kFALSE),
  isMCptc(kFALSE),
  fMCcode(0),
  fPDGcode(0),
  fMCmumIdx(0),
  fMCmumPDG(0),
  fMCgrandmumIdx(0),
  fMCgrandmumPDG(0),
  index(0),
  mcFirstOriginType(kUnassigned),
  doSkipOver(kFALSE),
  fEtaS(0),
  fPhiS(0),
  isP(0),
  isaP(0)
{
  // std::fill(fMomentum,fMomentum+3,0.);
  // std::fill(fMomentumTruth,fMomentumTruth+3,0.);
  // std::fill(fShiftedGlobalPosition,fShiftedGlobalPosition+3,0.);
  // std::fill(iptoPV,iptoPV+2,0.);
  // std::fill(nSigmaFirstTPC,nSigmaFirstTPC+5,0.);
  // std::fill(nSigmaFirstTOF,nSigmaFirstTOF+5,0.);

  // copy constructor
}

//_____________________________________________________________________________

AliReconstructedSecond::AliReconstructedSecond() :
  sPt(0),
  sEta(0),
  sTheta(0),
  sPhi(0),
  sRap(0),
  sCharge(0),
  sDCAxy(0),
  sDCAz(0),
  isTOFmismatch(kFALSE),
  isMCptc(kFALSE),
  sMCcode(0),
  sPDGcode(0),
  sMCmumIdx(0),
  sMCmumPDG(0),
  sMCgrandmumIdx(0),
  sMCgrandmumPDG(0),
  index(0),
  mcSecondOriginType(kUnassigned),
  doSkipOver(kFALSE),
  sEtaS(0),
  sPhiS(0),
  isP(0),
  isaP(0)
{
  // std::fill(sMomentum,sMomentum+3,0.);
  // std::fill(sMomentumTruth,sMomentumTruth+3,0.);
  // std::fill(sShiftedGlobalPosition,sShiftedGlobalPosition+3,0.);
  // std::fill(iptoPV,iptoPV+2,0.);
  // std::fill(nSigmaSecondTPC,nSigmaSecondTPC+5,0.);
  // std::fill(nSigmaSecondTOF,nSigmaSecondTOF+5,0.);

  // Default constructor

}
//_____________________________________________________________________________

AliReconstructedFirst::~AliReconstructedFirst()

{

}

//_____________________________________________________________________________

AliReconstructedSecond::~AliReconstructedSecond()

 {

 }

//_____________________________________________________________________________

AliAnalysisKPEvent::AliAnalysisKPEvent():
  fNumberCandidateFirst(0),
  fNumberCandidateSecond(0),
  fReconstructedFirst(0x0),
  fReconstructedSecond(0x0)
{
  //Default constructor
}
//_____________________________________________________________________________
AliAnalysisKPEvent::~AliAnalysisKPEvent()
{
  //Destructor

  if(fReconstructedFirst){
    delete fReconstructedFirst;
    fReconstructedFirst= NULL;
  }
  if(fReconstructedSecond){
    delete fReconstructedSecond;
    fReconstructedSecond= NULL;
  }

}
//_____________________________________________________________________________
AliAnalysisKPEventCollection::AliAnalysisKPEventCollection() :
  fEvt(0x0),
  fifo(0)
{

}

//______________________________________________________________________________

AliAnalysisKPEventCollection::~AliAnalysisKPEventCollection(){

  for(Int_t i = 0; i < fifo; i++){
     if((fEvt + i)->fReconstructedFirst != NULL){
       delete [] (fEvt + i)->fReconstructedFirst;
     }
     if((fEvt + i)->fReconstructedSecond != NULL){
       delete [] (fEvt + i)->fReconstructedSecond;
     }
   }
   delete [] fEvt;fEvt = NULL;
 }

//_____________________________________________________________________________

AliAnalysisKPEventCollection::AliAnalysisKPEventCollection(Short_t eventBuffSize, Int_t maxFirstMult, Int_t maxSecondMult) : fEvt(0x0), fifo(0) {

  SetBuffSize(eventBuffSize);

  fEvt = new AliAnalysisKPEvent[fifo];  //allocate pointer array of AliAnalysisKPEvents

  for(Int_t ii = 0; ii < fifo; ii++){ //Initialize particle table pointers to NULL

    (fEvt + ii)->fReconstructedFirst = NULL;

    (fEvt + ii)->fNumberCandidateFirst = 0;

    (fEvt + ii)->fReconstructedFirst = new AliReconstructedFirst[maxFirstMult];

    (fEvt + ii)->fReconstructedSecond = NULL;

    (fEvt + ii)->fNumberCandidateSecond = 0;

    (fEvt + ii)->fReconstructedSecond = new AliReconstructedSecond[maxSecondMult];

  }

}

//_____________________________________________________________________________
void AliAnalysisKPEventCollection::FifoShift() { //Shift elements in FIFO by one and clear last element in FIFO

  for(unsigned short i=fifo-1 ; i > 0; i--) {

    for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateFirst; j++){

      (fEvt + i)->fReconstructedFirst[j] = (fEvt + i-1)->fReconstructedFirst[j];

    }

    (fEvt + i)->fNumberCandidateFirst = (fEvt + i-1)->fNumberCandidateFirst;

    for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateSecond; j++){

      (fEvt + i)->fReconstructedSecond[j] = (fEvt + i-1)->fReconstructedSecond[j];

    }

    (fEvt + i)->fNumberCandidateSecond = (fEvt + i-1)->fNumberCandidateSecond;

    for(Int_t j=0; j<3; j++){

      (fEvt + i)->fPrimaryVertex[j] = (fEvt + i-1)->fPrimaryVertex[j];

    }

  }

   (fEvt)->fNumberCandidateFirst=0;
   (fEvt)->fNumberCandidateSecond=0;

   for(Int_t j=0; j<3; j++) {

     (fEvt)->fPrimaryVertex[j] = 0.;

   }

}

<commit_msg>Additional improvement to the event collection task<commit_after>////////////////////////////////////////////////////////////////////////////////
//
//  This class provides storage for event and track information which
//  are used for same-event as well as mixed-event analyses in AliAnalysisTaskKPFemto
//  Author: ramona.lea@cern.ch
//  was: maria.nicassio@cern.ch (derived and adapted from D. Gangadharan PWGCF/FEMTOSCOPY/Chaoticity/AliChaoticityEventCollection
//                                  and J. Salzwedel PWGCF/FEMTOSCOPY/V0LamAnalysis/AliAnalysisV0LamEventCollection)
//
////////////////////////////////////////////////////////////////////////////////

#include "AliAnalysisKPEventCollection.h"

//_____________________________________________________________________________
// Default constructor
AliReconstructedFirst::AliReconstructedFirst() :
  fPt(0),
  fEta(0),
  fTheta(0),
  fPhi(0),
  fRap(0),
  fCharge(0),
  fDCAxy(0),
  fDCAz(0),
  isTOFmismatch(kFALSE),
  isMCptc(kFALSE),
  fMCcode(0),
  fPDGcode(0),
  fMCmumIdx(0),
  fMCmumPDG(0),
  fMCgrandmumIdx(0),
  fMCgrandmumPDG(0),
  index(0),
  mcFirstOriginType(kUnassigned),
  doSkipOver(kFALSE),
  fEtaS(0),
  fPhiS(0),
  isP(0),
  isaP(0)
{
  // std::fill(fMomentum,fMomentum+3,0.);
  // std::fill(fMomentumTruth,fMomentumTruth+3,0.);
  // std::fill(fShiftedGlobalPosition,fShiftedGlobalPosition+3,0.);
  // std::fill(iptoPV,iptoPV+2,0.);
  // std::fill(nSigmaFirstTPC,nSigmaFirstTPC+5,0.);
  // std::fill(nSigmaFirstTOF,nSigmaFirstTOF+5,0.);

  // default constructor constructor
}
//_____________________________________________________________________________
AliReconstructedFirst::AliReconstructedFirst(const AliReconstructedFirst &obj) :
  fPt(obj.fPt),
  fEta(obj.fEta),
  fTheta(obj.fTheta),
  fPhi(obj.fPhi),
  fRap(obj.fRap),
  fCharge(obj.fCharge),
  fDCAxy(obj.fDCAxy),
  fDCAz(obj.fDCAz),
  isTOFmismatch(obj.isTOFmismatch),
  isMCptc(obj.isMCptc),
  fMCcode(obj.fMCcode),
  fPDGcode(obj.fPDGcode),
  fMCmumIdx(obj.fMCmumIdx),
  fMCmumPDG(obj.fMCmumPDG),
  fMCgrandmumIdx(obj.fMCgrandmumIdx),
  fMCgrandmumPDG(obj.fMCgrandmumPDG),
  index(obj.index),
  mcFirstOriginType(kUnassigned),
  doSkipOver(obj.doSkipOver),
  fEtaS(obj.fEtaS),
  fPhiS(obj.fPhiS),
  isP(obj.isP),
  isaP(obj.isaP)
{
  // copy constructor
}
//_____________________________________________________________________________
AliReconstructedFirst &AliReconstructedFirst::operator=(const AliReconstructedFirst &obj)
{
  //Assignment operator
  if(this == &obj) return *this;

  fPt            = obj.fPt;
  fEta           = obj.fEta;
  fTheta         = obj.fTheta;
  fPhi           = obj.fPhi;
  fRap           = obj.fRap;
  fCharge        = obj.fCharge;
  fDCAxy         = obj.fDCAxy;
  fDCAz          = obj.fDCAz;
  isTOFmismatch  = obj.isTOFmismatch;
  isMCptc        = obj.isMCptc;
  fMCcode        = obj.fMCcode;
  fPDGcode       = obj.fPDGcode;
  fMCmumIdx      = obj.fMCmumIdx;
  fMCmumPDG      = obj.fMCmumPDG;
  fMCgrandmumIdx = obj.fMCgrandmumIdx;
  fMCgrandmumPDG = obj.fMCgrandmumPDG;
  index          = obj.index;
  mcFirstOriginType = kUnassigned;
  doSkipOver     = obj.doSkipOver;
  fEtaS          = obj.fEtaS;
  fPhiS          = obj.fPhiS;
  isP            = obj.isP;
  isaP           = obj.isaP;

  return (*this);

}

//_____________________________________________________________________________

AliReconstructedFirst::~AliReconstructedFirst()

{

}

//_____________________________________________________________________________

AliReconstructedSecond::AliReconstructedSecond() :
  sPt(0),
  sEta(0),
  sTheta(0),
  sPhi(0),
  sRap(0),
  sCharge(0),
  sDCAxy(0),
  sDCAz(0),
  isTOFmismatch(kFALSE),
  isMCptc(kFALSE),
  sMCcode(0),
  sPDGcode(0),
  sMCmumIdx(0),
  sMCmumPDG(0),
  sMCgrandmumIdx(0),
  sMCgrandmumPDG(0),
  index(0),
  mcSecondOriginType(kUnassigned),
  doSkipOver(kFALSE),
  sEtaS(0),
  sPhiS(0),
  isP(0),
  isaP(0)
{
  // std::fill(sMomentum,sMomentum+3,0.);
  // std::fill(sMomentumTruth,sMomentumTruth+3,0.);
  // std::fill(sShiftedGlobalPosition,sShiftedGlobalPosition+3,0.);
  // std::fill(iptoPV,iptoPV+2,0.);
  // std::fill(nSigmaSecondTPC,nSigmaSecondTPC+5,0.);
  // std::fill(nSigmaSecondTOF,nSigmaSecondTOF+5,0.);

  // Default constructor

}
//_____________________________________________________________________________
AliReconstructedSecond::AliReconstructedSecond(const AliReconstructedSecond &obj) :
  sPt(obj.sPt),
  sEta(obj.sEta),
  sTheta(obj.sTheta),
  sPhi(obj.sPhi),
  sRap(obj.sRap),
  sCharge(obj.sCharge),
  sDCAxy(obj.sDCAxy),
  sDCAz(obj.sDCAz),
  isTOFmismatch(obj.isTOFmismatch),
  isMCptc(obj.isMCptc),
  sMCcode(obj.sMCcode),
  sPDGcode(obj.sPDGcode),
  sMCmumIdx(obj.sMCmumIdx),
  sMCmumPDG(obj.sMCmumPDG),
  sMCgrandmumIdx(obj.sMCgrandmumIdx),
  sMCgrandmumPDG(obj.sMCgrandmumPDG),
  index(obj.index),
  mcSecondOriginType(kUnassigned),
  doSkipOver(obj.doSkipOver),
  sEtaS(obj.sEtaS),
  sPhiS(obj.sPhiS),
  isP(obj.isP),
  isaP(obj.isaP)
{
  // copy constructor
}
//_____________________________________________________________________________
AliReconstructedSecond &AliReconstructedSecond::operator=(const AliReconstructedSecond &obj)
{
  //Assignment operator
  if(this == &obj) return *this;

  sPt            = obj.sPt;
  sEta           = obj.sEta;
  sTheta         = obj.sTheta;
  sPhi           = obj.sPhi;
  sRap           = obj.sRap;
  sCharge        = obj.sCharge;
  sDCAxy         = obj.sDCAxy;
  sDCAz          = obj.sDCAz;
  isTOFmismatch  = obj.isTOFmismatch;
  isMCptc        = obj.isMCptc;
  sMCcode        = obj.sMCcode;
  sPDGcode       = obj.sPDGcode;
  sMCmumIdx      = obj.sMCmumIdx;
  sMCmumPDG      = obj.sMCmumPDG;
  sMCgrandmumIdx = obj.sMCgrandmumIdx;
  sMCgrandmumPDG = obj.sMCgrandmumPDG;
  index          = obj.index;
  mcSecondOriginType = kUnassigned;
  doSkipOver     = obj.doSkipOver;
  sEtaS          = obj.sEtaS;
  sPhiS          = obj.sPhiS;
  isP            = obj.isP;
  isaP           = obj.isaP;

  return (*this);

}

//_____________________________________________________________________________

AliReconstructedSecond::~AliReconstructedSecond()

 {

 }

//_____________________________________________________________________________

AliAnalysisKPEvent::AliAnalysisKPEvent():
  fNumberCandidateFirst(0),
  fNumberCandidateSecond(0),
  fReconstructedFirst(0x0),
  fReconstructedSecond(0x0)
{
  //Default constructor
}
//_____________________________________________________________________________
AliAnalysisKPEvent::~AliAnalysisKPEvent()
{
  //Destructor

  if(fReconstructedFirst){
    delete fReconstructedFirst;
    fReconstructedFirst= NULL;
  }
  if(fReconstructedSecond){
    delete fReconstructedSecond;
    fReconstructedSecond= NULL;
  }

}
//_____________________________________________________________________________
AliAnalysisKPEventCollection::AliAnalysisKPEventCollection() :
  fEvt(0x0),
  fifo(0)
{

}

//______________________________________________________________________________

AliAnalysisKPEventCollection::~AliAnalysisKPEventCollection(){

  for(Int_t i = 0; i < fifo; i++){
     if((fEvt + i)->fReconstructedFirst != NULL){
       delete [] (fEvt + i)->fReconstructedFirst;
     }
     if((fEvt + i)->fReconstructedSecond != NULL){
       delete [] (fEvt + i)->fReconstructedSecond;
     }
   }
   delete [] fEvt;fEvt = NULL;
 }

//_____________________________________________________________________________

AliAnalysisKPEventCollection::AliAnalysisKPEventCollection(Short_t eventBuffSize, Int_t maxFirstMult, Int_t maxSecondMult) : fEvt(0x0), fifo(0) {

  SetBuffSize(eventBuffSize);

  fEvt = new AliAnalysisKPEvent[fifo];  //allocate pointer array of AliAnalysisKPEvents

  for(Int_t ii = 0; ii < fifo; ii++){ //Initialize particle table pointers to NULL

    (fEvt + ii)->fReconstructedFirst = NULL;

    (fEvt + ii)->fNumberCandidateFirst = 0;

    (fEvt + ii)->fReconstructedFirst = new AliReconstructedFirst[maxFirstMult];

    (fEvt + ii)->fReconstructedSecond = NULL;

    (fEvt + ii)->fNumberCandidateSecond = 0;

    (fEvt + ii)->fReconstructedSecond = new AliReconstructedSecond[maxSecondMult];

  }

}

//_____________________________________________________________________________
void AliAnalysisKPEventCollection::FifoShift() { //Shift elements in FIFO by one and clear last element in FIFO

  for(unsigned short i=fifo-1 ; i > 0; i--) {

    for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateFirst; j++){

      (fEvt + i)->fReconstructedFirst[j] = (fEvt + i-1)->fReconstructedFirst[j];

    }

    (fEvt + i)->fNumberCandidateFirst = (fEvt + i-1)->fNumberCandidateFirst;

    for(Int_t j=0; j<(fEvt + i-1)->fNumberCandidateSecond; j++){

      (fEvt + i)->fReconstructedSecond[j] = (fEvt + i-1)->fReconstructedSecond[j];

    }

    (fEvt + i)->fNumberCandidateSecond = (fEvt + i-1)->fNumberCandidateSecond;

    for(Int_t j=0; j<3; j++){

      (fEvt + i)->fPrimaryVertex[j] = (fEvt + i-1)->fPrimaryVertex[j];

    }

  }

   (fEvt)->fNumberCandidateFirst=0;
   (fEvt)->fNumberCandidateSecond=0;

   for(Int_t j=0; j<3; j++) {

     (fEvt)->fPrimaryVertex[j] = 0.;

   }

}

<|endoftext|>


<commit_before>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <compat/sanity.h>

#include <key.h>

#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(basic_sanity) {
    BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
    BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "openssl ECC test");
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>test: fix message for ECC_InitSanityCheck test<commit_after>// Copyright (c) 2012-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <compat/sanity.h>

#include <key.h>

#include <test/util/setup_common.h>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(sanity_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(basic_sanity) {
    BOOST_CHECK_MESSAGE(glibcxx_sanity_test() == true, "stdlib sanity test");
    BOOST_CHECK_MESSAGE(ECC_InitSanityCheck() == true, "secp256k1 sanity test");
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/ml/ml.hpp>

//#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>

#include <iostream>
#include <fstream>
#include <cstdlib>

#include "ocr_train.hpp"

using namespace cv;
using namespace std;

namespace fs = boost::filesystem;

Mat vector2Mat1D(vector<int> vec) {
	Mat result;

	Mat_<int> templ = Mat_<int>(vec.size(),1);

	for(vector<int>::iterator i = vec.begin(); i != vec.end(); ++i) {
		templ << *i;
	}

	result = (templ);

	return result;
}

Mat vector2Mat2D(vector< vector<int> > vec) {
	Mat result;

	Mat_<int> templ = Mat_<int>(vec.at(0).size(),2); //todo: vec.at(0).size() remove this hack

	for(vector< vector<int> >::iterator i = vec.begin(); i != vec.end(); ++i) {
		for(vector<int>::iterator j = (*i).begin(); j != (*i).end(); ++j) {
			templ << *j;
		}
	}

	result = (templ);

	return result;
}

int main() {

	//1. training

	string samples_str = "samples";
	string responses_str = "responses";
	vector<int> responses = loadArray< vector<int> >(responses_str);
	vector< vector<int> > samples = loadArray<vector < vector<int> > >(samples_str);

	//test: convert vector to Mat
	Mat samples_mat = vector2Mat2D(samples);
	Mat responses_mat = vector2Mat1D(responses);

	//train
	CvKNearest kn_model = CvKNearest();
	kn_model.train(samples_mat, responses_mat);

	//2. testing

	return 0;

}
<commit_msg>Finished porting ocr_recognizer, need to test<commit_after>#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/ml/ml.hpp>

#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>

#include <iostream>
#include <fstream>
#include <cstdlib>

#include "ocr_train.hpp"

using namespace cv;
using namespace std;

namespace fs = boost::filesystem;

Mat vector2Mat1D(vector<int> vec) {
	Mat result;

	Mat_<int> templ = Mat_<int>(vec.size(),1);

	for(vector<int>::iterator i = vec.begin(); i != vec.end(); ++i) {
		templ << *i;
	}

	result = (templ);

	return result;
}

Mat vector2Mat2D(vector< vector<int> > vec) {
	Mat result;

	Mat_<int> templ = Mat_<int>(vec.at(0).size(),2); //todo: vec.at(0).size() remove this hack

	for(vector< vector<int> >::iterator i = vec.begin(); i != vec.end(); ++i) {
		for(vector<int>::iterator j = (*i).begin(); j != (*i).end(); ++j) {
			templ << *j;
		}
	}

	result = (templ);

	return result;
}

int main() {

	//1. training

	string samples_str = "samples";
	string responses_str = "responses";
	vector<int> responses = loadArray< vector<int> >(responses_str);
	vector< vector<int> > samples = loadArray<vector < vector<int> > >(samples_str);

	//test: convert vector to Mat
	Mat samples_mat = vector2Mat2D(samples);
	Mat responses_mat = vector2Mat1D(responses);

	//train
	CvKNearest kn_model = CvKNearest();
	kn_model.train(samples_mat, responses_mat);

	//2. testing

	//Loads test image with numbers
	Mat img = imread("test.jpg");
	Mat img_original;
	img.copyTo(img_original);

	//Grayscale
	Mat gray;
	cvtColor(img, gray, CV_BGR2GRAY);

	//Builds a threshold making a binary image
	Mat thresh;
	adaptiveThreshold(gray, thresh, 255, 1, 1, 11, 2);

	//Output
	Mat out;

	//Find contours
	vector<vector<Point> > contours;
	vector<Vec4i> hierarchy;
	findContours(thresh, contours, hierarchy, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

	double cntArea;
	Mat contourMat;
	for (vector< vector<Point> >::iterator it = contours.begin();
		 it != contours.end(); ++it ) {

		vector<Point> cnt = *it;
		cntArea = contourArea(cnt);

		if (cntArea<50) {
			continue;
		}

		Rect boundbox = boundingRect(cnt);
		int x = boundbox.x;
		int y = boundbox.y;
		int width = boundbox.width;
		int height = boundbox.height;

		if (height<25) { //If it isn't high enough
			continue;
		}

		Point px(x,y);
		Point py(x+width, y+height);
		Scalar color(0, 0, 255); //red

		img.copyTo(contourMat);
		rectangle(contourMat, px, py, color, 2); //draws a rectangle on top of img

		Mat roi;
		roi = thresh(boundbox); //todo could be reverse (x,y) (y,x), am not sure

		//resize it to 10x10
		Mat roismall;
		Size_<int> smallSize(10,10);
		resize(roi, roismall, smallSize);

		//todo ""  roismall = roismall.reshape((1,100))
		//roismall = np.float32(roismall)

		Mat results, neighborResponses, dist;

		float retval = kn_model.find_nearest(roismall, 1, results, neighborResponses, dist);
		float number_res = results.at<float>(0,0);

		string str_result = boost::lexical_cast<string>(number_res);

		Point start_point(x,y+height);
		putText(out, str_result, start_point, 0, 1, color);
	}

	imshow("img", img);
	imshow("out", out);

	return 0;

}
<|endoftext|>


<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("MYCONFIGPID Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();
    //Set Reduce Size dAOD
  vHF->SetMakeReducedRHF(kTRUE);

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  //vHF->SetLikeSignOn(); // like-sign pairs and triplets
  //  vHF->SetLikeSign3prongOff();
  //vHF->Set4ProngOff();
  // vHF->SetDstarOff();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  //Cascade
  vHF->SetCascadesOn();
  vHF->SetFindVertexForCascades(kTRUE);
  vHF->SetV0TypeForCascadeVertex(AliRDHFCuts::kAllV0s); //All V0s 0, Offline 1, OnTheFly 2 //as in Config_Pb_AllCent
  vHF->SetUseProtonPIDforLambdaC2V0();

  vHF->SetMassCutBeforeVertexing(kTRUE); // PbPb

  //set PID
  vHF->SetUseKaonPIDfor3Prong(kTRUE);
  vHF->SetUseProtonAndPionPIDforLambdaC();
  vHF->SetnSigmaTOFforKaonSel(3., 5.);
  vHF->SetnSigmaTPCforKaonSel(5., 5.);
  vHF->SetnSigmaTOFforProtonSel(3.,5.);
  vHF->SetnSigmaTPCforProtonSel(5., 5.);
  vHF->SetnSigmaTPCforPionSel(4., 4.);
  vHF->SetnSigmaTOFforPionSel(40.,40.);
  vHF->SetMaxMomForTPCPid(9999999999.);
  vHF->SetUseTPCPID(kTRUE);
  vHF->SetUseTOFPID(kTRUE);
  vHF->SetUseTPCPIDOnlyIfNoTOF(kTRUE);

//--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetMinNClustersTPC(70);
  esdTrackCuts->SetRequireITSRefit(kTRUE);
  //esdTrackCuts->SetMinNClustersITS(4);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
					 AliESDtrackCuts::kAny);
  // |d0|>30 micron for pt<2GeV, no cut above 2
  esdTrackCuts->SetMinDCAToVertexXYPtDep("0.003*TMath::Max(0.,(1-TMath::Floor(TMath::Abs(pt)/2.)))");
  esdTrackCuts->SetMaxDCAToVertexXY(1.);
  esdTrackCuts->SetMaxDCAToVertexZ(1.);
  esdTrackCuts->SetPtRange(0.4,1.e10);
  esdTrackCuts->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(2);
  esdTrackCutsSoftPi->SetMaxDCAToVertexXY(1.);
  esdTrackCutsSoftPi->SetMaxDCAToVertexZ(1.);
  esdTrackCutsSoftPi->SetPtRange(0.2,1.e10);
  esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  Int_t nptbins=2; Float_t ptlimits[2]={0.,1000000.};
  AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi");
  cutsD0toKpi->SetStandardCutsPbPb2010();
  cutsD0toKpi->SetMinCentrality(-10);
  cutsD0toKpi->SetMaxCentrality(110);
  cutsD0toKpi->SetUseSpecialCuts(kFALSE);
  cutsD0toKpi->SetMinPtCandidate(0.);
  cutsD0toKpi->SetUsePID(kFALSE);
  cutsD0toKpi->SetUsePhysicsSelection(kFALSE);
  cutsD0toKpi->SetMaxVtxZ(1.e6);
  cutsD0toKpi->SetTriggerClass("");
  Float_t cutsArrayD0toKpi[11]={0.4,999999.,1.1,0.,0.,999999.,999999.,0.,0.5,-1,0.};
  cutsD0toKpi->SetPtBins(nptbins,ptlimits);
  cutsD0toKpi->SetCuts(11,cutsArrayD0toKpi);
  cutsD0toKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpi(cutsD0toKpi);
  AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee");
  Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1};
  cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee);
  cutsJpsitoee->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsJpsitoee(cutsJpsitoee);
  AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi");
  cutsDplustoKpipi->SetStandardCutsPbPb2010();
  cutsDplustoKpipi->SetUsePID(kFALSE);
  Float_t cutsArrayDplustoKpipi[14]={0.,0.3,0.3,0.,0.,0.01,0.05,0.05,0.,0.88,0.,10000000000.,0.,-1.};
  cutsDplustoKpipi->SetPtBins(nptbins,ptlimits);
  cutsDplustoKpipi->SetCuts(14,cutsArrayDplustoKpipi);
  cutsDplustoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDplustoKpipi->SetMinPtCandidate(2000000000.);
  vHF->SetCutsDplustoKpipi(cutsDplustoKpipi);
  AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi");
  cutsDstoKKpi->SetStandardCutsPbPb2010();
  cutsDstoKKpi->SetUsePID(kFALSE);
  Float_t cutsArrayDstoKKpi[20]={0.,0.3,0.3,0.,0.,0.005,0.06,0.,0.,0.9,0.,100000.,0.035,0.0001,-1.,1.,0.,0.,0.,-1.};
  cutsDstoKKpi->SetPtBins(nptbins,ptlimits);
  cutsDstoKKpi->SetCuts(20,cutsArrayDstoKKpi);
  cutsDstoKKpi->AddTrackCuts(esdTrackCuts);
  cutsDstoKKpi->SetMinPtCandidate(1000000000.);
  vHF->SetCutsDstoKKpi(cutsDstoKKpi);
  AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi");
  cutsLctopKpi->SetStandardCutsPbPb2010();
  cutsLctopKpi->SetUsePID(kFALSE);
  Float_t cutsArrayLctopKpi[13]={0.13,0.4,0.4,0.,0.,0.,0.06,0.,0.,0.,0.,0.05,0.4};
  cutsLctopKpi->SetPtBins(nptbins,ptlimits);
  cutsLctopKpi->SetCuts(13,cutsArrayLctopKpi);
  cutsLctopKpi->AddTrackCuts(esdTrackCuts);
  cutsLctopKpi->SetMinPtCandidate(2.);
  vHF->SetCutsLctopKpi(cutsLctopKpi);
  AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi");
  Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.};
  cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi);
  cutsD0toKpipipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpipipi(cutsD0toKpipipi);

 // D* pt dependent cuts ------------------------------------------

  AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi");
  cutsDStartoKpipi->SetUsePID(kFALSE);

  const Int_t nvars=16;
  const Int_t nptbins=2;

  Float_t* ptbins;
  ptbins=new Float_t[nptbins+1];
  ptbins[0]=0.;
  ptbins[1]=5.;
  ptbins[2]=999.;

  cutsDStartoKpipi->SetPtBins(nptbins+1,ptbins);

  Float_t** rdcutsvalmine;
  rdcutsvalmine=new Float_t*[nvars];
  for(Int_t iv=0;iv<nvars;iv++){
    rdcutsvalmine[iv]=new Float_t[nptbins];
  }
  //0-5
  rdcutsvalmine[0][0]=0.10;  //D0 inv mass window
  rdcutsvalmine[1][0]=0.06;   // dca
  rdcutsvalmine[2][0]=0.9;    // thetastar
  rdcutsvalmine[3][0]=0.5;    // pt Pion
  rdcutsvalmine[4][0]=0.5;    // Pt Kaon
  rdcutsvalmine[5][0]=0.1;    // d0K
  rdcutsvalmine[6][0]=0.1;    // d0Pi
  rdcutsvalmine[7][0]=0.0001; // d0xd0
  rdcutsvalmine[8][0]=0.8;    // costhetapoint
  rdcutsvalmine[9][0]=0.15;   // Dstar inv mass window
  rdcutsvalmine[10][0]=0.03;  // half width of (M_Kpipi-M_D0)
  rdcutsvalmine[11][0]=0.1;   // Pt min of Pi soft
  rdcutsvalmine[12][0]=100.;  // Pt max of pi soft
  rdcutsvalmine[13][0]=9999.; // theta
  rdcutsvalmine[14][0]=0.9;   // |cosThetaPointXY|
  rdcutsvalmine[15][0]=1.;    // NormDecayLenghtXY
 //5-999
  rdcutsvalmine[0][1]=0.10;   //D0 inv mass window
  rdcutsvalmine[1][1]=0.06;   // dca
  rdcutsvalmine[2][1]=0.9;    // thetastar
  rdcutsvalmine[3][1]=0.5;    // pt Pion
  rdcutsvalmine[4][1]=0.5;    // Pt Kaon
  rdcutsvalmine[5][1]=0.1;    // d0K
  rdcutsvalmine[6][1]=0.1;    // d0Pi
  rdcutsvalmine[7][1]=0.0001; // d0xd0
  rdcutsvalmine[8][1]=0.7;    // costhetapoint
  rdcutsvalmine[9][1]=0.15;   // Dstar inv mass window
  rdcutsvalmine[10][1]=0.03;  // half width of (M_Kpipi-M_D0)
  rdcutsvalmine[11][1]=0.1;   // Pt min of Pi soft
  rdcutsvalmine[12][1]=100.;  // Pt max of pi soft
  rdcutsvalmine[13][1]=9999.; // theta
  rdcutsvalmine[14][1]=0.8;   // |cosThetaPointXY|
  rdcutsvalmine[15][1]=0.;    // NormDecayLenghtXY

  cutsDStartoKpipi->SetCuts(nvars,nptbins,rdcutsvalmine);

  cutsDStartoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi);
  cutsDStartoKpipi->SetMinPtCandidate(2.);
  vHF->SetCutsDStartoKpipi(cutsDStartoKpipi);

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

  AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0");

  Float_t cutsArrayLctoV0[21]={1.0,1.0,0.05,0.05,0.0,0.0,0.0,1000.,1000.,0.99,3.,1000.,0.,0.,0.,0.,9999.,-9999.,-9999.,-9999.,0.0};//from the Config_Pb_AllCent_NOLS

  cutsLctoV0->SetCuts(21,cutsArrayLctoV0);
  cutsLctoV0->AddTrackCuts(esdTrackCuts);
    AliESDtrackCuts *esdV0daughterTrackCuts = new AliESDtrackCuts("AliESDtrackCutsForV0D","default cuts for V0 daughters");
  esdV0daughterTrackCuts->SetRequireTPCRefit(kTRUE);
  esdV0daughterTrackCuts->SetMinNClustersTPC(30);
  esdV0daughterTrackCuts->SetRequireITSRefit(kFALSE);
  esdV0daughterTrackCuts->SetMinDCAToVertexXY(0.);
  esdV0daughterTrackCuts->SetPtRange(0.05,1.e10);
  esdV0daughterTrackCuts->SetEtaRange(-1.1,+1.1);
  esdV0daughterTrackCuts->SetAcceptKinkDaughters(kTRUE);
  esdV0daughterTrackCuts->SetRequireSigmaToVertex(kFALSE);
  cutsLctoV0->AddTrackCutsV0daughters(esdV0daughterTrackCuts);
  vHF->SetCutsLctoV0(cutsLctoV0);
  //
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //  AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}

<commit_msg>Fix for the ConfigVertexingHF for the MC upgrade production<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() {

  printf("MYCONFIGPID Call to AliAnalysisVertexingHF parameters setting :\n");
  vHF = new AliAnalysisVertexingHF();
    //Set Reduce Size dAOD
  vHF->SetMakeReducedRHF(kTRUE);

  //--- switch-off candidates finding (default: all on)
  //vHF->SetD0toKpiOff();
  // vHF->SetD0toKpiOn();
  vHF->SetJPSItoEleOff();
  //vHF->Set3ProngOff();
  //vHF->SetLikeSignOn(); // like-sign pairs and triplets
  //  vHF->SetLikeSign3prongOff();
  //vHF->Set4ProngOff();
  // vHF->SetDstarOn();
  vHF->SetFindVertexForDstar(kFALSE);
  //--- secondary vertex with KF?
  //vHF->SetSecVtxWithKF();
  //Cascade
  vHF->SetCascadesOn();
  vHF->SetFindVertexForCascades(kFALSE);
   vHF->SetMassCutBeforeVertexing(kTRUE); // PbPb
  vHF->SetV0TypeForCascadeVertex(AliRDHFCuts::kAllV0s); //All V0s 0, Offline 1, OnTheFly 2 //as in Config_Pb_AllCent
  vHF->SetUseProtonPIDforLambdaC2V0();

  vHF->SetMassCutBeforeVertexing(kTRUE); // PbPb

//--- set cuts for single-track selection
  //     displaced tracks
  AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCuts->SetRequireTPCRefit(kTRUE);
  esdTrackCuts->SetMinNClustersTPC(70);
 esdTrackCuts->SetRequireITSRefit(kTRUE);
  //esdTrackCuts->SetMinNClustersITS(4);
  esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,	 AliESDtrackCuts::kAny);
  // |d0|>30 micron for pt<2GeV, no cut above 2
  esdTrackCuts->SetMinDCAToVertexXYPtDep("0.003*TMath::Max(0.,(1-TMath::Floor(TMath::Abs(pt)/2.)))");
  esdTrackCuts->SetMaxDCAToVertexXY(1.);
  esdTrackCuts->SetMaxDCAToVertexZ(1.);
  esdTrackCuts->SetPtRange(0.4,1.e10);
  esdTrackCuts->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
  trkFilter->AddCuts(esdTrackCuts);
  vHF->SetTrackFilter(trkFilter);
  //     D* soft pion tracks
  AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
  esdTrackCutsSoftPi->SetMinNClustersITS(2);
  esdTrackCutsSoftPi->SetMaxDCAToVertexXY(1.);
  esdTrackCutsSoftPi->SetMaxDCAToVertexZ(1.);
  esdTrackCutsSoftPi->SetPtRange(0.1,1.e10);
  esdTrackCutsSoftPi->SetEtaRange(-0.8,+0.8);
  AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
  trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
  vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
  //--- set cuts for candidates selection
  Int_t nptbins=2; Float_t ptlimits[2]={0.,1000000.};
  AliRDHFCutsD0toKpi *cutsD0toKpi = new AliRDHFCutsD0toKpi("CutsD0toKpi");
  cutsD0toKpi->SetStandardCutsPbPb2010();
   cutsD0toKpi->SetUseCentrality(kFALSE);
  // cutsD0toKpi->SetMinCentrality(-10);
  //cutsD0toKpi->SetMaxCentrality(110);
  cutsD0toKpi->SetUseSpecialCuts(kFALSE);
  cutsD0toKpi->SetMinPtCandidate(0.);
  cutsD0toKpi->SetUsePID(kFALSE);
  cutsD0toKpi->SetUsePhysicsSelection(kFALSE);
  cutsD0toKpi->SetMaxVtxZ(1.e6);
  cutsD0toKpi->SetTriggerClass("");
  Float_t cutsArrayD0toKpi[11]={0.4,999999.,1.1,0.,0.,999999.,999999.,0.,0.5,-1,0.};
  cutsD0toKpi->SetPtBins(nptbins,ptlimits);
  cutsD0toKpi->SetCuts(11,cutsArrayD0toKpi);
  cutsD0toKpi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpi(cutsD0toKpi);
  AliRDHFCutsJpsitoee *cutsJpsitoee = new AliRDHFCutsJpsitoee("CutsJpsitoee");
  Float_t cutsArrayJpsitoee[9]={0.350,100000.,1.1,0.,0.,100000.,100000.,100000000.,-1.1};
  cutsJpsitoee->SetCuts(9,cutsArrayJpsitoee);
  cutsJpsitoee->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsJpsitoee(cutsJpsitoee);
  AliRDHFCutsDplustoKpipi *cutsDplustoKpipi = new AliRDHFCutsDplustoKpipi("CutsDplustoKpipi");
  cutsDplustoKpipi->SetStandardCutsPbPb2010();
  cutsDplustoKpipi->SetUseCentrality(kFALSE);
  cutsDplustoKpipi->SetUsePID(kFALSE);
  Float_t cutsArrayDplustoKpipi[14]={0.25,0.3,0.3,0.,0.,0.01,0.05,0.05,0.,0.7,0.,10000000000.,0.,-1.};
  cutsDplustoKpipi->SetPtBins(nptbins,ptlimits);
  cutsDplustoKpipi->SetCuts(14,cutsArrayDplustoKpipi);
  cutsDplustoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDplustoKpipi->SetMinPtCandidate(2.);
  vHF->SetCutsDplustoKpipi(cutsDplustoKpipi);
  AliRDHFCutsDstoKKpi *cutsDstoKKpi = new AliRDHFCutsDstoKKpi("CutsDstoKKpi");
  cutsDstoKKpi->SetStandardCutsPbPb2010();
   cutsDstoKKpi->SetUseCentrality(kFALSE);
  cutsDstoKKpi->SetUsePID(kFALSE);
  Float_t cutsArrayDstoKKpi[20]={0.35,0.3,0.3,0.,0.,0.005,0.06,0.,0.,0.7,0.,100000.,0.035,0.0001,-1.,1.,0.,0.,0.,-1.};
  cutsDstoKKpi->SetPtBins(nptbins,ptlimits);
  cutsDstoKKpi->SetCuts(20,cutsArrayDstoKKpi);
  cutsDstoKKpi->AddTrackCuts(esdTrackCuts);
  cutsDstoKKpi->SetMinPtCandidate(2.);
  vHF->SetCutsDstoKKpi(cutsDstoKKpi);
  AliRDHFCutsLctopKpi *cutsLctopKpi = new AliRDHFCutsLctopKpi("CutsLctopKpi");
  cutsLctopKpi->SetStandardCutsPbPb2010();
  cutsLctopKpi->SetUseCentrality(kFALSE);
  cutsLctopKpi->SetUsePID(kFALSE);
  Float_t cutsArrayLctopKpi[13]={0.13,0.4,0.4,0.,0.,0.,0.06,0.,0.,0.,0.,0.05,0.4};
  cutsLctopKpi->SetPtBins(nptbins,ptlimits);
  cutsLctopKpi->SetCuts(13,cutsArrayLctopKpi);
  cutsLctopKpi->AddTrackCuts(esdTrackCuts);
  cutsLctopKpi->SetMinPtCandidate(2.);
  vHF->SetCutsLctopKpi(cutsLctopKpi);
  AliRDHFCutsD0toKpipipi *cutsD0toKpipipi = new AliRDHFCutsD0toKpipipi("CutsD0toKpipipi");
  Float_t cutsArrayD0toKpipipi[9]={0.2,0.04,0.00,0.01,0.02,0.8,0.,0.1,0.};
  cutsD0toKpipipi->SetCuts(9,cutsArrayD0toKpipipi);
  cutsD0toKpipipi->AddTrackCuts(esdTrackCuts);
  vHF->SetCutsD0toKpipipi(cutsD0toKpipipi);

   AliRDHFCutsDStartoKpipi *cutsDStartoKpipi = new AliRDHFCutsDStartoKpipi("CutsDStartoKpipi");
  Float_t cutsArrayDStartoKpipi[16]={0.1,999999.,1.1,0.,0.,999999.,999999.,999999.,0.7,0.03, 0.1, 0.05, 100000000000.0, 0.5,-1.,1.}; // first 9 for D0 from D*, next 5 for D*, last 2 for D0 again
  cutsDStartoKpipi->SetUsePID(kFALSE);
  cutsDStartoKpipi->SetCuts(16,cutsArrayDStartoKpipi);
  cutsDStartoKpipi->AddTrackCuts(esdTrackCuts);
  cutsDStartoKpipi->AddTrackCutsSoftPi(esdTrackCutsSoftPi);
  cutsDStartoKpipi->SetMinPtCandidate(2.);
  vHF->SetCutsDStartoKpipi(cutsDStartoKpipi);

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

  AliRDHFCutsLctoV0 *cutsLctoV0 = new AliRDHFCutsLctoV0("CutsLctoV0");
  /*
  Float_t cutsArrayLctoV0[9]={4.0,4.0,2.0,2.0,0.0,0.0,0.0,1000.,1000.};
  cutsLctoV0->SetCuts(9,cutsArrayLctoV0);
  */
  //last dummy
  Float_t cutsArrayLctoV0[21]={1.0,1.0,0.05,0.05,0.0,0.0,0.0,1000.,1000.,0.99,3.,1000.,0.,0.,0.,0.,9999.,-9999.,-9999.,-9999.,0.0};//from the Config_Pb_AllCent_NOLS

  cutsLctoV0->SetCuts(21,cutsArrayLctoV0);
  cutsLctoV0->AddTrackCuts(esdTrackCuts);
    AliESDtrackCuts *esdV0daughterTrackCuts = new AliESDtrackCuts("AliESDtrackCutsForV0D","default cuts for V0 daughters");
  esdV0daughterTrackCuts->SetRequireTPCRefit(kTRUE);
  esdV0daughterTrackCuts->SetMinNClustersTPC(30);
  esdV0daughterTrackCuts->SetRequireITSRefit(kFALSE);
  esdV0daughterTrackCuts->SetMinDCAToVertexXY(0.);
  esdV0daughterTrackCuts->SetPtRange(0.05,1.e10);
  esdV0daughterTrackCuts->SetEtaRange(-1.1,+1.1);
  esdV0daughterTrackCuts->SetAcceptKinkDaughters(kTRUE);
  esdV0daughterTrackCuts->SetRequireSigmaToVertex(kFALSE);
  cutsLctoV0->AddTrackCutsV0daughters(esdV0daughterTrackCuts);
  vHF->SetCutsLctoV0(cutsLctoV0);
  //
  //--- set this if you want to reconstruct primary vertex candidate by
  //    candidate using other tracks in the event (for pp, broad
  //    interaction region)
  //vHF->SetRecoPrimVtxSkippingTrks();
  //--- OR set this if you want to remove the candidate daughters from
  //    the primary vertex, without recostructing it from scratch
  //vHF->SetRmTrksFromPrimVtx();

  //--- check the settings
  vHF->PrintStatus();
  //--- verbose
  //  AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);

  return vHF;
}
<|endoftext|>


<commit_before>#include "osg/Uniform"
#include "osg/io_utils"
#include "osg/Notify"

#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"

#include "Matrix.h"

using namespace osg;
using namespace osgDB;
using namespace std;

// forward declare functions to use later.
bool Uniform_readLocalData(Object& obj, Input& fr);
bool Uniform_writeLocalData(const Object& obj, Output& fw);

// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_UniformProxy
(
    new osg::Uniform,
    "Uniform",
    "Object Uniform",
    &Uniform_readLocalData,
    &Uniform_writeLocalData
);

bool Uniform_readLocalData(Object& obj, Input& fr)
{
    bool iteratorAdvanced = false;

    Uniform& uniform = static_cast<Uniform&>(obj);

    if (fr.matchSequence("name %s"))
    {
        uniform.setName(fr[1].getStr());
        fr+=2;
        iteratorAdvanced = true;
    }

    if (fr[0].isWord())
    {
        uniform.setType( Uniform::getTypeId(fr[0].getStr()) );
        fr+=1;
        iteratorAdvanced = true;
    }

    switch( Uniform::getGlApiType(uniform.getType()) )
    {
        case(osg::Uniform::FLOAT):
        {
            float value;
            if (fr[0].getFloat(value))
            {
                uniform.set(value);
                fr+=1;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC2):
        {
            osg::Vec2 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]))
            {
                uniform.set(value);
                fr+=2;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC3):
        {
            osg::Vec3 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]))
            {
                uniform.set(value);
                fr+=3;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC4):
        {
            osg::Vec4 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]) && fr[3].getFloat(value[3]))
            {
                uniform.set(value);
                fr+=4;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT):
        {
            int value;
            if (fr[0].getInt(value))
            {
                uniform.set(value);
                fr+=1;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC2):
        {
            int value[2];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]))
            {
                uniform.set(value[0],value[1]);
                fr+=2;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC3):
        {
            int value[3];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]))
            {
                uniform.set(value[0],value[1],value[2]);
                fr+=3;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC4):
        {
            int value[4];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]) && fr[3].getInt(value[3]))
            {
                uniform.set(value[0],value[1],value[2],value[3]);
                fr+=4;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_MAT2):
        {
            osg::notify(osg::WARN)<<"Warning : type mat2 not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT3):
        {
            osg::notify(osg::WARN)<<"Warning : type mat3 not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT4):
        {
            Matrix value;
            if( readMatrix(value,fr) )
            {
                uniform.set(value);
               iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::UNDEFINED):
        {
            break;
        }
    }

    return iteratorAdvanced;
}

bool Uniform_writeLocalData(const Object& obj,Output& fw)
{
    const Uniform& uniform = static_cast<const Uniform&>(obj);

    fw.indent() << "name "<< fw.wrapString(uniform.getName()) << std::endl;

    fw.indent() << Uniform::getTypename( uniform.getType() ) << " ";

    switch( Uniform::getGlApiType(uniform.getType()) )
    {
        case(osg::Uniform::FLOAT):
        {
            float value = 0.0f;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC2):
        {
            Vec2 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC3):
        {
            Vec3 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC4):
        {
            Vec4 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::INT):
        {
            int value = 0;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::INT_VEC2):
        {
            int value[2];
            uniform.get(value[0],value[1]);
            fw << value[0]<<" "<<value[1];
            break;
        }
        case(osg::Uniform::INT_VEC3):
        {
            int value[3];
            uniform.get(value[0],value[1],value[2]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2];
            break;
        }
        case(osg::Uniform::INT_VEC4):
        {
            int value[4];
            uniform.get(value[0],value[1],value[2],value[3]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2]<<" "<<value[3];
            break;
        }
        case(osg::Uniform::FLOAT_MAT2):
        {
            osg::notify(osg::WARN)<<"Warning : type mat2 not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT3):
        {
            osg::notify(osg::WARN)<<"Warning : type mat3 not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT4):
        {
            Matrix value;
            uniform.get(value);
            writeMatrix(value,fw);
            break;
        }
        case(osg::Uniform::UNDEFINED):
        {
            break;
        }
    }

    fw << std::endl;

    return true;
}
<commit_msg>Fixed compile warning.<commit_after>#include "osg/Uniform"
#include "osg/io_utils"
#include "osg/Notify"

#include "osgDB/Registry"
#include "osgDB/Input"
#include "osgDB/Output"

#include "Matrix.h"

using namespace osg;
using namespace osgDB;
using namespace std;

// forward declare functions to use later.
bool Uniform_readLocalData(Object& obj, Input& fr);
bool Uniform_writeLocalData(const Object& obj, Output& fw);

// register the read and write functions with the osgDB::Registry.
RegisterDotOsgWrapperProxy g_UniformProxy
(
    new osg::Uniform,
    "Uniform",
    "Object Uniform",
    &Uniform_readLocalData,
    &Uniform_writeLocalData
);

bool Uniform_readLocalData(Object& obj, Input& fr)
{
    bool iteratorAdvanced = false;

    Uniform& uniform = static_cast<Uniform&>(obj);

    if (fr.matchSequence("name %s"))
    {
        uniform.setName(fr[1].getStr());
        fr+=2;
        iteratorAdvanced = true;
    }

    if (fr[0].isWord())
    {
        uniform.setType( Uniform::getTypeId(fr[0].getStr()) );
        fr+=1;
        iteratorAdvanced = true;
    }

    switch( Uniform::getGlApiType(uniform.getType()) )
    {
        case(osg::Uniform::FLOAT):
        {
            float value;
            if (fr[0].getFloat(value))
            {
                uniform.set(value);
                fr+=1;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC2):
        {
            osg::Vec2 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]))
            {
                uniform.set(value);
                fr+=2;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC3):
        {
            osg::Vec3 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]))
            {
                uniform.set(value);
                fr+=3;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_VEC4):
        {
            osg::Vec4 value;
            if (fr[0].getFloat(value[0]) && fr[1].getFloat(value[1]) && fr[2].getFloat(value[2]) && fr[3].getFloat(value[3]))
            {
                uniform.set(value);
                fr+=4;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT):
        {
            int value;
            if (fr[0].getInt(value))
            {
                uniform.set(value);
                fr+=1;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC2):
        {
            int value[2];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]))
            {
                uniform.set(value[0],value[1]);
                fr+=2;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC3):
        {
            int value[3];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]))
            {
                uniform.set(value[0],value[1],value[2]);
                fr+=3;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::INT_VEC4):
        {
            int value[4];
            if (fr[0].getInt(value[0]) && fr[1].getInt(value[1]) && fr[2].getInt(value[2]) && fr[3].getInt(value[3]))
            {
                uniform.set(value[0],value[1],value[2],value[3]);
                fr+=4;
                iteratorAdvanced = true;
            }
            break;
        }
        case(osg::Uniform::FLOAT_MAT2):
        {
            osg::notify(osg::WARN)<<"Warning : type mat2 not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT3):
        {
            osg::notify(osg::WARN)<<"Warning : type mat3 not supported for reading."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT4):
        {
            Matrix value;
            if( readMatrix(value,fr) )
            {
                uniform.set(value);
               iteratorAdvanced = true;
            }
            break;
        }
        default:
        {
            break;
        }
    }

    return iteratorAdvanced;
}

bool Uniform_writeLocalData(const Object& obj,Output& fw)
{
    const Uniform& uniform = static_cast<const Uniform&>(obj);

    fw.indent() << "name "<< fw.wrapString(uniform.getName()) << std::endl;

    fw.indent() << Uniform::getTypename( uniform.getType() ) << " ";

    switch( Uniform::getGlApiType(uniform.getType()) )
    {
        case(osg::Uniform::FLOAT):
        {
            float value = 0.0f;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC2):
        {
            Vec2 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC3):
        {
            Vec3 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::FLOAT_VEC4):
        {
            Vec4 value;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::INT):
        {
            int value = 0;
            uniform.get(value);
            fw << value;
            break;
        }
        case(osg::Uniform::INT_VEC2):
        {
            int value[2];
            uniform.get(value[0],value[1]);
            fw << value[0]<<" "<<value[1];
            break;
        }
        case(osg::Uniform::INT_VEC3):
        {
            int value[3];
            uniform.get(value[0],value[1],value[2]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2];
            break;
        }
        case(osg::Uniform::INT_VEC4):
        {
            int value[4];
            uniform.get(value[0],value[1],value[2],value[3]);
            fw << value[0]<<" "<<value[1]<<" "<<value[2]<<" "<<value[3];
            break;
        }
        case(osg::Uniform::FLOAT_MAT2):
        {
            osg::notify(osg::WARN)<<"Warning : type mat2 not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT3):
        {
            osg::notify(osg::WARN)<<"Warning : type mat3 not supported for writing."<<std::endl;
            break;
        }
        case(osg::Uniform::FLOAT_MAT4):
        {
            Matrix value;
            uniform.get(value);
            writeMatrix(value,fw);
            break;
        }
        default:
        {
            break;
        }
    }

    fw << std::endl;

    return true;
}
<|endoftext|>