<commit_before>/*****************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *****************************************************************************/

#include "commentitemsviewdelegate.h"

#include "views/gametextlabel.h"

#include "lib/models/commentsmodel.h"

#include <KDE/KDebug>

#include <QtGui/QPainter>
#include <QtGui/QSortFilterProxyModel>
#include <QtGui/QApplication>
#include <QtGui/QToolButton>

enum {
    DelegateCommentAuthor,
    DelegateCommentTitle,
    DelegateCommentBody,
    DelegateCommentDateTime,
    DelegateCommentRating,
    DelegateCommentReplyButton
};

static const int PreviewWidth = 96;
static const int PreviewHeight = 72;

using namespace GluonKDEPlayer;

CommentItemsViewDelegate::CommentItemsViewDelegate(QAbstractItemView *itemView, QObject * parent)
        : KWidgetItemDelegate(itemView, parent)
        , m_itemView( itemView )
        , m_preview( new KIcon( "gluon_creator" ) )
{
}

CommentItemsViewDelegate::~CommentItemsViewDelegate()
{
}

bool CommentItemsViewDelegate::eventFilter(QObject *watched, QEvent *event)
{
   if (event->type() == QEvent::MouseButtonDblClick) {
       return true;
   }

   return KWidgetItemDelegate::eventFilter(watched, event);
}

QList<QWidget*> CommentItemsViewDelegate::createItemWidgets() const
{
    QList<QWidget*> list;

    KSqueezedTextLabel* author = new KSqueezedTextLabel();
    author->setOpenExternalLinks(true);
    // not so nice - work around constness to install the event filter
    CommentItemsViewDelegate* delegate = const_cast<CommentItemsViewDelegate*>(this);
    author->installEventFilter(delegate);
    list << author;

    KSqueezedTextLabel* title = new KSqueezedTextLabel();
    title->setOpenExternalLinks(true);
    list << title;

    KSqueezedTextLabel* dateTime = new KSqueezedTextLabel();
    dateTime->setOpenExternalLinks(true);
    list << dateTime;

    KSqueezedTextLabel* rating = new KSqueezedTextLabel();
    rating->setOpenExternalLinks(true);
    list << rating;

    KSqueezedTextLabel* body = new KSqueezedTextLabel();
    body->setOpenExternalLinks(true);
    body->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
    list << body;

    KPushButton* replyButton = new KPushButton();
    replyButton->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
    list << replyButton;
    setBlockedEventTypes(replyButton, QList<QEvent::Type>() << QEvent::MouseButtonPress
                          << QEvent::MouseButtonRelease << QEvent::MouseButtonDblClick);
    connect(replyButton, SIGNAL(clicked()), SLOT(slotReplyClicked()));

    return list;
}

void CommentItemsViewDelegate::updateItemWidgets(const QList<QWidget*> widgets,
        const QStyleOptionViewItem &option,
        const QPersistentModelIndex &index) const
{
    const GluonPlayer::CommentsModel* model = qobject_cast<const GluonPlayer::CommentsModel*>(index.model());
    if (!model) {
        kDebug() << "Warning - Invalid Model!";
        return;
    }

    // setup the install button
    int margin = option.fontMetrics.height() / 2;
    int right = option.rect.width();
    int bottom = option.rect.height();

    const_cast<QSize&>(m_buttonSize) = QSize(32, 32);

    KPushButton* replyButton = qobject_cast<KPushButton*>(widgets.at(DelegateCommentReplyButton));
    if (replyButton) {
        replyButton->setVisible(const_cast<GluonPlayer::CommentsModel*>(model)->isOnline());
        replyButton->setIcon( KIcon( "edit-undo" ) );
        replyButton->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
        replyButton->resize( m_buttonSize );
        replyButton->move( right - replyButton->width() - margin, bottom - m_buttonSize.height() * 1.5);
    }

    KSqueezedTextLabel* author = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentAuthor));
    if (author) {
        author->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
        author->resize( right / 5, m_buttonSize.height() );
        author->move( margin, option.fontMetrics.height());
        qDebug() << "AUTHOR: " << index.data(GluonPlayer::CommentsModel::AuthorRole).toString();
        author->setText(index.data(GluonPlayer::CommentsModel::AuthorRole).toString());
    }

    KSqueezedTextLabel* dateTime = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentDateTime));
    if (dateTime) {
        dateTime->resize(author->size().width(), author->size().height());
        dateTime->move(author->x() + author->size().width(), author->y());
        qDebug() << "DATE TIME: " << index.data(GluonPlayer::CommentsModel::DateTimeRole).toString();
        dateTime->setText(index.data(GluonPlayer::CommentsModel::DateTimeRole).toString());
    }

    KSqueezedTextLabel* title = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentTitle));
    if (title) {
        title->resize(dateTime->size().width(), dateTime->size().height());
        title->move(dateTime->x() + dateTime->size().width(), dateTime->y());
        qDebug() << "TITLE: " << index.data(GluonPlayer::CommentsModel::TitleRole).toString();
        title->setText(index.data(GluonPlayer::CommentsModel::TitleRole).toString());
    }

    KSqueezedTextLabel* rating = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentRating));
    if (rating) {
        rating->resize(dateTime->size().width(), dateTime->size().height());
        rating->move(dateTime->x() + dateTime->size().width(), dateTime->y());
        qDebug() << "RATING: " << index.data(GluonPlayer::CommentsModel::RatingRole).toString();
        rating->setText(index.data(GluonPlayer::CommentsModel::RatingRole).toString());
    }

    KSqueezedTextLabel* body = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentBody));
    if (body) {
        body->resize(right - 2 * margin, bottom - author->size().height() - 2 * margin);
        body->move(margin, option.fontMetrics.height()  + author->size().height());
        qDebug() << "BODY: " << index.data(GluonPlayer::CommentsModel::BodyRole).toString();
    qDebug() << endl << endl << endl;
        body->setText(index.data(GluonPlayer::CommentsModel::BodyRole).toString());
    }

}

// draws the preview
void CommentItemsViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    int margin = option.fontMetrics.height() / 2;

    QStyle *style = QApplication::style();
    style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, 0);

    painter->save();

    if (option.state & QStyle::State_Selected) {
        painter->setPen(QPen(option.palette.highlightedText().color()));
    } else {
        painter->setPen(QPen(option.palette.text().color()));
    }

    /* const GluonPlayer::GameItemsModel* realmodel = qobject_cast<const GluonPlayer::GameItemsModel*>(index.model());

    int height = option.rect.height();
    QPoint point(option.rect.left() + margin, option.rect.top() + ((height - PreviewHeight) / 2));

    QImage image = KIcon("gluon-cretor").pixmap(32, 32).toImage();
    if (!image.isNull()) {
        point.setX((PreviewWidth - image.width())/2 + 5);
        point.setY(option.rect.top() + ((height - image.height()) / 2));
        painter->drawImage(point, image);

        QPoint framePoint(point.x() - 5, point.y() - 5);
        painter->drawPixmap(framePoint, KIcon("gluon-creator").pixmap(32, 32).scaled(image.width() + 10, image.height() + 10));
    } else {
        QRect rect(point, QSize(PreviewWidth, PreviewHeight));
        painter->drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, i18n("Loading Preview"));
    } */
    painter->restore();
}

QSize CommentItemsViewDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);

    QSize size;

    size.setWidth(option.fontMetrics.height() * 4);
    size.setHeight(qMax(option.fontMetrics.height() * 7, PreviewHeight)); // up to 6 lines of text, and two margins
    return size;
}

void CommentItemsViewDelegate::slotReplyClicked()
{
    QModelIndex index = focusedIndex();
    if (index.isValid()) {
        emit commentReplyClicked( index );
    }
}
<commit_msg>KDE Ext. Player: Fix the rating position (move after the "title").<commit_after>/*****************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *****************************************************************************/

#include "commentitemsviewdelegate.h"

#include "views/gametextlabel.h"

#include "lib/models/commentsmodel.h"

#include <KDE/KDebug>

#include <QtGui/QPainter>
#include <QtGui/QSortFilterProxyModel>
#include <QtGui/QApplication>
#include <QtGui/QToolButton>

enum {
    DelegateCommentAuthor,
    DelegateCommentTitle,
    DelegateCommentBody,
    DelegateCommentDateTime,
    DelegateCommentRating,
    DelegateCommentReplyButton
};

static const int PreviewWidth = 96;
static const int PreviewHeight = 72;

using namespace GluonKDEPlayer;

CommentItemsViewDelegate::CommentItemsViewDelegate(QAbstractItemView *itemView, QObject * parent)
        : KWidgetItemDelegate(itemView, parent)
        , m_itemView( itemView )
        , m_preview( new KIcon( "gluon_creator" ) )
{
}

CommentItemsViewDelegate::~CommentItemsViewDelegate()
{
}

bool CommentItemsViewDelegate::eventFilter(QObject *watched, QEvent *event)
{
   if (event->type() == QEvent::MouseButtonDblClick) {
       return true;
   }

   return KWidgetItemDelegate::eventFilter(watched, event);
}

QList<QWidget*> CommentItemsViewDelegate::createItemWidgets() const
{
    QList<QWidget*> list;

    KSqueezedTextLabel* author = new KSqueezedTextLabel();
    author->setOpenExternalLinks(true);
    // not so nice - work around constness to install the event filter
    CommentItemsViewDelegate* delegate = const_cast<CommentItemsViewDelegate*>(this);
    author->installEventFilter(delegate);
    list << author;

    KSqueezedTextLabel* title = new KSqueezedTextLabel();
    title->setOpenExternalLinks(true);
    list << title;

    KSqueezedTextLabel* dateTime = new KSqueezedTextLabel();
    dateTime->setOpenExternalLinks(true);
    list << dateTime;

    KSqueezedTextLabel* rating = new KSqueezedTextLabel();
    rating->setOpenExternalLinks(true);
    list << rating;

    KSqueezedTextLabel* body = new KSqueezedTextLabel();
    body->setOpenExternalLinks(true);
    body->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
    list << body;

    KPushButton* replyButton = new KPushButton();
    replyButton->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
    list << replyButton;
    setBlockedEventTypes(replyButton, QList<QEvent::Type>() << QEvent::MouseButtonPress
                          << QEvent::MouseButtonRelease << QEvent::MouseButtonDblClick);
    connect(replyButton, SIGNAL(clicked()), SLOT(slotReplyClicked()));

    return list;
}

