<commit_before>#include "core/polarcoord.h"

#include "core/numeric.h"
#include "core/range.h"
#include "core/assert.h"
#include "core/random.h"

namespace euphoria::core
{
    PolarCoord::PolarCoord(float azimuthal01, float polar01)
        : azimuthal(Angle::FromPercentOf360(azimuthal01))
        , polar(Angle::FromPercentOf180(polar01))
    {
        ASSERT(IsWithin(R01(), azimuthal01));
        ASSERT(IsWithin(R01(), polar01));
    }

    unit3f
    PolarCoord::ToUnitVector() const
    {
        const float cos_a = Cos(azimuthal);
        const float sin_p = Sin(polar);
        const float sin_a = Sin(azimuthal);
        const float cos_p = Cos(polar);

        const float x = cos_a * sin_p;
        const float y = sin_a * sin_p;
        const float z = cos_p;

        return unit3f::ToUnit(x, y, z);
    }

    PolarCoord
    PolarCoord::Random(::euphoria::core::Random* random)
    {
        const float az    = random->NextFloat01();
        const float polar = random->NextFloat01();
        return {az, polar};
    }

    unit3f
    RandomUnit3(Random* random)
    {
        return PolarCoord::Random(random).ToUnitVector();
    }

}  // namespace euphoria::core
<commit_msg>fixed assert<commit_after>#include "core/polarcoord.h"

#include "core/numeric.h"
#include "core/range.h"
#include "core/assert.h"
#include "core/random.h"

namespace euphoria::core
{
    PolarCoord::PolarCoord(float azimuthal01, float polar01)
        : azimuthal(Angle::FromPercentOf360(azimuthal01))
        , polar(Angle::FromPercentOf180(polar01))
    {
        ASSERT(IsWithin(R01(), azimuthal01));
        ASSERT(IsWithin(Range<float>{0,2}, polar01));
    }

    unit3f
    PolarCoord::ToUnitVector() const
    {
        const float cos_a = Cos(azimuthal);
        const float sin_p = Sin(polar);
        const float sin_a = Sin(azimuthal);
        const float cos_p = Cos(polar);

        const float x = cos_a * sin_p;
        const float y = sin_a * sin_p;
        const float z = cos_p;

        return unit3f::ToUnit(x, y, z);
    }

    PolarCoord
    PolarCoord::Random(::euphoria::core::Random* random)
    {
        const float az    = random->NextFloat01();
        const float polar = random->NextFloat01();
        return {az, polar};
    }

    unit3f
    RandomUnit3(Random* random)
    {
        return PolarCoord::Random(random).ToUnitVector();
    }

}  // namespace euphoria::core
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "scannerpluginmanager.h"

#include <logging/logger.h>
#include <tools/hostosinfo.h>

#include <QCoreApplication>
#include <QDirIterator>
#include <QLibrary>

namespace qbs {
namespace Internal {

ScannerPluginManager *ScannerPluginManager::instance()
{
    static ScannerPluginManager *i = new ScannerPluginManager;
    return i;
}

ScannerPluginManager::ScannerPluginManager()
{
}

QList<ScannerPlugin *> ScannerPluginManager::scannersForFileTag(const FileTag &fileTag)
{
    return instance()->m_scannerPlugins.value(fileTag);
}

void ScannerPluginManager::loadPlugins(const QStringList &pluginPaths, const Logger &logger)
{
    QStringList filters;

    if (HostOsInfo::isWindowsHost())
        filters << "*.dll";
    else if (HostOsInfo::isOsxHost())
        filters << "*.dylib";
    else
        filters << "*.so";

    foreach (const QString &pluginPath, pluginPaths) {
        logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: loading plugins from '%1'.")
                             .arg(QDir::toNativeSeparators(pluginPath));
        QDirIterator it(pluginPath, filters, QDir::Files);
        while (it.hasNext()) {
            const QString fileName = it.next();
            QScopedPointer<QLibrary> lib(new QLibrary(fileName));
            if (!lib->load()) {
                logger.qbsWarning() << QString::fromLocal8Bit("pluginmanager: couldn't load plugin '%1'.")
                                       .arg(QDir::toNativeSeparators(fileName));
                continue;
            }

            getScanners_f getScanners = reinterpret_cast<getScanners_f>(lib->resolve("getScanners"));
            if (!getScanners) {
                logger.qbsWarning() << QString::fromLocal8Bit("pluginmanager: couldn't resolve "
                        "symbol in '%1'.").arg(QDir::toNativeSeparators(fileName));
                continue;
            }

            ScannerPlugin **plugins = getScanners();
            if (plugins == 0) {
                logger.qbsWarning() << QString::fromLocal8Bit("pluginmanager: no scanners "
                        "returned from '%1'.").arg(QDir::toNativeSeparators(fileName));
                continue;
            }

            logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: scanner plugin '%1' "
                    "loaded.").arg(QDir::toNativeSeparators(fileName));

            for (int i = 0; plugins[i] != 0; ++i)
                m_scannerPlugins[FileTag(plugins[i]->fileTag)] += plugins[i];
            m_libs.append(lib.take());
        }
    }
}

} // namespace Internal
} // namespace qbs
<commit_msg>use tr in scanner plugin manager<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "scannerpluginmanager.h"

#include <logging/logger.h>
#include <logging/translator.h>
#include <tools/hostosinfo.h>

#include <QCoreApplication>
#include <QDirIterator>
#include <QLibrary>

namespace qbs {
namespace Internal {

ScannerPluginManager *ScannerPluginManager::instance()
{
    static ScannerPluginManager *i = new ScannerPluginManager;
    return i;
}

ScannerPluginManager::ScannerPluginManager()
{
}

QList<ScannerPlugin *> ScannerPluginManager::scannersForFileTag(const FileTag &fileTag)
{
    return instance()->m_scannerPlugins.value(fileTag);
}

void ScannerPluginManager::loadPlugins(const QStringList &pluginPaths, const Logger &logger)
{
    QStringList filters;

    if (HostOsInfo::isWindowsHost())
        filters << "*.dll";
    else if (HostOsInfo::isOsxHost())
        filters << "*.dylib";
    else
        filters << "*.so";

    foreach (const QString &pluginPath, pluginPaths) {
        logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: loading plugins from '%1'.")
                             .arg(QDir::toNativeSeparators(pluginPath));
        QDirIterator it(pluginPath, filters, QDir::Files);
        while (it.hasNext()) {
            const QString fileName = it.next();
            QScopedPointer<QLibrary> lib(new QLibrary(fileName));
            if (!lib->load()) {
                logger.qbsWarning() << Tr::tr("pluginmanager: couldn't load plugin '%1'.")
                                       .arg(QDir::toNativeSeparators(fileName));
                continue;
            }

            getScanners_f getScanners = reinterpret_cast<getScanners_f>(lib->resolve("getScanners"));
            if (!getScanners) {
                logger.qbsWarning() << Tr::tr("pluginmanager: couldn't resolve "
                        "symbol in '%1'.").arg(QDir::toNativeSeparators(fileName));
                continue;
            }

            ScannerPlugin **plugins = getScanners();
            if (plugins == 0) {
                logger.qbsWarning() << Tr::tr("pluginmanager: no scanners "
                        "returned from '%1'.").arg(QDir::toNativeSeparators(fileName));
                continue;
            }

            logger.qbsTrace() << QString::fromLocal8Bit("pluginmanager: scanner plugin '%1' "
                    "loaded.").arg(QDir::toNativeSeparators(fileName));

            for (int i = 0; plugins[i] != 0; ++i)
                m_scannerPlugins[FileTag(plugins[i]->fileTag)] += plugins[i];
            m_libs.append(lib.take());
        }
    }
}

} // namespace Internal
} // namespace qbs
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef MTAC_OPERATOR_H
#define MTAC_OPERATOR_H

#include "ast/Operator.hpp"

namespace eddic {

namespace mtac {

enum class Operator : unsigned int {
    /* Assignment operators  */
    ASSIGN,
    FASSIGN,
    PASSIGN,

    /* Integer operators */
    ADD,
    SUB,
    MUL,
    DIV,
    MOD,

    /* Float operators  */
    FADD,
    FSUB,
    FMUL,
    FDIV,

    /* relational operators for expressions */
    EQUALS,
    NOT_EQUALS,
    GREATER,
    GREATER_EQUALS,
    LESS,
    LESS_EQUALS,

    /* Operators for If */

    IF_UNARY,

    /* relational operators */
    IF_EQUALS,
    IF_NOT_EQUALS,
    IF_GREATER,
    IF_GREATER_EQUALS,
    IF_LESS,
    IF_LESS_EQUALS,

    /* float relational operators */
    IF_FE,
    IF_FNE,
    IF_FG,
    IF_FGE,
    IF_FLE,
    IF_FL,

    /* Operators for IfFalse */

    IF_FALSE_UNARY,

    /* relational operators */
    IF_FALSE_EQUALS,
    IF_FALSE_NOT_EQUALS,
    IF_FALSE_GREATER,
    IF_FALSE_GREATER_EQUALS,
    IF_FALSE_LESS,
    IF_FALSE_LESS_EQUALS,

    /* float relational operators */
    IF_FALSE_FE,
    IF_FALSE_FNE,
    IF_FALSE_FG,
    IF_FALSE_FGE,
    IF_FALSE_FLE,
    IF_FALSE_FL,

    /* boolean operators */
    NOT,
    AND,

    /* float relational operators */
    FE,
    FNE,
    FG,
    FGE,
    FLE,
    FL,

    MINUS,          //result = -arg1
    FMINUS,         //result = -arg1

    I2F,            //result = (float) arg1
    F2I,            //result = (int) arg1

    DOT,            //result = (arg1)+arg2
    FDOT,           //result = (arg1)+arg2
    PDOT,           //result = address of arg1 + arg2

    DOT_ASSIGN,     //result+arg1=arg2
    DOT_FASSIGN,    //result+arg1=arg2
    DOT_PASSIGN,    //result+arg1=arg2

    GOTO,           //jump to a basic block (label in arg1)

    RETURN,         //return from a function

    NOP,            //for optimization purpose

    PARAM,          //for parameter passing
    PPARAM,         //for parameter passing by address

    CALL,           //call functions

    LABEL           //label in arg1
};

mtac::Operator toOperator(ast::Operator op);
mtac::Operator toFloatOperator(ast::Operator op);

mtac::Operator toRelationalOperator(ast::Operator op);
mtac::Operator toFloatRelationalOperator(ast::Operator op);

} //end of mtac

} //end of eddic

#endif
<commit_msg>Some doc<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2016.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef MTAC_OPERATOR_H
#define MTAC_OPERATOR_H

#include "ast/Operator.hpp"

namespace eddic {

namespace mtac {

/*!
 * \brief Type of operator in MTAC
 */
enum class Operator : unsigned int {
  ASSIGN,  ///< Assign
  FASSIGN, ///< Float assign
  PASSIGN, ///< Pointer assign

  /* Integer operators */
  ADD,
  SUB,
  MUL,
  DIV,
  MOD,

