<commit_before>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciContainerLogLevel.cpp,v 1.3 2007/10/05 14:10:47 hsommer Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bgustafs 2002-04-15 corrected shutdown action
* msekoran  2001/12/23  created
*/

/** @file maciContainerSetLogLevel.cpp
 *  maciContainerSetLogLevel is used to set container log levels runtime.
 *  @htmlonly
 *

 *  @endhtmlonly

 *  @param container This is simply the name of the container in the CDB that we want to stop.
 *  @htmlonly
 *

 *  @endhtmlonly

 */

#include <vltPort.h>
#include <acsutil.h>

#include <logging.h>
#include <maciHelper.h>
#include <maciContainerImpl.h>

 using namespace maci;

void
printUsageAndExit(int argc, char *argv[])
{
	ACE_OS::printf("\n\tusage: %s <container name wildcard> {set,get,list,refresh} [<loggerName | \"default\"> <minLogLevel> <minLogLevelLocal>] [<ORB options>]\n\n", argv[0]);
	exit(-1);
}

int
main (int argc, char *argv[])
{

    if (argc < 3)
    	printUsageAndExit(argc, argv);

	char * command = argv[2];

	#define SET 1
	#define GET 2
	#define LIST 3
	#define REFRESH 4
	int cmd;
	if (ACE_OS::strcmp(command, "set") == 0)
		cmd = SET;
	else if (ACE_OS::strcmp(command, "get") == 0)
		cmd = GET;
	else if (ACE_OS::strcmp(command, "list") == 0)
		cmd = LIST;
	else if (ACE_OS::strcmp(command, "refresh") == 0)
		cmd = REFRESH;
	else
	{
		ACE_OS::printf("Invalid command, must be one of {set,get,list,refresh}.\n");
	    printUsageAndExit(argc, argv);
	}

	if (cmd == SET && argc < 4)
	{
		// if only 4 then default is set
		ACE_OS::printf("Not enough parameters.\n");
	    printUsageAndExit(argc, argv);
	}

	if (cmd == GET && argc < 4)
	{
		ACE_OS::printf("Not enough parameters.\n");
	    printUsageAndExit(argc, argv);
	}

    LoggingProxy * logger = new LoggingProxy(0, 0, 31);
    if (logger)
    {
	LoggingProxy::init(logger);
	LoggingProxy::ProcessName(argv[0]);
	LoggingProxy::ThreadName("main");
    }
    else
	ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging."));

    try
    {
	// Initialize the ORB.
	CORBA::ORB_var orb = CORBA::ORB_init (argc,
					      argv,
					      "TAO"
					      );

	maci::Manager_var mgr = MACIHelper::resolveManager(orb.ptr(), argc, argv, 0, 0);
        if (mgr.ptr() == maci::Manager::_nil())
	{
	    ACS_SHORT_LOG((LM_ERROR, "Failed to resolve Manager reference."));
	    return -1;
	}

	maci::HandleSeq handles;
	handles.length(0);

	// a little hack to manager (this clas should implement administrator interface, etc..)
	maci::Handle h = 0x05000000;
	maci::ContainerInfoSeq_var containers = mgr->get_container_info(h, handles, argv[1]);

	if (!containers.ptr() || containers->length()==0)
	{
	    ACS_SHORT_LOG((LM_INFO, "No containers matching name %s found.", argv[1]));
	    return -1;
	}

	for (CORBA::ULong i = 0; i < containers->length(); i++)
	{
	    try
	    {
	    	ACS_SHORT_LOG((LM_INFO, "Container: %s", containers[i].name.in()));

	    	if (cmd == LIST)
	    	{
	    		ACS_SHORT_LOG((LM_INFO, "\tLogger names:"));
	    		maci::stringSeq_var loggerNames = containers[i].reference->get_logger_names();
	    		for (CORBA::ULong j = 0; j < loggerNames->length(); j++)
	   				ACS_SHORT_LOG((LM_INFO, "\t\t%s", loggerNames[j].in()));
	    	}
	    	else if (cmd == REFRESH)
	    	{
	    		ACS_SHORT_LOG((LM_INFO, "\tRefreshing logging config."));
				containers[i].reference->refresh_logging_config();
	    	}
	    	else if (cmd == GET)
	    	{
	    		char * loggerName = argv[3];

			    LoggingConfigurable::LogLevels logLevels;
			    if (ACE_OS::strcmp(loggerName, "default") == 0)
			     	logLevels = containers[i].reference->get_default_logLevels();
			    else
			    	logLevels = containers[i].reference->get_logLevels(loggerName);

			    ACS_SHORT_LOG((LM_INFO, "\tLog levels for logger '%s':", loggerName));
			    ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault      : %s", logLevels.useDefault ? "true" : "false"));
			    ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel     : %d", logLevels.minLogLevel));
			    ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal));
	    	}
	    	else if (cmd == SET)
	    	{
	    		char * loggerName = argv[3];

			    LoggingConfigurable::LogLevels logLevels;

			    logLevels.useDefault = argc < 6;
			    if (!logLevels.useDefault)
			    {
	    			logLevels.minLogLevel = atoi(argv[4]);
	    			logLevels.minLogLevelLocal = atoi(argv[5]);
			    }
			    else
			    {
	    			logLevels.minLogLevel = 0;
	    			logLevels.minLogLevelLocal = 0;
			    }

			    ACS_SHORT_LOG((LM_INFO, "\tSetting levels for logger '%s':", loggerName));
			    ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault      : %s", logLevels.useDefault ? "true" : "false"));
			    //if (!logLevels.useDefault)
			    {
			    	ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel     : %d", logLevels.minLogLevel));
			    	ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal));
			    }

			    if (ACE_OS::strcmp(loggerName, "default") == 0)
	    			containers[i].reference->set_default_logLevels(logLevels);
				else
	    			containers[i].reference->set_logLevels(loggerName, logLevels);
	    	}

			ACS_SHORT_LOG((LM_INFO, "\t... done."));
	    }
	    catch( CORBA::Exception &ex )
	    {
	        ACS_SHORT_LOG((LM_INFO, "... failed!"));
			ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, ACE_TEXT ("Exception caught while calling remote method."));
	    }

	}

	ACS_SHORT_LOG((LM_INFO, "Done all."));

    }
  catch( CORBA::Exception &ex )
  {
      ACS_SHORT_LOG((LM_INFO, "Failed."));
      ACE_PRINT_EXCEPTION (ex,
                           ACE_TEXT ("Caught unexpected exception:"));

      return -1;
  }

  return 0;
}

<commit_msg>Enforces correct log levels before setting them. Also prints the valid levels (0,2-6,8-11) in the help message.<commit_after>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciContainerLogLevel.cpp,v 1.4 2007/11/09 14:00:17 hsommer Exp $"
*
* who       when      what
* --------  --------  ----------------------------------------------
* bgustafs 2002-04-15 corrected shutdown action
* msekoran  2001/12/23  created
*/

/** @file maciContainerSetLogLevel.cpp
 *  maciContainerSetLogLevel is used to set container log levels runtime.
 *  @htmlonly
 *

 *  @endhtmlonly

 *  @param container This is simply the name of the container in the CDB that we want to stop.
 *  @htmlonly
 *

 *  @endhtmlonly

 */

#include <vltPort.h>
#include <acsutil.h>

#include <logging.h>
#include <maciHelper.h>
#include <maciContainerImpl.h>

 using namespace maci;

void
printUsageAndExit(int argc, char *argv[])
{
	ACE_OS::printf("\n\tusage: %s <container name wildcard> {set,get,list,refresh} [<loggerName | \"default\"> <minLogLevel> <minLogLevelLocal>] [<ORB options>]\nWith log level values {0,2-6,8-11}\n", argv[0]);
	exit(-1);
}

// Only integer values for certain levels are defined, e.g. DEBUG = 3.
// No illegal levels should be sent to the LoggingConfigurable processes (containers, manager, ...)
int
isLogLevelValid(int logLevel)
{
	return (logLevel >= 0 && logLevel <= 11 && logLevel != 1 && logLevel != 7);
}

