<commit_before>/*
    This file is part of KAddressbook.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "kde2_xxport.h"

#include <QtCore/QFile>

#include <kdebug.h>
#include <kfiledialog.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kprocess.h>
#include <kstandarddirs.h>
#include <ktemporaryfile.h>
#include <kurl.h>

#include "xxportmanager.h"

K_EXPORT_KADDRESSBOOK_XXFILTER( kaddrbk_kde2_xxport, KDE2XXPort )

KDE2XXPort::KDE2XXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )
  : KAB::XXPort( ab, parent, name )
{
  createImportAction( i18n( "Import KDE 2 Addressbook..." ) );
}

KABC::Addressee::List KDE2XXPort::importContacts( const QString& ) const
{
  QString fileName = KStandardDirs::locateLocal( "data", "kabc/std.vcf" );
  if ( !QFile::exists( fileName ) ) {
    KMessageBox::sorry( parentWidget(), i18n( "<qt>Could not find a KDE 2 address book %1.</qt>", fileName ) );
    return KABC::AddresseeList();
  }

  int result = KMessageBox::questionYesNoCancel( parentWidget(),
      i18n( "Override previously imported entries?" ),
      i18n( "Import KDE 2 Addressbook" ), KGuiItem(i18n("Import")), KGuiItem(i18n("Do Not Import")) );

  if ( !result ) return KABC::AddresseeList();

  KProcess proc;

  if ( result == KMessageBox::Yes ) {
    proc << "kab2kabc";
    proc << "--override";
  } else if ( result == KMessageBox::No )
    proc << "kab2kabc";
  else
    kDebug(5720) <<"KAddressBook::importKDE2(): Unknow return value.";

  proc.execute();

  addressBook()->load();

  return KABC::AddresseeList();
}

#include "kde2_xxport.moc"
<commit_msg>Backport: don't exec proc if we canceled it<commit_after>/*
    This file is part of KAddressbook.
    Copyright (c) 2003 Tobias Koenig <tokoe@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "kde2_xxport.h"

#include <QtCore/QFile>

#include <kdebug.h>
#include <kfiledialog.h>
#include <kio/netaccess.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kprocess.h>
#include <kstandarddirs.h>
#include <ktemporaryfile.h>
#include <kurl.h>

#include "xxportmanager.h"

K_EXPORT_KADDRESSBOOK_XXFILTER( kaddrbk_kde2_xxport, KDE2XXPort )

KDE2XXPort::KDE2XXPort( KABC::AddressBook *ab, QWidget *parent, const char *name )
  : KAB::XXPort( ab, parent, name )
{
  createImportAction( i18n( "Import KDE 2 Addressbook..." ) );
}

KABC::Addressee::List KDE2XXPort::importContacts( const QString& ) const
{
  QString fileName = KStandardDirs::locateLocal( "data", "kabc/std.vcf" );
  if ( !QFile::exists( fileName ) ) {
    KMessageBox::sorry( parentWidget(), i18n( "<qt>Could not find a KDE 2 address book %1.</qt>", fileName ) );
    return KABC::AddresseeList();
  }

  int result = KMessageBox::questionYesNoCancel( parentWidget(),
      i18n( "Override previously imported entries?" ),
      i18n( "Import KDE 2 Addressbook" ), KGuiItem(i18n("Import")), KGuiItem(i18n("Do Not Import")) );

  if ( !result ) return KABC::AddresseeList();

  KProcess proc;

  if ( result == KMessageBox::Yes ) {
    proc << "kab2kabc";
    proc << "--override";
  } else if ( result == KMessageBox::No )
    proc << "kab2kabc";
  else {
    kDebug(5720) <<"KAddressBook::importKDE2(): Unknow return value.";
    return KABC::AddresseeList();
  }
  proc.execute();

  addressBook()->load();

  return KABC::AddresseeList();
}

#include "kde2_xxport.moc"
<|endoftext|>


<commit_before><commit_msg>Add missing include<commit_after><|endoftext|>


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

#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <QVariant>
#include <sstream>
#include "com/centreon/broker/database.hh"
#include "com/centreon/broker/database_query.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/misc/shared_ptr.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/storage/metric.hh"
#include "com/centreon/broker/storage/rebuild.hh"
#include "com/centreon/broker/storage/status.hh"
#include "com/centreon/broker/storage/rebuilder.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::storage;

// Local types.
struct index_info {
  unsigned int index_id;
  unsigned int host_id;
  unsigned int service_id;
  unsigned int rrd_retention;
};

struct metric_info {
  unsigned int metric_id;
  QString metric_name;
  short metric_type;
};

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] db_cfg                  Database configuration.
 *  @param[in] rebuild_check_interval  How often the rebuild thread will
 *                                     check for rebuild.
 *  @param[in] rrd_length              Length of RRD files.
 */
rebuilder::rebuilder(
             database_config const& db_cfg,
             unsigned int rebuild_check_interval,
             unsigned int rrd_length)
  : _db_cfg(db_cfg),
    _interval(rebuild_check_interval),
    _rrd_len(rrd_length),
    _should_exit(false) {}

/**
 *  Destructor.
 */
rebuilder::~rebuilder() throw () {}

/**
 *  Set the exit flag.
 */
void rebuilder::exit() throw () {
  _should_exit = true;
  return ;
}

/**
 *  Get the rebuild check interval.
 *
 *  @return Rebuild check interval in seconds.
 */
unsigned int rebuilder::get_interval() const throw () {
  return (_interval);
}

/**
 *  Get the RRD length in seconds.
 *
 *  @return RRD length in seconds.
 */
unsigned int rebuilder::get_rrd_length() const throw () {
  return (_rrd_len);
}

/**
 *  Thread entry point.
 */
