<commit_before>/*
 * IceWM
 *
 * Copyright (C) 1997-2002 Marko Macek
 */
#include "config.h"
#include "ykey.h"
#include "ylib.h"

#include "yprefs.h"

#define CFGDEF
#include "wmconfig.h"
#include "bindkey.h"
#include "default.h"

#include "wmoption.h"
#include "wmmgr.h"
#include "yaction.h"
#include "yapp.h"
#include "sysdep.h"

#include "intl.h"

long workspaceCount = 0;
char *workspaceNames[MAXWORKSPACES];
YAction *workspaceActionActivate[MAXWORKSPACES];
YAction *workspaceActionMoveTo[MAXWORKSPACES];

void WMConfig::loadConfiguration(IApp *app, const char *fileName) {
#ifndef NO_CONFIGURE
    YConfig::findLoadConfigFile(app, icewm_preferences, fileName);
    YConfig::findLoadConfigFile(app, icewm_themable_preferences, fileName);
#endif
}

void WMConfig::loadThemeConfiguration(IApp *app, const char *themeName) {
#ifndef NO_CONFIGURE
    bool ok = YConfig::findLoadThemeFile(app,
                icewm_themable_preferences,
                upath("themes").child(themeName));
    if (ok == false)
        fail(_("Failed to load theme %s"), themeName);
#endif
}

void WMConfig::freeConfiguration() {
#ifndef NO_CONFIGURE
    YConfig::freeConfig(icewm_preferences);
#endif
}

void addWorkspace(const char * /*name*/, const char *value, bool append) {
    if (!append) {
        for (int i = 0; i < workspaceCount; i++) {
            delete[] workspaceNames[i];
            delete workspaceActionActivate[i];
            delete workspaceActionMoveTo[i];
        }
        workspaceCount = 0;
    }

    if (workspaceCount >= MAXWORKSPACES)
        return;
    workspaceNames[workspaceCount] = newstr(value);
    workspaceActionActivate[workspaceCount] = new YAction(); // !! fix
    workspaceActionMoveTo[workspaceCount] = new YAction();
    PRECONDITION(workspaceNames[workspaceCount] != NULL);
    workspaceCount++;
}

static const struct {
    const char name[8];
    enum WMLook value;
} wmLookNames[] = {
    { "win95",  lookWin95  },
    { "motif",  lookMotif  },
    { "warp3",  lookWarp3  },
    { "warp4",  lookWarp4  },
    { "nice",   lookNice   },
    { "pixmap", lookPixmap },
    { "metal",  lookMetal  },
    { "gtk",    lookGtk    },
    { "flat",   lookFlat   },
};

const char* getLookName(enum WMLook look) {
    for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
        if (look == wmLookNames[k].value)
            return wmLookNames[k].name;
    }
    return "";
}

bool getLook(const char *name, const char *arg, enum WMLook *lookPtr) {
    for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
        if (0 == strcmp(arg, wmLookNames[k].name)) {
            if (lookPtr) {
                *lookPtr = wmLookNames[k].value;
            }
            return true;
        }
    }
    return false;
}

#ifndef NO_CONFIGURE
void setLook(const char *name, const char *arg, bool) {
    enum WMLook look = wmLook;
    if (getLook(name, arg, &look)) {
        wmLook = look;
    } else {
        msg(_("Unknown value '%s' for option '%s'."), arg, name);
    }
}
#endif

static bool ensureDirectory(const upath& path) {
    if (path.dirExists())
        return true;
    if (path.mkdir() != 0) {
        fail(_("Unable to create directory %s"), path.string().c_str());
    }
    return path.dirExists();
}

static upath getDefaultsFilePath(const pstring& basename) {
    upath xdg(YApplication::getXdgConfDir());
    if (xdg.dirExists()) {
        upath file(xdg + basename);
        if (file.fileExists())
            return file;
    }
    upath prv(YApplication::getPrivConfDir());
    if (ensureDirectory(prv)) {
        return prv + basename;
    }
    ensureDirectory(xdg.parent());
    if (ensureDirectory(xdg)) {
        return xdg + basename;
    }
    return null;
}

int WMConfig::setDefault(const char *basename, const char *content) {
    upath confOld(getDefaultsFilePath(basename));
    if (confOld == null) {
        return -1; // no directory
    }
    upath confNew(confOld.path() + ".new.tmp");

    FILE *fpNew = confNew.fopen("w");
    if (fpNew) {
        fputs(content, fpNew);
        if (content[0] && content[strlen(content)-1] != '\n')
            fputc('\n', fpNew);
    }
    if (fpNew == NULL || fflush(fpNew) || ferror(fpNew)) {
        fail(_("Unable to write to %s"), confNew.string().c_str());
        if (fpNew)
            fclose(fpNew);
        confNew.remove();
        return -1;
    }

    FILE *fpOld = confOld.fopen("r");
    if (fpOld) {
        for (int i = 0; i < 10; ++i) {
            char buf[600] = "#", *line = buf;
            if (fgets(1 + buf, sizeof buf - 1, fpOld)) {
                while (line[1] == '#')
                    ++line;
                fputs(line, fpNew);
                if ('\n' != line[strlen(line)-1])
                    fputc('\n', fpNew);
            }
        }
        fclose(fpOld);
    }
    fclose(fpNew);

    if (fpOld != 0 || confOld.access() == 0) {
        confOld.remove();
    }
    if (confNew.renameAs(confOld)) {
        fail(_("Unable to rename %s to %s"),
                confNew.string().c_str(), confOld.string().c_str());
        confNew.remove();
    }
    return 0;
}

static void print_options(cfoption *options) {
    for (int i = 0; options[i].type != cfoption::CF_NONE; ++i) {
        if (options[i].notify) {
            if (0 == strcmp("Look", options[i].name)) {
                printf("%s=%s\n", "Look", getLookName(wmLook));
            }
            continue;
        }
        switch (options[i].type) {
        case cfoption::CF_BOOL:
            printf("%s=%d\n", options[i].name, *options[i].v.bool_value);
            break;
        case cfoption::CF_INT:
            printf("%s=%d\n", options[i].name, *options[i].v.i.int_value);
            break;
        case cfoption::CF_STR:
            printf("%s=\"%s\"\n", options[i].name,
                    options[i].v.s.string_value && *options[i].v.s.string_value
                    ? *options[i].v.s.string_value : "");
            break;
#ifndef NO_KEYBIND
        case cfoption::CF_KEY:
            printf("%s=\"%s\"\n", options[i].name,
                    options[i].v.k.key_value->name);
            break;
#endif
        case cfoption::CF_NONE:
            break;
        }
    }
}

void WMConfig::print_preferences() {
#ifndef NO_CONFIGURE
    print_options(icewm_preferences);
    print_options(icewm_themable_preferences);
#endif
}

<commit_msg>Free theme_preferences when done.<commit_after>/*
 * IceWM
 *
 * Copyright (C) 1997-2002 Marko Macek
 */
#include "config.h"
#include "ykey.h"
#include "ylib.h"

#include "yprefs.h"

#define CFGDEF
#include "wmconfig.h"
#include "bindkey.h"
#include "default.h"

#include "wmoption.h"
#include "wmmgr.h"
#include "yaction.h"
#include "yapp.h"
#include "sysdep.h"

#include "intl.h"

long workspaceCount = 0;
char *workspaceNames[MAXWORKSPACES];
YAction *workspaceActionActivate[MAXWORKSPACES];
YAction *workspaceActionMoveTo[MAXWORKSPACES];

void WMConfig::loadConfiguration(IApp *app, const char *fileName) {
#ifndef NO_CONFIGURE
    YConfig::findLoadConfigFile(app, icewm_preferences, fileName);
    YConfig::findLoadConfigFile(app, icewm_themable_preferences, fileName);
#endif
}

void WMConfig::loadThemeConfiguration(IApp *app, const char *themeName) {
#ifndef NO_CONFIGURE
    bool ok = YConfig::findLoadThemeFile(app,
                icewm_themable_preferences,
                upath("themes").child(themeName));
    if (ok == false)
        fail(_("Failed to load theme %s"), themeName);
#endif
}

void WMConfig::freeConfiguration() {
#ifndef NO_CONFIGURE
    YConfig::freeConfig(icewm_preferences);
    YConfig::freeConfig(icewm_themable_preferences);
#endif
}

void addWorkspace(const char * /*name*/, const char *value, bool append) {
    if (!append) {
        for (int i = 0; i < workspaceCount; i++) {
            delete[] workspaceNames[i];
            delete workspaceActionActivate[i];
            delete workspaceActionMoveTo[i];
        }
        workspaceCount = 0;
    }

    if (workspaceCount >= MAXWORKSPACES)
        return;
    workspaceNames[workspaceCount] = newstr(value);
    workspaceActionActivate[workspaceCount] = new YAction(); // !! fix
    workspaceActionMoveTo[workspaceCount] = new YAction();
    PRECONDITION(workspaceNames[workspaceCount] != NULL);
    workspaceCount++;
}

static const struct {
    const char name[8];
    enum WMLook value;
} wmLookNames[] = {
    { "win95",  lookWin95  },
    { "motif",  lookMotif  },
    { "warp3",  lookWarp3  },
    { "warp4",  lookWarp4  },
    { "nice",   lookNice   },
    { "pixmap", lookPixmap },
    { "metal",  lookMetal  },
    { "gtk",    lookGtk    },
    { "flat",   lookFlat   },
};

const char* getLookName(enum WMLook look) {
    for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
        if (look == wmLookNames[k].value)
            return wmLookNames[k].name;
    }
    return "";
}

