<commit_before>/*
 * Copyright © 2012 Intel Corporation
 *
 * 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 of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Benjamin Segovia <benjamin.segovia@intel.com>
 */

#ifndef __GBE_PLATFORM_HPP__
#define __GBE_PLATFORM_HPP__

#include <cstddef>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <ostream>
#include <istream>
#include <string>
#include <cassert>
#include <new>

////////////////////////////////////////////////////////////////////////////////
/// CPU architecture
////////////////////////////////////////////////////////////////////////////////

/* detect 32 or 64 platform */
#if defined(__x86_64__) || defined(__ia64__) || defined(_M_X64)
#define __X86_64__
#else
#define __X86__
#endif

/* We require SSE ... */
#ifndef __SSE__
#define __SSE__
#endif

/* ... and SSE2 */
#ifndef __SSE2__
#define __SSE2__
#endif

#if defined(_INCLUDED_IMM)
// #define __AVX__
#endif

#if defined(_MSC_VER) && (_MSC_VER < 1600) && !defined(__INTEL_COMPILER) || defined(_DEBUG) && defined(_WIN32)
#define __NO_AVX__
#endif

#if defined(_MSC_VER) && !defined(__SSE4_2__)
// #define __SSE4_2__  //! activates SSE4.2 support
#endif

////////////////////////////////////////////////////////////////////////////////
/// Operating system
////////////////////////////////////////////////////////////////////////////////

/* detect Linux platform */
#if defined(linux) || defined(__linux__) || defined(__LINUX__)
#  if !defined(__LINUX__)
#     define __LINUX__
#  endif
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* detect FreeBSD platform */
#if defined(__FreeBSD__) || defined(__FREEBSD__)
#  if !defined(__FREEBSD__)
#     define __FREEBSD__
#  endif
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* detect Windows 95/98/NT/2000/XP/Vista/7 platform */
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)) && !defined(__CYGWIN__)
#  if !defined(__WIN32__)
#     define __WIN32__
#  endif
#endif

/* detect Cygwin platform */
#if defined(__CYGWIN__)
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* detect MAC OS X platform */
#if defined(__APPLE__) || defined(MACOSX) || defined(__MACOSX__)
#  if !defined(__MACOSX__)
#     define __MACOSX__
#  endif
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* try to detect other Unix systems */
#if defined(__unix__) || defined (unix) || defined(__unix) || defined(_unix)
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

////////////////////////////////////////////////////////////////////////////////
/// Compiler
////////////////////////////////////////////////////////////////////////////////

/*! GCC compiler */
#ifdef __GNUC__
// #define __GNUC__
#endif

/*! Intel compiler */
#ifdef __INTEL_COMPILER
#define __ICC__
#endif

/*! Visual C compiler */
#ifdef _MSC_VER
#define __MSVC__
#endif

////////////////////////////////////////////////////////////////////////////////
/// Makros
////////////////////////////////////////////////////////////////////////////////

#ifdef __WIN32__
#define __dllexport extern "C" __declspec(dllexport)
#define __dllimport extern "C" __declspec(dllimport)
#else
#define __dllexport extern "C"
#define __dllimport extern "C"
#endif

#ifdef __MSVC__
#undef NOINLINE
#define NOINLINE             __declspec(noinline)
#define INLINE               __forceinline
#define RESTRICT             __restrict
#define THREAD               __declspec(thread)
#define ALIGNED(...)         __declspec(align(__VA_ARGS__))
//#define __FUNCTION__           __FUNCTION__
#define DEBUGBREAK()         __debugbreak()
#else
#undef NOINLINE
#undef INLINE
#define NOINLINE        __attribute__((noinline))
#define INLINE          inline __attribute__((always_inline))
#define RESTRICT        __restrict
#define THREAD          __thread
#define ALIGNED(...)    __attribute__((aligned(__VA_ARGS__)))
#define __FUNCTION__    __PRETTY_FUNCTION__
#define DEBUGBREAK()    asm ("int $3")
#endif

/*! Modern x86 processors */
#define CACHE_LINE 64
#define CACHE_LINE_ALIGNED ALIGNED(CACHE_LINE)

#ifdef __GNUC__
  #define MAYBE_UNUSED __attribute__((used))
#else
  #define MAYBE_UNUSED
#endif

#if defined(_MSC_VER)
#define __builtin_expect(expr,b) expr
#endif

/*! Debug syntactic sugar */
#if GBE_DEBUG
#define IF_DEBUG(EXPR) EXPR
#else
#define IF_DEBUG(EXPR)
#endif /* GBE_DEBUG */

/*! Debug printing macros */
#define STRING(x) #x
#define PING std::cout << __FILE__ << " (" << __LINE__ << "): " << __FUNCTION__ << std::endl
#define PRINT(x) std::cout << STRING(x) << " = " << (x) << std::endl

/*! Branch hint */
#define LIKELY(x)       __builtin_expect(!!(x),1)
#define UNLIKELY(x)     __builtin_expect((x),0)

/*! Stringify macros */
#define JOIN(X, Y) _DO_JOIN(X, Y)
#define _DO_JOIN(X, Y) _DO_JOIN2(X, Y)
#define _DO_JOIN2(X, Y) X##Y

/*! Run-time assertion */
#if GBE_DEBUG
#define GBE_ASSERT(EXPR) do { \
  if (UNLIKELY(!(EXPR))) \
    gbe::onFailedAssertion(#EXPR, __FILE__, __FUNCTION__, __LINE__); \
} while (0)
#define GBE_ASSERTM(EXPR, MSG) do { \
  if (UNLIKELY(!(EXPR))) \
    gbe::onFailedAssertion(MSG, __FILE__, __FUNCTION__, __LINE__); \
} while (0)
#else
#define GBE_ASSERT(EXPR) do { } while (0)
#define GBE_ASSERTM(EXPR, MSG) do { } while (0)
#endif /* GBE_DEBUG */

#define NOT_IMPLEMENTED GBE_ASSERTM (false, "Not implemented")
#define NOT_SUPPORTED GBE_ASSERTM (false, "Not supported")

/*! Fatal error macros */
#define FATAL_IF(COND, MSG) \
do { \
  if(UNLIKELY(COND)) FATAL(MSG); \
} while (0)

/* Safe deletion macros */
#define GBE_SAFE_DELETE_ARRAY(x) do { if (x != NULL) GBE_DELETE_ARRAY(x); } while (0)
#define GBE_SAFE_DELETE(x) do { if (x != NULL) GBE_DELETE(x); } while (0)

/* Number of elements in an array */
#define ARRAY_ELEM_NUM(x) (sizeof(x) / sizeof(x[0]))

/* Align X on A */
#define ALIGN(X,A) (((X) % (A)) ? ((X) + (A) - ((X) % (A))) : (X))

/*! Produce a string from the macro locatiom */
#define HERE (STRING(__LINE__) "@" __FILE__)

/*! Typesafe encapusalation of a type (mostly for integers) */
#define TYPE_SAFE(SAFE, UNSAFE) \
class SAFE \
{ \
public: \
  INLINE SAFE(void) {} \
  explicit INLINE SAFE(uint16_t unsafe) : unsafe(unsafe) {} \
  INLINE operator UNSAFE (void) const { return unsafe; } \
  UNSAFE value(void) const { return unsafe; } \
private: \
  UNSAFE unsafe; \
};

/*! Default alignment for the platform */
#define GBE_DEFAULT_ALIGNMENT 16

/*! Useful constants */
#define KB 1024
#define MB (KB*KB)

/*! Portable AlignOf */
template <typename T>
struct AlignOf {
  struct Helper { char x; T t; };
  enum { value = offsetof(Helper, t) };
};

//gcc 4.8+ support C++11 alignof keyword
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8)
#define ALIGNOF(T) (alignof(T))
#else
#define ALIGNOF(T) (AlignOf<T>::value)
#endif

////////////////////////////////////////////////////////////////////////////////
/// Visibility parameters (DLL export and so on)
////////////////////////////////////////////////////////////////////////////////
#if defined __WIN32__
  #if defined __GNUC__
    #define GBE_EXPORT_SYMBOL __attribute__ ((dllexport))
    #define GBE_IMPORT_SYMBOL __attribute__ ((dllimport))
  #else
    #define GBE_IMPORT_SYMBOL __declspec(dllimport)
    #define GBE_EXPORT_SYMBOL __declspec(dllexport)
  #endif /* __GNUC__ */
#else
  #define GBE_EXPORT_SYMBOL __attribute__ ((visibility ("default")))
  #define GBE_IMPORT_SYMBOL
#endif /* __WIN32__ */

////////////////////////////////////////////////////////////////////////////////
/// Basic Types
////////////////////////////////////////////////////////////////////////////////

#if defined(__MSVC__)
typedef          __int64_t  int64_t;
typedef unsigned __int64_t uint64_t;
typedef          __int32_t  int32_t;
typedef unsigned __int32_t uint32_t;
typedef          __int16_t  int16_t;
typedef unsigned __int16_t uint16_t;
typedef          __int8_t    int8_t;
typedef unsigned __int8_t   uint8_t;
#else
#include <cstdint>
#endif

#if defined(__X86_64__)
typedef int64_t index_t;
#else
typedef int32_t index_t;
#endif

/*! To protect some classes from being copied */
class NonCopyable
{
protected:
  INLINE NonCopyable(void) {}
  INLINE ~NonCopyable(void) {}
private:
  INLINE NonCopyable(const NonCopyable&) {}
  INLINE NonCopyable& operator= (const NonCopyable&) {return *this;}
};

#define TO_MAGIC(A, B, C, D)  (A<<24 | B<<16 | C<<8 | D)

class Serializable
{
public:
  INLINE Serializable(void) = default;
  INLINE Serializable(const Serializable&) = default;
  INLINE Serializable& operator= (const Serializable&) = default;

  virtual size_t serializeToBin(std::ostream& outs) = 0;
  virtual size_t deserializeFromBin(std::istream& ins) = 0;

  /* These two will follow LLVM's ABI. */
  virtual size_t serializeToLLVM(void) { return 0;/* not implemented now. */}
  virtual size_t deserializeFromLLVM(void) { return 0;/* not implemented now. */}

  virtual void printStatus(int indent = 0, std::ostream& outs = std::cout) { }

  virtual ~Serializable(void) { }

protected:
  static std::string indent_to_str(int indent) {
    std::string ind(indent, ' ');
    return ind;
  }
};

/* Help Macro for serialization. */
#define SERIALIZE_OUT(elt, out, sz)			\
     do {						\
	  auto tmp_val = elt;				\
	  out.write((char *)(&tmp_val), sizeof(elt));	\
	  sz += sizeof(elt);				\
     } while(0)

#define DESERIALIZE_IN(elt, in, sz)			\
     do {						\
	  in.read((char *)(&(elt)), sizeof(elt));	\
	  sz += sizeof(elt);				\
     } while(0)

////////////////////////////////////////////////////////////////////////////////
/// Disable some compiler warnings
////////////////////////////////////////////////////////////////////////////////

#ifdef __ICC__
#pragma warning(disable:265)  // floating-point operation result is out of range
#pragma warning(disable:383)  // value copied to temporary, reference to temporary used
#pragma warning(disable:869)  // parameter was never referenced
#pragma warning(disable:981)  // operands are evaluated in unspecified order
#pragma warning(disable:1418) // external function definition with no prior declaration
#pragma warning(disable:1419) // external declaration in primary source file
#pragma warning(disable:1572) // floating-point equality and inequality comparisons are unreliable
#pragma warning(disable:1125) // virtual function override intended?
#endif /* __ICC__ */

////////////////////////////////////////////////////////////////////////////////
/// Default Includes and Functions
////////////////////////////////////////////////////////////////////////////////

#include "sys/alloc.hpp"