void CommentItemsViewDelegate::updateItemWidgets(const QList<QWidget*> widgets,
        const QStyleOptionViewItem &option,
        const QPersistentModelIndex &index) const
{
    const GluonPlayer::CommentsModel* model = qobject_cast<const GluonPlayer::CommentsModel*>(index.model());
    if (!model) {
        kDebug() << "Warning - Invalid Model!";
        return;
    }

    // setup the install button
    int margin = option.fontMetrics.height() / 2;
    int right = option.rect.width();
    int bottom = option.rect.height();

    const_cast<QSize&>(m_buttonSize) = QSize(32, 32);

    KPushButton* replyButton = qobject_cast<KPushButton*>(widgets.at(DelegateCommentReplyButton));
    if (replyButton) {
        replyButton->setVisible(const_cast<GluonPlayer::CommentsModel*>(model)->isOnline());
        replyButton->setIcon( KIcon( "edit-undo" ) );
        replyButton->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
        replyButton->resize( m_buttonSize );
        replyButton->move( right - replyButton->width() - margin, bottom - m_buttonSize.height() * 1.5);
    }

    KSqueezedTextLabel* author = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentAuthor));
    if (author) {
        author->setSizePolicy( QSizePolicy::Maximum, QSizePolicy::MinimumExpanding );
        author->resize( right / 5, m_buttonSize.height() );
        author->move( margin, option.fontMetrics.height());
        author->setText(index.data(GluonPlayer::CommentsModel::AuthorRole).toString());
    }

    KSqueezedTextLabel* dateTime = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentDateTime));
    if (dateTime) {
        dateTime->resize(author->size().width(), author->size().height());
        dateTime->move(author->x() + author->size().width(), author->y());
        dateTime->setText(index.data(GluonPlayer::CommentsModel::DateTimeRole).toString());
    }

    KSqueezedTextLabel* title = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentTitle));
    if (title) {
        title->resize(dateTime->size().width(), dateTime->size().height());
        title->move(dateTime->x() + dateTime->size().width(), dateTime->y());
        title->setText(index.data(GluonPlayer::CommentsModel::TitleRole).toString());
    }

    KSqueezedTextLabel* rating = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentRating));
    if (rating) {
        rating->resize(title->size().width(), title->size().height());
        rating->move(title->x() + title->size().width(), title->y());
        rating->setText(index.data(GluonPlayer::CommentsModel::RatingRole).toString());
    }

    KSqueezedTextLabel* body = qobject_cast<KSqueezedTextLabel*>(widgets.at(DelegateCommentBody));
    if (body) {
        body->resize(right - 2 * margin, bottom - author->size().height() - 2 * margin);
        body->move(margin, option.fontMetrics.height()  + author->size().height());
        body->setText(index.data(GluonPlayer::CommentsModel::BodyRole).toString());
    }
}

// draws the preview
void CommentItemsViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    int margin = option.fontMetrics.height() / 2;

    QStyle *style = QApplication::style();
    style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, 0);

    painter->save();

    if (option.state & QStyle::State_Selected) {
        painter->setPen(QPen(option.palette.highlightedText().color()));
    } else {
        painter->setPen(QPen(option.palette.text().color()));
    }

    /* const GluonPlayer::GameItemsModel* realmodel = qobject_cast<const GluonPlayer::GameItemsModel*>(index.model());

    int height = option.rect.height();
    QPoint point(option.rect.left() + margin, option.rect.top() + ((height - PreviewHeight) / 2));

    QImage image = KIcon("gluon-cretor").pixmap(32, 32).toImage();
    if (!image.isNull()) {
        point.setX((PreviewWidth - image.width())/2 + 5);
        point.setY(option.rect.top() + ((height - image.height()) / 2));
        painter->drawImage(point, image);

        QPoint framePoint(point.x() - 5, point.y() - 5);
        painter->drawPixmap(framePoint, KIcon("gluon-creator").pixmap(32, 32).scaled(image.width() + 10, image.height() + 10));
    } else {
        QRect rect(point, QSize(PreviewWidth, PreviewHeight));
        painter->drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, i18n("Loading Preview"));
    } */
    painter->restore();
}

QSize CommentItemsViewDelegate::sizeHint(const QStyleOptionViewItem & option, const QModelIndex & index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);

    QSize size;

    size.setWidth(option.fontMetrics.height() * 4);
    size.setHeight(qMax(option.fontMetrics.height() * 7, PreviewHeight)); // up to 6 lines of text, and two margins
    return size;
}

void CommentItemsViewDelegate::slotReplyClicked()
{
    QModelIndex index = focusedIndex();
    if (index.isValid()) {
        emit commentReplyClicked( index );
    }
}
<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main()
{
	int numEntries = 0;
	cin >> numEntries;
	cin.ignore();

	while (numEntries--)
	{
	}
	return 0;
}
<commit_msg>Oplossing voor D: Collatz.<commit_after>#include <iostream>
#include <vector>
#include <utility>

using namespace std;

int main()
{
	int numEntries = 0;
	cin >> numEntries;
	cin.ignore();

	while (numEntries--)
	{
		int n;
		cin >> n;
		vector<bool> ropes(n+1);
		ropes[1] = true;
		int ropeCount = n / 2 + n % 2;

		for (int i = 1; i <= n; i++) {
			if (i % 2) {
				if (3 * i + 1 > n) {
					ropeCount++;
				}
			}
		}
		cout << ropeCount << endl;

	}
	return 0;
}
<|endoftext|>


<commit_before>/*
 *  Copyright 2008-2009 NVIDIA Corporation
 *
 *  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
 *
 *  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.
 */

/*! \file for_each.inl
 *  \brief Inline file for for_each.h.
 */

// do not attempt to compile this file with any other compiler
#ifdef __CUDACC__

#include <algorithm>

#include <thrust/detail/device/dereference.h>
#include <thrust/detail/device/cuda/launch_closure.h>

namespace thrust
{

namespace detail
{

namespace device
{

namespace cuda
{

template<typename RandomAccessIterator,
         typename Size,
         typename UnaryFunction>
  struct for_each_n_closure
{
  typedef void result_type;

  RandomAccessIterator first;
  Size n;
  UnaryFunction f;

  for_each_n_closure(RandomAccessIterator first_,
                     Size n_,
                     UnaryFunction f_)
    : first(first_),
      n(n_),
      f(f_)
  {}

  __device__
  result_type operator()(void)
  {
    const Size grid_size = blockDim.x * gridDim.x;

    Size i = blockIdx.x * blockDim.x + threadIdx.x;

    while(i < n)
    {
      f(thrust::detail::device::dereference(first, i));
      i += grid_size;
    }
  }
};

template<typename InputIterator,
         typename UnaryFunction>
void for_each(InputIterator first,
              InputIterator last,
              UnaryFunction f)
{
  if (first >= last) return;  //empty range

  typedef for_each_n_closure<InputIterator, size_t, UnaryFunction> Closure;
  Closure closure(first, last - first, f);

  launch_closure(closure, last - first);
}

} // end namespace cuda

} // end namespace device

} // end namespace detail

} // end namespace thrust

#endif // __CUDACC__

<commit_msg>Remove unnecessary #include <algorithm> from cuda for_each.inl.<commit_after>/*
 *  Copyright 2008-2009 NVIDIA Corporation
 *
 *  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
 *
 *  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.
 */

/*! \file for_each.inl
 *  \brief Inline file for for_each.h.
 */

// do not attempt to compile this file with any other compiler
#ifdef __CUDACC__

#include <thrust/detail/device/dereference.h>
#include <thrust/detail/device/cuda/launch_closure.h>

namespace thrust
{

namespace detail
{

namespace device
{

namespace cuda
{

template<typename RandomAccessIterator,
         typename Size,
         typename UnaryFunction>
  struct for_each_n_closure
{
  typedef void result_type;

  RandomAccessIterator first;
  Size n;
  UnaryFunction f;

  for_each_n_closure(RandomAccessIterator first_,
                     Size n_,
                     UnaryFunction f_)
    : first(first_),
      n(n_),
      f(f_)
  {}

  __device__
  result_type operator()(void)
  {
    const Size grid_size = blockDim.x * gridDim.x;

    Size i = blockIdx.x * blockDim.x + threadIdx.x;

    while(i < n)
    {
      f(thrust::detail::device::dereference(first, i));
      i += grid_size;
    }
  }
};

template<typename InputIterator,
         typename UnaryFunction>
void for_each(InputIterator first,
              InputIterator last,
              UnaryFunction f)
{
  if (first >= last) return;  //empty range

  typedef for_each_n_closure<InputIterator, size_t, UnaryFunction> Closure;
  Closure closure(first, last - first, f);

  launch_closure(closure, last - first);
}

} // end namespace cuda

} // end namespace device

} // end namespace detail

} // end namespace thrust

#endif // __CUDACC__

<|endoftext|>


<commit_before>
#include "itkImage.h"
#include "itkTranslationTransform.h"
#include "itkAffineTransform.h"
#include "itkRigid2DTransform.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkLinearInterpolateImageFunction.h"

#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"

#include "OptImageToImageMetricsTest.h"

int main(int argc, char* argv[])
{
#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  std::cout << "Default number of threads : "
            << itk::MultiThreader::GetGlobalDefaultNumberOfThreads()
            << std::endl;

  typedef itk::Image< unsigned int > FixedImageType;
  typedef itk::Image< unsigned int > MovingImageType;
  typedef itk::ImageFileReader< FixedImageType  > FixedImageReaderType;
  typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
  FixedImageReaderType::Pointer  fixedImageReader  = FixedImageReaderType::New();
  MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();

  fixedImageReader->SetFileName(  argv[1] );
  movingImageReader->SetFileName( argv[2] );

  TranslationLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  RigidLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  AffineLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  // DO EXPERIMENTS WITH NUMBER OF THREADS SET TO 1!!!
  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << "Running tests with : " << std::endl;
  std::cout << "\t itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1); " << std::endl;
  std::cout << "\t itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1); " << std::endl;
  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << std::endl;

  itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);
  itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);

  TranslationLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  RigidLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  AffineLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  return EXIT_SUCCESS;
}
<commit_msg>ENH: Make this test fail so that we can gather information from the platforms running the Opt code.<commit_after>
#include "itkImage.h"
#include "itkTranslationTransform.h"
#include "itkAffineTransform.h"
#include "itkRigid2DTransform.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

