<commit_before>// RTK includes
#include "rtkConfiguration.h"
#include <rtkFDKBackProjectionImageFilter.h>
#include <rtkConstantImageSource.h>
#include <rtkThreeDCircularProjectionGeometry.h>
#include <rtkRayEllipsoidIntersectionImageFilter.h>
#include <rtkDisplacedDetectorImageFilter.h>
#include <rtkParkerShortScanImageFilter.h>
#include <rtkFDKConeBeamReconstructionFilter.h>

// ITK includes
#include <itkImageFileWriter.h>
#include <itkStreamingImageFilter.h>

int main(int , char **)
{
  // Defines the image type
  typedef itk::Image< float, 3 > ImageType;

  // Defines the RTK geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();

  // Projection matrices
  unsigned int numberOfProjections = 360;
  unsigned int firstAngle = 0;
  unsigned int angularArc = 360;
  unsigned int sid = 600; // source to isocenter distance in mm
  unsigned int sdd = 1200; // source to detector distance in mm
  int isox = 0; // X coordinate on the projection image of isocenter
  int isoy = 0; // Y coordinate on the projection image of isocenter

  for(unsigned int noProj=0; noProj<numberOfProjections; noProj++)
    {
    double angle = (float)firstAngle + (float)noProj * angularArc / (float)numberOfProjections;
    geometry->AddProjection(sid,
                            sdd,
                            angle,
                            isox,
                            isoy);
    }

  // Create a stack of empty projection images
  typedef rtk::ConstantImageSource< ImageType > ConstantImageSourceType;
  ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SpacingType spacing;
  ConstantImageSourceType::SizeType sizeOutput;

  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;

  // Adjust size according to geometry
  sizeOutput[0] = 256;
  sizeOutput[1] = 256;
  sizeOutput[2] = numberOfProjections;

  spacing[0] = 1.;
  spacing[1] = 1.;
  spacing[2] = 1.;
  constantImageSource->SetOrigin( origin );
  constantImageSource->SetSpacing( spacing );
  constantImageSource->SetSize( sizeOutput );
  constantImageSource->SetConstant( 0. );

   // Create the projector
  typedef rtk::RayEllipsoidIntersectionImageFilter<ImageType, ImageType> REIType;
  REIType::Pointer rei = REIType::New();
  REIType::VectorType semiprincipalaxis, center;
  semiprincipalaxis.Fill(50.);
  center.Fill(0.);
  //Set GrayScale value, axes, center...
  rei->SetDensity(2.);
  rei->SetAngle(0.);
  rei->SetGeometry( geometry );
  rei->SetInput( constantImageSource->GetOutput() );
  rei->Update();

  // Create reconstructed image
  ConstantImageSourceType::Pointer constantImageSource2 = ConstantImageSourceType::New();

  // Adjust size according to geometry
  sizeOutput[0] = 256;
  sizeOutput[1] = 256;
  sizeOutput[2] = 256;

  constantImageSource2->SetOrigin( origin );
  constantImageSource2->SetSpacing( spacing );
  constantImageSource2->SetSize( sizeOutput );
  constantImageSource2->SetConstant( 0. );

  // FDK reconstruction filtering
  typedef rtk::FDKConeBeamReconstructionFilter< ImageType > FDKCPUType;
  FDKCPUType::Pointer feldkamp = FDKCPUType::New();
  feldkamp->SetInput( 0, constantImageSource2->GetOutput() );
  feldkamp->SetInput( 1, rei->GetOutput() );
  feldkamp->SetGeometry( geometry );
  feldkamp->GetRampFilter()->SetTruncationCorrection(0.);
  feldkamp->GetRampFilter()->SetHannCutFrequency(0.0);
  feldkamp->Update();

  // Writer
  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( "output.mha" );
  writer->SetUseCompression(true);
  writer->SetInput( feldkamp->GetOutput() );
  writer->Update();

  return 0;
}

<commit_msg>BUG: Missing center and axis for the RayEllipsoidIntersectionImageFilter<commit_after>// RTK includes
#include "rtkConfiguration.h"
#include <rtkFDKBackProjectionImageFilter.h>
#include <rtkConstantImageSource.h>
#include <rtkThreeDCircularProjectionGeometry.h>
#include <rtkRayEllipsoidIntersectionImageFilter.h>
#include <rtkDisplacedDetectorImageFilter.h>
#include <rtkParkerShortScanImageFilter.h>
#include <rtkFDKConeBeamReconstructionFilter.h>

// ITK includes
#include <itkImageFileWriter.h>
#include <itkStreamingImageFilter.h>

int main(int , char **)
{
  // Defines the image type
  typedef itk::Image< float, 3 > ImageType;

  // Defines the RTK geometry object
  typedef rtk::ThreeDCircularProjectionGeometry GeometryType;
  GeometryType::Pointer geometry = GeometryType::New();

  // Projection matrices
  unsigned int numberOfProjections = 360;
  unsigned int firstAngle = 0;
  unsigned int angularArc = 360;
  unsigned int sid = 600; // source to isocenter distance in mm
  unsigned int sdd = 1200; // source to detector distance in mm
  int isox = 0; // X coordinate on the projection image of isocenter
  int isoy = 0; // Y coordinate on the projection image of isocenter

  for(unsigned int noProj=0; noProj<numberOfProjections; noProj++)
    {
    double angle = (float)firstAngle + (float)noProj * angularArc / (float)numberOfProjections;
    geometry->AddProjection(sid,
                            sdd,
                            angle,
                            isox,
                            isoy);
    }

  // Create a stack of empty projection images
  typedef rtk::ConstantImageSource< ImageType > ConstantImageSourceType;
  ConstantImageSourceType::Pointer constantImageSource = ConstantImageSourceType::New();
  ConstantImageSourceType::PointType origin;
  ConstantImageSourceType::SpacingType spacing;
  ConstantImageSourceType::SizeType sizeOutput;

  origin[0] = -127.;
  origin[1] = -127.;
  origin[2] = -127.;

  // Adjust size according to geometry
  sizeOutput[0] = 256;
  sizeOutput[1] = 256;
  sizeOutput[2] = numberOfProjections;

  spacing[0] = 1.;
  spacing[1] = 1.;
  spacing[2] = 1.;
  constantImageSource->SetOrigin( origin );
  constantImageSource->SetSpacing( spacing );
  constantImageSource->SetSize( sizeOutput );
  constantImageSource->SetConstant( 0. );

   // Create the projector
  typedef rtk::RayEllipsoidIntersectionImageFilter<ImageType, ImageType> REIType;
  REIType::Pointer rei = REIType::New();
  REIType::VectorType semiprincipalaxis, center;
  semiprincipalaxis.Fill(50.);
  center.Fill(0.);
  //Set GrayScale value, axes, center...
  rei->SetDensity(2.);
  rei->SetAngle(0.);
  rei->SetCenter(center);
  rei->SetAxis(semiprincipalaxis);
  rei->SetGeometry( geometry );
  rei->SetInput( constantImageSource->GetOutput() );
  rei->Update();

  // Create reconstructed image
  ConstantImageSourceType::Pointer constantImageSource2 = ConstantImageSourceType::New();

  // Adjust size according to geometry
  sizeOutput[0] = 256;
  sizeOutput[1] = 256;
  sizeOutput[2] = 256;

  constantImageSource2->SetOrigin( origin );
  constantImageSource2->SetSpacing( spacing );
  constantImageSource2->SetSize( sizeOutput );
  constantImageSource2->SetConstant( 0. );

  std::cout << "Performing reconstruction" << std::endl;

  // FDK reconstruction filtering
  typedef rtk::FDKConeBeamReconstructionFilter< ImageType > FDKCPUType;
  FDKCPUType::Pointer feldkamp = FDKCPUType::New();
  feldkamp->SetInput( 0, constantImageSource2->GetOutput() );
  feldkamp->SetInput( 1, rei->GetOutput() );
  feldkamp->SetGeometry( geometry );
  feldkamp->GetRampFilter()->SetTruncationCorrection(0.);
  feldkamp->GetRampFilter()->SetHannCutFrequency(0.0);
  feldkamp->Update();

  std::cout << "Writing output image" << std::endl;

  // Writer
  typedef itk::ImageFileWriter<ImageType> WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( "output.mha" );
  writer->SetUseCompression(true);
  writer->SetInput( feldkamp->GetOutput() );
  writer->Update();

  std::cout << "Done" << std::endl;

  return 0;
}

<|endoftext|>


<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    importcertificatecommand.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "importcertificatecommand.h"

#include <kleo/cryptobackendfactory.h>
#include <kleo/importjob.h>

#include <gpgme++/global.h>
#include <gpgme++/importresult.h>

#include <KLocale>
#include <KMessageBox>
#include <KJob>

#include <QByteArray>
#include <QFile>
#include <QFileDialog>
#include <QPointer>
#include <QString>
#include <QWidget>

#include <memory>

using namespace GpgME;
using namespace Kleo;

class ImportCertificateCommand::Private {
    friend class ::ImportCertificateCommand;
    ImportCertificateCommand * const q;
public:
    explicit Private( ImportCertificateCommand * qq );
    ~Private();

    bool ensureHaveFile();
    void startImport( const QByteArray& data );
    void importResult( const GpgME::ImportResult& );
    GpgME::Protocol checkProtocol( const QByteArray& data, const QString& filename ) const;
    void showError( const GpgME::Error& error );
    void showDetails( const ImportResult& result );

private:
    QWidget* parent;
    QPointer<ImportJob> importJob;
    QString filename;
};

ImportCertificateCommand::Private::Private( ImportCertificateCommand * qq )
    : q( qq ), parent( 0 ), importJob( 0 )
{

}

ImportCertificateCommand::Private::~Private()
{
    if ( importJob )
        importJob->slotCancel();
}

ImportCertificateCommand::ImportCertificateCommand( KeyListController * parent )
  : Command( parent ), d( new Private( this ) )
{

}

ImportCertificateCommand::~ImportCertificateCommand() {}

void ImportCertificateCommand::setParentWidget( QWidget* parent )
{
    d->parent = parent;
}

QString ImportCertificateCommand::fileName() const
{
    return d->filename;
}

void ImportCertificateCommand::setFileName( const QString& fileName )
{
    d->filename = fileName;
}

void ImportCertificateCommand::doStart()
{
    if ( !d->ensureHaveFile() )
    {
        emit canceled();
        return;
    }
    //TODO: use KIO here
    QFile in( d->filename );
    if ( !in.open( QIODevice::ReadOnly ) )
    {
        KMessageBox::error( d->parent, i18n( "Could not open file %1 for reading", d->filename ), i18n( "Certificate Import Failed" ) );

        emit finished(); //TODO: correct signal??
        return;
    }
    d->startImport( in.readAll() );
    emit info( i18n( "Importing certificate..." ) );
}