void rebuilder::run() {
  while (!_should_exit && _interval) {
    try {
      // Open DB.
      std::auto_ptr<database> db;
      try {
        db.reset(new database(_db_cfg));
      }
      catch (std::exception const& e) {
        throw (broker::exceptions::msg() << "storage: rebuilder: could "
               "not connect to Centreon Storage database: "
               << e.what());
      }

      // Database schema version.
      bool db_v2(db->schema_version() == database::v2);

      // Fetch index to rebuild.
      std::list<index_info> index_to_rebuild;
      {
        std::ostringstream query;
        query << "SELECT " << (db_v2 ? "id" : "index_id")
              << "       , host_id, service_id, rrd_retention"
                 "  FROM " << (db_v2 ? "index_data" : "rt_index_data")
              << "  WHERE must_be_rebuild=1";
        database_query index_to_rebuild_query(*db);
        index_to_rebuild_query.run_query(
          query.str(),
          "storage: rebuilder: could not fetch index to rebuild");
        while (!_should_exit && index_to_rebuild_query.next()) {
          index_info info;
          info.index_id = index_to_rebuild_query.value(0).toUInt();
          info.host_id = index_to_rebuild_query.value(1).toUInt();
          info.service_id = index_to_rebuild_query.value(2).toUInt();
          info.rrd_retention
            = (index_to_rebuild_query.value(3).isNull()
               ? 0
               : index_to_rebuild_query.value(3).toUInt());
          if (!info.rrd_retention)
            info.rrd_retention = _rrd_len;
          index_to_rebuild.push_back(info);
        }
      }

      // Browse list of index to rebuild.
      while (!_should_exit && !index_to_rebuild.empty()) {
        // Get check interval of host/service.
        unsigned int index_id;
        unsigned int check_interval(0);
        unsigned int rrd_len;
        {
          index_info info(index_to_rebuild.front());
          index_id = info.index_id;
          rrd_len = info.rrd_retention;
          index_to_rebuild.pop_front();

          std::ostringstream oss;
          if (!info.service_id)
            oss << "SELECT check_interval"
                << " FROM " << (db_v2 ? "hosts" : "rt_hosts")
                << " WHERE host_id=" << info.host_id;
          else
            oss << "SELECT check_interval"
                << " FROM " << (db_v2 ? "services" : "rt_services")
                << " WHERE host_id=" << info.host_id
                << "  AND service_id=" << info.service_id;
          database_query query(*db);
          query.run_query(oss.str());
          if (query.next())
            check_interval = query.value(0).toUInt();
          if (!check_interval)
            check_interval = 5;
        }
        logging::info(logging::medium) << "storage: rebuilder: index "
          << index_id << " (interval " << check_interval
          << ") will be rebuild";

        // Set index as being rebuilt.
        _set_index_rebuild(*db, index_id, 2);

        try {
          // Fetch metrics to rebuild.
          std::list<metric_info> metrics_to_rebuild;
          {
            std::ostringstream oss;
            oss << "SELECT metric_id, metric_name, data_source_type"
                << " FROM " << (db_v2 ? "metrics" : "rt_metrics")
                << " WHERE index_id=" << index_id;
            database_query metrics_to_rebuild_query(*db);
            try { metrics_to_rebuild_query.run_query(oss.str()); }
            catch (std::exception const& e) {
              throw (exceptions::msg()
                     << "storage: rebuilder: could not fetch "
                     << "metrics of index " << index_id);
            }
            while (!_should_exit && metrics_to_rebuild_query.next()) {
              metric_info info;
              info.metric_id
                = metrics_to_rebuild_query.value(0).toUInt();
              info.metric_name
                = metrics_to_rebuild_query.value(1).toString();
              info.metric_type
                = metrics_to_rebuild_query.value(2).toInt();
              metrics_to_rebuild.push_back(info);
            }
          }

          // Browse metrics to rebuild.
          while (!_should_exit && !metrics_to_rebuild.empty()) {
            metric_info info(metrics_to_rebuild.front());
            metrics_to_rebuild.pop_front();
            _rebuild_metric(
              *db,
              info.metric_id,
              info.metric_name,
              info.metric_type,
              check_interval,
              rrd_len);
          }

          // Rebuild status.
          _rebuild_status(
            *db,
            index_id,
            check_interval);
        }
        catch (...) {
          // Set index as to-be-rebuilt.
          _set_index_rebuild(*db, index_id, 1);

          // Rethrow exception.
          throw ;
        }

        // Set index as rebuilt or to-be-rebuild
        // if we were interrupted.
        _set_index_rebuild(*db, index_id, (_should_exit ? 1 : 0));
      }
    }
    catch (std::exception const& e) {
      logging::error(logging::high) << e.what();
    }
    catch (...) {
      logging::error(logging::high)
        << "storage: rebuilder: unknown error";
    }

    // Sleep a while.
    time_t target(time(NULL) + _interval);
    while (!_should_exit && (target > time(NULL)))
      sleep(1);
  }
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Rebuild a metric.
 *
 *  @param[in] db           Database object.
 *  @param[in] metric_id    Metric ID.
 *  @param[in] metric_name  Metric name.
 *  @param[in] type         Metric type.
 *  @param[in] interval     Host/service check interval.
 *  @param[in] length       Metric RRD length in seconds.
 */
void rebuilder::_rebuild_metric(
                  database& db,
                  unsigned int metric_id,
                  QString const& metric_name,
                  short metric_type,
                  unsigned int interval,
                  unsigned int length) {
  // Log.
  logging::info(logging::low)
    << "storage: rebuilder: rebuilding metric " << metric_id
    << " (name " << metric_name << ", type " << metric_type
    << ", interval " << interval << ")";

  // Send rebuild start event.
  _send_rebuild_event(false, metric_id, false);

  // Database schema version.
  bool db_v2(db.schema_version() == database::v2);

  try {
    // Get data.
    std::ostringstream oss;
    oss << "SELECT ctime, value"
        << " FROM " << (db_v2 ? "data_bin" : "log_data_bin")
        << " WHERE metric_id=" << metric_id
        << " ORDER BY ctime ASC";
    database_query data_bin_query(db);
    bool caught(false);
    try { data_bin_query.run_query(oss.str()); }
    catch (std::exception const& e) {
      caught = true;
      logging::error(logging::medium) << "storage: rebuilder: "
        << "cannot fetch data of metric " << metric_id << ": "
        << e.what();
    }
    if (!caught)
      while (!_should_exit && data_bin_query.next()) {
        misc::shared_ptr<storage::metric> entry(new storage::metric);
        entry->ctime = data_bin_query.value(0).toUInt();
        entry->interval = interval;
        entry->is_for_rebuild = true;
        entry->metric_id = metric_id;
        entry->name = metric_name;
        entry->rrd_len = length;
        entry->value_type = metric_type;
        entry->value = data_bin_query.value(1).toDouble();
        if (entry->value > FLT_MAX * 0.999)
          entry->value = INFINITY;
        else if (entry->value < -FLT_MAX * 0.999)
          entry->value = -INFINITY;
        multiplexing::publisher().write(entry);
      }
  }
  catch (...) {
    // Send rebuild end event.
    _send_rebuild_event(true, metric_id, false);

    // Rethrow exception.
    throw ;
  }

  // Send rebuild end event.
  _send_rebuild_event(true, metric_id, false);

  return ;
}

/**
 *  Rebuild a status.
 *
 *  @param[in] db        Database object.
 *  @param[in] index_id  Index ID.
 *  @param[in] interval  Host/service check interval.
 */
void rebuilder::_rebuild_status(
                  database& db,
                  unsigned int index_id,
                  unsigned int interval) {
  // Log.
  logging::info(logging::low)
    << "storage: rebuilder: rebuilding status " << index_id
    << "(interval " << interval << ")";

  // Send rebuild start event.
  _send_rebuild_event(false, index_id, true);

  // Database schema version.
  bool db_v2(db.schema_version() == database::v2);

  try {
    // Get data.
    std::ostringstream oss;
    oss << "SELECT d.ctime, d.status"
        << " FROM " << (db_v2 ? "metrics" : "rt_metrics") << " AS m"
        << " JOIN " << (db_v2 ? "data_bin" : "log_data_bin") << " AS d"
        << "   ON m.metric_id=d.id_metric"
        << " WHERE m.index_id=" << index_id
        << " ORDER BY d.ctime ASC";
    database_query data_bin_query(db);
    bool caught(false);
    try { data_bin_query.run_query(oss.str()); }
    catch (std::exception const& e) {
      caught = true;
      logging::error(logging::medium) << "storage: rebuilder: "
        << "cannot fetch data of index " << index_id << ": "
        << e.what();
    }
    if (!caught)
      while (!_should_exit && data_bin_query.next()) {
        misc::shared_ptr<storage::status> entry(new storage::status);
        entry->ctime = data_bin_query.value(0).toUInt();
        entry->index_id = index_id;
        entry->interval = interval;
        entry->is_for_rebuild = true;
        entry->rrd_len = _rrd_len;
        entry->state = data_bin_query.value(1).toInt();
        multiplexing::publisher().write(entry);
      }
  }
  catch (...) {
    // Send rebuild end event.
    _send_rebuild_event(true, index_id, true);

    // Rethrow exception.
    throw ;
  }

  // Send rebuild end event.
  _send_rebuild_event(true, index_id, true);

  return ;
}

/**
 *  Send a rebuild event.
 *
 *  @param[in] end      false if rebuild is starting, true if it is ending.
 *  @param[in] id       Index or metric ID.
 *  @param[in] is_index true for an index ID, false for a metric ID.
 */
void rebuilder::_send_rebuild_event(
                  bool end,
                  unsigned int id,
                  bool is_index) {
  misc::shared_ptr<storage::rebuild> rb(new storage::rebuild);
  rb->end = end;
  rb->id = id;
  rb->is_index = is_index;
  multiplexing::publisher().write(rb);
  return ;
}

/**
 *  Set index rebuild flag.
 *
 *  @param[in] db        Database object.
 *  @param[in] index_id  Index to update.
 *  @param[in] state     Rebuild state (0, 1 or 2).
 */
void rebuilder::_set_index_rebuild(
                  database& db,
                  unsigned int index_id,
                  short state) {
  bool db_v2(db.schema_version() == database::v2);
  std::ostringstream oss;
  oss << "UPDATE " << (db_v2 ? "index_data" : "rt_index_data")
      << " SET must_be_rebuild=" << state
      << " WHERE " << (db_v2 ? "id" : "index_id") << "=" << index_id;
  database_query update_index_query(db);
  try { update_index_query.run_query(oss.str()); }
  catch (std::exception const& e) {
    logging::error(logging::low)
      << "storage: rebuilder: cannot update state of index "
      << index_id << ": " << e.what();
  }
  return ;
}
<commit_msg>storage: fix rebuild queries regarding must_be_rebuild flag.<commit_after>/*
** Copyright 2012-2015 Centreon
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
**     http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
**
** For more information : contact@centreon.com
*/

#include <cfloat>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <QVariant>
#include <sstream>
#include "com/centreon/broker/database.hh"
#include "com/centreon/broker/database_query.hh"
#include "com/centreon/broker/exceptions/msg.hh"
#include "com/centreon/broker/logging/logging.hh"
#include "com/centreon/broker/misc/shared_ptr.hh"
#include "com/centreon/broker/multiplexing/publisher.hh"
#include "com/centreon/broker/storage/metric.hh"
#include "com/centreon/broker/storage/rebuild.hh"
#include "com/centreon/broker/storage/status.hh"
#include "com/centreon/broker/storage/rebuilder.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::storage;

// Local types.
struct index_info {
  unsigned int index_id;
  unsigned int host_id;
  unsigned int service_id;
  unsigned int rrd_retention;
};

struct metric_info {
  unsigned int metric_id;
  QString metric_name;
  short metric_type;
};

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] db_cfg                  Database configuration.
 *  @param[in] rebuild_check_interval  How often the rebuild thread will
 *                                     check for rebuild.
 *  @param[in] rrd_length              Length of RRD files.
 */
rebuilder::rebuilder(
             database_config const& db_cfg,
             unsigned int rebuild_check_interval,
             unsigned int rrd_length)
  : _db_cfg(db_cfg),
    _interval(rebuild_check_interval),
    _rrd_len(rrd_length),
    _should_exit(false) {}

/**
 *  Destructor.
 */
rebuilder::~rebuilder() throw () {}

/**
 *  Set the exit flag.
 */
void rebuilder::exit() throw () {
  _should_exit = true;
  return ;
}

/**
 *  Get the rebuild check interval.
 *
 *  @return Rebuild check interval in seconds.
 */
unsigned int rebuilder::get_interval() const throw () {
  return (_interval);
}

/**
 *  Get the RRD length in seconds.
 *
 *  @return RRD length in seconds.
 */
unsigned int rebuilder::get_rrd_length() const throw () {
  return (_rrd_len);
}

/**
 *  Thread entry point.
 */