namespace gbe
{
  /*! selects */
  INLINE bool  select(bool s, bool  t , bool f) { return s ? t : f; }
  INLINE int   select(bool s, int   t,   int f) { return s ? t : f; }
  INLINE float select(bool s, float t, float f) { return s ? t : f; }

  /*! Fatal error function */
  void FATAL(const std::string&);

  /*! Return the next power of 2 */
  INLINE uint32_t nextHighestPowerOf2(uint32_t x) {
    x--;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    return ++x;
  }

  INLINE uint32_t logi2(uint32_t x) {
    uint32_t r = 0;
    while(x >>= 1) r++;
    return r;
  }

  template<uint32_t N>
  INLINE uint32_t isPowerOf(uint32_t i) {
    while (i > 1) {
      if (i%N) return false;
      i = i/N;
    }
    return true;
  }
  template<> INLINE uint32_t isPowerOf<2>(uint32_t i) { return ((i-1)&i) == 0; }

  /*! random functions */
  template<typename T> T     random() { return T(0); }
  template<> INLINE int32_t  random() { return int(rand()); }
  template<> INLINE uint32_t random() { return uint32_t(rand()); }
  template<> INLINE float    random() { return random<uint32_t>()/float(RAND_MAX); }
  template<> INLINE double   random() { return random<uint32_t>()/double(RAND_MAX); }

  /** returns performance counter in seconds */
  double getSeconds();

} /* namespace gbe */

#endif /* __GBE_PLATFORM_HPP__ */

<commit_msg>Change the KB and MB define to enum.<commit_after>/*
 * Copyright © 2012 Intel Corporation
 *
 * 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 of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Benjamin Segovia <benjamin.segovia@intel.com>
 */

#ifndef __GBE_PLATFORM_HPP__
#define __GBE_PLATFORM_HPP__

#include <cstddef>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <ostream>
#include <istream>
#include <string>
#include <cassert>
#include <new>

////////////////////////////////////////////////////////////////////////////////
/// CPU architecture
////////////////////////////////////////////////////////////////////////////////

/* detect 32 or 64 platform */
#if defined(__x86_64__) || defined(__ia64__) || defined(_M_X64)
#define __X86_64__
#else
#define __X86__
#endif

/* We require SSE ... */
#ifndef __SSE__
#define __SSE__
#endif

/* ... and SSE2 */
#ifndef __SSE2__
#define __SSE2__
#endif

#if defined(_INCLUDED_IMM)
// #define __AVX__
#endif

#if defined(_MSC_VER) && (_MSC_VER < 1600) && !defined(__INTEL_COMPILER) || defined(_DEBUG) && defined(_WIN32)
#define __NO_AVX__
#endif

#if defined(_MSC_VER) && !defined(__SSE4_2__)
// #define __SSE4_2__  //! activates SSE4.2 support
#endif

////////////////////////////////////////////////////////////////////////////////
/// Operating system
////////////////////////////////////////////////////////////////////////////////

/* detect Linux platform */
#if defined(linux) || defined(__linux__) || defined(__LINUX__)
#  if !defined(__LINUX__)
#     define __LINUX__
#  endif
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* detect FreeBSD platform */
#if defined(__FreeBSD__) || defined(__FREEBSD__)
#  if !defined(__FREEBSD__)
#     define __FREEBSD__
#  endif
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* detect Windows 95/98/NT/2000/XP/Vista/7 platform */
#if (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)) && !defined(__CYGWIN__)
#  if !defined(__WIN32__)
#     define __WIN32__
#  endif
#endif

/* detect Cygwin platform */
#if defined(__CYGWIN__)
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* detect MAC OS X platform */
#if defined(__APPLE__) || defined(MACOSX) || defined(__MACOSX__)
#  if !defined(__MACOSX__)
#     define __MACOSX__
#  endif
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

/* try to detect other Unix systems */
#if defined(__unix__) || defined (unix) || defined(__unix) || defined(_unix)
#  if !defined(__UNIX__)
#     define __UNIX__
#  endif
#endif

////////////////////////////////////////////////////////////////////////////////
/// Compiler
////////////////////////////////////////////////////////////////////////////////

/*! GCC compiler */
#ifdef __GNUC__
// #define __GNUC__
#endif

/*! Intel compiler */
#ifdef __INTEL_COMPILER
#define __ICC__
#endif

/*! Visual C compiler */
#ifdef _MSC_VER
#define __MSVC__
#endif

////////////////////////////////////////////////////////////////////////////////
/// Makros
////////////////////////////////////////////////////////////////////////////////

#ifdef __WIN32__
#define __dllexport extern "C" __declspec(dllexport)
#define __dllimport extern "C" __declspec(dllimport)
#else
#define __dllexport extern "C"
#define __dllimport extern "C"
#endif

#ifdef __MSVC__
#undef NOINLINE
#define NOINLINE             __declspec(noinline)
#define INLINE               __forceinline
#define RESTRICT             __restrict
#define THREAD               __declspec(thread)
#define ALIGNED(...)         __declspec(align(__VA_ARGS__))
//#define __FUNCTION__           __FUNCTION__
#define DEBUGBREAK()         __debugbreak()
#else
#undef NOINLINE
#undef INLINE
#define NOINLINE        __attribute__((noinline))
#define INLINE          inline __attribute__((always_inline))
#define RESTRICT        __restrict
#define THREAD          __thread
#define ALIGNED(...)    __attribute__((aligned(__VA_ARGS__)))
#define __FUNCTION__    __PRETTY_FUNCTION__
#define DEBUGBREAK()    asm ("int $3")
#endif

/*! Modern x86 processors */
#define CACHE_LINE 64
#define CACHE_LINE_ALIGNED ALIGNED(CACHE_LINE)

#ifdef __GNUC__
  #define MAYBE_UNUSED __attribute__((used))
#else
  #define MAYBE_UNUSED
#endif

#if defined(_MSC_VER)
#define __builtin_expect(expr,b) expr
#endif

/*! Debug syntactic sugar */
#if GBE_DEBUG
#define IF_DEBUG(EXPR) EXPR
#else
#define IF_DEBUG(EXPR)
#endif /* GBE_DEBUG */

/*! Debug printing macros */
#define STRING(x) #x
#define PING std::cout << __FILE__ << " (" << __LINE__ << "): " << __FUNCTION__ << std::endl
#define PRINT(x) std::cout << STRING(x) << " = " << (x) << std::endl

/*! Branch hint */
#define LIKELY(x)       __builtin_expect(!!(x),1)
#define UNLIKELY(x)     __builtin_expect((x),0)

/*! Stringify macros */
#define JOIN(X, Y) _DO_JOIN(X, Y)
#define _DO_JOIN(X, Y) _DO_JOIN2(X, Y)
#define _DO_JOIN2(X, Y) X##Y

/*! Run-time assertion */
#if GBE_DEBUG
#define GBE_ASSERT(EXPR) do { \
  if (UNLIKELY(!(EXPR))) \
    gbe::onFailedAssertion(#EXPR, __FILE__, __FUNCTION__, __LINE__); \
} while (0)
#define GBE_ASSERTM(EXPR, MSG) do { \
  if (UNLIKELY(!(EXPR))) \
    gbe::onFailedAssertion(MSG, __FILE__, __FUNCTION__, __LINE__); \
} while (0)
#else
#define GBE_ASSERT(EXPR) do { } while (0)
#define GBE_ASSERTM(EXPR, MSG) do { } while (0)
#endif /* GBE_DEBUG */

#define NOT_IMPLEMENTED GBE_ASSERTM (false, "Not implemented")
#define NOT_SUPPORTED GBE_ASSERTM (false, "Not supported")

/*! Fatal error macros */
#define FATAL_IF(COND, MSG) \
do { \
  if(UNLIKELY(COND)) FATAL(MSG); \
} while (0)

/* Safe deletion macros */
#define GBE_SAFE_DELETE_ARRAY(x) do { if (x != NULL) GBE_DELETE_ARRAY(x); } while (0)
#define GBE_SAFE_DELETE(x) do { if (x != NULL) GBE_DELETE(x); } while (0)

/* Number of elements in an array */
#define ARRAY_ELEM_NUM(x) (sizeof(x) / sizeof(x[0]))

/* Align X on A */
#define ALIGN(X,A) (((X) % (A)) ? ((X) + (A) - ((X) % (A))) : (X))

/*! Produce a string from the macro locatiom */
#define HERE (STRING(__LINE__) "@" __FILE__)

/*! Typesafe encapusalation of a type (mostly for integers) */
#define TYPE_SAFE(SAFE, UNSAFE) \
class SAFE \
{ \
public: \
  INLINE SAFE(void) {} \
  explicit INLINE SAFE(uint16_t unsafe) : unsafe(unsafe) {} \
  INLINE operator UNSAFE (void) const { return unsafe; } \
  UNSAFE value(void) const { return unsafe; } \
private: \
  UNSAFE unsafe; \
};

/*! Default alignment for the platform */
#define GBE_DEFAULT_ALIGNMENT 16

namespace gbe
{
/*! Useful constants */
  enum {
    KB = 1024,
    MB = (KB*KB),
  };
}
/*! Portable AlignOf */
template <typename T>
struct AlignOf {
  struct Helper { char x; T t; };
  enum { value = offsetof(Helper, t) };
};

//gcc 4.8+ support C++11 alignof keyword
#if (__GNUC__ >= 4 && __GNUC_MINOR__ >= 8)
#define ALIGNOF(T) (alignof(T))
#else
#define ALIGNOF(T) (AlignOf<T>::value)
#endif

////////////////////////////////////////////////////////////////////////////////
/// Visibility parameters (DLL export and so on)
////////////////////////////////////////////////////////////////////////////////
#if defined __WIN32__
  #if defined __GNUC__
    #define GBE_EXPORT_SYMBOL __attribute__ ((dllexport))
    #define GBE_IMPORT_SYMBOL __attribute__ ((dllimport))
  #else
    #define GBE_IMPORT_SYMBOL __declspec(dllimport)
    #define GBE_EXPORT_SYMBOL __declspec(dllexport)
  #endif /* __GNUC__ */
#else
  #define GBE_EXPORT_SYMBOL __attribute__ ((visibility ("default")))
  #define GBE_IMPORT_SYMBOL
#endif /* __WIN32__ */

////////////////////////////////////////////////////////////////////////////////
/// Basic Types
////////////////////////////////////////////////////////////////////////////////

#if defined(__MSVC__)
typedef          __int64_t  int64_t;
typedef unsigned __int64_t uint64_t;
typedef          __int32_t  int32_t;
typedef unsigned __int32_t uint32_t;
typedef          __int16_t  int16_t;
typedef unsigned __int16_t uint16_t;
typedef          __int8_t    int8_t;
typedef unsigned __int8_t   uint8_t;
#else
#include <cstdint>
#endif

#if defined(__X86_64__)
typedef int64_t index_t;
#else
typedef int32_t index_t;
#endif

/*! To protect some classes from being copied */
class NonCopyable
{
protected:
  INLINE NonCopyable(void) {}
  INLINE ~NonCopyable(void) {}
private:
  INLINE NonCopyable(const NonCopyable&) {}
  INLINE NonCopyable& operator= (const NonCopyable&) {return *this;}
};

#define TO_MAGIC(A, B, C, D)  (A<<24 | B<<16 | C<<8 | D)

class Serializable
{
public:
  INLINE Serializable(void) = default;
  INLINE Serializable(const Serializable&) = default;
  INLINE Serializable& operator= (const Serializable&) = default;

  virtual size_t serializeToBin(std::ostream& outs) = 0;
  virtual size_t deserializeFromBin(std::istream& ins) = 0;

  /* These two will follow LLVM's ABI. */
  virtual size_t serializeToLLVM(void) { return 0;/* not implemented now. */}
  virtual size_t deserializeFromLLVM(void) { return 0;/* not implemented now. */}

  virtual void printStatus(int indent = 0, std::ostream& outs = std::cout) { }