bool ImportCertificateCommand::Private::ensureHaveFile()
{
   if ( filename.isNull() )
        filename = QFileDialog::getOpenFileName( parent, i18n( "Select Certificate File" ), QString(), i18n( "Certificates (*.asc *.pem *.der *.p7c *.p12)" )  );
   return !filename.isNull();
}

void ImportCertificateCommand::Private::showDetails( const ImportResult& res )
{
      const KLocalizedString normalLine = ki18n("
%1	%2
");
        const KLocalizedString boldLine = ki18n("
%1	%2
");

        QStringList lines;
        lines.push_back( normalLine.subs( i18n("Total number processed:") )
                         .subs( res.numConsidered() ).toString() );
        lines.push_back( normalLine.subs( i18n("Imported:") )
                         .subs( res.numImported() ).toString() );
        if ( res.newSignatures() )
            lines.push_back( normalLine.subs( i18n("New signatures:") )
                             .subs( res.newSignatures() ).toString() );
        if ( res.newUserIDs() )
            lines.push_back( normalLine.subs( i18n("New user IDs:") )
                             .subs( res.newUserIDs() ).toString() );
        if ( res.numKeysWithoutUserID() )
            lines.push_back( normalLine.subs( i18n("Keys without user IDs:") )
                             .subs( res.numKeysWithoutUserID() ).toString() );
        if ( res.newSubkeys() )
            lines.push_back( normalLine.subs( i18n("New subkeys:") )
                             .subs( res.newSubkeys() ).toString() );
        if ( res.newRevocations() )
            lines.push_back( boldLine.subs( i18n("Newly revoked:") )
                             .subs( res.newRevocations() ).toString() );
        if ( res.notImported() )
            lines.push_back( boldLine.subs( i18n("Not imported:") )
                             .subs( res.notImported() ).toString() );
        if ( res.numUnchanged() )
            lines.push_back( normalLine.subs( i18n("Unchanged:") )
                             .subs( res.numUnchanged() ).toString() );
        if ( res.numSecretKeysConsidered() )
            lines.push_back( normalLine.subs( i18n("Secret keys processed:") )
                             .subs( res.numSecretKeysConsidered() ).toString() );
        if ( res.numSecretKeysImported() )
            lines.push_back( normalLine.subs( i18n("Secret keys imported:") )
                             .subs( res.numSecretKeysImported() ).toString() );
        if ( res.numSecretKeysConsidered() - res.numSecretKeysImported() - res.numSecretKeysUnchanged() > 0 )
            lines.push_back( boldLine.subs( i18n("Secret keys not imported:") )
                             .subs(  res.numSecretKeysConsidered()
                                     - res.numSecretKeysImported()
                                     - res.numSecretKeysUnchanged() ).toString() );
        if ( res.numSecretKeysUnchanged() )
            lines.push_back( normalLine.subs( i18n("Secret keys unchanged:") )
                             .subs( res.numSecretKeysUnchanged() ).toString() );

        KMessageBox::information( parent,
                                  i18n( "<qt>
Detailed results of importing %1:
"
                                        "
%2
</qt>" ,
                                        filename, lines.join( QString() ) ),
                                  i18n( "Certificate Import Result" ) );
}

void ImportCertificateCommand::Private::showError( const GpgME::Error& err )
{
  assert( err );
  const QString msg = i18n( "<qt>
An error occurred while trying "
			    "to import the certificate %1:
"
			    "
%2
</qt>",
                            filename,
                            QString::fromLocal8Bit( err.asString() ) );
  KMessageBox::error( parent, msg, i18n( "Certificate Import Failed" ) );
}

void ImportCertificateCommand::Private::importResult( const GpgME::ImportResult& result )
{
    if ( result.error().isCanceled() ) {
        emit q->canceled();
        return;
    }

    if ( result.error() ) {
        showError( result.error() );
        emit q->finished();
        return;
    }

    showDetails( result );
}

GpgME::Protocol ImportCertificateCommand::Private::checkProtocol( const QByteArray& data, const QString& filename ) const
{
    QStringList smimeSuffixes;
    smimeSuffixes << ".pem" << ".der", ".p7c", ".p12";
    Q_FOREACH ( const QString& i, smimeSuffixes )
        if ( filename.endsWith( i, Qt::CaseInsensitive ) )
            return GpgME::CMS;
    if ( filename.endsWith( ".asc", Qt::CaseInsensitive ) )
        return GpgME::OpenPGP;
    return GpgME::UnknownProtocol;
}

void ImportCertificateCommand::Private::startImport( const QByteArray& data )
{
    const GpgME::Protocol protocol = checkProtocol( data, filename );
    if ( protocol == GpgME::UnknownProtocol ) //TODO: might use exceptions here
    {
        KMessageBox::error( parent, i18n( "Could not determine certificate type.", filename ), i18n( "Certificate Import Failed" ) );
        emit q->canceled(); //TODO: use correct signal
        return;
    }

    std::auto_ptr<ImportJob> job( CryptoBackendFactory::instance()->protocol( protocol )->importJob() );
    assert( job.get() );
    connect( job.get(), SIGNAL(result( GpgME::ImportResult ) ),
             q, SLOT( importResult( GpgME::ImportResult ) ) );
    connect( job.get(), SIGNAL( process( QString, int, int ) ),
             q, SIGNAL( process( QString, int, int ) ) );
    const GpgME::Error err = job->start( data );

    importJob = job.release();
}

void ImportCertificateCommand::doCancel()
{
    if ( d->importJob )
        d->importJob->slotCancel();
}

#include "moc_importcertificatecommand.cpp"

<commit_msg>++emit finished<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    importcertificatecommand.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include "importcertificatecommand.h"

#include <kleo/cryptobackendfactory.h>
#include <kleo/importjob.h>

#include <gpgme++/global.h>
#include <gpgme++/importresult.h>

#include <KLocale>
#include <KMessageBox>
#include <KJob>

#include <QByteArray>
#include <QFile>
#include <QFileDialog>
#include <QPointer>
#include <QString>
#include <QWidget>

#include <memory>

using namespace GpgME;
using namespace Kleo;

class ImportCertificateCommand::Private {
    friend class ::ImportCertificateCommand;
    ImportCertificateCommand * const q;
public:
    explicit Private( ImportCertificateCommand * qq );
    ~Private();

    bool ensureHaveFile();
    void startImport( const QByteArray& data );
    void importResult( const GpgME::ImportResult& );
    GpgME::Protocol checkProtocol( const QByteArray& data, const QString& filename ) const;
    void showError( const GpgME::Error& error );
    void showDetails( const ImportResult& result );

private:
    QWidget* parent;
    QPointer<ImportJob> importJob;
    QString filename;
};

ImportCertificateCommand::Private::Private( ImportCertificateCommand * qq )
    : q( qq ), parent( 0 ), importJob( 0 )
{

}

ImportCertificateCommand::Private::~Private()
{
    if ( importJob )
        importJob->slotCancel();
}

ImportCertificateCommand::ImportCertificateCommand( KeyListController * parent )
  : Command( parent ), d( new Private( this ) )
{

}

ImportCertificateCommand::~ImportCertificateCommand() {}

void ImportCertificateCommand::setParentWidget( QWidget* parent )
{
    d->parent = parent;
}

QString ImportCertificateCommand::fileName() const
{
    return d->filename;
}

void ImportCertificateCommand::setFileName( const QString& fileName )
{
    d->filename = fileName;
}

void ImportCertificateCommand::doStart()
{
    if ( !d->ensureHaveFile() )
    {
        emit canceled();
        return;
    }
    //TODO: use KIO here
    QFile in( d->filename );
    if ( !in.open( QIODevice::ReadOnly ) )
    {
        KMessageBox::error( d->parent, i18n( "Could not open file %1 for reading", d->filename ), i18n( "Certificate Import Failed" ) );

        emit finished(); //TODO: correct signal??
        return;
    }
    d->startImport( in.readAll() );
    emit info( i18n( "Importing certificate..." ) );
}

bool ImportCertificateCommand::Private::ensureHaveFile()
{
   if ( filename.isNull() )
        filename = QFileDialog::getOpenFileName( parent, i18n( "Select Certificate File" ), QString(), i18n( "Certificates (*.asc *.pem *.der *.p7c *.p12)" )  );
   return !filename.isNull();
}

void ImportCertificateCommand::Private::showDetails( const ImportResult& res )
{
      const KLocalizedString normalLine = ki18n("
%1	%2
");
        const KLocalizedString boldLine = ki18n("
%1	%2
");

        QStringList lines;
        lines.push_back( normalLine.subs( i18n("Total number processed:") )
                         .subs( res.numConsidered() ).toString() );
        lines.push_back( normalLine.subs( i18n("Imported:") )
                         .subs( res.numImported() ).toString() );
        if ( res.newSignatures() )
            lines.push_back( normalLine.subs( i18n("New signatures:") )
                             .subs( res.newSignatures() ).toString() );
        if ( res.newUserIDs() )
            lines.push_back( normalLine.subs( i18n("New user IDs:") )
                             .subs( res.newUserIDs() ).toString() );
        if ( res.numKeysWithoutUserID() )
            lines.push_back( normalLine.subs( i18n("Keys without user IDs:") )
                             .subs( res.numKeysWithoutUserID() ).toString() );
        if ( res.newSubkeys() )
            lines.push_back( normalLine.subs( i18n("New subkeys:") )
                             .subs( res.newSubkeys() ).toString() );
        if ( res.newRevocations() )
            lines.push_back( boldLine.subs( i18n("Newly revoked:") )
                             .subs( res.newRevocations() ).toString() );
        if ( res.notImported() )
            lines.push_back( boldLine.subs( i18n("Not imported:") )
                             .subs( res.notImported() ).toString() );
        if ( res.numUnchanged() )
            lines.push_back( normalLine.subs( i18n("Unchanged:") )
                             .subs( res.numUnchanged() ).toString() );
        if ( res.numSecretKeysConsidered() )
            lines.push_back( normalLine.subs( i18n("Secret keys processed:") )
                             .subs( res.numSecretKeysConsidered() ).toString() );
        if ( res.numSecretKeysImported() )
            lines.push_back( normalLine.subs( i18n("Secret keys imported:") )
                             .subs( res.numSecretKeysImported() ).toString() );
        if ( res.numSecretKeysConsidered() - res.numSecretKeysImported() - res.numSecretKeysUnchanged() > 0 )
            lines.push_back( boldLine.subs( i18n("Secret keys not imported:") )
                             .subs(  res.numSecretKeysConsidered()
                                     - res.numSecretKeysImported()
                                     - res.numSecretKeysUnchanged() ).toString() );
        if ( res.numSecretKeysUnchanged() )
            lines.push_back( normalLine.subs( i18n("Secret keys unchanged:") )
                             .subs( res.numSecretKeysUnchanged() ).toString() );

        KMessageBox::information( parent,
                                  i18n( "<qt>
Detailed results of importing %1:
"
                                        "
%2
</qt>" ,
                                        filename, lines.join( QString() ) ),
                                  i18n( "Certificate Import Result" ) );
}

void ImportCertificateCommand::Private::showError( const GpgME::Error& err )
{
  assert( err );
  const QString msg = i18n( "<qt>
An error occurred while trying "
			    "to import the certificate %1:
"
			    "
%2
</qt>",
                            filename,
                            QString::fromLocal8Bit( err.asString() ) );
  KMessageBox::error( parent, msg, i18n( "Certificate Import Failed" ) );
}

void ImportCertificateCommand::Private::importResult( const GpgME::ImportResult& result )
{
    if ( result.error().isCanceled() ) {
        emit q->canceled();
        return;
    }

    if ( result.error() ) {
        showError( result.error() );
        emit q->finished();
        return;
    }

    showDetails( result );
    emit q->finished();
}

GpgME::Protocol ImportCertificateCommand::Private::checkProtocol( const QByteArray& data, const QString& filename ) const
{
    QStringList smimeSuffixes;
    smimeSuffixes << ".pem" << ".der", ".p7c", ".p12";
    Q_FOREACH ( const QString& i, smimeSuffixes )
        if ( filename.endsWith( i, Qt::CaseInsensitive ) )
            return GpgME::CMS;
    if ( filename.endsWith( ".asc", Qt::CaseInsensitive ) )
        return GpgME::OpenPGP;
    return GpgME::UnknownProtocol;
}

void ImportCertificateCommand::Private::startImport( const QByteArray& data )
{
    const GpgME::Protocol protocol = checkProtocol( data, filename );
    if ( protocol == GpgME::UnknownProtocol ) //TODO: might use exceptions here
    {
        KMessageBox::error( parent, i18n( "Could not determine certificate type.", filename ), i18n( "Certificate Import Failed" ) );
        emit q->canceled(); //TODO: use correct signal
        return;
    }

    std::auto_ptr<ImportJob> job( CryptoBackendFactory::instance()->protocol( protocol )->importJob() );
    assert( job.get() );
    connect( job.get(), SIGNAL(result( GpgME::ImportResult ) ),
             q, SLOT( importResult( GpgME::ImportResult ) ) );
    connect( job.get(), SIGNAL( process( QString, int, int ) ),
             q, SIGNAL( process( QString, int, int ) ) );
    const GpgME::Error err = job->start( data );

    importJob = job.release();
}

void ImportCertificateCommand::doCancel()
{
    if ( d->importJob )
        d->importJob->slotCancel();
}

#include "moc_importcertificatecommand.cpp"

<|endoftext|>


<commit_before>/*
 * CocircConn.cpp
 *
 *  Created on: Nov 10, 2008
 *      Author: rasmussn
 */

#include "GeislerConn.hpp"
#include "../PetaVision/src/io/io.h"
#include "../PetaVision/src/utils/conversions.h"
#include "../PetaVision/src/include/pv_types.h"
#include <assert.h>
#include <string.h>

namespace PV {

GeislerConn::GeislerConn()
{
   printf("GeislerConn::GeislerConn: running default constructor\n");
   initialize_base();
}

GeislerConn::GeislerConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
      HyPerLayer * post, int channel)
{
   initialize_base();
   initialize(name, hc, pre, post, channel);
}

GeislerConn::GeislerConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
      HyPerLayer * post)
{
   initialize_base();
   initialize(name, hc, pre, post, channel, NULL); // use default channel
}

// provide filename or set to NULL
GeislerConn::GeislerConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
      HyPerLayer * post, int channel, const char * filename)
{
   initialize_base();
   initialize(name, hc, pre, post, channel, filename);
}

int GeislerConn::initialize_base()
{
	numUpdates = 0;
	avePreActivity = 0.0;
	avePostActivity = 0.0;
	geislerPatches = NULL;
	return KernelConn::initialize_base();
}

PVPatch ** GeislerConn::createWeights(PVPatch ** patches, int nPatches, int nxPatch,
      int nyPatch, int nfPatch)
{
	geislerPatches = allocWeights(patches, nPatches, nxPatch, nyPatch, nfPatch);
	return KernelConn::createWeights(patches, nPatches, nxPatch, nyPatch, nfPatch);
}

int GeislerConn::deleteWeights()
{
   const int arbor = 0;

   for (int k = 0; k < numDataPatches(arbor); k++) {
      pvpatch_inplace_delete(geislerPatches[k]);
   }
   free(geislerPatches);

   return KernelConn::deleteWeights();
}

PVPatch ** GeislerConn::initializeDefaultWeights(PVPatch ** patches, int numPatches)
{
   // patches should already be initialized to zero
   return patches;
}

int GeislerConn::updateState(float time, float dt)
{
	int axonID = 0;
	numUpdates++;
	int nPreEx = pre->clayer->numExtended;
	const pvdata_t * aPre = pre->getLayerData();
	pvdata_t avePre = 0.0;
	for (int kPre = 0; kPre < nPreEx; kPre++){
		avePre += aPre[kPre];
	}
	avePre /= nPreEx;
	avePreActivity += avePre;
	int nPost = post->clayer->numNeurons;
	const pvdata_t * aPost = post->getLayerData();

	pvdata_t avePost = 0.0;
	for (int kPost = 0; kPost < nPost; kPost++){
		avePost += aPost[kPost];
	}
	avePost /= nPost;
	avePostActivity += avePost;

	// initialize geislerPatches
	int numKernels = this->numDataPatches(axonID);
	int numWeights = nxp * nyp * nfp;
	for (int iKernel = 0; iKernel < numKernels; iKernel++){
		pvdata_t * kernelWeights = kernelPatches[iKernel]->data;
		pvdata_t * geislerWeights = geislerPatches[iKernel]->data;
		for (int iWeight = 0; iWeight < numWeights; iWeight++){
			kernelWeights[iWeight] = geislerWeights[iWeight];
			geislerWeights[iWeight] = 0.0;
		}
	}

	int status = updateWeights(axonID);

	// normalize geislerPatches
	for (int iKernel = 0; iKernel < numKernels; iKernel++){
		pvdata_t * kernelWeights = kernelPatches[iKernel]->data;
		pvdata_t * geislerWeights = geislerPatches[iKernel]->data;
		for (int iWeight = 0; iWeight < numWeights; iWeight++){
			geislerWeights[iWeight] /= nPost;
			geislerWeights[iWeight] += kernelWeights[iWeight];
#ifdef APPLY_GEISLER_WEIGHTS
			kernelWeights[iWeight] /= numUpdates;
			pvdata_t kernelNorm = (avePreActivity / numUpdates ) * (avePostActivity / numUpdates );
			kernelWeights[iWeight] -= kernelNorm;
#else
			kernelWeights[iWeight] = 0.0;
#endif
		}
	}
#ifdef APPLY_GEISLER_WEIGHTS
	this->normalizeWeights(this->kernelPatches, this->numDataPatches(axonID));
#endif
	return status;
}

int GeislerConn::updateWeights(int axonID)
{
	// this stride is in extended space for post-synaptic activity and
	// STDP decrement variable
	const int postStrideY = post->clayer->numFeatures
                         * (post->clayer->loc.nx + 2 * post->clayer->loc.nPad);

	const int numExtended = pre->clayer->numExtended;
	assert(numExtended == numWeightPatches(axonID));

	const pvdata_t * preLayerData = pre->getLayerData();

	int numKernelPatches = numDataPatches(axonID);

	for (int kPre = 0; kPre < numExtended; kPre++) {
      PVAxonalArbor * arbor = axonalArbor(kPre, axonID);

      const float aPre = preLayerData[kPre];

      PVPatch * wPatch = arbor->weights;
      size_t postOffset = arbor->offset;
      const pvdata_t * aPost = &post->getLayerData()[postOffset];

      int nk  = wPatch->nf * wPatch->nx; // one line in x at a time
      int ny  = wPatch->ny;
      int sy  = wPatch->sy;

      const int nKernels = this->numDataPatches(axonID);
      int kfPre = kPre % nKernels;
      PVPatch * gPatch = geislerPatches[kfPre];

      pvdata_t * data_head = (pvdata_t *) ((char*) wPatch + sizeof(PVPatch));
      size_t data_offset = wPatch->data - data_head;
      pvdata_t * gWeights = &gPatch->data[data_offset];

      for (int y = 0; y < ny; y++) {
         for (int k = 0; k < nk; k++) {
             gWeights[k] += aPre  * aPost[k];
         }
          // advance pointers in y
         gWeights += sy;
         // postActivity and M are extended layer
         aPost += postStrideY;
     }
   }

   return 0;
}

int GeislerConn::writeWeights(float time, bool last)
{
#ifdef APPLY_GEISLER_WEIGHTS
	// do nothing, kernels are already up to date
#else
	// copy geislerPatches to kernelPatches
	const int axonID = 0;
	const int numKernels = numDataPatches(axonID);
	const int numWeights = nxp * nyp * nfp;
	for (int iKernel = 0; iKernel < numKernels; iKernel++){
			pvdata_t * kernelWeights = kernelPatches[iKernel]->data;
			pvdata_t * geislerWeights = geislerPatches[iKernel]->data;
			for (int iWeight = 0; iWeight < numWeights; iWeight++){
				kernelWeights[iWeight] = geislerWeights[iWeight];
				kernelWeights[iWeight] /= numUpdates;
				pvdata_t kernelNorm = (avePreActivity / numUpdates ) * (avePostActivity / numUpdates );
				kernelWeights[iWeight] -= kernelNorm;
			}
		}
	this->normalizeWeights(this->kernelPatches, this->numDataPatches(axonID));
#endif
	return KernelConn::writeWeights(time, last);
}

} // namespace PV
<commit_msg>bug fixes<commit_after>/*
 * CocircConn.cpp
 *
 *  Created on: Nov 10, 2008
 *      Author: rasmussn
 */

#include "GeislerConn.hpp"
#include "../PetaVision/src/io/io.h"
#include "../PetaVision/src/utils/conversions.h"
#include "../PetaVision/src/include/pv_types.h"
#include <assert.h>
#include <string.h>

namespace PV {

GeislerConn::GeislerConn()
{
   printf("GeislerConn::GeislerConn: running default constructor\n");
   initialize_base();
}

GeislerConn::GeislerConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
      HyPerLayer * post, int channel)
{
   initialize_base();
   initialize(name, hc, pre, post, channel);
}

GeislerConn::GeislerConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
      HyPerLayer * post)
{
   initialize_base();
   initialize(name, hc, pre, post, channel, NULL); // use default channel
}