void rebuilder::run() {
  while (!_should_exit && _interval) {
    try {
      // Open DB.
      std::auto_ptr<database> db;
      try {
        db.reset(new database(_db_cfg));
      }
      catch (std::exception const& e) {
        throw (broker::exceptions::msg() << "storage: rebuilder: could "
               "not connect to Centreon Storage database: "
               << e.what());
      }

      // Database schema version.
      bool db_v2(db->schema_version() == database::v2);

      // Fetch index to rebuild.
      std::list<index_info> index_to_rebuild;
      {
        std::ostringstream query;
        query << "SELECT " << (db_v2 ? "id" : "index_id")
              << "       , host_id, service_id, rrd_retention"
                 "  FROM " << (db_v2 ? "index_data" : "rt_index_data")
              << "  WHERE must_be_rebuild=" << (db_v2 ? "'1'" : "1");
        database_query index_to_rebuild_query(*db);
        index_to_rebuild_query.run_query(
          query.str(),
          "storage: rebuilder: could not fetch index to rebuild");
        while (!_should_exit && index_to_rebuild_query.next()) {
          index_info info;
          info.index_id = index_to_rebuild_query.value(0).toUInt();
          info.host_id = index_to_rebuild_query.value(1).toUInt();
          info.service_id = index_to_rebuild_query.value(2).toUInt();
          info.rrd_retention
            = (index_to_rebuild_query.value(3).isNull()
               ? 0
               : index_to_rebuild_query.value(3).toUInt());
          if (!info.rrd_retention)
            info.rrd_retention = _rrd_len;
          index_to_rebuild.push_back(info);
        }
      }

      // Browse list of index to rebuild.
      while (!_should_exit && !index_to_rebuild.empty()) {
        // Get check interval of host/service.
        unsigned int index_id;
        unsigned int check_interval(0);
        unsigned int rrd_len;
        {
          index_info info(index_to_rebuild.front());
          index_id = info.index_id;
          rrd_len = info.rrd_retention;
          index_to_rebuild.pop_front();

          std::ostringstream oss;
          if (!info.service_id)
            oss << "SELECT check_interval"
                << " FROM " << (db_v2 ? "hosts" : "rt_hosts")
                << " WHERE host_id=" << info.host_id;
          else
            oss << "SELECT check_interval"
                << " FROM " << (db_v2 ? "services" : "rt_services")
                << " WHERE host_id=" << info.host_id
                << "  AND service_id=" << info.service_id;
          database_query query(*db);
          query.run_query(oss.str());
          if (query.next())
            check_interval = query.value(0).toUInt();
          if (!check_interval)
            check_interval = 5;
        }
        logging::info(logging::medium) << "storage: rebuilder: index "
          << index_id << " (interval " << check_interval
          << ") will be rebuild";

        // Set index as being rebuilt.
        _set_index_rebuild(*db, index_id, 2);

        try {
          // Fetch metrics to rebuild.
          std::list<metric_info> metrics_to_rebuild;
          {
            std::ostringstream oss;
            oss << "SELECT metric_id, metric_name, data_source_type"
                << " FROM " << (db_v2 ? "metrics" : "rt_metrics")
                << " WHERE index_id=" << index_id;
            database_query metrics_to_rebuild_query(*db);
            try { metrics_to_rebuild_query.run_query(oss.str()); }
            catch (std::exception const& e) {
              throw (exceptions::msg()
                     << "storage: rebuilder: could not fetch "
                     << "metrics of index " << index_id);
            }
            while (!_should_exit && metrics_to_rebuild_query.next()) {
              metric_info info;
              info.metric_id
                = metrics_to_rebuild_query.value(0).toUInt();
              info.metric_name
                = metrics_to_rebuild_query.value(1).toString();
              info.metric_type
                = metrics_to_rebuild_query.value(2).toInt();
              metrics_to_rebuild.push_back(info);
            }
          }

          // Browse metrics to rebuild.
          while (!_should_exit && !metrics_to_rebuild.empty()) {
            metric_info info(metrics_to_rebuild.front());
            metrics_to_rebuild.pop_front();
            _rebuild_metric(
              *db,
              info.metric_id,
              info.metric_name,
              info.metric_type,
              check_interval,
              rrd_len);
          }

          // Rebuild status.
          _rebuild_status(
            *db,
            index_id,
            check_interval);
        }
        catch (...) {
          // Set index as to-be-rebuilt.
          _set_index_rebuild(*db, index_id, 1);

          // Rethrow exception.
          throw ;
        }

        // Set index as rebuilt or to-be-rebuild
        // if we were interrupted.
        _set_index_rebuild(*db, index_id, (_should_exit ? 1 : 0));
      }
    }
    catch (std::exception const& e) {
      logging::error(logging::high) << e.what();
    }
    catch (...) {
      logging::error(logging::high)
        << "storage: rebuilder: unknown error";
    }

    // Sleep a while.
    time_t target(time(NULL) + _interval);
    while (!_should_exit && (target > time(NULL)))
      sleep(1);
  }
  return ;
}

/**************************************
*                                     *
*           Private Methods           *
*                                     *
**************************************/

/**
 *  Rebuild a metric.
 *
 *  @param[in] db           Database object.
 *  @param[in] metric_id    Metric ID.
 *  @param[in] metric_name  Metric name.
 *  @param[in] type         Metric type.
 *  @param[in] interval     Host/service check interval.
 *  @param[in] length       Metric RRD length in seconds.
 */
void rebuilder::_rebuild_metric(
                  database& db,
                  unsigned int metric_id,
                  QString const& metric_name,
                  short metric_type,
                  unsigned int interval,
                  unsigned int length) {
  // Log.
  logging::info(logging::low)
    << "storage: rebuilder: rebuilding metric " << metric_id
    << " (name " << metric_name << ", type " << metric_type
    << ", interval " << interval << ")";

  // Send rebuild start event.
  _send_rebuild_event(false, metric_id, false);

  // Database schema version.
  bool db_v2(db.schema_version() == database::v2);

  try {
    // Get data.
    std::ostringstream oss;
    oss << "SELECT ctime, value"
        << " FROM " << (db_v2 ? "data_bin" : "log_data_bin")
        << " WHERE metric_id=" << metric_id
        << " ORDER BY ctime ASC";
    database_query data_bin_query(db);
    bool caught(false);
    try { data_bin_query.run_query(oss.str()); }
    catch (std::exception const& e) {
      caught = true;
      logging::error(logging::medium) << "storage: rebuilder: "
        << "cannot fetch data of metric " << metric_id << ": "
        << e.what();
    }
    if (!caught)
      while (!_should_exit && data_bin_query.next()) {
        misc::shared_ptr<storage::metric> entry(new storage::metric);
        entry->ctime = data_bin_query.value(0).toUInt();
        entry->interval = interval;
        entry->is_for_rebuild = true;
        entry->metric_id = metric_id;
        entry->name = metric_name;
        entry->rrd_len = length;
        entry->value_type = metric_type;
        entry->value = data_bin_query.value(1).toDouble();
        if (entry->value > FLT_MAX * 0.999)
          entry->value = INFINITY;
        else if (entry->value < -FLT_MAX * 0.999)
          entry->value = -INFINITY;
        multiplexing::publisher().write(entry);
      }
  }
  catch (...) {
    // Send rebuild end event.
    _send_rebuild_event(true, metric_id, false);

    // Rethrow exception.
    throw ;
  }

  // Send rebuild end event.
  _send_rebuild_event(true, metric_id, false);

  return ;
}

/**
 *  Rebuild a status.
 *
 *  @param[in] db        Database object.
 *  @param[in] index_id  Index ID.
 *  @param[in] interval  Host/service check interval.
 */
void rebuilder::_rebuild_status(
                  database& db,
                  unsigned int index_id,
                  unsigned int interval) {
  // Log.
  logging::info(logging::low)
    << "storage: rebuilder: rebuilding status " << index_id
    << "(interval " << interval << ")";

  // Send rebuild start event.
  _send_rebuild_event(false, index_id, true);

  // Database schema version.
  bool db_v2(db.schema_version() == database::v2);

  try {
    // Get data.
    std::ostringstream oss;
    oss << "SELECT d.ctime, d.status"
        << " FROM " << (db_v2 ? "metrics" : "rt_metrics") << " AS m"
        << " JOIN " << (db_v2 ? "data_bin" : "log_data_bin") << " AS d"
        << "   ON m.metric_id=d.id_metric"
        << " WHERE m.index_id=" << index_id
        << " ORDER BY d.ctime ASC";
    database_query data_bin_query(db);
    bool caught(false);
    try { data_bin_query.run_query(oss.str()); }
    catch (std::exception const& e) {
      caught = true;
      logging::error(logging::medium) << "storage: rebuilder: "
        << "cannot fetch data of index " << index_id << ": "
        << e.what();
    }
    if (!caught)
      while (!_should_exit && data_bin_query.next()) {
        misc::shared_ptr<storage::status> entry(new storage::status);
        entry->ctime = data_bin_query.value(0).toUInt();
        entry->index_id = index_id;
        entry->interval = interval;
        entry->is_for_rebuild = true;
        entry->rrd_len = _rrd_len;
        entry->state = data_bin_query.value(1).toInt();
        multiplexing::publisher().write(entry);
      }
  }
  catch (...) {
    // Send rebuild end event.
    _send_rebuild_event(true, index_id, true);

    // Rethrow exception.
    throw ;
  }

  // Send rebuild end event.
  _send_rebuild_event(true, index_id, true);

  return ;
}

/**
 *  Send a rebuild event.
 *
 *  @param[in] end      false if rebuild is starting, true if it is ending.
 *  @param[in] id       Index or metric ID.
 *  @param[in] is_index true for an index ID, false for a metric ID.
 */
void rebuilder::_send_rebuild_event(
                  bool end,
                  unsigned int id,
                  bool is_index) {
  misc::shared_ptr<storage::rebuild> rb(new storage::rebuild);
  rb->end = end;
  rb->id = id;
  rb->is_index = is_index;
  multiplexing::publisher().write(rb);
  return ;
}

/**
 *  Set index rebuild flag.
 *
 *  @param[in] db        Database object.
 *  @param[in] index_id  Index to update.
 *  @param[in] state     Rebuild state (0, 1 or 2).
 */
