text
stringlengths
54
60.6k
<commit_before>#ifndef CLUE_MEMORY__ #define CLUE_MEMORY__ #include <clue/common.hpp> namespace clue { #if (defined(_WIN32) || defined(_WIN64)) && defined(_MSC_VER) inline void* aligned_alloc(size_t nbytes, unsigned int alignment) { void* p = ::_aligned_malloc(nbytes, alignment)); if (!p) { throw std::bad_alloc(); } return p; } inline void aligned_free(void *p) { ::_aligned_free(p); } #else inline void* aligned_alloc(size_t nbytes, unsigned int alignment) { char* p = 0; if (::posix_memalign((void**)(&p), alignment, nbytes) != 0) { throw std::bad_alloc(); } return p; } inline void aligned_free(void *p) { ::free(p); } #endif } #endif <commit_msg>add relevant header in memory.hpp<commit_after>#ifndef CLUE_MEMORY__ #define CLUE_MEMORY__ #include <clue/common.hpp> #if (defined(_WIN32) || defined(_WIN64)) && defined(_MSC_VER) #include <malloc.h> #else #include <stdlib.h> #endif namespace clue { #if (defined(_WIN32) || defined(_WIN64)) && defined(_MSC_VER) inline void* aligned_alloc(size_t nbytes, unsigned int alignment) { void* p = ::_aligned_malloc(nbytes, alignment)); if (!p) { throw std::bad_alloc(); } return p; } inline void aligned_free(void *p) { ::_aligned_free(p); } #else inline void* aligned_alloc(size_t nbytes, unsigned int alignment) { char* p = 0; if (::posix_memalign((void**)(&p), alignment, nbytes) != 0) { throw std::bad_alloc(); } return p; } inline void aligned_free(void *p) { ::free(p); } #endif } #endif <|endoftext|>
<commit_before>#line 2 "togo/kvs.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file kvs.hpp @brief KVS interface. @ingroup kvs */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/utility.hpp> #include <togo/kvs_types.hpp> #include <togo/assert.hpp> #include <togo/hash.hpp> namespace togo { namespace kvs { /** @addtogroup kvs @{ */ namespace { static constexpr KVSType const type_mask_vector = KVSType::vec1 | KVSType::vec2 | KVSType::vec3 | KVSType::vec4 ; /*static constexpr KVSType const type_mask_value = KVSType::integer | KVSType::decimal | KVSType::boolean | KVSType::string | type_mask_vector ; static constexpr KVSType const type_mask_value_nullable = KVSType::null | type_mask_value ;*/ static constexpr KVSType const type_mask_collection = KVSType::array | KVSType::node ; } // anonymous namespace /// Get type. inline KVSType type(KVS const& kvs) { return kvs._type; } /// Check type equivalence. inline bool is_type(KVS const& kvs, KVSType const type) { return kvs._type == type; } /// Check type by set. inline bool is_type_any(KVS const& kvs, KVSType const type) { return enum_bool(kvs._type & type); } /// Check if type is KVSType::null. inline bool is_null(KVS const& kvs) { return kvs::is_type(kvs, KVSType::null); } /// Check if type is KVSType::integer. inline bool is_integer(KVS const& kvs) { return kvs::is_type(kvs, KVSType::integer); } /// Check if type is KVSType::decimal. inline bool is_decimal(KVS const& kvs) { return kvs::is_type(kvs, KVSType::decimal); } /// Check if type is KVSType::boolean. inline bool is_boolean(KVS const& kvs) { return kvs::is_type(kvs, KVSType::boolean); } /// Check if type is KVSType::string. inline bool is_string(KVS const& kvs) { return kvs::is_type(kvs, KVSType::string); } /// Check if type is a vector type. inline bool is_vector(KVS const& kvs) { return kvs::is_type_any(kvs, type_mask_vector); } /// Check if type is an array or node. inline bool is_collection(KVS const& kvs) { return kvs::is_type_any(kvs, type_mask_collection); } /// Get name. /// /// This will return nullptr if the KVS has no name. inline char const* name(KVS const& kvs) { return kvs._name; } /// Get name size. inline unsigned name_size(KVS const& kvs) { return kvs._name_size; } /// Get name hash. inline hash64 name_hash(KVS const& kvs) { return kvs._name_hash; } /// Check if named. inline bool is_named(KVS const& kvs) { return kvs._name; } /// Number of values in the collection. inline unsigned size(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.size : 0; } /// Returns true if there are any values in the collection. inline bool any(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.size : false; } /// Returns true if there are no values in the collection. inline bool empty(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.size == 0 : true; } /// Beginning iterator: [begin, end). inline KVS* begin(KVS& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data : nullptr ; } /// Beginning iterator: [begin, end). inline KVS const* begin(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data : nullptr ; } /// Ending iterator: [begin, end). inline KVS* end(KVS& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data + kvs._value.collection.size : nullptr ; } /// Ending iterator: [begin, end). inline KVS const* end(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data + kvs._value.collection.size : nullptr ; } /// Get integer value. inline s64 integer(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::integer)); return kvs._value.integer; } /// Get decimal value. inline f64 decimal(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::decimal)); return kvs._value.decimal; } /// Get boolean value. inline bool boolean(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::boolean)); return kvs._value.boolean; } /// Get string value. inline char const* string(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::string)); return kvs._value.string.data; } /// Get string value size. inline unsigned string_size(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::string)); return kvs._value.string.size; } /// Get 1-dimensional vector value. inline Vec1 const& vec1(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec1)); return kvs._value.vec1; } /// Get 2-dimensional vector value. inline Vec2 const& vec2(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec2)); return kvs._value.vec2; } /// Get 3-dimensional vector value. inline Vec3 const& vec3(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec3)); return kvs._value.vec3; } /// Get 4-dimensional vector value. inline Vec4 const& vec4(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec4)); return kvs._value.vec4; } /// Clear value (if dynamic) and change type iff type differs. bool set_type(KVS& kvs, KVSType const type); /// Set name. void set_name(KVS& kvs, char const* const name, unsigned const size); /// Set name. template<unsigned N> inline void set_name(KVS& kvs, char const (&name)[N]) { kvs::set_name(kvs, name, N); } /// Clear name. void clear_name(KVS& kvs); /// Clear value. void clear(KVS& kvs); /// Clear value (if dynamic) and change type to KVSType::null. inline void nullify(KVS& kvs) { kvs::set_type(kvs, KVSType::null); } /// Set integer value. inline void integer(KVS& kvs, s64 const value) { kvs::set_type(kvs, KVSType::integer); kvs._value.integer = value; } /// Set decimal value. inline void decimal(KVS& kvs, f64 const value) { kvs::set_type(kvs, KVSType::decimal); kvs._value.decimal = value; } /// Set boolean value. inline void boolean(KVS& kvs, bool const value) { kvs::set_type(kvs, KVSType::boolean); kvs._value.boolean = value; } /// Set string value. void string(KVS& kvs, char const* const value, unsigned const size); /// Set 1-dimensional vector value. inline void vec1(KVS& kvs, Vec1 const& value) { kvs::set_type(kvs, KVSType::vec1); kvs._value.vec1 = value; } /// Set 2-dimensional vector value. inline void vec2(KVS& kvs, Vec2 const& value) { kvs::set_type(kvs, KVSType::vec2); kvs._value.vec2 = value; } /// Set 3-dimensional vector value. inline void vec3(KVS& kvs, Vec3 const& value) { kvs::set_type(kvs, KVSType::vec3); kvs._value.vec3 = value; } /// Set 4-dimensional vector value. inline void vec4(KVS& kvs, Vec4 const& value) { kvs::set_type(kvs, KVSType::vec4); kvs._value.vec4 = value; } /** @} */ // end of doc-group kvs } // namespace kvs /// This will nullify the KVS. inline KVS::~KVS() { kvs::nullify(*this); kvs::clear_name(*this); } /// Construct null KVS. inline KVS::KVS() : KVS(KVSType::null) {} /// Construct with integer value. inline KVS::KVS(s64 const value) : KVS(KVSType::integer) { _value.integer = value; } /// Construct with decimal value. inline KVS::KVS(f64 const value) : KVS(KVSType::decimal) { _value.decimal = value; } /// Construct with boolean value. inline KVS::KVS(bool const value) : KVS(KVSType::boolean) { _value.boolean = value; } /// Construct with string value. template<unsigned N> inline KVS::KVS(char const (&value)[N]) : KVS(value, N) {} /// Construct with 1-dimensional vector value. inline KVS::KVS(Vec1 const& value) : KVS(KVSType::vec1) { _value.vec1 = value; } /// Construct with 2-dimensional vector value. inline KVS::KVS(Vec2 const& value) : KVS(KVSType::vec2) { _value.vec2 = value; } /// Construct with 3-dimensional vector value. inline KVS::KVS(Vec3 const& value) : KVS(KVSType::vec3) { _value.vec3 = value; } /// Construct with 4-dimensional vector value. inline KVS::KVS(Vec4 const& value) : KVS(KVSType::vec4) { _value.vec4 = value; } inline KVS::KVS(KVSType const type) : _type(type) , _name(nullptr) , _name_size(0) , _name_hash(hash::IDENTITY64) , _value() {} /** @cond INTERNAL */ // ADL support inline KVS* begin(KVS& kvs) { return kvs::begin(kvs); } inline KVS const* begin(KVS const& kvs) { return kvs::begin(kvs); } inline KVS* end(KVS& kvs) { return kvs::end(kvs); } inline KVS const* end(KVS const& kvs) { return kvs::end(kvs); } /** @endcond */ // INTERNAL } // namespace togo <commit_msg>kvs: ensure name() and string() always return a valid pointer.<commit_after>#line 2 "togo/kvs.hpp" /** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file kvs.hpp @brief KVS interface. @ingroup kvs */ #pragma once #include <togo/config.hpp> #include <togo/types.hpp> #include <togo/utility.hpp> #include <togo/kvs_types.hpp> #include <togo/assert.hpp> #include <togo/hash.hpp> namespace togo { namespace kvs { /** @addtogroup kvs @{ */ namespace { static constexpr KVSType const type_mask_vector = KVSType::vec1 | KVSType::vec2 | KVSType::vec3 | KVSType::vec4 ; /*static constexpr KVSType const type_mask_value = KVSType::integer | KVSType::decimal | KVSType::boolean | KVSType::string | type_mask_vector ; static constexpr KVSType const type_mask_value_nullable = KVSType::null | type_mask_value ;*/ static constexpr KVSType const type_mask_collection = KVSType::array | KVSType::node ; } // anonymous namespace /// Get type. inline KVSType type(KVS const& kvs) { return kvs._type; } /// Check type equivalence. inline bool is_type(KVS const& kvs, KVSType const type) { return kvs._type == type; } /// Check type by set. inline bool is_type_any(KVS const& kvs, KVSType const type) { return enum_bool(kvs._type & type); } /// Check if type is KVSType::null. inline bool is_null(KVS const& kvs) { return kvs::is_type(kvs, KVSType::null); } /// Check if type is KVSType::integer. inline bool is_integer(KVS const& kvs) { return kvs::is_type(kvs, KVSType::integer); } /// Check if type is KVSType::decimal. inline bool is_decimal(KVS const& kvs) { return kvs::is_type(kvs, KVSType::decimal); } /// Check if type is KVSType::boolean. inline bool is_boolean(KVS const& kvs) { return kvs::is_type(kvs, KVSType::boolean); } /// Check if type is KVSType::string. inline bool is_string(KVS const& kvs) { return kvs::is_type(kvs, KVSType::string); } /// Check if type is a vector type. inline bool is_vector(KVS const& kvs) { return kvs::is_type_any(kvs, type_mask_vector); } /// Check if type is an array or node. inline bool is_collection(KVS const& kvs) { return kvs::is_type_any(kvs, type_mask_collection); } /// Get name (NUL-terminated). inline char const* name(KVS const& kvs) { return kvs._name ? kvs._name : ""; } /// Get name size. /// /// This does not include the NUL terminator. inline unsigned name_size(KVS const& kvs) { return kvs._name_size; } /// Get name hash. inline hash64 name_hash(KVS const& kvs) { return kvs._name_hash; } /// Check if named. inline bool is_named(KVS const& kvs) { return kvs._name; } /// Number of values in the collection. inline unsigned size(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.size : 0; } /// Returns true if there are any values in the collection. inline bool any(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.size : false; } /// Returns true if there are no values in the collection. inline bool empty(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.size == 0 : true; } /// Beginning iterator: [begin, end). inline KVS* begin(KVS& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data : nullptr ; } /// Beginning iterator: [begin, end). inline KVS const* begin(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data : nullptr ; } /// Ending iterator: [begin, end). inline KVS* end(KVS& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data + kvs._value.collection.size : nullptr ; } /// Ending iterator: [begin, end). inline KVS const* end(KVS const& kvs) { return kvs::is_collection(kvs) ? kvs._value.collection.data + kvs._value.collection.size : nullptr ; } /// Get integer value. inline s64 integer(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::integer)); return kvs._value.integer; } /// Get decimal value. inline f64 decimal(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::decimal)); return kvs._value.decimal; } /// Get boolean value. inline bool boolean(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::boolean)); return kvs._value.boolean; } /// Get string value (NUL-terminated). inline char const* string(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::string)); return kvs._value.string.data ? kvs._value.string.data : ""; } /// Get string value size. /// /// This does not include the NUL terminator. inline unsigned string_size(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::string)); return kvs._value.string.size; } /// Get 1-dimensional vector value. inline Vec1 const& vec1(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec1)); return kvs._value.vec1; } /// Get 2-dimensional vector value. inline Vec2 const& vec2(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec2)); return kvs._value.vec2; } /// Get 3-dimensional vector value. inline Vec3 const& vec3(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec3)); return kvs._value.vec3; } /// Get 4-dimensional vector value. inline Vec4 const& vec4(KVS const& kvs) { TOGO_ASSERTE(kvs::is_type(kvs, KVSType::vec4)); return kvs._value.vec4; } /// Clear value (if dynamic) and change type iff type differs. bool set_type(KVS& kvs, KVSType const type); /// Set name. void set_name(KVS& kvs, char const* const name, unsigned const size); /// Set name. template<unsigned N> inline void set_name(KVS& kvs, char const (&name)[N]) { kvs::set_name(kvs, name, N); } /// Clear name. void clear_name(KVS& kvs); /// Clear value. void clear(KVS& kvs); /// Clear value (if dynamic) and change type to KVSType::null. inline void nullify(KVS& kvs) { kvs::set_type(kvs, KVSType::null); } /// Set integer value. inline void integer(KVS& kvs, s64 const value) { kvs::set_type(kvs, KVSType::integer); kvs._value.integer = value; } /// Set decimal value. inline void decimal(KVS& kvs, f64 const value) { kvs::set_type(kvs, KVSType::decimal); kvs._value.decimal = value; } /// Set boolean value. inline void boolean(KVS& kvs, bool const value) { kvs::set_type(kvs, KVSType::boolean); kvs._value.boolean = value; } /// Set string value. void string(KVS& kvs, char const* const value, unsigned const size); /// Set 1-dimensional vector value. inline void vec1(KVS& kvs, Vec1 const& value) { kvs::set_type(kvs, KVSType::vec1); kvs._value.vec1 = value; } /// Set 2-dimensional vector value. inline void vec2(KVS& kvs, Vec2 const& value) { kvs::set_type(kvs, KVSType::vec2); kvs._value.vec2 = value; } /// Set 3-dimensional vector value. inline void vec3(KVS& kvs, Vec3 const& value) { kvs::set_type(kvs, KVSType::vec3); kvs._value.vec3 = value; } /// Set 4-dimensional vector value. inline void vec4(KVS& kvs, Vec4 const& value) { kvs::set_type(kvs, KVSType::vec4); kvs._value.vec4 = value; } /** @} */ // end of doc-group kvs } // namespace kvs /// This will nullify the KVS. inline KVS::~KVS() { kvs::nullify(*this); kvs::clear_name(*this); } /// Construct null KVS. inline KVS::KVS() : KVS(KVSType::null) {} /// Construct with integer value. inline KVS::KVS(s64 const value) : KVS(KVSType::integer) { _value.integer = value; } /// Construct with decimal value. inline KVS::KVS(f64 const value) : KVS(KVSType::decimal) { _value.decimal = value; } /// Construct with boolean value. inline KVS::KVS(bool const value) : KVS(KVSType::boolean) { _value.boolean = value; } /// Construct with string value. template<unsigned N> inline KVS::KVS(char const (&value)[N]) : KVS(value, N) {} /// Construct with 1-dimensional vector value. inline KVS::KVS(Vec1 const& value) : KVS(KVSType::vec1) { _value.vec1 = value; } /// Construct with 2-dimensional vector value. inline KVS::KVS(Vec2 const& value) : KVS(KVSType::vec2) { _value.vec2 = value; } /// Construct with 3-dimensional vector value. inline KVS::KVS(Vec3 const& value) : KVS(KVSType::vec3) { _value.vec3 = value; } /// Construct with 4-dimensional vector value. inline KVS::KVS(Vec4 const& value) : KVS(KVSType::vec4) { _value.vec4 = value; } inline KVS::KVS(KVSType const type) : _type(type) , _name(nullptr) , _name_size(0) , _name_hash(hash::IDENTITY64) , _value() {} /** @cond INTERNAL */ // ADL support inline KVS* begin(KVS& kvs) { return kvs::begin(kvs); } inline KVS const* begin(KVS const& kvs) { return kvs::begin(kvs); } inline KVS* end(KVS& kvs) { return kvs::end(kvs); } inline KVS const* end(KVS const& kvs) { return kvs::end(kvs); } /** @endcond */ // INTERNAL } // namespace togo <|endoftext|>
<commit_before>#pragma once #include <cybozu/inttype.hpp> namespace cybozu { template<class T> uint32_t hash32(const T *x, size_t n, uint32_t v = 0) { if (v == 0) v = 2166136261U; for (size_t i = 0; i < n; i++) { v ^= x[i]; v *= 16777619; } return v; } template<class T> uint64_t hash64(const T *x, size_t n, uint64_t v = 0) { if (v == 0) v = 14695981039346656037ULL; for (size_t i = 0; i < n; i++) { v ^= x[i]; v *= 1099511628211ULL; } v ^= v >> 32; return v; } } // cybozu namespace boost { template<class T> struct hash; } // boost namespace std { CYBOZU_NAMESPACE_TR1_BEGIN #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4099) // missmatch class and struct #endif template<class T> struct hash; #ifdef _MSC_VER #pragma warning(pop) #endif CYBOZU_NAMESPACE_TR1_END } // std <commit_msg>accept any container for hash<commit_after>#pragma once #include <cybozu/inttype.hpp> namespace cybozu { template<class Iter> uint32_t hash32(Iter begin, Iter end, uint32_t v = 0) { if (v == 0) v = 2166136261U; while (begin != end) { v ^= *begin++; v *= 16777619; } return v; } template<class Iter> uint64_t hash64(Iter begin, Iter end, uint64_t v = 0) { if (v == 0) v = 14695981039346656037ULL; while (begin != end) { v ^= *begin++; v *= 1099511628211ULL; } v ^= v >> 32; return v; } template<class T> uint32_t hash32(const T *x, size_t n, uint32_t v = 0) { return hash32(x, x + n, v); } template<class T> uint64_t hash64(const T *x, size_t n, uint64_t v = 0) { return hash64(x, x + n, v); } } // cybozu namespace boost { template<class T> struct hash; } // boost namespace std { CYBOZU_NAMESPACE_TR1_BEGIN #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4099) // missmatch class and struct #endif template<class T> struct hash; #ifdef _MSC_VER #pragma warning(pop) #endif CYBOZU_NAMESPACE_TR1_END } // std <|endoftext|>
<commit_before>#ifndef ENUM_CLASS_FLAGS_HPP #define ENUM_CLASS_FLAGS_HPP #include "allow_flags.hpp" #include "iterator.hpp" #include <bitset> #include <initializer_list> #include <numeric> #include <utility> namespace flags { constexpr struct empty_t{} empty; template <class E> struct flags { public: static_assert(is_flags<E>::value, "flags::flags is disallowed for this type; " "use ALLOW_FLAGS_FOR_ENUM macro."); using enum_type = typename std::decay<E>::type; using underlying_type = typename std::underlying_type<enum_type>::type; using impl_type = typename std::make_unsigned<underlying_type>::type; using iterator = FlagsIterator<enum_type>; using const_iterator = iterator; using value_type = typename iterator::value_type; using reference = typename iterator::reference; using const_reference = typename iterator::reference; using pointer = enum_type *; using const_pointer = const enum_type *; using size_type = std::size_t; using difference_type = typename iterator::difference_type; constexpr static std::size_t bit_size() { return sizeof(impl_type) * 8; } private: template <class T, class Res = std::nullptr_t> using convertible = std::enable_if<std::is_convertible<T, enum_type>::value, Res>; public: flags() noexcept = default; flags(const flags &fl) noexcept = default; flags &operator=(const flags &fl) noexcept = default; flags(flags &&fl) noexcept = default; flags &operator=(flags &&fl) noexcept= default; explicit constexpr flags(empty_t) noexcept : val_(0) {} #ifdef ENUM_CLASS_FLAGS_FORBID_IMPLICT_CONVERSION explicit #endif constexpr flags(enum_type e) noexcept : val_(static_cast<impl_type>(e)) {} flags &operator=(enum_type e) noexcept { val_ = static_cast<impl_type>(e); return *this; } flags(std::initializer_list<enum_type> il) noexcept : val_(0) { insert(il); } flags &operator=(std::initializer_list<enum_type> il) noexcept { clear(); insert(il); return *this; } template <class ... Args> flags(enum_type e, Args ... args) noexcept : flags{e, args...} {} template <class FwIter> flags(FwIter b, FwIter e, typename convertible<decltype(*b)>::type = nullptr) noexcept(noexcept(std::declval<flags>().insert(std::declval<FwIter>(), std::declval<FwIter>()))) : val_(0) { insert(b, e); } constexpr explicit operator bool() const noexcept { return val_; } constexpr bool operator!() const noexcept { return !val_; } flags operator~() const noexcept { return flags(~val_); } flags &operator|=(const flags &fl) noexcept { val_ |= fl.val_; return *this; } flags &operator&=(const flags &fl) noexcept { val_ &= fl.val_; return *this; } flags &operator^=(const flags &fl) noexcept { val_ ^= fl.val_; return *this; } flags &operator|=(enum_type e) noexcept { val_ |= static_cast<impl_type>(e); return *this; } flags &operator&=(enum_type e) noexcept { val_ &= static_cast<impl_type>(e); return *this; } flags &operator^=(enum_type e) noexcept { val_ ^= static_cast<impl_type>(e); return *this; } void swap(flags &fl) noexcept { std::swap(val_, fl.val_); } constexpr underlying_type underlying_value() const noexcept { return static_cast<underlying_type>(val_); } void set_underlying_value(underlying_type newval) noexcept { val_ = static_cast<impl_type>(newval); } constexpr explicit operator std::bitset<bit_size()>() const noexcept { return to_bitset(); } constexpr std::bitset<bit_size()> to_bitset() const noexcept { return {val_}; } bool empty() const noexcept { return !val_; } size_type size() const noexcept { return std::distance(this->begin(), this->end()); } constexpr size_type max_size() const noexcept { return bit_size(); } iterator begin() const noexcept { return cbegin(); } iterator cbegin() const noexcept { return iterator{val_}; } iterator end() const noexcept { return cend(); } iterator cend() const noexcept { return {}; } iterator find(enum_type e) const noexcept { return {val_, e}; } size_type count(enum_type e) const noexcept { return find(e) != end() ? 1 : 0; } std::pair<iterator, iterator> equal_range(enum_type e) const noexcept { auto i = find(e); auto j = i; return {i, ++j}; } template <class... Args> std::pair<iterator, bool> emplace(Args && ... args) noexcept { return insert(enum_type{args...}); } template <class... Args> iterator emplace_hint(iterator, Args && ... args) noexcept { return emplace(args...).first; } std::pair<iterator, bool> insert(enum_type e) noexcept { auto i = find(e); if (i == end()) { i.mask_ = static_cast<impl_type>(e); val_ |= i.mask_; update_uvalue(i); return {i, true}; } return {i, false}; } std::pair<iterator, bool> insert(iterator, enum_type e) noexcept { return insert(e); } template <class FwIter> auto insert(FwIter i1, FwIter i2) noexcept(noexcept(++i1) && noexcept(*i1) && noexcept(i1 == i2)) -> typename convertible<decltype(*i1), void>::type { val_ |= std::accumulate(i1, i2, impl_type{0}, [](impl_type i, enum_type e) { return i | static_cast<impl_type>(e); }); } template <class Container> auto insert(const Container &ctn) noexcept -> decltype(std::begin(ctn), std::end(ctn), void()) { insert(std::begin(ctn), std::end(ctn)); } iterator erase(iterator i) noexcept { val_ ^= i.mask_; update_uvalue(i); return ++i; } size_type erase(enum_type e) noexcept { auto e_count = count(e); val_ ^= static_cast<impl_type>(e); return e_count; } iterator erase(iterator i1, iterator i2) noexcept { val_ ^= flags(i1, i2).val_; update_uvalue(i2); return ++i2; } void clear() noexcept { val_ = 0; } private: constexpr explicit flags(impl_type val) noexcept : val_(val) {} void update_uvalue(iterator &it) const noexcept { it.uvalue_ = val_; } impl_type val_; }; template <class E> constexpr flags<E> operator|(flags<E> f1, flags<E> f2) noexcept { return f1 |= f2; } template <class E> constexpr flags<E> operator|(flags<E> f, E e) noexcept { return f |= e; } template <class E> constexpr flags<E> operator|(E e, flags<E> f) noexcept { return f |= e; } template <class E> constexpr flags<E> operator&(flags<E> f1, flags<E> f2) noexcept { return f1 &= f2; } template <class E> constexpr flags<E> operator&(flags<E> f, E e) noexcept { return f &= e; } template <class E> constexpr flags<E> operator&(E e, flags<E> f) noexcept {; return f &= e; } template <class E> constexpr flags<E> operator^(flags<E> f1, flags<E> f2) noexcept { return f1 ^= f2; } template <class E> constexpr flags<E> operator^(flags<E> f, E e) noexcept { return f ^= e; } template <class E> constexpr flags<E> operator^(E e, flags<E> f) noexcept { return f ^= e; } template <class E> constexpr bool operator==(const flags<E> &fl1, const flags<E> &fl2) noexcept { return fl1.underlying_value() == fl2.underlying_value(); } template <class E> constexpr bool operator!=(const flags<E> &fl1, const flags<E> &fl2) noexcept { return fl1.underlying_value() != fl2.underlying_value(); } template <class E> constexpr void swap(flags<E> &fl1, flags<E> &fl2) noexcept { fl1.swap(fl2); } } // namespace flags template <class E> constexpr auto operator|(E e1, E e2) noexcept -> typename std::enable_if<flags::is_flags<E>::value, flags::flags<E>>::type { return flags::flags<E>{e1} |= e2; } template <class E> constexpr auto operator&(E e1, E e2) noexcept -> typename std::enable_if<flags::is_flags<E>::value, flags::flags<E>>::type { return flags::flags<E>{e1} &= e2; } template <class E> constexpr auto operator^(E e1, E e2) noexcept -> typename std::enable_if<flags::is_flags<E>::value, flags::flags<E>>::type { return flags::flags<E>{e1} ^= e2; } #endif // ENUM_CLASS_FLAGS_HPP <commit_msg>fix constexps struct with user defined constructor<commit_after>#ifndef ENUM_CLASS_FLAGS_HPP #define ENUM_CLASS_FLAGS_HPP #include "allow_flags.hpp" #include "iterator.hpp" #include <bitset> #include <initializer_list> #include <numeric> #include <utility> namespace flags { constexpr struct empty_t { constexpr empty_t() noexcept {} } empty; template <class E> struct flags { public: static_assert(is_flags<E>::value, "flags::flags is disallowed for this type; " "use ALLOW_FLAGS_FOR_ENUM macro."); using enum_type = typename std::decay<E>::type; using underlying_type = typename std::underlying_type<enum_type>::type; using impl_type = typename std::make_unsigned<underlying_type>::type; using iterator = FlagsIterator<enum_type>; using const_iterator = iterator; using value_type = typename iterator::value_type; using reference = typename iterator::reference; using const_reference = typename iterator::reference; using pointer = enum_type *; using const_pointer = const enum_type *; using size_type = std::size_t; using difference_type = typename iterator::difference_type; constexpr static std::size_t bit_size() { return sizeof(impl_type) * 8; } private: template <class T, class Res = std::nullptr_t> using convertible = std::enable_if<std::is_convertible<T, enum_type>::value, Res>; public: flags() noexcept = default; flags(const flags &fl) noexcept = default; flags &operator=(const flags &fl) noexcept = default; flags(flags &&fl) noexcept = default; flags &operator=(flags &&fl) noexcept= default; explicit constexpr flags(empty_t) noexcept : val_(0) {} #ifdef ENUM_CLASS_FLAGS_FORBID_IMPLICT_CONVERSION explicit #endif constexpr flags(enum_type e) noexcept : val_(static_cast<impl_type>(e)) {} flags &operator=(enum_type e) noexcept { val_ = static_cast<impl_type>(e); return *this; } flags(std::initializer_list<enum_type> il) noexcept : val_(0) { insert(il); } flags &operator=(std::initializer_list<enum_type> il) noexcept { clear(); insert(il); return *this; } template <class ... Args> flags(enum_type e, Args ... args) noexcept : flags{e, args...} {} template <class FwIter> flags(FwIter b, FwIter e, typename convertible<decltype(*b)>::type = nullptr) noexcept(noexcept(std::declval<flags>().insert(std::declval<FwIter>(), std::declval<FwIter>()))) : val_(0) { insert(b, e); } constexpr explicit operator bool() const noexcept { return val_; } constexpr bool operator!() const noexcept { return !val_; } flags operator~() const noexcept { return flags(~val_); } flags &operator|=(const flags &fl) noexcept { val_ |= fl.val_; return *this; } flags &operator&=(const flags &fl) noexcept { val_ &= fl.val_; return *this; } flags &operator^=(const flags &fl) noexcept { val_ ^= fl.val_; return *this; } flags &operator|=(enum_type e) noexcept { val_ |= static_cast<impl_type>(e); return *this; } flags &operator&=(enum_type e) noexcept { val_ &= static_cast<impl_type>(e); return *this; } flags &operator^=(enum_type e) noexcept { val_ ^= static_cast<impl_type>(e); return *this; } void swap(flags &fl) noexcept { std::swap(val_, fl.val_); } constexpr underlying_type underlying_value() const noexcept { return static_cast<underlying_type>(val_); } void set_underlying_value(underlying_type newval) noexcept { val_ = static_cast<impl_type>(newval); } constexpr explicit operator std::bitset<bit_size()>() const noexcept { return to_bitset(); } constexpr std::bitset<bit_size()> to_bitset() const noexcept { return {val_}; } bool empty() const noexcept { return !val_; } size_type size() const noexcept { return std::distance(this->begin(), this->end()); } constexpr size_type max_size() const noexcept { return bit_size(); } iterator begin() const noexcept { return cbegin(); } iterator cbegin() const noexcept { return iterator{val_}; } iterator end() const noexcept { return cend(); } iterator cend() const noexcept { return {}; } iterator find(enum_type e) const noexcept { return {val_, e}; } size_type count(enum_type e) const noexcept { return find(e) != end() ? 1 : 0; } std::pair<iterator, iterator> equal_range(enum_type e) const noexcept { auto i = find(e); auto j = i; return {i, ++j}; } template <class... Args> std::pair<iterator, bool> emplace(Args && ... args) noexcept { return insert(enum_type{args...}); } template <class... Args> iterator emplace_hint(iterator, Args && ... args) noexcept { return emplace(args...).first; } std::pair<iterator, bool> insert(enum_type e) noexcept { auto i = find(e); if (i == end()) { i.mask_ = static_cast<impl_type>(e); val_ |= i.mask_; update_uvalue(i); return {i, true}; } return {i, false}; } std::pair<iterator, bool> insert(iterator, enum_type e) noexcept { return insert(e); } template <class FwIter> auto insert(FwIter i1, FwIter i2) noexcept(noexcept(++i1) && noexcept(*i1) && noexcept(i1 == i2)) -> typename convertible<decltype(*i1), void>::type { val_ |= std::accumulate(i1, i2, impl_type{0}, [](impl_type i, enum_type e) { return i | static_cast<impl_type>(e); }); } template <class Container> auto insert(const Container &ctn) noexcept -> decltype(std::begin(ctn), std::end(ctn), void()) { insert(std::begin(ctn), std::end(ctn)); } iterator erase(iterator i) noexcept { val_ ^= i.mask_; update_uvalue(i); return ++i; } size_type erase(enum_type e) noexcept { auto e_count = count(e); val_ ^= static_cast<impl_type>(e); return e_count; } iterator erase(iterator i1, iterator i2) noexcept { val_ ^= flags(i1, i2).val_; update_uvalue(i2); return ++i2; } void clear() noexcept { val_ = 0; } private: constexpr explicit flags(impl_type val) noexcept : val_(val) {} void update_uvalue(iterator &it) const noexcept { it.uvalue_ = val_; } impl_type val_; }; template <class E> constexpr flags<E> operator|(flags<E> f1, flags<E> f2) noexcept { return f1 |= f2; } template <class E> constexpr flags<E> operator|(flags<E> f, E e) noexcept { return f |= e; } template <class E> constexpr flags<E> operator|(E e, flags<E> f) noexcept { return f |= e; } template <class E> constexpr flags<E> operator&(flags<E> f1, flags<E> f2) noexcept { return f1 &= f2; } template <class E> constexpr flags<E> operator&(flags<E> f, E e) noexcept { return f &= e; } template <class E> constexpr flags<E> operator&(E e, flags<E> f) noexcept {; return f &= e; } template <class E> constexpr flags<E> operator^(flags<E> f1, flags<E> f2) noexcept { return f1 ^= f2; } template <class E> constexpr flags<E> operator^(flags<E> f, E e) noexcept { return f ^= e; } template <class E> constexpr flags<E> operator^(E e, flags<E> f) noexcept { return f ^= e; } template <class E> constexpr bool operator==(const flags<E> &fl1, const flags<E> &fl2) noexcept { return fl1.underlying_value() == fl2.underlying_value(); } template <class E> constexpr bool operator!=(const flags<E> &fl1, const flags<E> &fl2) noexcept { return fl1.underlying_value() != fl2.underlying_value(); } template <class E> constexpr void swap(flags<E> &fl1, flags<E> &fl2) noexcept { fl1.swap(fl2); } } // namespace flags template <class E> constexpr auto operator|(E e1, E e2) noexcept -> typename std::enable_if<flags::is_flags<E>::value, flags::flags<E>>::type { return flags::flags<E>{e1} |= e2; } template <class E> constexpr auto operator&(E e1, E e2) noexcept -> typename std::enable_if<flags::is_flags<E>::value, flags::flags<E>>::type { return flags::flags<E>{e1} &= e2; } template <class E> constexpr auto operator^(E e1, E e2) noexcept -> typename std::enable_if<flags::is_flags<E>::value, flags::flags<E>>::type { return flags::flags<E>{e1} ^= e2; } #endif // ENUM_CLASS_FLAGS_HPP <|endoftext|>
<commit_before>#ifndef LIBICS3_ICS3_EEPROM_H_ #define LIBICS3_ICS3_EEPROM_H_ #include"ics3/eepparam.hpp" #include<algorithm> namespace ics { class ICS3; class EepRom { public: friend ICS3; // for ICS3::getRom() EepParam get(EepParam) const; void set(const EepParam&) noexcept; template<typename Iter> void write(Iter&&) const noexcept; private: explicit EepRom(const std::array<uint8_t, 64>&); std::array<uint8_t, 64> data; }; inline ics::EepParam ics::EepRom::get(EepParam place) const { place.read(data); return place; } inline void EepRom::set(const EepParam& param) noexcept { param.write(data); } template<typename Iter> inline void EepRom::write(Iter&& dest) const noexcept { std::copy(data.begin(), data.end(), dest); } inline EepRom::EepRom(const std::array<uint8_t, 64>& src) : data {} { std::copy(src.begin(), src.end(), data.begin()); } } #endif // LIBICS3_ICS3_EEPROM_H_ <commit_msg>Update interface<commit_after>#ifndef LIBICS3_ICS3_EEPROM_H_ #define LIBICS3_ICS3_EEPROM_H_ #include"ics3/eepparam.hpp" #include<algorithm> namespace ics { class ICS3; class EepRom { public: friend ICS3; // for ICS3::getRom() EepParam get(EepParam) const; void set(const EepParam&) noexcept; template<typename Iter> void write(Iter&&) const; private: explicit EepRom(const std::array<uint8_t, 64>&); std::array<uint8_t, 64> data; }; inline ics::EepParam ics::EepRom::get(EepParam place) const { place.read(data); // throw std::out_of_range return place; } inline void EepRom::set(const EepParam& param) noexcept { param.write(data); } template<typename Iter> inline void EepRom::write(Iter&& dest) const { std::copy(data.begin(), data.end(), dest); } inline EepRom::EepRom(const std::array<uint8_t, 64>& src) : data {} { std::copy(src.begin(), src.end(), data.begin()); } } #endif // LIBICS3_ICS3_EEPROM_H_ <|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ // Network API based on boost::asio #ifndef LIBPORT_ASIO_HH # define LIBPORT_ASIO_HH # include <libport/config.h> # include <libport/sys/socket.h> # include <libport/iostream> // At least on OS X, many symbols are not available where we expect // them. And it is clearly connected to our using // -fvisibility=hidden. I (AD) could not exactly pinpoint the // problem, but at least I know one cure: do not play dirty visibility // tricks with Asio. # if ! defined WIN32 # pragma GCC visibility push(default) # endif # include <boost/asio.hpp> # if defined LIBPORT_ENABLE_SSL # include <boost/asio/ssl.hpp> # endif # if ! defined WIN32 # pragma GCC visibility pop # endif # include <boost/function.hpp> # include <libport/destructible.hh> # include <libport/export.hh> # include <libport/finally.hh> # include <libport/utime.hh> # include <boost/version.hpp> # if BOOST_VERSION >= 103600 # include <libport/rs232.hh> # endif namespace libport { class LIBPORT_API AsioDestructible: public Destructible { protected: virtual void doDestroy(); }; //FIXME: extend to provide a way to ensure workerThread not started. /** Get the io_service handling all asynchronous operations. * * \param startWorkerThread create a thread in which to run the io_service. * If \b startWorkerThread is false on \b first invocation, the user * is responsible for calling the work or poll methods of the io_service. */ LIBPORT_API boost::asio::io_service& get_io_service(bool startWorkerThread = true); /** BaseSocket class. * * This class has a callback-based API: onReadFunc() and onErrorFunc(). */ class LIBPORT_API BaseSocket: public AsioDestructible { public: virtual ~BaseSocket(){} libport::Finally deletor; /// Write data asynchronously to the socket. virtual void write(const void* data, unsigned int length) = 0; /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } /// Alias on close() for API compatibility. void disconnect() { close(); } /// Return if the socket is connected to a remote host. virtual bool isConnected() const = 0; /// Disconnect the socket from the remote host, calls onError. virtual void close() = 0; /// Get port of remote endpoint virtual unsigned short getRemotePort() const = 0; /// Get IP address of remote endpoint virtual std::string getRemoteHost() const = 0; /// Get port of local endpoint virtual unsigned short getLocalPort() const = 0; /// Get IP address of local endpoint virtual std::string getLocalHost() const = 0; virtual int stealFD() = 0; virtual int getFD() = 0; /// Callback function called each time new data is available. boost::function1<bool, boost::asio::streambuf&> onReadFunc; /// Callback function called in case of error on the socket. boost::function1<void, boost::system::error_code> onErrorFunc; /// Mutex to protect access to the above callbacks. Lockable callbackLock; }; /// Endpoint on an UDP socket. class LIBPORT_API UDPLink { public: virtual ~UDPLink() {} virtual void reply(const void* data, size_t length) = 0; void reply(const std::string& s) { reply(s.c_str(), s.length()); } }; /** Socket class with a higher API. * * It is recommended that you always asynchronously destroy Socket instances * by calling the destroy() method. If you want to put instances in the stack, * or explicitly call delete for whatever reason, you must in your destructor: * - call close() * - call wasDestroyed() * - call waitForDestructionPermission(), if the io_service is running in * another thread(the default behavior). */ class LIBPORT_API Socket: public AsioDestructible { public: Socket(boost::asio::io_service& io = libport::get_io_service()) : base_(0) , io_(io) {} virtual ~Socket(); /** Set underlying BaseSocket object, setup its callbacks to call our virtual functions. */ virtual void setBase(BaseSocket*); /** Called each time new data is received. * \return the number of bytes used in buffer. The remaining data will * be passed again to this function as soon as at least an extra byte * is available. */ virtual int onRead(const void*, size_t length) { return length; } /** Called in case of error on the socket. By default, do nothing. */ virtual void onError(boost::system::error_code); /** Called on socket connection */ virtual void onConnect() {} /// Ask for the asynchronous destruction of this object. virtual void destroy(); void write(const void* data, unsigned int length) { base_->write(data, length); } /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } void send(const std::string& s) { write(s.c_str(), s.length()); } void close() { if (base_) base_->close(); } unsigned short getRemotePort() const { return base_->getRemotePort();} std::string getRemoteHost() const { return base_->getRemoteHost();} unsigned short getLocalPort() const { return base_->getLocalPort();} std::string getLocalHost() const { return base_->getLocalHost();} bool isConnected() const {return base_ ? base_->isConnected() : false;} /** Connect to a remote host. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. * \param asynchronous make an asynchronous attempt. The function will * return immediately, and either onConnect will be called when the * connection succeeds, or onError() will be called. * \return an error code if the connection failed. * */ boost::system::error_code connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); boost::system::error_code connect(const std::string& host, unsigned port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); # if BOOST_VERSION >= 103600 boost::system::error_code open_serial(const std::string& device, unsigned int rate); # endif /** Make an asynchronous connection attempt to a remote host. * This API garantees that either the onConnect() or the onError() function * will be called. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. */ void async_connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0) { connect(host, port, udp, usTimeout, true); } typedef void* Handle; typedef boost::function0<Socket*> SocketFactory; /** Listen using udp. * Call onRead(data, length, link) for each new packet. Link can be used * to reply to the sender through its UDPLink::reply() method. */ static Handle listenUDP(const std::string& host, const std::string& port, boost::function3<void, const void*, int, boost::shared_ptr<UDPLink> > onRead, boost::system::error_code& erc); /** Listen using TCP or UDP. * * \param f a socket factory. For each new connection the function will * be called and the resulting socket object bound to the new connection. */ boost::system::error_code listen(SocketFactory f, const std::string& host, const std::string& port, bool udp = false); boost::system::error_code listen(SocketFactory f, const std::string& host, unsigned port, bool udp = false); #if defined LIBPORT_ENABLE_SSL boost::system::error_code listenSSL(SocketFactory f, const std::string& host, const std::string& port, boost::asio::ssl::context_base::method ctx = boost::asio::ssl::context::sslv23_server, boost::asio::ssl::context::options options = boost::asio::ssl::context::verify_none, const std::string& privateKeyFile = "", const std::string& certChainFile = "", const std::string& tmpDHFile = "" , const std::string& cipherList = ""); #endif /// Steal file descriptor from Socket. Return the file descriptor. int stealFD(); /// Get file descriptor from Socket. int getFD(); /// Set file descriptor template<class Sock> void setFD(int fd, typename Sock::protocol_type proto); /** Sleep for specified amount of time, polling if current thread is * the asio worker thread */ static void sleep(utime_t duration); boost::asio::io_service& get_io_service(); protected: bool onRead_(boost::asio::streambuf&); std::string buffer; BaseSocket* base_; private: template<typename Proto, typename BaseFactory> boost::system::error_code listenProto(SocketFactory f, const std::string& host, const std::string&port, BaseFactory bf); template<typename Proto, typename BaseFactory> boost::system::error_code connectProto(const std::string& host, const std::string& port, utime_t timeout, bool async, BaseFactory bf); boost::asio::io_service& io_; }; /** Wrapper of libport::Socket to be able to use Socket without inherit from * it. */ class LIBPORT_API ConcreteSocket: public Socket { public: typedef boost::function2<int, const void*, size_t> onread_type; typedef boost::function1<void, boost::system::error_code> onerror_type; typedef boost::function0<void> onconnect_type; typedef Socket super_type; ConcreteSocket(boost::asio::io_service& io = libport::get_io_service()) : Socket(io) , onconnect_(boost::bind(&super_type::onConnect, this)) , onerror_(boost::bind(&super_type::onError, this, _1)) , onread_(boost::bind(&super_type::onRead, this, _1, _2)) {} ConcreteSocket& onConnect(onconnect_type cb) { onconnect_ = cb; return *this; } ConcreteSocket& onError(onerror_type cb) { onerror_ = cb; return *this; } ConcreteSocket& onRead(onread_type cb) { onread_ = cb; return *this; } virtual void onConnect() { onconnect_(); } virtual void onError(boost::system::error_code erc) { onerror_(erc); } virtual int onRead(const void* data, size_t length) { return onread_(data, length); } private: onconnect_type onconnect_; onerror_type onerror_; onread_type onread_; }; LIBPORT_API bool isPollThread(); /** Poll on an io_service for given duration in microseconds. * @param duration max duration for which to poll in microseconds * @param once process at most one handler before returning if true */ LIBPORT_API void pollFor(utime_t duration, bool once = false, boost::asio::io_service& io = get_io_service()); typedef boost::shared_ptr<boost::asio::deadline_timer> AsyncCallHandler; /** Call \b callback() in \b usDelay microseconds. * If the method cancel() of the returned timer object is invoked before * expiration of the delay, the call is aborted and callback() is not * called. */ AsyncCallHandler asyncCall(boost::function0<void> callback, utime_t usDelay, boost::asio::io_service& io = get_io_service()); } # include "libport/asio.hxx" #endif <commit_msg>80 columns.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ // Network API based on boost::asio #ifndef LIBPORT_ASIO_HH # define LIBPORT_ASIO_HH # include <libport/config.h> # include <libport/sys/socket.h> # include <libport/iostream> // At least on OS X, many symbols are not available where we expect // them. And it is clearly connected to our using // -fvisibility=hidden. I (AD) could not exactly pinpoint the // problem, but at least I know one cure: do not play dirty visibility // tricks with Asio. # if ! defined WIN32 # pragma GCC visibility push(default) # endif # include <boost/asio.hpp> # if defined LIBPORT_ENABLE_SSL # include <boost/asio/ssl.hpp> # endif # if ! defined WIN32 # pragma GCC visibility pop # endif # include <boost/function.hpp> # include <libport/destructible.hh> # include <libport/export.hh> # include <libport/finally.hh> # include <libport/utime.hh> # include <boost/version.hpp> # if BOOST_VERSION >= 103600 # include <libport/rs232.hh> # endif namespace libport { class LIBPORT_API AsioDestructible: public Destructible { protected: virtual void doDestroy(); }; //FIXME: extend to provide a way to ensure workerThread not started. /** Get the io_service handling all asynchronous operations. * * \param startWorkerThread create a thread in which to run the io_service. * If \b startWorkerThread is false on \b first invocation, the user * is responsible for calling the work or poll methods of the io_service. */ LIBPORT_API boost::asio::io_service& get_io_service(bool startWorkerThread = true); /** BaseSocket class. * * This class has a callback-based API: onReadFunc() and onErrorFunc(). */ class LIBPORT_API BaseSocket: public AsioDestructible { public: virtual ~BaseSocket(){} libport::Finally deletor; /// Write data asynchronously to the socket. virtual void write(const void* data, unsigned int length) = 0; /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } /// Alias on close() for API compatibility. void disconnect() { close(); } /// Return if the socket is connected to a remote host. virtual bool isConnected() const = 0; /// Disconnect the socket from the remote host, calls onError. virtual void close() = 0; /// Get port of remote endpoint virtual unsigned short getRemotePort() const = 0; /// Get IP address of remote endpoint virtual std::string getRemoteHost() const = 0; /// Get port of local endpoint virtual unsigned short getLocalPort() const = 0; /// Get IP address of local endpoint virtual std::string getLocalHost() const = 0; virtual int stealFD() = 0; virtual int getFD() = 0; /// Callback function called each time new data is available. boost::function1<bool, boost::asio::streambuf&> onReadFunc; /// Callback function called in case of error on the socket. boost::function1<void, boost::system::error_code> onErrorFunc; /// Mutex to protect access to the above callbacks. Lockable callbackLock; }; /// Endpoint on an UDP socket. class LIBPORT_API UDPLink { public: virtual ~UDPLink() {} virtual void reply(const void* data, size_t length) = 0; void reply(const std::string& s) { reply(s.c_str(), s.length()); } }; /** Socket class with a higher API. * * It is recommended that you always asynchronously destroy Socket instances * by calling the destroy() method. If you want to put instances in the stack, * or explicitly call delete for whatever reason, you must in your destructor: * - call close() * - call wasDestroyed() * - call waitForDestructionPermission(), if the io_service is running in * another thread(the default behavior). */ class LIBPORT_API Socket: public AsioDestructible { public: Socket(boost::asio::io_service& io = libport::get_io_service()) : base_(0) , io_(io) {} virtual ~Socket(); /* Set underlying BaseSocket object, setup its callbacks to call * our virtual functions. */ virtual void setBase(BaseSocket*); /** Called each time new data is received. * \return the number of bytes used in buffer. The remaining data will * be passed again to this function as soon as at least an extra byte * is available. */ virtual int onRead(const void*, size_t length) { return length; } /** Called in case of error on the socket. By default, do nothing. */ virtual void onError(boost::system::error_code); /** Called on socket connection */ virtual void onConnect() {} /// Ask for the asynchronous destruction of this object. virtual void destroy(); void write(const void* data, unsigned int length) { base_->write(data, length); } /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } void send(const std::string& s) { write(s.c_str(), s.length()); } void close() { if (base_) base_->close(); } unsigned short getRemotePort() const { return base_->getRemotePort();} std::string getRemoteHost() const { return base_->getRemoteHost();} unsigned short getLocalPort() const { return base_->getLocalPort();} std::string getLocalHost() const { return base_->getLocalHost();} bool isConnected() const {return base_ ? base_->isConnected() : false;} /** Connect to a remote host. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. * \param asynchronous make an asynchronous attempt. The function will * return immediately, and either onConnect will be called when the * connection succeeds, or onError() will be called. * \return an error code if the connection failed. * */ boost::system::error_code connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); boost::system::error_code connect(const std::string& host, unsigned port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); # if BOOST_VERSION >= 103600 boost::system::error_code open_serial(const std::string& device, unsigned int rate); # endif /** Make an asynchronous connection attempt to a remote host. * This API garantees that either the onConnect() or the onError() function * will be called. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. */ void async_connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0) { connect(host, port, udp, usTimeout, true); } typedef void* Handle; typedef boost::function0<Socket*> SocketFactory; /** Listen using udp. * Call onRead(data, length, link) for each new packet. Link can be used * to reply to the sender through its UDPLink::reply() method. */ static Handle listenUDP(const std::string& host, const std::string& port, boost::function3<void, const void*, int, boost::shared_ptr<UDPLink> > onRead, boost::system::error_code& erc); /** Listen using TCP or UDP. * * \param f a socket factory. For each new connection the function will * be called and the resulting socket object bound to the new connection. */ boost::system::error_code listen(SocketFactory f, const std::string& host, const std::string& port, bool udp = false); boost::system::error_code listen(SocketFactory f, const std::string& host, unsigned port, bool udp = false); #if defined LIBPORT_ENABLE_SSL boost::system::error_code listenSSL(SocketFactory f, const std::string& host, const std::string& port, boost::asio::ssl::context_base::method ctx = boost::asio::ssl::context::sslv23_server, boost::asio::ssl::context::options options = boost::asio::ssl::context::verify_none, const std::string& privateKeyFile = "", const std::string& certChainFile = "", const std::string& tmpDHFile = "" , const std::string& cipherList = ""); #endif /// Steal file descriptor from Socket. Return the file descriptor. int stealFD(); /// Get file descriptor from Socket. int getFD(); /// Set file descriptor template<class Sock> void setFD(int fd, typename Sock::protocol_type proto); /** Sleep for specified amount of time, polling if current thread is * the asio worker thread */ static void sleep(utime_t duration); boost::asio::io_service& get_io_service(); protected: bool onRead_(boost::asio::streambuf&); std::string buffer; BaseSocket* base_; private: template<typename Proto, typename BaseFactory> boost::system::error_code listenProto(SocketFactory f, const std::string& host, const std::string&port, BaseFactory bf); template<typename Proto, typename BaseFactory> boost::system::error_code connectProto(const std::string& host, const std::string& port, utime_t timeout, bool async, BaseFactory bf); boost::asio::io_service& io_; }; /** Wrapper of libport::Socket to be able to use Socket without inherit from * it. */ class LIBPORT_API ConcreteSocket: public Socket { public: typedef boost::function2<int, const void*, size_t> onread_type; typedef boost::function1<void, boost::system::error_code> onerror_type; typedef boost::function0<void> onconnect_type; typedef Socket super_type; ConcreteSocket(boost::asio::io_service& io = libport::get_io_service()) : Socket(io) , onconnect_(boost::bind(&super_type::onConnect, this)) , onerror_(boost::bind(&super_type::onError, this, _1)) , onread_(boost::bind(&super_type::onRead, this, _1, _2)) {} ConcreteSocket& onConnect(onconnect_type cb) { onconnect_ = cb; return *this; } ConcreteSocket& onError(onerror_type cb) { onerror_ = cb; return *this; } ConcreteSocket& onRead(onread_type cb) { onread_ = cb; return *this; } virtual void onConnect() { onconnect_(); } virtual void onError(boost::system::error_code erc) { onerror_(erc); } virtual int onRead(const void* data, size_t length) { return onread_(data, length); } private: onconnect_type onconnect_; onerror_type onerror_; onread_type onread_; }; LIBPORT_API bool isPollThread(); /** Poll on an io_service for given duration in microseconds. * @param duration max duration for which to poll in microseconds * @param once process at most one handler before returning if true */ LIBPORT_API void pollFor(utime_t duration, bool once = false, boost::asio::io_service& io = get_io_service()); typedef boost::shared_ptr<boost::asio::deadline_timer> AsyncCallHandler; /** Call \b callback() in \b usDelay microseconds. * If the method cancel() of the returned timer object is invoked before * expiration of the delay, the call is aborted and callback() is not * called. */ AsyncCallHandler asyncCall(boost::function0<void> callback, utime_t usDelay, boost::asio::io_service& io = get_io_service()); } # include "libport/asio.hxx" #endif <|endoftext|>
<commit_before>/* This file is part of the yazpp toolkit. * Copyright (C) 1998-2013 Index Data and Mike Taylor * See the file LICENSE for details. */ #if HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <yazpp/z-query.h> using namespace yazpp_1; void tst1(const char *query_str_in, const char *query_expected) { Yaz_Z_Query q; q = query_str_in; Yaz_Z_Query q2; q2 = q; char query_str_out[100]; q2.print(query_str_out, sizeof(query_str_out)-1); if (strcmp(query_str_out, query_expected)) { fprintf(stderr, "tstquery: query mismatch out=%s expected=%s\n", query_str_out, query_expected); exit(1); } } int main(int argc, char **argv) { tst1("", ""); tst1("x", "RPN @attrset Bib-1 x"); tst1("@and a b", "RPN @attrset Bib-1 @and a b"); } /* * Local variables: * c-basic-offset: 4 * c-file-style: "Stroustrup" * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */ <commit_msg>tstquery using YAZ check<commit_after>/* This file is part of the yazpp toolkit. * Copyright (C) 1998-2013 Index Data and Mike Taylor * See the file LICENSE for details. */ #if HAVE_CONFIG_H #include <config.h> #endif #include <stdlib.h> #include <yazpp/z-query.h> #include <yaz/test.h> #include <yaz/log.h> using namespace yazpp_1; int tst1(const char *query_str_in, const char *query_expected) { Yaz_Z_Query q; q = query_str_in; Yaz_Z_Query q2; q2 = q; char query_str_out[100]; q2.print(query_str_out, sizeof(query_str_out)-1); if (strcmp(query_str_out, query_expected)) { yaz_log(YLOG_LOG, "query mismatch out=%s expected=%s", query_str_out, query_expected); return 0; } return 1; } int main(int argc, char **argv) { YAZ_CHECK_INIT(argc, argv); YAZ_CHECK(tst1("", "")); YAZ_CHECK(tst1("x", "RPN @attrset Bib-1 x")); YAZ_CHECK(tst1("@and a b", "RPN @attrset Bib-1 @and a b")); YAZ_CHECK_TERM; } /* * Local variables: * c-basic-offset: 4 * c-file-style: "Stroustrup" * indent-tabs-mode: nil * End: * vim: shiftwidth=4 tabstop=8 expandtab */ <|endoftext|>
<commit_before>#include "osl/state/numEffectState.h" #include "osl/effect_util/effectUtil.h" #include "osl/container/moveVector.h" #include "osl/record/csa.h" #include "osl/record/csaIOError.h" #include "osl/move_generator/legalMoves.h" #include <boost/random/mersenne_twister.hpp> #include <string> #include <sys/time.h> namespace osl { void showState(const NumEffectState& state) { std::cout << state << std::endl; } Move selectMove(const NumEffectState& state, const MoveVector& moves) { static boost::mt11213b generator(random()); return moves[generator() % moves.size()]; } bool isMated(const NumEffectState& state) { return state.inCheck(alt(state.turn())); } bool computerOperate(NumEffectState& state) { MoveVector moves; LegalMoves::generate(state, moves); if (moves.empty()) { std::cout << "You Win!" << std::endl; return true; } const Move my_move = selectMove(state, moves); assert(state.isValidMove(my_move)); state.makeMove(my_move); showState(state); csaShow(std::cout, my_move); std::cout << "\n"; if (isMated(state)) { std::cout << "You Lose..." << std::endl; return true; } return false; } bool playerOperate(NumEffectState& state, std::string line) { Move op_move; if (line.length() == 4) { MoveVector moves; LegalMoves::generate(state, moves); int i; for (i = 0; i < moves.size(); i++) { Move m = moves[i]; Square from = m.from(); Square to = m.to(); if (((int)line[0] - (int)'0') == from.x() && ((int)line[1] - (int)'0') == from.y() && ((int)line[2] - (int)'0') == to.x() && ((int)line[3] - (int)'0') == to.y()) { op_move = m; break; } } } else if (line.length() != 7) { std::cout << "error: invalid format." << std::endl; return true; } else { try { op_move = record::csa::strToMove(line, state); } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; return true; } } if (! state.isValidMove(op_move)) { return true; } state.makeMove(op_move); showState(state); csaShow(std::cout, op_move); std::cout << "\n"; return false; } std::string inputLine(void) { std::string line; if (! std::getline(std::cin, line)) { return NULL; } return line; } } int main() { using namespace osl; srandom(time(0)); NumEffectState state((SimpleState(HIRATE))); while (true) { bool ended = computerOperate(state); if (ended) { break; } std::string line = inputLine(); bool failed = playerOperate(state, line); if (failed) { break; } } } <commit_msg>Indent<commit_after>#include "osl/state/numEffectState.h" #include "osl/effect_util/effectUtil.h" #include "osl/container/moveVector.h" #include "osl/record/csa.h" #include "osl/record/csaIOError.h" #include "osl/move_generator/legalMoves.h" #include <boost/random/mersenne_twister.hpp> #include <string> #include <sys/time.h> namespace osl { void showState(const NumEffectState& state) { std::cout << state << std::endl; } Move selectMove(const NumEffectState& state, const MoveVector& moves) { static boost::mt11213b generator(random()); return moves[generator() % moves.size()]; } bool isMated(const NumEffectState& state) { return state.inCheck(alt(state.turn())); } bool computerOperate(NumEffectState& state) { MoveVector moves; LegalMoves::generate(state, moves); if (moves.empty()) { std::cout << "You Win!" << std::endl; return true; } const Move my_move = selectMove(state, moves); assert(state.isValidMove(my_move)); state.makeMove(my_move); showState(state); csaShow(std::cout, my_move); std::cout << "\n"; if (isMated(state)) { std::cout << "You Lose..." << std::endl; return true; } return false; } bool playerOperate(NumEffectState& state, std::string line) { Move op_move; if (line.length() == 4) { MoveVector moves; LegalMoves::generate(state, moves); int i; for (i = 0; i < moves.size(); i++) { Move m = moves[i]; Square from = m.from(); Square to = m.to(); if (((int)line[0] - (int)'0') == from.x() && ((int)line[1] - (int)'0') == from.y() && ((int)line[2] - (int)'0') == to.x() && ((int)line[3] - (int)'0') == to.y()) { op_move = m; break; } } } else if (line.length() != 7) { std::cout << "error: invalid format." << std::endl; return true; } else { try { op_move = record::csa::strToMove(line, state); } catch (const std::runtime_error& e) { std::cout << e.what() << std::endl; return true; } } if (! state.isValidMove(op_move)) { return true; } state.makeMove(op_move); showState(state); csaShow(std::cout, op_move); std::cout << "\n"; return false; } std::string inputLine(void) { std::string line; if (! std::getline(std::cin, line)) { return NULL; } return line; } } int main() { using namespace osl; srandom(time(0)); NumEffectState state((SimpleState(HIRATE))); while (true) { bool ended = computerOperate(state); if (ended) { break; } std::string line = inputLine(); bool failed = playerOperate(state, line); if (failed) { break; } } } <|endoftext|>
<commit_before>// // peglint.cc // // Copyright (c) 2015 Yuji Hirose. All rights reserved. // MIT License // #include <peglib.h> #include <fstream> using namespace std; bool read_file(const char* path, vector<char>& buff) { ifstream ifs(path, ios::in | ios::binary); if (ifs.fail()) { return false; } buff.resize(static_cast<unsigned int>(ifs.seekg(0, ios::end).tellg())); if (!buff.empty()) { ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size())); } return true; } int main(int argc, const char** argv) { auto opt_ast = false; auto opt_optimize_ast_nodes = false; auto opt_help = false; vector<const char*> path_list; auto argi = 1; while (argi < argc) { auto arg = argv[argi++]; if (string("--help") == arg) { opt_help = true; } else if (string("--ast") == arg) { opt_ast = true; } else if (string("--optimize_ast_nodes") == arg || string("--opt") == arg) { opt_optimize_ast_nodes = true; } else { path_list.push_back(arg); } } if (path_list.empty() || opt_help) { cerr << "usage: peglint [--ast] [--optimize_ast_nodes|--opt] [grammar file path] [source file path]" << endl; return 1; } // Check PEG grammar auto syntax_path = path_list[0]; vector<char> syntax; if (!read_file(syntax_path, syntax)) { cerr << "can't open the grammar file." << endl; return -1; } peglib::peg peg; peg.log = [&](auto ln, auto col, const auto& msg) { cerr << syntax_path << ":" << ln << ":" << col << ": " << msg << endl; }; if (!peg.load_grammar(syntax.data(), syntax.size())) { return -1; } if (path_list.size() < 2) { return 0; } // Check source auto source_path = path_list[1]; vector<char> source; if (!read_file(source_path, source)) { auto beg = source_path; auto end = source_path + strlen(source_path); source.assign(beg, end); source_path = "[commendline]"; } peg.log = [&](auto ln, auto col, const auto& msg) { cerr << source_path << ":" << ln << ":" << col << ": " << msg << endl; }; if (opt_ast) { peg.enable_ast(opt_optimize_ast_nodes); std::shared_ptr<peglib::Ast> ast; if (!peg.parse_n(source.data(), source.size(), ast)) { return -1; } peglib::AstPrint().print(*ast); } else { if (!peg.parse_n(source.data(), source.size())) { return -1; } } return 0; } // vim: et ts=4 sw=4 cin cino={1s ff=unix <commit_msg>Fixed source code format.<commit_after>// // peglint.cc // // Copyright (c) 2015 Yuji Hirose. All rights reserved. // MIT License // #include <peglib.h> #include <fstream> using namespace std; bool read_file(const char* path, vector<char>& buff) { ifstream ifs(path, ios::in | ios::binary); if (ifs.fail()) { return false; } buff.resize(static_cast<unsigned int>(ifs.seekg(0, ios::end).tellg())); if (!buff.empty()) { ifs.seekg(0, ios::beg).read(&buff[0], static_cast<streamsize>(buff.size())); } return true; } int main(int argc, const char** argv) { auto opt_ast = false; auto opt_optimize_ast_nodes = false; auto opt_help = false; vector<const char*> path_list; auto argi = 1; while (argi < argc) { auto arg = argv[argi++]; if (string("--help") == arg) { opt_help = true; } else if (string("--ast") == arg) { opt_ast = true; } else if (string("--optimize_ast_nodes") == arg || string("--opt") == arg) { opt_optimize_ast_nodes = true; } else { path_list.push_back(arg); } } if (path_list.empty() || opt_help) { cerr << "usage: peglint [--ast] [--optimize_ast_nodes|--opt] [grammar file path] [source file path]" << endl; return 1; } // Check PEG grammar auto syntax_path = path_list[0]; vector<char> syntax; if (!read_file(syntax_path, syntax)) { cerr << "can't open the grammar file." << endl; return -1; } peglib::peg peg; peg.log = [&](auto ln, auto col, const auto& msg) { cerr << syntax_path << ":" << ln << ":" << col << ": " << msg << endl; }; if (!peg.load_grammar(syntax.data(), syntax.size())) { return -1; } if (path_list.size() < 2) { return 0; } // Check source auto source_path = path_list[1]; vector<char> source; if (!read_file(source_path, source)) { auto beg = source_path; auto end = source_path + strlen(source_path); source.assign(beg, end); source_path = "[commendline]"; } peg.log = [&](auto ln, auto col, const auto& msg) { cerr << source_path << ":" << ln << ":" << col << ": " << msg << endl; }; if (opt_ast) { peg.enable_ast(opt_optimize_ast_nodes); std::shared_ptr<peglib::Ast> ast; if (!peg.parse_n(source.data(), source.size(), ast)) { return -1; } peglib::AstPrint().print(*ast); } else { if (!peg.parse_n(source.data(), source.size())) { return -1; } } return 0; } // vim: et ts=4 sw=4 cin cino={1s ff=unix <|endoftext|>
<commit_before>/*** tws_util.cpp -- common utils * * Copyright (C) 2010, 2011 Ruediger Meier * * Author: Ruediger Meier <sweet_f_a@gmx.de> * * This file is part of atem. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of any contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 REGENTS 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 "tws_util.h" #include "debug.h" // from global installed twsapi #include "twsapi/EWrapper.h" //IB::TickType #include "twsapi/Execution.h" #include "twsapi/Contract.h" #include <string.h> #include <sys/time.h> #include <time.h> int64_t nowInMsecs() { timeval tv; int err = gettimeofday( &tv, NULL ); assert( err == 0 ); const int64_t now_ms = (int64_t)(tv.tv_sec*1000ULL) + (int64_t)(tv.tv_usec/1000ULL); return now_ms; } std::string msecs_to_string( int64_t msecs ) { const time_t s = msecs / 1000; const uint ms = msecs % 1000; char buf[ 19 + 4 + 1 ]; // "yyyy-mm-dd hh:mm:ss.zzz" const struct tm *tmp_tm = localtime( &s ); size_t tmp_sz; tmp_sz = strftime(buf, 19+1 , "%F %T", tmp_tm); assert( tmp_sz == 19); tmp_sz = snprintf( buf+19, 4+1, ".%03u", ms ); assert( tmp_sz == 4); return std::string(buf); } /** * Convert IB style date or date time string to struct tm. * Return 0 on success or -1 on error; */ int ib_strptime( struct tm *tm, const std::string &ib_datetime ) { char *tmp; memset(tm, 0, sizeof(struct tm)); tmp = strptime( ib_datetime.c_str(), "%Y%m%d", tm); if( tmp != NULL && *tmp == '\0' ) { return 0; } memset(tm, 0, sizeof(struct tm)); tmp = strptime( ib_datetime.c_str(), "%Y%m%d%t%H:%M:%S", tm); if( tmp != NULL && *tmp == '\0' ) { return 0; } return -1; } std::string ib_date2iso( const std::string &ibDate ) { struct tm tm; char buf[255]; char *tmp; memset(&tm, 0, sizeof(struct tm)); tmp = strptime( ibDate.c_str(), "%Y%m%d", &tm); if( tmp != NULL && *tmp == '\0' ) { strftime(buf, sizeof(buf), "%F", &tm); return buf; } memset(&tm, 0, sizeof(struct tm)); tmp = strptime( ibDate.c_str(), "%Y%m%d%t%H:%M:%S", &tm); if( tmp != NULL && *tmp == '\0' ) { strftime(buf, sizeof(buf), "%F %T", &tm); return buf; } return ""; } std::string ibToString( int tickType) { switch ( tickType) { case IB::BID_SIZE: return "bidSize"; case IB::BID: return "bidPrice"; case IB::ASK: return "askPrice"; case IB::ASK_SIZE: return "askSize"; case IB::LAST: return "lastPrice"; case IB::LAST_SIZE: return "lastSize"; case IB::HIGH: return "high"; case IB::LOW: return "low"; case IB::VOLUME: return "volume"; case IB::CLOSE: return "close"; case IB::BID_OPTION_COMPUTATION: return "bidOptComp"; case IB::ASK_OPTION_COMPUTATION: return "askOptComp"; case IB::LAST_OPTION_COMPUTATION: return "lastOptComp"; case IB::MODEL_OPTION: return "modelOptComp"; case IB::OPEN: return "open"; case IB::LOW_13_WEEK: return "13WeekLow"; case IB::HIGH_13_WEEK: return "13WeekHigh"; case IB::LOW_26_WEEK: return "26WeekLow"; case IB::HIGH_26_WEEK: return "26WeekHigh"; case IB::LOW_52_WEEK: return "52WeekLow"; case IB::HIGH_52_WEEK: return "52WeekHigh"; case IB::AVG_VOLUME: return "AvgVolume"; case IB::OPEN_INTEREST: return "OpenInterest"; case IB::OPTION_HISTORICAL_VOL: return "OptionHistoricalVolatility"; case IB::OPTION_IMPLIED_VOL: return "OptionImpliedVolatility"; case IB::OPTION_BID_EXCH: return "OptionBidExchStr"; case IB::OPTION_ASK_EXCH: return "OptionAskExchStr"; case IB::OPTION_CALL_OPEN_INTEREST: return "OptionCallOpenInterest"; case IB::OPTION_PUT_OPEN_INTEREST: return "OptionPutOpenInterest"; case IB::OPTION_CALL_VOLUME: return "OptionCallVolume"; case IB::OPTION_PUT_VOLUME: return "OptionPutVolume"; case IB::INDEX_FUTURE_PREMIUM: return "IndexFuturePremium"; case IB::BID_EXCH: return "bidExch"; case IB::ASK_EXCH: return "askExch"; case IB::AUCTION_VOLUME: return "auctionVolume"; case IB::AUCTION_PRICE: return "auctionPrice"; case IB::AUCTION_IMBALANCE: return "auctionImbalance"; case IB::MARK_PRICE: return "markPrice"; case IB::BID_EFP_COMPUTATION: return "bidEFP"; case IB::ASK_EFP_COMPUTATION: return "askEFP"; case IB::LAST_EFP_COMPUTATION: return "lastEFP"; case IB::OPEN_EFP_COMPUTATION: return "openEFP"; case IB::HIGH_EFP_COMPUTATION: return "highEFP"; case IB::LOW_EFP_COMPUTATION: return "lowEFP"; case IB::CLOSE_EFP_COMPUTATION: return "closeEFP"; case IB::LAST_TIMESTAMP: return "lastTimestamp"; case IB::SHORTABLE: return "shortable"; case IB::FUNDAMENTAL_RATIOS: return "fundamentals"; case IB::RT_VOLUME: return "rtVolume"; case IB::HALTED: return "halted"; default: return "unknown"; } } std::string ibToString( const IB::Execution& ex ) { char buf[1024]; snprintf( buf, sizeof(buf), "orderId:%ld: clientId:%ld, execId:%s, " "time:%s, acctNumber:%s, exchange:%s, side:%s, shares:%d, price:%g, " "permId:%d, liquidation:%d, cumQty:%d, avgPrice:%g", ex.orderId, ex.clientId, ex.execId.c_str(), ex.time.c_str(), ex.acctNumber.c_str(), ex.exchange.c_str(), ex.side.c_str(), ex.shares, ex.price, ex.permId, ex.liquidation, ex.cumQty, ex.avgPrice); return std::string(buf); } std::string ibToString( const IB::Contract &c, bool showFields ) { char buf[1024]; const char *fmt; if( showFields ) { fmt = "conId:%ld, symbol:%s, secType:%s, expiry:%s, strike:%g, " "right:%s, multiplier:%s, exchange:%s, currency:%s, localSymbol:%s"; } else { fmt = "%ld,%s,%s,%s,%g,%s,%s,%s,%s,%s"; } snprintf( buf, sizeof(buf), fmt, c.conId, c.symbol.c_str(), c.secType.c_str(), c.expiry.c_str(), c.strike, c.right.c_str(), c.multiplier.c_str(), c.exchange.c_str(), c.currency.c_str(), c.localSymbol.c_str() ); return std::string(buf); } <commit_msg>ib_date2iso(), add comment and avoid magic buf length<commit_after>/*** tws_util.cpp -- common utils * * Copyright (C) 2010, 2011 Ruediger Meier * * Author: Ruediger Meier <sweet_f_a@gmx.de> * * This file is part of atem. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the author nor the names of any contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 REGENTS 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 "tws_util.h" #include "debug.h" // from global installed twsapi #include "twsapi/EWrapper.h" //IB::TickType #include "twsapi/Execution.h" #include "twsapi/Contract.h" #include <string.h> #include <sys/time.h> #include <time.h> int64_t nowInMsecs() { timeval tv; int err = gettimeofday( &tv, NULL ); assert( err == 0 ); const int64_t now_ms = (int64_t)(tv.tv_sec*1000ULL) + (int64_t)(tv.tv_usec/1000ULL); return now_ms; } std::string msecs_to_string( int64_t msecs ) { const time_t s = msecs / 1000; const uint ms = msecs % 1000; char buf[ 19 + 4 + 1 ]; // "yyyy-mm-dd hh:mm:ss.zzz" const struct tm *tmp_tm = localtime( &s ); size_t tmp_sz; tmp_sz = strftime(buf, 19+1 , "%F %T", tmp_tm); assert( tmp_sz == 19); tmp_sz = snprintf( buf+19, 4+1, ".%03u", ms ); assert( tmp_sz == 4); return std::string(buf); } /** * Convert IB style date or date time string to struct tm. * Return 0 on success or -1 on error; */ int ib_strptime( struct tm *tm, const std::string &ib_datetime ) { char *tmp; memset(tm, 0, sizeof(struct tm)); tmp = strptime( ib_datetime.c_str(), "%Y%m%d", tm); if( tmp != NULL && *tmp == '\0' ) { return 0; } memset(tm, 0, sizeof(struct tm)); tmp = strptime( ib_datetime.c_str(), "%Y%m%d%t%H:%M:%S", tm); if( tmp != NULL && *tmp == '\0' ) { return 0; } return -1; } /** * Convert IB style date or date time string to standard format "%F" or "%F %T". * The converted string is always a valid date. * Return empty string on parse errors or invalid dates. */ std::string ib_date2iso( const std::string &ibDate ) { struct tm tm; char buf[sizeof("yyyy-mm-dd HH:MM:SS")]; char *tmp; memset(&tm, 0, sizeof(struct tm)); tmp = strptime( ibDate.c_str(), "%Y%m%d", &tm); if( tmp != NULL && *tmp == '\0' ) { strftime(buf, sizeof(buf), "%F", &tm); return buf; } memset(&tm, 0, sizeof(struct tm)); tmp = strptime( ibDate.c_str(), "%Y%m%d%t%H:%M:%S", &tm); if( tmp != NULL && *tmp == '\0' ) { strftime(buf, sizeof(buf), "%F %T", &tm); return buf; } return ""; } std::string ibToString( int tickType) { switch ( tickType) { case IB::BID_SIZE: return "bidSize"; case IB::BID: return "bidPrice"; case IB::ASK: return "askPrice"; case IB::ASK_SIZE: return "askSize"; case IB::LAST: return "lastPrice"; case IB::LAST_SIZE: return "lastSize"; case IB::HIGH: return "high"; case IB::LOW: return "low"; case IB::VOLUME: return "volume"; case IB::CLOSE: return "close"; case IB::BID_OPTION_COMPUTATION: return "bidOptComp"; case IB::ASK_OPTION_COMPUTATION: return "askOptComp"; case IB::LAST_OPTION_COMPUTATION: return "lastOptComp"; case IB::MODEL_OPTION: return "modelOptComp"; case IB::OPEN: return "open"; case IB::LOW_13_WEEK: return "13WeekLow"; case IB::HIGH_13_WEEK: return "13WeekHigh"; case IB::LOW_26_WEEK: return "26WeekLow"; case IB::HIGH_26_WEEK: return "26WeekHigh"; case IB::LOW_52_WEEK: return "52WeekLow"; case IB::HIGH_52_WEEK: return "52WeekHigh"; case IB::AVG_VOLUME: return "AvgVolume"; case IB::OPEN_INTEREST: return "OpenInterest"; case IB::OPTION_HISTORICAL_VOL: return "OptionHistoricalVolatility"; case IB::OPTION_IMPLIED_VOL: return "OptionImpliedVolatility"; case IB::OPTION_BID_EXCH: return "OptionBidExchStr"; case IB::OPTION_ASK_EXCH: return "OptionAskExchStr"; case IB::OPTION_CALL_OPEN_INTEREST: return "OptionCallOpenInterest"; case IB::OPTION_PUT_OPEN_INTEREST: return "OptionPutOpenInterest"; case IB::OPTION_CALL_VOLUME: return "OptionCallVolume"; case IB::OPTION_PUT_VOLUME: return "OptionPutVolume"; case IB::INDEX_FUTURE_PREMIUM: return "IndexFuturePremium"; case IB::BID_EXCH: return "bidExch"; case IB::ASK_EXCH: return "askExch"; case IB::AUCTION_VOLUME: return "auctionVolume"; case IB::AUCTION_PRICE: return "auctionPrice"; case IB::AUCTION_IMBALANCE: return "auctionImbalance"; case IB::MARK_PRICE: return "markPrice"; case IB::BID_EFP_COMPUTATION: return "bidEFP"; case IB::ASK_EFP_COMPUTATION: return "askEFP"; case IB::LAST_EFP_COMPUTATION: return "lastEFP"; case IB::OPEN_EFP_COMPUTATION: return "openEFP"; case IB::HIGH_EFP_COMPUTATION: return "highEFP"; case IB::LOW_EFP_COMPUTATION: return "lowEFP"; case IB::CLOSE_EFP_COMPUTATION: return "closeEFP"; case IB::LAST_TIMESTAMP: return "lastTimestamp"; case IB::SHORTABLE: return "shortable"; case IB::FUNDAMENTAL_RATIOS: return "fundamentals"; case IB::RT_VOLUME: return "rtVolume"; case IB::HALTED: return "halted"; default: return "unknown"; } } std::string ibToString( const IB::Execution& ex ) { char buf[1024]; snprintf( buf, sizeof(buf), "orderId:%ld: clientId:%ld, execId:%s, " "time:%s, acctNumber:%s, exchange:%s, side:%s, shares:%d, price:%g, " "permId:%d, liquidation:%d, cumQty:%d, avgPrice:%g", ex.orderId, ex.clientId, ex.execId.c_str(), ex.time.c_str(), ex.acctNumber.c_str(), ex.exchange.c_str(), ex.side.c_str(), ex.shares, ex.price, ex.permId, ex.liquidation, ex.cumQty, ex.avgPrice); return std::string(buf); } std::string ibToString( const IB::Contract &c, bool showFields ) { char buf[1024]; const char *fmt; if( showFields ) { fmt = "conId:%ld, symbol:%s, secType:%s, expiry:%s, strike:%g, " "right:%s, multiplier:%s, exchange:%s, currency:%s, localSymbol:%s"; } else { fmt = "%ld,%s,%s,%s,%g,%s,%s,%s,%s,%s"; } snprintf( buf, sizeof(buf), fmt, c.conId, c.symbol.c_str(), c.secType.c_str(), c.expiry.c_str(), c.strike, c.right.c_str(), c.multiplier.c_str(), c.exchange.c_str(), c.currency.c_str(), c.localSymbol.c_str() ); return std::string(buf); } <|endoftext|>
<commit_before>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Ensure the result will fit. assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end)); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= std::distance(src_begin, src_end)); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(2 * half_length + 1); // Iterators in source and destination I1 src_pos = src_begin; I1 dest_pos = dest_begin; // Get the initial window in sequential order with reflection // Insert elements in order to the multiset for sorting. // Store all multiset iterators into the deque in sequential order. std::deque<T> window_init(2 * half_length + 1); window_init[half_length] = *(src_pos++); for (I_diff_t j = 1; j < half_length + 1; j++) { window_init[half_length - j] = *src_pos; window_init[half_length + j] = *src_pos; src_pos++; } for (I_diff_t j = 0; j < 2 * half_length + 1; j++) { window_iters[j] = sorted_window.insert(window_init.front()); window_init.pop_front(); } // Window position corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); typename multiset::iterator rank_point = sorted_window.begin(); // Move our selection point to the corresponding rank. for (I_diff_t i = 0; i < rank_pos; i++) { rank_point++; } // Roll window forward one value at a time. typename multiset::iterator prev_iter; T prev_value; T next_value; I_diff_t window_reflect_pos = 2 * half_length; while ( window_reflect_pos >= 0 ) { *(dest_pos++) = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); // Determine next value to add to window. // Handle special cases like reflection at the end. if ( src_pos == src_end ) { if ( window_reflect_pos == 0 ) { window_reflect_pos -= 2; next_value = prev_value; } else { window_reflect_pos -= 2; next_value = *(window_iters[window_reflect_pos]); } } else { next_value = *(src_pos++); } // Remove old value and add new value to the window. // Handle special cases where `rank_pos` may have an adjusted position // due to where the old and new values are inserted. if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <commit_msg>Use `std::advance` to get `rank_point`<commit_after>#ifndef __RANK_FILTER__ #define __RANK_FILTER__ #include <deque> #include <cassert> #include <functional> #include <iostream> #include <iterator> #include <boost/array.hpp> #include <boost/container/set.hpp> #include <boost/container/node_allocator.hpp> #include <boost/math/special_functions/round.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits.hpp> namespace rank_filter { template<class I1, class I2> inline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end, I2& dest_begin, I2& dest_end, size_t half_length, double rank) { // Types in use. typedef typename std::iterator_traits<I1>::value_type T1; typedef typename std::iterator_traits<I2>::value_type T2; typedef typename std::iterator_traits<I1>::difference_type I1_diff_t; typedef typename std::iterator_traits<I2>::difference_type I2_diff_t; // Establish common types to work with source and destination values. BOOST_STATIC_ASSERT((boost::is_same<T1, T2>::value)); typedef T1 T; typedef typename boost::common_type<I1_diff_t, I2_diff_t>::type I_diff_t; // Define container types that will be used. typedef boost::container::multiset< T, std::less<T>, boost::container::node_allocator<T>, boost::container::tree_assoc_options< boost::container::tree_type<boost::container::scapegoat_tree> >::type> multiset; typedef std::deque< typename multiset::iterator > deque; // Ensure the result will fit. assert(std::distance(src_begin, src_end) <= std::distance(dest_begin, dest_end)); // Window length cannot exceed input data with reflection. assert((half_length + 1) <= std::distance(src_begin, src_end)); // Rank must be in the range 0 to 1. assert((0 <= rank) && (rank <= 1)); // Track values in window both in sorted and sequential order. multiset sorted_window; deque window_iters(2 * half_length + 1); // Iterators in source and destination I1 src_pos = src_begin; I1 dest_pos = dest_begin; // Get the initial window in sequential order with reflection // Insert elements in order to the multiset for sorting. // Store all multiset iterators into the deque in sequential order. std::deque<T> window_init(2 * half_length + 1); window_init[half_length] = *(src_pos++); for (I_diff_t j = 1; j < half_length + 1; j++) { window_init[half_length - j] = *src_pos; window_init[half_length + j] = *src_pos; src_pos++; } for (I_diff_t j = 0; j < 2 * half_length + 1; j++) { window_iters[j] = sorted_window.insert(window_init.front()); window_init.pop_front(); } // Window position corresponding to this rank. const I_diff_t rank_pos = static_cast<I_diff_t>(boost::math::round(rank * (2 * half_length))); typename multiset::iterator rank_point = sorted_window.begin(); std::advance(rank_point, rank_pos); // Roll window forward one value at a time. typename multiset::iterator prev_iter; T prev_value; T next_value; I_diff_t window_reflect_pos = 2 * half_length; while ( window_reflect_pos >= 0 ) { *(dest_pos++) = *rank_point; prev_iter = window_iters.front(); prev_value = *prev_iter; window_iters.pop_front(); // Determine next value to add to window. // Handle special cases like reflection at the end. if ( src_pos == src_end ) { if ( window_reflect_pos == 0 ) { window_reflect_pos -= 2; next_value = prev_value; } else { window_reflect_pos -= 2; next_value = *(window_iters[window_reflect_pos]); } } else { next_value = *(src_pos++); } // Remove old value and add new value to the window. // Handle special cases where `rank_pos` may have an adjusted position // due to where the old and new values are inserted. if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) ) { if ( rank_point == prev_iter ) { window_iters.push_back(sorted_window.insert(next_value)); rank_point--; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); } } else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) ) { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point--; } else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) ) { if (rank_point == prev_iter) { window_iters.push_back(sorted_window.insert(next_value)); rank_point++; sorted_window.erase(prev_iter); } else { sorted_window.erase(prev_iter); window_iters.push_back(sorted_window.insert(next_value)); rank_point++; } } } } } namespace std { template <class T, size_t N> ostream& operator<<(ostream& out, const boost::array<T, N>& that) { out << "{ "; for (unsigned int i = 0; i < (N - 1); i++) { out << that[i] << ", "; } out << that[N - 1] << " }"; return(out); } } #endif //__RANK_FILTER__ <|endoftext|>
<commit_before>#pragma once #include "simlib/concat.hh" #include "simlib/concat_tostr.hh" #include "simlib/inplace_array.hh" #include "simlib/logger.hh" #include <cstdlib> #include <exception> #define eprintf(...) fprintf(stderr, __VA_ARGS__) #ifdef DEBUG #define D(...) __VA_ARGS__ #define ND(...) #else #define D(...) #define ND(...) __VA_ARGS__ #endif #define STRINGIZE2(x) #x #define STRINGIZE(x) STRINGIZE2(x) #define LOG_LINE stdlog(__FILE__ ":" STRINGIZE(__LINE__)) #define E(...) eprintf(__VA_ARGS__) #define throw_assert(expr) \ ((expr) ? (void)0 \ : throw std::runtime_error(concat_tostr( \ __FILE__ ":" STRINGIZE(__LINE__) ": ", __PRETTY_FUNCTION__, \ ": Assertion `" #expr "` failed."))) // Very useful - includes exception origin #define THROW(...) \ throw std::runtime_error(concat_tostr( \ __VA_ARGS__, " (thrown at " __FILE__ ":" STRINGIZE(__LINE__) ")")) namespace simlib_debug { constexpr bool is_va_empty() { return true; } template <class T1, class... T> constexpr bool is_va_empty(T1&& /*unused*/, T&&... /*unused*/) { return false; } constexpr const char* what_of() { return ""; } inline const char* what_of(const std::exception& e) { return e.what(); } } // namespace simlib_debug inline InplaceBuff<4096> errmsg(int errnum) noexcept { static_assert( to_string(std::numeric_limits<decltype(errnum)>::max()).size() + 1 < 90, // +1 for minus a sign "Needed to fit error message in the returned buffer"); std::array<char, 4000> buff{}; return concat<4096>(" - ", errnum, ": ", strerror_r(errnum, buff.data(), buff.size())); } inline auto errmsg() noexcept { return errmsg(errno); } namespace stack_unwinding { class StackGuard { static inline thread_local uintmax_t event_stamp; bool inside_catch_ = static_cast<bool>(std::current_exception()); int uncaught_counter_ = std::uncaught_exceptions(); uintmax_t creation_stamp_ = event_stamp++; const char* file_; size_t line_; const char* pretty_func_; public: struct StackMark { InplaceBuff<512> description; uintmax_t stamp = event_stamp++; template <class... Args, std::enable_if_t<(is_string_argument<Args> and ...), int> = 0> explicit StackMark(Args&&... args) : description(std::in_place, std::forward<Args>(args)...) {} }; static inline thread_local InplaceArray<StackMark, 128> marks_collected; StackGuard(const char* file, size_t line, const char* pretty_function) noexcept : file_(file) , line_(line) , pretty_func_(pretty_function) {} StackGuard(const StackGuard&) = delete; StackGuard(StackGuard&&) = delete; StackGuard& operator=(const StackGuard&) = delete; StackGuard& operator=(StackGuard&&) = delete; ~StackGuard() { if (std::uncaught_exceptions() == 1 and uncaught_counter_ == 0 and not inside_catch_) { // Remove stack marks that are from earlier exceptions if (marks_collected.size() > 0 and marks_collected.back().stamp < creation_stamp_) { marks_collected.clear(); } try { StackMark a; StackMark b; assert(a.stamp + 1 == b.stamp); marks_collected.emplace_back(pretty_func_, " at ", file_, ':', line_); } catch (...) { // Nothing we can do here } } } }; } // namespace stack_unwinding #define STACK_UNWINDING_MARK_CONCATENATE_DETAIL(x, y) x##y #define STACK_UNWINDING_MARK_CONCAT(x, y) \ STACK_UNWINDING_MARK_CONCATENATE_DETAIL(x, y) #define STACK_UNWINDING_MARK \ ::stack_unwinding::StackGuard STACK_UNWINDING_MARK_CONCAT( \ stack_unwind_mark_no_, __COUNTER__)(__FILE__, __LINE__, \ __PRETTY_FUNCTION__) #define ERRLOG_CATCH(...) \ do { \ auto tmplog = \ errlog(__FILE__ ":" STRINGIZE(__LINE__) ": Caught exception", \ ::simlib_debug::is_va_empty(__VA_ARGS__) ? "" : " -> ", \ ::simlib_debug::what_of(__VA_ARGS__), \ "\nStack unwinding marks:\n"); \ \ size_t i = 0; \ for (auto const& mark : \ ::stack_unwinding::StackGuard::marks_collected) \ tmplog('[', i++, "] ", mark.description, "\n"); \ \ tmplog.flush_no_nl(); \ ::stack_unwinding::StackGuard::marks_collected.clear(); \ } while (false) class ThrowingIsBug { bool thrown = true; public: template <class T> decltype(auto) evaluate(T&& expr) noexcept { thrown = false; return std::forward<T>(expr); } ThrowingIsBug() = default; ThrowingIsBug(const ThrowingIsBug&) = delete; ThrowingIsBug(ThrowingIsBug&&) = delete; ThrowingIsBug& operator=(const ThrowingIsBug&) = delete; ThrowingIsBug& operator=(ThrowingIsBug&&) = delete; ~ThrowingIsBug() { if (thrown) { errlog("BUG: this was expected to not throw"); std::abort(); } } }; // Sadly it won't preserve prvalue-ness, a prvalue will become an xvalue #define WONT_THROW(...) (ThrowingIsBug().evaluate(__VA_ARGS__)) <commit_msg>debug.hh: added DebugLogger<commit_after>#pragma once #include "simlib/concat.hh" #include "simlib/concat_tostr.hh" #include "simlib/inplace_array.hh" #include "simlib/logger.hh" #include <cstdlib> #include <exception> #define eprintf(...) fprintf(stderr, __VA_ARGS__) #ifdef DEBUG #define D(...) __VA_ARGS__ #define ND(...) #else #define D(...) #define ND(...) __VA_ARGS__ #endif #define STRINGIZE2(x) #x #define STRINGIZE(x) STRINGIZE2(x) #define LOG_LINE stdlog(__FILE__ ":" STRINGIZE(__LINE__)) #define E(...) eprintf(__VA_ARGS__) #define throw_assert(expr) \ ((expr) ? (void)0 \ : throw std::runtime_error(concat_tostr( \ __FILE__ ":" STRINGIZE(__LINE__) ": ", __PRETTY_FUNCTION__, \ ": Assertion `" #expr "` failed."))) // Very useful - includes exception origin #define THROW(...) \ throw std::runtime_error(concat_tostr( \ __VA_ARGS__, " (thrown at " __FILE__ ":" STRINGIZE(__LINE__) ")")) namespace simlib_debug { constexpr bool is_va_empty() { return true; } template <class T1, class... T> constexpr bool is_va_empty(T1&& /*unused*/, T&&... /*unused*/) { return false; } constexpr const char* what_of() { return ""; } inline const char* what_of(const std::exception& e) { return e.what(); } } // namespace simlib_debug inline InplaceBuff<4096> errmsg(int errnum) noexcept { static_assert( to_string(std::numeric_limits<decltype(errnum)>::max()).size() + 1 < 90, // +1 for minus a sign "Needed to fit error message in the returned buffer"); std::array<char, 4000> buff{}; return concat<4096>(" - ", errnum, ": ", strerror_r(errnum, buff.data(), buff.size())); } inline auto errmsg() noexcept { return errmsg(errno); } namespace stack_unwinding { class StackGuard { static inline thread_local uintmax_t event_stamp; bool inside_catch_ = static_cast<bool>(std::current_exception()); int uncaught_counter_ = std::uncaught_exceptions(); uintmax_t creation_stamp_ = event_stamp++; const char* file_; size_t line_; const char* pretty_func_; public: struct StackMark { InplaceBuff<512> description; uintmax_t stamp = event_stamp++; template <class... Args, std::enable_if_t<(is_string_argument<Args> and ...), int> = 0> explicit StackMark(Args&&... args) : description(std::in_place, std::forward<Args>(args)...) {} }; static inline thread_local InplaceArray<StackMark, 128> marks_collected; StackGuard(const char* file, size_t line, const char* pretty_function) noexcept : file_(file) , line_(line) , pretty_func_(pretty_function) {} StackGuard(const StackGuard&) = delete; StackGuard(StackGuard&&) = delete; StackGuard& operator=(const StackGuard&) = delete; StackGuard& operator=(StackGuard&&) = delete; ~StackGuard() { if (std::uncaught_exceptions() == 1 and uncaught_counter_ == 0 and not inside_catch_) { // Remove stack marks that are from earlier exceptions if (marks_collected.size() > 0 and marks_collected.back().stamp < creation_stamp_) { marks_collected.clear(); } try { StackMark a; StackMark b; assert(a.stamp + 1 == b.stamp); marks_collected.emplace_back(pretty_func_, " at ", file_, ':', line_); } catch (...) { // Nothing we can do here } } } }; } // namespace stack_unwinding #define STACK_UNWINDING_MARK_CONCATENATE_DETAIL(x, y) x##y #define STACK_UNWINDING_MARK_CONCAT(x, y) \ STACK_UNWINDING_MARK_CONCATENATE_DETAIL(x, y) #define STACK_UNWINDING_MARK \ ::stack_unwinding::StackGuard STACK_UNWINDING_MARK_CONCAT( \ stack_unwind_mark_no_, __COUNTER__)(__FILE__, __LINE__, \ __PRETTY_FUNCTION__) #define ERRLOG_CATCH(...) \ do { \ auto tmplog = \ errlog(__FILE__ ":" STRINGIZE(__LINE__) ": Caught exception", \ ::simlib_debug::is_va_empty(__VA_ARGS__) ? "" : " -> ", \ ::simlib_debug::what_of(__VA_ARGS__), \ "\nStack unwinding marks:\n"); \ \ size_t i = 0; \ for (auto const& mark : \ ::stack_unwinding::StackGuard::marks_collected) \ tmplog('[', i++, "] ", mark.description, "\n"); \ \ tmplog.flush_no_nl(); \ ::stack_unwinding::StackGuard::marks_collected.clear(); \ } while (false) class ThrowingIsBug { bool thrown = true; public: template <class T> decltype(auto) evaluate(T&& expr) noexcept { thrown = false; return std::forward<T>(expr); } ThrowingIsBug() = default; ThrowingIsBug(const ThrowingIsBug&) = delete; ThrowingIsBug(ThrowingIsBug&&) = delete; ThrowingIsBug& operator=(const ThrowingIsBug&) = delete; ThrowingIsBug& operator=(ThrowingIsBug&&) = delete; ~ThrowingIsBug() { if (thrown) { errlog("BUG: this was expected to not throw"); std::abort(); } } }; // Sadly it won't preserve prvalue-ness, a prvalue will become an xvalue #define WONT_THROW(...) (ThrowingIsBug().evaluate(__VA_ARGS__)) // E.g. use: // static DebugLogger<true> debuglog; // debuglog("sth: ", sth); template <bool enable> struct DebugLogger { static constexpr bool enabled = enable; template <class... Args> void operator()(Args&&... args) const { if constexpr (enabled) { stdlog(args...); } } }; <|endoftext|>
<commit_before>#pragma once #ifndef _SDL_UTILS_H #define _SDL_UTILS_H #include <iostream> #include <string> #include <SDL.h> namespace Snake { class Utils { public: static void logSDLError(std::ostream &os, const std::string &msg) { os << msg << " Error: " << SDL_GetError() << std::endl; } static void debug(const std::string &msg) { std::cout << "Debug: " << msg << std::endl; } }; } #endif <commit_msg>Print debugging output only when DEBUG=1 is passed<commit_after>#pragma once #include <iostream> #include <string> #include <SDL.h> namespace Snake { class Utils { public: static void logSDLError(std::ostream &os, const std::string &msg) { os << msg << " Error: " << SDL_GetError() << std::endl; } static void debug(const std::string &msg) { bool shouldDebug = false; char* debugEnv = std::getenv("DEBUG"); if (debugEnv != NULL && strcmp(debugEnv, "1") == 0) { shouldDebug = true; } if (shouldDebug) { std::cout << "Debug: " << msg << std::endl; } } }; } <|endoftext|>
<commit_before>/** * Zillians MMO * Copyright (C) 2007-2011 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "language/stage/parser/ThorScriptParserStage.h" #include "language/context/ParserContext.h" #include "language/grammar/ThorScript.h" #include "language/action/SemanticActions.h" #include "language/tree/visitor/general/PrettyPrintVisitor.h" #include "language/ThorScriptCompiler.h" #include "utility/Foreach.h" #include "utility/UnicodeUtil.h" namespace classic = boost::spirit::classic; namespace qi = boost::spirit::qi; namespace zillians { namespace language { namespace stage { namespace { // since '\t' may be printed in spaces and I don't know a way to change std::wcout, we simply replace the tab with desired number of spaces // so that we can have correct error pointing cursor // (note that because '\t' equals to 4 spaces reported by spirit, we have to make sure it's printed in the exact same way) static void expand_tabs(const std::wstring& input, std::wstring& output, int number_of_space_for_tab = 4) { for(std::wstring::const_iterator it = input.begin(); it != input.end(); ++it) { if(*it == '\t') for(int i=0;i<number_of_space_for_tab;++i) output.push_back(L' '); else output.push_back(*it); } } } ThorScriptParserStage::ThorScriptParserStage() : skip_parse(false), dump_parse(false) { } ThorScriptParserStage::~ThorScriptParserStage() { } const char* ThorScriptParserStage::name() { return "thorscript_parser_stage"; } void ThorScriptParserStage::initializeOptions(po::options_description& option_desc, po::positional_options_description& positional_desc) { option_desc.add_options() ("skip-parse", "skip parsing stage and use provided parser context") ("dump-parse", "dump parse tree for debugging purpose") ("input,i", po::value<std::vector<std::string>>(), "thorscript files"); positional_desc.add("input", -1); } bool ThorScriptParserStage::parseOptions(po::variables_map& vm) { skip_parse = (vm.count("skip-parse") > 0); dump_parse = (vm.count("dump-parse") > 0); if(vm.count("input") > 0) { inputs = vm["input"].as<std::vector<std::string>>(); return true; } else { return false; } } bool ThorScriptParserStage::execute(bool& continue_execution) { if(skip_parse) return true; setParserContext(new ParserContext()); if(inputs.size() > 0) { foreach(i, inputs) { if(!parse(*i)) return false; } return true; } else { return true; } } bool ThorScriptParserStage::parse(std::string filename) { std::ifstream in(filename, std::ios_base::in); if(!in.good()) { LOG4CXX_ERROR(Logger::ParserStage, "failed to open file: " << filename); return false; } // ignore the BOM marking the beginning of a UTF-8 file in Windows if(in.peek() == '\xef') { char s[3]; in >> s[0] >> s[1] >> s[2]; s[3] = '\0'; if (s != std::string("\xef\xbb\xbf")) { std::cerr << "parser error: unexpected characters from input file: " << filename << std::endl; return false; } } std::string source_code_raw; in.unsetf(std::ios::skipws); // disable white space skipping std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(source_code_raw)); // convert it from UTF8 into UCS4 as a string by using u8_to_u32_iterator std::wstring source_code; utf8_to_ucs4(source_code_raw, source_code); // enable correct locale so that we can print UCS4 characters enable_default_locale(std::wcout); getParserContext().enable_debug_parser = dump_parse; getParserContext().enable_semantic_action = !dump_parse; getParserContext().debug.current_source_index = ModuleSourceInfoContext::get(getParserContext().program)->addSource(filename); // try to parse typedef classic::position_iterator2<std::wstring::iterator> pos_iterator_type; try { pos_iterator_type begin(source_code.begin(), source_code.end(), s_to_ws(filename)); pos_iterator_type end; grammar::ThorScript<pos_iterator_type, action::ThorScriptTreeAction> parser; grammar::detail::WhiteSpace<pos_iterator_type> skipper; if(!qi::phrase_parse( begin, end, parser, skipper)) { return false; } } catch (const qi::expectation_failure<pos_iterator_type>& e) { const classic::file_position_base<std::wstring>& pos = e.first.get_position(); // TODO output error using Logger std::wstring current_line; expand_tabs(e.first.get_currentline(), current_line); std::wcerr << L"parse error at file " << pos.file << L" line " << pos.line << L" column " << pos.column << std::endl << L"'" << current_line << L"'" << std::endl << std::setw(pos.column) << L" " << L"^- here" << std::endl; return false; } return true; } } } } <commit_msg>fix uninitialized ModuleSourceInfoContext<commit_after>/** * Zillians MMO * Copyright (C) 2007-2011 Zillians.com, Inc. * For more information see http://www.zillians.com * * Zillians MMO is the library and runtime for massive multiplayer online game * development in utility computing model, which runs as a service for every * developer to build their virtual world running on our GPU-assisted machines. * * This is a close source library intended to be used solely within Zillians.com * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * COPYRIGHT HOLDER(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "language/stage/parser/ThorScriptParserStage.h" #include "language/context/ParserContext.h" #include "language/grammar/ThorScript.h" #include "language/action/SemanticActions.h" #include "language/tree/visitor/general/PrettyPrintVisitor.h" #include "language/ThorScriptCompiler.h" #include "utility/Foreach.h" #include "utility/UnicodeUtil.h" namespace classic = boost::spirit::classic; namespace qi = boost::spirit::qi; namespace zillians { namespace language { namespace stage { namespace { // since '\t' may be printed in spaces and I don't know a way to change std::wcout, we simply replace the tab with desired number of spaces // so that we can have correct error pointing cursor // (note that because '\t' equals to 4 spaces reported by spirit, we have to make sure it's printed in the exact same way) static void expand_tabs(const std::wstring& input, std::wstring& output, int number_of_space_for_tab = 4) { for(std::wstring::const_iterator it = input.begin(); it != input.end(); ++it) { if(*it == '\t') for(int i=0;i<number_of_space_for_tab;++i) output.push_back(L' '); else output.push_back(*it); } } } ThorScriptParserStage::ThorScriptParserStage() : skip_parse(false), dump_parse(false) { } ThorScriptParserStage::~ThorScriptParserStage() { } const char* ThorScriptParserStage::name() { return "thorscript_parser_stage"; } void ThorScriptParserStage::initializeOptions(po::options_description& option_desc, po::positional_options_description& positional_desc) { option_desc.add_options() ("skip-parse", "skip parsing stage and use provided parser context") ("dump-parse", "dump parse tree for debugging purpose") ("input,i", po::value<std::vector<std::string>>(), "thorscript files"); positional_desc.add("input", -1); } bool ThorScriptParserStage::parseOptions(po::variables_map& vm) { skip_parse = (vm.count("skip-parse") > 0); dump_parse = (vm.count("dump-parse") > 0); if(vm.count("input") > 0) { inputs = vm["input"].as<std::vector<std::string>>(); return true; } else { return false; } } bool ThorScriptParserStage::execute(bool& continue_execution) { if(skip_parse) return true; // prepare the global parser context setParserContext(new ParserContext()); // prepare the module source info context for the root program node ModuleSourceInfoContext::set(getParserContext().program, new ModuleSourceInfoContext()); if(inputs.size() > 0) { foreach(i, inputs) { if(!parse(*i)) return false; } return true; } else { return true; } } bool ThorScriptParserStage::parse(std::string filename) { std::ifstream in(filename, std::ios_base::in); if(!in.good()) { LOG4CXX_ERROR(Logger::ParserStage, "failed to open file: " << filename); return false; } // ignore the BOM marking the beginning of a UTF-8 file in Windows if(in.peek() == '\xef') { char s[3]; in >> s[0] >> s[1] >> s[2]; s[3] = '\0'; if (s != std::string("\xef\xbb\xbf")) { std::cerr << "parser error: unexpected characters from input file: " << filename << std::endl; return false; } } std::string source_code_raw; in.unsetf(std::ios::skipws); // disable white space skipping std::copy(std::istream_iterator<char>(in), std::istream_iterator<char>(), std::back_inserter(source_code_raw)); // convert it from UTF8 into UCS4 as a string by using u8_to_u32_iterator std::wstring source_code; utf8_to_ucs4(source_code_raw, source_code); // enable correct locale so that we can print UCS4 characters enable_default_locale(std::wcout); getParserContext().enable_debug_parser = dump_parse; getParserContext().enable_semantic_action = !dump_parse; getParserContext().debug.current_source_index = ModuleSourceInfoContext::get(getParserContext().program)->addSource(filename); // try to parse typedef classic::position_iterator2<std::wstring::iterator> pos_iterator_type; try { pos_iterator_type begin(source_code.begin(), source_code.end(), s_to_ws(filename)); pos_iterator_type end; grammar::ThorScript<pos_iterator_type, action::ThorScriptTreeAction> parser; grammar::detail::WhiteSpace<pos_iterator_type> skipper; if(!qi::phrase_parse( begin, end, parser, skipper)) { return false; } } catch (const qi::expectation_failure<pos_iterator_type>& e) { const classic::file_position_base<std::wstring>& pos = e.first.get_position(); // TODO output error using Logger std::wstring current_line; expand_tabs(e.first.get_currentline(), current_line); std::wcerr << L"parse error at file " << pos.file << L" line " << pos.line << L" column " << pos.column << std::endl << L"'" << current_line << L"'" << std::endl << std::setw(pos.column) << L" " << L"^- here" << std::endl; return false; } return true; } } } } <|endoftext|>
<commit_before>/* Copyright 2016-2017 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QtCore/QJsonDocument> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> #include <QtCore/QFile> #include <QtCore/QRegularExpression> #include "trikKitInterpreterCommon/trikTextualInterpreter.h" #include <qrgui/plugins/toolPluginInterface/usedInterfaces/errorReporterInterface.h> #include <twoDModel/engine/model/timeline.h> Q_DECLARE_METATYPE(utils::AbstractTimer*) const QString jsOverrides = "script.random = brick.random;script.wait = brick.wait;script.time = brick.time;" "script.readAll = brick.readAll;script.timer = brick.timer;" "arrayPPinternal = function(arg) {" "var res = '[';" "for(var i = 0; i < arg.length; i++) {" "var separator = i + 1 != arg.length ? ', ' : '';" "if (arg[i] instanceof Array) {" "res += arrayPPinternal(arg[i]) + separator;" "} else { res += arg[i].toString() + separator; }" "}" "res += ']';" "return res;" "};" "print = function() " "{" "var res = '';" "for(var i = 0; i < arguments.length; i++) {" "if (arguments[i] instanceof Array) {res += arrayPPinternal(arguments[i]);" "} else {res += arguments[i].toString();}" "};" "brick.log(res);" "return res;" "};" "script.system = function() {print('system is disabled in the interpreter');};"; const QString pyOverrides ="\ndef print(args): brick.log(args);\n"; trik::TrikTextualInterpreter::TrikTextualInterpreter(const QSharedPointer<trik::robotModel::twoD::TrikTwoDRobotModel> &model) : mRunning(false), mBrick(model), mScriptRunner(mBrick, nullptr), mErrorReporter(nullptr) { connect(&mBrick, &TrikBrick::error, this, &TrikTextualInterpreter::reportError); connect(&mBrick, &TrikBrick::warning, this, &TrikTextualInterpreter::reportWarning); auto atimerToScriptValue = [](QScriptEngine *engine, utils::AbstractTimer* const &in){ return engine->newQObject(in); }; auto atimerFromScriptValue = [](const QScriptValue &object, utils::AbstractTimer* &out){ out = qobject_cast<utils::AbstractTimer*>(object.toQObject()); }; mScriptRunner.addCustomEngineInitStep([&atimerToScriptValue, &atimerFromScriptValue](QScriptEngine *engine){ qScriptRegisterMetaType<utils::AbstractTimer*>(engine, atimerToScriptValue, atimerFromScriptValue); }); connect(&mScriptRunner, SIGNAL(completed(QString,int)), this, SLOT(scriptFinished(QString,int))); } trik::TrikTextualInterpreter::~TrikTextualInterpreter() { abort(); } void trik::TrikTextualInterpreter::interpretCommand(const QString &script) { mScriptRunner.runDirectCommand(script); } void trik::TrikTextualInterpreter::interpretScript(const QString &script, const QString &languageExtension) { mRunning = true; mBrick.processSensors(true); if (languageExtension.contains("js")) { mScriptRunner.run(jsOverrides + script); } else if (languageExtension.contains("py")) { QString updatedScript = script; int lastIndexOfImport = updatedScript.lastIndexOf(QRegularExpression("^import .*" , QRegularExpression::MultilineOption)); int indexOf = updatedScript.indexOf(QRegularExpression("$", QRegularExpression::MultilineOption) , lastIndexOfImport); updatedScript.insert(indexOf + 1, pyOverrides); mScriptRunner.run(updatedScript, "dummyFile.py"); } else { Q_ASSERT(false); } } void trik::TrikTextualInterpreter::interpretScriptExercise(const QString &script , const QString &inputs, const QString &languageExtension) { Q_UNUSED(languageExtension) mRunning = true; mBrick.processSensors(true); mBrick.setCurrentInputs(inputs); QString newScript = jsOverrides + "script.writeToFile = null;\n" + script; //qDebug() << newScript; mScriptRunner.run(newScript); } void trik::TrikTextualInterpreter::abort() { //mScriptRunner.abort(); mBrick.stopWaiting(); Q_ASSERT(mScriptRunner.thread() == thread()); QMetaObject::invokeMethod(&mScriptRunner, "abort", Qt::QueuedConnection); // just a wild test mRunning = false; // reset brick? mBrick.processSensors(false); } void trik::TrikTextualInterpreter::init() { mBrick.init(); // very crucial. Maybe move into interpret methods? } void trik::TrikTextualInterpreter::setErrorReporter(qReal::ErrorReporterInterface &errorReporter) { mErrorReporter = &errorReporter; } bool trik::TrikTextualInterpreter::isRunning() const { return mRunning; } void trik::TrikTextualInterpreter::reportError(const QString &msg) { mErrorReporter->addError(msg); // mBrick.abort(); what if there are more errors? } void trik::TrikTextualInterpreter::reportWarning(const QString &msg) { mErrorReporter->addWarning(msg); } void trik::TrikTextualInterpreter::reportLog(const QString &msg) { mErrorReporter->addInformation("log: " + msg); } QString trik::TrikTextualInterpreter::initInputs(const QString &inputs) const { auto jsValToStr = [this](const QJsonValue &val) -> QString { switch (val.type()) { case QJsonValue::Bool: return val.toBool() ? "true" : "false"; case QJsonValue::Double: return QString::number(val.Double);//maybe increase precision case QJsonValue::String: return QString("\"%1\"").arg(val.toString()); case QJsonValue::Array: return QString(QJsonDocument(val.toArray()).toJson(QJsonDocument::Compact)); case QJsonValue::Object: return QString(QJsonDocument(val.toObject()).toJson(QJsonDocument::Compact)); default: mErrorReporter->addError(QObject::tr("Bogus input values")); return ""; } }; QString result; if (!inputs.isEmpty()) { QString val; QFile file; file.setFileName(inputs); if (file.open(QIODevice::ReadOnly)) { val = file.readAll(); file.close(); QJsonDocument document = QJsonDocument::fromJson(val.toUtf8()); QJsonObject object = document.object(); for (const QString &name : object.keys()) { QJsonValue value = object[name]; QString valueStr = jsValToStr(value); QString line("var " + name + " = " + valueStr + ";\n"); result.append(line); } } else { mErrorReporter->addError(QObject::tr("Error: File %1 couldn't be opened!").arg(inputs)); } } return result; } void trik::TrikTextualInterpreter::setRunning(bool running) { mRunning = running; mBrick.processSensors(running); } void trik::TrikTextualInterpreter::setCurrentDir(const QString &dir) { mBrick.setCurrentDir(dir); } QStringList trik::TrikTextualInterpreter::supportedRobotModelNames() const { return {"TwoDRobotModelForTrikV62RealRobotModel", "TwoDRobotModelForTrikV6RealRobotModel"}; } QStringList trik::TrikTextualInterpreter::knownMethodNames() const { return mScriptRunner.knownMethodNames(); } void trik::TrikTextualInterpreter::reinitRobotsParts() { mBrick.reinitImitationCamera(); } void trik::TrikTextualInterpreter::scriptFinished(const QString &error, int scriptId) { Q_UNUSED(scriptId); if (!error.isEmpty()) { reportError(error); } if (mRunning) { /// @todo: figure out better place for this check - it should avoid double aborts mRunning = false; mBrick.processSensors(false); emit completed(); } } <commit_msg>make vera happy<commit_after>/* Copyright 2016-2017 CyberTech Labs Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QtCore/QJsonDocument> #include <QtCore/QJsonArray> #include <QtCore/QJsonObject> #include <QtCore/QFile> #include <QtCore/QRegularExpression> #include "trikKitInterpreterCommon/trikTextualInterpreter.h" #include <qrgui/plugins/toolPluginInterface/usedInterfaces/errorReporterInterface.h> #include <twoDModel/engine/model/timeline.h> Q_DECLARE_METATYPE(utils::AbstractTimer*) const QString jsOverrides = "script.random = brick.random;script.wait = brick.wait;script.time = brick.time;" "script.readAll = brick.readAll;script.timer = brick.timer;" "arrayPPinternal = function(arg) {" "var res = '[';" "for(var i = 0; i < arg.length; i++) {" "var separator = i + 1 != arg.length ? ', ' : '';" "if (arg[i] instanceof Array) {" "res += arrayPPinternal(arg[i]) + separator;" "} else { res += arg[i].toString() + separator; }" "}" "res += ']';" "return res;" "};" "print = function() " "{" "var res = '';" "for(var i = 0; i < arguments.length; i++) {" "if (arguments[i] instanceof Array) {res += arrayPPinternal(arguments[i]);" "} else {res += arguments[i].toString();}" "};" "brick.log(res);" "return res;" "};" "script.system = function() {print('system is disabled in the interpreter');};"; const QString pyOverrides ="\ndef print(args): brick.log(args);\n"; trik::TrikTextualInterpreter::TrikTextualInterpreter( const QSharedPointer<trik::robotModel::twoD::TrikTwoDRobotModel> &model) : mRunning(false), mBrick(model), mScriptRunner(mBrick, nullptr), mErrorReporter(nullptr) { connect(&mBrick, &TrikBrick::error, this, &TrikTextualInterpreter::reportError); connect(&mBrick, &TrikBrick::warning, this, &TrikTextualInterpreter::reportWarning); auto atimerToScriptValue = [](QScriptEngine *engine, utils::AbstractTimer* const &in){ return engine->newQObject(in); }; auto atimerFromScriptValue = [](const QScriptValue &object, utils::AbstractTimer* &out){ out = qobject_cast<utils::AbstractTimer*>(object.toQObject()); }; mScriptRunner.addCustomEngineInitStep([&atimerToScriptValue, &atimerFromScriptValue](QScriptEngine *engine){ qScriptRegisterMetaType<utils::AbstractTimer*>(engine, atimerToScriptValue, atimerFromScriptValue); }); connect(&mScriptRunner, SIGNAL(completed(QString,int)), this, SLOT(scriptFinished(QString,int))); } trik::TrikTextualInterpreter::~TrikTextualInterpreter() { abort(); } void trik::TrikTextualInterpreter::interpretCommand(const QString &script) { mScriptRunner.runDirectCommand(script); } void trik::TrikTextualInterpreter::interpretScript(const QString &script, const QString &languageExtension) { mRunning = true; mBrick.processSensors(true); if (languageExtension.contains("js")) { mScriptRunner.run(jsOverrides + script); } else if (languageExtension.contains("py")) { QString updatedScript = script; int lastIndexOfImport = updatedScript.lastIndexOf(QRegularExpression("^import .*" , QRegularExpression::MultilineOption)); int indexOf = updatedScript.indexOf(QRegularExpression("$", QRegularExpression::MultilineOption) , lastIndexOfImport); updatedScript.insert(indexOf + 1, pyOverrides); mScriptRunner.run(updatedScript, "dummyFile.py"); } else { Q_ASSERT(false); } } void trik::TrikTextualInterpreter::interpretScriptExercise(const QString &script , const QString &inputs, const QString &languageExtension) { Q_UNUSED(languageExtension) mRunning = true; mBrick.processSensors(true); mBrick.setCurrentInputs(inputs); QString newScript = jsOverrides + "script.writeToFile = null;\n" + script; //qDebug() << newScript; mScriptRunner.run(newScript); } void trik::TrikTextualInterpreter::abort() { //mScriptRunner.abort(); mBrick.stopWaiting(); Q_ASSERT(mScriptRunner.thread() == thread()); QMetaObject::invokeMethod(&mScriptRunner, "abort", Qt::QueuedConnection); // just a wild test mRunning = false; // reset brick? mBrick.processSensors(false); } void trik::TrikTextualInterpreter::init() { mBrick.init(); // very crucial. Maybe move into interpret methods? } void trik::TrikTextualInterpreter::setErrorReporter(qReal::ErrorReporterInterface &errorReporter) { mErrorReporter = &errorReporter; } bool trik::TrikTextualInterpreter::isRunning() const { return mRunning; } void trik::TrikTextualInterpreter::reportError(const QString &msg) { mErrorReporter->addError(msg); // mBrick.abort(); what if there are more errors? } void trik::TrikTextualInterpreter::reportWarning(const QString &msg) { mErrorReporter->addWarning(msg); } void trik::TrikTextualInterpreter::reportLog(const QString &msg) { mErrorReporter->addInformation("log: " + msg); } QString trik::TrikTextualInterpreter::initInputs(const QString &inputs) const { auto jsValToStr = [this](const QJsonValue &val) -> QString { switch (val.type()) { case QJsonValue::Bool: return val.toBool() ? "true" : "false"; case QJsonValue::Double: return QString::number(val.Double);//maybe increase precision case QJsonValue::String: return QString("\"%1\"").arg(val.toString()); case QJsonValue::Array: return QString(QJsonDocument(val.toArray()).toJson(QJsonDocument::Compact)); case QJsonValue::Object: return QString(QJsonDocument(val.toObject()).toJson(QJsonDocument::Compact)); default: mErrorReporter->addError(QObject::tr("Bogus input values")); return ""; } }; QString result; if (!inputs.isEmpty()) { QString val; QFile file; file.setFileName(inputs); if (file.open(QIODevice::ReadOnly)) { val = file.readAll(); file.close(); QJsonDocument document = QJsonDocument::fromJson(val.toUtf8()); QJsonObject object = document.object(); for (const QString &name : object.keys()) { QJsonValue value = object[name]; QString valueStr = jsValToStr(value); QString line("var " + name + " = " + valueStr + ";\n"); result.append(line); } } else { mErrorReporter->addError(QObject::tr("Error: File %1 couldn't be opened!").arg(inputs)); } } return result; } void trik::TrikTextualInterpreter::setRunning(bool running) { mRunning = running; mBrick.processSensors(running); } void trik::TrikTextualInterpreter::setCurrentDir(const QString &dir) { mBrick.setCurrentDir(dir); } QStringList trik::TrikTextualInterpreter::supportedRobotModelNames() const { return {"TwoDRobotModelForTrikV62RealRobotModel", "TwoDRobotModelForTrikV6RealRobotModel"}; } QStringList trik::TrikTextualInterpreter::knownMethodNames() const { return mScriptRunner.knownMethodNames(); } void trik::TrikTextualInterpreter::reinitRobotsParts() { mBrick.reinitImitationCamera(); } void trik::TrikTextualInterpreter::scriptFinished(const QString &error, int scriptId) { Q_UNUSED(scriptId); if (!error.isEmpty()) { reportError(error); } if (mRunning) { /// @todo: figure out better place for this check - it should avoid double aborts mRunning = false; mBrick.processSensors(false); emit completed(); } } <|endoftext|>
<commit_before>#include "PDBHelper.h" #include "../Misc/Trace.hpp" #include <cstdint> #include <sstream> #define CHECK_SUCCESS(e)\ { \ HRESULT hresult = (e); \ if(FAILED(hresult)) \ { \ BLACKBONE_TRACE( "PDB: %s: (%s) failed with HRESULT 0x%08x", __FUNCTION__, #e , hresult ); \ return hresult; \ } \ } namespace blackbone { PDBHelper::PDBHelper() { CoInitialize( nullptr ); // If _NT_SYMBOL_PATH exists, use it wchar_t path[MAX_PATH] = { }; if (GetEnvironmentVariableW( L"_NT_SYMBOL_PATH", path, _countof( path ) ) == 0) { if (GetTempPathW( _countof( path ), path ) != -1) { std::wstringstream wss; wss << L"srv*" << path << L"Symbols*https://msdl.microsoft.com/download/symbols"; _sympath = wss.str(); } } } PDBHelper::~PDBHelper() { // Must be released before CoUninitialize _global.Release(); _session.Release(); _source.Release(); CoUninitialize(); } /// <summary> /// Initialize symbols for target file /// </summary> /// <param name="file">Fully qualified path to target PE file</param> /// <param name="base">Base ptr to add to RVAs</param> /// <returns>Status code</returns> HRESULT PDBHelper::Init( const std::wstring& file, ptr_t base /*= 0*/ ) { CHECK_SUCCESS( CoCreateDiaDataSource() ); CHECK_SUCCESS( _source->loadDataForExe( file.c_str(), _sympath.empty() ? nullptr : _sympath.c_str(), nullptr ) ); CHECK_SUCCESS( _source->openSession( &_session ) ); CHECK_SUCCESS( _session->get_globalScope( &_global ) ); _base = base; return PopulateSymbols(); } /// <summary> /// Get symbol RVA /// </summary> /// <param name="symName">Symbol name</param> /// <param name="result">Resulting RVA</param> /// <returns>Status code</returns> HRESULT PDBHelper::GetSymAddress( const std::wstring& symName, ptr_t& result ) { auto found = _cache.find( symName ); if (found != _cache.end()) { result = _base + found->second; return S_OK; } return E_PDB_DBG_NOT_FOUND; } /// <summary> /// Initialize DIA /// </summary> /// <returns>Status code</returns> HRESULT PDBHelper::CoCreateDiaDataSource() { const auto pSource = reinterpret_cast<void**>(&_source); // Try to get from COM HRESULT hr = CoCreateInstance( CLSID_DiaSource, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IDiaDataSource), pSource ); // Retry with direct export call if (hr == REGDB_E_CLASSNOTREG) { HMODULE hMod = LoadLibraryW( L"msdia140.dll" ); if (!hMod) { BLACKBONE_TRACE( "PDB: Failed to load msdia140.dll, error 0x08%x", GetLastError() ); return HRESULT_FROM_WIN32( GetLastError() ); } auto DllGetClassObject = reinterpret_cast<BOOL( WINAPI* )(REFCLSID, REFIID, LPVOID)>(GetProcAddress( hMod, "DllGetClassObject" )); if (!DllGetClassObject) { BLACKBONE_TRACE( "PDB: Failed to get DllGetClassObject from msdia140.dll" ); return HRESULT_FROM_WIN32( GetLastError() ); } CComPtr<IClassFactory> classFactory; CHECK_SUCCESS( DllGetClassObject( CLSID_DiaSource, IID_IClassFactory, &classFactory ) ); hr = classFactory->CreateInstance( nullptr, IID_IDiaDataSource, pSource ); } if (FAILED( hr )) { BLACKBONE_TRACE( "PDB: %s failed with HRESULT 0x08%x", __FUNCTION__, hr ); } return hr; } /// <summary> /// Build module symbol map /// </summary> /// <returns>Status code</returns> HRESULT PDBHelper::PopulateSymbols() { CComPtr<IDiaEnumSymbols> symbols; CHECK_SUCCESS( _global->findChildren( SymTagNull, nullptr, nsNone, &symbols ) ); ULONG count = 0; CComPtr<IDiaSymbol> symbol; while (SUCCEEDED( symbols->Next( 1, &symbol, &count ) ) && count != 0) { DWORD rva = 0; BSTR name = nullptr; symbol->get_relativeVirtualAddress( &rva ); symbol->get_undecoratedName( &name ); if (name && rva) { std::wstring wname( name ); // Remove x86 __stdcall decoration if (wname[0] == L'@' || wname[0] == L'_') { wname.erase( 0, 1 ); } auto pos = wname.rfind( L'@' ); if (pos != wname.npos) { wname.erase( pos ); } _cache.emplace( std::move( wname ), rva ); } symbol.Release(); } return S_OK; } }<commit_msg>Symbol download fix<commit_after>#include "PDBHelper.h" #include "../Misc/Trace.hpp" #include <cstdint> #include <sstream> #define CHECK_SUCCESS(e)\ { \ HRESULT hresult = (e); \ if(FAILED(hresult)) \ { \ BLACKBONE_TRACE( "PDB: %s: (%s) failed with HRESULT 0x%08x", __FUNCTION__, #e , hresult ); \ return hresult; \ } \ } namespace blackbone { PDBHelper::PDBHelper() { CoInitialize( nullptr ); // If _NT_SYMBOL_PATH exists, use it wchar_t path[MAX_PATH] = { }; if (GetEnvironmentVariableW( L"_NT_SYMBOL_PATH", path, _countof( path ) ) == 0) { if (GetTempPathW( _countof( path ), path ) != 0) { std::wstringstream wss; wss << L"srv*" << path << L"Symbols*http://msdl.microsoft.com/download/symbols"; _sympath = wss.str(); } } } PDBHelper::~PDBHelper() { // Must be released before CoUninitialize _global.Release(); _session.Release(); _source.Release(); CoUninitialize(); } /// <summary> /// Initialize symbols for target file /// </summary> /// <param name="file">Fully qualified path to target PE file</param> /// <param name="base">Base ptr to add to RVAs</param> /// <returns>Status code</returns> HRESULT PDBHelper::Init( const std::wstring& file, ptr_t base /*= 0*/ ) { CHECK_SUCCESS( CoCreateDiaDataSource() ); CHECK_SUCCESS( _source->loadDataForExe( file.c_str(), _sympath.empty() ? nullptr : _sympath.c_str(), nullptr ) ); CHECK_SUCCESS( _source->openSession( &_session ) ); CHECK_SUCCESS( _session->get_globalScope( &_global ) ); _base = base; return PopulateSymbols(); } /// <summary> /// Get symbol RVA /// </summary> /// <param name="symName">Symbol name</param> /// <param name="result">Resulting RVA</param> /// <returns>Status code</returns> HRESULT PDBHelper::GetSymAddress( const std::wstring& symName, ptr_t& result ) { auto found = _cache.find( symName ); if (found != _cache.end()) { result = _base + found->second; return S_OK; } return E_PDB_DBG_NOT_FOUND; } /// <summary> /// Initialize DIA /// </summary> /// <returns>Status code</returns> HRESULT PDBHelper::CoCreateDiaDataSource() { const auto pSource = reinterpret_cast<void**>(&_source); // Try to get from COM HRESULT hr = CoCreateInstance( CLSID_DiaSource, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IDiaDataSource), pSource ); // Retry with direct export call if (hr == REGDB_E_CLASSNOTREG) { HMODULE hMod = LoadLibraryW( L"msdia140.dll" ); if (!hMod) { BLACKBONE_TRACE( "PDB: Failed to load msdia140.dll, error 0x08%x", GetLastError() ); return HRESULT_FROM_WIN32( GetLastError() ); } auto DllGetClassObject = reinterpret_cast<BOOL( WINAPI* )(REFCLSID, REFIID, LPVOID)>(GetProcAddress( hMod, "DllGetClassObject" )); if (!DllGetClassObject) { BLACKBONE_TRACE( "PDB: Failed to get DllGetClassObject from msdia140.dll" ); return HRESULT_FROM_WIN32( GetLastError() ); } CComPtr<IClassFactory> classFactory; CHECK_SUCCESS( DllGetClassObject( CLSID_DiaSource, IID_IClassFactory, &classFactory ) ); hr = classFactory->CreateInstance( nullptr, IID_IDiaDataSource, pSource ); } if (FAILED( hr )) { BLACKBONE_TRACE( "PDB: %s failed with HRESULT 0x08%x", __FUNCTION__, hr ); } return hr; } /// <summary> /// Build module symbol map /// </summary> /// <returns>Status code</returns> HRESULT PDBHelper::PopulateSymbols() { CComPtr<IDiaEnumSymbols> symbols; CHECK_SUCCESS( _global->findChildren( SymTagNull, nullptr, nsNone, &symbols ) ); ULONG count = 0; CComPtr<IDiaSymbol> symbol; while (SUCCEEDED( symbols->Next( 1, &symbol, &count ) ) && count != 0) { DWORD rva = 0; BSTR name = nullptr; symbol->get_relativeVirtualAddress( &rva ); symbol->get_undecoratedName( &name ); if (name && rva) { std::wstring wname( name ); // Remove x86 __stdcall decoration if (wname[0] == L'@' || wname[0] == L'_') { wname.erase( 0, 1 ); } auto pos = wname.rfind( L'@' ); if (pos != wname.npos) { wname.erase( pos ); } _cache.emplace( std::move( wname ), rva ); } symbol.Release(); } return S_OK; } }<|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #include "debug/Dtu.hh" #include "debug/DtuPf.hh" #include "mem/dtu/dtu.hh" #include "mem/dtu/pt_unit.hh" const std::string PtUnit::TranslateEvent::name() const { return unit.dtu.name(); } void PtUnit::TranslateEvent::requestPTE() { auto pkt = unit.createPacket(virt, ptAddr, level); if (!pkt) { finish(false, NocAddr(0)); return; } unit.dtu.sendMemRequest(pkt, reinterpret_cast<Addr>(this), Dtu::MemReqType::TRANSLATION, Cycles(0)); } void PtUnit::TranslateEvent::process() { if (pf) { if (!unit.sendPagefaultMsg(this, virt, access)) finish(false, NocAddr(0)); } else requestPTE(); } void PtUnit::TranslateEvent::recvFromMem(PacketPtr pkt) { Addr phys; uint flags = access; bool success = unit.finishTranslate(pkt, virt, level, &flags, &phys); if (success) { if (level > 0) { level--; ptAddr = phys; requestPTE(); return; } Addr tlbVirt = virt & ~DtuTlb::PAGE_MASK; // we can't insert an entry twice NocAddr newPhys; if (unit.dtu.tlb->lookup(tlbVirt, access, &newPhys) != DtuTlb::HIT) { DPRINTFS(DtuPf, (&unit.dtu), "Inserting into TLB: virt=%p phys=%p flags=%u\n", tlbVirt, phys, flags); unit.dtu.tlb->insert(tlbVirt, NocAddr(phys), flags); } else assert(newPhys.getAddr() == phys); finish(success, NocAddr(phys + (virt & DtuTlb::PAGE_MASK))); } else { if (!unit.sendPagefaultMsg(this, virt, access)) finish(false, NocAddr(0)); } } bool PtUnit::translateFunctional(Addr virt, uint access, NocAddr *phys) { Addr ptePhys; Addr ptAddr = dtu.regs().get(DtuReg::ROOT_PT); for (int level = DtuTlb::LEVEL_CNT - 1; level >= 0; --level) { auto pkt = createPacket(virt, ptAddr, level); if (!pkt) return false; dtu.sendFunctionalMemRequest(pkt); if (!finishTranslate(pkt, virt, level, &access, &ptePhys)) return false; ptAddr = ptePhys; } *phys = NocAddr(ptePhys + (virt & DtuTlb::PAGE_MASK)); return true; } const char * PtUnit::describeAccess(uint access) { static char rwx[4]; rwx[0] = (access & DtuTlb::READ ) ? 'r' : '-'; rwx[1] = (access & DtuTlb::WRITE) ? 'w' : '-'; rwx[2] = (access & DtuTlb::EXEC ) ? 'x' : '-'; return rwx; } bool PtUnit::sendPagefaultMsg(TranslateEvent *ev, Addr virt, uint access) { if (~dtu.regs().get(DtuReg::STATUS) & static_cast<int>(Status::PAGEFAULTS)) { DPRINTFS(DtuPf, (&dtu), "Pagefault (%s @ %p), but pagefault sending is disabled\n", describeAccess(access), virt); if (!pfqueue.empty()) { DPRINTFS(DtuPf, (&dtu), "Dropping all pending pagefaults (%lu)\n", pfqueue.size()); for (auto qev = pfqueue.begin(); qev != pfqueue.end(); ++qev) (*qev)->finish(false, NocAddr(0)); pfqueue.clear(); } return false; } int pfep = ev->toKernel ? Dtu::SYSCALL_EP : dtu.regs().get(DtuReg::PF_EP); assert(pfep < dtu.numEndpoints); SendEp ep = dtu.regs().getSendEp(pfep); // fall back to syscall EP, if the PF ep is invalid if(ep.maxMsgSize == 0) { ev->toKernel = true; pfep = Dtu::SYSCALL_EP; ep = dtu.regs().getSendEp(pfep); } size_t size = sizeof(Dtu::MessageHeader) + sizeof(PagefaultMessage); assert(size <= ep.maxMsgSize); if (pfqueue.empty()) pfqueue.push_back(ev); else if (pfqueue.front() != ev) { uint page = virt >> DtuTlb::PAGE_BITS; for(auto qev = pfqueue.begin(); qev != pfqueue.end(); ++qev) { // can we merge the requests? if (access == (*qev)->access && page == ((*qev)->virt >> DtuTlb::PAGE_BITS)) { DPRINTFS(DtuPf, (&dtu), "Adding Pagefault @ %#x to running request (%s @ %#x)\n", virt, describeAccess(access), (*qev)->virt); (*qev)->trans.push_back(*ev->trans.begin()); delete ev; return true; } } // try again later DPRINTFS(DtuPf, (&dtu), "Appending Pagefault (%s @ %#x) to queue\n", describeAccess(access), virt); ev->pf = true; pfqueue.push_back(ev); return true; } // create packet NocAddr nocAddr = NocAddr(ep.targetCore, ep.vpeId, ep.targetEp); auto pkt = dtu.generateRequest(nocAddr.getAddr(), size, MemCmd::WriteReq); // build the message and put it in the packet Dtu::MessageHeader header; header.length = sizeof(PagefaultMessage); header.flags = Dtu::PAGEFAULT | Dtu::REPLY_ENABLED; header.label = ep.label; header.senderEpId = pfep; header.senderCoreId = dtu.coreId; header.replyLabel = reinterpret_cast<uint64_t>(ev); // not used header.replyEpId = 0; memcpy(pkt->getPtr<uint8_t>(), &header, sizeof(header)); PagefaultMessage msg; msg.opcode = PagefaultMessage::OPCODE_PF; msg.virt = virt; msg.access = access; memcpy(pkt->getPtr<uint8_t>() + sizeof(header), &msg, sizeof(msg)); DPRINTFS(Dtu, (&dtu), "\e[1m[sd -> %u]\e[0m with EP%u for Pagefault (%s @ %p)\n", ep.targetCore, pfep, describeAccess(access), virt); DPRINTFS(Dtu, (&dtu), " header: flags=%#x tgtEP=%u lbl=%#018lx rpLbl=%#018lx rpEP=%u\n", header.flags, ep.targetEp, header.label, header.replyLabel, header.replyEpId); // send the packet Cycles delay = dtu.transferToNocLatency; // delay += dtu.ticksToCycles(headerDelay); // pkt->payloadDelay = payloadDelay; dtu.printPacket(pkt); dtu.sendNocRequest(Dtu::NocPacketType::PAGEFAULT, pkt, delay); return true; } void PtUnit::sendingPfFailed(PacketPtr pkt, int error) { Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>(); TranslateEvent *ev = reinterpret_cast<TranslateEvent*>(header->replyLabel); DPRINTFS(DtuPf, (&dtu), "Sending Pagefault (%s @ %p) failed (%d); notifying kernel\n", describeAccess(ev->access), ev->virt, error); if (error == Dtu::VPE_GONE) { ev->pf = true; ev->toKernel = true; dtu.schedule(ev, dtu.clockEdge(Cycles(1))); } else { panic("Unable to resolve pagefault (%s @ %p)", describeAccess(ev->access), ev->virt); } nextPagefault(ev); } void PtUnit::finishPagefault(PacketPtr pkt) { Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>(); uint64_t *errorPtr = reinterpret_cast<uint64_t*>(header + 1); size_t expSize = sizeof(Dtu::MessageHeader) + sizeof(uint64_t); int error = pkt->getSize() == expSize ? *errorPtr : -1; TranslateEvent *ev = reinterpret_cast<TranslateEvent*>(header->label); DPRINTFS(Dtu, (&dtu), "\e[1m[rv <- %u]\e[0m %lu bytes for Pagefault (%s @ %p)\n", header->senderCoreId, header->length, describeAccess(ev->access), ev->virt); dtu.printPacket(pkt); pkt->makeResponse(); nextPagefault(ev); if (!dtu.atomicMode) { Cycles delay = dtu.ticksToCycles( pkt->headerDelay + pkt->payloadDelay); delay += dtu.nocToTransferLatency; pkt->headerDelay = 0; pkt->payloadDelay = 0; dtu.schedNocRequestFinished(dtu.clockEdge(Cycles(1))); dtu.schedNocResponse(pkt, dtu.clockEdge(delay)); } if (error != 0) { if (pkt->getSize() != expSize) DPRINTFS(DtuPf, (&dtu), "Invalid response for pagefault\n"); else { DPRINTFS(DtuPf, (&dtu), "Pagefault for %s @ %p could not been resolved: %d\n", describeAccess(ev->access), ev->virt, error); } ev->finish(false, NocAddr(0)); return; } DPRINTFS(DtuPf, (&dtu), "Retrying pagetable walk for %s @ %p\n", describeAccess(ev->access), ev->virt); // retry the translation ev->pf = false; ev->toKernel = false; dtu.schedule(ev, dtu.clockEdge(Cycles(1))); } void PtUnit::nextPagefault(TranslateEvent *ev) { assert(pfqueue.front() == ev); pfqueue.pop_front(); if (!pfqueue.empty()) { TranslateEvent *ev = pfqueue.front(); dtu.schedule(ev, dtu.clockEdge(Cycles(1))); } } PacketPtr PtUnit::createPacket(Addr virt, Addr ptAddr, int level) { Addr idx = virt >> (DtuTlb::PAGE_BITS + level * DtuTlb::LEVEL_BITS); idx &= DtuTlb::LEVEL_MASK; NocAddr pteAddr(ptAddr + (idx << DtuTlb::PTE_BITS)); auto pkt = dtu.generateRequest(pteAddr.getAddr(), sizeof(PtUnit::PageTableEntry), MemCmd::ReadReq); DPRINTFS(DtuPf, (&dtu), "Loading level %d PTE for %p from %p\n", level, virt, pteAddr.getAddr()); return pkt; } bool PtUnit::finishTranslate(PacketPtr pkt, Addr virt, int level, uint *access, Addr *phys) { PageTableEntry *e = pkt->getPtr<PageTableEntry>(); DPRINTFS(DtuPf, (&dtu), "Received level %d PTE for %p: %#x\n", level, virt, (uint64_t)*e); // for last-level PTEs, we need the desired access permissions if (level == 0) { if ((e->ixwr & *access) != *access) return false; } // for others, we don't need the INTERN bit else { uint pteAccess = *access & ~DtuTlb::INTERN; if ((e->ixwr & pteAccess) != pteAccess) return false; } *access = static_cast<uint>((uint64_t)e->ixwr); *phys = e->base << DtuTlb::PAGE_BITS; return true; } void PtUnit::startTranslate(Addr virt, uint access, Translation *trans, bool pf) { TranslateEvent *event = new TranslateEvent(*this); event->level = DtuTlb::LEVEL_CNT - 1; event->virt = virt; event->access = access; event->trans.push_back(trans); event->ptAddr = dtu.regs().get(DtuReg::ROOT_PT); event->pf = pf; event->toKernel = false; dtu.schedule(event, dtu.clockEdge(Cycles(1))); } <commit_msg>DTU: fixed bug in functional translate.<commit_after>/* * Copyright (c) 2015, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #include "debug/Dtu.hh" #include "debug/DtuPf.hh" #include "mem/dtu/dtu.hh" #include "mem/dtu/pt_unit.hh" const std::string PtUnit::TranslateEvent::name() const { return unit.dtu.name(); } void PtUnit::TranslateEvent::requestPTE() { auto pkt = unit.createPacket(virt, ptAddr, level); if (!pkt) { finish(false, NocAddr(0)); return; } unit.dtu.sendMemRequest(pkt, reinterpret_cast<Addr>(this), Dtu::MemReqType::TRANSLATION, Cycles(0)); } void PtUnit::TranslateEvent::process() { if (pf) { if (!unit.sendPagefaultMsg(this, virt, access)) finish(false, NocAddr(0)); } else requestPTE(); } void PtUnit::TranslateEvent::recvFromMem(PacketPtr pkt) { Addr phys; uint flags = access; bool success = unit.finishTranslate(pkt, virt, level, &flags, &phys); if (success) { if (level > 0) { level--; ptAddr = phys; requestPTE(); return; } Addr tlbVirt = virt & ~DtuTlb::PAGE_MASK; // we can't insert an entry twice NocAddr newPhys; if (unit.dtu.tlb->lookup(tlbVirt, access, &newPhys) != DtuTlb::HIT) { DPRINTFS(DtuPf, (&unit.dtu), "Inserting into TLB: virt=%p phys=%p flags=%u\n", tlbVirt, phys, flags); unit.dtu.tlb->insert(tlbVirt, NocAddr(phys), flags); } else assert(newPhys.getAddr() == phys); finish(success, NocAddr(phys + (virt & DtuTlb::PAGE_MASK))); } else { if (!unit.sendPagefaultMsg(this, virt, access)) finish(false, NocAddr(0)); } } bool PtUnit::translateFunctional(Addr virt, uint access, NocAddr *phys) { Addr ptePhys; Addr ptAddr = dtu.regs().get(DtuReg::ROOT_PT); for (int level = DtuTlb::LEVEL_CNT - 1; level >= 0; --level) { auto pkt = createPacket(virt, ptAddr, level); if (!pkt) return false; dtu.sendFunctionalMemRequest(pkt); uint acccopy = access; if (!finishTranslate(pkt, virt, level, &acccopy, &ptePhys)) return false; ptAddr = ptePhys; } *phys = NocAddr(ptePhys + (virt & DtuTlb::PAGE_MASK)); return true; } const char * PtUnit::describeAccess(uint access) { static char rwx[4]; rwx[0] = (access & DtuTlb::READ ) ? 'r' : '-'; rwx[1] = (access & DtuTlb::WRITE) ? 'w' : '-'; rwx[2] = (access & DtuTlb::EXEC ) ? 'x' : '-'; return rwx; } bool PtUnit::sendPagefaultMsg(TranslateEvent *ev, Addr virt, uint access) { if (~dtu.regs().get(DtuReg::STATUS) & static_cast<int>(Status::PAGEFAULTS)) { DPRINTFS(DtuPf, (&dtu), "Pagefault (%s @ %p), but pagefault sending is disabled\n", describeAccess(access), virt); if (!pfqueue.empty()) { DPRINTFS(DtuPf, (&dtu), "Dropping all pending pagefaults (%lu)\n", pfqueue.size()); for (auto qev = pfqueue.begin(); qev != pfqueue.end(); ++qev) (*qev)->finish(false, NocAddr(0)); pfqueue.clear(); } return false; } int pfep = ev->toKernel ? Dtu::SYSCALL_EP : dtu.regs().get(DtuReg::PF_EP); assert(pfep < dtu.numEndpoints); SendEp ep = dtu.regs().getSendEp(pfep); // fall back to syscall EP, if the PF ep is invalid if(ep.maxMsgSize == 0) { ev->toKernel = true; pfep = Dtu::SYSCALL_EP; ep = dtu.regs().getSendEp(pfep); } size_t size = sizeof(Dtu::MessageHeader) + sizeof(PagefaultMessage); assert(size <= ep.maxMsgSize); if (pfqueue.empty()) pfqueue.push_back(ev); else if (pfqueue.front() != ev) { uint page = virt >> DtuTlb::PAGE_BITS; for(auto qev = pfqueue.begin(); qev != pfqueue.end(); ++qev) { // can we merge the requests? if (access == (*qev)->access && page == ((*qev)->virt >> DtuTlb::PAGE_BITS)) { DPRINTFS(DtuPf, (&dtu), "Adding Pagefault @ %#x to running request (%s @ %#x)\n", virt, describeAccess(access), (*qev)->virt); (*qev)->trans.push_back(*ev->trans.begin()); delete ev; return true; } } // try again later DPRINTFS(DtuPf, (&dtu), "Appending Pagefault (%s @ %#x) to queue\n", describeAccess(access), virt); ev->pf = true; pfqueue.push_back(ev); return true; } // create packet NocAddr nocAddr = NocAddr(ep.targetCore, ep.vpeId, ep.targetEp); auto pkt = dtu.generateRequest(nocAddr.getAddr(), size, MemCmd::WriteReq); // build the message and put it in the packet Dtu::MessageHeader header; header.length = sizeof(PagefaultMessage); header.flags = Dtu::PAGEFAULT | Dtu::REPLY_ENABLED; header.label = ep.label; header.senderEpId = pfep; header.senderCoreId = dtu.coreId; header.replyLabel = reinterpret_cast<uint64_t>(ev); // not used header.replyEpId = 0; memcpy(pkt->getPtr<uint8_t>(), &header, sizeof(header)); PagefaultMessage msg; msg.opcode = PagefaultMessage::OPCODE_PF; msg.virt = virt; msg.access = access; memcpy(pkt->getPtr<uint8_t>() + sizeof(header), &msg, sizeof(msg)); DPRINTFS(Dtu, (&dtu), "\e[1m[sd -> %u]\e[0m with EP%u for Pagefault (%s @ %p)\n", ep.targetCore, pfep, describeAccess(access), virt); DPRINTFS(Dtu, (&dtu), " header: flags=%#x tgtEP=%u lbl=%#018lx rpLbl=%#018lx rpEP=%u\n", header.flags, ep.targetEp, header.label, header.replyLabel, header.replyEpId); // send the packet Cycles delay = dtu.transferToNocLatency; // delay += dtu.ticksToCycles(headerDelay); // pkt->payloadDelay = payloadDelay; dtu.printPacket(pkt); dtu.sendNocRequest(Dtu::NocPacketType::PAGEFAULT, pkt, delay); return true; } void PtUnit::sendingPfFailed(PacketPtr pkt, int error) { Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>(); TranslateEvent *ev = reinterpret_cast<TranslateEvent*>(header->replyLabel); DPRINTFS(DtuPf, (&dtu), "Sending Pagefault (%s @ %p) failed (%d); notifying kernel\n", describeAccess(ev->access), ev->virt, error); if (error == Dtu::VPE_GONE) { ev->pf = true; ev->toKernel = true; dtu.schedule(ev, dtu.clockEdge(Cycles(1))); } else { panic("Unable to resolve pagefault (%s @ %p)", describeAccess(ev->access), ev->virt); } nextPagefault(ev); } void PtUnit::finishPagefault(PacketPtr pkt) { Dtu::MessageHeader* header = pkt->getPtr<Dtu::MessageHeader>(); uint64_t *errorPtr = reinterpret_cast<uint64_t*>(header + 1); size_t expSize = sizeof(Dtu::MessageHeader) + sizeof(uint64_t); int error = pkt->getSize() == expSize ? *errorPtr : -1; TranslateEvent *ev = reinterpret_cast<TranslateEvent*>(header->label); DPRINTFS(Dtu, (&dtu), "\e[1m[rv <- %u]\e[0m %lu bytes for Pagefault (%s @ %p)\n", header->senderCoreId, header->length, describeAccess(ev->access), ev->virt); dtu.printPacket(pkt); pkt->makeResponse(); nextPagefault(ev); if (!dtu.atomicMode) { Cycles delay = dtu.ticksToCycles( pkt->headerDelay + pkt->payloadDelay); delay += dtu.nocToTransferLatency; pkt->headerDelay = 0; pkt->payloadDelay = 0; dtu.schedNocRequestFinished(dtu.clockEdge(Cycles(1))); dtu.schedNocResponse(pkt, dtu.clockEdge(delay)); } if (error != 0) { if (pkt->getSize() != expSize) DPRINTFS(DtuPf, (&dtu), "Invalid response for pagefault\n"); else { DPRINTFS(DtuPf, (&dtu), "Pagefault for %s @ %p could not been resolved: %d\n", describeAccess(ev->access), ev->virt, error); } ev->finish(false, NocAddr(0)); return; } DPRINTFS(DtuPf, (&dtu), "Retrying pagetable walk for %s @ %p\n", describeAccess(ev->access), ev->virt); // retry the translation ev->pf = false; ev->toKernel = false; dtu.schedule(ev, dtu.clockEdge(Cycles(1))); } void PtUnit::nextPagefault(TranslateEvent *ev) { assert(pfqueue.front() == ev); pfqueue.pop_front(); if (!pfqueue.empty()) { TranslateEvent *ev = pfqueue.front(); dtu.schedule(ev, dtu.clockEdge(Cycles(1))); } } PacketPtr PtUnit::createPacket(Addr virt, Addr ptAddr, int level) { Addr idx = virt >> (DtuTlb::PAGE_BITS + level * DtuTlb::LEVEL_BITS); idx &= DtuTlb::LEVEL_MASK; NocAddr pteAddr(ptAddr + (idx << DtuTlb::PTE_BITS)); auto pkt = dtu.generateRequest(pteAddr.getAddr(), sizeof(PtUnit::PageTableEntry), MemCmd::ReadReq); DPRINTFS(DtuPf, (&dtu), "Loading level %d PTE for %p from %p\n", level, virt, pteAddr.getAddr()); return pkt; } bool PtUnit::finishTranslate(PacketPtr pkt, Addr virt, int level, uint *access, Addr *phys) { PageTableEntry *e = pkt->getPtr<PageTableEntry>(); DPRINTFS(DtuPf, (&dtu), "Received level %d PTE for %p: %#x\n", level, virt, (uint64_t)*e); // for last-level PTEs, we need the desired access permissions if (level == 0) { if ((e->ixwr & *access) != *access) return false; } // for others, we don't need the INTERN bit else { uint pteAccess = *access & ~DtuTlb::INTERN; if ((e->ixwr & pteAccess) != pteAccess) return false; } *access = static_cast<uint>((uint64_t)e->ixwr); *phys = e->base << DtuTlb::PAGE_BITS; return true; } void PtUnit::startTranslate(Addr virt, uint access, Translation *trans, bool pf) { TranslateEvent *event = new TranslateEvent(*this); event->level = DtuTlb::LEVEL_CNT - 1; event->virt = virt; event->access = access; event->trans.push_back(trans); event->ptAddr = dtu.regs().get(DtuReg::ROOT_PT); event->pf = pf; event->toKernel = false; dtu.schedule(event, dtu.clockEdge(Cycles(1))); } <|endoftext|>
<commit_before>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include "device.h" #include <QtCore/QTimer> #include <kdebug.h> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h> K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_monitoredConfig(0) , m_iteration(0) , m_pendingSave(false) , m_monitoring(false) , m_timer(new QTimer()) { setenv("KSCREEN_BACKEND", "XRandR", 0); KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged(bool))); m_timer->setInterval(300); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig())); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); monitorConnectedChange(); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); Device::destroy(); } void KScreenDaemon::init() { applyConfig(); } void KScreenDaemon::applyConfig() { kDebug() << "Applying config"; if (Serializer::configExists()) { applyKnownConfig(); return; } applyIdealConfig(); } void KScreenDaemon::applyKnownConfig() { kDebug() << "Applying known config"; setMonitorForChanges(false); KScreen::Config::setConfig(Serializer::config(Serializer::currentId())); QMetaObject::invokeMethod(this, "scheduleMonitorChange", Qt::QueuedConnection); } void KScreenDaemon::applyIdealConfig() { kDebug() << "Applying ideal config"; setMonitorForChanges(true); KScreen::Config::setConfig(Generator::self()->idealConfig()); } void KScreenDaemon::configChanged() { kDebug() << "Change detected"; if (m_pendingSave) { return; } kDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { kDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { kDebug() << "displayBtn triggered"; if (m_timer->isActive()) { kDebug() << "Too fast cowboy"; return; } m_timer->start(); } void KScreenDaemon::resetDisplaySwitch() { kDebug(); m_iteration = 0; } void KScreenDaemon::applyGenericConfig() { if (m_iteration == 5) { m_iteration = 0; } setMonitorForChanges(true); m_iteration++; kDebug() << "displayButton: " << m_iteration; KDebug::Block genericConfig("Applying display switch"); KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration)); } void KScreenDaemon::lidClosedChanged(bool lidIsClosed) { KDebug::Block genericConfig(" Lid closed"); kDebug() << "Lid is closed:" << lidIsClosed; //If the laptop is closed, use ideal config WITHOUT saving it if (lidIsClosed) { setMonitorForChanges(false); KScreen::Config::setConfig(Generator::self()->idealConfig()); return; } //If the lid is open, restore config (or generate a new one if needed applyConfig(); } void KScreenDaemon::monitorConnectedChange() { if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); if (!m_monitoredConfig) { return; } KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); connect(output, SIGNAL(isConnectedChanged()), SLOT(resetDisplaySwitch())); } } void KScreenDaemon::setMonitorForChanges(bool enabled) { if (m_monitoring == enabled) { return; } kDebug() << "Monitor for changes: " << enabled; if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); if (!m_monitoredConfig) { return; } KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } m_monitoring = enabled; KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { if (m_monitoring) { enableMonitor(output); } else { disableMonitor(output); } } } void KScreenDaemon::scheduleMonitorChange() { QMetaObject::invokeMethod(this, "setMonitorForChanges", Qt::QueuedConnection, Q_ARG(bool, true)); } void KScreenDaemon::enableMonitor(KScreen::Output* output) { connect(output, SIGNAL(currentModeIdChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } void KScreenDaemon::disableMonitor(KScreen::Output* output) { disconnect(output, SIGNAL(currentModeIdChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(isEnabledChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(isPrimaryChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(outputChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(clonesChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(posChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(rotationChanged()), this, SLOT(configChanged())); } <commit_msg>Check if the backend is loaded correctly before doing anything.<commit_after>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "daemon.h" #include "serializer.h" #include "generator.h" #include "device.h" #include <QtCore/QTimer> #include <kdebug.h> #include <kdemacros.h> #include <kaction.h> #include <KLocalizedString> #include <KActionCollection> #include <KPluginFactory> #include <kscreen/config.h> #include <kscreen/configmonitor.h> K_PLUGIN_FACTORY(KScreenDaemonFactory, registerPlugin<KScreenDaemon>();) K_EXPORT_PLUGIN(KScreenDaemonFactory("kscreen", "kscreen")) KScreenDaemon::KScreenDaemon(QObject* parent, const QList< QVariant >& ) : KDEDModule(parent) , m_monitoredConfig(0) , m_iteration(0) , m_pendingSave(false) , m_monitoring(false) , m_timer(new QTimer()) { setenv("KSCREEN_BACKEND", "XRandR", 0); if (!KScreen::Config::loadBackend()) { kWarning() << "Couldn't load backend: " << getenv("KSCREEN_BACKEND"); return; } KActionCollection *coll = new KActionCollection(this); KAction* action = coll->addAction("display"); action->setText(i18n("Switch Display" )); action->setGlobalShortcut(KShortcut(Qt::Key_Display)); connect(Device::self(), SIGNAL(lidIsClosedChanged(bool,bool)), SLOT(lidClosedChanged(bool))); m_timer->setInterval(300); m_timer->setSingleShot(true); connect(m_timer, SIGNAL(timeout()), SLOT(applyGenericConfig())); connect(action, SIGNAL(triggered(bool)), SLOT(displayButton())); connect(Generator::self(), SIGNAL(ready()), SLOT(init())); monitorConnectedChange(); } KScreenDaemon::~KScreenDaemon() { Generator::destroy(); Device::destroy(); } void KScreenDaemon::init() { applyConfig(); } void KScreenDaemon::applyConfig() { kDebug() << "Applying config"; if (Serializer::configExists()) { applyKnownConfig(); return; } applyIdealConfig(); } void KScreenDaemon::applyKnownConfig() { kDebug() << "Applying known config"; setMonitorForChanges(false); KScreen::Config::setConfig(Serializer::config(Serializer::currentId())); QMetaObject::invokeMethod(this, "scheduleMonitorChange", Qt::QueuedConnection); } void KScreenDaemon::applyIdealConfig() { kDebug() << "Applying ideal config"; setMonitorForChanges(true); KScreen::Config::setConfig(Generator::self()->idealConfig()); } void KScreenDaemon::configChanged() { kDebug() << "Change detected"; if (m_pendingSave) { return; } kDebug() << "Scheduling screen save"; m_pendingSave = true; QMetaObject::invokeMethod(this, "saveCurrentConfig", Qt::QueuedConnection); } void KScreenDaemon::saveCurrentConfig() { kDebug() << "Saving current config"; m_pendingSave = false; Serializer::saveConfig(KScreen::Config::current()); } void KScreenDaemon::displayButton() { kDebug() << "displayBtn triggered"; if (m_timer->isActive()) { kDebug() << "Too fast cowboy"; return; } m_timer->start(); } void KScreenDaemon::resetDisplaySwitch() { kDebug(); m_iteration = 0; } void KScreenDaemon::applyGenericConfig() { if (m_iteration == 5) { m_iteration = 0; } setMonitorForChanges(true); m_iteration++; kDebug() << "displayButton: " << m_iteration; KDebug::Block genericConfig("Applying display switch"); KScreen::Config::setConfig(Generator::self()->displaySwitch(m_iteration)); } void KScreenDaemon::lidClosedChanged(bool lidIsClosed) { KDebug::Block genericConfig(" Lid closed"); kDebug() << "Lid is closed:" << lidIsClosed; //If the laptop is closed, use ideal config WITHOUT saving it if (lidIsClosed) { setMonitorForChanges(false); KScreen::Config::setConfig(Generator::self()->idealConfig()); return; } //If the lid is open, restore config (or generate a new one if needed applyConfig(); } void KScreenDaemon::monitorConnectedChange() { if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); if (!m_monitoredConfig) { return; } KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { connect(output, SIGNAL(isConnectedChanged()), SLOT(applyConfig())); connect(output, SIGNAL(isConnectedChanged()), SLOT(resetDisplaySwitch())); } } void KScreenDaemon::setMonitorForChanges(bool enabled) { if (m_monitoring == enabled) { return; } kDebug() << "Monitor for changes: " << enabled; if (!m_monitoredConfig) { m_monitoredConfig = KScreen::Config::current(); if (!m_monitoredConfig) { return; } KScreen::ConfigMonitor::instance()->addConfig(m_monitoredConfig); } m_monitoring = enabled; KScreen::OutputList outputs = m_monitoredConfig->outputs(); Q_FOREACH(KScreen::Output* output, outputs) { if (m_monitoring) { enableMonitor(output); } else { disableMonitor(output); } } } void KScreenDaemon::scheduleMonitorChange() { QMetaObject::invokeMethod(this, "setMonitorForChanges", Qt::QueuedConnection, Q_ARG(bool, true)); } void KScreenDaemon::enableMonitor(KScreen::Output* output) { connect(output, SIGNAL(currentModeIdChanged()), SLOT(configChanged())); connect(output, SIGNAL(isEnabledChanged()), SLOT(configChanged())); connect(output, SIGNAL(isPrimaryChanged()), SLOT(configChanged())); connect(output, SIGNAL(outputChanged()), SLOT(configChanged())); connect(output, SIGNAL(clonesChanged()), SLOT(configChanged())); connect(output, SIGNAL(posChanged()), SLOT(configChanged())); connect(output, SIGNAL(rotationChanged()), SLOT(configChanged())); } void KScreenDaemon::disableMonitor(KScreen::Output* output) { disconnect(output, SIGNAL(currentModeIdChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(isEnabledChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(isPrimaryChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(outputChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(clonesChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(posChanged()), this, SLOT(configChanged())); disconnect(output, SIGNAL(rotationChanged()), this, SLOT(configChanged())); } <|endoftext|>
<commit_before>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "device.h" #include "kded/freedesktop_interface.h" Device* Device::m_instance = 0; Device* Device::self() { if (!Device::m_instance) { m_instance = new Device(); } return m_instance; } void Device::destroy() { delete m_instance; m_instance = 0; } Device::Device(QObject* parent) : QObject(parent) , m_isReady(false) , m_isLaptop(false) , m_isLidClosed(false) , m_isDocked(false) { m_freedesktop = new OrgFreedesktopDBusPropertiesInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", QDBusConnection::systemBus()); QDBusConnection::systemBus().connect("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", "Changed", this, SLOT(changed())); QMetaObject::invokeMethod(this, "init", Qt::QueuedConnection); } Device::~Device() { delete m_freedesktop; } void Device::init() { fetchIsLaptop(); } void Device::changed() { fetchLidIsClosed(); } void Device::setReady() { m_isReady = true; Q_EMIT ready(); } bool Device::isReady() { return m_isReady; } bool Device::isLaptop() { return m_isLaptop; } bool Device::isLidClosed() { return m_isLidClosed; } bool Device::isDocked() { return m_isDocked; } void Device::fetchIsLaptop() { QDBusPendingReply<QVariant> res = m_freedesktop->Get("org.freedesktop.UPower", "LidIsPresent"); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(res); connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(isLaptopFetched(QDBusPendingCallWatcher*))); } void Device::isLaptopFetched(QDBusPendingCallWatcher* watcher) { const QDBusPendingReply<QVariant> reply = *watcher; if (reply.isError()) { qDebug() << "Couldn't get if the device is a laptop: " << reply.error().message(); return; } m_isLaptop = reply.value().toBool(); watcher->deleteLater(); if (!m_isLaptop) { setReady(); return; } fetchLidIsClosed(); } void Device::fetchLidIsClosed() { QDBusPendingReply<QVariant> res = m_freedesktop->Get("org.freedesktop.UPower", "LidIsClosed"); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(res); connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(isLidClosedFetched(QDBusPendingCallWatcher*))); } void Device::isLidClosedFetched(QDBusPendingCallWatcher* watcher) { const QDBusPendingReply<QVariant> reply = *watcher; if (reply.isError()) { qDebug() << "Couldn't get if the device is a laptop: " << reply.error().message(); return; } bool oldValue = m_isLidClosed;; m_isLidClosed = reply.value().toBool(); watcher->deleteLater(); if (m_isReady && (oldValue != m_isLidClosed)) { Q_EMIT lidIsClosedChanged(m_isLidClosed, oldValue); } fetchIsDocked(); } void Device::fetchIsDocked() { setReady(); }<commit_msg>minor fixes<commit_after>/************************************************************************************* * Copyright (C) 2012 by Alejandro Fiestas Olivares <afiestas@kde.org> * * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * *************************************************************************************/ #include "device.h" #include "kded/freedesktop_interface.h" Device* Device::m_instance = 0; Device* Device::self() { if (!Device::m_instance) { m_instance = new Device(); } return m_instance; } void Device::destroy() { delete m_instance; m_instance = 0; } Device::Device(QObject* parent) : QObject(parent) , m_isReady(false) , m_isLaptop(false) , m_isLidClosed(false) , m_isDocked(false) { m_freedesktop = new OrgFreedesktopDBusPropertiesInterface("org.freedesktop.UPower", "/org/freedesktop/UPower", QDBusConnection::systemBus()); QDBusConnection::systemBus().connect("org.freedesktop.UPower", "/org/freedesktop/UPower", "org.freedesktop.UPower", "Changed", this, SLOT(changed())); QMetaObject::invokeMethod(this, "init", Qt::QueuedConnection); } Device::~Device() { delete m_freedesktop; } void Device::init() { fetchIsLaptop(); } void Device::changed() { fetchLidIsClosed(); } void Device::setReady() { m_isReady = true; Q_EMIT ready(); } bool Device::isReady() { return m_isReady; } bool Device::isLaptop() { return m_isLaptop; } bool Device::isLidClosed() { return m_isLidClosed; } bool Device::isDocked() { return m_isDocked; } void Device::fetchIsLaptop() { QDBusPendingReply<QVariant> res = m_freedesktop->Get("org.freedesktop.UPower", "LidIsPresent"); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(res); connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(isLaptopFetched(QDBusPendingCallWatcher*))); } void Device::isLaptopFetched(QDBusPendingCallWatcher* watcher) { const QDBusPendingReply<QVariant> reply = *watcher; if (reply.isError()) { qDebug() << "Couldn't get if the device is a laptop: " << reply.error().message(); return; } m_isLaptop = reply.value().toBool(); watcher->deleteLater(); if (!m_isLaptop) { setReady(); return; } fetchLidIsClosed(); } void Device::fetchLidIsClosed() { QDBusPendingReply<QVariant> res = m_freedesktop->Get("org.freedesktop.UPower", "LidIsClosed"); QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(res); connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), this, SLOT(isLidClosedFetched(QDBusPendingCallWatcher*))); } void Device::isLidClosedFetched(QDBusPendingCallWatcher* watcher) { const QDBusPendingReply<QVariant> reply = *watcher; if (reply.isError()) { qDebug() << "Couldn't get if the laptop has the lid closed: " << reply.error().message(); return; } bool oldValue = m_isLidClosed; m_isLidClosed = reply.value().toBool(); watcher->deleteLater(); if (m_isReady && (oldValue != m_isLidClosed)) { Q_EMIT lidIsClosedChanged(m_isLidClosed, oldValue); } fetchIsDocked(); } void Device::fetchIsDocked() { setReady(); } <|endoftext|>
<commit_before>#include "buddy.hh" #if BUDDY_DEBUG #include "kstream.hh" #endif #include <cassert> #include <cstring> #include <iterator> using namespace std; buddy_allocator::buddy_allocator(void *base, size_t len) { uintptr_t end = (uintptr_t)base + len; // Use a linear allocator to allocate buddy bitmaps. // XXX(Austin) Should we check if we have more unaligned space at // the end? Currently, we skip 16 megs between each buddy region. size_t nBlocks = len / MIN_SIZE; for (size_t i = 0; i < MAX_ORDER; ++i) { size_t bitmapSize = (nBlocks + 7) / 8; orders[i].bitmap = (unsigned char*)base; memset(orders[i].bitmap, 0, bitmapSize); base = (char*)base + bitmapSize; #if BUDDY_DEBUG orders[i].debug = (unsigned char*)base; memset(orders[i].debug, 0, bitmapSize); base = (char*)base + bitmapSize; #endif nBlocks /= 2; } // The MAX_ORDER bitmap is unused because it doesn't have buddy // pairs. orders[MAX_ORDER].bitmap = nullptr; #if BUDDY_DEBUG orders[MAX_ORDER].debug = nullptr; #endif // Round both bounds to multiples of MIN_SIZE << MAX_ORDER. Without // this, some blocks wouldn't have buddies, which would complicate // other logic. this->base = ((uintptr_t)base + MAX_SIZE - 1) & ~(MAX_SIZE - 1); limit = end & ~(MAX_SIZE - 1); assert(this->base < limit); // Create block list for (uintptr_t block = this->base; block < limit; block += MAX_SIZE) orders[MAX_ORDER].blocks.push_back((struct block*)block); } void* buddy_allocator::alloc_order(size_t order) { // Is a block of this order available? if (!orders[order].blocks.empty()) { // Get a block struct block *block = &orders[order].blocks.front(); orders[order].blocks.pop_front(); // Mark it as allocated if (order < MAX_ORDER) { bool state = flip_bit(block, order); // Now both buddies must be allocated (otherwise they would have // been promoted). assert(state == 0); mark_allocated(block, order, true); } return (void*)block; } else if (order == MAX_ORDER) { return nullptr; } else { // We need to split a block. We'll allocate one of order + 1, use // the first half of it and add the second half to order's free // list. void *parent = alloc_order(order + 1); if (!parent) return nullptr; struct block *second_half = (struct block*)((char*)parent + (MIN_SIZE << order)); orders[order].blocks.push_front(second_half); // Mark this pair as half-allocated bool state = flip_bit(parent, order); assert(state == 1); mark_allocated(parent, order, true); return parent; } } void buddy_allocator::free_order(void *ptr, size_t order) { assert(base <= (uintptr_t)ptr && (uintptr_t)ptr < limit); #if BUDDY_DEBUG if (order < MAX_ORDER) if (!is_allocated(ptr, order)) spanic.println("double free or too-small free of ", ptr, " of size ", MIN_SIZE << order, " (order ", order, ")"); if (order > 0) if (is_allocated(ptr, order - 1)) spanic.println("too-large free of ", ptr, " of size ", MIN_SIZE << order, " (order ", order, ")"); #endif mark_allocated(ptr, order, false); if (order < MAX_ORDER && flip_bit(ptr, order) == 0) { // This block's buddy is also free. Remove the buddy from its // list, combine them, and free to the higher order. uintptr_t buddy = (uintptr_t)ptr ^ ((uintptr_t)MIN_SIZE << order); orders[order].blocks.erase( orders[order].blocks.iterator_to((struct block*)buddy)); uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order); free_order((void*)parent, order + 1); } else { // This block's buddy is allocated. Release this block to the // current order. orders[order].blocks.push_front((struct block*)ptr); } } bool buddy_allocator::flip_bit(void *ptr, size_t order) { size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1); unsigned char mask = 1 << (bit % 8); return (orders[order].bitmap[bit / 8] ^= mask) & mask; } #if BUDDY_DEBUG bool buddy_allocator::is_allocated(void *ptr, size_t order) { size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1); unsigned char mask = 1 << (bit % 8); uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order); bool debug = orders[order].debug[bit / 8] & mask; if ((uintptr_t)ptr == parent) // First of buddy pair return debug; else // Second of buddy pair return debug ^ !!(orders[order].bitmap[bit / 8] & mask); } void buddy_allocator::mark_allocated(void *ptr, std::size_t order, bool allocated) { uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order); if ((uintptr_t)ptr != parent) return; size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1); unsigned char mask = 1 << (bit % 8); if (allocated) orders[order].debug[bit / 8] |= mask; else orders[order].debug[bit / 8] &= ~mask; } #else void buddy_allocator::mark_allocated(void *ptr, std::size_t order, bool allocated) { } #endif void buddy_allocator::get_stats(stats *out) const { out->free = 0; for (size_t order = 0; order <= MAX_ORDER; ++order) { out->nfree[order] = 0; for (auto &b : orders[order].blocks) { (void)b; // Hush g++ ++out->nfree[order]; } out->free += out->nfree[order] * (MIN_SIZE << order); } } <commit_msg>buddy: Avoid nullptr dereference in debugging code<commit_after>#include "buddy.hh" #if BUDDY_DEBUG #include "kstream.hh" #endif #include <cassert> #include <cstring> #include <iterator> using namespace std; buddy_allocator::buddy_allocator(void *base, size_t len) { uintptr_t end = (uintptr_t)base + len; // Use a linear allocator to allocate buddy bitmaps. // XXX(Austin) Should we check if we have more unaligned space at // the end? Currently, we skip 16 megs between each buddy region. size_t nBlocks = len / MIN_SIZE; for (size_t i = 0; i < MAX_ORDER; ++i) { size_t bitmapSize = (nBlocks + 7) / 8; orders[i].bitmap = (unsigned char*)base; memset(orders[i].bitmap, 0, bitmapSize); base = (char*)base + bitmapSize; #if BUDDY_DEBUG orders[i].debug = (unsigned char*)base; memset(orders[i].debug, 0, bitmapSize); base = (char*)base + bitmapSize; #endif nBlocks /= 2; } // The MAX_ORDER bitmap is unused because it doesn't have buddy // pairs. orders[MAX_ORDER].bitmap = nullptr; #if BUDDY_DEBUG orders[MAX_ORDER].debug = nullptr; #endif // Round both bounds to multiples of MIN_SIZE << MAX_ORDER. Without // this, some blocks wouldn't have buddies, which would complicate // other logic. this->base = ((uintptr_t)base + MAX_SIZE - 1) & ~(MAX_SIZE - 1); limit = end & ~(MAX_SIZE - 1); assert(this->base < limit); // Create block list for (uintptr_t block = this->base; block < limit; block += MAX_SIZE) orders[MAX_ORDER].blocks.push_back((struct block*)block); } void* buddy_allocator::alloc_order(size_t order) { // Is a block of this order available? if (!orders[order].blocks.empty()) { // Get a block struct block *block = &orders[order].blocks.front(); orders[order].blocks.pop_front(); // Mark it as allocated if (order < MAX_ORDER) { bool state = flip_bit(block, order); // Now both buddies must be allocated (otherwise they would have // been promoted). assert(state == 0); mark_allocated(block, order, true); } return (void*)block; } else if (order == MAX_ORDER) { return nullptr; } else { // We need to split a block. We'll allocate one of order + 1, use // the first half of it and add the second half to order's free // list. void *parent = alloc_order(order + 1); if (!parent) return nullptr; struct block *second_half = (struct block*)((char*)parent + (MIN_SIZE << order)); orders[order].blocks.push_front(second_half); // Mark this pair as half-allocated bool state = flip_bit(parent, order); assert(state == 1); mark_allocated(parent, order, true); return parent; } } void buddy_allocator::free_order(void *ptr, size_t order) { assert(base <= (uintptr_t)ptr && (uintptr_t)ptr < limit); #if BUDDY_DEBUG if (order < MAX_ORDER) if (!is_allocated(ptr, order)) spanic.println("double free or too-small free of ", ptr, " of size ", MIN_SIZE << order, " (order ", order, ")"); if (order > 0) if (is_allocated(ptr, order - 1)) spanic.println("too-large free of ", ptr, " of size ", MIN_SIZE << order, " (order ", order, ")"); #endif mark_allocated(ptr, order, false); if (order < MAX_ORDER && flip_bit(ptr, order) == 0) { // This block's buddy is also free. Remove the buddy from its // list, combine them, and free to the higher order. uintptr_t buddy = (uintptr_t)ptr ^ ((uintptr_t)MIN_SIZE << order); orders[order].blocks.erase( orders[order].blocks.iterator_to((struct block*)buddy)); uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order); free_order((void*)parent, order + 1); } else { // This block's buddy is allocated. Release this block to the // current order. orders[order].blocks.push_front((struct block*)ptr); } } bool buddy_allocator::flip_bit(void *ptr, size_t order) { size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1); unsigned char mask = 1 << (bit % 8); return (orders[order].bitmap[bit / 8] ^= mask) & mask; } #if BUDDY_DEBUG bool buddy_allocator::is_allocated(void *ptr, size_t order) { size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1); unsigned char mask = 1 << (bit % 8); uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order); bool debug = orders[order].debug[bit / 8] & mask; if ((uintptr_t)ptr == parent) // First of buddy pair return debug; else // Second of buddy pair return debug ^ !!(orders[order].bitmap[bit / 8] & mask); } void buddy_allocator::mark_allocated(void *ptr, std::size_t order, bool allocated) { if (order == MAX_ORDER) return; uintptr_t parent = (uintptr_t)ptr & ~((uintptr_t)MIN_SIZE << order); if ((uintptr_t)ptr != parent) return; size_t bit = (((uintptr_t)ptr - base) / MIN_SIZE) >> (order + 1); unsigned char mask = 1 << (bit % 8); if (allocated) orders[order].debug[bit / 8] |= mask; else orders[order].debug[bit / 8] &= ~mask; } #else void buddy_allocator::mark_allocated(void *ptr, std::size_t order, bool allocated) { } #endif void buddy_allocator::get_stats(stats *out) const { out->free = 0; for (size_t order = 0; order <= MAX_ORDER; ++order) { out->nfree[order] = 0; for (auto &b : orders[order].blocks) { (void)b; // Hush g++ ++out->nfree[order]; } out->free += out->nfree[order] * (MIN_SIZE << order); } } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" #include "material.h" #include "renderer.h" #include "Globals.h" #include "utilities.h" #include "Logs.h" opengl_material::opengl_material() { for (size_t i = 0; i < params.size(); i++) params[i] = glm::vec4(std::numeric_limits<float>::quiet_NaN()); } bool opengl_material::deserialize( cParser &Input, bool const Loadnow ) { parse_info = std::make_unique<parse_info_s>(); bool result { false }; while( true == deserialize_mapping( Input, 0, Loadnow ) ) { result = true; // once would suffice but, eh } return result; } void opengl_material::log_error(const std::string &str) { ErrorLog("bad material: " + name + ": " + str, logtype::material); } void opengl_material::finalize(bool Loadnow) { if (parse_info) { for (auto it : parse_info->tex_mapping) { std::string key = it.first; std::string value = it.second.name; if (key.size() > 0 && key[0] != '_') { size_t num = std::stoi(key) - 1; if (num < gl::MAX_TEXTURES) textures[num] = GfxRenderer.Fetch_Texture(value, Loadnow); else log_error("invalid texture binding: " + std::to_string(num)); } else if (key.size() > 2) { key.erase(0, 1); key.pop_back(); if (shader && shader->texture_conf.find(key) != shader->texture_conf.end()) textures[shader->texture_conf[key].id] = GfxRenderer.Fetch_Texture(value, Loadnow); else log_error("unknown texture binding: " + key); } else log_error("unrecognized texture binding: " + key); } if (!shader) { if (textures[0] == null_handle) { log_error("shader not specified, assuming \"default_0\""); shader = GfxRenderer.Fetch_Shader("default_0"); } else if (textures[1] == null_handle) { log_error("shader not specified, assuming \"default_1\""); shader = GfxRenderer.Fetch_Shader("default_1"); } else if (textures[2] == null_handle) { log_error("shader not specified, assuming \"default_2\""); shader = GfxRenderer.Fetch_Shader("default_2"); } } for (auto it : parse_info->param_mapping) { std::string key = it.first; glm::vec4 value = it.second.data; if (key.size() > 1 && key[0] != '_') { size_t num = std::stoi(key) - 1; if (num < gl::MAX_PARAMS) params[num] = value; else log_error("invalid param binding: " + std::to_string(num)); } else if (key.size() > 2) { key.erase(0, 1); key.pop_back(); if (shader->param_conf.find(key) != shader->param_conf.end()) { gl::shader::param_entry entry = shader->param_conf[key]; for (size_t i = 0; i < entry.size; i++) params[entry.location][entry.offset + i] = value[i]; } else log_error("unknown param binding: " + key); } else log_error("unrecognized param binding: " + key); } parse_info.reset(); } for (auto it : shader->param_conf) { gl::shader::param_entry entry = it.second; if (std::isnan(params[entry.location][entry.offset])) { float value = std::numeric_limits<float>::quiet_NaN(); if (entry.defaultparam == gl::shader::defaultparam_e::one) value = 1.0f; else if (entry.defaultparam == gl::shader::defaultparam_e::zero) value = 0.0f; else if (entry.defaultparam == gl::shader::defaultparam_e::required) log_error("unspecified required param: " + it.first); else if (entry.defaultparam != gl::shader::defaultparam_e::nan) { params_state.push_back(entry); continue; } for (size_t i = 0; i < entry.size; i++) params[entry.location][entry.offset + i] = value; } } for (auto it : shader->texture_conf) { gl::shader::texture_entry &entry = it.second; texture_handle handle = textures[entry.id]; if (handle) GfxRenderer.Texture(handle).set_components_hint((GLint)entry.components); } } // imports member data pair from the config file bool opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool const Loadnow ) { // token can be a key or block end std::string key = Input.getToken<std::string>( true, "\n\r\t ,;[]" ); if( ( true == key.empty() ) || ( key == "}" ) ) { return false; } auto value { Input.getToken<std::string>( true, "\n\r\t ,;" ) }; if( Priority != -1 ) { // regular attribute processing mode if( key == Global.Weather ) { // weather textures override generic (pri 0) and seasonal (pri 1) textures // seasonal weather textures (pri 1+2=3) override generic weather (pri 2) textures while( true == deserialize_mapping( Input, Priority + 2, Loadnow ) ) { ; // all work is done in the header } } else if( key == Global.Season ) { // seasonal textures override generic textures while( true == deserialize_mapping( Input, 1, Loadnow ) ) { ; // all work is done in the header } } else if (key.compare(0, 7, "texture") == 0) { key.erase(0, 7); std::replace(value.begin(), value.end(), '\\', '/'); auto it = parse_info->tex_mapping.find(key); if (it == parse_info->tex_mapping.end()) parse_info->tex_mapping.emplace(std::make_pair(key, parse_info_s::tex_def({ value, Priority }))); else if (Priority > it->second.priority) { parse_info->tex_mapping.erase(it); parse_info->tex_mapping.emplace(std::make_pair(key, parse_info_s::tex_def({ value, Priority }))); } /* size_t num = std::stoi(key) - 1; if (num < textures.size() && (textures[num] == null_handle || Priority > m_texture_priority[num])) { std::replace(value.begin(), value.end(), '\\', '/'); textures[num] = GfxRenderer.Fetch_Texture( value, Loadnow ); m_texture_priority[num] = Priority; } */ } else if (key.compare(0, 5, "param") == 0) { key.erase(0, 5); std::istringstream stream(value); glm::vec4 data; stream >> data.r; stream >> data.g; stream >> data.b; stream >> data.a; auto it = parse_info->param_mapping.find(key); if (it == parse_info->param_mapping.end()) parse_info->param_mapping.emplace(std::make_pair(key, parse_info_s::param_def({ data, Priority }))); else if (Priority > it->second.priority) { parse_info->param_mapping.erase(it); parse_info->param_mapping.emplace(std::make_pair(key, parse_info_s::param_def({ data, Priority }))); } /* size_t num = std::stoi(key) - 1; if (num < params.size() && (Priority > m_param_priority[num])) { std::istringstream stream(value); stream >> params[num].r; stream >> params[num].g; stream >> params[num].b; stream >> params[num].a; m_param_priority[num] = Priority; }*/ } else if (key == "shader:" && (!shader || Priority > m_shader_priority)) { try { shader = GfxRenderer.Fetch_Shader(value); m_shader_priority = Priority; } catch (gl::shader_exception const &e) { log_error("invalid shader: " + std::string(e.what())); } } else if (key == "opacity:" && Priority > m_opacity_priority) { opacity = std::stoi(value); //m7t: handle exception m_opacity_priority = Priority; } else if (key == "selfillum:" && Priority > m_selfillum_priority) { selfillum = std::stoi(value); //m7t: handle exception m_selfillum_priority = Priority; } else if( value == "{" ) { // unrecognized or ignored token, but comes with attribute block and potential further nesting // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { ; // all work is done in the header } } } else { // discard mode; ignores all retrieved tokens if( value == "{" ) { // ignored tokens can come with their own blocks, ignore these recursively // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { ; // all work is done in the header } } } return true; // return value marks a key: value pair was extracted, nothing about whether it's recognized } float opengl_material::get_or_guess_opacity() { if (!std::isnan(opacity)) return opacity; if (textures[0] != null_handle) { opengl_texture &tex = GfxRenderer.Texture(textures[0]); if (tex.has_alpha) return 0.0f; else return 0.5f; } return 0.0f; } // create material object from data stored in specified file. // NOTE: the deferred load parameter is passed to textures defined by material, the material itself is always loaded immediately material_handle material_manager::create( std::string const &Filename, bool const Loadnow ) { auto filename { Filename }; if( filename.find( '|' ) != std::string::npos ) filename.erase( filename.find( '|' ) ); // po | może być nazwa kolejnej tekstury erase_extension( filename ); if( filename[ 0 ] == '/' ) { // filename can potentially begin with a slash, and we don't need it filename.erase( 0, 1 ); } // try to locate requested material in the databank auto const databanklookup { find_in_databank( filename ) }; if( databanklookup != null_handle ) { return databanklookup; } // if this fails, try to look for it on disk opengl_material material; auto const disklookup { find_on_disk( filename ) }; if( false == disklookup.first.empty() ) { cParser materialparser( disklookup.first + disklookup.second, cParser::buffer_FILE ); if( false == material.deserialize( materialparser, Loadnow ) ) { // deserialization failed but the .mat file does exist, so we give up at this point return null_handle; } material.name = disklookup.first; } else { // if there's no .mat file, this could be legacy method of referring just to diffuse texture directly, make a material out of it in such case material.textures[0] = GfxRenderer.Fetch_Texture( Filename, Loadnow ); if( material.textures[0] == null_handle ) { // if there's also no texture, give up return null_handle; } // material would attach default shader anyway, but it would spit to error log material.shader = GfxRenderer.Fetch_Shader("default_1"); // use texture path and name to tell the newly created materials apart filename = GfxRenderer.Texture( material.textures[0] ).name; erase_extension( filename ); material.name = filename; } material.finalize(Loadnow); material_handle handle = m_materials.size(); m_materialmappings.emplace(material.name, handle); m_materials.emplace_back( std::move(material) ); return handle; }; // checks whether specified material is in the material bank. returns handle to the material, or a null handle material_handle material_manager::find_in_databank( std::string const &Materialname ) const { std::vector<std::string> const filenames { Global.asCurrentTexturePath + Materialname, Materialname, szTexturePath + Materialname }; for( auto const &filename : filenames ) { auto const lookup { m_materialmappings.find( filename ) }; if( lookup != m_materialmappings.end() ) { return lookup->second; } } // all lookups failed return null_handle; } // checks whether specified file exists. // NOTE: technically could be static, but we might want to switch from global texture path to instance-specific at some point std::pair<std::string, std::string> material_manager::find_on_disk( std::string const &Materialname ) const { return ( FileExists( { Global.asCurrentTexturePath + Materialname, Materialname, szTexturePath + Materialname }, { ".mat" } ) ); } //--------------------------------------------------------------------------- <commit_msg>log missing material texture errors<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "stdafx.h" #include "material.h" #include "renderer.h" #include "Globals.h" #include "utilities.h" #include "Logs.h" opengl_material::opengl_material() { for (size_t i = 0; i < params.size(); i++) params[i] = glm::vec4(std::numeric_limits<float>::quiet_NaN()); } bool opengl_material::deserialize( cParser &Input, bool const Loadnow ) { parse_info = std::make_unique<parse_info_s>(); bool result { false }; while( true == deserialize_mapping( Input, 0, Loadnow ) ) { result = true; // once would suffice but, eh } return result; } void opengl_material::log_error(const std::string &str) { ErrorLog("bad material: " + name + ": " + str, logtype::material); } void opengl_material::finalize(bool Loadnow) { if (parse_info) { for (auto it : parse_info->tex_mapping) { std::string key = it.first; std::string value = it.second.name; if (key.size() > 0 && key[0] != '_') { size_t num = std::stoi(key) - 1; if (num < gl::MAX_TEXTURES) textures[num] = GfxRenderer.Fetch_Texture(value, Loadnow); else log_error("invalid texture binding: " + std::to_string(num)); } else if (key.size() > 2) { key.erase(0, 1); key.pop_back(); if (shader && shader->texture_conf.find(key) != shader->texture_conf.end()) textures[shader->texture_conf[key].id] = GfxRenderer.Fetch_Texture(value, Loadnow); else log_error("unknown texture binding: " + key); } else log_error("unrecognized texture binding: " + key); } if (!shader) { if (textures[0] == null_handle) { log_error("shader not specified, assuming \"default_0\""); shader = GfxRenderer.Fetch_Shader("default_0"); } else if (textures[1] == null_handle) { log_error("shader not specified, assuming \"default_1\""); shader = GfxRenderer.Fetch_Shader("default_1"); } else if (textures[2] == null_handle) { log_error("shader not specified, assuming \"default_2\""); shader = GfxRenderer.Fetch_Shader("default_2"); } } for (auto it : parse_info->param_mapping) { std::string key = it.first; glm::vec4 value = it.second.data; if (key.size() > 1 && key[0] != '_') { size_t num = std::stoi(key) - 1; if (num < gl::MAX_PARAMS) params[num] = value; else log_error("invalid param binding: " + std::to_string(num)); } else if (key.size() > 2) { key.erase(0, 1); key.pop_back(); if (shader->param_conf.find(key) != shader->param_conf.end()) { gl::shader::param_entry entry = shader->param_conf[key]; for (size_t i = 0; i < entry.size; i++) params[entry.location][entry.offset + i] = value[i]; } else log_error("unknown param binding: " + key); } else log_error("unrecognized param binding: " + key); } parse_info.reset(); } for (auto it : shader->param_conf) { gl::shader::param_entry entry = it.second; if (std::isnan(params[entry.location][entry.offset])) { float value = std::numeric_limits<float>::quiet_NaN(); if (entry.defaultparam == gl::shader::defaultparam_e::one) value = 1.0f; else if (entry.defaultparam == gl::shader::defaultparam_e::zero) value = 0.0f; else if (entry.defaultparam == gl::shader::defaultparam_e::required) log_error("unspecified required param: " + it.first); else if (entry.defaultparam != gl::shader::defaultparam_e::nan) { params_state.push_back(entry); continue; } for (size_t i = 0; i < entry.size; i++) params[entry.location][entry.offset + i] = value; } } for (auto it : shader->texture_conf) { gl::shader::texture_entry &entry = it.second; texture_handle handle = textures[entry.id]; if (handle) GfxRenderer.Texture(handle).set_components_hint((GLint)entry.components); else log_error("missing texture: " + it.first); } } // imports member data pair from the config file bool opengl_material::deserialize_mapping( cParser &Input, int const Priority, bool const Loadnow ) { // token can be a key or block end std::string key = Input.getToken<std::string>( true, "\n\r\t ,;[]" ); if( ( true == key.empty() ) || ( key == "}" ) ) { return false; } auto value { Input.getToken<std::string>( true, "\n\r\t ,;" ) }; if( Priority != -1 ) { // regular attribute processing mode if( key == Global.Weather ) { // weather textures override generic (pri 0) and seasonal (pri 1) textures // seasonal weather textures (pri 1+2=3) override generic weather (pri 2) textures while( true == deserialize_mapping( Input, Priority + 2, Loadnow ) ) { ; // all work is done in the header } } else if( key == Global.Season ) { // seasonal textures override generic textures while( true == deserialize_mapping( Input, 1, Loadnow ) ) { ; // all work is done in the header } } else if (key.compare(0, 7, "texture") == 0) { key.erase(0, 7); std::replace(value.begin(), value.end(), '\\', '/'); auto it = parse_info->tex_mapping.find(key); if (it == parse_info->tex_mapping.end()) parse_info->tex_mapping.emplace(std::make_pair(key, parse_info_s::tex_def({ value, Priority }))); else if (Priority > it->second.priority) { parse_info->tex_mapping.erase(it); parse_info->tex_mapping.emplace(std::make_pair(key, parse_info_s::tex_def({ value, Priority }))); } /* size_t num = std::stoi(key) - 1; if (num < textures.size() && (textures[num] == null_handle || Priority > m_texture_priority[num])) { std::replace(value.begin(), value.end(), '\\', '/'); textures[num] = GfxRenderer.Fetch_Texture( value, Loadnow ); m_texture_priority[num] = Priority; } */ } else if (key.compare(0, 5, "param") == 0) { key.erase(0, 5); std::istringstream stream(value); glm::vec4 data; stream >> data.r; stream >> data.g; stream >> data.b; stream >> data.a; auto it = parse_info->param_mapping.find(key); if (it == parse_info->param_mapping.end()) parse_info->param_mapping.emplace(std::make_pair(key, parse_info_s::param_def({ data, Priority }))); else if (Priority > it->second.priority) { parse_info->param_mapping.erase(it); parse_info->param_mapping.emplace(std::make_pair(key, parse_info_s::param_def({ data, Priority }))); } /* size_t num = std::stoi(key) - 1; if (num < params.size() && (Priority > m_param_priority[num])) { std::istringstream stream(value); stream >> params[num].r; stream >> params[num].g; stream >> params[num].b; stream >> params[num].a; m_param_priority[num] = Priority; }*/ } else if (key == "shader:" && (!shader || Priority > m_shader_priority)) { try { shader = GfxRenderer.Fetch_Shader(value); m_shader_priority = Priority; } catch (gl::shader_exception const &e) { log_error("invalid shader: " + std::string(e.what())); } } else if (key == "opacity:" && Priority > m_opacity_priority) { opacity = std::stoi(value); //m7t: handle exception m_opacity_priority = Priority; } else if (key == "selfillum:" && Priority > m_selfillum_priority) { selfillum = std::stoi(value); //m7t: handle exception m_selfillum_priority = Priority; } else if( value == "{" ) { // unrecognized or ignored token, but comes with attribute block and potential further nesting // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { ; // all work is done in the header } } } else { // discard mode; ignores all retrieved tokens if( value == "{" ) { // ignored tokens can come with their own blocks, ignore these recursively // go through it and discard the content while( true == deserialize_mapping( Input, -1, Loadnow ) ) { ; // all work is done in the header } } } return true; // return value marks a key: value pair was extracted, nothing about whether it's recognized } float opengl_material::get_or_guess_opacity() { if (!std::isnan(opacity)) return opacity; if (textures[0] != null_handle) { opengl_texture &tex = GfxRenderer.Texture(textures[0]); if (tex.has_alpha) return 0.0f; else return 0.5f; } return 0.0f; } // create material object from data stored in specified file. // NOTE: the deferred load parameter is passed to textures defined by material, the material itself is always loaded immediately material_handle material_manager::create( std::string const &Filename, bool const Loadnow ) { auto filename { Filename }; if( filename.find( '|' ) != std::string::npos ) filename.erase( filename.find( '|' ) ); // po | może być nazwa kolejnej tekstury erase_extension( filename ); if( filename[ 0 ] == '/' ) { // filename can potentially begin with a slash, and we don't need it filename.erase( 0, 1 ); } // try to locate requested material in the databank auto const databanklookup { find_in_databank( filename ) }; if( databanklookup != null_handle ) { return databanklookup; } // if this fails, try to look for it on disk opengl_material material; auto const disklookup { find_on_disk( filename ) }; if( false == disklookup.first.empty() ) { cParser materialparser( disklookup.first + disklookup.second, cParser::buffer_FILE ); if( false == material.deserialize( materialparser, Loadnow ) ) { // deserialization failed but the .mat file does exist, so we give up at this point return null_handle; } material.name = disklookup.first; } else { // if there's no .mat file, this could be legacy method of referring just to diffuse texture directly, make a material out of it in such case material.textures[0] = GfxRenderer.Fetch_Texture( Filename, Loadnow ); if( material.textures[0] == null_handle ) { // if there's also no texture, give up return null_handle; } // material would attach default shader anyway, but it would spit to error log material.shader = GfxRenderer.Fetch_Shader("default_1"); // use texture path and name to tell the newly created materials apart filename = GfxRenderer.Texture( material.textures[0] ).name; erase_extension( filename ); material.name = filename; } material.finalize(Loadnow); material_handle handle = m_materials.size(); m_materialmappings.emplace(material.name, handle); m_materials.emplace_back( std::move(material) ); return handle; }; // checks whether specified material is in the material bank. returns handle to the material, or a null handle material_handle material_manager::find_in_databank( std::string const &Materialname ) const { std::vector<std::string> const filenames { Global.asCurrentTexturePath + Materialname, Materialname, szTexturePath + Materialname }; for( auto const &filename : filenames ) { auto const lookup { m_materialmappings.find( filename ) }; if( lookup != m_materialmappings.end() ) { return lookup->second; } } // all lookups failed return null_handle; } // checks whether specified file exists. // NOTE: technically could be static, but we might want to switch from global texture path to instance-specific at some point std::pair<std::string, std::string> material_manager::find_on_disk( std::string const &Materialname ) const { return ( FileExists( { Global.asCurrentTexturePath + Materialname, Materialname, szTexturePath + Materialname }, { ".mat" } ) ); } //--------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include "Genes/Pawn_Advancement_Gene.h" #include <string> #include "Game/Board.h" #include "Pieces/Piece.h" #include "Genes/Piece_Strength_Gene.h" #include "Utility.h" Pawn_Advancement_Gene::Pawn_Advancement_Gene(const std::shared_ptr<const Piece_Strength_Gene>& piece_strength_source_in) : Gene(0.0), piece_strength_source(piece_strength_source_in), promoted_pawn_bonus(0.0) { } void Pawn_Advancement_Gene::reset_properties() const { reset_base_properties(); properties["Promoted Pawn Bonus"] = promoted_pawn_bonus; } void Pawn_Advancement_Gene::load_properties() { load_base_properties(); promoted_pawn_bonus = properties["Promoted Pawn Bonus"]; } double Pawn_Advancement_Gene::score_board(const Board& board, Color color) const { double score = 0.0; for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 1; rank <= 8; ++rank) { auto piece = board.piece_on_square(file, rank); if(piece && piece->color() == color && toupper(piece->fen_symbol()) == 'P') { // 1 point per pawn + 1 point per move towards promotion score += std::abs((color == WHITE ? 1 : 8) - rank); } } } for(size_t i = (color == WHITE ? 0 : 1); i < board.get_game_record().size(); i += 2) { if(board.get_game_record()[i].find('=') != std::string::npos) { auto piece_symbol = toupper(String::split(board.get_game_record()[i], "=")[1][0]); // char score += promoted_pawn_bonus*piece_strength_source->piece_value(piece_symbol); } } return score; } Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const { return new Pawn_Advancement_Gene(*this); } std::string Pawn_Advancement_Gene::name() const { return "Pawn Advancement Gene"; } void Pawn_Advancement_Gene::mutate() { Gene::mutate(); promoted_pawn_bonus += Random::random_normal(1.0); promoted_pawn_bonus = std::max(promoted_pawn_bonus, 0.0); } void Pawn_Advancement_Gene::reset_piece_strength_gene(const std::shared_ptr<const Piece_Strength_Gene>& psg) { piece_strength_source = psg; } <commit_msg>Pawn_Advancement_Gene board_score() change<commit_after>#include "Genes/Pawn_Advancement_Gene.h" #include <string> #include "Game/Board.h" #include "Pieces/Piece.h" #include "Genes/Piece_Strength_Gene.h" #include "Utility.h" Pawn_Advancement_Gene::Pawn_Advancement_Gene(const std::shared_ptr<const Piece_Strength_Gene>& piece_strength_source_in) : Gene(0.0), piece_strength_source(piece_strength_source_in), promoted_pawn_bonus(0.0) { } void Pawn_Advancement_Gene::reset_properties() const { reset_base_properties(); properties["Promoted Pawn Bonus"] = promoted_pawn_bonus; } void Pawn_Advancement_Gene::load_properties() { load_base_properties(); promoted_pawn_bonus = properties["Promoted Pawn Bonus"]; } double Pawn_Advancement_Gene::score_board(const Board& board, Color color) const { double score = 0.0; for(char file = 'a'; file <= 'h'; ++file) { for(int rank = 1; rank <= 8; ++rank) { auto piece = board.piece_on_square(file, rank); if(piece && piece->color() == color && toupper(piece->fen_symbol()) == 'P') { // 1 point per pawn + 1 point per move towards promotion score += std::abs((color == WHITE ? 1 : 8) - rank); } } } if(board.get_game_record().size() < 2) { return score; } auto last_move_index = board.get_game_record().size() - (color == board.whose_turn() ? 2 : 1); auto last_move = board.get_game_record()[last_move_index]; if(last_move.find('=') != std::string::npos) { auto piece_symbol = String::split(last_move, "=")[1][0]; // char score += promoted_pawn_bonus*piece_strength_source->piece_value(piece_symbol); } return score; } Pawn_Advancement_Gene* Pawn_Advancement_Gene::duplicate() const { return new Pawn_Advancement_Gene(*this); } std::string Pawn_Advancement_Gene::name() const { return "Pawn Advancement Gene"; } void Pawn_Advancement_Gene::mutate() { Gene::mutate(); promoted_pawn_bonus += Random::random_normal(1.0); promoted_pawn_bonus = std::max(promoted_pawn_bonus, 0.0); } void Pawn_Advancement_Gene::reset_piece_strength_gene(const std::shared_ptr<const Piece_Strength_Gene>& psg) { piece_strength_source = psg; } <|endoftext|>
<commit_before>//===-- GRConstants.cpp - Simple, Path-Sens. Constant Prop. ------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Constant Propagation via Graph Reachability // // This files defines a simple analysis that performs path-sensitive // constant propagation within a function. An example use of this analysis // is to perform simple checks for NULL dereferences. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/GREngine.h" #include "clang/AST/Expr.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "clang/Analysis/Visitors/CFGStmtVisitor.h" #include "llvm/Support/Casting.h" #include "llvm/Support/DataTypes.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #ifndef NDEBUG #include "llvm/Support/GraphWriter.h" #include <sstream> #endif using namespace clang; using llvm::APInt; using llvm::APFloat; using llvm::dyn_cast; using llvm::cast; //===----------------------------------------------------------------------===// /// DSPtr - A variant smart pointer that wraps either a ValueDecl* or a /// Stmt*. Use cast<> or dyn_cast<> to get actual pointer type //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN DSPtr { uintptr_t Raw; public: enum VariantKind { IsValueDecl=0x1, IsBlkLvl=0x2, IsSubExp=0x3, Flags=0x3 }; inline void* getPtr() const { return reinterpret_cast<void*>(Raw & ~Flags); } inline VariantKind getKind() const { return (VariantKind) (Raw & Flags); } DSPtr(ValueDecl* D) : Raw(reinterpret_cast<uintptr_t>(D) | IsValueDecl) {} DSPtr(Stmt* S, bool isBlkLvl) : Raw(reinterpret_cast<uintptr_t>(S) | (isBlkLvl ? IsBlkLvl : IsSubExp)) {} bool isSubExpr() const { return getKind() == IsSubExp; } inline void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddPointer(getPtr()); ID.AddInteger((unsigned) getKind()); } inline bool operator==(const DSPtr& X) const { return Raw == X.Raw; } inline bool operator!=(const DSPtr& X) const { return Raw != X.Raw; } inline bool operator<(const DSPtr& X) const { return Raw < X.Raw; } }; } // end anonymous namespace // Machinery to get cast<> and dyn_cast<> working with DSPtr. namespace llvm { template<> inline bool isa<ValueDecl,DSPtr>(const DSPtr& V) { return V.getKind() == DSPtr::IsValueDecl; } template<> inline bool isa<Stmt,DSPtr>(const DSPtr& V) { return ((unsigned) V.getKind()) > DSPtr::IsValueDecl; } template<> struct VISIBILITY_HIDDEN cast_retty_impl<ValueDecl,DSPtr> { typedef const ValueDecl* ret_type; }; template<> struct VISIBILITY_HIDDEN cast_retty_impl<Stmt,DSPtr> { typedef const Stmt* ret_type; }; template<> struct VISIBILITY_HIDDEN simplify_type<DSPtr> { typedef void* SimpleType; static inline SimpleType getSimplifiedValue(const DSPtr &V) { return V.getPtr(); } }; } // end llvm namespace //===----------------------------------------------------------------------===// // DeclStmtMapTy - A ImmutableMap type from Decl*/Stmt* to integers. // // FIXME: We may eventually use APSInt, or a mixture of APSInt and // integer primitives to do this right; this will handle both // different bit-widths and allow us to detect integer overflows, etc. // //===----------------------------------------------------------------------===// typedef llvm::ImmutableMap<DSPtr,uint64_t> DeclStmtMapTy; namespace clang { template<> struct VISIBILITY_HIDDEN GRTrait<DeclStmtMapTy> { static inline void* toPtr(DeclStmtMapTy M) { return reinterpret_cast<void*>(M.getRoot()); } static inline DeclStmtMapTy toState(void* P) { return DeclStmtMapTy(static_cast<DeclStmtMapTy::TreeTy*>(P)); } }; } //===----------------------------------------------------------------------===// // The Checker! //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN ExprVariantTy { const uint64_t val; const bool isConstant; public: ExprVariantTy() : val(0), isConstant(false) {} ExprVariantTy(uint64_t v) : val(v), isConstant(true) {} operator bool() const { return isConstant; } uint64_t getVal() const { assert (isConstant); return val; } ExprVariantTy operator+(const ExprVariantTy& X) const { if (!isConstant || !X.isConstant) return ExprVariantTy(); else return ExprVariantTy(val+X.val); } ExprVariantTy operator-(const ExprVariantTy& X) const { if (!isConstant || !X.isConstant) return ExprVariantTy(); else return ExprVariantTy(val-X.val); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // The Checker! //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN GRConstants : public CFGStmtVisitor<GRConstants> { public: typedef DeclStmtMapTy StateTy; typedef GRNodeBuilder<GRConstants> NodeBuilder; typedef ExplodedNode<StateTy> NodeTy; protected: // Liveness - live-variables information the ValueDecl* and Expr* (block-level) // in the CFG. Used to prune out dead state. LiveVariables* Liveness; // Builder - The current GRNodeBuilder which is used when building the nodes // for a given statement. NodeBuilder* Builder; DeclStmtMapTy::Factory StateMgr; // cfg - the current CFG. CFG* cfg; typedef llvm::SmallVector<NodeTy*,8> NodeSetTy; NodeSetTy NodeSetA; NodeSetTy NodeSetB; NodeSetTy* Nodes; NodeSetTy* OldNodes; StateTy CurrentState; public: GRConstants() : Liveness(NULL), Builder(NULL), cfg(NULL), Nodes(&NodeSetA), OldNodes(&NodeSetB), CurrentState(StateMgr.GetEmptyMap()) {} ~GRConstants() { delete Liveness; } CFG& getCFG() { assert (cfg); return *cfg; } void Initialize(CFG& c) { cfg = &c; Liveness = new LiveVariables(c); Liveness->runOnCFG(c); } StateTy getInitialState() { return StateMgr.GetEmptyMap(); } void ProcessStmt(Stmt* S, NodeBuilder& builder); void SwitchNodeSets(); void DoStmt(Stmt* S); StateTy RemoveGrandchildrenMappings(Stmt* S, StateTy M); void AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl = false); void AddBinding(ValueDecl* D, ExprVariantTy V); ExprVariantTy GetBinding(Expr* E); void BlockStmt_VisitStmt(Stmt* S) { DoStmt(S); } void VisitAssign(BinaryOperator* O); void VisitIntegerLiteral(IntegerLiteral* L); void VisitBinAdd(BinaryOperator* O); void VisitBinSub(BinaryOperator* O); void VisitBinAssign(BinaryOperator* D); }; } // end anonymous namespace void GRConstants::ProcessStmt(Stmt* S, NodeBuilder& builder) { Builder = &builder; Nodes->clear(); OldNodes->clear(); NodeTy* N = Builder->getLastNode(); assert (N); OldNodes->push_back(N); BlockStmt_Visit(S); Builder = NULL; } ExprVariantTy GRConstants::GetBinding(Expr* E) { DSPtr P(NULL); if (DeclRefExpr* D = dyn_cast<DeclRefExpr>(E)) P = DSPtr(D->getDecl()); else P = DSPtr(E, getCFG().isBlkExpr(E)); StateTy::iterator I = CurrentState.find(P); if (I == CurrentState.end()) return ExprVariantTy(); return (*I).second; } void GRConstants::AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl) { if (V) CurrentState = StateMgr.Add(CurrentState, DSPtr(E,isBlkLvl), V.getVal()); } void GRConstants::AddBinding(ValueDecl* D, ExprVariantTy V) { if (V) CurrentState = StateMgr.Add(CurrentState, DSPtr(D), V.getVal()); else CurrentState = StateMgr.Remove(CurrentState, DSPtr(D)); } void GRConstants::SwitchNodeSets() { NodeSetTy* Tmp = OldNodes; OldNodes = Nodes; Nodes = Tmp; Nodes->clear(); } GRConstants::StateTy GRConstants::RemoveGrandchildrenMappings(Stmt* S, GRConstants::StateTy State) { typedef Stmt::child_iterator iterator; for (iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) if (Stmt* C = *I) for (iterator CI=C->child_begin(), CE=C->child_end(); CI!=CE; ++CI) { // Observe that this will only remove mappings to non-block level // expressions. This is valid even if *CI is a block-level expression, // since it simply won't be in the map in the first place. // Note: This should also work if 'C' is a block-level expression, // although ideally we would want to skip processing C's children. State = StateMgr.Remove(State, DSPtr(*CI,false)); } return State; } void GRConstants::DoStmt(Stmt* S) { for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) if (*I) DoStmt(*I); for (NodeSetTy::iterator I=OldNodes->begin(), E=OldNodes->end(); I!=E; ++I) { NodeTy* Pred = *I; CurrentState = Pred->getState(); StateTy OldState = CurrentState; CurrentState = RemoveGrandchildrenMappings(S, CurrentState); Visit(S); if (CurrentState != OldState) { NodeTy* N = Builder->generateNode(S, CurrentState, Pred); if (N) Nodes->push_back(N); } else Nodes->push_back(Pred); } SwitchNodeSets(); } void GRConstants::VisitIntegerLiteral(IntegerLiteral* L) { AddBinding(L, L->getValue().getZExtValue()); } void GRConstants::VisitBinAdd(BinaryOperator* B) { AddBinding(B, GetBinding(B->getLHS()) + GetBinding(B->getRHS())); } void GRConstants::VisitBinSub(BinaryOperator* B) { AddBinding(B, GetBinding(B->getLHS()) - GetBinding(B->getRHS())); } static inline Expr* IgnoreParen(Expr* E) { while (ParenExpr* P = dyn_cast<ParenExpr>(E)) E = P->getSubExpr(); return E; } void GRConstants::VisitBinAssign(BinaryOperator* B) { if (DeclRefExpr* D = dyn_cast<DeclRefExpr>(IgnoreParen(B->getLHS()))) AddBinding(D->getDecl(), GetBinding(B->getRHS())); } //===----------------------------------------------------------------------===// // Driver. //===----------------------------------------------------------------------===// #ifndef NDEBUG namespace llvm { template<> struct VISIBILITY_HIDDEN DOTGraphTraits<GRConstants::NodeTy*> : public DefaultDOTGraphTraits { static std::string getNodeLabel(const GRConstants::NodeTy* N, void*) { std::ostringstream Out; Out << "Vertex: " << (void*) N << '\n'; ProgramPoint Loc = N->getLocation(); switch (Loc.getKind()) { case ProgramPoint::BlockEntranceKind: Out << "Block Entrance: B" << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); break; case ProgramPoint::BlockExitKind: assert (false); break; case ProgramPoint::PostStmtKind: { const PostStmt& L = cast<PostStmt>(Loc); Out << "Stmt: " << (void*) L.getStmt() << '\n'; L.getStmt()->printPretty(Out); break; } default: { const BlockEdge& E = cast<BlockEdge>(Loc); Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" << E.getDst()->getBlockID() << ')'; } } Out << "\n{"; GRConstants::StateTy M = N->getState(); bool isFirst = true; for (GRConstants::StateTy::iterator I=M.begin(), E=M.end(); I!=E; ++I) { if (!isFirst) Out << '\n'; else isFirst = false; if (ValueDecl* V = dyn_cast<ValueDecl>(I.getKey())) { Out << "Decl: " << (void*) V << ", " << V->getName(); } else { Stmt* E = cast<Stmt>(I.getKey()); Out << "Stmt: " << (void*) E; } Out << " => " << I.getData(); } Out << " }"; return Out.str(); } }; } // end llvm namespace #endif namespace clang { void RunGRConstants(CFG& cfg) { GREngine<GRConstants> Engine(cfg); Engine.ExecuteWorkList(); #ifndef NDEBUG llvm::ViewGraph(*Engine.getGraph().roots_begin(),"GRConstants"); #endif } } <commit_msg>IntegerLiterals are no longer evaluated to create separate nodes; their values are determined when evaluating the parent expression.<commit_after>//===-- GRConstants.cpp - Simple, Path-Sens. Constant Prop. ------*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Constant Propagation via Graph Reachability // // This files defines a simple analysis that performs path-sensitive // constant propagation within a function. An example use of this analysis // is to perform simple checks for NULL dereferences. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/GREngine.h" #include "clang/AST/Expr.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "clang/Analysis/Visitors/CFGStmtVisitor.h" #include "llvm/Support/Casting.h" #include "llvm/Support/DataTypes.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #ifndef NDEBUG #include "llvm/Support/GraphWriter.h" #include <sstream> #endif using namespace clang; using llvm::APInt; using llvm::APFloat; using llvm::dyn_cast; using llvm::cast; //===----------------------------------------------------------------------===// /// DSPtr - A variant smart pointer that wraps either a ValueDecl* or a /// Stmt*. Use cast<> or dyn_cast<> to get actual pointer type //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN DSPtr { uintptr_t Raw; public: enum VariantKind { IsValueDecl=0x1, IsBlkLvl=0x2, IsSubExp=0x3, Flags=0x3 }; inline void* getPtr() const { return reinterpret_cast<void*>(Raw & ~Flags); } inline VariantKind getKind() const { return (VariantKind) (Raw & Flags); } DSPtr(ValueDecl* D) : Raw(reinterpret_cast<uintptr_t>(D) | IsValueDecl) {} DSPtr(Stmt* S, bool isBlkLvl) : Raw(reinterpret_cast<uintptr_t>(S) | (isBlkLvl ? IsBlkLvl : IsSubExp)) {} bool isSubExpr() const { return getKind() == IsSubExp; } inline void Profile(llvm::FoldingSetNodeID& ID) const { ID.AddPointer(getPtr()); ID.AddInteger((unsigned) getKind()); } inline bool operator==(const DSPtr& X) const { return Raw == X.Raw; } inline bool operator!=(const DSPtr& X) const { return Raw != X.Raw; } inline bool operator<(const DSPtr& X) const { return Raw < X.Raw; } }; } // end anonymous namespace // Machinery to get cast<> and dyn_cast<> working with DSPtr. namespace llvm { template<> inline bool isa<ValueDecl,DSPtr>(const DSPtr& V) { return V.getKind() == DSPtr::IsValueDecl; } template<> inline bool isa<Stmt,DSPtr>(const DSPtr& V) { return ((unsigned) V.getKind()) > DSPtr::IsValueDecl; } template<> struct VISIBILITY_HIDDEN cast_retty_impl<ValueDecl,DSPtr> { typedef const ValueDecl* ret_type; }; template<> struct VISIBILITY_HIDDEN cast_retty_impl<Stmt,DSPtr> { typedef const Stmt* ret_type; }; template<> struct VISIBILITY_HIDDEN simplify_type<DSPtr> { typedef void* SimpleType; static inline SimpleType getSimplifiedValue(const DSPtr &V) { return V.getPtr(); } }; } // end llvm namespace //===----------------------------------------------------------------------===// // DeclStmtMapTy - A ImmutableMap type from Decl*/Stmt* to integers. // // FIXME: We may eventually use APSInt, or a mixture of APSInt and // integer primitives to do this right; this will handle both // different bit-widths and allow us to detect integer overflows, etc. // //===----------------------------------------------------------------------===// typedef llvm::ImmutableMap<DSPtr,uint64_t> DeclStmtMapTy; namespace clang { template<> struct VISIBILITY_HIDDEN GRTrait<DeclStmtMapTy> { static inline void* toPtr(DeclStmtMapTy M) { return reinterpret_cast<void*>(M.getRoot()); } static inline DeclStmtMapTy toState(void* P) { return DeclStmtMapTy(static_cast<DeclStmtMapTy::TreeTy*>(P)); } }; } //===----------------------------------------------------------------------===// // The Checker! //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN ExprVariantTy { const uint64_t val; const bool isConstant; public: ExprVariantTy() : val(0), isConstant(false) {} ExprVariantTy(uint64_t v) : val(v), isConstant(true) {} operator bool() const { return isConstant; } uint64_t getVal() const { assert (isConstant); return val; } ExprVariantTy operator+(const ExprVariantTy& X) const { if (!isConstant || !X.isConstant) return ExprVariantTy(); else return ExprVariantTy(val+X.val); } ExprVariantTy operator-(const ExprVariantTy& X) const { if (!isConstant || !X.isConstant) return ExprVariantTy(); else return ExprVariantTy(val-X.val); } }; } // end anonymous namespace //===----------------------------------------------------------------------===// // The Checker! //===----------------------------------------------------------------------===// namespace { class VISIBILITY_HIDDEN GRConstants : public CFGStmtVisitor<GRConstants> { public: typedef DeclStmtMapTy StateTy; typedef GRNodeBuilder<GRConstants> NodeBuilder; typedef ExplodedNode<StateTy> NodeTy; protected: // Liveness - live-variables information the ValueDecl* and Expr* (block-level) // in the CFG. Used to prune out dead state. LiveVariables* Liveness; // Builder - The current GRNodeBuilder which is used when building the nodes // for a given statement. NodeBuilder* Builder; DeclStmtMapTy::Factory StateMgr; // cfg - the current CFG. CFG* cfg; typedef llvm::SmallVector<NodeTy*,8> NodeSetTy; NodeSetTy NodeSetA; NodeSetTy NodeSetB; NodeSetTy* Nodes; NodeSetTy* OldNodes; StateTy CurrentState; public: GRConstants() : Liveness(NULL), Builder(NULL), cfg(NULL), Nodes(&NodeSetA), OldNodes(&NodeSetB), CurrentState(StateMgr.GetEmptyMap()) {} ~GRConstants() { delete Liveness; } CFG& getCFG() { assert (cfg); return *cfg; } void Initialize(CFG& c) { cfg = &c; Liveness = new LiveVariables(c); Liveness->runOnCFG(c); } StateTy getInitialState() { return StateMgr.GetEmptyMap(); } void ProcessStmt(Stmt* S, NodeBuilder& builder); void SwitchNodeSets(); void DoStmt(Stmt* S); StateTy RemoveGrandchildrenMappings(Stmt* S, StateTy M); void AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl = false); void AddBinding(ValueDecl* D, ExprVariantTy V); ExprVariantTy GetBinding(Expr* E); void BlockStmt_VisitStmt(Stmt* S) { DoStmt(S); } void VisitAssign(BinaryOperator* O); void VisitBinAdd(BinaryOperator* O); void VisitBinSub(BinaryOperator* O); void VisitBinAssign(BinaryOperator* D); }; } // end anonymous namespace static inline Expr* IgnoreParen(Expr* E) { while (ParenExpr* P = dyn_cast<ParenExpr>(E)) E = P->getSubExpr(); return E; } void GRConstants::ProcessStmt(Stmt* S, NodeBuilder& builder) { Builder = &builder; Nodes->clear(); OldNodes->clear(); NodeTy* N = Builder->getLastNode(); assert (N); OldNodes->push_back(N); BlockStmt_Visit(S); Builder = NULL; } ExprVariantTy GRConstants::GetBinding(Expr* E) { DSPtr P(NULL); E = IgnoreParen(E); switch (E->getStmtClass()) { case Stmt::DeclRefExprClass: P = DSPtr(cast<DeclRefExpr>(E)->getDecl()); break; case Stmt::IntegerLiteralClass: return cast<IntegerLiteral>(E)->getValue().getZExtValue(); default: P = DSPtr(E, getCFG().isBlkExpr(E)); break; } StateTy::iterator I = CurrentState.find(P); if (I == CurrentState.end()) return ExprVariantTy(); return (*I).second; } void GRConstants::AddBinding(Expr* E, ExprVariantTy V, bool isBlkLvl) { if (V) CurrentState = StateMgr.Add(CurrentState, DSPtr(E,isBlkLvl), V.getVal()); } void GRConstants::AddBinding(ValueDecl* D, ExprVariantTy V) { if (V) CurrentState = StateMgr.Add(CurrentState, DSPtr(D), V.getVal()); else CurrentState = StateMgr.Remove(CurrentState, DSPtr(D)); } void GRConstants::SwitchNodeSets() { NodeSetTy* Tmp = OldNodes; OldNodes = Nodes; Nodes = Tmp; Nodes->clear(); } GRConstants::StateTy GRConstants::RemoveGrandchildrenMappings(Stmt* S, GRConstants::StateTy State) { typedef Stmt::child_iterator iterator; for (iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) if (Stmt* C = *I) for (iterator CI=C->child_begin(), CE=C->child_end(); CI!=CE; ++CI) { // Observe that this will only remove mappings to non-block level // expressions. This is valid even if *CI is a block-level expression, // since it simply won't be in the map in the first place. // Note: This should also work if 'C' is a block-level expression, // although ideally we would want to skip processing C's children. State = StateMgr.Remove(State, DSPtr(*CI,false)); } return State; } void GRConstants::DoStmt(Stmt* S) { for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) if (*I) DoStmt(*I); for (NodeSetTy::iterator I=OldNodes->begin(), E=OldNodes->end(); I!=E; ++I) { NodeTy* Pred = *I; CurrentState = Pred->getState(); StateTy OldState = CurrentState; CurrentState = RemoveGrandchildrenMappings(S, CurrentState); Visit(S); if (CurrentState != OldState) { NodeTy* N = Builder->generateNode(S, CurrentState, Pred); if (N) Nodes->push_back(N); } else Nodes->push_back(Pred); } SwitchNodeSets(); } void GRConstants::VisitBinAdd(BinaryOperator* B) { AddBinding(B, GetBinding(B->getLHS()) + GetBinding(B->getRHS())); } void GRConstants::VisitBinSub(BinaryOperator* B) { AddBinding(B, GetBinding(B->getLHS()) - GetBinding(B->getRHS())); } void GRConstants::VisitBinAssign(BinaryOperator* B) { if (DeclRefExpr* D = dyn_cast<DeclRefExpr>(IgnoreParen(B->getLHS()))) AddBinding(D->getDecl(), GetBinding(B->getRHS())); } //===----------------------------------------------------------------------===// // Driver. //===----------------------------------------------------------------------===// #ifndef NDEBUG namespace llvm { template<> struct VISIBILITY_HIDDEN DOTGraphTraits<GRConstants::NodeTy*> : public DefaultDOTGraphTraits { static std::string getNodeLabel(const GRConstants::NodeTy* N, void*) { std::ostringstream Out; Out << "Vertex: " << (void*) N << '\n'; ProgramPoint Loc = N->getLocation(); switch (Loc.getKind()) { case ProgramPoint::BlockEntranceKind: Out << "Block Entrance: B" << cast<BlockEntrance>(Loc).getBlock()->getBlockID(); break; case ProgramPoint::BlockExitKind: assert (false); break; case ProgramPoint::PostStmtKind: { const PostStmt& L = cast<PostStmt>(Loc); Out << "Stmt: " << (void*) L.getStmt() << '\n'; L.getStmt()->printPretty(Out); break; } default: { const BlockEdge& E = cast<BlockEdge>(Loc); Out << "Edge: (B" << E.getSrc()->getBlockID() << ", B" << E.getDst()->getBlockID() << ')'; } } Out << "\n{"; GRConstants::StateTy M = N->getState(); bool isFirst = true; for (GRConstants::StateTy::iterator I=M.begin(), E=M.end(); I!=E; ++I) { if (!isFirst) Out << '\n'; else isFirst = false; if (ValueDecl* V = dyn_cast<ValueDecl>(I.getKey())) { Out << "Decl: " << (void*) V << ", " << V->getName(); } else { Stmt* E = cast<Stmt>(I.getKey()); Out << "Stmt: " << (void*) E; } Out << " => " << I.getData(); } Out << " }"; return Out.str(); } }; } // end llvm namespace #endif namespace clang { void RunGRConstants(CFG& cfg) { GREngine<GRConstants> Engine(cfg); Engine.ExecuteWorkList(); #ifndef NDEBUG llvm::ViewGraph(*Engine.getGraph().roots_begin(),"GRConstants"); #endif } } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of 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 "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/thread.hpp" #include <boost/tuple/tuple.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/extensions/metadata_transfer.hpp" #include "libtorrent/extensions/ut_metadata.hpp" #include <iostream> using boost::tuples::ignore; enum flags_t { clear_files = 1, disconnect = 2, full_encryption = 4, reverse = 8 }; void test_transfer(int flags , boost::shared_ptr<libtorrent::torrent_plugin> (*constructor)(libtorrent::torrent*, void*) , int timeout) { using namespace libtorrent; fprintf(stderr, "test transfer: timeout=%d %s%s%s\n" , timeout , (flags & clear_files) ? "clear-files " : "" , (flags & disconnect) ? "disconnect " : "" , (flags & full_encryption) ? "encryption " : ""); // these are declared before the session objects // so that they are destructed last. This enables // the sessions to destruct in parallel session_proxy p1; session_proxy p2; // TODO: it would be nice to test reversing // which session is making the connection as well session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48100, 49000), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49100, 50000), "0.0.0.0", 0); ses1.add_extension(constructor); ses2.add_extension(constructor); torrent_handle tor1; torrent_handle tor2; #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.prefer_rc4 = (flags & full_encryption); pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); #endif session* downloader = &ses2; session* seed = &ses1; if (flags & reverse) { std::swap(downloader, seed); } boost::tie(tor1, tor2, ignore) = setup_transfer(seed, downloader, NULL, flags & clear_files, true, true, "_meta"); for (int i = 0; i < timeout * 10; ++i) { // make sure this function can be called on // torrents without metadata if ((flags & disconnect) == 0) tor2.status(); print_alerts(*seed, "seed", false, true); print_alerts(*downloader, "downloader", false, true); if ((flags & disconnect) && tor2.is_valid()) downloader->remove_torrent(tor2); if ((flags & disconnect) == 0 && tor2.status().has_metadata) break; test_sleep(100); } if (flags & disconnect) goto done; TEST_CHECK(tor2.status().has_metadata); std::cerr << "waiting for transfer to complete\n"; for (int i = 0; i < timeout * 10; ++i) { torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); print_alerts(*seed, "seed", false, true); print_alerts(*downloader, "downloader", false, true); print_ses_rate(i / 10.f, &st1, &st2); if (st2.is_seeding) break; test_sleep(100); } TEST_CHECK(tor2.status().is_seeding); if (tor2.status().is_seeding) std::cerr << "done\n"; done: // this allows shutting down the sessions in parallel p1 = seed->abort(); p2 = downloader->abort(); error_code ec; remove_all("tmp1_meta", ec); remove_all("tmp2_meta", ec); } int test_main() { using namespace libtorrent; #ifdef TORRENT_USE_VALGRIND const int timeout = 8; #else const int timeout = 3; #endif test_transfer(full_encryption | reverse, &create_ut_metadata_plugin, 2); test_transfer(reverse, &create_ut_metadata_plugin, 2); for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f) test_transfer(f, &create_metadata_plugin, timeout * 2); for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f) test_transfer(f, &create_ut_metadata_plugin, timeout); error_code ec; remove_all("tmp1", ec); remove_all("tmp2", ec); return 0; } <commit_msg>fix valgrind run of test_metadata_extension<commit_after>/* Copyright (c) 2008, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of 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 "libtorrent/session.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/thread.hpp" #include <boost/tuple/tuple.hpp> #include "test.hpp" #include "setup_transfer.hpp" #include "libtorrent/extensions/metadata_transfer.hpp" #include "libtorrent/extensions/ut_metadata.hpp" #include <iostream> using boost::tuples::ignore; enum flags_t { clear_files = 1, disconnect = 2, full_encryption = 4, reverse = 8 }; void test_transfer(int flags , boost::shared_ptr<libtorrent::torrent_plugin> (*constructor)(libtorrent::torrent*, void*) , int timeout) { using namespace libtorrent; fprintf(stderr, "test transfer: timeout=%d %s%s%s\n" , timeout , (flags & clear_files) ? "clear-files " : "" , (flags & disconnect) ? "disconnect " : "" , (flags & full_encryption) ? "encryption " : ""); // these are declared before the session objects // so that they are destructed last. This enables // the sessions to destruct in parallel session_proxy p1; session_proxy p2; // TODO: it would be nice to test reversing // which session is making the connection as well session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48100, 49000), "0.0.0.0", 0); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49100, 50000), "0.0.0.0", 0); ses1.add_extension(constructor); ses2.add_extension(constructor); torrent_handle tor1; torrent_handle tor2; #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.prefer_rc4 = (flags & full_encryption); pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); #endif session* downloader = &ses2; session* seed = &ses1; if (flags & reverse) { std::swap(downloader, seed); } boost::tie(tor1, tor2, ignore) = setup_transfer(seed, downloader, NULL, flags & clear_files, true, true, "_meta"); for (int i = 0; i < timeout * 10; ++i) { // make sure this function can be called on // torrents without metadata if ((flags & disconnect) == 0) tor2.status(); print_alerts(*seed, "seed", false, true); print_alerts(*downloader, "downloader", false, true); if ((flags & disconnect) && tor2.is_valid()) downloader->remove_torrent(tor2); if ((flags & disconnect) == 0 && tor2.status().has_metadata) break; test_sleep(100); } if (flags & disconnect) goto done; TEST_CHECK(tor2.status().has_metadata); std::cerr << "waiting for transfer to complete\n"; for (int i = 0; i < timeout * 10; ++i) { torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); print_alerts(*seed, "seed", false, true); print_alerts(*downloader, "downloader", false, true); print_ses_rate(i / 10.f, &st1, &st2); if (st2.is_seeding) break; test_sleep(100); } TEST_CHECK(tor2.status().is_seeding); if (tor2.status().is_seeding) std::cerr << "done\n"; done: // this allows shutting down the sessions in parallel p1 = seed->abort(); p2 = downloader->abort(); error_code ec; remove_all("tmp1_meta", ec); remove_all("tmp2_meta", ec); } int test_main() { using namespace libtorrent; #ifdef TORRENT_USE_VALGRIND const int timeout = 8; #else const int timeout = 3; #endif test_transfer(full_encryption | reverse, &create_ut_metadata_plugin, timeout); test_transfer(reverse, &create_ut_metadata_plugin, timeout); for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f) test_transfer(f, &create_metadata_plugin, timeout * 2); for (int f = 0; f <= (clear_files | disconnect | full_encryption); ++f) test_transfer(f, &create_ut_metadata_plugin, timeout); error_code ec; remove_all("tmp1", ec); remove_all("tmp2", ec); return 0; } <|endoftext|>
<commit_before>#include "BasicExample.h" #include "btBulletDynamicsCommon.h" #define ARRAY_SIZE_Y 5 #define ARRAY_SIZE_X 5 #define ARRAY_SIZE_Z 5 #include "LinearMath/btVector3.h" #include "LinearMath/btAlignedObjectArray.h" #include "CommonInterfaces/CommonRigidBodyBase.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #include "LinearHypothesis.h" #include "ActionRecorder.h" LinearHypothesis lh; ActionRecorder AR; bool needStuding = true; int num = 0; short collisionFilterGroup = short(btBroadphaseProxy::CharacterFilter); short collisionFilterMask = short(btBroadphaseProxy::AllFilter ^ (btBroadphaseProxy::CharacterFilter)); static btScalar radius(0.2); struct BasicExample : public CommonRigidBodyBase { bool m_once; btAlignedObjectArray<btJointFeedback*> m_jointFeedback; btHingeConstraint* hinge; btRigidBody* linkBody; btVector3 groundOrigin_target; btRigidBody* body; btBoxShape* box; BasicExample(struct GUIHelperInterface* helper); virtual ~BasicExample(); virtual void initPhysics(); virtual void stepSimulation(float deltaTime); void lockLiftHinge(void); virtual bool keyboardCallback(int key, int state); virtual void resetCamera() { float dist = 5; float pitch = 270; float yaw = 21; float targetPos[3] = { -1.34,3.4,-0.44 }; m_guiHelper->resetCamera(dist, pitch, yaw, targetPos[0], targetPos[1], targetPos[2]); } }; BasicExample::BasicExample(struct GUIHelperInterface* helper) :CommonRigidBodyBase(helper), m_once(true) { } BasicExample::~BasicExample() { for (int i = 0; i<m_jointFeedback.size(); i++) { delete m_jointFeedback[i]; } } /******************************************************************************************** * start custom Functions *********************************************************************************************/ void initState(BasicExample* target) { target->m_guiHelper->removeAllGraphicsInstances(); target->initPhysics(); } void moveLeft(btHingeConstraint *target) { target->setLimit(-M_PI / 1.2f, M_PI / 1.2f); target->enableAngularMotor(true, -15.0, 4000.f); } void moveRight(btHingeConstraint *target) { target->setLimit(-M_PI / 1.2f, M_PI / 1.2f); target->enableAngularMotor(true, 15.0, 4000.f); } /******************************************************************************************** * end custom Functions *********************************************************************************************/ void BasicExample::stepSimulation(float deltaTime) { if (0)//m_once) { m_once = false; btHingeConstraint* hinge = (btHingeConstraint*)m_dynamicsWorld->getConstraint(0); btRigidBody& bodyA = hinge->getRigidBodyA(); btTransform trA = bodyA.getWorldTransform(); btVector3 hingeAxisInWorld = trA.getBasis()*hinge->getFrameOffsetA().getBasis().getColumn(2); hinge->getRigidBodyA().applyTorque(-hingeAxisInWorld * 10); hinge->getRigidBodyB().applyTorque(hingeAxisInWorld * 10); } //get distance btScalar distance = sqrt(pow((body->getCenterOfMassPosition().getZ() - linkBody->getCenterOfMassPosition().getZ()), 2) + pow((body->getCenterOfMassPosition().getY() - linkBody->getCenterOfMassPosition().getY()), 2)) - 0.225; //b3Printf("distance = %f\n", distance); //collison check int numManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { if (m_dynamicsWorld->getDispatcher()->getNumManifolds() == 0) continue; btPersistentManifold* contactManifold = m_dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); const btCollisionObject* obA = contactManifold->getBody0(); const btCollisionObject* obB = contactManifold->getBody1(); int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& pt = contactManifold->getContactPoint(j); if (pt.getDistance() < 0.f) { const btVector3& ptA = pt.getPositionWorldOnA(); const btVector3& ptB = pt.getPositionWorldOnB(); const btVector3& normalOnB = pt.m_normalWorldOnB; initState(this); b3Printf("check\n"); /******************************************************************************************** * start RL *********************************************************************************************/ float lr = 0.5f; // LR for (int t = 0; t < 10000; t++) { for (int i = 0; i < AR.memory.num_elements; i++) { float a = (float)AR.memory.moved_array[i]; float b = AR.memory.reward_array[i]; const float error = b - lh.getY(a); const float sqr_error = 0.5 * error * error; const float da = 2.0 * error * -a; const float db = 2.0 * error * -1; lh.a -= da * lr; lh.b -= db * lr; } } needStuding = false; AR.clearHistory(); /******************************************************************************************** * end RL *********************************************************************************************/ } } } /******************************************************************************************** * start select Move *********************************************************************************************/ int thisMoved = -1; if (needStuding) { // random move thisMoved = ((int)rand() % 2 == 0) ? (1) : (0); } else { // learned move thisMoved = (lh.getY(distance) >= 0.5) ? (0) : (1); } // moving if (thisMoved == ACT_MOVE_LEFT) { moveLeft(hinge); } else { moveRight(hinge); } // check current b3Printf("moved = %d\tdistance=%f\ttcurrent Y = %f\n", thisMoved, distance, lh.getY(distance)); // Memory AR.recordHistory(thisMoved, distance); /******************************************************************************************** * end select RL *********************************************************************************************/ m_dynamicsWorld->stepSimulation(1. / 240, 0); static int count = 0; } void BasicExample::initPhysics() { int upAxis = 1; m_guiHelper->setUpAxis(upAxis); createEmptyDynamicsWorld(); m_dynamicsWorld->getSolverInfo().m_splitImpulse = false; m_dynamicsWorld->setGravity(btVector3(0, 0, -10)); m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld); int mode = btIDebugDraw::DBG_DrawWireframe + btIDebugDraw::DBG_DrawConstraints + btIDebugDraw::DBG_DrawConstraintLimits; m_dynamicsWorld->getDebugDrawer()->setDebugMode(mode); { // create a door using hinge constraint attached to the world int numLinks = 2; bool spherical = false; //set it ot false -to use 1DoF hinges instead of 3DoF sphericals bool canSleep = false; bool selfCollide = false; btVector3 baseHalfExtents(0.05, 0.37, 0.1); btVector3 linkHalfExtents(0.05, 0.37, 0.1); btBoxShape* baseBox = new btBoxShape(baseHalfExtents); btVector3 basePosition = btVector3(-0.4f, 4.f, 0.f); btTransform baseWorldTrans; baseWorldTrans.setIdentity(); baseWorldTrans.setOrigin(basePosition); //mbC->forceMultiDof(); //if !spherical, you can comment this line to check the 1DoF algorithm //init the base btVector3 baseInertiaDiag(0.f, 0.f, 0.f); float baseMass = 0.f; float linkMass = 1.f; btRigidBody* base = createRigidBody(baseMass, baseWorldTrans, baseBox); m_dynamicsWorld->removeRigidBody(base); base->setDamping(0, 0); m_dynamicsWorld->addRigidBody(base, collisionFilterGroup, collisionFilterMask); btBoxShape* linkBox1 = new btBoxShape(linkHalfExtents); btSphereShape* linkSphere = new btSphereShape(radius); btRigidBody* prevBody = base; for (int i = 0; i<numLinks; i++) { btTransform linkTrans; linkTrans = baseWorldTrans; linkTrans.setOrigin(basePosition - btVector3(0, linkHalfExtents[1] * 2.f*(i + 1), 0)); btCollisionShape* colOb = 0; if (i == 0) { colOb = linkBox1; } else { colOb = linkSphere; } linkBody = createRigidBody(linkMass, linkTrans, colOb); m_dynamicsWorld->removeRigidBody(linkBody); m_dynamicsWorld->addRigidBody(linkBody, collisionFilterGroup, collisionFilterMask); linkBody->setDamping(0, 0); btTypedConstraint* con = 0; if (i == 0) { //create a hinge constraint btVector3 pivotInA(0, -linkHalfExtents[1], 0); btVector3 pivotInB(0, linkHalfExtents[1], 0); btVector3 axisInA(1, 0, 0); btVector3 axisInB(1, 0, 0); bool useReferenceA = true; hinge = new btHingeConstraint(*prevBody, *linkBody, pivotInA, pivotInB, axisInA, axisInB, useReferenceA); hinge->setLimit(0.0f, 0.0f); m_dynamicsWorld->addConstraint(hinge, true); con = hinge; } else { btTransform pivotInA(btQuaternion::getIdentity(), btVector3(0, -radius, 0)); //par body's COM to cur body's COM offset btTransform pivotInB(btQuaternion::getIdentity(), btVector3(0, radius, 0)); //cur body's COM to cur body's PIV offset btGeneric6DofSpring2Constraint* fixed = new btGeneric6DofSpring2Constraint(*prevBody, *linkBody, pivotInA, pivotInB); fixed->setLinearLowerLimit(btVector3(0, 0, 0)); fixed->setLinearUpperLimit(btVector3(0, 0, 0)); fixed->setAngularLowerLimit(btVector3(0, 0, 0)); fixed->setAngularUpperLimit(btVector3(0, 0, 0)); con = fixed; } btAssert(con); if (con) { btJointFeedback* fb = new btJointFeedback(); m_jointFeedback.push_back(fb); con->setJointFeedback(fb); m_dynamicsWorld->addConstraint(con, true); } prevBody = linkBody; } } if (1) { btVector3 groundHalfExtents(0.4, 0.0, 0.4); groundHalfExtents[upAxis] = 0.025f; btBoxShape* box = new btBoxShape(groundHalfExtents); box->initializePolyhedralFeatures(); btTransform start; start.setIdentity(); groundOrigin_target = btVector3(-0.4f, 3.9f, -0.77f); /* btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f); btQuaternion groundOrn(btVector3(0, 1, 0), 0.25*SIMD_PI);*/ start.setOrigin(groundOrigin_target); body = createRigidBody(0, start, box); body->setFriction(0); } m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); } bool BasicExample::keyboardCallback(int key, int state) { bool handled = false; if (state) { switch (key) { case B3G_HOME: { // b3Printf("Rest.\n"); initState(this); break; } case B3G_LEFT_ARROW: { // b3Printf("left.\n"); moveLeft(hinge); handled = true; break; } case B3G_RIGHT_ARROW: { // b3Printf("right.\n"); moveRight(hinge); handled = true; break; } case B3G_UP_ARROW: { // b3Printf("left.\n"); btVector3 basePosition = btVector3(0.0, 0.0f,1.54f); body->translate(basePosition); break; } case B3G_DOWN_ARROW: { // b3Printf("left.\n"); btVector3 basePosition = btVector3(0.0, 0.0f, -0.77f); body->translate(basePosition); break; } } } else { switch (key) { case B3G_LEFT_ARROW: case B3G_RIGHT_ARROW: { lockLiftHinge(); handled = true; break; } default: break; } } return handled; } void BasicExample::lockLiftHinge(void) { btScalar hingeAngle = hinge->getHingeAngle(); btScalar lowLim = hinge->getLowerLimit(); btScalar hiLim = hinge->getUpperLimit(); hinge->enableAngularMotor(false, 0, 0); if (hingeAngle < lowLim) { // m_liftHinge->setLimit(lowLim, lowLim + LIFT_EPS); hinge->setLimit(lowLim, lowLim); } else if (hingeAngle > hiLim) { // m_liftHinge->setLimit(hiLim - LIFT_EPS, hiLim); hinge->setLimit(hiLim, hiLim); } else { // m_liftHinge->setLimit(hingeAngle - LIFT_EPS, hingeAngle + LIFT_EPS); hinge->setLimit(hingeAngle, hingeAngle); } return; } CommonExampleInterface* BasicExampleCreateFunc(CommonExampleOptions& options) { return new BasicExample(options.m_guiHelper); } B3_STANDALONE_EXAMPLE(BasicExampleCreateFunc)<commit_msg>check the distance<commit_after>#include "BasicExample.h" #include "btBulletDynamicsCommon.h" #define ARRAY_SIZE_Y 5 #define ARRAY_SIZE_X 5 #define ARRAY_SIZE_Z 5 #include "LinearMath/btVector3.h" #include "LinearMath/btAlignedObjectArray.h" #include "CommonInterfaces/CommonRigidBodyBase.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #include "LinearHypothesis.h" #include "ActionRecorder.h" LinearHypothesis lh; ActionRecorder AR; bool needStuding = true; int num = 0; short collisionFilterGroup = short(btBroadphaseProxy::CharacterFilter); short collisionFilterMask = short(btBroadphaseProxy::AllFilter ^ (btBroadphaseProxy::CharacterFilter)); static btScalar radius(0.2); struct BasicExample : public CommonRigidBodyBase { bool m_once; btScalar distance; btAlignedObjectArray<btJointFeedback*> m_jointFeedback; btHingeConstraint* hinge; btRigidBody* linkBody; btVector3 groundOrigin_target; btRigidBody* body; btBoxShape* box; BasicExample(struct GUIHelperInterface* helper); virtual ~BasicExample(); virtual void initPhysics(); virtual void stepSimulation(float deltaTime); void lockLiftHinge(void); virtual bool keyboardCallback(int key, int state); virtual void resetCamera() { float dist = 5; float pitch = 270; float yaw = 21; float targetPos[3] = { -1.34,3.4,-0.44 }; m_guiHelper->resetCamera(dist, pitch, yaw, targetPos[0], targetPos[1], targetPos[2]); } }; BasicExample::BasicExample(struct GUIHelperInterface* helper) :CommonRigidBodyBase(helper), m_once(true) { } BasicExample::~BasicExample() { for (int i = 0; i<m_jointFeedback.size(); i++) { delete m_jointFeedback[i]; } } /******************************************************************************************** * start custom Functions *********************************************************************************************/ void initState(BasicExample* target) { target->m_guiHelper->removeAllGraphicsInstances(); target->initPhysics(); } void moveLeft(btHingeConstraint *target) { target->setLimit(-M_PI / 1.2f, M_PI / 1.2f); target->enableAngularMotor(true, -15.0, 4000.f); } void moveRight(btHingeConstraint *target) { target->setLimit(-M_PI / 1.2f, M_PI / 1.2f); target->enableAngularMotor(true, 15.0, 4000.f); } /******************************************************************************************** * end custom Functions *********************************************************************************************/ void BasicExample::stepSimulation(float deltaTime) { if (0)//m_once) { m_once = false; btHingeConstraint* hinge = (btHingeConstraint*)m_dynamicsWorld->getConstraint(0); btRigidBody& bodyA = hinge->getRigidBodyA(); btTransform trA = bodyA.getWorldTransform(); btVector3 hingeAxisInWorld = trA.getBasis()*hinge->getFrameOffsetA().getBasis().getColumn(2); hinge->getRigidBodyA().applyTorque(-hingeAxisInWorld * 10); hinge->getRigidBodyB().applyTorque(hingeAxisInWorld * 10); } //get distance //check distance if (body->getCenterOfMassPosition().getZ() < 0) distance = sqrt(pow((body->getCenterOfMassPosition().getZ() - linkBody->getCenterOfMassPosition().getZ()), 2) + pow((body->getCenterOfMassPosition().getY() - linkBody->getCenterOfMassPosition().getY()), 2)) - 0.225; //b3Printf("distance = %f\n", distance); else distance = -sqrt(pow((body->getCenterOfMassPosition().getZ() - linkBody->getCenterOfMassPosition().getZ()), 2) + pow((body->getCenterOfMassPosition().getY() - linkBody->getCenterOfMassPosition().getY()), 2)) - 0.225; //collison check int numManifolds = m_dynamicsWorld->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { if (m_dynamicsWorld->getDispatcher()->getNumManifolds() == 0) continue; btPersistentManifold* contactManifold = m_dynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); const btCollisionObject* obA = contactManifold->getBody0(); const btCollisionObject* obB = contactManifold->getBody1(); int numContacts = contactManifold->getNumContacts(); for (int j = 0; j < numContacts; j++) { btManifoldPoint& pt = contactManifold->getContactPoint(j); if (pt.getDistance() < 0.f) { const btVector3& ptA = pt.getPositionWorldOnA(); const btVector3& ptB = pt.getPositionWorldOnB(); const btVector3& normalOnB = pt.m_normalWorldOnB; initState(this); b3Printf("check\n"); /******************************************************************************************** * start RL *********************************************************************************************/ float lr = 0.5f; // LR for (int t = 0; t < 10000; t++) { for (int i = 0; i < AR.memory.num_elements; i++) { float a = (float)AR.memory.moved_array[i]; float b = AR.memory.reward_array[i]; const float error = b - lh.getY(a); const float sqr_error = 0.5 * error * error; const float da = 2.0 * error * -a; const float db = 2.0 * error * -1; lh.a -= da * lr; lh.b -= db * lr; } } needStuding = false; AR.clearHistory(); /******************************************************************************************** * end RL *********************************************************************************************/ } } } /******************************************************************************************** * start select Move *********************************************************************************************/ int thisMoved = -1; if (needStuding) { // random move thisMoved = ((int)rand() % 2 == 0) ? (1) : (0); } else { // learned move thisMoved = (lh.getY(distance) >= 0.5) ? (0) : (1); } // moving if (thisMoved == ACT_MOVE_LEFT) { moveLeft(hinge); } else { moveRight(hinge); } // check current b3Printf("moved = %d\tdistance=%f\ttcurrent Y = %f\n", thisMoved, distance, lh.getY(distance)); // Memory AR.recordHistory(thisMoved, distance); /******************************************************************************************** * end select RL *********************************************************************************************/ m_dynamicsWorld->stepSimulation(1. / 240, 0); static int count = 0; } void BasicExample::initPhysics() { int upAxis = 1; m_guiHelper->setUpAxis(upAxis); createEmptyDynamicsWorld(); m_dynamicsWorld->getSolverInfo().m_splitImpulse = false; m_dynamicsWorld->setGravity(btVector3(0, 0, -10)); m_guiHelper->createPhysicsDebugDrawer(m_dynamicsWorld); int mode = btIDebugDraw::DBG_DrawWireframe + btIDebugDraw::DBG_DrawConstraints + btIDebugDraw::DBG_DrawConstraintLimits; m_dynamicsWorld->getDebugDrawer()->setDebugMode(mode); { // create a door using hinge constraint attached to the world int numLinks = 2; bool spherical = false; //set it ot false -to use 1DoF hinges instead of 3DoF sphericals bool canSleep = false; bool selfCollide = false; btVector3 baseHalfExtents(0.05, 0.37, 0.1); btVector3 linkHalfExtents(0.05, 0.37, 0.1); btBoxShape* baseBox = new btBoxShape(baseHalfExtents); btVector3 basePosition = btVector3(-0.4f, 4.f, 0.f); btTransform baseWorldTrans; baseWorldTrans.setIdentity(); baseWorldTrans.setOrigin(basePosition); //mbC->forceMultiDof(); //if !spherical, you can comment this line to check the 1DoF algorithm //init the base btVector3 baseInertiaDiag(0.f, 0.f, 0.f); float baseMass = 0.f; float linkMass = 1.f; btRigidBody* base = createRigidBody(baseMass, baseWorldTrans, baseBox); m_dynamicsWorld->removeRigidBody(base); base->setDamping(0, 0); m_dynamicsWorld->addRigidBody(base, collisionFilterGroup, collisionFilterMask); btBoxShape* linkBox1 = new btBoxShape(linkHalfExtents); btSphereShape* linkSphere = new btSphereShape(radius); btRigidBody* prevBody = base; for (int i = 0; i<numLinks; i++) { btTransform linkTrans; linkTrans = baseWorldTrans; linkTrans.setOrigin(basePosition - btVector3(0, linkHalfExtents[1] * 2.f*(i + 1), 0)); btCollisionShape* colOb = 0; if (i == 0) { colOb = linkBox1; } else { colOb = linkSphere; } linkBody = createRigidBody(linkMass, linkTrans, colOb); m_dynamicsWorld->removeRigidBody(linkBody); m_dynamicsWorld->addRigidBody(linkBody, collisionFilterGroup, collisionFilterMask); linkBody->setDamping(0, 0); btTypedConstraint* con = 0; if (i == 0) { //create a hinge constraint btVector3 pivotInA(0, -linkHalfExtents[1], 0); btVector3 pivotInB(0, linkHalfExtents[1], 0); btVector3 axisInA(1, 0, 0); btVector3 axisInB(1, 0, 0); bool useReferenceA = true; hinge = new btHingeConstraint(*prevBody, *linkBody, pivotInA, pivotInB, axisInA, axisInB, useReferenceA); hinge->setLimit(0.0f, 0.0f); m_dynamicsWorld->addConstraint(hinge, true); con = hinge; } else { btTransform pivotInA(btQuaternion::getIdentity(), btVector3(0, -radius, 0)); //par body's COM to cur body's COM offset btTransform pivotInB(btQuaternion::getIdentity(), btVector3(0, radius, 0)); //cur body's COM to cur body's PIV offset btGeneric6DofSpring2Constraint* fixed = new btGeneric6DofSpring2Constraint(*prevBody, *linkBody, pivotInA, pivotInB); fixed->setLinearLowerLimit(btVector3(0, 0, 0)); fixed->setLinearUpperLimit(btVector3(0, 0, 0)); fixed->setAngularLowerLimit(btVector3(0, 0, 0)); fixed->setAngularUpperLimit(btVector3(0, 0, 0)); con = fixed; } btAssert(con); if (con) { btJointFeedback* fb = new btJointFeedback(); m_jointFeedback.push_back(fb); con->setJointFeedback(fb); m_dynamicsWorld->addConstraint(con, true); } prevBody = linkBody; } } if (1) { btVector3 groundHalfExtents(0.4, 0.0, 0.4); groundHalfExtents[upAxis] = 0.025f; btBoxShape* box = new btBoxShape(groundHalfExtents); box->initializePolyhedralFeatures(); btTransform start; start.setIdentity(); groundOrigin_target = btVector3(-0.4f, 3.9f, -0.77f); /* btVector3 basePosition = btVector3(-0.4f, 3.f, 0.f); btQuaternion groundOrn(btVector3(0, 1, 0), 0.25*SIMD_PI);*/ start.setOrigin(groundOrigin_target); body = createRigidBody(0, start, box); body->setFriction(0); } m_guiHelper->autogenerateGraphicsObjects(m_dynamicsWorld); } bool BasicExample::keyboardCallback(int key, int state) { bool handled = false; if (state) { switch (key) { case B3G_HOME: { // b3Printf("Rest.\n"); initState(this); break; } case B3G_LEFT_ARROW: { // b3Printf("left.\n"); moveLeft(hinge); handled = true; break; } case B3G_RIGHT_ARROW: { // b3Printf("right.\n"); moveRight(hinge); handled = true; break; } case B3G_UP_ARROW: { // b3Printf("left.\n"); btVector3 basePosition = btVector3(0.0, 0.0f,1.54f); body->translate(basePosition); break; } case B3G_DOWN_ARROW: { // b3Printf("left.\n"); btVector3 basePosition = btVector3(0.0, 0.0f, -1.54f); body->translate(basePosition); break; } } } else { switch (key) { case B3G_LEFT_ARROW: case B3G_RIGHT_ARROW: { lockLiftHinge(); handled = true; break; } default: break; } } return handled; } void BasicExample::lockLiftHinge(void) { btScalar hingeAngle = hinge->getHingeAngle(); btScalar lowLim = hinge->getLowerLimit(); btScalar hiLim = hinge->getUpperLimit(); hinge->enableAngularMotor(false, 0, 0); if (hingeAngle < lowLim) { // m_liftHinge->setLimit(lowLim, lowLim + LIFT_EPS); hinge->setLimit(lowLim, lowLim); } else if (hingeAngle > hiLim) { // m_liftHinge->setLimit(hiLim - LIFT_EPS, hiLim); hinge->setLimit(hiLim, hiLim); } else { // m_liftHinge->setLimit(hingeAngle - LIFT_EPS, hingeAngle + LIFT_EPS); hinge->setLimit(hingeAngle, hingeAngle); } return; } CommonExampleInterface* BasicExampleCreateFunc(CommonExampleOptions& options) { return new BasicExample(options.m_guiHelper); } B3_STANDALONE_EXAMPLE(BasicExampleCreateFunc)<|endoftext|>
<commit_before>/* * Copyright (C) 2017-present ScyllaDB * */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <seastar/core/coroutine.hh> #include "table_helper.hh" #include "cql3/query_processor.hh" #include "cql3/statements/create_table_statement.hh" #include "cql3/statements/modification_statement.hh" #include "replica/database.hh" #include "service/migration_manager.hh" future<> table_helper::setup_table(cql3::query_processor& qp, const sstring& create_cql) { auto db = qp.db(); auto parsed = cql3::query_processor::parse_statement(create_cql); cql3::statements::raw::cf_statement* parsed_cf_stmt = static_cast<cql3::statements::raw::cf_statement*>(parsed.get()); (void)parsed_cf_stmt->keyspace(); // This will assert if cql statement did not contain keyspace ::shared_ptr<cql3::statements::create_table_statement> statement = static_pointer_cast<cql3::statements::create_table_statement>( parsed_cf_stmt->prepare(db, qp.get_cql_stats())->statement); auto schema = statement->get_cf_meta_data(db); if (db.has_schema(schema->ks_name(), schema->cf_name())) { return make_ready_future<>(); } // Generate the CF UUID based on its KF names. This is needed to ensure that // all Nodes that create it would create it with the same UUID and we don't // hit the #420 issue. auto uuid = generate_legacy_id(schema->ks_name(), schema->cf_name()); schema_builder b(schema); b.set_uuid(uuid); // We don't care it it fails really - this may happen due to concurrent // "CREATE TABLE" invocation on different Nodes. // The important thing is that it will converge eventually (some traces may // be lost in a process but that's ok). return qp.get_migration_manager().announce_new_column_family(b.build()).discard_result().handle_exception([] (auto ep) {});; } future<> table_helper::cache_table_info(cql3::query_processor& qp, service::query_state& qs) { if (!_prepared_stmt) { // if prepared statement has been invalidated - drop cached pointers _insert_stmt = nullptr; } else if (!_is_fallback_stmt) { // we've already prepared the non-fallback statement return now(); } return qp.prepare(_insert_cql, qs.get_client_state(), false) .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept { _prepared_stmt = std::move(msg_ptr->get_prepared()); shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement; _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt); _is_fallback_stmt = false; }).handle_exception_type([this, &qs, &qp] (exceptions::invalid_request_exception& eptr) { // the non-fallback statement can't be prepared if (!_insert_cql_fallback) { return make_exception_future(eptr); } if (_is_fallback_stmt && _prepared_stmt) { // we have already prepared the fallback statement return now(); } return qp.prepare(_insert_cql_fallback.value(), qs.get_client_state(), false) .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept { _prepared_stmt = std::move(msg_ptr->get_prepared()); shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement; _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt); _is_fallback_stmt = true; }); }).handle_exception([this, &qp] (auto eptr) { // One of the possible causes for an error here could be the table that doesn't exist. //FIXME: discarded future. (void)setup_table(qp, _create_cql).discard_result(); // We throw the bad_column_family exception because the caller // expects and accounts this type of errors. try { std::rethrow_exception(eptr); } catch (std::exception& e) { throw bad_column_family(_keyspace, _name, e); } catch (...) { throw bad_column_family(_keyspace, _name); } }); } future<> table_helper::insert(cql3::query_processor& qp, service::query_state& qs, noncopyable_function<cql3::query_options ()> opt_maker) { return cache_table_info(qp, qs).then([this, &qp, &qs, opt_maker = std::move(opt_maker)] () mutable { return do_with(opt_maker(), [this, &qp, &qs] (auto& opts) { opts.prepare(_prepared_stmt->bound_names); return _insert_stmt->execute(qp, qs, opts); }); }).discard_result(); } future<> table_helper::setup_keyspace(cql3::query_processor& qp, std::string_view keyspace_name, sstring replication_factor, service::query_state& qs, std::vector<table_helper*> tables) { if (this_shard_id() != 0) { co_return; } if (std::any_of(tables.begin(), tables.end(), [&] (table_helper* t) { return t->_keyspace != keyspace_name; })) { throw std::invalid_argument("setup_keyspace called with table_helper for different keyspace"); } data_dictionary::database db = qp.db(); // Create a keyspace if (!db.has_keyspace(keyspace_name)) { std::map<sstring, sstring> opts; opts["replication_factor"] = replication_factor; auto ksm = keyspace_metadata::new_keyspace(keyspace_name, "org.apache.cassandra.locator.SimpleStrategy", std::move(opts), true); co_await qp.get_migration_manager().announce_new_keyspace(ksm); } qs.get_client_state().set_keyspace(db.real_database(), keyspace_name); // Create tables co_await parallel_for_each(tables, [&qp] (table_helper* t) { return table_helper::setup_table(qp, t->_create_cql); }); } <commit_msg>table_helper: move schema creation code to use raft<commit_after>/* * Copyright (C) 2017-present ScyllaDB * */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <seastar/core/coroutine.hh> #include "table_helper.hh" #include "cql3/query_processor.hh" #include "cql3/statements/create_table_statement.hh" #include "cql3/statements/modification_statement.hh" #include "replica/database.hh" #include "service/migration_manager.hh" future<> table_helper::setup_table(cql3::query_processor& qp, const sstring& create_cql) { auto db = qp.db(); auto parsed = cql3::query_processor::parse_statement(create_cql); cql3::statements::raw::cf_statement* parsed_cf_stmt = static_cast<cql3::statements::raw::cf_statement*>(parsed.get()); (void)parsed_cf_stmt->keyspace(); // This will assert if cql statement did not contain keyspace ::shared_ptr<cql3::statements::create_table_statement> statement = static_pointer_cast<cql3::statements::create_table_statement>( parsed_cf_stmt->prepare(db, qp.get_cql_stats())->statement); auto schema = statement->get_cf_meta_data(db); if (db.has_schema(schema->ks_name(), schema->cf_name())) { co_return; } auto& mm = qp.get_migration_manager(); co_await mm.schema_read_barrier(); if (db.has_schema(schema->ks_name(), schema->cf_name())) { // re-check after read barrier co_return; } // Generate the CF UUID based on its KF names. This is needed to ensure that // all Nodes that create it would create it with the same UUID and we don't // hit the #420 issue. auto uuid = generate_legacy_id(schema->ks_name(), schema->cf_name()); schema_builder b(schema); b.set_uuid(uuid); // We don't care it it fails really - this may happen due to concurrent // "CREATE TABLE" invocation on different Nodes. // The important thing is that it will converge eventually (some traces may // be lost in a process but that's ok). try { co_return co_await mm.announce(co_await mm.prepare_new_column_family_announcement(b.build())); } catch (...) {} } future<> table_helper::cache_table_info(cql3::query_processor& qp, service::query_state& qs) { if (!_prepared_stmt) { // if prepared statement has been invalidated - drop cached pointers _insert_stmt = nullptr; } else if (!_is_fallback_stmt) { // we've already prepared the non-fallback statement return now(); } return qp.prepare(_insert_cql, qs.get_client_state(), false) .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept { _prepared_stmt = std::move(msg_ptr->get_prepared()); shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement; _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt); _is_fallback_stmt = false; }).handle_exception_type([this, &qs, &qp] (exceptions::invalid_request_exception& eptr) { // the non-fallback statement can't be prepared if (!_insert_cql_fallback) { return make_exception_future(eptr); } if (_is_fallback_stmt && _prepared_stmt) { // we have already prepared the fallback statement return now(); } return qp.prepare(_insert_cql_fallback.value(), qs.get_client_state(), false) .then([this] (shared_ptr<cql_transport::messages::result_message::prepared> msg_ptr) noexcept { _prepared_stmt = std::move(msg_ptr->get_prepared()); shared_ptr<cql3::cql_statement> cql_stmt = _prepared_stmt->statement; _insert_stmt = dynamic_pointer_cast<cql3::statements::modification_statement>(cql_stmt); _is_fallback_stmt = true; }); }).handle_exception([this, &qp] (auto eptr) { // One of the possible causes for an error here could be the table that doesn't exist. //FIXME: discarded future. (void)qp.container().invoke_on(0, [create_cql = _create_cql] (cql3::query_processor& qp) -> future<> { co_return co_await table_helper::setup_table(qp, create_cql); }); // We throw the bad_column_family exception because the caller // expects and accounts this type of errors. try { std::rethrow_exception(eptr); } catch (std::exception& e) { throw bad_column_family(_keyspace, _name, e); } catch (...) { throw bad_column_family(_keyspace, _name); } }); } future<> table_helper::insert(cql3::query_processor& qp, service::query_state& qs, noncopyable_function<cql3::query_options ()> opt_maker) { return cache_table_info(qp, qs).then([this, &qp, &qs, opt_maker = std::move(opt_maker)] () mutable { return do_with(opt_maker(), [this, &qp, &qs] (auto& opts) { opts.prepare(_prepared_stmt->bound_names); return _insert_stmt->execute(qp, qs, opts); }); }).discard_result(); } future<> table_helper::setup_keyspace(cql3::query_processor& qp, std::string_view keyspace_name, sstring replication_factor, service::query_state& qs, std::vector<table_helper*> tables) { if (this_shard_id() != 0) { co_return; } if (std::any_of(tables.begin(), tables.end(), [&] (table_helper* t) { return t->_keyspace != keyspace_name; })) { throw std::invalid_argument("setup_keyspace called with table_helper for different keyspace"); } data_dictionary::database db = qp.db(); auto& mm = qp.get_migration_manager(); if (!db.has_keyspace(keyspace_name)) { co_await mm.schema_read_barrier(); // Create a keyspace if (!db.has_keyspace(keyspace_name)) { std::map<sstring, sstring> opts; opts["replication_factor"] = replication_factor; auto ksm = keyspace_metadata::new_keyspace(keyspace_name, "org.apache.cassandra.locator.SimpleStrategy", std::move(opts), true); co_await mm.announce(mm.prepare_new_keyspace_announcement(ksm)); } } qs.get_client_state().set_keyspace(db.real_database(), keyspace_name); // Create tables co_await parallel_for_each(tables, [&qp] (table_helper* t) { return table_helper::setup_table(qp, t->_create_cql); }); } <|endoftext|>
<commit_before>#include "LinearRegression.h" #include <armadillo> #include <assert.h> #include <iostream> using namespace arma; LinearRegression::LinearRegression(mat &x, vec &y) : x{x}, y{y}, trained{false} { assert(x.n_rows == y.n_rows); // Create bias column and append at the end of x mat bias = ones<mat>(this->ExampleNumber(), 1); this->x.insert_cols(this->x.n_cols, bias); } LinearRegression::~LinearRegression() {} void LinearRegression::AddData(mat &extraX, vec &extraY) { assert(extraX.n_rows == extraY.n_rows); // Add 1 because x has a bias column assert((extraX.n_cols + 1) == this->x.n_cols); this->trained = false; // Add Bias column to latest added input mat bias = ones<mat>(extraX.n_rows, 1); mat inputX = extraX; inputX.insert_cols(inputX.n_cols, bias); this->x.insert_rows(this->x.n_rows, inputX); this->y.insert_rows(this->y.n_rows, extraY); } void LinearRegression::Train(bool NormEqu, double alpha, unsigned int iters) { if (NormEqu) { this->NormalEquation(); } else { this->GradientDescent(alpha, iters); } } void LinearRegression::NormalEquation() { mat xtx = (this->x.t() * this->x); // Check if xtx is full-rank matrix if (rank(xtx) == xtx.n_rows) { this->theta = pinv(xtx) * this->x.t() * this->y; this->trained = true; } else { std::cerr << "you have to regularize your data set" << std::endl; } } uword LinearRegression::ExampleNumber() { return this->x.n_rows; } double LinearRegression::Predict(vec &x) { if (!this->trained) { std::cerr << "This model hasn't been trained" << std::endl; return 0.0; } vec bias = vec("1"); vec input = x; input.insert_rows(x.n_rows, bias); return (input.t() * this->theta).eval()(0, 0); } vec LinearRegression::CostDerivative() { vec deriv = (((this->x * this->theta) - this->y).t() * this->x).t(); return 1 / (float)this->ExampleNumber() * deriv; } void LinearRegression::GradientDescent(double alpha, unsigned int iters) { if (this->trained != true) { // Initialize Theta this->theta = ones<vec>(this->x.n_cols); } for (unsigned int i = 0; i < iters; i++) { this->theta = this->theta - (alpha * this->CostDerivative()); } this->trained = true; } <commit_msg>Modified if statement of Gradient Descent<commit_after>#include "LinearRegression.h" #include <armadillo> #include <assert.h> #include <iostream> using namespace arma; LinearRegression::LinearRegression(mat &x, vec &y) : x{x}, y{y}, trained{false} { assert(x.n_rows == y.n_rows); // Create bias column and append at the end of x mat bias = ones<mat>(this->ExampleNumber(), 1); this->x.insert_cols(this->x.n_cols, bias); } LinearRegression::~LinearRegression() {} void LinearRegression::AddData(mat &extraX, vec &extraY) { assert(extraX.n_rows == extraY.n_rows); // Add 1 because x has a bias column assert((extraX.n_cols + 1) == this->x.n_cols); this->trained = false; // Add Bias column to latest added input mat bias = ones<mat>(extraX.n_rows, 1); mat inputX = extraX; inputX.insert_cols(inputX.n_cols, bias); this->x.insert_rows(this->x.n_rows, inputX); this->y.insert_rows(this->y.n_rows, extraY); } void LinearRegression::Train(bool NormEqu, double alpha, unsigned int iters) { if (NormEqu) { this->NormalEquation(); } else { this->GradientDescent(alpha, iters); } } void LinearRegression::NormalEquation() { mat xtx = (this->x.t() * this->x); // Check if xtx is full-rank matrix if (rank(xtx) == xtx.n_rows) { this->theta = pinv(xtx) * this->x.t() * this->y; this->trained = true; } else { std::cerr << "you have to regularize your data set" << std::endl; } } uword LinearRegression::ExampleNumber() { return this->x.n_rows; } double LinearRegression::Predict(vec &x) { if (!this->trained) { std::cerr << "This model hasn't been trained" << std::endl; return 0.0; } vec bias = vec("1"); vec input = x; input.insert_rows(x.n_rows, bias); return (input.t() * this->theta).eval()(0, 0); } vec LinearRegression::CostDerivative() { vec deriv = (((this->x * this->theta) - this->y).t() * this->x).t(); return 1 / (float)this->ExampleNumber() * deriv; } void LinearRegression::GradientDescent(double alpha, unsigned int iters) { if (this->trained != true || this->theta.n_rows != this->x.n_cols) { // Initialize Theta this->theta = ones<vec>(this->x.n_cols); } for (unsigned int i = 0; i < iters; i++) { this->theta = this->theta - (alpha * this->CostDerivative()); } this->trained = true; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (c) Wolf Vollprecht, Johan Mabille and Sylvain Corlay * * Copyright (c) QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include "gtest/gtest.h" #include "xtensor-python/pyarray.hpp" namespace xt { namespace testing { class pyarray_traits: public ::testing::Test { protected: using dynamic_type = xt::pyarray<double>; using row_major_type = xt::pyarray<double, xt::layout_type::row_major>; using column_major_type = xt::pyarray<double, xt::layout_type::column_major>; dynamic_type d1 = {{0., 1.}, {0., 10.}, {0., 100.}}; dynamic_type d2 = {{0., 2.}, {0., 20.}, {0., 200.}}; row_major_type r1 = {{0., 1.}, {0., 10.}, {0., 100.}}; row_major_type r2 = {{0., 2.}, {0., 20.}, {0., 200.}}; column_major_type c1 = {{0., 1.}, {0., 10.}, {0., 100.}}; column_major_type c2 = {{0., 2.}, {0., 20.}, {0., 200.}}; template <class T> bool test_has_strides(T const&) { return xt::has_strides<T>::value; } template <class T> xt::layout_type test_result_layout(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return (tmp1 + tmp2).layout(); } template <class T> bool test_linear_assign(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); T res = tmp1 + tmp2; return xt::xassign_traits<T, decltype(tmp1 + tmp2)>::linear_assign(res, tmp1 + tmp2, true); } template <class T> bool test_simd_linear_assign(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return xt::xassign_traits<T, decltype(tmp2)>::simd_linear_assign(); } template <class T> bool test_linear_static_layout(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return xt::detail::linear_static_layout<decltype(tmp1), decltype(tmp2)>(); } template <class T> bool test_contiguous_layout(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return decltype(tmp1)::contiguous_layout && decltype(tmp2)::contiguous_layout; } }; TEST_F(pyarray_traits, result_layout) { EXPECT_TRUE(d1.layout() == layout_type::row_major); EXPECT_TRUE(test_result_layout(d1, d2) == layout_type::row_major); EXPECT_TRUE(r1.layout() == layout_type::row_major); EXPECT_TRUE(test_result_layout(r1, r2) == layout_type::row_major); EXPECT_TRUE(c1.layout() == layout_type::column_major); EXPECT_TRUE(test_result_layout(c1, c2) == layout_type::column_major); } TEST_F(pyarray_traits, has_strides) { EXPECT_TRUE(test_has_strides(d1)); EXPECT_TRUE(test_has_strides(r1)); EXPECT_TRUE(test_has_strides(c1)); } TEST_F(pyarray_traits, has_linear_assign) { EXPECT_TRUE(d2.has_linear_assign(d1.strides())); EXPECT_TRUE(r2.has_linear_assign(r1.strides())); EXPECT_TRUE(c2.has_linear_assign(c1.strides())); } TEST_F(pyarray_traits, linear_assign) { EXPECT_TRUE(test_linear_assign(d1, d2)); EXPECT_TRUE(test_linear_assign(r1, r2)); EXPECT_TRUE(test_linear_assign(c1, c2)); } TEST_F(pyarray_traits, simd_linear_assign) { #ifdef XTENSOR_USE_XSIMD EXPECT_FALSE(test_simd_linear_assign(d1, d2)); EXPECT_TRUE(test_simd_linear_assign(r1, r2)); EXPECT_TRUE(test_simd_linear_assign(c1, c2)); #else EXPECT_FALSE(test_simd_linear_assign(d1, d2)); EXPECT_FALSE(test_simd_linear_assign(r1, r2)); EXPECT_FALSE(test_simd_linear_assign(c1, c2)); #endif } TEST_F(pyarray_traits, linear_static_layout) { EXPECT_FALSE(test_linear_static_layout(d1, d2)); EXPECT_TRUE(test_linear_static_layout(r1, r2)); EXPECT_TRUE(test_linear_static_layout(c1, c2)); } TEST_F(pyarray_traits, contiguous_layout) { EXPECT_FALSE(test_contiguous_layout(d1, d2)); EXPECT_TRUE(test_contiguous_layout(r1, r2)); EXPECT_TRUE(test_contiguous_layout(c1, c2)); } } } <commit_msg>test both static and dynamic simd linear assign<commit_after>/*************************************************************************** * Copyright (c) Wolf Vollprecht, Johan Mabille and Sylvain Corlay * * Copyright (c) QuantStack * * * * Distributed under the terms of the BSD 3-Clause License. * * * * The full license is in the file LICENSE, distributed with this software. * ****************************************************************************/ #include "gtest/gtest.h" #include "xtensor-python/pyarray.hpp" namespace xt { namespace testing { class pyarray_traits: public ::testing::Test { protected: using dynamic_type = xt::pyarray<double>; using row_major_type = xt::pyarray<double, xt::layout_type::row_major>; using column_major_type = xt::pyarray<double, xt::layout_type::column_major>; dynamic_type d1 = {{0., 1.}, {0., 10.}, {0., 100.}}; dynamic_type d2 = {{0., 2.}, {0., 20.}, {0., 200.}}; row_major_type r1 = {{0., 1.}, {0., 10.}, {0., 100.}}; row_major_type r2 = {{0., 2.}, {0., 20.}, {0., 200.}}; column_major_type c1 = {{0., 1.}, {0., 10.}, {0., 100.}}; column_major_type c2 = {{0., 2.}, {0., 20.}, {0., 200.}}; template <class T> bool test_has_strides(T const&) { return xt::has_strides<T>::value; } template <class T> xt::layout_type test_result_layout(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return (tmp1 + tmp2).layout(); } template <class T> bool test_linear_assign(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); T res = tmp1 + tmp2; return xt::xassign_traits<T, decltype(tmp1 + tmp2)>::linear_assign(res, tmp1 + tmp2, true); } template <class T> bool test_static_simd_linear_assign(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return xt::xassign_traits<T, decltype(tmp2)>::simd_linear_assign(); } template <class T> bool test_dynamic_simd_linear_assign(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return xt::xassign_traits<T, decltype(tmp2)>::simd_linear_assign(a1, tmp2); } template <class T> bool test_linear_static_layout(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return xt::detail::linear_static_layout<decltype(tmp1), decltype(tmp2)>(); } template <class T> bool test_contiguous_layout(T const& a1, T const& a2) { auto tmp1 = pow(sin((a2 - a1) / 2.), 2.); auto tmp2 = cos(a1); return decltype(tmp1)::contiguous_layout && decltype(tmp2)::contiguous_layout; } }; TEST_F(pyarray_traits, result_layout) { EXPECT_TRUE(d1.layout() == layout_type::row_major); EXPECT_TRUE(test_result_layout(d1, d2) == layout_type::row_major); EXPECT_TRUE(r1.layout() == layout_type::row_major); EXPECT_TRUE(test_result_layout(r1, r2) == layout_type::row_major); EXPECT_TRUE(c1.layout() == layout_type::column_major); EXPECT_TRUE(test_result_layout(c1, c2) == layout_type::column_major); } TEST_F(pyarray_traits, has_strides) { EXPECT_TRUE(test_has_strides(d1)); EXPECT_TRUE(test_has_strides(r1)); EXPECT_TRUE(test_has_strides(c1)); } TEST_F(pyarray_traits, has_linear_assign) { EXPECT_TRUE(d2.has_linear_assign(d1.strides())); EXPECT_TRUE(r2.has_linear_assign(r1.strides())); EXPECT_TRUE(c2.has_linear_assign(c1.strides())); } TEST_F(pyarray_traits, linear_assign) { EXPECT_TRUE(test_linear_assign(d1, d2)); EXPECT_TRUE(test_linear_assign(r1, r2)); EXPECT_TRUE(test_linear_assign(c1, c2)); } TEST_F(pyarray_traits, static_simd_linear_assign) { #ifdef XTENSOR_USE_XSIMD EXPECT_FALSE(test_static_simd_linear_assign(d1, d2)); EXPECT_TRUE(test_static_simd_linear_assign(r1, r2)); EXPECT_TRUE(test_static_simd_linear_assign(c1, c2)); #else EXPECT_FALSE(test_static_simd_linear_assign(d1, d2)); EXPECT_FALSE(test_static_simd_linear_assign(r1, r2)); EXPECT_FALSE(test_static_simd_linear_assign(c1, c2)); #endif } TEST_F(pyarray_traits, dynamic_simd_linear_assign) { #ifdef XTENSOR_USE_XSIMD EXPECT_TRUE(test_dynamic_simd_linear_assign(d1, d2)); EXPECT_TRUE(test_dynamic_simd_linear_assign(r1, r2)); EXPECT_TRUE(test_dynamic_simd_linear_assign(c1, c2)); #else EXPECT_FALSE(test_dynamic_simd_linear_assign(d1, d2)); EXPECT_FALSE(test_dynamic_simd_linear_assign(r1, r2)); EXPECT_FALSE(test_dynamic_simd_linear_assign(c1, c2)); #endif } TEST_F(pyarray_traits, linear_static_layout) { EXPECT_FALSE(test_linear_static_layout(d1, d2)); EXPECT_TRUE(test_linear_static_layout(r1, r2)); EXPECT_TRUE(test_linear_static_layout(c1, c2)); } TEST_F(pyarray_traits, contiguous_layout) { EXPECT_FALSE(test_contiguous_layout(d1, d2)); EXPECT_TRUE(test_contiguous_layout(r1, r2)); EXPECT_TRUE(test_contiguous_layout(c1, c2)); } } } <|endoftext|>
<commit_before>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <dcopclient.h> #include "kopeteiface.h" #include "kimifaceimpl.h" #define KOPETE_VERSION "0.10.90 >= 20050522" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo"), "andre@duffeck.de" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer, IRC maintainer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Developer"), "klingens@kde.org" ); aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, AIM, ICQ, and Yahoo plugin maintainer"), "mattr@kde.org" ); aboutData.addAuthor ( "Zack Rusin", I18N_NOOP("Developer, original Gadu plugin author"), "zack@kde.org" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN"), "shock@shockdev.ca.tc", "http://mlarouche.blogspot.com" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" ); aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; new KIMIfaceImpl(); kapp->dcopClient()->registerAs( "kopete", false ); kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <commit_msg>credit updates:<commit_after>/* Kopete , The KDE Instant Messenger Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org> Viva Chile Mierda! Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile Kopete (c) 2002-2005 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <kcmdlineargs.h> #include <kaboutdata.h> #include "kopeteapplication.h" #include <dcopclient.h> #include "kopeteiface.h" #include "kimifaceimpl.h" #define KOPETE_VERSION "0.10.90 >= 20050522" static const char description[] = I18N_NOOP( "Kopete, the KDE Instant Messenger" ); static KCmdLineOptions options[] = { { "noplugins", I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 }, { "noconnect", I18N_NOOP( "Disable auto-connection" ), 0 }, { "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n" "to auto-connect multiple accounts." ), 0 }, { "disable <plugins>", I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n" "to disable multiple plugins." ), 0 }, { "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n" "to load multiple plugins. This option has no effect when\n" "--noplugins is set and overrides all other plugin related\n" "command line options." ), 0 }, // { "url <url>", I18N_NOOP( "Load the given Kopete URL" ), 0 }, // { "!+[plugin]", I18N_NOOP( "Load specified plugins" ), 0 }, { "!+[URL]", I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0}, KCmdLineLastOption }; int main( int argc, char *argv[] ) { KAboutData aboutData( "kopete", I18N_NOOP("Kopete"), KOPETE_VERSION, description, KAboutData::License_GPL, I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org"); aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, Developer"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" ); aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" ); aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net"); aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Developer, MSN plugin maintainer"), "ogoffart @ kde.org"); aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" ); aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" ); aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk"); aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" ); aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org"); aboutData.addAuthor ( "Chetan Reddy", I18N_NOOP("Developer, Yahoo"), "chetan13@gmail.com" ); aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" ); aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" ); aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" ); aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Developer, MSN"), "shock@shockdev.ca.tc", "http://mlarouche.blogspot.com" ); aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") ); aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") ); aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") ); aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" ); aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") ); aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org"); aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" ); aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" ); aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" ); aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" ); aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" ); aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" ); aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org"); aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org"); aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net"); aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de"); aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" ); aboutData.setTranslator( I18N_NOOP("_: NAME OF TRANSLATORS\nYour names"), I18N_NOOP("_: EMAIL OF TRANSLATORS\nYour emails") ); KCmdLineArgs::init( argc, argv, &aboutData ); KCmdLineArgs::addCmdLineOptions( options ); // Add our own options. KUniqueApplication::addCmdLineOptions(); KopeteApplication kopete; new KIMIfaceImpl(); kapp->dcopClient()->registerAs( "kopete", false ); kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec kopete.exec(); } // vim: set noet ts=4 sts=4 sw=4: <|endoftext|>
<commit_before>void Config() { // 7-DEC-2000 09:00 // Switch on Transition Radiation simulation. 6/12/00 18:00 // iZDC=1 7/12/00 09:00 // ThetaRange is (0., 180.). It was (0.28,179.72) 7/12/00 09:00 new AliGeant3("C++ Interface to Geant3"); if (!gSystem->Getenv("CONFIG_FILE")) { TFile *rootfile = new TFile("galice.root","recreate"); rootfile->SetCompressionLevel(2); } TGeant3 *geant3 = (TGeant3*)gMC; // // Set External decayer AliDecayer* decayer = new AliDecayerPythia(); decayer->SetForceDecay(kAll); decayer->Init(); gMC->SetExternalDecayer(decayer); // // //======================================================================= // ******* GEANT STEERING parameters FOR ALICE SIMULATION ******* geant3->SetTRIG(1); //Number of events to be processed geant3->SetSWIT(4,10); geant3->SetDEBU(0,0,1); //geant3->SetSWIT(2,2); geant3->SetDCAY(1); geant3->SetPAIR(1); geant3->SetCOMP(1); geant3->SetPHOT(1); geant3->SetPFIS(0); geant3->SetDRAY(0); geant3->SetANNI(1); geant3->SetBREM(1); geant3->SetMUNU(1); geant3->SetCKOV(1); geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) geant3->SetLOSS(2); geant3->SetMULS(1); geant3->SetRAYL(1); geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2) geant3->SetERAN(5.e-7); Float_t cut = 1.e-3; // 1MeV cut by default Float_t tofmax = 1.e10; // GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX geant3->SetCUTS(cut,cut, cut, cut, cut, cut, cut, cut, cut, cut, tofmax); // //======================================================================= // ************* STEERING parameters FOR ALICE SIMULATION ************** // --- Specify event type to be tracked through the ALICE setup // --- All positions are in cm, angles in degrees, and P and E in GeV if (gSystem->Getenv("CONFIG_NPARTICLES")) { int nParticles = atoi(gSystem->Getenv("CONFIG_NPARTICLES")); } else { int nParticles = 50; } AliGenHIJINGpara *gener = new AliGenHIJINGpara(nParticles); gener->SetMomentumRange(0,999); gener->SetPhiRange(0,360); // gener->SetThetaRange(0.28,179.72); gener->SetThetaRange(0.,180.); gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position gener->Init(); // // Activate this line if you want the vertex smearing to happen // track by track // //gener->SetVertexSmear(perTrack); gAlice->SetField(-999,2); //Specify maximum magnetic field in Tesla (neg. ==> default field) Int_t iABSO=1; Int_t iCASTOR=1; Int_t iDIPO=1; Int_t iFMD=1; Int_t iFRAME=1; Int_t iHALL=1; Int_t iITS=1; Int_t iMAG=1; Int_t iMUON=1; Int_t iPHOS=1; Int_t iPIPE=1; Int_t iPMD=1; Int_t iRICH=1; Int_t iSHIL=1; Int_t iSTART=1; Int_t iTOF=1; Int_t iTPC=1; Int_t iTRD=1; Int_t iZDC=1; //=================== Alice BODY parameters ============================= AliBODY *BODY = new AliBODY("BODY","Alice envelop"); if(iMAG) { //=================== MAG parameters ============================ // --- Start with Magnet since detector layouts may be depending --- // --- on the selected Magnet dimensions --- AliMAG *MAG = new AliMAG("MAG","Magnet"); } if(iABSO) { //=================== ABSO parameters ============================ AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber"); } if(iDIPO) { //=================== DIPO parameters ============================ AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2"); } if(iHALL) { //=================== HALL parameters ============================ AliHALL *HALL = new AliHALL("HALL","Alice Hall"); } if(iFRAME) { //=================== FRAME parameters ============================ AliFRAME *FRAME = new AliFRAMEv2("FRAME","Space Frame"); } if(iSHIL) { //=================== SHIL parameters ============================ AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding"); } if(iPIPE) { //=================== PIPE parameters ============================ AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe"); } if(iITS) { //=================== ITS parameters ============================ // // As the innermost detector in ALICE, the Inner Tracking System "impacts" on // almost all other detectors. This involves the fact that the ITS geometry // still has several options to be followed in parallel in order to determine // the best set-up which minimizes the induced background. All the geometries // available to date are described in the following. Read carefully the comments // and use the default version (the only one uncommented) unless you are making // comparisons and you know what you are doing. In this case just uncomment the // ITS geometry you want to use and run Aliroot. // // Detailed geometries: // // //AliITS *ITS = new AliITSv3("ITS","Old ITS detailed version as of the ALICE TP"); // //AliITS *ITS = new AliITSv5("ITS","Current ITS detailed version used for the ITS TDR"); // //AliITS *ITS = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services"); // AliITS *ITS = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services"); // //AliITSvPPRasymm *ITS = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // //AliITSvPPRsymm *ITS = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // // // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful // for reconstruction !): // // // //AliITS *ITS = new AliITSv1("ITS","Old ITS coarse version as of the ALICE TP"); // //AliITSvPPRcoarseasymm *ITS = new AliITSvPPRcoarseasymm("ITS","New ITS coarse version with asymmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // //AliITS *ITS = new AliITSvPPRcoarsesymm("ITS","New ITS coarse version with symmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // // // // Geant3 <-> EUCLID conversion // ============================ // // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and // media to two ASCII files (called by default ITSgeometry.euc and // ITSgeometry.tme) in a format understandable to the CAD system EUCLID. // The default (=0) means that you dont want to use this facility. // ITS->SetEUCLID(0); } if(iTPC) { //============================ TPC parameters ================================ // --- This allows the user to specify sectors for the SLOW (TPC geometry 2) // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper) // --- sectors are specified, any value other than that requires at least one // --- sector (lower or upper)to be specified! // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0) // --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0) // --- SecLows - number of lower sectors specified (up to 6) // --- SecUps - number of upper sectors specified (up to 12) // --- Sens - sensitive strips for the Slow Simulator !!! // --- This does NOT work if all S or L-sectors are specified, i.e. // --- if SecAL or SecAU < 0 // // //----------------------------------------------------------------------------- // gROOT->LoadMacro("SetTPCParam.C"); // AliTPCParam *param = SetTPCParam(); AliTPC *TPC = new AliTPCv2("TPC","Default"); // All sectors included TPC->SetSecAL(-1); TPC->SetSecAU(-1); } if(iTOF) { //=================== TOF parameters ============================ AliTOF *TOF = new AliTOFv2("TOF","normal TOF"); } if(iRICH) { //=================== RICH parameters =========================== AliRICH *RICH = new AliRICHv1("RICH","normal RICH"); } if(iZDC) { //=================== ZDC parameters ============================ AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC"); } if(iCASTOR) { //=================== CASTOR parameters ============================ AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR"); } if(iTRD) { //=================== TRD parameters ============================ AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator"); // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2) TRD->SetGasMix(1); // With hole in front of PHOS TRD->SetPHOShole(); // With hole in front of RICH TRD->SetRICHhole(); // Switch on TR AliTRDsim *TRDsim = TRD->CreateTR(); } if(iFMD) { //=================== FMD parameters ============================ AliFMD *FMD = new AliFMDv0("FMD","normal FMD"); } if(iMUON) { //=================== MUON parameters =========================== AliMUON *MUON = new AliMUONv1("MUON","default"); } //=================== PHOS parameters =========================== if(iPHOS) { AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2"); } if(iPMD) { //=================== PMD parameters ============================ AliPMD *PMD = new AliPMDv1("PMD","normal PMD"); PMD->SetPAR(1., 1., 0.8, 0.02); PMD->SetIN(6., 18., -580., 27., 27.); PMD->SetGEO(0.0, 0.2, 4.); PMD->SetPadSize(0.8, 1.0, 1.0, 1.5); } if(iSTART) { //=================== START parameters ============================ AliSTART *START = new AliSTARTv1("START","START Detector"); } } <commit_msg>Minor changes (R.Barbera)<commit_after>void Config() { // 7-DEC-2000 09:00 // Switch on Transition Radiation simulation. 6/12/00 18:00 // iZDC=1 7/12/00 09:00 // ThetaRange is (0., 180.). It was (0.28,179.72) 7/12/00 09:00 new AliGeant3("C++ Interface to Geant3"); if (!gSystem->Getenv("CONFIG_FILE")) { TFile *rootfile = new TFile("galice.root","recreate"); rootfile->SetCompressionLevel(2); } TGeant3 *geant3 = (TGeant3*)gMC; // // Set External decayer AliDecayer* decayer = new AliDecayerPythia(); decayer->SetForceDecay(kAll); decayer->Init(); gMC->SetExternalDecayer(decayer); // // //======================================================================= // ******* GEANT STEERING parameters FOR ALICE SIMULATION ******* geant3->SetTRIG(1); //Number of events to be processed geant3->SetSWIT(4,10); geant3->SetDEBU(0,0,1); //geant3->SetSWIT(2,2); geant3->SetDCAY(1); geant3->SetPAIR(1); geant3->SetCOMP(1); geant3->SetPHOT(1); geant3->SetPFIS(0); geant3->SetDRAY(0); geant3->SetANNI(1); geant3->SetBREM(1); geant3->SetMUNU(1); geant3->SetCKOV(1); geant3->SetHADR(1); //Select pure GEANH (HADR 1) or GEANH/NUCRIN (HADR 3) geant3->SetLOSS(2); geant3->SetMULS(1); geant3->SetRAYL(1); geant3->SetAUTO(1); //Select automatic STMIN etc... calc. (AUTO 1) or manual (AUTO 0) geant3->SetABAN(0); //Restore 3.16 behaviour for abandoned tracks geant3->SetOPTI(2); //Select optimisation level for GEANT geometry searches (0,1,2) geant3->SetERAN(5.e-7); Float_t cut = 1.e-3; // 1MeV cut by default Float_t tofmax = 1.e10; // GAM ELEC NHAD CHAD MUON EBREM MUHAB EDEL MUDEL MUPA TOFMAX geant3->SetCUTS(cut,cut, cut, cut, cut, cut, cut, cut, cut, cut, tofmax); // //======================================================================= // ************* STEERING parameters FOR ALICE SIMULATION ************** // --- Specify event type to be tracked through the ALICE setup // --- All positions are in cm, angles in degrees, and P and E in GeV if (gSystem->Getenv("CONFIG_NPARTICLES")) { int nParticles = atoi(gSystem->Getenv("CONFIG_NPARTICLES")); } else { int nParticles = 50; } AliGenHIJINGpara *gener = new AliGenHIJINGpara(nParticles); gener->SetMomentumRange(0,999); gener->SetPhiRange(0,360); // gener->SetThetaRange(0.28,179.72); gener->SetThetaRange(0.,180.); gener->SetOrigin(0,0,0); //vertex position gener->SetSigma(0,0,0); //Sigma in (X,Y,Z) (cm) on IP position gener->Init(); // // Activate this line if you want the vertex smearing to happen // track by track // //gener->SetVertexSmear(perTrack); gAlice->SetField(-999,2); //Specify maximum magnetic field in Tesla (neg. ==> default field) Int_t iABSO=1; Int_t iCASTOR=1; Int_t iDIPO=1; Int_t iFMD=1; Int_t iFRAME=1; Int_t iHALL=1; Int_t iITS=1; Int_t iMAG=1; Int_t iMUON=1; Int_t iPHOS=1; Int_t iPIPE=1; Int_t iPMD=1; Int_t iRICH=1; Int_t iSHIL=1; Int_t iSTART=1; Int_t iTOF=1; Int_t iTPC=1; Int_t iTRD=1; Int_t iZDC=1; //=================== Alice BODY parameters ============================= AliBODY *BODY = new AliBODY("BODY","Alice envelop"); if(iMAG) { //=================== MAG parameters ============================ // --- Start with Magnet since detector layouts may be depending --- // --- on the selected Magnet dimensions --- AliMAG *MAG = new AliMAG("MAG","Magnet"); } if(iABSO) { //=================== ABSO parameters ============================ AliABSO *ABSO = new AliABSOv0("ABSO","Muon Absorber"); } if(iDIPO) { //=================== DIPO parameters ============================ AliDIPO *DIPO = new AliDIPOv2("DIPO","Dipole version 2"); } if(iHALL) { //=================== HALL parameters ============================ AliHALL *HALL = new AliHALL("HALL","Alice Hall"); } if(iFRAME) { //=================== FRAME parameters ============================ AliFRAME *FRAME = new AliFRAMEv2("FRAME","Space Frame"); } if(iSHIL) { //=================== SHIL parameters ============================ AliSHIL *SHIL = new AliSHILv0("SHIL","Shielding"); } if(iPIPE) { //=================== PIPE parameters ============================ AliPIPE *PIPE = new AliPIPEv0("PIPE","Beam Pipe"); } if(iITS) { //=================== ITS parameters ============================ // // As the innermost detector in ALICE, the Inner Tracking System "impacts" on // almost all other detectors. This involves the fact that the ITS geometry // still has several options to be followed in parallel in order to determine // the best set-up which minimizes the induced background. All the geometries // available to date are described in the following. Read carefully the comments // and use the default version (the only one uncommented) unless you are making // comparisons and you know what you are doing. In this case just uncomment the // ITS geometry you want to use and run Aliroot. // // Detailed geometries: // // // //AliITS *ITS = new AliITSv5symm("ITS","Updated ITS TDR detailed version with symmetric services"); // AliITS *ITS = new AliITSv5asymm("ITS","Updates ITS TDR detailed version with asymmetric services"); // //AliITSvPPRasymm *ITS = new AliITSvPPRasymm("ITS","New ITS PPR detailed version with asymmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRasymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // //AliITSvPPRsymm *ITS = new AliITSvPPRsymm("ITS","New ITS PPR detailed version with symmetric services"); //ITS->SetMinorVersion(2); //ITS->SetReadDet(kFALSE); //ITS->SetWriteDet("$ALICE_ROOT/ITS/ITSgeometry_vPPRsymm2.det"); //ITS->SetThicknessDet1(300.); // detector thickness on layer 1 must be in the range [100,300] //ITS->SetThicknessDet2(300.); // detector thickness on layer 2 must be in the range [100,300] //ITS->SetThicknessChip1(300.); // chip thickness on layer 1 must be in the range [150,300] //ITS->SetThicknessChip2(300.); // chip thickness on layer 2 must be in the range [150,300] //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetCoolingFluid(1); // 1 --> water ; 0 --> freon // // // Coarse geometries (warning: no hits are produced with these coarse geometries and they unuseful // for reconstruction !): // // // //AliITSvPPRcoarseasymm *ITS = new AliITSvPPRcoarseasymm("ITS","New ITS coarse version with asymmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // //AliITS *ITS = new AliITSvPPRcoarsesymm("ITS","New ITS coarse version with symmetric services"); //ITS->SetRails(1); // 1 --> rails in ; 0 --> rails out //ITS->SetSupportMaterial(0); // 0 --> Copper ; 1 --> Aluminum ; 2 --> Carbon // // // // Geant3 <-> EUCLID conversion // ============================ // // SetEUCLID is a flag to output (=1) or not to output (=0) both geometry and // media to two ASCII files (called by default ITSgeometry.euc and // ITSgeometry.tme) in a format understandable to the CAD system EUCLID. // The default (=0) means that you dont want to use this facility. // ITS->SetEUCLID(0); } if(iTPC) { //============================ TPC parameters ================================ // --- This allows the user to specify sectors for the SLOW (TPC geometry 2) // --- Simulator. SecAL (SecAU) <0 means that ALL lower (upper) // --- sectors are specified, any value other than that requires at least one // --- sector (lower or upper)to be specified! // --- Reminder: sectors 1-24 are lower sectors (1-12 -> z>0, 13-24 -> z<0) // --- sectors 25-72 are the upper ones (25-48 -> z>0, 49-72 -> z<0) // --- SecLows - number of lower sectors specified (up to 6) // --- SecUps - number of upper sectors specified (up to 12) // --- Sens - sensitive strips for the Slow Simulator !!! // --- This does NOT work if all S or L-sectors are specified, i.e. // --- if SecAL or SecAU < 0 // // //----------------------------------------------------------------------------- // gROOT->LoadMacro("SetTPCParam.C"); // AliTPCParam *param = SetTPCParam(); AliTPC *TPC = new AliTPCv2("TPC","Default"); // All sectors included TPC->SetSecAL(-1); TPC->SetSecAU(-1); } if(iTOF) { //=================== TOF parameters ============================ AliTOF *TOF = new AliTOFv2("TOF","normal TOF"); } if(iRICH) { //=================== RICH parameters =========================== AliRICH *RICH = new AliRICHv1("RICH","normal RICH"); } if(iZDC) { //=================== ZDC parameters ============================ AliZDC *ZDC = new AliZDCv1("ZDC","normal ZDC"); } if(iCASTOR) { //=================== CASTOR parameters ============================ AliCASTOR *CASTOR = new AliCASTORv1("CASTOR","normal CASTOR"); } if(iTRD) { //=================== TRD parameters ============================ AliTRD *TRD = new AliTRDv1("TRD","TRD slow simulator"); // Select the gas mixture (0: 97% Xe + 3% isobutane, 1: 90% Xe + 10% CO2) TRD->SetGasMix(1); // With hole in front of PHOS TRD->SetPHOShole(); // With hole in front of RICH TRD->SetRICHhole(); // Switch on TR AliTRDsim *TRDsim = TRD->CreateTR(); } if(iFMD) { //=================== FMD parameters ============================ AliFMD *FMD = new AliFMDv0("FMD","normal FMD"); } if(iMUON) { //=================== MUON parameters =========================== AliMUON *MUON = new AliMUONv1("MUON","default"); } //=================== PHOS parameters =========================== if(iPHOS) { AliPHOS *PHOS = new AliPHOSv1("PHOS","GPS2"); } if(iPMD) { //=================== PMD parameters ============================ AliPMD *PMD = new AliPMDv1("PMD","normal PMD"); PMD->SetPAR(1., 1., 0.8, 0.02); PMD->SetIN(6., 18., -580., 27., 27.); PMD->SetGEO(0.0, 0.2, 4.); PMD->SetPadSize(0.8, 1.0, 1.0, 1.5); } if(iSTART) { //=================== START parameters ============================ AliSTART *START = new AliSTARTv1("START","START Detector"); } } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> #include <algorithm> #include <vector> #include <iomanip> #include <sstream> using namespace std; void inputValue(); void print2DVector(vector<vector<int> >& v2D); void printVector(vector<int>& v); //ECE 528 //Tenzin Ngodup //KL Partioning Software // PART II // OCT 22/2013 // Consider a Graph G(V,E) = undirected connected graph. // 2n = Total number of Vertices // {P1,P2} = Two equal size partition of vertices //Main Function int main (){ cout << "KL Programming Step 1 \n " << endl ; cout << "Iteration Number: 1 \n " << endl ; inputValue(); return 0; } void inputValue(){ string Vertices_2n; //opens the inputfile ifstream myfile; myfile.open ("input.txt"); getline (myfile,Vertices_2n); cout<<"total vertices:" << Vertices_2n << "\n"; int Vertices_n; int VerticesInt_2n = atoi(Vertices_2n.c_str()) ; Vertices_n = int(VerticesInt_2n)/2; vector< vector<int> > matrix; // to hold everything. std:: vector<int> PreVecter; std::vector<int> partition1; // to hold partition1 std::vector<int> partition2; // to hold partition2 std::string line; std::vector< vector<int> > cValue; //std::vector< vector<int> > cost; std::vector< vector<int> > gainVector( 5, std::vector<int>(5)); int cost[11][11] = {0}; std::vector< std::vector<int> > dvalue; int CostExt = 0; int CostInt = 0; while (myfile) { string s; int a; if (!getline( myfile, s )) break; istringstream ss( s ); vector <int> record; while (ss) { string s; if (!getline( ss, s, ',' )) break; stringstream(s) >> a; record.push_back( a ); } matrix.push_back( record ); } // printing the main vector matrix array & pushing in vecter prevecter for partition array. for( int i=0; i < matrix.size(); i++ ) { for( int j=0; j < matrix[i].size(); j++ ) { PreVecter.push_back( matrix[i][j]); } } print2DVector(matrix); /* // sorting the main vector array for partition for( int i=0; i < matrix.size(); i++ ) { for( int j=0; j < matrix[i].size(); j++ ) { PreVecter.push_back( matrix[i][j]); } } */ cout << "Pre-sorting state:" << endl; //sort function sort(PreVecter.begin(),PreVecter.end() ); //eliminates repeat (has error as the produces a last redundant integer value) PreVecter.erase(std::unique(PreVecter.begin(), PreVecter.end()), PreVecter.end()); PreVecter.pop_back(); printVector(PreVecter); for( int i=0; i<=PreVecter.size(); i++ ) { cout << PreVecter[i] << " "; if(PreVecter[i]<= Vertices_n) { partition1.push_back(PreVecter[i]); } else if (PreVecter[i]> Vertices_n) { partition2.push_back(PreVecter[i]); } } cout << endl << endl ; cout <<"\n" << "Partition 1" << "\n"; printVector(partition1); cout <<"\n" << "Partition 2" << "\n"; printVector(partition2); // Part for finding the cost partition // If (first element is in parititon 1 & any element is in parition2) // cost added // else if ( first element is in partition 2 & any element is in partion 1) // cost added for( int i=0; i < matrix.size(); i++ ) { cout << "Matrix: " << matrix[i][0] << endl; std::vector <int> vi; vi.push_back(matrix[i][0]); if(std::find(partition1.begin(), partition1.end(), matrix[i][0]) != partition1.end()) { int internalEdge = 0; int externalEdge = 0; for( int j=1; j<matrix[i].size(); j++ ) { if( std::find(partition2.begin(), partition2.end(), matrix[i][j])!=partition2.end()) { CostExt = CostExt + 1; externalEdge = externalEdge + 1; // cost[i][j] = 1; // cost[j][i] = 1; } else if( std::find(partition1.begin(), partition1.end(), matrix[i][j])!=partition1.end()) { CostInt = CostInt + 1; internalEdge = internalEdge + 1; // cost[i][j] = 1; // cost[j][i] = 1; } } vi.push_back(externalEdge); vi.push_back(internalEdge); vi.push_back(externalEdge - internalEdge); dvalue.push_back( vi ); } else if(std::find(partition2.begin(), partition2.end(), matrix[i][0]) != partition2.end()) { int internalEdge = 0; int externalEdge = 0; for( int j=1; j<matrix[i].size(); j++ ) { if( std::find(partition1.begin(), partition1.end(), matrix[i][j])!=partition1.end()) { CostExt = CostExt + 1; externalEdge = externalEdge + 1; } else if( std::find(partition2.begin(), partition2.end(), matrix[i][j])!=partition2.end()) { CostInt = CostInt + 1; internalEdge = internalEdge + 1; } } vi.push_back(externalEdge); vi.push_back(internalEdge); vi.push_back(externalEdge - internalEdge); dvalue.push_back( vi ); } } /* xvalue --> 0 1 2 3 4 5 ........2n-1 1 2 3 4 5 6 ...... 2n yvalue 0 1 [ ] | 1 2 [ ] | 2 3 [ ] V 3 . [ ] . [ ] 2n-1 2n[ ] */ for( int i=0; i < matrix.size(); i++ ) { for( int j=0; j<matrix[i].size(); j++ ) { int rowval = matrix[i][0]; int colval = matrix[i][j]; cost[rowval][colval] = 1; if ( rowval = colval) { cost[rowval][colval] = 0;} } } cout<< "dvalue size" << dvalue.size() << endl; int p =0; int q =0; int k = 0, l = 0; for( int i=0; i < dvalue.size()/2; i++ ) { //if(std::find(partition1.begin(), partition1.end(), dvalue[i][0]) != partition1.end()) // { for( int j= dvalue.size()/2; j<(dvalue.size()-1); j++ ) { k = dvalue[j][0]; l = dvalue[i][0]; cout<< dvalue[i][3] <<" " << dvalue [j][3] << " " << cost[k][l] << endl; gainVector[p][q] = dvalue[i][3] + dvalue [j][3] - 2*cost[k][l]; q=q+1; } p=p+1; } cout<<"gainVector" <<endl; print2DVector(gainVector); cout << endl << "dvalue" << endl; print2DVector(dvalue); cout << endl << "cvalue" << endl; // ofstream outfile; // outfile.open("output.txt"); //outfile << "Cost of Partition External: " << object1.internal << endl << endl; //outfile << "Cost of Partition Internal: " << object1.external << endl << endl; cout << "Cost of Partition External: " << CostExt << endl << endl; cout << "Cost of Partition Internal: " << CostInt << endl << endl; cout << "Cost " <<" "; cout << endl; for (int i = 0; i < 11; ++i) { for (int j = 0; j < 11; ++j) { cout << cost[i][j] << ' '; } cout << endl; } system ("pause"); } void print2DVector(vector<vector<int> >& v2D) { for( int i=0; i < v2D.size(); i++ ) { for( int j=0; j < v2D[i].size(); j++ ) { cout << v2D[i][j]; } cout << endl ; } } void printVector(vector<int>& v) { for( int i=0; i<v.size(); i++ ) { cout << v[i] << " "; } cout << endl << endl ; } <commit_msg>renamed file<commit_after><|endoftext|>
<commit_before>#include "balancer.hpp" #include <net/tcp/stream.hpp> #define READQ_PER_CLIENT 4096 #define MAX_READQ_PER_NODE 8192 #define READQ_FOR_NODES 8192 #define MAX_OUTGOING_ATTEMPTS 100 // checking if nodes are dead or not #define ACTIVE_INITIAL_PERIOD 8s #define ACTIVE_CHECK_PERIOD 30s // connection attempt timeouts #define CONNECT_TIMEOUT 10s #define CONNECT_THROW_PERIOD 20s #define LB_VERBOSE 0 #if LB_VERBOSE #define LBOUT(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define LBOUT(fmt, ...) /** **/ #endif using namespace std::chrono; namespace microLB { Balancer::Balancer( netstack_t& incoming, uint16_t in_port, netstack_t& outgoing, bool active_check) : nodes(active_check), netin(incoming), netout(outgoing), signal({this, &Balancer::handle_queue}) { netin.tcp().listen(in_port, [this] (auto conn) { if (conn != nullptr) { this->incoming(std::make_unique<net::tcp::Stream> (conn)); } }); this->init_liveupdate(); } int Balancer::wait_queue() const { return this->queue.size(); } int Balancer::connect_throws() const { return this->throw_counter; } netstack_t& Balancer::get_client_network() noexcept { return this->netin; } netstack_t& Balancer::get_nodes_network() noexcept { return this->netout; } const pool_signal_t& Balancer::get_pool_signal() const { return this->signal; } void Balancer::incoming(net::Stream_ptr conn) { assert(conn != nullptr); queue.emplace_back(std::move(conn)); LBOUT("Queueing connection (q=%lu)\n", queue.size()); // IMPORTANT: try to handle queue, in case its ready // don't directly call handle_connections() from here! this->handle_queue(); } void Balancer::handle_queue() { // check waitq while (nodes.pool_size() > 0 && queue.empty() == false) { auto& client = queue.front(); assert(client.conn != nullptr); if (client.conn->is_connected()) { // NOTE: explicitly want to copy buffers net::Stream_ptr rval = nodes.assign(std::move(client.conn), client.readq); if (rval == nullptr) { // done with this queue item queue.pop_front(); } else { // put connection back in queue item client.conn = std::move(rval); } } else { queue.pop_front(); } } // waitq check // check if we need to create more connections this->handle_connections(); } void Balancer::handle_connections() { LBOUT("Handle_connections. %i waiting \n", queue.size()); // stop any rethrow timer since this is a de-facto retry if (this->throw_retry_timer != Timers::UNUSED_ID) { Timers::stop(this->throw_retry_timer); this->throw_retry_timer = Timers::UNUSED_ID; } // prune dead clients because the "number of clients" is being // used in a calculation right after this to determine how many // nodes to connect to auto new_end = std::remove_if(queue.begin(), queue.end(), [](Waiting& client) { return client.conn == nullptr || client.conn->is_connected() == false; }); queue.erase(new_end, queue.end()); // calculating number of connection attempts to create int np_connecting = nodes.pool_connecting(); int estimate = queue.size() - (np_connecting + nodes.pool_size()); estimate = std::min(estimate, MAX_OUTGOING_ATTEMPTS); estimate = std::max(0, estimate - np_connecting); // create more outgoing connections LBOUT("Estimated connections needed: %d\n", estimate); if (estimate > 0) { try { nodes.create_connections(estimate); } catch (std::exception& e) { this->throw_counter++; // assuming the failure is due to not enough eph. ports this->throw_retry_timer = Timers::oneshot(CONNECT_THROW_PERIOD, [this] (int) { this->throw_retry_timer = Timers::UNUSED_ID; this->handle_connections(); }); } } // estimate } // handle_connections() Waiting::Waiting(net::Stream_ptr incoming) : conn(std::move(incoming)), total(0) { assert(this->conn != nullptr); assert(this->conn->is_connected()); // Release connection if it closes before it's assigned to a node. this->conn->on_close([this](){ if (this->conn != nullptr) this->conn->reset_callbacks(); this->conn = nullptr; }); // queue incoming data from clients not yet // assigned to a node this->conn->on_read(READQ_PER_CLIENT, [this] (auto buf) { // prevent buffer bloat attack this->total += buf->size(); if (this->total > MAX_READQ_PER_NODE) { this->conn->close(); } else { LBOUT("*** Queued %lu bytes\n", buf->size()); readq.push_back(buf); } }); } void Nodes::create_connections(int total) { // temporary iterator for (int i = 0; i < total; i++) { bool dest_found = false; // look for next active node up to *size* times for (size_t i = 0; i < nodes.size(); i++) { const int iter = conn_iterator; conn_iterator = (conn_iterator + 1) % nodes.size(); // if the node is active, connect immediately auto& dest_node = nodes[iter]; if (dest_node.is_active()) { dest_node.connect(); dest_found = true; break; } } // if no active node found, simply delegate to the next node if (dest_found == false) { // with active-checks we can return here later when we get a connection if (this->do_active_check) return; const int iter = conn_iterator; conn_iterator = (conn_iterator + 1) % nodes.size(); nodes[iter].connect(); } } } net::Stream_ptr Nodes::assign(net::Stream_ptr conn, queue_vector_t& readq) { for (size_t i = 0; i < nodes.size(); i++) { auto outgoing = nodes[algo_iterator].get_connection(); // algorithm here // algo_iterator = (algo_iterator + 1) % nodes.size(); // check if connection was retrieved if (outgoing != nullptr) { assert(outgoing->is_connected()); LBOUT("Assigning client to node %d (%s)\n", algo_iterator, outgoing->to_string().c_str()); auto& session = this->create_session( std::move(conn), std::move(outgoing)); // flush readq to session.outgoing for (auto buffer : readq) { LBOUT("*** Flushing %lu bytes\n", buffer->size()); session.outgoing->write(buffer); } return nullptr; } } return conn; } size_t Nodes::size() const noexcept { return nodes.size(); } Nodes::const_iterator Nodes::begin() const { return nodes.cbegin(); } Nodes::const_iterator Nodes::end() const { return nodes.cend(); } int Nodes::pool_connecting() const { int count = 0; for (auto& node : nodes) count += node.connection_attempts(); return count; } int Nodes::pool_size() const { int count = 0; for (auto& node : nodes) count += node.pool_size(); return count; } int32_t Nodes::open_sessions() const { return session_cnt; } int64_t Nodes::total_sessions() const { return session_total; } int32_t Nodes::timed_out_sessions() const { return 0; } Session& Nodes::create_session(net::Stream_ptr client, net::Stream_ptr outgoing) { int idx = -1; if (free_sessions.empty()) { idx = sessions.size(); sessions.emplace_back(*this, idx, std::move(client), std::move(outgoing)); } else { idx = free_sessions.back(); new (&sessions[idx]) Session(*this, idx, std::move(client), std::move(outgoing)); free_sessions.pop_back(); } session_total++; session_cnt++; LBOUT("New session %d (current = %d, total = %ld)\n", idx, session_cnt, session_total); return sessions[idx]; } Session& Nodes::get_session(int idx) { auto& session = sessions.at(idx); assert(session.is_alive()); return session; } void Nodes::close_session(int idx) { auto& session = get_session(idx); // remove connections session.incoming->reset_callbacks(); session.incoming = nullptr; session.outgoing->reset_callbacks(); session.outgoing = nullptr; // free session free_sessions.push_back(session.self); session_cnt--; LBOUT("Session %d closed (total = %d)\n", session.self, session_cnt); } Node::Node(netstack_t& stk, net::Socket a, const pool_signal_t& sig, bool da) : stack(stk), pool_signal(sig), addr(a), do_active_check(da) { if (this->do_active_check) { // periodically connect to node and determine if active // however, perform first check immediately this->active_timer = Timers::periodic(0s, ACTIVE_CHECK_PERIOD, {this, &Node::perform_active_check}); } } void Node::perform_active_check(int) { assert(this->do_active_check); try { this->stack.tcp().connect(this->addr, [this] (auto conn) { this->active = (conn != nullptr); // if we are connected, its alive if (conn != nullptr) { // hopefully put this to good use pool.push_back(std::make_unique<net::tcp::Stream>(conn)); // stop any active check this->stop_active_check(); // signal change in pool this->pool_signal(); } else { // if no periodic check is being done right now, // start doing it (after initial delay) this->restart_active_check(); } }); } catch (std::exception& e) { // do nothing, because might just be eph.ports used up } } void Node::restart_active_check() { // set as inactive this->active = false; if (this->do_active_check) { // begin checking active again if (this->active_timer == Timers::UNUSED_ID) { this->active_timer = Timers::periodic( ACTIVE_INITIAL_PERIOD, ACTIVE_CHECK_PERIOD, {this, &Node::perform_active_check}); LBOUT("Node %s restarting active check (and is inactive)\n", this->addr.to_string().c_str()); } else { LBOUT("Node %s still trying to connect...\n", this->addr.to_string().c_str()); } } } void Node::stop_active_check() { // set as active this->active = true; if (this->do_active_check) { // stop active checking for now if (this->active_timer != Timers::UNUSED_ID) { Timers::stop(this->active_timer); this->active_timer = Timers::UNUSED_ID; } } } void Node::connect() { auto outgoing = this->stack.tcp().connect(this->addr); // connecting to node atm. this->connecting++; // retry timer when connect takes too long int fail_timer = Timers::oneshot(CONNECT_TIMEOUT, [this, outgoing] (int) { // close connection outgoing->abort(); // no longer connecting assert(this->connecting > 0); this->connecting --; // restart active check this->restart_active_check(); // signal change in pool this->pool_signal(); }); // add connection to pool on success, otherwise.. retry outgoing->on_connect( [this, fail_timer] (auto conn) { // stop retry timer Timers::stop(fail_timer); // no longer connecting assert(this->connecting > 0); this->connecting --; // connection may be null, apparently if (conn != nullptr && conn->is_connected()) { LBOUT("Connected to %s (%ld total)\n", addr.to_string().c_str(), pool.size()); this->pool.push_back(std::make_unique<net::tcp::Stream>(conn)); // stop any active check this->stop_active_check(); // signal change in pool this->pool_signal(); } else { this->restart_active_check(); } }); } net::Stream_ptr Node::get_connection() { while (pool.empty() == false) { auto conn = std::move(pool.back()); assert(conn != nullptr); pool.pop_back(); if (conn->is_connected()) return conn; else conn->close(); } return nullptr; } // use indexing to access Session because std::vector Session::Session(Nodes& n, int idx, net::Stream_ptr inc, net::Stream_ptr out) : parent(n), self(idx), incoming(std::move(inc)), outgoing(std::move(out)) { incoming->on_read(READQ_PER_CLIENT, [this] (auto buf) { assert(this->is_alive()); this->outgoing->write(buf); }); incoming->on_close( [&nodes = n, idx] () { nodes.close_session(idx); }); outgoing->on_read(READQ_FOR_NODES, [this] (auto buf) { assert(this->is_alive()); this->incoming->write(buf); }); outgoing->on_close( [&nodes = n, idx] () { nodes.close_session(idx); }); // get the actual TCP connections auto conn_in = dynamic_cast<net::tcp::Stream*>(incoming->bottom_transport())->tcp(); assert(conn_in != nullptr); auto conn_out = dynamic_cast<net::tcp::Stream*>(outgoing->bottom_transport())->tcp(); assert(conn_out != nullptr); static const uint32_t sendq_max = 0x400000; // set recv window handlers conn_in->set_recv_wnd_getter( [conn_out] () -> uint32_t { auto sendq_size = conn_out->sendq_size(); if (sendq_size > sendq_max) printf("WARNING: Incoming reports sendq size: %u\n", sendq_size); return sendq_max - sendq_size; }); conn_out->set_recv_wnd_getter( [conn_in] () -> uint32_t { auto sendq_size = conn_in->sendq_size(); if (sendq_size > sendq_max) printf("WARNING: Outgoing reports sendq size: %u\n", sendq_size); return sendq_max - sendq_size; }); } bool Session::is_alive() const { return incoming != nullptr; } } <commit_msg>microlb: use TCP's internal receive window calculations<commit_after>#include "balancer.hpp" #include <net/tcp/stream.hpp> #define READQ_PER_CLIENT 4096 #define MAX_READQ_PER_NODE 8192 #define READQ_FOR_NODES 8192 #define MAX_OUTGOING_ATTEMPTS 100 // checking if nodes are dead or not #define ACTIVE_INITIAL_PERIOD 8s #define ACTIVE_CHECK_PERIOD 30s // connection attempt timeouts #define CONNECT_TIMEOUT 10s #define CONNECT_THROW_PERIOD 20s #define LB_VERBOSE 0 #if LB_VERBOSE #define LBOUT(fmt, ...) printf(fmt, ##__VA_ARGS__) #else #define LBOUT(fmt, ...) /** **/ #endif using namespace std::chrono; namespace microLB { Balancer::Balancer( netstack_t& incoming, uint16_t in_port, netstack_t& outgoing, bool active_check) : nodes(active_check), netin(incoming), netout(outgoing), signal({this, &Balancer::handle_queue}) { netin.tcp().listen(in_port, [this] (auto conn) { if (conn != nullptr) { this->incoming(std::make_unique<net::tcp::Stream> (conn)); } }); this->init_liveupdate(); } int Balancer::wait_queue() const { return this->queue.size(); } int Balancer::connect_throws() const { return this->throw_counter; } netstack_t& Balancer::get_client_network() noexcept { return this->netin; } netstack_t& Balancer::get_nodes_network() noexcept { return this->netout; } const pool_signal_t& Balancer::get_pool_signal() const { return this->signal; } void Balancer::incoming(net::Stream_ptr conn) { assert(conn != nullptr); queue.emplace_back(std::move(conn)); LBOUT("Queueing connection (q=%lu)\n", queue.size()); // IMPORTANT: try to handle queue, in case its ready // don't directly call handle_connections() from here! this->handle_queue(); } void Balancer::handle_queue() { // check waitq while (nodes.pool_size() > 0 && queue.empty() == false) { auto& client = queue.front(); assert(client.conn != nullptr); if (client.conn->is_connected()) { // NOTE: explicitly want to copy buffers net::Stream_ptr rval = nodes.assign(std::move(client.conn), client.readq); if (rval == nullptr) { // done with this queue item queue.pop_front(); } else { // put connection back in queue item client.conn = std::move(rval); } } else { queue.pop_front(); } } // waitq check // check if we need to create more connections this->handle_connections(); } void Balancer::handle_connections() { LBOUT("Handle_connections. %i waiting \n", queue.size()); // stop any rethrow timer since this is a de-facto retry if (this->throw_retry_timer != Timers::UNUSED_ID) { Timers::stop(this->throw_retry_timer); this->throw_retry_timer = Timers::UNUSED_ID; } // prune dead clients because the "number of clients" is being // used in a calculation right after this to determine how many // nodes to connect to auto new_end = std::remove_if(queue.begin(), queue.end(), [](Waiting& client) { return client.conn == nullptr || client.conn->is_connected() == false; }); queue.erase(new_end, queue.end()); // calculating number of connection attempts to create int np_connecting = nodes.pool_connecting(); int estimate = queue.size() - (np_connecting + nodes.pool_size()); estimate = std::min(estimate, MAX_OUTGOING_ATTEMPTS); estimate = std::max(0, estimate - np_connecting); // create more outgoing connections LBOUT("Estimated connections needed: %d\n", estimate); if (estimate > 0) { try { nodes.create_connections(estimate); } catch (std::exception& e) { this->throw_counter++; // assuming the failure is due to not enough eph. ports this->throw_retry_timer = Timers::oneshot(CONNECT_THROW_PERIOD, [this] (int) { this->throw_retry_timer = Timers::UNUSED_ID; this->handle_connections(); }); } } // estimate } // handle_connections() Waiting::Waiting(net::Stream_ptr incoming) : conn(std::move(incoming)), total(0) { assert(this->conn != nullptr); assert(this->conn->is_connected()); // Release connection if it closes before it's assigned to a node. this->conn->on_close([this](){ if (this->conn != nullptr) this->conn->reset_callbacks(); this->conn = nullptr; }); // queue incoming data from clients not yet // assigned to a node this->conn->on_read(READQ_PER_CLIENT, [this] (auto buf) { // prevent buffer bloat attack this->total += buf->size(); if (this->total > MAX_READQ_PER_NODE) { this->conn->close(); } else { LBOUT("*** Queued %lu bytes\n", buf->size()); readq.push_back(buf); } }); } void Nodes::create_connections(int total) { // temporary iterator for (int i = 0; i < total; i++) { bool dest_found = false; // look for next active node up to *size* times for (size_t i = 0; i < nodes.size(); i++) { const int iter = conn_iterator; conn_iterator = (conn_iterator + 1) % nodes.size(); // if the node is active, connect immediately auto& dest_node = nodes[iter]; if (dest_node.is_active()) { dest_node.connect(); dest_found = true; break; } } // if no active node found, simply delegate to the next node if (dest_found == false) { // with active-checks we can return here later when we get a connection if (this->do_active_check) return; const int iter = conn_iterator; conn_iterator = (conn_iterator + 1) % nodes.size(); nodes[iter].connect(); } } } net::Stream_ptr Nodes::assign(net::Stream_ptr conn, queue_vector_t& readq) { for (size_t i = 0; i < nodes.size(); i++) { auto outgoing = nodes[algo_iterator].get_connection(); // algorithm here // algo_iterator = (algo_iterator + 1) % nodes.size(); // check if connection was retrieved if (outgoing != nullptr) { assert(outgoing->is_connected()); LBOUT("Assigning client to node %d (%s)\n", algo_iterator, outgoing->to_string().c_str()); auto& session = this->create_session( std::move(conn), std::move(outgoing)); // flush readq to session.outgoing for (auto buffer : readq) { LBOUT("*** Flushing %lu bytes\n", buffer->size()); session.outgoing->write(buffer); } return nullptr; } } return conn; } size_t Nodes::size() const noexcept { return nodes.size(); } Nodes::const_iterator Nodes::begin() const { return nodes.cbegin(); } Nodes::const_iterator Nodes::end() const { return nodes.cend(); } int Nodes::pool_connecting() const { int count = 0; for (auto& node : nodes) count += node.connection_attempts(); return count; } int Nodes::pool_size() const { int count = 0; for (auto& node : nodes) count += node.pool_size(); return count; } int32_t Nodes::open_sessions() const { return session_cnt; } int64_t Nodes::total_sessions() const { return session_total; } int32_t Nodes::timed_out_sessions() const { return 0; } Session& Nodes::create_session(net::Stream_ptr client, net::Stream_ptr outgoing) { int idx = -1; if (free_sessions.empty()) { idx = sessions.size(); sessions.emplace_back(*this, idx, std::move(client), std::move(outgoing)); } else { idx = free_sessions.back(); new (&sessions[idx]) Session(*this, idx, std::move(client), std::move(outgoing)); free_sessions.pop_back(); } session_total++; session_cnt++; LBOUT("New session %d (current = %d, total = %ld)\n", idx, session_cnt, session_total); return sessions[idx]; } Session& Nodes::get_session(int idx) { auto& session = sessions.at(idx); assert(session.is_alive()); return session; } void Nodes::close_session(int idx) { auto& session = get_session(idx); // remove connections session.incoming->reset_callbacks(); session.incoming = nullptr; session.outgoing->reset_callbacks(); session.outgoing = nullptr; // free session free_sessions.push_back(session.self); session_cnt--; LBOUT("Session %d closed (total = %d)\n", session.self, session_cnt); } Node::Node(netstack_t& stk, net::Socket a, const pool_signal_t& sig, bool da) : stack(stk), pool_signal(sig), addr(a), do_active_check(da) { if (this->do_active_check) { // periodically connect to node and determine if active // however, perform first check immediately this->active_timer = Timers::periodic(0s, ACTIVE_CHECK_PERIOD, {this, &Node::perform_active_check}); } } void Node::perform_active_check(int) { assert(this->do_active_check); try { this->stack.tcp().connect(this->addr, [this] (auto conn) { this->active = (conn != nullptr); // if we are connected, its alive if (conn != nullptr) { // hopefully put this to good use pool.push_back(std::make_unique<net::tcp::Stream>(conn)); // stop any active check this->stop_active_check(); // signal change in pool this->pool_signal(); } else { // if no periodic check is being done right now, // start doing it (after initial delay) this->restart_active_check(); } }); } catch (std::exception& e) { // do nothing, because might just be eph.ports used up } } void Node::restart_active_check() { // set as inactive this->active = false; if (this->do_active_check) { // begin checking active again if (this->active_timer == Timers::UNUSED_ID) { this->active_timer = Timers::periodic( ACTIVE_INITIAL_PERIOD, ACTIVE_CHECK_PERIOD, {this, &Node::perform_active_check}); LBOUT("Node %s restarting active check (and is inactive)\n", this->addr.to_string().c_str()); } else { LBOUT("Node %s still trying to connect...\n", this->addr.to_string().c_str()); } } } void Node::stop_active_check() { // set as active this->active = true; if (this->do_active_check) { // stop active checking for now if (this->active_timer != Timers::UNUSED_ID) { Timers::stop(this->active_timer); this->active_timer = Timers::UNUSED_ID; } } } void Node::connect() { auto outgoing = this->stack.tcp().connect(this->addr); // connecting to node atm. this->connecting++; // retry timer when connect takes too long int fail_timer = Timers::oneshot(CONNECT_TIMEOUT, [this, outgoing] (int) { // close connection outgoing->abort(); // no longer connecting assert(this->connecting > 0); this->connecting --; // restart active check this->restart_active_check(); // signal change in pool this->pool_signal(); }); // add connection to pool on success, otherwise.. retry outgoing->on_connect( [this, fail_timer] (auto conn) { // stop retry timer Timers::stop(fail_timer); // no longer connecting assert(this->connecting > 0); this->connecting --; // connection may be null, apparently if (conn != nullptr && conn->is_connected()) { LBOUT("Connected to %s (%ld total)\n", addr.to_string().c_str(), pool.size()); this->pool.push_back(std::make_unique<net::tcp::Stream>(conn)); // stop any active check this->stop_active_check(); // signal change in pool this->pool_signal(); } else { this->restart_active_check(); } }); } net::Stream_ptr Node::get_connection() { while (pool.empty() == false) { auto conn = std::move(pool.back()); assert(conn != nullptr); pool.pop_back(); if (conn->is_connected()) return conn; else conn->close(); } return nullptr; } // use indexing to access Session because std::vector Session::Session(Nodes& n, int idx, net::Stream_ptr inc, net::Stream_ptr out) : parent(n), self(idx), incoming(std::move(inc)), outgoing(std::move(out)) { incoming->on_read(READQ_PER_CLIENT, [this] (auto buf) { assert(this->is_alive()); this->outgoing->write(buf); }); incoming->on_close( [&nodes = n, idx] () { nodes.close_session(idx); }); outgoing->on_read(READQ_FOR_NODES, [this] (auto buf) { assert(this->is_alive()); this->incoming->write(buf); }); outgoing->on_close( [&nodes = n, idx] () { nodes.close_session(idx); }); } bool Session::is_alive() const { return incoming != nullptr; } } <|endoftext|>
<commit_before>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include <sys/time.h> #include <time.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <ctype.h> #include <unistd.h> #ifndef __MINGW32__ #include <sys/wait.h> #endif #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; #ifdef __MINGW32__ printf("-p doesn't work on MinGW as it is lacking fork. Running inside the process\b"); runOneTest(plugin, result); #else int info; pid_t pid = (isRunInSeperateProcess()) ? fork() : 0; if (pid) { wait(&info); if (WIFEXITED(info) && WEXITSTATUS(info) > result.getFailureCount()) result.addFailure(TestFailure(this, "failed in seperate process")); } else { runOneTest(plugin, result); if (isRunInSeperateProcess()) exit(result.getFailureCount() ); } #endif jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { return TestOutput::eclipse; } ///////////// Time in millis static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return (char*) strstr(s1, s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { return vsnprintf( str, size, format, args); } char PlatformSpecificToLower(char c) { return (char) tolower((char) c); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return isnan((float)d); } <commit_msg><commit_after>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 <stdlib.h> #include "CppUTest/TestHarness.h" #undef malloc #undef free #undef calloc #undef realloc #include "CppUTest/TestRegistry.h" #include <sys/time.h> #include <time.h> #include <stdio.h> #include <stdarg.h> #include <setjmp.h> #include <string.h> #include <math.h> #include <ctype.h> #include <unistd.h> #ifndef __MINGW32__ #include <sys/wait.h> #endif #include "CppUTest/PlatformSpecificFunctions.h" static jmp_buf test_exit_jmp_buf[10]; static int jmp_buf_index = 0; bool Utest::executePlatformSpecificSetup() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; setup(); jmp_buf_index--; return true; } return false; } void Utest::executePlatformSpecificTestBody() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; testBody(); jmp_buf_index--; } } void Utest::executePlatformSpecificTeardown() { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; teardown(); jmp_buf_index--; } } void Utest::executePlatformSpecificRunOneTest(TestPlugin* plugin, TestResult& result) { if (0 == setjmp(test_exit_jmp_buf[jmp_buf_index])) { jmp_buf_index++; #ifdef __MINGW32__ if (isRunInSeperateProcess()) printf("-p doesn't work on MinGW as it is lacking fork. Running inside the process\b"); runOneTest(plugin, result); #else int info; pid_t pid = (isRunInSeperateProcess()) ? fork() : 0; if (pid) { wait(&info); if (WIFEXITED(info) && WEXITSTATUS(info) > result.getFailureCount()) result.addFailure(TestFailure(this, "failed in seperate process")); } else { runOneTest(plugin, result); if (isRunInSeperateProcess()) exit(result.getFailureCount() ); } #endif jmp_buf_index--; } } void Utest::executePlatformSpecificExitCurrentTest() { jmp_buf_index--; longjmp(test_exit_jmp_buf[jmp_buf_index], 1); } TestOutput::WorkingEnvironment PlatformSpecificGetWorkingEnvironment() { return TestOutput::eclipse; } ///////////// Time in millis static long TimeInMillisImplementation() { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); return (tv.tv_sec * 1000) + (long)((double)tv.tv_usec * 0.001); } static long (*timeInMillisFp) () = TimeInMillisImplementation; long GetPlatformSpecificTimeInMillis() { return timeInMillisFp(); } void SetPlatformSpecificTimeInMillisMethod(long (*platformSpecific) ()) { timeInMillisFp = (platformSpecific == 0) ? TimeInMillisImplementation : platformSpecific; } ///////////// Time in String static const char* TimeStringImplementation() { time_t tm = time(NULL); return ctime(&tm); } static const char* (*timeStringFp) () = TimeStringImplementation; const char* GetPlatformSpecificTimeString() { return timeStringFp(); } void SetPlatformSpecificTimeStringMethod(const char* (*platformMethod) ()) { timeStringFp = (platformMethod == 0) ? TimeStringImplementation : platformMethod; } int PlatformSpecificAtoI(const char*str) { return atoi(str); } size_t PlatformSpecificStrLen(const char* str) { return strlen(str); } char* PlatformSpecificStrCat(char* s1, const char* s2) { return strcat(s1, s2); } char* PlatformSpecificStrCpy(char* s1, const char* s2) { return strcpy(s1, s2); } char* PlatformSpecificStrNCpy(char* s1, const char* s2, size_t size) { return strncpy(s1, s2, size); } int PlatformSpecificStrCmp(const char* s1, const char* s2) { return strcmp(s1, s2); } int PlatformSpecificStrNCmp(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } char* PlatformSpecificStrStr(const char* s1, const char* s2) { return (char*) strstr(s1, s2); } int PlatformSpecificVSNprintf(char *str, unsigned int size, const char* format, va_list args) { return vsnprintf( str, size, format, args); } char PlatformSpecificToLower(char c) { return (char) tolower((char) c); } PlatformSpecificFile PlatformSpecificFOpen(const char* filename, const char* flag) { return fopen(filename, flag); } void PlatformSpecificFPuts(const char* str, PlatformSpecificFile file) { fputs(str, (FILE*)file); } void PlatformSpecificFClose(PlatformSpecificFile file) { fclose((FILE*)file); } void PlatformSpecificFlush() { fflush(stdout); } int PlatformSpecificPutchar(int c) { return putchar(c); } void* PlatformSpecificMalloc(size_t size) { return malloc(size); } void* PlatformSpecificRealloc (void* memory, size_t size) { return realloc(memory, size); } void PlatformSpecificFree(void* memory) { free(memory); } void* PlatformSpecificMemCpy(void* s1, const void* s2, size_t size) { return memcpy(s1, s2, size); } void* PlatformSpecificMemset(void* mem, int c, size_t size) { return memset(mem, c, size); } double PlatformSpecificFabs(double d) { return fabs(d); } int PlatformSpecificIsNan(double d) { return isnan((float)d); } <|endoftext|>
<commit_before>#ifdef HAVE_PYTHON #include "../script.h" #include "python.h" #include <string> #include "../globals.h" #include "../util/funcs.h" #include "../world.h" #include <sstream> #include <Python.h> using namespace std; static PyObject * paintown_levelLength(PyObject * dummy, PyObject * args){ PyObject * cobject; if (PyArg_ParseTuple(args, "O", &cobject)){ World * world = (World*) PyCObject_AsVoidPtr(cobject); int length = world->levelLength(); return Py_BuildValue("i", length); } Py_INCREF(Py_None); return Py_None; } static PyMethodDef PaintownModule[] = { {"levelLength", paintown_levelLength, METH_VARARGS, "Register a paintown engine."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PythonEngine::PythonEngine(const string & path): Script::Engine(), path(path){ Global::debug(1) << "Loading python.." << endl; Py_Initialize(); Py_InitModule("paintown", PaintownModule); Global::debug(1) << "Load module " << path << endl; /* TODO: Use PySys_GetObject() to get sys.path and then use * PyString_FromStringAndSize() and PyList_Append() */ ostringstream python_string; python_string << "x = \"" << (Util::getDataPath() + path) << "\"; import sys; sys.path.append(x[0:x.rfind('/')]); sys.path.append('scripts.zip/build/modules');"; Global::debug(1) << "Executing '" << python_string.str() << "'" << endl; Global::debug(1) << "Python: " << PyRun_SimpleString(python_string.str().c_str()) << endl; int from = path.rfind("/")+1; int to = path.rfind("."); module = path.substr(from, to - from); } void PythonEngine::init(){ } void PythonEngine::shutdown(){ } void PythonEngine::createWorld(const World & world){ Global::debug(1) << "Loading module " << module << endl; PyObject * python_module = PyImport_ImportModule(module.c_str()); Global::debug(1) << "Loaded " << python_module << endl; if (python_module == NULL){ PyErr_Print(); } PyObject * api_module = PyImport_ImportModule("api"); if (api_module == NULL){ PyErr_Print(); } PyObject * create = PyObject_GetAttrString(api_module, "createWorld"); if (create == NULL){ PyErr_Print(); } PyObject * cobject = PyCObject_FromVoidPtr((void*) &world, NULL); if (cobject == NULL){ PyErr_Print(); } PyObject * result = PyObject_CallFunction(create, (char*) "(O)", cobject); if (result == NULL){ PyErr_Print(); } else { Py_DECREF(result); } Py_DECREF(create); /* ostringstream python_string; Global::debug(1) << "[python] Create world" << endl; python_string << "if True: import build.modules.api; build.modules.api.createWorld()" << endl; Global::debug(1) << "Python: " << PyRun_SimpleString(python_string.str().c_str()) << endl; */ } void PythonEngine::destroyWorld(const World & world){ } PythonEngine::~PythonEngine(){ Py_Finalize(); } #endif <commit_msg>add python reference counts<commit_after>#ifdef HAVE_PYTHON #include "../script.h" #include "python.h" #include <string> #include "../globals.h" #include "../util/funcs.h" #include "../world.h" #include <sstream> #include <Python.h> using namespace std; static PyObject * paintown_levelLength(PyObject * dummy, PyObject * args){ PyObject * cobject; if (PyArg_ParseTuple(args, "O", &cobject)){ World * world = (World*) PyCObject_AsVoidPtr(cobject); int length = world->levelLength(); Py_DECREF(cobject); return Py_BuildValue("i", length); } Py_INCREF(Py_None); return Py_None; } static PyMethodDef PaintownModule[] = { {"levelLength", paintown_levelLength, METH_VARARGS, "Register a paintown engine."}, {NULL, NULL, 0, NULL} /* Sentinel */ }; PythonEngine::PythonEngine(const string & path): Script::Engine(), path(path){ Global::debug(1) << "Loading python.." << endl; Py_Initialize(); Py_InitModule("paintown", PaintownModule); Global::debug(1) << "Load module " << path << endl; /* TODO: Use PySys_GetObject() to get sys.path and then use * PyString_FromStringAndSize() and PyList_Append() */ ostringstream python_string; python_string << "x = \"" << (Util::getDataPath() + path) << "\"; import sys; sys.path.append(x[0:x.rfind('/')]); sys.path.append('scripts.zip/build/modules');"; Global::debug(1) << "Executing '" << python_string.str() << "'" << endl; Global::debug(1) << "Python: " << PyRun_SimpleString(python_string.str().c_str()) << endl; int from = path.rfind("/")+1; int to = path.rfind("."); module = path.substr(from, to - from); } void PythonEngine::init(){ } void PythonEngine::shutdown(){ } void PythonEngine::createWorld(const World & world){ Global::debug(1) << "Loading module " << module << endl; PyObject * python_module = PyImport_ImportModule(module.c_str()); Global::debug(1) << "Loaded " << python_module << endl; if (python_module == NULL){ PyErr_Print(); } PyObject * api_module = PyImport_ImportModule("api"); if (api_module == NULL){ PyErr_Print(); } PyObject * create = PyObject_GetAttrString(api_module, "createWorld"); if (create == NULL){ PyErr_Print(); } Py_DECREF(api_module); PyObject * cobject = PyCObject_FromVoidPtr((void*) &world, NULL); if (cobject == NULL){ PyErr_Print(); } PyObject * result = PyObject_CallFunction(create, (char*) "(O)", cobject); if (result == NULL){ PyErr_Print(); } else { Py_DECREF(result); } Py_DECREF(create); Py_DECREF(cobject); /* ostringstream python_string; Global::debug(1) << "[python] Create world" << endl; python_string << "if True: import build.modules.api; build.modules.api.createWorld()" << endl; Global::debug(1) << "Python: " << PyRun_SimpleString(python_string.str().c_str()) << endl; */ } void PythonEngine::destroyWorld(const World & world){ } PythonEngine::~PythonEngine(){ Py_Finalize(); } #endif <|endoftext|>
<commit_before>#include "./obb.h" #include <Eigen/Eigenvalues> #include <iostream> Obb::Obb(Eigen::MatrixXf points) { Eigen::Matrix3Xf centered = points.colwise() - points.rowwise().mean(); Eigen::MatrixXf cov = centered * centered.adjoint(); std::cout << "cov" << std::endl; std::cout << cov << std::endl; Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(cov); Eigen::MatrixXf eigenVectors = eig.eigenvectors(); std::cout << "eigenvectors" << std::endl; std::cout << eigenVectors << std::endl; // Gram-Schmidt process axis1 = eigenVectors.row(2).normalized(); auto eigen2 = eigenVectors.row(1); auto dir2 = eigen2 - eigen2.dot(axis1) * eigen2; axis2 = dir2.normalized(); axis3 = axis1.cross(axis2); std::cout << "centered: " << axis1.rows() << "x" << axis1.cols() << std::endl; std::cout << "points: " << points.rows() << "x" << centered.cols() << std::endl; Eigen::MatrixXf onAxis1 = axis1.transpose() * points; Eigen::MatrixXf onAxis2 = axis2.transpose() * points; Eigen::MatrixXf onAxis3 = axis3.transpose() * points; /* std::cout << "Projected onto axis 1" << std::endl; std::cout << onAxis1 << std::endl; std::cout << "Projected onto axis 2" << std::endl; std::cout << onAxis2 << std::endl; std::cout << "Projected onto axis 3" << std::endl; std::cout << onAxis3 << std::endl; */ auto upper = Eigen::Vector3f(onAxis1.maxCoeff(), onAxis2.maxCoeff(), onAxis3.maxCoeff()); auto lower = Eigen::Vector3f(onAxis1.minCoeff(), onAxis2.minCoeff(), onAxis3.minCoeff()); halfWidths = 0.5f * (upper - lower); auto halfSum = 0.5f * (upper + lower); center = halfSum.x() * axis1 + halfSum.y() * axis2 + halfSum.z() * axis3; std::cout << "center " << center << std::endl; std::cout << "half widths " << halfWidths << std::endl; corners[0] = center - halfWidths.x() * axis1 - halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[1] = center + halfWidths.x() * axis1 - halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[2] = center + halfWidths.x() * axis1 - halfWidths.y() * axis2 + halfWidths.z() * axis3; corners[3] = center - halfWidths.x() * axis1 - halfWidths.y() * axis2 + halfWidths.z() * axis3; corners[4] = center - halfWidths.x() * axis1 + halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[5] = center + halfWidths.x() * axis1 + halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[6] = center + halfWidths.x() * axis1 + halfWidths.y() * axis2 + halfWidths.z() * axis3; corners[7] = center - halfWidths.x() * axis1 + halfWidths.y() * axis2 + halfWidths.z() * axis3; } <commit_msg>Remove unused debug output.<commit_after>#include "./obb.h" #include <Eigen/Eigenvalues> #include <iostream> Obb::Obb(Eigen::MatrixXf points) { Eigen::Matrix3Xf centered = points.colwise() - points.rowwise().mean(); Eigen::MatrixXf cov = centered * centered.adjoint(); std::cout << "cov" << std::endl; std::cout << cov << std::endl; Eigen::SelfAdjointEigenSolver<Eigen::MatrixXf> eig(cov); Eigen::MatrixXf eigenVectors = eig.eigenvectors(); // Gram-Schmidt process axis1 = eigenVectors.row(2).normalized(); auto eigen2 = eigenVectors.row(1); auto dir2 = eigen2 - eigen2.dot(axis1) * eigen2; axis2 = dir2.normalized(); axis3 = axis1.cross(axis2); std::cout << "Axes:" << std::endl; std::cout << axis1 << std::endl; std::cout << axis2 << std::endl; std::cout << axis3 << std::endl; Eigen::MatrixXf onAxis1 = axis1.transpose() * points; Eigen::MatrixXf onAxis2 = axis2.transpose() * points; Eigen::MatrixXf onAxis3 = axis3.transpose() * points; auto upper = Eigen::Vector3f(onAxis1.maxCoeff(), onAxis2.maxCoeff(), onAxis3.maxCoeff()); auto lower = Eigen::Vector3f(onAxis1.minCoeff(), onAxis2.minCoeff(), onAxis3.minCoeff()); halfWidths = 0.5f * (upper - lower); auto halfSum = 0.5f * (upper + lower); center = halfSum.x() * axis1 + halfSum.y() * axis2 + halfSum.z() * axis3; std::cout << "center " << center << std::endl; std::cout << "half widths " << halfWidths << std::endl; corners[0] = center - halfWidths.x() * axis1 - halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[1] = center + halfWidths.x() * axis1 - halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[2] = center + halfWidths.x() * axis1 - halfWidths.y() * axis2 + halfWidths.z() * axis3; corners[3] = center - halfWidths.x() * axis1 - halfWidths.y() * axis2 + halfWidths.z() * axis3; corners[4] = center - halfWidths.x() * axis1 + halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[5] = center + halfWidths.x() * axis1 + halfWidths.y() * axis2 - halfWidths.z() * axis3; corners[6] = center + halfWidths.x() * axis1 + halfWidths.y() * axis2 + halfWidths.z() * axis3; corners[7] = center - halfWidths.x() * axis1 + halfWidths.y() * axis2 + halfWidths.z() * axis3; } <|endoftext|>
<commit_before>/* * Copyright (c) 2015 Oleg Morozenkov * Copyright (c) 2018 Egor Pugin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "tgbot/net/HttpClient.h" #include <boost/asio/ssl.hpp> using namespace std; using namespace boost::asio; using namespace boost::asio::ip; namespace TgBot { BoostHttpClient& BoostHttpClient::getInstance() { static BoostHttpClient result; return result; } string BoostHttpClient::makeRequest(const Url& url, const vector<HttpReqArg>& args) const { ssl::context context(ssl::context::sslv23); context.set_default_verify_paths(); ssl::stream<tcp::socket> socket(_ioService, context); tcp::resolver resolver(_ioService); tcp::resolver::query query(url.host, url.protocol); connect(socket.lowest_layer(), resolver.resolve(query)); #ifdef TGBOT_DISABLE_NAGLES_ALGORITHM socket.lowest_layer().set_option(tcp::no_delay(true)); #endif //TGBOT_DISABLE_NAGLES_ALGORITHM #ifdef TGBOT_CHANGE_SOCKET_BUFFER_SIZE #if _WIN64 || __amd64__ || __x86_64__ || __MINGW64__ || __aarch64__ || __powerpc64__ socket.lowest_layer().set_option(socket_base::send_buffer_size(65536)); socket.lowest_layer().set_option(socket_base::receive_buffer_size(65536)); #else //for 32-bit socket.lowest_layer().set_option(socket_base::send_buffer_size(32768)); socket.lowest_layer().set_option(socket_base::receive_buffer_size(32768)); #endif //Processor architecture #endif //TGBOT_CHANGE_SOCKET_BUFFER_SIZE socket.set_verify_mode(ssl::verify_none); socket.set_verify_callback(ssl::rfc2818_verification(url.host)); socket.handshake(ssl::stream<tcp::socket>::client); string requestText = HttpParser::getInstance().generateRequest(url, args, false); write(socket, buffer(requestText.c_str(), requestText.length())); string response; #ifdef TGBOT_CHANGE_READ_BUFFER_SIZE #if _WIN64 || __amd64__ || __x86_64__ || __MINGW64__ || __aarch64__ || __powerpc64__ char buff[65536]; #else //for 32-bit char buff[32768]; #endif //Processor architecture #else char buff[1024]; #endif //TGBOT_CHANGE_READ_BUFFER_SIZE boost::system::error_code error; while (!error) { size_t bytes = read(socket, buffer(buff), error); response += string(buff, bytes); } return HttpParser::getInstance().parseResponse(response); } #ifdef HAVE_CURL CurlHttpClient::CurlHttpClient() { curlSettings = curl_easy_init(); } CurlHttpClient::~CurlHttpClient() { curl_easy_cleanup(curlSettings); } CurlHttpClient& CurlHttpClient::getInstance() { static CurlHttpClient result; return result; } static size_t curl_write_string(char *ptr, size_t size, size_t nmemb, void *userdata) { std::string &s = *(std::string *)userdata; auto read = size * nmemb; s.append(ptr, ptr + read); return read; }; string CurlHttpClient::makeRequest(const Url& url, const vector<HttpReqArg>& args) const { // Copy settings for each call because we change CURLOPT_URL and other stuff. // This also protects multithreaded case. auto curl = curl_easy_duphandle(curlSettings); auto u = url.protocol + "://" + url.host + url.path; curl_easy_setopt(curl, CURLOPT_URL, u.c_str()); if (!args.empty()) { std::string data; for (auto &a : args) data += a.name + "=" + a.value + "&"; data.resize(data.size() - 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); } std::string response; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_string); auto res = curl_easy_perform(curl); long http_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); curl_easy_cleanup(curl); if (res != CURLE_OK) throw std::runtime_error(std::string("curl error: ") + curl_easy_strerror(res)); if (http_code != 200) throw std::runtime_error("http request returned with code = " + std::to_string(http_code)); return HttpParser::getInstance().parseResponse(response); } #endif } <commit_msg>Don't destroy post data early.<commit_after>/* * Copyright (c) 2015 Oleg Morozenkov * Copyright (c) 2018 Egor Pugin * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "tgbot/net/HttpClient.h" #include <boost/asio/ssl.hpp> using namespace std; using namespace boost::asio; using namespace boost::asio::ip; namespace TgBot { BoostHttpClient& BoostHttpClient::getInstance() { static BoostHttpClient result; return result; } string BoostHttpClient::makeRequest(const Url& url, const vector<HttpReqArg>& args) const { ssl::context context(ssl::context::sslv23); context.set_default_verify_paths(); ssl::stream<tcp::socket> socket(_ioService, context); tcp::resolver resolver(_ioService); tcp::resolver::query query(url.host, url.protocol); connect(socket.lowest_layer(), resolver.resolve(query)); #ifdef TGBOT_DISABLE_NAGLES_ALGORITHM socket.lowest_layer().set_option(tcp::no_delay(true)); #endif //TGBOT_DISABLE_NAGLES_ALGORITHM #ifdef TGBOT_CHANGE_SOCKET_BUFFER_SIZE #if _WIN64 || __amd64__ || __x86_64__ || __MINGW64__ || __aarch64__ || __powerpc64__ socket.lowest_layer().set_option(socket_base::send_buffer_size(65536)); socket.lowest_layer().set_option(socket_base::receive_buffer_size(65536)); #else //for 32-bit socket.lowest_layer().set_option(socket_base::send_buffer_size(32768)); socket.lowest_layer().set_option(socket_base::receive_buffer_size(32768)); #endif //Processor architecture #endif //TGBOT_CHANGE_SOCKET_BUFFER_SIZE socket.set_verify_mode(ssl::verify_none); socket.set_verify_callback(ssl::rfc2818_verification(url.host)); socket.handshake(ssl::stream<tcp::socket>::client); string requestText = HttpParser::getInstance().generateRequest(url, args, false); write(socket, buffer(requestText.c_str(), requestText.length())); string response; #ifdef TGBOT_CHANGE_READ_BUFFER_SIZE #if _WIN64 || __amd64__ || __x86_64__ || __MINGW64__ || __aarch64__ || __powerpc64__ char buff[65536]; #else //for 32-bit char buff[32768]; #endif //Processor architecture #else char buff[1024]; #endif //TGBOT_CHANGE_READ_BUFFER_SIZE boost::system::error_code error; while (!error) { size_t bytes = read(socket, buffer(buff), error); response += string(buff, bytes); } return HttpParser::getInstance().parseResponse(response); } #ifdef HAVE_CURL CurlHttpClient::CurlHttpClient() { curlSettings = curl_easy_init(); } CurlHttpClient::~CurlHttpClient() { curl_easy_cleanup(curlSettings); } CurlHttpClient& CurlHttpClient::getInstance() { static CurlHttpClient result; return result; } static size_t curl_write_string(char *ptr, size_t size, size_t nmemb, void *userdata) { std::string &s = *(std::string *)userdata; auto read = size * nmemb; s.append(ptr, ptr + read); return read; }; string CurlHttpClient::makeRequest(const Url& url, const vector<HttpReqArg>& args) const { // Copy settings for each call because we change CURLOPT_URL and other stuff. // This also protects multithreaded case. auto curl = curl_easy_duphandle(curlSettings); auto u = url.protocol + "://" + url.host + url.path; curl_easy_setopt(curl, CURLOPT_URL, u.c_str()); std::string data; if (!args.empty()) { for (auto &a : args) data += a.name + "=" + a.value + "&"; data.resize(data.size() - 1); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); } std::string response; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_write_string); auto res = curl_easy_perform(curl); long http_code; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); curl_easy_cleanup(curl); if (res != CURLE_OK) throw std::runtime_error(std::string("curl error: ") + curl_easy_strerror(res)); if (http_code != 200) throw std::runtime_error("http request returned with code = " + std::to_string(http_code)); return HttpParser::getInstance().parseResponse(response); } #endif } <|endoftext|>
<commit_before>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "win_dev_wifi_native.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::DisposeNative___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeInit___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeConnect___WindowsDevicesWiFiWiFiConnectionStatus__STRING__STRING__WindowsDevicesWiFiWiFiReconnectionKind, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeDisconnect___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeScanAsync___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::GetNativeScanReport___SZARRAY_U1, NULL, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeFindWirelessAdapters___STATIC__SZARRAY_U1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_Windows_Devices_Wifi = { "Windows.Devices.Wifi", 0x5AC050C9, method_lookup, { 1, 0, 0, 0 } }; <commit_msg>Normalize line endings (#903)<commit_after>// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // #include "win_dev_wifi_native.h" static const CLR_RT_MethodHandler method_lookup[] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::DisposeNative___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeInit___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeConnect___WindowsDevicesWiFiWiFiConnectionStatus__STRING__STRING__WindowsDevicesWiFiWiFiReconnectionKind, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeDisconnect___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeScanAsync___VOID, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::GetNativeScanReport___SZARRAY_U1, NULL, Library_win_dev_wifi_native_Windows_Devices_WiFi_WiFiAdapter::NativeFindWirelessAdapters___STATIC__SZARRAY_U1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; const CLR_RT_NativeAssemblyData g_CLR_AssemblyNative_Windows_Devices_Wifi = { "Windows.Devices.Wifi", 0x5AC050C9, method_lookup, { 1, 0, 0, 0 } }; <|endoftext|>
<commit_before>#ifndef INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH #define INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH #include <gtest/gtest.h> #include <Unittests/unittests_common.hh> #include <iostream> class OpenMeshAddFaceTriangleMesh : public OpenMeshBase { protected: // This function is called before each test is run virtual void SetUp() { // Do some initial stuff with the member data here... } // This function is called after all tests are through virtual void TearDown() { // Do some final stuff with the member data here... } // Member already defined in OpenMeshBase //Mesh mesh_; }; class OpenMeshAddFacePolyMesh : public OpenMeshBasePoly { protected: // This function is called before each test is run virtual void SetUp() { // Do some initial stuff with the member data here... } // This function is called after all tests are through virtual void TearDown() { // Do some final stuff with the member data here... } // Member already defined in OpenMeshBase //Mesh mesh_; }; /* * ==================================================================== * Define tests below * ==================================================================== */ /* Adds two triangles to a tri mesh */ TEST_F(OpenMeshAddFaceTriangleMesh, AddTrianglesToTrimesh) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[4]; vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0)); vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0)); vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0)); vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0)); // Add two faces std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[0]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); // Test setup: // 1 === 2 // | / | // | / | // | / | // 0 === 3 // Check setup EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(2u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a quad to a trimesh (should be triangulated afterwards) */ TEST_F(OpenMeshAddFaceTriangleMesh, AddQuadToTrimesh) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[4]; vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0)); vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0)); vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0)); vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0)); // Add two faces std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); // Test setup: // 1 === 2 // | / | // | / | // | / | // 0 === 3 // Check setup EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(2u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a cube to a trimesh */ TEST_F(OpenMeshAddFaceTriangleMesh, CreateTriangleMeshCube) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[8]; vhandle[0] = mesh_.add_vertex(Mesh::Point(-1, -1, 1)); vhandle[1] = mesh_.add_vertex(Mesh::Point( 1, -1, 1)); vhandle[2] = mesh_.add_vertex(Mesh::Point( 1, 1, 1)); vhandle[3] = mesh_.add_vertex(Mesh::Point(-1, 1, 1)); vhandle[4] = mesh_.add_vertex(Mesh::Point(-1, -1, -1)); vhandle[5] = mesh_.add_vertex(Mesh::Point( 1, -1, -1)); vhandle[6] = mesh_.add_vertex(Mesh::Point( 1, 1, -1)); vhandle[7] = mesh_.add_vertex(Mesh::Point(-1, 1, -1)); // Add six faces to form a cube std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[4]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[6]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[6]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[7]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[7]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); // Test setup: // // // 3 ======== 2 // / /| // / / | z // 0 ======== 1 | | // | | | | y // | 7 | 6 | / // | | / | / // | |/ |/ // 4 ======== 5 -------> x // // Check setup EXPECT_EQ(8u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(12u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a quad to a polymesh (should be a quad afterwards) */ TEST_F(OpenMeshAddFacePolyMesh, AddQuadToPolymesh) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[4]; vhandle[0] = mesh_.add_vertex(PolyMesh::Point(0, 0, 0)); vhandle[1] = mesh_.add_vertex(PolyMesh::Point(0, 1, 0)); vhandle[2] = mesh_.add_vertex(PolyMesh::Point(1, 1, 0)); vhandle[3] = mesh_.add_vertex(PolyMesh::Point(1, 0, 0)); // Add two faces std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); // Test setup: // 1 === 2 // | | // | | // | | // 0 === 3 // Check setup EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(1u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a cube to a polymesh */ TEST_F(OpenMeshAddFacePolyMesh, CreatePolyMeshCube) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[8]; vhandle[0] = mesh_.add_vertex(PolyMesh::Point(-1, -1, 1)); vhandle[1] = mesh_.add_vertex(PolyMesh::Point( 1, -1, 1)); vhandle[2] = mesh_.add_vertex(PolyMesh::Point( 1, 1, 1)); vhandle[3] = mesh_.add_vertex(PolyMesh::Point(-1, 1, 1)); vhandle[4] = mesh_.add_vertex(PolyMesh::Point(-1, -1, -1)); vhandle[5] = mesh_.add_vertex(PolyMesh::Point( 1, -1, -1)); vhandle[6] = mesh_.add_vertex(PolyMesh::Point( 1, 1, -1)); vhandle[7] = mesh_.add_vertex(PolyMesh::Point(-1, 1, -1)); // Add six faces to form a cube std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[4]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[6]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[7]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); // Test setup: // // // 3 ======== 2 // / /| // / / | z // 0 ======== 1 | | // | | | | y // | 7 | 6 | / // | | / | / // | |/ |/ // 4 ======== 5 -------> x // // Check setup EXPECT_EQ(8u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(6u, mesh_.n_faces() ) << "Wrong number of faces"; } #endif // INCLUDE GUARD <commit_msg>Added a unittest to create the strange configuration. Still have to analyze in more detail.<commit_after>#ifndef INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH #define INCLUDE_UNITTESTS_OpenMeshAddFaceTriangleMesh_HH #include <gtest/gtest.h> #include <Unittests/unittests_common.hh> #include <iostream> class OpenMeshAddFaceTriangleMesh : public OpenMeshBase { protected: // This function is called before each test is run virtual void SetUp() { // Do some initial stuff with the member data here... } // This function is called after all tests are through virtual void TearDown() { // Do some final stuff with the member data here... } // Member already defined in OpenMeshBase //Mesh mesh_; }; class OpenMeshAddFacePolyMesh : public OpenMeshBasePoly { protected: // This function is called before each test is run virtual void SetUp() { // Do some initial stuff with the member data here... } // This function is called after all tests are through virtual void TearDown() { // Do some final stuff with the member data here... } // Member already defined in OpenMeshBase //Mesh mesh_; }; /* * ==================================================================== * Define tests below * ==================================================================== */ /* Adds two triangles to a tri mesh */ TEST_F(OpenMeshAddFaceTriangleMesh, AddTrianglesToTrimesh) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[4]; vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0)); vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0)); vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0)); vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0)); // Add two faces std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[0]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); // Test setup: // 1 === 2 // | / | // | / | // | / | // 0 === 3 // Check setup EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(2u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a quad to a trimesh (should be triangulated afterwards) */ TEST_F(OpenMeshAddFaceTriangleMesh, AddQuadToTrimesh) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[4]; vhandle[0] = mesh_.add_vertex(Mesh::Point(0, 0, 0)); vhandle[1] = mesh_.add_vertex(Mesh::Point(0, 1, 0)); vhandle[2] = mesh_.add_vertex(Mesh::Point(1, 1, 0)); vhandle[3] = mesh_.add_vertex(Mesh::Point(1, 0, 0)); // Add two faces std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); // Test setup: // 1 === 2 // | / | // | / | // | / | // 0 === 3 // Check setup EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(2u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a cube to a trimesh */ TEST_F(OpenMeshAddFaceTriangleMesh, CreateTriangleMeshCube) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[8]; vhandle[0] = mesh_.add_vertex(Mesh::Point(-1, -1, 1)); vhandle[1] = mesh_.add_vertex(Mesh::Point( 1, -1, 1)); vhandle[2] = mesh_.add_vertex(Mesh::Point( 1, 1, 1)); vhandle[3] = mesh_.add_vertex(Mesh::Point(-1, 1, 1)); vhandle[4] = mesh_.add_vertex(Mesh::Point(-1, -1, -1)); vhandle[5] = mesh_.add_vertex(Mesh::Point( 1, -1, -1)); vhandle[6] = mesh_.add_vertex(Mesh::Point( 1, 1, -1)); vhandle[7] = mesh_.add_vertex(Mesh::Point(-1, 1, -1)); // Add six faces to form a cube std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[4]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[6]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[6]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[7]); mesh_.add_face(face_vhandles); //======================= face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[7]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); // Test setup: // // // 3 ======== 2 // / /| // / / | z // 0 ======== 1 | | // | | | | y // | 7 | 6 | / // | | / | / // | |/ |/ // 4 ======== 5 -------> x // // Check setup EXPECT_EQ(8u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(12u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a quite strange configuration to the mesh */ TEST_F(OpenMeshAddFaceTriangleMesh, CreateStrangeConfig) { Mesh::VertexHandle vh[7]; Mesh::FaceHandle fh[4]; // // 2 x-----------x 1 // \ / // \ / // \ / // \ / // \ / // 0 x ---x 6 // /|\ | // / | \ | // / | \ | // / | \| // x----x x // 3 4 5 // // // // Add vertices vh[0] = mesh_.add_vertex (Mesh::Point (0, 0, 0)); vh[1] = mesh_.add_vertex (Mesh::Point (1, 1, 1)); vh[2] = mesh_.add_vertex (Mesh::Point (2, 2, 2)); vh[3] = mesh_.add_vertex (Mesh::Point (3, 3, 3)); vh[4] = mesh_.add_vertex (Mesh::Point (4, 4, 4)); vh[5] = mesh_.add_vertex (Mesh::Point (5, 5, 5)); vh[6] = mesh_.add_vertex (Mesh::Point (6, 6, 6)); mesh_.add_face( vh[0], vh[1], vh[2] ); mesh_.add_face( vh[0], vh[3], vh[4] ); mesh_.add_face( vh[0], vh[5], vh[6] ); // non-manifold! mesh_.add_face( vh[3], vh[0], vh[4] ); // Check setup EXPECT_EQ(7u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(4u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a quad to a polymesh (should be a quad afterwards) */ TEST_F(OpenMeshAddFacePolyMesh, AddQuadToPolymesh) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[4]; vhandle[0] = mesh_.add_vertex(PolyMesh::Point(0, 0, 0)); vhandle[1] = mesh_.add_vertex(PolyMesh::Point(0, 1, 0)); vhandle[2] = mesh_.add_vertex(PolyMesh::Point(1, 1, 0)); vhandle[3] = mesh_.add_vertex(PolyMesh::Point(1, 0, 0)); // Add two faces std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); // Test setup: // 1 === 2 // | | // | | // | | // 0 === 3 // Check setup EXPECT_EQ(4u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(1u, mesh_.n_faces() ) << "Wrong number of faces"; } /* Adds a cube to a polymesh */ TEST_F(OpenMeshAddFacePolyMesh, CreatePolyMeshCube) { mesh_.clear(); // Add some vertices Mesh::VertexHandle vhandle[8]; vhandle[0] = mesh_.add_vertex(PolyMesh::Point(-1, -1, 1)); vhandle[1] = mesh_.add_vertex(PolyMesh::Point( 1, -1, 1)); vhandle[2] = mesh_.add_vertex(PolyMesh::Point( 1, 1, 1)); vhandle[3] = mesh_.add_vertex(PolyMesh::Point(-1, 1, 1)); vhandle[4] = mesh_.add_vertex(PolyMesh::Point(-1, -1, -1)); vhandle[5] = mesh_.add_vertex(PolyMesh::Point( 1, -1, -1)); vhandle[6] = mesh_.add_vertex(PolyMesh::Point( 1, 1, -1)); vhandle[7] = mesh_.add_vertex(PolyMesh::Point(-1, 1, -1)); // Add six faces to form a cube std::vector<Mesh::VertexHandle> face_vhandles; face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[3]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[4]); face_vhandles.push_back(vhandle[5]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[1]); face_vhandles.push_back(vhandle[5]); face_vhandles.push_back(vhandle[6]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[2]); face_vhandles.push_back(vhandle[6]); face_vhandles.push_back(vhandle[7]); mesh_.add_face(face_vhandles); face_vhandles.clear(); face_vhandles.push_back(vhandle[0]); face_vhandles.push_back(vhandle[3]); face_vhandles.push_back(vhandle[7]); face_vhandles.push_back(vhandle[4]); mesh_.add_face(face_vhandles); // Test setup: // // // 3 ======== 2 // / /| // / / | z // 0 ======== 1 | | // | | | | y // | 7 | 6 | / // | | / | / // | |/ |/ // 4 ======== 5 -------> x // // Check setup EXPECT_EQ(8u, mesh_.n_vertices() ) << "Wrong number of vertices"; EXPECT_EQ(6u, mesh_.n_faces() ) << "Wrong number of faces"; } #endif // INCLUDE GUARD <|endoftext|>
<commit_before>// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // REQUIRES: fcoroutines-ts // These configurations run the tests with '-g', which hits a bug in Clangs // coroutine implementation. // XFAIL: asan, msan, ubsan, tsan // RUN: %build -fcoroutines-ts // RUN: %run // A simple "breathing" test that checks that <experimental/coroutine> // can be parsed and used in all dialects, including C++03 in order to match // Clang's behavior. #include <experimental/coroutine> namespace coro = std::experimental::coroutines_v1; coro::suspend_always sa; coro::suspend_never sn; struct MyFuture { struct promise_type { typedef coro::coroutine_handle<promise_type> HandleT; coro::suspend_always initial_suspend() { return sa; } coro::suspend_never final_suspend() { return sn; } coro::suspend_never yield_value(int) { return sn; } MyFuture get_return_object() { MyFuture f(HandleT::from_address(this)); return f; } void return_void() {} void unhandled_exception() {} }; typedef promise_type::HandleT HandleT; MyFuture() : p() {} MyFuture(HandleT h) : p(h) {} private: coro::coroutine_handle<promise_type> p; }; MyFuture test_coro() { co_await sn; co_yield 42; co_return; } int main() { MyFuture f = test_coro(); } <commit_msg>Remove XFAIL's for recently fixed bug<commit_after>// -*- C++ -*- //===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // REQUIRES: fcoroutines-ts // RUN: %build -fcoroutines-ts // RUN: %run // A simple "breathing" test that checks that <experimental/coroutine> // can be parsed and used in all dialects, including C++03 in order to match // Clang's behavior. #include <experimental/coroutine> namespace coro = std::experimental::coroutines_v1; coro::suspend_always sa; coro::suspend_never sn; struct MyFuture { struct promise_type { typedef coro::coroutine_handle<promise_type> HandleT; coro::suspend_always initial_suspend() { return sa; } coro::suspend_never final_suspend() { return sn; } coro::suspend_never yield_value(int) { return sn; } MyFuture get_return_object() { MyFuture f(HandleT::from_address(this)); return f; } void return_void() {} void unhandled_exception() {} }; typedef promise_type::HandleT HandleT; MyFuture() : p() {} MyFuture(HandleT h) : p(h) {} private: coro::coroutine_handle<promise_type> p; }; MyFuture test_coro() { co_await sn; co_yield 42; co_return; } int main() { MyFuture f = test_coro(); } <|endoftext|>
<commit_before>// Copyright (c) 2015-2016 The Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pos.h" #include "chain.h" #include "chainparams.h" #include "coins.h" #include "hash.h" #include "hash.h" #include "main.h" #include "uint256.h" #include "util.h" #include "primitives/transaction.h" #include "consensus/validation.h" #include "script/standard.h" #include "consensus/consensus.h" #include "policy/policy.h" // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. const int STAKE_TIMESTAMP_MASK = 15; uint256 ComputeStakeModifier(const CBlockIndex* pindexPrev, const uint256& kernel) { if (!pindexPrev) return uint256(); // genesis block's modifier is 0 CHashWriter ss(SER_GETHASH, 0); ss << kernel << pindexPrev->nStakeModifier; return ss.GetHash(); } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx) { return (nTimeBlock == nTimeTx); } // BlackCoin kernel protocol v3 // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.nTime + txPrev.vout.hash + txPrev.vout.n + nTime) < bnTarget * nWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coins one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake // txPrev.nTime: slightly scrambles computation // txPrev.vout.hash: hash of txPrev, to reduce the chance of nodes // generating coinstake at the same time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // nTime: current timestamp // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. bool CheckStakeKernelHash(const CBlockIndex* pindexPrev, unsigned int nBits, const CCoins* txPrev, const COutPoint& prevout, unsigned int nTimeTx) { // Weight int64_t nValueIn = txPrev->vout[prevout.n].nValue; if (nValueIn == 0) return false; // Base target arith_uint256 bnTarget; bnTarget.SetCompact(nBits); // Calculate hash CHashWriter ss(SER_GETHASH, 0); ss << pindexPrev->nStakeModifier << txPrev->nTime << prevout.hash << prevout.n << nTimeTx; uint256 hashProofOfStake = ss.GetHash(); // Now check if proof-of-stake hash meets target protocol if ((UintToArith256(hashProofOfStake) / nValueIn ) > bnTarget){ LogPrintf("CheckStakeKernelHash() : hash does not meet protocol target \n"); return false; } return true; } bool CheckKernel(CBlockIndex* pindexPrev, unsigned int nBits, int64_t nTime, const COutPoint& prevout, int64_t* pBlockTime) { uint256 hashProofOfStake, targetProofOfStake; CValidationState state; const CChainParams& chainparams = Params(); CCoinsViewCache &view = *pcoinsTip; const CCoins *coins = view.AccessCoins(prevout.hash); if (!coins) return false; // Read block header CBlock block; if (!ReadBlockFromDisk(block, pindexPrev, chainparams.GetConsensus())) return false; // Maturity requirement if (pindexPrev->nHeight - coins->nHeight < STAKE_MIN_CONFIRMATIONS) return false; if (pBlockTime) *pBlockTime = block.GetBlockTime(); // Min age requirement if (coins->nTime + Params().GetConsensus().nStakeMinAge > nTime) // Min age requirement return false; return CheckStakeKernelHash(pindexPrev->pprev, block.nBits, coins, prevout, block.vtx[1].nTime); } // Check kernel hash target and coinstake signature bool CheckProofOfStake(CBlockIndex* pindexPrev, const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { CValidationState state; const CChainParams& chainparams = Params(); if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s \n", tx.GetHash().ToString()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CCoinsViewCache &view = *pcoinsTip; const COutPoint &prevout = txin.prevout; const CCoins *coins = view.AccessCoins(prevout.hash); if (!coins) return state.DoS(100, error("%s: kernel input unavailable", __func__), REJECT_INVALID, "bad-cs-kernel"); CTransaction prevtx; uint256 hashBlock; const uint256& hash = txin.prevout.hash; if (!GetTransaction(hash, prevtx, Params().GetConsensus(), hashBlock, true)) return state.DoS(1, false, REJECT_INVALID, "read-txPrev-failed"); // Verify signature const CTxOut& txout = prevtx.vout[txin.prevout.n]; if (txin.prevout.n >= prevtx.vout.size()) return false; if (txin.prevout.hash != prevtx.GetHash()) return false; ScriptError serror = SCRIPT_ERR_OK; if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, SCRIPT_VERIFY_NONE, TransactionSignatureChecker(&tx, 0), &serror)) return state.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s, scriptsig = %s, scriptPubKey=%s , extsiting errors = %s \n", tx.GetHash().ToString(), txin.scriptSig.ToString(), txout.scriptPubKey.ToString(), std::string(ScriptErrorString(serror)).c_str())); // Read block header CBlock block; if (!ReadBlockFromDisk(block, pindexPrev, chainparams.GetConsensus())) return fDebug? error("CheckProofOfStake(): *** ReadBlockFromDisk failed at %d, hash=%s \n", pindexPrev->nHeight, pindexPrev->GetBlockHash().ToString()) : false; // Min age requirement if (pindexPrev->nHeight - coins->nHeight < STAKE_MIN_CONFIRMATIONS) return state.DoS(100, error("%s: tried to stake at depth %d \n", __func__, pindexPrev->nHeight - coins->nHeight), REJECT_INVALID, "bad-cs-premature"); if (prevtx.nTime + Params().GetConsensus().nStakeMinAge > tx.nTime) // Min age requirement return error("CheckProofOfStake() : min age violation - nTimeBlockFrom=%d nStakeMinAge=%d nTimeTx=%d \n", coins->nTime, Params().GetConsensus().nStakeMinAge, tx.nTime); if (!CheckStakeKernelHash(pindexPrev->pprev, block.nBits, coins, prevout, block.vtx[1].nTime)) return state.DoS(1, error("%s: pos hash doesn't match nBits \n", __func__), REJECT_INVALID, "bad-cs-proofhash"); return true; } <commit_msg>Stake time fix<commit_after>// Copyright (c) 2015-2016 The Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pos.h" #include "chain.h" #include "chainparams.h" #include "coins.h" #include "hash.h" #include "hash.h" #include "main.h" #include "uint256.h" #include "util.h" #include "primitives/transaction.h" #include "consensus/validation.h" #include "script/standard.h" #include "consensus/consensus.h" #include "policy/policy.h" // Stake Modifier (hash modifier of proof-of-stake): // The purpose of stake modifier is to prevent a txout (coin) owner from // computing future proof-of-stake generated by this txout at the time // of transaction confirmation. To meet kernel protocol, the txout // must hash with a future stake modifier to generate the proof. const int STAKE_TIMESTAMP_MASK = 15; uint256 ComputeStakeModifier(const CBlockIndex* pindexPrev, const uint256& kernel) { if (!pindexPrev) return uint256(); // genesis block's modifier is 0 CHashWriter ss(SER_GETHASH, 0); ss << kernel << pindexPrev->nStakeModifier; return ss.GetHash(); } // Check whether the coinstake timestamp meets protocol bool CheckCoinStakeTimestamp(int64_t nTimeBlock, int64_t nTimeTx) { return (nTimeBlock == nTimeTx); } // BlackCoin kernel protocol v3 // coinstake must meet hash target according to the protocol: // kernel (input 0) must meet the formula // hash(nStakeModifier + txPrev.nTime + txPrev.vout.hash + txPrev.vout.n + nTime) < bnTarget * nWeight // this ensures that the chance of getting a coinstake is proportional to the // amount of coins one owns. // The reason this hash is chosen is the following: // nStakeModifier: scrambles computation to make it very difficult to precompute // future proof-of-stake // txPrev.nTime: slightly scrambles computation // txPrev.vout.hash: hash of txPrev, to reduce the chance of nodes // generating coinstake at the same time // txPrev.vout.n: output number of txPrev, to reduce the chance of nodes // generating coinstake at the same time // nTime: current timestamp // block/tx hash should not be used here as they can be generated in vast // quantities so as to generate blocks faster, degrading the system back into // a proof-of-work situation. bool CheckStakeKernelHash(const CBlockIndex* pindexPrev, unsigned int nBits, const CCoins* txPrev, const COutPoint& prevout, unsigned int nTimeTx) { // Weight int64_t nValueIn = txPrev->vout[prevout.n].nValue; if (nValueIn == 0) return false; // Base target arith_uint256 bnTarget; bnTarget.SetCompact(nBits); // Calculate hash CHashWriter ss(SER_GETHASH, 0); ss << pindexPrev->nStakeModifier << txPrev->nTime << prevout.hash << prevout.n << nTimeTx; uint256 hashProofOfStake = ss.GetHash(); // Now check if proof-of-stake hash meets target protocol if ((UintToArith256(hashProofOfStake) / nValueIn ) > bnTarget){ LogPrintf("CheckStakeKernelHash() : hash does not meet protocol target \n"); return false; } return true; } bool CheckKernel(CBlockIndex* pindexPrev, unsigned int nBits, int64_t nTime, const COutPoint& prevout, int64_t* pBlockTime) { uint256 hashProofOfStake, targetProofOfStake; CValidationState state; const CChainParams& chainparams = Params(); CCoinsViewCache &view = *pcoinsTip; const CCoins *coins = view.AccessCoins(prevout.hash); if (!coins) return false; // Read block header CBlock block; if (!ReadBlockFromDisk(block, pindexPrev, chainparams.GetConsensus())) return false; // Maturity requirement if (pindexPrev->nHeight - coins->nHeight < STAKE_MIN_CONFIRMATIONS) return false; if (pBlockTime) *pBlockTime = block.GetBlockTime(); // Min age requirement if (coins->nTime + Params().GetConsensus().nStakeMinAge > nTime) // Min age requirement return false; return CheckStakeKernelHash(pindexPrev->pprev, block.nBits, coins, prevout, nTime); } // Check kernel hash target and coinstake signature bool CheckProofOfStake(CBlockIndex* pindexPrev, const CTransaction& tx, unsigned int nBits, uint256& hashProofOfStake, uint256& targetProofOfStake) { CValidationState state; const CChainParams& chainparams = Params(); if (!tx.IsCoinStake()) return error("CheckProofOfStake() : called on non-coinstake %s \n", tx.GetHash().ToString()); // Kernel (input 0) must match the stake hash target per coin age (nBits) const CTxIn& txin = tx.vin[0]; // First try finding the previous transaction in database CCoinsViewCache &view = *pcoinsTip; const COutPoint &prevout = txin.prevout; const CCoins *coins = view.AccessCoins(prevout.hash); if (!coins) return state.DoS(100, error("%s: kernel input unavailable", __func__), REJECT_INVALID, "bad-cs-kernel"); CTransaction prevtx; uint256 hashBlock; const uint256& hash = txin.prevout.hash; if (!GetTransaction(hash, prevtx, Params().GetConsensus(), hashBlock, true)) return state.DoS(1, false, REJECT_INVALID, "read-txPrev-failed"); // Verify signature const CTxOut& txout = prevtx.vout[txin.prevout.n]; if (txin.prevout.n >= prevtx.vout.size()) return false; if (txin.prevout.hash != prevtx.GetHash()) return false; ScriptError serror = SCRIPT_ERR_OK; if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, SCRIPT_VERIFY_NONE, TransactionSignatureChecker(&tx, 0), &serror)) return state.DoS(100, error("CheckProofOfStake() : VerifySignature failed on coinstake %s, scriptsig = %s, scriptPubKey=%s , extsiting errors = %s \n", tx.GetHash().ToString(), txin.scriptSig.ToString(), txout.scriptPubKey.ToString(), std::string(ScriptErrorString(serror)).c_str())); // Read block header CBlock block; if (!ReadBlockFromDisk(block, pindexPrev, chainparams.GetConsensus())) return fDebug? error("CheckProofOfStake(): *** ReadBlockFromDisk failed at %d, hash=%s \n", pindexPrev->nHeight, pindexPrev->GetBlockHash().ToString()) : false; // Min age requirement if (pindexPrev->nHeight - coins->nHeight < STAKE_MIN_CONFIRMATIONS) return state.DoS(100, error("%s: tried to stake at depth %d \n", __func__, pindexPrev->nHeight - coins->nHeight), REJECT_INVALID, "bad-cs-premature"); if (prevtx.nTime + Params().GetConsensus().nStakeMinAge > tx.nTime) // Min age requirement return error("CheckProofOfStake() : min age violation - nTimeBlockFrom=%d nStakeMinAge=%d nTimeTx=%d \n", coins->nTime, Params().GetConsensus().nStakeMinAge, tx.nTime); if (!CheckStakeKernelHash(pindexPrev->pprev, block.nBits, coins, prevout, block.vtx[1].nTime)) return state.DoS(1, error("%s: pos hash doesn't match nBits \n", __func__), REJECT_INVALID, "bad-cs-proofhash"); return true; } <|endoftext|>
<commit_before>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "Test.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkColor.h" #include "SkFontHost.h" #include "SkGraphics.h" #include "SkPaint.h" #include "SkPoint.h" #include "SkRect.h" #include "SkTypeface.h" /////////////////////////////////////////////////////////////////////////////// static const SkColor bgColor = SK_ColorWHITE; static void create(SkBitmap* bm, SkIRect bound, SkBitmap::Config config) { bm->setConfig(config, bound.width(), bound.height()); bm->allocPixels(); } static void drawBG(SkCanvas* canvas) { canvas->drawColor(bgColor); } /** Assumes that the ref draw was completely inside ref canvas -- implies that everything outside is "bgColor". Checks that all overlap is the same and that all non-overlap on the ref is "bgColor". */ static bool compare(const SkBitmap& ref, const SkIRect& iref, const SkBitmap& test, const SkIRect& itest) { const int xOff = itest.fLeft - iref.fLeft; const int yOff = itest.fTop - iref.fTop; SkAutoLockPixels alpRef(ref); SkAutoLockPixels alpTest(test); for (int y = 0; y < test.height(); ++y) { for (int x = 0; x < test.width(); ++x) { SkColor testColor = test.getColor(x, y); int refX = x + xOff; int refY = y + yOff; SkColor refColor; if (refX >= 0 && refX < ref.width() && refY >= 0 && refY < ref.height()) { refColor = ref.getColor(refX, refY); } else { refColor = bgColor; } if (refColor != testColor) { return false; } } } return true; } static void test_fontHostStream(skiatest::Reporter* reporter) { { SkPaint paint; paint.setColor(SK_ColorGRAY); paint.setTextSize(SkIntToScalar(30)); paint.setTypeface(SkTypeface::CreateFromName("Georgia", SkTypeface::kNormal))->unref(); SkIRect origRect = SkIRect::MakeWH(64, 64); SkBitmap origBitmap; create(&origBitmap, origRect, SkBitmap::kARGB_8888_Config); SkCanvas origCanvas(origBitmap); SkIRect streamRect = SkIRect::MakeWH(64, 64); SkBitmap streamBitmap; create(&streamBitmap, streamRect, SkBitmap::kARGB_8888_Config); SkCanvas streamCanvas(streamBitmap); SkPoint point = SkPoint::Make(24, 32); // Test: origTypeface and streamTypeface from orig data draw the same drawBG(&origCanvas); origCanvas.drawText("A", 1, point.fX, point.fY, paint); SkTypeface* origTypeface = paint.getTypeface(); SkAutoTUnref<SkTypeface> aur; if (NULL == origTypeface) { origTypeface = aur.reset(SkTypeface::RefDefault()); } int ttcIndex; SkStream* fontData = origTypeface->openStream(&ttcIndex); SkTypeface* streamTypeface = SkTypeface::CreateFromStream(fontData); SkSafeUnref(paint.setTypeface(streamTypeface)); drawBG(&streamCanvas); streamCanvas.drawPosText("A", 1, &point, paint); REPORTER_ASSERT(reporter, compare(origBitmap, origRect, streamBitmap, streamRect)); } //Make sure the typeface is deleted and removed. SkGraphics::PurgeFontCache(); } #include "TestClassDef.h" DEFINE_TESTCLASS("FontHost::CreateTypefaceFromStream", FontHostStreamTestClass, test_fontHostStream) <commit_msg>Check whether font creation is failed to avoid segment fault. In some rare cases, SkFontHost::CreateTypeface in src/ports/SkFontHost_fontconfig.cpp will return NULL, this will lead to segment fault because the previous code would access to 0x0 by (SkTypeface *)NULL->unref(). BUG= R=reed@google.com, bungeman@google.com<commit_after>/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkTypes.h" #include "Test.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkColor.h" #include "SkFontHost.h" #include "SkGraphics.h" #include "SkPaint.h" #include "SkPoint.h" #include "SkRect.h" #include "SkTypeface.h" /////////////////////////////////////////////////////////////////////////////// static const SkColor bgColor = SK_ColorWHITE; static void create(SkBitmap* bm, SkIRect bound, SkBitmap::Config config) { bm->setConfig(config, bound.width(), bound.height()); bm->allocPixels(); } static void drawBG(SkCanvas* canvas) { canvas->drawColor(bgColor); } /** Assumes that the ref draw was completely inside ref canvas -- implies that everything outside is "bgColor". Checks that all overlap is the same and that all non-overlap on the ref is "bgColor". */ static bool compare(const SkBitmap& ref, const SkIRect& iref, const SkBitmap& test, const SkIRect& itest) { const int xOff = itest.fLeft - iref.fLeft; const int yOff = itest.fTop - iref.fTop; SkAutoLockPixels alpRef(ref); SkAutoLockPixels alpTest(test); for (int y = 0; y < test.height(); ++y) { for (int x = 0; x < test.width(); ++x) { SkColor testColor = test.getColor(x, y); int refX = x + xOff; int refY = y + yOff; SkColor refColor; if (refX >= 0 && refX < ref.width() && refY >= 0 && refY < ref.height()) { refColor = ref.getColor(refX, refY); } else { refColor = bgColor; } if (refColor != testColor) { return false; } } } return true; } static void test_fontHostStream(skiatest::Reporter* reporter) { { SkPaint paint; paint.setColor(SK_ColorGRAY); paint.setTextSize(SkIntToScalar(30)); SkTypeface* fTypeface = SkTypeface::CreateFromName("Georgia", SkTypeface::kNormal); SkSafeUnref(paint.setTypeface(fTypeface)); SkIRect origRect = SkIRect::MakeWH(64, 64); SkBitmap origBitmap; create(&origBitmap, origRect, SkBitmap::kARGB_8888_Config); SkCanvas origCanvas(origBitmap); SkIRect streamRect = SkIRect::MakeWH(64, 64); SkBitmap streamBitmap; create(&streamBitmap, streamRect, SkBitmap::kARGB_8888_Config); SkCanvas streamCanvas(streamBitmap); SkPoint point = SkPoint::Make(24, 32); // Test: origTypeface and streamTypeface from orig data draw the same drawBG(&origCanvas); origCanvas.drawText("A", 1, point.fX, point.fY, paint); SkTypeface* origTypeface = paint.getTypeface(); SkAutoTUnref<SkTypeface> aur; if (NULL == origTypeface) { origTypeface = aur.reset(SkTypeface::RefDefault()); } int ttcIndex; SkStream* fontData = origTypeface->openStream(&ttcIndex); SkTypeface* streamTypeface = SkTypeface::CreateFromStream(fontData); SkSafeUnref(paint.setTypeface(streamTypeface)); drawBG(&streamCanvas); streamCanvas.drawPosText("A", 1, &point, paint); REPORTER_ASSERT(reporter, compare(origBitmap, origRect, streamBitmap, streamRect)); } //Make sure the typeface is deleted and removed. SkGraphics::PurgeFontCache(); } #include "TestClassDef.h" DEFINE_TESTCLASS("FontHost::CreateTypefaceFromStream", FontHostStreamTestClass, test_fontHostStream) <|endoftext|>
<commit_before>/* * IceWM * * Copyright (C) 1997-2003 Marko Macek * * Window list */ #include "config.h" #include "ykey.h" #include "ypaint.h" #include "wmwinlist.h" #include "ymenuitem.h" #include "yaction.h" #include "prefs.h" #include "wmaction.h" #include "wmclient.h" #include "wmframe.h" #include "wmmgr.h" #include "wmapp.h" #include "sysdep.h" #include "yrect.h" #include "intl.h" WindowList *windowList = 0; WindowListItem::WindowListItem(ClientData *frame, int workspace): YListItem() { fFrame = frame; fWorkspace = workspace; } WindowListItem::~WindowListItem() { if (fFrame) { fFrame->setWinListItem(0); fFrame = 0; } } int WindowListItem::getOffset() { int ofs = -20; ClientData *w = getFrame(); if (w) { ofs += 40; while (w->owner()) { ofs += 20; w = w->owner(); } } return ofs; } ustring WindowListItem::getText() { if (fFrame) return getFrame()->getTitle(); else if (fWorkspace < 0) return _("All Workspaces"); else return workspaceNames[fWorkspace]; } ref<YIcon> WindowListItem::getIcon() { if (fFrame) return getFrame()->getIcon(); return null; } WindowListBox::WindowListBox(YScrollView *view, YWindow *aParent): YListBox(view, aParent) { } WindowListBox::~WindowListBox() { } void WindowListBox::activateItem(YListItem *item) { WindowListItem *i = (WindowListItem *)item; ClientData *f = i->getFrame(); if (f) { f->activateWindow(true); windowList->getFrame()->wmHide(); } else { int w = i->getWorkspace(); if (w != -1) { manager->activateWorkspace(w); windowList->getFrame()->wmHide(); } } } void WindowListBox::getSelectedWindows(YArray<YFrameWindow *> &frames) { if (hasSelection()) { for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; ClientData *f = item->getFrame(); if (f) frames.append((YFrameWindow *)f); } } } } void WindowListBox::actionPerformed(YAction action, unsigned int modifiers) { YArray<YFrameWindow *> frameList; getSelectedWindows(frameList); if (action == actionTileVertical || action == actionTileHorizontal) { if (frameList.getCount() > 0) manager->tileWindows(frameList.getItemPtr(0), frameList.getCount(), (action == actionTileVertical) ? true : false); } else if (action == actionCascade || action == actionArrange) { if (frameList.getCount() > 0) { if (action == actionCascade) { manager->cascadePlace(frameList.getItemPtr(0), frameList.getCount()); } else if (action == actionArrange) { manager->smartPlace(frameList.getItemPtr(0), frameList.getCount()); } } } else { for (int i = 0; i < frameList.getCount(); i++) { if (action == actionHide) if (frameList[i]->isHidden()) continue; if (action == actionMinimize) if (frameList[i]->isMinimized()) continue; frameList[i]->actionPerformed(action, modifiers); } } } bool WindowListBox::handleKey(const XKeyEvent &key) { if (key.type == KeyPress) { KeySym k = keyCodeToKeySym(key.keycode); int m = KEY_MODMASK(key.state); switch (k) { case XK_Escape: windowList->getFrame()->wmHide(); return true; case XK_F10: case XK_Menu: if (k != XK_F10 || m == ShiftMask) { if (hasSelection()) { enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } } break; case XK_Delete: { if (m & ShiftMask) actionPerformed(actionKill, key.state); else actionPerformed(actionClose, key.state); } break; } } return YListBox::handleKey(key); } void WindowListBox::handleClick(const XButtonEvent &up, int count) { if (up.button == 3 && count == 1 && IS_BUTTON(up.state, Button3Mask)) { int no = findItemByPoint(up.x, up.y); if (no != -1) { YListItem *i = getItem(no); if (!isSelected(i)) { focusSelectItem(no); } else { //fFocusedItem = -1; } enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } return ; } YListBox::handleClick(up, count); } void WindowListBox::enableCommands(YMenu *popup) { bool noItems = true; long workspace = -1; bool sameWorkspace = false; bool notHidden = false; bool notMinimized = false; // enable minimize,hide if appropriate // enable workspace selections if appropriate popup->enableCommand(actionNull); for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; if (!item->getFrame()) { continue; } noItems = false; if (!item->getFrame()->isHidden()) notHidden = true; if (!item->getFrame()->isMinimized()) notMinimized = true; long ws = item->getFrame()->getWorkspace(); if (workspace == -1) { workspace = ws; sameWorkspace = true; } else if (workspace != ws) { sameWorkspace = false; } if (item->getFrame()->isAllWorkspaces()) sameWorkspace = false; } } if (!notHidden) popup->disableCommand(actionHide); if (!notMinimized) popup->disableCommand(actionMinimize); moveMenu->enableCommand(actionNull); if (sameWorkspace && workspace != -1) { for (int i = 0; i < moveMenu->itemCount(); i++) { YMenuItem *item = moveMenu->getItem(i); for (int w = 0; w < workspaceCount; w++) if (item && item->getAction() == workspaceActionMoveTo[w]) item->setEnabled(w != workspace); } } if (noItems) { moveMenu->disableCommand(actionNull); popup->disableCommand(actionNull); } } WindowList::WindowList(YWindow *aParent, YActionListener *wmActionListener): YFrameClient(aParent, 0) { this->wmActionListener = wmActionListener; scroll = new YScrollView(this); list = new WindowListBox(scroll, scroll); scroll->setView(list); list->show(); scroll->show(); fWorkspaceCount = workspaceCount; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; for (int ws = 0; ws < fWorkspaceCount; ws++) { workspaceItem[ws] = new WindowListItem(0, ws); list->addItem(workspaceItem[ws]); } workspaceItem[fWorkspaceCount] = new WindowListItem(0, -1); list->addItem(workspaceItem[fWorkspaceCount]); YMenu *closeSubmenu = new YMenu(); assert(closeSubmenu != 0); closeSubmenu->addItem(_("_Close"), -2, _("Del"), actionClose); closeSubmenu->addSeparator(); closeSubmenu->addItem(_("_Kill Client"), -2, null, actionKill); #if 0 closeSubmenu->addItem(_("_Terminate Process"), -2, 0, actionTermProcess)->setEnabled(false); closeSubmenu->addItem(_("Kill _Process"), -2, 0, actionKillProcess)->setEnabled(false); #endif windowListPopup = new YMenu(); windowListPopup->setActionListener(list); windowListPopup->addItem(_("_Show"), -2, null, actionShow); windowListPopup->addItem(_("_Hide"), -2, null, actionHide); windowListPopup->addItem(_("_Minimize"), -2, null, actionMinimize); windowListPopup->addSubmenu(_("Move _To"), -2, moveMenu); windowListPopup->addSeparator(); windowListPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Close"), -2, actionClose, closeSubmenu); windowListAllPopup = new YMenu(); windowListAllPopup->setActionListener(wmActionListener); windowListAllPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListAllPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListAllPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListAllPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListAllPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListAllPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListAllPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, 0); unsigned w = dw; unsigned h = dh; setGeometry(YRect(w / 4, h / 4, w / 2, h / 2)); windowList = this; setWindowTitle(_("Window list")); setIconTitle(_("Window list")); setWinHintsHint(WinHintsSkipTaskBar); setWinWorkspaceHint(-1); setWinLayerHint(WinLayerAboveDock); } WindowList::~WindowList() { delete list; list = 0; delete scroll; scroll = 0; windowList = 0; delete windowListAllPopup; windowListAllPopup = 0; for (int ws = 0; ws <= fWorkspaceCount; ws++) { delete workspaceItem[ws]; } delete[] workspaceItem; } void WindowList::updateWorkspaces() { long fOldWorkspaceCount = fWorkspaceCount; fWorkspaceCount = workspaceCount; if (fWorkspaceCount != fOldWorkspaceCount) { WindowListItem **oldWorkspaceItem = workspaceItem; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; workspaceItem[fWorkspaceCount] = oldWorkspaceItem[fOldWorkspaceCount]; list->removeItem(workspaceItem[fWorkspaceCount]); if (fWorkspaceCount > fOldWorkspaceCount) { for (long w = 0; w < fOldWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fOldWorkspaceCount; w < fWorkspaceCount; w++) { workspaceItem[w] = new WindowListItem(0, w); list->addItem(workspaceItem[w]); } } else if (fWorkspaceCount < fOldWorkspaceCount) { for (long w = 0; w < fWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fWorkspaceCount; w < fOldWorkspaceCount; w++) { list->removeItem(oldWorkspaceItem[w]); delete oldWorkspaceItem[w]; } } list->addItem(workspaceItem[fWorkspaceCount]); delete[] oldWorkspaceItem; } } void WindowList::handleFocus(const XFocusChangeEvent &focus) { if (focus.type == FocusIn && focus.mode != NotifyUngrab) { list->setWindowFocus(); } else if (focus.type == FocusOut) { } } void WindowList::relayout() { list->repaint(); } WindowListItem *WindowList::addWindowListApp(YFrameWindow *frame) { if (!frame->client()->adopted()) return 0; WindowListItem *item = new WindowListItem(frame); if (item) { insertApp(item); } return item; } void WindowList::insertApp(WindowListItem *item) { ClientData *frame = item->getFrame(); if (frame->owner() && frame->owner()->winListItem()) { list->addAfter(frame->owner()->winListItem(), item); } else { int nw = frame->getWorkspace(); if (!frame->isAllWorkspaces()) list->addAfter(workspaceItem[nw], item); else list->addItem(item); } } void WindowList::removeWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); delete item; } } void WindowList::updateWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); insertApp(item); } } void WindowList::configure(const YRect &r) { YFrameClient::configure(r); scroll->setGeometry(YRect(0, 0, r.width(), r.height())); } void WindowList::handleClose() { if (!getFrame()->isHidden()) getFrame()->wmHide(); } void WindowList::showFocused(int x, int y) { YFrameWindow *f = manager->getFocus(); if (f != getFrame()) { if (f) list->focusSelectItem(list->findItem(f->winListItem())); else list->focusSelectItem(0); } if (getFrame() == 0) manager->manageClient(handle(), false); if (getFrame() != 0) { if (x != -1 && y != -1) { int px, py; int xiscreen = manager->getScreenForRect(x, y, 1, 1); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, xiscreen); px = x - getFrame()->width() / 2; py = y - getFrame()->height() / 2; if (px + getFrame()->width() > dx + dw) px = dx + dw - getFrame()->width(); if (py + getFrame()->height() > dy + dh) py = dx + dh - getFrame()->height(); if (px < dx) px = dx; if (py < dy) py = dy; getFrame()->setNormalPositionOuter(px, py); } getFrame()->setRequestedLayer(WinLayerAboveDock); getFrame()->setAllWorkspaces(); getFrame()->activateWindow(true); } } // vim: set sw=4 ts=4 et: <commit_msg>Set window list title + class.<commit_after>/* * IceWM * * Copyright (C) 1997-2003 Marko Macek * * Window list */ #include "config.h" #include "ykey.h" #include "ypaint.h" #include "wmwinlist.h" #include "ymenuitem.h" #include "yaction.h" #include "prefs.h" #include "wmaction.h" #include "wmclient.h" #include "wmframe.h" #include "wmmgr.h" #include "wmapp.h" #include "sysdep.h" #include "yrect.h" #include "intl.h" WindowList *windowList = 0; WindowListItem::WindowListItem(ClientData *frame, int workspace): YListItem() { fFrame = frame; fWorkspace = workspace; } WindowListItem::~WindowListItem() { if (fFrame) { fFrame->setWinListItem(0); fFrame = 0; } } int WindowListItem::getOffset() { int ofs = -20; ClientData *w = getFrame(); if (w) { ofs += 40; while (w->owner()) { ofs += 20; w = w->owner(); } } return ofs; } ustring WindowListItem::getText() { if (fFrame) return getFrame()->getTitle(); else if (fWorkspace < 0) return _("All Workspaces"); else return workspaceNames[fWorkspace]; } ref<YIcon> WindowListItem::getIcon() { if (fFrame) return getFrame()->getIcon(); return null; } WindowListBox::WindowListBox(YScrollView *view, YWindow *aParent): YListBox(view, aParent) { } WindowListBox::~WindowListBox() { } void WindowListBox::activateItem(YListItem *item) { WindowListItem *i = (WindowListItem *)item; ClientData *f = i->getFrame(); if (f) { f->activateWindow(true); windowList->getFrame()->wmHide(); } else { int w = i->getWorkspace(); if (w != -1) { manager->activateWorkspace(w); windowList->getFrame()->wmHide(); } } } void WindowListBox::getSelectedWindows(YArray<YFrameWindow *> &frames) { if (hasSelection()) { for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; ClientData *f = item->getFrame(); if (f) frames.append((YFrameWindow *)f); } } } } void WindowListBox::actionPerformed(YAction action, unsigned int modifiers) { YArray<YFrameWindow *> frameList; getSelectedWindows(frameList); if (action == actionTileVertical || action == actionTileHorizontal) { if (frameList.getCount() > 0) manager->tileWindows(frameList.getItemPtr(0), frameList.getCount(), (action == actionTileVertical) ? true : false); } else if (action == actionCascade || action == actionArrange) { if (frameList.getCount() > 0) { if (action == actionCascade) { manager->cascadePlace(frameList.getItemPtr(0), frameList.getCount()); } else if (action == actionArrange) { manager->smartPlace(frameList.getItemPtr(0), frameList.getCount()); } } } else { for (int i = 0; i < frameList.getCount(); i++) { if (action == actionHide) if (frameList[i]->isHidden()) continue; if (action == actionMinimize) if (frameList[i]->isMinimized()) continue; frameList[i]->actionPerformed(action, modifiers); } } } bool WindowListBox::handleKey(const XKeyEvent &key) { if (key.type == KeyPress) { KeySym k = keyCodeToKeySym(key.keycode); int m = KEY_MODMASK(key.state); switch (k) { case XK_Escape: windowList->getFrame()->wmHide(); return true; case XK_F10: case XK_Menu: if (k != XK_F10 || m == ShiftMask) { if (hasSelection()) { enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, key.x_root, key.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } } break; case XK_Delete: { if (m & ShiftMask) actionPerformed(actionKill, key.state); else actionPerformed(actionClose, key.state); } break; } } return YListBox::handleKey(key); } void WindowListBox::handleClick(const XButtonEvent &up, int count) { if (up.button == 3 && count == 1 && IS_BUTTON(up.state, Button3Mask)) { int no = findItemByPoint(up.x, up.y); if (no != -1) { YListItem *i = getItem(no); if (!isSelected(i)) { focusSelectItem(no); } else { //fFocusedItem = -1; } enableCommands(windowListPopup); windowListPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } else { windowListAllPopup->popup(0, 0, 0, up.x_root, up.y_root, YPopupWindow::pfCanFlipVertical | YPopupWindow::pfCanFlipHorizontal | YPopupWindow::pfPopupMenu); } return ; } YListBox::handleClick(up, count); } void WindowListBox::enableCommands(YMenu *popup) { bool noItems = true; long workspace = -1; bool sameWorkspace = false; bool notHidden = false; bool notMinimized = false; // enable minimize,hide if appropriate // enable workspace selections if appropriate popup->enableCommand(actionNull); for (YListItem *i = getFirst(); i; i = i->getNext()) { if (isSelected(i)) { WindowListItem *item = (WindowListItem *)i; if (!item->getFrame()) { continue; } noItems = false; if (!item->getFrame()->isHidden()) notHidden = true; if (!item->getFrame()->isMinimized()) notMinimized = true; long ws = item->getFrame()->getWorkspace(); if (workspace == -1) { workspace = ws; sameWorkspace = true; } else if (workspace != ws) { sameWorkspace = false; } if (item->getFrame()->isAllWorkspaces()) sameWorkspace = false; } } if (!notHidden) popup->disableCommand(actionHide); if (!notMinimized) popup->disableCommand(actionMinimize); moveMenu->enableCommand(actionNull); if (sameWorkspace && workspace != -1) { for (int i = 0; i < moveMenu->itemCount(); i++) { YMenuItem *item = moveMenu->getItem(i); for (int w = 0; w < workspaceCount; w++) if (item && item->getAction() == workspaceActionMoveTo[w]) item->setEnabled(w != workspace); } } if (noItems) { moveMenu->disableCommand(actionNull); popup->disableCommand(actionNull); } } WindowList::WindowList(YWindow *aParent, YActionListener *wmActionListener): YFrameClient(aParent, 0) { this->wmActionListener = wmActionListener; scroll = new YScrollView(this); list = new WindowListBox(scroll, scroll); scroll->setView(list); list->show(); scroll->show(); fWorkspaceCount = workspaceCount; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; for (int ws = 0; ws < fWorkspaceCount; ws++) { workspaceItem[ws] = new WindowListItem(0, ws); list->addItem(workspaceItem[ws]); } workspaceItem[fWorkspaceCount] = new WindowListItem(0, -1); list->addItem(workspaceItem[fWorkspaceCount]); YMenu *closeSubmenu = new YMenu(); assert(closeSubmenu != 0); closeSubmenu->addItem(_("_Close"), -2, _("Del"), actionClose); closeSubmenu->addSeparator(); closeSubmenu->addItem(_("_Kill Client"), -2, null, actionKill); #if 0 closeSubmenu->addItem(_("_Terminate Process"), -2, 0, actionTermProcess)->setEnabled(false); closeSubmenu->addItem(_("Kill _Process"), -2, 0, actionKillProcess)->setEnabled(false); #endif windowListPopup = new YMenu(); windowListPopup->setActionListener(list); windowListPopup->addItem(_("_Show"), -2, null, actionShow); windowListPopup->addItem(_("_Hide"), -2, null, actionHide); windowListPopup->addItem(_("_Minimize"), -2, null, actionMinimize); windowListPopup->addSubmenu(_("Move _To"), -2, moveMenu); windowListPopup->addSeparator(); windowListPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); windowListPopup->addSeparator(); windowListPopup->addItem(_("_Close"), -2, actionClose, closeSubmenu); windowListAllPopup = new YMenu(); windowListAllPopup->setActionListener(wmActionListener); windowListAllPopup->addItem(_("Tile _Vertically"), -2, KEY_NAME(gKeySysTileVertical), actionTileVertical); windowListAllPopup->addItem(_("T_ile Horizontally"), -2, KEY_NAME(gKeySysTileHorizontal), actionTileHorizontal); windowListAllPopup->addItem(_("Ca_scade"), -2, KEY_NAME(gKeySysCascade), actionCascade); windowListAllPopup->addItem(_("_Arrange"), -2, KEY_NAME(gKeySysArrange), actionArrange); windowListAllPopup->addItem(_("_Minimize All"), -2, KEY_NAME(gKeySysMinimizeAll), actionMinimizeAll); windowListAllPopup->addItem(_("_Hide All"), -2, KEY_NAME(gKeySysHideAll), actionHideAll); windowListAllPopup->addItem(_("_Undo"), -2, KEY_NAME(gKeySysUndoArrange), actionUndoArrange); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, 0); unsigned w = dw; unsigned h = dh; setGeometry(YRect(w / 4, h / 4, w / 2, h / 2)); windowList = this; setTitle("WindowList"); setWindowTitle(_("Window list")); setIconTitle(_("Window list")); setClassHint("windowList", "IceWM"); setWinHintsHint(WinHintsSkipTaskBar); setWinWorkspaceHint(-1); setWinLayerHint(WinLayerAboveDock); } WindowList::~WindowList() { delete list; list = 0; delete scroll; scroll = 0; windowList = 0; delete windowListAllPopup; windowListAllPopup = 0; for (int ws = 0; ws <= fWorkspaceCount; ws++) { delete workspaceItem[ws]; } delete[] workspaceItem; } void WindowList::updateWorkspaces() { long fOldWorkspaceCount = fWorkspaceCount; fWorkspaceCount = workspaceCount; if (fWorkspaceCount != fOldWorkspaceCount) { WindowListItem **oldWorkspaceItem = workspaceItem; workspaceItem = new WindowListItem *[fWorkspaceCount + 1]; workspaceItem[fWorkspaceCount] = oldWorkspaceItem[fOldWorkspaceCount]; list->removeItem(workspaceItem[fWorkspaceCount]); if (fWorkspaceCount > fOldWorkspaceCount) { for (long w = 0; w < fOldWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fOldWorkspaceCount; w < fWorkspaceCount; w++) { workspaceItem[w] = new WindowListItem(0, w); list->addItem(workspaceItem[w]); } } else if (fWorkspaceCount < fOldWorkspaceCount) { for (long w = 0; w < fWorkspaceCount; w++) workspaceItem[w] = oldWorkspaceItem[w]; for (long w = fWorkspaceCount; w < fOldWorkspaceCount; w++) { list->removeItem(oldWorkspaceItem[w]); delete oldWorkspaceItem[w]; } } list->addItem(workspaceItem[fWorkspaceCount]); delete[] oldWorkspaceItem; } } void WindowList::handleFocus(const XFocusChangeEvent &focus) { if (focus.type == FocusIn && focus.mode != NotifyUngrab) { list->setWindowFocus(); } else if (focus.type == FocusOut) { } } void WindowList::relayout() { list->repaint(); } WindowListItem *WindowList::addWindowListApp(YFrameWindow *frame) { if (!frame->client()->adopted()) return 0; WindowListItem *item = new WindowListItem(frame); if (item) { insertApp(item); } return item; } void WindowList::insertApp(WindowListItem *item) { ClientData *frame = item->getFrame(); if (frame->owner() && frame->owner()->winListItem()) { list->addAfter(frame->owner()->winListItem(), item); } else { int nw = frame->getWorkspace(); if (!frame->isAllWorkspaces()) list->addAfter(workspaceItem[nw], item); else list->addItem(item); } } void WindowList::removeWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); delete item; } } void WindowList::updateWindowListApp(WindowListItem *item) { if (item) { list->removeItem(item); insertApp(item); } } void WindowList::configure(const YRect &r) { YFrameClient::configure(r); scroll->setGeometry(YRect(0, 0, r.width(), r.height())); } void WindowList::handleClose() { if (!getFrame()->isHidden()) getFrame()->wmHide(); } void WindowList::showFocused(int x, int y) { YFrameWindow *f = manager->getFocus(); if (f != getFrame()) { if (f) list->focusSelectItem(list->findItem(f->winListItem())); else list->focusSelectItem(0); } if (getFrame() == 0) manager->manageClient(handle(), false); if (getFrame() != 0) { if (x != -1 && y != -1) { int px, py; int xiscreen = manager->getScreenForRect(x, y, 1, 1); int dx, dy; unsigned dw, dh; manager->getScreenGeometry(&dx, &dy, &dw, &dh, xiscreen); px = x - getFrame()->width() / 2; py = y - getFrame()->height() / 2; if (px + getFrame()->width() > dx + dw) px = dx + dw - getFrame()->width(); if (py + getFrame()->height() > dy + dh) py = dx + dh - getFrame()->height(); if (px < dx) px = dx; if (py < dy) py = dy; getFrame()->setNormalPositionOuter(px, py); } getFrame()->setRequestedLayer(WinLayerAboveDock); getFrame()->setAllWorkspaces(); getFrame()->activateWindow(true); } } // vim: set sw=4 ts=4 et: <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2017 PM-Tech // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include <cmath> static const int64_t nDiffChangeTarget = 56000; // Patch effective @ block 56000 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { int nHeight = pindexLast->nHeight + 1; bool fNewDifficultyProtocol = (nHeight >= nDiffChangeTarget); if (fNewDifficultyProtocol) { return DigiShield(pindexLast, pblock, params); } else { static const int64_t BlocksTargetSpacing = 60; // 1 minute unsigned int TimeDaySeconds = 60 * 60 * 24; int64_t PastSecondsMin = TimeDaySeconds * 0.25; int64_t PastSecondsMax = TimeDaySeconds * 7; uint64_t PastBlocksMin = PastSecondsMin / BlocksTargetSpacing; uint64_t PastBlocksMax = PastSecondsMax / BlocksTargetSpacing; return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax, params); } } unsigned int DigiShield(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { // Only change once per interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { return pindexLast->nBits; } // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = params.DifficultyAdjustmentInterval()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval()) blockstogoback = params.DifficultyAdjustmentInterval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; arith_uint256 bnNew; bnNew.SetCompact(pindexLast->nBits); //DigiShield implementation - thanks to RealSolid & WDC for this code //amplitude filter - thanks to daft27 for this code nActualTimespan = params.nPowTargetTimespan + (nActualTimespan - params.nPowTargetTimespan)/8; if (nActualTimespan < (params.nPowTargetTimespan - (params.nPowTargetTimespan/4)) ) nActualTimespan = (params.nPowTargetTimespan - (params.nPowTargetTimespan/4)); if (nActualTimespan > (params.nPowTargetTimespan + (params.nPowTargetTimespan/2)) ) nActualTimespan = (params.nPowTargetTimespan + (params.nPowTargetTimespan/2)); // Retarget bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if (bnNew > bnPowLimit) bnNew = bnPowLimit; /// debug print LogPrintf("GetNextWorkRequired: DIGISHIELD RETARGET\n"); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } unsigned int KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params) { /* current difficulty formula - kimoto gravity well */ const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; uint64_t PastBlocksMass = 0; int64_t PastRateActualSeconds = 0; int64_t PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; double EventHorizonDeviation; double EventHorizonDeviationFast; double EventHorizonDeviationSlow; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnPowLimit.GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } PastBlocksMass++; if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else //Einsteinium: workaround were to overcome the overflow issue when changing from CBigNum to arith_uint256 if (arith_uint256().SetCompact(BlockReading->nBits) >= PastDifficultyAveragePrev) PastDifficultyAverage = ((arith_uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; else PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - arith_uint256().SetCompact(BlockReading->nBits)) / i); PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass; PastRateAdjustmentRatio = double(1); if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); } EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(144)), -1.228)); EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if (PastBlocksMass >= PastBlocksMin) { if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } arith_uint256 bnNew(PastDifficultyAverage); if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { LogPrintf("Difficulty Retarget - Kimoto Gravity Well\n"); bnNew *= PastRateActualSeconds; bnNew /= PastRateTargetSeconds; } if (bnNew > bnPowLimit) bnNew = bnPowLimit; /* debug print (commented out due to spamming logs when the loop above breaks) printf("Difficulty Retarget - Kimoto Gravity Well\n"); printf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio); printf("Before: %08x %s\n", BlockLastSolved->nBits, arith_uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str()); */ return bnNew.GetCompact(); } <commit_msg>Extension for testnet and regtest case<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2017 PM-Tech // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" #include "util.h" #include <cmath> static const int64_t nDiffChangeTarget = 56000; // Patch effective @ block 56000 unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { int nHeight = pindexLast->nHeight + 1; bool fNewDifficultyProtocol = (nHeight >= nDiffChangeTarget); if (fNewDifficultyProtocol || params.fPowAllowMinDifficultyBlocks) { return DigiShield(pindexLast, pblock, params); } else { static const int64_t BlocksTargetSpacing = 60; // 1 minute unsigned int TimeDaySeconds = 60 * 60 * 24; int64_t PastSecondsMin = TimeDaySeconds * 0.25; int64_t PastSecondsMax = TimeDaySeconds * 7; uint64_t PastBlocksMin = PastSecondsMin / BlocksTargetSpacing; uint64_t PastBlocksMax = PastSecondsMax / BlocksTargetSpacing; return KimotoGravityWell(pindexLast, pblock, BlocksTargetSpacing, PastBlocksMin, PastBlocksMax, params); } } unsigned int DigiShield(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Genesis block if (pindexLast == NULL) return nProofOfWorkLimit; // Only change once per interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } return pindexLast->nBits; } } // Litecoin: This fixes an issue where a 51% attack can change difficulty at will. // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz int blockstogoback = params.DifficultyAdjustmentInterval()-1; if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval()) blockstogoback = params.DifficultyAdjustmentInterval(); // Go back by what we want to be 14 days worth of blocks const CBlockIndex* pindexFirst = pindexLast; for (int i = 0; pindexFirst && i < blockstogoback; i++) pindexFirst = pindexFirst->pprev; assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; arith_uint256 bnNew; bnNew.SetCompact(pindexLast->nBits); //DigiShield implementation - thanks to RealSolid & WDC for this code //amplitude filter - thanks to daft27 for this code nActualTimespan = params.nPowTargetTimespan + (nActualTimespan - params.nPowTargetTimespan)/8; if (nActualTimespan < (params.nPowTargetTimespan - (params.nPowTargetTimespan/4)) ) nActualTimespan = (params.nPowTargetTimespan - (params.nPowTargetTimespan/4)); if (nActualTimespan > (params.nPowTargetTimespan + (params.nPowTargetTimespan/2)) ) nActualTimespan = (params.nPowTargetTimespan + (params.nPowTargetTimespan/2)); // Retarget bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if (bnNew > bnPowLimit) bnNew = bnPowLimit; /// debug print LogPrintf("GetNextWorkRequired: DIGISHIELD RETARGET\n"); return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; } unsigned int KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64_t TargetBlocksSpacingSeconds, uint64_t PastBlocksMin, uint64_t PastBlocksMax, const Consensus::Params& params) { /* current difficulty formula - kimoto gravity well */ const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; uint64_t PastBlocksMass = 0; int64_t PastRateActualSeconds = 0; int64_t PastRateTargetSeconds = 0; double PastRateAdjustmentRatio = double(1); arith_uint256 PastDifficultyAverage; arith_uint256 PastDifficultyAveragePrev; double EventHorizonDeviation; double EventHorizonDeviationFast; double EventHorizonDeviationSlow; const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64_t)BlockLastSolved->nHeight < PastBlocksMin) { return bnPowLimit.GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } PastBlocksMass++; if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else //Einsteinium: workaround were to overcome the overflow issue when changing from CBigNum to arith_uint256 if (arith_uint256().SetCompact(BlockReading->nBits) >= PastDifficultyAveragePrev) PastDifficultyAverage = ((arith_uint256().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; else PastDifficultyAverage = PastDifficultyAveragePrev - ((PastDifficultyAveragePrev - arith_uint256().SetCompact(BlockReading->nBits)) / i); PastDifficultyAveragePrev = PastDifficultyAverage; PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime(); PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass; PastRateAdjustmentRatio = double(1); if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; } if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds); } EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(144)), -1.228)); EventHorizonDeviationFast = EventHorizonDeviation; EventHorizonDeviationSlow = 1 / EventHorizonDeviation; if (PastBlocksMass >= PastBlocksMin) { if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } arith_uint256 bnNew(PastDifficultyAverage); if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) { LogPrintf("Difficulty Retarget - Kimoto Gravity Well\n"); bnNew *= PastRateActualSeconds; bnNew /= PastRateTargetSeconds; } if (bnNew > bnPowLimit) bnNew = bnPowLimit; /* debug print (commented out due to spamming logs when the loop above breaks) printf("Difficulty Retarget - Kimoto Gravity Well\n"); printf("PastRateAdjustmentRatio = %g\n", PastRateAdjustmentRatio); printf("Before: %08x %s\n", BlockLastSolved->nBits, arith_uint256().SetCompact(BlockLastSolved->nBits).ToString().c_str()); printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str()); */ return bnNew.GetCompact(); } <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nl_bond.h" #include <cassert> #include <glog/logging.h> #include <linux/if_bridge.h> #include <netlink/route/link.h> #include <netlink/route/link/bonding.h> #include "cnetlink.h" #include "nl_output.h" #include "sai.h" namespace basebox { nl_bond::nl_bond(cnetlink *nl) : swi(nullptr), nl(nl) {} void nl_bond::clear() noexcept { lag_members.clear(); ifi2lag.clear(); } uint32_t nl_bond::get_lag_id(rtnl_link *bond) { assert(bond); return get_lag_id(rtnl_link_get_ifindex(bond)); } uint32_t nl_bond::get_lag_id(int ifindex) { auto it = ifi2lag.find(ifindex); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": lag_id not found for if=" << ifindex; return 0; } return it->second; } std::set<uint32_t> nl_bond::get_members(rtnl_link *bond) { auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } return mem_it->second; } std::set<uint32_t> nl_bond::get_members_by_port_id(uint32_t port_id) { auto mem_it = lag_members.find(port_id); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for port_id=" << port_id; return {}; } return mem_it->second; } int nl_bond::update_lag(rtnl_link *old_link, rtnl_link *new_link) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE VLOG(1) << __FUNCTION__ << ": updating bond interface "; int rv = 0; uint8_t o_mode, n_mode; uint32_t lag_id = nl->get_port_id(new_link); if (lag_id == 0) { rv = add_lag(new_link); if (rv < 0) return rv; lag_id = rv; } rv = rtnl_link_bond_get_mode(old_link, &o_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } rv = rtnl_link_bond_get_mode(new_link, &n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } if (o_mode != n_mode) { VLOG(1) << __FUNCTION__ << ": bond mode updated " << static_cast<uint32_t>(n_mode); rv = swi->lag_set_mode(lag_id, n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to set active state for " << OBJ_CAST(new_link); } return 0; } nl->add_l3_configuration(new_link); #endif return 0; } int nl_bond::add_lag(rtnl_link *bond) { uint32_t lag_id = 0; int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint8_t mode; rtnl_link_bond_get_mode(bond, &mode); assert(bond); rv = swi->lag_create(&lag_id, rtnl_link_get_name(bond), mode); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to create lag for " << OBJ_CAST(bond); return rv; } rv = lag_id; auto rv_emp = ifi2lag.emplace(std::make_pair(rtnl_link_get_ifindex(bond), lag_id)); if (!rv_emp.second) { VLOG(1) << __FUNCTION__ << ": lag exists with lag_id=" << rv_emp.first->second << " for bond " << OBJ_CAST(bond); rv = rv_emp.first->second; if (lag_id != rv_emp.first->second) swi->lag_remove(lag_id); } #endif return rv; } int nl_bond::remove_lag(rtnl_link *bond) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE int rv = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return -ENODEV; } rv = swi->lag_remove(it->second); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to remove lag with lag_id=" << it->second << " for bond " << OBJ_CAST(bond); return rv; } ifi2lag.erase(it); #endif return 0; } int nl_bond::add_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint32_t lag_id; uint8_t state = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": no lag_id found creating new for " << OBJ_CAST(bond); rv = add_lag(bond); if (rv < 0) return rv; lag_id = rv; } else { lag_id = it->second; } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignoring port " << OBJ_CAST(link); return -EINVAL; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { // No ports in lag std::set<uint32_t> members; members.insert(port_id); auto lm_rv = lag_members.emplace(lag_id, members); } else { mem_it->second.insert(port_id); } rv = rtnl_link_bond_slave_get_state(link, &state); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get slave state for " << OBJ_CAST(link); } rv = swi->lag_add_member(lag_id, port_id); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed add member " << port_id; return -EINVAL; } rv = swi->lag_set_member_active(lag_id, port_id, state == 0); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed set active member " << port_id; return -EINVAL; } if (rtnl_link_get_master(bond)) { // check bridge attachement auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); if (br_link) { VLOG(2) << __FUNCTION__ << ": bond was already bridge slave: " << OBJ_CAST(br_link); nl->link_created(br_link); if (nl->get_bridge_stp_state() == 0) return rv; auto new_state = rtnl_link_bridge_get_port_state(br_link); std::string state; switch (new_state) { case BR_STATE_FORWARDING: state = "forward"; break; case BR_STATE_BLOCKING: state = "block"; break; case BR_STATE_DISABLED: state = "disable"; break; case BR_STATE_LISTENING: state = "listen"; break; case BR_STATE_LEARNING: state = "learn"; break; default: VLOG(1) << __FUNCTION__ << ": stp state change not supported"; return rv; } swi->ofdpa_stg_state_port_set(port_id, 1, state); } rv = nl->set_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } else { std::deque<uint16_t> vlans; nl->get_vlans(rtnl_link_get_ifindex(bond), &vlans); for (auto vid : vlans) { swi->ingress_port_vlan_add(port_id, vid, false); swi->egress_port_vlan_add(port_id, vid, false); } } // XXX FIXME check for vlan interfaces // Adding an IP address here will ensure that every slave that is // added will retry to add the address. It will not be written to the // ASIC, but repeated messages will be seen // This should be done in ::add_lag, but for currently unknown reasons // this fails when the lag has no members yet. So keep it here for now. nl->add_l3_configuration(bond); #endif return rv; } int nl_bond::remove_lag_member(rtnl_link *link) { assert(link); int master_id = rtnl_link_get_master(link); auto master = nl->get_link(master_id, AF_UNSPEC); return remove_lag_member(master, link); } int nl_bond::remove_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(FATAL) << __FUNCTION__ << ": no lag_id found for " << OBJ_CAST(bond); } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignore invalid lag port " << OBJ_CAST(link); return -EINVAL; } auto lm_rv = lag_members.find(it->second); if (lm_rv == lag_members.end()) { VLOG(1) << __FUNCTION__ << ": ignore invalid attached port " << OBJ_CAST(link); return -EINVAL; } rv = swi->lag_remove_member(it->second, port_id); lag_members.erase(lm_rv); if (nl->is_bridge_interface(bond)) { swi->ofdpa_stg_state_port_set(port_id, 1, "forward"); auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); rv = nl->unset_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } else { std::deque<uint16_t> vlans; nl->get_vlans(rtnl_link_get_ifindex(bond), &vlans); if (lm_rv->second.empty()) nl->remove_l3_configuration(bond); if (nl->is_bridge_interface(bond)) swi->ofdpa_stg_state_port_set(port_id, 1, "forward"); for (auto vid : vlans) { swi->ingress_port_vlan_remove(port_id, vid, false); swi->egress_port_vlan_remove(port_id, vid); } } #endif return rv; } int nl_bond::update_lag_member(rtnl_link *old_slave, rtnl_link *new_slave) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(new_slave); int rv; uint8_t new_state; uint8_t old_state; int n_master_id = rtnl_link_get_master(new_slave); int o_master_id = rtnl_link_get_master(old_slave); auto new_master = nl->get_link(n_master_id, AF_UNSPEC); auto old_master = nl->get_link(o_master_id, AF_UNSPEC); auto port_id = nl->get_port_id(new_slave); if (old_master != new_master || new_master == 0) { return -EINVAL; } rv = rtnl_link_bond_slave_get_state(new_slave, &new_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rtnl_link_bond_slave_get_state(old_slave, &old_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rv = swi->lag_set_member_active(nl->get_port_id(new_master), port_id, new_state == 0); #endif return 0; } } // namespace basebox <commit_msg>nl_bond: don't create bond intefaces on link updates<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nl_bond.h" #include <cassert> #include <glog/logging.h> #include <linux/if_bridge.h> #include <netlink/route/link.h> #include <netlink/route/link/bonding.h> #include "cnetlink.h" #include "nl_output.h" #include "sai.h" namespace basebox { nl_bond::nl_bond(cnetlink *nl) : swi(nullptr), nl(nl) {} void nl_bond::clear() noexcept { lag_members.clear(); ifi2lag.clear(); } uint32_t nl_bond::get_lag_id(rtnl_link *bond) { assert(bond); return get_lag_id(rtnl_link_get_ifindex(bond)); } uint32_t nl_bond::get_lag_id(int ifindex) { auto it = ifi2lag.find(ifindex); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": lag_id not found for if=" << ifindex; return 0; } return it->second; } std::set<uint32_t> nl_bond::get_members(rtnl_link *bond) { auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return {}; } return mem_it->second; } std::set<uint32_t> nl_bond::get_members_by_port_id(uint32_t port_id) { auto mem_it = lag_members.find(port_id); if (mem_it == lag_members.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for port_id=" << port_id; return {}; } return mem_it->second; } int nl_bond::update_lag(rtnl_link *old_link, rtnl_link *new_link) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE VLOG(1) << __FUNCTION__ << ": updating bond interface "; int rv = 0; uint8_t o_mode, n_mode; uint32_t lag_id = nl->get_port_id(new_link); if (lag_id == 0) { VLOG(2) << __FUNCTION__ ": ignoring update for foreign bond interface " << OBJ_CAST(new_link); return 0; } rv = rtnl_link_bond_get_mode(old_link, &o_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } rv = rtnl_link_bond_get_mode(new_link, &n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get mode for " << OBJ_CAST(new_link); } if (o_mode != n_mode) { VLOG(1) << __FUNCTION__ << ": bond mode updated " << static_cast<uint32_t>(n_mode); rv = swi->lag_set_mode(lag_id, n_mode); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to set active state for " << OBJ_CAST(new_link); } return 0; } nl->add_l3_configuration(new_link); #endif return 0; } int nl_bond::add_lag(rtnl_link *bond) { uint32_t lag_id = 0; int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint8_t mode; rtnl_link_bond_get_mode(bond, &mode); assert(bond); rv = swi->lag_create(&lag_id, rtnl_link_get_name(bond), mode); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to create lag for " << OBJ_CAST(bond); return rv; } rv = lag_id; auto rv_emp = ifi2lag.emplace(std::make_pair(rtnl_link_get_ifindex(bond), lag_id)); if (!rv_emp.second) { VLOG(1) << __FUNCTION__ << ": lag exists with lag_id=" << rv_emp.first->second << " for bond " << OBJ_CAST(bond); rv = rv_emp.first->second; if (lag_id != rv_emp.first->second) swi->lag_remove(lag_id); } #endif return rv; } int nl_bond::remove_lag(rtnl_link *bond) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE int rv = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(WARNING) << __FUNCTION__ << ": lag does not exist for " << OBJ_CAST(bond); return -ENODEV; } rv = swi->lag_remove(it->second); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed to remove lag with lag_id=" << it->second << " for bond " << OBJ_CAST(bond); return rv; } ifi2lag.erase(it); #endif return 0; } int nl_bond::add_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE uint32_t lag_id; uint8_t state = 0; auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { VLOG(1) << __FUNCTION__ << ": no lag_id found creating new for " << OBJ_CAST(bond); rv = add_lag(bond); if (rv < 0) return rv; lag_id = rv; } else { lag_id = it->second; } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignoring port " << OBJ_CAST(link); return -EINVAL; } auto mem_it = lag_members.find(it->second); if (mem_it == lag_members.end()) { // No ports in lag std::set<uint32_t> members; members.insert(port_id); auto lm_rv = lag_members.emplace(lag_id, members); } else { mem_it->second.insert(port_id); } rv = rtnl_link_bond_slave_get_state(link, &state); if (rv < 0) { VLOG(1) << __FUNCTION__ << ": failed to get slave state for " << OBJ_CAST(link); } rv = swi->lag_add_member(lag_id, port_id); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed add member " << port_id; return -EINVAL; } rv = swi->lag_set_member_active(lag_id, port_id, state == 0); if (rv < 0) { LOG(ERROR) << __FUNCTION__ << ": failed set active member " << port_id; return -EINVAL; } if (rtnl_link_get_master(bond)) { // check bridge attachement auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); if (br_link) { VLOG(2) << __FUNCTION__ << ": bond was already bridge slave: " << OBJ_CAST(br_link); nl->link_created(br_link); if (nl->get_bridge_stp_state() == 0) return rv; auto new_state = rtnl_link_bridge_get_port_state(br_link); std::string state; switch (new_state) { case BR_STATE_FORWARDING: state = "forward"; break; case BR_STATE_BLOCKING: state = "block"; break; case BR_STATE_DISABLED: state = "disable"; break; case BR_STATE_LISTENING: state = "listen"; break; case BR_STATE_LEARNING: state = "learn"; break; default: VLOG(1) << __FUNCTION__ << ": stp state change not supported"; return rv; } swi->ofdpa_stg_state_port_set(port_id, 1, state); } rv = nl->set_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } else { std::deque<uint16_t> vlans; nl->get_vlans(rtnl_link_get_ifindex(bond), &vlans); for (auto vid : vlans) { swi->ingress_port_vlan_add(port_id, vid, false); swi->egress_port_vlan_add(port_id, vid, false); } } // XXX FIXME check for vlan interfaces // Adding an IP address here will ensure that every slave that is // added will retry to add the address. It will not be written to the // ASIC, but repeated messages will be seen // This should be done in ::add_lag, but for currently unknown reasons // this fails when the lag has no members yet. So keep it here for now. nl->add_l3_configuration(bond); #endif return rv; } int nl_bond::remove_lag_member(rtnl_link *link) { assert(link); int master_id = rtnl_link_get_master(link); auto master = nl->get_link(master_id, AF_UNSPEC); return remove_lag_member(master, link); } int nl_bond::remove_lag_member(rtnl_link *bond, rtnl_link *link) { int rv = 0; #ifdef HAVE_RTNL_LINK_BOND_GET_MODE auto it = ifi2lag.find(rtnl_link_get_ifindex(bond)); if (it == ifi2lag.end()) { LOG(FATAL) << __FUNCTION__ << ": no lag_id found for " << OBJ_CAST(bond); } uint32_t port_id = nl->get_port_id(link); if (port_id == 0) { VLOG(1) << __FUNCTION__ << ": ignore invalid lag port " << OBJ_CAST(link); return -EINVAL; } auto lm_rv = lag_members.find(it->second); if (lm_rv == lag_members.end()) { VLOG(1) << __FUNCTION__ << ": ignore invalid attached port " << OBJ_CAST(link); return -EINVAL; } rv = swi->lag_remove_member(it->second, port_id); lag_members.erase(lm_rv); if (nl->is_bridge_interface(bond)) { swi->ofdpa_stg_state_port_set(port_id, 1, "forward"); auto br_link = nl->get_link(rtnl_link_get_ifindex(bond), AF_BRIDGE); rv = nl->unset_bridge_port_vlan_tpid(br_link); if (rv < 0) LOG(ERROR) << __FUNCTION__ << ": failed to set egress TPID entry for port " << OBJ_CAST(link); } else { std::deque<uint16_t> vlans; nl->get_vlans(rtnl_link_get_ifindex(bond), &vlans); if (lm_rv->second.empty()) nl->remove_l3_configuration(bond); if (nl->is_bridge_interface(bond)) swi->ofdpa_stg_state_port_set(port_id, 1, "forward"); for (auto vid : vlans) { swi->ingress_port_vlan_remove(port_id, vid, false); swi->egress_port_vlan_remove(port_id, vid); } } #endif return rv; } int nl_bond::update_lag_member(rtnl_link *old_slave, rtnl_link *new_slave) { #ifdef HAVE_RTNL_LINK_BOND_GET_MODE assert(new_slave); int rv; uint8_t new_state; uint8_t old_state; int n_master_id = rtnl_link_get_master(new_slave); int o_master_id = rtnl_link_get_master(old_slave); auto new_master = nl->get_link(n_master_id, AF_UNSPEC); auto old_master = nl->get_link(o_master_id, AF_UNSPEC); auto port_id = nl->get_port_id(new_slave); if (old_master != new_master || new_master == 0) { return -EINVAL; } rv = rtnl_link_bond_slave_get_state(new_slave, &new_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rtnl_link_bond_slave_get_state(old_slave, &old_state); if (rv != 0) { VLOG(1) << __FUNCTION__ << ": failed to get state"; return -EINVAL; } rv = swi->lag_set_member_active(nl->get_port_id(new_master), port_id, new_state == 0); #endif return 0; } } // namespace basebox <|endoftext|>
<commit_before>#include <ting/debug.hpp> #include <algorithm> #include <ting/Buffer.hpp> #include "../src/cliser/ServerThread.hpp" #include "../src/cliser/ClientThread.hpp" namespace{ const ting::u32 DMaxCnt = 16384; const ting::u16 DPort = 13666; const char* DIpAddress = "127.0.0.1"; } class Connection : public cliser::Connection{ public: ting::StaticBuffer<ting::u8, sizeof(ting::u32)> rbuf; ting::Inited<unsigned, 0> rbufBytes; ting::Inited<ting::u32, 0> cnt; ting::Inited<ting::u32, 0> rcnt; ting::Inited<bool, false> isConnected; Connection(){ // TRACE(<< "Connection::" << __func__ << "(): invoked" << std::endl) } ~Connection(){ // TRACE(<< "Connection::" << __func__ << "(): invoked" << std::endl) } void SendPortion(){ ASSERT_INFO(this->cnt <= DMaxCnt, "this->cnt = " << this->cnt) if(this->cnt == DMaxCnt){ if(this->rcnt == DMaxCnt){ this->Disconnect_ts(); } return; } ting::Array<ting::u8> buf(sizeof(ting::u32) * ( (std::min)(ting::u32(0xfffff / 4), DMaxCnt - this->cnt)) ); ASSERT(buf.Size() > 0) for(ting::u8* p = buf.Begin(); p != buf.End(); p += sizeof(ting::u32)){ ting::Serialize32(this->cnt, p); ++this->cnt; } this->Send_ts(buf); } void HandleReceivedData(const ting::Buffer<ting::u8>& d){ for(const ting::u8* p = d.Begin(); p != d.End(); ++p){ this->rbuf[this->rbufBytes] = *p; ++this->rbufBytes; if(this->rbufBytes == this->rbuf.Size()){ this->rbufBytes = 0; ting::u32 num = ting::Deserialize32(this->rbuf.Begin()); ASSERT_INFO_ALWAYS(this->rcnt == num, "num = " << num << " rcnt = " << this->rcnt) ++this->rcnt; } } ASSERT_INFO(this->rcnt <= DMaxCnt, "this->rcnt = " << this->rcnt) if(this->rcnt == DMaxCnt){ if(this->cnt == DMaxCnt){ this->Disconnect_ts(); } } } static ting::Ref<Connection> New(){ return ting::Ref<Connection>(new Connection()); } }; class Server : private cliser::Listener, public cliser::ServerThread{ public: Server() : cliser::Listener(), cliser::ServerThread(DPort, 2, this) {} private: //override ting::Ref<cliser::Connection> CreateConnectionObject(){ return Connection::New(); } //override void OnConnected_ts(const ting::Ref<cliser::Connection>& c){ TRACE_ALWAYS(<< "Server: sending data" << std::endl) c.StaticCast<Connection>()->SendPortion(); } //override void OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){ //do nothing } class HandleDataMessage : public ting::Message{ ting::Ref<Connection> conn; public: HandleDataMessage(const ting::Ref<Connection>& conn) : conn(conn) {} //override void Handle(){ if(ting::Array<ting::u8> d = this->conn->GetReceivedData_ts()){ this->conn->HandleReceivedData(d); } } }; //override bool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){ TRACE_ALWAYS(<< "Client: data received" << std::endl) this->PushMessage( ting::Ptr<ting::Message>( new HandleDataMessage(c.StaticCast<Connection>()) ) ); return false; } //override void OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){ if(numPacketsInQueue >= 2) return; TRACE_ALWAYS(<< "Server: sending data" << std::endl) c.StaticCast<Connection>()->SendPortion(); } }; class Client : private cliser::Listener, public cliser::ClientThread{ public: Client() : cliser::Listener(), cliser::ClientThread(63, this) //max connections {} private: //override ting::Ref<cliser::Connection> CreateConnectionObject(){ return Connection::New(); } //override void OnConnected_ts(const ting::Ref<cliser::Connection>& c){ ting::Ref<Connection> conn = c.StaticCast<Connection>(); ASSERT_ALWAYS(!conn->isConnected) conn->isConnected = true; TRACE_ALWAYS(<< "Client: sending data" << std::endl) conn->SendPortion(); } //override void OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){ ting::Ref<Connection> conn = c.StaticCast<Connection>(); if(conn->isConnected){ conn->isConnected = false; }else{ //if we get here then it is a connect request failure ASSERT_ALWAYS(false) } this->Connect_ts(ting::IPAddress(DIpAddress, DPort)); } //override bool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){ ting::Ref<Connection> con = c.StaticCast<Connection>(); con->HandleReceivedData(d); TRACE_ALWAYS(<< "Server: data received" << std::endl) return true; } //override void OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){ if(numPacketsInQueue >= 2) return; TRACE_ALWAYS(<< "Client: sending data" << std::endl) c.StaticCast<Connection>()->SendPortion(); } }; int main(int argc, char *argv[]){ TRACE_ALWAYS(<< "Cliser test" << std::endl) ting::SocketLib socketsLib; Server server; server.Start(); ting::Thread::Sleep(100);//give server thread some time to start waiting on the socket Client client; client.Start(); for(unsigned i = 0; i < client.MaxConnections(); ++i){ client.Connect_ts(ting::IPAddress(DIpAddress, DPort)); } ting::Thread::Sleep(20000); client.PushQuitMessage(); client.Join(); server.PushQuitMessage(); server.Join(); return 0; } <commit_msg>infinite running of connect/disconnect test<commit_after>#include <ting/debug.hpp> #include <algorithm> #include <ting/Buffer.hpp> #include "../src/cliser/ServerThread.hpp" #include "../src/cliser/ClientThread.hpp" namespace{ const ting::u32 DMaxCnt = 16384; const ting::u16 DPort = 13666; const char* DIpAddress = "127.0.0.1"; } class Connection : public cliser::Connection{ public: ting::StaticBuffer<ting::u8, sizeof(ting::u32)> rbuf; ting::Inited<unsigned, 0> rbufBytes; ting::Inited<ting::u32, 0> cnt; ting::Inited<ting::u32, 0> rcnt; ting::Inited<bool, false> isConnected; Connection(){ // TRACE(<< "Connection::" << __func__ << "(): invoked" << std::endl) } ~Connection(){ // TRACE(<< "Connection::" << __func__ << "(): invoked" << std::endl) } void SendPortion(){ ASSERT_INFO(this->cnt <= DMaxCnt, "this->cnt = " << this->cnt) if(this->cnt == DMaxCnt){ if(this->rcnt == DMaxCnt){ this->Disconnect_ts(); } return; } ting::Array<ting::u8> buf(sizeof(ting::u32) * ( (std::min)(ting::u32(0xfffff / 4), DMaxCnt - this->cnt)) ); ASSERT(buf.Size() > 0) for(ting::u8* p = buf.Begin(); p != buf.End(); p += sizeof(ting::u32)){ ting::Serialize32(this->cnt, p); ++this->cnt; } this->Send_ts(buf); } void HandleReceivedData(const ting::Buffer<ting::u8>& d){ for(const ting::u8* p = d.Begin(); p != d.End(); ++p){ this->rbuf[this->rbufBytes] = *p; ++this->rbufBytes; if(this->rbufBytes == this->rbuf.Size()){ this->rbufBytes = 0; ting::u32 num = ting::Deserialize32(this->rbuf.Begin()); ASSERT_INFO_ALWAYS(this->rcnt == num, "num = " << num << " rcnt = " << this->rcnt) ++this->rcnt; } } ASSERT_INFO(this->rcnt <= DMaxCnt, "this->rcnt = " << this->rcnt) if(this->rcnt == DMaxCnt){ if(this->cnt == DMaxCnt){ this->Disconnect_ts(); } } } static ting::Ref<Connection> New(){ return ting::Ref<Connection>(new Connection()); } }; class Server : private cliser::Listener, public cliser::ServerThread{ public: Server() : cliser::Listener(), cliser::ServerThread(DPort, 2, this) {} private: //override ting::Ref<cliser::Connection> CreateConnectionObject(){ return Connection::New(); } //override void OnConnected_ts(const ting::Ref<cliser::Connection>& c){ TRACE_ALWAYS(<< "Server: sending data" << std::endl) c.StaticCast<Connection>()->SendPortion(); } //override void OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){ //do nothing } class HandleDataMessage : public ting::Message{ ting::Ref<Connection> conn; public: HandleDataMessage(const ting::Ref<Connection>& conn) : conn(conn) {} //override void Handle(){ if(ting::Array<ting::u8> d = this->conn->GetReceivedData_ts()){ this->conn->HandleReceivedData(d); } } }; //override bool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){ TRACE_ALWAYS(<< "Client: data received" << std::endl) this->PushMessage( ting::Ptr<ting::Message>( new HandleDataMessage(c.StaticCast<Connection>()) ) ); return false; } //override void OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){ if(numPacketsInQueue >= 2) return; TRACE_ALWAYS(<< "Server: sending data" << std::endl) c.StaticCast<Connection>()->SendPortion(); } }; class Client : private cliser::Listener, public cliser::ClientThread{ public: Client() : cliser::Listener(), cliser::ClientThread(63, this) //max connections {} private: //override ting::Ref<cliser::Connection> CreateConnectionObject(){ return Connection::New(); } //override void OnConnected_ts(const ting::Ref<cliser::Connection>& c){ ting::Ref<Connection> conn = c.StaticCast<Connection>(); ASSERT_ALWAYS(!conn->isConnected) conn->isConnected = true; TRACE_ALWAYS(<< "Client: sending data" << std::endl) conn->SendPortion(); } //override void OnDisconnected_ts(const ting::Ref<cliser::Connection>& c){ ting::Ref<Connection> conn = c.StaticCast<Connection>(); if(conn->isConnected){ conn->isConnected = false; }else{ //if we get here then it is a connect request failure ASSERT_ALWAYS(false) } this->Connect_ts(ting::IPAddress(DIpAddress, DPort)); } //override bool OnDataReceived_ts(const ting::Ref<cliser::Connection>& c, const ting::Buffer<ting::u8>& d){ ting::Ref<Connection> con = c.StaticCast<Connection>(); con->HandleReceivedData(d); TRACE_ALWAYS(<< "Server: data received" << std::endl) return true; } //override void OnDataSent_ts(const ting::Ref<cliser::Connection>& c, unsigned numPacketsInQueue, bool addedToQueue){ if(numPacketsInQueue >= 2) return; TRACE_ALWAYS(<< "Client: sending data" << std::endl) c.StaticCast<Connection>()->SendPortion(); } }; int main(int argc, char *argv[]){ TRACE_ALWAYS(<< "Cliser test" << std::endl) unsigned msec = 20000; if(argc >= 2){ if(std::string("0") == argv[1]){ msec = 0; } } ting::SocketLib socketsLib; Server server; server.Start(); ting::Thread::Sleep(100);//give server thread some time to start waiting on the socket Client client; client.Start(); for(unsigned i = 0; i < client.MaxConnections(); ++i){ client.Connect_ts(ting::IPAddress(DIpAddress, DPort)); } if(msec == 0){ while(true){ ting::Thread::Sleep(1000000); } }else{ ting::Thread::Sleep(20000); } client.PushQuitMessage(); client.Join(); server.PushQuitMessage(); server.Join(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/PlatformSpecificFunctions.h" class MemoryLeakFailureForTest : public MemoryLeakFailure { public: virtual ~MemoryLeakFailureForTest(){}; virtual void fail(char* fail_string) {*message = fail_string;} SimpleString *message; }; TEST_GROUP(MemoryLeakDetectorTest) { MemoryLeakDetector* detector; MemoryLeakFailureForTest *reporter; void setup() { detector = new MemoryLeakDetector; reporter = new MemoryLeakFailureForTest; detector->init(reporter); detector->enable(); detector->startChecking(); reporter->message = new SimpleString(); } void teardown() { delete reporter->message; delete detector; delete reporter; } }; TEST(MemoryLeakDetectorTest, OneLeak) { char* mem = detector->allocOperatorNew(4); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains(MEM_LEAK_HEADER)); CHECK(output.contains("size: 4")); CHECK(output.contains("new")); CHECK(output.contains(MEM_LEAK_FOOTER)); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, OneLeakOutsideCheckingPeriod) { detector->stopChecking(); char* mem = detector->allocOperatorNew(4); SimpleString output = detector->report(mem_leak_period_all); CHECK(output.contains(MEM_LEAK_HEADER)); CHECK(output.contains("size: 4")); CHECK(output.contains("new")); CHECK(output.contains(MEM_LEAK_FOOTER)); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, NoLeaksWhatsoever) { detector->stopChecking(); STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_checking)); STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_all)); } TEST(MemoryLeakDetectorTest, TwoLeaksUsingOperatorNew) { char* mem = detector->allocOperatorNew(4); char* mem2 = detector->allocOperatorNew(8); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(output.contains("size: 8")); CHECK(output.contains("size: 4")); PlatformSpecificFree(mem); PlatformSpecificFree(mem2); } TEST(MemoryLeakDetectorTest, OneAllocButNoLeak) { char* mem = detector->allocOperatorNew(4); detector->freeOperatorDelete(mem); detector->stopChecking(); STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_checking)); } TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeak) { char* mem = detector->allocOperatorNew(4); char* mem2 = detector->allocOperatorNew(12); detector->freeOperatorDelete(mem); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(output.contains("size: 12")); CHECK(!output.contains("size: 4")); PlatformSpecificFree (mem2); } TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeakReverseOrder) { char* mem = detector->allocOperatorNew(4); char* mem2 = detector->allocOperatorNew(12); detector->freeOperatorDelete(mem2); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(!output.contains("size: 12")); CHECK(output.contains("size: 4")); PlatformSpecificFree (mem); } TEST(MemoryLeakDetectorTest, DeleteNonAlocatedMemory) { char a; char* pa = &a; detector->freeFree(pa, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains(MEM_LEAK_DEALLOC_NON_ALLOCATED)); CHECK(reporter->message->contains(" allocated at file: <unknown> line: 0 size: 0 type: unknown")); CHECK(reporter->message->contains(" dealllocated at file: FREE.c line: 100 type: malloc")); } TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriod) { detector->stopChecking(); char* mem = detector->allocOperatorNew(4); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->freeOperatorDelete(mem); } TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriodComplicatedCase) { char* mem = detector->allocOperatorNew(4); detector->stopChecking(); char* mem2 = detector->allocOperatorNew(8); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->clearAllAccounting(mem_leak_period_checking); PlatformSpecificFree(mem); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->startChecking(); char* mem3 = detector->allocOperatorNew(4); detector->stopChecking(); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); detector->clearAllAccounting(mem_leak_period_checking); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->clearAllAccounting(mem_leak_period_all); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); PlatformSpecificFree(mem2); PlatformSpecificFree(mem3); } TEST(MemoryLeakDetectorTest, OneLeakUsingOperatorNewWithFileLine) { char* mem = detector->allocOperatorNew(4, "file.cpp", 1234); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("file.cpp")); CHECK(output.contains("1234")); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingArrayNew) { char* mem = detector->allocOperatorNewArray(10, "file.cpp", 1234); char* mem2 = detector->allocOperatorNewArray(12); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("new []")); detector->freeOperatorDeleteArray(mem); detector->freeOperatorDeleteArray(mem2); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingMalloc) { char* mem = detector->allocMalloc(10, "file.cpp", 1234); char* mem2 = detector->allocMalloc(12); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("malloc")); detector->freeFree(mem); detector->freeFree(mem2, "file.c", 5678); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, OneRealloc) { char* mem1 = detector->allocMalloc(10, "file.cpp", 1234); char* mem2 = detector->allocRealloc(mem1, 1000, "other.cpp", 5678); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("other.cpp")); detector->freeFree(mem2); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherType) { char* mem = detector->allocOperatorNewArray(100, "ALLOC.c", 10); detector->freeFree(mem, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains(MEM_LEAK_ALLOC_DEALLOC_MISMATCH)); CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 100 type: new []")); CHECK(reporter->message->contains(" dealllocated at file: FREE.c line: 100 type: malloc")); } TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherTypeWithCheckingDisabled) { detector->disableAllocationTypeChecking (); char* mem = detector->allocOperatorNewArray(100, "ALLOC.c", 10); detector->freeFree(mem, "FREE.c", 100); detector->stopChecking(); STRCMP_EQUAL("", reporter->message->asCharString()); detector->enableAllocationTypeChecking (); } TEST(MemoryLeakDetectorTest, MarkCheckingPeriodLeaksAsNonCheckingPeriod) { char* mem = detector->allocOperatorNewArray(100); char* mem2 = detector->allocOperatorNewArray(100); detector->stopChecking(); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); detector->markCheckingPeriodLeaksAsNonCheckingPeriod(); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); PlatformSpecificFree(mem); PlatformSpecificFree(mem2); } TEST(MemoryLeakDetectorTest, memoryCorruption) { char* mem = detector->allocMalloc(10, "ALLOC.c", 10); mem[10] = 'O'; mem[11] = 'H'; detector->freeFree(mem, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains(MEM_LEAK_MEMORY_CORRUPTION)); CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 10 type: malloc")); CHECK(reporter->message->contains(" dealllocated at file: FREE.c line: 100 type: malloc")); } TEST(MemoryLeakDetectorTest, safelyDeleteNULL) { detector->freeOperatorDelete(0); STRCMP_EQUAL("", reporter->message->asCharString()); } TEST(MemoryLeakDetectorTest, periodDisabled) { detector->disable(); char* mem = detector->allocMalloc(2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->freeFree(mem); } TEST(MemoryLeakDetectorTest, periodEnabled) { detector->enable(); char* mem = detector->allocMalloc(2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->freeFree(mem); } TEST(MemoryLeakDetectorTest, periodChecking) { char* mem = detector->allocMalloc(2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->freeFree(mem); } <commit_msg><commit_after>/* * Copyright (c) 2007, Michael Feathers, James Grenning and Bas Vodde * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> 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 EARLIER MENTIONED AUTHORS ``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 <copyright holder> 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 "CppUTest/TestHarness.h" #include "CppUTest/MemoryLeakDetector.h" #include "CppUTest/PlatformSpecificFunctions.h" class MemoryLeakFailureForTest : public MemoryLeakFailure { public: virtual ~MemoryLeakFailureForTest(){}; virtual void fail(char* fail_string) {*message = fail_string;} SimpleString *message; }; TEST_GROUP(MemoryLeakDetectorTest) { MemoryLeakDetector* detector; MemoryLeakFailureForTest *reporter; void setup() { detector = new MemoryLeakDetector; reporter = new MemoryLeakFailureForTest; detector->init(reporter); detector->enable(); detector->startChecking(); reporter->message = new SimpleString(); } void teardown() { delete reporter->message; delete detector; delete reporter; } }; TEST(MemoryLeakDetectorTest, OneLeak) { char* mem = detector->allocOperatorNew(1); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains(MEM_LEAK_HEADER)); CHECK(output.contains("size: 1")); CHECK(output.contains("new")); CHECK(output.contains(MEM_LEAK_FOOTER)); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, OneLeakOutsideCheckingPeriod) { detector->stopChecking(); char* mem = detector->allocOperatorNew(4); SimpleString output = detector->report(mem_leak_period_all); CHECK(output.contains(MEM_LEAK_HEADER)); CHECK(output.contains("size: 4")); CHECK(output.contains("new")); CHECK(output.contains(MEM_LEAK_FOOTER)); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, NoLeaksWhatsoever) { detector->stopChecking(); STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_checking)); STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_all)); } TEST(MemoryLeakDetectorTest, TwoLeaksUsingOperatorNew) { char* mem = detector->allocOperatorNew(4); char* mem2 = detector->allocOperatorNew(8); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(output.contains("size: 8")); CHECK(output.contains("size: 4")); PlatformSpecificFree(mem); PlatformSpecificFree(mem2); } TEST(MemoryLeakDetectorTest, OneAllocButNoLeak) { char* mem = detector->allocOperatorNew(4); detector->freeOperatorDelete(mem); detector->stopChecking(); STRCMP_EQUAL(MEM_LEAK_NONE, detector->report(mem_leak_period_checking)); } TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeak) { char* mem = detector->allocOperatorNew(4); char* mem2 = detector->allocOperatorNew(12); detector->freeOperatorDelete(mem); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(output.contains("size: 12")); CHECK(!output.contains("size: 4")); PlatformSpecificFree (mem2); } TEST(MemoryLeakDetectorTest, TwoAllocOneFreeOneLeakReverseOrder) { char* mem = detector->allocOperatorNew(4); char* mem2 = detector->allocOperatorNew(12); detector->freeOperatorDelete(mem2); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); CHECK(!output.contains("size: 12")); CHECK(output.contains("size: 4")); PlatformSpecificFree (mem); } TEST(MemoryLeakDetectorTest, DeleteNonAlocatedMemory) { char a; char* pa = &a; detector->freeFree(pa, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains(MEM_LEAK_DEALLOC_NON_ALLOCATED)); CHECK(reporter->message->contains(" allocated at file: <unknown> line: 0 size: 0 type: unknown")); CHECK(reporter->message->contains(" dealllocated at file: FREE.c line: 100 type: malloc")); } TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriod) { detector->stopChecking(); char* mem = detector->allocOperatorNew(4); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->freeOperatorDelete(mem); } TEST(MemoryLeakDetectorTest, IgnoreMemoryAllocatedOutsideCheckingPeriodComplicatedCase) { char* mem = detector->allocOperatorNew(4); detector->stopChecking(); char* mem2 = detector->allocOperatorNew(8); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->clearAllAccounting(mem_leak_period_checking); PlatformSpecificFree(mem); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->startChecking(); char* mem3 = detector->allocOperatorNew(4); detector->stopChecking(); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); detector->clearAllAccounting(mem_leak_period_checking); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); detector->clearAllAccounting(mem_leak_period_all); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); PlatformSpecificFree(mem2); PlatformSpecificFree(mem3); } TEST(MemoryLeakDetectorTest, OneLeakUsingOperatorNewWithFileLine) { char* mem = detector->allocOperatorNew(4, "file.cpp", 1234); detector->stopChecking(); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("file.cpp")); CHECK(output.contains("1234")); PlatformSpecificFree(mem); } TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingArrayNew) { char* mem = detector->allocOperatorNewArray(10, "file.cpp", 1234); char* mem2 = detector->allocOperatorNewArray(12); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("new []")); detector->freeOperatorDeleteArray(mem); detector->freeOperatorDeleteArray(mem2); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, OneAllocAndFreeUsingMalloc) { char* mem = detector->allocMalloc(10, "file.cpp", 1234); char* mem2 = detector->allocMalloc(12); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("malloc")); detector->freeFree(mem); detector->freeFree(mem2, "file.c", 5678); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, OneRealloc) { char* mem1 = detector->allocMalloc(10, "file.cpp", 1234); char* mem2 = detector->allocRealloc(mem1, 1000, "other.cpp", 5678); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); SimpleString output = detector->report(mem_leak_period_checking); CHECK(output.contains("other.cpp")); detector->freeFree(mem2); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_all)); detector->stopChecking(); } TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherType) { char* mem = detector->allocOperatorNewArray(100, "ALLOC.c", 10); detector->freeFree(mem, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains(MEM_LEAK_ALLOC_DEALLOC_MISMATCH)); CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 100 type: new []")); CHECK(reporter->message->contains(" dealllocated at file: FREE.c line: 100 type: malloc")); } TEST(MemoryLeakDetectorTest, AllocOneTypeFreeAnotherTypeWithCheckingDisabled) { detector->disableAllocationTypeChecking (); char* mem = detector->allocOperatorNewArray(100, "ALLOC.c", 10); detector->freeFree(mem, "FREE.c", 100); detector->stopChecking(); STRCMP_EQUAL("", reporter->message->asCharString()); detector->enableAllocationTypeChecking (); } TEST(MemoryLeakDetectorTest, MarkCheckingPeriodLeaksAsNonCheckingPeriod) { char* mem = detector->allocOperatorNewArray(100); char* mem2 = detector->allocOperatorNewArray(100); detector->stopChecking(); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); detector->markCheckingPeriodLeaksAsNonCheckingPeriod(); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); LONGS_EQUAL(2, detector->totalMemoryLeaks(mem_leak_period_all)); PlatformSpecificFree(mem); PlatformSpecificFree(mem2); } TEST(MemoryLeakDetectorTest, memoryCorruption) { char* mem = detector->allocMalloc(10, "ALLOC.c", 10); mem[10] = 'O'; mem[11] = 'H'; detector->freeFree(mem, "FREE.c", 100); detector->stopChecking(); CHECK(reporter->message->contains(MEM_LEAK_MEMORY_CORRUPTION)); CHECK(reporter->message->contains(" allocated at file: ALLOC.c line: 10 size: 10 type: malloc")); CHECK(reporter->message->contains(" dealllocated at file: FREE.c line: 100 type: malloc")); } TEST(MemoryLeakDetectorTest, safelyDeleteNULL) { detector->freeOperatorDelete(0); STRCMP_EQUAL("", reporter->message->asCharString()); } TEST(MemoryLeakDetectorTest, periodDisabled) { detector->disable(); char* mem = detector->allocMalloc(2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->freeFree(mem); } TEST(MemoryLeakDetectorTest, periodEnabled) { detector->enable(); char* mem = detector->allocMalloc(2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->freeFree(mem); } TEST(MemoryLeakDetectorTest, periodChecking) { char* mem = detector->allocMalloc(2); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_all)); LONGS_EQUAL(0, detector->totalMemoryLeaks(mem_leak_period_disabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_enabled)); LONGS_EQUAL(1, detector->totalMemoryLeaks(mem_leak_period_checking)); detector->freeFree(mem); } <|endoftext|>
<commit_before>/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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. * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "Session.hxx" #include "pool/UniquePtr.hxx" #include "event/net/BufferedSocket.hxx" #include "net/SocketAddress.hxx" #include "util/IntrusiveList.hxx" struct pool; class FilteredSocket; class HttpServerConnectionHandler; class HttpServerRequestHandler; namespace NgHttp2 { class ServerConnection final : BufferedSocketHandler { struct pool &pool; const UniquePoolPtr<FilteredSocket> socket; HttpServerConnectionHandler &handler; HttpServerRequestHandler &request_handler; const SocketAddress local_address, remote_address; const char *const local_host_and_port; const char *const remote_host; NgHttp2::Session session; class Request; using RequestList = IntrusiveList<Request>; RequestList requests; #ifndef NDEBUG /** * The total number of bytes passed to our * data_chunk_recv_callback() which needs to be reported to * nghttp2_session_consume(). */ size_t unconsumed = 0; #endif public: ServerConnection(struct pool &_pool, UniquePoolPtr<FilteredSocket> _socket, SocketAddress remote_address, HttpServerConnectionHandler &_handler, HttpServerRequestHandler &request_handler); ~ServerConnection() noexcept; void Consume(std::size_t nbytes) noexcept { nghttp2_session_consume_connection(session.get(), nbytes); DeferWrite(); } private: void DeferWrite() noexcept; ssize_t SendCallback(std::span<const std::byte> src) noexcept; static ssize_t SendCallback(nghttp2_session *, const uint8_t *data, size_t length, int, void *user_data) noexcept { auto &c = *(ServerConnection *)user_data; return c.SendCallback({(const std::byte *)data, length}); } int OnFrameRecvCallback(const nghttp2_frame *frame) noexcept; static int OnFrameRecvCallback(nghttp2_session *, const nghttp2_frame *frame, void *user_data) noexcept { auto &c = *(ServerConnection *)user_data; return c.OnFrameRecvCallback(frame); } int OnBeginHeaderCallback(const nghttp2_frame *frame) noexcept; static int OnBeginHeaderCallback(nghttp2_session *, const nghttp2_frame *frame, void *user_data) noexcept { auto &c = *(ServerConnection *)user_data; return c.OnBeginHeaderCallback(frame); } /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override; bool OnBufferedClosed() noexcept override; bool OnBufferedWrite() override; // TODO bool OnBufferedDrained() noexcept override; void OnBufferedError(std::exception_ptr e) noexcept override; }; } // namespace NgHttp2 <commit_msg>nghttp2/Server: remove obsolete debug-only field "unconsumed"<commit_after>/* * Copyright 2007-2022 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * 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. * * 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 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "Session.hxx" #include "pool/UniquePtr.hxx" #include "event/net/BufferedSocket.hxx" #include "net/SocketAddress.hxx" #include "util/IntrusiveList.hxx" struct pool; class FilteredSocket; class HttpServerConnectionHandler; class HttpServerRequestHandler; namespace NgHttp2 { class ServerConnection final : BufferedSocketHandler { struct pool &pool; const UniquePoolPtr<FilteredSocket> socket; HttpServerConnectionHandler &handler; HttpServerRequestHandler &request_handler; const SocketAddress local_address, remote_address; const char *const local_host_and_port; const char *const remote_host; NgHttp2::Session session; class Request; using RequestList = IntrusiveList<Request>; RequestList requests; public: ServerConnection(struct pool &_pool, UniquePoolPtr<FilteredSocket> _socket, SocketAddress remote_address, HttpServerConnectionHandler &_handler, HttpServerRequestHandler &request_handler); ~ServerConnection() noexcept; void Consume(std::size_t nbytes) noexcept { nghttp2_session_consume_connection(session.get(), nbytes); DeferWrite(); } private: void DeferWrite() noexcept; ssize_t SendCallback(std::span<const std::byte> src) noexcept; static ssize_t SendCallback(nghttp2_session *, const uint8_t *data, size_t length, int, void *user_data) noexcept { auto &c = *(ServerConnection *)user_data; return c.SendCallback({(const std::byte *)data, length}); } int OnFrameRecvCallback(const nghttp2_frame *frame) noexcept; static int OnFrameRecvCallback(nghttp2_session *, const nghttp2_frame *frame, void *user_data) noexcept { auto &c = *(ServerConnection *)user_data; return c.OnFrameRecvCallback(frame); } int OnBeginHeaderCallback(const nghttp2_frame *frame) noexcept; static int OnBeginHeaderCallback(nghttp2_session *, const nghttp2_frame *frame, void *user_data) noexcept { auto &c = *(ServerConnection *)user_data; return c.OnBeginHeaderCallback(frame); } /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override; bool OnBufferedClosed() noexcept override; bool OnBufferedWrite() override; // TODO bool OnBufferedDrained() noexcept override; void OnBufferedError(std::exception_ptr e) noexcept override; }; } // namespace NgHttp2 <|endoftext|>
<commit_before>/* * RandomNumber.cc * * Copyright (C) 2015 Linas Vepstas * * Author: Linas Vepstas <linasvepstas@gmail.com> January 2009 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/mt19937ar.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atoms/NumberNode.h> #include "RandomNumber.h" using namespace opencog; static MT19937RandGen randy(616432); void RandomNumberLink::init() { if (_outgoing.size() != 2) throw SyntaxException(TRACE_INFO, "Expecting a numerical min and max; got %s", toString().c_str()); } RandomNumberLink::RandomNumberLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FunctionLink(RANDOM_NUMBER_LINK, oset, tv, av) { init(); } RandomNumberLink::RandomNumberLink(Link &l) : FunctionLink(l) { // Type must be as expected Type tscope = l.getType(); if (not classserver().isA(tscope, RANDOM_NUMBER_LINK)) { const std::string& tname = classserver().getTypeName(tscope); throw InvalidParamException(TRACE_INFO, "Expecting an RandomNumberLink, got %s", tname.c_str()); } init(); } // --------------------------------------------------------------- // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. static NumberNodePtr unwrap_set(Handle h) { if (SET_LINK == h->getType()) { if (1 != h->getArity()) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); h = h->getOutgoingAtom(0); } NumberNodePtr na(NumberNodeCast(h)); if (nullptr == na) throw SyntaxException(TRACE_INFO, "Don't know how to do arithmetic with this: %s", h->toString().c_str()); return na; } Handle RandomNumberLink::execute(AtomSpace * as) const { NumberNodePtr nmin(unwrap_set(_outgoing[0])); NumberNodePtr nmax(unwrap_set(_outgoing[1])); double cept = nmin->get_value(); double slope = nmax->get_value() - cept; double ary = slope * randy.randdouble() + cept; // XXX This is probably wrong ... if the as is null, we should // probably use the atomspace that this link is in, right? // We need to make a decision here and in many other places... // We should probably be doing "lazy-add-to-atomsapce" ... if (NULL == as) return Handle(createNumberNode(ary)); return as->add_atom(createNumberNode(ary)); } /* ===================== END OF FILE ===================== */ <commit_msg>Clarify the error message<commit_after>/* * RandomNumber.cc * * Copyright (C) 2015 Linas Vepstas * * Author: Linas Vepstas <linasvepstas@gmail.com> January 2009 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the * exceptions at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/mt19937ar.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atoms/NumberNode.h> #include "RandomNumber.h" using namespace opencog; static MT19937RandGen randy(616432); void RandomNumberLink::init() { if (_outgoing.size() != 2) throw SyntaxException(TRACE_INFO, "Expecting a numerical min and max; got %s", toString().c_str()); } RandomNumberLink::RandomNumberLink(const HandleSeq& oset, TruthValuePtr tv, AttentionValuePtr av) : FunctionLink(RANDOM_NUMBER_LINK, oset, tv, av) { init(); } RandomNumberLink::RandomNumberLink(Link &l) : FunctionLink(l) { // Type must be as expected Type tscope = l.getType(); if (not classserver().isA(tscope, RANDOM_NUMBER_LINK)) { const std::string& tname = classserver().getTypeName(tscope); throw InvalidParamException(TRACE_INFO, "Expecting an RandomNumberLink, got %s", tname.c_str()); } init(); } // --------------------------------------------------------------- // Pattern matching hack. The pattern matcher returns sets of atoms; // if that set contains numbers or something numeric, then unwrap it. static NumberNodePtr unwrap_set(Handle h) { if (SET_LINK == h->getType()) { if (0 == h->getArity()) throw SyntaxException(TRACE_INFO, "Expecting a number, got the empty set!\n"); if (1 != h->getArity()) throw SyntaxException(TRACE_INFO, "Expecting only one number, got more than that: %s", h->toString().c_str()); h = h->getOutgoingAtom(0); } NumberNodePtr na(NumberNodeCast(h)); if (nullptr == na) throw SyntaxException(TRACE_INFO, "Expecting a number, got this: %s", h->toString().c_str()); return na; } Handle RandomNumberLink::execute(AtomSpace * as) const { NumberNodePtr nmin(unwrap_set(_outgoing[0])); NumberNodePtr nmax(unwrap_set(_outgoing[1])); double cept = nmin->get_value(); double slope = nmax->get_value() - cept; double ary = slope * randy.randdouble() + cept; // XXX This is probably wrong ... if the as is null, we should // probably use the atomspace that this link is in, right? // We need to make a decision here and in many other places... // We should probably be doing "lazy-add-to-atomsapce" ... if (NULL == as) return Handle(createNumberNode(ary)); return as->add_atom(createNumberNode(ary)); } /* ===================== END OF FILE ===================== */ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Raine Makelainen <raine.makelainen@jolla.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "testobject.h" #include <QQmlComponent> #include <QQmlContext> #include <QQmlEngine> #include <QQuickView> #include <QQuickItem> #include <QSignalSpy> #include <QTime> #include <QtTest> TestObject::TestObject() : QObject() { QTime time = QTime::currentTime(); qsrand((uint)time.msec()); } TestObject::TestObject(QByteArray qmlData) : QObject() { QTime time = QTime::currentTime(); qsrand((uint)time.msec()); setTestData(qmlData); mView.showFullScreen(); QTest::qWaitForWindowExposed(&mView); } void TestObject::init(const QUrl &url) { setTestUrl(url); mView.showFullScreen(); QTest::qWaitForWindowExposed(&mView); } /*! Wait signal of \a spy to be emitted \a expectedSignalCount. Note: this might cause indefinite loop, if not used cautiously. Check that \a spy is initialized before expected emits can happen. */ void TestObject::waitSignals(QSignalSpy &spy, int expectedSignalCount, int timeout) const { int i = 0; int maxWaits = 10; while (spy.count() < expectedSignalCount && i < maxWaits) { spy.wait(timeout); ++i; } } void TestObject::setTestData(QByteArray qmlData) { QQmlComponent component(mView.engine()); component.setData(qmlData, QUrl()); mRootObject = component.create(mView.engine()->rootContext()); mView.setContent(QUrl(""), 0, mRootObject); } void TestObject::setTestUrl(const QUrl &url) { mView.setSource(url); mRootObject = mView.rootObject(); } void TestObject::setContextProperty(const QString &name, QObject *value) { mView.rootContext()->setContextProperty(name, value); } int TestObject::random(int min, int max) { return qrand() % ((max + 1) - min) + min; } <commit_msg>Persist scene graph and opengl context similarly as with browser app<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Raine Makelainen <raine.makelainen@jolla.com> ** ****************************************************************************/ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "testobject.h" #include <QQmlComponent> #include <QQmlContext> #include <QQmlEngine> #include <QQuickView> #include <QQuickItem> #include <QSignalSpy> #include <QTime> #include <QtTest> TestObject::TestObject() : QObject() { QTime time = QTime::currentTime(); qsrand((uint)time.msec()); } TestObject::TestObject(QByteArray qmlData) : QObject() { QTime time = QTime::currentTime(); qsrand((uint)time.msec()); mView.setPersistentOpenGLContext(true); mView.setPersistentSceneGraph(true); setTestData(qmlData); mView.showFullScreen(); QTest::qWaitForWindowExposed(&mView); } void TestObject::init(const QUrl &url) { mView.setPersistentOpenGLContext(true); mView.setPersistentSceneGraph(true); setTestUrl(url); mView.showFullScreen(); QTest::qWaitForWindowExposed(&mView); } /*! Wait signal of \a spy to be emitted \a expectedSignalCount. Note: this might cause indefinite loop, if not used cautiously. Check that \a spy is initialized before expected emits can happen. */ void TestObject::waitSignals(QSignalSpy &spy, int expectedSignalCount, int timeout) const { int i = 0; int maxWaits = 10; while (spy.count() < expectedSignalCount && i < maxWaits) { spy.wait(timeout); ++i; } } void TestObject::setTestData(QByteArray qmlData) { QQmlComponent component(mView.engine()); component.setData(qmlData, QUrl()); mRootObject = component.create(mView.engine()->rootContext()); mView.setContent(QUrl(""), 0, mRootObject); } void TestObject::setTestUrl(const QUrl &url) { mView.setSource(url); mRootObject = mView.rootObject(); } void TestObject::setContextProperty(const QString &name, QObject *value) { mView.rootContext()->setContextProperty(name, value); } int TestObject::random(int min, int max) { return qrand() % ((max + 1) - min) + min; } <|endoftext|>
<commit_before>#include <apfMDS.h> #include <apfMesh2.h> #include <apfShape.h> #include <fstream> #include <gmi.h> #define MAX_ELEM_NODES 10 namespace apf { static void ansys2apf(int ansysType, int& apfType, apf::FieldShape*& shape) { switch (ansysType) { case 702: apfType = apf::Mesh::TET; shape = apf::getLagrange(1); return; case 902: apfType = apf::Mesh::TET; shape = apf::getLagrange(2); return; }; } static void parseElemInt(std::string const& line, int at, int& out) { assert(line.length() >= ((size_t)at + 1) * 6); std::string field = line.substr(at * 6, 6); if (field != " ") { std::stringstream ss(field); ss >> out; } } static bool parseElem(std::istream& f, int nodes[MAX_ELEM_NODES], int& apfType, int& id, apf::FieldShape*& shape) { std::string line; std::getline(f, line); if (!line.length()) return false; for (int i = 0; i < 8; ++i) parseElemInt(line, i, nodes[i]); int ansysType; parseElemInt(line, 9, ansysType); parseElemInt(line, 13, id); ansys2apf(ansysType, apfType, shape); int nnodes = shape->getEntityShape(apfType)->countNodes(); if (nnodes <= 8) return true; std::getline(f, line); for (int i = 0; i < (nnodes - 8); ++i) parseElemInt(line, i, nodes[i + 8]); return true; } typedef std::map<int, apf::Vector3> Nodes; static bool parseNode(std::istream& f, int& id, apf::Vector3& p) { std::string line; std::getline(f, line); if (!line.length()) return false; std::stringstream ss(line); ss >> id; int i = 0; while (ss >> p[i]) ++i; for (; i < 3; ++i) p[i] = 0; return true; } static void parseNodes(const char* nodefile, Nodes& nodes) { std::ifstream f(nodefile); if (!f.is_open()) { fprintf(stderr, "couldn't open ANSYS node file \"%s\"\n", nodefile); abort(); } std::pair<int, apf::Vector3> entry; while (parseNode(f, entry.first, entry.second)) nodes.insert(entry); } typedef std::map<int, MeshEntity*> Vertices; static Mesh2* parseElems(const char* elemfile, Nodes& nodes) { Mesh2* m = 0; std::ifstream f(elemfile); if (!f.is_open()) { fprintf(stderr, "couldn't open ANSYS elem file \"%s\"\n", elemfile); abort(); } Vertices verts; int en[MAX_ELEM_NODES]; int type; int id; apf::FieldShape* shape = 0; apf::FieldShape* prevShape = 0; while (parseElem(f, en, type, id, shape)) { if (!m) { m = makeEmptyMdsMesh(gmi_load(".null"), Mesh::typeDimension[type], false); if (shape != m->getShape()) changeMeshShape(m, shape, false); } if (prevShape) assert(prevShape == shape); int nev = Mesh::adjacentCount[type][0]; int nen = shape->getEntityShape(type)->countNodes(); Downward ev; for (int i = 0; i < nen; ++i) if (!nodes.count(en[i])) { fprintf(stderr, "node %d in file \"%s\" not found in node file\n", en[i], elemfile); abort(); } int i = 0; for (i = 0; i < nev; ++i) { if (!verts.count(en[i])) { MeshEntity* v = m->createVert(0); m->setPoint(v, 0, nodes[en[i]]); verts[en[i]] = v; } ev[i] = verts[en[i]]; } MeshEntity* e = buildElement(m, 0, type, ev); for (int d = 1; d <= m->getDimension(); ++d) { if (!shape->hasNodesIn(d)) continue; Downward ee; int nee = m->getDownward(e, d, ee); for (int j = 0; j < nee; ++j) { assert(shape->countNodesOn(m->getType(ee[j])) == 1); m->setPoint(ee[j], 0, nodes[en[i]]); ++i; } } assert(i == nen); prevShape = shape; } return m; } Mesh2* loadMdsFromANSYS(const char* nodefile, const char* elemfile) { Nodes nodes; parseNodes(nodefile, nodes); Mesh2* m = parseElems(elemfile, nodes); m->acceptChanges(); deriveMdsModel(m); return m; } } <commit_msg>recording ANSYS element numbers<commit_after>#include "apfMDS.h" #include <apfMesh2.h> #include <apfShape.h> #include <apfNumbering.h> #include <fstream> #include <gmi.h> #define MAX_ELEM_NODES 10 namespace apf { static void ansys2apf(int ansysType, int& apfType, apf::FieldShape*& shape) { switch (ansysType) { case 702: apfType = apf::Mesh::TET; shape = apf::getLagrange(1); return; case 902: apfType = apf::Mesh::TET; shape = apf::getLagrange(2); return; }; } static void parseElemInt(std::string const& line, int at, int& out) { assert(line.length() >= ((size_t)at + 1) * 6); std::string field = line.substr(at * 6, 6); if (field != " ") { std::stringstream ss(field); ss >> out; } } static bool parseElem(std::istream& f, int nodes[MAX_ELEM_NODES], int& apfType, int& id, apf::FieldShape*& shape) { std::string line; std::getline(f, line); if (!line.length()) return false; for (int i = 0; i < 8; ++i) parseElemInt(line, i, nodes[i]); int ansysType; parseElemInt(line, 9, ansysType); parseElemInt(line, 13, id); ansys2apf(ansysType, apfType, shape); int nnodes = shape->getEntityShape(apfType)->countNodes(); if (nnodes <= 8) return true; std::getline(f, line); for (int i = 0; i < (nnodes - 8); ++i) parseElemInt(line, i, nodes[i + 8]); return true; } typedef std::map<int, apf::Vector3> Nodes; static bool parseNode(std::istream& f, int& id, apf::Vector3& p) { std::string line; std::getline(f, line); if (!line.length()) return false; std::stringstream ss(line); ss >> id; int i = 0; while (ss >> p[i]) ++i; for (; i < 3; ++i) p[i] = 0; return true; } static void parseNodes(const char* nodefile, Nodes& nodes) { std::ifstream f(nodefile); if (!f.is_open()) { fprintf(stderr, "couldn't open ANSYS node file \"%s\"\n", nodefile); abort(); } std::pair<int, apf::Vector3> entry; while (parseNode(f, entry.first, entry.second)) nodes.insert(entry); } typedef std::map<int, MeshEntity*> Vertices; static Mesh2* parseElems(const char* elemfile, Nodes& nodes) { Mesh2* m = 0; std::ifstream f(elemfile); if (!f.is_open()) { fprintf(stderr, "couldn't open ANSYS elem file \"%s\"\n", elemfile); abort(); } Vertices verts; int en[MAX_ELEM_NODES]; int type; int id; apf::FieldShape* shape = 0; apf::FieldShape* prevShape = 0; apf::Numbering* enumbers = 0; while (parseElem(f, en, type, id, shape)) { if (!m) { m = makeEmptyMdsMesh(gmi_load(".null"), Mesh::typeDimension[type], false); if (shape != m->getShape()) changeMeshShape(m, shape, false); enumbers = createNumbering(m, "ansys_element", getConstant(m->getDimension()), 1); } if (prevShape) assert(prevShape == shape); int nev = Mesh::adjacentCount[type][0]; int nen = shape->getEntityShape(type)->countNodes(); Downward ev; for (int i = 0; i < nen; ++i) if (!nodes.count(en[i])) { fprintf(stderr, "node %d in file \"%s\" not found in node file\n", en[i], elemfile); abort(); } int i = 0; for (i = 0; i < nev; ++i) { if (!verts.count(en[i])) { MeshEntity* v = m->createVert(0); m->setPoint(v, 0, nodes[en[i]]); verts[en[i]] = v; } ev[i] = verts[en[i]]; } MeshEntity* e = buildElement(m, 0, type, ev); for (int d = 1; d <= m->getDimension(); ++d) { if (!shape->hasNodesIn(d)) continue; Downward ee; int nee = m->getDownward(e, d, ee); for (int j = 0; j < nee; ++j) { assert(shape->countNodesOn(m->getType(ee[j])) == 1); m->setPoint(ee[j], 0, nodes[en[i]]); ++i; } } number(enumbers, e, 0, 0, id); assert(i == nen); prevShape = shape; } return m; } Mesh2* loadMdsFromANSYS(const char* nodefile, const char* elemfile) { Nodes nodes; parseNodes(nodefile, nodes); Mesh2* m = parseElems(elemfile, nodes); m->acceptChanges(); deriveMdsModel(m); return m; } } <|endoftext|>
<commit_before>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/kernel_cache.hpp> #include <miopen/softmax.hpp> #include <miopen/float_equal.hpp> #include <miopen/check_numerics.hpp> namespace miopen { int nextPow2(int v) { if(v == 1) { return (v << 1); } else { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } } miopenStatus_t SoftmaxForward( Handle& handle, const void* alpha, const void* beta, const TensorDescriptor& yDesc, Data_t y) { if(!float_equal(*(static_cast<const float*>(alpha)), 1.0) || !float_equal(*(static_cast<const float*>(beta)), 0)) { MIOPEN_THROW("Only alpha=1 and beta=0 is supported"); } int n, c, h, w; std::tie(n, c, h, w) = tien<4>(yDesc.GetLengths()); // using workgroup size of 256 by default int grid_size = n * h * w; int spatial_dim = h * w; // num_spatial_dims or pixels each workgroup can compute int num_batch = c < 256 ? nextPow2(256 / c) : 1; const std::vector<size_t> vld{256, 1, 1}; bool usefp16 = false; bool usefp32 = true; if(yDesc.GetType() == miopenHalf) { usefp16 = true; usefp32 = false; } // See Kernels/MIOpenSoftmax.cl for description if(num_batch == 1) { // CSR-Vector like approach // Control the max. number of workgroups launched so that we do not // start getting workgroup scheduling overheads size_t workgroups = std::min(grid_size, 64 * 40 * 8); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxForwardOneBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { //auto kernel = kernels.front(); kernels.front()(y, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxForward"; // compile parameters std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, c, grid_size, spatial_dim); } } else { // CSR-Stream like approach // num_threads iterating over channels for one spatial_dim int batch_size = 256 / num_batch; // num_channels each threads iterates over to cover all the channels int u_batch_size = (c > batch_size) ? nextPow2(c / batch_size) : 1; //size_t workgroups = // grid_size % num_batch == 0 ? grid_size / num_batch : grid_size / num_batch + 1; size_t workgroups = (grid_size % num_batch == 0) ? (grid_size / num_batch) : (grid_size / num_batch + 1); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxForwardMultiBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c) + std::to_string(u_batch_size) + std::to_string(batch_size); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { kernels.front()(y, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxForward"; std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DBATCH_SIZE=" + std::to_string(batch_size) + " -DU_BATCH_SIZE=" + std::to_string(u_batch_size) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, c, grid_size, spatial_dim); } } if(miopen::CheckNumericsEnabled()) { miopen::checkNumericsOutput(handle, yDesc, y); } return miopenStatusSuccess; } miopenStatus_t SoftmaxBackward(Handle& handle, const void* alpha, const TensorDescriptor& yDesc, ConstData_t y, const void* beta, const TensorDescriptor& dxDesc, Data_t dx) { if(yDesc != dxDesc) { MIOPEN_THROW(miopenStatusBadParm); } if(!float_equal(*(static_cast<const float*>(alpha)), 1.0) || !float_equal(*(static_cast<const float*>(beta)), 0)) { MIOPEN_THROW("Only alpha=1 and beta=0 is supported"); } if(miopen::CheckNumericsEnabled()) { miopen::checkNumericsInput(handle, yDesc, y); } int n, c, h, w; std::tie(n, c, h, w) = tien<4>(dxDesc.GetLengths()); // using workgroup size of 256 by default int grid_size = n * h * w; int spatial_dim = h * w; int num_batch = (c < 256) ? nextPow2(256 / c) : 1; const std::vector<size_t> vld{256, 1, 1}; bool usefp16 = false; bool usefp32 = true; if(yDesc.GetType() == miopenHalf) { usefp16 = true; usefp32 = false; } // See Kernels/MIOpenSoftmax.cl for description if(num_batch == 1) { // CSR-Vector like approach // Control the max. number of workgroups launched so that we do not // start getting workgroup scheduling overheads size_t workgroups = std::min(grid_size, 64 * 40 * 8); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxBackwardOneBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { kernels.front()(y, dx, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxBackward"; std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, dx, c, grid_size, spatial_dim); } } else { // CSR-Stream like approach int batch_size = 256 / num_batch; int u_batch_size = (c > batch_size) ? nextPow2(c / batch_size) : 1; size_t workgroups = (grid_size % num_batch == 0) ? (grid_size / num_batch) : (grid_size / num_batch + 1); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxBackwardMultiBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c) + std::to_string(u_batch_size) + std::to_string(batch_size); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { kernels.front()(y, dx, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxBackward"; std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DBATCH_SIZE=" + std::to_string(batch_size) + " -DU_BATCH_SIZE=" + std::to_string(u_batch_size) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, dx, c, grid_size, spatial_dim); } } if(miopen::CheckNumericsEnabled()) { miopen::checkNumericsOutput(handle, dxDesc, dx); } return miopenStatusSuccess; } } // namespace miopen <commit_msg>Formatting.<commit_after>/******************************************************************************* * * MIT License * * Copyright (c) 2017 Advanced Micro Devices, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * *******************************************************************************/ #include <miopen/kernel_cache.hpp> #include <miopen/softmax.hpp> #include <miopen/float_equal.hpp> #include <miopen/check_numerics.hpp> namespace miopen { int nextPow2(int v) { if(v == 1) { return (v << 1); } else { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } } miopenStatus_t SoftmaxForward( Handle& handle, const void* alpha, const void* beta, const TensorDescriptor& yDesc, Data_t y) { if(!float_equal(*(static_cast<const float*>(alpha)), 1.0) || !float_equal(*(static_cast<const float*>(beta)), 0)) { MIOPEN_THROW("Only alpha=1 and beta=0 is supported"); } int n, c, h, w; std::tie(n, c, h, w) = tien<4>(yDesc.GetLengths()); // using workgroup size of 256 by default int grid_size = n * h * w; int spatial_dim = h * w; // num_spatial_dims or pixels each workgroup can compute int num_batch = c < 256 ? nextPow2(256 / c) : 1; const std::vector<size_t> vld{256, 1, 1}; bool usefp16 = false; bool usefp32 = true; if(yDesc.GetType() == miopenHalf) { usefp16 = true; usefp32 = false; } // See Kernels/MIOpenSoftmax.cl for description if(num_batch == 1) { // CSR-Vector like approach // Control the max. number of workgroups launched so that we do not // start getting workgroup scheduling overheads size_t workgroups = std::min(grid_size, 64 * 40 * 8); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxForwardOneBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { // auto kernel = kernels.front(); kernels.front()(y, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxForward"; // compile parameters std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, c, grid_size, spatial_dim); } } else { // CSR-Stream like approach // num_threads iterating over channels for one spatial_dim int batch_size = 256 / num_batch; // num_channels each threads iterates over to cover all the channels int u_batch_size = (c > batch_size) ? nextPow2(c / batch_size) : 1; // size_t workgroups = // grid_size % num_batch == 0 ? grid_size / num_batch : grid_size / num_batch + 1; size_t workgroups = (grid_size % num_batch == 0) ? (grid_size / num_batch) : (grid_size / num_batch + 1); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxForwardMultiBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c) + std::to_string(u_batch_size) + std::to_string(batch_size); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { kernels.front()(y, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxForward"; std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DBATCH_SIZE=" + std::to_string(batch_size) + " -DU_BATCH_SIZE=" + std::to_string(u_batch_size) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, c, grid_size, spatial_dim); } } if(miopen::CheckNumericsEnabled()) { miopen::checkNumericsOutput(handle, yDesc, y); } return miopenStatusSuccess; } miopenStatus_t SoftmaxBackward(Handle& handle, const void* alpha, const TensorDescriptor& yDesc, ConstData_t y, const void* beta, const TensorDescriptor& dxDesc, Data_t dx) { if(yDesc != dxDesc) { MIOPEN_THROW(miopenStatusBadParm); } if(!float_equal(*(static_cast<const float*>(alpha)), 1.0) || !float_equal(*(static_cast<const float*>(beta)), 0)) { MIOPEN_THROW("Only alpha=1 and beta=0 is supported"); } if(miopen::CheckNumericsEnabled()) { miopen::checkNumericsInput(handle, yDesc, y); } int n, c, h, w; std::tie(n, c, h, w) = tien<4>(dxDesc.GetLengths()); // using workgroup size of 256 by default int grid_size = n * h * w; int spatial_dim = h * w; int num_batch = (c < 256) ? nextPow2(256 / c) : 1; const std::vector<size_t> vld{256, 1, 1}; bool usefp16 = false; bool usefp32 = true; if(yDesc.GetType() == miopenHalf) { usefp16 = true; usefp32 = false; } // See Kernels/MIOpenSoftmax.cl for description if(num_batch == 1) { // CSR-Vector like approach // Control the max. number of workgroups launched so that we do not // start getting workgroup scheduling overheads size_t workgroups = std::min(grid_size, 64 * 40 * 8); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxBackwardOneBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { kernels.front()(y, dx, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxBackward"; std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, dx, c, grid_size, spatial_dim); } } else { // CSR-Stream like approach int batch_size = 256 / num_batch; int u_batch_size = (c > batch_size) ? nextPow2(c / batch_size) : 1; size_t workgroups = (grid_size % num_batch == 0) ? (grid_size / num_batch) : (grid_size / num_batch + 1); const std::vector<size_t> vgd{workgroups * vld[0], 1, 1}; std::string algo_name = "SoftmaxBackwardMultiBatch"; std::string network_config = std::to_string(num_batch) + std::to_string(usefp16) + std::to_string(usefp32) + std::to_string(vgd[0]) + std::to_string(vld[0]) + std::to_string(spatial_dim) + std::to_string(grid_size) + std::to_string(workgroups) + std::to_string(c) + std::to_string(u_batch_size) + std::to_string(batch_size); auto&& kernels = handle.GetKernels(algo_name, network_config); if(!kernels.empty()) { kernels.front()(y, dx, c, grid_size, spatial_dim); } else { std::string program_name = "MIOpenSoftmax.cl"; std::string kernel_name = "SoftmaxBackward"; std::string parms = "-DNUM_BATCH=" + std::to_string(num_batch) + " -DBATCH_SIZE=" + std::to_string(batch_size) + " -DU_BATCH_SIZE=" + std::to_string(u_batch_size) + " -DMIOPEN_USE_FP16=" + std::to_string(usefp16) + " -DMIOPEN_USE_FP32=" + std::to_string(usefp32); handle.AddKernel(algo_name, network_config, program_name, kernel_name, vld, vgd, parms)( y, dx, c, grid_size, spatial_dim); } } if(miopen::CheckNumericsEnabled()) { miopen::checkNumericsOutput(handle, dxDesc, dx); } return miopenStatusSuccess; } } // namespace miopen <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkQuaternionRigidTransform.h" #include "itkMutualInformationImageToImageMetric.h" #include "itkQuaternionRigidTransformGradientDescentOptimizer.h" #include "itkTextOutput.h" #include "itkSimpleMultiResolutionImageRegistrationUI.h" namespace { double F( itk::Vector<double,3> & v ); } /** * This program test one instantiation of the * itk::MultiResolutionImageRegistrationMethod class * * This file tests the combination of: * - MutualInformation * - QuaternionRigidTransform * - QuaternionRigidTransformGradientDescentOptimizer * - LinearInterpolateImageFunction * - RecursiveMultiResolutionPyramidImageFilter * * The test image pattern consists of a 3D gaussian in the middle * with some directional pattern on the outside. * One image is rotated and shifted relative to the other. * * Notes: * ===== * This example performs an rigid * registration between a 3D moving image and a 3D fixed image using * mutual information and a multi-resolution strategy. * * See notes for itkImageRegistrationMethodTest_14.cxx for more * detailed information on the algorithm. * * A simple user-interface, allows the user to define the number * of iteration and learning rate at each resolution level. * */ int itkMultiResolutionImageRegistrationMethodTest_2(int, char* [] ) { itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); bool pass = true; const unsigned int dimension = 3; unsigned int j; typedef float PixelType; // Fixed Image Type typedef itk::Image<PixelType,dimension> FixedImageType; // Moving Image Type typedef itk::Image<PixelType,dimension> MovingImageType; // Transform Type typedef itk::QuaternionRigidTransform< double > TransformType; // Optimizer Type typedef itk::QuaternionRigidTransformGradientDescentOptimizer OptimizerType; // Metric Type typedef itk::MutualInformationImageToImageMetric< FixedImageType, MovingImageType > MetricType; // Interpolation technique typedef itk:: LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; // Fixed Image Pyramid Type typedef itk::RecursiveMultiResolutionPyramidImageFilter< FixedImageType, FixedImageType > FixedImagePyramidType; // Moving Image Pyramid Type typedef itk::RecursiveMultiResolutionPyramidImageFilter< MovingImageType, MovingImageType > MovingImagePyramidType; // Registration Method typedef itk::MultiResolutionImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; MetricType::Pointer metric = MetricType::New(); TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); FixedImageType::Pointer fixedImage = FixedImageType::New(); MovingImageType::Pointer movingImage = MovingImageType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); FixedImagePyramidType::Pointer fixedImagePyramid = FixedImagePyramidType::New(); MovingImagePyramidType::Pointer movingImagePyramid = MovingImagePyramidType::New(); RegistrationType::Pointer registration = RegistrationType::New(); /********************************************************* * Set up the two input images. * One image rotated (xy plane) and shifted with respect to the other. **********************************************************/ double displacement[dimension] = {7,3,2}; double angle = 10.0 / 180.0 * itk::Math::pi; FixedImageType::SizeType size = {{100,100,40}}; FixedImageType::IndexType index = {{0,0,0}}; FixedImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); fixedImage->SetLargestPossibleRegion( region ); fixedImage->SetBufferedRegion( region ); fixedImage->SetRequestedRegion( region ); fixedImage->Allocate(); movingImage->SetLargestPossibleRegion( region ); movingImage->SetBufferedRegion( region ); movingImage->SetRequestedRegion( region ); movingImage->Allocate(); typedef itk::ImageRegionIterator<MovingImageType> MovingImageIterator; typedef itk::ImageRegionIterator<FixedImageType> FixedImageIterator; itk::Point<double,dimension> center; for ( j = 0; j < dimension; j++ ) { center[j] = 0.5 * (double)region.GetSize()[j]; } itk::Point<double,dimension> p; itk::Vector<double,dimension> d, d2; MovingImageIterator mIter( movingImage, region ); FixedImageIterator fIter( fixedImage, region ); while( !mIter.IsAtEnd() ) { for ( j = 0; j < dimension; j++ ) { p[j] = mIter.GetIndex()[j]; } d = p - center; fIter.Set( (PixelType) F(d) ); d2[0] = d[0] * std::cos(angle) + d[1] * std::sin(angle) + displacement[0]; d2[1] = -d[0] * std::sin(angle) + d[1] * std::cos(angle) + displacement[1]; d2[2] = d[2] + displacement[2]; mIter.Set( (PixelType) F(d2) ); ++fIter; ++mIter; } // set the image origin to be center of the image double transCenter[dimension]; for ( j = 0; j < dimension; j++ ) { transCenter[j] = -0.5 * double(size[j]); } movingImage->SetOrigin( transCenter ); fixedImage->SetOrigin( transCenter ); /****************************************************************** * Set up the optimizer. ******************************************************************/ // set the translation scale typedef OptimizerType::ScalesType ScalesType; ScalesType parametersScales( transform->GetNumberOfParameters() ); parametersScales.Fill( 1.0 ); for ( j = 4; j < 7; j++ ) { parametersScales[j] = 0.0001; } optimizer->SetScales( parametersScales ); // need to maximize for mutual information optimizer->MaximizeOn(); /****************************************************************** * Set up the optimizer observer ******************************************************************/ /* typedef itk::CommandIterationUpdate< OptimizerType > CommandIterationType; CommandIterationType::Pointer iterationCommand = CommandIterationType::New(); iterationCommand->SetOptimizer( optimizer ); */ /****************************************************************** * Set up the metric. ******************************************************************/ metric->SetMovingImageStandardDeviation( 5.0 ); metric->SetFixedImageStandardDeviation( 5.0 ); metric->SetNumberOfSpatialSamples( 50 ); /****************************************************************** * Set up the registrator. ******************************************************************/ // connect up the components registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetFixedImage( fixedImage ); registration->SetMovingImage( movingImage ); registration->SetInterpolator( interpolator ); registration->SetFixedImagePyramid( fixedImagePyramid ); registration->SetMovingImagePyramid( movingImagePyramid ); registration->SetFixedImageRegion( fixedImage->GetBufferedRegion() ); // set initial parameters to identity RegistrationType::ParametersType initialParameters( transform->GetNumberOfParameters() ); initialParameters.Fill( 0.0 ); initialParameters[3] = 1.0; /****************************************************************** * Attach registration to a simple UI and run registration ******************************************************************/ SimpleMultiResolutionImageRegistrationUI2<RegistrationType> simpleUI( registration ); unsigned short numberOfLevels = 3; itk::Array<unsigned int> niter( numberOfLevels ); itk::Array<double> rates( numberOfLevels ); niter[0] = 300; niter[1] = 300; niter[2] = 350; rates[0] = 1e-3; rates[1] = 5e-4; rates[2] = 1e-4; simpleUI.SetNumberOfIterations( niter ); simpleUI.SetLearningRates( rates ); try { registration->SetNumberOfLevels( numberOfLevels ); registration->SetInitialTransformParameters( initialParameters ); registration->Update(); } catch( itk::ExceptionObject & e ) { std::cout << "Registration failed" << std::endl; std::cout << "Reason " << e.GetDescription() << std::endl; return EXIT_FAILURE; } /*********************************************************** * Check the results ************************************************************/ RegistrationType::ParametersType solution = registration->GetLastTransformParameters(); std::cout << "Solution is: " << solution << std::endl; RegistrationType::ParametersType trueParameters( transform->GetNumberOfParameters() ); trueParameters.Fill( 0.0 ); trueParameters[2] = std::sin( angle / 2.0 ); trueParameters[3] = std::cos( angle / 2.0 ); trueParameters[4] = -1.0 * ( displacement[0] * std::cos(angle) - displacement[1] * std::sin(angle) ); trueParameters[5] = -1.0 * ( displacement[0] * std::sin(angle) + displacement[1] * std::cos(angle) ); trueParameters[6] = -1.0 * displacement[2]; std::cout << "True solution is: " << trueParameters << std::endl; for( j = 0; j < 4; j++ ) { if( itk::Math::abs( solution[j] - trueParameters[j] ) > 0.025 ) { pass = false; } } for( j = 4; j < 7; j++ ) { if( itk::Math::abs( solution[j] - trueParameters[j] ) > 1.0 ) { pass = false; } } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } /************************************************* * Check for parzen window exception **************************************************/ double oldValue = metric->GetMovingImageStandardDeviation(); metric->SetMovingImageStandardDeviation( 0.005 ); try { pass = false; registration->Update(); } catch(itk::ExceptionObject& err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if( !pass ) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } metric->SetMovingImageStandardDeviation( oldValue ); /************************************************* * Check for mapped out of image error **************************************************/ solution[5] = 1000; registration->SetInitialTransformParameters( solution ); try { pass = false; registration->Update(); } catch(itk::ExceptionObject& err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if( !pass ) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } namespace { /** * This function defines the test image pattern. * The pattern is a 3D gaussian in the middle * and some directional pattern on the outside. */ double F( itk::Vector<double,3> & v ) { double x = v[0]; double y = v[1]; double z = v[2]; const double s = 50; double value = 200.0 * std::exp( - ( x*x + y*y + z*z )/(s*s) ); x -= 8; y += 3; z += 0; double r = std::sqrt( x*x + y*y + z*z ); if( r > 35 ) { value = 2 * ( itk::Math::abs( x ) + 0.8 * itk::Math::abs( y ) + 0.5 * itk::Math::abs( z ) ); } if( r < 4 ) { value = 400; } return value; } } <commit_msg>BUG: Initialized the sampling seed for v3 registration test<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkQuaternionRigidTransform.h" #include "itkMutualInformationImageToImageMetric.h" #include "itkQuaternionRigidTransformGradientDescentOptimizer.h" #include "itkTextOutput.h" #include "itkSimpleMultiResolutionImageRegistrationUI.h" namespace { double F( itk::Vector<double,3> & v ); } /** * This program test one instantiation of the * itk::MultiResolutionImageRegistrationMethod class * * This file tests the combination of: * - MutualInformation * - QuaternionRigidTransform * - QuaternionRigidTransformGradientDescentOptimizer * - LinearInterpolateImageFunction * - RecursiveMultiResolutionPyramidImageFilter * * The test image pattern consists of a 3D gaussian in the middle * with some directional pattern on the outside. * One image is rotated and shifted relative to the other. * * Notes: * ===== * This example performs an rigid * registration between a 3D moving image and a 3D fixed image using * mutual information and a multi-resolution strategy. * * See notes for itkImageRegistrationMethodTest_14.cxx for more * detailed information on the algorithm. * * A simple user-interface, allows the user to define the number * of iteration and learning rate at each resolution level. * */ int itkMultiResolutionImageRegistrationMethodTest_2(int, char* [] ) { itk::OutputWindow::SetInstance(itk::TextOutput::New().GetPointer()); bool pass = true; const unsigned int dimension = 3; unsigned int j; typedef float PixelType; // Fixed Image Type typedef itk::Image<PixelType,dimension> FixedImageType; // Moving Image Type typedef itk::Image<PixelType,dimension> MovingImageType; // Transform Type typedef itk::QuaternionRigidTransform< double > TransformType; // Optimizer Type typedef itk::QuaternionRigidTransformGradientDescentOptimizer OptimizerType; // Metric Type typedef itk::MutualInformationImageToImageMetric< FixedImageType, MovingImageType > MetricType; // Interpolation technique typedef itk:: LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; // Fixed Image Pyramid Type typedef itk::RecursiveMultiResolutionPyramidImageFilter< FixedImageType, FixedImageType > FixedImagePyramidType; // Moving Image Pyramid Type typedef itk::RecursiveMultiResolutionPyramidImageFilter< MovingImageType, MovingImageType > MovingImagePyramidType; // Registration Method typedef itk::MultiResolutionImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; MetricType::Pointer metric = MetricType::New(); TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); FixedImageType::Pointer fixedImage = FixedImageType::New(); MovingImageType::Pointer movingImage = MovingImageType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); FixedImagePyramidType::Pointer fixedImagePyramid = FixedImagePyramidType::New(); MovingImagePyramidType::Pointer movingImagePyramid = MovingImagePyramidType::New(); RegistrationType::Pointer registration = RegistrationType::New(); /********************************************************* * Set up the two input images. * One image rotated (xy plane) and shifted with respect to the other. **********************************************************/ double displacement[dimension] = {7,3,2}; double angle = 10.0 / 180.0 * itk::Math::pi; FixedImageType::SizeType size = {{100,100,40}}; FixedImageType::IndexType index = {{0,0,0}}; FixedImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); fixedImage->SetLargestPossibleRegion( region ); fixedImage->SetBufferedRegion( region ); fixedImage->SetRequestedRegion( region ); fixedImage->Allocate(); movingImage->SetLargestPossibleRegion( region ); movingImage->SetBufferedRegion( region ); movingImage->SetRequestedRegion( region ); movingImage->Allocate(); typedef itk::ImageRegionIterator<MovingImageType> MovingImageIterator; typedef itk::ImageRegionIterator<FixedImageType> FixedImageIterator; itk::Point<double,dimension> center; for ( j = 0; j < dimension; j++ ) { center[j] = 0.5 * (double)region.GetSize()[j]; } itk::Point<double,dimension> p; itk::Vector<double,dimension> d, d2; MovingImageIterator mIter( movingImage, region ); FixedImageIterator fIter( fixedImage, region ); while( !mIter.IsAtEnd() ) { for ( j = 0; j < dimension; j++ ) { p[j] = mIter.GetIndex()[j]; } d = p - center; fIter.Set( (PixelType) F(d) ); d2[0] = d[0] * std::cos(angle) + d[1] * std::sin(angle) + displacement[0]; d2[1] = -d[0] * std::sin(angle) + d[1] * std::cos(angle) + displacement[1]; d2[2] = d[2] + displacement[2]; mIter.Set( (PixelType) F(d2) ); ++fIter; ++mIter; } // set the image origin to be center of the image double transCenter[dimension]; for ( j = 0; j < dimension; j++ ) { transCenter[j] = -0.5 * double(size[j]); } movingImage->SetOrigin( transCenter ); fixedImage->SetOrigin( transCenter ); /****************************************************************** * Set up the optimizer. ******************************************************************/ // set the translation scale typedef OptimizerType::ScalesType ScalesType; ScalesType parametersScales( transform->GetNumberOfParameters() ); parametersScales.Fill( 1.0 ); for ( j = 4; j < 7; j++ ) { parametersScales[j] = 0.0001; } optimizer->SetScales( parametersScales ); // need to maximize for mutual information optimizer->MaximizeOn(); /****************************************************************** * Set up the optimizer observer ******************************************************************/ /* typedef itk::CommandIterationUpdate< OptimizerType > CommandIterationType; CommandIterationType::Pointer iterationCommand = CommandIterationType::New(); iterationCommand->SetOptimizer( optimizer ); */ /****************************************************************** * Set up the metric. ******************************************************************/ metric->SetMovingImageStandardDeviation( 5.0 ); metric->SetFixedImageStandardDeviation( 5.0 ); metric->SetNumberOfSpatialSamples( 50 ); metric->ReinitializeSeed( 121212 ); /****************************************************************** * Set up the registrator. ******************************************************************/ // connect up the components registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetFixedImage( fixedImage ); registration->SetMovingImage( movingImage ); registration->SetInterpolator( interpolator ); registration->SetFixedImagePyramid( fixedImagePyramid ); registration->SetMovingImagePyramid( movingImagePyramid ); registration->SetFixedImageRegion( fixedImage->GetBufferedRegion() ); // set initial parameters to identity RegistrationType::ParametersType initialParameters( transform->GetNumberOfParameters() ); initialParameters.Fill( 0.0 ); initialParameters[3] = 1.0; /****************************************************************** * Attach registration to a simple UI and run registration ******************************************************************/ SimpleMultiResolutionImageRegistrationUI2<RegistrationType> simpleUI( registration ); unsigned short numberOfLevels = 3; itk::Array<unsigned int> niter( numberOfLevels ); itk::Array<double> rates( numberOfLevels ); niter[0] = 300; niter[1] = 300; niter[2] = 350; rates[0] = 1e-3; rates[1] = 5e-4; rates[2] = 1e-4; simpleUI.SetNumberOfIterations( niter ); simpleUI.SetLearningRates( rates ); try { registration->SetNumberOfLevels( numberOfLevels ); registration->SetInitialTransformParameters( initialParameters ); registration->Update(); } catch( itk::ExceptionObject & e ) { std::cout << "Registration failed" << std::endl; std::cout << "Reason " << e.GetDescription() << std::endl; return EXIT_FAILURE; } /*********************************************************** * Check the results ************************************************************/ RegistrationType::ParametersType solution = registration->GetLastTransformParameters(); std::cout << "Solution is: " << solution << std::endl; RegistrationType::ParametersType trueParameters( transform->GetNumberOfParameters() ); trueParameters.Fill( 0.0 ); trueParameters[2] = std::sin( angle / 2.0 ); trueParameters[3] = std::cos( angle / 2.0 ); trueParameters[4] = -1.0 * ( displacement[0] * std::cos(angle) - displacement[1] * std::sin(angle) ); trueParameters[5] = -1.0 * ( displacement[0] * std::sin(angle) + displacement[1] * std::cos(angle) ); trueParameters[6] = -1.0 * displacement[2]; std::cout << "True solution is: " << trueParameters << std::endl; for( j = 0; j < 4; j++ ) { if( itk::Math::abs( solution[j] - trueParameters[j] ) > 0.025 ) { pass = false; } } for( j = 4; j < 7; j++ ) { if( itk::Math::abs( solution[j] - trueParameters[j] ) > 1.0 ) { pass = false; } } if( !pass ) { std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } /************************************************* * Check for parzen window exception **************************************************/ double oldValue = metric->GetMovingImageStandardDeviation(); metric->SetMovingImageStandardDeviation( 0.005 ); try { pass = false; registration->Update(); } catch(itk::ExceptionObject& err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if( !pass ) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } metric->SetMovingImageStandardDeviation( oldValue ); /************************************************* * Check for mapped out of image error **************************************************/ solution[5] = 1000; registration->SetInitialTransformParameters( solution ); try { pass = false; registration->Update(); } catch(itk::ExceptionObject& err) { std::cout << "Caught expected ExceptionObject" << std::endl; std::cout << err << std::endl; pass = true; } if( !pass ) { std::cout << "Should have caught an exception" << std::endl; std::cout << "Test failed." << std::endl; return EXIT_FAILURE; } std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; } namespace { /** * This function defines the test image pattern. * The pattern is a 3D gaussian in the middle * and some directional pattern on the outside. */ double F( itk::Vector<double,3> & v ) { double x = v[0]; double y = v[1]; double z = v[2]; const double s = 50; double value = 200.0 * std::exp( - ( x*x + y*y + z*z )/(s*s) ); x -= 8; y += 3; z += 0; double r = std::sqrt( x*x + y*y + z*z ); if( r > 35 ) { value = 2 * ( itk::Math::abs( x ) + 0.8 * itk::Math::abs( y ) + 0.5 * itk::Math::abs( z ) ); } if( r < 4 ) { value = 400; } return value; } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkRadiomicsTransformationView.h" // QT includes (GUI) #include <qlabel.h> #include <qspinbox.h> #include <qpushbutton.h> #include <qcheckbox.h> #include <qgroupbox.h> #include <qradiobutton.h> #include <qmessagebox.h> // Berry includes (selection service) #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // MITK includes (GUI) #include <QmitkDataStorageComboBox.h> #include "QmitkDataNodeSelectionProvider.h" #include "mitkDataNodeObject.h" // MITK includes (general #include <mitkNodePredicateDataType.h> #include <mitkNodePredicateAnd.h> #include <mitkProperties.h> #include <mitkTransformationOperation.h> #include <mitkLabelSetImage.h> // Specific GUI Includes #include "QmitkGIFConfigurationPanel.h" QmitkRadiomicsTransformation::QmitkRadiomicsTransformation() : QmitkAbstractView(), m_Controls(nullptr) { } QmitkRadiomicsTransformation::~QmitkRadiomicsTransformation() { //berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); //if(s) // s->RemoveSelectionListener(m_SelectionListener); } void QmitkRadiomicsTransformation::CreateQtPartControl(QWidget *parent) { if (m_Controls == nullptr) { m_Controls = new Ui::QmitkRadiomicsTransformationViewControls; m_Controls->setupUi(parent); QLabel * label1 = new QLabel("Image: "); QLabel * label2 = new QLabel("Mask: "); QmitkDataStorageComboBox * cb_inputimage = new QmitkDataStorageComboBox(this->GetDataStorage(), mitk::TNodePredicateDataType<mitk::Image>::New()); m_Controls->m_InputImageGroup->layout()->addWidget(label1); m_Controls->m_InputImageGroup->layout()->addWidget(cb_inputimage); this->CreateConnections(); } } void QmitkRadiomicsTransformation::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->buttonExecuteMultiresolution), SIGNAL(clicked() ), this, SLOT(executeButtonMultiResolutionPressed() ) ); connect((QObject*)(m_Controls->m_WaveletExecuteButton), SIGNAL(clicked()), this, SLOT(executeButtonWaveletPressed())); connect((QObject*)(m_Controls->m_ExecuteLOG), SIGNAL(clicked()), this, SLOT(executeButtonLoGPressed())); connect((QObject*)(m_Controls->buttonResampleImage), SIGNAL(clicked()), this, SLOT(executeButtonResamplingPressed())); } } void QmitkRadiomicsTransformation::executeButtonMultiResolutionPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull() ) ) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } unsigned int numberOfLevels = m_Controls->m_NumberOfLevels->value(); bool resultAsDouble = m_Controls->m_resultAsDouble->isChecked(); auto results = mitk::TransformationOperation::MultiResolution(raw_image, numberOfLevels, resultAsDouble); unsigned int level = 1; for (auto image : results) { mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName+"::MultiRes::Level-"+us::Any(numberOfLevels-level).ToString())); result->SetData(image); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); ++level; } } void QmitkRadiomicsTransformation::executeButtonWaveletPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull())) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } unsigned int numberOfLevels = m_Controls->m_WaveletNumberOfLevels->value(); unsigned int numberOfBands = m_Controls->m_WaveletNumberOfBands->value(); mitk::BorderCondition condition = mitk::BorderCondition::Constant; mitk::WaveletType waveletType = mitk::WaveletType::Held; std::string waveletStr = m_Controls->m_WaveletWavelet->currentText().toStdString(); if (waveletStr == "Shannon") { waveletType = mitk::WaveletType::Shannon; } if (waveletStr == "Simoncelli") { waveletType = mitk::WaveletType::Simoncelli; } if (waveletStr == "Vow") { waveletType = mitk::WaveletType::Vow; } if (waveletStr == "Held") { waveletType = mitk::WaveletType::Held; } std::string conditionStr = m_Controls->m_WaveletBorderCondition->currentText().toStdString(); if (conditionStr == "Constant") { condition = mitk::BorderCondition::Constant; } if (conditionStr == "Periodic") { condition = mitk::BorderCondition::Periodic; } if (conditionStr == "Zero Flux Neumann") { condition = mitk::BorderCondition::ZeroFluxNeumann; } auto results = mitk::TransformationOperation::WaveletForward(raw_image, numberOfLevels, numberOfBands, condition, waveletType); unsigned int level = 0; for (auto image : results) { mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Wavelet::"+waveletStr+"-"+conditionStr+"::Level-" + us::Any(level).ToString())); result->SetData(image); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); ++level; } } void QmitkRadiomicsTransformation::executeButtonLoGPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull())) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } double sigma = m_Controls->m_LoGSigma->value(); bool resultAsDouble = m_Controls->m_LogResultAsDouble->isChecked(); auto results = mitk::TransformationOperation::LaplacianOfGaussian(raw_image, sigma, resultAsDouble); mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName + "::LoG::Sigma-" + us::Any(sigma).ToString())); result->SetData(results); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); } void QmitkRadiomicsTransformation::executeButtonResamplingPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull())) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } mitk::ImageMappingInterpolator::Type interpolatorType; switch (m_Controls->comboInterpolationMode->currentIndex()) { case 0: interpolatorType = mitk::ImageMappingInterpolator::Linear; break; case 1: interpolatorType = mitk::ImageMappingInterpolator::BSpline_3; break; case 2: interpolatorType = mitk::ImageMappingInterpolator::NearestNeighbor; break; case 3: interpolatorType = mitk::ImageMappingInterpolator::WSinc_Hamming; break; case 4: interpolatorType = mitk::ImageMappingInterpolator::WSinc_Welch; break; default: interpolatorType = mitk::ImageMappingInterpolator::Linear; } mitk::GridInterpolationPositionType gridPosition; switch (m_Controls->comboAxisAlignment->currentIndex()) { case 0: gridPosition = mitk::GridInterpolationPositionType::OriginAligned; break; case 1: gridPosition = mitk::GridInterpolationPositionType::CenterAligned; break; case 2: gridPosition = mitk::GridInterpolationPositionType::SameSize; break; default: gridPosition = mitk::GridInterpolationPositionType::OriginAligned; } bool resultAsDouble = m_Controls->checkResamplingOutputAsDouble->isChecked(); bool roundResult = m_Controls->checkResamplingRoundOutput->isChecked(); mitk::Vector3D spacing; spacing.Fill(-1); if (m_Controls->checkResampleX->isChecked()) { spacing[0] = m_Controls->doubleSpinDimensionX->value(); } if (m_Controls->checkResampleY->isChecked()) { spacing[1] = m_Controls->doubleSpinDimensionY->value(); } if (m_Controls->checkResampleZ->isChecked()) { spacing[2] = m_Controls->doubleSpinDimensionZ->value(); } mitk::Image::Pointer results; if (m_Controls->checkResampleAsMask->isChecked()) { results = mitk::TransformationOperation::ResampleMask(raw_image, spacing, interpolatorType, gridPosition); mitk::LabelSetImage::Pointer oldLabelImage = dynamic_cast<mitk::LabelSetImage *> (raw_image.GetPointer()); if (oldLabelImage.IsNotNull()) { mitk::LabelSetImage::Pointer labelResult = mitk::LabelSetImage::New(); labelResult->InitializeByLabeledImage(results); labelResult->AddLabelSetToLayer(labelResult->GetActiveLayer(), oldLabelImage->GetLabelSet()); results = dynamic_cast<mitk::Image*>(labelResult.GetPointer()); } } else { results = mitk::TransformationOperation::ResampleImage(raw_image, spacing, interpolatorType, gridPosition, resultAsDouble, roundResult); } mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Resampled" )); result->SetData(results); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); } void QmitkRadiomicsTransformation::SetFocus() { } //datamanager selection changed void QmitkRadiomicsTransformation::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes) { //any nodes there? if (!nodes.empty()) { } } <commit_msg>Remove unused variable<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkRadiomicsTransformationView.h" // QT includes (GUI) #include <qlabel.h> #include <qspinbox.h> #include <qpushbutton.h> #include <qcheckbox.h> #include <qgroupbox.h> #include <qradiobutton.h> #include <qmessagebox.h> // Berry includes (selection service) #include <berryISelectionService.h> #include <berryIWorkbenchWindow.h> // MITK includes (GUI) #include <QmitkDataStorageComboBox.h> #include "QmitkDataNodeSelectionProvider.h" #include "mitkDataNodeObject.h" // MITK includes (general #include <mitkNodePredicateDataType.h> #include <mitkNodePredicateAnd.h> #include <mitkProperties.h> #include <mitkTransformationOperation.h> #include <mitkLabelSetImage.h> // Specific GUI Includes #include "QmitkGIFConfigurationPanel.h" QmitkRadiomicsTransformation::QmitkRadiomicsTransformation() : QmitkAbstractView(), m_Controls(nullptr) { } QmitkRadiomicsTransformation::~QmitkRadiomicsTransformation() { //berry::ISelectionService* s = GetSite()->GetWorkbenchWindow()->GetSelectionService(); //if(s) // s->RemoveSelectionListener(m_SelectionListener); } void QmitkRadiomicsTransformation::CreateQtPartControl(QWidget *parent) { if (m_Controls == nullptr) { m_Controls = new Ui::QmitkRadiomicsTransformationViewControls; m_Controls->setupUi(parent); QLabel * label1 = new QLabel("Image: "); QmitkDataStorageComboBox * cb_inputimage = new QmitkDataStorageComboBox(this->GetDataStorage(), mitk::TNodePredicateDataType<mitk::Image>::New()); m_Controls->m_InputImageGroup->layout()->addWidget(label1); m_Controls->m_InputImageGroup->layout()->addWidget(cb_inputimage); this->CreateConnections(); } } void QmitkRadiomicsTransformation::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(m_Controls->buttonExecuteMultiresolution), SIGNAL(clicked() ), this, SLOT(executeButtonMultiResolutionPressed() ) ); connect((QObject*)(m_Controls->m_WaveletExecuteButton), SIGNAL(clicked()), this, SLOT(executeButtonWaveletPressed())); connect((QObject*)(m_Controls->m_ExecuteLOG), SIGNAL(clicked()), this, SLOT(executeButtonLoGPressed())); connect((QObject*)(m_Controls->buttonResampleImage), SIGNAL(clicked()), this, SLOT(executeButtonResamplingPressed())); } } void QmitkRadiomicsTransformation::executeButtonMultiResolutionPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull() ) ) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } unsigned int numberOfLevels = m_Controls->m_NumberOfLevels->value(); bool resultAsDouble = m_Controls->m_resultAsDouble->isChecked(); auto results = mitk::TransformationOperation::MultiResolution(raw_image, numberOfLevels, resultAsDouble); unsigned int level = 1; for (auto image : results) { mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName+"::MultiRes::Level-"+us::Any(numberOfLevels-level).ToString())); result->SetData(image); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); ++level; } } void QmitkRadiomicsTransformation::executeButtonWaveletPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull())) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } unsigned int numberOfLevels = m_Controls->m_WaveletNumberOfLevels->value(); unsigned int numberOfBands = m_Controls->m_WaveletNumberOfBands->value(); mitk::BorderCondition condition = mitk::BorderCondition::Constant; mitk::WaveletType waveletType = mitk::WaveletType::Held; std::string waveletStr = m_Controls->m_WaveletWavelet->currentText().toStdString(); if (waveletStr == "Shannon") { waveletType = mitk::WaveletType::Shannon; } if (waveletStr == "Simoncelli") { waveletType = mitk::WaveletType::Simoncelli; } if (waveletStr == "Vow") { waveletType = mitk::WaveletType::Vow; } if (waveletStr == "Held") { waveletType = mitk::WaveletType::Held; } std::string conditionStr = m_Controls->m_WaveletBorderCondition->currentText().toStdString(); if (conditionStr == "Constant") { condition = mitk::BorderCondition::Constant; } if (conditionStr == "Periodic") { condition = mitk::BorderCondition::Periodic; } if (conditionStr == "Zero Flux Neumann") { condition = mitk::BorderCondition::ZeroFluxNeumann; } auto results = mitk::TransformationOperation::WaveletForward(raw_image, numberOfLevels, numberOfBands, condition, waveletType); unsigned int level = 0; for (auto image : results) { mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Wavelet::"+waveletStr+"-"+conditionStr+"::Level-" + us::Any(level).ToString())); result->SetData(image); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); ++level; } } void QmitkRadiomicsTransformation::executeButtonLoGPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull())) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } double sigma = m_Controls->m_LoGSigma->value(); bool resultAsDouble = m_Controls->m_LogResultAsDouble->isChecked(); auto results = mitk::TransformationOperation::LaplacianOfGaussian(raw_image, sigma, resultAsDouble); mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName + "::LoG::Sigma-" + us::Any(sigma).ToString())); result->SetData(results); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); } void QmitkRadiomicsTransformation::executeButtonResamplingPressed() { QmitkDataStorageComboBox * cb_image = dynamic_cast<QmitkDataStorageComboBox *>(m_Controls->m_InputImageGroup->layout()->itemAt(1)->widget()); mitk::BaseData* baseDataRawImage = NULL; mitk::Image::Pointer raw_image; std::string nodeName; if ((cb_image->GetSelectedNode().IsNotNull())) { baseDataRawImage = (cb_image->GetSelectedNode()->GetData()); nodeName = cb_image->GetSelectedNode()->GetName(); } if ((baseDataRawImage != NULL)) { raw_image = dynamic_cast<mitk::Image *>(baseDataRawImage); } else { QMessageBox msgBox; msgBox.setText("Please specify the images that shlould be used."); msgBox.exec(); return; } if (raw_image.IsNull()) { QMessageBox msgBox; msgBox.setText("Error during processing the specified images."); msgBox.exec(); return; } mitk::ImageMappingInterpolator::Type interpolatorType; switch (m_Controls->comboInterpolationMode->currentIndex()) { case 0: interpolatorType = mitk::ImageMappingInterpolator::Linear; break; case 1: interpolatorType = mitk::ImageMappingInterpolator::BSpline_3; break; case 2: interpolatorType = mitk::ImageMappingInterpolator::NearestNeighbor; break; case 3: interpolatorType = mitk::ImageMappingInterpolator::WSinc_Hamming; break; case 4: interpolatorType = mitk::ImageMappingInterpolator::WSinc_Welch; break; default: interpolatorType = mitk::ImageMappingInterpolator::Linear; } mitk::GridInterpolationPositionType gridPosition; switch (m_Controls->comboAxisAlignment->currentIndex()) { case 0: gridPosition = mitk::GridInterpolationPositionType::OriginAligned; break; case 1: gridPosition = mitk::GridInterpolationPositionType::CenterAligned; break; case 2: gridPosition = mitk::GridInterpolationPositionType::SameSize; break; default: gridPosition = mitk::GridInterpolationPositionType::OriginAligned; } bool resultAsDouble = m_Controls->checkResamplingOutputAsDouble->isChecked(); bool roundResult = m_Controls->checkResamplingRoundOutput->isChecked(); mitk::Vector3D spacing; spacing.Fill(-1); if (m_Controls->checkResampleX->isChecked()) { spacing[0] = m_Controls->doubleSpinDimensionX->value(); } if (m_Controls->checkResampleY->isChecked()) { spacing[1] = m_Controls->doubleSpinDimensionY->value(); } if (m_Controls->checkResampleZ->isChecked()) { spacing[2] = m_Controls->doubleSpinDimensionZ->value(); } mitk::Image::Pointer results; if (m_Controls->checkResampleAsMask->isChecked()) { results = mitk::TransformationOperation::ResampleMask(raw_image, spacing, interpolatorType, gridPosition); mitk::LabelSetImage::Pointer oldLabelImage = dynamic_cast<mitk::LabelSetImage *> (raw_image.GetPointer()); if (oldLabelImage.IsNotNull()) { mitk::LabelSetImage::Pointer labelResult = mitk::LabelSetImage::New(); labelResult->InitializeByLabeledImage(results); labelResult->AddLabelSetToLayer(labelResult->GetActiveLayer(), oldLabelImage->GetLabelSet()); results = dynamic_cast<mitk::Image*>(labelResult.GetPointer()); } } else { results = mitk::TransformationOperation::ResampleImage(raw_image, spacing, interpolatorType, gridPosition, resultAsDouble, roundResult); } mitk::DataNode::Pointer result = mitk::DataNode::New(); result->SetProperty("name", mitk::StringProperty::New(nodeName + "::Resampled" )); result->SetData(results); GetDataStorage()->Add(result, cb_image->GetSelectedNode()); } void QmitkRadiomicsTransformation::SetFocus() { } //datamanager selection changed void QmitkRadiomicsTransformation::OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList<mitk::DataNode::Pointer>& nodes) { //any nodes there? if (!nodes.empty()) { } } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mediasource.h" #include "mediasource_p.h" #include "iodevicestream.h" #include <QFile> namespace Phonon { MediaSource::MediaSource() : d(new MediaSourcePrivate(Invalid)) { } MediaSource::MediaSource(const QString &filename) : d(new MediaSourcePrivate(LocalFile)) { if (filename.size() > 0 && filename.startsWith(QLatin1Char(':'))) { // it's a Qt resource -> use QFile d->type = Stream; d->resourceFile = new QFile(filename); d->stream = new IODeviceStream(d->resourceFile, d->resourceFile); } else { d->url = QUrl::fromLocalFile(filename); } } MediaSource::MediaSource(const QUrl &url) : d(new MediaSourcePrivate(Url)) { d->url = url; } MediaSource::MediaSource(Phonon::DiscType dt, const QString &deviceName) : d(new MediaSourcePrivate(Disc)) { d->discType = dt; d->deviceName = deviceName; } MediaSource::MediaSource(AbstractMediaStream *stream) : d(new MediaSourcePrivate(Stream)) { d->stream = stream; } MediaSource::MediaSource(QIODevice *ioDevice) : d(new MediaSourcePrivate(Stream)) { d->stream = new IODeviceStream(ioDevice, ioDevice); } MediaSource::~MediaSource() { delete d->resourceFile; d->resourceFile = 0; } MediaSource::MediaSource(const MediaSource &rhs) : d(rhs.d) { } MediaSource &MediaSource::operator=(const MediaSource &rhs) { d = rhs.d; return *this; } bool MediaSource::operator==(const MediaSource &rhs) const { return d == rhs.d; } MediaSource::Type MediaSource::type() const { if (d->type == Stream && d->stream == 0) { return Invalid; } return d->type; } QString MediaSource::filename() const { return d->url.toLocalFile(); } QUrl MediaSource::url() const { return d->url; } Phonon::DiscType MediaSource::discType() const { return d->discType; } QString MediaSource::deviceName() const { return d->deviceName; } AbstractMediaStream *MediaSource::stream() const { return d->stream; } //X AudioCaptureDevice MediaSource::audioCaptureDevice() const //X { //X return d->audioCaptureDevice; //X } //X //X VideoCaptureDevice MediaSource::videoCaptureDevice() const //X { //X return d->videoCaptureDevice; //X } } // namespace Phonon // vim: sw=4 sts=4 et tw=100 <commit_msg>passing NoDisc makes it an invalid MediaSource<commit_after>/* This file is part of the KDE project Copyright (C) 2007 Matthias Kretz <kretz@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "mediasource.h" #include "mediasource_p.h" #include "iodevicestream.h" #include <QFile> namespace Phonon { MediaSource::MediaSource() : d(new MediaSourcePrivate(Invalid)) { } MediaSource::MediaSource(const QString &filename) : d(new MediaSourcePrivate(LocalFile)) { if (filename.size() > 0 && filename.startsWith(QLatin1Char(':'))) { // it's a Qt resource -> use QFile d->type = Stream; d->resourceFile = new QFile(filename); d->stream = new IODeviceStream(d->resourceFile, d->resourceFile); } else { d->url = QUrl::fromLocalFile(filename); } } MediaSource::MediaSource(const QUrl &url) : d(new MediaSourcePrivate(Url)) { d->url = url; } MediaSource::MediaSource(Phonon::DiscType dt, const QString &deviceName) : d(new MediaSourcePrivate(Disc)) { if (dt == NoDisc) { d->type = Invalid; return; } d->discType = dt; d->deviceName = deviceName; } MediaSource::MediaSource(AbstractMediaStream *stream) : d(new MediaSourcePrivate(Stream)) { d->stream = stream; } MediaSource::MediaSource(QIODevice *ioDevice) : d(new MediaSourcePrivate(Stream)) { d->stream = new IODeviceStream(ioDevice, ioDevice); } MediaSource::~MediaSource() { delete d->resourceFile; d->resourceFile = 0; } MediaSource::MediaSource(const MediaSource &rhs) : d(rhs.d) { } MediaSource &MediaSource::operator=(const MediaSource &rhs) { d = rhs.d; return *this; } bool MediaSource::operator==(const MediaSource &rhs) const { return d == rhs.d; } MediaSource::Type MediaSource::type() const { if (d->type == Stream && d->stream == 0) { return Invalid; } return d->type; } QString MediaSource::filename() const { return d->url.toLocalFile(); } QUrl MediaSource::url() const { return d->url; } Phonon::DiscType MediaSource::discType() const { return d->discType; } QString MediaSource::deviceName() const { return d->deviceName; } AbstractMediaStream *MediaSource::stream() const { return d->stream; } //X AudioCaptureDevice MediaSource::audioCaptureDevice() const //X { //X return d->audioCaptureDevice; //X } //X //X VideoCaptureDevice MediaSource::videoCaptureDevice() const //X { //X return d->videoCaptureDevice; //X } } // namespace Phonon // vim: sw=4 sts=4 et tw=100 <|endoftext|>
<commit_before>#define png_infopp_NULL (png_infopp)NULL #define int_p_NULL (int*)NULL #include <boost/gil/extension/io/png_io.hpp> #include "cctag/utils/FileDebug.hpp" #include "cctag/utils/VisualDebug.hpp" #include "cctag/utils/Exceptions.hpp" #include "cctag/Detection.hpp" #include "CmdLine.hpp" #ifdef WITH_CUDA #include "cuda/device_prop.hpp" #include "cuda/debug_macros.hpp" #endif // WITH_CUDA #include <boost/filesystem/convenience.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/exception/all.hpp> #include <boost/ptr_container/ptr_list.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <opencv/cv.h> #include <opencv2/videoio.hpp> #include <opencv2/core/core.hpp> #include "opencv2/opencv.hpp" #include <sstream> #include <iostream> #include <string> #include <fstream> #include <exception> #define PRINT_TO_CERR using namespace cctag; using boost::timer; using namespace boost::gil; namespace bfs = boost::filesystem; // static const std::string kUsageString = "Usage: detection image_file.png\n"; void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ostream & output, std::string debugFileName = "") { if (debugFileName == "") { debugFileName = "00000"; } // Process markers detection boost::timer t; boost::ptr_list<CCTag> markers; CCTagVisualDebug::instance().initBackgroundImage(src); CCTagVisualDebug::instance().setImageFileName(debugFileName); CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath()); static cctag::logtime::Mgmt* durations = 0; #if 0 if( not durations ) { durations = new cctag::logtime::Mgmt( 25 ); } else { durations->resetStartTime(); } #endif cctagDetection( markers, frameId , src, params, bank, true, durations ); if( durations ) { durations->print( std::cerr ); } CCTagFileDebug::instance().outPutAllSessions(); CCTagFileDebug::instance().clearSessions(); CCTagVisualDebug::instance().outPutAllSessions(); CCTagVisualDebug::instance().clearSessions(); CCTAG_COUT( markers.size() << " markers."); CCTAG_COUT("Total time: " << t.elapsed()); CCTAG_COUT_NOENDL("Id : "); int i = 0; output << "#frame " << frameId << '\n'; output << markers.size() << '\n'; BOOST_FOREACH(const cctag::CCTag & marker, markers) { output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n'; if (i == 0) { CCTAG_COUT_NOENDL(marker.id() + 1); } else { CCTAG_COUT_NOENDL(", " << marker.id() + 1); } ++i; } CCTAG_COUT(""); } /*************************************************************/ /* Main entry */ /*************************************************************/ int main(int argc, char** argv) { CmdLine cmdline; if( cmdline.parse( argc, argv ) == false ) { cmdline.usage( argv[0] ); return EXIT_FAILURE; } cmdline.print( argv[0] ); // Check input path if( cmdline._filename.compare("") != 0){ if (!boost::filesystem::exists( cmdline._filename )) { std::cerr << std::endl << "The input file \""<< cmdline._filename << "\" is missing" << std::endl; return EXIT_FAILURE; } }else{ std::cerr << std::endl << "An input file is required" << std::endl; cmdline.usage( argv[0] ); return EXIT_FAILURE; } #ifdef WITH_CUDA popart::pop_cuda_only_sync_calls( cmdline._switchSync ); #endif // Check the (optional) parameters path std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str()); cctag::Parameters params(nCrowns); if( cmdline._paramsFilename != "" ) { if (!boost::filesystem::exists( cmdline._paramsFilename )) { std::cerr << std::endl << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl; return EXIT_FAILURE; } // Read the parameter file provided by the user std::ifstream ifs( cmdline._paramsFilename.c_str() ); boost::archive::xml_iarchive ia(ifs); ia >> boost::serialization::make_nvp("CCTagsParams", params); CCTAG_COUT(params._nCrowns); CCTAG_COUT(nCrowns); assert( nCrowns == params._nCrowns ); } else { // Use the default parameters and save them in defaultParameters.xml cmdline._paramsFilename = "defaultParameters.xml"; std::ofstream ofs( cmdline._paramsFilename.c_str() ); boost::archive::xml_oarchive oa(ofs); oa << boost::serialization::make_nvp("CCTagsParams", params); CCTAG_COUT("Parameter file not provided. Default parameters are used."); } CCTagMarkersBank bank(params._nCrowns); if ( !cmdline._cctagBankFilename.empty()) { bank = CCTagMarkersBank(cmdline._cctagBankFilename); } #ifdef WITH_CUDA if( cmdline._useCuda ) { params.setUseCuda( true ); } else { params.setUseCuda( false ); } if( cmdline._debugDir != "" ) { params.setDebugDir( cmdline._debugDir ); } popart::device_prop_t deviceInfo( false ); #if 0 deviceInfo.print( ); #endif #endif // WITH_CUDA bfs::path myPath( cmdline._filename ); std::string ext(myPath.extension().string()); const bfs::path subFilenamePath(myPath.filename()); const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path()); std::string outputFileName; if (!bfs::is_directory(myPath)) { CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns ); outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out"; }else { CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns ); outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out"; } std::ofstream outputFile; outputFile.open( outputFileName ); if ( (ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG")) { POP_INFO("looking at image " << myPath.string()); // Gray scale convertion cv::Mat src = cv::imread(cmdline._filename); cv::Mat graySrc; cv::cvtColor( src, graySrc, CV_BGR2GRAY ); // Upscale original image /*{ rgb8_image_t simage; simage.recreate( 2 * image.width(), 2 * image.height() ); rgb8_view_t osvw( view( simage ) ); terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() ); }*/ // Call the CCTag detection #ifdef PRINT_TO_CERR detection(0, graySrc, params, bank, std::cerr, myPath.stem().string()); #else detection(0, graySrc, params, bank, outputFile, myPath.stem().string()); #endif } else if (ext == ".avi" ) { CCTAG_COUT("*** Video mode ***"); POP_INFO( "looking at video " << myPath.string() ); // open video and check cv::VideoCapture video( cmdline._filename.c_str() ); if(!video.isOpened()) { CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1; } // play loop int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT); std::list<cv::Mat*> frames; std::cerr << "Starting to read video frames" << std::endl; while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame ) { cv::Mat frame; video >> frame; cv::Mat* imgGray = new cv::Mat; cv::cvtColor( frame, *imgGray, CV_BGR2GRAY ); frames.push_back( imgGray ); } std::cerr << "Done. Now processing." << std::endl; boost::timer t; std::size_t frameId = 0; #if 0 boost::mutex frame_mutex; boost::thread_group frame_processor; for( int proc=0; proc<1 ; proc++ ) { frame_processor.create_thread( [&frames, &frameId, &frame_mutex, &t, params, bank, &outputFile](){ bool empty; do { cv::Mat* imgGray; frame_mutex.lock(); empty = frames.empty(); if( not empty ) { imgGray = frames.front(); frames.pop_front(); ++frameId; } frame_mutex.unlock(); std::stringstream outFileName; outFileName << std::setfill('0') << std::setw(5) << frameId; detection(frameId, *imgGray, params, bank, outputFile, outFileName.str()); if( frameId % 100 == 0 ) { std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") "; } delete imgGray; } while( not empty ); } ); } frame_processor.join_all(); #else for( cv::Mat* imgGray : frames ) { // Set the output folder std::stringstream outFileName; outFileName << std::setfill('0') << std::setw(5) << frameId; // Invert the image for the projection scenario //cv::Mat imgGrayInverted; //bitwise_not ( imgGray, imgGrayInverted ); // Call the CCTag detection #ifdef PRINT_TO_CERR detection(frameId, *imgGray, params, bank, std::cerr, outFileName.str()); #else detection(frameId, *imgGray, params, bank, outputFile, outFileName.str()); #endif ++frameId; if( frameId % 100 == 0 ) { std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") "; } } #endif std::cerr << std::endl; } else if (bfs::is_directory(myPath)) { CCTAG_COUT("*** Image sequence mode ***"); std::vector<bfs::path> vFileInFolder; std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is std::sort(vFileInFolder.begin(), vFileInFolder.end()); std::size_t frameId = 0; for(const auto & fileInFolder : vFileInFolder) { const std::string subExt(bfs::extension(fileInFolder)); if ( (subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG") ) { CCTAG_COUT( "Processing image " << fileInFolder.string() ); cv::Mat src; src = cv::imread(fileInFolder.string()); cv::Mat imgGray; cv::cvtColor( src, imgGray, CV_BGR2GRAY ); // Call the CCTag detection #ifdef PRINT_TO_CERR detection(frameId, imgGray, params, bank, std::cerr, fileInFolder.stem().string()); #else detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string()); #endif ++frameId; } } }else { throw std::logic_error("Unrecognized input."); } outputFile.close(); return 0; } <commit_msg>[application] Print elapsed time in any case.<commit_after>#define png_infopp_NULL (png_infopp)NULL #define int_p_NULL (int*)NULL #include <boost/gil/extension/io/png_io.hpp> #include "cctag/utils/FileDebug.hpp" #include "cctag/utils/VisualDebug.hpp" #include "cctag/utils/Exceptions.hpp" #include "cctag/Detection.hpp" #include "CmdLine.hpp" #ifdef WITH_CUDA #include "cuda/device_prop.hpp" #include "cuda/debug_macros.hpp" #endif // WITH_CUDA #include <boost/filesystem/convenience.hpp> #include <boost/filesystem.hpp> #include <boost/progress.hpp> #include <boost/exception/all.hpp> #include <boost/ptr_container/ptr_list.hpp> #include <boost/archive/xml_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <opencv/cv.h> #include <opencv2/videoio.hpp> #include <opencv2/core/core.hpp> #include "opencv2/opencv.hpp" #include <sstream> #include <iostream> #include <string> #include <fstream> #include <exception> #define PRINT_TO_CERR using namespace cctag; using boost::timer; using namespace boost::gil; namespace bfs = boost::filesystem; // static const std::string kUsageString = "Usage: detection image_file.png\n"; void detection(std::size_t frameId, const cv::Mat & src, const cctag::Parameters & params, const cctag::CCTagMarkersBank & bank, std::ostream & output, std::string debugFileName = "") { if (debugFileName == "") { debugFileName = "00000"; } // Process markers detection boost::timer t; boost::ptr_list<CCTag> markers; CCTagVisualDebug::instance().initBackgroundImage(src); CCTagVisualDebug::instance().setImageFileName(debugFileName); CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath()); static cctag::logtime::Mgmt* durations = 0; #if 0 if( not durations ) { durations = new cctag::logtime::Mgmt( 25 ); } else { durations->resetStartTime(); } #endif cctagDetection( markers, frameId , src, params, bank, true, durations ); if( durations ) { durations->print( std::cerr ); } CCTagFileDebug::instance().outPutAllSessions(); CCTagFileDebug::instance().clearSessions(); CCTagVisualDebug::instance().outPutAllSessions(); CCTagVisualDebug::instance().clearSessions(); CCTAG_COUT( markers.size() << " markers."); std::cout << "Total time: " << t.elapsed() << std::endl; CCTAG_COUT_NOENDL("Id : "); int i = 0; output << "#frame " << frameId << '\n'; output << markers.size() << '\n'; BOOST_FOREACH(const cctag::CCTag & marker, markers) { output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n'; if (i == 0) { CCTAG_COUT_NOENDL(marker.id() + 1); } else { CCTAG_COUT_NOENDL(", " << marker.id() + 1); } ++i; } CCTAG_COUT(""); } /*************************************************************/ /* Main entry */ /*************************************************************/ int main(int argc, char** argv) { CmdLine cmdline; if( cmdline.parse( argc, argv ) == false ) { cmdline.usage( argv[0] ); return EXIT_FAILURE; } cmdline.print( argv[0] ); // Check input path if( cmdline._filename.compare("") != 0){ if (!boost::filesystem::exists( cmdline._filename )) { std::cerr << std::endl << "The input file \""<< cmdline._filename << "\" is missing" << std::endl; return EXIT_FAILURE; } }else{ std::cerr << std::endl << "An input file is required" << std::endl; cmdline.usage( argv[0] ); return EXIT_FAILURE; } #ifdef WITH_CUDA popart::pop_cuda_only_sync_calls( cmdline._switchSync ); #endif // Check the (optional) parameters path std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str()); cctag::Parameters params(nCrowns); if( cmdline._paramsFilename != "" ) { if (!boost::filesystem::exists( cmdline._paramsFilename )) { std::cerr << std::endl << "The input file \""<< cmdline._paramsFilename << "\" is missing" << std::endl; return EXIT_FAILURE; } // Read the parameter file provided by the user std::ifstream ifs( cmdline._paramsFilename.c_str() ); boost::archive::xml_iarchive ia(ifs); ia >> boost::serialization::make_nvp("CCTagsParams", params); CCTAG_COUT(params._nCrowns); CCTAG_COUT(nCrowns); assert( nCrowns == params._nCrowns ); } else { // Use the default parameters and save them in defaultParameters.xml cmdline._paramsFilename = "defaultParameters.xml"; std::ofstream ofs( cmdline._paramsFilename.c_str() ); boost::archive::xml_oarchive oa(ofs); oa << boost::serialization::make_nvp("CCTagsParams", params); CCTAG_COUT("Parameter file not provided. Default parameters are used."); } CCTagMarkersBank bank(params._nCrowns); if ( !cmdline._cctagBankFilename.empty()) { bank = CCTagMarkersBank(cmdline._cctagBankFilename); } #ifdef WITH_CUDA if( cmdline._useCuda ) { params.setUseCuda( true ); } else { params.setUseCuda( false ); } if( cmdline._debugDir != "" ) { params.setDebugDir( cmdline._debugDir ); } popart::device_prop_t deviceInfo( false ); #if 0 deviceInfo.print( ); #endif #endif // WITH_CUDA bfs::path myPath( cmdline._filename ); std::string ext(myPath.extension().string()); const bfs::path subFilenamePath(myPath.filename()); const bfs::path parentPath( myPath.parent_path() == "" ? "." : myPath.parent_path()); std::string outputFileName; if (!bfs::is_directory(myPath)) { CCTagVisualDebug::instance().initializeFolders( parentPath , cmdline._outputFolderName , params._nCrowns ); outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out"; }else { CCTagVisualDebug::instance().initializeFolders( myPath , cmdline._outputFolderName , params._nCrowns ); outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out"; } std::ofstream outputFile; outputFile.open( outputFileName ); if ( (ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG")) { POP_INFO("looking at image " << myPath.string()); // Gray scale convertion cv::Mat src = cv::imread(cmdline._filename); cv::Mat graySrc; cv::cvtColor( src, graySrc, CV_BGR2GRAY ); // Upscale original image /*{ rgb8_image_t simage; simage.recreate( 2 * image.width(), 2 * image.height() ); rgb8_view_t osvw( view( simage ) ); terry::resize_view( svw, osvw, terry::sampler::bicubic_sampler() ); }*/ // Call the CCTag detection #ifdef PRINT_TO_CERR detection(0, graySrc, params, bank, std::cerr, myPath.stem().string()); #else detection(0, graySrc, params, bank, outputFile, myPath.stem().string()); #endif } else if (ext == ".avi" ) { CCTAG_COUT("*** Video mode ***"); POP_INFO( "looking at video " << myPath.string() ); // open video and check cv::VideoCapture video( cmdline._filename.c_str() ); if(!video.isOpened()) { CCTAG_COUT("Unable to open the video : " << cmdline._filename); return -1; } // play loop int lastFrame = video.get(CV_CAP_PROP_FRAME_COUNT); std::list<cv::Mat*> frames; std::cerr << "Starting to read video frames" << std::endl; while( video.get(CV_CAP_PROP_POS_FRAMES) < lastFrame ) { cv::Mat frame; video >> frame; cv::Mat* imgGray = new cv::Mat; cv::cvtColor( frame, *imgGray, CV_BGR2GRAY ); frames.push_back( imgGray ); } std::cerr << "Done. Now processing." << std::endl; boost::timer t; std::size_t frameId = 0; #if 0 boost::mutex frame_mutex; boost::thread_group frame_processor; for( int proc=0; proc<1 ; proc++ ) { frame_processor.create_thread( [&frames, &frameId, &frame_mutex, &t, params, bank, &outputFile](){ bool empty; do { cv::Mat* imgGray; frame_mutex.lock(); empty = frames.empty(); if( not empty ) { imgGray = frames.front(); frames.pop_front(); ++frameId; } frame_mutex.unlock(); std::stringstream outFileName; outFileName << std::setfill('0') << std::setw(5) << frameId; detection(frameId, *imgGray, params, bank, outputFile, outFileName.str()); if( frameId % 100 == 0 ) { std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") "; } delete imgGray; } while( not empty ); } ); } frame_processor.join_all(); #else for( cv::Mat* imgGray : frames ) { // Set the output folder std::stringstream outFileName; outFileName << std::setfill('0') << std::setw(5) << frameId; // Invert the image for the projection scenario //cv::Mat imgGrayInverted; //bitwise_not ( imgGray, imgGrayInverted ); // Call the CCTag detection #ifdef PRINT_TO_CERR detection(frameId, *imgGray, params, bank, std::cerr, outFileName.str()); #else detection(frameId, *imgGray, params, bank, outputFile, outFileName.str()); #endif ++frameId; if( frameId % 100 == 0 ) { std::cerr << frameId << " (" << std::setprecision(3) << t.elapsed()*1000.0/frameId << ") "; } } #endif std::cerr << std::endl; } else if (bfs::is_directory(myPath)) { CCTAG_COUT("*** Image sequence mode ***"); std::vector<bfs::path> vFileInFolder; std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is std::sort(vFileInFolder.begin(), vFileInFolder.end()); std::size_t frameId = 0; for(const auto & fileInFolder : vFileInFolder) { const std::string subExt(bfs::extension(fileInFolder)); if ( (subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG") ) { CCTAG_COUT( "Processing image " << fileInFolder.string() ); cv::Mat src; src = cv::imread(fileInFolder.string()); cv::Mat imgGray; cv::cvtColor( src, imgGray, CV_BGR2GRAY ); // Call the CCTag detection #ifdef PRINT_TO_CERR detection(frameId, imgGray, params, bank, std::cerr, fileInFolder.stem().string()); #else detection(frameId, imgGray, params, bank, outputFile, fileInFolder.stem().string()); #endif ++frameId; } } }else { throw std::logic_error("Unrecognized input."); } outputFile.close(); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2018 The OTS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "stat.h" #include "name.h" namespace ots { // ----------------------------------------------------------------------------- // OpenTypeSTAT // ----------------------------------------------------------------------------- bool OpenTypeSTAT::ValidateNameId(uint16_t nameid, bool allowPredefined) { OpenTypeNAME* name = static_cast<OpenTypeNAME*>( GetFont()->GetTypedTable(OTS_TAG_NAME)); if (!name->IsValidNameId(nameid)) { Drop("Invalid nameID: %d", nameid); return false; } if (!allowPredefined && nameid < 26) { Warning("nameID out of range: %d", nameid); return true; } if ((nameid >= 26 && nameid <= 255) || nameid >= 32768) { Warning("nameID out of range: %d", nameid); return true; } return true; } bool OpenTypeSTAT::Parse(const uint8_t* data, size_t length) { Buffer table(data, length); if (!table.ReadU16(&this->majorVersion) || !table.ReadU16(&this->minorVersion) || !table.ReadU16(&this->designAxisSize) || !table.ReadU16(&this->designAxisCount) || !table.ReadU32(&this->designAxesOffset) || !table.ReadU16(&this->axisValueCount) || !table.ReadU32(&this->offsetToAxisValueOffsets) || !(this->minorVersion < 1 || table.ReadU16(&this->elidedFallbackNameID))) { return Drop("Failed to read table header"); } if (this->majorVersion != 1) { return Drop("Unknown table version"); } if (this->minorVersion > 2) { Warning("Unknown minor version, downgrading to 2"); this->minorVersion = 2; } if (this->designAxisSize < sizeof(AxisRecord)) { return Drop("Invalid designAxisSize"); } size_t headerEnd = table.offset(); if (this->designAxisCount == 0) { if (this->designAxesOffset != 0) { Warning("Unexpected non-zero designAxesOffset"); this->designAxesOffset = 0; } } else { if (this->designAxesOffset < headerEnd || size_t(this->designAxesOffset) + size_t(this->designAxisCount) * size_t(this->designAxisSize) > length) { return Drop("Invalid designAxesOffset"); } } for (size_t i = 0; i < this->designAxisCount; i++) { table.set_offset(this->designAxesOffset + i * this->designAxisSize); this->designAxes.emplace_back(); auto& axis = this->designAxes[i]; if (!table.ReadU32(&axis.axisTag) || !table.ReadU16(&axis.axisNameID) || !table.ReadU16(&axis.axisOrdering)) { return Drop("Failed to read design axis"); } if (!CheckTag(axis.axisTag)) { return Drop("Bad design axis tag"); } if (!ValidateNameId(axis.axisNameID, false)) { return true; } } // TODO // - check that all axes defined in fvar are covered by STAT // - check that axisOrdering values are not duplicated (warn only) if (this->axisValueCount == 0) { if (this->offsetToAxisValueOffsets != 0) { Warning("Unexpected non-zero offsetToAxisValueOffsets"); this->offsetToAxisValueOffsets = 0; } } else { if (this->offsetToAxisValueOffsets < headerEnd || size_t(this->offsetToAxisValueOffsets) + size_t(this->axisValueCount) * sizeof(uint16_t) > length) { return Drop("Invalid offsetToAxisValueOffsets"); } } for (size_t i = 0; i < this->axisValueCount; i++) { table.set_offset(this->offsetToAxisValueOffsets + i * sizeof(uint16_t)); uint16_t axisValueOffset; if (!table.ReadU16(&axisValueOffset)) { return Drop("Failed to read axis value offset"); } if (this->offsetToAxisValueOffsets + axisValueOffset > length) { return Drop("Invalid axis value offset"); } table.set_offset(this->offsetToAxisValueOffsets + axisValueOffset); uint16_t format; if (!table.ReadU16(&format)) { return Drop("Failed to read axis value format"); } this->axisValues.emplace_back(format); auto& axisValue = axisValues[i]; switch (format) { case 1: if (!table.ReadU16(&axisValue.format1.axisIndex) || !table.ReadU16(&axisValue.format1.flags) || !table.ReadU16(&axisValue.format1.valueNameID) || !table.ReadS32(&axisValue.format1.value)) { return Drop("Failed to read axis value (format 1)"); } if (axisValue.format1.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } if ((axisValue.format1.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format1.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format1.valueNameID)) { return true; } break; case 2: if (!table.ReadU16(&axisValue.format2.axisIndex) || !table.ReadU16(&axisValue.format2.flags) || !table.ReadU16(&axisValue.format2.valueNameID) || !table.ReadS32(&axisValue.format2.nominalValue) || !table.ReadS32(&axisValue.format2.rangeMinValue) || !table.ReadS32(&axisValue.format2.rangeMaxValue)) { return Drop("Failed to read axis value (format 2)"); } if (axisValue.format2.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } if ((axisValue.format2.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format1.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format2.valueNameID)) { return true; } if (!(axisValue.format2.rangeMinValue <= axisValue.format2.nominalValue && axisValue.format2.nominalValue <= axisValue.format2.rangeMaxValue)) { Warning("Bad axis value range or nominal value"); } break; case 3: if (!table.ReadU16(&axisValue.format3.axisIndex) || !table.ReadU16(&axisValue.format3.flags) || !table.ReadU16(&axisValue.format3.valueNameID) || !table.ReadS32(&axisValue.format3.value) || !table.ReadS32(&axisValue.format3.linkedValue)) { return Drop("Failed to read axis value (format 3)"); } if (axisValue.format3.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } if ((axisValue.format3.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format3.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format3.valueNameID)) { return true; } break; case 4: if (this->minorVersion < 2) { Warning("Invalid table version for format 4 axis values - updating"); this->minorVersion = 2; } if (!table.ReadU16(&axisValue.format4.axisCount) || !table.ReadU16(&axisValue.format4.flags) || !table.ReadU16(&axisValue.format4.valueNameID)) { return Drop("Failed to read axis value (format 4)"); } if (axisValue.format4.axisCount > this->designAxisCount) { return Drop("Axis count out of range"); } if ((axisValue.format4.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format4.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format4.valueNameID)) { return true; } for (unsigned j = 0; j < axisValue.format4.axisCount; j++) { axisValue.format4.axisValues.emplace_back(); auto& v = axisValue.format4.axisValues[j]; if (!table.ReadU16(&v.axisIndex) || !table.ReadS32(&v.value)) { return Drop("Failed to read axis value"); } if (v.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } } break; default: return Drop("Unknown axis value format"); } } return true; } bool OpenTypeSTAT::Serialize(OTSStream* out) { off_t tableStart = out->Tell(); size_t headerSize = 5 * sizeof(uint16_t) + 2 * sizeof(uint32_t); if (this->minorVersion >= 1) { headerSize += sizeof(uint16_t); } if (this->designAxisCount == 0) { this->designAxesOffset = 0; } else { this->designAxesOffset = headerSize; } this->designAxisSize = sizeof(AxisRecord); if (this->axisValueCount == 0) { this->offsetToAxisValueOffsets = 0; } else { if (this->designAxesOffset == 0) { this->offsetToAxisValueOffsets = headerSize; } else { this->offsetToAxisValueOffsets = this->designAxesOffset + this->designAxisCount * this->designAxisSize; } } if (!out->WriteU16(this->majorVersion) || !out->WriteU16(this->minorVersion) || !out->WriteU16(this->designAxisSize) || !out->WriteU16(this->designAxisCount) || !out->WriteU32(this->designAxesOffset) || !out->WriteU16(this->axisValueCount) || !out->WriteU32(this->offsetToAxisValueOffsets) || !(this->minorVersion < 1 || out->WriteU16(this->elidedFallbackNameID))) { return Error("Failed to write table header"); } if (this->designAxisCount > 0) { if (out->Tell() - tableStart != this->designAxesOffset) { return Error("Error computing designAxesOffset"); } } for (unsigned i = 0; i < this->designAxisCount; i++) { const auto& axis = this->designAxes[i]; if (!out->WriteU32(axis.axisTag) || !out->WriteU16(axis.axisNameID) || !out->WriteU16(axis.axisOrdering)) { return Error("Failed to write design axis"); } } if (this->axisValueCount > 0) { if (out->Tell() - tableStart != this->offsetToAxisValueOffsets) { return Error("Error computing offsetToAxisValueOffsets"); } } uint32_t axisValueOffset = this->axisValueCount * sizeof(uint16_t); for (unsigned i = 0; i < this->axisValueCount; i++) { const auto& value = this->axisValues[i]; if (!out->WriteU16(axisValueOffset)) { return Error("Failed to write axis value offset"); } axisValueOffset += value.Length(); } for (unsigned i = 0; i < this->axisValueCount; i++) { const auto& value = this->axisValues[i]; if (!out->WriteU16(value.format)) { return Error("Failed to write axis value"); } switch (value.format) { case 1: if (!out->WriteU16(value.format1.axisIndex) || !out->WriteU16(value.format1.flags) || !out->WriteU16(value.format1.valueNameID) || !out->WriteS32(value.format1.value)) { return Error("Failed to write axis value"); } break; case 2: if (!out->WriteU16(value.format2.axisIndex) || !out->WriteU16(value.format2.flags) || !out->WriteU16(value.format2.valueNameID) || !out->WriteS32(value.format2.nominalValue) || !out->WriteS32(value.format2.rangeMinValue) || !out->WriteS32(value.format2.rangeMaxValue)) { return Error("Failed to write axis value"); } break; case 3: if (!out->WriteU16(value.format3.axisIndex) || !out->WriteU16(value.format3.flags) || !out->WriteU16(value.format3.valueNameID) || !out->WriteS32(value.format3.value) || !out->WriteS32(value.format3.linkedValue)) { return Error("Failed to write axis value"); } break; case 4: if (!out->WriteU16(value.format4.axisCount) || !out->WriteU16(value.format4.flags) || !out->WriteU16(value.format4.valueNameID)) { return Error("Failed to write axis value"); } for (unsigned j = 0; j < value.format4.axisValues.size(); j++) { if (!out->WriteU16(value.format4.axisValues[j].axisIndex) || !out->WriteS32(value.format4.axisValues[j].value)) { return Error("Failed to write axis value"); } } break; default: return Error("Bad value format"); } } return true; } } // namespace ots <commit_msg>[STAT] Add null-check to silence coverity warning<commit_after>// Copyright (c) 2018 The OTS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "stat.h" #include "name.h" namespace ots { // ----------------------------------------------------------------------------- // OpenTypeSTAT // ----------------------------------------------------------------------------- bool OpenTypeSTAT::ValidateNameId(uint16_t nameid, bool allowPredefined) { OpenTypeNAME* name = static_cast<OpenTypeNAME*>( GetFont()->GetTypedTable(OTS_TAG_NAME)); if (!name || !name->IsValidNameId(nameid)) { Drop("Invalid nameID: %d", nameid); return false; } if (!allowPredefined && nameid < 26) { Warning("nameID out of range: %d", nameid); return true; } if ((nameid >= 26 && nameid <= 255) || nameid >= 32768) { Warning("nameID out of range: %d", nameid); return true; } return true; } bool OpenTypeSTAT::Parse(const uint8_t* data, size_t length) { Buffer table(data, length); if (!table.ReadU16(&this->majorVersion) || !table.ReadU16(&this->minorVersion) || !table.ReadU16(&this->designAxisSize) || !table.ReadU16(&this->designAxisCount) || !table.ReadU32(&this->designAxesOffset) || !table.ReadU16(&this->axisValueCount) || !table.ReadU32(&this->offsetToAxisValueOffsets) || !(this->minorVersion < 1 || table.ReadU16(&this->elidedFallbackNameID))) { return Drop("Failed to read table header"); } if (this->majorVersion != 1) { return Drop("Unknown table version"); } if (this->minorVersion > 2) { Warning("Unknown minor version, downgrading to 2"); this->minorVersion = 2; } if (this->designAxisSize < sizeof(AxisRecord)) { return Drop("Invalid designAxisSize"); } size_t headerEnd = table.offset(); if (this->designAxisCount == 0) { if (this->designAxesOffset != 0) { Warning("Unexpected non-zero designAxesOffset"); this->designAxesOffset = 0; } } else { if (this->designAxesOffset < headerEnd || size_t(this->designAxesOffset) + size_t(this->designAxisCount) * size_t(this->designAxisSize) > length) { return Drop("Invalid designAxesOffset"); } } for (size_t i = 0; i < this->designAxisCount; i++) { table.set_offset(this->designAxesOffset + i * this->designAxisSize); this->designAxes.emplace_back(); auto& axis = this->designAxes[i]; if (!table.ReadU32(&axis.axisTag) || !table.ReadU16(&axis.axisNameID) || !table.ReadU16(&axis.axisOrdering)) { return Drop("Failed to read design axis"); } if (!CheckTag(axis.axisTag)) { return Drop("Bad design axis tag"); } if (!ValidateNameId(axis.axisNameID, false)) { return true; } } // TODO // - check that all axes defined in fvar are covered by STAT // - check that axisOrdering values are not duplicated (warn only) if (this->axisValueCount == 0) { if (this->offsetToAxisValueOffsets != 0) { Warning("Unexpected non-zero offsetToAxisValueOffsets"); this->offsetToAxisValueOffsets = 0; } } else { if (this->offsetToAxisValueOffsets < headerEnd || size_t(this->offsetToAxisValueOffsets) + size_t(this->axisValueCount) * sizeof(uint16_t) > length) { return Drop("Invalid offsetToAxisValueOffsets"); } } for (size_t i = 0; i < this->axisValueCount; i++) { table.set_offset(this->offsetToAxisValueOffsets + i * sizeof(uint16_t)); uint16_t axisValueOffset; if (!table.ReadU16(&axisValueOffset)) { return Drop("Failed to read axis value offset"); } if (this->offsetToAxisValueOffsets + axisValueOffset > length) { return Drop("Invalid axis value offset"); } table.set_offset(this->offsetToAxisValueOffsets + axisValueOffset); uint16_t format; if (!table.ReadU16(&format)) { return Drop("Failed to read axis value format"); } this->axisValues.emplace_back(format); auto& axisValue = axisValues[i]; switch (format) { case 1: if (!table.ReadU16(&axisValue.format1.axisIndex) || !table.ReadU16(&axisValue.format1.flags) || !table.ReadU16(&axisValue.format1.valueNameID) || !table.ReadS32(&axisValue.format1.value)) { return Drop("Failed to read axis value (format 1)"); } if (axisValue.format1.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } if ((axisValue.format1.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format1.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format1.valueNameID)) { return true; } break; case 2: if (!table.ReadU16(&axisValue.format2.axisIndex) || !table.ReadU16(&axisValue.format2.flags) || !table.ReadU16(&axisValue.format2.valueNameID) || !table.ReadS32(&axisValue.format2.nominalValue) || !table.ReadS32(&axisValue.format2.rangeMinValue) || !table.ReadS32(&axisValue.format2.rangeMaxValue)) { return Drop("Failed to read axis value (format 2)"); } if (axisValue.format2.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } if ((axisValue.format2.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format1.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format2.valueNameID)) { return true; } if (!(axisValue.format2.rangeMinValue <= axisValue.format2.nominalValue && axisValue.format2.nominalValue <= axisValue.format2.rangeMaxValue)) { Warning("Bad axis value range or nominal value"); } break; case 3: if (!table.ReadU16(&axisValue.format3.axisIndex) || !table.ReadU16(&axisValue.format3.flags) || !table.ReadU16(&axisValue.format3.valueNameID) || !table.ReadS32(&axisValue.format3.value) || !table.ReadS32(&axisValue.format3.linkedValue)) { return Drop("Failed to read axis value (format 3)"); } if (axisValue.format3.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } if ((axisValue.format3.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format3.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format3.valueNameID)) { return true; } break; case 4: if (this->minorVersion < 2) { Warning("Invalid table version for format 4 axis values - updating"); this->minorVersion = 2; } if (!table.ReadU16(&axisValue.format4.axisCount) || !table.ReadU16(&axisValue.format4.flags) || !table.ReadU16(&axisValue.format4.valueNameID)) { return Drop("Failed to read axis value (format 4)"); } if (axisValue.format4.axisCount > this->designAxisCount) { return Drop("Axis count out of range"); } if ((axisValue.format4.flags & 0xFFFCu) != 0) { Warning("Unexpected axis value flags"); axisValue.format4.flags &= ~0xFFFCu; } if (!ValidateNameId(axisValue.format4.valueNameID)) { return true; } for (unsigned j = 0; j < axisValue.format4.axisCount; j++) { axisValue.format4.axisValues.emplace_back(); auto& v = axisValue.format4.axisValues[j]; if (!table.ReadU16(&v.axisIndex) || !table.ReadS32(&v.value)) { return Drop("Failed to read axis value"); } if (v.axisIndex >= this->designAxisCount) { return Drop("Axis index out of range"); } } break; default: return Drop("Unknown axis value format"); } } return true; } bool OpenTypeSTAT::Serialize(OTSStream* out) { off_t tableStart = out->Tell(); size_t headerSize = 5 * sizeof(uint16_t) + 2 * sizeof(uint32_t); if (this->minorVersion >= 1) { headerSize += sizeof(uint16_t); } if (this->designAxisCount == 0) { this->designAxesOffset = 0; } else { this->designAxesOffset = headerSize; } this->designAxisSize = sizeof(AxisRecord); if (this->axisValueCount == 0) { this->offsetToAxisValueOffsets = 0; } else { if (this->designAxesOffset == 0) { this->offsetToAxisValueOffsets = headerSize; } else { this->offsetToAxisValueOffsets = this->designAxesOffset + this->designAxisCount * this->designAxisSize; } } if (!out->WriteU16(this->majorVersion) || !out->WriteU16(this->minorVersion) || !out->WriteU16(this->designAxisSize) || !out->WriteU16(this->designAxisCount) || !out->WriteU32(this->designAxesOffset) || !out->WriteU16(this->axisValueCount) || !out->WriteU32(this->offsetToAxisValueOffsets) || !(this->minorVersion < 1 || out->WriteU16(this->elidedFallbackNameID))) { return Error("Failed to write table header"); } if (this->designAxisCount > 0) { if (out->Tell() - tableStart != this->designAxesOffset) { return Error("Error computing designAxesOffset"); } } for (unsigned i = 0; i < this->designAxisCount; i++) { const auto& axis = this->designAxes[i]; if (!out->WriteU32(axis.axisTag) || !out->WriteU16(axis.axisNameID) || !out->WriteU16(axis.axisOrdering)) { return Error("Failed to write design axis"); } } if (this->axisValueCount > 0) { if (out->Tell() - tableStart != this->offsetToAxisValueOffsets) { return Error("Error computing offsetToAxisValueOffsets"); } } uint32_t axisValueOffset = this->axisValueCount * sizeof(uint16_t); for (unsigned i = 0; i < this->axisValueCount; i++) { const auto& value = this->axisValues[i]; if (!out->WriteU16(axisValueOffset)) { return Error("Failed to write axis value offset"); } axisValueOffset += value.Length(); } for (unsigned i = 0; i < this->axisValueCount; i++) { const auto& value = this->axisValues[i]; if (!out->WriteU16(value.format)) { return Error("Failed to write axis value"); } switch (value.format) { case 1: if (!out->WriteU16(value.format1.axisIndex) || !out->WriteU16(value.format1.flags) || !out->WriteU16(value.format1.valueNameID) || !out->WriteS32(value.format1.value)) { return Error("Failed to write axis value"); } break; case 2: if (!out->WriteU16(value.format2.axisIndex) || !out->WriteU16(value.format2.flags) || !out->WriteU16(value.format2.valueNameID) || !out->WriteS32(value.format2.nominalValue) || !out->WriteS32(value.format2.rangeMinValue) || !out->WriteS32(value.format2.rangeMaxValue)) { return Error("Failed to write axis value"); } break; case 3: if (!out->WriteU16(value.format3.axisIndex) || !out->WriteU16(value.format3.flags) || !out->WriteU16(value.format3.valueNameID) || !out->WriteS32(value.format3.value) || !out->WriteS32(value.format3.linkedValue)) { return Error("Failed to write axis value"); } break; case 4: if (!out->WriteU16(value.format4.axisCount) || !out->WriteU16(value.format4.flags) || !out->WriteU16(value.format4.valueNameID)) { return Error("Failed to write axis value"); } for (unsigned j = 0; j < value.format4.axisValues.size(); j++) { if (!out->WriteU16(value.format4.axisValues[j].axisIndex) || !out->WriteS32(value.format4.axisValues[j].value)) { return Error("Failed to write axis value"); } } break; default: return Error("Bad value format"); } } return true; } } // namespace ots <|endoftext|>
<commit_before>b0c8dc2e-2e4d-11e5-9284-b827eb9e62be<commit_msg>b0cddee0-2e4d-11e5-9284-b827eb9e62be<commit_after>b0cddee0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* * Copyright 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include <boost/algorithm/cxx11/any_of.hpp> #include <boost/range/irange.hpp> #include <vector> #include <random> #include "utils/dynamic_bitset.hh" BOOST_AUTO_TEST_CASE(test_set_clear_test) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } for (size_t i = 0; i < 178; i += 2) { bits.set(i); } for (size_t i = 0; i < 178; i++) { if (i % 2) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } for (size_t i = 0; i < 178; i++) { if (i % 2 || i % 4 == 0) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } } BOOST_AUTO_TEST_CASE(test_find_first_next) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_first_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 0); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 2, j); i = j; } while (i < 176); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 2); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 4, j); i = j; } while (i < 174); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); } BOOST_AUTO_TEST_CASE(test_find_last_prev) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_last_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 176); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 174); } static void test_random_ops(size_t size, std::random_device& rd ) { // BOOST_REQUIRE and friends are very slow, just use regular throws instead. auto require = [] (bool b) { if (!b) { throw 0; } }; auto require_equal = [&] (const auto& a, const auto& b) { require(a == b); }; utils::dynamic_bitset db{size}; std::vector<bool> bv(size, false); std::uniform_int_distribution<size_t> global_op_dist(0, size-1); std::uniform_int_distribution<size_t> bit_dist(0, size-1); std::uniform_int_distribution<int> global_op_selection_dist(0, 1); std::uniform_int_distribution<int> single_op_selection_dist(0, 5); auto is_set = [&] (size_t i) -> bool { return bv[i]; }; size_t limit = size * 100; #ifdef SEASTAR_DEBUG limit = std::min<size_t>(limit, 20000); #endif for (size_t i = 0; i != limit; ++i) { if (global_op_dist(rd) == 0) { // perform a global operation switch (global_op_selection_dist(rd)) { case 0: for (size_t j = 0; j != size; ++j) { db.clear(j); bv[j] = false; } break; case 1: for (size_t j = 0; j != size; ++j) { db.set(j); bv[j] = true; } break; } } else { // perform a single-bit operation switch (single_op_selection_dist(rd)) { case 0: { auto bit = bit_dist(rd); db.set(bit); bv[bit] = true; break; } case 1: { auto bit = bit_dist(rd); db.clear(bit); bv[bit] = false; break; } case 2: { auto bit = bit_dist(rd); bool dbb = db.test(bit); bool bvb = bv[bit]; require_equal(dbb, bvb); break; } case 3: { auto bit = bit_dist(rd); auto next = db.find_next_set(bit); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(bit+1, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(bit+1, next), is_set)); require(is_set(next)); } break; } case 4: { auto next = db.find_first_set(); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(0, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(0, next), is_set)); require(is_set(next)); } break; } case 5: { auto next = db.find_last_set(); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(0, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(next + 1, size), is_set)); require(is_set(next)); } break; } } } } } BOOST_AUTO_TEST_CASE(test_random_operations) { std::random_device rd; for (auto size : { 1, 63, 64, 65, 2000, 4096-65, 4096-64, 4096-63, 4096-1, 4096, 4096+1, 262144-1, 262144, 262144+1}) { BOOST_CHECK_NO_THROW(test_random_ops(size, rd)); } } <commit_msg>tests: reduce the number of iterations of dynamic_bitset_test<commit_after>/* * Copyright 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include <boost/algorithm/cxx11/any_of.hpp> #include <boost/range/irange.hpp> #include <vector> #include <random> #include "utils/dynamic_bitset.hh" BOOST_AUTO_TEST_CASE(test_set_clear_test) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } for (size_t i = 0; i < 178; i += 2) { bits.set(i); } for (size_t i = 0; i < 178; i++) { if (i % 2) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } for (size_t i = 0; i < 178; i++) { if (i % 2 || i % 4 == 0) { BOOST_REQUIRE(!bits.test(i)); } else { BOOST_REQUIRE(bits.test(i)); } } } BOOST_AUTO_TEST_CASE(test_find_first_next) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_first_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 0); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 2, j); i = j; } while (i < 176); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_first_set(); BOOST_REQUIRE_EQUAL(i, 2); do { auto j = bits.find_next_set(i); BOOST_REQUIRE_EQUAL(i + 4, j); i = j; } while (i < 174); BOOST_REQUIRE_EQUAL(bits.find_next_set(i), utils::dynamic_bitset::npos); } BOOST_AUTO_TEST_CASE(test_find_last_prev) { utils::dynamic_bitset bits(178); for (size_t i = 0; i < 178; i++) { BOOST_REQUIRE(!bits.test(i)); } BOOST_REQUIRE_EQUAL(bits.find_last_set(), utils::dynamic_bitset::npos); for (size_t i = 0; i < 178; i += 2) { bits.set(i); } size_t i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 176); for (size_t i = 0; i < 178; i += 4) { bits.clear(i); } i = bits.find_last_set(); BOOST_REQUIRE_EQUAL(i, 174); } static void test_random_ops(size_t size, std::random_device& rd ) { // BOOST_REQUIRE and friends are very slow, just use regular throws instead. auto require = [] (bool b) { if (!b) { throw 0; } }; auto require_equal = [&] (const auto& a, const auto& b) { require(a == b); }; utils::dynamic_bitset db{size}; std::vector<bool> bv(size, false); std::uniform_int_distribution<size_t> global_op_dist(0, size-1); std::uniform_int_distribution<size_t> bit_dist(0, size-1); std::uniform_int_distribution<int> global_op_selection_dist(0, 1); std::uniform_int_distribution<int> single_op_selection_dist(0, 5); auto is_set = [&] (size_t i) -> bool { return bv[i]; }; size_t limit = std::log(size) * 1000; for (size_t i = 0; i != limit; ++i) { if (global_op_dist(rd) == 0) { // perform a global operation switch (global_op_selection_dist(rd)) { case 0: for (size_t j = 0; j != size; ++j) { db.clear(j); bv[j] = false; } break; case 1: for (size_t j = 0; j != size; ++j) { db.set(j); bv[j] = true; } break; } } else { // perform a single-bit operation switch (single_op_selection_dist(rd)) { case 0: { auto bit = bit_dist(rd); db.set(bit); bv[bit] = true; break; } case 1: { auto bit = bit_dist(rd); db.clear(bit); bv[bit] = false; break; } case 2: { auto bit = bit_dist(rd); bool dbb = db.test(bit); bool bvb = bv[bit]; require_equal(dbb, bvb); break; } case 3: { auto bit = bit_dist(rd); auto next = db.find_next_set(bit); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(bit+1, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(bit+1, next), is_set)); require(is_set(next)); } break; } case 4: { auto next = db.find_first_set(); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(0, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(0, next), is_set)); require(is_set(next)); } break; } case 5: { auto next = db.find_last_set(); if (next == db.npos) { require(!boost::algorithm::any_of(boost::irange<size_t>(0, size), is_set)); } else { require(!boost::algorithm::any_of(boost::irange<size_t>(next + 1, size), is_set)); require(is_set(next)); } break; } } } } } BOOST_AUTO_TEST_CASE(test_random_operations) { std::random_device rd; for (auto size : { 1, 63, 64, 65, 2000, 4096-65, 4096-64, 4096-63, 4096-1, 4096, 4096+1, 262144-1, 262144, 262144+1}) { BOOST_CHECK_NO_THROW(test_random_ops(size, rd)); } } <|endoftext|>
<commit_before>#include "openslideobject.h" Nan::Persistent<v8::Function> OpenSlideObject::constructor; OpenSlideObject::OpenSlideObject(string fileName) { _fileName = fileName; } OpenSlideObject::~OpenSlideObject() { if (_osr != NULL) { openslide_close(_osr); } } void OpenSlideObject::Init(v8::Local<v8::Object> exports) { Nan::HandleScope scope; // Prepare constructor template v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("OpenSlideObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl,"open",Open); constructor.Reset(tpl->GetFunction()); exports->Set(Nan::New("OpenSlideObject").ToLocalChecked(), tpl->GetFunction()); } void OpenSlideObject::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if (info.IsConstructCall()) { // Invoked as constructor: `new OpenSlideObject(...)` v8::String::Utf8Value val(info[0]->ToString()); std::string filePath (*val); OpenSlideObject *obj = new OpenSlideObject(filePath); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { // Invoked as plain function `OpenSlideObject(...)`, turn into construct call. const int argc = 1; v8::Local<v8::Value> argv[argc] = { info[0] }; v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); info.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } void OpenSlideObject::Open(const Nan::FunctionCallbackInfo<v8::Value>& info) { OpenSlideObject *obj = ObjectWrap::Unwrap<OpenSlideObject>(info.Holder()); openslide_t *osr = openslide_open(obj->_fileName.c_str()); bool success = osr != NULL; if (!success) { info.GetReturnValue().Set(Nan::New(success)); return; } // Assign osr to member variable obj->_osr = osr; // Store level count int32_t levelCount = openslide_get_level_count(osr); obj->_levelCount = levelCount; // Store dimensions for (int i = 0; i < levelCount; i++) { int64_t w, h; double downsample; openslide_get_level_dimensions(osr,i,&w,&h); downsample = openslide_get_level_downsample(osr,i); obj->_levelWidths.push_back(w); obj->_levelHeights.push_back(h); obj->_levelDownsamples.push_back(downsample); } // Properties const char* const *pNames = openslide_get_property_names(osr); int i = 0; while (pNames[i] != 0) { const char *pValue = openslide_get_property_value(osr,pNames[i]); obj->_properties[pNames[i]] = pValue; } // Return success info.GetReturnValue().Set(Nan::New(success)); }<commit_msg>Fix get properties error<commit_after>#include "openslideobject.h" Nan::Persistent<v8::Function> OpenSlideObject::constructor; OpenSlideObject::OpenSlideObject(string fileName) { _fileName = fileName; } OpenSlideObject::~OpenSlideObject() { if (_osr != NULL) { openslide_close(_osr); } } void OpenSlideObject::Init(v8::Local<v8::Object> exports) { Nan::HandleScope scope; // Prepare constructor template v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("OpenSlideObject").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl,"open",Open); constructor.Reset(tpl->GetFunction()); exports->Set(Nan::New("OpenSlideObject").ToLocalChecked(), tpl->GetFunction()); } void OpenSlideObject::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if (info.IsConstructCall()) { // Invoked as constructor: `new OpenSlideObject(...)` v8::String::Utf8Value val(info[0]->ToString()); std::string filePath (*val); OpenSlideObject *obj = new OpenSlideObject(filePath); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } else { // Invoked as plain function `OpenSlideObject(...)`, turn into construct call. const int argc = 1; v8::Local<v8::Value> argv[argc] = { info[0] }; v8::Local<v8::Function> cons = Nan::New<v8::Function>(constructor); info.GetReturnValue().Set(cons->NewInstance(argc, argv)); } } void OpenSlideObject::Open(const Nan::FunctionCallbackInfo<v8::Value>& info) { OpenSlideObject *obj = ObjectWrap::Unwrap<OpenSlideObject>(info.Holder()); openslide_t *osr = openslide_open(obj->_fileName.c_str()); bool success = osr != NULL; if (!success) { info.GetReturnValue().Set(Nan::New(success)); return; } info.GetReturnValue().Set(Nan::New(success)); return; // Assign osr to member variable obj->_osr = osr; // Store level count int32_t levelCount = openslide_get_level_count(osr); obj->_levelCount = levelCount; // Store dimensions for (int i = 0; i < levelCount; i++) { int64_t w, h; double downsample; openslide_get_level_dimensions(osr,i,&w,&h); downsample = openslide_get_level_downsample(osr,i); obj->_levelWidths.push_back(w); obj->_levelHeights.push_back(h); obj->_levelDownsamples.push_back(downsample); } // Properties const char* const *pNames = openslide_get_property_names(osr); int i = 0; while (pNames[i] != 0) { const char *pValue = openslide_get_property_value(osr,pNames[i]); obj->_properties[pNames[i]] = pValue; i++; } // Return success info.GetReturnValue().Set(Nan::New(success)); }<|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <utility> // template <class T, class U> struct pair; // pair(pair const&) = default; // pair(pair &&) = default; // pair& operator=(pair const&); // pair& operator=(pair&&); // Test that the copy/move constructors and assignment operators are // correctly defined or deleted based on the properties of `T` and `U`. #include <cassert> #include <string> #include <tuple> #include "archetypes.hpp" namespace ConstructorTest { template <class T1, bool CanCopy = true, bool CanMove = CanCopy> void test() { using P1 = std::pair<T1, int>; using P2 = std::pair<int, T1>; static_assert(std::is_copy_constructible<P1>::value == CanCopy); static_assert(std::is_move_constructible<P1>::value == CanMove); static_assert(std::is_copy_constructible<P2>::value == CanCopy); static_assert(std::is_move_constructible<P2>::value == CanMove); }; } // namespace ConstructorTest void test_constructors_exist() { using namespace ConstructorTest; { test<int>(); test<int &>(); test<int &&, false, true>(); test<const int>(); test<const int &>(); test<const int &&, false, true>(); } { test<Copyable>(); test<Copyable &>(); test<Copyable &&, false, true>(); } { test<NonCopyable, false>(); test<NonCopyable &, true>(); test<NonCopyable &&, false, true>(); } { // Even though CopyOnly has an explicitly deleted move constructor // pair's move constructor is only implicitly deleted and therefore // it doesn't participate in overload resolution. test<CopyOnly, true, true>(); test<CopyOnly &, true>(); test<CopyOnly &&, false, true>(); } { test<MoveOnly, false, true>(); test<MoveOnly &, true>(); test<MoveOnly &&, false, true>(); } } namespace AssignmentOperatorTest { template <class T1, bool CanCopy = true, bool CanMove = CanCopy> void test() { using P1 = std::pair<T1, int>; using P2 = std::pair<int, T1>; static_assert(std::is_copy_assignable<P1>::value == CanCopy); static_assert(std::is_move_assignable<P1>::value == CanMove); static_assert(std::is_copy_assignable<P2>::value == CanCopy); static_assert(std::is_move_assignable<P2>::value == CanMove); }; } // namespace AssignmentOperatorTest void test_assignment_operator_exists() { using namespace AssignmentOperatorTest; { test<int>(); test<int &>(); test<int &&>(); test<const int, false>(); test<const int &, false>(); test<const int &&, false>(); } { test<Copyable>(); test<Copyable &>(); test<Copyable &&>(); } { test<NonCopyable, false>(); test<NonCopyable &, false>(); test<NonCopyable &&, false>(); } { test<CopyOnly, true>(); test<CopyOnly &, true>(); test<CopyOnly &&, true>(); } { test<MoveOnly, false, true>(); test<MoveOnly &, false, false>(); test<MoveOnly &&, false, true>(); } } int main() { test_constructors_exist(); test_assignment_operator_exists(); } <commit_msg>Remove use of C++1z static assert in C++11 test<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03 // <utility> // template <class T, class U> struct pair; // pair(pair const&) = default; // pair(pair &&) = default; // pair& operator=(pair const&); // pair& operator=(pair&&); // Test that the copy/move constructors and assignment operators are // correctly defined or deleted based on the properties of `T` and `U`. #include <cassert> #include <string> #include <tuple> #include "archetypes.hpp" namespace ConstructorTest { template <class T1, bool CanCopy = true, bool CanMove = CanCopy> void test() { using P1 = std::pair<T1, int>; using P2 = std::pair<int, T1>; static_assert(std::is_copy_constructible<P1>::value == CanCopy, ""); static_assert(std::is_move_constructible<P1>::value == CanMove, ""); static_assert(std::is_copy_constructible<P2>::value == CanCopy, ""); static_assert(std::is_move_constructible<P2>::value == CanMove, ""); }; } // namespace ConstructorTest void test_constructors_exist() { using namespace ConstructorTest; { test<int>(); test<int &>(); test<int &&, false, true>(); test<const int>(); test<const int &>(); test<const int &&, false, true>(); } { test<Copyable>(); test<Copyable &>(); test<Copyable &&, false, true>(); } { test<NonCopyable, false>(); test<NonCopyable &, true>(); test<NonCopyable &&, false, true>(); } { // Even though CopyOnly has an explicitly deleted move constructor // pair's move constructor is only implicitly deleted and therefore // it doesn't participate in overload resolution. test<CopyOnly, true, true>(); test<CopyOnly &, true>(); test<CopyOnly &&, false, true>(); } { test<MoveOnly, false, true>(); test<MoveOnly &, true>(); test<MoveOnly &&, false, true>(); } } namespace AssignmentOperatorTest { template <class T1, bool CanCopy = true, bool CanMove = CanCopy> void test() { using P1 = std::pair<T1, int>; using P2 = std::pair<int, T1>; static_assert(std::is_copy_assignable<P1>::value == CanCopy, ""); static_assert(std::is_move_assignable<P1>::value == CanMove, ""); static_assert(std::is_copy_assignable<P2>::value == CanCopy, ""); static_assert(std::is_move_assignable<P2>::value == CanMove, ""); }; } // namespace AssignmentOperatorTest void test_assignment_operator_exists() { using namespace AssignmentOperatorTest; { test<int>(); test<int &>(); test<int &&>(); test<const int, false>(); test<const int &, false>(); test<const int &&, false>(); } { test<Copyable>(); test<Copyable &>(); test<Copyable &&>(); } { test<NonCopyable, false>(); test<NonCopyable &, false>(); test<NonCopyable &&, false>(); } { test<CopyOnly, true>(); test<CopyOnly &, true>(); test<CopyOnly &&, true>(); } { test<MoveOnly, false, true>(); test<MoveOnly &, false, false>(); test<MoveOnly &&, false, true>(); } } int main() { test_constructors_exist(); test_assignment_operator_exists(); } <|endoftext|>
<commit_before>namespace mimosa { template <typename Value, StringRef (*GetKey)(Value value)> inline Trie<Value, GetKey>::Trie(uint32_t depth) : value_(), childs_(nullptr), depth_(depth), size_(0) { } template <typename Value, StringRef (*GetKey)(Value value)> inline Trie<Value, GetKey>::~Trie() { clear(); } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::clear() { if (childs_) { for (int i = 0; i < 256; ++i) delete childs_[i]; free(childs_); childs_ = nullptr; } } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::allocateChilds() { assert(!childs_); childs_ = (Trie<Value, GetKey>**)calloc(sizeof (*childs_), 256); // check if value_ should go to childs_ if (!value_) return; StringRef key = GetKey(value_); if (key.size() == depth_) return; insert(key, value_); value_ = nullptr; --size_; } template <typename Value, StringRef (*GetKey)(Value value)> inline bool Trie<Value, GetKey>::insert(const StringRef & key, Value value) { assert(key.size() >= depth_); if (key.size() == depth_) { if (!value_) { value_ = value; ++size_; return true; } if (GetKey(value_).size() > depth_) { std::swap(value, value_); insert(value); return true; } return false; } if (!value_ && !childs_) { value_ = value; ++size_; return true; } if (!childs_) allocateChilds(); if (!childs_[(uint8_t)key[depth_]]) childs_[(uint8_t)key[depth_]] = new Trie<Value, GetKey>(depth_ + 1); if (!childs_[(uint8_t)key[depth_]]->insert(key, value)) return false; ++size_; return true; } template <typename Value, StringRef (*GetKey)(Value value)> inline Value Trie<Value, GetKey>::find(const StringRef & key) const { assert(key.size() >= depth_); if (key.size() == depth_) { if (value_) return value_; return nullptr; } if (!childs_ || !childs_[(uint8_t)key[depth_]]) return nullptr; return childs_[(uint8_t)key[depth_]]->find(key); } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::erase(const StringRef & key) { if (key.size() == depth_) { value_ = nullptr; --size_; return; } if (!childs_ || !childs_[(uint8_t)key[depth_]]) return; childs_[(uint8_t)key[depth_]]->erase(key); --size_; if (childs_[(uint8_t)key[depth_]]->empty()) { delete childs_[(uint8_t)key[depth_]]; childs_[(uint8_t)key[depth_]] = nullptr; } } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::foreach(const std::function<void (Value)> & callback) const { if (value_) callback(value_); if (childs_) for (int i = 0; i < 256; ++i) if (childs_[i]) childs_[i]->foreach(callback); } } <commit_msg>Trie: fix a bug in insert() and remove()<commit_after>namespace mimosa { template <typename Value, StringRef (*GetKey)(Value value)> inline Trie<Value, GetKey>::Trie(uint32_t depth) : value_(), childs_(nullptr), depth_(depth), size_(0) { } template <typename Value, StringRef (*GetKey)(Value value)> inline Trie<Value, GetKey>::~Trie() { clear(); } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::clear() { if (childs_) { for (int i = 0; i < 256; ++i) delete childs_[i]; free(childs_); childs_ = nullptr; } } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::allocateChilds() { assert(!childs_); childs_ = (Trie<Value, GetKey>**)calloc(sizeof (*childs_), 256); // check if value_ should go to childs_ if (!value_) return; StringRef key = GetKey(value_); if (key.size() == depth_) return; insert(key, value_); value_ = nullptr; --size_; } template <typename Value, StringRef (*GetKey)(Value value)> inline bool Trie<Value, GetKey>::insert(const StringRef & key, Value value) { assert(key.size() >= depth_); if (key.size() == depth_) { if (!value_) { value_ = value; ++size_; return true; } if (GetKey(value_).size() > depth_) { std::swap(value, value_); insert(value); return true; } return false; } if (!value_ && !childs_) { value_ = value; ++size_; return true; } if (!childs_) allocateChilds(); if (!childs_[(uint8_t)key[depth_]]) childs_[(uint8_t)key[depth_]] = new Trie<Value, GetKey>(depth_ + 1); if (!childs_[(uint8_t)key[depth_]]->insert(key, value)) return false; ++size_; return true; } template <typename Value, StringRef (*GetKey)(Value value)> inline Value Trie<Value, GetKey>::find(const StringRef & key) const { assert(key.size() >= depth_); if (key.size() == depth_ || size_ == 1) { if (value_ && GetKey(value_) == key) return value_; return nullptr; } if (!childs_ || !childs_[(uint8_t)key[depth_]]) return nullptr; return childs_[(uint8_t)key[depth_]]->find(key); } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::erase(const StringRef & key) { if ((key.size() == depth_ || size_ == 1) && (value_ && GetKey(value_) == key)) { value_ = nullptr; --size_; return; } if (!childs_ || !childs_[(uint8_t)key[depth_]]) return; childs_[(uint8_t)key[depth_]]->erase(key); --size_; if (childs_[(uint8_t)key[depth_]]->empty()) { delete childs_[(uint8_t)key[depth_]]; childs_[(uint8_t)key[depth_]] = nullptr; } } template <typename Value, StringRef (*GetKey)(Value value)> inline void Trie<Value, GetKey>::foreach(const std::function<void (Value)> & callback) const { if (value_) callback(value_); if (childs_) for (int i = 0; i < 256; ++i) if (childs_[i]) childs_[i]->foreach(callback); } } <|endoftext|>
<commit_before>d576f650-2e4d-11e5-9284-b827eb9e62be<commit_msg>d57be804-2e4d-11e5-9284-b827eb9e62be<commit_after>d57be804-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Referenced> #include <osg/Notify> #include <typeinfo> namespace osg { static std::auto_ptr<DeleteHandler> s_deleteHandler(0); void Referenced::setDeleteHandler(DeleteHandler* handler) { // s_deleteHandler.reset(handler); } DeleteHandler* Referenced::getDeleteHandler() { return s_deleteHandler.get(); } Referenced::~Referenced() { if (_refCount>0) { notify(WARN)<<"Warning: deleting still referenced object "<<this<<" of type '"<<typeid(this).name()<<"'"<<std::endl; notify(WARN)<<" the final reference count was "<<_refCount<<", memory corruption possible."<<std::endl; } } }; // end of namespace osg <commit_msg>Added #include <memory> for Win32 build<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osg/Referenced> #include <osg/Notify> #include <typeinfo> #include <memory> namespace osg { static std::auto_ptr<DeleteHandler> s_deleteHandler(0); void Referenced::setDeleteHandler(DeleteHandler* handler) { // s_deleteHandler.reset(handler); } DeleteHandler* Referenced::getDeleteHandler() { return s_deleteHandler.get(); } Referenced::~Referenced() { if (_refCount>0) { notify(WARN)<<"Warning: deleting still referenced object "<<this<<" of type '"<<typeid(this).name()<<"'"<<std::endl; notify(WARN)<<" the final reference count was "<<_refCount<<", memory corruption possible."<<std::endl; } } }; // end of namespace osg <|endoftext|>
<commit_before>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file TransientDirectory.cpp * @author Marek Kotewicz <marek@ethdev.com> * @date 2015 */ #include <thread> #include <boost/filesystem.hpp> #include "Exceptions.h" #include "TransientDirectory.h" #include "CommonIO.h" using namespace std; using namespace dev; TransientDirectory::TransientDirectory(): TransientDirectory((boost::filesystem::temp_directory_path() / "eth_transient" / toString(FixedHash<4>::random())).string()) {} TransientDirectory::TransientDirectory(std::string const& _path): m_path(_path) { // we never ever want to delete a directory (including all its contents) that we did not create ourselves. if (boost::filesystem::exists(m_path)) BOOST_THROW_EXCEPTION(FileError()); boost::filesystem::create_directories(m_path); } TransientDirectory::~TransientDirectory() { for (int i = 0; i < 3; ++i) { try { boost::filesystem::remove_all(m_path); break; } catch (...) { this_thread::sleep_for(chrono::milliseconds(10)); } } } <commit_msg>Update TransientDirectory.cpp<commit_after>/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file TransientDirectory.cpp * @author Marek Kotewicz <marek@ethdev.com> * @date 2015 */ #include <thread> #include <boost/filesystem.hpp> #include "Exceptions.h" #include "TransientDirectory.h" #include "CommonIO.h" #include "Log.h" using namespace std; using namespace dev; TransientDirectory::TransientDirectory(): TransientDirectory((boost::filesystem::temp_directory_path() / "eth_transient" / toString(FixedHash<4>::random())).string()) {} TransientDirectory::TransientDirectory(std::string const& _path): m_path(_path) { // we never ever want to delete a directory (including all its contents) that we did not create ourselves. if (boost::filesystem::exists(m_path)) BOOST_THROW_EXCEPTION(FileError()); boost::filesystem::create_directories(m_path); } TransientDirectory::~TransientDirectory() { boost::system::error_code ec; boost::filesystem::remove_all(m_path, ec); if (0 == ec) return; // In some cases, antivirus runnig on Windows will scan all the newly created directories. // As a consequence, directory is locked and can not be deleted immediately. // Retry after 10 milliseconds usually is successful. // This will help our tests run smoothly in such environment. this_thread::sleep_for(chrono::milliseconds(10)); ec.clear(); boost::filesystem::remove_all(m_path, ec); if (ec != 0) cwarn << "Failed to delete directory '" << m_path << "': " << ec.message(); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 NorthScale, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "buckets.h" #include <assert.h> #include <iostream> #include <cassert> using namespace std; static void testSingleBucket() { vector<uint16_t> buckets; try { parseBuckets(buckets, "102"); } catch (string& e) { cerr << e.c_str() << std::endl; abort(); } assert(buckets.size() == 1); assert(buckets[0] == 102); } static void testMultipleBuckets() { vector<uint16_t> buckets; try { parseBuckets(buckets, "102, \t\n\r 103; 104 "); } catch (string& e) { cerr << e.c_str() << std::endl; abort(); } assert(buckets.size() == 3); assert(buckets[0] == 102); assert(buckets[1] == 103); assert(buckets[2] == 104); } static void testBucketRange() { vector<uint16_t> buckets; try { parseBuckets(buckets, "[102, \t\n\r 105]"); } catch (string& e) { cerr << e.c_str() << std::endl; abort(); } assert(buckets.size() == 4); assert(buckets[0] == 102); assert(buckets[1] == 103); assert(buckets[2] == 104); assert(buckets[3] == 105); } static void testIllegalSyntax() { vector<uint16_t> buckets; try { parseBuckets(buckets, "[102, 10 2]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "[102,,]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "[a,12]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "[1,a]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1,a,2,3"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1,,"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1,"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1 2 3"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, ""); abort(); } catch (string& e) { /* Success! */ } } int main(int argc, char **argv) { (void)argc; (void)argv; testSingleBucket(); testMultipleBuckets(); testBucketRange(); testIllegalSyntax(); return 0; } <commit_msg>need <cstdlib> for abort()<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2010 NorthScale, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "buckets.h" #include <assert.h> #include <iostream> #include <cassert> #include <cstdlib> using namespace std; static void testSingleBucket() { vector<uint16_t> buckets; try { parseBuckets(buckets, "102"); } catch (string& e) { cerr << e.c_str() << std::endl; abort(); } assert(buckets.size() == 1); assert(buckets[0] == 102); } static void testMultipleBuckets() { vector<uint16_t> buckets; try { parseBuckets(buckets, "102, \t\n\r 103; 104 "); } catch (string& e) { cerr << e.c_str() << std::endl; abort(); } assert(buckets.size() == 3); assert(buckets[0] == 102); assert(buckets[1] == 103); assert(buckets[2] == 104); } static void testBucketRange() { vector<uint16_t> buckets; try { parseBuckets(buckets, "[102, \t\n\r 105]"); } catch (string& e) { cerr << e.c_str() << std::endl; abort(); } assert(buckets.size() == 4); assert(buckets[0] == 102); assert(buckets[1] == 103); assert(buckets[2] == 104); assert(buckets[3] == 105); } static void testIllegalSyntax() { vector<uint16_t> buckets; try { parseBuckets(buckets, "[102, 10 2]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "[102,,]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "[a,12]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "[1,a]"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1,a,2,3"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1,,"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1,"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, "1 2 3"); abort(); } catch (string& e) { /* Success! */ } try { parseBuckets(buckets, ""); abort(); } catch (string& e) { /* Success! */ } } int main(int argc, char **argv) { (void)argc; (void)argv; testSingleBucket(); testMultipleBuckets(); testBucketRange(); testIllegalSyntax(); return 0; } <|endoftext|>
<commit_before>5fefa4a4-2e4d-11e5-9284-b827eb9e62be<commit_msg>5ff4ad1e-2e4d-11e5-9284-b827eb9e62be<commit_after>5ff4ad1e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2014 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUI/ComboBox> #include <osgText/String> #include <osgText/Font> #include <osgText/Text> #include <osg/Notify> #include <osg/io_utils> using namespace osgUI; ComboBox::ComboBox() { } ComboBox::ComboBox(const osgUI::ComboBox& combobox, const osg::CopyOp& copyop): Widget(combobox, copyop), _items(combobox._items) { } bool ComboBox::handleImplementation(osgGA::EventVisitor* ev, osgGA::Event* event) { // OSG_NOTICE<<"ComboBox::handleImplementation"<<std::endl; osgGA::GUIEventAdapter* ea = event->asGUIEventAdapter(); if (!ea) return false; switch(ea->getEventType()) { case(osgGA::GUIEventAdapter::SCROLL): OSG_NOTICE<<"Scroll "<<std::endl; if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_DOWN) { OSG_NOTICE<<"Scroll Down`"<<std::endl; if (getCurrentItem()<getNumItems()-1) setCurrentItem(getCurrentItem()+1); } else if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_UP) { OSG_NOTICE<<"Scroll Up`"<<std::endl; if (getCurrentItem()>0) setCurrentItem(getCurrentItem()-1); } break; case(osgGA::GUIEventAdapter::PUSH): OSG_NOTICE<<"Button pressed "<<std::endl; break; case(osgGA::GUIEventAdapter::RELEASE): OSG_NOTICE<<"Button release "<<std::endl; break; default: break; } return false; } void ComboBox::enterImplementation() { OSG_NOTICE<<"ComboBox enter"<<std::endl; } void ComboBox::leaveImplementation() { OSG_NOTICE<<"ComboBox leave"<<std::endl; } void ComboBox::setCurrentItem(unsigned int i) { OSG_NOTICE << "ComboBox::setCurrentItem("<<i<<")"<<std::endl; _currentItem = i; if (_switch.valid()) _switch->setSingleChildOn(_currentItem); } void ComboBox::createGraphicsImplementation() { if (_switch.valid() && _switch->getNumChildren()==_items.size()) { OSG_NOTICE<<"Need to update existing scene graph"<<std::endl; _graphicsInitialized = true; } else { OSG_NOTICE<<"ComboBox::createGraphicsImplementation()"<<std::endl; Widget::createGraphicsImplementation(); Style* style = (getStyle()!=0) ? getStyle() : Style::instance().get(); _switch = new osg::Switch; addChild(_switch.get()); if (!_items.empty()) { for(Items::iterator itr = _items.begin(); itr != _items.end(); ++itr) { Item* item = itr->get(); OSG_NOTICE<<"Creating item "<<item->getText()<<", "<<item->getColor()<<std::endl; osg::ref_ptr<osg::Group> group = new osg::Group; if (item->getColor().a()!=0.0f) group->addChild( style->createPanel(_extents, item->getColor()) ); if (!item->getText().empty()) group->addChild( style->createText(_extents, getAlignmentSettings(), getTextSettings(), item->getText()) ); _switch->addChild(group.get()); } } else { _switch->addChild( style->createPanel(_extents, osg::Vec4(1.0f,1.0f,1.0f,1.0f)) ); } _switch->setSingleChildOn(_currentItem); } } <commit_msg>Added handling of up/down key to ComboBox<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2014 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * 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 * OpenSceneGraph Public License for more details. */ #include <osgUI/ComboBox> #include <osgText/String> #include <osgText/Font> #include <osgText/Text> #include <osg/Notify> #include <osg/io_utils> using namespace osgUI; ComboBox::ComboBox() { } ComboBox::ComboBox(const osgUI::ComboBox& combobox, const osg::CopyOp& copyop): Widget(combobox, copyop), _items(combobox._items) { } bool ComboBox::handleImplementation(osgGA::EventVisitor* ev, osgGA::Event* event) { // OSG_NOTICE<<"ComboBox::handleImplementation"<<std::endl; osgGA::GUIEventAdapter* ea = event->asGUIEventAdapter(); if (!ea) return false; switch(ea->getEventType()) { case(osgGA::GUIEventAdapter::SCROLL): if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_DOWN) { if (getCurrentItem()<getNumItems()-1) setCurrentItem(getCurrentItem()+1); return true; } else if (ea->getScrollingMotion()==osgGA::GUIEventAdapter::SCROLL_UP) { if (getCurrentItem()>0) setCurrentItem(getCurrentItem()-1); return true; } break; case(osgGA::GUIEventAdapter::KEYDOWN): if (ea->getKey()==osgGA::GUIEventAdapter::KEY_Down) { if (getCurrentItem()<getNumItems()-1) setCurrentItem(getCurrentItem()+1); return true; } else if (ea->getKey()==osgGA::GUIEventAdapter::KEY_Up) { if (getCurrentItem()>0) setCurrentItem(getCurrentItem()-1); return true; } break; case(osgGA::GUIEventAdapter::PUSH): OSG_NOTICE<<"Button pressed "<<std::endl; break; case(osgGA::GUIEventAdapter::RELEASE): OSG_NOTICE<<"Button release "<<std::endl; break; default: break; } return false; } void ComboBox::enterImplementation() { OSG_NOTICE<<"ComboBox enter"<<std::endl; } void ComboBox::leaveImplementation() { OSG_NOTICE<<"ComboBox leave"<<std::endl; } void ComboBox::setCurrentItem(unsigned int i) { OSG_NOTICE << "ComboBox::setCurrentItem("<<i<<")"<<std::endl; _currentItem = i; if (_switch.valid()) _switch->setSingleChildOn(_currentItem); } void ComboBox::createGraphicsImplementation() { if (_switch.valid() && _switch->getNumChildren()==_items.size()) { OSG_NOTICE<<"Need to update existing scene graph"<<std::endl; _graphicsInitialized = true; } else { OSG_NOTICE<<"ComboBox::createGraphicsImplementation()"<<std::endl; Widget::createGraphicsImplementation(); Style* style = (getStyle()!=0) ? getStyle() : Style::instance().get(); _switch = new osg::Switch; addChild(_switch.get()); if (!_items.empty()) { for(Items::iterator itr = _items.begin(); itr != _items.end(); ++itr) { Item* item = itr->get(); OSG_NOTICE<<"Creating item "<<item->getText()<<", "<<item->getColor()<<std::endl; osg::ref_ptr<osg::Group> group = new osg::Group; if (item->getColor().a()!=0.0f) group->addChild( style->createPanel(_extents, item->getColor()) ); if (!item->getText().empty()) group->addChild( style->createText(_extents, getAlignmentSettings(), getTextSettings(), item->getText()) ); _switch->addChild(group.get()); } } else { _switch->addChild( style->createPanel(_extents, osg::Vec4(1.0f,1.0f,1.0f,1.0f)) ); } _switch->setSingleChildOn(_currentItem); } } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <errno.h> #include "server.h" #include "stinger_net/stinger_server_state.h" //#define LOG_AT_D #include "stinger_core/stinger_error.h" typedef struct { struct stinger * S; int sock; } handle_stream_args; void * handle_stream(void * args) { StingerServerState & server_state = StingerServerState::get_server_state(); /* should be able to remove these */ struct stinger *S = ((handle_stream_args *) args)->S; int sock = ((handle_stream_args *) args)->sock; free(args); int nfail = 0; LOG_V("Ready to accept messages."); while(1) { StingerBatch * batch = new StingerBatch(); if (recv_message(sock, *batch)) { nfail = 0; LOG_V_A("Received message of size %ld", (long)batch->ByteSize()); if (0 == batch->insertions_size () && 0 == batch->deletions_size ()) { LOG_V("Empty batch."); if (!batch->keep_alive ()) { delete batch; break; } else { delete batch; continue; } } server_state.enqueue_batch(batch); if(!batch->keep_alive()) { delete batch; break; } } else { ++nfail; LOG_E("Parsing failed."); if (nfail > 2) break; } } } void * start_tcp_batch_server (void * args) { StingerServerState & server_state = StingerServerState::get_server_state(); struct stinger * S = server_state.get_stinger(); int port_streams = server_state.get_port_streams(); int sock_handle, newsockfd; pthread_t garbage_thread_handle; socklen_t clilen; struct sockaddr_in serv_addr, cli_addr; pid_t pid; if (-1 == (sock_handle = socket(AF_INET, SOCK_STREAM, 0))) { perror("Socket create failed.\n"); exit(-1); } bzero ((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port_streams); if (-1 == bind(sock_handle, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) { perror("Socket bind failed.\n"); exit(-1); } if (-1 == listen(sock_handle, 5)) { perror("Socket listen failed.\n"); exit(-1); } clilen = sizeof(cli_addr); LOG_V_A("STINGER server listening for input on port %d", (int)port_streams); pthread_t alg_handling; pthread_create(&alg_handling, NULL, start_alg_handling, NULL); while (1) { newsockfd = accept (sock_handle, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) { perror("Accept new connection failed.\n"); exit(-1); } handle_stream_args * args = (handle_stream_args *)calloc(1, sizeof(handle_stream_args)); args->S = S; args->sock = newsockfd; pthread_create(&garbage_thread_handle, NULL, handle_stream, (void *)args); } close(sock_handle); } <commit_msg>Dropping batches when queue reaches 100 and logging it.<commit_after>#include <cstdio> #include <cstdlib> #include <cstring> #include <cassert> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <errno.h> #include "server.h" #include "stinger_core/stinger_atomics.h" #include "stinger_net/stinger_server_state.h" //#define LOG_AT_D #include "stinger_core/stinger_error.h" #define STINGER_MAX_BATCHES 100 typedef struct { struct stinger * S; int sock; } handle_stream_args; void * handle_stream(void * args) { StingerServerState & server_state = StingerServerState::get_server_state(); /* should be able to remove these */ struct stinger *S = ((handle_stream_args *) args)->S; int sock = ((handle_stream_args *) args)->sock; free(args); int nfail = 0; LOG_V("Ready to accept messages."); while(1) { StingerBatch * batch = new StingerBatch(); if (recv_message(sock, *batch)) { nfail = 0; LOG_V_A("Received message of size %ld", (long)batch->ByteSize()); if (0 == batch->insertions_size () && 0 == batch->deletions_size ()) { LOG_V("Empty batch."); if (!batch->keep_alive ()) { delete batch; break; } else { delete batch; continue; } } if (server_state.get_queue_size() >= STINGER_MAX_BATCHES) { LOG_W("Dropping a batch"); stinger_uint64_fetch_add(&(S->dropped_batches), 1); delete batch; continue; } server_state.enqueue_batch(batch); if(!batch->keep_alive()) { delete batch; break; } } else { ++nfail; LOG_E("Parsing failed."); if (nfail > 2) break; } } } void * start_tcp_batch_server (void * args) { StingerServerState & server_state = StingerServerState::get_server_state(); struct stinger * S = server_state.get_stinger(); int port_streams = server_state.get_port_streams(); int sock_handle, newsockfd; pthread_t garbage_thread_handle; socklen_t clilen; struct sockaddr_in serv_addr, cli_addr; pid_t pid; if (-1 == (sock_handle = socket(AF_INET, SOCK_STREAM, 0))) { perror("Socket create failed.\n"); exit(-1); } bzero ((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(port_streams); if (-1 == bind(sock_handle, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) { perror("Socket bind failed.\n"); exit(-1); } if (-1 == listen(sock_handle, 5)) { perror("Socket listen failed.\n"); exit(-1); } clilen = sizeof(cli_addr); LOG_V_A("STINGER server listening for input on port %d", (int)port_streams); pthread_t alg_handling; pthread_create(&alg_handling, NULL, start_alg_handling, NULL); while (1) { newsockfd = accept (sock_handle, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) { perror("Accept new connection failed.\n"); exit(-1); } handle_stream_args * args = (handle_stream_args *)calloc(1, sizeof(handle_stream_args)); args->S = S; args->sock = newsockfd; pthread_create(&garbage_thread_handle, NULL, handle_stream, (void *)args); } close(sock_handle); } <|endoftext|>
<commit_before>#include "tree.h" #include "mpi_util.h" #include <cstdlib> #include <cmath> #include <limits> #include <utility> #include <glog/logging.h> Tree::Tree(unsigned int max_depth, unsigned int n_bins, unsigned int n_splits): max_depth_(max_depth), n_bins_(n_bins), n_splits_(n_splits), current_node_id_(0), current_depth_(0) { }; void Tree::Train(const DataMatrix& data) { Train(data, data.GetTargets()); }; void Tree::Train(const DataMatrix& data, const std::vector<double>& targets) { InitializeRootNode(data); while (current_depth_ < max_depth_) { ProcessCurrentNodes(data, targets); current_depth_ += 1; } }; std::vector<double> Tree::Predict(const DataMatrix& data) const { std::vector<double> predictions; predictions.reserve(data.Size()); for (unsigned int i = 0; i < data.Size(); ++i) { //LOG(INFO) << "Predicting for sample #" << i; predictions.push_back(Predict(data.GetRow(i))); } return predictions; }; double Tree::Predict(const DataMatrix::SamplePoint& sample) const { return TraverseTree(sample); }; void Tree::InitializeRootNode(const DataMatrix& data) { nodes_.resize(1 << (max_depth_+1)); unsigned int root_id = current_node_id_++; Node& root = nodes_[root_id]; root.samples.reserve(data.Size()); root.depth = 0; // NOTE: Even if the almost unncessary label is to be filled, it has to be // determined by the master later. for (unsigned int i = 0; i < data.Size(); ++i) { root.samples.push_back(i); } current_queue_.push_back(root_id); }; void Tree::ProcessCurrentNodes(const DataMatrix& data, const std::vector<double>& targets) { // Histograms are stored by features. In the distributed version, a message // completely covers a feature (over multiple nodes), so that the number of // messages sent does not grow with tree depth. // histograms[x][y]: Histogram for feature x at node y const std::vector<unsigned int> feature_keys = data.GetFeatureKeys(); std::vector<std::vector<Histogram> > histograms(feature_keys.size(), std::vector<Histogram>(current_queue_.size(), Histogram(n_bins_))); mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; //LOG(INFO) << "Rank: " << world.rank(); //LOG(INFO) << "Environment intialized: " << env.initialized(); // In case of slaves int total_reqs_push_histograms = histograms.size(); mpi::request reqs_push_histograms[total_reqs_push_histograms]; std::vector<HistogramsPerFeature> messages(total_reqs_push_histograms); for (unsigned int i = 0; i < feature_keys.size(); ++i) { unsigned int fkey = feature_keys[i]; const auto& column = data.GetColumn(fkey); for (unsigned int j = 0; j < current_queue_.size(); ++j) { histograms[i][j] = ComputeHistogram(column, targets, nodes_[current_queue_[j]].samples); } messages[i].histograms = histograms[i]; messages[i].feature_index = i; // TODO: i or fkey? if (world.rank() >= 1) { int tag = (world.rank()-1)*feature_keys.size() + i; //LOG(INFO) << "Push tag: " << tag; reqs_push_histograms[i] = world.isend(0, tag, messages[i]); // TODO: Need to run a dummy test() to kick start the process? } } if (world.rank() == 0 && world.size() > 1) { LOG(INFO) << "Pulling"; MPI_PullHistograms(histograms); } else if (world.rank() >= 1) { LOG(INFO) << "Finalize pushing"; mpi::wait_all(reqs_push_histograms, reqs_push_histograms + total_reqs_push_histograms); LOG(INFO) << "Pushed all histograms"; } next_queue_.clear(); // This way ordering of nodes in the next processing queue is defined by the // master process. std::vector<SplitResult> best_splits_by_nodes(current_queue_.size()); if ( world.rank() == 0 ) { for (unsigned int j = 0; j < current_queue_.size(); ++j) { SplitResult best_result; best_result.can_split = false; best_result.cost = std::numeric_limits<double>::max(); for (unsigned int i = 0; i < feature_keys.size(); ++i) { SplitResult result = FindBestSplit(histograms[i][j]); if (result.can_split && result.cost < best_result.cost) { // TODO: Options to check for number of observations per leaf, etc. Or // check for these within FindBestSplit using the histogram? best_result = result; best_result.feature_index = i; } } // TODO: Make a ref? best_splits_by_nodes[j] = best_result; } MPI_PushBestSplits(best_splits_by_nodes); } else { LOG(INFO) << "Receiving split results..."; MPI_PullBestSplits(best_splits_by_nodes); } for (unsigned int j = 0; j < current_queue_.size(); ++j) { SplitResult& best_result = best_splits_by_nodes[j]; if (!best_result.can_split) { return; } best_result.id_left = current_node_id_++; best_result.id_right = current_node_id_++; //LOG(INFO) << "Node [" << current_queue_[j] <<"]: Making a split on feature " << best_result.feature_index << " with threshold " << best_result.threshold << "; label_left: " << best_result.label_left << " label_right: " << best_result.label_right; FinalizeAndSplitNode(data, best_result, nodes_[current_queue_[j]]); //LOG(INFO) << "Done processing node " << current_queue_[j]; next_queue_.push_back(best_result.id_left); next_queue_.push_back(best_result.id_right); } current_queue_.swap(next_queue_); }; void Tree::MPI_PullHistograms(std::vector<std::vector<Histogram> >& histograms) const { // TODO: or pass in env and world? mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; int total_reqs = (world.size()-1) * histograms.size(); //LOG(INFO) << "MPI_PullHistograms: # total reqs: " << total_reqs; mpi::request reqs[total_reqs]; std::vector<HistogramsPerFeature> messages(total_reqs); for (unsigned int i = 0; i < histograms.size(); ++i) { for (int k = 1; k < world.size(); ++k) { int cur_idx = i*(world.size()-1) + (k-1); int tag = (k-1)*histograms.size() + i; //LOG(INFO) << "MPI_PullHistograms: Current message index to pull: " << cur_idx; reqs[cur_idx] = world.irecv(k, tag, messages[cur_idx]); } } LOG(INFO) << "MPI_PullHistograms: Start waiting for slave histograms"; mpi::wait_all(reqs, reqs + total_reqs); LOG(INFO) << "MPI_PulHistograms: Finished waiting in pull"; for (int i = 0; i < total_reqs; i++) { unsigned int feature_index = messages[i].feature_index; std::vector<Histogram>& h = messages[i].histograms; for (unsigned int j = 0; j < h.size(); ++j) { histograms[feature_index][j].Merge(h[j]); } } }; void Tree::MPI_PushHistograms(const std::vector<std::vector<Histogram> >& histograms) const { mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; }; void Tree::MPI_PushBestSplits(const std::vector<SplitResult>& best_splits_by_nodes) const { LOG(INFO) << "MPI_PushBestSplits: Pushing best splits"; mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; mpi::request reqs[world.size()-1]; for (int k = 1; k < world.size(); ++k) { reqs[k-1] = world.isend(k, MPI_TagBestSplits(), best_splits_by_nodes); } mpi::wait_all(reqs, reqs + world.size() - 1); LOG(INFO) << "MPI_PushBestSplits: Pushes finalized"; }; void Tree::MPI_PullBestSplits(std::vector<SplitResult>& best_splits_by_nodes) const { LOG(INFO) << "MPI_PullBestSplits: Pulling best splits"; mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; world.recv(0, MPI_TagBestSplits(), best_splits_by_nodes); LOG(INFO) << "MPI_PullBestSplits: Pull finalized"; }; int Tree::MPI_TagBestSplits() const { return 1001; }; void Tree::FinalizeAndSplitNode(const DataMatrix& data, const SplitResult& result, Node& parent) { // Finalize current node parent.is_leaf = false; parent.feature_index = result.feature_index; parent.threshold = result.threshold; // Reference is OK since nodes_ will not be reallocated Node& next_left = nodes_[result.id_left]; Node& next_right = nodes_[result.id_right]; next_left.id = result.id_left; next_left.depth = parent.depth + 1; next_left.label = result.label_left; next_left.is_leaf = true; next_right.id = result.id_right; next_right.depth = parent.depth + 1; next_right.label = result.label_right; next_right.is_leaf = true; auto features = data.GetColumn(parent.feature_index); for(unsigned int i = 0; i < parent.samples.size(); ++i) { unsigned int sample_idx = parent.samples[i]; if (features[sample_idx].value < parent.threshold) { next_left.samples.push_back(sample_idx); } else { next_right.samples.push_back(sample_idx); } } // After split is decided and samples divided to the children, no longer need // to retain the sample indices parent.samples.clear(); // Link parent and childrens parent.left_id = result.id_left; parent.right_id = result.id_right; //LOG(INFO) << "Node " << nodes_[node_id].id << "'s left: " << nodes_[node_id].left_id << "; right: " << nodes_[node_id].right_id; }; Tree::SplitResult Tree::FindBestSplit(const Histogram& histogram) const { //LOG(INFO) << "Finding best split"; SplitResult best_split; best_split.cost = std::numeric_limits<double>::max(); best_split.can_split = false; // Possible that the histogram is empty because of no sample at all (TO CHECK) if (histogram.get_num_bins() == 0) { return best_split; } std::vector<double> candidates = histogram.Uniform(n_splits_); //CHECK(candidates.size() > 0) << "Empty split (uniformed) candidates"; Histogram::BinVal val_inf = histogram.InterpolateInf(); double l_inf = val_inf.y; double m_inf = val_inf.m; // Minimum samples required to initiate a split if (m_inf <= 2) { return best_split; } for (unsigned int i = 0; i < candidates.size(); ++i) { double s = candidates[i]; // TODO: Make sure that cache is in action Histogram::BinVal val_s = histogram.Interpolate(s); double l_s = val_s.y; double m_s = val_s.m; double y_left = l_s / m_s; double y_right = (l_inf - l_s) / (m_inf - m_s); // (Estimated) Minimum observations at leaf if (!(m_s > 0 && (m_inf-m_s) > 0)) { continue; } // No need to split if node is already pure // TODO: Can be checked out of this loop ? if (std::fabs(y_left - y_right) < 10e-6) { continue; } CHECK((m_inf - m_s) > 0) << "Deviding by zero in right side at s = " << s << ": i = " << i << "; m_inf: " << m_inf << "; m_s: " << m_s; double cost = - (l_s*l_s)/(m_s) - (l_inf-l_s)*(l_inf-l_s)/(m_inf-m_s); if (cost < best_split.cost) { best_split.cost = cost; best_split.threshold = s; best_split.label_left = y_left; best_split.label_right = y_right; best_split.can_split = true; } } //LOG(INFO) << "Done finding best split with cost: " << best_split.cost; return best_split; }; Histogram Tree::ComputeHistogram( const std::vector<DataMatrix::FeaturePoint>& column, const std::vector<double>& targets, const std::vector<unsigned int>& samples) const { //TODO: What if samples is empty? Now in the next step find best split will //ignore the resulted empty histogram. //LOG(INFO) << "Computing histogram"; Histogram histogram(n_bins_); for (unsigned int i = 0; i < samples.size(); ++i) { unsigned int sample_idx = samples[i]; double fval = column[sample_idx].value; double tval = targets[sample_idx]; histogram.Update(fval, tval); } //LOG(INFO) << "Done computing histogram"; return histogram; }; double Tree::TraverseTree(const DataMatrix::SamplePoint& sample) const { unsigned int id = 0; while (true) { //LOG(INFO) << "Traversing: Now at node " << id; if (nodes_[id].is_leaf) { return nodes_[id].label; } unsigned int fidx = nodes_[id].feature_index; //LOG(INFO) << "Considering feature " << fidx << " at node " << id; double thres = nodes_[id].threshold; if (sample.features.at(fidx) <= thres) { id = nodes_[id].left_id; } else { id = nodes_[id].right_id; } }; }; <commit_msg>Log when a tree level finishes<commit_after>#include "tree.h" #include "mpi_util.h" #include <cstdlib> #include <cmath> #include <limits> #include <utility> #include <glog/logging.h> Tree::Tree(unsigned int max_depth, unsigned int n_bins, unsigned int n_splits): max_depth_(max_depth), n_bins_(n_bins), n_splits_(n_splits), current_node_id_(0), current_depth_(0) { }; void Tree::Train(const DataMatrix& data) { Train(data, data.GetTargets()); }; void Tree::Train(const DataMatrix& data, const std::vector<double>& targets) { InitializeRootNode(data); while (current_depth_ < max_depth_) { ProcessCurrentNodes(data, targets); current_depth_ += 1; } }; std::vector<double> Tree::Predict(const DataMatrix& data) const { std::vector<double> predictions; predictions.reserve(data.Size()); for (unsigned int i = 0; i < data.Size(); ++i) { //LOG(INFO) << "Predicting for sample #" << i; predictions.push_back(Predict(data.GetRow(i))); } return predictions; }; double Tree::Predict(const DataMatrix::SamplePoint& sample) const { return TraverseTree(sample); }; void Tree::InitializeRootNode(const DataMatrix& data) { nodes_.resize(1 << (max_depth_+1)); unsigned int root_id = current_node_id_++; Node& root = nodes_[root_id]; root.samples.reserve(data.Size()); root.depth = 0; // NOTE: Even if the almost unncessary label is to be filled, it has to be // determined by the master later. for (unsigned int i = 0; i < data.Size(); ++i) { root.samples.push_back(i); } current_queue_.push_back(root_id); }; void Tree::ProcessCurrentNodes(const DataMatrix& data, const std::vector<double>& targets) { // Histograms are stored by features. In the distributed version, a message // completely covers a feature (over multiple nodes), so that the number of // messages sent does not grow with tree depth. // histograms[x][y]: Histogram for feature x at node y const std::vector<unsigned int> feature_keys = data.GetFeatureKeys(); std::vector<std::vector<Histogram> > histograms(feature_keys.size(), std::vector<Histogram>(current_queue_.size(), Histogram(n_bins_))); mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; //LOG(INFO) << "Rank: " << world.rank(); //LOG(INFO) << "Environment intialized: " << env.initialized(); // In case of slaves int total_reqs_push_histograms = histograms.size(); mpi::request reqs_push_histograms[total_reqs_push_histograms]; std::vector<HistogramsPerFeature> messages(total_reqs_push_histograms); for (unsigned int i = 0; i < feature_keys.size(); ++i) { unsigned int fkey = feature_keys[i]; const auto& column = data.GetColumn(fkey); for (unsigned int j = 0; j < current_queue_.size(); ++j) { histograms[i][j] = ComputeHistogram(column, targets, nodes_[current_queue_[j]].samples); } messages[i].histograms = histograms[i]; messages[i].feature_index = i; // TODO: i or fkey? if (world.rank() >= 1) { int tag = (world.rank()-1)*feature_keys.size() + i; //LOG(INFO) << "Push tag: " << tag; reqs_push_histograms[i] = world.isend(0, tag, messages[i]); // TODO: Need to run a dummy test() to kick start the process? } } if (world.rank() == 0 && world.size() > 1) { LOG(INFO) << "Pulling"; MPI_PullHistograms(histograms); } else if (world.rank() >= 1) { LOG(INFO) << "Finalize pushing"; mpi::wait_all(reqs_push_histograms, reqs_push_histograms + total_reqs_push_histograms); LOG(INFO) << "Pushed all histograms"; } next_queue_.clear(); // This way ordering of nodes in the next processing queue is defined by the // master process. std::vector<SplitResult> best_splits_by_nodes(current_queue_.size()); if ( world.rank() == 0 ) { for (unsigned int j = 0; j < current_queue_.size(); ++j) { SplitResult best_result; best_result.can_split = false; best_result.cost = std::numeric_limits<double>::max(); for (unsigned int i = 0; i < feature_keys.size(); ++i) { SplitResult result = FindBestSplit(histograms[i][j]); if (result.can_split && result.cost < best_result.cost) { // TODO: Options to check for number of observations per leaf, etc. Or // check for these within FindBestSplit using the histogram? best_result = result; best_result.feature_index = i; } } // TODO: Make a ref? best_splits_by_nodes[j] = best_result; } MPI_PushBestSplits(best_splits_by_nodes); } else { LOG(INFO) << "Receiving split results..."; MPI_PullBestSplits(best_splits_by_nodes); } for (unsigned int j = 0; j < current_queue_.size(); ++j) { SplitResult& best_result = best_splits_by_nodes[j]; if (!best_result.can_split) { return; } best_result.id_left = current_node_id_++; best_result.id_right = current_node_id_++; //LOG(INFO) << "Node [" << current_queue_[j] <<"]: Making a split on feature " << best_result.feature_index << " with threshold " << best_result.threshold << "; label_left: " << best_result.label_left << " label_right: " << best_result.label_right; FinalizeAndSplitNode(data, best_result, nodes_[current_queue_[j]]); //LOG(INFO) << "Done processing node " << current_queue_[j]; next_queue_.push_back(best_result.id_left); next_queue_.push_back(best_result.id_right); } current_queue_.swap(next_queue_); LOG(INFO) << "ProcessCurrentNodes: Done depth " << current_depth_; }; void Tree::MPI_PullHistograms(std::vector<std::vector<Histogram> >& histograms) const { // TODO: or pass in env and world? mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; int total_reqs = (world.size()-1) * histograms.size(); //LOG(INFO) << "MPI_PullHistograms: # total reqs: " << total_reqs; mpi::request reqs[total_reqs]; std::vector<HistogramsPerFeature> messages(total_reqs); for (unsigned int i = 0; i < histograms.size(); ++i) { for (int k = 1; k < world.size(); ++k) { int cur_idx = i*(world.size()-1) + (k-1); int tag = (k-1)*histograms.size() + i; //LOG(INFO) << "MPI_PullHistograms: Current message index to pull: " << cur_idx; reqs[cur_idx] = world.irecv(k, tag, messages[cur_idx]); } } LOG(INFO) << "MPI_PullHistograms: Start waiting for slave histograms"; mpi::wait_all(reqs, reqs + total_reqs); LOG(INFO) << "MPI_PulHistograms: Finished waiting in pull"; for (int i = 0; i < total_reqs; i++) { unsigned int feature_index = messages[i].feature_index; std::vector<Histogram>& h = messages[i].histograms; for (unsigned int j = 0; j < h.size(); ++j) { histograms[feature_index][j].Merge(h[j]); } } }; void Tree::MPI_PushHistograms(const std::vector<std::vector<Histogram> >& histograms) const { mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; }; void Tree::MPI_PushBestSplits(const std::vector<SplitResult>& best_splits_by_nodes) const { LOG(INFO) << "MPI_PushBestSplits: Pushing best splits"; mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; mpi::request reqs[world.size()-1]; for (int k = 1; k < world.size(); ++k) { reqs[k-1] = world.isend(k, MPI_TagBestSplits(), best_splits_by_nodes); } mpi::wait_all(reqs, reqs + world.size() - 1); LOG(INFO) << "MPI_PushBestSplits: Pushes finalized"; }; void Tree::MPI_PullBestSplits(std::vector<SplitResult>& best_splits_by_nodes) const { LOG(INFO) << "MPI_PullBestSplits: Pulling best splits"; mpi::environment& env = MPIHandle::Get().env; mpi::communicator& world = MPIHandle::Get().world; world.recv(0, MPI_TagBestSplits(), best_splits_by_nodes); LOG(INFO) << "MPI_PullBestSplits: Pull finalized"; }; int Tree::MPI_TagBestSplits() const { return 1001; }; void Tree::FinalizeAndSplitNode(const DataMatrix& data, const SplitResult& result, Node& parent) { // Finalize current node parent.is_leaf = false; parent.feature_index = result.feature_index; parent.threshold = result.threshold; // Reference is OK since nodes_ will not be reallocated Node& next_left = nodes_[result.id_left]; Node& next_right = nodes_[result.id_right]; next_left.id = result.id_left; next_left.depth = parent.depth + 1; next_left.label = result.label_left; next_left.is_leaf = true; next_right.id = result.id_right; next_right.depth = parent.depth + 1; next_right.label = result.label_right; next_right.is_leaf = true; auto features = data.GetColumn(parent.feature_index); for(unsigned int i = 0; i < parent.samples.size(); ++i) { unsigned int sample_idx = parent.samples[i]; if (features[sample_idx].value < parent.threshold) { next_left.samples.push_back(sample_idx); } else { next_right.samples.push_back(sample_idx); } } // After split is decided and samples divided to the children, no longer need // to retain the sample indices parent.samples.clear(); // Link parent and childrens parent.left_id = result.id_left; parent.right_id = result.id_right; //LOG(INFO) << "Node " << nodes_[node_id].id << "'s left: " << nodes_[node_id].left_id << "; right: " << nodes_[node_id].right_id; }; Tree::SplitResult Tree::FindBestSplit(const Histogram& histogram) const { //LOG(INFO) << "Finding best split"; SplitResult best_split; best_split.cost = std::numeric_limits<double>::max(); best_split.can_split = false; // Possible that the histogram is empty because of no sample at all (TO CHECK) if (histogram.get_num_bins() == 0) { return best_split; } std::vector<double> candidates = histogram.Uniform(n_splits_); //CHECK(candidates.size() > 0) << "Empty split (uniformed) candidates"; Histogram::BinVal val_inf = histogram.InterpolateInf(); double l_inf = val_inf.y; double m_inf = val_inf.m; // Minimum samples required to initiate a split if (m_inf <= 2) { return best_split; } for (unsigned int i = 0; i < candidates.size(); ++i) { double s = candidates[i]; // TODO: Make sure that cache is in action Histogram::BinVal val_s = histogram.Interpolate(s); double l_s = val_s.y; double m_s = val_s.m; double y_left = l_s / m_s; double y_right = (l_inf - l_s) / (m_inf - m_s); // (Estimated) Minimum observations at leaf if (!(m_s > 0 && (m_inf-m_s) > 0)) { continue; } // No need to split if node is already pure // TODO: Can be checked out of this loop ? if (std::fabs(y_left - y_right) < 10e-6) { continue; } CHECK((m_inf - m_s) > 0) << "Deviding by zero in right side at s = " << s << ": i = " << i << "; m_inf: " << m_inf << "; m_s: " << m_s; double cost = - (l_s*l_s)/(m_s) - (l_inf-l_s)*(l_inf-l_s)/(m_inf-m_s); if (cost < best_split.cost) { best_split.cost = cost; best_split.threshold = s; best_split.label_left = y_left; best_split.label_right = y_right; best_split.can_split = true; } } //LOG(INFO) << "Done finding best split with cost: " << best_split.cost; return best_split; }; Histogram Tree::ComputeHistogram( const std::vector<DataMatrix::FeaturePoint>& column, const std::vector<double>& targets, const std::vector<unsigned int>& samples) const { //TODO: What if samples is empty? Now in the next step find best split will //ignore the resulted empty histogram. //LOG(INFO) << "Computing histogram"; Histogram histogram(n_bins_); for (unsigned int i = 0; i < samples.size(); ++i) { unsigned int sample_idx = samples[i]; double fval = column[sample_idx].value; double tval = targets[sample_idx]; histogram.Update(fval, tval); } //LOG(INFO) << "Done computing histogram"; return histogram; }; double Tree::TraverseTree(const DataMatrix::SamplePoint& sample) const { unsigned int id = 0; while (true) { //LOG(INFO) << "Traversing: Now at node " << id; if (nodes_[id].is_leaf) { return nodes_[id].label; } unsigned int fidx = nodes_[id].feature_index; //LOG(INFO) << "Considering feature " << fidx << " at node " << id; double thres = nodes_[id].threshold; if (sample.features.at(fidx) <= thres) { id = nodes_[id].left_id; } else { id = nodes_[id].right_id; } }; }; <|endoftext|>
<commit_before>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __xoutcell_hxx #define __xoutcell_hxx #include "xoutcell.h" namespace xoutlibrary { using namespace std; /** * ************************ Constructor ************************* */ template< class charT, class traits > xoutcell< charT, traits >::xoutcell() { this->AddTargetCell( "InternalBuffer", &( this->m_InternalBuffer ) ); } // end Constructor /** * ********************* Destructor ***************************** */ template< class charT, class traits > xoutcell< charT, traits >::~xoutcell() { //nothing } // end Destructor /** * ******************** WriteBufferedData *********************** * * The buffered data is sent to the outputs. */ template< class charT, class traits > void xoutcell< charT, traits >::WriteBufferedData( void ) { /** Make sure all data is written to the string */ this->m_InternalBuffer << flush; const std::string & strbuf = this->m_InternalBuffer.str(); const char * charbuf = strbuf.c_str(); /** Send the string to the outputs */ for( CStreamMapIteratorType cit = this->m_COutputs.begin(); cit != this->m_COutputs.end(); ++cit ) { *( cit->second ) << charbuf << flush; } /** Send the string to the outputs */ for( XStreamMapIteratorType xit = this->m_XOutputs.begin(); xit != this->m_XOutputs.end(); ++xit ) { *( xit->second ) << charbuf; xit->second->WriteBufferedData(); } /** Empty the internal buffer */ this->m_InternalBuffer.str( string( "" ) ); } // end WriteBufferedData } // end namespace xoutlibrary #endif // end #ifndef __xoutcell_hxx <commit_msg>STYLE: Fix /analyze warning "Don't dereference 'strbuf'"<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __xoutcell_hxx #define __xoutcell_hxx #include "xoutcell.h" namespace xoutlibrary { using namespace std; /** * ************************ Constructor ************************* */ template< class charT, class traits > xoutcell< charT, traits >::xoutcell() { this->AddTargetCell( "InternalBuffer", &( this->m_InternalBuffer ) ); } // end Constructor /** * ********************* Destructor ***************************** */ template< class charT, class traits > xoutcell< charT, traits >::~xoutcell() { //nothing } // end Destructor /** * ******************** WriteBufferedData *********************** * * The buffered data is sent to the outputs. */ template< class charT, class traits > void xoutcell< charT, traits >::WriteBufferedData( void ) { /** Make sure all data is written to the string */ this->m_InternalBuffer << flush; const std::string strbuf = this->m_InternalBuffer.str(); const char * const charbuf = strbuf.c_str(); /** Send the string to the outputs */ for( CStreamMapIteratorType cit = this->m_COutputs.begin(); cit != this->m_COutputs.end(); ++cit ) { *( cit->second ) << charbuf << flush; } /** Send the string to the outputs */ for( XStreamMapIteratorType xit = this->m_XOutputs.begin(); xit != this->m_XOutputs.end(); ++xit ) { *( xit->second ) << charbuf; xit->second->WriteBufferedData(); } /** Empty the internal buffer */ this->m_InternalBuffer.str( string( "" ) ); } // end WriteBufferedData } // end namespace xoutlibrary #endif // end #ifndef __xoutcell_hxx <|endoftext|>
<commit_before>92e9bc68-2e4e-11e5-9284-b827eb9e62be<commit_msg>92eeb5c4-2e4e-11e5-9284-b827eb9e62be<commit_after>92eeb5c4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> Copyright © 2015 Jonathan Hale <squareys@googlemail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <memory.h> #include <Corrade/Containers/Array.h> #include <Magnum/Magnum.h> #include <Magnum/Math/Vector2.h> #include <Magnum/Math/Vector3.h> #include <Magnum/Mesh.h> #include <Corrade/Utility/utilities.h> #include <Magnum/Buffer.h> #include <Magnum/DefaultFramebuffer.h> #include <Magnum/Renderer.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/MeshData3D.h> #include <Magnum/Math/Quaternion.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/Framebuffer.h> #include <Magnum/Renderbuffer.h> #include <Magnum/Texture.h> #include <Magnum/TextureFormat.h> #include <Magnum/Context.h> #include "Types.h" #include "HmdCamera.h" #include "CubeDrawable.h" #include <Magnum/LibOvrIntegration/LibOvrIntegration.h> #include <Magnum/LibOvrIntegration/Context.h> #include <Magnum/LibOvrIntegration/Hmd.h> #include <Magnum/LibOvrIntegration/HmdEnum.h> namespace Magnum { namespace Examples { using namespace LibOvrIntegration; /** * @brief The Application class of OvrExample. * @author Jonathan Hale (Squareys) */ class OvrExample: public Platform::Application { public: explicit OvrExample(const Arguments& arguments); virtual ~OvrExample(); private: void drawEvent() override; LibOvrIntegration::Context _ovrContext; std::unique_ptr<Hmd> _hmd; std::unique_ptr<Buffer> _indexBuffer, _vertexBuffer; std::unique_ptr<Mesh> _mesh; std::unique_ptr<Shaders::Phong> _shader; Scene3D _scene; Object3D _cameraObject; Object3D _eyes[2]; SceneGraph::DrawableGroup3D _drawables; std::unique_ptr<HmdCamera> _cameras[2]; std::unique_ptr<Object3D> _cubes[4]; std::unique_ptr<CubeDrawable> _cubeDrawables[4]; std::unique_ptr<Framebuffer> _mirrorFramebuffer; Texture2D* _mirrorTexture; LayerEyeFov* _layer; }; OvrExample::OvrExample(const Arguments& arguments) : Platform::Application(arguments, nullptr), _indexBuffer(nullptr), _vertexBuffer(nullptr), _mesh(nullptr), _shader(nullptr), _scene(), _cameraObject(&_scene) { /* connect to an Hmd, or create a debug hmd with DK2 type in case none is connected. */ _hmd = LibOvrIntegration::Context::get().createHmd(0, HmdType::DK2); /* get the hmd display resolution */ Vector2i resolution = _hmd->resolution() / 2; /* create a context with the hmd display resolution */ Configuration conf; conf.setTitle("Magnum OculusVR Example") .setSize(resolution) .setSampleCount(16); if(!tryCreateContext(conf)) createContext(conf.setSampleCount(0)); /* the oculus sdk compositor does some "magic" to reduce latency. For * that to work, vsync needs to be turned off. */ if(!setSwapInterval(0)) Error() << "Could not turn off vsync."; Renderer::enable(Renderer::Feature::DepthTest); _hmd->setEnabledCaps(HmdCapability::LowPersistence | HmdCapability::DynamicPrediction ); _hmd->configureTracking(HmdTrackingCapability::Orientation | HmdTrackingCapability::MagYawCorrection | HmdTrackingCapability::Position, {}); _hmd->configureRendering(); /* setup mirroring of oculus sdk compositor results to a texture which can later be blitted * onto the defaultFramebuffer. */ _mirrorTexture = &_hmd->createMirrorTexture(TextureFormat::RGBA, resolution); _mirrorFramebuffer.reset(new Framebuffer(Range2Di::fromSize({}, resolution))); _mirrorFramebuffer->attachTexture(Framebuffer::ColorAttachment(0), *_mirrorTexture, 0) .mapForRead(Framebuffer::ColorAttachment(0)); /* Setup cube mesh. */ const Trade::MeshData3D cube = Primitives::Cube::solid(); _vertexBuffer.reset(new Buffer()); _vertexBuffer->setData( MeshTools::interleave(cube.positions(0), cube.normals(0)), BufferUsage::StaticDraw); Containers::Array<char> indexData; Mesh::IndexType indexType; UnsignedInt indexStart, indexEnd; std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cube.indices()); _indexBuffer.reset(new Buffer()); _indexBuffer->setData(indexData, BufferUsage::StaticDraw); _mesh.reset(new Mesh()); _mesh->setPrimitive(cube.primitive()).setCount(cube.indices().size()).addVertexBuffer( *_vertexBuffer, 0, Shaders::Phong::Position {}, Shaders::Phong::Normal {}).setIndexBuffer(*_indexBuffer, 0, indexType, indexStart, indexEnd); /* setup shader */ _shader.reset(new Shaders::Phong()); /* setup scene */ _cubes[0] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[0]->rotateY(Deg(45.0f)); _cubes[0]->translate({0.0f, 0.0f, -3.0f}); _cubeDrawables[0] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 1.0f, 0.0f}, _cubes[0].get(), &_drawables)); _cubes[1] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[1]->rotateY(Deg(45.0f)); _cubes[1]->translate({5.0f, 0.0f, 0.0f}); _cubeDrawables[1] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 0.0f, 0.0f}, _cubes[1].get(), &_drawables)); _cubes[2] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[2]->rotateY(Deg(45.0f)); _cubes[2]->translate({-10.0f, 0.0f, 0.0f}); _cubeDrawables[2] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 0.0f, 1.0f}, _cubes[2].get(), &_drawables)); _cubes[3] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[3]->rotateY(Deg(45.0f)); _cubes[3]->translate({0.0f, 0.0f, 7.0f}); _cubeDrawables[3] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 1.0f, 1.0f}, _cubes[3].get(), &_drawables)); /* setup compositor layers */ _layer = &LibOvrIntegration::Context::get().compositor().addLayerEyeFov(); _layer->setFov(*_hmd.get()); _layer->setHighQuality(true); /* setup cameras */ _eyes[0].setParent(&_cameraObject); _eyes[1].setParent(&_cameraObject); for(int eye = 0; eye < 2; ++eye) { /* projection matrix is set in the camera, since it requires some hmd-specific fov etc. */ _cameras[eye].reset(new HmdCamera(*_hmd, eye, _eyes[eye])); _layer->setColorTexture(eye, _cameras[eye]->textureSet()); _layer->setViewport(eye, {{}, _cameras[eye]->viewport()}); } } OvrExample::~OvrExample() { } void OvrExample::drawEvent() { /* get orientation and position of the hmd. */ std::array<DualQuaternion, 2> poses = _hmd->pollEyePoses().eyePoses(); /* draw the scene for both cameras */ for(int eye = 0; eye < 2; ++eye) { /* set the transformation according to rift trackers */ _eyes[eye].setTransformation(poses[eye].toMatrix()); /* render each eye. */ _cameras[eye]->draw(_drawables); } /* set the layers eye poses to the poses chached in the _hmd. */ _layer->setRenderPoses(*_hmd.get()); /* let the libOVR sdk compositor do its magic! */ LibOvrIntegration::Context::get().compositor().submitFrame(*_hmd.get()); /* blit mirror texture to defaultFramebuffer. */ const Vector2i size = _mirrorTexture->imageSize(0); Framebuffer::blit(*_mirrorFramebuffer, defaultFramebuffer, {{0, size.y()}, {size.x(), 0}}, {{}, size}, FramebufferBlit::Color, FramebufferBlitFilter::Nearest); if(_hmd->isDebugHmd()) { /* provide some rotation, but only without real devices to avoid vr sickness ;) */ _cameraObject.rotateY(Deg(0.1f)); } swapBuffers(); redraw(); } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::OvrExample) <commit_msg>ovr: Show the performance HUD with F11.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015 Vladimír Vondruš <mosra@centrum.cz> Copyright © 2015 Jonathan Hale <squareys@googlemail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <memory.h> #include <Corrade/Containers/Array.h> #include <Magnum/Magnum.h> #include <Magnum/Math/Vector2.h> #include <Magnum/Math/Vector3.h> #include <Magnum/Mesh.h> #include <Corrade/Utility/utilities.h> #include <Magnum/Buffer.h> #include <Magnum/DefaultFramebuffer.h> #include <Magnum/Renderer.h> #include <Magnum/MeshTools/Interleave.h> #include <Magnum/MeshTools/CompressIndices.h> #include <Magnum/Platform/Sdl2Application.h> #include <Magnum/Primitives/Cube.h> #include <Magnum/Shaders/Phong.h> #include <Magnum/Trade/MeshData3D.h> #include <Magnum/Math/Quaternion.h> #include <Magnum/SceneGraph/Scene.h> #include <Magnum/SceneGraph/Drawable.h> #include <Magnum/SceneGraph/Camera.h> #include <Magnum/Framebuffer.h> #include <Magnum/Renderbuffer.h> #include <Magnum/Texture.h> #include <Magnum/TextureFormat.h> #include <Magnum/Context.h> #include "Types.h" #include "HmdCamera.h" #include "CubeDrawable.h" #include <Magnum/LibOvrIntegration/LibOvrIntegration.h> #include <Magnum/LibOvrIntegration/Context.h> #include <Magnum/LibOvrIntegration/Hmd.h> #include <Magnum/LibOvrIntegration/HmdEnum.h> namespace Magnum { namespace Examples { using namespace LibOvrIntegration; /** * @brief The Application class of OvrExample. * @author Jonathan Hale (Squareys) */ class OvrExample: public Platform::Application { public: explicit OvrExample(const Arguments& arguments); virtual ~OvrExample(); protected: virtual void keyPressEvent(KeyEvent& event) override; private: void drawEvent() override; LibOvrIntegration::Context _ovrContext; std::unique_ptr<Hmd> _hmd; std::unique_ptr<Buffer> _indexBuffer, _vertexBuffer; std::unique_ptr<Mesh> _mesh; std::unique_ptr<Shaders::Phong> _shader; Scene3D _scene; Object3D _cameraObject; Object3D _eyes[2]; SceneGraph::DrawableGroup3D _drawables; std::unique_ptr<HmdCamera> _cameras[2]; std::unique_ptr<Object3D> _cubes[4]; std::unique_ptr<CubeDrawable> _cubeDrawables[4]; std::unique_ptr<Framebuffer> _mirrorFramebuffer; Texture2D* _mirrorTexture; LayerEyeFov* _layer; PerformanceHudMode _curPerfHudMode; }; OvrExample::OvrExample(const Arguments& arguments) : Platform::Application(arguments, nullptr), _indexBuffer(nullptr), _vertexBuffer(nullptr), _mesh(nullptr), _shader(nullptr), _scene(), _cameraObject(&_scene), _curPerfHudMode(PerformanceHudMode::Off) { /* connect to an Hmd, or create a debug hmd with DK2 type in case none is connected. */ _hmd = LibOvrIntegration::Context::get().createHmd(0, HmdType::DK2); /* get the hmd display resolution */ Vector2i resolution = _hmd->resolution() / 2; /* create a context with the hmd display resolution */ Configuration conf; conf.setTitle("Magnum OculusVR Example") .setSize(resolution) .setSampleCount(16); if(!tryCreateContext(conf)) createContext(conf.setSampleCount(0)); /* the oculus sdk compositor does some "magic" to reduce latency. For * that to work, vsync needs to be turned off. */ if(!setSwapInterval(0)) Error() << "Could not turn off vsync."; Renderer::enable(Renderer::Feature::DepthTest); _hmd->setEnabledCaps(HmdCapability::LowPersistence | HmdCapability::DynamicPrediction ); _hmd->configureTracking(HmdTrackingCapability::Orientation | HmdTrackingCapability::MagYawCorrection | HmdTrackingCapability::Position, {}); _hmd->configureRendering(); /* setup mirroring of oculus sdk compositor results to a texture which can later be blitted * onto the defaultFramebuffer. */ _mirrorTexture = &_hmd->createMirrorTexture(TextureFormat::RGBA, resolution); _mirrorFramebuffer.reset(new Framebuffer(Range2Di::fromSize({}, resolution))); _mirrorFramebuffer->attachTexture(Framebuffer::ColorAttachment(0), *_mirrorTexture, 0) .mapForRead(Framebuffer::ColorAttachment(0)); /* Setup cube mesh. */ const Trade::MeshData3D cube = Primitives::Cube::solid(); _vertexBuffer.reset(new Buffer()); _vertexBuffer->setData( MeshTools::interleave(cube.positions(0), cube.normals(0)), BufferUsage::StaticDraw); Containers::Array<char> indexData; Mesh::IndexType indexType; UnsignedInt indexStart, indexEnd; std::tie(indexData, indexType, indexStart, indexEnd) = MeshTools::compressIndices(cube.indices()); _indexBuffer.reset(new Buffer()); _indexBuffer->setData(indexData, BufferUsage::StaticDraw); _mesh.reset(new Mesh()); _mesh->setPrimitive(cube.primitive()).setCount(cube.indices().size()).addVertexBuffer( *_vertexBuffer, 0, Shaders::Phong::Position {}, Shaders::Phong::Normal {}).setIndexBuffer(*_indexBuffer, 0, indexType, indexStart, indexEnd); /* setup shader */ _shader.reset(new Shaders::Phong()); /* setup scene */ _cubes[0] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[0]->rotateY(Deg(45.0f)); _cubes[0]->translate({0.0f, 0.0f, -3.0f}); _cubeDrawables[0] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 1.0f, 0.0f}, _cubes[0].get(), &_drawables)); _cubes[1] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[1]->rotateY(Deg(45.0f)); _cubes[1]->translate({5.0f, 0.0f, 0.0f}); _cubeDrawables[1] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {1.0f, 0.0f, 0.0f}, _cubes[1].get(), &_drawables)); _cubes[2] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[2]->rotateY(Deg(45.0f)); _cubes[2]->translate({-10.0f, 0.0f, 0.0f}); _cubeDrawables[2] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 0.0f, 1.0f}, _cubes[2].get(), &_drawables)); _cubes[3] = std::unique_ptr<Object3D>(new Object3D(&_scene)); _cubes[3]->rotateY(Deg(45.0f)); _cubes[3]->translate({0.0f, 0.0f, 7.0f}); _cubeDrawables[3] = std::unique_ptr<CubeDrawable>(new CubeDrawable(_mesh.get(), _shader.get(), {0.0f, 1.0f, 1.0f}, _cubes[3].get(), &_drawables)); /* setup compositor layers */ _layer = &LibOvrIntegration::Context::get().compositor().addLayerEyeFov(); _layer->setFov(*_hmd.get()); _layer->setHighQuality(true); /* setup cameras */ _eyes[0].setParent(&_cameraObject); _eyes[1].setParent(&_cameraObject); for(int eye = 0; eye < 2; ++eye) { /* projection matrix is set in the camera, since it requires some hmd-specific fov etc. */ _cameras[eye].reset(new HmdCamera(*_hmd, eye, _eyes[eye])); _layer->setColorTexture(eye, _cameras[eye]->textureSet()); _layer->setViewport(eye, {{}, _cameras[eye]->viewport()}); } } OvrExample::~OvrExample() { } void OvrExample::drawEvent() { /* get orientation and position of the hmd. */ std::array<DualQuaternion, 2> poses = _hmd->pollEyePoses().eyePoses(); /* draw the scene for both cameras */ for(int eye = 0; eye < 2; ++eye) { /* set the transformation according to rift trackers */ _eyes[eye].setTransformation(poses[eye].toMatrix()); /* render each eye. */ _cameras[eye]->draw(_drawables); } /* set the layers eye poses to the poses chached in the _hmd. */ _layer->setRenderPoses(*_hmd.get()); /* let the libOVR sdk compositor do its magic! */ LibOvrIntegration::Context::get().compositor().submitFrame(*_hmd.get()); /* blit mirror texture to defaultFramebuffer. */ const Vector2i size = _mirrorTexture->imageSize(0); Framebuffer::blit(*_mirrorFramebuffer, defaultFramebuffer, {{0, size.y()}, {size.x(), 0}}, {{}, size}, FramebufferBlit::Color, FramebufferBlitFilter::Nearest); if(_hmd->isDebugHmd()) { /* provide some rotation, but only without real devices to avoid vr sickness ;) */ _cameraObject.rotateY(Deg(0.1f)); } swapBuffers(); redraw(); } void OvrExample::keyPressEvent(KeyEvent& event) { if(event.key() == KeyEvent::Key::F11) { /* toggle through the performance hud modes */ switch(_curPerfHudMode) { case PerformanceHudMode::Off: _curPerfHudMode = PerformanceHudMode::LatencyTiming; break; case PerformanceHudMode::LatencyTiming: _curPerfHudMode = PerformanceHudMode::RenderTiming; break; case PerformanceHudMode::RenderTiming: _curPerfHudMode = PerformanceHudMode::Off; break; } /** libovr has a bug where performance hud will block the app when using a debug hmd */ if(!_hmd->isDebugHmd()) { _hmd->setPerformanceHudMode(_curPerfHudMode); } } } }} MAGNUM_APPLICATION_MAIN(Magnum::Examples::OvrExample) <|endoftext|>
<commit_before>/*------------------------------------------------------------------------- * * FILE * robusttransaction.cxx * * DESCRIPTION * implementation of the pqxx::robusttransaction class. * pqxx::robusttransaction is a slower but safer transaction class * * Copyright (c) 2002-2005, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler.h" #include <stdexcept> #include "pqxx/connection_base" #include "pqxx/result" #include "pqxx/robusttransaction" using namespace PGSTD; using namespace pqxx::internal; // TODO: Use two-phase transaction if backend supports it #define SQL_COMMIT_WORK "COMMIT" #define SQL_ROLLBACK_WORK "ROLLBACK" pqxx::basic_robusttransaction::basic_robusttransaction(connection_base &C, const string &IsolationLevel, const string &TName) : dbtransaction(C, IsolationLevel, TName, "robusttransaction<"+IsolationLevel+">"), m_ID(oid_none), m_LogTable(), m_backendpid(-1) { m_LogTable = string("PQXXLOG_") + conn().username(); } pqxx::basic_robusttransaction::~basic_robusttransaction() { } void pqxx::basic_robusttransaction::do_begin() { start_backend_transaction(); try { CreateTransactionRecord(); } catch (const exception &) { // The problem here *may* be that the log table doesn't exist yet. Create // one, start a new transaction, and try again. try { DirectExec(SQL_ROLLBACK_WORK); } catch (const exception &e) {} CreateLogTable(); start_backend_transaction(); m_backendpid = conn().backendpid(); CreateTransactionRecord(); } } void pqxx::basic_robusttransaction::do_commit() { const IDType ID = m_ID; if (ID == oid_none) throw logic_error("libpqxx internal error: transaction " "'" + name() + "' " "has no ID"); // Check constraints before sending the COMMIT to the database to reduce the // work being done inside our in-doubt window. It also implicitly provides // one last check that our connection is really working before sending the // commit command. // // This may not be an entirely clear-cut 100% obvious unambiguous Good Thing. // If we lose our connection during the in-doubt window, it may be better if // the transaction didn't actually go though, and having constraints checked // first theoretically makes it more likely that it will once we get to that // stage. // // However, it seems reasonable to assume that most transactions will satisfy // their constraints. Besides, the goal of robusttransaction is to weed out // indeterminacy, rather than to improve the odds of desirable behaviour when // all bets are off anyway. DirectExec("SET CONSTRAINTS ALL IMMEDIATE"); // Here comes the critical part. If we lose our connection here, we'll be // left clueless as to whether the backend got the message and is trying to // commit the transaction (let alone whether it will succeed if so). This // case requires some special handling that makes robusttransaction what it // is. try { DirectExec(SQL_COMMIT_WORK); } catch (const exception &e) { // TODO: Can we limit this handler to broken_connection exceptions? m_ID = oid_none; if (!conn().is_open()) { // We've lost the connection while committing. We'll have to go back to // the backend and check our transaction log to see what happened. process_notice(e.what() + string("\n")); // See if transaction record ID exists; if yes, our transaction was // committed before the connection went down. If not, the transaction // was aborted. bool Exists; try { Exists = CheckTransactionRecord(ID); } catch (const exception &f) { // Couldn't check for transaction record. We're still in doubt as to // whether the transaction was performed. const string Msg = "WARNING: " "Connection lost while committing transaction " "'" + name() + "' (oid " + to_string(ID) + "). " "Please check for this record in the " "'" + m_LogTable + "' table. " "If the record exists, the transaction was executed. " "If not, then it wasn't.\n"; process_notice(Msg); process_notice("Could not verify existence of transaction record " "because of the following error:\n"); process_notice(string(f.what()) + "\n"); throw in_doubt_error(Msg); } // Transaction record is gone, so all we have is a "normal" transaction // failure. if (!Exists) throw; } else { // Commit failed--probably due to a constraint violation or something // similar. But we're still connected, so no worries from a consistency // point of view. // Try to delete transaction record ID, if it still exists (although it // really shouldn't) DeleteTransactionRecord(ID); throw; } } m_ID = oid_none; DeleteTransactionRecord(ID); } void pqxx::basic_robusttransaction::do_abort() { m_ID = oid_none; // Rollback transaction. Our transaction record will be dropped as a side // effect, which is what we want since "it never happened." DirectExec(SQL_ROLLBACK_WORK); } // Create transaction log table if it didn't already exist void pqxx::basic_robusttransaction::CreateLogTable() { // Create log table in case it doesn't already exist. This code must only be // executed before the backend transaction has properly started. const string CrTab = "CREATE TABLE " + m_LogTable + "(" "name VARCHAR(256), " "date TIMESTAMP" ")"; try { DirectExec(CrTab.c_str(), 1); } catch (const exception &) { } } void pqxx::basic_robusttransaction::CreateTransactionRecord() { // TODO: Might as well include real transaction ID and backend PID const string Insert = "INSERT INTO " + m_LogTable + " " "(name, date) " "VALUES " "(" + (name().empty() ? "null" : "'"+sqlesc(name())+"'") + ", " "CURRENT_TIMESTAMP" ")"; m_ID = DirectExec(Insert.c_str()).inserted_oid(); if (m_ID == oid_none) throw runtime_error("Could not create transaction log record"); } void pqxx::basic_robusttransaction::DeleteTransactionRecord(IDType ID) throw () { if (ID == oid_none) return; try { // Try very, very hard to delete record. Specify an absurd retry count to // ensure that the server gets a chance to restart before we give up. const string Del = "DELETE FROM " + m_LogTable + " " "WHERE oid=" + to_string(ID); DirectExec(Del.c_str(), 20); // Now that we've arrived here, we're almost sure that record is quite dead. ID = oid_none; } catch (const exception &) { } if (ID != oid_none) try { process_notice("WARNING: " "Failed to delete obsolete transaction record with oid " + to_string(ID) + " ('" + name() + "'). " "Please delete it manually. Thank you.\n"); } catch (const exception &) { } } // Attempt to establish whether transaction record with given ID still exists bool pqxx::basic_robusttransaction::CheckTransactionRecord(IDType ID) { /* First, wait for the old backend (with the lost connection) to die. * * On 2004-09-18, Tom Lane wrote: * * I don't see any reason for guesswork. Remember the PID of the backend * you were connected to. On reconnect, look in pg_stat_activity to see * if that backend is still alive; if so, sleep till it's not. Then check * to see if your transaction committed or not. No need for anything so * dangerous as a timeout. */ /* Actually, looking if the query has finished is only possible if the * stats_command_string has been set in postgresql.conf and we're running * as the postgres superuser. If we get a string saying this option has not * been enabled, we must wait as if the query were still executing--and hope * that the backend dies. */ // TODO: Tom says we need stats_start_collector, not stats_command_string!? /* Starting with PostgreSQL 7.4, we can use pg_locks. The entry for the * zombied transaction will have a "relation" field of null, a "transaction" * field with the transaction ID (which we don't have--m_ID is the ID of our * own transaction record!), and "pid" set to our backendpid. If the relation * exists but no such record is found, then the transaction is no longer * running. */ // TODO: Support multiple means of detection for zombied transaction? bool hold = true; for (int c=20; hold && c; internal::sleep_seconds(5), --c) { const result R(DirectExec(("SELECT current_query " "FROM pq_stat_activity " "WHERE procpid=" + to_string(m_backendpid)).c_str())); hold = (!R.empty() && !R[0][0].as(string()).empty() && (R[0][0].as(string()) != "<IDLE>")); } if (hold) throw runtime_error("Old backend process stays alive too long to wait for"); // Now look for our transaction record const string Find = "SELECT oid FROM " + m_LogTable + " " "WHERE oid=" + to_string(ID); return !DirectExec(Find.c_str(), 20).empty(); } <commit_msg>Transaction log table is now all lower-case everywhere; create table WITH OIDS if possible<commit_after>/*------------------------------------------------------------------------- * * FILE * robusttransaction.cxx * * DESCRIPTION * implementation of the pqxx::robusttransaction class. * pqxx::robusttransaction is a slower but safer transaction class * * Copyright (c) 2002-2005, Jeroen T. Vermeulen <jtv@xs4all.nl> * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. * *------------------------------------------------------------------------- */ #include "pqxx/compiler.h" #include <stdexcept> #include "pqxx/connection_base" #include "pqxx/result" #include "pqxx/robusttransaction" using namespace PGSTD; using namespace pqxx::internal; // TODO: Use two-phase transaction if backend supports it #define SQL_COMMIT_WORK "COMMIT" #define SQL_ROLLBACK_WORK "ROLLBACK" pqxx::basic_robusttransaction::basic_robusttransaction(connection_base &C, const string &IsolationLevel, const string &TName) : dbtransaction(C, IsolationLevel, TName, "robusttransaction<"+IsolationLevel+">"), m_ID(oid_none), m_LogTable(), m_backendpid(-1) { m_LogTable = string("pqxxlog_") + conn().username(); } pqxx::basic_robusttransaction::~basic_robusttransaction() { } void pqxx::basic_robusttransaction::do_begin() { start_backend_transaction(); try { CreateTransactionRecord(); } catch (const exception &) { // The problem here *may* be that the log table doesn't exist yet. Create // one, start a new transaction, and try again. try { DirectExec(SQL_ROLLBACK_WORK); } catch (const exception &e) {} CreateLogTable(); start_backend_transaction(); m_backendpid = conn().backendpid(); CreateTransactionRecord(); } } void pqxx::basic_robusttransaction::do_commit() { const IDType ID = m_ID; if (ID == oid_none) throw logic_error("libpqxx internal error: transaction " "'" + name() + "' " "has no ID"); // Check constraints before sending the COMMIT to the database to reduce the // work being done inside our in-doubt window. It also implicitly provides // one last check that our connection is really working before sending the // commit command. // // This may not be an entirely clear-cut 100% obvious unambiguous Good Thing. // If we lose our connection during the in-doubt window, it may be better if // the transaction didn't actually go though, and having constraints checked // first theoretically makes it more likely that it will once we get to that // stage. // // However, it seems reasonable to assume that most transactions will satisfy // their constraints. Besides, the goal of robusttransaction is to weed out // indeterminacy, rather than to improve the odds of desirable behaviour when // all bets are off anyway. DirectExec("SET CONSTRAINTS ALL IMMEDIATE"); // Here comes the critical part. If we lose our connection here, we'll be // left clueless as to whether the backend got the message and is trying to // commit the transaction (let alone whether it will succeed if so). This // case requires some special handling that makes robusttransaction what it // is. try { DirectExec(SQL_COMMIT_WORK); } catch (const exception &e) { m_ID = oid_none; if (!conn().is_open()) { // We've lost the connection while committing. We'll have to go back to // the backend and check our transaction log to see what happened. process_notice(e.what() + string("\n")); // See if transaction record ID exists; if yes, our transaction was // committed before the connection went down. If not, the transaction // was aborted. bool Exists; try { Exists = CheckTransactionRecord(ID); } catch (const exception &f) { // Couldn't check for transaction record. We're still in doubt as to // whether the transaction was performed. const string Msg = "WARNING: " "Connection lost while committing transaction " "'" + name() + "' (oid " + to_string(ID) + "). " "Please check for this record in the " "'" + m_LogTable + "' table. " "If the record exists, the transaction was executed. " "If not, then it wasn't.\n"; process_notice(Msg); process_notice("Could not verify existence of transaction record " "because of the following error:\n"); process_notice(string(f.what()) + "\n"); throw in_doubt_error(Msg); } // Transaction record is gone, so all we have is a "normal" transaction // failure. if (!Exists) throw; } else { // Commit failed--probably due to a constraint violation or something // similar. But we're still connected, so no worries from a consistency // point of view. // Try to delete transaction record ID, if it still exists (although it // really shouldn't) DeleteTransactionRecord(ID); throw; } } m_ID = oid_none; DeleteTransactionRecord(ID); } void pqxx::basic_robusttransaction::do_abort() { m_ID = oid_none; // Rollback transaction. Our transaction record will be dropped as a side // effect, which is what we want since "it never happened." DirectExec(SQL_ROLLBACK_WORK); } // Create transaction log table if it didn't already exist void pqxx::basic_robusttransaction::CreateLogTable() { // Create log table in case it doesn't already exist. This code must only be // executed before the backend transaction has properly started. string CrTab = "CREATE TABLE \"" + m_LogTable + "\" " "(" "name VARCHAR(256), " "date TIMESTAMP, " "CONSTRAINT identity UNIQUE(oid))"; if (conn().supports(connection_base::cap_create_table_with_oids)) CrTab += " WITH OIDS"; try { DirectExec(CrTab.c_str(), 1); } catch (const exception &) { } } void pqxx::basic_robusttransaction::CreateTransactionRecord() { static const string Fail = "Could not create transaction log record: "; // TODO: Might as well include real transaction ID and backend PID const string Insert = "INSERT INTO \"" + m_LogTable + "\" " "(name, date) " "VALUES " "(" + (name().empty() ? "null" : "'"+sqlesc(name())+"'") + ", " "CURRENT_TIMESTAMP" ")"; try { const result R(DirectExec(Insert.c_str())); m_ID = R.inserted_oid(); } catch (const sql_error &e) { throw sql_error(Fail+e.what(), Insert); } catch (const broken_connection &) { throw; } catch (const bad_alloc &) { throw; } catch (const out_of_range &e) { throw out_of_range(Fail+e.what()); } catch (const range_error &e) { throw range_error(Fail+e.what()); } catch (const invalid_argument &e) { throw invalid_argument(Fail+e.what()); } catch (const runtime_error &e) { throw runtime_error(Fail+e.what()); } catch (const domain_error &e) { throw domain_error(Fail+e.what()); } catch (const logic_error &e) { throw logic_error(Fail+e.what()); } catch (const exception &e) { throw sql_error(Fail+e.what(), Insert); } if (m_ID == oid_none) { if (conn().supports(connection_base::cap_create_table_with_oids)) throw runtime_error(Fail + "Transaction log table " + m_LogTable + " exists but does not seem\n" "to have been created with an implicit oid column.\n" "This column was automatically present in all tables prior to " "PostgreSQL 8.1.\n" "It may be missing here because the table was created by a libpqxx " "version prior to 2.6.0,\n" "or the table may have been imported from a PostgreSQL version prior " "to 8.1 without preserving the oid column.\n" "It should be safe to drop the table; a new one will then be created " "with the oid column present."); throw runtime_error(Fail + "For some reason the transaction log record " "was not assigned a valid oid by the backend."); } } void pqxx::basic_robusttransaction::DeleteTransactionRecord(IDType ID) throw () { if (ID == oid_none) return; try { // Try very, very hard to delete record. Specify an absurd retry count to // ensure that the server gets a chance to restart before we give up. const string Del = "DELETE FROM \"" + m_LogTable + "\" " "WHERE oid=" + to_string(ID); DirectExec(Del.c_str(), 20); // Now that we've arrived here, we're almost sure that record is quite dead. ID = oid_none; } catch (const exception &) { } if (ID != oid_none) try { process_notice("WARNING: " "Failed to delete obsolete transaction record with oid " + to_string(ID) + " ('" + name() + "'). " "Please delete it manually. Thank you.\n"); } catch (const exception &) { } } // Attempt to establish whether transaction record with given ID still exists bool pqxx::basic_robusttransaction::CheckTransactionRecord(IDType ID) { /* First, wait for the old backend (with the lost connection) to die. * * On 2004-09-18, Tom Lane wrote: * * I don't see any reason for guesswork. Remember the PID of the backend * you were connected to. On reconnect, look in pg_stat_activity to see * if that backend is still alive; if so, sleep till it's not. Then check * to see if your transaction committed or not. No need for anything so * dangerous as a timeout. */ /* Actually, looking if the query has finished is only possible if the * stats_command_string has been set in postgresql.conf and we're running * as the postgres superuser. If we get a string saying this option has not * been enabled, we must wait as if the query were still executing--and hope * that the backend dies. */ // TODO: Tom says we need stats_start_collector, not stats_command_string!? /* Starting with PostgreSQL 7.4, we can use pg_locks. The entry for the * zombied transaction will have a "relation" field of null, a "transaction" * field with the transaction ID (which we don't have--m_ID is the ID of our * own transaction record!), and "pid" set to our backendpid. If the relation * exists but no such record is found, then the transaction is no longer * running. */ // TODO: Support multiple means of detection for zombied transaction? bool hold = true; for (int c=20; hold && c; internal::sleep_seconds(5), --c) { const result R(DirectExec(("SELECT current_query " "FROM pq_stat_activity " "WHERE procpid=" + to_string(m_backendpid)).c_str())); hold = (!R.empty() && !R[0][0].as(string()).empty() && (R[0][0].as(string()) != "<IDLE>")); } if (hold) throw runtime_error("Old backend process stays alive too long to wait for"); // Now look for our transaction record const string Find = "SELECT oid FROM \"" + m_LogTable + "\" " "WHERE oid=" + to_string(ID); return !DirectExec(Find.c_str(), 20).empty(); } <|endoftext|>
<commit_before>/* * Copyright (c) 2013 - 2016, Roland Bock * 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. * * 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 HOLDER 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 "TabSample.h" #include <sqlpp11/mysql/mysql.h> #include <sqlpp11/sqlpp11.h> #include <cassert> #include <iostream> #include <vector> SQLPP_ALIAS_PROVIDER(left) SQLPP_ALIAS_PROVIDER(right) namespace mysql = sqlpp::mysql; int main() { mysql::global_library_init(); auto config = std::make_shared<mysql::connection_config>(); config->user = "root"; config->database = "sqlpp_mysql"; config->debug = true; try { mysql::connection db(config); } catch (const sqlpp::exception& e) { std::cerr << "For testing, you'll need to create a database sqlpp_mysql for user root (no password)" << std::endl; std::cerr << e.what() << std::endl; return 1; } try { mysql::connection db(config); db.execute(R"(DROP TABLE IF EXISTS tab_sample)"); db.execute(R"(CREATE TABLE tab_sample ( alpha bigint(20) AUTO_INCREMENT, beta varchar(255) DEFAULT NULL, gamma bool DEFAULT NULL, PRIMARY KEY (alpha) ))"); db.execute(R"(DROP TABLE IF EXISTS tab_foo)"); db.execute(R"(CREATE TABLE tab_foo ( omega bigint(20) DEFAULT NULL ))"); assert(not db(select(sqlpp::value(false).as(sqlpp::alias::a))).front().a); const auto tab = TabSample{}; // clear the table db(remove_from(tab).unconditionally()); // Several ways of ensuring that tab is empty assert(not db(select(exists(select(tab.alpha).from(tab).unconditionally()))) .front() .exists); // this is probably the fastest assert(not db(select(count(tab.alpha)).from(tab).unconditionally()).front().count); assert(db(select(tab.alpha).from(tab).unconditionally()).empty()); // explicit all_of(tab) std::cerr << __FILE__ << ": " << __LINE__ << std::endl; select(all_of(tab)).from(tab); std::cerr << __FILE__ << ": " << __LINE__ << std::endl; db(select(all_of(tab)).from(tab).unconditionally()); std::cerr << __FILE__ << ": " << __LINE__ << std::endl; for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally())) { std::cerr << __FILE__ << ": " << __LINE__ << std::endl; std::cerr << "row.alpha: " << row.alpha << ", row.beta: " << row.beta << ", row.gamma: " << row.gamma << std::endl; }; // insert db(insert_into(tab).default_values()); const auto x = select(all_of(tab)).from(tab).unconditionally(); const auto y = db.prepare(x); for (const auto& row : db(db.prepare(select(all_of(tab)).from(tab).unconditionally()))) { std::cerr << "alpha: " << row.alpha.is_null() << std::endl; std::cerr << "beta: " << row.beta.is_null() << std::endl; std::cerr << "gamma: " << row.gamma.is_null() << std::endl; } db(insert_into(tab).set(tab.beta = "kaesekuchen", tab.gamma = true)); db(insert_into(tab).default_values()); db(insert_into(tab).set(tab.beta = "", tab.gamma = true)); // update db(update(tab).set(tab.gamma = false).where(tab.alpha.in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); db(update(tab).set(tab.gamma = true).where(tab.alpha.in(1))); // remove db(remove_from(tab).where(tab.alpha == tab.alpha + 3)); std::cerr << "+++++++++++++++++++++++++++" << std::endl; for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally())) { std::cerr << __LINE__ << " row.beta: " << row.beta << std::endl; } std::cerr << "+++++++++++++++++++++++++++" << std::endl; decltype(db(select(all_of(tab)).from(tab).unconditionally())) result; result = db(select(all_of(tab)).from(tab).unconditionally()); std::cerr << "Accessing a field directly from the result (using the current row): " << result.begin()->alpha << std::endl; std::cerr << "Can do that again, no problem: " << result.begin()->alpha << std::endl; auto tx = start_transaction(db); if (const auto& row = *db(select(all_of(tab), select(max(tab.alpha)).from(tab)).from(tab).unconditionally()).begin()) { int a = row.alpha; int m = row.max; std::cerr << __LINE__ << " row.alpha: " << a << ", row.max: " << m << std::endl; } tx.commit(); TabFoo foo; for (const auto& row : db(select(tab.alpha).from(tab.join(foo).on(tab.alpha == foo.omega)).unconditionally())) { std::cerr << row.alpha << std::endl; } for (const auto& row : db(select(tab.alpha).from(tab.left_outer_join(foo).on(tab.alpha == foo.omega)).unconditionally())) { std::cerr << row.alpha << std::endl; } auto ps = db.prepare(select(all_of(tab)) .from(tab) .where(tab.alpha != parameter(tab.alpha) and tab.beta != parameter(tab.beta) and tab.gamma != parameter(tab.gamma))); ps.params.alpha = 7; ps.params.beta = "wurzelbrunft"; ps.params.gamma = true; for (const auto& row : db(ps)) { std::cerr << "bound result: alpha: " << row.alpha << std::endl; std::cerr << "bound result: beta: " << row.beta << std::endl; std::cerr << "bound result: gamma: " << row.gamma << std::endl; } std::cerr << "--------" << std::endl; ps.params.gamma = "false"; for (const auto& row : db(ps)) { std::cerr << "bound result: alpha: " << row.alpha << std::endl; std::cerr << "bound result: beta: " << row.beta << std::endl; std::cerr << "bound result: gamma: " << row.gamma << std::endl; } std::cerr << "--------" << std::endl; ps.params.beta = "kaesekuchen"; for (const auto& row : db(ps)) { std::cerr << "bound result: alpha: " << row.alpha << std::endl; std::cerr << "bound result: beta: " << row.beta << std::endl; std::cerr << "bound result: gamma: " << row.gamma << std::endl; } auto pi = db.prepare(insert_into(tab).set(tab.beta = parameter(tab.beta), tab.gamma = true)); pi.params.beta = "prepared cake"; std::cerr << "Inserted: " << db(pi) << std::endl; auto pu = db.prepare(update(tab).set(tab.gamma = parameter(tab.gamma)).where(tab.beta == "prepared cake")); pu.params.gamma = false; std::cerr << "Updated: " << db(pu) << std::endl; auto pr = db.prepare(remove_from(tab).where(tab.beta != parameter(tab.beta))); pr.params.beta = "prepared cake"; std::cerr << "Deleted lines: " << db(pr) << std::endl; for (const auto& row : db(select(case_when(tab.gamma).then(tab.alpha).else_(foo.omega).as(tab.alpha)) .from(tab.cross_join(foo)) .unconditionally())) { std::cerr << row.alpha << std::endl; } } catch (const std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return 1; } } <commit_msg>Add dynamic_insert_into test.<commit_after>/* * Copyright (c) 2013 - 2016, Roland Bock * 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. * * 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 HOLDER 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 "TabSample.h" #include <sqlpp11/mysql/mysql.h> #include <sqlpp11/sqlpp11.h> #include <cassert> #include <iostream> #include <vector> SQLPP_ALIAS_PROVIDER(left) SQLPP_ALIAS_PROVIDER(right) namespace mysql = sqlpp::mysql; int main() { mysql::global_library_init(); auto config = std::make_shared<mysql::connection_config>(); config->user = "root"; config->database = "sqlpp_mysql"; config->debug = true; try { mysql::connection db(config); } catch (const sqlpp::exception& e) { std::cerr << "For testing, you'll need to create a database sqlpp_mysql for user root (no password)" << std::endl; std::cerr << e.what() << std::endl; return 1; } try { mysql::connection db(config); db.execute(R"(DROP TABLE IF EXISTS tab_sample)"); db.execute(R"(CREATE TABLE tab_sample ( alpha bigint(20) AUTO_INCREMENT, beta varchar(255) DEFAULT NULL, gamma bool DEFAULT NULL, PRIMARY KEY (alpha) ))"); db.execute(R"(DROP TABLE IF EXISTS tab_foo)"); db.execute(R"(CREATE TABLE tab_foo ( omega bigint(20) DEFAULT NULL ))"); assert(not db(select(sqlpp::value(false).as(sqlpp::alias::a))).front().a); const auto tab = TabSample{}; // clear the table db(remove_from(tab).unconditionally()); // Several ways of ensuring that tab is empty assert(not db(select(exists(select(tab.alpha).from(tab).unconditionally()))) .front() .exists); // this is probably the fastest assert(not db(select(count(tab.alpha)).from(tab).unconditionally()).front().count); assert(db(select(tab.alpha).from(tab).unconditionally()).empty()); // explicit all_of(tab) std::cerr << __FILE__ << ": " << __LINE__ << std::endl; select(all_of(tab)).from(tab); std::cerr << __FILE__ << ": " << __LINE__ << std::endl; db(select(all_of(tab)).from(tab).unconditionally()); std::cerr << __FILE__ << ": " << __LINE__ << std::endl; for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally())) { std::cerr << __FILE__ << ": " << __LINE__ << std::endl; std::cerr << "row.alpha: " << row.alpha << ", row.beta: " << row.beta << ", row.gamma: " << row.gamma << std::endl; }; // insert db(insert_into(tab).default_values()); const auto x = select(all_of(tab)).from(tab).unconditionally(); const auto y = db.prepare(x); for (const auto& row : db(db.prepare(select(all_of(tab)).from(tab).unconditionally()))) { std::cerr << "alpha: " << row.alpha.is_null() << std::endl; std::cerr << "beta: " << row.beta.is_null() << std::endl; std::cerr << "gamma: " << row.gamma.is_null() << std::endl; } db(insert_into(tab).set(tab.beta = "kaesekuchen", tab.gamma = true)); db(insert_into(tab).default_values()); db(insert_into(tab).set(tab.beta = "", tab.gamma = true)); // update db(update(tab).set(tab.gamma = false).where(tab.alpha.in(sqlpp::value_list(std::vector<int>{1, 2, 3, 4})))); db(update(tab).set(tab.gamma = true).where(tab.alpha.in(1))); // dynamic insert auto dynin = dynamic_insert_into(db, tab).dynamic_set(tab.gamma = true); dynin.insert_list.add(tab.beta = "cheesecake"); db(dynin); // remove db(remove_from(tab).where(tab.alpha == tab.alpha + 3)); std::cerr << "+++++++++++++++++++++++++++" << std::endl; for (const auto& row : db(select(all_of(tab)).from(tab).unconditionally())) { std::cerr << __LINE__ << " row.beta: " << row.beta << std::endl; } std::cerr << "+++++++++++++++++++++++++++" << std::endl; decltype(db(select(all_of(tab)).from(tab).unconditionally())) result; result = db(select(all_of(tab)).from(tab).unconditionally()); std::cerr << "Accessing a field directly from the result (using the current row): " << result.begin()->alpha << std::endl; std::cerr << "Can do that again, no problem: " << result.begin()->alpha << std::endl; auto tx = start_transaction(db); if (const auto& row = *db(select(all_of(tab), select(max(tab.alpha)).from(tab)).from(tab).unconditionally()).begin()) { int a = row.alpha; int m = row.max; std::cerr << __LINE__ << " row.alpha: " << a << ", row.max: " << m << std::endl; } tx.commit(); TabFoo foo; for (const auto& row : db(select(tab.alpha).from(tab.join(foo).on(tab.alpha == foo.omega)).unconditionally())) { std::cerr << row.alpha << std::endl; } for (const auto& row : db(select(tab.alpha).from(tab.left_outer_join(foo).on(tab.alpha == foo.omega)).unconditionally())) { std::cerr << row.alpha << std::endl; } auto ps = db.prepare(select(all_of(tab)) .from(tab) .where(tab.alpha != parameter(tab.alpha) and tab.beta != parameter(tab.beta) and tab.gamma != parameter(tab.gamma))); ps.params.alpha = 7; ps.params.beta = "wurzelbrunft"; ps.params.gamma = true; for (const auto& row : db(ps)) { std::cerr << "bound result: alpha: " << row.alpha << std::endl; std::cerr << "bound result: beta: " << row.beta << std::endl; std::cerr << "bound result: gamma: " << row.gamma << std::endl; } std::cerr << "--------" << std::endl; ps.params.gamma = "false"; for (const auto& row : db(ps)) { std::cerr << "bound result: alpha: " << row.alpha << std::endl; std::cerr << "bound result: beta: " << row.beta << std::endl; std::cerr << "bound result: gamma: " << row.gamma << std::endl; } std::cerr << "--------" << std::endl; ps.params.beta = "kaesekuchen"; for (const auto& row : db(ps)) { std::cerr << "bound result: alpha: " << row.alpha << std::endl; std::cerr << "bound result: beta: " << row.beta << std::endl; std::cerr << "bound result: gamma: " << row.gamma << std::endl; } auto pi = db.prepare(insert_into(tab).set(tab.beta = parameter(tab.beta), tab.gamma = true)); pi.params.beta = "prepared cake"; std::cerr << "Inserted: " << db(pi) << std::endl; auto pu = db.prepare(update(tab).set(tab.gamma = parameter(tab.gamma)).where(tab.beta == "prepared cake")); pu.params.gamma = false; std::cerr << "Updated: " << db(pu) << std::endl; auto pr = db.prepare(remove_from(tab).where(tab.beta != parameter(tab.beta))); pr.params.beta = "prepared cake"; std::cerr << "Deleted lines: " << db(pr) << std::endl; for (const auto& row : db(select(case_when(tab.gamma).then(tab.alpha).else_(foo.omega).as(tab.alpha)) .from(tab.cross_join(foo)) .unconditionally())) { std::cerr << row.alpha << std::endl; } } catch (const std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return 1; } } <|endoftext|>
<commit_before>9904d35e-2e4d-11e5-9284-b827eb9e62be<commit_msg>9909cc9c-2e4d-11e5-9284-b827eb9e62be<commit_after>9909cc9c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/* MPL3115A2 Barometric Pressure Sensor Library By: Nathan Seidle SparkFun Electronics Date: September 24th, 2013 License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license). Get pressure, altitude and temperature from the MPL3115A2 sensor. September 6, 2016: Modified for use in OpenROV's Software */ #include <Arduino.h> #include <CI2C.h> #include "MPL3115A2.h" using namespace mpl3115a2; MPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn ) : m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS ) , m_pI2C( i2cInterfaceIn ) , m_sensorId( 420 ) { } ERetCode MPL3115A2::Initialize() { m_isInitialized = false; delay( 500 ); //Verify that the sensor is up and running if( VerifyChipId() != ERetCode::SUCCESS ) { //We were unable to verify this sensor return ERetCode::FAILED; } m_isInitialized = true; return ERetCode::SUCCESS; } ERetCode MPL3115A2::SetMode( EMode modeIn ) { switch (modeIn) { case EMode::BAROMETER: { return SetModeBarometer(); } case EMode::ALTIMETER: { return SetModeAltimeter(); } case EMode::STANDBY: { return SetModeStandby(); } case EMode::ACTIVE: { return SetModeActive(); } default: { return ERetCode::FAILED; } } } //Call with a rate from 0 to 7. See page 33 for table of ratios. //Sets the over sample rate. Datasheet calls for 128 but you can set it //from 1 to 128 samples. The higher the oversample rate the greater //the time between data samples. ERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn ) { int32_t returnCode; auto sampleRate = static_cast<int>( osrIn ); //Align it for the control register sampleRate <<= 3; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Clear out old Oversample bits tempSetting &= B11000111; //Mask new sample rate tempSetting |= sampleRate; //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Enables the pressure and temp measurement event flags so that we can //test against them. This is recommended in datasheet during setup. ERetCode MPL3115A2::EnableEventFlags() { // Enable all three pressure and temp event flags auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Reads the current pressure in Pa //Unit must be set in barometric pressure mode ERetCode MPL3115A2::ReadPressure( float& pressureOut ) { Serial.println( "In read pressure loop" ); ToggleOneShot(); int32_t returnCode; uint8_t pdr; //Wait for PDR bit, indicates we have new pressure data auto counter = 0; while( ( pdr & (1<<2) ) == 0 ) { Serial.println( counter ); returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_PRESSURE_READ; } if( ++counter > 100 ) { return ERetCode::TIMED_OUT; } delay(1); } //Read pressure registers uint8_t buffer[3]; memset( buffer, 0, 3); returnCode = ReadNBytes( MPL3115A2_REGISTER::PRESSURE_OUT_MSB, buffer, 3 ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_PRESSURE_READ; } //Toggle the OST bit causing the sensor to immediately take another reading ToggleOneShot(); auto msb = buffer[0]; auto csb = buffer[1]; auto lsb = buffer[2]; // Pressure comes back as a left shifted 20 bit number uint64_t pressure = (uint64_t)msb<<16 | (uint64_t)csb<<8 | (uint64_t)lsb; //Pressure is an 18 bit number with 2 bits of decimal. Get rid of decimal portion. pressure >>= 6; //Bits 5/4 represent the fractional component lsb &= B00110000; //Get it right aligned lsb >>= 4; //Turn it into fraction float pressure_decimal = (float)lsb/4.0; pressureOut = (float)pressure + pressure_decimal; return ERetCode::SUCCESS; } /*************************************************************************** PRIVATE FUNCTIONS ***************************************************************************/ ERetCode MPL3115A2::VerifyChipId() { //Read the chip id uint8_t id; auto ret = ReadByte( MPL3115A2_REGISTER::WHO_AM_I, id ); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Check to see if it matches the proper ID (0xC4) if( id != 0xC4 ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } ERetCode MPL3115A2::SetModeBarometer() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Clear the altimeter bit tempSetting &= ~(1<<7); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } m_mode = tempSetting; return ERetCode::SUCCESS; } ERetCode MPL3115A2::SetModeAltimeter() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Set the altimeter bit tempSetting |= (1<<7); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Puts the sensor in standby mode //This is needed so that we can modify the major control registers ERetCode MPL3115A2::SetModeStandby() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Clear SBYB bit for Standby mode tempSetting &= ~(1<<0); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Puts the sensor in active mode //This is needed so that we can modify the major control registers ERetCode MPL3115A2::SetModeActive() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Set SBYB bit for Active mode tempSetting |= (1<<0); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Clears and then sets the OST bit which causes the sensor to take another readings //Needed to sample faster than 1Hz ERetCode MPL3115A2::ToggleOneShot() { Serial.println( "Toggling one shot." ); Serial.print( "Mode: " ); Serial.println( m_mode ); int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } //Clear the one shot bit tempSetting &= ~(1<<1); returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } //Reat the current settings, just to be safe :) returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } //Set the overshot bit tempSetting |= (1<<1); returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } return ERetCode::SUCCESS; } int32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn ) { return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn ); } int32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut ) { return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut ); } int32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn ) { return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn ); }<commit_msg>Debug<commit_after>/* MPL3115A2 Barometric Pressure Sensor Library By: Nathan Seidle SparkFun Electronics Date: September 24th, 2013 License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license). Get pressure, altitude and temperature from the MPL3115A2 sensor. September 6, 2016: Modified for use in OpenROV's Software */ #include <Arduino.h> #include <CI2C.h> #include "MPL3115A2.h" using namespace mpl3115a2; MPL3115A2::MPL3115A2( CI2C *i2cInterfaceIn ) : m_i2cAddress( mpl3115a2::MPL3115A2_ADDRESS ) , m_pI2C( i2cInterfaceIn ) , m_sensorId( 420 ) { } ERetCode MPL3115A2::Initialize() { m_isInitialized = false; delay( 500 ); //Verify that the sensor is up and running if( VerifyChipId() != ERetCode::SUCCESS ) { //We were unable to verify this sensor return ERetCode::FAILED; } m_isInitialized = true; return ERetCode::SUCCESS; } ERetCode MPL3115A2::SetMode( EMode modeIn ) { switch (modeIn) { case EMode::BAROMETER: { return SetModeBarometer(); } case EMode::ALTIMETER: { return SetModeAltimeter(); } case EMode::STANDBY: { return SetModeStandby(); } case EMode::ACTIVE: { return SetModeActive(); } default: { return ERetCode::FAILED; } } } //Call with a rate from 0 to 7. See page 33 for table of ratios. //Sets the over sample rate. Datasheet calls for 128 but you can set it //from 1 to 128 samples. The higher the oversample rate the greater //the time between data samples. ERetCode MPL3115A2::SetOversampleRatio( EOversampleRatio osrIn ) { int32_t returnCode; auto sampleRate = static_cast<int>( osrIn ); //Align it for the control register sampleRate <<= 3; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Clear out old Oversample bits tempSetting &= B11000111; //Mask new sample rate tempSetting |= sampleRate; //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Enables the pressure and temp measurement event flags so that we can //test against them. This is recommended in datasheet during setup. ERetCode MPL3115A2::EnableEventFlags() { // Enable all three pressure and temp event flags auto ret = WriteByte( MPL3115A2_REGISTER::PT_DATA_CFG, 0x07); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Reads the current pressure in Pa //Unit must be set in barometric pressure mode ERetCode MPL3115A2::ReadPressure( float& pressureOut ) { Serial.println( "In read pressure loop" ); ToggleOneShot(); int32_t returnCode; uint8_t pdr; //Wait for PDR bit, indicates we have new pressure data auto counter = 0; returnCode = ReadByte( MPL3115A2_REGISTER::STATUS, pdr ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_PRESSURE_READ; } Serial.println(pdr, HEX); // while( ( pdr & (1<<2) ) == 0 ) // { // Serial.println( counter ); // if( ++counter > 100 ) // { // return ERetCode::TIMED_OUT; // } // delay(1); // } //Read pressure registers uint8_t buffer[3]; memset( buffer, 0, 3); returnCode = ReadNBytes( MPL3115A2_REGISTER::PRESSURE_OUT_MSB, buffer, 3 ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_PRESSURE_READ; } //Toggle the OST bit causing the sensor to immediately take another reading ToggleOneShot(); auto msb = buffer[0]; auto csb = buffer[1]; auto lsb = buffer[2]; // Pressure comes back as a left shifted 20 bit number uint64_t pressure = (uint64_t)msb<<16 | (uint64_t)csb<<8 | (uint64_t)lsb; //Pressure is an 18 bit number with 2 bits of decimal. Get rid of decimal portion. pressure >>= 6; //Bits 5/4 represent the fractional component lsb &= B00110000; //Get it right aligned lsb >>= 4; //Turn it into fraction float pressure_decimal = (float)lsb/4.0; pressureOut = (float)pressure + pressure_decimal; return ERetCode::SUCCESS; } /*************************************************************************** PRIVATE FUNCTIONS ***************************************************************************/ ERetCode MPL3115A2::VerifyChipId() { //Read the chip id uint8_t id; auto ret = ReadByte( MPL3115A2_REGISTER::WHO_AM_I, id ); if( ret != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Check to see if it matches the proper ID (0xC4) if( id != 0xC4 ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } ERetCode MPL3115A2::SetModeBarometer() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Clear the altimeter bit tempSetting &= ~(1<<7); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } m_mode = tempSetting; return ERetCode::SUCCESS; } ERetCode MPL3115A2::SetModeAltimeter() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Set the altimeter bit tempSetting |= (1<<7); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Puts the sensor in standby mode //This is needed so that we can modify the major control registers ERetCode MPL3115A2::SetModeStandby() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Clear SBYB bit for Standby mode tempSetting &= ~(1<<0); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Puts the sensor in active mode //This is needed so that we can modify the major control registers ERetCode MPL3115A2::SetModeActive() { int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } //Set SBYB bit for Active mode tempSetting |= (1<<0); //And write it to the register returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED; } return ERetCode::SUCCESS; } //Clears and then sets the OST bit which causes the sensor to take another readings //Needed to sample faster than 1Hz ERetCode MPL3115A2::ToggleOneShot() { Serial.println( "Toggling one shot." ); Serial.print( "Mode: " ); Serial.println( m_mode ); int32_t returnCode; //Read the current settings uint8_t tempSetting; returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } //Clear the one shot bit tempSetting &= ~(1<<1); returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } //Reat the current settings, just to be safe :) returnCode = ReadByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } //Set the overshot bit tempSetting |= (1<<1); returnCode = WriteByte( MPL3115A2_REGISTER::CONTROL_REGISTER_1, tempSetting ); if( returnCode != I2C::ERetCode::SUCCESS ) { return ERetCode::FAILED_ONESHOT; } return ERetCode::SUCCESS; } int32_t MPL3115A2::WriteByte( MPL3115A2_REGISTER addressIn, uint8_t dataIn ) { return (int32_t)m_pI2C->WriteByte( m_i2cAddress, (uint8_t)addressIn, dataIn ); } int32_t MPL3115A2::ReadByte( MPL3115A2_REGISTER addressIn, uint8_t &dataOut ) { return (int32_t)m_pI2C->ReadByte( m_i2cAddress, (uint8_t)addressIn, &dataOut ); } int32_t MPL3115A2::ReadNBytes( MPL3115A2_REGISTER addressIn, uint8_t* dataOut, uint8_t byteCountIn ) { return (int32_t)m_pI2C->ReadBytes( m_i2cAddress, (uint8_t)addressIn, dataOut, byteCountIn ); }<|endoftext|>
<commit_before>c1f0d122-2e4e-11e5-9284-b827eb9e62be<commit_msg>c1f5c8d0-2e4e-11e5-9284-b827eb9e62be<commit_after>c1f5c8d0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before><commit_msg>Planning: adjust log level for easier debug<commit_after><|endoftext|>
<commit_before>#include "p0compile/parser.hpp" #include "p0compile/expression_tree.hpp" #include "p0compile/scanner.hpp" #include "p0compile/compiler_error.hpp" #include <boost/test/unit_test.hpp> namespace { bool handle_unexpected_error(p0::compiler_error const &error) { (void)error; BOOST_CHECK(nullptr == "No error expected"); return true; } } BOOST_AUTO_TEST_CASE(parse_empty_file_test) { std::string const source = ""; p0::source_range const source_range( source.data(), source.data() + source.size()); p0::scanner scanner(source_range); p0::parser parser(scanner, handle_unexpected_error); auto const ast = parser.parse_unit(); BOOST_REQUIRE(ast); } <commit_msg>generalize parser test<commit_after>#include "p0compile/parser.hpp" #include "p0compile/expression_tree.hpp" #include "p0compile/scanner.hpp" #include "p0compile/compiler_error.hpp" #include <boost/test/unit_test.hpp> namespace { bool handle_unexpected_error(p0::compiler_error const &error) { (void)error; BOOST_CHECK(nullptr == "No error expected"); return true; } template <class ASTHandler> void test_parser(std::string const &source, ASTHandler const &handle_ast) { p0::source_range const source_range( source.data(), source.data() + source.size()); p0::scanner scanner(source_range); p0::parser parser(scanner, handle_unexpected_error); auto const ast = parser.parse_unit(); BOOST_REQUIRE(ast); handle_ast(*ast); } } BOOST_AUTO_TEST_CASE(parse_empty_file_test) { test_parser("", [](p0::function_tree const &ast) { BOOST_CHECK(ast.parameters().empty()); //TODO check empty body }); } <|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "History.hpp" #include <QSettings> #include <ndb/query.hpp> #include <ndb/function.hpp> #include "Web/WebView.hpp" #include "History/HistoryModel.hpp" namespace Sn { QString History::titleCaseLocalizedMonth(int month) { switch (month) { case 1: return tr("January"); case 2: return tr("February"); case 3: return tr("March"); case 4: return tr("April"); case 5: return tr("May"); case 6: return tr("June"); case 7: return tr("July"); case 8: return tr("August"); case 9: return tr("September"); case 10: return tr("October"); case 11: return tr("November"); case 12: return tr("December"); default: qWarning("Month number out of range!"); return QString(); } } History::History(QObject* parent) : QObject(parent) { loadSettings(); } History::~History() { // Empty } HistoryModel *History::model() { if (!m_model) m_model = new HistoryModel(this); return m_model; } void History::addHistoryEntry(WebView* view) { if (!m_isSaving) return; const QUrl url{view->url()}; const QString title{view->title()}; addHistoryEntry(url, title); } void History::addHistoryEntry(const QUrl& url, QString title) { if (!m_isSaving) return; const QStringList ignoredSchemes = { QStringLiteral("sielo"), QStringLiteral("view-source"), QStringLiteral("file"), QStringLiteral("data") }; if (url.isEmpty() || ignoredSchemes.contains(url.scheme())) return; if (title.isEmpty()) title = tr("Empty page"); auto oquery = ndb::oquery<dbs::navigation>() << (history.url == url.toString()); if (!oquery.has_result()) { ndb::query<dbs::navigation>() + ( history.title = title, history.url = url.toString(), history.date = QDateTime::currentMSecsSinceEpoch(), history.count = 1 ); qint64 id = ndb::last_id<dbs::navigation>(); HistoryEntry entry{}; entry.id = id; entry.count = 1; entry.date = QDateTime::currentDateTime(); entry.url = url; entry.urlString = url.toEncoded(); entry.title = title; emit historyEntryAdded(entry); } else { qint64 id{oquery[0].id}; qint64 count{oquery[0].count}; QDateTime date{QDateTime::fromMSecsSinceEpoch(oquery[0].date)}; QString oldTitle{oquery[0].title}; ndb::query<dbs::navigation>() >> ( ( history.count = count + 1, history.date = QDateTime::currentMSecsSinceEpoch(), history.title = title ) << (history.url == url.toString()) ); HistoryEntry before{}; before.id = id; before.count = count; before.date = date; before.url = url; before.urlString = url.toEncoded(); before.title = oldTitle; HistoryEntry after = before; after.count = count + 1; after.date = QDateTime::currentDateTime(); after.title = title; emit historyEntryEdited(before, after); } } void History::deleteHistoryEntry(int index) { QList<int> list{}; list.append(index); deleteHistoryEntry(list); } void History::deleteHistoryEntry(const QList<int>& list) { for (int index : list) { auto query = ndb::oquery<dbs::navigation>() << (history.id == index); if (!query.has_result()) return; HistoryEntry entry{query[0]}; ndb::query<dbs::navigation>() - (history.id == index); ndb::query<dbs::navigation>() - (history.url == QString::fromUtf8(entry.url.toEncoded(QUrl::RemoveFragment))); emit historyEntryDeleted(entry); } } void History::deleteHistoryEntry(const QString& url, const QString& title) { auto query = ndb::query<dbs::navigation>() << ((history.id) << (history.url == url && history.title == title)); if (query.has_result()) { int id = query[0][history.id]; deleteHistoryEntry(id); } } QList<int> History::indexesFromTimeRange(qint64 start, qint64 end) { QList<int> list{}; if (start < 0 || end < 0) return list; for (auto& data : ndb::query<dbs::navigation>() << ((history.id) << ndb::range( history.date, end, start))) list.append(data[history.id]); return list; } bool History::urlIsStored(const QString& url) { auto query = ndb::query<dbs::navigation>() << (history.url == url); return query.has_result(); } QVector<History::HistoryEntry> History::mostVisited(int count) { QVector<HistoryEntry> list{}; //auto oquery = ndb::oquery<dbs::navigation>() << ((ndb::sort(ndb::desc(history.count)) << ndb::limit(count))); //for (auto& data : oquery) { // HistoryEntry entry{data}; // list.append(entry); //} for (auto& data : ndb::query<dbs::navigation>() << ((history.id, history.url, history.title, history.count, history.date) << (ndb::sort(ndb::desc(history.count)) << ndb::limit(count)))) { HistoryEntry entry{}; entry.id = data[history.id]; entry.date = QDateTime::fromMSecsSinceEpoch(data[history.date]); entry.url = QUrl(data[history.url]); entry.urlString = QUrl(data[history.url]).toEncoded(); entry.title = data[history.title]; list.append(entry); } return list; } void History::clearHistory() { ndb::clear<dbs::navigation>(history); Application::instance()->webProfile()->clearAllVisitedLinks(); emit resetHistory(); } void History::setSaving(bool state) { m_isSaving = state; } void History::loadSettings() { QSettings settings{}; settings.beginGroup("Web-Settings"); m_isSaving = settings.value("allowHistory", true).toBool(); settings.endGroup(); } } <commit_msg>[Update] Replace ndb by Qt queries<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "History.hpp" #include <QSettings> #include <QSqlQuery> #include "Web/WebView.hpp" #include "History/HistoryModel.hpp" namespace Sn { QString History::titleCaseLocalizedMonth(int month) { switch (month) { case 1: return tr("January"); case 2: return tr("February"); case 3: return tr("March"); case 4: return tr("April"); case 5: return tr("May"); case 6: return tr("June"); case 7: return tr("July"); case 8: return tr("August"); case 9: return tr("September"); case 10: return tr("October"); case 11: return tr("November"); case 12: return tr("December"); default: qWarning("Month number out of range!"); return QString(); } } History::History(QObject* parent) : QObject(parent) { loadSettings(); } History::~History() { // Empty } HistoryModel *History::model() { if (!m_model) m_model = new HistoryModel(this); return m_model; } void History::addHistoryEntry(WebView* view) { if (!m_isSaving) return; const QUrl url{view->url()}; const QString title{view->title()}; addHistoryEntry(url, title); } void History::addHistoryEntry(const QUrl& url, QString title) { if (!m_isSaving) return; const QStringList ignoredSchemes = { QStringLiteral("sielo"), QStringLiteral("view-source"), QStringLiteral("file"), QStringLiteral("data") }; if (url.isEmpty() || ignoredSchemes.contains(url.scheme())) return; if (title.isEmpty()) title = tr("Empty page"); QSqlQuery query(SqlDatabase::instance()->database()); query.prepare("SELECT id, count, date, title FROM history WHERE url=?"); query.bindValue(0, url); query.exec(); if (!query.next()) { query.prepare("INSERT INTO history (count, date, url, title) VALUES (1,?,?,?)"); query.bindValue(0, QDateTime::currentMSecsSinceEpoch()); query.bindValue(1, url); query.bindValue(2, title); query.exec(); int id = query.lastInsertId().toInt(); HistoryEntry entry; entry.id = id; entry.count = 1; entry.date = QDateTime::currentDateTime(); entry.url = url; entry.urlString = url.toEncoded(); entry.title = title; emit historyEntryAdded(entry); } else { int id = query.value(0).toInt(); int count = query.value(1).toInt(); QDateTime date = QDateTime::fromMSecsSinceEpoch(query.value(2).toLongLong()); QString oldTitle = query.value(3).toString(); query.prepare("UPDATE history SET count = count + 1, date=?, title=? WHERE url=?"); query.bindValue(0, QDateTime::currentMSecsSinceEpoch()); query.bindValue(1, title); query.bindValue(2, url); query.exec(); HistoryEntry before; before.id = id; before.count = count; before.date = date; before.url = url; before.urlString = url.toEncoded(); before.title = oldTitle; HistoryEntry after = before; after.count = count + 1; after.date = QDateTime::currentDateTime(); after.title = title; emit historyEntryEdited(before, after); } } void History::deleteHistoryEntry(int index) { QList<int> list{}; list.append(index); deleteHistoryEntry(list); } void History::deleteHistoryEntry(const QList<int>& list) { QSqlDatabase db = SqlDatabase::instance()->database(); db.transaction(); QList<QUrl> urls; for (int index : list) { QSqlQuery query{SqlDatabase::instance()->database()}; query.prepare("SELECT count, date, url, title FROM history WHERE id=?"); query.addBindValue(index); query.exec(); if (!query.isActive() || !query.next()) continue; HistoryEntry entry{}; entry.id = index; entry.count = query.value(0).toInt(); entry.date = QDateTime::fromMSecsSinceEpoch(query.value(1).toLongLong()); entry.url = query.value(2).toUrl(); entry.urlString = entry.url.toEncoded(); entry.title = query.value(3).toString(); query.prepare("DELETE FROM history WHERE id=?"); query.addBindValue(index); query.exec(); query.prepare("DELETE FROM icons WHERE url=?"); query.addBindValue(entry.url.toEncoded(QUrl::RemoveFragment)); query.exec(); urls.append(entry.url); emit historyEntryDeleted(entry); } Application::instance()->webProfile()->clearVisitedLinks(urls); db.commit(); } void History::deleteHistoryEntry(const QString& url, const QString& title) { QSqlQuery query{SqlDatabase::instance()->database())}; query.prepare("SELECT id FROM history WHERE url=? AND title=?"); query.bindValue(0, url); query.bindValue(1, title); query.exec(); if (query.next()) { const int id{query.value(0).toInt()}; deleteHistoryEntry(id); } } QList<int> History::indexesFromTimeRange(qint64 start, qint64 end) { QList<int> list{}; if (start < 0 || end < 0) return list; QSqlQuery query{SqlDatabase::instance()->database()}; query.prepare("SELECT id FROM history WHERE date BETWEEN ? AND ?"); query.addBindValue(end); query.addBindValue(start); query.exec(); while (query.next()) list.append(query.value(0).toInt()); return list; } bool History::urlIsStored(const QString& url) { QSqlQuery query{SqlDatabase::instance()->database()}; query.prepare("SELECT id FROM history WHERE url=?"); query.bindValue(0, url); query.exec(); return query.next(); } QVector<History::HistoryEntry> History::mostVisited(int count) { QVector<HistoryEntry> list; QSqlQuery query{SqlDatabase::instance()->database()}; query.prepare(QString("SELECT count, date, id, title, url FROM history ORDER BY count DESC LIMIT %1").arg(count)); query.exec(); while (query.next()) { HistoryEntry entry{}; entry.count = query.value(0).toInt(); entry.date = query.value(1).toDateTime(); entry.id = query.value(2).toInt(); entry.title = query.value(3).toString(); entry.url = query.value(4).toUrl(); list.append(entry); } return list; } void History::clearHistory() { QSqlQuery query{SqlDatabase::instance()->database()}; query.exec("DELETE FROM history"); query.exec("VACUUM"); Application::instance()->webProfile()->clearAllVisitedLinks(); emit resetHistory(); } void History::setSaving(bool state) { m_isSaving = state; } void History::loadSettings() { QSettings settings{}; settings.beginGroup("Web-Settings"); m_isSaving = settings.value("allowHistory", true).toBool(); settings.endGroup(); } } <|endoftext|>
<commit_before>c5287cf2-2e4c-11e5-9284-b827eb9e62be<commit_msg>c52d77de-2e4c-11e5-9284-b827eb9e62be<commit_after>c52d77de-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5dc45f6c-2e4d-11e5-9284-b827eb9e62be<commit_msg>5dc96d04-2e4d-11e5-9284-b827eb9e62be<commit_after>5dc96d04-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>874b912a-2e4d-11e5-9284-b827eb9e62be<commit_msg>875087ca-2e4d-11e5-9284-b827eb9e62be<commit_after>875087ca-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>54c5d0ee-2e4d-11e5-9284-b827eb9e62be<commit_msg>54cae1ec-2e4d-11e5-9284-b827eb9e62be<commit_after>54cae1ec-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2944d95a-2e4e-11e5-9284-b827eb9e62be<commit_msg>2949e97c-2e4e-11e5-9284-b827eb9e62be<commit_after>2949e97c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>c5ef8fb8-2e4c-11e5-9284-b827eb9e62be<commit_msg>c5f47d02-2e4c-11e5-9284-b827eb9e62be<commit_after>c5f47d02-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>5c18e952-2e4e-11e5-9284-b827eb9e62be<commit_msg>5c1df0c8-2e4e-11e5-9284-b827eb9e62be<commit_after>5c1df0c8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>abc122a8-2e4e-11e5-9284-b827eb9e62be<commit_msg>abc623c0-2e4e-11e5-9284-b827eb9e62be<commit_after>abc623c0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>b51566f8-2e4d-11e5-9284-b827eb9e62be<commit_msg>b51a5b22-2e4d-11e5-9284-b827eb9e62be<commit_after>b51a5b22-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>e45b24d0-2e4c-11e5-9284-b827eb9e62be<commit_msg>e46034ca-2e4c-11e5-9284-b827eb9e62be<commit_after>e46034ca-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>016bc550-2e4f-11e5-9284-b827eb9e62be<commit_msg>0170cb54-2e4f-11e5-9284-b827eb9e62be<commit_after>0170cb54-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>17a26b5a-2e4d-11e5-9284-b827eb9e62be<commit_msg>17a774d8-2e4d-11e5-9284-b827eb9e62be<commit_after>17a774d8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6ebf7040-2e4d-11e5-9284-b827eb9e62be<commit_msg>6ed4f762-2e4d-11e5-9284-b827eb9e62be<commit_after>6ed4f762-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>043901fe-2e4e-11e5-9284-b827eb9e62be<commit_msg>043dfab0-2e4e-11e5-9284-b827eb9e62be<commit_after>043dfab0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>12492a4e-2e4e-11e5-9284-b827eb9e62be<commit_msg>124e22ce-2e4e-11e5-9284-b827eb9e62be<commit_after>124e22ce-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>21b351bc-2e4e-11e5-9284-b827eb9e62be<commit_msg>21b87f84-2e4e-11e5-9284-b827eb9e62be<commit_after>21b87f84-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>45a5b99e-2e4d-11e5-9284-b827eb9e62be<commit_msg>45aab0b6-2e4d-11e5-9284-b827eb9e62be<commit_after>45aab0b6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>3703d7ac-2e4f-11e5-9284-b827eb9e62be<commit_msg>3708d9e6-2e4f-11e5-9284-b827eb9e62be<commit_after>3708d9e6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>2e3b5fa6-2e4e-11e5-9284-b827eb9e62be<commit_msg>2e409c6e-2e4e-11e5-9284-b827eb9e62be<commit_after>2e409c6e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>0f4af184-2e4d-11e5-9284-b827eb9e62be<commit_msg>0f4fe9fa-2e4d-11e5-9284-b827eb9e62be<commit_after>0f4fe9fa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>