// provide filename or set to NULL
GeislerConn::GeislerConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
      HyPerLayer * post, int channel, const char * filename)
{
   initialize_base();
   initialize(name, hc, pre, post, channel, filename);
}

int GeislerConn::initialize_base()
{
	numUpdates = 0;
	avePreActivity = 0.0;
	avePostActivity = 0.0;
	geislerPatches = NULL;
	return KernelConn::initialize_base();
}

PVPatch ** GeislerConn::createWeights(PVPatch ** patches, int nPatches, int nxPatch,
      int nyPatch, int nfPatch)
{
	const int arbor = 0;
	int numGeislerPatches = numDataPatches(arbor);

	geislerPatches = (PVPatch**) calloc(sizeof(PVPatch*), numGeislerPatches);
	assert(geislerPatches != NULL);

	for (int geislerIndex = 0; geislerIndex < numGeislerPatches; geislerIndex++) {
		geislerPatches[geislerIndex] = pvpatch_inplace_new(nxPatch, nyPatch, nfPatch);
		assert(geislerPatches[geislerIndex] != NULL );
	}

	return KernelConn::createWeights(patches, nPatches, nxPatch, nyPatch, nfPatch);
}

int GeislerConn::deleteWeights()
{
   const int arbor = 0;

   for (int k = 0; k < numDataPatches(arbor); k++) {
      pvpatch_inplace_delete(geislerPatches[k]);
   }
   free(geislerPatches);

   return KernelConn::deleteWeights();
}