bool getLook(const char *name, const char *arg, enum WMLook *lookPtr) {
    for (size_t k = 0; k < ACOUNT(wmLookNames); ++k) {
        if (0 == strcmp(arg, wmLookNames[k].name)) {
            if (lookPtr) {
                *lookPtr = wmLookNames[k].value;
            }
            return true;
        }
    }
    return false;
}

#ifndef NO_CONFIGURE
void setLook(const char *name, const char *arg, bool) {
    enum WMLook look = wmLook;
    if (getLook(name, arg, &look)) {
        wmLook = look;
    } else {
        msg(_("Unknown value '%s' for option '%s'."), arg, name);
    }
}
#endif

static bool ensureDirectory(const upath& path) {
    if (path.dirExists())
        return true;
    if (path.mkdir() != 0) {
        fail(_("Unable to create directory %s"), path.string().c_str());
    }
    return path.dirExists();
}

static upath getDefaultsFilePath(const pstring& basename) {
    upath xdg(YApplication::getXdgConfDir());
    if (xdg.dirExists()) {
        upath file(xdg + basename);
        if (file.fileExists())
            return file;
    }
    upath prv(YApplication::getPrivConfDir());
    if (ensureDirectory(prv)) {
        return prv + basename;
    }
    ensureDirectory(xdg.parent());
    if (ensureDirectory(xdg)) {
        return xdg + basename;
    }
    return null;
}

int WMConfig::setDefault(const char *basename, const char *content) {
    upath confOld(getDefaultsFilePath(basename));
    if (confOld == null) {
        return -1; // no directory
    }
    upath confNew(confOld.path() + ".new.tmp");

    FILE *fpNew = confNew.fopen("w");
    if (fpNew) {
        fputs(content, fpNew);
        if (content[0] && content[strlen(content)-1] != '\n')
            fputc('\n', fpNew);
    }
    if (fpNew == NULL || fflush(fpNew) || ferror(fpNew)) {
        fail(_("Unable to write to %s"), confNew.string().c_str());
        if (fpNew)
            fclose(fpNew);
        confNew.remove();
        return -1;
    }

    FILE *fpOld = confOld.fopen("r");
    if (fpOld) {
        for (int i = 0; i < 10; ++i) {
            char buf[600] = "#", *line = buf;
            if (fgets(1 + buf, sizeof buf - 1, fpOld)) {
                while (line[1] == '#')
                    ++line;
                fputs(line, fpNew);
                if ('\n' != line[strlen(line)-1])
                    fputc('\n', fpNew);
            }
        }
        fclose(fpOld);
    }
    fclose(fpNew);

    if (fpOld != 0 || confOld.access() == 0) {
        confOld.remove();
    }
    if (confNew.renameAs(confOld)) {
        fail(_("Unable to rename %s to %s"),
                confNew.string().c_str(), confOld.string().c_str());
        confNew.remove();
    }
    return 0;
}

static void print_options(cfoption *options) {
    for (int i = 0; options[i].type != cfoption::CF_NONE; ++i) {
        if (options[i].notify) {
            if (0 == strcmp("Look", options[i].name)) {
                printf("%s=%s\n", "Look", getLookName(wmLook));
            }
            continue;
        }
        switch (options[i].type) {
        case cfoption::CF_BOOL:
            printf("%s=%d\n", options[i].name, *options[i].v.bool_value);
            break;
        case cfoption::CF_INT:
            printf("%s=%d\n", options[i].name, *options[i].v.i.int_value);
            break;
        case cfoption::CF_STR:
            printf("%s=\"%s\"\n", options[i].name,
                    options[i].v.s.string_value && *options[i].v.s.string_value
                    ? *options[i].v.s.string_value : "");
            break;
#ifndef NO_KEYBIND
        case cfoption::CF_KEY:
            printf("%s=\"%s\"\n", options[i].name,
                    options[i].v.k.key_value->name);
            break;
#endif
        case cfoption::CF_NONE:
            break;
        }
    }
}

void WMConfig::print_preferences() {
#ifndef NO_CONFIGURE
    print_options(icewm_preferences);
    print_options(icewm_themable_preferences);
#endif
}

<|endoftext|>


<commit_before>// This file was copied from dune-fem and slightly modified.
// See http://dune.mathematik.uni-freiburg.de/ for the orginal
// file, authors, licence and readme!

#ifndef DUNE_GRID_PART_INDEXSET_DEFAULT_HH
#define DUNE_GRID_PART_INDEXSET_DEFAULT_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

// system
#include <vector>
#include <rpc/rpc.h>

// dune-common
#include <dune/common/misc.hh>
#include <dune/common/typetraits.hh>
#include <dune/common/version.hh>

// dune-grid
#include <dune/grid/common/grid.hh>
//#include <dune/grid/common/adaptcallback.hh> // for compatibility only

// dune-grid-multiscale
#include <dune/grid/part/indexset/empty.hh>

//#include <dune/fem/misc/capabilities.hh>
//#include <dune/fem/misc/mpimanager.hh>

namespace Dune {

namespace grid {

namespace Part {

namespace IndexSet {

namespace Default {

//! Wraps the interface methods of indexsets and adds the addiotnal needed
//! functions
template <class IndexSetImp >
class Wrapper : public Empty
{
public:
  typedef typename IndexSetImp :: IndexType  IndexType ;
  //! The types of the iterator
  template<int cd>
  struct Codim
  {
    template<PartitionIteratorType pitype>
    struct Partition
    {
      typedef typename IndexSetImp::template Codim<cd>::
        template Partition<pitype>::Iterator  Iterator;
    };
  };

  //! store const reference to set
  Wrapper(const IndexSetImp & set, bool /*adaptive*/ = false)
    : Empty()
    , set_(set)
  {}

  //! store const reference to set
  Wrapper(const Wrapper<IndexSetImp> & s)
    : Empty(/*s.adaptive_*/),
      set_(s.set_)
  {}

  //! return persistent status
  bool persistent () const { return false; }

  //! return size of set for codim
  int size ( GeometryType type ) const
  {
    return set_.size(type);
  }

  //! return size of grid entities per level and codim
  int size ( int codim ) const
  {
    return set_.size(codim);
  }

  //! return index of en
  template <class EntityType>
  int index (const EntityType & en) const
  {
    return set_.index(en);
  }

  //! return sub index of given entities sub entity with codim and number
  template< int codim, class EntityType >
  int DUNE_DEPRECATED subIndex ( const EntityType &entity, int num ) const
  {
    return set_.template subIndex< codim >( entity, num );
  }

  template< class Entity >
  int subIndex ( const Entity &entity, int num, unsigned int codim ) const
  {
    return set_.subIndex( entity, num, codim );
  }

  //! wrap geomTypes method of set
  const std::vector< GeometryType > & geomTypes (int codim) const
  {
    return set_.geomTypes(codim);
  }

  //! returns true if this set provides an index for given entity
  template<class EntityType>
  bool contains (const EntityType& en) const
  {
    return set_.contains(en);
  }

  //! return index
  template< int codim, class Entity >
  int DUNE_DEPRECATED index ( const Entity &entity, int i ) const
  {
    static const int DUNE_UNUSED(cc) = Entity::codimension;
    return set_.subIndex( entity, i, codim );
  }

  /** @brief Iterator to first entity of given codimension and partition type.
   */
  template<int cd, PartitionIteratorType pitype>
  typename Codim<cd>::template Partition<pitype>::Iterator begin () const
  {
    return set_.template begin<cd,pitype> ();
  }

  /** @brief Iterator to one past the last entity of given codim for partition type
   */
  template<int cd, PartitionIteratorType pitype>
  typename Codim<cd>::template Partition<pitype>::Iterator end () const
  {
    return set_.template end<cd,pitype> ();
  }

private:
  const IndexSetImp & set_;
}; // class Wrapper

//! Wraps LeafIndexSet of Dune Grids for use with LagrangeFunctionSpace
template <class GridType>
class Leaf
:  public Wrapper<typename GridType :: Traits :: LeafIndexSet>
{
  // my type, to be revised
  enum { myType = 5 };

  // my index set type
  typedef typename GridType :: Traits :: LeafIndexSet IndexSetType;
  typedef Leaf<GridType> ThisType;
public:
  //! number of codimensions
  enum { ncodim = GridType::dimension + 1 };
  //! constructor
  Leaf ( const GridType & grid , const int /*level*/ =-1 )
    : Wrapper < IndexSetType > (grid.leafIndexSet()) {}

  //! constructor taking grid part
  template <class GridPartType>
  Leaf ( const GridPartType& gridPart )
    : Wrapper < IndexSetType > (gridPart.grid().leafIndexSet()) {}

  //! return type (for Grape In/Output)
  static int type() { return myType; }
  //! returns reference to singleton
  static ThisType & instance (const GridType & grid)
  {
    static ThisType set(grid,grid.maxLevel());
    return set;
  }
}; // class Leaf

} // namespace Default

} // namespace IndexSet

} // namespace Part

} // namespace grid

} // namespace Dune

#endif // DUNE_GRID_PART_INDEXSET_DEFAULT_HH
<commit_msg>[indexset.default] add another index() to please dune-pdelab<commit_after>// This file was copied from dune-fem and slightly modified.
// See http://dune.mathematik.uni-freiburg.de/ for the orginal
// file, authors, licence and readme!

#ifndef DUNE_GRID_PART_INDEXSET_DEFAULT_HH
#define DUNE_GRID_PART_INDEXSET_DEFAULT_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

// system
#include <vector>
#include <rpc/rpc.h>

// dune-common
#include <dune/common/misc.hh>
#include <dune/common/typetraits.hh>
#include <dune/common/version.hh>

// dune-grid
#include <dune/grid/common/grid.hh>
//#include <dune/grid/common/adaptcallback.hh> // for compatibility only