  /* Float operators  */
  FADD,
  FSUB,
  FMUL,
  FDIV,

  /* relational operators for expressions */
  EQUALS,
  NOT_EQUALS,
  GREATER,
  GREATER_EQUALS,
  LESS,
  LESS_EQUALS,

  /* Operators for If */

  IF_UNARY,

  /* relational operators */
  IF_EQUALS,
  IF_NOT_EQUALS,
  IF_GREATER,
  IF_GREATER_EQUALS,
  IF_LESS,
  IF_LESS_EQUALS,

  /* float relational operators */
  IF_FE,
  IF_FNE,
  IF_FG,
  IF_FGE,
  IF_FLE,
  IF_FL,

  /* Operators for IfFalse */

  IF_FALSE_UNARY,

  /* relational operators */
  IF_FALSE_EQUALS,
  IF_FALSE_NOT_EQUALS,
  IF_FALSE_GREATER,
  IF_FALSE_GREATER_EQUALS,
  IF_FALSE_LESS,
  IF_FALSE_LESS_EQUALS,

  /* float relational operators */
  IF_FALSE_FE,
  IF_FALSE_FNE,
  IF_FALSE_FG,
  IF_FALSE_FGE,
  IF_FALSE_FLE,
  IF_FALSE_FL,

  /* boolean operators */
  NOT,
  AND,

  /* float relational operators */
  FE,
  FNE,
  FG,
  FGE,
  FLE,
  FL,

  MINUS, // result = -arg1
  FMINUS, // result = -arg1

  I2F, // result = (float) arg1
  F2I, // result = (int) arg1

  DOT, // result = (arg1)+arg2
  FDOT, // result = (arg1)+arg2
  PDOT, // result = address of arg1 + arg2

  DOT_ASSIGN, // result+arg1=arg2
  DOT_FASSIGN, // result+arg1=arg2
  DOT_PASSIGN, // result+arg1=arg2

  GOTO, // jump to a basic block (label in arg1)

  RETURN, // return from a function

  NOP, // for optimization purpose

  PARAM, // for parameter passing
  PPARAM, // for parameter passing by address

  CALL, // call functions

  LABEL // label in arg1
};

mtac::Operator toOperator(ast::Operator op);
mtac::Operator toFloatOperator(ast::Operator op);

mtac::Operator toRelationalOperator(ast::Operator op);
mtac::Operator toFloatRelationalOperator(ast::Operator op);

} //end of mtac

} //end of eddic

#endif
<|endoftext|>


<commit_before>#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <assert.h>

#include <vector>
#include <string>

using namespace std;

#include "Coordinate.h"
#include "potions.h"
#include "scrolls.h"
#include "io.h"
#include "armor.h"
#include "pack.h"
#include "rings.h"
#include "misc.h"
#include "level.h"
#include "player.h"
#include "weapons.h"
#include "wand.h"
#include "os.h"
#include "options.h"
#include "rogue.h"

#include "things.h"

/* Only oi_prob is used */
vector<obj_info> things = {
/*   oi_name oi_prob oi_worth oi_guess oi_know */
    { "potion",	26,	0,	"",	false },
    { "scroll",	36,	0,	"",	false },
    { "food",	16,	0,	"",	false },
    { "weapon",	 7,	0,	"",	false },
    { "armor",	 7,	0,	"",	false },
    { "ring",	 4,	0,	"",	false },
    { "stick",	 4,	0,	"",	false },
};

char*
inv_name(char* buf, Item const* item, bool drop)
{
  buf[MAXSTR -1] = '\0';
  switch (item->o_type)
  {
    case POTION: potion_description(item, buf); break;
    case RING:   ring_description(item, buf); break;
    case STICK:  wand_description(item, buf); break;
    case SCROLL: scroll_description(item, buf); break;
    case WEAPON: case AMMO: weapon_description(item, buf); break;
    case ARMOR:  armor_description(item, buf); break;
    case FOOD:
    {
      char const* obj_type = item->o_which == 1 ? "fruit" : "food ration";
      if (item->o_count == 1)
        sprintf(buf, "A %s", obj_type);
      else
        sprintf(buf, "%d %ss", item->o_count, obj_type);
    }
    break;
    case AMULET: strcpy(buf, "The Amulet of Yendor"); break;
    case GOLD:   sprintf(buf, "%d Gold pieces", item->o_goldval); break;
    default:
      io_msg("You feel a disturbance in the force");
      sprintf(buf, "Something bizarre %s", unctrl(static_cast<chtype>(item->o_type)));
      break;
  }

  buf[0] = static_cast<char>(drop ? tolower(buf[0]) : toupper(buf[0]));
  assert (buf[MAXSTR -1] == '\0');
  return buf;
}

Item*
new_food(int which)
{
  /* Reset levels-without-food counter */
  levels_without_food = 0;

  Item* cur = new Item();
  cur->o_count = 1;
  cur->o_type = FOOD;
  switch (which)
  {
    case 0: case 1: cur->o_which = which; break;
    default: cur->o_which = os_rand_range(10) ? 0 : 1; break;
  }
  return cur;
}

Item*
new_amulet(void)
{
  Item* obj       = new Item();
  obj->o_damage  = {1, 2};
  obj->o_hurldmg = {1, 2};
  obj->o_type    = AMULET;

  return obj;
}

Item*
new_thing(void)
{
  /* Decide what kind of object it will be
   * If we haven't had food for a while, let it be food. */
  int r;
  if (levels_without_food > 3)
    r = 2;
  else
    r = static_cast<int>(pick_one(things, things.size()));

  Item* cur = nullptr;
  switch (r)
  {
    case 0: cur = potion_create(-1); break;
    case 1: cur = scroll_create(-1); break;
    case 2: cur = new_food(-1); break;
    case 3: cur = weapon_create(-1, true); break;
    case 4: cur = armor_create(-1, true); break;
    case 5: cur = ring_create(-1, true); break;
    case 6: cur = wand_create(-1); break;
    default:
      io_msg("Picked a bad kind of object (this should not happen)");
      io_wait_for_key(KEY_SPACE);
      break;
  }

  assert(cur != nullptr);
  assert(cur->o_damage.sides >= 0 && cur->o_damage.dices >= 0);
  assert(cur->o_hurldmg.sides >= 0 && cur->o_hurldmg.dices >= 0);
  return cur;
}

size_t
pick_one(vector<obj_info>& start, size_t nitems)
{
  for (size_t rand = static_cast<size_t>(os_rand_range(100)), i = 0; i < nitems; ++i)
    if (rand < start.at(i).oi_prob)
      return i;
    else
      rand -= start.at(i).oi_prob;

  /* The functions should have returned by now */
  throw range_error("Probability was not in range");
}

/* list what the player has discovered of this type */
static void
discovered_by_type(char type, vector<obj_info>& info, size_t max_items)
{
  WINDOW *printscr = dupwin(stdscr);

  Coordinate orig_pos;
  getyx(stdscr, orig_pos.y, orig_pos.x);

  Item printable_object;
  memset(&printable_object, 0, sizeof(printable_object));
  printable_object.o_type = type;
  printable_object.o_flags = 0;
  printable_object.o_count = 1;

  int items_found = 0;
  for (size_t i = 0; i < max_items; ++i)
    if (info.at(i).oi_know || !info.at(i).oi_guess.empty())
    {
      char buf[MAXSTR];
      printable_object.o_which = static_cast<int>(i);
      mvwprintw(printscr, ++items_found, 1,
                "%s", inv_name(buf, &printable_object, false));
    }

  if (items_found == 0)
  {
    char const* type_as_str = nullptr;
    switch (type)
    {
      case POTION: type_as_str = "potion"; break;
      case SCROLL: type_as_str = "scroll"; break;
      case RING:   type_as_str = "ring"; break;
      case STICK:  type_as_str = "stick"; break;
    }
    mvwprintw(printscr, 1, 1, "No known %s", type_as_str);
  }

  move(orig_pos.y, orig_pos.x);
  wrefresh(printscr);
  delwin(printscr);
}

void
discovered(void)
{
  io_msg("for what type of objects do you want a list? (%c%c%c%c) ",
      POTION, SCROLL, RING, STICK);
  while (true)
  {
    char ch = io_readchar(true);
    touchwin(stdscr);
    refresh();
    switch (ch)
    {
      case POTION: discovered_by_type(ch, potion_info, NPOTIONS); break;
      case SCROLL: discovered_by_type(ch, scroll_info, NSCROLLS); break;
      case RING: discovered_by_type(ch, ring_info, NRINGS); break;
      case STICK: discovered_by_type(ch, wands_info, MAXSTICKS); break;
      default: io_msg_clear(); return;
    }
  }

  touchwin(stdscr);
  io_msg_clear();
}

<commit_msg>remove C headers<commit_after>#include <vector>
#include <string>

using namespace std;

#include "Coordinate.h"
#include "potions.h"
#include "scrolls.h"
#include "io.h"
#include "armor.h"
#include "pack.h"
#include "rings.h"
#include "misc.h"
#include "level.h"
#include "player.h"
#include "weapons.h"
#include "wand.h"
#include "os.h"
#include "options.h"
#include "rogue.h"

#include "things.h"

/* Only oi_prob is used */
vector<obj_info> things = {
/*   oi_name oi_prob oi_worth oi_guess oi_know */
    { "potion",	26,	0,	"",	false },
    { "scroll",	36,	0,	"",	false },
    { "food",	16,	0,	"",	false },
    { "weapon",	 7,	0,	"",	false },
    { "armor",	 7,	0,	"",	false },
    { "ring",	 4,	0,	"",	false },
    { "stick",	 4,	0,	"",	false },
};

char*
inv_name(char* buf, Item const* item, bool drop)
{
  buf[MAXSTR -1] = '\0';
  switch (item->o_type)
  {
    case POTION: potion_description(item, buf); break;
    case RING:   ring_description(item, buf); break;
    case STICK:  wand_description(item, buf); break;
    case SCROLL: scroll_description(item, buf); break;
    case WEAPON: case AMMO: weapon_description(item, buf); break;
    case ARMOR:  armor_description(item, buf); break;
    case FOOD:
    {
      char const* obj_type = item->o_which == 1 ? "fruit" : "food ration";
      if (item->o_count == 1)
        sprintf(buf, "A %s", obj_type);
      else
        sprintf(buf, "%d %ss", item->o_count, obj_type);
    }
    break;
    case AMULET: strcpy(buf, "The Amulet of Yendor"); break;
    case GOLD:   sprintf(buf, "%d Gold pieces", item->o_goldval); break;
    default:
      io_msg("You feel a disturbance in the force");
      sprintf(buf, "Something bizarre %s", unctrl(static_cast<chtype>(item->o_type)));
      break;
  }

  buf[0] = static_cast<char>(drop ? tolower(buf[0]) : toupper(buf[0]));
  if (buf[MAXSTR -1] != '\0')
    throw runtime_error("Buffer no null-terminated");
  return buf;
}