#include "itkLinearInterpolateImageFunction.h"

#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMattesMutualInformationImageToImageMetric.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"

#include "OptImageToImageMetricsTest.h"

int main(int argc, char* argv[])
{
#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  std::cout << "Default number of threads : "
            << itk::MultiThreader::GetGlobalDefaultNumberOfThreads()
            << std::endl;

  typedef itk::Image< unsigned int > FixedImageType;
  typedef itk::Image< unsigned int > MovingImageType;
  typedef itk::ImageFileReader< FixedImageType  > FixedImageReaderType;
  typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;
  FixedImageReaderType::Pointer  fixedImageReader  = FixedImageReaderType::New();
  MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();

  fixedImageReader->SetFileName(  argv[1] );
  movingImageReader->SetFileName( argv[2] );

  TranslationLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  RigidLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  AffineLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  // DO EXPERIMENTS WITH NUMBER OF THREADS SET TO 1!!!
  // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << "Running tests with : " << std::endl;
  std::cout << "\t itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1); " << std::endl;
  std::cout << "\t itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1); " << std::endl;
  std::cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << std::endl;
  std::cout << std::endl;

  itk::MultiThreader::SetGlobalDefaultNumberOfThreads(1);
  itk::MultiThreader::SetGlobalMaximumNumberOfThreads(1);

  TranslationLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  RigidLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

  AffineLinearTest( fixedImageReader.GetPointer(),
                    movingImageReader.GetPointer() );

#ifdef ITK_USE_OPTIMIZED_REGISTRATION_METHODS
  std::cout << "OPTIMIZED ON" << std::endl;
#else
  std::cout << "OPTIMIZED OFF" << std::endl;
#endif

  // For right now, make this test always fail so that we can gather
  // some performance information from the platforms running the new
  // optimized code.
  return EXIT_FAILURE;
}
<|endoftext|>


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

Program:   ORFEO Toolbox
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbFullResolutionImageWidget.h"
#include "otbImageFileReader.h"
#include <FL/Fl.H>