// dune-grid-multiscale
#include <dune/grid/part/indexset/empty.hh>

//#include <dune/fem/misc/capabilities.hh>
//#include <dune/fem/misc/mpimanager.hh>

namespace Dune {

namespace grid {

namespace Part {

namespace IndexSet {

namespace Default {

//! Wraps the interface methods of indexsets and adds the addiotnal needed
//! functions
template <class IndexSetImp >
class Wrapper : public Empty
{
public:
  typedef typename IndexSetImp :: IndexType  IndexType ;
  //! The types of the iterator
  template<int cd>
  struct Codim
  {
    template<PartitionIteratorType pitype>
    struct Partition
    {
      typedef typename IndexSetImp::template Codim<cd>::
        template Partition<pitype>::Iterator  Iterator;
    };
  };

  //! store const reference to set
  Wrapper(const IndexSetImp & set, bool /*adaptive*/ = false)
    : Empty()
    , set_(set)
  {}

  //! store const reference to set
  Wrapper(const Wrapper<IndexSetImp> & s)
    : Empty(/*s.adaptive_*/),
      set_(s.set_)
  {}

  //! return persistent status
  bool persistent () const { return false; }

  //! return size of set for codim
  int size ( GeometryType type ) const
  {
    return set_.size(type);
  }

  //! return size of grid entities per level and codim
  int size ( int codim ) const
  {
    return set_.size(codim);
  }

  //! return index of en
  template <class EntityType>
  int index (const EntityType & en) const
  {
    return set_.index(en);
  }

  //! return index of en
  template< int cc, class EntityType >
  int index(const EntityType & en) const
  {
    return set_.index(en);
  }

  //! return sub index of given entities sub entity with codim and number
  template< int codim, class EntityType >
  int DUNE_DEPRECATED subIndex ( const EntityType &entity, int num ) const
  {
    return set_.template subIndex< codim >( entity, num );
  }

  template< class Entity >
  int subIndex ( const Entity &entity, int num, unsigned int codim ) const
  {
    return set_.subIndex( entity, num, codim );
  }

  //! wrap geomTypes method of set
  const std::vector< GeometryType > & geomTypes (int codim) const
  {
    return set_.geomTypes(codim);
  }

  //! returns true if this set provides an index for given entity
  template<class EntityType>
  bool contains (const EntityType& en) const
  {
    return set_.contains(en);
  }

  //! return index
  template< int codim, class Entity >
  int DUNE_DEPRECATED index ( const Entity &entity, int i ) const
  {
    static const int DUNE_UNUSED(cc) = Entity::codimension;
    return set_.subIndex( entity, i, codim );
  }

  /** @brief Iterator to first entity of given codimension and partition type.
   */
  template<int cd, PartitionIteratorType pitype>
  typename Codim<cd>::template Partition<pitype>::Iterator begin () const
  {
    return set_.template begin<cd,pitype> ();
  }

  /** @brief Iterator to one past the last entity of given codim for partition type
   */
  template<int cd, PartitionIteratorType pitype>
  typename Codim<cd>::template Partition<pitype>::Iterator end () const
  {
    return set_.template end<cd,pitype> ();
  }

private:
  const IndexSetImp & set_;
}; // class Wrapper

//! Wraps LeafIndexSet of Dune Grids for use with LagrangeFunctionSpace
template <class GridType>
class Leaf
:  public Wrapper<typename GridType :: Traits :: LeafIndexSet>
{
  // my type, to be revised
  enum { myType = 5 };

  // my index set type
  typedef typename GridType :: Traits :: LeafIndexSet IndexSetType;
  typedef Leaf<GridType> ThisType;
public:
  //! number of codimensions
  enum { ncodim = GridType::dimension + 1 };
  //! constructor
  Leaf ( const GridType & grid , const int /*level*/ =-1 )
    : Wrapper < IndexSetType > (grid.leafIndexSet()) {}

  //! constructor taking grid part
  template <class GridPartType>
  Leaf ( const GridPartType& gridPart )
    : Wrapper < IndexSetType > (gridPart.grid().leafIndexSet()) {}

  //! return type (for Grape In/Output)
  static int type() { return myType; }
  //! returns reference to singleton
  static ThisType & instance (const GridType & grid)
  {
    static ThisType set(grid,grid.maxLevel());
    return set;
  }
}; // class Leaf

} // namespace Default

} // namespace IndexSet

} // namespace Part

} // namespace grid

} // namespace Dune

#endif // DUNE_GRID_PART_INDEXSET_DEFAULT_HH
<|endoftext|>


<commit_before>#include <config.h>
#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/parallel/collectivecommunication.hh>
#include <dune/stuff/common/validation.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/multiscale/problems/selector.hh>
#include <math.h>
#include <sstream>
#include <mpi.h>

#include "dune/multiscale/problems/base.hh"

#include "random.hh"

#if HAVE_RANDOM_PROBLEM
#include "random_permeability.hh"
#endif

namespace Dune {
namespace Multiscale {
namespace Problem {
namespace Random {

ModelProblemData::ModelProblemData()
  : IModelProblemData()
  , boundaryInfo_(DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings()))
  , subBoundaryInfo_() {}

// functions actually unused
std::string ModelProblemData::getMacroGridFile() const { return ""; }

std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const {
  CommonTraits::DomainType lowerLeft(0.0);
  CommonTraits::DomainType upperRight(1.0);
  return {lowerLeft, upperRight};
}

void ModelProblemData::problem_init(DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
                                    MPIHelper::MPICommunicator local) {
  problem.getMutableDiffusion().init(problem, global, local);
}

void ModelProblemData::prepare_new_evaluation(DMP::ProblemContainer& problem) {
  problem.getMutableDiffusion().prepare_new_evaluation();
}

void Diffusion::init(const DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
                     MPIHelper::MPICommunicator local) {
  const auto cells_per_dim = problem.config().get<std::vector<std::size_t>>("grids.macro_cells_per_dim");
  std::for_each(cells_per_dim.begin(), cells_per_dim.end(), [&](size_t t) { assert(t == cells_per_dim[0]); });
  const int log2Seg = std::log2l(cells_per_dim[0]);
  int seed = 0;
  MPI_Comm_rank(global, &seed);
  assert(seed >= 0);
  const int overlap = problem.config().get("grids.overlap", 1u);
  const auto corrLen = problem.config().get("mlmc.correlation_length", 0.2f);
  const auto sigma = problem.config().get("mlmc.correlation_sigma", 1.0f);
  correlation_ = DSC::make_unique<Correlation>(corrLen, sigma);
  DSC::ScopedTiming field_tm("msfem.perm_field.init");
#if HAVE_RANDOM_PROBLEM
  field_ = DSC::make_unique<PermeabilityType>(local, *correlation_, log2Seg, seed + 1, overlap);
#else
  DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}

void Diffusion::prepare_new_evaluation() {
  DSC::ScopedTiming field_tm("msfem.perm_field.create");
#if HAVE_RANDOM_PROBLEM
  assert(field_);
  field_->create();
#else
  DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}

const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; }

const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return subBoundaryInfo_; }

ParameterTree ModelProblemData::boundary_settings() const {
  Dune::ParameterTree boundarySettings;
  if (DSC_CONFIG.has_sub("problem.boundaryInfo")) {
    boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo");
  } else {
    boundarySettings["default"] = "dirichlet";
    boundarySettings["compare_tolerance"] = "1e-10";
    switch (CommonTraits::world_dim) {
      case 1:
        DUNE_THROW(InvalidStateException, "no boundary settings for 1D random field problem");
      case 3:
        boundarySettings["neumann.0"] = "[0.0  1.0  0.0]";
        boundarySettings["neumann.1"] = "[0.0 -1.0  0.0]";
        boundarySettings["neumann.2"] = "[0.0  0.0  1.0]";
        boundarySettings["neumann.3"] = "[0.0  0.0 -1.0]";
        break;
      case 2:
        boundarySettings["neumann.0"] = "[0.0  1.0]";
        boundarySettings["neumann.1"] = "[0.0 -1.0]";
        break;
    }
  }
  return boundarySettings;
}

Diffusion::Diffusion() {}

void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& ret) const {
#if HAVE_RANDOM_PROBLEM
  assert(field_);
  const double scalar = field_->operator()(x);
  ret[0][0] = 1 * scalar;
  ret[1][1] = ret[0][0];
#else
  DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}

PURE HOT void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction,
                                       Problem::JacobianRangeType& flux) const {
  Diffusion::RangeType eval;
  evaluate(x, eval);
  flux[0][0] = eval[0][0] * direction[0][0];
  flux[0][1] = eval[1][1] * direction[0][1];
} // diffusiveFlux

size_t Diffusion::order() const { return 1; }

PURE void DirichletData::evaluate(const DomainType& x, RangeType& y) const { y = 1.0 - x[0]; } // evaluate

PURE void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.; } // evaluate

} // namespace Nine
} // namespace Problem
} // namespace Multiscale {
} // namespace Dune {
<commit_msg>fixes random perm eval in 3D<commit_after>#include <config.h>
#include <dune/common/exceptions.hh>
#include <dune/common/parallel/mpihelper.hh>
#include <dune/common/parallel/collectivecommunication.hh>
#include <dune/stuff/common/validation.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/grid/boundaryinfo.hh>
#include <dune/stuff/common/profiler.hh>
#include <dune/stuff/common/configuration.hh>
#include <dune/multiscale/problems/selector.hh>
#include <math.h>
#include <sstream>
#include <mpi.h>

#include "dune/multiscale/problems/base.hh"

#include "random.hh"

#if HAVE_RANDOM_PROBLEM
#include "random_permeability.hh"
#endif