PVPatch ** GeislerConn::initializeDefaultWeights(PVPatch ** patches, int numPatches)
{
   // patches should already be initialized to zero
   return patches;
}

int GeislerConn::updateState(float time, float dt)
{
	int axonID = 0;
	numUpdates++;
	int nPreEx = pre->clayer->numExtended;
	const pvdata_t * aPre = pre->getLayerData();
	pvdata_t avePre = 0.0;
	for (int kPre = 0; kPre < nPreEx; kPre++){
		avePre += aPre[kPre];
	}
	avePre /= nPreEx;
	avePreActivity += avePre;
	int nPost = post->clayer->numNeurons;
	const pvdata_t * aPost = post->getLayerData();

	pvdata_t avePost = 0.0;
	for (int kPost = 0; kPost < nPost; kPost++){
		avePost += aPost[kPost];
	}
	avePost /= nPost;
	avePostActivity += avePost;

	// initialize geislerPatches
	int numKernels = this->numDataPatches(axonID);
	int numWeights = nxp * nyp * nfp;
	for (int iKernel = 0; iKernel < numKernels; iKernel++){
		pvdata_t * kernelWeights = kernelPatches[iKernel]->data;
		pvdata_t * geislerWeights = geislerPatches[iKernel]->data;
		for (int iWeight = 0; iWeight < numWeights; iWeight++){
			kernelWeights[iWeight] = geislerWeights[iWeight];
			geislerWeights[iWeight] = 0.0;
		}
	}

	int status = updateWeights(axonID);

	// normalize geislerPatches
	for (int iKernel = 0; iKernel < numKernels; iKernel++){
		pvdata_t * kernelWeights = kernelPatches[iKernel]->data;
		pvdata_t * geislerWeights = geislerPatches[iKernel]->data;
		for (int iWeight = 0; iWeight < numWeights; iWeight++){
			geislerWeights[iWeight] /= nPost;
			geislerWeights[iWeight] += kernelWeights[iWeight];
#ifdef APPLY_GEISLER_WEIGHTS
			kernelWeights[iWeight] /= numUpdates;
			pvdata_t kernelNorm = (avePreActivity / numUpdates ) * (avePostActivity / numUpdates );
			kernelWeights[iWeight] -= kernelNorm;
#else
			kernelWeights[iWeight] = 0.0;
#endif
		}
	}
#ifdef APPLY_GEISLER_WEIGHTS
	this->normalizeWeights(this->kernelPatches, this->numDataPatches(axonID));
#endif
	return status;
}

int GeislerConn::updateWeights(int axonID)
{
	// this stride is in extended space for post-synaptic activity and
	// STDP decrement variable
	int postStrideY = post->clayer->numFeatures
                         * (post->clayer->loc.nx + 2 * post->clayer->loc.nPad);

	int numExtended = pre->clayer->numExtended;
	assert(numExtended == numWeightPatches(axonID));

	const pvdata_t * preLayerData = pre->getLayerData();

	int nKernels = numDataPatches(axonID);

	for (int kPre = 0; kPre < numExtended; kPre++) {
      PVAxonalArbor * arbor = axonalArbor(kPre, axonID);

      float aPre = preLayerData[kPre];
      if (aPre == 0.0) continue;

      PVPatch * wPatch = arbor->weights;
      size_t postOffset = arbor->offset;
      const pvdata_t * aPost = &post->getLayerData()[postOffset];

      int nk  = wPatch->nf * wPatch->nx; // one line in x at a time
      int ny  = wPatch->ny;
      int sy  = wPatch->sy;

      int kfPre = kPre % nKernels;
      PVPatch * gPatch = geislerPatches[kfPre];
      PVPatch * kPatch = kernelPatches[kfPre];

      pvdata_t * data_head = (pvdata_t *) ((char*) kPatch + sizeof(PVPatch));
      pvdata_t * data_begin = kPatch->data;
      size_t data_offset = data_begin - data_head;
      pvdata_t * gWeights = &gPatch->data[data_offset];

      for (int y = 0; y < ny; y++) {
         for (int k = 0; k < nk; k++) {
             gWeights[k] += aPre  * aPost[k];
         }
          // advance pointers in y
         gWeights += sy;
         // postActivity and M are extended layer
         aPost += postStrideY;
     }
   }

   return 0;
}

int GeislerConn::writeWeights(float time, bool last)
{
#ifdef APPLY_GEISLER_WEIGHTS
	// do nothing, kernels are already up to date
#else
	// copy geislerPatches to kernelPatches
	const int axonID = 0;
	const int numKernels = numDataPatches(axonID);
	const int numWeights = nxp * nyp * nfp;
	for (int iKernel = 0; iKernel < numKernels; iKernel++){
			pvdata_t * kernelWeights = kernelPatches[iKernel]->data;
			pvdata_t * geislerWeights = geislerPatches[iKernel]->data;
			for (int iWeight = 0; iWeight < numWeights; iWeight++){
				kernelWeights[iWeight] = geislerWeights[iWeight];
				kernelWeights[iWeight] /= numUpdates;
				pvdata_t kernelNorm = (avePreActivity / numUpdates ) * (avePostActivity / numUpdates );
				kernelWeights[iWeight] -= kernelNorm;
			}
		}
	this->normalizeWeights(this->kernelPatches, this->numDataPatches(axonID));
#endif
	return KernelConn::writeWeights(time, last);
}

} // namespace PV
<|endoftext|>


<commit_before>/*
 Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
*/

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        if(!s[0] && !p[0])
            return true;
        else if(!s[0])
            return p[0] == '*' && !p[1];
        else if(!p[0])
            return false;

        vector<vector<bool> > his;
        int ssize = -1;
		int pcount = 0;

        for(int i = 0; p[i]; ++i){
            his.push_back(vector<bool>(pcount, false));
            vector<bool> &res = his.back();

			int j;
            for(j = pcount; (ssize == -1 || j < ssize) && s[j]; ++j){
                bool pmatch = (!j || !i) || his[i - 1][j - 1]; //<! if his[i - 1][j - 1] matched
                bool match = false;
                if(p[i] == '*'){
                    match = pmatch || (j > 0 && his[i][j - 1]) || (i > 0 && his[i - 1][j]);
                }
				else if((p[i] == '?' || s[j] == p[i]) && (i || i == j)){
                    match = pmatch;
                }

                res.push_back(match);
            }
			ssize = j;

			pcount += p[i] != '*';
        }

        return his.back().back();
    }
};
<commit_msg>add Yu Zhu wildcard solution<commit_after>/*
 Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
*/

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        //NOTE: copy from http://yucoding.blogspot.com/2013/02/leetcode-question-123-wildcard-matching.html
        // Start typing your C/C++ solution below
        // DO NOT write int main() function

        const char* star=NULL;
        const char* ss=s;
        while (*s){
            if ((*p=='?')||(*p==*s)){s++;p++;continue;}
            if (*p=='*'){star=p++; ss=s;continue;}
            if (star){ p = star+1; s=++ss;continue;}
            return false;
        }
        while (*p=='*'){p++;}
        return !*p;
    }
};
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 pengjian.uestc @ gmail.com
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is seastar::sharded 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 Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "redis/options.hh"
#include "redis/protocol_parser.hh"
#include "redis/query_processor.hh"
#include "redis/reply.hh"
#include "redis/request.hh"
#include "redis/stats.hh"

#include "auth/authenticator.hh"
#include "auth/service.hh"
#include "cql3/values.hh"
#include "service/client_state.hh"
#include "service/storage_proxy.hh"
#include "service_permit.hh"
#include "timeout_config.hh"
#include "utils/estimated_histogram.hh"
#include "utils/fragmented_temporary_buffer.hh"

#include <seastar/core/seastar.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/sharded.hh>
#include <seastar/net/tls.hh>

#include <memory>

db::consistency_level make_consistency_level(const sstring&);

class redis_exception;

namespace redis_transport {

struct redis_server_config {
    ::timeout_config _timeout_config;
    size_t _max_request_size;
    db::consistency_level _read_consistency_level;
    db::consistency_level _write_consistency_level;
    size_t _total_redis_db_count;
};

class redis_server {
    std::vector<server_socket> _listeners;
    seastar::sharded<service::storage_proxy>& _proxy;
    seastar::sharded<redis::query_processor>& _query_processor;
    redis_server_config _config;
    size_t _max_request_size;
    semaphore _memory_available;
    redis::stats _stats;
    uint64_t _requests_blocked_memory = 0;
    auth::service& _auth_service;
    size_t _total_redis_db_count;

public:
    redis_server(seastar::sharded<service::storage_proxy>& proxy, seastar::sharded<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config);
    future<> listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> = {}, bool keepalive = false);
    future<> do_accepts(int which, bool keepalive, socket_address server_addr);
    future<> stop();

    struct result {
        result(redis::redis_message&& m) : _data(make_foreign(std::make_unique<redis::redis_message>(std::move(m)))) {}
        foreign_ptr<std::unique_ptr<redis::redis_message>> _data;
        inline lw_shared_ptr<scattered_message<char>> make_message()  {
            return _data->message();
        }
    };
    using response_type = result;

private:
    friend class connection;
    class connection : public boost::intrusive::list_base_hook<> {
        redis_server& _server;
        socket_address _server_addr;
        connected_socket _fd;
        input_stream<char> _read_buf;
        output_stream<char> _write_buf;
        redis_protocol_parser _parser;
        seastar::gate _pending_requests_gate;
        redis::redis_options _options;
        future<> _ready_to_respond = make_ready_future<>();
    private:
        enum class tracing_request_type : uint8_t {
            not_requested,
            no_write_on_close,
            write_on_close
        };