void rebuilder::_set_index_rebuild(
                  database& db,
                  unsigned int index_id,
                  short state) {
  bool db_v2(db.schema_version() == database::v2);
  std::ostringstream oss;
  oss << "UPDATE " << (db_v2 ? "index_data" : "rt_index_data")
      << " SET must_be_rebuild="
      << (db_v2 ? "'" : "") << state << (db_v2 ? "'" : "")
      << " WHERE " << (db_v2 ? "id" : "index_id") << "=" << index_id;
  database_query update_index_query(db);
  try { update_index_query.run_query(oss.str()); }
  catch (std::exception const& e) {
    logging::error(logging::low)
      << "storage: rebuilder: cannot update state of index "
      << index_id << ": " << e.what();
  }
  return ;
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageAdaptorNthElementTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
//-------------------------------------------
//
//  Example of the use of Adaptors
//  to get access to the N-th component
//  of an image with pixels of container type
//
//-------------------------------------------

#include <itkImage.h>
#include <itkIndex.h>
#include <itkImageAdaptor.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkNthElementImageAdaptor.h>
#include <itkAddImageFilter.h>
#include <itkVector.h>

int main()
{

  //-------------------------------------------------------------
  //                        Typedefs
  //-------------------------------------------------------------

  // Float Image typedefs
  typedef   float                                       myFloatPixelType;
  typedef   itk::Image<myFloatPixelType, 3>     myFloatImageType;

  typedef   myFloatImageType::SizeType                  mySizeType;
  typedef   myFloatImageType::IndexType                 myIndexType;
  typedef   myFloatImageType::RegionType                myRegionType;

  // RGBPixel Image typedefs
  typedef   itk::Vector<myFloatPixelType,3>             myContainerPixelType;
  typedef   itk::Image<
                       myContainerPixelType, 3>    myContainerPixelImageType;

  typedef   itk::NthElementImageAdaptor< myContainerPixelImageType,
                                         myFloatPixelType >        myAdaptorType;

  typedef itk::ImageRegionIteratorWithIndex<
                                   myFloatImageType > myFloatIteratorType;

  typedef itk::ImageRegionIteratorWithIndex<
                         myContainerPixelImageType >   myContainerPixelIteratorType;

  typedef itk::AddImageFilter< myAdaptorType,
                               myFloatImageType,
                               myFloatImageType >       myFilterType;

  //-------------------------------------------------------------
  //                 Create and Allocate the image
  //-------------------------------------------------------------

  // Define their size, and start index
  mySizeType size;
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;    // Small size, because we are printing it

  myIndexType start;
  start = myIndexType::ZeroIndex;

  myRegionType region;
  region.SetIndex( start );
  region.SetSize( size );

  float spacing[3];
  spacing[0] = 1.0;
  spacing[1] = 1.0;
  spacing[2] = 1.0;

  //-------------------------------------------------------------
  //                 Create and Initialize the RGBPixel image
  //-------------------------------------------------------------

  myContainerPixelImageType::Pointer   myContainerPixelImage
                                          = myContainerPixelImageType::New();

  myContainerPixelImage->SetLargestPossibleRegion( region );
  myContainerPixelImage->SetBufferedRegion( region );
  myContainerPixelImage->SetRequestedRegion( region );
  myContainerPixelImage->Allocate();
  myContainerPixelImage->SetSpacing( spacing );

  myContainerPixelIteratorType it(  myContainerPixelImage,
                            myContainerPixelImage->GetRequestedRegion() );

  myContainerPixelType initialPixelValue;
  initialPixelValue[ 0 ] =  5;
  initialPixelValue[ 1 ] = 11;
  initialPixelValue[ 2 ] = 17;

  while( !it.IsAtEnd() )
  {
    it.Set( initialPixelValue );
    ++it;
  }

  std::cout << "Initial Container Image Values : " << std::endl;
  it.GoToBegin();
  while( !it.IsAtEnd() )
  {
    myIndexType index = it.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(4);
    std::cout <<  it.Get()[0] << ",";
    std::cout.width(4);
    std::cout <<  it.Get()[1] << ",";
    std::cout.width(4);
    std::cout <<  it.Get()[2] << std::endl;
    ++it;
  }

  std::cout << "Container Image Initializaed" << std::endl;

  //-------------------------------------------------------------
  //                 Create and Initialize the Float image
  //-------------------------------------------------------------

  myFloatImageType::Pointer   myFloatImage = myFloatImageType::New();

  myFloatImage->SetLargestPossibleRegion( region );
  myFloatImage->SetBufferedRegion( region );
  myFloatImage->SetRequestedRegion( region );
  myFloatImage->Allocate();
  myFloatImage->SetSpacing( spacing );

  myFloatIteratorType itf(  myFloatImage, myFloatImage->GetRequestedRegion() );

  myFloatPixelType initialFloatValue = 5.0;

  while( !itf.IsAtEnd() )
  {
    itf.Set( initialFloatValue );
    ++itf;
  }

  std::cout << "Initial Float Image Values : " << std::endl;
  itf.GoToBegin();
  while( !itf.IsAtEnd() )
  {
    myIndexType index = itf.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  itf.Get() << std::endl;
    ++itf;
  }

  std::cout << "Float Image Initializaed" << std::endl;

  //-------------------------------------------------------------
  //         Create the adaptor and connect the image
  //-------------------------------------------------------------

  myAdaptorType::Pointer myAdaptor = myAdaptorType::New();

  myAdaptor->SetImage( myContainerPixelImage );

  //-------------------------------------------------------------
  //         Create the filter and connect the inputs
  //-------------------------------------------------------------

  myFilterType::Pointer    filter   = myFilterType::New();

  filter->SetInput1( myAdaptor );
  filter->SetInput2( myFloatImage );

  //-------------------------------------------------------------
  //      Set the requested region of  the Output image
  //-------------------------------------------------------------

  myFloatImageType::Pointer myFloatOutputImage = filter->GetOutput();
  myFloatOutputImage->SetSpacing( spacing );

  std::cout << "Float Output Image Initializaed" << std::endl;

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------

  std::cout << "Calling filter Update" << std::endl;

 // Multiplex !!
  myAdaptor->SelectNthElement( 0 );

  filter->Update();

  std::cout << "Filter Updated" << std::endl;

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------

  myFloatOutputImage = filter->GetOutput();

  myFloatIteratorType ito(  myFloatOutputImage, myFloatOutputImage->GetRequestedRegion() );

  std::cout << std::endl;
  std::cout << "Filter Output :" << std::endl;
  while( !ito.IsAtEnd() )
  {
    myIndexType index = ito.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  ito.Get() << std::endl;
    ++ito;
  }

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------
  // Second Multiplex !!

  myAdaptor->SelectNthElement( 1 );

  filter->Update();

  std::cout << std::endl;
  std::cout << "Second Filter Output :" << std::endl;
  ito.GoToBegin();
  while( !ito.IsAtEnd() )
  {
    myIndexType index = ito.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  ito.Get() << std::endl;
    ++ito;
  }

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------
  // Third Multiplex !!

  myAdaptor->SelectNthElement( 2 );

  filter->Update();

  std::cout << std::endl;
  std::cout << "Second Filter Output :" << std::endl;
  ito.GoToBegin();
  while( !ito.IsAtEnd() )
  {
    myIndexType index = ito.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  ito.Get() << std::endl;
    ++ito;
  }

  return 0;

}

<commit_msg>FIX: iterator initialization<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkImageAdaptorNthElementTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

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

=========================================================================*/
//-------------------------------------------
//
//  Example of the use of Adaptors
//  to get access to the N-th component
//  of an image with pixels of container type
//
//-------------------------------------------

#include <itkImage.h>
#include <itkIndex.h>
#include <itkImageAdaptor.h>
#include <itkImageRegionIteratorWithIndex.h>
#include <itkNthElementImageAdaptor.h>
#include <itkAddImageFilter.h>
#include <itkVector.h>

int main()
{

  //-------------------------------------------------------------
  //                        Typedefs
  //-------------------------------------------------------------

  // Float Image typedefs
  typedef   float                                       myFloatPixelType;
  typedef   itk::Image<myFloatPixelType, 3>     myFloatImageType;

  typedef   myFloatImageType::SizeType                  mySizeType;
  typedef   myFloatImageType::IndexType                 myIndexType;
  typedef   myFloatImageType::RegionType                myRegionType;

  // RGBPixel Image typedefs
  typedef   itk::Vector<myFloatPixelType,3>             myContainerPixelType;
  typedef   itk::Image<
                       myContainerPixelType, 3>    myContainerPixelImageType;

  typedef   itk::NthElementImageAdaptor< myContainerPixelImageType,
                                         myFloatPixelType >        myAdaptorType;

  typedef itk::ImageRegionIteratorWithIndex<
                                   myFloatImageType > myFloatIteratorType;

  typedef itk::ImageRegionIteratorWithIndex<
                         myContainerPixelImageType >   myContainerPixelIteratorType;

  typedef itk::AddImageFilter< myAdaptorType,
                               myFloatImageType,
                               myFloatImageType >       myFilterType;

  //-------------------------------------------------------------
  //                 Create and Allocate the image
  //-------------------------------------------------------------

  // Define their size, and start index
  mySizeType size;
  size[0] = 2;
  size[1] = 2;
  size[2] = 2;    // Small size, because we are printing it

  myIndexType start;
  start = myIndexType::ZeroIndex;

  myRegionType region;
  region.SetIndex( start );
  region.SetSize( size );

  float spacing[3];
  spacing[0] = 1.0;
  spacing[1] = 1.0;
  spacing[2] = 1.0;

  //-------------------------------------------------------------
  //                 Create and Initialize the RGBPixel image
  //-------------------------------------------------------------

  myContainerPixelImageType::Pointer   myContainerPixelImage
                                          = myContainerPixelImageType::New();

  myContainerPixelImage->SetLargestPossibleRegion( region );
  myContainerPixelImage->SetBufferedRegion( region );
  myContainerPixelImage->SetRequestedRegion( region );
  myContainerPixelImage->Allocate();
  myContainerPixelImage->SetSpacing( spacing );

  myContainerPixelIteratorType it(  myContainerPixelImage,
                            myContainerPixelImage->GetRequestedRegion() );

  myContainerPixelType initialPixelValue;
  initialPixelValue[ 0 ] =  5;
  initialPixelValue[ 1 ] = 11;
  initialPixelValue[ 2 ] = 17;

  while( !it.IsAtEnd() )
  {
    it.Set( initialPixelValue );
    ++it;
  }

  std::cout << "Initial Container Image Values : " << std::endl;
  it.GoToBegin();
  while( !it.IsAtEnd() )
  {
    myIndexType index = it.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(4);
    std::cout <<  it.Get()[0] << ",";
    std::cout.width(4);
    std::cout <<  it.Get()[1] << ",";
    std::cout.width(4);
    std::cout <<  it.Get()[2] << std::endl;
    ++it;
  }

  std::cout << "Container Image Initializaed" << std::endl;

  //-------------------------------------------------------------
  //                 Create and Initialize the Float image
  //-------------------------------------------------------------

  myFloatImageType::Pointer   myFloatImage = myFloatImageType::New();

  myFloatImage->SetLargestPossibleRegion( region );
  myFloatImage->SetBufferedRegion( region );
  myFloatImage->SetRequestedRegion( region );
  myFloatImage->Allocate();
  myFloatImage->SetSpacing( spacing );

  myFloatIteratorType itf(  myFloatImage, myFloatImage->GetRequestedRegion() );

  myFloatPixelType initialFloatValue = 5.0;

  while( !itf.IsAtEnd() )
  {
    itf.Set( initialFloatValue );
    ++itf;
  }

  std::cout << "Initial Float Image Values : " << std::endl;
  itf.GoToBegin();
  while( !itf.IsAtEnd() )
  {
    myIndexType index = itf.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  itf.Get() << std::endl;
    ++itf;
  }

  std::cout << "Float Image Initializaed" << std::endl;

  //-------------------------------------------------------------
  //         Create the adaptor and connect the image
  //-------------------------------------------------------------

  myAdaptorType::Pointer myAdaptor = myAdaptorType::New();

  myAdaptor->SetImage( myContainerPixelImage );

  //-------------------------------------------------------------
  //         Create the filter and connect the inputs
  //-------------------------------------------------------------

  myFilterType::Pointer    filter   = myFilterType::New();

  filter->SetInput1( myAdaptor );
  filter->SetInput2( myFloatImage );

  //-------------------------------------------------------------
  //      Set the requested region of  the Output image
  //-------------------------------------------------------------

  myFloatImageType::Pointer myFloatOutputImage = filter->GetOutput();
  myFloatOutputImage->SetSpacing( spacing );

  std::cout << "Float Output Image Initializaed" << std::endl;

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------

  std::cout << "Calling filter Update" << std::endl;

 // Multiplex !!
  myAdaptor->SelectNthElement( 0 );

  filter->Update();

  std::cout << "Filter Updated" << std::endl;

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------

  myFloatOutputImage = filter->GetOutput();

  myFloatIteratorType ito(  myFloatOutputImage, myFloatOutputImage->GetRequestedRegion() );

  std::cout << std::endl;
  std::cout << "Filter Output :" << std::endl;
  while( !ito.IsAtEnd() )
  {
    myIndexType index = ito.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  ito.Get() << std::endl;
    ++ito;
  }

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------
  // Second Multiplex !!

  myAdaptor->SelectNthElement( 1 );

  filter->Update();

  std::cout << std::endl;
  std::cout << "Second Filter Output :" << std::endl;
  ito = myFloatIteratorType(  myFloatOutputImage, myFloatOutputImage->GetRequestedRegion() );
  while( !ito.IsAtEnd() )
  {
    myIndexType index = ito.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  ito.Get() << std::endl;
    ++ito;
  }

  //-------------------------------------------------------------
  //         Force the execution of the filter
  //-------------------------------------------------------------
  // Third Multiplex !!

  myAdaptor->SelectNthElement( 2 );

  filter->Update();

  std::cout << std::endl;
  std::cout << "Second Filter Output :" << std::endl;
  ito = myFloatIteratorType(  myFloatOutputImage, myFloatOutputImage->GetRequestedRegion() );
  while( !ito.IsAtEnd() )
  {
    myIndexType index = ito.GetIndex();
    std::cout <<  "[";
    std::cout.width(3);
    std::cout << index[0] << ",";
    std::cout.width(3);
    std::cout << index[1] << ",";
    std::cout.width(3);
    std::cout << index[2] << "] =  ";
    std::cout.width(8);
    std::cout <<  ito.Get() << std::endl;
    ++ito;
  }

  return 0;

}

<|endoftext|>


<commit_before>//
// Created by Miguel Rentes on 09/03/17.
//

#include "strings.h"

vector<int> parseInts(string str) {
    // Complete this function
}

int main() {
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }

    return 0;
}<commit_msg>Adds solution for the StringStream challenge.<commit_after>//
// Created by Miguel Rentes on 09/03/17.
//