int
main (int argc, char *argv[])
{

    if (argc < 3)
    	printUsageAndExit(argc, argv);

	char * command = argv[2];

	#define SET 1
	#define GET 2
	#define LIST 3
	#define REFRESH 4
	int cmd;
	if (ACE_OS::strcmp(command, "set") == 0)
		cmd = SET;
	else if (ACE_OS::strcmp(command, "get") == 0)
		cmd = GET;
	else if (ACE_OS::strcmp(command, "list") == 0)
		cmd = LIST;
	else if (ACE_OS::strcmp(command, "refresh") == 0)
		cmd = REFRESH;
	else
	{
		ACE_OS::printf("Invalid command, must be one of {set,get,list,refresh}.\n");
	    printUsageAndExit(argc, argv);
	}

	if (cmd == SET && argc < 4)
	{
		// if only 4 then default is set
		ACE_OS::printf("Not enough parameters.\n");
	    printUsageAndExit(argc, argv);
	}

	if (cmd == GET && argc < 4)
	{
		ACE_OS::printf("Not enough parameters.\n");
		printUsageAndExit(argc, argv);
	}

    LoggingProxy * logger = new LoggingProxy(0, 0, 31);
    if (logger)
    {
    	LoggingProxy::init(logger);
    	LoggingProxy::ProcessName(argv[0]);
    	LoggingProxy::ThreadName("main");
    }
    else
    	ACS_SHORT_LOG((LM_INFO, "Failed to initialize logging."));

    try
    {
	// Initialize the ORB.
	CORBA::ORB_var orb = CORBA::ORB_init (argc,
					      argv,
					      "TAO"
					      );

	maci::Manager_var mgr = MACIHelper::resolveManager(orb.ptr(), argc, argv, 0, 0);
        if (mgr.ptr() == maci::Manager::_nil())
	{
	    ACS_SHORT_LOG((LM_ERROR, "Failed to resolve Manager reference."));
	    return -1;
	}

	maci::HandleSeq handles;
	handles.length(0);

	// a little hack to manager (this clas should implement administrator interface, etc..)
	maci::Handle h = 0x05000000;
	maci::ContainerInfoSeq_var containers = mgr->get_container_info(h, handles, argv[1]);

	if (!containers.ptr() || containers->length()==0)
	{
	    ACS_SHORT_LOG((LM_INFO, "No containers matching name %s found.", argv[1]));
	    return -1;
	}

	for (CORBA::ULong i = 0; i < containers->length(); i++)
	{
	    try
	    {
	    	ACS_SHORT_LOG((LM_INFO, "Container: %s", containers[i].name.in()));

	    	if (cmd == LIST)
	    	{
	    		ACS_SHORT_LOG((LM_INFO, "\tLogger names:"));
	    		maci::stringSeq_var loggerNames = containers[i].reference->get_logger_names();
	    		for (CORBA::ULong j = 0; j < loggerNames->length(); j++)
	   				ACS_SHORT_LOG((LM_INFO, "\t\t%s", loggerNames[j].in()));
	    	}
	    	else if (cmd == REFRESH)
	    	{
	    		ACS_SHORT_LOG((LM_INFO, "\tRefreshing logging config."));
				containers[i].reference->refresh_logging_config();
	    	}
	    	else if (cmd == GET)
	    	{
	    		char * loggerName = argv[3];

			    LoggingConfigurable::LogLevels logLevels;
			    if (ACE_OS::strcmp(loggerName, "default") == 0)
			     	logLevels = containers[i].reference->get_default_logLevels();
			    else
			    	logLevels = containers[i].reference->get_logLevels(loggerName);

			    ACS_SHORT_LOG((LM_INFO, "\tLog levels for logger '%s':", loggerName));
			    ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault      : %s", logLevels.useDefault ? "true" : "false"));
			    ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel     : %d", logLevels.minLogLevel));
			    ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal));
	    	}
	    	else if (cmd == SET)
	    	{
	    		char * loggerName = argv[3];

			    LoggingConfigurable::LogLevels logLevels;

			    logLevels.useDefault = argc < 6;
			    if (!logLevels.useDefault)
			    {
	    			logLevels.minLogLevel = atoi(argv[4]);
	    			logLevels.minLogLevelLocal = atoi(argv[5]);
			    	if (!isLogLevelValid(logLevels.minLogLevel) || !isLogLevelValid(logLevels.minLogLevelLocal))
			    	{
			    		printUsageAndExit(argc, argv);
			    	}
			    }
			    else
			    {
	    			logLevels.minLogLevel = 0;
	    			logLevels.minLogLevelLocal = 0;
			    }

			    ACS_SHORT_LOG((LM_INFO, "\tSetting levels for logger '%s':", loggerName));
			    ACS_SHORT_LOG((LM_INFO, "\t\tuseDefault      : %s", logLevels.useDefault ? "true" : "false"));
			    //if (!logLevels.useDefault)
			    {
			    	ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevel     : %d", logLevels.minLogLevel));
			    	ACS_SHORT_LOG((LM_INFO, "\t\tminLogLevelLocal: %d", logLevels.minLogLevelLocal));
			    }

			    if (ACE_OS::strcmp(loggerName, "default") == 0)
	    			containers[i].reference->set_default_logLevels(logLevels);
				else
	    			containers[i].reference->set_logLevels(loggerName, logLevels);
	    	}

			ACS_SHORT_LOG((LM_INFO, "\t... done."));
	    }
	    catch( CORBA::Exception &ex )
	    {
	        ACS_SHORT_LOG((LM_INFO, "... failed!"));
			ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, ACE_TEXT ("Exception caught while calling remote method."));
	    }

	}

	ACS_SHORT_LOG((LM_INFO, "Done all."));

    }
  catch( CORBA::Exception &ex )
  {
      ACS_SHORT_LOG((LM_INFO, "Failed."));
      ACE_PRINT_EXCEPTION (ex,
                           ACE_TEXT ("Caught unexpected exception:"));

      return -1;
  }

  return 0;
}

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#ifndef itkPriorityQueueContainer_hxx
#define itkPriorityQueueContainer_hxx

#include <utility>

#include "itkNumericTraits.h"
#include "itkPriorityQueueContainer.h"