        using execution_stage_type = inheriting_concrete_execution_stage<
                future<redis_server::result>,
                redis_server::connection*,
                redis::request&&,
                redis::redis_options&,
                service_permit
        >;
        static thread_local execution_stage_type _process_request_stage;
    public:
        connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr);
        ~connection();
        future<> process();
        future<> process_request();
        void write_reply(const redis_exception&);
        void write_reply(redis_server::result result);
        future<> shutdown();
    private:
        const ::timeout_config& timeout_config() { return _server.timeout_config(); }
        friend class process_request_executor;
        future<result> process_request_one(redis::request&& request, redis::redis_options&, service_permit permit);
        future<result> process_request_internal();
    };

    bool _stopping = false;
    promise<> _all_connections_stopped;
    future<> _stopped = _all_connections_stopped.get_future();
    boost::intrusive::list<connection> _connections_list;

    void maybe_idle() {
        if (_stopping && !_stats._connections_being_accepted && !_stats._current_connections) {
            _all_connections_stopped.set_value();
        }
    }
    const ::timeout_config& timeout_config() { return _config._timeout_config; }
};
}
<commit_msg>redis: Remove unused process_request_executor friend declaration<commit_after>/*
 * Copyright (C) 2019 pengjian.uestc @ gmail.com
 */

/*
 * This file is part of Scylla.
 *
 * Scylla is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Scylla is seastar::sharded 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 Scylla.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include "redis/options.hh"
#include "redis/protocol_parser.hh"
#include "redis/query_processor.hh"
#include "redis/reply.hh"
#include "redis/request.hh"
#include "redis/stats.hh"

#include "auth/authenticator.hh"
#include "auth/service.hh"
#include "cql3/values.hh"
#include "service/client_state.hh"
#include "service/storage_proxy.hh"
#include "service_permit.hh"
#include "timeout_config.hh"
#include "utils/estimated_histogram.hh"
#include "utils/fragmented_temporary_buffer.hh"

#include <seastar/core/seastar.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/sharded.hh>
#include <seastar/net/tls.hh>

#include <memory>

db::consistency_level make_consistency_level(const sstring&);

class redis_exception;

namespace redis_transport {

struct redis_server_config {
    ::timeout_config _timeout_config;
    size_t _max_request_size;
    db::consistency_level _read_consistency_level;
    db::consistency_level _write_consistency_level;
    size_t _total_redis_db_count;
};

class redis_server {
    std::vector<server_socket> _listeners;
    seastar::sharded<service::storage_proxy>& _proxy;
    seastar::sharded<redis::query_processor>& _query_processor;
    redis_server_config _config;
    size_t _max_request_size;
    semaphore _memory_available;
    redis::stats _stats;
    uint64_t _requests_blocked_memory = 0;
    auth::service& _auth_service;
    size_t _total_redis_db_count;

public:
    redis_server(seastar::sharded<service::storage_proxy>& proxy, seastar::sharded<redis::query_processor>& qp, auth::service& auth_service, redis_server_config config);
    future<> listen(socket_address addr, std::shared_ptr<seastar::tls::credentials_builder> = {}, bool keepalive = false);
    future<> do_accepts(int which, bool keepalive, socket_address server_addr);
    future<> stop();

    struct result {
        result(redis::redis_message&& m) : _data(make_foreign(std::make_unique<redis::redis_message>(std::move(m)))) {}
        foreign_ptr<std::unique_ptr<redis::redis_message>> _data;
        inline lw_shared_ptr<scattered_message<char>> make_message()  {
            return _data->message();
        }
    };
    using response_type = result;

private:
    friend class connection;
    class connection : public boost::intrusive::list_base_hook<> {
        redis_server& _server;
        socket_address _server_addr;
        connected_socket _fd;
        input_stream<char> _read_buf;
        output_stream<char> _write_buf;
        redis_protocol_parser _parser;
        seastar::gate _pending_requests_gate;
        redis::redis_options _options;
        future<> _ready_to_respond = make_ready_future<>();
    private:
        enum class tracing_request_type : uint8_t {
            not_requested,
            no_write_on_close,
            write_on_close
        };

        using execution_stage_type = inheriting_concrete_execution_stage<
                future<redis_server::result>,
                redis_server::connection*,
                redis::request&&,
                redis::redis_options&,
                service_permit
        >;
        static thread_local execution_stage_type _process_request_stage;
    public:
        connection(redis_server& server, socket_address server_addr, connected_socket&& fd, socket_address addr);
        ~connection();
        future<> process();
        future<> process_request();
        void write_reply(const redis_exception&);
        void write_reply(redis_server::result result);
        future<> shutdown();
    private:
        const ::timeout_config& timeout_config() { return _server.timeout_config(); }
        future<result> process_request_one(redis::request&& request, redis::redis_options&, service_permit permit);
        future<result> process_request_internal();
    };

    bool _stopping = false;
    promise<> _all_connections_stopped;
    future<> _stopped = _all_connections_stopped.get_future();
    boost::intrusive::list<connection> _connections_list;

    void maybe_idle() {
        if (_stopping && !_stats._connections_being_accepted && !_stats._current_connections) {
            _all_connections_stopped.set_value();
        }
    }
    const ::timeout_config& timeout_config() { return _config._timeout_config; }
};
}
<|endoftext|>


<commit_before>#include "GeneratedTypes.h"
#include "MainRequest.h"

void app_init (MainRequestProxy* device) {
  ForwardTableReqT key = {0, 0x000cc47aa32535};
  ForwardTableRspT val = {1};
  fprintf(stderr, "insert table entry\n");
  device->forward_table_add_entry(key, val);

  TestTblReqT udp_key = {0, 0x9091};
  TestTblRspT udp_val = {1};
  device->test_tbl_add_entry(udp_key, udp_val);

//  SendFrameReqT sendFrame_key = {1};
//  SendFrameRspT sendFrame_val = {1, 0xaabbcceeddff};
//  device->send_frame_add_entry(sendFrame_key, sendFrame_val);
}
<commit_msg>benchmark clean up<commit_after>#include "GeneratedTypes.h"
#include "MainRequest.h"

void app_init (MainRequestProxy* device) {
  ForwardTableReqT key = {0, 0x003417eb96bf1c};
  ForwardTableRspT val = {1};
  fprintf(stderr, "insert table entry\n");
  device->forward_table_add_entry(key, val);

  sleep(1);

  key = {0, 0x000cc47aa32535};
  val = {1};
  fprintf(stderr, "insert table entry\n");
  device->forward_table_add_entry(key, val);

  TestTblReqT udp_key = {0, 0x4e20};
  TestTblRspT udp_val = {1};
  device->test_tbl_add_entry(udp_key, udp_val);

  sleep(1);

  udp_key = {0, 0x9091};
  udp_val = {1};
  device->test_tbl_add_entry(udp_key, udp_val);

//  SendFrameReqT sendFrame_key = {1};
//  SendFrameRspT sendFrame_val = {1, 0xaabbcceeddff};
//  device->send_frame_add_entry(sendFrame_key, sendFrame_val);
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright  2007, Casey Langen
//
// Sources and Binaries of: win32cpp
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

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

#include <win32cpp/Win32Config.hpp>          // Must be first!

#include <win32cpp/Application.hpp>
#include <win32cpp/BarLayout.hpp>
#include <win32cpp/Button.hpp>
#include <win32cpp/Color.hpp>
#include <win32cpp/Config.hpp>
#include <win32cpp/Container.hpp>
#include <win32cpp/DeviceContext.hpp>
#include <win32cpp/EditView.hpp>
#include <win32cpp/FolderBrowseDialog.hpp>
#include <win32cpp/Font.hpp>
#include <win32cpp/Frame.hpp>
#include <win32cpp/Label.hpp>
#include <win32cpp/LinearLayout.hpp>
#include <win32cpp/ListView.hpp>
#include <win32cpp/Locale.hpp>
#include <win32cpp/MemoryDC.hpp>
#include <win32cpp/Menu.hpp>
#include <win32cpp/Panel.hpp>
#include <win32cpp/RedrawLock.hpp>
#include <win32cpp/Trackbar.hpp>
#include <win32cpp/Splitter.hpp>
#include <win32cpp/TabView.hpp>
#include <win32cpp/TopLevelWindow.hpp>
#include <win32cpp/Types.hpp>
#include <win32cpp/Utility.hpp>
#include <win32cpp/Window.hpp>

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

///\brief
///namespace root
namespace win32cpp {
}

//////////////////////////////////////////////////////////////////////////////<commit_msg>Added some missing win32cpp headers.  Slightly improves build time.<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// License Agreement:
//
// The following are Copyright  2007, Casey Langen
//
// Sources and Binaries of: win32cpp
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//    * Redistributions of source code must retain the above copyright notice,
//      this list of conditions and the following disclaimer.
//
//    * Redistributions in binary form must reproduce the above copyright
//      notice, this list of conditions and the following disclaimer in the
//      documentation and/or other materials provided with the distribution.
//
//    * Neither the name of the author nor the names of other contributors may
//      be used to endorse or promote products derived from this software
//      without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////

#pragma once

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

#include <win32cpp/Win32Config.hpp>          // Must be first!

#include <win32cpp/Application.hpp>
#include <win32cpp/ApplicationThread.hpp>
#include <win32cpp/BarLayout.hpp>
#include <win32cpp/Button.hpp>
#include <win32cpp/Color.hpp>
#include <win32cpp/Config.hpp>
#include <win32cpp/Container.hpp>
#include <win32cpp/DeviceContext.hpp>
#include <win32cpp/EditView.hpp>
#include <win32cpp/Exception.hpp>
#include <win32cpp/FolderBrowseDialog.hpp>
#include <win32cpp/Font.hpp>
#include <win32cpp/Frame.hpp>
#include <win32cpp/ILayout.hpp>
#include <win32cpp/Label.hpp>
#include <win32cpp/LinearLayout.hpp>
#include <win32cpp/ListView.hpp>
#include <win32cpp/Locale.hpp>
#include <win32cpp/MemoryDC.hpp>
#include <win32cpp/Menu.hpp>
#include <win32cpp/Panel.hpp>
#include <win32cpp/ProgressBar.hpp>
#include <win32cpp/RedrawLock.hpp>
#include <win32cpp/Splitter.hpp>
#include <win32cpp/Trackbar.hpp>
#include <win32cpp/TabView.hpp>
#include <win32cpp/Timer.hpp>
#include <win32cpp/TopLevelWindow.hpp>
#include <win32cpp/Types.hpp>
#include <win32cpp/Utility.hpp>
#include <win32cpp/Window.hpp>
#include <win32cpp/WindowGeometry.hpp>

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

///\brief
///namespace root
namespace win32cpp {
}

//////////////////////////////////////////////////////////////////////////////<|endoftext|>


<commit_before><commit_msg>Fix off by one error in PCAN file loader<commit_after><|endoftext|>


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

  Program:   Monteverdi2
  Language:  C++

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

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdImageViewManipulator.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ImageViewManipulator

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
  QObject( parent )
{
  this->InitializeContext(500,500);
}

/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}

void ImageViewManipulator::InitializeContext(int width, int height)
{
  ImageRegionType::SizeType  initialSize;
  initialSize[0] = width;
  initialSize[1] = height;

  // initialize with the given size
  m_NavigationContext.bufferedRegion.SetSize(initialSize);
}

void ImageViewManipulator::mousePressEvent(  QMouseEvent * event)
{
  // Update the context with the pressed position
  m_MouseContext.x = event->x();
  m_MouseContext.y = event->y();
}

void ImageViewManipulator::mouseMoveEvent(  QMouseEvent * event)
{
  //std::cout <<" ImageViewManipulator::MouseMoveEvent" << std::endl;

  // Update the mouse context
  m_MouseContext.dx = -event->x() + m_MouseContext.x;
  m_MouseContext.dy = -event->y() + m_MouseContext.y;

  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.bufferedRegion;

  // print the region
  //std::cout << "Region Before offset : "<<   currentRegion << std::endl;

  // Apply the offset to the (start) index of the stored region
  ImageRegionType::OffsetType offset;
  offset[0] = m_MouseContext.dx;
  offset[1] = m_MouseContext.dy;

  // Apply the offset to the (start) index of the stored region
  IndexType    index = currentRegion.GetIndex() + offset;
  currentRegion.SetIndex(index);

  // print the region
  //std::cout << "Region After offset : "<< m_NavigationContext.bufferedRegion   << std::endl;
}

void ImageViewManipulator::mouseReleaseEvent(  QMouseEvent * event)
{
  std::cout <<" Not Implemented yet ..." << std::endl;
}

void ImageViewManipulator::resizeEvent ( QResizeEvent * event )
{
  //std::cout <<" ImageViewManipulator::resizeEvent" << std::endl;
  //std::cout <<"Widget Resized with new size "<< event->size().width() << ","
            << event->size().height() << std::endl;

  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.bufferedRegion;

  // print the region
  //std::cout << "Region Before offset : "<<   currentRegion << std::endl;

  // Get the new widget size
  SizeType size;
  size[0] = event->size().width();
  size[1] = event->size().height();

  // Update the stored region with the new size
  currentRegion.SetSize(size);
  //std::cout << "Region After Resize : "<<   m_NavigationContext.bufferedRegion << std::endl;

  //emit widgetResized(event->size().width(), event->size().height());
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/

/*****************************************************************************/

} // end namespace 'mvd'
<commit_msg>COMP: forgotten uncommented line<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

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

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdImageViewManipulator.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ImageViewManipulator

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
  QObject( parent )
{
  this->InitializeContext(500,500);
}

