<commit_before>/******************************************************************************\
 *           ___        __                                                    *
 *          /\_ \    __/\ \                                                   *
 *          \//\ \  /\_\ \ \____    ___   _____   _____      __               *
 *            \ \ \ \/\ \ \ '__`\  /'___\/\ '__`\/\ '__`\  /'__`\             *
 *             \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_           *
 *             /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\          *
 *             \/____/ \/_/\/___/  \/____/ \ \ \/  \ \ \/  \/__/\/_/          *
 *                                          \ \_\   \ \_\                     *
 *                                           \/_/    \/_/                     *
 *                                                                            *
 * Copyright (C) 2011-2013                                                    *
 * Dominik Charousset <dominik.charousset@haw-hamburg.de>                     *
 *                                                                            *
 * This file is part of libcppa.                                              *
 * libcppa is free software: you can redistribute it and/or modify it under   *
 * the terms of the GNU Lesser General Public License as published by the     *
 * Free Software Foundation; either version 2.1 of the License,               *
 * or (at your option) any later version.                                     *
 *                                                                            *
 * libcppa is distributed in the hope that it will be useful,                 *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                       *
 * See the GNU Lesser General Public License for more details.                *
 *                                                                            *
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with libcppa. If not, see <http://www.gnu.org/licenses/>.            *
\******************************************************************************/

#ifndef OPTIONAL_VARIANT_HPP
#define OPTIONAL_VARIANT_HPP

#include <stdexcept>
#include <type_traits>

#include "cppa/none.hpp"
#include "cppa/unit.hpp"
#include "cppa/optional.hpp"
#include "cppa/match_hint.hpp"

#include "cppa/util/type_list.hpp"
#include "cppa/util/type_traits.hpp"

#include "cppa/detail/optional_variant_data.hpp"

#define CPPA_OPTIONAL_VARIANT_CASE(x)                                          \
    case x: return do_visit(from, visitor,                                     \
                            make_bool_token<void_pos == x >(),                 \
                            make_int_token< x >())                             \

namespace cppa {

template<int Value>
constexpr std::integral_constant<int, Value> make_int_token() { return {}; }

template<bool Value>
constexpr std::integral_constant<bool, Value> make_bool_token() { return {}; }

template<typename T>
struct optional_variant_copy_helper {
    T& lhs;
    optional_variant_copy_helper(T& lhs_ref) : lhs(lhs_ref) { }
    template<typename U>
    inline void operator()(const U& rhs) const {
        lhs = rhs;
    }
    inline void operator()() const {
        lhs = unit;
    }
};

template<typename T>
struct optional_variant_move_helper {
    T& lhs;
    optional_variant_move_helper(T& lhs_ref) : lhs(lhs_ref) { }
    template<typename U>
    inline void operator()(const U& rhs) const {
        lhs = std::move(rhs);
    }
    inline void operator()() const {
        lhs = unit;
    }
};

template<typename... Ts>
class optional_variant;

template<typename T>
struct is_optional_variant {
    static constexpr bool value = false;
};

template<typename... Ts>
struct is_optional_variant<optional_variant<Ts...>> {
    static constexpr bool value = true;
};

/**
 * @brief A optional_variant is either invalid or holds
          a value of one of the types <tt>Ts</tt>.
 */
template<typename... Ts>
class optional_variant {

 public:

    typedef util::type_list<Ts...> types;

    static constexpr int void_pos = util::tl_find<types, void>::value;

    static constexpr bool has_match_hint = util::tl_find<types, match_hint>::value != -1;

    /**
     * @brief Checks whether this objects holds a value of type @p T.
     */
    template<typename T>
    inline bool is() const {
        return m_type != -1 && m_type == util::tl_find<types, T>::value;
    }

    template<typename U>
    optional_variant& operator=(U&& arg) {
        destroy_data();
        set(std::forward<U>(arg));
        return *this;
    }

    optional_variant& operator=(const optional_variant& other) {
        destroy_data();
        optional_variant_copy_helper<optional_variant> helper{*this};
        other.apply(helper);
        return *this;
    }

    optional_variant& operator=(optional_variant&& other) {
        destroy_data();
        optional_variant_move_helper<optional_variant> helper{*this};
        other.apply(helper);
        return *this;
    }

    optional_variant() : m_type(-1) { }

    template<typename U>
    optional_variant(U&& arg) {
        set(std::forward<U>(arg));
    }