namespace Dune {
namespace Multiscale {
namespace Problem {
namespace Random {

ModelProblemData::ModelProblemData()
  : IModelProblemData()
  , boundaryInfo_(DSG::BoundaryInfos::NormalBased<typename View::Intersection>::create(boundary_settings()))
  , subBoundaryInfo_() {}

// functions actually unused
std::string ModelProblemData::getMacroGridFile() const { return ""; }

std::pair<CommonTraits::DomainType, CommonTraits::DomainType> ModelProblemData::gridCorners() const {
  CommonTraits::DomainType lowerLeft(0.0);
  CommonTraits::DomainType upperRight(1.0);
  return {lowerLeft, upperRight};
}

void ModelProblemData::problem_init(DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
                                    MPIHelper::MPICommunicator local) {
  problem.getMutableDiffusion().init(problem, global, local);
}

void ModelProblemData::prepare_new_evaluation(DMP::ProblemContainer& problem) {
  problem.getMutableDiffusion().prepare_new_evaluation();
}

void Diffusion::init(const DMP::ProblemContainer& problem, MPIHelper::MPICommunicator global,
                     MPIHelper::MPICommunicator local) {
  const auto cells_per_dim = problem.config().get<std::vector<std::size_t>>("grids.macro_cells_per_dim");
  std::for_each(cells_per_dim.begin(), cells_per_dim.end(), [&](size_t t) { assert(t == cells_per_dim[0]); });
  const int log2Seg = std::log2l(cells_per_dim[0]);
  int seed = 0;
  MPI_Comm_rank(global, &seed);
  assert(seed >= 0);
  const int overlap = problem.config().get("grids.overlap", 1u);
  const auto corrLen = problem.config().get("mlmc.correlation_length", 0.2f);
  const auto sigma = problem.config().get("mlmc.correlation_sigma", 1.0f);
  correlation_ = DSC::make_unique<Correlation>(corrLen, sigma);
  DSC::ScopedTiming field_tm("msfem.perm_field.init");
#if HAVE_RANDOM_PROBLEM
  field_ = DSC::make_unique<PermeabilityType>(local, *correlation_, log2Seg, seed + 1, overlap);
#else
  DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}

void Diffusion::prepare_new_evaluation() {
  DSC::ScopedTiming field_tm("msfem.perm_field.create");
#if HAVE_RANDOM_PROBLEM
  assert(field_);
  field_->create();
#else
  DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}

const ModelProblemData::BoundaryInfoType& ModelProblemData::boundaryInfo() const { return *boundaryInfo_; }

const ModelProblemData::SubBoundaryInfoType& ModelProblemData::subBoundaryInfo() const { return subBoundaryInfo_; }

ParameterTree ModelProblemData::boundary_settings() const {
  Dune::ParameterTree boundarySettings;
  if (DSC_CONFIG.has_sub("problem.boundaryInfo")) {
    boundarySettings = DSC_CONFIG.sub("problem.boundaryInfo");
  } else {
    boundarySettings["default"] = "dirichlet";
    boundarySettings["compare_tolerance"] = "1e-10";
    switch (CommonTraits::world_dim) {
      case 1:
        DUNE_THROW(InvalidStateException, "no boundary settings for 1D random field problem");
      case 3:
        boundarySettings["neumann.0"] = "[0.0  1.0  0.0]";
        boundarySettings["neumann.1"] = "[0.0 -1.0  0.0]";
        boundarySettings["neumann.2"] = "[0.0  0.0  1.0]";
        boundarySettings["neumann.3"] = "[0.0  0.0 -1.0]";
        break;
      case 2:
        boundarySettings["neumann.0"] = "[0.0  1.0]";
        boundarySettings["neumann.1"] = "[0.0 -1.0]";
        break;
    }
  }
  return boundarySettings;
}

Diffusion::Diffusion() {}

void Diffusion::evaluate(const DomainType& x, Diffusion::RangeType& ret) const {
#if HAVE_RANDOM_PROBLEM
  assert(field_);
  const double scalar = field_->operator()(x);
  ret = 0;
  for(const auto i : DSC::valueRange(CommonTraits::world_dim))
    ret[i][i] = scalar;
#else
  DUNE_THROW(InvalidStateException, "random problem needs additional libs to be configured properly");
#endif
}

PURE HOT void Diffusion::diffusiveFlux(const DomainType& x, const Problem::JacobianRangeType& direction,
                                       Problem::JacobianRangeType& flux) const {
  Diffusion::RangeType eval;
  evaluate(x, eval);
  flux = 0;
  for(const auto i : DSC::valueRange(CommonTraits::world_dim))
    flux[0][i] = eval[i][i] * direction[0][i];

} // diffusiveFlux

size_t Diffusion::order() const { return 1; }

PURE void DirichletData::evaluate(const DomainType& x, RangeType& y) const { y = 1.0 - x[0]; } // evaluate

PURE void NeumannData::evaluate(const DomainType& /*x*/, RangeType& y) const { y = 0.; } // evaluate

} // namespace Nine
} // namespace Problem
} // namespace Multiscale {
} // namespace Dune {
<|endoftext|>


<commit_before>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
#define DUNE_PYMOR_FUNCTIONS_INTERFACES_HH

#include <dune/common/fmatrix.hh>
#include <dune/common/fvector.hh>

#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/common/exceptions.hh>