  virtual ~Serializable(void) { }

protected:
  static std::string indent_to_str(int indent) {
    std::string ind(indent, ' ');
    return ind;
  }
};

/* Help Macro for serialization. */
#define SERIALIZE_OUT(elt, out, sz)			\
     do {						\
	  auto tmp_val = elt;				\
	  out.write((char *)(&tmp_val), sizeof(elt));	\
	  sz += sizeof(elt);				\
     } while(0)

#define DESERIALIZE_IN(elt, in, sz)			\
     do {						\
	  in.read((char *)(&(elt)), sizeof(elt));	\
	  sz += sizeof(elt);				\
     } while(0)

////////////////////////////////////////////////////////////////////////////////
/// Disable some compiler warnings
////////////////////////////////////////////////////////////////////////////////

#ifdef __ICC__
#pragma warning(disable:265)  // floating-point operation result is out of range
#pragma warning(disable:383)  // value copied to temporary, reference to temporary used
#pragma warning(disable:869)  // parameter was never referenced
#pragma warning(disable:981)  // operands are evaluated in unspecified order
#pragma warning(disable:1418) // external function definition with no prior declaration
#pragma warning(disable:1419) // external declaration in primary source file
#pragma warning(disable:1572) // floating-point equality and inequality comparisons are unreliable
#pragma warning(disable:1125) // virtual function override intended?
#endif /* __ICC__ */

////////////////////////////////////////////////////////////////////////////////
/// Default Includes and Functions
////////////////////////////////////////////////////////////////////////////////

#include "sys/alloc.hpp"

namespace gbe
{
  /*! selects */
  INLINE bool  select(bool s, bool  t , bool f) { return s ? t : f; }
  INLINE int   select(bool s, int   t,   int f) { return s ? t : f; }
  INLINE float select(bool s, float t, float f) { return s ? t : f; }

  /*! Fatal error function */
  void FATAL(const std::string&);

  /*! Return the next power of 2 */
  INLINE uint32_t nextHighestPowerOf2(uint32_t x) {
    x--;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
    x |= x >> 16;
    return ++x;
  }

  INLINE uint32_t logi2(uint32_t x) {
    uint32_t r = 0;
    while(x >>= 1) r++;
    return r;
  }

  template<uint32_t N>
  INLINE uint32_t isPowerOf(uint32_t i) {
    while (i > 1) {
      if (i%N) return false;
      i = i/N;
    }
    return true;
  }
  template<> INLINE uint32_t isPowerOf<2>(uint32_t i) { return ((i-1)&i) == 0; }

  /*! random functions */
  template<typename T> T     random() { return T(0); }
  template<> INLINE int32_t  random() { return int(rand()); }
  template<> INLINE uint32_t random() { return uint32_t(rand()); }
  template<> INLINE float    random() { return random<uint32_t>()/float(RAND_MAX); }
  template<> INLINE double   random() { return random<uint32_t>()/double(RAND_MAX); }

  /** returns performance counter in seconds */
  double getSeconds();

} /* namespace gbe */

#endif /* __GBE_PLATFORM_HPP__ */

<|endoftext|>


<commit_before>// Write bits into a bit stream.  See BitStream for reading.

#ifndef __THIS_FILE_Q__
#define __THIS_FILE_Q__

class Pipeline;

class BitWriter
{
  public:
    // Write bits to the pipeline.  It is the caller's responsibility
    // to eventually call finish on the pipeline.
    BitWriter(Pipeline* pl);
    void writeBits(unsigned long val, int bits);
    // Force any partial byte to be written to the pipeline.
    void flush();

  private:
    Pipeline* pl;
    unsigned char ch;
    unsigned int bit_offset;
};

#endif // __THIS_FILE_Q__
<commit_msg>fix header symbol<commit_after>// Write bits into a bit stream.  See BitStream for reading.

#ifndef __BITWRITER_HH__
#define __BITWRITER_HH__

class Pipeline;

class BitWriter
{
  public:
    // Write bits to the pipeline.  It is the caller's responsibility
    // to eventually call finish on the pipeline.
    BitWriter(Pipeline* pl);
    void writeBits(unsigned long val, int bits);
    // Force any partial byte to be written to the pipeline.
    void flush();

  private:
    Pipeline* pl;
    unsigned char ch;
    unsigned int bit_offset;
};

#endif // __BITWRITER_HH__
<|endoftext|>


<commit_before><commit_msg>Fixing metadata printout - it is now nicely aligned<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <cstdlib>
#include <deque>
#include <ctime>
#include <vector>

using namespace std;

class nAryInt{
private:
  const unsigned int base;
  // Digits stored with least significant digit first
  deque<unsigned int> digits;
  vector<bool> digitsUsed;

public:
  // Constructor from single digit
  nAryInt(unsigned int digit, unsigned int base): base(base){
	digitsUsed=vector<bool>(base,false);
	digitsUsed[digit-1]=true;
	digits.push_back(digit);
  }

  // Add an extra digit at the least significant place, shifting the existing
  void appendDigit(unsigned int digit){
	if(digit>=base){
  	  cout << "The digit to append must be smaller than the base number!" << endl;
  	  exit(0);
  	}
	digits.push_front(digit);
	digitsUsed[digit-1]=true;
  }

  void removeDigit(){
	digitsUsed[digits.front()-1]=false;
	digits.pop_front();
	return;
  }

  // Check if some digit is already contained
  bool contains(unsigned int digit){
    return digitsUsed[digit-1];
  }

  // Check if divisible by some digit
  // Mimics the pencil-and-paper division method
  bool isDivisible(unsigned int digit){
	unsigned int remainder=0;
    for(auto i=digits.crbegin();i!=digits.rend();i++){
	  remainder=(base*remainder+*i)%digit;
	}
	if(remainder!=0){
	  return false;
	}
	return true;
  }

  unsigned int size(){
	return digits.size();
  }

  unsigned int getBase(){
	return base;
  }

  friend std::ostream& operator<< (std::ostream & out, nAryInt const& obj);
};

// Printing of nAryInt-objects
std::ostream& operator<< (std::ostream & out, nAryInt const& obj){
  for(auto i=obj.digits.crbegin();i!=obj.digits.rend();i++){
	out << *i << ", ";
  }
  return out;
}

// Recursive function to check possible digits to add
void expand(nAryInt &a){
  if(a.size()==a.getBase()-1){
	cout << a << endl;
	return;
  }
  for(unsigned int digit=1;digit<a.getBase();digit++){
	if(!a.contains(digit)){
	  // Append the digit and expand further if it gives a feasible subsolution
	  a.appendDigit(digit);
	  if(a.isDivisible(a.size())){
		expand(a);
	  }
	  a.removeDigit();
	}
  }
  return;
}

int main(int argc, char* argv[]){
  if(argc!=2){
	cout << "The program expects as input the base number" << endl;
	exit(0);
  }
  unsigned int base=strtoul(argv[1],NULL,10);
  cout << "Polydivisible numbers in base " << base << ":" << endl;
  clock_t startTime=clock();
  #pragma omp parallel for
  for(unsigned int i=1;i<base;i++){
	nAryInt a(i,base);
	expand(a);
  }
  clock_t endTime=clock();
  cout << "Answer computed in "
	   << ((float)(endTime-startTime))/CLOCKS_PER_SEC << " seconds" << endl;
  return 0;
}
<commit_msg>Untabify<commit_after>#include <iostream>
#include <cstdlib>
#include <deque>
#include <ctime>
#include <vector>

using namespace std;

class nAryInt{
private:
  const unsigned int base;
  // Digits stored with least significant digit first
  deque<unsigned int> digits;
  vector<bool> digitsUsed;

public:
  // Constructor from single digit
  nAryInt(unsigned int digit, unsigned int base): base(base){
    digitsUsed=vector<bool>(base,false);
    digitsUsed[digit-1]=true;
    digits.push_back(digit);
  }

  // Add an extra digit at the least significant place, shifting the existing
  void appendDigit(unsigned int digit){
    if(digit>=base){
      cout << "The digit to append must be smaller than the base number!" << endl;
      exit(0);
    }
    digits.push_front(digit);
    digitsUsed[digit-1]=true;
  }

  void removeDigit(){
    digitsUsed[digits.front()-1]=false;
    digits.pop_front();
    return;
  }

  // Check if some digit is already contained
  bool contains(unsigned int digit){
    return digitsUsed[digit-1];
  }

  // Check if divisible by some digit
  // Mimics the pencil-and-paper division method
  bool isDivisible(unsigned int digit){
    unsigned int remainder=0;
    for(auto i=digits.crbegin();i!=digits.rend();i++){
      remainder=(base*remainder+*i)%digit;
    }
    if(remainder!=0){
      return false;
    }
    return true;
  }

  unsigned int size(){
    return digits.size();
  }

  unsigned int getBase(){
    return base;
  }

  friend std::ostream& operator<< (std::ostream & out, nAryInt const& obj);
};

// Printing of nAryInt-objects
std::ostream& operator<< (std::ostream & out, nAryInt const& obj){
  for(auto i=obj.digits.crbegin();i!=obj.digits.rend();i++){
    out << *i << ", ";
  }
  return out;
}

// Recursive function to check possible digits to add
void expand(nAryInt &a){
  if(a.size()==a.getBase()-1){
    cout << a << endl;
    return;
  }
  for(unsigned int digit=1;digit<a.getBase();digit++){
    if(!a.contains(digit)){
      // Append the digit and expand further if it gives a feasible subsolution
      a.appendDigit(digit);
      if(a.isDivisible(a.size())){
        expand(a);
      }
      a.removeDigit();
    }
  }
  return;
}

int main(int argc, char* argv[]){
  if(argc!=2){
    cout << "The program expects as input the base number" << endl;
    exit(0);
  }
  unsigned int base=strtoul(argv[1],NULL,10);
  cout << "Polydivisible numbers in base " << base << ":" << endl;
  clock_t startTime=clock();
#pragma omp parallel for
  for(unsigned int i=1;i<base;i++){
    nAryInt a(i,base);
    expand(a);
  }
  clock_t endTime=clock();
  cout << "Answer computed in "
       << ((float)(endTime-startTime))/CLOCKS_PER_SEC << " seconds" << endl;
  return 0;
}
<|endoftext|>


<commit_before>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef __YLIKUUTIO_LINEAR_ALGEBRA_TENSOR3_HPP_INCLUDED
#define __YLIKUUTIO_LINEAR_ALGEBRA_TENSOR3_HPP_INCLUDED

#include "matrix.hpp"

// Include standard headers
#include <cstddef>  // std::size_t
#include <memory>   // std::make_shared, std::shared_ptr
#include <vector>   // std::vector

namespace yli::linear_algebra
{
    class Tensor3
    {
        // `class Tensor3` uses the coordinate order x, y, z:
        // x = 0 is the leftmost slice.
        // y = 0 is the uppermost slice
        // z = 0 is the front slice.

        public:
            // constructor.
            Tensor3(std::size_t width, std::size_t height, std::size_t depth);

            // copy constructor.
            Tensor3(const yli::linear_algebra::Tensor3& old_tensor3);
            Tensor3(std::shared_ptr<yli::linear_algebra::Tensor3> old_matrix)
                : Tensor3(*old_matrix) { }

            // constructor.
            explicit Tensor3(const yli::linear_algebra::Matrix& old_matrix);

            // Inspired by http://stackoverflow.com/questions/6969881/operator-overload/6969904#6969904
            class Proxy2D
            {
                public:
                    explicit Proxy2D(const std::vector<std::vector<float>>& array_of_arrays)
                        : array_of_arrays(array_of_arrays)
                    { }

                    class Proxy
                    {
                        public:
                            explicit Proxy(std::vector<float>& proxy_array)
                                : proxy_array(proxy_array)
                            { }

                            float& operator[](const std::size_t index)
                            {
                                return proxy_array[index];
                            }