    optional_variant(const optional_variant& other) : m_type(-1) {
        optional_variant_copy_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    optional_variant(optional_variant&& other) : m_type(-1) {
        optional_variant_move_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    ~optional_variant() {
        destroy_data();
    }

    /**
     * @brief Checks whether this optional_variant is valid.
     */
    inline explicit operator bool() const {
        return m_type != -1;
    }

    /**
     * @brief Checks whether this optional_variant is invalid.
     */
    inline bool operator!() const {
        return m_type == -1;
    }

    /** @cond PRIVATE */

    template<int Pos>
    inline const typename util::tl_at<types, Pos>::type&
    get(std::integral_constant<int, Pos> token,
        typename std::enable_if<Pos < sizeof...(Ts) && Pos != void_pos>::type* = nullptr) const {
        return m_data.get(token);
    }

    template<int Pos>
    inline void get(std::integral_constant<int, Pos>,
                    typename std::enable_if<Pos >= sizeof...(Ts) || Pos == void_pos>::type* = nullptr) const { }

    template<int Pos>
    inline typename util::tl_at<types, Pos>::type&
    get(std::integral_constant<int, Pos> token,
        typename std::enable_if<Pos < sizeof...(Ts) && Pos != void_pos>::type* = nullptr) {
        return m_data.get(token);
    }

    template<typename Visitor>
    auto apply(const Visitor& visitor) const -> decltype(visitor(none_t{})) {
        return do_apply(*this, visitor);
    }

    template<typename Visitor>
    auto apply(const Visitor& visitor) -> decltype(visitor(none_t{})) {
        return do_apply(*this, visitor);
    }

    /** @endcond */

 private:

    template<typename Self, typename Visitor, int Pos>
    static auto do_visit(Self& from,
                         const Visitor& visitor,
                         std::integral_constant<bool, false> /* is_not_void */,
                         std::integral_constant<int, Pos> token,
                         typename std::enable_if<Pos < sizeof...(Ts)>::type* = nullptr)
    -> decltype(visitor(none_t{})) {
        return visitor(from.get(token));
    }

    template<typename Self, typename Visitor, int Pos>
    static auto do_visit(Self&,
                         const Visitor& visitor,
                         std::integral_constant<bool, true> /* is_void */,
                         std::integral_constant<int, Pos>,
                         typename std::enable_if<Pos < sizeof...(Ts)>::type* = nullptr)
    -> decltype(visitor(none_t{})) {
        return visitor();
    }

    template<typename Self, typename Visitor, int Pos>
    static auto do_visit(Self&,
                         const Visitor& visitor,
                         std::integral_constant<bool, false>,
                         std::integral_constant<int, Pos>,
                         typename std::enable_if<Pos >= sizeof...(Ts)>::type* = nullptr)
    -> decltype(visitor(none_t{})) {
        // this is not the function you are looking for
        throw std::runtime_error("invalid type found");
    }

    template<typename Self, typename Visitor>
    static auto do_apply(Self& from, const Visitor& visitor) -> decltype(visitor(none_t{})) {
        switch (from.m_type) {
            default: throw std::runtime_error("invalid type found");
            case -1: return visitor(none_t{});
            CPPA_OPTIONAL_VARIANT_CASE(0);
            CPPA_OPTIONAL_VARIANT_CASE(1);
            CPPA_OPTIONAL_VARIANT_CASE(2);
            CPPA_OPTIONAL_VARIANT_CASE(3);
            CPPA_OPTIONAL_VARIANT_CASE(4);
            CPPA_OPTIONAL_VARIANT_CASE(5);
            CPPA_OPTIONAL_VARIANT_CASE(6);
            CPPA_OPTIONAL_VARIANT_CASE(7);
            CPPA_OPTIONAL_VARIANT_CASE(8);
            CPPA_OPTIONAL_VARIANT_CASE(9);
        }
    }

    inline void destroy_data() {
        apply(detail::optional_variant_data_destructor{});
    }

    template<typename U>
    typename std::enable_if<
           !std::is_same<typename util::rm_const_and_ref<U>::type, none_t>::value
        && !is_optional_variant<typename util::rm_const_and_ref<U>::type>::value
        && !is_optional<typename util::rm_const_and_ref<U>::type>::value
    >::type
    set(U&& arg) {
        typedef typename util::rm_const_and_ref<U>::type stripped_type;
        typedef typename detail::unlift_void<stripped_type>::type type;
        static constexpr int type_id = util::tl_find<types, type>::value;
        static_assert(type_id != -1, "invalid type");
        m_type = type_id;
        auto& ref = m_data.get(make_int_token<type_id>());
        new (&ref) stripped_type (std::forward<U>(arg));
    }

    inline void set(const optional_variant& other) {
        optional_variant_copy_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    inline void set(optional_variant&& other) {
        optional_variant_move_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    template<typename T>
    inline void set(const optional<T>& arg) {
        if (arg) set(*arg);
        else set(none);
    }

    template<typename T>
    inline void set(optional<T>&& arg) {
        if (arg) set(std::move(*arg));
        else set(none);
    }

    inline void set(const none_t&) { m_type = -1; }

    int m_type;
    detail::optional_variant_data<typename detail::lift_void<Ts>::type...> m_data;

};

/**
 * @relates optional_variant
 */
template<typename T, typename... Us>
const T& get(const optional_variant<Us...>& value) {
    std::integral_constant<int, util::tl_find<util::type_list<Us...>, T>::value> token;
    return value.get(token);
}

/**
 * @relates optional_variant
 */
template<typename T, typename... Us>
T& get_ref(optional_variant<Us...>& value) {
    std::integral_constant<int, util::tl_find<util::type_list<Us...>, T>::value> token;
    return value.get(token);
}

/**
 * @relates optional_variant
 */
template<typename Visitor, typename... Ts>
auto apply_visitor(const Visitor& visitor, const optional_variant<Ts...>& data) -> decltype(visitor(none_t{})) {
    return data.apply(visitor);
}

/**
 * @relates optional_variant
 */
template<typename Visitor, typename... Ts>
auto apply_visitor(const Visitor& visitor, optional_variant<Ts...>& data) -> decltype(visitor(none_t{})) {
    return data.apply(visitor);
}

template<typename T>
struct optional_variant_from_type_list;

template<typename... Ts>
struct optional_variant_from_type_list<util::type_list<Ts...>> {
    typedef optional_variant<Ts...> type;
};

} // namespace cppa

#endif // OPTIONAL_VARIANT_HPP
<commit_msg>added operator== and streaming to optional_variant<commit_after>/******************************************************************************\
 *           ___        __                                                    *
 *          /\_ \    __/\ \                                                   *
 *          \//\ \  /\_\ \ \____    ___   _____   _____      __               *
 *            \ \ \ \/\ \ \ '__`\  /'___\/\ '__`\/\ '__`\  /'__`\             *
 *             \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_           *
 *             /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\          *
 *             \/____/ \/_/\/___/  \/____/ \ \ \/  \ \ \/  \/__/\/_/          *
 *                                          \ \_\   \ \_\                     *
 *                                           \/_/    \/_/                     *
 *                                                                            *
 * Copyright (C) 2011-2013                                                    *
 * Dominik Charousset <dominik.charousset@haw-hamburg.de>                     *
 *                                                                            *
 * This file is part of libcppa.                                              *
 * libcppa is free software: you can redistribute it and/or modify it under   *
 * the terms of the GNU Lesser General Public License as published by the     *
 * Free Software Foundation; either version 2.1 of the License,               *
 * or (at your option) any later version.                                     *
 *                                                                            *
 * libcppa is distributed in the hope that it will be useful,                 *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                       *
 * See the GNU Lesser General Public License for more details.                *
 *                                                                            *
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with libcppa. If not, see <http://www.gnu.org/licenses/>.            *
\******************************************************************************/

#ifndef OPTIONAL_VARIANT_HPP
#define OPTIONAL_VARIANT_HPP

#include <iosfwd>
#include <stdexcept>
#include <type_traits>

#include "cppa/none.hpp"
#include "cppa/unit.hpp"
#include "cppa/optional.hpp"
#include "cppa/match_hint.hpp"

#include "cppa/util/type_list.hpp"
#include "cppa/util/type_traits.hpp"

#include "cppa/detail/optional_variant_data.hpp"

#define CPPA_OPTIONAL_VARIANT_CASE(x)                                          \
    case x: return do_visit(from, visitor,                                     \
                            make_bool_token<void_pos == x >(),                 \
                            make_int_token< x >())                             \

namespace cppa {

template<int Value>
constexpr std::integral_constant<int, Value> make_int_token() { return {}; }

template<bool Value>
constexpr std::integral_constant<bool, Value> make_bool_token() { return {}; }

template<typename T>
struct optional_variant_copy_helper {
    T& lhs;
    optional_variant_copy_helper(T& lhs_ref) : lhs(lhs_ref) { }
    template<typename U>
    inline void operator()(const U& rhs) const {
        lhs = rhs;
    }
    inline void operator()() const {
        lhs = unit;
    }
};

template<typename T>
struct optional_variant_move_helper {
    T& lhs;
    optional_variant_move_helper(T& lhs_ref) : lhs(lhs_ref) { }
    template<typename U>
    inline void operator()(const U& rhs) const {
        lhs = std::move(rhs);
    }
    inline void operator()() const {
        lhs = unit;
    }
};

template<typename... Ts>
class optional_variant;

template<typename T>
struct is_optional_variant {
    static constexpr bool value = false;
};

template<typename... Ts>
struct is_optional_variant<optional_variant<Ts...>> {
    static constexpr bool value = true;
};

/**
 * @brief A optional_variant is either invalid or holds
          a value of one of the types <tt>Ts</tt>.
 */
template<typename... Ts>
class optional_variant {

 public:

    typedef util::type_list<Ts...> types;

    static constexpr int void_pos = util::tl_find<types, void>::value;

    static constexpr bool has_match_hint = util::tl_find<types, match_hint>::value != -1;

    /**
     * @brief Checks whether this objects holds a value of type @p T.
     */
    template<typename T>
    inline bool is() const {
        return m_type != -1 && m_type == util::tl_find<types, T>::value;
    }

    template<typename U>
    optional_variant& operator=(U&& arg) {
        destroy_data();
        set(std::forward<U>(arg));
        return *this;
    }

    optional_variant& operator=(const optional_variant& other) {
        destroy_data();
        optional_variant_copy_helper<optional_variant> helper{*this};
        other.apply(helper);
        return *this;
    }

    optional_variant& operator=(optional_variant&& other) {
        destroy_data();
        optional_variant_move_helper<optional_variant> helper{*this};
        other.apply(helper);
        return *this;
    }

    optional_variant() : m_type(-1) { }

    template<typename U>
    optional_variant(U&& arg) {
        set(std::forward<U>(arg));
    }

    optional_variant(const optional_variant& other) : m_type(-1) {
        optional_variant_copy_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    optional_variant(optional_variant&& other) : m_type(-1) {
        optional_variant_move_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    ~optional_variant() {
        destroy_data();
    }

    /**
     * @brief Checks whether this optional_variant is valid.
     */
    inline explicit operator bool() const {
        return m_type != -1;
    }

    /**
     * @brief Checks whether this optional_variant is invalid.
     */
    inline bool operator!() const {
        return m_type == -1;
    }

    /** @cond PRIVATE */

    template<int Pos>
    inline const typename util::tl_at<types, Pos>::type&
    get(std::integral_constant<int, Pos> token,
        typename std::enable_if<Pos < sizeof...(Ts) && Pos != void_pos>::type* = nullptr) const {
        return m_data.get(token);
    }

    template<int Pos>
    inline void get(std::integral_constant<int, Pos>,
                    typename std::enable_if<Pos >= sizeof...(Ts) || Pos == void_pos>::type* = nullptr) const { }

    template<int Pos>
    inline typename util::tl_at<types, Pos>::type&
    get(std::integral_constant<int, Pos> token,
        typename std::enable_if<Pos < sizeof...(Ts) && Pos != void_pos>::type* = nullptr) {
        return m_data.get(token);
    }

    template<typename Visitor>
    auto apply(Visitor& visitor) const -> decltype(visitor(none_t{})) {
        return do_apply(*this, visitor);
    }

    template<typename Visitor>
    auto apply(Visitor& visitor) -> decltype(visitor(none_t{})) {
        return do_apply(*this, visitor);
    }

    /** @endcond */

 private:

    template<typename Self, typename Visitor, int Pos>
    static auto do_visit(Self& from,
                         const Visitor& visitor,
                         std::integral_constant<bool, false> /* is_not_void */,
                         std::integral_constant<int, Pos> token,
                         typename std::enable_if<Pos < sizeof...(Ts)>::type* = nullptr)
    -> decltype(visitor(none_t{})) {
        return visitor(from.get(token));
    }

    template<typename Self, typename Visitor, int Pos>
    static auto do_visit(Self&,
                         const Visitor& visitor,
                         std::integral_constant<bool, true> /* is_void */,
                         std::integral_constant<int, Pos>,
                         typename std::enable_if<Pos < sizeof...(Ts)>::type* = nullptr)
    -> decltype(visitor(none_t{})) {
        return visitor();
    }

    template<typename Self, typename Visitor, int Pos>
    static auto do_visit(Self&,
                         const Visitor& visitor,
                         std::integral_constant<bool, false>,
                         std::integral_constant<int, Pos>,
                         typename std::enable_if<Pos >= sizeof...(Ts)>::type* = nullptr)
    -> decltype(visitor(none_t{})) {
        // this is not the function you are looking for
        throw std::runtime_error("invalid type found");
    }

    template<typename Self, typename Visitor>
    static auto do_apply(Self& from, Visitor& visitor) -> decltype(visitor(none_t{})) {
        switch (from.m_type) {
            default: throw std::runtime_error("invalid type found");
            case -1: return visitor(none_t{});
            CPPA_OPTIONAL_VARIANT_CASE(0);
            CPPA_OPTIONAL_VARIANT_CASE(1);
            CPPA_OPTIONAL_VARIANT_CASE(2);
            CPPA_OPTIONAL_VARIANT_CASE(3);
            CPPA_OPTIONAL_VARIANT_CASE(4);
            CPPA_OPTIONAL_VARIANT_CASE(5);
            CPPA_OPTIONAL_VARIANT_CASE(6);
            CPPA_OPTIONAL_VARIANT_CASE(7);
            CPPA_OPTIONAL_VARIANT_CASE(8);
            CPPA_OPTIONAL_VARIANT_CASE(9);
        }
    }

    inline void destroy_data() {
        detail::optional_variant_data_destructor f;
        apply(f);
    }

    template<typename U>
    typename std::enable_if<
           !std::is_same<typename util::rm_const_and_ref<U>::type, none_t>::value
        && !is_optional_variant<typename util::rm_const_and_ref<U>::type>::value
        && !is_optional<typename util::rm_const_and_ref<U>::type>::value
    >::type
    set(U&& arg) {
        typedef typename util::rm_const_and_ref<U>::type stripped_type;
        typedef typename detail::unlift_void<stripped_type>::type type;
        static constexpr int type_id = util::tl_find<types, type>::value;
        static_assert(type_id != -1, "invalid type");
        m_type = type_id;
        auto& ref = m_data.get(make_int_token<type_id>());
        new (&ref) stripped_type (std::forward<U>(arg));
    }

    inline void set(const optional_variant& other) {
        optional_variant_copy_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    inline void set(optional_variant&& other) {
        optional_variant_move_helper<optional_variant> helper{*this};
        other.apply(helper);
    }

    template<typename T>
    inline void set(const optional<T>& arg) {
        if (arg) set(*arg);
        else set(none);
    }

    template<typename T>
    inline void set(optional<T>&& arg) {
        if (arg) set(std::move(*arg));
        else set(none);
    }

    inline void set(const none_t&) { m_type = -1; }

    int m_type;
    detail::optional_variant_data<typename detail::lift_void<Ts>::type...> m_data;

};

/**
 * @relates optional_variant
 */
template<typename T, typename... Us>
const T& get(const optional_variant<Us...>& value) {
    std::integral_constant<int, util::tl_find<util::type_list<Us...>, T>::value> token;
    return value.get(token);
}

/**
 * @relates optional_variant
 */
template<typename T, typename... Us>
T& get_ref(optional_variant<Us...>& value) {
    std::integral_constant<int, util::tl_find<util::type_list<Us...>, T>::value> token;
    return value.get(token);
}

/**
 * @relates optional_variant
 */
template<typename Visitor, typename... Ts>
auto apply_visitor(Visitor& visitor, const optional_variant<Ts...>& data) -> decltype(visitor(none_t{})) {
    return data.apply(visitor);
}

/**
 * @relates optional_variant
 */
template<typename Visitor, typename... Ts>
auto apply_visitor(const Visitor& visitor, const optional_variant<Ts...>& data) -> decltype(visitor(none_t{})) {
    return data.apply(visitor);
}

/**
 * @relates optional_variant
 */
template<typename Visitor, typename... Ts>
auto apply_visitor(Visitor& visitor, optional_variant<Ts...>& data) -> decltype(visitor(none_t{})) {
    return data.apply(visitor);
}

/**
 * @relates optional_variant
 */
template<typename Visitor, typename... Ts>
auto apply_visitor(const Visitor& visitor, optional_variant<Ts...>& data) -> decltype(visitor(none_t{})) {
    return data.apply(visitor);
}

template<typename T>
struct optional_variant_from_type_list;

template<typename... Ts>
struct optional_variant_from_type_list<util::type_list<Ts...>> {
    typedef optional_variant<Ts...> type;
};

namespace detail {
template<typename T>
struct optional_variant_cmp_helper {
    const T& lhs;
    optional_variant_cmp_helper(const T& value) : lhs{value} { }
    // variant is comparable
    template<typename U>
    typename std::enable_if<util::is_comparable<T, U>::value, bool>::type
    operator()(const U& rhs) const { return lhs == rhs; }
    // variant is not comparable
    template<typename U>
    typename std::enable_if<!util::is_comparable<T, U>::value, bool>::type
    operator()(const U&) const { return false; }
    // variant is void
    bool operator()() const { return false; }
};
} // namespace detail

/**
 * @relates optional_variant
 */
template<typename T, typename... Ts>
bool operator==(const T& lhs, const optional_variant<Ts...>& rhs) {
    return apply_visitor(detail::optional_variant_cmp_helper<T>{lhs}, rhs);
}

/**
 * @relates optional_variant
 */
template<typename T, typename... Ts>
bool operator==(const optional_variant<Ts...>& lhs, const T& rhs) {
    return rhs == lhs;
}

namespace detail {
struct optional_variant_ostream_helper {
    std::ostream& lhs;
    inline optional_variant_ostream_helper(std::ostream& os) : lhs(os) { }
    template<typename T>
    std::ostream& operator()(const T& value) const { return lhs << value; }
    inline std::ostream& operator()(const none_t&) const { return lhs; }
    inline std::ostream& operator()() const { return lhs; }
};
} // namespace detail

/**
 * @relates optional_variant
 */
template<typename T0, typename... Ts>
std::ostream& operator<<(std::ostream& lhs, const optional_variant<T0, Ts...>& rhs) {
    return apply_visitor(detail::optional_variant_ostream_helper{lhs}, rhs);
}

} // namespace cppa

#endif // OPTIONAL_VARIANT_HPP
<|endoftext|>


<commit_before>#pragma once

const long double PI = 3.14159265358979323846;
const int INF = 0x3f3f3f3f;
const long double EPS = 1e-9;
const long long LINF = 0x3f3f3f3f3f3f3f3fLL;

const int DX[] = { -1, 0, 1, 0, -1, -1, 1, 1 };
const int DY[] = { 0, 1, 0, -1, -1, 1, 1, -1 };

enum class Direction {
	Up,
	Right,
	Down,
	Left,
	UpLeft,
	UpRight,
	DownRight,
	DownLeft,
	North = Up,
	East = Right,
	South = Down,
	West = Left,
	NorthWest = UpLeft,
	NorthEast = UpRight,
	SouthEast = DownRight,
	SouthWest = DownLeft
};
<commit_msg>Added constexpr qualifier to constants.<commit_after>#pragma once

constexpr const long double PI = 3.14159265358979323846;
constexpr const int INF = 0x3f3f3f3f;
constexpr const long double EPS = 1e-9;
constexpr const long long LINF = 0x3f3f3f3f3f3f3f3fLL;

constexpr const int DX[] = { -1, 0, 1, 0, -1, -1, 1, 1 };
constexpr const int DY[] = { 0, 1, 0, -1, -1, 1, 1, -1 };

enum class Direction {
	Up,
	Right,
	Down,
	Left,
	UpLeft,
	UpRight,
	DownRight,
	DownLeft,
	North = Up,
	East = Right,
	South = Down,
	West = Left,
	NorthWest = UpLeft,
	NorthEast = UpRight,
	SouthEast = DownRight,
	SouthWest = DownLeft
};
<|endoftext|>


<commit_before>/**
 * @author ChalkPE <chalk@chalk.pe>
 * @since 2016-05-30
 */

#include <stdio.h>

int main(){
    int i, n, sum = 0; for(i = 1; ; i++){
        scanf("%d", &n); sum += n;
        if(n >= 100) return 0 * printf("%d\n%.1lf", sum, (double) sum / i);
    }
}
<commit_msg>Reduced lines!<commit_after>/**
 * @author ChalkPE <chalk@chalk.pe>
 * @since 2016-05-30
 */

#include <stdio.h>

int main(){
    int i, n = 0, sum = 0; for(i = 1; n < 100; sum += n, i++) scanf("%d", &n);
    return 0 * printf("%d\n%.1lf", sum, (double) sum / --i);
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 * Copyright (C) 2006 10East Corp.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef __PLACEMENT_FINDER__
#define __PLACEMENT_FINDER__

#include <mapnik/ctrans.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/text_symbolizer.hpp>
#include <mapnik/shield_symbolizer.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/text_path.hpp>

#include <queue>

namespace mapnik
{
   typedef text_path placement_element;

   struct placement : boost::noncopyable
   {
         placement(string_info & info_,
                   //path_type & shape_path_,
                   shield_symbolizer const& sym);

         placement(string_info & info_,
                   //path_type & shape_path_,
                   text_symbolizer const& sym);

         ~placement();

         //helpers
         //std::pair<double, double> get_position_at_distance(double target_distance);
         //double get_total_distance();

         string_info & info;
         //path_type & shape_path;
         //double total_distance_; //cache for distance

         position displacement_;
         label_placement_e label_placement;

         std::queue< Envelope<double> > envelopes;

         //output
         boost::ptr_vector<placement_element> placements;

         int wrap_width;
         int text_ratio;

         int label_spacing; // distance between repeated labels on a single geometry
         unsigned label_position_tolerance; //distance the label can be moved on the line to fit, if 0 the default is used
         bool force_odd_labels; //Always try render an odd amount of labels

         double max_char_angle_delta;
         double minimum_distance;
         bool avoid_edges;
         bool has_dimensions;
         std::pair<double, double> dimensions;
   };

   template <typename DetectorT>
   class placement_finder : boost::noncopyable
   {
      public:
         placement_finder(DetectorT & detector);

         //Try place a single label at the given point
         void find_point_placement(placement & p, double, double);

         //Iterate over the given path, placing point labels with respect to label_spacing
         template <typename T>
         void find_point_placements(placement & p, T & path);

         //Iterate over the given path, placing line-following labels with respect to label_spacing
         template <typename T>
         void find_line_placements(placement & p, T & path);

         void clear();

      private:
         ///Helpers for find_line_placement

         ///Returns a possible placement on the given line, does not test for collisions
         //index: index of the node the current line ends on
         //distance: distance along the given index that the placement should start at, this includes the offset,
         //          as such it may be > or < the length of the current line, so this must be checked for
         //orientation: if set to != 0 the placement will be attempted with the given orientation
         //             otherwise it will autodetect the orientation.
         //             If >= 50% of the characters end up upside down, it will be retried the other way.
         //             RETURN: 1/-1 depending which way up the string ends up being.
         std::auto_ptr<placement_element> get_placement_offset(placement & p, const std::vector<vertex2d> & path_positions, const std::vector<double> & path_distances, int & orientation, unsigned index, double distance);

         ///Tests wether the given placement_element be placed without a collision
         // Returns true if it can
         // NOTE: This edits p.envelopes so it can be used afterwards (you must clear it otherwise)
         bool test_placement(placement & p, const std::auto_ptr<placement_element> & current_placement, const int & orientation);

         ///Does a line-circle intersect calculation
         // NOTE: Follow the strict pre conditions
         // Pre Conditions: x1,y1 is within radius distance of cx,cy. x2,y2 is outside radius distance of cx,cy
         //                 This means there is exactly one intersect point
         // Result is returned in ix, iy
         void find_line_circle_intersection(
            const double &cx, const double &cy, const double &radius,
            const double &x1, const double &y1, const double &x2, const double &y2,
            double &ix, double &iy);

         ///General Internals

         void update_detector(placement & p);

         DetectorT & detector_;
         Envelope<double> const& dimensions_;
   };
}

#endif

<commit_msg>+ make 'update_detectot' public<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 * Copyright (C) 2006 10East Corp.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef __PLACEMENT_FINDER__
#define __PLACEMENT_FINDER__

#include <mapnik/ctrans.hpp>
#include <mapnik/label_collision_detector.hpp>
#include <mapnik/text_symbolizer.hpp>
#include <mapnik/shield_symbolizer.hpp>
#include <mapnik/geometry.hpp>
#include <mapnik/text_path.hpp>

#include <queue>

namespace mapnik
{
   typedef text_path placement_element;

   struct placement : boost::noncopyable
   {
         placement(string_info & info_,
                   //path_type & shape_path_,
                   shield_symbolizer const& sym);

         placement(string_info & info_,
                   //path_type & shape_path_,
                   text_symbolizer const& sym);

         ~placement();

         //helpers
         //std::pair<double, double> get_position_at_distance(double target_distance);
         //double get_total_distance();

         string_info & info;
         //path_type & shape_path;
         //double total_distance_; //cache for distance

         position displacement_;
         label_placement_e label_placement;

         std::queue< Envelope<double> > envelopes;

         //output
         boost::ptr_vector<placement_element> placements;

         int wrap_width;
         int text_ratio;

         int label_spacing; // distance between repeated labels on a single geometry
         unsigned label_position_tolerance; //distance the label can be moved on the line to fit, if 0 the default is used
         bool force_odd_labels; //Always try render an odd amount of labels

         double max_char_angle_delta;
         double minimum_distance;
         bool avoid_edges;
         bool has_dimensions;
         std::pair<double, double> dimensions;
   };

   template <typename DetectorT>
   class placement_finder : boost::noncopyable
   {
      public:
         placement_finder(DetectorT & detector);

         //Try place a single label at the given point
         void find_point_placement(placement & p, double, double);

         //Iterate over the given path, placing point labels with respect to label_spacing
         template <typename T>
         void find_point_placements(placement & p, T & path);

         //Iterate over the given path, placing line-following labels with respect to label_spacing
         template <typename T>
         void find_line_placements(placement & p, T & path);

         void update_detector(placement & p);

         void clear();

      private:
         ///Helpers for find_line_placement

         ///Returns a possible placement on the given line, does not test for collisions
         //index: index of the node the current line ends on
         //distance: distance along the given index that the placement should start at, this includes the offset,
         //          as such it may be > or < the length of the current line, so this must be checked for
         //orientation: if set to != 0 the placement will be attempted with the given orientation
         //             otherwise it will autodetect the orientation.
         //             If >= 50% of the characters end up upside down, it will be retried the other way.
         //             RETURN: 1/-1 depending which way up the string ends up being.
         std::auto_ptr<placement_element> get_placement_offset(placement & p, const std::vector<vertex2d> & path_positions, const std::vector<double> & path_distances, int & orientation, unsigned index, double distance);

         ///Tests wether the given placement_element be placed without a collision
         // Returns true if it can
         // NOTE: This edits p.envelopes so it can be used afterwards (you must clear it otherwise)
         bool test_placement(placement & p, const std::auto_ptr<placement_element> & current_placement, const int & orientation);

         ///Does a line-circle intersect calculation
         // NOTE: Follow the strict pre conditions
         // Pre Conditions: x1,y1 is within radius distance of cx,cy. x2,y2 is outside radius distance of cx,cy
         //                 This means there is exactly one intersect point
         // Result is returned in ix, iy
         void find_line_circle_intersection(
            const double &cx, const double &cy, const double &radius,
            const double &x1, const double &y1, const double &x2, const double &y2,
            double &ix, double &iy);

         ///General Internals

         DetectorT & detector_;
         Envelope<double> const& dimensions_;
   };
}

#endif

<|endoftext|>


<commit_before>#include "Common.hpp"
#include "GetOpt.hpp"
#include "ZCMGen.hpp"
#include "emit/Emit.hpp"

extern "C" {
#include "version.h"
#include "tokenize.h"
}

int main(int argc, char *argv[])
{
    GetOpt gopt;
    gopt.addBool('h',  "help",     0,    "Show this help");
    gopt.addBool('t',  "tokenize", 0,    "Show tokenization");
    gopt.addBool('d',  "debug",    0,    "Show parsed file");
    gopt.addBool(0,    "lazy",     0,    "Generate output file only if .zcm is newer");
    gopt.addString(0,    "package-prefix",     "",
                      "Add this package name as a prefix to the declared package");
    gopt.addBool(0,  "version",    0,    "Show version information and exit");

    // we only support portable declarations now.
    // getopt_add_bool  (gopt, 0,    "warn-unsafe", 1, "Warn about unportable declarations");

    gopt.addSpacer("**** C options ****");
    gopt.addBool('c', "c",         0,     "Emit C code");
    setupOptionsC(gopt);

    // getopt_add_spacer(gopt, "**** C++ options ****");
    // getopt_add_bool  (gopt, 'x', "cpp",         0,     "Emit C++ code");
    // setup_cpp_options(gopt);

    gopt.addSpacer("**** Java options ****");
    gopt.addBool('j', "java",      0,     "Emit Java code");
    setupOptionsJava(gopt);

    gopt.addSpacer("**** Python options ****");
    gopt.addBool('p', "python",      0,     "Emit Python code");
    setupOptionsPython(gopt);

    // getopt_add_spacer(gopt, "**** Javascript options ****");
    // getopt_add_bool  (gopt, 's', "js",      0,     "Emit Javascript code");
    // setup_js_options(gopt);

    // getopt_add_spacer(gopt, "**** Lua options ****");
    // getopt_add_bool  (gopt, 'l', "lua",      0,     "Emit Lua code");
    // setup_lua_options(gopt);

    // getopt_add_spacer(gopt, "**** C#.NET options ****");
    // getopt_add_bool  (gopt, 0, "csharp",      0,     "Emit C#.NET code");
    // setup_csharp_options(gopt);

    if (!gopt.parse(argc, argv, 1) || gopt.getBool("help")) {
        printf("Usage: %s [options] <input files>\n\n", argv[0]);
        gopt.doUsage();
        return 0;
    }

    ZCMGen zcm;
    zcm.gopt = &gopt;

    for (int i = 2; i < argc; i++) {
        int res = zcm.handleFile(argv[i]);
        if (res)
            return res;
    }

    // for (unsigned int i = 0; i < g_ptr_array_size(gopt->extraargs); i++) {
    //     char *path = (char *) g_ptr_array_index(gopt->extraargs, i);

    //     int res = zcm.handleFile(path);
    //     if (res)
    //         return res;
    // }

    // If "--version" was specified, then show version information and exit.
    if (gopt.getBool("version")) {
      printf("zcm-gen %d.%d.%d\n", ZCM_MAJOR_VERSION, ZCM_MINOR_VERSION,
             ZCM_MICRO_VERSION);
      return 0;
    }

    // If "-t" or "--tokenize" was specified, then show tokenization
    // information and exit.
    if (gopt.getBool("tokenize")) {
        return 0;
    }

    int did_something = 0;
    if (gopt.getBool("debug")) {
        did_something = 1;
        zcm.dump();
    }

    if (gopt.getBool("c")) {
        did_something = 1;
        if (emitC(zcm)) {
            printf("An error occurred while emitting C code.\n");
        }
    }

    // if (getopt_get_bool(gopt, "cpp")) {
    //     did_something = 1;
    //     if (emit_cpp(zcm)) {
    //         printf("An error occurred while emitting C++ code.\n");
    //     }
    // }

    if (gopt.getBool("java")) {
        did_something = 1;
        if (emitJava(zcm)) {
            printf("An error occurred while emitting Java code.\n");
        }
    }

    if (gopt.getBool("python")) {
        did_something = 1;
        if (emitPython(zcm)) {
            printf("An error occurred while emitting Python code.\n");
        }
    }

    // if (getopt_get_bool(gopt, "js")) {
    //     did_something = 1;
    //     if (emit_js(zcm)) {
    //         printf("An error occurred while emitting Javascript code.\n");
    //     }
    // }

    // if (getopt_get_bool(gopt, "lua")) {
    // 	did_something = 1;
    // 	if (emit_lua(zcm)) {
    // 		printf("An error occurred while emitting Lua code.\n");
    // 	}
    // }

    // if (getopt_get_bool(gopt, "csharp")) {
    //     did_something = 1;
    //     if (emit_csharp(zcm)) {
    //         printf("An error occurred while emitting C#.NET code.\n");
    //     }
    // }

    if (did_something == 0) {
        printf("No actions specified. Try --help.\n");
    }

    return 0;
}
<commit_msg>fixed zcm-gen bug<commit_after>#include "Common.hpp"
#include "GetOpt.hpp"
#include "ZCMGen.hpp"
#include "emit/Emit.hpp"

extern "C" {
#include "version.h"
#include "tokenize.h"
}

int main(int argc, char *argv[])
{
    GetOpt gopt;
    gopt.addBool('h',  "help",     0,    "Show this help");
    gopt.addBool('t',  "tokenize", 0,    "Show tokenization");
    gopt.addBool('d',  "debug",    0,    "Show parsed file");
    gopt.addBool(0,    "lazy",     0,    "Generate output file only if .zcm is newer");
    gopt.addString(0,    "package-prefix",     "",
                      "Add this package name as a prefix to the declared package");
    gopt.addBool(0,  "version",    0,    "Show version information and exit");

    // we only support portable declarations now.
    // getopt_add_bool  (gopt, 0,    "warn-unsafe", 1, "Warn about unportable declarations");

    gopt.addSpacer("**** C options ****");
    gopt.addBool('c', "c",         0,     "Emit C code");
    setupOptionsC(gopt);

    // getopt_add_spacer(gopt, "**** C++ options ****");
    // getopt_add_bool  (gopt, 'x', "cpp",         0,     "Emit C++ code");
    // setup_cpp_options(gopt);

    gopt.addSpacer("**** Java options ****");
    gopt.addBool('j', "java",      0,     "Emit Java code");
    setupOptionsJava(gopt);

    gopt.addSpacer("**** Python options ****");
    gopt.addBool('p', "python",      0,     "Emit Python code");
    setupOptionsPython(gopt);

    // getopt_add_spacer(gopt, "**** Javascript options ****");
    // getopt_add_bool  (gopt, 's', "js",      0,     "Emit Javascript code");
    // setup_js_options(gopt);

    // getopt_add_spacer(gopt, "**** Lua options ****");
    // getopt_add_bool  (gopt, 'l', "lua",      0,     "Emit Lua code");
    // setup_lua_options(gopt);

    // getopt_add_spacer(gopt, "**** C#.NET options ****");
    // getopt_add_bool  (gopt, 0, "csharp",      0,     "Emit C#.NET code");
    // setup_csharp_options(gopt);

    if (!gopt.parse(argc, argv, 1) || gopt.getBool("help")) {
        printf("Usage: %s [options] <input files>\n\n", argv[0]);
        gopt.doUsage();
        return 0;
    }

    ZCMGen zcm;
    zcm.gopt = &gopt;

    for (auto& fname : gopt.extraargs)
        if (int res = zcm.handleFile(fname))
            return res;

    // for (unsigned int i = 0; i < g_ptr_array_size(gopt->extraargs); i++) {
    //     char *path = (char *) g_ptr_array_index(gopt->extraargs, i);

    //     int res = zcm.handleFile(path);
    //     if (res)
    //         return res;
    // }

    // If "--version" was specified, then show version information and exit.
    if (gopt.getBool("version")) {
      printf("zcm-gen %d.%d.%d\n", ZCM_MAJOR_VERSION, ZCM_MINOR_VERSION,
             ZCM_MICRO_VERSION);
      return 0;
    }

    // If "-t" or "--tokenize" was specified, then show tokenization
    // information and exit.
    if (gopt.getBool("tokenize")) {
        return 0;
    }

    int did_something = 0;
    if (gopt.getBool("debug")) {
        did_something = 1;
        zcm.dump();
    }

    if (gopt.getBool("c")) {
        did_something = 1;
        if (emitC(zcm)) {
            printf("An error occurred while emitting C code.\n");
        }
    }

    // if (getopt_get_bool(gopt, "cpp")) {
    //     did_something = 1;
    //     if (emit_cpp(zcm)) {
    //         printf("An error occurred while emitting C++ code.\n");
    //     }
    // }

    if (gopt.getBool("java")) {
        did_something = 1;
        if (emitJava(zcm)) {
            printf("An error occurred while emitting Java code.\n");
        }
    }

    if (gopt.getBool("python")) {
        did_something = 1;
        if (emitPython(zcm)) {
            printf("An error occurred while emitting Python code.\n");
        }
    }

    // if (getopt_get_bool(gopt, "js")) {
    //     did_something = 1;
    //     if (emit_js(zcm)) {
    //         printf("An error occurred while emitting Javascript code.\n");
    //     }
    // }

    // if (getopt_get_bool(gopt, "lua")) {
    // 	did_something = 1;
    // 	if (emit_lua(zcm)) {
    // 		printf("An error occurred while emitting Lua code.\n");
    // 	}
    // }

    // if (getopt_get_bool(gopt, "csharp")) {
    //     did_something = 1;
    //     if (emit_csharp(zcm)) {
    //         printf("An error occurred while emitting C#.NET code.\n");
    //     }
    // }

    if (did_something == 0) {
        printf("No actions specified. Try --help.\n");
    }

    return 0;
}
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/prepared_statement.hxx
 *
 *   DESCRIPTION
 *      Helper classes for defining and executing prepared statements
 *   See the connection_base hierarchy for more about prepared statements
 *
 * Copyright (c) 2006,2007, 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-public.hxx"
#include "pqxx/compiler-internal-pre.hxx"

#include "pqxx/util"

namespace pqxx
{
class connection_base;
class transaction_base;
class result;

/// Dedicated namespace for helper types related to prepared statements
namespace prepare
{
/// Type of treatment of a particular parameter to a prepared statement
/** This information is needed to determine whether a parameter needs to be
 * quoted, escaped, binary-escaped, and/or converted to boolean as it is
 * passed to a prepared statement on execution.
 *
 * This treatment becomes relevant when either the available libpq version
 * doesn't provide direct support for prepared statements, so the definition
 * must be generated as SQL.  This is the case with libpq versions prior to the
 * one shipped with PostgreSQL 7.4).
 */
enum param_treatment
{
  /// Pass as raw, binary bytes
  treat_binary,
  /// Escape special characters and add quotes
  treat_string,
  /// Represent as named Boolean value
  treat_bool,
  /// Include directly in SQL without conversion (e.g. for numeric types)
  treat_direct
};

/// Helper class for declaring parameters to prepared statements
/** You probably won't want to use this class.  It's here just so you can
 * declare parameters by adding parenthesized declarations directly after the
 * statement declaration itself:
 *
 * @code
 * C.prepare(name, query)(paramtype1)(paramtype2, treatment)(paramtype3);
 * @endcode
 */
class PQXX_LIBEXPORT declaration
{
public:
  declaration(connection_base &, const PGSTD::string &statement);

  /// Add a parameter specification to prepared statement declaration
  const declaration &
  operator()(const PGSTD::string &sqltype, param_treatment) const;

private:
  connection_base &m_home;
  const PGSTD::string m_statement;
};

/// Helper class for passing parameters to, and executing, prepared statements
class PQXX_LIBEXPORT invocation
{
public:
  invocation(transaction_base &, const PGSTD::string &statement);

  /// Execute!
  result exec() const;

  /// Pass null parameter
  invocation &operator()();

  /// Pass parameter value
  /**
   * @param v parameter value (will be represented as a string internally)
   * @param nonnull replaces value with null if set to false
   */
  template<typename T>
    invocation &operator()(const T &v, bool nonnull=true)
	{ return setparam(to_string(v), nonnull); }

  /// Pass C-style parameter string, or null if pointer is null
  /**
   * This version is for passing C-style strings; it's a template, so any
   * pointer type that @c to_string accepts will do.
   *
   * @warning Be very careful with the special constant @c NULL!  Since @c NULL
   * in C++ is an @c int, not a pointer, a value of @c NULL would cause the
   * wrong version of this template to be invoked.  To all intents and purposes
   * it would look like you were trying to pass a regular zero as an integer
   * value, instead of a null string.  This is not a problem with pointer
   * variables that may happen to be @c NULL, since in that case the value's
   * type is not subject to any confusion.  So if you know at compile time that
   * you want to pass a null value, use the zero-argument version of this
   * operator; if you don't want to do that, at least add a second argument of
   * @c false to make clear that you want a null, not a zero.
   *
   * @param v parameter value (will be represented as a C++ string internally)
   * @param nonnull replaces value with null if set to @c false
   */
  template<typename T>
    invocation &operator()(T *v, bool nonnull=true)
	{ return setparam((v ? to_string(v) : ""), nonnull); }

  /// Pass C-style string parameter, or null if pointer is null
  /** This duplicates the pointer-to-template-argument-type version of the
   * operator, but helps compilers with less advanced template implementations
   * disambiguate calls where C-style strings are passed.
   */
  invocation &operator()(const char *v, bool nonnull=true)
	{ return setparam((v ? to_string(v) : ""), nonnull); }

private:
  transaction_base &m_home;
  const PGSTD::string m_statement;
  PGSTD::vector<PGSTD::string> m_values;
  PGSTD::vector<bool> m_nonnull;

  invocation &setparam(const PGSTD::string &, bool nonnull);
};

namespace internal
{
/// Internal representation of a prepared statement definition
struct PQXX_PRIVATE prepared_def
{
  /// Parameter definition
  struct param
  {
    PGSTD::string sqltype;
    param_treatment treatment;

    param(const PGSTD::string &SQLtype, param_treatment);
  };

  /// Text of prepared query
  PGSTD::string definition;
  /// Parameter list
  PGSTD::vector<param> parameters;
  /// Has this prepared statement been prepared in the current session?
  bool registered;
  /// Is this definition complete?
  bool complete;

  prepared_def();
  explicit prepared_def(const PGSTD::string &);

  void addparam(const PGSTD::string &sqltype, param_treatment);
};

/// Utility functor: get prepared-statement parameter's SQL type string
struct PQXX_PRIVATE get_sqltype
{
  template<typename IT> const PGSTD::string &operator()(IT i)
  {
    return i->sqltype;
  }
};

} // namespace pqxx::prepared::internal
} // namespace pqxx::prepared
} // namespace pqxx

#include "pqxx/compiler-internal-post.hxx"
<commit_msg>Disallow copy assignment of definitions and invocations<commit_after>/*-------------------------------------------------------------------------
 *
 *   FILE
 *	pqxx/prepared_statement.hxx
 *
 *   DESCRIPTION
 *      Helper classes for defining and executing prepared statements
 *   See the connection_base hierarchy for more about prepared statements
 *
 * Copyright (c) 2006,2007, 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-public.hxx"
#include "pqxx/compiler-internal-pre.hxx"

#include "pqxx/util"

namespace pqxx
{
class connection_base;
class transaction_base;
class result;

/// Dedicated namespace for helper types related to prepared statements
namespace prepare
{
/// Type of treatment of a particular parameter to a prepared statement
/** This information is needed to determine whether a parameter needs to be
 * quoted, escaped, binary-escaped, and/or converted to boolean as it is
 * passed to a prepared statement on execution.
 *
 * This treatment becomes relevant when either the available libpq version
 * doesn't provide direct support for prepared statements, so the definition
 * must be generated as SQL.  This is the case with libpq versions prior to the
 * one shipped with PostgreSQL 7.4).
 */
enum param_treatment
{
  /// Pass as raw, binary bytes
  treat_binary,
  /// Escape special characters and add quotes
  treat_string,
  /// Represent as named Boolean value
  treat_bool,
  /// Include directly in SQL without conversion (e.g. for numeric types)
  treat_direct
};

/// Helper class for declaring parameters to prepared statements
/** You probably won't want to use this class.  It's here just so you can
 * declare parameters by adding parenthesized declarations directly after the
 * statement declaration itself:
 *
 * @code
 * C.prepare(name, query)(paramtype1)(paramtype2, treatment)(paramtype3);
 * @endcode
 */
class PQXX_LIBEXPORT declaration
{
public:
  declaration(connection_base &, const PGSTD::string &statement);

  /// Add a parameter specification to prepared statement declaration
  const declaration &
  operator()(const PGSTD::string &sqltype, param_treatment) const;

private:
  /// Not allowed
  declaration &operator=(const declaration &);

  connection_base &m_home;
  const PGSTD::string m_statement;
};

/// Helper class for passing parameters to, and executing, prepared statements
class PQXX_LIBEXPORT invocation
{
public:
  invocation(transaction_base &, const PGSTD::string &statement);

  /// Execute!
  result exec() const;

  /// Pass null parameter
  invocation &operator()();

  /// Pass parameter value
  /**
   * @param v parameter value (will be represented as a string internally)
   * @param nonnull replaces value with null if set to false
   */
  template<typename T>
    invocation &operator()(const T &v, bool nonnull=true)
	{ return setparam(to_string(v), nonnull); }

  /// Pass C-style parameter string, or null if pointer is null
  /**
   * This version is for passing C-style strings; it's a template, so any
   * pointer type that @c to_string accepts will do.
   *
   * @warning Be very careful with the special constant @c NULL!  Since @c NULL
   * in C++ is an @c int, not a pointer, a value of @c NULL would cause the
   * wrong version of this template to be invoked.  To all intents and purposes
   * it would look like you were trying to pass a regular zero as an integer
   * value, instead of a null string.  This is not a problem with pointer
   * variables that may happen to be @c NULL, since in that case the value's
   * type is not subject to any confusion.  So if you know at compile time that
   * you want to pass a null value, use the zero-argument version of this
   * operator; if you don't want to do that, at least add a second argument of
   * @c false to make clear that you want a null, not a zero.
   *
   * @param v parameter value (will be represented as a C++ string internally)
   * @param nonnull replaces value with null if set to @c false
   */
  template<typename T>
    invocation &operator()(T *v, bool nonnull=true)
	{ return setparam((v ? to_string(v) : ""), nonnull); }

  /// Pass C-style string parameter, or null if pointer is null
  /** This duplicates the pointer-to-template-argument-type version of the
   * operator, but helps compilers with less advanced template implementations
   * disambiguate calls where C-style strings are passed.
   */
  invocation &operator()(const char *v, bool nonnull=true)
	{ return setparam((v ? to_string(v) : ""), nonnull); }

private:
  /// Not allowed
  invocation &operator=(const invocation &);

  transaction_base &m_home;
  const PGSTD::string m_statement;
  PGSTD::vector<PGSTD::string> m_values;
  PGSTD::vector<bool> m_nonnull;

  invocation &setparam(const PGSTD::string &, bool nonnull);
};

namespace internal
{
/// Internal representation of a prepared statement definition
struct PQXX_PRIVATE prepared_def
{
  /// Parameter definition
  struct param
  {
    PGSTD::string sqltype;
    param_treatment treatment;

    param(const PGSTD::string &SQLtype, param_treatment);
  };

  /// Text of prepared query
  PGSTD::string definition;
  /// Parameter list
  PGSTD::vector<param> parameters;
  /// Has this prepared statement been prepared in the current session?
  bool registered;
  /// Is this definition complete?
  bool complete;

  prepared_def();
  explicit prepared_def(const PGSTD::string &);

  void addparam(const PGSTD::string &sqltype, param_treatment);
};

/// Utility functor: get prepared-statement parameter's SQL type string
struct PQXX_PRIVATE get_sqltype
{
  template<typename IT> const PGSTD::string &operator()(IT i)
  {
    return i->sqltype;
  }
};

} // namespace pqxx::prepared::internal
} // namespace pqxx::prepared
} // namespace pqxx

#include "pqxx/compiler-internal-post.hxx"
<|endoftext|>


<commit_before>/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 * This file is part of sot-core.
 * sot-core is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * sot-core is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.  You should
 * have received a copy of the GNU Lesser General Public License along
 * with sot-core.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef __SOT_FEATURE_POINT6D_HH__
#define __SOT_FEATURE_POINT6D_HH__

/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */

/* SOT */
#include <sot/core/feature-abstract.hh>
#include <sot/core/exception-task.hh>
#include <sot/core/exception-feature.hh>
#include <sot/core/matrix-geometry.hh>

/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */

#if defined (WIN32)
#  if defined (feature_point6d_EXPORTS)
#    define SOTFEATUREPOINT6D_EXPORT __declspec(dllexport)
#  else
#    define SOTFEATUREPOINT6D_EXPORT __declspec(dllimport)
#  endif
#else
#  define SOTFEATUREPOINT6D_EXPORT
#endif

/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */

namespace dynamicgraph { namespace sot {
namespace dg = dynamicgraph;

/*!
  \class FeaturePoint6d
  \brief Class that defines point-6d control feature
*/
class SOTFEATUREPOINT6D_EXPORT FeaturePoint6d
  : public FeatureAbstract, public FeatureReferenceHelper<FeaturePoint6d>
{

 public:
  static const std::string CLASS_NAME;
  virtual const std::string& getClassName( void ) const { return CLASS_NAME; }

  /* --- Frame type --------------------------------------------------------- */
 protected:
  enum ComputationFrameType
    {
      FRAME_DESIRED
      ,FRAME_CURRENT
    };
  static const ComputationFrameType COMPUTATION_FRAME_DEFAULT;
 public:
  /// \brief Set computation frame
  void computationFrame(const std::string& inFrame);
  /// \brief Get computation frame
  std::string computationFrame() const;
 private:
  ComputationFrameType computationFrame_;

  /* --- SIGNALS ------------------------------------------------------------ */
 public:
  dg::SignalPtr< MatrixHomogeneous,int > positionSIN;
  dg::SignalPtr< dg::Vector, int > velocitySIN;
  dg::SignalPtr< dg::Matrix,int > articularJacobianSIN;

  using FeatureAbstract::selectionSIN;
  using FeatureAbstract::jacobianSOUT;
  using FeatureAbstract::errorSOUT;

  /*! \name Dealing with the reference value to be reach with this feature.
    @{  */
  DECLARE_REFERENCE_FUNCTIONS(FeaturePoint6d);
  /*! @} */

 public:
  FeaturePoint6d( const std::string& name );
  virtual ~FeaturePoint6d( void ) {}

  virtual unsigned int& getDimension( unsigned int & dim, int time );

  virtual dg::Vector& computeError( dg::Vector& res,int time );
  virtual dg::Vector& computeErrordot( dg::Vector& res,int time );
  virtual dg::Matrix& computeJacobian( dg::Matrix& res,int time );

  /** Static Feature selection. */
  inline static Flags selectX( void )  { return FLAG_LINE_1; }
  inline static Flags selectY( void )  { return FLAG_LINE_2; }
  inline static Flags selectZ( void )  { return FLAG_LINE_3; }
  inline static Flags selectRX( void ) { return FLAG_LINE_4; }
  inline static Flags selectRY( void ) { return FLAG_LINE_5; }
  inline static Flags selectRZ( void ) { return FLAG_LINE_6; }

  inline static Flags selectTranslation( void ) { return Flags(7); }
  inline static Flags selectRotation( void ) { return Flags(56); }

  virtual void display( std::ostream& os ) const;

 public:
  void servoCurrentPosition( void );
 private:
  // Intermediate variables for internal computations
  Eigen::Vector3d v_, omega_, errordot_t_, errordot_th_, Rreftomega_,
    t_, tref_;
  VectorUTheta  error_th_;
  MatrixRotation R_, Rref_, Rt_, Rreft_;
  dg::Matrix P_, Pinv_;
  double accuracy_;
  void inverseJacobianRodrigues ();
} ;

} /* namespace sot */} /* namespace dynamicgraph */

#endif // #ifndef __SOT_FEATURE_POINT6D_HH__

/*
 * Local variables:
 * c-basic-offset: 2
 * End:
 */
<commit_msg>[feature] Fix a pb in DEBUG mode when computing error dot. Found by Fanny Risbourg<commit_after>/*
 * Copyright 2010,
 * François Bleibel,
 * Olivier Stasse,
 *
 * CNRS/AIST
 *
 * This file is part of sot-core.
 * sot-core is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 * sot-core is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.  You should
 * have received a copy of the GNU Lesser General Public License along
 * with sot-core.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef __SOT_FEATURE_POINT6D_HH__
#define __SOT_FEATURE_POINT6D_HH__

/* --------------------------------------------------------------------- */
/* --- INCLUDE --------------------------------------------------------- */
/* --------------------------------------------------------------------- */

/* SOT */
#include <sot/core/feature-abstract.hh>
#include <sot/core/exception-task.hh>
#include <sot/core/exception-feature.hh>
#include <sot/core/matrix-geometry.hh>

/* --------------------------------------------------------------------- */
/* --- API ------------------------------------------------------------- */
/* --------------------------------------------------------------------- */

#if defined (WIN32)
#  if defined (feature_point6d_EXPORTS)
#    define SOTFEATUREPOINT6D_EXPORT __declspec(dllexport)
#  else
#    define SOTFEATUREPOINT6D_EXPORT __declspec(dllimport)
#  endif
#else
#  define SOTFEATUREPOINT6D_EXPORT
#endif

/* --------------------------------------------------------------------- */
/* --- CLASS ----------------------------------------------------------- */
/* --------------------------------------------------------------------- */

namespace dynamicgraph { namespace sot {
namespace dg = dynamicgraph;

/*!
  \class FeaturePoint6d
  \brief Class that defines point-6d control feature
*/
class SOTFEATUREPOINT6D_EXPORT FeaturePoint6d
  : public FeatureAbstract, public FeatureReferenceHelper<FeaturePoint6d>
{

 public:
  static const std::string CLASS_NAME;
  virtual const std::string& getClassName( void ) const { return CLASS_NAME; }

  /* --- Frame type --------------------------------------------------------- */
 protected:
  enum ComputationFrameType
    {
      FRAME_DESIRED
      ,FRAME_CURRENT
    };
  static const ComputationFrameType COMPUTATION_FRAME_DEFAULT;
 public:
  /// \brief Set computation frame
  void computationFrame(const std::string& inFrame);
  /// \brief Get computation frame
  std::string computationFrame() const;
 private:
  ComputationFrameType computationFrame_;

  /* --- SIGNALS ------------------------------------------------------------ */
 public:
  dg::SignalPtr< MatrixHomogeneous,int > positionSIN;
  dg::SignalPtr< dg::Vector, int > velocitySIN;
  dg::SignalPtr< dg::Matrix,int > articularJacobianSIN;

  using FeatureAbstract::selectionSIN;
  using FeatureAbstract::jacobianSOUT;
  using FeatureAbstract::errorSOUT;

  /*! \name Dealing with the reference value to be reach with this feature.
    @{  */
  DECLARE_REFERENCE_FUNCTIONS(FeaturePoint6d);
  /*! @} */

 public:
  FeaturePoint6d( const std::string& name );
  virtual ~FeaturePoint6d( void ) {}

  virtual unsigned int& getDimension( unsigned int & dim, int time );

  virtual dg::Vector& computeError( dg::Vector& res,int time );
  virtual dg::Vector& computeErrordot( dg::Vector& res,int time );
  virtual dg::Matrix& computeJacobian( dg::Matrix& res,int time );

  /** Static Feature selection. */
  inline static Flags selectX( void )  { return FLAG_LINE_1; }
  inline static Flags selectY( void )  { return FLAG_LINE_2; }
  inline static Flags selectZ( void )  { return FLAG_LINE_3; }
  inline static Flags selectRX( void ) { return FLAG_LINE_4; }
  inline static Flags selectRY( void ) { return FLAG_LINE_5; }
  inline static Flags selectRZ( void ) { return FLAG_LINE_6; }

  inline static Flags selectTranslation( void ) { return Flags(7); }
  inline static Flags selectRotation( void ) { return Flags(56); }

  virtual void display( std::ostream& os ) const;

 public:
  void servoCurrentPosition( void );
 private:
  // Intermediate variables for internal computations
  Eigen::Vector3d v_, omega_, errordot_t_, errordot_th_, Rreftomega_,
    t_, tref_;
  VectorUTheta  error_th_;
  MatrixRotation R_, Rref_, Rt_, Rreft_;
  Eigen::Matrix3d P_, Pinv_;
  double accuracy_;
  void inverseJacobianRodrigues ();
} ;

} /* namespace sot */} /* namespace dynamicgraph */

#endif // #ifndef __SOT_FEATURE_POINT6D_HH__

/*
 * Local variables:
 * c-basic-offset: 2
 * End:
 */
<|endoftext|>


<commit_before>#include "mitkPerfusionDataGenerator.h"
#include "itkMultiOutputNaryFunctorImageFilter.h"
#include "mitkArbitraryTimeGeometry.h"
#include "mitkImageCast.h"
#include "mitkImageAccessByItk.h"
#include "mitkITKImageImport.h"

void mitk::PerfusionDataGenerator::SetParameterInputImage(const ParametersIndexType parameterIndex, ParameterImageType parameterImage)
{
    m_ParameterInputMap.insert(std::make_pair(parameterIndex,parameterImage));

}

mitk::PerfusionDataGenerator::ResultImageType mitk::PerfusionDataGenerator::GetGeneratedImage()
{
    Generate();
    return m_ResultImage;
}

template <typename TPixel, unsigned int VDim>
void
  mitk::PerfusionDataGenerator::DoPrepareMask(itk::Image<TPixel, VDim>* image)
{
  m_InternalMask = dynamic_cast<InternalMaskType*>(image);

  if (m_InternalMask.IsNull())
  {
    MITK_INFO << "Parameter Fit Generator. Need to cast mask for parameter fit.";
    typedef itk::Image<TPixel, VDim> InputImageType;
    typedef itk::CastImageFilter< InputImageType, InternalMaskType > CastFilterType;
    typename CastFilterType::Pointer  spImageCaster =  CastFilterType::New();

    spImageCaster->SetInput(image);

    m_InternalMask = spImageCaster->GetOutput();
    spImageCaster->Update();
  }
}

template <typename TPixel, unsigned int VDim>
void  mitk::PerfusionDataGenerator::DoGenerateData(itk::Image<TPixel, VDim>* image)
{
    typedef itk::Image<TPixel, VDim> InputFrameImageType;
    typedef itk::Image<ScalarType, VDim> OutputImageType;

    typedef itk::MultiOutputNaryFunctorImageFilter<InputFrameImageType, OutputImageType, SimpleFunctorPolicy, InternalMaskType> FilterType;
    typename FilterType::Pointer filter;

    for(unsigned int i=0; i<this->m_ParameterInputMap.size(); ++i)
    {
        typename InputFrameImageType::Pointer frameImage;
        Image::Pointer parameterImage = m_InputParameterImages.at(i);

        mitk::CastToItkImage(parameterImage, frameImage);
        filter->SetInput(i,frameImage);

    }

    SimpleFunctorPolicy functor;
    functor.SetFunctor(this->m_Functor);
    filter->SetFunctor(functor);
    if (this->m_InternalMask.IsNotNull())
    {
     filter->SetMask(this->m_InternalMask);
    }
    filter->Update();

    ArbitraryTimeGeometry::Pointer timeGeometry = ArbitraryTimeGeometry::New();
    timeGeometry->ClearAllGeometries();
    Image::Pointer dynamicImage= Image::New();

    if(filter->GetNumberOfOutputs() != this->m_Functor->GetGrid().GetSize())
    {
        itkExceptionMacro("Error. Number of computed output Images does not match Grid size!");
    }

    auto m_Grid = this->m_Functor->GetGrid();
    for (GridType::size_type i = 0; i<m_Grid.GetSize(); ++i)
    {
      mitk::Image::Pointer frameImage = mitk::ImportItkImage(filter->GetOutput(i))->Clone();

      dynamicImage->SetVolume(frameImage->GetVolumeData()->GetData(),i);

      auto currentTimePoint =  m_Grid[i];
      auto nextTimePoint =  m_Grid[i];
      if (i+1<m_Grid.GetSize())
      {
          nextTimePoint =  m_Grid[i+1];
      }

      timeGeometry->AppendNewTimeStepClone(frameImage->GetGeometry(), currentTimePoint, nextTimePoint);
    }

    dynamicImage->SetTimeGeometry(timeGeometry);

    this->m_ResultImage = dynamicImage;
}

void mitk::PerfusionDataGenerator::SortParameterImages()
{
    ParameterVectorType inputImages(this->m_ParameterInputMap.size());

    unsigned int i = 0;
    for (ParameterMapType::const_iterator pos = m_ParameterInputMap.begin(); pos != m_ParameterInputMap.end(); ++pos)
    {

      i = pos->first;
      inputImages[i] = pos->second;
    }

    this->m_InputParameterImages = inputImages;

}

void mitk::PerfusionDataGenerator::Generate()
{
     SortParameterImages();

    if(this->m_Mask.IsNotNull())
    {
      AccessFixedDimensionByItk(m_Mask, mitk::PerfusionDataGenerator::DoPrepareMask, 3);
    }
    else
    {
      this->m_InternalMask = NULL;
    }

    /** @todo #1 This did not work! The Access-Routine would be a much nicer solution, but for some reasons, the handling did not work.
     * Thats why the code for Generation the Data was pasted below
     */
//    mitk::Image::Pointer firstParameterImage = this->m_InputParameterImages[0];
//    AccessFixedDimensionByItk(firstParameterImage, mitk::PerfusionDataGenerator::DoGenerateData, 3);

    typedef itk::Image<double, 3> InputFrameImageType;
    typedef itk::Image<double, 3> OutputImageType;

    typedef itk::MultiOutputNaryFunctorImageFilter<InputFrameImageType, OutputImageType, SimpleFunctorPolicy, InternalMaskType> FilterType;
    /** @todo #3 The ParameterFitImageGenerator uses a typename instead of new. But this did not work somehow
     */
     FilterType::Pointer filter = FilterType::New();

    for(unsigned int i=0; i<this->m_ParameterInputMap.size(); ++i)
    {
        /** @todo #3 The ParameterFitImageGenerator uses a typename instead of new. But this did not work somehow
         */
        InputFrameImageType::Pointer frameImage = InputFrameImageType::New();
        Image::Pointer parameterImage = m_InputParameterImages.at(i);

        mitk::CastToItkImage(parameterImage, frameImage);
        filter->SetInput(i,frameImage);

    }

    SimpleFunctorPolicy functor;
    functor.SetFunctor(this->m_Functor);
    filter->SetFunctor(functor);
    if (this->m_InternalMask.IsNotNull())
    {
     filter->SetMask(this->m_InternalMask);
    }
    filter->Update();

    if (filter->GetNumberOfOutputs() != this->m_Functor->GetGrid().GetSize())
    {
      itkExceptionMacro("Error. Number of computed output Images does not match Grid size!");
    }

    /** @todo #1 Better solution than all this code!
     * This was copied from TestingHelper/TestArtifactGenerator. Just instantiating a mitk::Image and setting its Volumes
     * in the for-loop did not work somehow.
     * This was a work around
     */

    typedef itk::Image<double,4> DynamicITKImageType;

    Image::Pointer dynamicImage= Image::New();
    mitk::Image::Pointer tempImage = mitk::ImportItkImage(filter->GetOutput(0))->Clone();

    DynamicITKImageType::Pointer dynamicITKImage = DynamicITKImageType::New();
    DynamicITKImageType::RegionType dynamicITKRegion;
    DynamicITKImageType::PointType dynamicITKOrigin;
    DynamicITKImageType::IndexType dynamicITKIndex;
    DynamicITKImageType::SpacingType dynamicITKSpacing;

    dynamicITKSpacing[0] = tempImage->GetGeometry()->GetSpacing()[0];
    dynamicITKSpacing[1] = tempImage->GetGeometry()->GetSpacing()[1];
    dynamicITKSpacing[2] = tempImage->GetGeometry()->GetSpacing()[2];
    dynamicITKSpacing[3] = 3.0;

    dynamicITKIndex[0] = 0;  // The first pixel of the REGION
    dynamicITKIndex[1] = 0;
    dynamicITKIndex[2] = 0;
    dynamicITKIndex[3] = 0;

    dynamicITKRegion.SetSize( 0,tempImage->GetDimension(0));
    dynamicITKRegion.SetSize( 1,tempImage->GetDimension(1));
    dynamicITKRegion.SetSize( 2,tempImage->GetDimension(2));
    dynamicITKRegion.SetSize(3, filter->GetNumberOfOutputs());

    dynamicITKRegion.SetIndex( dynamicITKIndex );

    dynamicITKOrigin[0]=tempImage->GetGeometry()->GetOrigin()[0];
    dynamicITKOrigin[1]=tempImage->GetGeometry()->GetOrigin()[1];
    dynamicITKOrigin[2]=tempImage->GetGeometry()->GetOrigin()[2];

    dynamicITKImage->SetOrigin(dynamicITKOrigin);
    dynamicITKImage->SetSpacing(dynamicITKSpacing);
    dynamicITKImage->SetRegions( dynamicITKRegion);
    dynamicITKImage->Allocate();
    dynamicITKImage->FillBuffer(0); //not sure if this is necessary

    // Convert
    mitk::CastToMitkImage(dynamicITKImage, dynamicImage);

    ArbitraryTimeGeometry::Pointer timeGeometry = ArbitraryTimeGeometry::New();
    timeGeometry->ClearAllGeometries();

    auto nrOfOutputs = filter->GetNumberOfOutputs();
    auto grid = this->m_Functor->GetGrid();
    for (unsigned int i = 0; i<nrOfOutputs; ++i)
    {
      mitk::Image::Pointer frame = mitk::ImportItkImage(filter->GetOutput(i))->Clone();
      mitk::ImageReadAccessor readAccess(frame, frame->GetVolumeData(0));
      dynamicImage->SetVolume(readAccess.GetData(),i);

      double tmax = 0;
      if (i<(nrOfOutputs - 1))
      {
        tmax = grid[i + 1] * 1000;
      }
      else
      {
        tmax = grid[i] * 1000;
      }
      timeGeometry->AppendNewTimeStepClone(frame->GetGeometry(), grid[i] * 1000, tmax);
     }

    dynamicImage->SetTimeGeometry(timeGeometry);

    this->m_ResultImage = dynamicImage->Clone();

}
<commit_msg>Removed warnings<commit_after>#include "mitkPerfusionDataGenerator.h"
#include "itkMultiOutputNaryFunctorImageFilter.h"
#include "mitkArbitraryTimeGeometry.h"
#include "mitkImageCast.h"
#include "mitkImageAccessByItk.h"
#include "mitkITKImageImport.h"

void mitk::PerfusionDataGenerator::SetParameterInputImage(const ParametersIndexType parameterIndex, ParameterImageType parameterImage)
{
    m_ParameterInputMap.insert(std::make_pair(parameterIndex,parameterImage));

}

mitk::PerfusionDataGenerator::ResultImageType mitk::PerfusionDataGenerator::GetGeneratedImage()
{
    Generate();
    return m_ResultImage;
}

template <typename TPixel, unsigned int VDim>
void
  mitk::PerfusionDataGenerator::DoPrepareMask(itk::Image<TPixel, VDim>* image)
{
  m_InternalMask = dynamic_cast<InternalMaskType*>(image);

  if (m_InternalMask.IsNull())
  {
    MITK_INFO << "Parameter Fit Generator. Need to cast mask for parameter fit.";
    typedef itk::Image<TPixel, VDim> InputImageType;
    typedef itk::CastImageFilter< InputImageType, InternalMaskType > CastFilterType;
    typename CastFilterType::Pointer  spImageCaster =  CastFilterType::New();

    spImageCaster->SetInput(image);

    m_InternalMask = spImageCaster->GetOutput();
    spImageCaster->Update();
  }
}

template <typename TPixel, unsigned int VDim>
void  mitk::PerfusionDataGenerator::DoGenerateData(itk::Image<TPixel, VDim>*)
{
    typedef itk::Image<TPixel, VDim> InputFrameImageType;
    typedef itk::Image<ScalarType, VDim> OutputImageType;

    typedef itk::MultiOutputNaryFunctorImageFilter<InputFrameImageType, OutputImageType, SimpleFunctorPolicy, InternalMaskType> FilterType;
    typename FilterType::Pointer filter;

    for(unsigned int i=0; i<this->m_ParameterInputMap.size(); ++i)
    {
        typename InputFrameImageType::Pointer frameImage;
        Image::Pointer parameterImage = m_InputParameterImages.at(i);

        mitk::CastToItkImage(parameterImage, frameImage);
        filter->SetInput(i,frameImage);

    }

    SimpleFunctorPolicy functor;
    functor.SetFunctor(this->m_Functor);
    filter->SetFunctor(functor);
    if (this->m_InternalMask.IsNotNull())
    {
     filter->SetMask(this->m_InternalMask);
    }
    filter->Update();

    ArbitraryTimeGeometry::Pointer timeGeometry = ArbitraryTimeGeometry::New();
    timeGeometry->ClearAllGeometries();
    Image::Pointer dynamicImage= Image::New();

    if(filter->GetNumberOfOutputs() != this->m_Functor->GetGrid().GetSize())
    {
        itkExceptionMacro("Error. Number of computed output Images does not match Grid size!");
    }

    auto m_Grid = this->m_Functor->GetGrid();
    for (GridType::size_type i = 0; i<m_Grid.GetSize(); ++i)
    {
      mitk::Image::Pointer frameImage = mitk::ImportItkImage(filter->GetOutput(i))->Clone();

      mitk::ImageReadAccessor readAccess(frameImage, frameImage->GetVolumeData());
      dynamicImage->SetVolume(readAccess.GetData(),i);

      auto currentTimePoint =  m_Grid[i];
      auto nextTimePoint =  m_Grid[i];
      if (i+1<m_Grid.GetSize())
      {
          nextTimePoint =  m_Grid[i+1];
      }

      timeGeometry->AppendNewTimeStepClone(frameImage->GetGeometry(), currentTimePoint, nextTimePoint);
    }

    dynamicImage->SetTimeGeometry(timeGeometry);

    this->m_ResultImage = dynamicImage;
}

void mitk::PerfusionDataGenerator::SortParameterImages()
{
    ParameterVectorType inputImages(this->m_ParameterInputMap.size());

    unsigned int i = 0;
    for (ParameterMapType::const_iterator pos = m_ParameterInputMap.begin(); pos != m_ParameterInputMap.end(); ++pos)
    {

      i = pos->first;
      inputImages[i] = pos->second;
    }

    this->m_InputParameterImages = inputImages;

}

void mitk::PerfusionDataGenerator::Generate()
{
     SortParameterImages();

    if(this->m_Mask.IsNotNull())
    {
      AccessFixedDimensionByItk(m_Mask, mitk::PerfusionDataGenerator::DoPrepareMask, 3);
    }
    else
    {
      this->m_InternalMask = NULL;
    }

    /** @todo #1 This did not work! The Access-Routine would be a much nicer solution, but for some reasons, the handling did not work.
     * Thats why the code for Generation the Data was pasted below
     */
//    mitk::Image::Pointer firstParameterImage = this->m_InputParameterImages[0];
//    AccessFixedDimensionByItk(firstParameterImage, mitk::PerfusionDataGenerator::DoGenerateData, 3);

    typedef itk::Image<double, 3> InputFrameImageType;
    typedef itk::Image<double, 3> OutputImageType;

    typedef itk::MultiOutputNaryFunctorImageFilter<InputFrameImageType, OutputImageType, SimpleFunctorPolicy, InternalMaskType> FilterType;
    /** @todo #3 The ParameterFitImageGenerator uses a typename instead of new. But this did not work somehow
     */
     FilterType::Pointer filter = FilterType::New();

    for(unsigned int i=0; i<this->m_ParameterInputMap.size(); ++i)
    {
        /** @todo #3 The ParameterFitImageGenerator uses a typename instead of new. But this did not work somehow
         */
        InputFrameImageType::Pointer frameImage = InputFrameImageType::New();
        Image::Pointer parameterImage = m_InputParameterImages.at(i);

        mitk::CastToItkImage(parameterImage, frameImage);
        filter->SetInput(i,frameImage);

    }

    SimpleFunctorPolicy functor;
    functor.SetFunctor(this->m_Functor);
    filter->SetFunctor(functor);
    if (this->m_InternalMask.IsNotNull())
    {
     filter->SetMask(this->m_InternalMask);
    }
    filter->Update();

    if (filter->GetNumberOfOutputs() != this->m_Functor->GetGrid().GetSize())
    {
      itkExceptionMacro("Error. Number of computed output Images does not match Grid size!");
    }

    /** @todo #1 Better solution than all this code!
     * This was copied from TestingHelper/TestArtifactGenerator. Just instantiating a mitk::Image and setting its Volumes
     * in the for-loop did not work somehow.
     * This was a work around
     */

    typedef itk::Image<double,4> DynamicITKImageType;

    Image::Pointer dynamicImage= Image::New();
    mitk::Image::Pointer tempImage = mitk::ImportItkImage(filter->GetOutput(0))->Clone();

    DynamicITKImageType::Pointer dynamicITKImage = DynamicITKImageType::New();
    DynamicITKImageType::RegionType dynamicITKRegion;
    DynamicITKImageType::PointType dynamicITKOrigin;
    DynamicITKImageType::IndexType dynamicITKIndex;
    DynamicITKImageType::SpacingType dynamicITKSpacing;

    dynamicITKSpacing[0] = tempImage->GetGeometry()->GetSpacing()[0];
    dynamicITKSpacing[1] = tempImage->GetGeometry()->GetSpacing()[1];
    dynamicITKSpacing[2] = tempImage->GetGeometry()->GetSpacing()[2];
    dynamicITKSpacing[3] = 3.0;

    dynamicITKIndex[0] = 0;  // The first pixel of the REGION
    dynamicITKIndex[1] = 0;
    dynamicITKIndex[2] = 0;
    dynamicITKIndex[3] = 0;

    dynamicITKRegion.SetSize( 0,tempImage->GetDimension(0));
    dynamicITKRegion.SetSize( 1,tempImage->GetDimension(1));
    dynamicITKRegion.SetSize( 2,tempImage->GetDimension(2));
    dynamicITKRegion.SetSize(3, filter->GetNumberOfOutputs());

    dynamicITKRegion.SetIndex( dynamicITKIndex );

    dynamicITKOrigin[0]=tempImage->GetGeometry()->GetOrigin()[0];
    dynamicITKOrigin[1]=tempImage->GetGeometry()->GetOrigin()[1];
    dynamicITKOrigin[2]=tempImage->GetGeometry()->GetOrigin()[2];

    dynamicITKImage->SetOrigin(dynamicITKOrigin);
    dynamicITKImage->SetSpacing(dynamicITKSpacing);
    dynamicITKImage->SetRegions( dynamicITKRegion);
    dynamicITKImage->Allocate();
    dynamicITKImage->FillBuffer(0); //not sure if this is necessary

    // Convert
    mitk::CastToMitkImage(dynamicITKImage, dynamicImage);

    ArbitraryTimeGeometry::Pointer timeGeometry = ArbitraryTimeGeometry::New();
    timeGeometry->ClearAllGeometries();

    auto nrOfOutputs = filter->GetNumberOfOutputs();
    auto grid = this->m_Functor->GetGrid();
    for (unsigned int i = 0; i<nrOfOutputs; ++i)
    {
      mitk::Image::Pointer frame = mitk::ImportItkImage(filter->GetOutput(i))->Clone();
      mitk::ImageReadAccessor readAccess(frame, frame->GetVolumeData(0));
      dynamicImage->SetVolume(readAccess.GetData(),i);

      double tmax = 0;
      if (i<(nrOfOutputs - 1))
      {
        tmax = grid[i + 1] * 1000;
      }
      else
      {
        tmax = grid[i] * 1000;
      }
      timeGeometry->AppendNewTimeStepClone(frame->GetGeometry(), grid[i] * 1000, tmax);
     }

    dynamicImage->SetTimeGeometry(timeGeometry);

    this->m_ResultImage = dynamicImage->Clone();

}
<|endoftext|>


<commit_before>#pragma once
#include <inttypes.h>
#include <string>

#define NAMESPACE_REGION( x ) namespace x {
#define END_REGION }

//WEE WOO WEE WOO ITS THE DWORD POLICE
using ulong_t = unsigned long;
using uword_t = unsigned short;

NAMESPACE_REGION( util )

template < typename fn > __forceinline fn get_vfunc( void* classbase, int index ) {
	if ( !classbase ) return fn{ };
	return ( fn )( ( uintptr_t* )*( uintptr_t** )classbase )[ index ];
}

static __forceinline std::string unicode_to_ascii( const std::wstring& unicode ) {
	std::string ascii_str( unicode.begin( ), unicode.end( ) );
	return ascii_str;
}

static __forceinline std::wstring ascii_to_unicode( const std::string& ascii ) {
	std::wstring unicode_str( ascii.begin( ), ascii.end( ) );
	return unicode_str;
}

END_REGION<commit_msg>useless include<commit_after>#pragma once

#define NAMESPACE_REGION( x ) namespace x {
#define END_REGION }

//WEE WOO WEE WOO ITS THE DWORD POLICE
using ulong_t = unsigned long;
using uword_t = unsigned short;

NAMESPACE_REGION( util )

template < typename fn > __forceinline fn get_vfunc( void* classbase, int index ) {
	if ( !classbase ) return fn{ };
	return ( fn )( ( uintptr_t* )*( uintptr_t** )classbase )[ index ];
}

static __forceinline std::string unicode_to_ascii( const std::wstring& unicode ) {
	std::string ascii_str( unicode.begin( ), unicode.end( ) );
	return ascii_str;
}

static __forceinline std::wstring ascii_to_unicode( const std::string& ascii ) {
	std::wstring unicode_str( ascii.begin( ), ascii.end( ) );
	return unicode_str;
}

END_REGION
<|endoftext|>


<commit_before>#include <unistd.h>

#include <event/event_callback.h>
#include <event/event_main.h>

#include <io/stream_handle.h>

class Sink {
	LogHandle log_;

	StreamHandle fd_;
	Action *action_;
public:
	Sink(int fd)
	: log_("/sink"),
	  fd_(fd),
	  action_(NULL)
	{
		EventCallback *cb = callback(this, &Sink::read_complete);
		action_ = fd_.read(0, cb);
	}

	~Sink()
	{
		ASSERT(log_, action_ == NULL);
	}

	void read_complete(Event e)
	{
		action_->cancel();
		action_ = NULL;

		switch (e.type_) {
		case Event::Done:
		case Event::EOS:
			break;
		default:
			HALT(log_) << "Unexpected event: " << e;
			return;
		}

		if (e.type_ == Event::EOS) {
			SimpleCallback *cb = callback(this, &Sink::close_complete);
			action_ = fd_.close(cb);
			return;
		}

		EventCallback *cb = callback(this, &Sink::read_complete);
		action_ = fd_.read(0, cb);
	}

	void close_complete(void)
	{
		action_->cancel();
		action_ = NULL;
	}
};

int
main(void)
{
	Sink sink(STDIN_FILENO);

	event_main();
}
<commit_msg>Convert to use Handlers.  Could be simpler.<commit_after>#include <unistd.h>

#include <event/callback_handler.h>
#include <event/event_callback.h>
#include <event/event_handler.h>
#include <event/event_main.h>

#include <io/stream_handle.h>

class Sink {
	LogHandle log_;

	StreamHandle fd_;
	CallbackHandler close_handler_;
	EventHandler read_handler_;
public:
	Sink(int fd)
	: log_("/sink"),
	  fd_(fd),
	  read_handler_()
	{
		read_handler_.handler(Event::Done, this, &Sink::read_done);
		read_handler_.handler(Event::EOS, this, &Sink::read_eos);

		close_handler_.handler(this, &Sink::close_done);

		read_handler_.wait(fd_.read(0, read_handler_.callback()));
	}

	~Sink()
	{ }

	void read_done(Event)
	{
		read_handler_.wait(fd_.read(0, read_handler_.callback()));
	}

	void read_eos(Event)
	{
		close_handler_.wait(fd_.close(close_handler_.callback()));
	}

	void close_done(void)
	{ }
};

int
main(void)
{
	Sink sink(STDIN_FILENO);

	event_main();
}
<|endoftext|>