namespace Dune {
namespace Pymor {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class ParametricFunctionInterface
  : public Parametric
{
public:
  typedef DomainFieldImp                          DomainFieldType;
  static const unsigned int                       dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType,  >  DomainType;

  typedef RangeFieldImp                                                   RangeFieldType;
  static const unsigned int                                               dimRangeRows = rangeDimRows;
  static const unsigned int                                               dimRangeCols = rangeDimCols;
  typedef Dune::FieldMatrix< RangeFieldType, dimRangeRows, dimRangeCols > RangeType;

  static const std::string static_id()
  {
    return "parametricfunction";
  }

  virtual std::string id() const
  {
    return static_id();
  }

  virtual int order() const
  {
    return -1;
  }

  virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;

  virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
  {
    if (mu.type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "type of mu (" << mu.type() << ") does not match the parameter_type of this ("
                       << Parametric::parameter_type() << ")!");
    RangeType ret;
    evaluate(x, ret, mu);
    return ret;
  }
}; // class ParametricFunctionInterface

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows >
class ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, 1 >
  : public Parametric
{
public:
  typedef DomainFieldImp                          DomainFieldType;
  static const unsigned int                       dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType,  >  DomainType;

  typedef RangeFieldImp                                 RangeFieldType;
  static const unsigned int                             dimRangeRows = rangeDimRows;
  static const unsigned int                             dimRangeCols = 1;
  static const unsigned int                             dimRange = 1;
  typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;

  template< class... Args >
  ParametricFunctionInterface(Args&& ...args)
    : Parametric(std::forward< Args >(args)...)
  {}

  static const std::string static_id()
  {
    return "parametricfunction";
  }

  virtual std::string id() const
  {
    return static_id();
  }

  virtual int order() const
  {
    return -1;
  }

  virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;

  virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
  {
    if (mu.type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "type of mu (" << mu.type() << ") does not match the parameter_type of this ("
                       << Parametric::parameter_type() << ")!");
    RangeType ret;
    evaluate(x, ret, mu);
    return ret;
  }
}; // class ParametricFunctionInterface< ..., 1 >

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class AffineParametricFunctionInterface
  : public ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols >
{
public:
  typedef ParametricFunctionInterface<  DomainFieldImp, domainDim,
                                        RangeFieldImp, rangeDimRows, rangeDimCols > ParametricFunctionType;

  static const std::string static_id()
  {
    return "affineparametricfunction";
  }

  virtual std::string id() const
  {
    return static_id();
  }

  virtual bool hasAffinePart() const = 0;

  ParametricFunctionType* affinePart() const = 0;

  unsigned int size() const = 0;

  ParameterFunctional* coefficient(int ii) const = 0;

  ParametricFunctionType* component(int ii) const = 0;
}; // class AffineParametricFunctionInterface

} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
<commit_msg>[functions.interfaces] some fixes<commit_after>// This file is part of the dune-pymor project:
//   https://github.com/pyMor/dune-pymor
// Copyright Holders: Felix Albrecht, Stephan Rave
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
#define DUNE_PYMOR_FUNCTIONS_INTERFACES_HH

#include <dune/common/fmatrix.hh>
#include <dune/common/fvector.hh>

#include <dune/pymor/parameters/base.hh>
#include <dune/pymor/parameters/functional.hh>
#include <dune/pymor/common/exceptions.hh>

namespace Dune {
namespace Pymor {

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class ParametricFunctionInterface
  : public Parametric
{
public:
  typedef DomainFieldImp                                  DomainFieldType;
  static const unsigned int                               dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;

  typedef RangeFieldImp                                                   RangeFieldType;
  static const unsigned int                                               dimRangeRows = rangeDimRows;
  static const unsigned int                                               dimRangeCols = rangeDimCols;
  typedef Dune::FieldMatrix< RangeFieldType, dimRangeRows, dimRangeCols > RangeType;

  template< class... Args >
  ParametricFunctionInterface(Args&& ...args)
    : Parametric(std::forward< Args >(args)...)
  {}

  static const std::string static_id()
  {
    return "parametricfunction";
  }

  virtual std::string id() const
  {
    return static_id();
  }

  virtual int order() const
  {
    return -1;
  }

  virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;

  virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
  {
    if (mu.type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "type of mu (" << mu.type() << ") does not match the parameter_type of this ("
                       << Parametric::parameter_type() << ")!");
    RangeType ret;
    evaluate(x, ret, mu);
    return ret;
  }
}; // class ParametricFunctionInterface

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows >
class ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, 1 >
  : public Parametric
{
public:
  typedef DomainFieldImp                                  DomainFieldType;
  static const unsigned int                               dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;

  typedef RangeFieldImp                                 RangeFieldType;
  static const unsigned int                             dimRangeRows = rangeDimRows;
  static const unsigned int                             dimRangeCols = 1;
  static const unsigned int                             dimRange = 1;
  typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;

  template< class... Args >
  ParametricFunctionInterface(Args&& ...args)
    : Parametric(std::forward< Args >(args)...)
  {}

  static const std::string static_id()
  {
    return "parametricfunction";
  }

  virtual std::string id() const
  {
    return static_id();
  }

  virtual int order() const
  {
    return -1;
  }

  virtual evaluate(const DomainType& x, RangeType& ret, const Parameter mu = Parameter()) const = 0;

  virtual RangeType evaluate(const DomainType& x, const Parameter mu = Parameter()) const
  {
    if (mu.type() != Parametric::parameter_type())
      DUNE_PYMOR_THROW(Exception::wrong_parameter_type,
                       "type of mu (" << mu.type() << ") does not match the parameter_type of this ("
                       << Parametric::parameter_type() << ")!");
    RangeType ret;
    evaluate(x, ret, mu);
    return ret;
  }
}; // class ParametricFunctionInterface< ..., 1 >

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDimRows, int rangeDimCols >
class AffineParametricFunctionInterface
  : public ParametricFunctionInterface< DomainFieldImp, domainDim, RangeFieldImp, rangeDimRows, rangeDimCols >
{
public:
  typedef ParametricFunctionInterface<  DomainFieldImp, domainDim,
                                        RangeFieldImp, rangeDimRows, rangeDimCols > ParametricFunctionType;

  static const std::string static_id()
  {
    return "affineparametricfunction";
  }

  virtual std::string id() const
  {
    return static_id();
  }

  virtual bool hasAffinePart() const = 0;

  ParametricFunctionType* affinePart() const = 0;

  unsigned int size() const = 0;

  ParameterFunctional* coefficient(int ii) const = 0;

  ParametricFunctionType* component(int ii) const = 0;
}; // class AffineParametricFunctionInterface

} // namespace Pymor
} // namespace Dune

#endif // DUNE_PYMOR_FUNCTIONS_INTERFACES_HH
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageMomentsAlignmentCalculator.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKMeansUnsupervisedClassifier.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKernelFunction.h"
#include "itkLevelSet.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRFImageFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionImagePyramid.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperImage.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkRegistrationTransform.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkRelabelWatershedImageFilter.h"
#include "itkSegmentationBorder.h"
#include "itkSegmentationRegion.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoi2DDiagram.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedImageFilter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBalloonForce3DFilter.h"
#include "itkBalloonForceFilter.h"
#include "itkClassifier.h"
#include "itkConnectedRegionsMeshFilter.h"
#include "itkCurvatureFlowImageFilter.h"
#include "itkDeformableMesh.h"
#include "itkExtensionVelocitiesImageFilter.h"
#include "itkFastMarchingExtensionImageFilter.h"
#include "itkFastMarchingImageFilter.h"
#include "itkFuzzyConnectednessImageFilter.h"
#include "itkFuzzyConnectednessRGBImageFilter.h"
#include "itkGaussianSupervisedClassifier.h"
#include "itkGeodesicActiveContourImageFilter.h"
#include "itkGibbsPriorFilter.h"
#include "itkHybridFilter.h"
#include "itkImageMapper.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageToImageAffineMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageAffineMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffineMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageAffineNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityGradientDescentRegistration.h"
#include "itkImageToImageAffinePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkImageToImageMomentsAlignmentCalculator.h"
#include "itkImageToImageRigidMutualInformationGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkImageToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkImageToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkKLMRegionGrowImageFilter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKMeansUnsupervisedClassifier.h"
#include "itkKalmanLinearEstimator.h"
#include "itkKernelFunction.h"
#include "itkLevelSet.h"
#include "itkLevelSetImageFilter.h"
#include "itkLevelSetNeighborhoodExtractor.h"
#include "itkLevelSetVelocityNeighborhoodExtractor.h"
#include "itkMRFImageFilter.h"
#include "itkMeanSquaresImageToImageMetric.h"
#include "itkMeanSquaresPointSetToImageMetric.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkMultiResolutionImagePyramid.h"
#include "itkMultiResolutionMutualInformationAffineRegistration.h"
#include "itkMultiResolutionMutualInformationRigidRegistration.h"
#include "itkMultiResolutionRegistration.h"
#include "itkMutualInformationImageToImageMetric.h"
#include "itkNormalizedCorrelationImageToImageMetric.h"
#include "itkNormalizedCorrelationPointSetToImageMetric.h"
#include "itkPatternIntensityImageToImageMetric.h"
#include "itkPatternIntensityPointSetToImageMetric.h"
#include "itkPointSetToImageRigid3DPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageRigid3DPerspectivePatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationMeanSquaresRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationNormalizedCorrelationRegularStepGradientDescentRegistration.h"
#include "itkPointSetToImageTranslationPatternIntensityRegularStepGradientDescentRegistration.h"
#include "itkProcrustesRegistrationMetric.h"
#include "itkRGBGibbsPriorFilter.h"
#include "itkRegionGrowImageFilter.h"
#include "itkRegistrationMapper.h"
#include "itkRegistrationMapperImage.h"
#include "itkRegistrationMapperProcrustes.h"
#include "itkRegistrationMethod.h"
#include "itkRegistrationTransform.h"
#include "itkReinitializeLevelSetImageFilter.h"
#include "itkRelabelWatershedImageFilter.h"
#include "itkSegmentationBorder.h"
#include "itkSegmentationRegion.h"
#include "itkShapeDetectionLevelSetFilter.h"
#include "itkSimilarityRegistrationMetric.h"
#include "itkSupervisedClassifier.h"
#include "itkUnsupervisedClassifier.h"
#include "itkVectorFuzzyConnectednessImageFilter.h"
#include "itkVoronoi2DDiagram.h"
#include "itkVoronoiSegmentationImageFilter.h"
#include "itkVoronoiSegmentationRGBImageFilter.h"
#include "itkWatershedImageFilter.h"

int main ( int argc, char* argv )
{

  return 0;
}

<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkNeighborhoodOperatorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkScalar.h"
#include "itkRandomImageSource.h"
#include "itkFilterImageSingleOperator.h"
#include "itkWriteVTKImage.h"

int main()
{
  // Create a source
  itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::Pointer random;
  random = itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::New();

  // Create a neighborhood
  itk::NeighborhoodOperator< itkScalar<float>, 3> *neighborhood
    = itk::NeighborhoodOperator< itkScalar<float, 3>::New();

  // Create a filter
  itk::FilterImageSingleOperator< itkScalar<float>, 3>::Pointer filter;
  filter = itk::FilterImageSingleOperator< itkScalar<float>, 3>::New();
  filter->SetInput( random->GetOutput() );
  filter->SetOperator( neighborhood );

  // Create a mapper
  itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::Pointer writer;
  writer = itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::New();
  writer->SetInput(filter->GetOutput());
  writer->SetFileName("junkImage.vtk");
  writer->SetFileTypeToASCII();
  writer->DebugOn();
  writer->Write();

  return 1;
}

<commit_msg>BUG: Fixed some typos.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:    itkNeighborhoodOperatorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#include <iostream>
#include "itkImage.h"
#include "itkScalar.h"
#include "itkRandomImageSource.h"
#include "itkFilterImageSingleOperator.h"
#include "itkWriteVTKImage.h"

int main()
{
  // Create a source
  itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::Pointer random;
  random = itk::RandomImageSource< itk::Image<itk::Scalar<float>,2> >::New();

  // Create a neighborhood
  itk::Neighborhood< itk::Scalar<float>, 2> neighborhood;
  neighborhood.SetRadius(1);

  // Create a filter
  itk::FilterImageSingleOperator< itk::Scalar<float>, 2>::Pointer filter;
  filter = itk::FilterImageSingleOperator< itk::Scalar<float>, 2>::New();
  filter->SetInput( random->GetOutput() );
  filter->SetOperator( neighborhood );

  // Create a mapper
  itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::Pointer writer;
  writer = itk::WriteVTKImage< itk::Image<itk::Scalar<float>,2> >::New();
  writer->SetInput(filter->GetOutput());
  writer->SetFileName("junkImage.vtk");
  writer->SetFileTypeToASCII();
  writer->DebugOn();
  writer->Write();

  return 1;
}

<|endoftext|>


<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Authors:
//   Eugen Wintersberger <eugen.wintersberger@desy.de>
//   Martin Shetty <martin.shetty@esss.se>
// Created on: Aug 23, 2017
//

#include <gtest/gtest.h>
#include <h5cpp/datatype/factory.hpp>
#include <h5cpp/datatype/integer.hpp>

using namespace hdf5;

template<class T>
class Integer : public testing::Test {
 protected:
  Integer() {}
  virtual ~Integer() {}
  T value_;
};

template <class T>
class SignedInteger : public Integer<T> { };

template <class T>
class UnsignedInteger : public Integer<T> { };

using testing::Types;

// The list of types we want to test.
typedef
Types<
    char, unsigned char, signed char,
    short, unsigned short,
    int, unsigned int,
    long, unsigned long,
    long long, unsigned long long>
    test_types;

// The list of unsigned types we want to test.
typedef
Types<
    unsigned char,
    unsigned short,
    unsigned int,
    unsigned long,
    unsigned long long>
    test_unsigned_types;

// The list of signed types we want to test.
typedef
Types<char, signed char, short, int, long, long long>
    test_signed_types;

TYPED_TEST_CASE(Integer, test_types);
TYPED_TEST_CASE(SignedInteger, test_signed_types);
TYPED_TEST_CASE(UnsignedInteger, test_unsigned_types);

TYPED_TEST(Integer, Exceptions) {
  datatype::Datatype dtype;
  EXPECT_THROW((datatype::Integer(dtype)), std::runtime_error);

  auto ft = datatype::create<double>();
  EXPECT_THROW((datatype::Integer(ft)), std::runtime_error);
}

TYPED_TEST(Integer, General) {
  auto t = datatype::create<decltype(this->value_)>();
  EXPECT_TRUE((std::is_same<decltype(t), datatype::Integer>::value));
  EXPECT_TRUE(t.get_class() == datatype::Class::INTEGER);
  EXPECT_EQ(t.size(), sizeof(this->value_));

  datatype::Datatype &generic = t;
  datatype::Integer new_type(generic);
  EXPECT_EQ(new_type.get_class(), datatype::Class::INTEGER);

  datatype::Datatype default_constructed;
  EXPECT_FALSE(default_constructed.is_valid());
  EXPECT_THROW((datatype::Integer(default_constructed)), std::runtime_error);
}

TYPED_TEST(SignedInteger, Signed) {
  auto t = datatype::create<decltype(this->value_)>();

  ASSERT_EQ(t.is_signed(), true);
  t.make_signed(true);
  ASSERT_EQ(t.is_signed(), true);
  t.make_signed(false);
  ASSERT_EQ(t.is_signed(), false);
}

TYPED_TEST(UnsignedInteger, Signed) {
  auto t = datatype::create<decltype(this->value_)>();

  ASSERT_EQ(t.is_signed(), false);
  t.make_signed(true);
  ASSERT_EQ(t.is_signed(), true);
  t.make_signed(false);
  ASSERT_EQ(t.is_signed(), false);
}

<commit_msg>relax char tests for signed<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Authors:
//   Eugen Wintersberger <eugen.wintersberger@desy.de>
//   Martin Shetty <martin.shetty@esss.se>
// Created on: Aug 23, 2017
//

#include <gtest/gtest.h>
#include <h5cpp/datatype/factory.hpp>
#include <h5cpp/datatype/integer.hpp>

using namespace hdf5;

template<class T>
class Integer : public testing::Test {
 protected:
  Integer() {}
  virtual ~Integer() {}
  T value_;
};

template <class T>
class SignedInteger : public Integer<T> { };

template <class T>
class UnsignedInteger : public Integer<T> { };

using testing::Types;

// The list of types we want to test.
typedef
Types<
    char, unsigned char, signed char,
    short, unsigned short,
    int, unsigned int,
    long, unsigned long,
    long long, unsigned long long>
    test_types;

// The list of unsigned types we want to test.
typedef
Types<
    unsigned char,
    unsigned short,
    unsigned int,
    unsigned long,
    unsigned long long>
    test_unsigned_types;

// The list of signed types we want to test.
typedef
Types<signed char, short, int, long, long long>
    test_signed_types;

TYPED_TEST_CASE(Integer, test_types);
TYPED_TEST_CASE(SignedInteger, test_signed_types);
TYPED_TEST_CASE(UnsignedInteger, test_unsigned_types);

TYPED_TEST(Integer, Exceptions) {
  datatype::Datatype dtype;
  EXPECT_THROW((datatype::Integer(dtype)), std::runtime_error);

  auto ft = datatype::create<double>();
  EXPECT_THROW((datatype::Integer(ft)), std::runtime_error);
}

TYPED_TEST(Integer, General) {
  auto t = datatype::create<decltype(this->value_)>();
  EXPECT_TRUE((std::is_same<decltype(t), datatype::Integer>::value));
  EXPECT_TRUE(t.get_class() == datatype::Class::INTEGER);
  EXPECT_EQ(t.size(), sizeof(this->value_));

  datatype::Datatype &generic = t;
  datatype::Integer new_type(generic);
  EXPECT_EQ(new_type.get_class(), datatype::Class::INTEGER);

  datatype::Datatype default_constructed;
  EXPECT_FALSE(default_constructed.is_valid());
  EXPECT_THROW((datatype::Integer(default_constructed)), std::runtime_error);
}

TYPED_TEST(SignedInteger, Signed) {
  auto t = datatype::create<decltype(this->value_)>();

  ASSERT_EQ(t.is_signed(), true);
  t.make_signed(true);
  ASSERT_EQ(t.is_signed(), true);
  t.make_signed(false);
  ASSERT_EQ(t.is_signed(), false);
}

TYPED_TEST(UnsignedInteger, Signed) {
  auto t = datatype::create<decltype(this->value_)>();

  ASSERT_EQ(t.is_signed(), false);
  t.make_signed(true);
  ASSERT_EQ(t.is_signed(), true);
  t.make_signed(false);
  ASSERT_EQ(t.is_signed(), false);
}

<|endoftext|>


<commit_before>#ifndef PK_DEPTHFIRSTSEARCH_HPP
#define PK_DEPTHFIRSTSEARCH_HPP

#include <algorithm>

#include "stack.hpp"

namespace pk
{

class depth_first_search
{
public:
    template<
            class graph_type,
            class visitor_type>
    static void run(
            const graph_type& g,
            const int starting_vertex_id,
            visitor_type& visitor)
    {
        pk::stack<int, graph_type::max_num_of_edges> s;

        bool visited[graph_type::num_of_vertices];
        std::fill(visited, visited + graph_type::num_of_vertices, false);

        s.push(starting_vertex_id);

        while(!s.empty())
        {
            const int v = s.top();
            s.pop();

            if(visited[v])
                continue;

            visitor.visit(v);
            visited[v] = true;

            const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);
            for(int i = adj_v.size(); i >= 0; --i)
            {
                const int u = adj_v[i].to;

                if(visited[u])
                    continue;

                s.push(u);
            }
        }
    }
};

} // namespace pk