                        private:
                            std::vector<float>& proxy_array;
                    };

                    Proxy operator[](const std::size_t index)
                    {
                        return Proxy(array_of_arrays[index]);
                    }

                private:
                    std::vector<std::vector<float>> array_of_arrays;
            };

            void operator<<(const float rhs);
            void operator<<(const std::vector<float>& rhs);
            bool operator==(const yli::linear_algebra::Tensor3& rhs) const;
            bool operator!=(const yli::linear_algebra::Tensor3& rhs) const;
            Proxy2D operator[](const std::size_t index)
            {
                return Proxy2D(this->array_of_arrays_of_arrays[index]);
            }

            bool is_cube;
            std::size_t width;
            std::size_t height;
            std::size_t depth;

        private:
            bool is_fully_populated;

            // For populating, the order of coordinates from
            // the one changing fastest to the one changing slowest is:
            // x, y, z
            std::size_t next_x_to_populate;
            std::size_t next_y_to_populate;
            std::size_t next_z_to_populate;

            std::vector<std::vector<std::vector<float>>> array_of_arrays_of_arrays;
    };
}

#endif
<commit_msg>`Tensor3`: make 1 parameter constructor `explicit`.<commit_after>// Ylikuutio - A 3D game and simulation engine.
//
// Copyright (C) 2015-2021 Antti Nuortimo.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

#ifndef __YLIKUUTIO_LINEAR_ALGEBRA_TENSOR3_HPP_INCLUDED
#define __YLIKUUTIO_LINEAR_ALGEBRA_TENSOR3_HPP_INCLUDED

#include "matrix.hpp"

// Include standard headers
#include <cstddef>  // std::size_t
#include <memory>   // std::make_shared, std::shared_ptr
#include <vector>   // std::vector

namespace yli::linear_algebra
{
    class Tensor3
    {
        // `class Tensor3` uses the coordinate order x, y, z:
        // x = 0 is the leftmost slice.
        // y = 0 is the uppermost slice
        // z = 0 is the front slice.

        public:
            // constructor.
            Tensor3(std::size_t width, std::size_t height, std::size_t depth);

            // copy constructor.
            Tensor3(const yli::linear_algebra::Tensor3& old_tensor3);

            explicit Tensor3(std::shared_ptr<yli::linear_algebra::Tensor3> old_matrix)
                : Tensor3(*old_matrix) { }

            // constructor.
            explicit Tensor3(const yli::linear_algebra::Matrix& old_matrix);

            // Inspired by http://stackoverflow.com/questions/6969881/operator-overload/6969904#6969904
            class Proxy2D
            {
                public:
                    explicit Proxy2D(const std::vector<std::vector<float>>& array_of_arrays)
                        : array_of_arrays(array_of_arrays)
                    { }

                    class Proxy
                    {
                        public:
                            explicit Proxy(std::vector<float>& proxy_array)
                                : proxy_array(proxy_array)
                            { }

                            float& operator[](const std::size_t index)
                            {
                                return proxy_array[index];
                            }

                        private:
                            std::vector<float>& proxy_array;
                    };

                    Proxy operator[](const std::size_t index)
                    {
                        return Proxy(array_of_arrays[index]);
                    }

                private:
                    std::vector<std::vector<float>> array_of_arrays;
            };

            void operator<<(const float rhs);
            void operator<<(const std::vector<float>& rhs);
            bool operator==(const yli::linear_algebra::Tensor3& rhs) const;
            bool operator!=(const yli::linear_algebra::Tensor3& rhs) const;
            Proxy2D operator[](const std::size_t index)
            {
                return Proxy2D(this->array_of_arrays_of_arrays[index]);
            }

            bool is_cube;
            std::size_t width;
            std::size_t height;
            std::size_t depth;

        private:
            bool is_fully_populated;

            // For populating, the order of coordinates from
            // the one changing fastest to the one changing slowest is:
            // x, y, z
            std::size_t next_x_to_populate;
            std::size_t next_y_to_populate;
            std::size_t next_z_to_populate;

            std::vector<std::vector<std::vector<float>>> array_of_arrays_of_arrays;
    };
}

#endif
<|endoftext|>


<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

//
// This file gets processed by doxygen and ends up as the main page in index.html.
// Do not put code here, just comments for doxyen that don't seem to fit elsewhere.
//
/**
 ***************************************************************
 @mainpage

 @section Introduction

 The watcher system is composed of three components: a number of test node daemons, a watcher daemon instance,

 @section Build
 @subsection Dependencies

 The watcher relies on a bunch of stuff, they are here: @ref WatcherDependencies.

 @subsection Instructions

 The watcher system is built using auto-tools.

 @section Components
 @subsection Test Node Daemons

  @ref sendColorMessage

  @ref sendConnectivityMessage

  @ref sendGPSMessage

 @subpage watcherd "Watcher Daemon"
 @subsection GUIs
 @subsubsection Legacy Watcher
 @subsubsection Watcher3d

 @section About

  Point of contact: Geoff Lawler <geoff.lawler@cobham.com>

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

/** @namespace libconfig
 * The libconfig namespace is the namespace in the third party library libconfig++, which the watcher system uses for reading and writing cfg files
 */
/** @namespace log4cxx
 * The namespace for the third party library log4cxx which the watcher uses to do all its logging. */

/**
 * @page UsersGuide
 * @section TOC
 *
Table of Contents

 * @section Modules
 *  Module Descriptions
 * @section HowTo
 *  How to do stuff
 * @section Glossary
 *  Glossary of Terms
 * @section Index
 */

/**
 * @page WatcherDependencies
 *
 * @section ThirdParty
 *
 * @li libconfig 1.3.1
 *
 *  the system uses this for creating, reading, and writing to configuration ("cfg") files.
 *
 * @li log4cxx 0.10.0, which depends on lib apr 1.3.3 and lib apr util 1.3.4
 *
 * This is used for all logging.
 *
 * @li boost 1.38
 *
 * C++ library used more many things: serialization, network code, regular expressions, etc.
 *
 * @li qt 4.3
 *
 * Used in the GUI for window frames, GUI widgets, mouse and keyboard handling, etc.
 *
 * @li sqlite 3
 *
 * This is the database used in the watcher daemon.
 *
 * @li qwt-5.1.1
 *
 * A small Qt-based library used to draw the 2d scrolling graphs in the watcher .
 *
 * @section Internal
 *
 * @li libwatcherutil
 *
 * Holds a few things that most components need, like parsing command line args to get to the cfg file.
 *
 * @li liblogger
 *
 * A small wrapper around log4cxx to abstract which logging library we use.
 *
 * @li libwatcher
 *
 * The core of the watcher messaging system, the watcher APIs between test node daemons, a watcher daemon, and the GUI(s)s.
 *
 *
 */
<commit_msg>Automated merge with ssh://src.columbia.sparta.com//project/watcher/hg/watcher<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
 *
 * This file is part of WATCHER.
 *
 *     WATCHER is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     WATCHER is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Watcher.  If not, see <http://www.gnu.org/licenses/>.
 */

//
// This file gets processed by doxygen and ends up as the main page in index.html.
// Do not put code here, just comments for doxyen that don't seem to fit elsewhere.
//
/**
 ***************************************************************
 @mainpage

 @section Introduction

 The watcher system is composed of three components: a number of test node daemons, a watcher daemon instance,

 @section Build
 @subsection Dependencies

 The watcher relies on a bunch of stuff, they are here: @ref WatcherDependencies.

 @subsection Instructions

 The watcher system is built using auto-tools.

 @section Components
 @subsection Test Node Daemons

  @ref sendColorMessage

  @ref sendConnectivityMessage

  @ref sendGPSMessage

 @subpage watcherd "Watcher Daemon"
 @subsection GUIs
 @subsubsection Legacy Watcher
 @subsubsection Watcher3d

 @section About

  Point of contact: Geoff Lawler <geoff.lawler@cobham.com>

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

/** @namespace libconfig
 * The libconfig namespace is the namespace in the third party library libconfig++, which the watcher system uses for reading and writing cfg files
 */
/** @namespace log4cxx
 * The namespace for the third party library log4cxx which the watcher uses to do all its logging. */

/**
 * @page UsersGuide
 * The User's Guide can be built by doing a 'make' in the ./src/doc directory.
 */

/**
 * @page WatcherDependencies
 *
 * @section ThirdParty
 *
 * @li libconfig 1.3.1
 *
 *  the system uses this for creating, reading, and writing to configuration ("cfg") files.
 *
 * @li log4cxx 0.10.0, which depends on lib apr 1.3.3 and lib apr util 1.3.4
 *
 * This is used for all logging.
 *
 * @li boost 1.38
 *
 * C++ library used more many things: serialization, network code, regular expressions, etc.
 *
 * @li qt 4.3
 *
 * Used in the GUI for window frames, GUI widgets, mouse and keyboard handling, etc.
 *
 * @li sqlite 3
 *
 * This is the database used in the watcher daemon.
 *
 * @li qwt-5.1.1
 *
 * A small Qt-based library used to draw the 2d scrolling graphs in the watcher .
 *
 * @section Internal
 *
 * @li libwatcherutil
 *
 * Holds a few things that most components need, like parsing command line args to get to the cfg file.
 *
 * @li liblogger
 *
 * A small wrapper around log4cxx to abstract which logging library we use.
 *
 * @li libwatcher
 *
 * The core of the watcher messaging system, the watcher APIs between test node daemons, a watcher daemon, and the GUI(s)s.
 *
 *
 */
<|endoftext|>


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

#include "base/object_watcher.h"

#include "base/logging.h"

namespace base {

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

struct ObjectWatcher::Watch : public Task {
  ObjectWatcher* watcher;    // The associated ObjectWatcher instance
  HANDLE object;             // The object being watched
  HANDLE wait_object;        // Returned by RegisterWaitForSingleObject
  MessageLoop* origin_loop;  // Used to get back to the origin thread
  Delegate* delegate;        // Delegate to notify when signaled
  bool did_signal;           // DoneWaiting was called

  virtual void Run() {
    // The watcher may have already been torn down, in which case we need to
    // just get out of dodge.
    if (!watcher)
      return;

    DCHECK(did_signal);
    watcher->StopWatching();

    delegate->OnObjectSignaled(object);
  }
};

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

ObjectWatcher::ObjectWatcher() : watch_(NULL) {
}

ObjectWatcher::~ObjectWatcher() {
  StopWatching();
}

bool ObjectWatcher::StartWatching(HANDLE object, Delegate* delegate) {
  if (watch_) {
    NOTREACHED() << "Already watching an object";
    return false;
  }

  Watch* watch = new Watch;
  watch->watcher = this;
  watch->object = object;
  watch->origin_loop = MessageLoop::current();
  watch->delegate = delegate;
  watch->did_signal = false;

  // Since our job is to just notice when an object is signaled and report the
  // result back to this thread, we can just run on a Windows wait thread.
  DWORD wait_flags = WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE;

  if (!RegisterWaitForSingleObject(&watch->wait_object, object, DoneWaiting,
                                   watch, INFINITE, wait_flags)) {
    NOTREACHED() << "RegisterWaitForSingleObject failed: " << GetLastError();
    delete watch;
    return false;
  }

  watch_ = watch;

  // We need to know if the current message loop is going away so we can
  // prevent the wait thread from trying to access a dead message loop.
  MessageLoop::current()->AddDestructionObserver(this);
  return true;
}

bool ObjectWatcher::StopWatching() {
  if (!watch_)
    return false;

  // Make sure ObjectWatcher is used in a single-threaded fashion.
  DCHECK(watch_->origin_loop == MessageLoop::current());

  // If DoneWaiting is in progress, we wait for it to finish.  We know whether
  // DoneWaiting happened or not by inspecting the did_signal flag.
  if (!UnregisterWaitEx(watch_->wait_object, INVALID_HANDLE_VALUE)) {
    NOTREACHED() << "UnregisterWaitEx failed: " << GetLastError();
    return false;
  }

  // Make sure that we see any mutation to did_signal.  This should be a no-op
  // since we expect that UnregisterWaitEx resulted in a memory barrier, but
  // just to be sure, we're going to be explicit.
  MemoryBarrier();

  // If the watch has been posted, then we need to make sure it knows not to do
  // anything once it is run.
  watch_->watcher = NULL;

  // If DoneWaiting was called, then the watch would have been posted as a
  // task, and will therefore be deleted by the MessageLoop.  Otherwise, we
  // need to take care to delete it here.
  if (!watch_->did_signal)
    delete watch_;

  watch_ = NULL;

  MessageLoop::current()->RemoveDestructionObserver(this);
  return true;
}

// static
void CALLBACK ObjectWatcher::DoneWaiting(void* param, BOOLEAN timed_out) {
  DCHECK(!timed_out);

  Watch* watch = static_cast<Watch*>(param);

  // Record that we ran this function.
  watch->did_signal = true;

  // We rely on the locking in PostTask() to ensure that a memory barrier is
  // provided, which in turn ensures our change to did_signal can be observed
  // on the target thread.
  watch->origin_loop->PostTask(FROM_HERE, watch);
}

void ObjectWatcher::WillDestroyCurrentMessageLoop() {
  // Need to shutdown the watch so that we don't try to access the MessageLoop
  // after this point.
  StopWatching();
}

}  // namespace base
<commit_msg>This is an experiment to see the impact of a boosted priority on the page cyclers.  I worry that this could lead to starvation of regular tasks (it is common for OnObjectSignaled to do another IO call), so I don't think this is necessarily a good solution.<commit_after>// Copyright 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "base/object_watcher.h"