Item*
new_food(int which)
{
  /* Reset levels-without-food counter */
  levels_without_food = 0;

  Item* cur = new Item();
  cur->o_count = 1;
  cur->o_type = FOOD;
  switch (which)
  {
    case 0: case 1: cur->o_which = which; break;
    default: cur->o_which = os_rand_range(10) ? 0 : 1; break;
  }
  return cur;
}

Item*
new_amulet(void)
{
  Item* obj       = new Item();
  obj->o_damage  = {1, 2};
  obj->o_hurldmg = {1, 2};
  obj->o_type    = AMULET;

  return obj;
}

Item*
new_thing(void)
{
  /* Decide what kind of object it will be
   * If we haven't had food for a while, let it be food. */
  int r;
  if (levels_without_food > 3)
    r = 2;
  else
    r = static_cast<int>(pick_one(things, things.size()));

  Item* cur = nullptr;
  switch (r)
  {
    case 0: cur = potion_create(-1); break;
    case 1: cur = scroll_create(-1); break;
    case 2: cur = new_food(-1); break;
    case 3: cur = weapon_create(-1, true); break;
    case 4: cur = armor_create(-1, true); break;
    case 5: cur = ring_create(-1, true); break;
    case 6: cur = wand_create(-1); break;
    default:
      io_msg("Picked a bad kind of object (this should not happen)");
      io_wait_for_key(KEY_SPACE);
      break;
  }

  if (cur == nullptr) {
    throw runtime_error("curr is null");
  }
  if (cur->o_damage.sides < 0 || cur->o_damage.dices < 0) {
    throw runtime_error("cur->damage is negative");
  }
  if (cur->o_hurldmg.sides < 0 || cur->o_hurldmg.dices < 0) {
    throw runtime_error("cur->hurldmg is negative");
  }
  return cur;
}

size_t
pick_one(vector<obj_info>& start, size_t nitems)
{
  for (size_t rand = static_cast<size_t>(os_rand_range(100)), i = 0; i < nitems; ++i)
    if (rand < start.at(i).oi_prob)
      return i;
    else
      rand -= start.at(i).oi_prob;

  /* The functions should have returned by now */
  throw range_error("Probability was not in range");
}

/* list what the player has discovered of this type */
static void
discovered_by_type(char type, vector<obj_info>& info, size_t max_items)
{
  WINDOW *printscr = dupwin(stdscr);

  Coordinate orig_pos;
  getyx(stdscr, orig_pos.y, orig_pos.x);

  Item printable_object;
  memset(&printable_object, 0, sizeof(printable_object));
  printable_object.o_type = type;
  printable_object.o_flags = 0;
  printable_object.o_count = 1;

  int items_found = 0;
  for (size_t i = 0; i < max_items; ++i)
    if (info.at(i).oi_know || !info.at(i).oi_guess.empty())
    {
      char buf[MAXSTR];
      printable_object.o_which = static_cast<int>(i);
      mvwprintw(printscr, ++items_found, 1,
                "%s", inv_name(buf, &printable_object, false));
    }

  if (items_found == 0)
  {
    char const* type_as_str = nullptr;
    switch (type)
    {
      case POTION: type_as_str = "potion"; break;
      case SCROLL: type_as_str = "scroll"; break;
      case RING:   type_as_str = "ring"; break;
      case STICK:  type_as_str = "stick"; break;
    }
    mvwprintw(printscr, 1, 1, "No known %s", type_as_str);
  }

  move(orig_pos.y, orig_pos.x);
  wrefresh(printscr);
  delwin(printscr);
}