#endif // PK_DEPTHFIRSTSEARCH_HPP
<commit_msg>Fixed DFS algorithm<commit_after>#ifndef PK_DEPTHFIRSTSEARCH_HPP
#define PK_DEPTHFIRSTSEARCH_HPP

#include <algorithm>

#include "stack.hpp"

namespace pk
{

class depth_first_search
{
public:
    template<
            class graph_type,
            class visitor_type>
    static void run(
            const graph_type& g,
            const int starting_vertex_id,
            visitor_type& visitor)
    {
        pk::stack<int, graph_type::max_num_of_edges> s;

        bool visited[graph_type::num_of_vertices];
        std::fill(visited, visited + graph_type::num_of_vertices, false);

        s.push(starting_vertex_id);

        while(!s.empty())
        {
            const int v = s.top();
            s.pop();

            if(visited[v])
                continue;

            visitor.visit(v);
            visited[v] = true;

            const typename graph_type::adjacency_list& adj_v = g.get_adjacency_list(v);
            for(int i = adj_v.size() - 1; i >= 0; --i)
            {
                const int u = adj_v[i].to;

                if(visited[u])
                    continue;

                s.push(u);
            }
        }
    }
};

} // namespace pk

#endif // PK_DEPTHFIRSTSEARCH_HPP
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "settingslayer_symbian.h"
#include <QVariant>
#include "xqsettingskey.h"
#include "xqpublishandsubscribeutils.h"

#include <QDebug>

Q_GLOBAL_STATIC(SymbianSettingsLayer, symbianSettingsLayer);
QVALUESPACE_AUTO_INSTALL_LAYER(SymbianSettingsLayer);

QT_BEGIN_NAMESPACE

SymbianSettingsLayer::SymbianSettingsLayer()
{
    qDebug("SymbianSettingsLayer::SymbianSettingsLayer()");
    connect(&m_settingsManager, SIGNAL(valueChanged(const XQSettingsKey&, const QVariant&)),
            this, SLOT(valueChanged(const XQSettingsKey&, const QVariant&)));
}

SymbianSettingsLayer::~SymbianSettingsLayer()
{
    qDebug("SymbianSettingsLayer::~SymbianSettingsLayer()");

    QMutableHashIterator<QString, SymbianSettingsHandle *> i(handles);
    while (i.hasNext()) {
        i.next();

        SymbianSettingsHandle *handle = i.value();

        if (handle->valueHandle)
            removeHandle(Handle(handle));
    }

    i.toFront();
    while (i.hasNext()) {
        i.next();

        removeHandle(Handle(i.value()));
    }
}

QString SymbianSettingsLayer::name()
{
    return QLatin1String("Symbian Settings Layer");
}

QUuid SymbianSettingsLayer::id()
{
    return QVALUESPACE_SYMBIAN_SETTINGS_LAYER;
}

unsigned int SymbianSettingsLayer::order()
{
    return 0;
}

QValueSpace::LayerOptions SymbianSettingsLayer::layerOptions() const
{
    return QValueSpace::PermanentLayer |
        QValueSpace::WriteableLayer;
}

SymbianSettingsLayer *SymbianSettingsLayer::instance()
{
    return symbianSettingsLayer();
}

bool SymbianSettingsLayer::startup(Type type)
{
    qDebug("bool SymbianSettingsLayer::startup(Type type)");
    return true;
}