#include "base/logging.h"

namespace base {

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

struct ObjectWatcher::Watch : public Task {
  ObjectWatcher* watcher;    // The associated ObjectWatcher instance
  HANDLE object;             // The object being watched
  HANDLE wait_object;        // Returned by RegisterWaitForSingleObject
  MessageLoop* origin_loop;  // Used to get back to the origin thread
  Delegate* delegate;        // Delegate to notify when signaled
  bool did_signal;           // DoneWaiting was called

  virtual void Run() {
    // The watcher may have already been torn down, in which case we need to
    // just get out of dodge.
    if (!watcher)
      return;

    DCHECK(did_signal);
    watcher->StopWatching();

    delegate->OnObjectSignaled(object);
  }
};

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

ObjectWatcher::ObjectWatcher() : watch_(NULL) {
}

ObjectWatcher::~ObjectWatcher() {
  StopWatching();
}

bool ObjectWatcher::StartWatching(HANDLE object, Delegate* delegate) {
  if (watch_) {
    NOTREACHED() << "Already watching an object";
    return false;
  }

  Watch* watch = new Watch;
  watch->watcher = this;
  watch->object = object;
  watch->origin_loop = MessageLoop::current();
  watch->delegate = delegate;
  watch->did_signal = false;

  // Since our job is to just notice when an object is signaled and report the
  // result back to this thread, we can just run on a Windows wait thread.
  DWORD wait_flags = WT_EXECUTEINWAITTHREAD | WT_EXECUTEONLYONCE;

  if (!RegisterWaitForSingleObject(&watch->wait_object, object, DoneWaiting,
                                   watch, INFINITE, wait_flags)) {
    NOTREACHED() << "RegisterWaitForSingleObject failed: " << GetLastError();
    delete watch;
    return false;
  }

  watch_ = watch;

  // We need to know if the current message loop is going away so we can
  // prevent the wait thread from trying to access a dead message loop.
  MessageLoop::current()->AddDestructionObserver(this);
  return true;
}

bool ObjectWatcher::StopWatching() {
  if (!watch_)
    return false;

  // Make sure ObjectWatcher is used in a single-threaded fashion.
  DCHECK(watch_->origin_loop == MessageLoop::current());

  // If DoneWaiting is in progress, we wait for it to finish.  We know whether
  // DoneWaiting happened or not by inspecting the did_signal flag.
  if (!UnregisterWaitEx(watch_->wait_object, INVALID_HANDLE_VALUE)) {
    NOTREACHED() << "UnregisterWaitEx failed: " << GetLastError();
    return false;
  }

  // Make sure that we see any mutation to did_signal.  This should be a no-op
  // since we expect that UnregisterWaitEx resulted in a memory barrier, but
  // just to be sure, we're going to be explicit.
  MemoryBarrier();

  // If the watch has been posted, then we need to make sure it knows not to do
  // anything once it is run.
  watch_->watcher = NULL;

  // If DoneWaiting was called, then the watch would have been posted as a
  // task, and will therefore be deleted by the MessageLoop.  Otherwise, we
  // need to take care to delete it here.
  if (!watch_->did_signal)
    delete watch_;

  watch_ = NULL;

  MessageLoop::current()->RemoveDestructionObserver(this);
  return true;
}

// static
void CALLBACK ObjectWatcher::DoneWaiting(void* param, BOOLEAN timed_out) {
  DCHECK(!timed_out);

  Watch* watch = static_cast<Watch*>(param);

  // Record that we ran this function.
  watch->did_signal = true;

  // Make this run very soon on the target thread.  TODO(darin): This could
  // lead to starving other tasks on the origin thread.
  watch->set_priority(1000);

  // We rely on the locking in PostTask() to ensure that a memory barrier is
  // provided, which in turn ensures our change to did_signal can be observed
  // on the target thread.
  watch->origin_loop->PostTask(FROM_HERE, watch);
}

void ObjectWatcher::WillDestroyCurrentMessageLoop() {
  // Need to shutdown the watch so that we don't try to access the MessageLoop
  // after this point.
  StopWatching();
}

}  // namespace base
<|endoftext|>


<commit_before><commit_msg>Bugfix: `Text3DStruct`: initialize `rotate_vector` & `translate_vector`.<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <string>

#include <kcpolydb.h>

/* long estimate_a(long *pack) {
  return (
    4 + pack[0] * 8 +
    4 + 1 + pack[1] * 8 * 5 +
    4 + 1 + pack[2] * 8 * 5 + 3 * 11 * 1 +
    4 + 1 + pack[3] * 8 * 5 + 3 * 11 * 2 +
    4 + 1 + pack[4] * 8 * 5 + 3 * 11 * 4 +
    4 + 1 + pack[5] * 8 * 5 + 3 * 11 * 6
  );
}

long estimate_b(long *pack) {
  return (
    4 + pack[0] * 9 +
    4 + 1 + pack[1] * 9 * 5 +
    4 + 1 + pack[2] * 9 * 5 + 4 * 2 * 3 * 8 * 1 +
    4 + 1 + pack[3] * 9 * 5 + 4 * 2 * 3 * 8 * 2 +
    4 + 1 + pack[4] * 9 * 5 + 4 * 2 * 3 * 8 * 4 +
    4 + 1 + pack[5] * 9 * 5 + 4 * 2 * 3 * 8 * 6
  );
} */

int main(int argc, char **argv) {
    if (argc <= 1) {
      std::cout << "Usage: stat <dbfile.kct>" << std::endl;
      return 1;
    }

    kyotocabinet::TreeDB db;

    if (!db.open(argv[1], kyotocabinet::TreeDB::OREADER)) {
      std::cout << "Could not open database." << std::endl;
      return 2;
    }

    std::auto_ptr<kyotocabinet::TreeDB::Cursor> cur(db.cursor());
    cur->jump();

    std::string key, value;

    long pack[] = {0, 0, 0, 0, 0, 0, 0};
    long total = 0;

    std::cout << "Scanning ..." << std::endl;

    while (cur->get(&key, &value, true)) {
        total++;
        if (value.size() == 8) {
            pack[0]++;
        } else {
            pack[value.at(0)]++;
        }

        if (total % 50000 == 0) {
            std::cerr << ".";
        }
    }

    std::cerr << std::endl;

    for (int i = 0; i < 6; i++) {
        std::cout << "Pack format " << i << ": " << pack[i] << " nodes " << std::endl;
    }

    std::cout << "Unique positions: " << total << std::endl;

    /* std::cout << std::endl;

    std::cout << "Scheme A: " << estimate_a(pack) << " bytes" << std::endl;
    std::cout << "Scheme B: " << estimate_b(pack) << " bytes" << std::endl;
    std::cout << "B/A: " << ((double)estimate_b(pack)/estimate_a(pack)) << std::endl; */

    return 0;
}
<commit_msg>Also output the 6th pack format<commit_after>#include <iostream>
#include <string>

#include <kcpolydb.h>

/* long estimate_a(long *pack) {
  return (
    4 + pack[0] * 8 +
    4 + 1 + pack[1] * 8 * 5 +
    4 + 1 + pack[2] * 8 * 5 + 3 * 11 * 1 +
    4 + 1 + pack[3] * 8 * 5 + 3 * 11 * 2 +
    4 + 1 + pack[4] * 8 * 5 + 3 * 11 * 4 +
    4 + 1 + pack[5] * 8 * 5 + 3 * 11 * 6
  );
}

long estimate_b(long *pack) {
  return (
    4 + pack[0] * 9 +
    4 + 1 + pack[1] * 9 * 5 +
    4 + 1 + pack[2] * 9 * 5 + 4 * 2 * 3 * 8 * 1 +
    4 + 1 + pack[3] * 9 * 5 + 4 * 2 * 3 * 8 * 2 +
    4 + 1 + pack[4] * 9 * 5 + 4 * 2 * 3 * 8 * 4 +
    4 + 1 + pack[5] * 9 * 5 + 4 * 2 * 3 * 8 * 6
  );
} */

int main(int argc, char **argv) {
    if (argc <= 1) {
      std::cout << "Usage: stat <dbfile.kct>" << std::endl;
      return 1;
    }

    kyotocabinet::TreeDB db;

    if (!db.open(argv[1], kyotocabinet::TreeDB::OREADER)) {
      std::cout << "Could not open database." << std::endl;
      return 2;
    }

    std::auto_ptr<kyotocabinet::TreeDB::Cursor> cur(db.cursor());
    cur->jump();

    std::string key, value;

    long pack[] = {0, 0, 0, 0, 0, 0, 0};
    long total = 0;

    std::cout << "Scanning ..." << std::endl;

    while (cur->get(&key, &value, true)) {
        total++;
        if (value.size() == 8) {
            pack[0]++;
        } else {
            pack[value.at(0)]++;
        }

        if (total % 50000 == 0) {
            std::cerr << ".";
        }
    }

    std::cerr << std::endl;

    for (int i = 0; i < 7; i++) {
        std::cout << "Pack format " << i << ": " << pack[i] << " nodes " << std::endl;
    }

    std::cout << "Unique positions: " << total << std::endl;

    /* std::cout << std::endl;

    std::cout << "Scheme A: " << estimate_a(pack) << " bytes" << std::endl;
    std::cout << "Scheme B: " << estimate_b(pack) << " bytes" << std::endl;
    std::cout << "B/A: " << ((double)estimate_b(pack)/estimate_a(pack)) << std::endl; */

    return 0;
}
<|endoftext|>


<commit_before>#include <string>

#include <gtest/gtest.h>

extern "C" {
#include "shoveler/view.h"
}

class ShovelerViewTest : public ::testing::Test {
public:
	virtual void SetUp()
	{
		view = shovelerViewCreate();
	}

	virtual void TearDown()
	{
		shovelerViewFree(view);
	}

	ShovelerView *view;
};