#include "strings.h"

vector<int> parseInts(string str) {
    stringstream ss(str);
    vector<int> integers;
    int a;
    char ch;

    do {
        ch = '\0';
        ss >> a >> ch;
        integers.push_back(a);
    } while (ch == ',');
    return integers;
}

int main() {
    string str;
    cin >> str;
    vector<int> integers = parseInts(str);
    for(int i = 0; i < integers.size(); i++) {
        cout << integers[i] << "\n";
    }

    return 0;
}<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: fileview.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: hr $ $Date: 2003-09-29 15:00:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVT_FILEVIEW_HXX
#define _SVT_FILEVIEW_HXX

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif

#include <vcl/ctrl.hxx>
#include <vcl/image.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/dialog.hxx>

// class SvtFileView -----------------------------------------------------

#define FILEVIEW_ONLYFOLDER         0x0001
#define FILEVIEW_MULTISELECTION     0x0002

#define FILEVIEW_SHOW_TITLE         0x0010
#define FILEVIEW_SHOW_SIZE          0x0020
#define FILEVIEW_SHOW_DATE          0x0040
#define FILEVIEW_SHOW_ALL           0x0070

class ViewTabListBox_Impl;
class SvtFileView_Impl;
class SvLBoxEntry;
class HeaderBar;

class IUrlFilter;
class SvtFileView : public Control
{
private:
    SvtFileView_Impl*       mpImp;

    void                    OpenFolder( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents );

    DECL_LINK(              HeaderSelect_Impl, HeaderBar * );
    DECL_LINK(              HeaderEndDrag_Impl, HeaderBar * );

protected:
    virtual void GetFocus();

public:
    SvtFileView( Window* pParent, const ResId& rResId, sal_Bool bOnlyFolder, sal_Bool bMultiSelection );
    SvtFileView( Window* pParent, const ResId& rResId, sal_Int8 nFlags );
    ~SvtFileView();

    const String&           GetViewURL() const;
    String                  GetURL( SvLBoxEntry* pEntry ) const;
    String                  GetCurrentURL() const;

    sal_Bool                CreateNewFolder( const String& rNewFolder );
    sal_Bool                HasPreviousLevel( String& rParentURL ) const;
    sal_Bool                PreviousLevel( String& rNewURL );

    void                    SetHelpId( sal_uInt32 nHelpId );
    sal_uInt32              GetHelpId( ) const;
    void                    SetSizePixel( const Size& rNewSize );
    void                    SetPosSizePixel( const Point& rNewPos, const Size& rNewSize );
    sal_Bool                Initialize( const String& rURL, const String& rFilter );
    sal_Bool                Initialize( const String& rURL,
                                        const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents );

    sal_Bool                ExecuteFilter( const String& rFilter );
    void                    SetNoSelection();
    void                    ResetCursor();

    void                    SetSelectHdl( const Link& rHdl );
    void                    SetDoubleClickHdl( const Link& rHdl );
    void                    SetOpenDoneHdl( const Link& rHdl );

    ULONG                   GetSelectionCount() const;
    SvLBoxEntry*            FirstSelected() const;
    SvLBoxEntry*            NextSelected( SvLBoxEntry* pEntry ) const;
    void                    EnableAutoResize();
    void                    SetFocus();

    void                    EnableContextMenu( sal_Bool bEnable );
    void                    EnableDelete( sal_Bool bEnable );
    void                    EnableNameReplacing( sal_Bool bEnable = sal_True );
                                // translate folder names or display doc-title instead of file name
                                // EnableContextMenu( TRUE )/EnableDelete(TRUE) disable name replacing!

                            // save and load column size and sort order
    String                  GetConfigString() const;
    void                    SetConfigString( const String& rCfgStr );

    void                    SetUrlFilter( const IUrlFilter* _pFilter );
    const IUrlFilter*       GetUrlFilter( ) const;
};

// struct SvtContentEntry ------------------------------------------------

struct SvtContentEntry
{
    sal_Bool    mbIsFolder;
    UniString   maURL;

    SvtContentEntry( const UniString& rURL, sal_Bool bIsFolder ) :
        mbIsFolder( bIsFolder ), maURL( rURL ) {}
};

namespace svtools {

// -----------------------------------------------------------------------
// QueryDeleteDlg_Impl
// -----------------------------------------------------------------------

enum QueryDeleteResult_Impl
{
    QUERYDELETE_YES = 0,
    QUERYDELETE_NO,
    QUERYDELETE_ALL,
    QUERYDELETE_CANCEL
};

class QueryDeleteDlg_Impl : public ModalDialog
{
    FixedText               _aEntryLabel;
    FixedText               _aEntry;
    FixedText               _aQueryMsg;

    PushButton              _aYesButton;
    PushButton              _aAllButton;
    PushButton              _aNoButton;
    CancelButton            _aCancelButton;

    QueryDeleteResult_Impl  _eResult;

private:

    DECL_STATIC_LINK( QueryDeleteDlg_Impl, ClickLink, PushButton* );

public:

                            QueryDeleteDlg_Impl( Window* pParent,
                                                 const String& rName );

    void                    EnableAllButton() { _aAllButton.Enable( sal_True ); }
    QueryDeleteResult_Impl  GetResult() const { return _eResult; }
};

}

#endif // _SVT_FILEVIEW_HXX

<commit_msg>INTEGRATION: CWS insight01 (1.14.22); FILE MERGED 2003/11/26 12:32:29 oj 1.14.22.1: #111075# changes for general xcontent handling<commit_after>/*************************************************************************
 *
 *  $RCSfile: fileview.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 14:32:20 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SVT_FILEVIEW_HXX
#define _SVT_FILEVIEW_HXX

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif

#include <vcl/ctrl.hxx>
#include <vcl/image.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/dialog.hxx>

// class SvtFileView -----------------------------------------------------

#define FILEVIEW_ONLYFOLDER         0x0001
#define FILEVIEW_MULTISELECTION     0x0002

#define FILEVIEW_SHOW_TITLE         0x0010
#define FILEVIEW_SHOW_SIZE          0x0020
#define FILEVIEW_SHOW_DATE          0x0040
#define FILEVIEW_SHOW_ALL           0x0070

class ViewTabListBox_Impl;
class SvtFileView_Impl;
class SvLBoxEntry;
class HeaderBar;

class IUrlFilter;
class SvtFileView : public Control
{
private:
    SvtFileView_Impl*       mpImp;

    void                    OpenFolder( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents );

    DECL_LINK(              HeaderSelect_Impl, HeaderBar * );
    DECL_LINK(              HeaderEndDrag_Impl, HeaderBar * );

protected:
    virtual void GetFocus();

public:
    SvtFileView( Window* pParent, const ResId& rResId, sal_Bool bOnlyFolder, sal_Bool bMultiSelection );
    SvtFileView( Window* pParent, const ResId& rResId, sal_Int8 nFlags );
    ~SvtFileView();