bool SymbianSettingsLayer::value(Handle handle, QVariant *data)
{
    qDebug("bool SymbianSettingsLayer::value(Handle handle, QVariant *data)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return false;

    return value(InvalidHandle, sh->path, data);
}

bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)
{
    qDebug("bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)");
    if (handle != InvalidHandle && !symbianSettingsHandle(handle))
        return false;

    QString path(subPath);
    while (path.endsWith(QLatin1Char('/')))
        path.chop(1);
    if (handle != InvalidHandle)
        while (path.startsWith(QLatin1Char('/')))
            path = path.mid(1);
    int index = path.lastIndexOf(QLatin1Char('/'), -1);

    bool createdHandle = false;

    QString value;
    if (index == -1) {
        value = path;
    } else {
        // want a value that is in a sub path under handle
        value = path.mid(index + 1);
        path.truncate(index);

        handle = item(handle, path);
        createdHandle = true;
    }

    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);

    QString fullPath(sh->path);
    if (fullPath != QLatin1String("/"))
        fullPath.append(QLatin1Char('/'));

    fullPath.append(value);

    bool success = false;
    if (sh) {
        PathMapper::Target target;
        quint32 category;
        quint32 key;
        if (pathMapper.resolvePath(fullPath, target, category, key)) {
            XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
            *data = m_settingsManager.readItemValue(settingsKey);
            if (!data->isNull()) {
                success = true;
            }
        }
    }

    if (createdHandle)
        removeHandle(handle);

    return success;
}

QSet<QString> SymbianSettingsLayer::children(Handle handle)
{
    qDebug("QSet<QString> SymbianSettingsLayer::children(Handle handle)");
    QSet<QString> foundChildren;

    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return foundChildren;

    pathMapper.getChildren(sh->path, foundChildren);
    return foundChildren;
}

QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)
{
    qDebug("QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)");
    QString fullPath;

    // Fail on invalid path.
    if (path.isEmpty() || path.contains(QLatin1String("//")))
        return InvalidHandle;

    if (parent == InvalidHandle) {
        fullPath = path;
    } else {
        SymbianSettingsHandle *sh = symbianSettingsHandle(parent);
        if (!sh)
            return InvalidHandle;

        if (path == QLatin1String("/")) {
            fullPath = sh->path;
        } else if (sh->path.endsWith(QLatin1Char('/')) && path.startsWith(QLatin1Char('/')))
            fullPath = sh->path + path.mid(1);
        else if (!sh->path.endsWith(QLatin1Char('/')) && !path.startsWith(QLatin1Char('/')))
            fullPath = sh->path + QLatin1Char('/') + path;
        else
            fullPath = sh->path + path;
    }

    if (handles.contains(fullPath)) {
        SymbianSettingsHandle *sh = handles.value(fullPath);
        ++sh->refCount;
        return Handle(sh);
    }

    // Create a new handle for path
    SymbianSettingsHandle *sh = new SymbianSettingsHandle(fullPath);
    handles.insert(fullPath, sh);

    return Handle(sh);
}

void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)
{
    qDebug("void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return;
    if (properties & QAbstractValueSpaceLayer::Publish) {
        QSet<QString> children;
        pathMapper.getChildren(sh->path, children);
        foreach(QString child, children) {
            QString fullPath = sh->path;
            if (fullPath.right(1) != QLatin1String("/"))
                fullPath += QLatin1Char('/');
            fullPath += child;

            PathMapper::Target target;
            quint32 category;
            quint32 key;
            if (pathMapper.resolvePath(fullPath, target, category, key)) {
                XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
                m_settingsManager.startMonitoring(settingsKey);
            }
            QByteArray hash;
            hash += qHash(target);
            hash += qHash((long)category);
            hash += qHash((unsigned long)key);
            m_monitoringHandles[hash] = sh;
        }
    }

    if (!(properties & QAbstractValueSpaceLayer::Publish)) {
        QSet<QString> children;
        pathMapper.getChildren(sh->path, children);
        foreach(QString child, children) {
            QString fullPath = sh->path;
            if (fullPath.right(1) != QLatin1String("/"))
                fullPath += QLatin1Char('/');
            fullPath += child;
            qDebug() << "TODO: Actual code for stop monitoring" << fullPath;
        }
    }
}

void SymbianSettingsLayer::removeHandle(Handle handle)
{
    qDebug("void SymbianSettingsLayer::removeHandle(Handle handle)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return;

    if (--sh->refCount)
        return;

    handles.remove(sh->path);

    delete sh;
}

bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath,
    const QVariant &data)
{
    qDebug("bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath, const QVariant &data)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return false;

    QString path(subPath);
    while (path.endsWith(QLatin1Char('/')))
        path.chop(1);

    int index = path.lastIndexOf(QLatin1Char('/'), -1);

    bool createdHandle = false;

    QString value;
    if (index == -1) {
        value = path;
    } else {
        // want a value that is in a sub path under handle
        value = path.mid(index + 1);
        path.truncate(index);

        if (path.isEmpty())
            path.append(QLatin1Char('/'));

        sh = symbianSettingsHandle(item(Handle(sh), path));
        createdHandle = true;
    }

    QString fullPath(sh->path);
    if (fullPath != QLatin1String("/"))
        fullPath.append(QLatin1Char('/'));

    fullPath.append(value);

    bool success = false;
    PathMapper::Target target;
    quint32 category;
    quint32 key;
    if (pathMapper.resolvePath(fullPath, target, category, key)) {
        if (target == PathMapper::TargetRPropery) {
            XQPublishAndSubscribeUtils utils(m_settingsManager);

            XQSettingsManager::Type type = XQSettingsManager::TypeVariant;
            switch (data.type()) {
            case QVariant::Int: type = XQSettingsManager::TypeInt; break;
            case QVariant::String: type = XQSettingsManager::TypeString; break;
            case QVariant::ByteArray: type = XQSettingsManager::TypeByteArray; break;
            default:
                return false;
            }
            utils.defineProperty(XQPublishAndSubscribeSettingsKey((long)category, (unsigned long)key), type);
        }
        XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
        success = m_settingsManager.writeItemValue(settingsKey, data);
    }

    if (createdHandle)
        removeHandle(Handle(sh));

    return success;
}

void SymbianSettingsLayer::sync()
{
    qDebug("void SymbianSettingsLayer::sync()");
    //TODO: Is this needed in Symbian?
}

bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)
{
    qDebug("bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)");
    //TODO: Is this needed in Symbian?
    return false;
}

bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator,
    Handle handle,
    const QString &subPath)
{
    qDebug("bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath)");
    //TODO: Is this needed in Symbian?
    return false;
}

void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)
{
    qDebug("void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)");
}

void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)
{
    qDebug("void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)");
}

bool SymbianSettingsLayer::supportsInterestNotification() const
{
    qDebug("bool SymbianSettingsLayer::supportsInterestNotification() const");
    return false;
}

bool SymbianSettingsLayer::notifyInterest(Handle, bool)
{
    qDebug("bool SymbianSettingsLayer::notifyInterest(Handle, bool)");
    return false;
}

void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)
{
    qDebug("void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)");
    QByteArray hash;
    hash += qHash(key.target());
    hash += qHash(key.uid());
    hash += qHash(key.key());

    if (m_monitoringHandles.contains(hash)) {
        emit handleChanged(Handle(m_monitoringHandles.value(hash)));
    }
}

QT_END_NAMESPACE
<commit_msg>Stop monitoring<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "settingslayer_symbian.h"
#include <QVariant>
#include "xqsettingskey.h"
#include "xqpublishandsubscribeutils.h"

#include <QDebug>

Q_GLOBAL_STATIC(SymbianSettingsLayer, symbianSettingsLayer);
QVALUESPACE_AUTO_INSTALL_LAYER(SymbianSettingsLayer);

QT_BEGIN_NAMESPACE

SymbianSettingsLayer::SymbianSettingsLayer()
{
    qDebug("SymbianSettingsLayer::SymbianSettingsLayer()");
    connect(&m_settingsManager, SIGNAL(valueChanged(const XQSettingsKey&, const QVariant&)),
            this, SLOT(valueChanged(const XQSettingsKey&, const QVariant&)));
}

SymbianSettingsLayer::~SymbianSettingsLayer()
{
    qDebug("SymbianSettingsLayer::~SymbianSettingsLayer()");

    QMutableHashIterator<QString, SymbianSettingsHandle *> i(handles);
    while (i.hasNext()) {
        i.next();

        SymbianSettingsHandle *handle = i.value();

        if (handle->valueHandle)
            removeHandle(Handle(handle));
    }

    i.toFront();
    while (i.hasNext()) {
        i.next();

        removeHandle(Handle(i.value()));
    }
}

QString SymbianSettingsLayer::name()
{
    return QLatin1String("Symbian Settings Layer");
}

QUuid SymbianSettingsLayer::id()
{
    return QVALUESPACE_SYMBIAN_SETTINGS_LAYER;
}

unsigned int SymbianSettingsLayer::order()
{
    return 0;
}

QValueSpace::LayerOptions SymbianSettingsLayer::layerOptions() const
{
    return QValueSpace::PermanentLayer |
        QValueSpace::WriteableLayer;
}

SymbianSettingsLayer *SymbianSettingsLayer::instance()
{
    return symbianSettingsLayer();
}

bool SymbianSettingsLayer::startup(Type type)
{
    qDebug("bool SymbianSettingsLayer::startup(Type type)");
    return true;
}