int otbFullResolutionImageWidget( int argc, char * argv[] )
{
  try
    {
      char * filename = argv[1];
      typedef float PixelType;
      typedef otb::FullResolutionImageWidget<PixelType> WidgetType;
      typedef WidgetType::ImageType ImageType;
      typedef otb::ImageFileReader<ImageType> ReaderType;

      ReaderType::Pointer reader = ReaderType::New();
      ImageType::SizeType size;
      ImageType::IndexType index;
      ImageType::RegionType region;

      index[0]=0;
      index[1]=0;
      size[0]=1;
      size[1]=1;
      reader->SetFileName(filename);
      reader->Update();

      Fl_Window window(size[0],size[1]);

      WidgetType::Pointer widget = WidgetType::New();
      window.resizable(widget.GetPointer());
      widget->SetInput(reader->GetOutput());
      if(reader->GetOutput()->GetNumberOfComponentsPerPixel()>=3)
	widget->SetViewModelToRGB();
      else
	widget->SetViewModelToGrayscale();
      widget->SetUpperRightCorner(index);
      widget->Init(0,0,size[0],size[1],"Test Full Resolution Widget");
      widget->redraw();
      window.end();
      window.show();
      window.show();
      widget->Show();
      widget->redraw();
      Fl::check();

      int StepX =(reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0]-size[0])/100;
   int StepY =(reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1]-size[1])/100;
    for(int i = 0;i<=100;i+=5)
	{
	  Fl::check();
	  window.resize(0,0,size[0]+i*StepX,size[1]+i*StepY);
	  Fl::wait(0.2);
	  Fl::check();
	}

  for(int i = 100;i>=0;i-=5)
	{
	  Fl::check();
	  window.resize(0,0,size[0]+i*StepX,size[1]+i*StepY);
	  Fl::wait(0.2);
	  Fl::check();
	}
     }

  catch( itk::ExceptionObject & err )
    {
      std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
      std::cout << err << std::endl;
      return EXIT_FAILURE;
    }
  catch( ... )
    {
      std::cout << "Exception levee inconnue !" << std::endl;
      return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<commit_msg>Correction erreur de compilation vue sur le dashboard.<commit_after>/*=========================================================================

Program:   ORFEO Toolbox
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbFullResolutionImageWidget.h"
#include "otbImageFileReader.h"
#include <FL/Fl.H>

int otbFullResolutionImageWidget( int argc, char * argv[] )
{
  try
    {
      char * filename = argv[1];
      typedef float PixelType;
      typedef otb::FullResolutionImageWidget<PixelType> WidgetType;
      typedef WidgetType::ImageType ImageType;
      typedef otb::ImageFileReader<ImageType> ReaderType;

      ReaderType::Pointer reader = ReaderType::New();
      ImageType::SizeType size;
      ImageType::IndexType index;
      ImageType::RegionType region;

      index[0]=0;
      index[1]=0;
      size[0]=1;
      size[1]=1;
      reader->SetFileName(filename);
      reader->Update();

      Fl_Window window(size[0],size[1]);

      WidgetType::Pointer widget = WidgetType::New();
      window.resizable(widget.GetPointer());
      widget->SetInput(reader->GetOutput());
      if(reader->GetOutput()->GetNumberOfComponentsPerPixel()>=3)
	widget->SetViewModelToRGB();
      else
	widget->SetViewModelToGrayscale();
      widget->SetUpperLeftCorner(index);
      widget->Init(0,0,size[0],size[1],"Test Full Resolution Widget");
      widget->redraw();
      window.end();
      window.show();
      window.show();
      widget->Show();
      widget->redraw();
      Fl::check();

      int StepX =(reader->GetOutput()->GetLargestPossibleRegion().GetSize()[0]-size[0])/100;
   int StepY =(reader->GetOutput()->GetLargestPossibleRegion().GetSize()[1]-size[1])/100;
    for(int i = 0;i<=100;i+=5)
	{
	  Fl::check();
	  window.resize(0,0,size[0]+i*StepX,size[1]+i*StepY);
	  Fl::wait(0.2);
	  Fl::check();
	}

  for(int i = 100;i>=0;i-=5)
	{
	  Fl::check();
	  window.resize(0,0,size[0]+i*StepX,size[1]+i*StepY);
	  Fl::wait(0.2);
	  Fl::check();
	}
     }

  catch( itk::ExceptionObject & err )
    {
      std::cout << "Exception itk::ExceptionObject levee !" << std::endl;
      std::cout << err << std::endl;
      return EXIT_FAILURE;
    }
  catch( ... )
    {
      std::cout << "Exception levee inconnue !" << std::endl;
      return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Time:  O(k^n)
// Space: O(k^n)

// https://en.wikipedia.org/wiki/De_Bruijn_sequence
class Solution {
public:
    string crackSafe(int n, int k) {
        const int M = pow(k, n - 1);
        vector<int> P;
        for (int i = 0; i < k; ++i) {
            for (int q = 0; q < M; ++q) {
                P.emplace_back(q * k + i);
            }
        }
        const int total = pow(k, n);
        string result(n - 1, '0' + k - 1);
        for (int i = 0; i < total; ++i) {
            int j = i;
            while (P[j] >= 0) {
                result.push_back('0' + j / M);
                auto Pj = P[j];
                P[j] = -1;
                j = Pj;
            }
        }
        return result;
    }
};

// Time:  O(n * k^n)
// Space: O(n * k^n)
class Solution2 {
public:
    string crackSafe(int n, int k) {
        string result(n, '0' + k - 1);
        unordered_set<string> lookup;
        lookup.emplace(result);
        const int total = pow(k, n);
        while (lookup.size() < total) {
            auto node = result.substr(result.length() - n + 1);
            for (int i = 0; i < k; ++i) {
                auto neighbor = node;
                neighbor.push_back('0' + i);
                if (!lookup.count(neighbor)) {
                    lookup.emplace(neighbor);
                    result.push_back('0' + i);
                    break;
                }
            }
        }
        return result;
    }
};

// Time:  O(n * k^n)
// Space: O(n * k^n)
class Solution3 {
public:
    string crackSafe(int n, int k) {
        unordered_set<string> lookup;
        string result(n - 1, '0' + k - 1);
        auto node = result;
        dfs(k, node, &lookup, &result);
        return result;
    }

private:
    void dfs(int k, const string& node, unordered_set<string> *lookup, string *result) {
        for (int i = 0; i < k; ++i) {
            const auto& neighbor = node + to_string(i);
            if (!lookup->count(neighbor)) {
                lookup->emplace(neighbor);
                result->push_back('0' + i);
                dfs(k, neighbor.substr(1), lookup, result);
                break;
            }
        }
    }
};
<commit_msg>Update cracking-the-safe.cpp<commit_after>// Time:  O(k^n)
// Space: O(k^n)

// https://en.wikipedia.org/wiki/De_Bruijn_sequence
class Solution {
public:
    string crackSafe(int n, int k) {
        const int M = pow(k, n - 1);
        vector<int> P;
        for (int i = 0; i < k; ++i) {
            for (int q = 0; q < M; ++q) {
                P.emplace_back(q * k + i);
            }
        }
        const int total = pow(k, n);
        string result(n - 1, '0' + k - 1);
        for (int i = 0; i < total; ++i) {
            int j = i;
            while (P[j] >= 0) {
                result.push_back('0' + j / M);
                auto Pj = P[j];
                P[j] = -1;
                j = Pj;
            }
        }
        return result;
    }
};

// Time:  O(n * k^n)
// Space: O(n * k^n)
class Solution2 {
public:
    string crackSafe(int n, int k) {
        string result(n, '0' + k - 1);
        unordered_set<string> lookup;
        lookup.emplace(result);
        const int total = pow(k, n);
        while (lookup.size() < total) {
            auto node = result.substr(result.length() - n + 1);
            for (int i = 0; i < k; ++i) {
                const auto& neighbor = node + to_string(i);
                if (!lookup.count(neighbor)) {
                    lookup.emplace(neighbor);
                    result.push_back('0' + i);
                    break;
                }
            }
        }
        return result;
    }
};

// Time:  O(n * k^n)
// Space: O(n * k^n)
class Solution3 {
public:
    string crackSafe(int n, int k) {
        unordered_set<string> lookup;
        string result(n - 1, '0' + k - 1);
        auto node = result;
        dfs(k, node, &lookup, &result);
        return result;
    }

private:
    void dfs(int k, const string& node, unordered_set<string> *lookup, string *result) {
        for (int i = 0; i < k; ++i) {
            const auto& neighbor = node + to_string(i);
            if (!lookup->count(neighbor)) {
                lookup->emplace(neighbor);
                result->push_back('0' + i);
                dfs(k, neighbor.substr(1), lookup, result);
                break;
            }
        }
    }
};
<|endoftext|>


<commit_before>// Time:  O(1)
// Space: O(1)

class Solution {
public:
    int mirrorReflection(int p, int q) {
        return (p & -p) > (q & -q) ? 2 : (p & -p) < (q & -q) ? 0 : 1;
    }
};

// Time:  O(log(max(p, q))) = O(1) due to 32-bit integer
// Space: O(1)
class Solution2 {
public:
    int mirrorReflection(int p, int q) {
        const auto lcm = p * q / gcd(p, q);
        // let a = lcm / p, b = lcm / q
        if (lcm / p % 2 == 1) {
            if (lcm / q % 2 == 1) {  // a is odd, b is odd <=> (p & -p) == (q & -q)
                return 1;
            }
            return 2;  // a is odd, b is even <=> (p & -p) > (q & -q)
        }
        return 0;  // a is even, b is odd <=> (p & -p) < (q & -q)
    }

private:
    int gcd(int a, int b) {
        while (b != 0) {
            int tmp = b;
            b = a % b;
            a = tmp;
        }
        return a;
    }
};
<commit_msg>Update mirror-reflection.cpp<commit_after>// Time:  O(1)
// Space: O(1)

class Solution {
public:
    int mirrorReflection(int p, int q) {
        // explanation commented in the following solution
        return (p & -p) > (q & -q) ? 2 : (p & -p) < (q & -q) ? 0 : 1;
    }
};

// Time:  O(log(max(p, q))) = O(1) due to 32-bit integer
// Space: O(1)
class Solution2 {
public:
    int mirrorReflection(int p, int q) {
        const auto lcm = p * q / gcd(p, q);
        // let a = lcm / p, b = lcm / q
        if (lcm / p % 2 == 1) {
            if (lcm / q % 2 == 1) {
                return 1;  // a is odd, b is odd <=> (p & -p) == (q & -q)
            }
            return 2;  // a is odd, b is even <=> (p & -p) > (q & -q)
        }
        return 0;  // a is even, b is odd <=> (p & -p) < (q & -q)
    }

private:
    int gcd(int a, int b) {
        while (b != 0) {
            int tmp = b;
            b = a % b;
            a = tmp;
        }
        return a;
    }
};
<|endoftext|>


<commit_before>// Time:  O(n * k)
// Space: O(n + k)

// DP solution. (596ms)
class Solution2 {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        vector<int> uglies(n), ugly_by_prime(primes), idx(primes.size());
        uglies[0] = 1;

        for (int i = 1; i < n; ++i) {
            int min_val = *min_element(ugly_by_prime.begin(), ugly_by_prime.end());
            uglies[i] = min_val;
            for (int k = 0; k < primes.size(); ++k) {
                if (min_val == ugly_by_prime[k]) {
                    ugly_by_prime[k] = primes[k] * uglies[++idx[k]];
                }
            }
        }

        return uglies[n - 1];
    }
};

// Time:  O(n * logk) ~ O(n * klogk)
// Space: O(k^2)
// Heap solution. (612ms)
class Solution2 {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        long long ugly_number = 0;
        priority_queue<long long , vector<long long>, greater<long long>> heap;

        heap.emplace(1);
        for (const auto& p: primes) {
            heap.emplace(p);
        }
        for (int i = 0; i < n; ++i) {
            ugly_number = heap.top();
            heap.pop();
            int j = 0;
            for (; j < primes.size(); ++j) {
                if (ugly_number % primes[j] == 0) {
                    for (int k = 0; k <= j; ++k) {
                        // worst time:  O(klogk)
                        // worst space: O(k^2)
                        heap.emplace(ugly_number * primes[k]);
                    }
                    break;
                }
            }
        }

        return ugly_number;
    }
};

// Time:  O(n * logk) ~ O(n * klogk)
// Space: O(n + k)
// Heap solution. (1184ms)
class Solution3 {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> ugly_by_prime;
        vector<int> uglies(n), idx(primes.size());
        uglies[0] = 1;

        for (int k = 0; k < primes.size(); ++k) {
            ugly_by_prime.push({primes[k], k});
        }

        for (int i = 1; i < n; ++i) {
            int min, k;
            tie(min, k) = ugly_by_prime.top();
            uglies[i] = min;

            while (ugly_by_prime.top().first == min) {  // worst time: O(klogk)
                tie(min, k) = ugly_by_prime.top();
                ugly_by_prime.pop();
                ugly_by_prime.push({primes[k] * uglies[++idx[k]], k});
            }
        }

        return uglies[n - 1];
    }
};
<commit_msg>Update super-ugly-number.cpp<commit_after>// Time:  O(n * k)
// Space: O(n + k)

// DP solution. (596ms)
class Solution {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        vector<int> uglies(n), ugly_by_prime(primes), idx(primes.size());
        uglies[0] = 1;

        for (int i = 1; i < n; ++i) {
            int min_val = *min_element(ugly_by_prime.begin(), ugly_by_prime.end());
            uglies[i] = min_val;
            for (int k = 0; k < primes.size(); ++k) {
                if (min_val == ugly_by_prime[k]) {
                    ugly_by_prime[k] = primes[k] * uglies[++idx[k]];
                }
            }
        }

        return uglies[n - 1];
    }
};

// Time:  O(n * logk) ~ O(n * klogk)
// Space: O(k^2)
// Heap solution. (612ms)
class Solution2 {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        long long ugly_number = 0;
        priority_queue<long long , vector<long long>, greater<long long>> heap;

        heap.emplace(1);
        for (const auto& p: primes) {
            heap.emplace(p);
        }
        for (int i = 0; i < n; ++i) {
            ugly_number = heap.top();
            heap.pop();
            int j = 0;
            for (; j < primes.size(); ++j) {
                if (ugly_number % primes[j] == 0) {
                    for (int k = 0; k <= j; ++k) {
                        // worst time:  O(klogk)
                        // worst space: O(k^2)
                        heap.emplace(ugly_number * primes[k]);
                    }
                    break;
                }
            }
        }

        return ugly_number;
    }
};

// Time:  O(n * logk) ~ O(n * klogk)
// Space: O(n + k)
// Heap solution. (1184ms)
class Solution3 {
public:
    int nthSuperUglyNumber(int n, vector<int>& primes) {
        priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> ugly_by_prime;
        vector<int> uglies(n), idx(primes.size());
        uglies[0] = 1;

        for (int k = 0; k < primes.size(); ++k) {
            ugly_by_prime.push({primes[k], k});
        }

        for (int i = 1; i < n; ++i) {
            int min, k;
            tie(min, k) = ugly_by_prime.top();
            uglies[i] = min;

            while (ugly_by_prime.top().first == min) {  // worst time: O(klogk)
                tie(min, k) = ugly_by_prime.top();
                ugly_by_prime.pop();
                ugly_by_prime.push({primes[k] * uglies[++idx[k]], k});
            }
        }

        return uglies[n - 1];
    }
};
<|endoftext|>


<commit_before>#include "DateTime.h"
#include "ArraySort.h"
#include <iostream>
#include <string>
#include <list>
using namespace std;
using namespace NP_DATETIME;
using namespace NP_ARRAYSORT;

// .h

int main();
void sortCTimesShow();
void sortDatesShow();
void sortDateTimesShow();

// .cpp

void sortCTimesShow() {
	cout << "For our first act, we're going to sort some times in our very own CTime class!" << endl;
	cout << "How many CTimes would you like to sort? ";

	short items;

	cin >> items;
	if (items <= 1) {
		cout << "Well it wouldn't be much of a show if I didn't sort at least 2 things, right? We'll sort 2 things for now." << endl;
		items = 2;
	}
	else {
		cout << items << " CTimes it is!" << endl;
	}

	cout << "Now if you could type these times in yourself..." << endl;

	Comparable ** timesToSort = nullptr;
	timesToSort = new Comparable * [items];

	for (short index = 0; index < items; index++)
		timesToSort[index] = nullptr;

	for (short tIndex = 0; tIndex < items; tIndex++) {
		cout << "CTime " << tIndex + 1 << " [hh:mm:ss]: ";
		CTime thisTime;
		Comparable * thisTimeComparable = &thisTime;
		cin >> thisTime;
		cout << "You entered: " << thisTime << endl;
		timesToSort[tIndex] = new CTime(dynamic_cast<CTime&>(*thisTimeComparable));
	}

	cout << "Awesome! Now that we have " << items << " different CTimes, let me present them in the order you entered..." << endl;

	printArray(cout, timesToSort, items);

	cout << endl << " ... and that's all of them! Now abracadraba, quicksort away! Here's the sorted list!" << endl;

	quickSort(timesToSort, 0, items - 1);
	// insertionSort(timesToSort, 0, items - 1);

	/*for (short tIndex = 0; tIndex < items; tIndex++) {
		timesToSort[tIndex]->print(cout);
		cout << ", ";
	}*/
	printArray(cout, timesToSort, items);

	char ignoreme;
	cin >> ignoreme;
}