/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}

void ImageViewManipulator::InitializeContext(int width, int height)
{
  ImageRegionType::SizeType  initialSize;
  initialSize[0] = width;
  initialSize[1] = height;

  // initialize with the given size
  m_NavigationContext.bufferedRegion.SetSize(initialSize);
}

void ImageViewManipulator::mousePressEvent(  QMouseEvent * event)
{
  // Update the context with the pressed position
  m_MouseContext.x = event->x();
  m_MouseContext.y = event->y();
}

void ImageViewManipulator::mouseMoveEvent(  QMouseEvent * event)
{
  //std::cout <<" ImageViewManipulator::MouseMoveEvent" << std::endl;

  // Update the mouse context
  m_MouseContext.dx = -event->x() + m_MouseContext.x;
  m_MouseContext.dy = -event->y() + m_MouseContext.y;

  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.bufferedRegion;

  // print the region
  //std::cout << "Region Before offset : "<<   currentRegion << std::endl;

  // Apply the offset to the (start) index of the stored region
  ImageRegionType::OffsetType offset;
  offset[0] = m_MouseContext.dx;
  offset[1] = m_MouseContext.dy;

  // Apply the offset to the (start) index of the stored region
  IndexType    index = currentRegion.GetIndex() + offset;
  currentRegion.SetIndex(index);

  // print the region
  //std::cout << "Region After offset : "<< m_NavigationContext.bufferedRegion   << std::endl;
}

void ImageViewManipulator::mouseReleaseEvent(  QMouseEvent * event)
{
  std::cout <<" Not Implemented yet ..." << std::endl;
}