TEST_F(ShovelerViewTest, activate)
{
	long long int testEntityId = 1337;
	const char *testComponentName = "test";
	long long int testDependencyEntityId = 42;
	const char *testDependencyComponentName = "dependency";

	bool entityAdded = shovelerViewAddEntity(view, testEntityId);
	ASSERT_TRUE(entityAdded);

	ShovelerViewEntity *testEntity = shovelerViewGetEntity(view, testEntityId);
	bool componentAdded = shovelerViewEntityAddComponent(testEntity, testComponentName, NULL, NULL);
	ASSERT_TRUE(componentAdded);

	bool dependencyAdded = shovelerViewEntityAddComponentDependency(testEntity, testComponentName, testDependencyEntityId, testDependencyComponentName);
	ASSERT_TRUE(dependencyAdded);

	bool activated = shovelerViewEntityActivateComponent(testEntity, testComponentName);
	ASSERT_FALSE(activated);

	bool dependencyEntityAdded = shovelerViewAddEntity(view, testDependencyEntityId);
	ASSERT_TRUE(dependencyEntityAdded);

	ShovelerViewEntity *testDependencyEntity = shovelerViewGetEntity(view, testDependencyEntityId);
	bool dependencyComponentAdded = shovelerViewEntityAddComponent(testDependencyEntity, testDependencyComponentName, NULL, NULL);
	ASSERT_TRUE(dependencyComponentAdded);

	bool dependencyActivated = shovelerViewEntityActivateComponent(testDependencyEntity, testDependencyComponentName);
	ASSERT_TRUE(dependencyActivated);

	ShovelerViewComponent *testComponent = shovelerViewEntityGetComponent(testEntity, testComponentName);
	ASSERT_TRUE(testComponent->active) << "test component has also been activated after activating its reverse dependency";
}

TEST_F(ShovelerViewTest, deactivateWhenAddingUnsatisfiedDependency)
{
	long long int testEntityId = 1337;
	const char *testComponentName = "test";
	long long int testDependencyEntityId = 42;
	const char *testDependencyComponentName = "dependency";

	bool entityAdded = shovelerViewAddEntity(view, testEntityId);
	ASSERT_TRUE(entityAdded);

	ShovelerViewEntity *testEntity = shovelerViewGetEntity(view, testEntityId);
	bool componentAdded = shovelerViewEntityAddComponent(testEntity, testComponentName, NULL, NULL);
	ASSERT_TRUE(componentAdded);

	bool activated = shovelerViewEntityActivateComponent(testEntity, testComponentName);
	ASSERT_TRUE(activated);

	bool dependencyAdded = shovelerViewEntityAddComponentDependency(testEntity, testComponentName, testDependencyEntityId, testDependencyComponentName);
	ASSERT_TRUE(dependencyAdded);

	ShovelerViewComponent *testComponent = shovelerViewEntityGetComponent(testEntity, testComponentName);
	ASSERT_FALSE(testComponent->active) << "test component should be deactivated after adding unsatisfied dependency";
}
<commit_msg>added reverse dependency deactivation unit test for view<commit_after>#include <string>

#include <gtest/gtest.h>

extern "C" {
#include "shoveler/view.h"
}

class ShovelerViewTest : public ::testing::Test {
public:
	virtual void SetUp()
	{
		view = shovelerViewCreate();
	}

	virtual void TearDown()
	{
		shovelerViewFree(view);
	}

	ShovelerView *view;
};

TEST_F(ShovelerViewTest, activate)
{
	long long int testEntityId = 1337;
	const char *testComponentName = "test";
	long long int testDependencyEntityId = 42;
	const char *testDependencyComponentName = "dependency";

	bool entityAdded = shovelerViewAddEntity(view, testEntityId);
	ASSERT_TRUE(entityAdded);

	ShovelerViewEntity *testEntity = shovelerViewGetEntity(view, testEntityId);
	bool componentAdded = shovelerViewEntityAddComponent(testEntity, testComponentName, NULL, NULL);
	ASSERT_TRUE(componentAdded);

	bool dependencyAdded = shovelerViewEntityAddComponentDependency(testEntity, testComponentName, testDependencyEntityId, testDependencyComponentName);
	ASSERT_TRUE(dependencyAdded);

	bool activated = shovelerViewEntityActivateComponent(testEntity, testComponentName);
	ASSERT_FALSE(activated);

	bool dependencyEntityAdded = shovelerViewAddEntity(view, testDependencyEntityId);
	ASSERT_TRUE(dependencyEntityAdded);

	ShovelerViewEntity *testDependencyEntity = shovelerViewGetEntity(view, testDependencyEntityId);
	bool dependencyComponentAdded = shovelerViewEntityAddComponent(testDependencyEntity, testDependencyComponentName, NULL, NULL);
	ASSERT_TRUE(dependencyComponentAdded);

	bool dependencyActivated = shovelerViewEntityActivateComponent(testDependencyEntity, testDependencyComponentName);
	ASSERT_TRUE(dependencyActivated);

	ShovelerViewComponent *testComponent = shovelerViewEntityGetComponent(testEntity, testComponentName);
	ASSERT_TRUE(testComponent->active) << "test component has also been activated after activating its reverse dependency";
}

TEST_F(ShovelerViewTest, deactivateWhenAddingUnsatisfiedDependency)
{
	long long int testEntityId = 1337;
	const char *testComponentName = "test";
	long long int testDependencyEntityId = 42;
	const char *testDependencyComponentName = "dependency";

	bool entityAdded = shovelerViewAddEntity(view, testEntityId);
	ASSERT_TRUE(entityAdded);

	ShovelerViewEntity *testEntity = shovelerViewGetEntity(view, testEntityId);
	bool componentAdded = shovelerViewEntityAddComponent(testEntity, testComponentName, NULL, NULL);
	ASSERT_TRUE(componentAdded);

	bool activated = shovelerViewEntityActivateComponent(testEntity, testComponentName);
	ASSERT_TRUE(activated);

	bool dependencyAdded = shovelerViewEntityAddComponentDependency(testEntity, testComponentName, testDependencyEntityId, testDependencyComponentName);
	ASSERT_TRUE(dependencyAdded);

	ShovelerViewComponent *testComponent = shovelerViewEntityGetComponent(testEntity, testComponentName);
	ASSERT_FALSE(testComponent->active) << "test component should be deactivated after adding unsatisfied dependency";
}

TEST_F(ShovelerViewTest, deactivateReverseDependencies)
{
	long long int testEntityId = 1337;
	const char *testComponentName = "test";
	long long int testDependencyEntityId = 42;
	const char *testDependencyComponentName = "dependency";

	bool entityAdded = shovelerViewAddEntity(view, testEntityId);
	ASSERT_TRUE(entityAdded);

	ShovelerViewEntity *testEntity = shovelerViewGetEntity(view, testEntityId);
	bool componentAdded = shovelerViewEntityAddComponent(testEntity, testComponentName, NULL, NULL);
	ASSERT_TRUE(componentAdded);

	bool dependencyEntityAdded = shovelerViewAddEntity(view, testDependencyEntityId);
	ASSERT_TRUE(dependencyEntityAdded);

	ShovelerViewEntity *testDependencyEntity = shovelerViewGetEntity(view, testDependencyEntityId);
	bool dependencyComponentAdded = shovelerViewEntityAddComponent(testDependencyEntity, testDependencyComponentName, NULL, NULL);
	ASSERT_TRUE(dependencyComponentAdded);

	bool dependencyAdded = shovelerViewEntityAddComponentDependency(testEntity, testComponentName, testDependencyEntityId, testDependencyComponentName);
	ASSERT_TRUE(dependencyAdded);

	bool activated = shovelerViewEntityActivateComponent(testDependencyEntity, testDependencyComponentName);
	ASSERT_TRUE(activated);

	bool deactivated = shovelerViewEntityDeactivateComponent(testDependencyEntity, testDependencyComponentName);
	ASSERT_TRUE(deactivated);

	ShovelerViewComponent *testComponent = shovelerViewEntityGetComponent(testEntity, testComponentName);
	ASSERT_FALSE(testComponent->active) << "test component has also been deactivated after deactivating its dependency";
}
<|endoftext|>


<commit_before>#ifndef __codex_vision_image_proc_h__
#define __codex_vision_image_proc_h__

#include <cassert>
#include <array>
#include <codex/vision/kernel.hpp>
#include <cmath>

namespace codex { namespace vision {

    template < typename typeT >
    image gray_scale( const image_base<typeT>& src  ){
        image dst( src.width() , src.height());
        for ( std::size_t y = 0 ; y < src.height() ; ++y ){
            uint8_t* dst_ptr = dst.ptr(y);
            const typeT* src_ptr = src.ptr(y);
            for ( std::size_t x = 0 ; x < src.width() ; ++x ) {
                if ( src.channel() == 3 || src.channel() == 4 ) {
                    // BGR to Y
                    *dst_ptr = 0.114 * src_ptr[ x * src.channel()]
                             + 0.587 * src_ptr[ x * src.channel() + 1]
                             + 0.299 * src_ptr[ x * src.channel() + 2];
                } else {
                    // mean
                    double val = 0;
                    for ( std::size_t c = 0 ; c < src.channel() ; ++c ) {
                        val += src_ptr[ x * src.channel() + c ];
                    }
                    *dst_ptr = codex::vision::operation<uint8_t,typeT>::clip(val/src.channel());
                }
                ++dst_ptr;
            }
        }
        return dst;
    }

    void histogram_equation( const image& src , image& dst , const std::size_t channel = 0);
    void histogram_equation_debug( const image& src
                                   , image& dst
                                   , image& orig_hist
                                   , image& equation_hist );
    void histogram_graph( const image& src , image& dst );

    template < typename typeT >
    void gaussian( const image_base<typeT>& src , image_base<typeT>& dst
                   , int k_size = 3
                   , double standard_deviation = 0.5 )
    {
        assert( is_same_format(src,dst));

        double gauss[32] = {0};
        if ( k_size % 2 == 0 ) {
            k_size += 1;
        }
        if ( k_size < 3 ) k_size = 3;
        if ( k_size > 9 ) k_size = 9;

        int half = k_size / 2;
        for ( int i = 0; i <= half ; ++i ) {
            gauss[ half - i ] = gauss[ half + i] = exp( ( i * i ) /(  -2 * standard_deviation * standard_deviation));
        }

        int width = src.width();
        int height = src.height();
        int channel = src.channel();

        image_base<typeT> intermediate( width , height, channel );

        for ( int r = 0 ; r < height; ++r ){
            const typeT* ptr = src.ptr(r);
            typeT* im_ptr = intermediate.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
                for ( int l = 0 ; l < channel ; ++l ) {
                    double sum = 0;
                    double tot = 0;
                    for ( int px = -half ; px <= half ; ++px ) {
                        int col_index = c + px;
                        if ( col_index >= 0 && col_index < width ) {
                            sum += ptr[col_index * channel + l ] * gauss[ half + px ];
                            tot += gauss[half+px];
                        }
                    }
                    im_ptr[ c * intermediate.channel() + l ] = static_cast<typeT>( sum/tot );
                }
            }
        }