int main()
{
	string name;
	cout << "Hello! Welcome the magic sorting show! Please enter your name: ";
	cin >> name;

	if (name.length() <= 1) {
		cout << "no name, huh? I'll just call you Bill!" << endl;
		name = "Bill";
	}
	else {
		cout << "Hello, " << name << "!" << endl;
	}

	cout << "We have quite a treat for you today! We're going to sort things for you in C++!" << endl;

	sortCTimesShow();

	Date date1;
	CTime time1;
	DateTime datetime1;

	/*
	cout << "date [dd/mm/yyyy]: ";
	cin >> date1;
	cout << endl << date1 << endl;

	cout << "time [hh:mm:ss]: ";
	cin >> time1;
	cout << endl << time1 << endl;
	//*/

	cout << "datetime [dd/mm/yyyy hh:mm:ss]: ";
	cin >> datetime1;
	cout << endl << datetime1 << endl;
	datetime1;
}<commit_msg>finish up main<commit_after>#include "DateTime.h"
#include "ArraySort.h"
#include <iostream>
#include <string>
#include <list>
using namespace std;
using namespace NP_DATETIME;
using namespace NP_ARRAYSORT;

// .h

int main();
void sortDateTimesShow();
void sortDatesShow();
void sortDateTimesShow();

// .cpp

void sortDateTimesShow() {
	cout << "For our first act, we're going to sort some times in our very own DateTime class!" << endl;
	cout << "How many DateTimes would you like to sort? ";

	short items;

	cin >> items;
	if (items <= 1) {
		cout << "Well it wouldn't be much of a show if I didn't sort at least 2 things, right? We'll sort 2 things for now." << endl;
		items = 2;
	}
	else {
		cout << items << " DateTimes it is!" << endl;
	}

	cout << "Now if you could type these times in yourself..." << endl;

	Comparable ** timesToSort = nullptr;
	timesToSort = new Comparable * [items];

	for (short index = 0; index < items; index++)
		timesToSort[index] = nullptr;

	for (short tIndex = 0; tIndex < items; tIndex++) {
		cout << "DateTime " << tIndex + 1 << " [dd/mm/yyyy hh:mm:ss]: ";
		DateTime thisTime;
		Comparable * thisTimeComparable = &thisTime;
		cin >> thisTime;
		cout << "You entered: " << thisTime << endl;
		timesToSort[tIndex] = new DateTime(dynamic_cast<DateTime&>(*thisTimeComparable));
	}

	cout << "Awesome! Now that we have " << items << " different DateTimes, let me present them in the order you entered..." << endl << endl;

	printArray(cout, timesToSort, items);

	cout << endl << endl << " ... and that's all of them! Now abracadraba, quicksort away! Here's the sorted list!" << endl << endl;

	quickSort(timesToSort, 0, items - 1);
	// insertionSort(timesToSort, 0, items - 1);

	printArray(cout, timesToSort, items);
	cout << endl << endl;
}

int main()
{
	string name;
	cout << "Hello! Welcome the magic sorting show! Please enter your name: ";
	cin >> name;

	if (name.length() <= 1) {
		cout << "no name, huh? I'll just call you Bill!" << endl;
		name = "Bill";
	}
	else {
		cout << "Hello, " << name << "!" << endl;
	}

	cout << "We have quite a treat for you today! We're going to sort things for you in C++!" << endl;

	sortDateTimesShow();

	cout << "Thank you Seattle, you have been an amazing audience!" << endl;
	cout << "I have been your host, Norton Pengra and I will see you later!" << endl;

	char tmp;
	cin >> tmp;
}<|endoftext|>


<commit_before>#include <iostream>
#include <sstream>
#include <string>
#include <regex>

#include "Calculator.h"
#include "ExpressionMaker.h"
#include "ExpressionUtil.h"

const std::string Calculator::m_validCommand("?REPITVQ");
const std::string Calculator::m_numberedCommand("EPIT");

Calculator::Calculator()
	: m_expMaker(ExpressionMaker(m_varTable))
{ }

Calculator::~Calculator()
{ }

void Calculator::Run()
{
	std::cout << "Calculator Version 1.02" << std::endl;
	PrintHelp();

	for (;;)
	{
		try
		{
			do
			{
				GetCommand();
				if (ValidCommand())
				{
					ExecuteCommand();
				}
			}
			while (m_command != 'Q');

			break;
		}
		catch (const std::exception& e)
		{
			std::cout << e.what() << std::endl;
		}
	}
}

void Calculator::PrintHelp()
{
	std::cout
		<< "?  : Help" << std::endl
		<< "R  : Read expression" << std::endl
		<< "E  : Evaluate and print latest expression" << std::endl
		<< "E n: Evaluate and print nth expression" << std::endl
		<< "P  : Print latest expression postfix" << std::endl
		<< "P n: Print nth expression postfix" << std::endl
		<< "I  : Print latest expression infix" << std::endl
		<< "I n: Print nth expression infix" << std::endl
		<< "T  : Print latest expression tree" << std::endl
		<< "T n: Print nth expression tree" << std::endl
		<< "V  : Print variable table list" << std::endl
		<< "Q  : Quit" << std::endl;
}

void Calculator::GetCommand()
{
	std::cout << ">> ";
	std::string readString = "";
	getline(std::cin, readString);
	std::istringstream iss(readString);

	iss >> std::ws;
	iss >> m_command;
	m_command = toupper(m_command);

	if (m_numberedCommand.find(m_command) != std::string::npos)
	{
		unsigned int readNumber = m_oldExpressions.size();
		iss >> std::ws;
		if (isdigit(iss.peek()))
		{
			iss >> readNumber;
			if (readNumber < 1 || readNumber > m_oldExpressions.size())
			{
				m_expressionNumber = m_oldExpressions.size() - 1;
				throw std::logic_error("The number is out of range");
			}

			m_expressionNumber = readNumber - 1;
		}
		else
		{
			m_expressionNumber = std::numeric_limits<unsigned int>::max();
		}
	}
}

bool Calculator::ValidCommand()
{
	if (m_validCommand.find(m_command) == std::string::npos)
	{
		std::cout << "Invalid Command: " << m_command << std::endl;
		return false;
	}

	return true;
}

void Calculator::ExecuteCommand()
{
	if (m_command == '?')
	{
		PrintHelp();
	}
	else if (m_command == 'R')
	{
		ReadExpression(std::cin);
	}
	else if (m_command == 'E')
	{
		EvaluateAndPrintExpression(std::cout);
	}
	else if (m_command == 'P')
	{
		PrintPostfix(std::cout);
	}
	else if (m_command == 'I')
	{
		PrintInfix(std::cout);
	}
	else if (m_command == 'T')
	{
		PrintTree(std::cout);
	}
	else if (m_command == 'V')
	{
		m_varTable.List(std::cout);
	}
	else if (m_command == 'Q')
	{
		std::cout << "Quit!" << std::endl;
	}
	else
	{
		std::cout << "Invalid Command" << std::endl;
	}
}

void Calculator::ReadExpression(std::istream& is)
{
	std::string infix;

	is >> std::ws;

	if (getline(is, infix))
	{
		std::vector<std::string> expressions = SplitExpression(infix, ",");

		for (auto& expression : expressions)
		{
			m_expMaker.SetPostfix(InfixToPostfix(expression));
			Expression exp = m_expMaker.GetExpression();
			m_oldExpressions.push_back(Expression(exp));
			m_currentExpression = exp;

			if (m_currentExpression.TopNodeIsAssign())
			{
				m_currentExpression.Evaluate();
			}
		}
	}
	else
	{
		std::cout << "Invalid Expression" << std::endl;
	}
}

void Calculator::PrintExpression(std::ostream& os) const
{
	std::vector<Expression>::const_iterator iter = m_oldExpressions.begin();

	for (int i = 1; iter != m_oldExpressions.end(); ++iter, ++i)
	{
		os << i << ": " << (*iter).GetInfix() << std::endl;
	}
}

void Calculator::EvaluateAndPrintExpression(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		os << m_currentExpression.Evaluate() << std::endl;
	}
	else
	{
		os << m_oldExpressions.at(m_expressionNumber).Evaluate() << std::endl;
	}
}

void Calculator::PrintPostfix(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		os << m_currentExpression.GetPostfix() << std::endl;
	}
	else
	{
		os << m_oldExpressions.at(m_expressionNumber).GetPostfix() << std::endl;
	}
}

void Calculator::PrintInfix(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		os << m_currentExpression.GetInfix() << std::endl;
	}
	else
	{
		os << m_oldExpressions.at(m_expressionNumber).GetInfix() << std::endl;
	}
}

void Calculator::PrintTree(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		m_currentExpression.PrintTree(os);
	}
	else
	{
		m_oldExpressions.at(m_expressionNumber).PrintTree(os);
	}
}

void Calculator::SetCurrentExpression()
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		throw std::logic_error("Too many expressions");
	}
	else
	{
		Expression exp = m_oldExpressions[m_expressionNumber];
		m_currentExpression = exp;
	}
}

std::vector<std::string> Calculator::SplitExpression(const std::string& input, const std::string& regex)
{
	// passing -1 as the submatch index parameter performs splitting
	std::regex re(regex);
	std::sregex_token_iterator first{ input.begin(), input.end(), re, -1 }, last;

	return { first, last };
}

<commit_msg>Change version 1.02 → 1.03<commit_after>#include <iostream>
#include <sstream>
#include <string>
#include <regex>

#include "Calculator.h"
#include "ExpressionMaker.h"
#include "ExpressionUtil.h"

const std::string Calculator::m_validCommand("?REPITVQ");
const std::string Calculator::m_numberedCommand("EPIT");

Calculator::Calculator()
	: m_expMaker(ExpressionMaker(m_varTable))
{ }

Calculator::~Calculator()
{ }

void Calculator::Run()
{
	std::cout << "Calculator Version 1.03" << std::endl;
	PrintHelp();

	for (;;)
	{
		try
		{
			do
			{
				GetCommand();
				if (ValidCommand())
				{
					ExecuteCommand();
				}
			}
			while (m_command != 'Q');

			break;
		}
		catch (const std::exception& e)
		{
			std::cout << e.what() << std::endl;
		}
	}
}