void ImageViewManipulator::resizeEvent ( QResizeEvent * event )
{
  //std::cout <<" ImageViewManipulator::resizeEvent" << std::endl;
  //std::cout <<"Widget Resized with new size "<< event->size().width() << ","
  //<< event->size().height() << std::endl;

  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.bufferedRegion;

  // print the region
  //std::cout << "Region Before offset : "<<   currentRegion << std::endl;

  // Get the new widget size
  SizeType size;
  size[0] = event->size().width();
  size[1] = event->size().height();

  // Update the stored region with the new size
  currentRegion.SetSize(size);
  //std::cout << "Region After Resize : "<<   m_NavigationContext.bufferedRegion << std::endl;

  //emit widgetResized(event->size().width(), event->size().height());
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/

/*****************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


<commit_before>#include "test_convertertopdf.hpp"

#include <QTest>
#include <QMap>
#include <QSqlDatabase>
#include <QSqlError>
#include <QFile>
#include <QDebug>

#include <qtreports/engine.hpp>
#include <qtreports/../../src/converters/convertertopdf.hpp>

Test_ConverterToPDF::Test_ConverterToPDF( QObject * parent ) :
    QObject( parent )
{}

Test_ConverterToPDF::~Test_ConverterToPDF() {}

void    Test_ConverterToPDF::convert()
{
    QString reportPath = QFINDTESTDATA( "../samples/reports/tests-images/test.full.qrxml" );

    qtreports::Engine engine;

    QString dbPath = QFINDTESTDATA( "../samples/databases/tests-images.db" );

    auto report = engine.getReport();
    auto outPath = "test.pdf";
    qtreports::detail::ConverterToPDF converter( report );

    QCOMPARE(converter.convert(outPath), false);

    QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );

    QMap < QString, QVariant > map;
    map[ "title" ] = "Best Title in World";

    QVERIFY2( engine.setParameters( map ), engine.getLastError().toStdString().c_str() );

    QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
    auto db = QSqlDatabase::addDatabase( "QSQLITE" );
    db.setDatabaseName( dbPath );
    QVERIFY2( db.open(), db.lastError().text().toStdString().c_str() );
    QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
    report = engine.getReport();

    converter = qtreports::detail::ConverterToPDF( report );
    QVERIFY2( converter.convert( outPath ), converter.getLastError().toStdString().c_str() );
    QCOMPARE( converter.getDPI(), 75 );
    QCOMPARE( converter.getLastError(), QString() );

    QCOMPARE( QFile::exists( outPath ), true );
    QFile file( outPath );
    QVERIFY2( file.open( QIODevice::OpenModeFlag::ReadOnly ), file.errorString().toStdString().c_str() );
    QVERIFY( file.size() != 0 );
    file.close();
    QCOMPARE( QFile::remove( outPath ), true );
}

void    Test_ConverterToPDF::setDPI()
{
    auto report = qtreports::detail::ReportPtr();
    qtreports::detail::ConverterToPDF converter( report );

    converter.setDPI( 500 );
    QCOMPARE( converter.getDPI(), 500 );
}

void    Test_ConverterToPDF::getDPI()
{
    auto report = qtreports::detail::ReportPtr();
    qtreports::detail::ConverterToPDF converter( report );

    QCOMPARE( converter.getDPI(), 75 );
}

void    Test_ConverterToPDF::getLastError()
{
    auto report = qtreports::detail::ReportPtr();
    qtreports::detail::ConverterToPDF converter( report );

    QCOMPARE( converter.getLastError(), QString() );
}
<commit_msg>Update test_convertertopdf.cpp<commit_after>#include "test_convertertopdf.hpp"

#include <QTest>
#include <QMap>
#include <QSqlDatabase>
#include <QSqlError>
#include <QFile>
#include <QDebug>

#include <qtreports/engine.hpp>
#include <qtreports/../../src/converters/convertertopdf.hpp>

Test_ConverterToPDF::Test_ConverterToPDF( QObject * parent ) :
    QObject( parent )
{}

Test_ConverterToPDF::~Test_ConverterToPDF() {}

void    Test_ConverterToPDF::convert()
{
    QString reportPath = QFINDTESTDATA( "../samples/reports/tests-images/test.withoutstyle.qrxml" );

    qtreports::Engine engine;

    QString dbPath = QFINDTESTDATA( "../samples/databases/tests-images.db" );

    auto report = engine.getReport();
    auto outPath = "test.pdf";
    qtreports::detail::ConverterToPDF converter( report );

    QCOMPARE(converter.convert(outPath), false);

    QVERIFY2( engine.open( reportPath ), engine.getLastError().toStdString().c_str() );

    QMap < QString, QVariant > map;
    map[ "title" ] = "Best Title in World";

    QVERIFY2( engine.setParameters( map ), engine.getLastError().toStdString().c_str() );

    QSqlDatabase::removeDatabase( QSqlDatabase::defaultConnection );
    auto db = QSqlDatabase::addDatabase( "QSQLITE" );
    db.setDatabaseName( dbPath );
    QVERIFY2( db.open(), db.lastError().text().toStdString().c_str() );
    QVERIFY2( engine.setConnection( db ), engine.getLastError().toStdString().c_str() );
    report = engine.getReport();

    converter = qtreports::detail::ConverterToPDF( report );
    QVERIFY2( converter.convert( outPath ), converter.getLastError().toStdString().c_str() );
    QCOMPARE( converter.getDPI(), 75 );
    QCOMPARE( converter.getLastError(), QString() );

    QCOMPARE( QFile::exists( outPath ), true );
    QFile file( outPath );
    QVERIFY2( file.open( QIODevice::OpenModeFlag::ReadOnly ), file.errorString().toStdString().c_str() );
    QVERIFY( file.size() != 0 );
    file.close();
    QCOMPARE( QFile::remove( outPath ), true );
}

void    Test_ConverterToPDF::setDPI()
{
    auto report = qtreports::detail::ReportPtr();
    qtreports::detail::ConverterToPDF converter( report );

    converter.setDPI( 500 );
    QCOMPARE( converter.getDPI(), 500 );
}

void    Test_ConverterToPDF::getDPI()
{
    auto report = qtreports::detail::ReportPtr();
    qtreports::detail::ConverterToPDF converter( report );

    QCOMPARE( converter.getDPI(), 75 );
}

void    Test_ConverterToPDF::getLastError()
{
    auto report = qtreports::detail::ReportPtr();
    qtreports::detail::ConverterToPDF converter( report );

    QCOMPARE( converter.getLastError(), QString() );
}
<|endoftext|>


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

  Library:   CTK

  Copyright (c) Kitware Inc.

  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.commontk.org/LICENSE

  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.

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

// Qt includes
#include <QColorDialog>
#include <QDebug>
#include <QIcon>
#include <QPainter>
#include <QPixmap>
#include <QStyle>
#include <QStyleOptionButton>
#include <QStylePainter>

// CTK includes
#include "ctkColorDialog.h"
#include "ctkColorPickerButton.h"

class ctkColorPickerButtonPrivate
{
  Q_DECLARE_PUBLIC(ctkColorPickerButton);
protected:
  ctkColorPickerButton* const q_ptr;
public:
  ctkColorPickerButtonPrivate(ctkColorPickerButton& object);
  void init();
  void computeIcon();

  QIcon  Icon;
  QColor Color;
  bool   DisplayColorName;
  ctkColorPickerButton::ColorDialogOptions DialogOptions;
};

//-----------------------------------------------------------------------------
ctkColorPickerButtonPrivate::ctkColorPickerButtonPrivate(ctkColorPickerButton& object)
  : q_ptr(&object)
{
  this->Color = Qt::black;
  this->DisplayColorName = true;
  this->DialogOptions = 0;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::init()
{
  Q_Q(ctkColorPickerButton);
  q->setCheckable(true);
  QObject::connect(q, SIGNAL(toggled(bool)),
                   q, SLOT(onToggled(bool)));
  this->computeIcon();
}

//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::computeIcon()
{
  Q_Q(ctkColorPickerButton);
  int _iconSize = q->style()->pixelMetric(QStyle::PM_SmallIconSize);
  QPixmap pix(_iconSize, _iconSize);
  pix.fill(q->palette().button().color());
  QPainter p(&pix);
  p.setPen(QPen(Qt::gray));
  p.setBrush(this->Color);
  p.drawRect(2, 2, pix.width() - 5, pix.height() - 5);

  this->Icon = QIcon(pix);
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(QWidget* _parent)
  : QPushButton(_parent)
  , d_ptr(new ctkColorPickerButtonPrivate(*this))
{
  Q_D(ctkColorPickerButton);
  d->init();
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QString& _text, QWidget* _parent)
  : QPushButton(_text, _parent)
  , d_ptr(new ctkColorPickerButtonPrivate(*this))
{
  Q_D(ctkColorPickerButton);
  d->init();
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QColor& _color,
                                           const QString& _text,
                                           QWidget* _parent)
  : QPushButton(_text, _parent)
  , d_ptr(new ctkColorPickerButtonPrivate(*this))
{
  Q_D(ctkColorPickerButton);
  d->init();
  this->setColor(_color);
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::~ctkColorPickerButton()
{
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::changeColor()
{
  Q_D(ctkColorPickerButton);
  QColor res;
    QColorDialog::ColorDialogOptions options;
    options |= QColorDialog::ColorDialogOption(
      static_cast<int>(d->DialogOptions & ShowAlphaChannel));
    options |= QColorDialog::ColorDialogOption(
      static_cast<int>(d->DialogOptions & NoButtons));
    options |= QColorDialog::ColorDialogOption(
      static_cast<int>(d->DialogOptions & DontUseNativeDialog));
  if (d->DialogOptions & UseCTKColorDialog)
    {
    res = ctkColorDialog::getColor(d->Color, this, QString(""),options);
    }
  else
    {
    res = QColorDialog::getColor(d->Color, this, QString(""), options);
    }
  if (res.isValid())
    {
    this->setColor(res);
    }
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::onToggled(bool change)
{
  if (change)
    {
    this->changeColor();
    this->setChecked(false);
    }
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDisplayColorName(bool displayColorName)
{
  Q_D(ctkColorPickerButton);
  d->DisplayColorName = displayColorName;
  this->update();
}

//-----------------------------------------------------------------------------
bool ctkColorPickerButton::displayColorName()const
{
  Q_D(const ctkColorPickerButton);
  return d->DisplayColorName;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDialogOptions(ColorDialogOptions options)
{
  Q_D(ctkColorPickerButton);
  d->DialogOptions = options;
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ColorDialogOptions ctkColorPickerButton::dialogOptions()const
{
  Q_D(const ctkColorPickerButton);
  return d->DialogOptions;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::setColor(const QColor& newColor)
{
  Q_D(ctkColorPickerButton);
  if (newColor == d->Color)
    {
    return;
    }

  d->Color = newColor;
  d->computeIcon();

  this->update();
  emit colorChanged(d->Color);
}

//-----------------------------------------------------------------------------
QColor ctkColorPickerButton::color()const
{
  Q_D(const ctkColorPickerButton);
  return d->Color;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::paintEvent(QPaintEvent *)
{
  Q_D(ctkColorPickerButton);
  QStylePainter p(this);
  QStyleOptionButton option;
  initStyleOption(&option);
  if (d->DisplayColorName)
    {
    option.text = d->Color.name();
    }
  option.icon = d->Icon;
  p.drawControl(QStyle::CE_PushButton, option);
}
<commit_msg>Register ColorDialogOptions property as metatype<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) Kitware Inc.

  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.commontk.org/LICENSE

  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.

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

// Qt includes
#include <QColorDialog>
#include <QDebug>
#include <QIcon>
#include <QPainter>
#include <QPixmap>
#include <QStyle>
#include <QStyleOptionButton>
#include <QStylePainter>

// CTK includes
#include "ctkColorDialog.h"
#include "ctkColorPickerButton.h"

class ctkColorPickerButtonPrivate
{
  Q_DECLARE_PUBLIC(ctkColorPickerButton);
protected:
  ctkColorPickerButton* const q_ptr;
public:
  ctkColorPickerButtonPrivate(ctkColorPickerButton& object);
  void init();
  void computeIcon();

  QIcon  Icon;
  QColor Color;
  bool   DisplayColorName;
  ctkColorPickerButton::ColorDialogOptions DialogOptions;
};

//-----------------------------------------------------------------------------
ctkColorPickerButtonPrivate::ctkColorPickerButtonPrivate(ctkColorPickerButton& object)
  : q_ptr(&object)
{
  qRegisterMetaType<ctkColorPickerButton::ColorDialogOptions>("ctkColorPickerButton::ColorDialogOptions");
  this->Color = Qt::black;
  this->DisplayColorName = true;
  this->DialogOptions = 0;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::init()
{
  Q_Q(ctkColorPickerButton);
  q->setCheckable(true);
  QObject::connect(q, SIGNAL(toggled(bool)),
                   q, SLOT(onToggled(bool)));
  this->computeIcon();
}

//-----------------------------------------------------------------------------
void ctkColorPickerButtonPrivate::computeIcon()
{
  Q_Q(ctkColorPickerButton);
  int _iconSize = q->style()->pixelMetric(QStyle::PM_SmallIconSize);
  QPixmap pix(_iconSize, _iconSize);
  pix.fill(q->palette().button().color());
  QPainter p(&pix);
  p.setPen(QPen(Qt::gray));
  p.setBrush(this->Color);
  p.drawRect(2, 2, pix.width() - 5, pix.height() - 5);

  this->Icon = QIcon(pix);
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(QWidget* _parent)
  : QPushButton(_parent)
  , d_ptr(new ctkColorPickerButtonPrivate(*this))
{
  Q_D(ctkColorPickerButton);
  d->init();
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QString& _text, QWidget* _parent)
  : QPushButton(_text, _parent)
  , d_ptr(new ctkColorPickerButtonPrivate(*this))
{
  Q_D(ctkColorPickerButton);
  d->init();
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ctkColorPickerButton(const QColor& _color,
                                           const QString& _text,
                                           QWidget* _parent)
  : QPushButton(_text, _parent)
  , d_ptr(new ctkColorPickerButtonPrivate(*this))
{
  Q_D(ctkColorPickerButton);
  d->init();
  this->setColor(_color);
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::~ctkColorPickerButton()
{
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::changeColor()
{
  Q_D(ctkColorPickerButton);
  QColor res;
    QColorDialog::ColorDialogOptions options;
    options |= QColorDialog::ColorDialogOption(
      static_cast<int>(d->DialogOptions & ShowAlphaChannel));
    options |= QColorDialog::ColorDialogOption(
      static_cast<int>(d->DialogOptions & NoButtons));
    options |= QColorDialog::ColorDialogOption(
      static_cast<int>(d->DialogOptions & DontUseNativeDialog));
  if (d->DialogOptions & UseCTKColorDialog)
    {
    res = ctkColorDialog::getColor(d->Color, this, QString(""),options);
    }
  else
    {
    res = QColorDialog::getColor(d->Color, this, QString(""), options);
    }
  if (res.isValid())
    {
    this->setColor(res);
    }
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::onToggled(bool change)
{
  if (change)
    {
    this->changeColor();
    this->setChecked(false);
    }
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDisplayColorName(bool displayColorName)
{
  Q_D(ctkColorPickerButton);
  d->DisplayColorName = displayColorName;
  this->update();
}

//-----------------------------------------------------------------------------
bool ctkColorPickerButton::displayColorName()const
{
  Q_D(const ctkColorPickerButton);
  return d->DisplayColorName;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::setDialogOptions(ColorDialogOptions options)
{
  Q_D(ctkColorPickerButton);
  d->DialogOptions = options;
}

//-----------------------------------------------------------------------------
ctkColorPickerButton::ColorDialogOptions ctkColorPickerButton::dialogOptions()const
{
  Q_D(const ctkColorPickerButton);
  return d->DialogOptions;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::setColor(const QColor& newColor)
{
  Q_D(ctkColorPickerButton);
  if (newColor == d->Color)
    {
    return;
    }

  d->Color = newColor;
  d->computeIcon();

  this->update();
  emit colorChanged(d->Color);
}

//-----------------------------------------------------------------------------
QColor ctkColorPickerButton::color()const
{
  Q_D(const ctkColorPickerButton);
  return d->Color;
}

//-----------------------------------------------------------------------------
void ctkColorPickerButton::paintEvent(QPaintEvent *)
{
  Q_D(ctkColorPickerButton);
  QStylePainter p(this);
  QStyleOptionButton option;
  initStyleOption(&option);
  if (d->DisplayColorName)
    {
    option.text = d->Color.name();
    }
  option.icon = d->Icon;
  p.drawControl(QStyle::CE_PushButton, option);
}
<|endoftext|>


<commit_before>/**
@file CharBuf.hpp
@brief Character buffer.

@author Tim Howard
@copyright 2010-2012 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef DUCT_CHARBUF_HPP_
#define DUCT_CHARBUF_HPP_

#include "./config.hpp"
#include "./stl.hpp"
#include "./char.hpp"
#include "./CharacterSet.hpp"
#include "./EncodingUtils.hpp"
#include "./StringUtils.hpp"

#include <cstdlib>
#include <type_traits>

namespace duct {

/**
	@addtogroup string
	@{
*/

// Forward declarations
class CharBuf;

/**
	Character buffer.
*/
class CharBuf /*final*/ {
public:
/** @name Types */ /// @{
	/** Internal character type. */
	typedef char32 char_type;
/// @}

private:
	duct::stl::vector<char_type>::type m_buffer;
	bool m_cached;
	u8string m_cache_string;

	DUCT_DISALLOW_COPY_AND_ASSIGN(CharBuf);

public:
/** @name Constructors */ /// @{
	/**
		Construct empty.
	*/
	CharBuf()
		: m_buffer()
		, m_cached(false)
		, m_cache_string()
	{}
	/**
		Construct with capacity.
		@param capacity Capacity of buffer.
	*/
	explicit CharBuf(std::size_t const capacity)
		: m_buffer()
		, m_cached(false)
		, m_cache_string()
	{
		m_buffer.reserve(capacity);
	}
/// @}

/** @name Properties */ /// @{
	/**
		Get size.
		@returns The number of characters in the buffer.
		@sa get_capacity().
	*/
	inline std::size_t get_size() const { return m_buffer.size(); }
	/**
		Get capacity.
		@returns The reserved size of the buffer.
		@sa get_size().
	*/
	inline std::size_t get_capacity() const { return m_buffer.capacity(); }
/// @}

/** @name Operations and comparison */ /// @{
	/**
		Reset.
	*/
	void reset() {
		m_cached=false;
		m_buffer.clear();
	}

	/**
		Cache buffer as string.
		@returns Reference to cached string.
	*/
	u8string const& cache() {
		if (!m_cached) {
			StringUtils::convert<UTF32Utils>(m_cache_string, m_buffer.cbegin(), m_buffer.cend());
			m_cached=true;
		}
		return m_cache_string;
	}

	/**
		Append code point to the end of the buffer.
		@warning Invalid code points are ignored.
		@warning An exception may be thrown by internal resizing.
		@note The cached string will be invalidated by this operation.
		@param cp Code point to insert.
	*/
	void push_back(char_type const cp) {
		if (DUCT_UNI_IS_CP_VALID(cp)) {
			grow();
			m_buffer.push_back(cp);
			m_cached=false;
		}
	}

	/**
		Compare all characters in the buffer to a character.
		@returns @c true if all characters match the character; @c false otherwise.
		@tparam charT Character type; inferred from @a c.
		@param c Character to compare against.
	*/
	template<typename charT>
	bool compare(charT const c) const {
		for (unsigned int i=0; get_size()>i; ++i) {
			if (m_buffer[i]!=c) {
				return false;
			}
		}
		return true;
	}
	/**
		Compare buffer to a character set.
		@returns @c true if all characters match a character from @a char_set; @c false otherwise.
		@param char_set Ccharacter set to compare against.
	*/
	bool compare(CharacterSet const& char_set) const {
		for (unsigned int i=0; get_size()>i; ++i) {
			if (!char_set.contains(m_buffer[i])) {
				return false;
			}
		}
		return true;
	}
/// @}

/** @name Output */ /// @{
	/**
		Convert buffer to a string.
		@returns Cache string converted to @a stringT.
		@tparam stringT String type to convert to. Encoding is inferred from the type's character size.
	*/
	template<class stringT>
	stringT to_string() {
		stringT str;
		StringUtils::convert<UTF32Utils>(str, m_buffer.cbegin(), m_buffer.cend(), true);
		return str;
	}
	/**
		Convert buffer to a @c u8string.
		@returns Cache string.
	*/
	u8string to_string() {
		return cache();
	}
	/**
		Convert buffer to a string (by-ref).
		@param[out] str Output string.
		@param append Whether to append to @a str; defaults to @c false (@a str is cleared on entry).
	*/
	template<class stringT>
	void to_string(stringT& str, bool append=false) {
		StringUtils::convert<UTF32Utils>(str, m_buffer.cbegin(), m_buffer.cend(), append);
	}

	/**
		Convert the buffer to an arithmetic type.
		@returns The buffer converted to arithmetic type @a T.
		@tparam T An arithmetic type.
		@sa to_arithmetic(T&)
	*/
	template<typename T>
	T to_arithmetic() {
		static_assert(std::is_arithmetic<T>::value, "T must be arithmetic");
		T val;
		to_arithmetic(val);
		return val;
	}
	/**
		Convert the buffer to a 32-bit integer with error return.
		@note @a value is guaranteed to be equal to @c T() if extraction failed.
		@returns @c true if the buffer was convertible to @a T (@a value is set); @c false otherwise (@a value equals @c T(0)).
		@tparam T An arithmetic type; inferred from @a value.
		@param[out] value Output value.
	*/
	template<typename T>
	bool to_arithmetic(T& value) {
		static_assert(std::is_arithmetic<T>::value, "T must be arithmetic");
		cache();
		duct::stl::istringstream stream(m_cache_string);
		stream>>value;
		if (stream.fail()) {
			value=T();
			return false;
		} else {
			return true;
		}
	}
/// @}

private:
	void grow() {
		if (0==get_capacity()) {
			m_buffer.reserve(64u);
		} else if (get_size()+1>=get_capacity()) {
			m_buffer.reserve(2*get_capacity());
		}
	}
};

/** @} */ // end of doc-group string

} // namespace duct