        for ( int r = 0 ; r < height; ++r ){
            typeT* dst_ptr = dst.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
                for ( int l = 0 ; l < channel ; ++l ) {
                    double sum = 0;
                    double tot = 0;
                    for ( int py = -half ; py <= half ; ++py ) {
                        int row_index = r + py;
                        if ( row_index >= 0 && row_index < height ) {
                            typeT* im_ptr = intermediate.ptr(row_index);
                            sum += im_ptr[c * channel + l ] * gauss[ half + py ];
                            tot += gauss[half+py];
                        }
                    }
                    dst_ptr[ c * channel + l ] = static_cast<typeT>( sum/tot );
                }
            }
        }
    }

    template < typename typeT >
    void mean( const image_base<typeT>& src , image_base<typeT>& dst
                   , int k_size = 3 )
    {
        assert( is_same_format(src,dst));
        if ( k_size % 2 == 0 ) {
            k_size += 1;
        }
        if ( k_size < 3 ) k_size = 3;
        if ( k_size > 9 ) k_size = 9;

        int half = k_size / 2;

        int width = src.width();
        int height = src.height();
        int channel = src.channel();

        typedef decltype ( std::numeric_limits<typeT>::max() + 1 ) value_type;

        for ( int r = 0 ; r < height ; ++r ) {
            typeT* dst_ptr = dst.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
            for ( int l = 0 ; l < channel ; ++l ) {
                value_type sum = 0;
                double count = 0;
                for ( int py = -half ; py <= half ; ++py ) {
                    int row_idx = r + py;
                    if ( row_idx >= 0 && row_idx < height ) {
                        const typeT* src_ptr = src.ptr(row_idx);
                        for ( int px = -half ; px <= half ; ++px ) {
                            int col_idx = c + px;
                            if ( col_idx >= 0 && col_idx < width ) {
                                sum += src_ptr[ col_idx * channel + l ];
                                count += 1;
                            }
                        }
                    }
                }
                dst_ptr[ c * channel + l ] = operation< typeT , double >::clip( sum / count );

            }   // channel
            }   // column
        }   // row
    }

    template < typename typeT >
    void median( const image_base<typeT>& src , image_base<typeT>& dst
                   , int k_size = 3 )
    {
        assert( is_same_format(src,dst));
        if ( k_size % 2 == 0 ) {
            k_size += 1;
        }
        if ( k_size < 3 ) k_size = 3;
        if ( k_size > 9 ) k_size = 9;

        int half = k_size / 2;

        int width = src.width();
        int height = src.height();
        int channel = src.channel();

        std::array< typeT , 32 > values;

        for ( int r = 0 ; r < height ; ++r ) {
            typeT* dst_ptr = dst.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
            for ( int l = 0 ; l < channel ; ++l ) {
                int index = 0;
                for ( int py = -half ; py <= half ; ++py ) {
                    int row_idx = r + py;
                    if ( row_idx >= 0 && row_idx < height ) {
                        const typeT* src_ptr = src.ptr(row_idx);
                        for ( int px = -half ; px <= half ; ++px ) {
                            int col_idx = c + px;
                            if ( col_idx >= 0 && col_idx < width ) {
                                values[index++] = src_ptr[ col_idx * channel + l ];
                            }
                        }
                    }
                }
                std::sort( &values[0] ,  &values[0] + index  );
                dst_ptr[ c * channel + l ] = values[ index / 2 ];

            }   // channel
            }   // column
        }   // row
    }

    double sqrt( double v );

    void fft1d( double* re , double* im , int N , int isign );
    int fft_size( int n );

    void fft_mag_image( const image_base<double>& re , const image_base<double>& im , image_base<uint8_t>& dst );
    void fft_phs_image( const image_base<double>& re , const image_base<double>& im , image_base<uint8_t>& dst );
    void fft_shift( image_base<double>& img );

    int clip( int orig , int max ){
        return orig < 0 ? 0 : orig > max ? max : orig;
    }

    template < typename typeT >
    typeT bilinear( const image_base<typeT>& src , double x , double y , std::size_t channel = 0 ){
        int xl = clip( static_cast<int>(x) , src.width() );
        int xr = clip( static_cast<int>(x) + 1 , src.width() );
        int yt = clip( static_cast<int>(y) , src.height() );
        int yb = clip( static_cast<int>(y) + 1 , src.height() );
        // 가중치 계산 대각선 방향에의 거리값( 크면 가깞고 , 작으면 멀다 )
        int lt = ( xr - x )*( yb - y );
        int rt = ( x - xl )*( yb - y );
        int lb = ( xr - x )*( y - yt );
        int rb = ( x - xl )*( y - yt );

        return codex::vision::operation<typeT,typeT>::clip(
                    lt * src.at(xl,yt,channel )
                    + rt * src.at(xr,yt,channel)
                    + lb * src.at(xl,yb,channel)
                    + rb * src.at(xr,yb,channel)
                    );
    }

    template < typename typeT >
    void tranform( const image_base<typeT>& src , image_base<typeT>& dst
                   , double rotation // degree
                   , double scale    // zoom default 1
                   , double cx       // center src.width() / 2.0
                   , double cy       // center src.height() / 2.0
                   , double tx       // trans x
                   , double ty )     // trans y
    {
        double cr = std::cos( rotation * M_PI/180.0 );
        double sr = std::sin( rotation * M_PI/180.0 );

        for ( std::size_t r = 0 ; r < src.height() ; ++r ) {
            for ( std::size_t c = 0 ; c < src.width() ; ++c ) {
                double srcx = scale * ( cr * (c - cx) + sr * ( r -cy )) + cx - tx;
                double srcy = scale * (-sr * (c - cx) + cr * ( r -cy )) + cy - ty;
                if ( srcx >= 0 && srcx < src.width() && srcy >= 0 && srcy < src.height() ) {
                    for ( std::size_t l = 0 ; l < src.channel() ; ++l ) {
                        dst.at(r,c,l) = bilinear( src , srcx , srcy , l );
                    }
                }
            }
        }
    }

/*
    void _FFT1d(double* g, unsigned long N, int isign)
    {
        int mmax, m, istep;
        double wtemp, wr, wpr, wpi, wi, theta;
        double tempr, tempi;
        double temp;

        // 스크램블 수행
        int n = N*2;
        int j = 1;
        for (int i=1 ; i<n ; i+=2)
        {
            if (j > i)
            {
                temp = g[j];
                g[j] = g[i];
                g[i] = temp;

                temp = g[j+1];
                g[j+1] = g[i+1];
                g[i+1] = temp;
            }
            m = n >> 1;
            while (j>m && m>=2)
            {
                j -= m;
                m >>= 1;
            }
            j += m;
        }

        // 버터플라이 알고리즘 수행
        mmax = 2; // 2원소 DFT로 시작
        while (n > mmax)
        {
            istep = mmax << 1;
            theta = isign*(6.28318530717959/mmax);
            wtemp = sin(0.5*theta);
            wpr = -2.0*wtemp*wtemp;
            wpi = sin(theta);
            wr = 1.0;
            wi = 0.0;
            for (m=1 ; m<mmax ; m+=2)
            {
                for (int i=m ; i<=n ; i+=istep)
                {
                    j = i + mmax;
                    tempr = double (wr*g[j]-wi*g[j+1]);
                    tempi = double (wr*g[j+1]+wi*g[j]);
                    g[j] = g[i]-tempr;
                    g[j+1] = g[i+1]-tempi;
                    g[i] += tempr;
                    g[i+1] += tempi;
                }
                wr = (wtemp=wr)*wpr-wi*wpi+wr;
                wi = wi*wpr+wtemp*wpi+wi;
            }
            mmax = istep;
        }

        if(isign == -1)
        {
            for (int i=1 ; i<= n ; i++)
            {
                g[i] /= N;
            }
        }
    }*/
}}

#endif
<commit_msg>add comment<commit_after>#ifndef __codex_vision_image_proc_h__
#define __codex_vision_image_proc_h__

#include <cassert>
#include <array>
#include <codex/vision/kernel.hpp>
#include <cmath>

namespace codex { namespace vision {

    template < typename typeT >
    image gray_scale( const image_base<typeT>& src  ){
        image dst( src.width() , src.height());
        for ( std::size_t y = 0 ; y < src.height() ; ++y ){
            uint8_t* dst_ptr = dst.ptr(y);
            const typeT* src_ptr = src.ptr(y);
            for ( std::size_t x = 0 ; x < src.width() ; ++x ) {
                if ( src.channel() == 3 || src.channel() == 4 ) {
                    // BGR to Y
                    *dst_ptr = 0.114 * src_ptr[ x * src.channel()]
                             + 0.587 * src_ptr[ x * src.channel() + 1]
                             + 0.299 * src_ptr[ x * src.channel() + 2];
                } else {
                    // mean
                    double val = 0;
                    for ( std::size_t c = 0 ; c < src.channel() ; ++c ) {
                        val += src_ptr[ x * src.channel() + c ];
                    }
                    *dst_ptr = codex::vision::operation<uint8_t,typeT>::clip(val/src.channel());
                }
                ++dst_ptr;
            }
        }
        return dst;
    }

    void histogram_equation( const image& src , image& dst , const std::size_t channel = 0);
    void histogram_equation_debug( const image& src
                                   , image& dst
                                   , image& orig_hist
                                   , image& equation_hist );
    void histogram_graph( const image& src , image& dst );

    template < typename typeT >
    void gaussian( const image_base<typeT>& src , image_base<typeT>& dst
                   , int k_size = 3
                   , double standard_deviation = 0.5 )
    {
        assert( is_same_format(src,dst));

        double gauss[32] = {0};
        if ( k_size % 2 == 0 ) {
            k_size += 1;
        }
        if ( k_size < 3 ) k_size = 3;
        if ( k_size > 9 ) k_size = 9;

        int half = k_size / 2;
        for ( int i = 0; i <= half ; ++i ) {
            gauss[ half - i ] = gauss[ half + i] = exp( ( i * i ) /(  -2 * standard_deviation * standard_deviation));
        }

        int width = src.width();
        int height = src.height();
        int channel = src.channel();

        image_base<typeT> intermediate( width , height, channel );

        for ( int r = 0 ; r < height; ++r ){
            const typeT* ptr = src.ptr(r);
            typeT* im_ptr = intermediate.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
                for ( int l = 0 ; l < channel ; ++l ) {
                    double sum = 0;
                    double tot = 0;
                    for ( int px = -half ; px <= half ; ++px ) {
                        int col_index = c + px;
                        if ( col_index >= 0 && col_index < width ) {
                            sum += ptr[col_index * channel + l ] * gauss[ half + px ];
                            tot += gauss[half+px];
                        }
                    }
                    im_ptr[ c * intermediate.channel() + l ] = static_cast<typeT>( sum/tot );
                }
            }
        }