void Calculator::PrintHelp()
{
	std::cout
		<< "?  : Help" << std::endl
		<< "R  : Read expression" << std::endl
		<< "E  : Evaluate and print latest expression" << std::endl
		<< "E n: Evaluate and print nth expression" << std::endl
		<< "P  : Print latest expression postfix" << std::endl
		<< "P n: Print nth expression postfix" << std::endl
		<< "I  : Print latest expression infix" << std::endl
		<< "I n: Print nth expression infix" << std::endl
		<< "T  : Print latest expression tree" << std::endl
		<< "T n: Print nth expression tree" << std::endl
		<< "V  : Print variable table list" << std::endl
		<< "Q  : Quit" << std::endl;
}

void Calculator::GetCommand()
{
	std::cout << ">> ";
	std::string readString = "";
	getline(std::cin, readString);
	std::istringstream iss(readString);

	iss >> std::ws;
	iss >> m_command;
	m_command = toupper(m_command);

	if (m_numberedCommand.find(m_command) != std::string::npos)
	{
		unsigned int readNumber = m_oldExpressions.size();
		iss >> std::ws;
		if (isdigit(iss.peek()))
		{
			iss >> readNumber;
			if (readNumber < 1 || readNumber > m_oldExpressions.size())
			{
				m_expressionNumber = m_oldExpressions.size() - 1;
				throw std::logic_error("The number is out of range");
			}

			m_expressionNumber = readNumber - 1;
		}
		else
		{
			m_expressionNumber = std::numeric_limits<unsigned int>::max();
		}
	}
}

bool Calculator::ValidCommand()
{
	if (m_validCommand.find(m_command) == std::string::npos)
	{
		std::cout << "Invalid Command: " << m_command << std::endl;
		return false;
	}

	return true;
}

void Calculator::ExecuteCommand()
{
	if (m_command == '?')
	{
		PrintHelp();
	}
	else if (m_command == 'R')
	{
		ReadExpression(std::cin);
	}
	else if (m_command == 'E')
	{
		EvaluateAndPrintExpression(std::cout);
	}
	else if (m_command == 'P')
	{
		PrintPostfix(std::cout);
	}
	else if (m_command == 'I')
	{
		PrintInfix(std::cout);
	}
	else if (m_command == 'T')
	{
		PrintTree(std::cout);
	}
	else if (m_command == 'V')
	{
		m_varTable.List(std::cout);
	}
	else if (m_command == 'Q')
	{
		std::cout << "Quit!" << std::endl;
	}
	else
	{
		std::cout << "Invalid Command" << std::endl;
	}
}

void Calculator::ReadExpression(std::istream& is)
{
	std::string infix;

	is >> std::ws;

	if (getline(is, infix))
	{
		std::vector<std::string> expressions = SplitExpression(infix, ",");

		for (auto& expression : expressions)
		{
			m_expMaker.SetPostfix(InfixToPostfix(expression));
			Expression exp = m_expMaker.GetExpression();
			m_oldExpressions.push_back(Expression(exp));
			m_currentExpression = exp;

			if (m_currentExpression.TopNodeIsAssign())
			{
				m_currentExpression.Evaluate();
			}
		}
	}
	else
	{
		std::cout << "Invalid Expression" << std::endl;
	}
}

void Calculator::PrintExpression(std::ostream& os) const
{
	std::vector<Expression>::const_iterator iter = m_oldExpressions.begin();

	for (int i = 1; iter != m_oldExpressions.end(); ++iter, ++i)
	{
		os << i << ": " << (*iter).GetInfix() << std::endl;
	}
}

void Calculator::EvaluateAndPrintExpression(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		os << m_currentExpression.Evaluate() << std::endl;
	}
	else
	{
		os << m_oldExpressions.at(m_expressionNumber).Evaluate() << std::endl;
	}
}

void Calculator::PrintPostfix(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		os << m_currentExpression.GetPostfix() << std::endl;
	}
	else
	{
		os << m_oldExpressions.at(m_expressionNumber).GetPostfix() << std::endl;
	}
}

void Calculator::PrintInfix(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		os << m_currentExpression.GetInfix() << std::endl;
	}
	else
	{
		os << m_oldExpressions.at(m_expressionNumber).GetInfix() << std::endl;
	}
}

void Calculator::PrintTree(std::ostream& os) const
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		m_currentExpression.PrintTree(os);
	}
	else
	{
		m_oldExpressions.at(m_expressionNumber).PrintTree(os);
	}
}

void Calculator::SetCurrentExpression()
{
	if (m_expressionNumber == std::numeric_limits<unsigned int>::max())
	{
		throw std::logic_error("Too many expressions");
	}
	else
	{
		Expression exp = m_oldExpressions[m_expressionNumber];
		m_currentExpression = exp;
	}
}

std::vector<std::string> Calculator::SplitExpression(const std::string& input, const std::string& regex)
{
	// passing -1 as the submatch index parameter performs splitting
	std::regex re(regex);
	std::sregex_token_iterator first{ input.begin(), input.end(), re, -1 }, last;

	return { first, last };
}<|endoftext|>


<commit_before>#include "PathVisibleSimple.h"

#include <easyshape.h>

namespace lr
{
namespace preview
{

PathVisibleSimple::PathVisibleSimple(const d2d::Rect& region)
	: m_region(region)
	, m_visited(this)
	, m_node_id(0)
{
}

void PathVisibleSimple::DisableRegion(const d2d::ISprite* spr, bool disable)
{
	std::map<const d2d::ISprite*, std::vector<Node*> >::iterator itr
		= m_bounds.find(spr);
	if (itr == m_bounds.end() && !disable) {
		InsertBoundary(spr);
	} else if (itr != m_bounds.end() && disable) {
		RemoveBoundary(itr);
	}
}

void PathVisibleSimple::QueryRoute(const d2d::Vector& start, const d2d::Vector& end)
{

}

void PathVisibleSimple::DebugDraw() const
{
	if (m_bounds.empty()) {
		return;
	}

 	std::map<const d2d::ISprite*, std::vector<Node*> >::const_iterator itr
 		= m_bounds.begin();
	for (int i = 0, n = itr->second.size(); i < n; ++i)
	{
		Node* node = itr->second[i];
		for (int i = 0, n = node->connections.size(); i < n; ++i) {
			const Connection& conn = node->connections[i];
			d2d::PrimitiveDraw::drawLine(node->pos, conn.n->pos, d2d::LIGHT_RED);
		}
	}
}

d2d::Vector PathVisibleSimple::TransIDToPos(int id) const
{
	d2d::Vector ret;
	ret.setInvalid();

	return ret;
}

void PathVisibleSimple::InsertBoundary(const d2d::ISprite* spr)
{
	// get bound
	std::vector<d2d::Vector> bound;
	const libshape::Sprite* shape = dynamic_cast<const libshape::Sprite*>(spr);
	if (shape && shape->getSymbol().GetType() == libshape::e_polygon) {
		const std::vector<d2d::IShape*>& shapes = shape->getSymbol().GetShapes();
		const libshape::PolygonShape* poly = static_cast<const libshape::PolygonShape*>(shapes[0]);
		bound = poly->GetVertices();
	} else {
		spr->getBounding()->getBoundPos(bound);
	}

	// fix
	std::vector<d2d::Vector> fixed;
	d2d::Math::removeDuplicatePoints(bound, fixed);
	d2d::Matrix mat;
	spr->GetTransMatrix(mat);
	for (int i = 0; i < fixed.size(); ++i) {
		fixed[i] = d2d::Math::transVector(fixed[i], mat);
	}

	// create nodes
	std::vector<Node*> nodes;
	for (int i = 0; i < fixed.size(); ++i) {
		Node* node = new Node(m_node_id++, fixed[i]);
		m_nodes.insert(std::make_pair(node->id, node));
		nodes.push_back(node);
	}

	// build connection
	BuildConnection(nodes);

	// insert to visible graph
	m_bounds.insert(std::make_pair(spr, nodes));
}

void PathVisibleSimple::RemoveBoundary(std::map<const d2d::ISprite*, std::vector<Node*> >::iterator itr)
{
	for (int i = 0, n = itr->second.size(); i < n; ++i)
	{
		Node* node = itr->second[i];

		std::map<int, Node*>::iterator itr_n = m_nodes.find(node->id);
		m_nodes.erase(itr_n);

		std::map<const d2d::ISprite*, std::vector<Node*> >::iterator itr_b
			= m_bounds.begin();
		for ( ; itr_b != m_bounds.end(); ++itr_b)
		{
			if (itr_b == itr) {
				continue;
			}
			for (int i = 0, n = itr_b->second.size(); i < n; ++i) {
				Node* node2 = itr_b->second[i];
				std::vector<Connection>::iterator itr_c = node2->connections.begin();
				for ( ; itr_c != node2->connections.end(); ) {
					if (itr_c->n == node) {
						itr_c = node2->connections.erase(itr_c);
					} else {
						++itr_c;
					}
				}
			}
		}

		delete node;
	}

	m_bounds.erase(itr);
}

void PathVisibleSimple::BuildConnection(const std::vector<Node*>& nodes) const
{
	for (int i = 0, n = nodes.size(); i < n; ++i)
	{
		Node* n0 = nodes[i];
		std::map<const d2d::ISprite*, std::vector<Node*> >::const_iterator itr
			= m_bounds.begin();
		for ( ; itr != m_bounds.end(); ++itr)
		{
			for (int i = 0, n = itr->second.size(); i < n; ++i)
			{
				Node* n1 = itr->second[i];
				if (!IsSegIntersectAllBound(n0->pos, n1->pos, nodes))
				{
					float dis = d2d::Math::getDistance(n0->pos, n1->pos);
					n0->connections.push_back(Connection(dis, n1));
					n1->connections.push_back(Connection(dis, n0));
				}
			}
		}
	}
}

bool PathVisibleSimple::IsSegIntersectAllBound(const d2d::Vector& p0, const d2d::Vector& p1,
											   const std::vector<Node*>& bound) const
{
	if (IsSegIntersectBound(p0, p1, bound)) {
		return true;
	}
	std::map<const d2d::ISprite*, std::vector<Node*> >::const_iterator itr
		= m_bounds.begin();
	for ( ; itr != m_bounds.end(); ++itr) {
		if (IsSegIntersectBound(p0, p1, itr->second)) {
			return true;
		}
	}
	return false;
}

bool PathVisibleSimple::IsSegIntersectBound(const d2d::Vector& p0, const d2d::Vector& p1,
											const std::vector<Node*>& bound) const
{
	std::vector<d2d::Vector> points;
	for (int i = 0, n = bound.size(); i < n; ++i) {
		points.push_back(bound[i]->pos);
	}
	return d2d::Math::IsSegmentIntersectPolyline(p0, p1, points);
}

}
}<commit_msg>[FIXED] visible graph display<commit_after>#include "PathVisibleSimple.h"