bool SymbianSettingsLayer::value(Handle handle, QVariant *data)
{
    qDebug("bool SymbianSettingsLayer::value(Handle handle, QVariant *data)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return false;

    return value(InvalidHandle, sh->path, data);
}

bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)
{
    qDebug("bool SymbianSettingsLayer::value(Handle handle, const QString &subPath, QVariant *data)");
    if (handle != InvalidHandle && !symbianSettingsHandle(handle))
        return false;

    QString path(subPath);
    while (path.endsWith(QLatin1Char('/')))
        path.chop(1);
    if (handle != InvalidHandle)
        while (path.startsWith(QLatin1Char('/')))
            path = path.mid(1);
    int index = path.lastIndexOf(QLatin1Char('/'), -1);

    bool createdHandle = false;

    QString value;
    if (index == -1) {
        value = path;
    } else {
        // want a value that is in a sub path under handle
        value = path.mid(index + 1);
        path.truncate(index);

        handle = item(handle, path);
        createdHandle = true;
    }

    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);

    QString fullPath(sh->path);
    if (fullPath != QLatin1String("/"))
        fullPath.append(QLatin1Char('/'));

    fullPath.append(value);

    bool success = false;
    if (sh) {
        PathMapper::Target target;
        quint32 category;
        quint32 key;
        if (pathMapper.resolvePath(fullPath, target, category, key)) {
            XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
            *data = m_settingsManager.readItemValue(settingsKey);
            if (!data->isNull()) {
                success = true;
            }
        }
    }

    if (createdHandle)
        removeHandle(handle);

    return success;
}

QSet<QString> SymbianSettingsLayer::children(Handle handle)
{
    qDebug("QSet<QString> SymbianSettingsLayer::children(Handle handle)");
    QSet<QString> foundChildren;

    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return foundChildren;

    pathMapper.getChildren(sh->path, foundChildren);
    return foundChildren;
}

QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)
{
    qDebug("QAbstractValueSpaceLayer::Handle SymbianSettingsLayer::item(Handle parent, const QString &path)");
    QString fullPath;

    // Fail on invalid path.
    if (path.isEmpty() || path.contains(QLatin1String("//")))
        return InvalidHandle;

    if (parent == InvalidHandle) {
        fullPath = path;
    } else {
        SymbianSettingsHandle *sh = symbianSettingsHandle(parent);
        if (!sh)
            return InvalidHandle;

        if (path == QLatin1String("/")) {
            fullPath = sh->path;
        } else if (sh->path.endsWith(QLatin1Char('/')) && path.startsWith(QLatin1Char('/')))
            fullPath = sh->path + path.mid(1);
        else if (!sh->path.endsWith(QLatin1Char('/')) && !path.startsWith(QLatin1Char('/')))
            fullPath = sh->path + QLatin1Char('/') + path;
        else
            fullPath = sh->path + path;
    }

    if (handles.contains(fullPath)) {
        SymbianSettingsHandle *sh = handles.value(fullPath);
        ++sh->refCount;
        return Handle(sh);
    }

    // Create a new handle for path
    SymbianSettingsHandle *sh = new SymbianSettingsHandle(fullPath);
    handles.insert(fullPath, sh);

    return Handle(sh);
}

void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)
{
    qDebug("void SymbianSettingsLayer::setProperty(Handle handle, Properties properties)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return;

    QSet<QString> children;
    pathMapper.getChildren(sh->path, children);
    foreach(QString child, children) {
        QString fullPath = sh->path;
        if (fullPath.right(1) != QLatin1String("/"))
            fullPath += QLatin1Char('/');
        fullPath += child;

        PathMapper::Target target;
        quint32 category;
        quint32 key;
        if (pathMapper.resolvePath(fullPath, target, category, key)) {
            XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
            QByteArray hash;
            hash += qHash(target);
            hash += qHash((long)category);
            hash += qHash((unsigned long)key);

            if (properties & QAbstractValueSpaceLayer::Publish) {
                qDebug() << "Start monitoring" << fullPath;
                m_settingsManager.startMonitoring(settingsKey);
                m_monitoringHandles[hash] = sh;
            } else {
                qDebug() << "Stop monitoring" << fullPath;
                m_settingsManager.stopMonitoring(settingsKey);
                m_monitoringHandles.remove(hash);
            }
        }
    }
}

void SymbianSettingsLayer::removeHandle(Handle handle)
{
    qDebug("void SymbianSettingsLayer::removeHandle(Handle handle)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return;

    if (--sh->refCount)
        return;

    handles.remove(sh->path);

    delete sh;
}

bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath,
    const QVariant &data)
{
    qDebug("bool SymbianSettingsLayer::setValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath, const QVariant &data)");
    SymbianSettingsHandle *sh = symbianSettingsHandle(handle);
    if (!sh)
        return false;

    QString path(subPath);
    while (path.endsWith(QLatin1Char('/')))
        path.chop(1);

    int index = path.lastIndexOf(QLatin1Char('/'), -1);

    bool createdHandle = false;

    QString value;
    if (index == -1) {
        value = path;
    } else {
        // want a value that is in a sub path under handle
        value = path.mid(index + 1);
        path.truncate(index);

        if (path.isEmpty())
            path.append(QLatin1Char('/'));

        sh = symbianSettingsHandle(item(Handle(sh), path));
        createdHandle = true;
    }

    QString fullPath(sh->path);
    if (fullPath != QLatin1String("/"))
        fullPath.append(QLatin1Char('/'));

    fullPath.append(value);

    bool success = false;
    PathMapper::Target target;
    quint32 category;
    quint32 key;
    if (pathMapper.resolvePath(fullPath, target, category, key)) {
        if (target == PathMapper::TargetRPropery) {
            XQPublishAndSubscribeUtils utils(m_settingsManager);

            XQSettingsManager::Type type = XQSettingsManager::TypeVariant;
            switch (data.type()) {
            case QVariant::Int: type = XQSettingsManager::TypeInt; break;
            case QVariant::String: type = XQSettingsManager::TypeString; break;
            case QVariant::ByteArray: type = XQSettingsManager::TypeByteArray; break;
            default:
                return false;
            }
            utils.defineProperty(XQPublishAndSubscribeSettingsKey((long)category, (unsigned long)key), type);
        }
        XQSettingsKey settingsKey(XQSettingsKey::Target(target), (long)category, (unsigned long)key);
        success = m_settingsManager.writeItemValue(settingsKey, data);
    }

    if (createdHandle)
        removeHandle(Handle(sh));

    return success;
}

void SymbianSettingsLayer::sync()
{
    qDebug("void SymbianSettingsLayer::sync()");
    //TODO: Is this needed in Symbian?
}

bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)
{
    qDebug("bool SymbianSettingsLayer::removeSubTree(QValueSpaceProvider *creator, Handle handle)");
    //TODO: Is this needed in Symbian?
    return false;
}

bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator,
    Handle handle,
    const QString &subPath)
{
    qDebug("bool SymbianSettingsLayer::removeValue(QValueSpaceProvider *creator, Handle handle, const QString &subPath)");
    //TODO: Is this needed in Symbian?
    return false;
}

void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)
{
    qDebug("void SymbianSettingsLayer::addWatch(QValueSpaceProvider *, Handle)");
}

void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)
{
    qDebug("void SymbianSettingsLayer::removeWatches(QValueSpaceProvider *, Handle)");
}

bool SymbianSettingsLayer::supportsInterestNotification() const
{
    qDebug("bool SymbianSettingsLayer::supportsInterestNotification() const");
    return false;
}

bool SymbianSettingsLayer::notifyInterest(Handle, bool)
{
    qDebug("bool SymbianSettingsLayer::notifyInterest(Handle, bool)");
    return false;
}

void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)
{
    qDebug("void SymbianSettingsLayer::valueChanged(const XQSettingsKey& key, const QVariant& value)");
    QByteArray hash;
    hash += qHash(key.target());
    hash += qHash(key.uid());
    hash += qHash(key.key());

    if (m_monitoringHandles.contains(hash)) {
        emit handleChanged(Handle(m_monitoringHandles.value(hash)));
    }
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#pragma once

#include <stdexcept>

namespace lw {
namespace error {

class Exception : public std::runtime_error {
public:
    Exception( const std::int64_t code, const std::string& message ):
        std::runtime_error( message ),
        m_error_code( code )
    {}

    // ---------------------------------------------------------------------- //

    std::int64_t error_code( void ) const {
        return m_error_code;
    }

    // ---------------------------------------------------------------------- //

private:
    std::int64_t m_error_code;
};

// -------------------------------------------------------------------------- //

#define LW_DEFINE_EXCEPTION_EX( _Type, _ParentNamespace, _Parent )  \
    class _Type : public _ParentNamespace::_Parent {                \
    public:                                                         \
        using _ParentNamespace::_Parent::_Parent;                   \
    };

#define LW_DEFINE_EXCEPTION( _Type ) \
    LW_DEFINE_EXCEPTION_EX( _Type, ::lw::error, Exception )

}
}
<commit_msg>Added UV-error macro<commit_after>#pragma once

#include <stdexcept>

namespace lw {
namespace error {

class Exception : public std::runtime_error {
public:
    Exception( const std::int64_t code, const std::string& message ):
        std::runtime_error( message ),
        m_error_code( code )
    {}

    // ---------------------------------------------------------------------- //

    std::int64_t error_code( void ) const {
        return m_error_code;
    }

    // ---------------------------------------------------------------------- //

private:
    std::int64_t m_error_code;
};

// -------------------------------------------------------------------------- //

#define LW_DEFINE_EXCEPTION_EX( _Type, _ParentNamespace, _Parent )  \
    class _Type : public _ParentNamespace::_Parent {                \
    public:                                                         \
        using _ParentNamespace::_Parent::_Parent;                   \
    };

#define LW_DEFINE_EXCEPTION( _Type ) \
    LW_DEFINE_EXCEPTION_EX( _Type, ::lw::error, Exception )

// -------------------------------------------------------------------------- //

#define LW_UV_ERROR( _Type, _code ) \
    _Type( _code, (std::string)uv_err_name( _code ) + ": " + uv_strerror( _code ) )

}
}
<|endoftext|>