    const String&           GetViewURL() const;
    String                  GetURL( SvLBoxEntry* pEntry ) const;
    String                  GetCurrentURL() const;

    sal_Bool                CreateNewFolder( const String& rNewFolder );
    sal_Bool                HasPreviousLevel( String& rParentURL ) const;
    sal_Bool                PreviousLevel( String& rNewURL );

    void                    SetHelpId( sal_uInt32 nHelpId );
    sal_uInt32              GetHelpId( ) const;
    void                    SetSizePixel( const Size& rNewSize );
    void                    SetPosSizePixel( const Point& rNewPos, const Size& rNewSize );
    sal_Bool                Initialize( const String& rURL, const String& rFilter );
    sal_Bool                Initialize( const String& rURL,
                                        const ::com::sun::star::uno::Sequence< ::rtl::OUString >& aContents );

    sal_Bool                Initialize( const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent>& _xContent, const String& rFilter );

    sal_Bool                ExecuteFilter( const String& rFilter );
    void                    SetNoSelection();
    void                    ResetCursor();

    void                    SetSelectHdl( const Link& rHdl );
    void                    SetDoubleClickHdl( const Link& rHdl );
    void                    SetOpenDoneHdl( const Link& rHdl );

    ULONG                   GetSelectionCount() const;
    SvLBoxEntry*            FirstSelected() const;
    SvLBoxEntry*            NextSelected( SvLBoxEntry* pEntry ) const;
    void                    EnableAutoResize();
    void                    SetFocus();

    void                    EnableContextMenu( sal_Bool bEnable );
    void                    EnableDelete( sal_Bool bEnable );
    void                    EnableNameReplacing( sal_Bool bEnable = sal_True );
                                // translate folder names or display doc-title instead of file name
                                // EnableContextMenu( TRUE )/EnableDelete(TRUE) disable name replacing!

                            // save and load column size and sort order
    String                  GetConfigString() const;
    void                    SetConfigString( const String& rCfgStr );

    void                    SetUrlFilter( const IUrlFilter* _pFilter );
    const IUrlFilter*       GetUrlFilter( ) const;
};

// struct SvtContentEntry ------------------------------------------------

struct SvtContentEntry
{
    sal_Bool    mbIsFolder;
    UniString   maURL;

    SvtContentEntry( const UniString& rURL, sal_Bool bIsFolder ) :
        mbIsFolder( bIsFolder ), maURL( rURL ) {}
};

namespace svtools {

// -----------------------------------------------------------------------
// QueryDeleteDlg_Impl
// -----------------------------------------------------------------------

enum QueryDeleteResult_Impl
{
    QUERYDELETE_YES = 0,
    QUERYDELETE_NO,
    QUERYDELETE_ALL,
    QUERYDELETE_CANCEL
};

class QueryDeleteDlg_Impl : public ModalDialog
{
    FixedText               _aEntryLabel;
    FixedText               _aEntry;
    FixedText               _aQueryMsg;

    PushButton              _aYesButton;
    PushButton              _aAllButton;
    PushButton              _aNoButton;
    CancelButton            _aCancelButton;

    QueryDeleteResult_Impl  _eResult;

private:

    DECL_STATIC_LINK( QueryDeleteDlg_Impl, ClickLink, PushButton* );

public:

                            QueryDeleteDlg_Impl( Window* pParent,
                                                 const String& rName );

    void                    EnableAllButton() { _aAllButton.Enable( sal_True ); }
    QueryDeleteResult_Impl  GetResult() const { return _eResult; }
};

}

#endif // _SVT_FILEVIEW_HXX

<|endoftext|>


<commit_before>// Apache Thrift Frame Layer Network Transport Server in C++

#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <string>
#include <iostream>
#include <memory>

using namespace apache::thrift::transport;
using boost::shared_ptr;
using boost::make_shared;

int main()
{
    const std::string msg("Hello Thrift!\n");
    const std::string stop_cmd("STOP");
    const int buf_size = 1024*8;
    char buf[buf_size] = "";
    auto port = 9090;

    auto acceptor = std::make_shared<TServerSocket>(port);
    acceptor->listen();
    std::cout << "[Server] listening on port " << port << std::endl;

    while (true) {
        auto trans_ep = acceptor->accept();
        std::cout << "[Server] handling request" << std::endl;
        auto trans = make_shared<TFramedTransport>(trans_ep);
        trans->read(reinterpret_cast<uint8_t *>(buf), buf_size);
        trans->write(reinterpret_cast<const uint8_t *>(msg.c_str()), msg.length());
        trans->flush();
        trans->close();
        if (0 == stop_cmd.compare(0, std::string::npos, buf, 4))
            break;
    }

    std::cout << "[Server] exiting" << std::endl;
    acceptor->close();
}

<commit_msg>updated cpp server output<commit_after>// Apache Thrift Frame Layer Network Transport Server in C++

#include <thrift/transport/TServerSocket.h>
#include <thrift/transport/TBufferTransports.h>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <string>
#include <iostream>
#include <memory>

using namespace apache::thrift::transport;
using boost::shared_ptr;
using boost::make_shared;

int main()
{
    const std::string msg("Hello Thrift!\n");
    const std::string stop_cmd("STOP");
    const int buf_size = 1024*8;
    char buf[buf_size] = "";
    auto port = 9090;

    auto acceptor = std::make_shared<TServerSocket>(port);
    acceptor->listen();
    std::cout << "[Server] listening on port " << port << std::endl;

    while (true) {
        auto trans_ep = acceptor->accept();
        auto trans = make_shared<TFramedTransport>(trans_ep);
        auto len = trans->read(reinterpret_cast<uint8_t *>(buf), buf_size);
        buf[(0 < len && len < buf_size) ? len : 0] = '\0';
        std::cout << "[Server] handling request: " << buf << std::endl;
        trans->write(reinterpret_cast<const uint8_t *>(msg.c_str()), msg.length());
        trans->flush();
        trans->close();
        if (0 == stop_cmd.compare(0, std::string::npos, buf, 4))
            break;
    }

    std::cout << "[Server] exiting" << std::endl;
    acceptor->close();
}

<|endoftext|>


<commit_before>#pragma once

#include <phosphor-logging/sdjournal.hpp>

#include <gmock/gmock.h>

namespace phosphor
{
namespace logging
{

class SdJournalMock : public SdJournalImpl
{
  public:
    virtual ~SdJournalMock() = default;

    /* Set your mock to catch this call. */
    MOCK_METHOD1(journal_send_call, int(const char*));

    int journal_send(const char* fmt, ...) override
    {
        return journal_send_call(fmt);
    }
}

} // namespace logging
} // namespace phosphor
<commit_msg>bugfix: add fixes to mock class<commit_after>#pragma once

#include <cstdarg>
#include <phosphor-logging/sdjournal.hpp>

#include <gmock/gmock.h>

namespace phosphor
{
namespace logging
{

class SdJournalMock : public SdJournalHandler
{
  public:
    virtual ~SdJournalMock() = default;

    /* Set your mock to catch this call. */
    MOCK_METHOD1(journal_send_call, int(const char*));

    int journal_send(const char* fmt, ...) override
        __attribute__((format(printf, 2, 0))) __attribute__((sentinel))
    {
        return journal_send_call(fmt);
    }
};

} // namespace logging
} // namespace phosphor
<|endoftext|>


<commit_before>#pragma once
#ifndef WTL_SFMT_HPP_
#define WTL_SFMT_HPP_

#include <random>
#include <limits>

#define HAVE_SSE2
#define SFMT_MEXP 19937
#include "SFMT/SFMT.h"

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

class sfmt19937 {
  public:
    typedef uint32_t result_type;
    typedef sfmt_t state_type;

    static constexpr result_type min() {return 0U;}
    static constexpr result_type max() {return std::numeric_limits<result_type>::max();}
    static constexpr result_type default_seed = 1234U;

    // constructors
    explicit sfmt19937(const result_type s=default_seed) {seed(s);}
    explicit sfmt19937(const state_type& state): state_(state) {}
    sfmt19937(const sfmt19937&) = default;
    sfmt19937(sfmt19937&&) = default;

    // [0, 2^32-1]
    result_type operator()() {
        return sfmt_genrand_uint32(&state_);
    }

    void seed(const result_type s) {
        sfmt_init_gen_rand(&state_, s);
    }

    void discard(unsigned long long n) {
        for (; n != 0ULL; --n) {(*this)();}
    }

    const state_type& getstate() const {return state_;}
    void setstate(const state_type& state) {state_ = state;}

  private:
    state_type state_;
};

class sfmt19937_64 {
  public:
    typedef uint64_t result_type;
    typedef sfmt_t state_type;

    static constexpr result_type min() {return 0U;}
    static constexpr result_type max() {return std::numeric_limits<result_type>::max();}
    static constexpr result_type default_seed = 4321U;

    // constructors
    explicit sfmt19937_64(const result_type s=default_seed) {seed(s);}
    explicit sfmt19937_64(const state_type& state): state_(state) {}
    sfmt19937_64(const sfmt19937_64&) = default;
    sfmt19937_64(sfmt19937_64&&) = default;

    // [0, 2^64-1]
    result_type operator()() {
        return sfmt_genrand_uint64(&state_);
    }

    void seed(const result_type s) {
        sfmt_init_gen_rand(&state_, static_cast<uint32_t>(s));
    }

    void discard(unsigned long long n) {
        for (; n != 0ULL; --n) {(*this)();}
    }

    const state_type& getstate() const {return state_;}
    void setstate(const state_type& state) {state_ = state;}

  private:
    state_type state_;
};

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

inline sfmt19937& sfmt() {
    static sfmt19937 generator(std::random_device{}());
    return generator;
}