namespace itk
{

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementIdentifier>
const typename ElementWrapperInterface<TElement, TElementIdentifier>::ElementIdentifierType
  ElementWrapperInterface<TElement, TElementIdentifier>::m_ElementNotFound = NumericTraits<TElementIdentifier>::max();
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
typename ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::ElementIdentifierType
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::GetLocation(
  const ElementWrapperPointerType & element) const
{
  return ((*element).GetLocation(*element));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
void
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::SetLocation(
  ElementWrapperPointerType &   element,
  const ElementIdentifierType & identifier)
{
  (*element).SetLocation(*element, identifier);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
bool
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::is_less(
  const ElementWrapperPointerType & element1,
  const ElementWrapperPointerType & element2) const
{
  return ((*element1).is_less((*element1), (*element2)));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
bool
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::is_greater(
  const ElementWrapperPointerType & element1,
  const ElementWrapperPointerType & element2) const
{
  return ((*element1).is_greater((*element1), (*element2)));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementIdentifier>
const TElementIdentifier ElementWrapperPointerInterface<TElement, TElementIdentifier>::m_ElementNotFound =
  NumericTraits<TElementIdentifier>::max();
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// MinPriorityQueueElementWrapper
// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MinPriorityQueueElementWrapper()
  : m_Element(NumericTraits<TElement>::ZeroValue())
  , m_Priority(NumericTraits<TElementPriority>::ZeroValue())
  , m_Location(Superclass::m_ElementNotFound)
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MinPriorityQueueElementWrapper(
  ElementType         element,
  ElementPriorityType priority)
  : m_Element(element)
  , m_Priority(std::move(priority))
  , m_Location(Superclass::m_ElementNotFound)
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::operator>(
  const MinPriorityQueueElementWrapper & other) const
{
  return this->m_Priority > other.m_Priority;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::operator<(
  const MinPriorityQueueElementWrapper & other) const
{
  return this->m_Priority < other.m_Priority;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::operator==(
  const MinPriorityQueueElementWrapper & other) const
{
  return this->m_Priority == other.m_Priority;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
typename MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::ElementIdentifierType
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::GetLocation(
  const MinPriorityQueueElementWrapper & element) const
{
  return element.m_Location;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
void
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::SetLocation(
  MinPriorityQueueElementWrapper & element,
  const ElementIdentifierType &    identifier)
{
  element.m_Location = identifier;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_less(
  const MinPriorityQueueElementWrapper & element1,
  const MinPriorityQueueElementWrapper & element2) const
{
  return (element1 < element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_greater(
  const MinPriorityQueueElementWrapper & element1,
  const MinPriorityQueueElementWrapper & element2) const
{
  return (element1 > element2);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// MaxPriorityQueueElementWrapper
// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MaxPriorityQueueElementWrapper()
  : Superclass()
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MaxPriorityQueueElementWrapper(
  ElementType         element,
  ElementPriorityType priority)
  : Superclass(element, priority)
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_less(
  const MaxPriorityQueueElementWrapper & element1,
  const MaxPriorityQueueElementWrapper & element2) const
{
  return (element1 > element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_less(
  const Superclass & element1,
  const Superclass & element2) const
{
  return Superclass::is_less(element1, element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_greater(
  const MaxPriorityQueueElementWrapper & element1,
  const MaxPriorityQueueElementWrapper & element2) const
{
  return (element1 < element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_greater(
  const Superclass & element1,
  const Superclass & element2) const
{
  return Superclass::is_greater(element1, element2);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// PriorityQueueContainer
// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
const TElementIdentifier
  PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::
    m_ElementNotFound = NumericTraits<TElementIdentifier>::max();
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::
  PriorityQueueContainer()
  : Superclass()
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Clear()
{
  this->Initialize();
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
bool
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Empty() const
{
  return (this->empty());
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Push(
  ElementWrapperType element)
{
  this->push_back(element);
  this->UpdateUpTree(this->Size() - 1);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
const typename PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::
  ElementWrapperType &
  PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Peek() const
{
  if (Empty())
  {
    itkGenericExceptionMacro(<< "Empty PriorityQueueContainer");
  }
  return (GetElementAtLocation(0));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Pop()
{
  m_Interface.SetLocation(this->front(), // GetElementAtLocation(0),
                          m_ElementNotFound);
  if (this->Size() > 1)
  {
    SetElementAtLocation(0, this->back()); // GetElementAtLocation( this->Size() - 1 ) );
    this->pop_back();
    UpdateDownTree(0);
  }
  else
  {
    if (this->Size() == 1)
    {
      this->pop_back();
    }
  }
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
bool
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Update(
  const ElementWrapperType & element)
{
  ElementIdentifierType location = m_Interface.GetLocation(element);

  if (location != m_ElementNotFound)
  {
    if (location >= this->Size())
    {
      itkGenericExceptionMacro(<< " ElementWrapperType location is out of range");
    }
    UpdateDownTree(location);
    UpdateUpTree(location);

    return true;
  }
  return false;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
bool
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::DeleteElement(
  const ElementWrapperType & element)
{
  ElementIdentifierType location = m_Interface.GetLocation(element);

  if (location != m_ElementNotFound)
  {
    // m_Interface.SetLocation(element, m_ElementNotFound);

    ElementIdentifierType tsize = this->Size();

    if (location >= tsize)
    {
      itkGenericExceptionMacro(<< " ElementWrapperType location is out of range");
    }
    else
    {
      if (location == tsize - 1)
      {
        this->pop_back();
      }
      else
      {
        SetElementAtLocation(location, GetElementAtLocation(tsize - 1));
        this->pop_back();
        UpdateDownTree(location);
        UpdateUpTree(location);
      }
    }
    return true;
  }
  return false;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::UpdateUpTree(
  const ElementIdentifierType & identifier)
{
  if (HasParent(identifier))
  {
    ElementIdentifierType id(identifier);
    ElementWrapperType    element = GetElementAtLocation(id);
    ElementIdentifierType parentIdentifier = GetParent(id);
    ElementWrapperType    parent_element = GetElementAtLocation(parentIdentifier);

    while (HasParent(id) && m_Interface.is_less(element, parent_element))
    {
      SetElementAtLocation(id, parent_element);
      id = parentIdentifier;
      if (HasParent(id))
      {
        parentIdentifier = GetParent(id);
        parent_element = GetElementAtLocation(parentIdentifier);
      }
    }
    SetElementAtLocation(id, element);
  }
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::UpdateDownTree(
  const ElementIdentifierType & identifier)
{
  ElementIdentifierType id(identifier);
  ElementWrapperType    element = GetElementAtLocation(id);

  ElementIdentifierType queueSize = this->Size();

  while (id < queueSize)
  {
    ElementIdentifierType childIdentifier = GetLeft(id);
    if (childIdentifier >= queueSize)
    {
      break;
    }
    if ((childIdentifier + 1 < queueSize) &&
        (m_Interface.is_less(GetElementAtLocation(childIdentifier + 1), GetElementAtLocation(childIdentifier))))
    {
      ++childIdentifier;
    }
    ElementWrapperType temp = GetElementAtLocation(childIdentifier);
    if (m_Interface.is_less(element, temp))
    {
      break;
    }

    SetElementAtLocation(id, temp);
    id = childIdentifier;
  }

  SetElementAtLocation(id, element);
}
// -----------------------------------------------------------------------------
} // namespace itk

#endif // itkPriorityQueueContainer_hxx
<commit_msg>BUG: MinPriorityQueueElementWrapper constructor needs default constructor<commit_after>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#ifndef itkPriorityQueueContainer_hxx
#define itkPriorityQueueContainer_hxx

#include <utility>

#include "itkNumericTraits.h"
#include "itkPriorityQueueContainer.h"

namespace itk
{

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementIdentifier>
const typename ElementWrapperInterface<TElement, TElementIdentifier>::ElementIdentifierType
  ElementWrapperInterface<TElement, TElementIdentifier>::m_ElementNotFound = NumericTraits<TElementIdentifier>::max();
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
typename ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::ElementIdentifierType
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::GetLocation(
  const ElementWrapperPointerType & element) const
{
  return ((*element).GetLocation(*element));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
void
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::SetLocation(
  ElementWrapperPointerType &   element,
  const ElementIdentifierType & identifier)
{
  (*element).SetLocation(*element, identifier);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
bool
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::is_less(
  const ElementWrapperPointerType & element1,
  const ElementWrapperPointerType & element2) const
{
  return ((*element1).is_less((*element1), (*element2)));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapperPointer, typename TElementIdentifier>
bool
ElementWrapperPointerInterface<TElementWrapperPointer, TElementIdentifier>::is_greater(
  const ElementWrapperPointerType & element1,
  const ElementWrapperPointerType & element2) const
{
  return ((*element1).is_greater((*element1), (*element2)));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementIdentifier>
const TElementIdentifier ElementWrapperPointerInterface<TElement, TElementIdentifier>::m_ElementNotFound =
  NumericTraits<TElementIdentifier>::max();
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// MinPriorityQueueElementWrapper
// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MinPriorityQueueElementWrapper()
  : m_Location(Superclass::m_ElementNotFound)
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MinPriorityQueueElementWrapper(
  ElementType         element,
  ElementPriorityType priority)
  : m_Element(element)
  , m_Priority(std::move(priority))
  , m_Location(Superclass::m_ElementNotFound)
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::operator>(
  const MinPriorityQueueElementWrapper & other) const
{
  return this->m_Priority > other.m_Priority;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::operator<(
  const MinPriorityQueueElementWrapper & other) const
{
  return this->m_Priority < other.m_Priority;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::operator==(
  const MinPriorityQueueElementWrapper & other) const
{
  return this->m_Priority == other.m_Priority;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
typename MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::ElementIdentifierType
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::GetLocation(
  const MinPriorityQueueElementWrapper & element) const
{
  return element.m_Location;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
void
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::SetLocation(
  MinPriorityQueueElementWrapper & element,
  const ElementIdentifierType &    identifier)
{
  element.m_Location = identifier;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_less(
  const MinPriorityQueueElementWrapper & element1,
  const MinPriorityQueueElementWrapper & element2) const
{
  return (element1 < element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MinPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_greater(
  const MinPriorityQueueElementWrapper & element1,
  const MinPriorityQueueElementWrapper & element2) const
{
  return (element1 > element2);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// MaxPriorityQueueElementWrapper
// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MaxPriorityQueueElementWrapper()
  : Superclass()
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::MaxPriorityQueueElementWrapper(
  ElementType         element,
  ElementPriorityType priority)
  : Superclass(element, priority)
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_less(
  const MaxPriorityQueueElementWrapper & element1,
  const MaxPriorityQueueElementWrapper & element2) const
{
  return (element1 > element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_less(
  const Superclass & element1,
  const Superclass & element2) const
{
  return Superclass::is_less(element1, element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_greater(
  const MaxPriorityQueueElementWrapper & element1,
  const MaxPriorityQueueElementWrapper & element2) const
{
  return (element1 < element2);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElement, typename TElementPriority, typename TElementIdentifier>
bool
MaxPriorityQueueElementWrapper<TElement, TElementPriority, TElementIdentifier>::is_greater(
  const Superclass & element1,
  const Superclass & element2) const
{
  return Superclass::is_greater(element1, element2);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// PriorityQueueContainer
// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
const TElementIdentifier
  PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::
    m_ElementNotFound = NumericTraits<TElementIdentifier>::max();
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::
  PriorityQueueContainer()
  : Superclass()
{}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Clear()
{
  this->Initialize();
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
bool
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Empty() const
{
  return (this->empty());
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Push(
  ElementWrapperType element)
{
  this->push_back(element);
  this->UpdateUpTree(this->Size() - 1);
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
const typename PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::
  ElementWrapperType &
  PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Peek() const
{
  if (Empty())
  {
    itkGenericExceptionMacro(<< "Empty PriorityQueueContainer");
  }
  return (GetElementAtLocation(0));
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Pop()
{
  m_Interface.SetLocation(this->front(), // GetElementAtLocation(0),
                          m_ElementNotFound);
  if (this->Size() > 1)
  {
    SetElementAtLocation(0, this->back()); // GetElementAtLocation( this->Size() - 1 ) );
    this->pop_back();
    UpdateDownTree(0);
  }
  else
  {
    if (this->Size() == 1)
    {
      this->pop_back();
    }
  }
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
bool
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::Update(
  const ElementWrapperType & element)
{
  ElementIdentifierType location = m_Interface.GetLocation(element);

  if (location != m_ElementNotFound)
  {
    if (location >= this->Size())
    {
      itkGenericExceptionMacro(<< " ElementWrapperType location is out of range");
    }
    UpdateDownTree(location);
    UpdateUpTree(location);

    return true;
  }
  return false;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
bool
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::DeleteElement(
  const ElementWrapperType & element)
{
  ElementIdentifierType location = m_Interface.GetLocation(element);

  if (location != m_ElementNotFound)
  {
    // m_Interface.SetLocation(element, m_ElementNotFound);

    ElementIdentifierType tsize = this->Size();

    if (location >= tsize)
    {
      itkGenericExceptionMacro(<< " ElementWrapperType location is out of range");
    }
    else
    {
      if (location == tsize - 1)
      {
        this->pop_back();
      }
      else
      {
        SetElementAtLocation(location, GetElementAtLocation(tsize - 1));
        this->pop_back();
        UpdateDownTree(location);
        UpdateUpTree(location);
      }
    }
    return true;
  }
  return false;
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::UpdateUpTree(
  const ElementIdentifierType & identifier)
{
  if (HasParent(identifier))
  {
    ElementIdentifierType id(identifier);
    ElementWrapperType    element = GetElementAtLocation(id);
    ElementIdentifierType parentIdentifier = GetParent(id);
    ElementWrapperType    parent_element = GetElementAtLocation(parentIdentifier);

    while (HasParent(id) && m_Interface.is_less(element, parent_element))
    {
      SetElementAtLocation(id, parent_element);
      id = parentIdentifier;
      if (HasParent(id))
      {
        parentIdentifier = GetParent(id);
        parent_element = GetElementAtLocation(parentIdentifier);
      }
    }
    SetElementAtLocation(id, element);
  }
}
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
template <typename TElementWrapper,
          typename TElementWrapperInterface,
          typename TElementPriority,
          typename TElementIdentifier>
void
PriorityQueueContainer<TElementWrapper, TElementWrapperInterface, TElementPriority, TElementIdentifier>::UpdateDownTree(
  const ElementIdentifierType & identifier)
{
  ElementIdentifierType id(identifier);
  ElementWrapperType    element = GetElementAtLocation(id);

  ElementIdentifierType queueSize = this->Size();

  while (id < queueSize)
  {
    ElementIdentifierType childIdentifier = GetLeft(id);
    if (childIdentifier >= queueSize)
    {
      break;
    }
    if ((childIdentifier + 1 < queueSize) &&
        (m_Interface.is_less(GetElementAtLocation(childIdentifier + 1), GetElementAtLocation(childIdentifier))))
    {
      ++childIdentifier;
    }
    ElementWrapperType temp = GetElementAtLocation(childIdentifier);
    if (m_Interface.is_less(element, temp))
    {
      break;
    }

    SetElementAtLocation(id, temp);
    id = childIdentifier;
  }

  SetElementAtLocation(id, element);
}
// -----------------------------------------------------------------------------
} // namespace itk

#endif // itkPriorityQueueContainer_hxx
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// semantic relations module
#include "mitkControlPointManager.h"
#include "mitkDICOMHelper.h"
#include "mitkUIDGeneratorBoost.h"

// mitk core
#include <mitkPropertyNameHelper.h>

double CalculateDistanceInDays(const mitk::SemanticTypes::ControlPoint& leftControlPoint, const mitk::SemanticTypes::ControlPoint& rightControlPoint);

mitk::SemanticTypes::ControlPoint mitk::GenerateControlPoint(const DataNode* datanode)
{
  SemanticTypes::ControlPoint controlPoint = GetDICOMDateFromDataNode(datanode);
  controlPoint.UID = UIDGeneratorBoost::GenerateUID();

  return controlPoint;
}

mitk::SemanticTypes::ControlPoint mitk::GetControlPointByUID(const SemanticTypes::ID& controlPointUID, const std::vector<SemanticTypes::ControlPoint>& allControlPoints)
{
  auto lambda = [&controlPointUID](const SemanticTypes::ControlPoint& currentControlPoint)
  {
    return currentControlPoint.UID == controlPointUID;
  };

  const auto existingControlPoint = std::find_if(allControlPoints.begin(), allControlPoints.end(), lambda);

  mitk::SemanticTypes::ControlPoint controlPoint;
  if (existingControlPoint != allControlPoints.end())
  {
    controlPoint = *existingControlPoint;
  }

  return controlPoint;
}

std::string mitk::GetControlPointAsString(const SemanticTypes::ControlPoint& controlPoint)
{
  std::stringstream controlPointAsString;
  controlPointAsString << std::to_string(controlPoint.year) << "-"
    << std::setfill('0') << std::setw(2) << std::to_string(controlPoint.month) << "-"
    << std::setfill('0') << std::setw(2) << std::to_string(controlPoint.day);

  return controlPointAsString.str();
}

mitk::SemanticTypes::ControlPoint mitk::FindExistingControlPoint(const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ControlPointVector& allControlPoints)
{
  for (const auto& currentControlPoint : allControlPoints)
  {
    if (controlPoint == currentControlPoint)
    {
      return currentControlPoint;
    }
  }

  return SemanticTypes::ControlPoint();
}

mitk::SemanticTypes::ControlPoint mitk::FindClosestControlPoint(const SemanticTypes::ControlPoint& controlPoint, SemanticTypes::ControlPointVector& allControlPoints)
{
  if (allControlPoints.empty())
  {
    return SemanticTypes::ControlPoint();
  }

  // sort the vector of control points for easier lookup
  std::sort(allControlPoints.begin(), allControlPoints.end());
  // new control point does not match an existing control point
  // check if the control point is close to an already existing control point
  std::vector<SemanticTypes::ControlPoint>::const_iterator it;
  for (it = allControlPoints.begin(); it != allControlPoints.end(); ++it)
  {
    if (controlPoint < *it)
    {
      break;
    }
  }

  SemanticTypes::ControlPoint nextControlPoint;
  SemanticTypes::ControlPoint previousControlPoint;
  if (it == allControlPoints.begin())
  {
    // new date is smaller ("older") than the smallest already existing control point
    nextControlPoint = *it;
  }
  else if (it != allControlPoints.end())
  {
    // new date is greater ("newer") than an already existing control point,
    // but smaller ("older") than another already existing control point
    nextControlPoint = *it;
    previousControlPoint = *(--it);
  }
  else
  {
    // new date is greater ("newer") than the greatest already existing control point
    previousControlPoint = *(--it);
  }

  // test distance to next and previous time period
  double distanceToNextExaminationPeriod = CalculateDistanceInDays(nextControlPoint, controlPoint);
  double distanceToPreviousExaminationPeriod = CalculateDistanceInDays(previousControlPoint, controlPoint);

  SemanticTypes::ControlPoint closestControlPoint;
  double closestDistanceInDays = 0.0;
  if (distanceToNextExaminationPeriod < distanceToPreviousExaminationPeriod)
  {
    // control point is closer to the next control point
    closestControlPoint = nextControlPoint;
    closestDistanceInDays = distanceToNextExaminationPeriod;
  }
  else
  {
    // control point is closer to the previous control point
    closestControlPoint = previousControlPoint;
    closestDistanceInDays = distanceToPreviousExaminationPeriod;
  }

  double THRESHOLD_DISTANCE_IN_DAYS = 30.0;
  if (std::abs(closestDistanceInDays) < THRESHOLD_DISTANCE_IN_DAYS)
  {
    return closestControlPoint;
  }

  return SemanticTypes::ControlPoint();
}

mitk::SemanticTypes::ExaminationPeriod mitk::FindExaminationPeriod(const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriodVector& allExaminationPeriods)
{
  for (const auto& examinationPeriod : allExaminationPeriods)
  {
    for (const auto& UID : examinationPeriod.controlPointUIDs)
    {
      if (controlPoint.UID == UID)
      {
        return examinationPeriod;
      }
    }
  }

  return SemanticTypes::ExaminationPeriod();
}

void mitk::SortExaminationPeriods(SemanticTypes::ExaminationPeriodVector& allExaminationPeriods, const SemanticTypes::ControlPointVector& allControlPoints)
{
  auto lambda = [allControlPoints](const SemanticTypes::ExaminationPeriod& leftExaminationPeriod, const SemanticTypes::ExaminationPeriod& rightExaminationPeriod)
  {
    if (leftExaminationPeriod.controlPointUIDs.empty())
    {
      return true;
    }

    if (rightExaminationPeriod.controlPointUIDs.empty())
    {
      return false;
    }
    const auto leftUID = leftExaminationPeriod.controlPointUIDs.front();
    const auto rightUID = rightExaminationPeriod.controlPointUIDs.front();
    const auto& leftControlPoint = GetControlPointByUID(leftUID, allControlPoints);
    const auto& rightControlPoint = GetControlPointByUID(rightUID, allControlPoints);

    return leftControlPoint < rightControlPoint;
  };

  std::sort(allExaminationPeriods.begin(), allExaminationPeriods.end(), lambda);
}

double CalculateDistanceInDays(const mitk::SemanticTypes::ControlPoint& leftControlPoint, const mitk::SemanticTypes::ControlPoint& rightControlPoint)
{
  std::tm leftTimeStructure = { 0, 0, 0, leftControlPoint.day,  leftControlPoint.month - 1,   leftControlPoint.year - 1900 };
  std::tm rightTimeStructure = { 0, 0, 0, rightControlPoint.day, rightControlPoint.month - 1,  rightControlPoint.year - 1900 };

  time_t leftTime = mktime(&leftTimeStructure);
  time_t rightTime = mktime(&rightTimeStructure);

  if (leftTime == -1 || rightTime == -1)
  {
    // date is not initialized, no difference can be computed
    return std::numeric_limits<double>::max();
  }

  // compute distance here
  double secondsPerDay = 60 * 60 * 24;
  double timeDifferenceInDays = std::difftime(leftTime, rightTime) / secondsPerDay;

  return timeDifferenceInDays;
}
<commit_msg>Fix time distance computation<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// semantic relations module
#include "mitkControlPointManager.h"
#include "mitkDICOMHelper.h"
#include "mitkUIDGeneratorBoost.h"

// mitk core
#include <mitkPropertyNameHelper.h>

double CalculateDistanceInDays(const mitk::SemanticTypes::ControlPoint& leftControlPoint, const mitk::SemanticTypes::ControlPoint& rightControlPoint);

mitk::SemanticTypes::ControlPoint mitk::GenerateControlPoint(const DataNode* datanode)
{
  SemanticTypes::ControlPoint controlPoint = GetDICOMDateFromDataNode(datanode);
  controlPoint.UID = UIDGeneratorBoost::GenerateUID();

  return controlPoint;
}

mitk::SemanticTypes::ControlPoint mitk::GetControlPointByUID(const SemanticTypes::ID& controlPointUID, const std::vector<SemanticTypes::ControlPoint>& allControlPoints)
{
  auto lambda = [&controlPointUID](const SemanticTypes::ControlPoint& currentControlPoint)
  {
    return currentControlPoint.UID == controlPointUID;
  };

  const auto existingControlPoint = std::find_if(allControlPoints.begin(), allControlPoints.end(), lambda);

  mitk::SemanticTypes::ControlPoint controlPoint;
  if (existingControlPoint != allControlPoints.end())
  {
    controlPoint = *existingControlPoint;
  }

  return controlPoint;
}

std::string mitk::GetControlPointAsString(const SemanticTypes::ControlPoint& controlPoint)
{
  std::stringstream controlPointAsString;
  controlPointAsString << std::to_string(controlPoint.year) << "-"
    << std::setfill('0') << std::setw(2) << std::to_string(controlPoint.month) << "-"
    << std::setfill('0') << std::setw(2) << std::to_string(controlPoint.day);

  return controlPointAsString.str();
}

mitk::SemanticTypes::ControlPoint mitk::FindExistingControlPoint(const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ControlPointVector& allControlPoints)
{
  for (const auto& currentControlPoint : allControlPoints)
  {
    if (controlPoint == currentControlPoint)
    {
      return currentControlPoint;
    }
  }

  return SemanticTypes::ControlPoint();
}

mitk::SemanticTypes::ControlPoint mitk::FindClosestControlPoint(const SemanticTypes::ControlPoint& controlPoint, SemanticTypes::ControlPointVector& allControlPoints)
{
  if (allControlPoints.empty())
  {
    return SemanticTypes::ControlPoint();
  }

  // sort the vector of control points for easier lookup
  std::sort(allControlPoints.begin(), allControlPoints.end());
  // new control point does not match an existing control point
  // check if the control point is close to an already existing control point
  std::vector<SemanticTypes::ControlPoint>::const_iterator it;
  for (it = allControlPoints.begin(); it != allControlPoints.end(); ++it)
  {
    if (controlPoint < *it)
    {
      break;
    }
  }

  SemanticTypes::ControlPoint nextControlPoint;
  SemanticTypes::ControlPoint previousControlPoint;
  if (it == allControlPoints.begin())
  {
    // new date is smaller ("older") than the smallest already existing control point
    nextControlPoint = *it;
  }
  else if (it != allControlPoints.end())
  {
    // new date is greater ("newer") than an already existing control point,
    // but smaller ("older") than another already existing control point
    nextControlPoint = *it;
    previousControlPoint = *(--it);
  }
  else
  {
    // new date is greater ("newer") than the greatest already existing control point
    previousControlPoint = *(--it);
  }

  // test distance to next and previous time period
  double distanceToNextExaminationPeriod = CalculateDistanceInDays(nextControlPoint, controlPoint);
  double distanceToPreviousExaminationPeriod = CalculateDistanceInDays(previousControlPoint, controlPoint);

  SemanticTypes::ControlPoint closestControlPoint;
  double closestDistanceInDays = 0.0;
  if (distanceToNextExaminationPeriod < distanceToPreviousExaminationPeriod)
  {
    // control point is closer to the next control point
    closestControlPoint = nextControlPoint;
    closestDistanceInDays = distanceToNextExaminationPeriod;
  }
  else
  {
    // control point is closer to the previous control point
    closestControlPoint = previousControlPoint;
    closestDistanceInDays = distanceToPreviousExaminationPeriod;
  }

  double THRESHOLD_DISTANCE_IN_DAYS = 30.0;
  if (closestDistanceInDays < THRESHOLD_DISTANCE_IN_DAYS)
  {
    return closestControlPoint;
  }

  return SemanticTypes::ControlPoint();
}

mitk::SemanticTypes::ExaminationPeriod mitk::FindExaminationPeriod(const SemanticTypes::ControlPoint& controlPoint, const SemanticTypes::ExaminationPeriodVector& allExaminationPeriods)
{
  for (const auto& examinationPeriod : allExaminationPeriods)
  {
    for (const auto& UID : examinationPeriod.controlPointUIDs)
    {
      if (controlPoint.UID == UID)
      {
        return examinationPeriod;
      }
    }
  }

  return SemanticTypes::ExaminationPeriod();
}

void mitk::SortExaminationPeriods(SemanticTypes::ExaminationPeriodVector& allExaminationPeriods, const SemanticTypes::ControlPointVector& allControlPoints)
{
  auto lambda = [allControlPoints](const SemanticTypes::ExaminationPeriod& leftExaminationPeriod, const SemanticTypes::ExaminationPeriod& rightExaminationPeriod)
  {
    if (leftExaminationPeriod.controlPointUIDs.empty())
    {
      return true;
    }

    if (rightExaminationPeriod.controlPointUIDs.empty())
    {
      return false;
    }
    const auto leftUID = leftExaminationPeriod.controlPointUIDs.front();
    const auto rightUID = rightExaminationPeriod.controlPointUIDs.front();
    const auto& leftControlPoint = GetControlPointByUID(leftUID, allControlPoints);
    const auto& rightControlPoint = GetControlPointByUID(rightUID, allControlPoints);

    return leftControlPoint < rightControlPoint;
  };

  std::sort(allExaminationPeriods.begin(), allExaminationPeriods.end(), lambda);
}

double CalculateDistanceInDays(const mitk::SemanticTypes::ControlPoint& leftControlPoint, const mitk::SemanticTypes::ControlPoint& rightControlPoint)
{
  std::tm leftTimeStructure = { 0, 0, 0, leftControlPoint.day,  leftControlPoint.month - 1,   leftControlPoint.year - 1900 };
  std::tm rightTimeStructure = { 0, 0, 0, rightControlPoint.day, rightControlPoint.month - 1,  rightControlPoint.year - 1900 };

  time_t leftTime = mktime(&leftTimeStructure);
  time_t rightTime = mktime(&rightTimeStructure);

  if (leftTime == -1 || rightTime == -1)
  {
    // date is not initialized, no difference can be computed
    return std::numeric_limits<double>::max();
  }

  // compute distance here
  double secondsPerDay = 60 * 60 * 24;
  double timeDifferenceInDays = std::difftime(leftTime, rightTime) / secondsPerDay;

  return std::abs(timeDifferenceInDays);
}
<|endoftext|>


<commit_before><commit_msg>Fix Keywords to run on MC on the Fly<commit_after><|endoftext|>


<commit_before><commit_msg>Updating AddTask and Config files for DCA analysis<commit_after><|endoftext|>


<commit_before>#include "DepthBufferCube.h"

using namespace Device;
using namespace Rendering;
using namespace Rendering::Texture;

void DepthBufferCube::Initialize(Device::DirectX& dx, const Size<uint>& size, bool useShaderResource)
{
	uint bindFlag =	D3D11_BIND_DEPTH_STENCIL |
					(useShaderResource ? D3D11_BIND_SHADER_RESOURCE : 0);

	D3D11_TEXTURE2D_DESC texDesc;
	memset(&texDesc, 0, sizeof(D3D11_TEXTURE2D_DESC));

	texDesc.Width				= size.w;
	texDesc.Height				= size.h;
	texDesc.MipLevels			= 1;
	texDesc.ArraySize			= 6;
	texDesc.Format				= DXGI_FORMAT_D32_FLOAT;
	texDesc.Usage				= D3D11_USAGE_DEFAULT;
	texDesc.BindFlags			= bindFlag;
	texDesc.MiscFlags			= D3D11_RESOURCE_MISC_TEXTURECUBE;
	texDesc.CPUAccessFlags		= 0;
	texDesc.SampleDesc.Count	= 1;
	texDesc.SampleDesc.Quality	= 0;

	_texture = dx.CreateTexture2D(texDesc);

	D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
	memset(&dsvDesc, 0, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC));
	dsvDesc.Format				= DXGI_FORMAT_D32_FLOAT;
	dsvDesc.ViewDimension		= D3D11_DSV_DIMENSION_TEXTURE2DARRAY;

	dsvDesc.Texture2DArray.FirstArraySlice	= 0;
	dsvDesc.Texture2DArray.ArraySize		= 6;
	dsvDesc.Texture2DArray.MipSlice			= 0;

	_depthStencilView = dx.CreateDepthStencilView(_texture.GetRaw(), dsvDesc);
}

void DepthBufferCube::Clear(Device::DirectX& dx, float depth, unsigned char stencil)
{
	dx.GetContext()->ClearDepthStencilView(_depthStencilView.GetRaw(), D3D11_CLEAR_DEPTH, depth, stencil);
}<commit_msg>Update DepthBufferCube.cpp<commit_after>#include "DepthBufferCube.h"

using namespace Device;
using namespace Rendering;
using namespace Rendering::Texture;

void DepthBufferCube::Initialize(Device::DirectX& dx, const Size<uint>& size, bool useShaderResource)
{
	uint bindFlag =	D3D11_BIND_DEPTH_STENCIL |
					(useShaderResource ? D3D11_BIND_SHADER_RESOURCE : 0);

	D3D11_TEXTURE2D_DESC texDesc;
	memset(&texDesc, 0, sizeof(D3D11_TEXTURE2D_DESC));

	texDesc.Width				= size.w;
	texDesc.Height				= size.h;
	texDesc.MipLevels			= 1;
	texDesc.ArraySize			= 6;
	texDesc.Format				= DXGI_FORMAT_D32_FLOAT;
	texDesc.Usage				= D3D11_USAGE_DEFAULT;
	texDesc.BindFlags			= bindFlag;
	texDesc.MiscFlags			= D3D11_RESOURCE_MISC_TEXTURECUBE;
	texDesc.CPUAccessFlags		= 0;
	texDesc.SampleDesc.Count	= 1;
	texDesc.SampleDesc.Quality	= 0;

	_texture = dx.CreateTexture2D(texDesc);

	D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc;
	memset(&dsvDesc, 0, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC));
	dsvDesc.Format				= DXGI_FORMAT_D32_FLOAT;
	dsvDesc.ViewDimension		= D3D11_DSV_DIMENSION_TEXTURE2DARRAY;

	dsvDesc.Texture2DArray.FirstArraySlice	= 0;
	dsvDesc.Texture2DArray.ArraySize		= 6;
	dsvDesc.Texture2DArray.MipSlice			= 0;

	_depthStencilView = dx.CreateDepthStencilView(_texture.GetRaw(), dsvDesc);

	if(useShaderResource)
		_srv.InitializeUsingTexture(dx, _texture, DXGI_FORMAT_R32_TYPELESS, 1, D3D11_SRV_DIMENSION_TEXTURE2D);
}

void DepthBufferCube::Clear(Device::DirectX& dx, float depth, unsigned char stencil)
{
	dx.GetContext()->ClearDepthStencilView(_depthStencilView.GetRaw(), D3D11_CLEAR_DEPTH, depth, stencil);
}
<|endoftext|>


<commit_before>#include <boost/smart_ptr.hpp>
#include <vector>
#include <iostream>
#include <Common/Timer.h>

//////////////////////////////////////////////////

template <typename T>
void intrusive_ptr_add_ref(T* p)
{
	++(p->refCount_);
}

template <typename T>
void intrusive_ptr_release(T* p)
{
	if ( ! --p->refCount_ ) delete p;
}

//////////////////////////////////////////////////

template<typename T>
class CRefCounted
{
	friend void intrusive_ptr_add_ref<T>(T* p);
  friend void intrusive_ptr_release<T>(T* p);
	std::atomic<int> refCount_{0};
};

//////////////////////////////////////////////////

class ClassWithVector : public CRefCounted<ClassWithVector>
{
public:
  ClassWithVector() : data_(1024) {}

private:
	std::vector<double> data_;
};

//////////////////////////////////////////////////

class ClassWithArray : public CRefCounted<ClassWithArray>
{
public:
  ClassWithArray() { std::fill(std::begin(data_), std::end(data_), 0); }

private:
	std::array<double,1024> data_;
};

//////////////////////////////////////////////////

class CheapClass : public CRefCounted<CheapClass> {};

//////////////////////////////////////////////////

template <typename T>
void RunDefaultConstructableObjectTimings(size_t objectCount, const char* objectName)
{
	std::cout << objectName << std::endl;

	{
		// No timing, warm up the heap
		for ( int i=0; i<1; ++i )
		{
			std::vector<std::shared_ptr<T>> objects;
			std::generate_n(std::back_inserter(objects), objectCount, []{return std::shared_ptr<T>(new T());});
		}
	}

	{
		auto t = make_timer("std::shared_ptr and new : ", objectName, " ", objectCount);
		std::vector<std::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return std::shared_ptr<T>(new T());});
	}

	{
		auto t = make_timer("std::shared_ptr and make_shared : ", objectName, " ", objectCount);
		std::vector<std::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return std::make_shared<T>();});
	}

	{
		auto t = make_timer("std::unique_ptr and new : ", objectName, " ", objectCount);
		std::vector<std::unique_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return std::unique_ptr<T>(new T());});
	}

	{
		auto t = make_timer("boost::shared_ptr and new : ", objectName, " ", objectCount);
		std::vector<boost::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return boost::shared_ptr<T>(new T());});
	}

	{
		auto t = make_timer("boost::shared_ptr and make_shared : ", objectName, " ", objectCount);
		std::vector<boost::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return boost::make_shared<T>();});
	}

	{
		auto t = make_timer("boost::intrusive_ptr : ", objectName, " ", objectCount);
		std::vector<boost::intrusive_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return boost::intrusive_ptr<T>(new T());});
	}

	{
		auto t = make_timer(objectName, "*  ", objectCount);
		std::vector<T*> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return new T();});
		for(auto o : objects) delete o;
	}

	std::cout << std::endl;
}

//////////////////////////////////////////////////

int main(int argc, char* argv[])
{
  RunDefaultConstructableObjectTimings<ClassWithVector>(5e5, "ClassWithVector");
  RunDefaultConstructableObjectTimings<ClassWithArray>(5e5, "ClassWithArray");
  RunDefaultConstructableObjectTimings<CheapClass>(2e7, "CheapClass");
}

<commit_msg>Fix indenting<commit_after>#include <boost/smart_ptr.hpp>
#include <vector>
#include <iostream>
#include <Common/Timer.h>

//////////////////////////////////////////////////

template <typename T>
void intrusive_ptr_add_ref(T* p)
{
	++(p->refCount_);
}

template <typename T>
void intrusive_ptr_release(T* p)
{
	if ( ! --p->refCount_ ) delete p;
}

//////////////////////////////////////////////////

template<typename T>
class CRefCounted
{
	friend void intrusive_ptr_add_ref<T>(T* p);
	friend void intrusive_ptr_release<T>(T* p);
	std::atomic<int> refCount_{0};
};

//////////////////////////////////////////////////

class ClassWithVector : public CRefCounted<ClassWithVector>
{
public:
  ClassWithVector() : data_(1024) {}

private:
	std::vector<double> data_;
};

//////////////////////////////////////////////////

class ClassWithArray : public CRefCounted<ClassWithArray>
{
public:
  ClassWithArray() { std::fill(std::begin(data_), std::end(data_), 0); }

private:
	std::array<double,1024> data_;
};

//////////////////////////////////////////////////

class CheapClass : public CRefCounted<CheapClass> {};

//////////////////////////////////////////////////

template <typename T>
void RunDefaultConstructableObjectTimings(size_t objectCount, const char* objectName)
{
	std::cout << objectName << std::endl;

	{
		// No timing, warm up the heap
		for ( int i=0; i<1; ++i )
		{
			std::vector<std::shared_ptr<T>> objects;
			std::generate_n(std::back_inserter(objects), objectCount, []{return std::shared_ptr<T>(new T());});
		}
	}

	{
		auto t = make_timer("std::shared_ptr and new : ", objectName, " ", objectCount);
		std::vector<std::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return std::shared_ptr<T>(new T());});
	}

	{
		auto t = make_timer("std::shared_ptr and make_shared : ", objectName, " ", objectCount);
		std::vector<std::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return std::make_shared<T>();});
	}

	{
		auto t = make_timer("std::unique_ptr and new : ", objectName, " ", objectCount);
		std::vector<std::unique_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return std::unique_ptr<T>(new T());});
	}

	{
		auto t = make_timer("boost::shared_ptr and new : ", objectName, " ", objectCount);
		std::vector<boost::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return boost::shared_ptr<T>(new T());});
	}

	{
		auto t = make_timer("boost::shared_ptr and make_shared : ", objectName, " ", objectCount);
		std::vector<boost::shared_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return boost::make_shared<T>();});
	}

	{
		auto t = make_timer("boost::intrusive_ptr : ", objectName, " ", objectCount);
		std::vector<boost::intrusive_ptr<T>> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return boost::intrusive_ptr<T>(new T());});
	}

	{
		auto t = make_timer(objectName, "*  ", objectCount);
		std::vector<T*> objects;
		std::generate_n(std::back_inserter(objects), objectCount, []{return new T();});
		for(auto o : objects) delete o;
	}

	std::cout << std::endl;
}

//////////////////////////////////////////////////

int main(int argc, char* argv[])
{
  RunDefaultConstructableObjectTimings<ClassWithVector>(5e5, "ClassWithVector");
  RunDefaultConstructableObjectTimings<ClassWithArray>(5e5, "ClassWithArray");
  RunDefaultConstructableObjectTimings<CheapClass>(2e7, "CheapClass");
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007-2011 Google Inc. 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 Google Inc. 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.
 */

#include "config.h"
#include "V8CSSStyleDeclaration.h"

#include "CSSPropertyNames.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8Binding.h"
#include "core/css/parser/BisonCSSParser.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/css/CSSValue.h"
#include "core/css/RuntimeCSSEnabled.h"
#include "core/events/EventTarget.h"
#include "wtf/ASCIICType.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/StringConcatenate.h"

using namespace WTF;
using namespace std;

namespace WebCore {

// Check for a CSS prefix.
// Passed prefix is all lowercase.
// First character of the prefix within the property name may be upper or lowercase.
// Other characters in the prefix within the property name must be lowercase.
// The prefix within the property name must be followed by a capital letter.
static bool hasCSSPropertyNamePrefix(const String& propertyName, const char* prefix)
{
#ifndef NDEBUG
    ASSERT(*prefix);
    for (const char* p = prefix; *p; ++p)
        ASSERT(isASCIILower(*p));
    ASSERT(propertyName.length());
#endif

    if (toASCIILower(propertyName[0]) != prefix[0])
        return false;

    unsigned length = propertyName.length();
    for (unsigned i = 1; i < length; ++i) {
        if (!prefix[i])
            return isASCIIUpper(propertyName[i]);
        if (propertyName[i] != prefix[i])
            return false;
    }
    return false;
}

struct CSSPropertyInfo {
    CSSPropertyID propID;
};

static CSSPropertyID cssResolvedPropertyID(const String& propertyName)
{
    unsigned length = propertyName.length();
    if (!length)
        return CSSPropertyInvalid;

    StringBuilder builder;
    builder.reserveCapacity(length);

    unsigned i = 0;
    bool hasSeenDash = false;

    if (hasCSSPropertyNamePrefix(propertyName, "css"))
        i += 3;
    else if (hasCSSPropertyNamePrefix(propertyName, "webkit"))
        builder.append('-');
    else if (isASCIIUpper(propertyName[0]))
        return CSSPropertyInvalid;

    bool hasSeenUpper = isASCIIUpper(propertyName[i]);

    builder.append(toASCIILower(propertyName[i++]));

    for (; i < length; ++i) {
        UChar c = propertyName[i];
        if (!isASCIIUpper(c)) {
            if (c == '-')
                hasSeenDash = true;
            builder.append(c);
        } else {
            hasSeenUpper = true;
            builder.append('-');
            builder.append(toASCIILower(c));
        }
    }

    // Reject names containing both dashes and upper-case characters, such as "border-rightColor".
    if (hasSeenDash && hasSeenUpper)
        return CSSPropertyInvalid;

    String propName = builder.toString();
    return cssPropertyID(propName);
}

// When getting properties on CSSStyleDeclarations, the name used from
// Javascript and the actual name of the property are not the same, so
// we have to do the following translation. The translation turns upper
// case characters into lower case characters and inserts dashes to
// separate words.
//
// Example: 'backgroundPositionY' -> 'background-position-y'
//
// Also, certain prefixes such as 'css-' are stripped.
static CSSPropertyInfo* cssPropertyInfo(v8::Handle<v8::String> v8PropertyName)
{
    String propertyName = toCoreString(v8PropertyName);
    typedef HashMap<String, CSSPropertyInfo*> CSSPropertyInfoMap;
    DEFINE_STATIC_LOCAL(CSSPropertyInfoMap, map, ());
    CSSPropertyInfo* propInfo = map.get(propertyName);
    if (!propInfo) {
        propInfo = new CSSPropertyInfo();
        propInfo->propID = cssResolvedPropertyID(propertyName);
        map.add(propertyName, propInfo);
    }
    if (propInfo->propID && RuntimeCSSEnabled::isCSSPropertyEnabled(propInfo->propID))
        return propInfo;
    return 0;
}

void V8CSSStyleDeclaration::namedPropertyEnumeratorCustom(const v8::PropertyCallbackInfo<v8::Array>& info)
{
    typedef Vector<String, numCSSProperties - 1> PreAllocatedPropertyVector;
    DEFINE_STATIC_LOCAL(PreAllocatedPropertyVector, propertyNames, ());
    static unsigned propertyNamesLength = 0;

    if (propertyNames.isEmpty()) {
        for (int id = firstCSSProperty; id <= lastCSSProperty; ++id) {
            CSSPropertyID propertyId = static_cast<CSSPropertyID>(id);
            if (RuntimeCSSEnabled::isCSSPropertyEnabled(propertyId))
                propertyNames.append(getJSPropertyName(propertyId));
        }
        sort(propertyNames.begin(), propertyNames.end(), codePointCompareLessThan);
        propertyNamesLength = propertyNames.size();
    }

    v8::Handle<v8::Array> properties = v8::Array::New(info.GetIsolate(), propertyNamesLength);
    for (unsigned i = 0; i < propertyNamesLength; ++i) {
        String key = propertyNames.at(i);
        ASSERT(!key.isNull());
        properties->Set(v8::Integer::New(info.GetIsolate(), i), v8String(info.GetIsolate(), key));
    }

    v8SetReturnValue(info, properties);
}

void V8CSSStyleDeclaration::namedPropertyQueryCustom(v8::Local<v8::String> v8Name, const v8::PropertyCallbackInfo<v8::Integer>& info)
{
    // NOTE: cssPropertyInfo lookups incur several mallocs.
    // Successful lookups have the same cost the first time, but are cached.
    if (cssPropertyInfo(v8Name)) {
        v8SetReturnValueInt(info, 0);
        return;
    }
}

void V8CSSStyleDeclaration::namedPropertyGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    // First look for API defined attributes on the style declaration object.
    if (info.Holder()->HasRealNamedCallbackProperty(name))
        return;

    // Search the style declaration.
    CSSPropertyInfo* propInfo = cssPropertyInfo(name);

    // Do not handle non-property names.
    if (!propInfo)
        return;

    CSSStyleDeclaration* impl = V8CSSStyleDeclaration::toNative(info.Holder());
    RefPtrWillBeRawPtr<CSSValue> cssValue = impl->getPropertyCSSValueInternal(static_cast<CSSPropertyID>(propInfo->propID));
    if (cssValue) {
        v8SetReturnValueStringOrNull(info, cssValue->cssText(), info.GetIsolate());
        return;
    }

    String result = impl->getPropertyValueInternal(static_cast<CSSPropertyID>(propInfo->propID));
    if (result.isNull())
        result = ""; // convert null to empty string.

    v8SetReturnValueString(info, result, info.GetIsolate());
}

void V8CSSStyleDeclaration::namedPropertySetterCustom(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    CSSStyleDeclaration* impl = V8CSSStyleDeclaration::toNative(info.Holder());
    CSSPropertyInfo* propInfo = cssPropertyInfo(name);
    if (!propInfo)
        return;

    TOSTRING_VOID(V8StringResource<WithNullCheck>, propertyValue, value);
    ExceptionState exceptionState(ExceptionState::SetterContext, getPropertyName(static_cast<CSSPropertyID>(propInfo->propID)), "CSSStyleDeclaration", info.Holder(), info.GetIsolate());
    impl->setPropertyInternal(static_cast<CSSPropertyID>(propInfo->propID), propertyValue, false, exceptionState);

    if (exceptionState.throwIfNeeded())
        return;

    v8SetReturnValue(info, value);
}

} // namespace WebCore
<commit_msg>Drop useless String::isNull() check in V8CSSStyleDeclaration::namedPropertyGetterCustom()<commit_after>/*
 * Copyright (C) 2007-2011 Google Inc. 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 Google Inc. 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.
 */

#include "config.h"
#include "V8CSSStyleDeclaration.h"

#include "CSSPropertyNames.h"
#include "bindings/v8/ExceptionState.h"
#include "bindings/v8/V8Binding.h"
#include "core/css/parser/BisonCSSParser.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSStyleDeclaration.h"
#include "core/css/CSSValue.h"
#include "core/css/RuntimeCSSEnabled.h"
#include "core/events/EventTarget.h"
#include "wtf/ASCIICType.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefPtr.h"
#include "wtf/StdLibExtras.h"
#include "wtf/Vector.h"
#include "wtf/text/StringBuilder.h"
#include "wtf/text/StringConcatenate.h"

using namespace WTF;
using namespace std;

namespace WebCore {

// Check for a CSS prefix.
// Passed prefix is all lowercase.
// First character of the prefix within the property name may be upper or lowercase.
// Other characters in the prefix within the property name must be lowercase.
// The prefix within the property name must be followed by a capital letter.
static bool hasCSSPropertyNamePrefix(const String& propertyName, const char* prefix)
{
#ifndef NDEBUG
    ASSERT(*prefix);
    for (const char* p = prefix; *p; ++p)
        ASSERT(isASCIILower(*p));
    ASSERT(propertyName.length());
#endif

    if (toASCIILower(propertyName[0]) != prefix[0])
        return false;

    unsigned length = propertyName.length();
    for (unsigned i = 1; i < length; ++i) {
        if (!prefix[i])
            return isASCIIUpper(propertyName[i]);
        if (propertyName[i] != prefix[i])
            return false;
    }
    return false;
}

struct CSSPropertyInfo {
    CSSPropertyID propID;
};

static CSSPropertyID cssResolvedPropertyID(const String& propertyName)
{
    unsigned length = propertyName.length();
    if (!length)
        return CSSPropertyInvalid;

    StringBuilder builder;
    builder.reserveCapacity(length);

    unsigned i = 0;
    bool hasSeenDash = false;

    if (hasCSSPropertyNamePrefix(propertyName, "css"))
        i += 3;
    else if (hasCSSPropertyNamePrefix(propertyName, "webkit"))
        builder.append('-');
    else if (isASCIIUpper(propertyName[0]))
        return CSSPropertyInvalid;

    bool hasSeenUpper = isASCIIUpper(propertyName[i]);

    builder.append(toASCIILower(propertyName[i++]));

    for (; i < length; ++i) {
        UChar c = propertyName[i];
        if (!isASCIIUpper(c)) {
            if (c == '-')
                hasSeenDash = true;
            builder.append(c);
        } else {
            hasSeenUpper = true;
            builder.append('-');
            builder.append(toASCIILower(c));
        }
    }

    // Reject names containing both dashes and upper-case characters, such as "border-rightColor".
    if (hasSeenDash && hasSeenUpper)
        return CSSPropertyInvalid;

    String propName = builder.toString();
    return cssPropertyID(propName);
}

// When getting properties on CSSStyleDeclarations, the name used from
// Javascript and the actual name of the property are not the same, so
// we have to do the following translation. The translation turns upper
// case characters into lower case characters and inserts dashes to
// separate words.
//
// Example: 'backgroundPositionY' -> 'background-position-y'
//
// Also, certain prefixes such as 'css-' are stripped.
static CSSPropertyInfo* cssPropertyInfo(v8::Handle<v8::String> v8PropertyName)
{
    String propertyName = toCoreString(v8PropertyName);
    typedef HashMap<String, CSSPropertyInfo*> CSSPropertyInfoMap;
    DEFINE_STATIC_LOCAL(CSSPropertyInfoMap, map, ());
    CSSPropertyInfo* propInfo = map.get(propertyName);
    if (!propInfo) {
        propInfo = new CSSPropertyInfo();
        propInfo->propID = cssResolvedPropertyID(propertyName);
        map.add(propertyName, propInfo);
    }
    if (propInfo->propID && RuntimeCSSEnabled::isCSSPropertyEnabled(propInfo->propID))
        return propInfo;
    return 0;
}

void V8CSSStyleDeclaration::namedPropertyEnumeratorCustom(const v8::PropertyCallbackInfo<v8::Array>& info)
{
    typedef Vector<String, numCSSProperties - 1> PreAllocatedPropertyVector;
    DEFINE_STATIC_LOCAL(PreAllocatedPropertyVector, propertyNames, ());
    static unsigned propertyNamesLength = 0;

    if (propertyNames.isEmpty()) {
        for (int id = firstCSSProperty; id <= lastCSSProperty; ++id) {
            CSSPropertyID propertyId = static_cast<CSSPropertyID>(id);
            if (RuntimeCSSEnabled::isCSSPropertyEnabled(propertyId))
                propertyNames.append(getJSPropertyName(propertyId));
        }
        sort(propertyNames.begin(), propertyNames.end(), codePointCompareLessThan);
        propertyNamesLength = propertyNames.size();
    }

    v8::Handle<v8::Array> properties = v8::Array::New(info.GetIsolate(), propertyNamesLength);
    for (unsigned i = 0; i < propertyNamesLength; ++i) {
        String key = propertyNames.at(i);
        ASSERT(!key.isNull());
        properties->Set(v8::Integer::New(info.GetIsolate(), i), v8String(info.GetIsolate(), key));
    }

    v8SetReturnValue(info, properties);
}

void V8CSSStyleDeclaration::namedPropertyQueryCustom(v8::Local<v8::String> v8Name, const v8::PropertyCallbackInfo<v8::Integer>& info)
{
    // NOTE: cssPropertyInfo lookups incur several mallocs.
    // Successful lookups have the same cost the first time, but are cached.
    if (cssPropertyInfo(v8Name)) {
        v8SetReturnValueInt(info, 0);
        return;
    }
}

void V8CSSStyleDeclaration::namedPropertyGetterCustom(v8::Local<v8::String> name, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    // First look for API defined attributes on the style declaration object.
    if (info.Holder()->HasRealNamedCallbackProperty(name))
        return;

    // Search the style declaration.
    CSSPropertyInfo* propInfo = cssPropertyInfo(name);

    // Do not handle non-property names.
    if (!propInfo)
        return;

    CSSStyleDeclaration* impl = V8CSSStyleDeclaration::toNative(info.Holder());
    RefPtrWillBeRawPtr<CSSValue> cssValue = impl->getPropertyCSSValueInternal(static_cast<CSSPropertyID>(propInfo->propID));
    if (cssValue) {
        v8SetReturnValueStringOrNull(info, cssValue->cssText(), info.GetIsolate());
        return;
    }

    String result = impl->getPropertyValueInternal(static_cast<CSSPropertyID>(propInfo->propID));
    v8SetReturnValueString(info, result, info.GetIsolate());
}

void V8CSSStyleDeclaration::namedPropertySetterCustom(v8::Local<v8::String> name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info)
{
    CSSStyleDeclaration* impl = V8CSSStyleDeclaration::toNative(info.Holder());
    CSSPropertyInfo* propInfo = cssPropertyInfo(name);
    if (!propInfo)
        return;

    TOSTRING_VOID(V8StringResource<WithNullCheck>, propertyValue, value);
    ExceptionState exceptionState(ExceptionState::SetterContext, getPropertyName(static_cast<CSSPropertyID>(propInfo->propID)), "CSSStyleDeclaration", info.Holder(), info.GetIsolate());
    impl->setPropertyInternal(static_cast<CSSPropertyID>(propInfo->propID), propertyValue, false, exceptionState);

    if (exceptionState.throwIfNeeded())
        return;

    v8SetReturnValue(info, value);
}

} // namespace WebCore
<|endoftext|>