void
discovered(void)
{
  io_msg("for what type of objects do you want a list? (%c%c%c%c) ",
      POTION, SCROLL, RING, STICK);
  while (true)
  {
    char ch = io_readchar(true);
    touchwin(stdscr);
    refresh();
    switch (ch)
    {
      case POTION: discovered_by_type(ch, potion_info, NPOTIONS); break;
      case SCROLL: discovered_by_type(ch, scroll_info, NSCROLLS); break;
      case RING: discovered_by_type(ch, ring_info, NRINGS); break;
      case STICK: discovered_by_type(ch, wands_info, MAXSTICKS); break;
      default: io_msg_clear(); return;
    }
  }

  touchwin(stdscr);
  io_msg_clear();
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#pragma once

#include <atomic>                // for std::atomic_bool
#include <chrono>                // for std::chrono
#include <future>                // for std::future, std::promise

using namespace std::chrono_literals;

enum class ThreadPolicyType {
	regular,
	wal_writer,
	logging,
	replication,
	committers,
	fsynchers,
	updaters,
	http_servers,
	binary_servers,
	http_clients,
	binary_clients,
};

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

int sched_getcpu();

void run_thread(void *(*thread_routine)(void *), void *arg, ThreadPolicyType thread_policy);
void setup_thread(const std::string& name, ThreadPolicyType thread_policy);

void set_thread_name(const std::string& name);

const std::string& get_thread_name(std::thread::id thread_id);

const std::string& get_thread_name();

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

template <typename ThreadImpl, ThreadPolicyType thread_policy>
class Thread {
	std::promise<void> _promise;
	std::future<void> _future;

	std::atomic_bool _running;
	std::atomic_bool _joined;

	static void* _runner(void* arg) {
		auto thread_impl = static_cast<ThreadImpl*>(arg);
		auto thread = static_cast<Thread*>(thread_impl);
		setup_thread(thread_impl->name(), thread_policy);
		try {
			thread_impl->operator()();
			thread->_running = false;
			try {
				// fulfill the promise
				thread->_promise.set_value();
			} catch(...) {} // set_value() may throw
		} catch (...) {
			thread->_running = false;
			try {
				// store anything thrown in the promise
				thread->_promise.set_exception(std::current_exception());
			} catch(...) {} // set_exception() may throw too
		}
		return nullptr;
	}

public:
	Thread() :
		_future{_promise.get_future()},
		_running{false},
		_joined{false}
	{}

	Thread(Thread&& other) :
		_promise{std::move(other._promise)},
		_future{std::move(other._future)},
		_running{other._running.load()},
		_joined{other._joined.load()}
	{}

	Thread& operator=(Thread&& other) {
		_promise = std::move(other._promise);
		_future = std::move(other._future);
		_running = other._running.load();
		_joined = other._joined.load();
		return *this;
	}

	void run() {
		if (!_running.exchange(true)) {
			_joined = false;
			run_thread(&Thread::_runner, static_cast<ThreadImpl*>(this), thread_policy);
		}
	}

	bool join(const std::chrono::time_point<std::chrono::system_clock>& wakeup) {
		if (!_joined && _running) {
			std::future_status status;
			do {
				status = _future.wait_until(wakeup);
				if (status == std::future_status::timeout) {
					if (_running) {
						return false;
					}
					_joined = true;
					return true;
				}
			} while (status != std::future_status::ready);
			if (!_joined.exchange(true)) {
				_future.get(); // rethrow any exceptions
			}
		}
		return true;
	}

	bool join(std::chrono::milliseconds timeout = 60s) {
		return join(std::chrono::system_clock::now() + timeout);
	}
};
<commit_msg>Thread: join() thread during Thread object destruction<commit_after>/*
 * Copyright (C) 2015-2018 Dubalu LLC. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#pragma once

#include <atomic>                // for std::atomic_bool
#include <chrono>                // for std::chrono
#include <future>                // for std::future, std::promise

using namespace std::chrono_literals;

enum class ThreadPolicyType {
	regular,
	wal_writer,
	logging,
	replication,
	committers,
	fsynchers,
	updaters,
	http_servers,
	binary_servers,
	http_clients,
	binary_clients,
};

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

int sched_getcpu();

void run_thread(void *(*thread_routine)(void *), void *arg, ThreadPolicyType thread_policy);
void setup_thread(const std::string& name, ThreadPolicyType thread_policy);

void set_thread_name(const std::string& name);

const std::string& get_thread_name(std::thread::id thread_id);

const std::string& get_thread_name();

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

template <typename ThreadImpl, ThreadPolicyType thread_policy>
class Thread {
	std::promise<void> _promise;
	std::future<void> _future;

	std::atomic_bool _running;
	std::atomic_bool _joined;

	static void* _runner(void* arg) {
		auto thread_impl = static_cast<ThreadImpl*>(arg);
		auto thread = static_cast<Thread*>(thread_impl);
		setup_thread(thread_impl->name(), thread_policy);
		try {
			thread_impl->operator()();
			thread->_running = false;
			try {
				// fulfill the promise
				thread->_promise.set_value();
			} catch(...) {} // set_value() may throw
		} catch (...) {
			thread->_running = false;
			try {
				// store anything thrown in the promise
				thread->_promise.set_exception(std::current_exception());
			} catch(...) {} // set_exception() may throw too
		}
		return nullptr;
	}

public:
	Thread() :
		_future{_promise.get_future()},
		_running{false},
		_joined{false} {}

	~Thread() noexcept {
		try {
			join();
		} catch (...) {}
	}

	Thread(Thread&& other) :
		_promise{std::move(other._promise)},
		_future{std::move(other._future)},
		_running{other._running.load()},
		_joined{other._joined.load()} {}

	Thread& operator=(Thread&& other) {
		_promise = std::move(other._promise);
		_future = std::move(other._future);
		_running = other._running.load();
		_joined = other._joined.load();
		return *this;
	}

	void run() {
		if (!_running.exchange(true)) {
			_joined = false;
			run_thread(&Thread::_runner, static_cast<ThreadImpl*>(this), thread_policy);
		}
	}

	bool join(const std::chrono::time_point<std::chrono::system_clock>& wakeup) {
		if (!_joined && _running) {
			std::future_status status;
			do {
				status = _future.wait_until(wakeup);
				if (status == std::future_status::timeout) {
					if (_running) {
						return false;
					}
					_joined = true;
					return true;
				}
			} while (status != std::future_status::ready);
			if (!_joined.exchange(true)) {
				_future.get(); // rethrow any exceptions
			}
		}
		return true;
	}

	bool join(std::chrono::milliseconds timeout = 60s) {
		return join(std::chrono::system_clock::now() + timeout);
	}
};
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2016      Los Alamos National Security, LLC
 *                         All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * LA-CC 10-123
 */

//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra     (dongarra@eecs.utk.edu)
// Piotr Luszczek    (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER

/*!
 @file GenerateProblem_ref.hpp

 HPCG routine
 */

#pragma once

#include "hpcg.hpp"
#include "LegionItems.hpp"
#include "LegionArrays.hpp"
#include "LegionMatrices.hpp"
// For STL serialization into regions.
#include "cereal/archives/binary.hpp"
#include "cereal/types/vector.hpp"

#include <sstream>
#include <cassert>

// TODO RM
#define HPCG_NO_MPI

/*!
    Reference version of GenerateProblem to generate the sparse matrix, right
    hand side, initial guess, and exact solution.

    @param[in]  A        The known system matrix
    @param[inout] b      The newly allocated and generated right hand side
    vector (if b!=0 on entry)
    @param[inout] x      The newly allocated solution vector with entries set to
    0.0 (if x!=0 on entry)
    @param[inout] xexact The newly allocated solution vector with entries set to
    the exact solution (if the xexact!=0 non-zero on entry)

    @see GenerateGeometry
*/
inline void
GenerateProblem(
    SparseMatrix &A,
    Array<floatType> *b,
    Array<floatType> *x,
    Array<floatType> *xexact,
    LegionRuntime::HighLevel::Context ctx,
    LegionRuntime::HighLevel::Runtime *runtime
) {
    using namespace std;
    // Make local copies of geometry information.  Use global_int_t since the
    // RHS products in the calculations below may result in global range values.
    global_int_t nx  = A.geom->nx;
    global_int_t ny  = A.geom->ny;
    global_int_t nz  = A.geom->nz;
    global_int_t npx = A.geom->npx;
    global_int_t npy = A.geom->npy;
    global_int_t npz = A.geom->npz;
    global_int_t ipx = A.geom->ipx;
    global_int_t ipy = A.geom->ipy;
    global_int_t ipz = A.geom->ipz;
    global_int_t gnx = nx*npx;
    global_int_t gny = ny*npy;
    global_int_t gnz = nz*npz;
    // This is the size of our subblock
    local_int_t localNumberOfRows = nx*ny*nz;
    // If this assert fails, it most likely means that the local_int_t is set to
    // int and should be set to.  Throw an exception of the number of rows is
    // less than zero (can happen if int overflow)long long
    assert(localNumberOfRows > 0);
    // We are approximating a 27-point finite element/volume/difference 3D
    // stencil
    local_int_t numberOfNonzerosPerRow = 27;

    // Total number of grid points in mesh
    global_int_t totalNumberOfRows =
        ((global_int_t)localNumberOfRows)*((global_int_t)A.geom->size);
    // If this assert fails, it most likely means that the global_int_t is set
    // to int and should be set to long long
    assert(totalNumberOfRows>0);
    ////////////////////////////////////////////////////////////////////////////
    // Allocate arrays
    ////////////////////////////////////////////////////////////////////////////
    // TODO add vector stats
    if (A.geom->rank == 0) {
        const size_t mn = localNumberOfRows * numberOfNonzerosPerRow;
        const size_t sparseMatMemInB = (
            sizeof(char)         * localNumberOfRows //nonzerosInRow
          + sizeof(global_int_t) * mn                //mtxIndG
          + sizeof(local_int_t)  * mn                //mtxIndL
          + sizeof(floatType)    * mn                //matrixValues
          + sizeof(floatType)    * localNumberOfRows //matrixDiagonal
          + sizeof(global_int_t) * localNumberOfRows //localToGlobalMap
        ) * A.geom->size;
        //
        const size_t vectorsMemInB = (
            (b      ? sizeof(floatType) * localNumberOfRows : 0)
          + (x      ? sizeof(floatType) * localNumberOfRows : 0)
          + (xexact ? sizeof(floatType) * localNumberOfRows : 0)
        ) * A.geom->size;
        //
        const size_t pMemInB = sparseMatMemInB + vectorsMemInB;
        const double pMemInMB = double(pMemInB)/1024/1024;
        cout << "*** Approx. Generate Problem Memory Footprint="
             << pMemInMB << "MB" << endl;
    }
    //
    ArrayAllocator<char> aaNonzerosInRow (
        localNumberOfRows,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    char *nonzerosInRow = aaNonzerosInRow.data();
    assert(nonzerosInRow);
    // Interpreted as 2D array
    ArrayAllocator<global_int_t> aaMtxIndG(
        localNumberOfRows * numberOfNonzerosPerRow,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    global_int_t *mtxIndG1D = aaMtxIndG.data();
    assert(mtxIndG1D);
    // Interpreted as 2D array
    Array2D<global_int_t> mtxIndG(
        localNumberOfRows, numberOfNonzerosPerRow, mtxIndG1D
    );
    // Interpreted as 2D array
    ArrayAllocator<local_int_t> aaMtxIndL(
        localNumberOfRows * numberOfNonzerosPerRow,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    local_int_t *mtxIndL = aaMtxIndL.data();
    assert(mtxIndL);
    ArrayAllocator<floatType> aaMatrixValues(
        localNumberOfRows * numberOfNonzerosPerRow,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    floatType *matrixValues1D = aaMatrixValues.data();
    assert(matrixValues1D);
    // Interpreted as 2D array
    Array2D<floatType> matrixValues(
        localNumberOfRows, numberOfNonzerosPerRow, matrixValues1D
    );
    // Interpreted as 1D array
    ArrayAllocator<floatType> aaMatrixDiagonal(
        localNumberOfRows,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    floatType *matrixDiagonal = aaMatrixDiagonal.data();
    assert(matrixDiagonal);
    // Local-to-global mapping
    ArrayAllocator<global_int_t> aaLocalToGlobalMap(
        localNumberOfRows,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    global_int_t *localToGlobalMap = aaLocalToGlobalMap.data();
    assert(localToGlobalMap);
    //
    floatType *bv      = 0;
    floatType *xv      = 0;
    floatType *xexactv = 0;
    if (b != 0) {
        bv = b->data(); // Only compute exact solution if requested
        assert(bv);
    }
    if (x != 0) {
        xv = x->data(); // Only compute exact solution if requested
        assert(xv);
    }
    if (xexact != 0) {
        xexactv = xexact->data(); // Only compute exact solution if requested
        assert(xexactv);
    }
    //!< global-to-local mapping TODO write back into LR
    std::map< global_int_t, local_int_t > globalToLocalMap;
    //
    local_int_t localNumberOfNonzeros = 0;
    //
    for (local_int_t iz=0; iz<nz; iz++) {
        global_int_t giz = ipz*nz+iz;
        for (local_int_t iy=0; iy<ny; iy++) {
            global_int_t giy = ipy*ny+iy;
            for (local_int_t ix=0; ix<nx; ix++) {
                global_int_t gix = ipx*nx+ix;
                local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;
                global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;
                globalToLocalMap[currentGlobalRow] = currentLocalRow;
                localToGlobalMap[currentLocalRow] = currentGlobalRow;
                char numberOfNonzerosInRow = 0;
                // Current index in current row
                global_int_t currentIndexG = 0;
                local_int_t currentNonZeroElemIndex = 0;
                for (int sz=-1; sz<=1; sz++) {
                    if (giz+sz>-1 && giz+sz<gnz) {
                        for (int sy=-1; sy<=1; sy++) {
                            if (giy+sy>-1 && giy+sy<gny) {
                                for (int sx=-1; sx<=1; sx++) {
                                    if (gix+sx>-1 && gix+sx<gnx) {
                                        global_int_t curcol = currentGlobalRow+sz*gnx*gny+sy*gnx+sx;
                                        if (curcol==currentGlobalRow) {
                                            matrixDiagonal[currentLocalRow]                        = 26.0;
                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = 26.0;
                                        } else {
                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = -1.0;
                                        }
                                        currentNonZeroElemIndex++;
                                        mtxIndG(currentLocalRow, currentIndexG++) = curcol;
                                        numberOfNonzerosInRow++;
                                    } // end x bounds test
                                } // end sx loop
                            } // end y bounds test
                        } // end sy loop
                    } // end z bounds test
                } // end sz loop
                nonzerosInRow[currentLocalRow] = numberOfNonzerosInRow;
                localNumberOfNonzeros += numberOfNonzerosInRow;
                if (b!=0) {
                    bv[currentLocalRow] = 26.0 - ((double)(numberOfNonzerosInRow-1));
                }
                if (x!=0) {
                    xv[currentLocalRow] = 0.0;
                }
                if (xexact!=0) {
                    xexactv[currentLocalRow] = 1.0;
                }
            } // end ix loop
        } // end iy loop
    } // end iz loop
    //
    global_int_t totalNumberOfNonzeros = 0;
#ifndef HPCG_NO_MPI
    // SKG TODO calculate totalNumberOfNonzeros
    // Use MPI's reduce function to sum all nonzeros
    // convert to 64 bit for MPI call
    long long lnnz = localNumberOfNonzeros, gnnz = 0;
    MPI_Allreduce(&lnnz, &gnnz, 1, MPI_LONG_LONG_INT, MPI_SUM, MPI_COMM_WORLD);
    totalNumberOfNonzeros = gnnz; // Copy back
#else
  totalNumberOfNonzeros = localNumberOfNonzeros;
#endif
    // If this assert fails, it most likely means that the global_int_t is set
    // to int and should be set to long long This assert is usually the first to
    // fail as problem size increases beyond the 32-bit integer range.  Throw an
    // exception of the number of nonzeros is less than zero (can happen if int
    // overflow)
    assert(totalNumberOfNonzeros>0);
#if 0
    // Perform serialization of items for storage into logical regions.
    std::stringstream localToGlobalMapStream;
    {
        cereal::BinaryOutputArchive oa(localToGlobalMapStream);
        oa(localToGlobalMap);
    }
    std::vector<global_int_t> testOut;
    {
        cereal::BinaryInputArchive ia(localToGlobalMapStream);
        ia(testOut);
    }
    for (auto i : testOut) {
        cout << "OUT: " << i << endl;
    }
#endif
    //
    A.localData->totalNumberOfRows     = totalNumberOfRows;
    A.localData->totalNumberOfNonzeros = totalNumberOfNonzeros;
    A.localData->localNumberOfRows     = localNumberOfRows;
    A.localData->localNumberOfColumns  = localNumberOfRows;
    A.localData->localNumberOfNonzeros = localNumberOfNonzeros;
    //
       aaNonzerosInRow.bindToLogicalRegion(*(A.pic.nonzerosInRow.data()));
             aaMtxIndG.bindToLogicalRegion(*(A.pic.mtxIndG.data()));
             aaMtxIndL.bindToLogicalRegion(*(A.pic.mtxIndL.data()));
        aaMatrixValues.bindToLogicalRegion(*(A.pic.matrixValues.data()));
      aaMatrixDiagonal.bindToLogicalRegion(*(A.pic.matrixDiagonal.data()));
    aaLocalToGlobalMap.bindToLogicalRegion(*(A.pic.localToGlobalMap.data()));
}
<commit_msg>First cut at globalToLocalMap serialization.<commit_after>/**
 * Copyright (c) 2016      Los Alamos National Security, LLC
 *                         All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * LA-CC 10-123
 */

//@HEADER
// ***************************************************
//
// HPCG: High Performance Conjugate Gradient Benchmark
//
// Contact:
// Michael A. Heroux ( maherou@sandia.gov)
// Jack Dongarra     (dongarra@eecs.utk.edu)
// Piotr Luszczek    (luszczek@eecs.utk.edu)
//
// ***************************************************
//@HEADER

/*!
 @file GenerateProblem_ref.hpp

 HPCG routine
 */

#pragma once

#include "hpcg.hpp"

#include "LegionItems.hpp"
#include "LegionArrays.hpp"
#include "LegionMatrices.hpp"

// For STL serialization into regions.
#include "cereal/archives/binary.hpp"
#include "cereal/types/map.hpp"

#include <map>
#include <sstream>
#include <cassert>

/*!
    Reference version of GenerateProblem to generate the sparse matrix, right
    hand side, initial guess, and exact solution.

    @param[in]  A        The known system matrix
    @param[inout] b      The newly allocated and generated right hand side
    vector (if b!=0 on entry)
    @param[inout] x      The newly allocated solution vector with entries set to
    0.0 (if x!=0 on entry)
    @param[inout] xexact The newly allocated solution vector with entries set to
    the exact solution (if the xexact!=0 non-zero on entry)

    @see GenerateGeometry
*/
inline void
GenerateProblem(
    SparseMatrix &A,
    Array<floatType> *b,
    Array<floatType> *x,
    Array<floatType> *xexact,
    LegionRuntime::HighLevel::Context ctx,
    LegionRuntime::HighLevel::Runtime *runtime
) {
    using namespace std;
    // Make local copies of geometry information.  Use global_int_t since the
    // RHS products in the calculations below may result in global range values.
    global_int_t nx  = A.geom->nx;
    global_int_t ny  = A.geom->ny;
    global_int_t nz  = A.geom->nz;
    global_int_t npx = A.geom->npx;
    global_int_t npy = A.geom->npy;
    global_int_t npz = A.geom->npz;
    global_int_t ipx = A.geom->ipx;
    global_int_t ipy = A.geom->ipy;
    global_int_t ipz = A.geom->ipz;
    global_int_t gnx = nx*npx;
    global_int_t gny = ny*npy;
    global_int_t gnz = nz*npz;
    // This is the size of our subblock
    local_int_t localNumberOfRows = nx*ny*nz;
    // If this assert fails, it most likely means that the local_int_t is set to
    // int and should be set to.  Throw an exception of the number of rows is
    // less than zero (can happen if int overflow)long long
    assert(localNumberOfRows > 0);
    // We are approximating a 27-point finite element/volume/difference 3D
    // stencil
    local_int_t numberOfNonzerosPerRow = 27;

    // Total number of grid points in mesh
    global_int_t totalNumberOfRows =
        ((global_int_t)localNumberOfRows)*((global_int_t)A.geom->size);
    // If this assert fails, it most likely means that the global_int_t is set
    // to int and should be set to long long
    assert(totalNumberOfRows>0);
    ////////////////////////////////////////////////////////////////////////////
    // Allocate arrays
    ////////////////////////////////////////////////////////////////////////////
    // TODO add vector stats
    if (A.geom->rank == 0) {
        const size_t mn = localNumberOfRows * numberOfNonzerosPerRow;
        const size_t sparseMatMemInB = (
            sizeof(char)         * localNumberOfRows //nonzerosInRow
          + sizeof(global_int_t) * mn                //mtxIndG
          + sizeof(local_int_t)  * mn                //mtxIndL
          + sizeof(floatType)    * mn                //matrixValues
          + sizeof(floatType)    * localNumberOfRows //matrixDiagonal
          + sizeof(global_int_t) * localNumberOfRows //localToGlobalMap
        ) * A.geom->size;
        //
        const size_t vectorsMemInB = (
            (b      ? sizeof(floatType) * localNumberOfRows : 0)
          + (x      ? sizeof(floatType) * localNumberOfRows : 0)
          + (xexact ? sizeof(floatType) * localNumberOfRows : 0)
        ) * A.geom->size;
        //
        const size_t pMemInB = sparseMatMemInB + vectorsMemInB;
        const double pMemInMB = double(pMemInB)/1024/1024;
        cout << "*** Approx. Generate Problem Memory Footprint="
             << pMemInMB << "MB" << endl;
    }
    //
    ArrayAllocator<char> aaNonzerosInRow (
        localNumberOfRows,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    char *nonzerosInRow = aaNonzerosInRow.data();
    assert(nonzerosInRow);
    // Interpreted as 2D array
    ArrayAllocator<global_int_t> aaMtxIndG(
        localNumberOfRows * numberOfNonzerosPerRow,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    global_int_t *mtxIndG1D = aaMtxIndG.data();
    assert(mtxIndG1D);
    // Interpreted as 2D array
    Array2D<global_int_t> mtxIndG(
        localNumberOfRows, numberOfNonzerosPerRow, mtxIndG1D
    );
    // Interpreted as 2D array
    ArrayAllocator<local_int_t> aaMtxIndL(
        localNumberOfRows * numberOfNonzerosPerRow,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    local_int_t *mtxIndL = aaMtxIndL.data();
    assert(mtxIndL);
    ArrayAllocator<floatType> aaMatrixValues(
        localNumberOfRows * numberOfNonzerosPerRow,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    floatType *matrixValues1D = aaMatrixValues.data();
    assert(matrixValues1D);
    // Interpreted as 2D array
    Array2D<floatType> matrixValues(
        localNumberOfRows, numberOfNonzerosPerRow, matrixValues1D
    );
    // Interpreted as 1D array
    ArrayAllocator<floatType> aaMatrixDiagonal(
        localNumberOfRows,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    floatType *matrixDiagonal = aaMatrixDiagonal.data();
    assert(matrixDiagonal);
    // Local-to-global mapping
    ArrayAllocator<global_int_t> aaLocalToGlobalMap(
        localNumberOfRows,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    global_int_t *localToGlobalMap = aaLocalToGlobalMap.data();
    assert(localToGlobalMap);
    //
    floatType *bv      = nullptr;
    floatType *xv      = nullptr;
    floatType *xexactv = nullptr;
    if (b != 0) {
        bv = b->data(); // Only compute exact solution if requested
        assert(bv);
    }
    if (x != 0) {
        xv = x->data(); // Only compute exact solution if requested
        assert(xv);
    }
    if (xexact != 0) {
        xexactv = xexact->data(); // Only compute exact solution if requested
        assert(xexactv);
    }
    //!< global-to-local mapping TODO write back into LR
    std::map< global_int_t, local_int_t > globalToLocalMap;
    //
    local_int_t localNumberOfNonzeros = 0;
    //
    for (local_int_t iz=0; iz<nz; iz++) {
        global_int_t giz = ipz*nz+iz;
        for (local_int_t iy=0; iy<ny; iy++) {
            global_int_t giy = ipy*ny+iy;
            for (local_int_t ix=0; ix<nx; ix++) {
                global_int_t gix = ipx*nx+ix;
                local_int_t currentLocalRow = iz*nx*ny+iy*nx+ix;
                global_int_t currentGlobalRow = giz*gnx*gny+giy*gnx+gix;
                globalToLocalMap[currentGlobalRow] = currentLocalRow;
                localToGlobalMap[currentLocalRow] = currentGlobalRow;
                char numberOfNonzerosInRow = 0;
                // Current index in current row
                global_int_t currentIndexG = 0;
                local_int_t currentNonZeroElemIndex = 0;
                for (int sz=-1; sz<=1; sz++) {
                    if (giz+sz>-1 && giz+sz<gnz) {
                        for (int sy=-1; sy<=1; sy++) {
                            if (giy+sy>-1 && giy+sy<gny) {
                                for (int sx=-1; sx<=1; sx++) {
                                    if (gix+sx>-1 && gix+sx<gnx) {
                                        global_int_t curcol = currentGlobalRow+sz*gnx*gny+sy*gnx+sx;
                                        if (curcol==currentGlobalRow) {
                                            matrixDiagonal[currentLocalRow]                        = 26.0;
                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = 26.0;
                                        } else {
                                            matrixValues(currentLocalRow, currentNonZeroElemIndex) = -1.0;
                                        }
                                        currentNonZeroElemIndex++;
                                        mtxIndG(currentLocalRow, currentIndexG++) = curcol;
                                        numberOfNonzerosInRow++;
                                    } // end x bounds test
                                } // end sx loop
                            } // end y bounds test
                        } // end sy loop
                    } // end z bounds test
                } // end sz loop
                nonzerosInRow[currentLocalRow] = numberOfNonzerosInRow;
                localNumberOfNonzeros += numberOfNonzerosInRow;
                if (b!=0) {
                    bv[currentLocalRow] = 26.0 - ((double)(numberOfNonzerosInRow-1));
                }
                if (x!=0) {
                    xv[currentLocalRow] = 0.0;
                }
                if (xexact!=0) {
                    xexactv[currentLocalRow] = 1.0;
                }
            } // end ix loop
        } // end iy loop
    } // end iz loop
    //
    global_int_t totalNumberOfNonzeros = 0;
#if 0
    // SKG TODO calculate totalNumberOfNonzeros
    // Use MPI's reduce function to sum all nonzeros
    // convert to 64 bit for MPI call
    long long lnnz = localNumberOfNonzeros, gnnz = 0;
    MPI_Allreduce(&lnnz, &gnnz, 1, MPI_LONG_LONG_INT, MPI_SUM, MPI_COMM_WORLD);
    totalNumberOfNonzeros = gnnz; // Copy back
#else
    totalNumberOfNonzeros = localNumberOfNonzeros;
#endif
    // If this assert fails, it most likely means that the global_int_t is set
    // to int and should be set to long long This assert is usually the first to
    // fail as problem size increases beyond the 32-bit integer range.  Throw an
    // exception of the number of nonzeros is less than zero (can happen if int
    // overflow)
    assert(totalNumberOfNonzeros>0);
    // Perform serialization of items for storage into logical regions.
    std::stringstream *ssGlobalToLocalMap = new std::stringstream;
    {   // Scoped to guarantee flushing, etc.
        cereal::BinaryOutputArchive oa(*ssGlobalToLocalMap);
        oa(globalToLocalMap);
    }
    // Get size of serialized buffer.
    ssGlobalToLocalMap->seekp(0, ios::end);
    auto regionSizeInB = ssGlobalToLocalMap->tellp();
    //
    string strBuff(ssGlobalToLocalMap->str());
    // Remove one copy of the data, since it is stored elsewhere now.
    delete ssGlobalToLocalMap;
    // Allocate region-based backing store for serialized data.
    ArrayAllocator<char> aaGlobalToLocalMap(
        regionSizeInB,
        WRITE_ONLY,
        EXCLUSIVE,
        ctx,
        runtime
    );
    char *globalToLocalMapBytesPtr = aaGlobalToLocalMap.data();
    assert(globalToLocalMapBytesPtr);
    // Write back into logical region
    memmove(globalToLocalMapBytesPtr, strBuff.c_str(), regionSizeInB);
    // Kill last unneeded intermediate buffer.
    strBuff.clear();
    //
    A.localData->totalNumberOfRows     = totalNumberOfRows;
    A.localData->totalNumberOfNonzeros = totalNumberOfNonzeros;
    A.localData->localNumberOfRows     = localNumberOfRows;
    A.localData->localNumberOfColumns  = localNumberOfRows;
    A.localData->localNumberOfNonzeros = localNumberOfNonzeros;
    //
       aaNonzerosInRow.bindToLogicalRegion(*(A.pic.nonzerosInRow.data()));
             aaMtxIndG.bindToLogicalRegion(*(A.pic.mtxIndG.data()));
             aaMtxIndL.bindToLogicalRegion(*(A.pic.mtxIndL.data()));
        aaMatrixValues.bindToLogicalRegion(*(A.pic.matrixValues.data()));
      aaMatrixDiagonal.bindToLogicalRegion(*(A.pic.matrixDiagonal.data()));
    aaLocalToGlobalMap.bindToLogicalRegion(*(A.pic.localToGlobalMap.data()));
}
<|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2012.  All rights reserved
 */
#ifndef _Stroika_Foundation_Execution_Resources_Accessor_inl_
#define _Stroika_Foundation_Execution_Resources_Accessor_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
namespace   Stroika {
    namespace   Foundation {
        namespace   Execution {
            namespace   Resources {

                //  class   Accessor
                inline  const Byte* Accessor::GetDataStart () const
                {
                    return fDataStart_;
                }
                inline  const Byte* Accessor::GetDataEnd () const
                {
                    return fDataEnd_;
                }
                inline  vector<Byte>    Accessor::GetData () const
                {
                    return vector<Byte> (fDataStart_, fDataEnd_);
                }

            }
        }
    }
}

#endif  /*_Stroika_Foundation_Execution_Resources_Accessor_inl_*/
<commit_msg>fixed missing CTOR in last checkin<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2012.  All rights reserved
 */
#ifndef _Stroika_Foundation_Execution_Resources_Accessor_inl_
#define _Stroika_Foundation_Execution_Resources_Accessor_inl_    1

/*
 ********************************************************************************
 ***************************** Implementation Details ***************************
 ********************************************************************************
 */
namespace   Stroika {
    namespace   Foundation {
        namespace   Execution {
            namespace   Resources {

                //  class   Accessor
                inline   Accessor::Accessor (const Byte* start, const Byte* end)
                    : fDataStart_ (start)
                    , fDataEnd_ (end)
                {
                }
                inline  const Byte* Accessor::GetDataStart () const
                {
                    return fDataStart_;
                }
                inline  const Byte* Accessor::GetDataEnd () const
                {
                    return fDataEnd_;
                }
                inline  vector<Byte>    Accessor::GetData () const
                {
                    return vector<Byte> (fDataStart_, fDataEnd_);
                }

            }
        }
    }
}

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


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

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.commontk.org/LICENSE

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QApplication>
#include <QTimer>
#include <QDebug>

// CTK includes
#include "ctkCommandLineParser.h"
#include "ctkVTKSliceView.h"

// VTK includes
#include <vtkImageReader2Factory.h>
#include <vtkImageReader2.h>
#include <vtkImageData.h>
#include <vtkSmartPointer.h>
#include <vtkInteractorStyleImage.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkLightBoxRendererManager.h>

// STD includes
#include <iostream>

//-----------------------------------------------------------------------------
int ctkVTKSliceViewTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  // Test arguments
  bool interactive = false;
  QString data_directory;
  QString filename = "HeadMRVolume.mhd";

  // Command line parser
  ctkCommandLineParser parser;
  parser.addBooleanArgument(0, "-I", &interactive);
  parser.addStringArgument(0, "-D", &data_directory);
  if (!parser.parseArguments(app.arguments()))
    {
    std::cerr << qPrintable(parser.errorString()) << std::endl;
    return EXIT_FAILURE;
    }

  QString imageFilename = data_directory + "/" + filename;

  // Instanciate the reader factory
  vtkSmartPointer<vtkImageReader2Factory> imageFactory =
      vtkSmartPointer<vtkImageReader2Factory>::New();

  // Instanciate an image reader
  vtkSmartPointer<vtkImageReader2> imageReader;
  imageReader.TakeReference(imageFactory->CreateImageReader2(imageFilename.toLatin1()));
  if (!imageReader)
    {
    std::cerr << "Failed to instanciate image reader using: "
              << qPrintable(imageFilename) << std::endl;
    return EXIT_FAILURE;
    }

  // Read image
  imageReader->SetFileName(imageFilename.toLatin1());
  imageReader->Update();
  vtkSmartPointer<vtkImageData> image = imageReader->GetOutput();

  ctkVTKSliceView sliceView;
  sliceView.resize(300, 300);
  sliceView.setImageData(image);
  sliceView.lightBoxRendererManager()->SetRenderWindowLayout(4, 3);
  sliceView.lightBoxRendererManager()->SetHighlighted(1, 1, true);
  sliceView.setCornerAnnotationText("CTK");
  sliceView.scheduleRender();
  sliceView.show();

  if (!interactive)
    {
    QTimer::singleShot(1000, &app, SLOT(quit()));
    }
  return app.exec();
}
<commit_msg>ENH: ctkVTKSliceViewTest1 - Add two QSpinBoxes allowing to dynamically change lightbox layout<commit_after>/*=========================================================================

  Library:   CTK

  Copyright (c) 2010  Kitware Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.commontk.org/LICENSE

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

// Qt includes
#include <QApplication>
#include <QTimer>
#include <QDebug>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QSpinBox>

// CTK includes
#include "ctkCommandLineParser.h"
#include "ctkVTKObjectEventsObserver.h"
#include "ctkVTKSliceView.h"

// VTK includes
#include <vtkImageReader2Factory.h>
#include <vtkImageReader2.h>
#include <vtkImageData.h>
#include <vtkSmartPointer.h>
#include <vtkInteractorStyleImage.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkLightBoxRendererManager.h>

// STD includes
#include <iostream>

//-----------------------------------------------------------------------------
int ctkVTKSliceViewTest1(int argc, char * argv [] )
{
  QApplication app(argc, argv);

  // Test arguments
  bool interactive = false;
  QString data_directory;
  QString filename = "HeadMRVolume.mhd";

  // Command line parser
  ctkCommandLineParser parser;
  parser.addBooleanArgument(0, "-I", &interactive);
  parser.addStringArgument(0, "-D", &data_directory);
  if (!parser.parseArguments(app.arguments()))
    {
    std::cerr << qPrintable(parser.errorString()) << std::endl;
    return EXIT_FAILURE;
    }

  QString imageFilename = data_directory + "/" + filename;

  // Instanciate the reader factory
  vtkSmartPointer<vtkImageReader2Factory> imageFactory =
      vtkSmartPointer<vtkImageReader2Factory>::New();

  // Instanciate an image reader
  vtkSmartPointer<vtkImageReader2> imageReader;
  imageReader.TakeReference(imageFactory->CreateImageReader2(imageFilename.toLatin1()));
  if (!imageReader)
    {
    std::cerr << "Failed to instanciate image reader using: "
              << qPrintable(imageFilename) << std::endl;
    return EXIT_FAILURE;
    }

  // Read image
  imageReader->SetFileName(imageFilename.toLatin1());
  imageReader->Update();
  vtkSmartPointer<vtkImageData> image = imageReader->GetOutput();

  // Top level widget
  QWidget widget;

  // .. and its associated layout
  QVBoxLayout * topLevelLayout = new QVBoxLayout(&widget);

  // Horizontal layout to contain the spinboxes
  QHBoxLayout * spinBoxLayout = new QHBoxLayout;
  topLevelLayout->addLayout(spinBoxLayout);

  int defaultRowCount = 4;
  int defaultColumnCount = 3;

  // SpinBox to change number of row in lightBox
  QSpinBox * rowSpinBox = new QSpinBox;
  rowSpinBox->setRange(1, 10);
  rowSpinBox->setSingleStep(1);
  rowSpinBox->setValue(defaultRowCount);
  spinBoxLayout->addWidget(rowSpinBox);

  // SpinBox to change number of column in lightBox
  QSpinBox * columnSpinBox = new QSpinBox;
  columnSpinBox->setRange(1, 10);
  columnSpinBox->setSingleStep(1);
  columnSpinBox->setValue(defaultColumnCount);
  spinBoxLayout->addWidget(columnSpinBox);

  ctkVTKSliceView * sliceView = new ctkVTKSliceView;
  sliceView->setRenderEnabled(true);
  sliceView->setMinimumSize(600, 600);
  sliceView->setImageData(image);
  sliceView->lightBoxRendererManager()->SetRenderWindowLayout(defaultRowCount, defaultColumnCount);
  sliceView->lightBoxRendererManager()->SetHighlighted(0, 0, true);
  sliceView->setCornerAnnotationText("CTK");
  sliceView->scheduleRender();
  topLevelLayout->addWidget(sliceView);

  // Set connection
  QObject::connect(rowSpinBox, SIGNAL(valueChanged(int)),
                   sliceView, SLOT(setLightBoxRendererManagerRowCount(int)));
  QObject::connect(columnSpinBox, SIGNAL(valueChanged(int)),
                   sliceView, SLOT(setLightBoxRendererManagerColumnCount(int)));

  ctkVTKObjectEventsObserver vtkObserver;
  vtkObserver.addConnection(sliceView->lightBoxRendererManager(), vtkCommand::ModifiedEvent,
                            sliceView, SLOT(scheduleRender()));

  widget.show();

  // TODO Add image regression test

  if (!interactive)
    {
    QTimer::singleShot(1000, &app, SLOT(quit()));
    }
  return app.exec();
}
<|endoftext|>


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

#include "lua-sandbox/luasb.hh"

int main(int argc, char * argv[])
{
        return 1;
}
<commit_msg>Removed licensing from tests (useless)<commit_after>#include "lua-sandbox/luasb.hh"

int main(int argc, char * argv[])
{
        return 1;
}
<|endoftext|>


<commit_before>#ifndef ALEPH_CONTAINERS_DATA_DESCRIPTORS_HH__
#define ALEPH_CONTAINERS_DATA_DESCRIPTORS_HH__

#include <cmath>

#include <algorithm>
#include <numeric>
#include <vector>

#include "distances/Euclidean.hh"
#include "distances/Traits.hh"

#include "geometry/BruteForce.hh"
#include "geometry/NearestNeighbours.hh"

namespace aleph
{

/**
  Order-based eccentricity calculations. Eccentricity assigns low values
  to central points in a point cloud without having to define the actual
  centre of it. The order parameter can be used to decrease how much the
  small distances influence the result.
*/

template <class Distance, class Container> std::vector<double> eccentricities( const Container& container,
                                                                               unsigned order = 1 )
{
  auto n = container.size();
  auto d = container.dimension();

  // Ensures that subsequent algorithms always operate on a non-empty
  // range of iterators.
  if( n == 0 )
    return {};

  std::vector<double> eccentricities;
  eccentricities.reserve( n );

  Distance dist;
  distances::Traits<Distance> traits;

  for( decltype(n) i = 0; i < n; i++ )
  {
    auto p = container[i];

    std::vector<double> distances;
    distances.reserve( n );

    double eccentricity = 0.0;

    for( decltype(n) j = 0; j < n; j++ )
    {
      if( i != j )
      {
        auto q        = container[j];
        auto distance = dist( p.begin(),
                              q.begin(),
                              d );

        distance = traits.from( distance );

        if( order > 0 )
          distance = std::pow( distance, decltype(distance)( order ) ) / decltype(distance)(n);

        distances.push_back( distance );
      }
    }

    if( order > 0 )
    {
      std::sort( distances.begin(), distances.end() );

      eccentricity = std::accumulate( distances.begin(), distances.end(), 0.0 );
      eccentricity = std::pow( eccentricity, 1.0 / order );
    }
    else
      eccentricity = *std::max_element( distances.begin(), distances.end() );

    eccentricities.push_back( eccentricity );
  }

  return eccentricities;
}

/**
  Density estimation using a truncated Gaussian estimator. Points whose
  Euclidean distance is smaller than the bandwidth will not be used for
  estimating the density.
*/

template <class Container> std::vector<double> estimateDensityTruncatedGaussian( const Container& container, double bandwidth )
{
  auto n = container.size();
  auto d = container.dimension();

  const auto bandwidthSquare = bandwidth * bandwidth;

  std::vector<double> densities;
  densities.reserve( n );

  distances::Euclidean<double> distanceFunctor;

  for( decltype(n) i = 0; i < n; i++ )
  {
    auto p       = container[i];
    auto density = 0.0;

    for( decltype(n) j = 0; j < n; j++ )
    {
      auto q        = container[j];
      auto distance = distanceFunctor( p.begin(),
                                       q.begin(),
                                       d );
      if( distance <= bandwidthSquare )
        density += std::exp( -1.0 * distance / ( 2.0 * bandwidth ) );
    }

    densities.push_back( density / static_cast<double>(n) );
  }

  return densities;
}

/**
  Density estimator using the distance to a measure density estimator as
  introduced by Chazal et al. in:

      Persistence-based clustering in Riemannian manifolds

  This density estimator is capable of using different distance
  functors.
*/

template <
  class Distance,
  class Container,
  class Wrapper = geometry::BruteForce<Container, Distance>
> std::vector<double> estimateDensityDistanceToMeasure( const Container& container,
                                                        unsigned k,
                                                        Distance /* distance */ = Distance() )
{
  auto n = container.size();

  std::vector<double> densities;
  densities.reserve( n );

  using IndexType = typename Wrapper::IndexType;

  std::vector< std::vector<IndexType> > indices;
  std::vector< std::vector<double> > distances;

  Wrapper nnWrapper( container );
  nnWrapper.neighbourSearch( k, indices, distances );

  for( decltype(n) i = 0; i < n; i++ )
  {

    double density  = std::accumulate( distances[i].begin(), distances[i].end(), 0.0 );
    density         = -density;
    density        /= static_cast<double>( n );

    densities.push_back( density );
  }

  return densities;
}

} // namespace aleph

#endif
<commit_msg>Using Kahan summation for all data descriptors<commit_after>#ifndef ALEPH_CONTAINERS_DATA_DESCRIPTORS_HH__
#define ALEPH_CONTAINERS_DATA_DESCRIPTORS_HH__

#include <cmath>

#include <algorithm>
#include <vector>

#include "distances/Euclidean.hh"
#include "distances/Traits.hh"

#include "geometry/BruteForce.hh"
#include "geometry/NearestNeighbours.hh"

#include "math/KahanSummation.hh"

namespace aleph
{

/**
  Order-based eccentricity calculations. Eccentricity assigns low values
  to central points in a point cloud without having to define the actual
  centre of it. The order parameter can be used to decrease how much the
  small distances influence the result.
*/

template <class Distance, class Container> std::vector<double> eccentricities( const Container& container,
                                                                               unsigned order = 1 )
{
  auto n = container.size();
  auto d = container.dimension();

  // Ensures that subsequent algorithms always operate on a non-empty
  // range of iterators.
  if( n == 0 )
    return {};

  std::vector<double> eccentricities;
  eccentricities.reserve( n );

  Distance dist;
  distances::Traits<Distance> traits;

  for( decltype(n) i = 0; i < n; i++ )
  {
    auto p = container[i];

    std::vector<double> distances;
    distances.reserve( n );

    double eccentricity = 0.0;

    for( decltype(n) j = 0; j < n; j++ )
    {
      if( i != j )
      {
        auto q        = container[j];
        auto distance = dist( p.begin(),
                              q.begin(),
                              d );

        distance = traits.from( distance );

        if( order > 0 )
          distance = std::pow( distance, decltype(distance)( order ) ) / decltype(distance)(n);

        distances.push_back( distance );
      }
    }

    if( order > 0 )
    {
      eccentricity = aleph::math::accumulate_kahan( distances.begin(), distances.end(), 0.0 );
      eccentricity = std::pow( eccentricity, 1.0 / order );
    }
    else
      eccentricity = *std::max_element( distances.begin(), distances.end() );

    eccentricities.push_back( eccentricity );
  }

  return eccentricities;
}

/**
  Density estimation using a truncated Gaussian estimator. Points whose
  Euclidean distance is smaller than the bandwidth will not be used for
  estimating the density.
*/

template <class Container> std::vector<double> estimateDensityTruncatedGaussian( const Container& container, double bandwidth )
{
  auto n = container.size();
  auto d = container.dimension();

  const auto bandwidthSquare = bandwidth * bandwidth;

  std::vector<double> densities;
  densities.reserve( n );

  distances::Euclidean<double> distanceFunctor;

  for( decltype(n) i = 0; i < n; i++ )
  {
    auto p                                      = container[i];
    aleph::math::KahanSummation<double> density = 0.0;

    for( decltype(n) j = 0; j < n; j++ )
    {
      auto q        = container[j];
      auto distance = distanceFunctor( p.begin(),
                                       q.begin(),
                                       d );
      if( distance <= bandwidthSquare )
        density += std::exp( -1.0 * distance / ( 2.0 * bandwidth ) );
    }

    densities.push_back( density / static_cast<double>(n) );
  }

  return densities;
}

/**
  Density estimator using the distance to a measure density estimator as
  introduced by Chazal et al. in:

      Persistence-based clustering in Riemannian manifolds

  This density estimator is capable of using different distance
  functors.
*/

template <
  class Distance,
  class Container,
  class Wrapper = geometry::BruteForce<Container, Distance>
> std::vector<double> estimateDensityDistanceToMeasure( const Container& container,
                                                        unsigned k,
                                                        Distance /* distance */ = Distance() )
{
  auto n = container.size();

  std::vector<double> densities;
  densities.reserve( n );

  using IndexType = typename Wrapper::IndexType;

  std::vector< std::vector<IndexType> > indices;
  std::vector< std::vector<double> > distances;

  Wrapper nnWrapper( container );
  nnWrapper.neighbourSearch( k, indices, distances );

  for( decltype(n) i = 0; i < n; i++ )
  {
    double density  = aleph::math::accumulate_kahan( distances[i].begin(), distances[i].end(), 0.0 );
    density         = -density;
    density        /= static_cast<double>( n );

    densities.push_back( density );
  }

  return densities;
}

} // namespace aleph

#endif
<|endoftext|>


<commit_before>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "ApplicationLinux.h"

int main(int argc, char* argv[])
{
    ouzel::ApplicationLinux application(argc, argv);

    return application.run();
}
<commit_msg>Fix engine initialization on Linux<commit_after>// Copyright (C) 2017 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "EngineLinux.h"

int main(int argc, char* argv[])
{
    ouzel::EngineLinux engine(argc, argv);

    return engine.run();
}
<|endoftext|>


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

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

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

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

 =========================================================================*/
#include "otbImageClassificationFilter.h"
#include "otbVectorImage.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMachineLearningModelFactory.h"

const unsigned int Dimension = 2;
typedef double PixelType;
typedef unsigned short LabeledPixelType;

typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::Image<LabeledPixelType, Dimension> LabeledImageType;
typedef otb::ImageClassificationFilter<ImageType, LabeledImageType> ClassificationFilterType;
typedef ClassificationFilterType::ModelType ModelType;
typedef ClassificationFilterType::ValueType ValueType;
typedef ClassificationFilterType::LabelType LabelType;
typedef otb::MachineLearningModelFactory<ValueType, LabelType> MachineLearningModelFactoryType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileWriter<LabeledImageType> WriterType;

int otbImageClassificationFilterNew(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
  ClassificationFilterType::Pointer filter = ClassificationFilterType::New();
  return EXIT_SUCCESS;
}

int otbImageClassificationFilter(int itkNotUsed(argc), char * argv[])
{
  const char * infname = argv[1];
  const char * modelfname = argv[2];
  const char * outfname = argv[3];

  // Instantiating object
  ClassificationFilterType::Pointer filter = ClassificationFilterType::New();

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(infname);

  ModelType::Pointer model;

  model = MachineLearningModelFactoryType::CreateMachineLearningModel(modelfname,
                                                                      MachineLearningModelFactoryType::ReadMode);

  model->Load(modelfname);

  filter->SetModel(model);
  filter->SetInput(reader->GetOutput());

  WriterType::Pointer writer = WriterType::New();
  writer->SetInput(filter->GetOutput());
  writer->SetFileName(outfname);
  writer->Update();

  return EXIT_SUCCESS;
}
<commit_msg>TEST: avoid segfault in otbImageClassificationFilter<commit_after>/*=========================================================================

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

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

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

 =========================================================================*/
#include "otbImageClassificationFilter.h"
#include "otbVectorImage.h"
#include "otbImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMachineLearningModelFactory.h"

const unsigned int Dimension = 2;
typedef double PixelType;
typedef unsigned short LabeledPixelType;

typedef otb::VectorImage<PixelType, Dimension> ImageType;
typedef otb::Image<LabeledPixelType, Dimension> LabeledImageType;
typedef otb::ImageClassificationFilter<ImageType, LabeledImageType> ClassificationFilterType;
typedef ClassificationFilterType::ModelType ModelType;
typedef ClassificationFilterType::ValueType ValueType;
typedef ClassificationFilterType::LabelType LabelType;
typedef otb::MachineLearningModelFactory<ValueType, LabelType> MachineLearningModelFactoryType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileWriter<LabeledImageType> WriterType;

int otbImageClassificationFilterNew(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
  ClassificationFilterType::Pointer filter = ClassificationFilterType::New();
  return EXIT_SUCCESS;
}

int otbImageClassificationFilter(int itkNotUsed(argc), char * argv[])
{
  const char * infname = argv[1];
  const char * modelfname = argv[2];
  const char * outfname = argv[3];

  // Instantiating object
  ClassificationFilterType::Pointer filter = ClassificationFilterType::New();

  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName(infname);

  ModelType::Pointer model;

  model = MachineLearningModelFactoryType::CreateMachineLearningModel(modelfname,
                                                                      MachineLearningModelFactoryType::ReadMode);

  if (model.IsNull())
  {
    std::cerr << "Unable to create a model from " << modelfname << std::endl;
    return EXIT_FAILURE;
  }

  model->Load(modelfname);

  filter->SetModel(model);
  filter->SetInput(reader->GetOutput());

  WriterType::Pointer writer = WriterType::New();
  writer->SetInput(filter->GetOutput());
  writer->SetFileName(outfname);
  writer->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Test function outside namespace...
int func_outside_namespace();

// Test class outside namespace...
class class_outside_namespace
{
	// Test basic types...
	char a;
	wchar_t b;
	short c;
	int d;
	long e;
	long long f;
	unsigned g;
	unsigned short h;
	unsigned long long i;
};

// Test variables outside namespace...
class_outside_namespace cls1;
int variable;

// Test a namespace...
namespace mynamespace
{
// Test class with a reserved Java name...
class String
{
	int m_count;

	// Test constructor initializer lists...
	String(int i) : m_count(i) { }
};

// Test basic template class...
template <class T>
class mypair {
	// Test array of template parameter types...
	T values [2];
	// Test access modifier...
	public:
	// Test constructor using template parameter types...
	mypair (T first, T second)
	{
		// Test array access...
		values[0] = first;
		values[1] = second;
	}
};

// Test template class with two parameters...
template <class T, class V>
class HashMap
{
	T one;
	V two;
};

template<class V, class T> class CT
{
	// Test using template types in as template parameters...
	HashMap<V, int> three;
	T one;
	V two;

};

// Test anonymous enums...
enum { value1, value2 };
enum { value3, value4 };

class foo
{
public:
	foo() { }
	foo(int i) {
		// Test use of anonymous enums values
		// and assigning enum values to int...
		i = value1;
		i = value4;
	}
	foo(int i, short t) {}

	// Test a function declaration with default values...
	int func_with_defaults1(int one, int two = 5);

	// Test a function declaration with one default value and void return...
	void func_with_defaults2(int x = 7);

	// Test a function definition with default values...
	int func_with_defaults_and_definition(int one, int two = 3)
	{
		two = 4;
		// Test a return statement...
		return two;
	}
};

// Test a class with a parent class...
class test : public foo {

	// Test an enclosed enumeration...
	enum test_enum
	{
		val1,
		// Test giving enumerators values...
		val2 = 1020,
		val3,
		val4 = 1045
	};

	// Test an anonymous enclosed class...
	class { int a, b; } anon_class1, anon_class2;
	class { int c, d; } anon_class3, anon_class4;

	// Test an enclosed class...
	class subby
	{
		int k;
	};

	// Test value in class with implicit constructor...
	foo test_foo_with_init;

	// Test bit fields...
	int test_with_bit_field : 5;

	int func2()
	{
		// Test setting of bit field...
		test_with_bit_field = 8;
		// Test getting of bit field...
		return test_with_bit_field;
	}

	// Test function for pointers and references...
	int func3(foo a, foo * b, foo ** c, foo& d, const foo& e, int& f)
	{
		// Test declaration in while...
		while (foo* j = b) { }

		// Test declaration in if...
		if (foo * l = b) { }

		// Test declaration in for...
		for (foo * a5 = b;a5;a5 = b) { }

		// Test while...
		while (b) { }

		// Test if...
		if (b) { }

		// Test standard looking for...
		for (int i = 0; i < 10; i++)
		{
			// Test nested for...
			for (i = 1; i < 5; i++)
			{
				// Test break statement...
				break;
			}
			// Test continue statement...
			continue;
		}

		// Test qualified enum access...
		int i = test::val1 + test::val2;

		// Test various pointer to basic types...
		char * ptr1;
		int ** ptr2;
		short * ptr3;
		unsigned * ptr4;
		bool * ptr5;
		int * ptr6;
		// Test multiple declarators with one declaration...
		foo * ptr7, * ptr8;

		// Test address of operator...
		ptr7 = &a;

		// Test basic pointer assignment...
		ptr8 = ptr7;

		// Test number literals...
		return 1072;
	}

	foo func4(int a, int b, short c = 55)
	{
		// Test implicity constructors with array...
		foo sd[15];

		// Test pointers to composite type...
		foo * foo1;
		foo ** foo2;

		// Test references to composite type...
		foo& foo3 = sd[1];

		// Test constructor call...
		foo foo4(1, 2);

		// Test implicity copy constructor call...
		foo foo5 = foo4;

		// Test pointer assignment from this...
		foo * foo6 = this;

		// Test copy from this...
		foo foo7 = *this;

		// Test bracketed expression...
		int d = (1 + 2) * 4;

		// Test && with non boolean expression...
		bool mybool1 = foo1 && foo6 && true;

		// Test || with non boolean expression...
		bool mybool2 = foo1 || foo6 || false;

		// Test function call...
		func2();

		// Test +=...
		d += 10;

		// Test switch...
		switch (d)
		{
			// Test fall through...
			case 1:
			case 2:
				break;
			default:
				return foo7;
		}

		// Test switch with declaration statement...
		switch (int decl = 1)
		{
			case 1:
				decl += 5;
				break;
		}

		// Test -> operator...
		foo6->func_with_defaults_and_definition(100);

		// Test dereference and call...
		(*foo6).func_with_defaults_and_definition(100, 2);

		// Test copy constructor on return...
		return sd[2];
	}

	// Test a union...
	union test_union
	{
		int a;
		float b;
	};

	// Test a struct...
	struct test_struct
	{
		int a;
		int b;
	};
};

// Test a namepace level union...
union test_union2
{
	short a, b;
};

// Test an anonymous class containing an anonymous class...
class
{
	class { int a; } anon_class1, anon_class2;
} anon_class3;

};

<commit_msg>Added tests for condition statements without braces.<commit_after>// Test function outside namespace...
int func_outside_namespace();

// Test class outside namespace...
class class_outside_namespace
{
	// Test basic types...
	char a;
	wchar_t b;
	short c;
	int d;
	long e;
	long long f;
	unsigned g;
	unsigned short h;
	unsigned long long i;
};

// Test variables outside namespace...
class_outside_namespace cls1;
int variable;

// Test a namespace...
namespace mynamespace
{
// Test class with a reserved Java name...
class String
{
	int m_count;

	// Test constructor initializer lists...
	String(int i) : m_count(i) { }
};

// Test basic template class...
template <class T>
class mypair {
	// Test array of template parameter types...
	T values [2];
	// Test access modifier...
	public:
	// Test constructor using template parameter types...
	mypair (T first, T second)
	{
		// Test array access...
		values[0] = first;
		values[1] = second;
	}
};

// Test template class with two parameters...
template <class T, class V>
class HashMap
{
	T one;
	V two;
};

template<class V, class T> class CT
{
	// Test using template types in as template parameters...
	HashMap<V, int> three;
	T one;
	V two;

};

// Test anonymous enums...
enum { value1, value2 };
enum { value3, value4 };

class foo
{
public:
	foo() { }
	foo(int i) {
		// Test use of anonymous enums values
		// and assigning enum values to int...
		i = value1;
		i = value4;
	}
	foo(int i, short t) {}

	// Test a function declaration with default values...
	int func_with_defaults1(int one, int two = 5);

	// Test a function declaration with one default value and void return...
	void func_with_defaults2(int x = 7);

	// Test a function definition with default values...
	int func_with_defaults_and_definition(int one, int two = 3)
	{
		two = 4;
		// Test a return statement...
		return two;
	}
};

// Test a class with a parent class...
class test : public foo {

	// Test an enclosed enumeration...
	enum test_enum
	{
		val1,
		// Test giving enumerators values...
		val2 = 1020,
		val3,
		val4 = 1045
	};

	// Test an anonymous enclosed class...
	class { int a, b; } anon_class1, anon_class2;
	class { int c, d; } anon_class3, anon_class4;

	// Test an enclosed class...
	class subby
	{
		int k;
	};

	// Test value in class with implicit constructor...
	foo test_foo_with_init;

	// Test bit fields...
	int test_with_bit_field : 5;

	int func2()
	{
		// Test setting of bit field...
		test_with_bit_field = 8;
		// Test getting of bit field...
		return test_with_bit_field;
	}

	// Test function for pointers and references...
	int func3(foo a, foo * b, foo ** c, foo& d, const foo& e, int& f)
	{
		// Test declaration in while...
		while (foo* j = b) { }

		// Test declaration in if...
		if (foo * l = b) { }

		// Test declaration in for...
		for (foo * a5 = b;a5;a5 = b) { }

		// Test while...
		while (b) { }

		// Test if...
		if (b) { }

		// Test standard looking for...
		for (int i = 0; i < 10; i++)
		{
			// Test nested for...
			for (i = 1; i < 5; i++)
			{
				// Test break statement...
				break;
			}
			// Test continue statement...
			continue;
		}

		// Test qualified enum access...
		int i = test::val1 + test::val2;

		// Test various pointer to basic types...
		char * ptr1;
		int ** ptr2;
		short * ptr3;
		unsigned * ptr4;
		bool * ptr5;
		int * ptr6;
		// Test multiple declarators with one declaration...
		foo * ptr7, * ptr8;

		// Test address of operator...
		ptr7 = &a;

		// Test basic pointer assignment...
		ptr8 = ptr7;

		// Test number literals...
		return 1072;
	}

	foo func4(int a, int b, short c = 55)
	{
		// Test implicity constructors with array...
		foo sd[15];

		// Test pointers to composite type...
		foo * foo1;
		foo ** foo2;

		// Test references to composite type...
		foo& foo3 = sd[1];

		// Test constructor call...
		foo foo4(1, 2);

		// Test implicity copy constructor call...
		foo foo5 = foo4;

		// Test pointer assignment from this...
		foo * foo6 = this;

		// Test copy from this...
		foo foo7 = *this;

		// Test bracketed expression...
		int d = (1 + 2) * 4;

		// Test && with non boolean expression...
		bool mybool1 = foo1 && foo6 && true;

		// Test || with non boolean expression...
		bool mybool2 = foo1 || foo6 || false;

		// Test function call...
		func2();

		// Test +=...
		d += 10;

		// Test switch...
		switch (d)
		{
			// Test fall through...
			case 1:
			case 2:
				break;
			default:
				return foo7;
		}

		// Test switch with declaration statement...
		switch (int decl = 1)
		{
			case 1:
				decl += 5;
				break;
		}

		// Test -> operator...
		foo6->func_with_defaults_and_definition(100);

		// Test dereference and call...
		(*foo6).func_with_defaults_and_definition(100, 2);

		// Test copy constructor on return...
		return sd[2];
	}

	void func5()
	{
		int i = 0;

		// Test condition statements without braces...
		if (true)
			i += 5;

		while (false)
			i -= 10;

		for (i = 0; i < 20; i++)
			i--;

		switch (i)
			case 1:
			return;
			case 2:
			i++;

		if (true)
			for ( ; ; )
				while (true) ;
	}

	// Test a union...
	union test_union
	{
		int a;
		float b;
	};

	// Test a struct...
	struct test_struct
	{
		int a;
		int b;
	};
};

// Test a namepace level union...
union test_union2
{
	short a, b;
};

// Test an anonymous class containing an anonymous class...
class
{
	class { int a; } anon_class1, anon_class2;
} anon_class3;

};

<|endoftext|>