inline sfmt19937_64& sfmt64() {
    static sfmt19937_64 generator(std::random_device{}());
    return generator;
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif /* WTL_SFMT_HPP_ */
<commit_msg>:art: Remove const from seed parameter<commit_after>#pragma once
#ifndef WTL_SFMT_HPP_
#define WTL_SFMT_HPP_

#include <random>
#include <limits>

#define HAVE_SSE2
#define SFMT_MEXP 19937
#include "SFMT/SFMT.h"

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

class sfmt19937 {
  public:
    typedef uint32_t result_type;
    typedef sfmt_t state_type;

    static constexpr result_type min() {return 0U;}
    static constexpr result_type max() {return std::numeric_limits<result_type>::max();}
    static constexpr result_type default_seed = 1234U;

    // constructors
    explicit sfmt19937(result_type s=default_seed) {seed(s);}
    explicit sfmt19937(const state_type& state): state_(state) {}
    sfmt19937(const sfmt19937&) = default;
    sfmt19937(sfmt19937&&) = default;

    // [0, 2^32-1]
    result_type operator()() {
        return sfmt_genrand_uint32(&state_);
    }

    void seed(result_type s) {
        sfmt_init_gen_rand(&state_, s);
    }

    void discard(unsigned long long n) {
        for (; n != 0ULL; --n) {(*this)();}
    }

    const state_type& getstate() const {return state_;}
    void setstate(const state_type& state) {state_ = state;}

  private:
    state_type state_;
};

class sfmt19937_64 {
  public:
    typedef uint64_t result_type;
    typedef sfmt_t state_type;

    static constexpr result_type min() {return 0U;}
    static constexpr result_type max() {return std::numeric_limits<result_type>::max();}
    static constexpr result_type default_seed = 4321U;

    // constructors
    explicit sfmt19937_64(result_type s=default_seed) {seed(s);}
    explicit sfmt19937_64(const state_type& state): state_(state) {}
    sfmt19937_64(const sfmt19937_64&) = default;
    sfmt19937_64(sfmt19937_64&&) = default;

    // [0, 2^64-1]
    result_type operator()() {
        return sfmt_genrand_uint64(&state_);
    }

    void seed(result_type s) {
        sfmt_init_gen_rand(&state_, static_cast<uint32_t>(s));
    }

    void discard(unsigned long long n) {
        for (; n != 0ULL; --n) {(*this)();}
    }

    const state_type& getstate() const {return state_;}
    void setstate(const state_type& state) {state_ = state;}

  private:
    state_type state_;
};

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

inline sfmt19937& sfmt() {
    static sfmt19937 generator(std::random_device{}());
    return generator;
}

inline sfmt19937_64& sfmt64() {
    static sfmt19937_64 generator(std::random_device{}());
    return generator;
}

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif /* WTL_SFMT_HPP_ */
<|endoftext|>


<commit_before>#pragma once
#include "bits.hpp"
#include <algorithm>
#include <iostream>
#include "optional.hpp"
#include "exception.hpp"

namespace spn {
	//! 任意の型の縦横サイズ
	template <class T>
	struct _Size {
		T	width, height;

		_Size() = default;
		_Size(const T& s): width(s), height(s) {}
		_Size(const T& w, const T& h): width(w), height(h) {}
		template <class T2>
		_Size(const _Size<T2>& s): width(s.width), height(s.height) {}
		_Size& operator *= (const T& s) {
			return *this = *this * s; }
		_Size& operator /= (const T& s) {
			return *this = *this / s; }
		_Size operator / (const T& s) const {
			return _Size(width/s, height/s); }
		_Size operator * (const T& s) const {
			return _Size(width*s, height*s); }
		template <class V>
		void shiftR(int n, typename std::enable_if<std::is_integral<V>::value>::type* = nullptr) {
			width >>= n;
			height >>= n;
		}
		template <class V>
		void shiftR(int n, typename std::enable_if<!std::is_integral<V>::value>::type* = nullptr) { *this *= std::pow(2.f, n); }
		_Size& operator >>= (int n) {
			shiftR<T>(n);
			return *this;
		}
		//! 指定したビット数分、右シフトしてもし値がゼロになったら1をセットする
		void shiftR_one(int n) {
			width >>= n;
			width |= ~Bit::ZeroOrFull(width) & 0x01;
			height >>= n;
			height |= ~Bit::ZeroOrFull(height) & 0x01;
		}
		//! 1右ビットシフトした値を2の累乗に合わせる
		void shiftR_2pow() {
			auto fn = [](const T& t) -> T {
				using UT = std::make_unsigned_t<T>;
				UT ut(t);
				auto v = Bit::LowClear(ut);
				if(v != ut)
					return v;
				return v >> 1;
			};
			width = fn(width);
			height = fn(height);
		}
		bool operator == (const _Size& s) const {
			return width == s.width &&
					height == s.height;
		}
		bool operator != (const _Size& s) const { return !(this->operator == (s)); }
		bool operator <= (const _Size& s) const {
			return width <= s.width &&
					height <= s.height;
		}
		//! 領域の拡大縮小
		/*!
			負数で領域の縮小
			\return		縮小によって面積が0になった場合はtrue, それ以外はfalse
		*/
		bool expand(const T& w, const T& h) {
			bool ret = false;
			width += w;
			height += h;
			if(width <= 0) {
				width = 0;
				ret = true;
			}
			if(height <= 0) {
				height = 0;
				ret = true;
			}
			return ret;
		}
		bool expand(const T& w) {
			return expand(w,w);
		}
		template <class V>
		auto toSize() const {
			return _Size<V>(width, height);
		}
	};
	template <class T>
	std::ostream& operator << (std::ostream& os, const spn::_Size<T>& s) {
		return os << "Size {width=" << s.width << ", height=" << s.height << "}";
	}
	using Size = _Size<int32_t>;
	using SizeF = _Size<float>;

	//! 任意の型の2D矩形
	template <class T>
	class _Rect {
		private:
			template <class E>
			void _checkValidnessT() const {
				if(x1 < x0 ||
					y1 < y0)
					throw E((boost::format("invalid region: x1(%1%)<x0(%2%) or y1(%3%)<y0(%4%)") % x1 % x0 % y1 % y0).str());
			}
		protected:
			void _checkValidness() const {
				#ifdef DEBUG
					_checkValidnessT<ValidationFail>();
				#endif
			}
		public:
			union {
				struct {
					T	x0, x1, y0, y1;
				};
				T	ar[4];
			};

			_Rect() = default;
			_Rect(const _Rect& r) = default;
			_Rect(const T& x_0, const T& x_1, const T& y_0, const T& y_1):
				x0(x_0), x1(x_1), y0(y_0), y1(y_1)
			{
				_checkValidness();
			}

			T width() const {
				_checkValidness();
				return x1-x0;
			}
			T height() const {
				_checkValidness();
				return y1-y0;
			}
			void checkValidness() const {
				_checkValidnessT<ValidationFailRuntime>();
			}
			void addOffset(const T& x, const T& y) {
				_checkValidness();
				x0 += x;
				x1 += x;
				y0 += y;
				y1 += y;
			}
			bool hit(const _Rect& r) const {
				_checkValidness();
				return !(r.x1 <= x0 ||
						r.x0 >= x1 ||
						r.y1 <= y0 ||
						r.y0 >= y1);
			}
			//! 面積
			T area() const {
				return width() * height();
			}
			_Rect move(const T& dx, const T& dy) const {
				return
					_Rect(
						x0 + dx,
						x1 + dx,
						y0 + dy,
						y1 + dy
					);
			}
			void shrinkRight(const T& s) {
				x1 = std::max(x0, x1-s);
			}
			void shrinkBottom(const T& s) {
				y1 = std::max(y0, y1-s);
			}
			void shrinkLeft(const T& s) {
				x0 = std::min(x1, x0+s);
			}
			void shrinkTop(const T& s) {
				y0 = std::min(y1, y0+s);
			}
			_Size<T> size() const {
				return _Size<T>(width(), height());
			}
			#define DEF_OP(op) \
				template <class V> \
				_Rect& operator op##= (const V& t) { \
					return *this = *this op t; } \
				_Rect operator op (const T& t) const { \
					_Rect r; \
					for(int i=0 ; i<int(countof(ar)) ; i++) \
						r.ar[i] = ar[i] op t; \
					return r; \
				} \
				template <class V> \
				_Rect operator op (const _Size<V>& s) const { \
					return {x0 op s.width, x1 op s.width, \
							y0 op s.height, y1 op s.height}; \
				}
			DEF_OP(+)
			DEF_OP(-)
			DEF_OP(*)
			DEF_OP(/)
			#undef DEF_OP

			//! 領域の拡大縮小
			/*!
				負数で領域の縮小
				\return		縮小によって面積が0になった場合はtrue, それ以外はfalse
			*/
			bool expand(const T& w, const T& h) {
				bool ret = false;
				x0 -= w;
				x1 += w;
				y0 -= h;
				y1 += h;
				if(x0 >= x1) {
					auto d = x0 - x1;
					x1 += d/2;
					x0 = x1;
					ret = true;
				}
				if(y0 >= y1) {
					auto d = y0 - y1;
					y1 += d/2;
					y0 = y1;
					ret = true;
				}
				return ret;
			}
			bool expand(const T& w) {
				return expand(w,w);
			}
			template <class V>
			auto toRect() const {
				return _Rect<V>(x0, x1, y0,y1);
			}
			bool operator == (const _Rect& r) const {
				return x0 == r.x0 &&
						x1 == r.x1 &&
						y0 == r.y0 &&
						y1 == r.y1;
			}
			bool operator != (const _Rect& r) const {
				return !(operator == (r));
			}
			//! 重なっている領域を算出
			Optional<_Rect> cross(const _Rect& r) const {
				if(hit(r)) {
					return _Rect(
								std::max(x0, r.x0),
								std::min(x1, r.x1),
								std::max(y0, r.y0),
								std::min(y1, r.y1)
							);
				}
				return spn::none;
			}
	};
	using Rect = _Rect<int32_t>;
	using RectF = _Rect<float>;
	template <class T>
	std::ostream& operator << (std::ostream& os, const spn::_Rect<T>& r) {
		return os << "Rect {x0=" << r.x0 << ", x1=" << r.x1 <<
				", y0=" << r.y0 << ", y1=" << r.y1 << "}";
	}

	//! 値の低い方に補正
	template <class T>
	struct PP_Lower {
		static T proc(const T& t) {
			T ret = spn::Bit::LowClear(t);
			return std::max(T(1), ret);
		}
	};
	//! 値の高い方に補正
	template <class T>
	struct PP_Higher {
		static T proc(const T& t) {
			T ret = spn::Bit::LowClear(t);
			if(t & ~ret)
				ret <<= 1;
			return std::max(T(1), ret);
		}
	};

	//! 2の乗数しか代入できない型
	/*! 0も許可されない */
	template <class T, template <class> class Policy>
	class PowValue {
		using P = Policy<T>;
		T _value;

		public:
			//TODO: テンプレートによる静的な値補正
			PowValue(const T& t): _value(P::proc(t)) {}
			PowValue(const PowValue& p) = default;

			PowValue& operator = (const PowValue& p) = default;
			PowValue& operator = (const T& t) {
				// 2の乗数に補正 (動的なチェック)
				_value = P::proc(t);
				return *this;
			}
			const T& get() const { return _value; }
			operator const T& () const { return _value; }
	};
	using PowInt = PowValue<uint32_t, PP_Higher>;
	using PowSize = _Size<PowInt>;
	template <class... Ts>
	std::ostream& operator << (std::ostream& os, const spn::PowValue<Ts...>& p) {
		return os << p.get();
	}
}
<commit_msg>Rect: operator (Vec2) に対応 Sizeの場合と一緒<commit_after>#pragma once
#include "bits.hpp"
#include <algorithm>
#include <iostream>
#include "optional.hpp"
#include "exception.hpp"
#include "vector.hpp"