#include <easyshape.h>

namespace lr
{
namespace preview
{

PathVisibleSimple::PathVisibleSimple(const d2d::Rect& region)
	: m_region(region)
	, m_visited(this)
	, m_node_id(0)
{
}

void PathVisibleSimple::DisableRegion(const d2d::ISprite* spr, bool disable)
{
	std::map<const d2d::ISprite*, std::vector<Node*> >::iterator itr
		= m_bounds.find(spr);
	if (itr == m_bounds.end() && !disable) {
		InsertBoundary(spr);
	} else if (itr != m_bounds.end() && disable) {
		RemoveBoundary(itr);
	}
}

void PathVisibleSimple::QueryRoute(const d2d::Vector& start, const d2d::Vector& end)
{

}

void PathVisibleSimple::DebugDraw() const
{
	if (m_bounds.empty()) {
		return;
	}

 	std::map<const d2d::ISprite*, std::vector<Node*> >::const_iterator itr
 		= m_bounds.begin();
	for ( ; itr != m_bounds.end(); ++itr)
	{
		for (int i = 0, n = itr->second.size(); i < n; ++i)
		{
			Node* node = itr->second[i];
			for (int j = 0, m = node->connections.size(); j < m; ++j) {
				const Connection& conn = node->connections[j];
				d2d::PrimitiveDraw::drawLine(node->pos, conn.n->pos, d2d::LIGHT_RED);
			}
		}
	}
}

d2d::Vector PathVisibleSimple::TransIDToPos(int id) const
{
	d2d::Vector ret;
	ret.setInvalid();

	return ret;
}

void PathVisibleSimple::InsertBoundary(const d2d::ISprite* spr)
{
	// get bound
	std::vector<d2d::Vector> bound;
	const libshape::Sprite* shape = dynamic_cast<const libshape::Sprite*>(spr);
	if (shape && shape->getSymbol().GetType() == libshape::e_polygon) {
		const std::vector<d2d::IShape*>& shapes = shape->getSymbol().GetShapes();
		const libshape::PolygonShape* poly = static_cast<const libshape::PolygonShape*>(shapes[0]);
		bound = poly->GetVertices();
	} else {
		spr->getBounding()->getBoundPos(bound);
	}

	// fix
	std::vector<d2d::Vector> fixed;
	d2d::Math::removeDuplicatePoints(bound, fixed);
	d2d::Matrix mat;
	spr->GetTransMatrix(mat);
	for (int i = 0; i < fixed.size(); ++i) {
		fixed[i] = d2d::Math::transVector(fixed[i], mat);
	}

	// create nodes
	std::vector<Node*> nodes;
	for (int i = 0; i < fixed.size(); ++i) {
		Node* node = new Node(m_node_id++, fixed[i]);
		m_nodes.insert(std::make_pair(node->id, node));
		nodes.push_back(node);
	}

	// build connection
	BuildConnection(nodes);

	// insert to visible graph
	m_bounds.insert(std::make_pair(spr, nodes));
}

void PathVisibleSimple::RemoveBoundary(std::map<const d2d::ISprite*, std::vector<Node*> >::iterator itr)
{
	for (int i = 0, n = itr->second.size(); i < n; ++i)
	{
		Node* node = itr->second[i];

		std::map<int, Node*>::iterator itr_n = m_nodes.find(node->id);
		m_nodes.erase(itr_n);

		std::map<const d2d::ISprite*, std::vector<Node*> >::iterator itr_b
			= m_bounds.begin();
		for ( ; itr_b != m_bounds.end(); ++itr_b)
		{
			if (itr_b == itr) {
				continue;
			}
			for (int i = 0, n = itr_b->second.size(); i < n; ++i) {
				Node* node2 = itr_b->second[i];
				std::vector<Connection>::iterator itr_c = node2->connections.begin();
				for ( ; itr_c != node2->connections.end(); ) {
					if (itr_c->n == node) {
						itr_c = node2->connections.erase(itr_c);
					} else {
						++itr_c;
					}
				}
			}
		}

		delete node;
	}

	m_bounds.erase(itr);
}

void PathVisibleSimple::BuildConnection(const std::vector<Node*>& nodes) const
{
	for (int i = 0, n = nodes.size(); i < n; ++i)
	{
		Node* n0 = nodes[i];
		std::map<const d2d::ISprite*, std::vector<Node*> >::const_iterator itr
			= m_bounds.begin();
		for ( ; itr != m_bounds.end(); ++itr)
		{
			for (int i = 0, n = itr->second.size(); i < n; ++i)
			{
				Node* n1 = itr->second[i];
				if (!IsSegIntersectAllBound(n0->pos, n1->pos, nodes))
				{
					float dis = d2d::Math::getDistance(n0->pos, n1->pos);
					n0->connections.push_back(Connection(dis, n1));
					n1->connections.push_back(Connection(dis, n0));
				}
			}
		}
	}
}

bool PathVisibleSimple::IsSegIntersectAllBound(const d2d::Vector& p0, const d2d::Vector& p1,
											   const std::vector<Node*>& bound) const
{
	if (IsSegIntersectBound(p0, p1, bound)) {
		return true;
	}
	std::map<const d2d::ISprite*, std::vector<Node*> >::const_iterator itr
		= m_bounds.begin();
	for ( ; itr != m_bounds.end(); ++itr) {
		if (IsSegIntersectBound(p0, p1, itr->second)) {
			return true;
		}
	}
	return false;
}

bool PathVisibleSimple::IsSegIntersectBound(const d2d::Vector& p0, const d2d::Vector& p1,
											const std::vector<Node*>& bound) const
{
	std::vector<d2d::Vector> points;
	for (int i = 0, n = bound.size(); i < n; ++i) {
		points.push_back(bound[i]->pos);
	}
	return d2d::Math::IsSegmentIntersectPolyline(p0, p1, points);
}

}
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/3/9 12:28:02
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

class Solve
{
  int N;
  vector<vector<int>> V;
  vector<vector<int>> B;
  vector<int> ans;
  vector<int> nums;

public:
  Solve(int N, vector<vector<int>> V) : N{N}, V(V), B(2), ans(N), nums{3, 1, 2}
  {
    dfs(0, true);
    flush();
  }

private:
  void dfs(int v, bool color, int parent = -1)
  {
    B[color].push_back(v);
    for (auto x : V[v])
    {
      if (x != parent)
      {
        dfs(x, !color, x);
      }
    }
  }

  void flush()
  {
    for (auto i = 0; i < N; ++i)
    {
      cout << ans[i] << endl;
    }
  }

  int pop_nums(int k)
  {
    auto res{nums[k]};
    if (res > N)
    {
      return -1;
    }
    nums[k] += 3;
    return res;
  }

  int pop_nums_k_0(int k)
  {
    auto tmp{pop_nums(k)};
    if (tmp < 0)
    {
      tmp = pop_nums(0);
    }
    return tmp;
  }

  int pop_arbitrary()
  {
    auto tmp{pop_nums(0)};
    if (tmp < 0)
    {
      tmp = pop_nums(1);
      if (tmp < 0)
      {
        tmp = pop_nums(2);
      }
    }
    return tmp;
  }

  void numbering()
  {
    if (static_cast<int>(B[0].size()) > N / 3 && static_cast<int>(B[1].size()) > N / 3)
    {
      // process
      for (auto x : B[0])
      {
        ans[x] = pop_nums_k_0(1);
      }
      for (auto x : B[1])
      {
        ans[x] = pop_nums_k_0(2);
      }
    }
    else
    {
      if (B[0].size() > B[1].size())
      {
        swap(B[0], B[1]);
      }
      // process
      for (auto x : B[0])
      {
        ans[x] = pop_nums(0);
      }
      for (auto x : B[1])
      {
        ans[x] = pop_arbitrary();
      }
    }
  }
};

int main()
{
  int N;
  cin >> N;
  vector<vector<int>> V(N);
  for (auto i = 0; i < N - 1; ++i)
  {
    int a, b;
    cin >> a >> b;
    --a;
    --b;
    V[a].push_back(b);
    V[b].push_back(a);
  }
  Solve solve(N, V);
}
<commit_msg>tried C.cpp to 'C'<commit_after>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2020/3/9 12:28:02
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

class Solve
{
  int N;
  vector<vector<int>> V;
  vector<vector<int>> B;
  vector<int> ans;
  vector<int> nums;

public:
  Solve(int N, vector<vector<int>> V) : N{N}, V(V), B(2), ans(N), nums{3, 1, 2}
  {
    dfs(0, true);
    numbering();
    flush();
  }

private:
  void dfs(int v, bool color, int parent = -1)
  {
    B[color].push_back(v);
    for (auto x : V[v])
    {
      if (x != parent)
      {
        dfs(x, !color, x);
      }
    }
  }

  void flush()
  {
    for (auto i = 0; i < N; ++i)
    {
      cout << ans[i];
      if (i < N - 1)
      {
        cout << " ";
      }
      else
      {
        cout << endl;
      }
    }
  }

  int pop_nums(int k)
  {
    auto res{nums[k]};
    if (res > N)
    {
      return -1;
    }
    nums[k] += 3;
    return res;
  }

  int pop_nums_k_0(int k)
  {
    auto tmp{pop_nums(k)};
    if (tmp < 0)
    {
      tmp = pop_nums(0);
    }
    return tmp;
  }