        for ( int r = 0 ; r < height; ++r ){
            typeT* dst_ptr = dst.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
                for ( int l = 0 ; l < channel ; ++l ) {
                    double sum = 0;
                    double tot = 0;
                    for ( int py = -half ; py <= half ; ++py ) {
                        int row_index = r + py;
                        if ( row_index >= 0 && row_index < height ) {
                            typeT* im_ptr = intermediate.ptr(row_index);
                            sum += im_ptr[c * channel + l ] * gauss[ half + py ];
                            tot += gauss[half+py];
                        }
                    }
                    dst_ptr[ c * channel + l ] = static_cast<typeT>( sum/tot );
                }
            }
        }
    }

    template < typename typeT >
    void mean( const image_base<typeT>& src , image_base<typeT>& dst
                   , int k_size = 3 )
    {
        assert( is_same_format(src,dst));
        if ( k_size % 2 == 0 ) {
            k_size += 1;
        }
        if ( k_size < 3 ) k_size = 3;
        if ( k_size > 9 ) k_size = 9;

        int half = k_size / 2;

        int width = src.width();
        int height = src.height();
        int channel = src.channel();

        typedef decltype ( std::numeric_limits<typeT>::max() + 1 ) value_type;

        for ( int r = 0 ; r < height ; ++r ) {
            typeT* dst_ptr = dst.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
            for ( int l = 0 ; l < channel ; ++l ) {
                value_type sum = 0;
                double count = 0;
                for ( int py = -half ; py <= half ; ++py ) {
                    int row_idx = r + py;
                    if ( row_idx >= 0 && row_idx < height ) {
                        const typeT* src_ptr = src.ptr(row_idx);
                        for ( int px = -half ; px <= half ; ++px ) {
                            int col_idx = c + px;
                            if ( col_idx >= 0 && col_idx < width ) {
                                sum += src_ptr[ col_idx * channel + l ];
                                count += 1;
                            }
                        }
                    }
                }
                dst_ptr[ c * channel + l ] = operation< typeT , double >::clip( sum / count );

            }   // channel
            }   // column
        }   // row
    }

    template < typename typeT >
    void median( const image_base<typeT>& src , image_base<typeT>& dst
                   , int k_size = 3 )
    {
        assert( is_same_format(src,dst));
        if ( k_size % 2 == 0 ) {
            k_size += 1;
        }
        if ( k_size < 3 ) k_size = 3;
        if ( k_size > 9 ) k_size = 9;

        int half = k_size / 2;

        int width = src.width();
        int height = src.height();
        int channel = src.channel();

        std::array< typeT , 32 > values;

        for ( int r = 0 ; r < height ; ++r ) {
            typeT* dst_ptr = dst.ptr(r);
            for ( int c = 0 ; c < width ; ++c ) {
            for ( int l = 0 ; l < channel ; ++l ) {
                int index = 0;
                for ( int py = -half ; py <= half ; ++py ) {
                    int row_idx = r + py;
                    if ( row_idx >= 0 && row_idx < height ) {
                        const typeT* src_ptr = src.ptr(row_idx);
                        for ( int px = -half ; px <= half ; ++px ) {
                            int col_idx = c + px;
                            if ( col_idx >= 0 && col_idx < width ) {
                                values[index++] = src_ptr[ col_idx * channel + l ];
                            }
                        }
                    }
                }
                std::sort( &values[0] ,  &values[0] + index  );
                dst_ptr[ c * channel + l ] = values[ index / 2 ];

            }   // channel
            }   // column
        }   // row
    }

    double sqrt( double v );

    void fft1d( double* re , double* im , int N , int isign );
    int fft_size( int n );

    void fft_mag_image( const image_base<double>& re , const image_base<double>& im , image_base<uint8_t>& dst );
    void fft_phs_image( const image_base<double>& re , const image_base<double>& im , image_base<uint8_t>& dst );
    void fft_shift( image_base<double>& img );

    int clip( int orig , int max ){
        return orig < 0 ? 0 : orig > max ? max : orig;
    }

    template < typename typeT >
    typeT bilinear( const image_base<typeT>& src , double x , double y , std::size_t channel = 0 ){
        int xl = clip( static_cast<int>(x) , src.width() );
        int xr = clip( static_cast<int>(x) + 1 , src.width() );
        int yt = clip( static_cast<int>(y) , src.height() );
        int yb = clip( static_cast<int>(y) + 1 , src.height() );
        // 가중치 계산 대각선 방향에의 거리값( 크면 가깞고 , 작으면 멀다 )
        int lt = ( xr - x )*( yb - y );
        int rt = ( x - xl )*( yb - y );
        int lb = ( xr - x )*( y - yt );
        int rb = ( x - xl )*( y - yt );

        return codex::vision::operation<typeT,typeT>::clip(
                    lt * src.at(xl,yt,channel )
                    + rt * src.at(xr,yt,channel)
                    + lb * src.at(xl,yb,channel)
                    + rb * src.at(xr,yb,channel)
                    );
    }

    template < typename typeT >
    void tranform( const image_base<typeT>& src , image_base<typeT>& dst
                   , double rotation // degree
                   , double scale    // zoom default 1
                   , double cx       // center src.width() / 2.0
                   , double cy       // center src.height() / 2.0
                   , double tx       // trans x
                   , double ty )     // trans y
    {
        double cr = std::cos( rotation * M_PI/180.0 );
        double sr = std::sin( rotation * M_PI/180.0 );

        for ( std::size_t r = 0 ; r < src.height() ; ++r ) {
            for ( std::size_t c = 0 ; c < src.width() ; ++c ) {
                // 중심을 원점으로 이동
                // 회전 적용
                // 원점 복귀
                // 확대 / 축소
                // 평행 이동
                double srcx = scale * ( cr * (c - cx) + sr * ( r -cy )) + cx - tx;
                double srcy = scale * (-sr * (c - cx) + cr * ( r -cy )) + cy - ty;
                if ( srcx >= 0 && srcx < src.width() && srcy >= 0 && srcy < src.height() ) {
                    for ( std::size_t l = 0 ; l < src.channel() ; ++l ) {
                        dst.at(r,c,l) = bilinear( src , srcx , srcy , l );
                    }
                }
            }
        }
    }
    /*
    template < typename typeT >
    void rgb_to_hsv( const image_base<typeT>& rgb , image_base<typeT>& dst )
*/
/*
    void _FFT1d(double* g, unsigned long N, int isign)
    {
        int mmax, m, istep;
        double wtemp, wr, wpr, wpi, wi, theta;
        double tempr, tempi;
        double temp;

        // 스크램블 수행
        int n = N*2;
        int j = 1;
        for (int i=1 ; i<n ; i+=2)
        {
            if (j > i)
            {
                temp = g[j];
                g[j] = g[i];
                g[i] = temp;

                temp = g[j+1];
                g[j+1] = g[i+1];
                g[i+1] = temp;
            }
            m = n >> 1;
            while (j>m && m>=2)
            {
                j -= m;
                m >>= 1;
            }
            j += m;
        }

        // 버터플라이 알고리즘 수행
        mmax = 2; // 2원소 DFT로 시작
        while (n > mmax)
        {
            istep = mmax << 1;
            theta = isign*(6.28318530717959/mmax);
            wtemp = sin(0.5*theta);
            wpr = -2.0*wtemp*wtemp;
            wpi = sin(theta);
            wr = 1.0;
            wi = 0.0;
            for (m=1 ; m<mmax ; m+=2)
            {
                for (int i=m ; i<=n ; i+=istep)
                {
                    j = i + mmax;
                    tempr = double (wr*g[j]-wi*g[j+1]);
                    tempi = double (wr*g[j+1]+wi*g[j]);
                    g[j] = g[i]-tempr;
                    g[j+1] = g[i+1]-tempi;
                    g[i] += tempr;
                    g[i+1] += tempi;
                }
                wr = (wtemp=wr)*wpr-wi*wpi+wr;
                wi = wi*wpr+wtemp*wpi+wi;
            }
            mmax = istep;
        }

        if(isign == -1)
        {
            for (int i=1 ; i<= n ; i++)
            {
                g[i] /= N;
            }
        }
    }*/
}}

#endif
<|endoftext|>


<commit_before>#include <vtkArrayPrint.h>
#include <vtkDenseArray.h>
#include <vtkSparseArray.h>

int main(int vtkNotUsed(argc), char *vtkNotUsed(argv)[])
{
  ////////////////////////////////////////////////////////
  // Creating N-Way Arrays

  // Creating a dense array of 10 integers:
  vtkDenseArray<vtkIdType>* array = vtkDenseArray<vtkIdType>::New();
  array->Resize(10);

  // Creating a dense 20 x 30 matrix:
  vtkDenseArray<double>* matrix = vtkDenseArray<double>::New();
  matrix->Resize(20, 30);

  // Creating a sparse 10 x 20 x 30 x 40 tensor:
  vtkArrayExtents extents;
  extents.SetDimensions(4);
  extents[0] = 10;
  extents[1] = 20;
  extents[2] = 30;
  extents[3] = 40;
  vtkSparseArray<vtkIdType>* tensor = vtkSparseArray<vtkIdType>::New();
  tensor->Resize(extents);

  ////////////////////////////////////////////////////////
  // Initializing N-Way Arrays

  // Filling a dense array with ones:
  array->Fill(1);

  // Filling a dense matrix with zeros:
  matrix->Fill(0.0);

  // There's nothing to do for a sparse array - it's already empty.

  ////////////////////////////////////////////////////////
  // Assigning N-Way Array Values

  // Assign array value [5]:
  array->SetValue(5, 42);

  // Assign matrix value [4, 3]:
  matrix->SetValue(4, 3, 1970);

  // Assign tensor value [3, 7, 1, 2]:
  vtkArrayCoordinates coordinates;
  coordinates.SetDimensions(4);
  coordinates[0] = 3;
  coordinates[1] = 7;
  coordinates[2] = 1;
  coordinates[3] = 2;
  tensor->SetValue(coordinates, 38);

  ////////////////////////////////////////////////////////
  // Accessing N-Way Array Values

  // Access array value [5]:
  cout << "array[5]: " << array->GetValue(5) << "\n\n";

  // Access matrix value [4, 3]:
  cout << "matrix[4, 3]: " << matrix->GetValue(4, 3) << "\n\n";

  // Access tensor value [3, 7, 1, 2]:
  cout << "tensor[3, 7, 1, 2]: " << tensor->GetValue(coordinates) << "\n\n";

  ////////////////////////////////////////////////////////
  // Printing N-Way Arrays

  cout << "array:\n";
  vtkPrintVectorFormat(cout, array);
  cout << "\n";

  cout << "matrix:\n";
  vtkPrintMatrixFormat(cout, matrix);
  cout << "\n";

  cout << "tensor:\n";
  vtkPrintCoordinateFormat(cout, tensor);
  cout << "\n";

  // Cleanup array instances ...
  tensor->Delete();
  matrix->Delete();
  array->Delete();

  return 0;
}
<commit_msg>COMP: Sync the ArrayBasics example with changes to the vtkArray API.<commit_after>#include <vtkArrayPrint.h>
#include <vtkDenseArray.h>
#include <vtkSparseArray.h>

int main(int vtkNotUsed(argc), char *vtkNotUsed(argv)[])
{
  ////////////////////////////////////////////////////////
  // Creating N-Way Arrays

  // Creating a dense array of 10 integers:
  vtkDenseArray<vtkIdType>* array = vtkDenseArray<vtkIdType>::New();
  array->Resize(10);

  // Creating a dense 20 x 30 matrix:
  vtkDenseArray<double>* matrix = vtkDenseArray<double>::New();
  matrix->Resize(20, 30);

  // Creating a sparse 10 x 20 x 30 x 40 tensor:
  vtkArrayExtents extents;
  extents.SetDimensions(4);
  extents[0] = vtkArrayRange(0, 10);
  extents[1] = vtkArrayRange(0, 20);
  extents[2] = vtkArrayRange(0, 30);
  extents[3] = vtkArrayRange(0, 40);
  vtkSparseArray<vtkIdType>* tensor = vtkSparseArray<vtkIdType>::New();
  tensor->Resize(extents);

  ////////////////////////////////////////////////////////
  // Initializing N-Way Arrays

  // Filling a dense array with ones:
  array->Fill(1);

  // Filling a dense matrix with zeros:
  matrix->Fill(0.0);

  // There's nothing to do for a sparse array - it's already empty.

  ////////////////////////////////////////////////////////
  // Assigning N-Way Array Values

  // Assign array value [5]:
  array->SetValue(5, 42);

  // Assign matrix value [4, 3]:
  matrix->SetValue(4, 3, 1970);

  // Assign tensor value [3, 7, 1, 2]:
  vtkArrayCoordinates coordinates;
  coordinates.SetDimensions(4);
  coordinates[0] = 3;
  coordinates[1] = 7;
  coordinates[2] = 1;
  coordinates[3] = 2;
  tensor->SetValue(coordinates, 38);

  ////////////////////////////////////////////////////////
  // Accessing N-Way Array Values

  // Access array value [5]:
  cout << "array[5]: " << array->GetValue(5) << "\n\n";

  // Access matrix value [4, 3]:
  cout << "matrix[4, 3]: " << matrix->GetValue(4, 3) << "\n\n";

  // Access tensor value [3, 7, 1, 2]:
  cout << "tensor[3, 7, 1, 2]: " << tensor->GetValue(coordinates) << "\n\n";

  ////////////////////////////////////////////////////////
  // Printing N-Way Arrays

  cout << "array:\n";
  vtkPrintVectorFormat(cout, array);
  cout << "\n";

  cout << "matrix:\n";
  vtkPrintMatrixFormat(cout, matrix);
  cout << "\n";

  cout << "tensor:\n";
  vtkPrintCoordinateFormat(cout, tensor);
  cout << "\n";

  // Cleanup array instances ...
  tensor->Delete();
  matrix->Delete();
  array->Delete();

  return 0;
}
<|endoftext|>