#endif // DUCT_CHARBUF_HPP_
<commit_msg>CharBuf: saner capacity growing; doc correction.<commit_after>/**
@file CharBuf.hpp
@brief Character buffer.

@author Tim Howard
@copyright 2010-2012 Tim Howard under the MIT license; see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef DUCT_CHARBUF_HPP_
#define DUCT_CHARBUF_HPP_

#include "./config.hpp"
#include "./stl.hpp"
#include "./char.hpp"
#include "./CharacterSet.hpp"
#include "./EncodingUtils.hpp"
#include "./StringUtils.hpp"

#include <cstdlib>
#include <type_traits>

namespace duct {

/**
	@addtogroup string
	@{
*/

// Forward declarations
class CharBuf;

/**
	Character buffer.
*/
class CharBuf /*final*/ {
public:
/** @name Types */ /// @{
	/** Internal character type. */
	typedef char32 char_type;
/// @}

private:
	duct::stl::vector<char_type>::type m_buffer;
	bool m_cached;
	u8string m_cache_string;

	DUCT_DISALLOW_COPY_AND_ASSIGN(CharBuf);

public:
/** @name Constructors */ /// @{
	/**
		Construct empty.
	*/
	CharBuf()
		: m_buffer()
		, m_cached(false)
		, m_cache_string()
	{}
	/**
		Construct with capacity.
		@param capacity Capacity of buffer.
	*/
	explicit CharBuf(std::size_t const capacity)
		: m_buffer()
		, m_cached(false)
		, m_cache_string()
	{
		m_buffer.reserve(capacity);
	}
/// @}

/** @name Properties */ /// @{
	/**
		Get size.
		@returns The number of characters in the buffer.
		@sa get_capacity().
	*/
	inline std::size_t get_size() const { return m_buffer.size(); }
	/**
		Get capacity.
		@returns The reserved size of the buffer.
		@sa get_size().
	*/
	inline std::size_t get_capacity() const { return m_buffer.capacity(); }
/// @}

/** @name Operations and comparison */ /// @{
	/**
		Reset.
	*/
	void reset() {
		m_cached=false;
		m_buffer.clear();
	}

	/**
		Cache buffer as string.
		@returns Reference to cached string.
	*/
	u8string const& cache() {
		if (!m_cached) {
			StringUtils::convert<UTF32Utils>(m_cache_string, m_buffer.cbegin(), m_buffer.cend());
			m_cached=true;
		}
		return m_cache_string;
	}

	/**
		Append code point to the end of the buffer.
		@warning Invalid code points are ignored.
		@warning An exception may be thrown by internal resizing.
		@note The cached string will be invalidated by this operation.
		@param cp Code point to insert.
	*/
	void push_back(char_type const cp) {
		if (DUCT_UNI_IS_CP_VALID(cp)) {
			grow();
			m_buffer.push_back(cp);
			m_cached=false;
		}
	}

	/**
		Compare all characters in the buffer to a character.
		@returns @c true if all characters match the character; @c false otherwise.
		@tparam charT Character type; inferred from @a c.
		@param c Character to compare against.
	*/
	template<typename charT>
	bool compare(charT const c) const {
		for (unsigned int i=0; get_size()>i; ++i) {
			if (m_buffer[i]!=c) {
				return false;
			}
		}
		return true;
	}
	/**
		Compare buffer to a character set.
		@returns @c true if all characters match a character from @a char_set; @c false otherwise.
		@param char_set Character set to compare against.
	*/
	bool compare(CharacterSet const& char_set) const {
		for (unsigned int i=0; get_size()>i; ++i) {
			if (!char_set.contains(m_buffer[i])) {
				return false;
			}
		}
		return true;
	}
/// @}

/** @name Output */ /// @{
	/**
		Convert buffer to a string.
		@returns Cache string converted to @a stringT.
		@tparam stringT String type to convert to. Encoding is inferred from the type's character size.
	*/
	template<class stringT>
	stringT to_string() {
		stringT str;
		StringUtils::convert<UTF32Utils>(str, m_buffer.cbegin(), m_buffer.cend(), true);
		return str;
	}
	/**
		Convert buffer to a @c u8string.
		@returns Cache string.
	*/
	u8string to_string() {
		return cache();
	}
	/**
		Convert buffer to a string (by-ref).
		@param[out] str Output string.
		@param append Whether to append to @a str; defaults to @c false (@a str is cleared on entry).
	*/
	template<class stringT>
	void to_string(stringT& str, bool append=false) {
		StringUtils::convert<UTF32Utils>(str, m_buffer.cbegin(), m_buffer.cend(), append);
	}

	/**
		Convert the buffer to an arithmetic type.
		@returns The buffer converted to arithmetic type @a T.
		@tparam T An arithmetic type.
		@sa to_arithmetic(T&)
	*/
	template<typename T>
	T to_arithmetic() {
		static_assert(std::is_arithmetic<T>::value, "T must be arithmetic");
		T val;
		to_arithmetic(val);
		return val;
	}
	/**
		Convert the buffer to a 32-bit integer with error return.
		@note @a value is guaranteed to be equal to @c T() if extraction failed.
		@returns @c true if the buffer was convertible to @a T (@a value is set); @c false otherwise (@a value equals @c T(0)).
		@tparam T An arithmetic type; inferred from @a value.
		@param[out] value Output value.
	*/
	template<typename T>
	bool to_arithmetic(T& value) {
		static_assert(std::is_arithmetic<T>::value, "T must be arithmetic");
		cache();
		duct::stl::istringstream stream(m_cache_string);
		stream>>value;
		if (stream.fail()) {
			value=T();
			return false;
		} else {
			return true;
		}
	}
/// @}

private:
	void grow() {
		if (0==get_capacity()) {
			m_buffer.reserve(64u);
		} else if (get_size()+1>=get_capacity()) {
			m_buffer.reserve((16>=get_capacity()) ? 64 : 2*get_capacity());
		}
	}
};

/** @} */ // end of doc-group string

} // namespace duct

#endif // DUCT_CHARBUF_HPP_
<|endoftext|>