  int pop_arbitrary()
  {
    auto tmp{pop_nums(0)};
    if (tmp < 0)
    {
      tmp = pop_nums(1);
      if (tmp < 0)
      {
        tmp = pop_nums(2);
      }
    }
    return tmp;
  }

  void numbering()
  {
    if (static_cast<int>(B[0].size()) > N / 3 && static_cast<int>(B[1].size()) > N / 3)
    {
      // process
      for (auto x : B[0])
      {
        ans[x] = pop_nums_k_0(1);
      }
      for (auto x : B[1])
      {
        ans[x] = pop_nums_k_0(2);
      }
    }
    else
    {
      if (B[0].size() > B[1].size())
      {
        swap(B[0], B[1]);
      }
      // process
      for (auto x : B[0])
      {
        ans[x] = pop_nums(0);
      }
      for (auto x : B[1])
      {
        ans[x] = pop_arbitrary();
      }
    }
  }
};

int main()
{
  int N;
  cin >> N;
  vector<vector<int>> V(N);
  for (auto i = 0; i < N - 1; ++i)
  {
    int a, b;
    cin >> a >> b;
    --a;
    --b;
    V[a].push_back(b);
    V[b].push_back(a);
  }
  Solve solve(N, V);
}
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

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

#include "QmitkPickingToolGUI.h"

#include <mitkPickingTool.h>
#include <QLabel>
#include <QPushbutton>
#include <QRadioButton>
#include <QBoxLayout>

MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkPickingToolGUI, "")

QmitkPickingToolGUI::QmitkPickingToolGUI() : QmitkAutoSegmentationToolGUIBase(false)
{
  auto enablePickingDelegate = [this](bool enabled)
  {
    bool result = false;
    auto tool = this->GetConnectedToolAs<mitk::PickingTool>();
    if (nullptr != tool)
    {
      result = enabled && tool->HasPicks();
    }

    return result;
  };

  m_EnableConfirmSegBtnFnc = enablePickingDelegate;
}

QmitkPickingToolGUI::~QmitkPickingToolGUI()
{
}

void QmitkPickingToolGUI::OnResetPicksClicked()
{
  auto tool = this->GetConnectedToolAs<mitk::PickingTool>();
  if (nullptr != tool)
  {
    tool->ClearPicks();
  }
}

void QmitkPickingToolGUI::OnRadioPickClicked(bool checked)
{
  if (checked)
  {
    this->SetMergeStyle(mitk::MultiLabelSegmentation::MergeStyle::Replace);
    this->SetOverwriteStyle(mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
  }
  else
  {
    this->SetMergeStyle(mitk::MultiLabelSegmentation::MergeStyle::Merge);
    this->SetOverwriteStyle(mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
  }
}

void QmitkPickingToolGUI::InitializeUI(QBoxLayout* mainLayout)
{
  auto radioPick = new QRadioButton("Picking mode", this);
  radioPick->setToolTip("Pick certain parts of the label and dismiss the rest of the label content");
  radioPick->setChecked(true);
  connect(radioPick, &QAbstractButton::toggled, this, &QmitkPickingToolGUI::OnRadioPickClicked);
  mainLayout->addWidget(radioPick);
  m_RadioPick = radioPick;
  this->OnRadioPickClicked(true);

  auto radioRelabel = new QRadioButton("Relabel mode", this);
  radioRelabel->setToolTip("Relabel certain parts of the segmentation as active label.");
  radioRelabel->setChecked(false);
  mainLayout->addWidget(radioRelabel);
  m_RadioRelabel = radioRelabel;

  QLabel* label = new QLabel("Press SHIFT and click to pick region(s).\nPress DEL to remove last pick.", this);
  mainLayout->addWidget(label);

  auto clearButton = new QPushButton("Reset picks",this);
  connect(clearButton, &QPushButton::clicked, this, &QmitkPickingToolGUI::OnResetPicksClicked);
  mainLayout->addWidget(clearButton);
  m_ClearPicksBtn = clearButton;

  Superclass::InitializeUI(mainLayout);
}

void QmitkPickingToolGUI::EnableWidgets(bool enabled)
{
  Superclass::EnableWidgets(enabled);

  if (nullptr != m_ClearPicksBtn)
  {
    m_ClearPicksBtn->setEnabled(enabled);
  }
  if (nullptr != m_RadioPick)
  {
    m_RadioPick->setEnabled(enabled);
  }
  if (nullptr != m_RadioRelabel)
  {
    m_RadioRelabel->setEnabled(enabled);
  }
}

<commit_msg>Fixed wrong include<commit_after>/*============================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.

Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.

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

#include "QmitkPickingToolGUI.h"

#include <mitkPickingTool.h>
#include <QLabel>
#include <QPushButton>
#include <QRadioButton>
#include <QBoxLayout>

MITK_TOOL_GUI_MACRO(MITKSEGMENTATIONUI_EXPORT, QmitkPickingToolGUI, "")

QmitkPickingToolGUI::QmitkPickingToolGUI() : QmitkAutoSegmentationToolGUIBase(false)
{
  auto enablePickingDelegate = [this](bool enabled)
  {
    bool result = false;
    auto tool = this->GetConnectedToolAs<mitk::PickingTool>();
    if (nullptr != tool)
    {
      result = enabled && tool->HasPicks();
    }

    return result;
  };

  m_EnableConfirmSegBtnFnc = enablePickingDelegate;
}

QmitkPickingToolGUI::~QmitkPickingToolGUI()
{
}

void QmitkPickingToolGUI::OnResetPicksClicked()
{
  auto tool = this->GetConnectedToolAs<mitk::PickingTool>();
  if (nullptr != tool)
  {
    tool->ClearPicks();
  }
}

void QmitkPickingToolGUI::OnRadioPickClicked(bool checked)
{
  if (checked)
  {
    this->SetMergeStyle(mitk::MultiLabelSegmentation::MergeStyle::Replace);
    this->SetOverwriteStyle(mitk::MultiLabelSegmentation::OverwriteStyle::RegardLocks);
  }
  else
  {
    this->SetMergeStyle(mitk::MultiLabelSegmentation::MergeStyle::Merge);
    this->SetOverwriteStyle(mitk::MultiLabelSegmentation::OverwriteStyle::IgnoreLocks);
  }
}

void QmitkPickingToolGUI::InitializeUI(QBoxLayout* mainLayout)
{
  auto radioPick = new QRadioButton("Picking mode", this);
  radioPick->setToolTip("Pick certain parts of the label and dismiss the rest of the label content");
  radioPick->setChecked(true);
  connect(radioPick, &QAbstractButton::toggled, this, &QmitkPickingToolGUI::OnRadioPickClicked);
  mainLayout->addWidget(radioPick);
  m_RadioPick = radioPick;
  this->OnRadioPickClicked(true);

  auto radioRelabel = new QRadioButton("Relabel mode", this);
  radioRelabel->setToolTip("Relabel certain parts of the segmentation as active label.");
  radioRelabel->setChecked(false);
  mainLayout->addWidget(radioRelabel);
  m_RadioRelabel = radioRelabel;

  QLabel* label = new QLabel("Press SHIFT and click to pick region(s).\nPress DEL to remove last pick.", this);
  mainLayout->addWidget(label);

  auto clearButton = new QPushButton("Reset picks",this);
  connect(clearButton, &QPushButton::clicked, this, &QmitkPickingToolGUI::OnResetPicksClicked);
  mainLayout->addWidget(clearButton);
  m_ClearPicksBtn = clearButton;

  Superclass::InitializeUI(mainLayout);
}

void QmitkPickingToolGUI::EnableWidgets(bool enabled)
{
  Superclass::EnableWidgets(enabled);

  if (nullptr != m_ClearPicksBtn)
  {
    m_ClearPicksBtn->setEnabled(enabled);
  }
  if (nullptr != m_RadioPick)
  {
    m_RadioPick->setEnabled(enabled);
  }
  if (nullptr != m_RadioRelabel)
  {
    m_RadioRelabel->setEnabled(enabled);
  }
}

<|endoftext|>


<commit_before><commit_msg>Delete a.cpp<commit_after><|endoftext|>


<commit_before>#include <BeaconTile.h>

BeaconTile::BeaconTile(int id) : Tile(id, &Material::metal) {
	tex = getTextureUVCoordinateSet("glass", 0);
	secondary_tex = getTextureUVCoordinateSet("obsidian", 0);
	terciary_tex = getTextureUVCoordinateSet("beacon", 0);
	//fourth_tex = getTextureUVCoordinateSet("beacon_beam", 0);
	//fifth_tex = getTextureUVCoordinateSet("beacon_beam", 1);
	beacon->renderPass = Tile::glass->renderPass;
	Tile::solid[id] = false;
	Tile::lightBlock[id] = 0;
	new TileItem(id - 256);
}

BeaconTile::isCubeShaped() {
     return false;
}

BeaconTile::isSolidRender() {
     return false;
}

const TextureUVCoordinateSet& BeaconTile::getTexture(signed char side, int data) {
	return side == 0 ? tex : (side == 1 ? secondary_tex : terciary_tex);
}
<commit_msg>Update BeaconTile.cpp<commit_after>#include "BeaconTile.h"

BeaconTile::BeaconTile(int id) : Tile(id, &Material::metal) {
	tex = getTextureUVCoordinateSet("glass", 0);
	secondary_tex = getTextureUVCoordinateSet("obsidian", 0);
	terciary_tex = getTextureUVCoordinateSet("beacon", 0);
	//fourth_tex = getTextureUVCoordinateSet("beacon_beam", 0);
	//fifth_tex = getTextureUVCoordinateSet("beacon_beam", 1);
	beacon->renderPass = Tile::glass->renderPass;
	Tile::solid[id] = false;
	Tile::lightBlock[id] = 0;
	new TileItem(id - 256);
}

bool BeaconTile::isCubeShaped() {
     return false;
}

bool BeaconTile::isSolidRender() {
     return false;
}

const TextureUVCoordinateSet& BeaconTile::getTexture(signed char side, int data) {
	return side == 0 ? tex : (side == 1 ? secondary_tex : terciary_tex);
}
<|endoftext|>