namespace spn {
	//! 任意の型の縦横サイズ
	template <class T>
	struct _Size {
		T	width, height;

		_Size() = default;
		_Size(const T& s): width(s), height(s) {}
		_Size(const T& w, const T& h): width(w), height(h) {}
		template <class T2>
		_Size(const _Size<T2>& s): width(s.width), height(s.height) {}
		_Size& operator *= (const T& s) {
			return *this = *this * s; }
		_Size& operator /= (const T& s) {
			return *this = *this / s; }
		_Size operator / (const T& s) const {
			return _Size(width/s, height/s); }
		_Size operator * (const T& s) const {
			return _Size(width*s, height*s); }
		template <class V>
		void shiftR(int n, typename std::enable_if<std::is_integral<V>::value>::type* = nullptr) {
			width >>= n;
			height >>= n;
		}
		template <class V>
		void shiftR(int n, typename std::enable_if<!std::is_integral<V>::value>::type* = nullptr) { *this *= std::pow(2.f, n); }
		_Size& operator >>= (int n) {
			shiftR<T>(n);
			return *this;
		}
		//! 指定したビット数分、右シフトしてもし値がゼロになったら1をセットする
		void shiftR_one(int n) {
			width >>= n;
			width |= ~Bit::ZeroOrFull(width) & 0x01;
			height >>= n;
			height |= ~Bit::ZeroOrFull(height) & 0x01;
		}
		//! 1右ビットシフトした値を2の累乗に合わせる
		void shiftR_2pow() {
			auto fn = [](const T& t) -> T {
				using UT = std::make_unsigned_t<T>;
				UT ut(t);
				auto v = Bit::LowClear(ut);
				if(v != ut)
					return v;
				return v >> 1;
			};
			width = fn(width);
			height = fn(height);
		}
		bool operator == (const _Size& s) const {
			return width == s.width &&
					height == s.height;
		}
		bool operator != (const _Size& s) const { return !(this->operator == (s)); }
		bool operator <= (const _Size& s) const {
			return width <= s.width &&
					height <= s.height;
		}
		//! 領域の拡大縮小
		/*!
			負数で領域の縮小
			\return		縮小によって面積が0になった場合はtrue, それ以外はfalse
		*/
		bool expand(const T& w, const T& h) {
			bool ret = false;
			width += w;
			height += h;
			if(width <= 0) {
				width = 0;
				ret = true;
			}
			if(height <= 0) {
				height = 0;
				ret = true;
			}
			return ret;
		}
		bool expand(const T& w) {
			return expand(w,w);
		}
		template <class V>
		auto toSize() const {
			return _Size<V>(width, height);
		}
	};
	template <class T>
	std::ostream& operator << (std::ostream& os, const spn::_Size<T>& s) {
		return os << "Size {width=" << s.width << ", height=" << s.height << "}";
	}
	using Size = _Size<int32_t>;
	using SizeF = _Size<float>;

	//! 任意の型の2D矩形
	template <class T>
	class _Rect {
		private:
			template <class E>
			void _checkValidnessT() const {
				if(x1 < x0 ||
					y1 < y0)
					throw E((boost::format("invalid region: x1(%1%)<x0(%2%) or y1(%3%)<y0(%4%)") % x1 % x0 % y1 % y0).str());
			}
		protected:
			void _checkValidness() const {
				#ifdef DEBUG
					_checkValidnessT<ValidationFail>();
				#endif
			}
		public:
			union {
				struct {
					T	x0, x1, y0, y1;
				};
				T	ar[4];
			};

			_Rect() = default;
			_Rect(const _Rect& r) = default;
			_Rect(const T& x_0, const T& x_1, const T& y_0, const T& y_1):
				x0(x_0), x1(x_1), y0(y_0), y1(y_1)
			{
				_checkValidness();
			}

			T width() const {
				_checkValidness();
				return x1-x0;
			}
			T height() const {
				_checkValidness();
				return y1-y0;
			}
			void checkValidness() const {
				_checkValidnessT<ValidationFailRuntime>();
			}
			void addOffset(const T& x, const T& y) {
				_checkValidness();
				x0 += x;
				x1 += x;
				y0 += y;
				y1 += y;
			}
			bool hit(const _Rect& r) const {
				_checkValidness();
				return !(r.x1 <= x0 ||
						r.x0 >= x1 ||
						r.y1 <= y0 ||
						r.y0 >= y1);
			}
			//! 面積
			T area() const {
				return width() * height();
			}
			_Rect move(const T& dx, const T& dy) const {
				return
					_Rect(
						x0 + dx,
						x1 + dx,
						y0 + dy,
						y1 + dy
					);
			}
			void shrinkRight(const T& s) {
				x1 = std::max(x0, x1-s);
			}
			void shrinkBottom(const T& s) {
				y1 = std::max(y0, y1-s);
			}
			void shrinkLeft(const T& s) {
				x0 = std::min(x1, x0+s);
			}
			void shrinkTop(const T& s) {
				y0 = std::min(y1, y0+s);
			}
			_Size<T> size() const {
				return _Size<T>(width(), height());
			}
			#define DEF_OP(op) \
				template <class V> \
				_Rect& operator op##= (const V& t) { \
					return *this = *this op t; } \
				_Rect operator op (const T& t) const { \
					_Rect r; \
					for(int i=0 ; i<int(countof(ar)) ; i++) \
						r.ar[i] = ar[i] op t; \
					return r; \
				} \
				_Rect operator op (const Vec2& v) const { \
					return *this op _Size<T>{v.x, v.y}; \
				} \
				template <class V> \
				_Rect operator op (const _Size<V>& s) const { \
					return {x0 op s.width, x1 op s.width, \
							y0 op s.height, y1 op s.height}; \
				}
			DEF_OP(+)
			DEF_OP(-)
			DEF_OP(*)
			DEF_OP(/)
			#undef DEF_OP

			//! 領域の拡大縮小
			/*!
				負数で領域の縮小
				\return		縮小によって面積が0になった場合はtrue, それ以外はfalse
			*/
			bool expand(const T& w, const T& h) {
				bool ret = false;
				x0 -= w;
				x1 += w;
				y0 -= h;
				y1 += h;
				if(x0 >= x1) {
					auto d = x0 - x1;
					x1 += d/2;
					x0 = x1;
					ret = true;
				}
				if(y0 >= y1) {
					auto d = y0 - y1;
					y1 += d/2;
					y0 = y1;
					ret = true;
				}
				return ret;
			}
			bool expand(const T& w) {
				return expand(w,w);
			}
			template <class V>
			auto toRect() const {
				return _Rect<V>(x0, x1, y0,y1);
			}
			bool operator == (const _Rect& r) const {
				return x0 == r.x0 &&
						x1 == r.x1 &&
						y0 == r.y0 &&
						y1 == r.y1;
			}
			bool operator != (const _Rect& r) const {
				return !(operator == (r));
			}
			//! 重なっている領域を算出
			Optional<_Rect> cross(const _Rect& r) const {
				if(hit(r)) {
					return _Rect(
								std::max(x0, r.x0),
								std::min(x1, r.x1),
								std::max(y0, r.y0),
								std::min(y1, r.y1)
							);
				}
				return spn::none;
			}
	};
	using Rect = _Rect<int32_t>;
	using RectF = _Rect<float>;
	template <class T>
	std::ostream& operator << (std::ostream& os, const spn::_Rect<T>& r) {
		return os << "Rect {x0=" << r.x0 << ", x1=" << r.x1 <<
				", y0=" << r.y0 << ", y1=" << r.y1 << "}";
	}

	//! 値の低い方に補正
	template <class T>
	struct PP_Lower {
		static T proc(const T& t) {
			T ret = spn::Bit::LowClear(t);
			return std::max(T(1), ret);
		}
	};
	//! 値の高い方に補正
	template <class T>
	struct PP_Higher {
		static T proc(const T& t) {
			T ret = spn::Bit::LowClear(t);
			if(t & ~ret)
				ret <<= 1;
			return std::max(T(1), ret);
		}
	};

	//! 2の乗数しか代入できない型
	/*! 0も許可されない */
	template <class T, template <class> class Policy>
	class PowValue {
		using P = Policy<T>;
		T _value;

		public:
			//TODO: テンプレートによる静的な値補正
			PowValue(const T& t): _value(P::proc(t)) {}
			PowValue(const PowValue& p) = default;

			PowValue& operator = (const PowValue& p) = default;
			PowValue& operator = (const T& t) {
				// 2の乗数に補正 (動的なチェック)
				_value = P::proc(t);
				return *this;
			}
			const T& get() const { return _value; }
			operator const T& () const { return _value; }
	};
	using PowInt = PowValue<uint32_t, PP_Higher>;
	using PowSize = _Size<PowInt>;
	template <class... Ts>
	std::ostream& operator << (std::ostream& os, const spn::PowValue<Ts...>& p) {
		return os << p.get();
	}
}
<|endoftext|>