text:
#ifndef XTENSOR_ITERATOR_HPP
#define XTENSOR_ITERATOR_HPP

#include <algorithm>
#include <array>
#include <cstddef>
#include <iterator>
#include <numeric>
#include <vector>

#include <xtl/xiterator_base.hpp>
#include <xtl/xsequence.hpp>

#include "xexception.hpp"
#include "xlayout.hpp"
#include "xshape.hpp"
#include "xutils.hpp"

namespace xt
{

    /***********************
     * iterator meta utils *
     ***********************/

    template <class CT>
    class xscalar;

    namespace detail
    {
        template <class C>
        struct get_stepper_iterator_impl
        {
            using type = typename C::container_iterator;
        };

        template <class C>
        struct get_stepper_iterator_impl<const C>
        {
            using type = typename C::const_container_iterator;
        };

        template <class CT>
        struct get_stepper_iterator_impl<xscalar<CT>>
        {
            using type = typename xscalar<CT>::dummy_iterator;
        };

        template <class CT>
        struct get_stepper_iterator_impl<const xscalar<CT>>
        {
            using type = typename xscalar<CT>::const_dummy_iterator;
        };
    }

    template <class C>
    using get_stepper_iterator = typename detail::get_stepper_iterator_impl<C>::type;

    namespace detail
    {
        template <class ST>
        struct index_type_impl
        {
            using type = dynamic_shape<typename ST::value_type>;
        };

        template <class V, std::size_t L>
        struct index_type_impl<std::array<V, L>>
        {
            using type = std::array<V, L>;
        };
    }

    template <class C>
    using xindex_type_t = typename detail::index_type_impl<C>::type;

    /************
     * xstepper *
     ************/

    template <class C>
    class xstepper
    {
    public:

        using storage_type = C;
        using subiterator_type = get_stepper_iterator<C>;
        using subiterator_traits = std::iterator_traits<subiterator_type>;
        using value_type = typename subiterator_traits::value_type;
        using reference = typename subiterator_traits::reference;
        using pointer = typename subiterator_traits::pointer;
        using difference_type = typename subiterator_traits::difference_type;
        using size_type = typename storage_type::size_type;
        using shape_type = typename storage_type::shape_type;
        using simd_type = xsimd::simd_type<value_type>;

        xstepper() = default;
        xstepper(storage_type* c, subiterator_type it, size_type offset) noexcept;

        reference operator*() const;

        void step(size_type dim, size_type n = 1);
        void step_back(size_type dim, size_type n = 1);
        void reset(size_type dim);
        void reset_back(size_type dim);

        void to_begin();
        void to_end(layout_type l);

        template <class R>
        R step_simd();

        value_type step_leading();

        template <class R>
        void store_simd(const R& vec);

    private:

        storage_type* p_c;
        subiterator_type m_it;
        size_type m_offset;
    };

    template <layout_type L>
    struct stepper_tools
    {
        // For performance reasons, increment_stepper and decrement_stepper are
        // specialized for the case where n=1, which underlies operator++ and
        // operator-- on xiterators.

        template <class S, class IT, class ST>
        static void increment_stepper(S& stepper,
                                      IT& index,
                                      const ST& shape);

        template <class S, class IT, class ST>
        static void decrement_stepper(S& stepper,
                                      IT& index,
                                      const ST& shape);

        template <class S, class IT, class ST>
        static void increment_stepper(S& stepper,
                                      IT& index,
                                      const ST& shape,
                                      typename S::size_type n);

        template <class S, class IT, class ST>
        static void decrement_stepper(S& stepper,
                                      IT& index,
                                      const ST& shape,
                                      typename S::size_type n);
    };

    /********************
     * xindexed_stepper *
     ********************/

    template <class E, bool is_const>
    class xindexed_stepper
    {
    public:

        using self_type = xindexed_stepper<E, is_const>;
        using xexpression_type = std::conditional_t<is_const, const E, E>;

        using value_type = typename xexpression_type::value_type;
        using reference = std::conditional_t<is_const,
                                             typename xexpression_type::const_reference,
                                             typename xexpression_type::reference>;
        using pointer = std::conditional_t<is_const,
                                           typename xexpression_type::const_pointer,
                                           typename xexpression_type::pointer>;
        using size_type = typename xexpression_type::size_type;
        using difference_type = typename xexpression_type::difference_type;

        using shape_type = typename xexpression_type::shape_type;
        using index_type = xindex_type_t<shape_type>;

        xindexed_stepper() = default;
        xindexed_stepper(xexpression_type* e, size_type offset, bool end = false) noexcept;

        reference operator*() const;

        void step(size_type dim, size_type n = 1);
        void step_back(size_type dim, size_type n = 1);
        void reset(size_type dim);
        void reset_back(size_type dim);

        void to_begin();
        void to_end(layout_type l);

    private:

        xexpression_type* p_e;
        index_type m_index;
        size_type m_offset;
    };

    template <class T>
    struct is_indexed_stepper
    {
        static const bool value = false;
    };

    template <class T, bool B>
    struct is_indexed_stepper<xindexed_stepper<T, B>>
    {
        static const bool value = true;
    };

    /*************
     * xiterator *
     *************/

    namespace detail
    {
        template <class S>
        class shape_storage
        {
        public:

            using shape_type = S;
            using param_type = const S&;

            shape_storage() = default;
            shape_storage(param_type shape);
            const S& shape() const;

        private:

            S m_shape;
        };

        template <class S>
        class shape_storage<S*>
        {
        public:

            using shape_type = S;
            using param_type = const S*;

            shape_storage(param_type shape = 0);
            const S& shape() const;

        private:

            const S* p_shape;
        };

        template <layout_type L>
        struct LAYOUT_FORBIDEN_FOR_XITERATOR;
    }

    template <class It, class S, layout_type L>
    class xiterator : public xtl::xrandom_access_iterator_base<xiterator<It, S, L>,
                                                               typename It::value_type,
                                                               typename It::difference_type,
                                                               typename It::pointer,
                                                               typename It::reference>,
                      private detail::shape_storage<S>
    {
    public:

        using self_type = xiterator<It, S, L>;

        using subiterator_type = It;
        using value_type = typename subiterator_type::value_type;
        using reference = typename subiterator_type::reference;
        using pointer = typename subiterator_type::pointer;
        using difference_type = typename subiterator_type::difference_type;
        using size_type = typename subiterator_type::size_type;
        using iterator_category = std::random_access_iterator_tag;

        using private_base = detail::shape_storage<S>;
        using shape_type = typename private_base::shape_type;
        using shape_param_type = typename private_base::param_type;
        using index_type = xindex_type_t<shape_type>;

        xiterator() = default;
        // end_index means either reverse_iterator && !end or !reverse_iterator && end
        xiterator(It it, shape_param_type shape, bool end_index);

        self_type& operator++();
        self_type& operator--();

        self_type& operator+=(difference_type n);
        self_type& operator-=(difference_type n);

        difference_type operator-(const self_type& rhs) const;

        reference operator*() const;
        pointer operator->() const;

        bool equal(const xiterator& rhs) const;
        bool less_than(const xiterator& rhs) const;

    private:

        subiterator_type m_it;
        index_type m_index;
        difference_type m_linear_index;

        using checking_type = typename detail::LAYOUT_FORBIDEN_FOR_XITERATOR<L>::type;
    };

    template <class It, class S, layout_type L>
    bool operator==(const xiterator<It, S, L>& lhs,
                    const xiterator<It, S, L>& rhs);

    template <class It, class S, layout_type L>
    bool operator<(const xiterator<It, S, L>& lhs,
                   const xiterator<It, S, L>& rhs);

    /*********************
     * xbounded_iterator *
     *********************/

    template <class It, class BIt>
    class xbounded_iterator : public xtl::xrandom_access_iterator_base<xbounded_iterator<It, BIt>,
                                                                       typename std::iterator_traits<It>::value_type,
                                                                       typename std::iterator_traits<It>::difference_type,
                                                                       typename std::iterator_traits<It>::pointer,
                                                                       typename std::iterator_traits<It>::reference>
    {
    public:

        using self_type = xbounded_iterator<It, BIt>;

        using subiterator_type = It;
        using bound_iterator_type = BIt;
        using value_type = typename std::iterator_traits<It>::value_type;
        using reference = typename std::iterator_traits<It>::reference;
        using pointer = typename std::iterator_traits<It>::pointer;
        using difference_type = typename std::iterator_traits<It>::difference_type;
        using iterator_category = std::random_access_iterator_tag;

        xbounded_iterator() = default;
        xbounded_iterator(It it, BIt bound_it);

        self_type& operator++();
        self_type& operator--();

        self_type& operator+=(difference_type n);
        self_type& operator-=(difference_type n);

        difference_type operator-(const self_type& rhs) const;

        value_type operator*() const;

        bool equal(const self_type& rhs) const;
        bool less_than(const self_type& rhs) const;

    private:

        subiterator_type m_it;
        bound_iterator_type m_bound_it;
    };

    template <class It, class BIt>
    bool operator==(const xbounded_iterator<It, BIt>& lhs,
                    const xbounded_iterator<It, BIt>& rhs);

    template <class It, class BIt>
    bool operator<(const xbounded_iterator<It, BIt>& lhs,
                   const xbounded_iterator<It, BIt>& rhs);

    /*******************************
    * trivial_begin / trivial_end *
    *******************************/

    namespace detail
    {
        template <class C>
        constexpr auto trivial_begin(C& c) noexcept
        {
            return c.storage_begin();
        }

        template <class C>
        constexpr auto trivial_end(C& c) noexcept
        {
            return c.storage_end();
        }

        template <class C>
        constexpr auto trivial_begin(const C& c) noexcept
        {
            return c.storage_begin();
        }

        template <class C>
        constexpr auto trivial_end(const C& c) noexcept
        {
            return c.storage_end();
        }
    }

    /***************************
     * xstepper implementation *
     ***************************/

    template <class C>
    inline xstepper<C>::xstepper(storage_type* c, subiterator_type it, size_type offset) noexcept
        : p_c(c), m_it(it), m_offset(offset)
    {
    }

    template <class C>
    inline auto xstepper<C>::operator*() const -> reference
    {
        return *m_it;
    }

    template <class C>
    inline void xstepper<C>::step(size_type dim, size_type n)
    {
        if (dim >= m_offset)
        {
            using strides_value_type = decltype(p_c->strides()[0]);
            m_it += difference_type(static_cast<strides_value_type>(n) * p_c->strides()[dim - m_offset]);
        }
    }

    template <class C>
    inline void xstepper<C>::step_back(size_type dim, size_type n)
    {
        if (dim >= m_offset)
        {
            using strides_value_type = decltype(p_c->strides()[0]);
            m_it -= difference_type(static_cast<strides_value_type>(n) * p_c->strides()[dim - m_offset]);
        }
    }

    template <class C>
    inline void xstepper<C>::reset(size_type dim)
    {
        if (dim >= m_offset)
        {
            m_it -= difference_type(p_c->backstrides()[dim - m_offset]);
        }
    }

    template <class C>
    inline void xstepper<C>::reset_back(size_type dim)
    {
        if (dim >= m_offset)
        {
            m_it += difference_type(p_c->backstrides()[dim - m_offset]);
        }
    }

    template <class C>
    inline void xstepper<C>::to_begin()
    {
        m_it = p_c->data_xbegin();
    }

    template <class C>
    inline void xstepper<C>::to_end(layout_type l)
    {
        m_it = p_c->data_xend(l);
    }

    template <class C>
    template <class R>
    inline R xstepper<C>::step_simd()
    {
        R reg;
        reg.load_unaligned(&(*m_it));
        m_it += xsimd::revert_simd_traits<R>::size;
        return reg;
    }

    template <class C>
    template <class R>
    inline void xstepper<C>::store_simd(const R& vec)
    {
        vec.store_unaligned(&(*m_it));
        m_it += xsimd::revert_simd_traits<R>::size;;
    }

    template <class C>
    auto xstepper<C>::step_leading() -> value_type
    {
        ++m_it;
        return *m_it;
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::row_major>::increment_stepper(S& stepper,
                                                                  IT& index,
                                                                  const ST& shape)
    {
        using size_type = typename S::size_type;
        size_type i = index.size();
        while (i != 0)
        {
            --i;
            if (index[i] != shape[i] - 1)
            {
                ++index[i];
                stepper.step(i);
                return;
            }
            else
            {
                index[i] = 0;
                if (i != 0)
                {
                    stepper.reset(i);
                }
            }
        }
        if (i == 0)
        {
            std::copy(shape.cbegin(), shape.cend(), index.begin());
            stepper.to_end(layout_type::row_major);
        }
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::row_major>::increment_stepper(S& stepper,
                                                                  IT& index,
                                                                  const ST& shape,
                                                                  typename S::size_type n)
    {
        using size_type = typename S::size_type;
        size_type i = index.size();
        size_type leading_i = index.size() - 1;
        while (i != 0 && n != 0)
        {
            --i;
            size_type inc = (i == leading_i) ? n : 1;
            if (index[i] + inc < shape[i])
            {
                index[i] += inc;
                stepper.step(i, inc);
                n -= inc;
                if (i != leading_i || index.size() == 1)
                {
                    i = index.size();
                }
            }
            else
            {
                if (i == leading_i)
                {
                    size_type off = shape[i] - index[i] - 1;
                    stepper.step(i, off);
                    n -= off;
                }
                index[i] = 0;
                if (i != 0)
                {
                    stepper.reset(i);
                }
            }
        }
        if (i == 0)
        {
            std::copy(shape.cbegin(), shape.cend(), index.begin());
            stepper.to_end(layout_type::row_major);
        }
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::row_major>::decrement_stepper(S& stepper,
                                                                  IT& index,
                                                                  const ST& shape)
    {
        using size_type = typename S::size_type;
        size_type i = index.size();
        while (i != 0)
        {
            --i;
            if (index[i] != 0)
            {
                --index[i];
                stepper.step_back(i);
                return;
            }
            else
            {
                index[i] = shape[i] - 1;
                if (i != 0)
                {
                    stepper.reset_back(i);
                }
            }
        }
        if (i == 0)
        {
            stepper.to_begin();
        }
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::row_major>::decrement_stepper(S& stepper,
                                                                  IT& index,
                                                                  const ST& shape,
                                                                  typename S::size_type n)
    {
        using size_type = typename S::size_type;
        size_type i = index.size();
        size_type leading_i = index.size() - 1;
        while (i != 0 && n != 0)
        {
            --i;
            size_type inc = (i == leading_i) ? n : 1;
            if (index[i] >= inc)
            {
                index[i] -= inc;
                stepper.step_back(i, inc);
                n -= inc;
                if (i != leading_i || index.size() == 1)
                {
                    i = index.size();
                }
            }
            else
            {
                if (i == leading_i)
                {
                    size_type off = index[i];
                    stepper.step_back(i, off);
                    n -= off;
                }
                index[i] = shape[i] - 1;
                if (i != 0)
                {
                    stepper.reset_back(i);
                }
            }
        }
        if (i == 0)
        {
            stepper.to_begin();
        }
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::column_major>::increment_stepper(S& stepper,
                                                                     IT& index,
                                                                     const ST& shape)
    {
        using size_type = typename S::size_type;
        size_type size = index.size();
        size_type i = 0;
        while (i != size)
        {
            if (index[i] != shape[i] - 1)
            {
                ++index[i];
                stepper.step(i);
                return;
            }
            else
            {
                index[i] = 0;
                if (i != size - 1)
                {
                    stepper.reset(i);
                }
            }
            ++i;
        }
        if (i == size)
        {
            std::copy(shape.cbegin(), shape.cend(), index.begin());
            stepper.to_end(layout_type::column_major);
        }
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::column_major>::increment_stepper(S& stepper,
                                                                     IT& index,
                                                                     const ST& shape,
                                                                     typename S::size_type n)
    {
        using size_type = typename S::size_type;
        size_type size = index.size();
        size_type i = 0;
        size_type leading_i = 0;
        while (i != size && n != 0)
        {
            size_type inc = (i == leading_i) ? n : 1;
            if (index[i] + inc < shape[i])
            {
                index[i] += inc;
                stepper.step(i, inc);
                n -= inc;
                if (i != leading_i || index.size() == 1)
                {
                    i = 0;
                    continue;
                }
            }
            else
            {
                if (i == leading_i)
                {
                    size_type off = shape[i] - index[i] - 1;
                    stepper.step(i, off);
                    n -= off;
                }
                index[i] = 0;
                if (i != size - 1)
                {
                    stepper.reset(i);
                }
            }
            ++i;
        }
        if (i == size)
        {
            std::copy(shape.cbegin(), shape.cend(), index.begin());
            stepper.to_end(layout_type::column_major);
        }
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::column_major>::decrement_stepper(S& stepper,
                                                                     IT& index,
                                                                     const ST& shape)
    {
        using size_type = typename S::size_type;
        size_type size = index.size();
        size_type i = 0;
        while (i != size)
        {
            if (index[i] != 0)
            {
                --index[i];
                stepper.step_back(i);
                return;
            }
            else
            {
                index[i] = shape[i] - 1;
                if (i != size - 1)
                {
                    stepper.reset_back(i);
                }
            }
            ++i;
        }
        if (i == size)
        {
            stepper.to_begin();
        }
    }

    template <>
    template <class S, class IT, class ST>
    void stepper_tools<layout_type::column_major>::decrement_stepper(S& stepper,
                                                                     IT& index,
                                                                     const ST& shape,
                                                                     typename S::size_type n)
    {
        using size_type = typename S::size_type;
        size_type size = index.size();
        size_type i = 0;
        size_type leading_i = 0;
        while (i != size && n != 0)
        {
            size_type inc = (i == leading_i) ? n : 1;
            if (index[i] >= inc)
            {
                index[i] -= inc;
                stepper.step_back(i, inc);
                n -= inc;
                if (i != leading_i || index.size() == 1)
                {
                    i = 0;
                    continue;
                }
            }
            else
            {
                if (i == leading_i)
                {
                    size_type off = index[i];
                    stepper.step_back(i, off);
                    n -= off;
                }
                index[i] = shape[i] - 1;
                if (i != size - 1)
                {
                    stepper.reset_back(i);
                }
            }
            ++i;
        }
        if (i == size)
        {
            stepper.to_begin();
        }
    }

    /***********************************
     * xindexed_stepper implementation *
     ***********************************/

    template <class C, bool is_const>
    inline xindexed_stepper<C, is_const>::xindexed_stepper(xexpression_type* e, size_type offset, bool end) noexcept
        : p_e(e), m_index(xtl::make_sequence<index_type>(e->shape().size(), size_type(0))), m_offset(offset)
    {
        if (end)
        {
            // Note: the layout here doesn't matter (unused) but using default layout looks more "correct"
            to_end(XTENSOR_DEFAULT_LAYOUT);
        }
    }

    template <class C, bool is_const>
    inline auto xindexed_stepper<C, is_const>::operator*() const -> reference
    {
        return p_e->element(m_index.cbegin(), m_index.cend());
    }

    template <class C, bool is_const>
    inline void xindexed_stepper<C, is_const>::step(size_type dim, size_type n)
    {
        if (dim >= m_offset)
        {
            m_index[dim - m_offset] += static_cast<typename index_type::value_type>(n);
        }
    }

    template <class C, bool is_const>
    inline void xindexed_stepper<C, is_const>::step_back(size_type dim, size_type n)
    {
        if (dim >= m_offset)
        {
            m_index[dim - m_offset] -= static_cast<typename index_type::value_type>(n);
        }
    }

    template <class C, bool is_const>
    inline void xindexed_stepper<C, is_const>::reset(size_type dim)
    {
        if (dim >= m_offset)
        {
            m_index[dim - m_offset] = 0;
        }
    }

    template <class C, bool is_const>
    inline void xindexed_stepper<C, is_const>::reset_back(size_type dim)
    {
        if (dim >= m_offset)
        {
            m_index[dim - m_offset] = p_e->shape()[dim - m_offset] - 1;
        }
    }

    template <class C, bool is_const>
    inline void xindexed_stepper<C, is_const>::to_begin()
    {
        std::fill(m_index.begin(), m_index.end(), size_type(0));
    }

    template <class C, bool is_const>
    inline void xindexed_stepper<C, is_const>::to_end(layout_type)
    {
        std::copy(p_e->shape().begin(), p_e->shape().end(), m_index.begin());
    }

    /****************************
     * xiterator implementation *
     ****************************/

    namespace detail
    {
        template <class S>
        inline shape_storage<S>::shape_storage(param_type shape)
            : m_shape(shape)
        {
        }

        template <class S>
        inline const S& shape_storage<S>::shape() const
        {
            return m_shape;
        }

        template <class S>
        inline shape_storage<S*>::shape_storage(param_type shape)
            : p_shape(shape)
        {
        }

        template <class S>
        inline const S& shape_storage<S*>::shape() const
        {
            return *p_shape;
        }

        template <>
        struct LAYOUT_FORBIDEN_FOR_XITERATOR<layout_type::row_major>
        {
            using type = int;
        };

        template <>
        struct LAYOUT_FORBIDEN_FOR_XITERATOR<layout_type::column_major>
        {
            using type = int;
        };
    }

    template <class It, class S, layout_type L>
    inline xiterator<It, S, L>::xiterator(It it, shape_param_type shape, bool end_index)
        : private_base(shape), m_it(it),
          m_index(end_index ? xtl::forward_sequence<index_type, const shape_type&>(this->shape())
                            : xtl::make_sequence<index_type>(this->shape().size(), size_type(0))),
          m_linear_index(0)
    {
        // end_index means either reverse_iterator && !end or !reverse_iterator && end
        if (end_index)
        {
            if (m_index.size() != size_type(0))
            {
                auto iter_begin = (L == layout_type::row_major) ? m_index.begin() : m_index.begin() + 1;
                auto iter_end = (L == layout_type::row_major) ? m_index.end() - 1 : m_index.end();
                std::transform(iter_begin, iter_end, iter_begin, [](const auto& v) { return v - 1; });
            }
            m_linear_index = difference_type(std::accumulate(this->shape().cbegin(), this->shape().cend(),
                                                             size_type(1), std::multiplies<size_type>()));
        }
    }

    template <class It, class S, layout_type L>
    inline auto xiterator<It, S, L>::operator++() -> self_type&
    {
        stepper_tools<L>::increment_stepper(m_it, m_index, this->shape());
        ++m_linear_index;
        return *this;
    }

    template <class It, class S, layout_type L>
    inline auto xiterator<It, S, L>::operator--() -> self_type&
    {
        stepper_tools<L>::decrement_stepper(m_it, m_index, this->shape());
        --m_linear_index;
        return *this;
    }

    template <class It, class S, layout_type L>
    inline auto xiterator<It, S, L>::operator+=(difference_type n) -> self_type&
    {
        if (n >= 0)
        {
            stepper_tools<L>::increment_stepper(m_it, m_index, this->shape(), static_cast<size_type>(n));
        }
        else
        {
            stepper_tools<L>::decrement_stepper(m_it, m_index, this->shape(), static_cast<size_type>(-n));
        }
        m_linear_index += n;
        return *this;
    }

    template <class It, class S, layout_type L>
    inline auto xiterator<It, S, L>::operator-=(difference_type n) -> self_type&
    {
        if (n >= 0)
        {
            stepper_tools<L>::decrement_stepper(m_it, m_index, this->shape(), static_cast<size_type>(n));
        }
        else
        {
            stepper_tools<L>::increment_stepper(m_it, m_index, this->shape(), static_cast<size_type>(-n));
        }
        m_linear_index -= n;
        return *this;
    }

    template <class It, class S, layout_type L>
    inline auto xiterator<It, S, L>::operator-(const self_type& rhs) const -> difference_type
    {
        return m_linear_index - rhs.m_linear_index;
    }

    template <class It, class S, layout_type L>
    inline auto xiterator<It, S, L>::operator*() const -> reference
    {
        return *m_it;
    }

    template <class It, class S, layout_type L>
    inline auto xiterator<It, S, L>::operator->() const -> pointer
    {
        return &(*m_it);
    }

    template <class It, class S, layout_type L>
    inline bool xiterator<It, S, L>::equal(const xiterator& rhs) const
    {
        XTENSOR_ASSERT(this->shape() == rhs.shape());
        return m_linear_index == rhs.m_linear_index;
    }

    template <class It, class S, layout_type L>
    inline bool xiterator<It, S, L>::less_than(const xiterator& rhs) const
    {
        XTENSOR_ASSERT(this->shape() == rhs.shape());
        return m_linear_index < rhs.m_linear_index;
    }

    template <class It, class S, layout_type L>
    inline bool operator==(const xiterator<It, S, L>& lhs,
                           const xiterator<It, S, L>& rhs)
    {
        return lhs.equal(rhs);
    }

    template <class It, class S, layout_type L>
    bool operator<(const xiterator<It, S, L>& lhs,
                   const xiterator<It, S, L>& rhs)
    {
        return lhs.less_than(rhs);
    }

    /************************************
     * xbounded_iterator implementation *
     ************************************/

    template <class It, class BIt>
    xbounded_iterator<It, BIt>::xbounded_iterator(It it, BIt bound_it)
        : m_it(it), m_bound_it(bound_it)
    {
    }

    template <class It, class BIt>
    inline auto xbounded_iterator<It, BIt>::operator++() -> self_type&
    {
        ++m_it;
        ++m_bound_it;
        return *this;
    }

    template <class It, class BIt>
    inline auto xbounded_iterator<It, BIt>::operator--() -> self_type&
    {
        --m_it;
        --m_bound_it;
        return *this;
    }

    template <class It, class BIt>
    inline auto xbounded_iterator<It, BIt>::operator+=(difference_type n) -> self_type&
    {
        m_it += n;
        m_bound_it += n;
        return *this;
    }

    template <class It, class BIt>
    inline auto xbounded_iterator<It, BIt>::operator-=(difference_type n) -> self_type&
    {
        m_it -= n;
        m_bound_it -= n;
        return *this;
    }

    template <class It, class BIt>
    inline auto xbounded_iterator<It, BIt>::operator-(const self_type& rhs) const -> difference_type
    {
        return m_it - rhs.m_it;
    }

    template <class It, class BIt>
    inline auto xbounded_iterator<It, BIt>::operator*() const -> value_type
    {
        using type = decltype(*m_bound_it);
        return (static_cast<type>(*m_it) < *m_bound_it) ? *m_it : static_cast<value_type>((*m_bound_it) - 1);
    }

    template <class It, class BIt>
    inline bool xbounded_iterator<It, BIt>::equal(const self_type& rhs) const
    {
        return m_it == rhs.m_it && m_bound_it == rhs.m_bound_it;
    }

    template <class It, class BIt>
    inline bool xbounded_iterator<It, BIt>::less_than(const self_type& rhs) const
    {
        return m_it < rhs.m_it;
    }

    template <class It, class BIt>
    inline bool operator==(const xbounded_iterator<It, BIt>& lhs,
                           const xbounded_iterator<It, BIt>& rhs)
    {
        return lhs.equal(rhs);
    }

    template <class It, class BIt>
    inline bool operator<(const xbounded_iterator<It, BIt>& lhs,
                          const xbounded_iterator<It, BIt>& rhs)
    {
        return lhs.less_than(rhs);
    }
}

#endif


text:
#include <lib/support/BitMask.h>
#include <lib/support/UnitTestRegistration.h>

#include <algorithm>
#include <cstring>
#include <initializer_list>
#include <nlunit-test.h>

using namespace chip;

namespace {

enum class TestEnum : uint16_t
{
    kZero = 0x0000, // not a valid mask or bit flag, here anyway

    kBit_0      = 0x0001,
    kBits_1_2   = 0x0006,
    kBits_4_7   = 0x00F0,
    kBits_High4 = 0xF000,
    kBits_High8 = 0xFF00,
};

void TestBitMaskOperations(nlTestSuite * inSuite, void * inContext)
{
    BitMask<TestEnum> mask;

    NL_TEST_ASSERT(inSuite, mask.Raw() == 0);

    mask.SetField(TestEnum::kBits_1_2, 2);
    NL_TEST_ASSERT(inSuite, mask.Raw() == 0x0004);

    mask.SetRaw(0);
    mask.SetField(TestEnum::kBits_4_7, 0x0B);
    NL_TEST_ASSERT(inSuite, mask.Raw() == 0x00B0);

    mask.SetRaw(0);

    for (uint16_t i = 0; i < 0x10; i++)
    {
        mask.SetField(TestEnum::kBits_High4, i);
        NL_TEST_ASSERT(inSuite, mask.Raw() == (i << 12));
    }

    mask.SetField(TestEnum::kBits_High8, 0x23);
    NL_TEST_ASSERT(inSuite, mask.Raw() == 0x2300);

    mask.SetField(TestEnum::kBits_High4, 0xA);
    NL_TEST_ASSERT(inSuite, mask.Raw() == 0xA300);
}

void TestBitFieldLogic(nlTestSuite * inSuite, void * inContext)
{
    BitMask<TestEnum> mask;

    // some general logic that still applies for bit fields just in case
    NL_TEST_ASSERT(inSuite, !mask.HasAny(TestEnum::kBits_High4));
    NL_TEST_ASSERT(inSuite, !mask.HasAny(TestEnum::kBits_High8));

    // setting something non-zero in the upper 4 bits sets "something" in both
    // upper and 4 and 8 bits
    mask.SetField(TestEnum::kBits_High4, 0x01);
    NL_TEST_ASSERT(inSuite, mask.HasAny(TestEnum::kBits_High4));
    NL_TEST_ASSERT(inSuite, mask.HasAny(TestEnum::kBits_High8));

    // sets something visible in high 8 bits, but not high 4 bits
    mask.SetField(TestEnum::kBits_High8, 0x01);
    NL_TEST_ASSERT(inSuite, !mask.HasAny(TestEnum::kBits_High4));
    NL_TEST_ASSERT(inSuite, mask.HasAny(TestEnum::kBits_High8));
}

void TestBitMaskInvalid(nlTestSuite * inSuite, void * inContext)
{
    BitMask<TestEnum> mask;

    // This generally tests for no infinite loops. Nothing to set here
    mask.SetField(TestEnum::kZero, 0x01);
    NL_TEST_ASSERT(inSuite, mask.Raw() == 0);

    mask.SetRaw(0x1234);
    mask.SetField(TestEnum::kZero, 0x01);
    NL_TEST_ASSERT(inSuite, mask.Raw() == 0x1234);
}

const nlTest sTests[] = {
    NL_TEST_DEF("BitMask operations", TestBitMaskOperations), //
    NL_TEST_DEF("BitFields logic", TestBitFieldLogic),        //
    NL_TEST_DEF("Invalid operations", TestBitMaskInvalid),    //
    NL_TEST_SENTINEL()                                        //
};

} // namespace

int TestBitMask()
{
    nlTestSuite theSuite = { "BitMask tests", &sTests[0], nullptr, nullptr };

    // Run test suit againt one context.
    nlTestRunner(&theSuite, nullptr);
    return nlTestRunnerStats(&theSuite);
}

CHIP_REGISTER_TEST_SUITE(TestBitMask)

redpajama_set_name: RedPajamaGithub


text:
#ifndef ROCKETCONTROLSLUAELEMENTFORMCONTROLINPUT_H
#define ROCKETCONTROLSLUAELEMENTFORMCONTROLINPUT_H

#include <Rocket/Core/Lua/lua.hpp>
#include <Rocket/Core/Lua/LuaType.h>
#include <Rocket/Controls/ElementFormControlInput.h>

using Rocket::Core::Lua::LuaType;
namespace Rocket {
namespace Controls {
namespace Lua {

//getters
int ElementFormControlInputGetAttrchecked(lua_State* L);
int ElementFormControlInputGetAttrmaxlength(lua_State* L);
int ElementFormControlInputGetAttrsize(lua_State* L);
int ElementFormControlInputGetAttrmax(lua_State* L);
int ElementFormControlInputGetAttrmin(lua_State* L);
int ElementFormControlInputGetAttrstep(lua_State* L);

//setters
int ElementFormControlInputSetAttrchecked(lua_State* L);
int ElementFormControlInputSetAttrmaxlength(lua_State* L);
int ElementFormControlInputSetAttrsize(lua_State* L);
int ElementFormControlInputSetAttrmax(lua_State* L);
int ElementFormControlInputSetAttrmin(lua_State* L);
int ElementFormControlInputSetAttrstep(lua_State* L);

extern Rocket::Core::Lua::RegType<ElementFormControlInput> ElementFormControlInputMethods[];
extern luaL_Reg ElementFormControlInputGetters[];
extern luaL_Reg ElementFormControlInputSetters[];

}
}
}
namespace Rocket { namespace Core { namespace Lua {
//inherits from ElementFormControl which inherits from Element
template<> void ExtraInit<Rocket::Controls::ElementFormControlInput>(lua_State* L, int metatable_index);
LUACONTROLSTYPEDECLARE(Rocket::Controls::ElementFormControlInput)
}}}
#endif


text:
using System;
using System.Collections;
using System.Collections.Generic;

namespace ShapefileSharp
{
    /// <summary>
    /// A Shape Index (.shx) file.
    /// </summary>
    internal sealed class ShxFile : IShxFile, IReadOnlyList<IShxRecord>, IDisposable
    {
        public ShxFile(string filePath) : base()
        {
            Reader = new ShxReader(filePath);
        }

        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls

        void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    Reader.Dispose();
                }

                disposedValue = true;
            }
        }

        // This code added to correctly implement the disposable pattern.
        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
        }
        #endregion

        private ShxReader Reader { get; }

        public IShapefileHeader Header {
            get
            {
                return Reader.ReadHeader();
            }
        }

        public IReadOnlyList<IShxRecord> Records
        {
            get
            {
                return this;
            }
        }

        int IReadOnlyCollection<IShxRecord>.Count
        {
            get
            {
                return Reader.GetRecordCount();
            }
        }

        IShxRecord IReadOnlyList<IShxRecord>.this[int index]
        {
            get
            {
                return Reader.ReadRecord(index);
            }
        }

        IEnumerator<IShxRecord> IEnumerable<IShxRecord>.GetEnumerator()
        {
            var self = (IReadOnlyList<IShxRecord>)this;

            for (int i = 0; i < self.Count; i++)
            {
                yield return self[i];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IReadOnlyList<IShxRecord>)this).GetEnumerator();
        }
    }
}


text:
- Update bundler version
- Update ruby version
- Update dependency version

# v2.0.0

## Changes
- Remove rest-client dependency
- Optimize symbols as keys

# v1.2.0

## Changes
- Add timeout to TWW gem request


text:
 - ltkaddwidget.lua
 -
 - an example for ltk.addwidget.
 -
 - Gunnar Zötl <gz@tset.de>, 2010.
 - Released under MIT/X11 license. See file LICENSE for details.
--]]

require "ltk"

-- these widget types already exist, this is just to demonstrate how
-- ltk.addtkwidget() works
ltk.addtkwidget('button', {'command'})

ltk.addtkwidget('text', {'xscrollcommand', 'yscrollcommand'}, {
	['create'] = {'create'},
	['window'] = {'create'},
	['bind'] = {3}
})

function pressme()
	local txt = ltk.wcmd(mytxt) {'get', '0.0', ltk.wcmd(mytxt){'index', 'end'}}
	io.write(txt)
	ltk.exit()
end

mytxt = ltk.x_text {}
mybtn = ltk.x_button {text="Press me!", command=pressme}

ltk.pack {mybtn, side="bottom"}
ltk.pack {mytxt, side="top"}

ltk.mainloop()


text:
/* global MAKE:false */

// process.env.YENV = 'production';

var PATH = require('path');

MAKE.decl('Arch', {

    blocksLevelsRegexp : /^.+?\.blocks/,
    bundlesLevelsRegexp : /^.+?\.bundles$/

});

MAKE.decl('BundleNode', {

    getTechs : function() {

        return [
            'bemdecl.js',
            'deps.js',
            'bemhtml',
            'bemtree',
            'browser.js',
            'node.js'
        ];

    },

    getLevelsMap : function() {
        return {
            desktop : [
                'libs/bnsf/pre-bem-core.blocks',
                'libs/bem-core/common.blocks',
                'libs/bem-core/desktop.blocks',
                'libs/bnsf/blocks',
                'libs/bnsf/dev.blocks',
                'desktop.blocks'
            ]
        };
    },

     getLevels : function() {
        var resolve = PATH.resolve.bind(PATH, this.root),
            buildLevel = this.getLevelPath().split('.')[0],
            levels = this.getLevelsMap()[buildLevel] || [];

        return levels
            .map(function(path) { return resolve(path); })
            .concat(resolve(PATH.dirname(this.getNodePrefix()), 'blocks'));
    },

    'create-browser.js-optimizer-node' : function() {
        return this['create-js-optimizer-node'].apply(this, arguments);
    }

});


text:
Using yawd-admin
================

.. _setup:

Set up
++++++

To use the yawd-admin website you first need to include yawdadmin in
your ``INSTALLED_APPS`` setting. You also not need to include
`django.contrib.admin` in ``INSTALLED_APPS`` and place
it **after** `yawdadmin` for yawd-admin to work properly. In `settings.py`:

.. code-block:: python

	INSTALLED_APPS = (
		...
		'yawdadmin',
		'django.contrib.admin',
		...
	)

yawd-admin uses the :class:`yawdadmin.middleware.PopupMiddleware` middleware
to replace the  standard django admin popups with fancybox. Make sure the
middleware is enabled in your ``MIDDLEWARE_CLASSES`` setting. In `settings.py`:

.. code-block:: python

	MIDDLEWARE_CLASSES = (
		...
		'yawdadmin.middleware.PopupMiddleware',
		...
	)

Note::

	If you're running Django 1.6 and above, you don't need to use this middleware.

Finally, the `django.core.context_processors.request` context
processor must also be enabled:

.. code-block:: python

	TEMPLATE_CONTEXT_PROCESSORS = (
		...
		"django.core.context_processors.request",
		...
	)

.. _register-urls:

Registering the yawd-admin urls
+++++++++++++++++++++++++++++++

To register the admin site views, use the following (inside your `urls.py`):

.. code-block:: python

	from yawdadmin import admin_site

	patterns = (''
		url(r'^admin/', include(admin_site.urls)),
		...
	)

You **do not** need to register the django admin urls as well, the
yawd ``admin_site`` extends the original admin class.

.. _auto-discover:

ModelAdmin registration and auto-discovery
++++++++++++++++++++++++++++++++++++++++++

Normally, to register your normal ModelAdmin class with yawd-admin you
should use ``yawdadmin.admin_site`` instead of the original
``django.contrib.admin.site`` instance (in `admin.py`):

.. code-block:: python

	from django.contrib import admin
	from models import MyModel

	class MyModelAdmin(admin.ModelAdmin):
		pass

	from yawdadmin import admin_site
	#you can use this instead of admin.site.register():
	admin_site.register(MyModel, MyModelAdmin)

However, many applications might have registered their `ModelAdmin`
classes with the default django admin site. As you can see from the
above snippet yawd-admin uses the `ModelAdmin` class as well, therefore
you can easily add all standard registrations to the yawd-admin website.
To do so, use the standard `admin.autodiscover()` method and then update
the yawd-admin registry as follows (in `urls.py`):

.. code-block:: python

	from django.contrib import admin
	from yawdadmin import admin_site

	admin.autodiscover()
	admin_site._registry.update(admin.site._registry)

.. _custom-user-models:

Integration with Custom User Models
+++++++++++++++++++++++++++++++++++

yawdadmin comes with a new admin view to allow staff users edit their own
account information (username,  first name, last name and email). This view
uses a ModelForm of the standard ``django.contrib.auth.models.User`` model.

If your projects makes use of the
`new django 1.5 custom user functionality <https://docs.djangoproject.com/en/dev/topics/auth/customizing/#auth-custom-user>`_
you can set the ``ADMIN_USER_MODELFORM`` yawd-admin setting to override the
ModelForm used by the view (in settings.py):

.. code-block:: python

	ADMIN_USER_MODELFORM = 'myapp.module.MyModelForm'

Note that the setting value can be a string or Class. A string is normally
preferred to avoid import errors during environment initialization.

.. settings:

Settings
++++++++

ADMIN_DISABLE_APP_INDEX
***********************

With yawd-admin you can optionaly disable the app index view (the one that lists an application's
models). Doing so will raise "Page Not Found" (404) errors when accessing the application urls and
will also hide all corresponding links from breadcrumbs.

.. code-block:: python

	ADMIN_DISABLE_APP_INDEX = True

ADMIN_GOOGLE_ANALYTICS
**********************

A dictionary holding configuration of the connected google analytics account. Please see
:ref:`google-analytics`.

ADMIN_SITE_NAME / ADMIN_SITE_DESCRIPTION
****************************************

You can change the admin site name and add a description to the login page
by adding a couple attributes to your settings:

.. code-block:: python

	ADMIN_SITE_NAME = 'My Admin Site'
	ADMIN_SITE_DESCRIPTION = 'This is a private site.  Please don\'t hack me'

If you don't want a description at all just null the attribute:

.. code-block:: python

	ADMIN_SITE_DESCRIPTION = None

ADMIN_SITE_LOGO_HTML
********************

To set a logo that will show up in the right side of the header:

.. code-block:: python

	ADMIN_SITE_LOGO_HTML = '
Logo
'

ADMIN_JS_CATALOG
****************

Additional javascript translation messages for use in the admin interface. Please see
:ref:`message-translations`.

ADMIN_JS_CATALOG_CACHE_TIMEOUT
****************

For how long you want the js catalog view to be cached. Yawd-admin will cache a different version
of the view per language. Use 0 if you want to disable caching on the jsi18n view.
Defaults to 60 * 60 (1 hour).

ADMIN_USER_MODELFORM
********************

If you implement a custom user model (django 1.5 and above) you can override the ModelForm that
yawd-admin uses to allow staff users edit their account data. For more info please see
:ref:`custom-user-models`.

.. code-block:: python

	ADMIN_USER_MODELFORM = 'myapp.module.MyModelForm'

ADMIN_CACHE_DB_OPTIONS
**********************

default: `3600`

Cache duration (in seconds) for the admin database options. Cache gets updated each time an option value
changes. That way cached values always reflect the db values. If set to 0 there will be no
caching.


text:
package org.wiztools.restclient.ui.component;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import org.wiztools.commons.StringUtil;
import org.wiztools.restclient.persistence.XMLException;
import org.wiztools.restclient.ui.ScriptEditor;
import org.wiztools.restclient.ui.TextEditorSyntax;
import org.wiztools.restclient.util.HTMLIndentUtil;
import org.wiztools.restclient.util.JSONUtil;
import org.wiztools.restclient.util.XMLIndentUtil;

/**
 *
 * @author subhash
 */
public class BodyPopupMenu extends JPopupMenu {

    private BackgroundFormatterJob job = new BackgroundFormatterJob();

    public BodyPopupMenu(final ScriptEditor se,
            final BodyPopupMenuListener listener,
            final boolean isSeparateThread) {
        super();

        // Syntax Format:
        JMenu jm_format = new JMenu("Format");

        { // XML:
            JMenuItem jmi_fmt_xml = new JMenuItem("XML");
            jmi_fmt_xml.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    final String unformatted = se.getText();
                    if(StringUtil.isEmpty(unformatted)) {
                        listener.onFailure("Body is empty.");
                        return;
                    }
                    Runnable r = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                final String out = XMLIndentUtil.getIndented(unformatted);
                                se.setText(out);
                                listener.onSuccess("Formatted successfully.");
                            }
                            catch(IOException | XMLException ex) {
                                listener.onFailure("Formatting error: " + ex.getMessage());
                            }
                        }

                    };
                    job.run(r, listener, isSeparateThread);

                }
            });
            jm_format.add(jmi_fmt_xml);
        }

        { // JSON:
            JMenuItem jmi_fmt_json = new JMenuItem("JSON");
            jmi_fmt_json.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    final String unformatted = se.getText();
                    if(StringUtil.isEmpty(unformatted)) {
                        listener.onFailure("Body is empty.");
                        return;
                    }
                    Runnable r = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                final String out = JSONUtil.indentJSON(unformatted);
                                se.setText(out);
                                listener.onSuccess("Formatted successfully.");
                            }
                            catch(JSONUtil.JSONParseException ex) {
                                listener.onFailure("Formatting error: " + ex.getMessage());
                            }
                        }
                    };
                    job.run(r, listener, isSeparateThread);
                }
            });
            jm_format.add(jmi_fmt_json);
        }

        { // HTML:
            JMenuItem jmi_fmt_html = new JMenuItem("HTML");
            jmi_fmt_html.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    final String unformatted = se.getText();
                    if(StringUtil.isEmpty(unformatted)) {
                        listener.onFailure("Body is empty.");
                        return;
                    }
                    Runnable r = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                final String out = HTMLIndentUtil.getIndented(unformatted);
                                se.setText(out);
                                listener.onSuccess("Formatted successfully.");
                            }
                            catch(Exception ex) {
                                listener.onFailure("Formatting error: " + ex.getMessage());
                            }
                        }
                    };
                    job.run(r, listener, isSeparateThread);
                }
            });
            jm_format.add(jmi_fmt_html);
        }

        this.add(jm_format);

        // Syntax Highlight:
        JMenu jm_syntax = new JMenu("Syntax Color");

        { // None:
            JMenuItem jmi_syntax_none = new JMenuItem("None");
            jmi_syntax_none.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    se.setSyntax(TextEditorSyntax.NONE);
                }
            });
            jm_syntax.add(jmi_syntax_none);
        }

        { // XML:
            JMenuItem jmi_syntax_xml = new JMenuItem("XML");
            jmi_syntax_xml.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    se.setSyntax(TextEditorSyntax.XML);
                }
            });
            jm_syntax.add(jmi_syntax_xml);
        }

        { // JSON:
            JMenuItem jmi_syntax_json = new JMenuItem("JSON");
            jmi_syntax_json.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    se.setSyntax(TextEditorSyntax.JSON);
                }
            });
            jm_syntax.add(jmi_syntax_json);
        }

        { // HTML:
            JMenuItem jmi_syntax_html = new JMenuItem("HTML");
            jmi_syntax_html.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    se.setSyntax(TextEditorSyntax.HTML);
                }
            });
            jm_syntax.add(jmi_syntax_html);
        }

        this.add(jm_syntax);
    }

    public void cancelRunningJob() {
        job.cancelRunningJob();
    }
}


text:
package com.rowland.texturepacker;

import java.io.IOException;

import com.badlogic.gdx.tools.imagepacker.TexturePacker2;
import com.badlogic.gdx.tools.imagepacker.TexturePacker2.Settings;

/**
 * @author Rowland
 *
 */
public class MyTexturePacker  {

	public static final String INPUT_DIR ="assets/images/input/yoyo/base/";
	public static final String OUTPUT_DIR ="assets/images/output/yoyo/base/";
	public static final String PACK_FILE_NAME ="base_atlas.pack";

	public static void main(String[] args) throws IOException
	{   //Sample settings
		Settings settings = new Settings();
		settings.maxWidth = 1024;
		settings.maxHeight = 1024;
		settings.stripWhitespaceX = true;
		settings.stripWhitespaceY = true;
		settings.flattenPaths = true;
		settings.paddingX = 0 ;
		settings.paddingY = 0;
		settings.combineSubdirectories = true;

		TexturePackerHolder packerHolder = new TexturePackerHolder(settings, INPUT_DIR, OUTPUT_DIR, PACK_FILE_NAME);

		TexturePacker2.process(packerHolder.getSettings(),  packerHolder.getInputDir(), packerHolder.getOutputDir(),  packerHolder.getPackFileName());
		System.out.print("DONE : Check Output Folder for Atlas");
	}

	public void process()
	{

	}

}


text:
package io.fabric8.apmagent.strategy.trace;

import io.fabric8.apmagent.ApmConfiguration;
import io.fabric8.apmagent.ClassInfo;
import io.fabric8.apmagent.Strategy;
import io.fabric8.apmagent.metrics.ApmAgentContext;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.util.CheckClassAdapter;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.lang.instrument.UnmodifiableClassException;
import java.security.ProtectionDomain;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicBoolean;

public class TraceStrategy implements Strategy, ClassFileTransformer {
    private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(TraceStrategy.class);

    private ApmAgentContext context;
    private ApmConfiguration configuration;
    private Instrumentation instrumentation;
    private BlockingQueue<Class<?>> blockingQueue = new LinkedBlockingDeque<>();
    private AtomicBoolean initialized = new AtomicBoolean();
    private AtomicBoolean started = new AtomicBoolean();
    private AtomicBoolean cleanUp = new AtomicBoolean();
    private Thread transformThread;

    public TraceStrategy(ApmAgentContext context, Instrumentation instrumentation) {
        this.context = context;
        this.configuration = context.getConfiguration();
        this.instrumentation = instrumentation;
    }

    @Override
    public void initialize() throws Exception {
        if (initialized.compareAndSet(false, true)) {
            configuration.addChangeListener(this);
        }
    }

    @Override
    public void start() throws Exception {
        if (started.compareAndSet(false, true)) {
            initialize();
            instrumentApplication();
        }
    }

    @Override
    public void stop() {
        if (started.compareAndSet(true, false)) {

        }
    }

    @Override
    public void shutDown() {
        if (initialized.compareAndSet(true, false)) {
            stop();
            configuration.removeChangeListener(this);
            instrumentation.removeTransformer(this);
            Thread t = transformThread;
            transformThread = null;
            if (t != null && !t.isInterrupted()) {
                t.interrupt();
            }
            cleanUp.set(true);
            try {
                //clean up
                instrumentApplication();
            } catch (Throwable e) {
                LOG.error("Failed to shutdown", e);
            }
        }
    }

    public boolean isAudit(String className) {
        return configuration.isAudit(className);
    }

    public boolean isAudit(String className, String methodName) {
        return configuration.isAudit(className, methodName);
    }

    @Override
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        byte[] buffer = null;
        ClassInfo classInfo = context.getClassInfo(className);
        classInfo.setOriginalClass(classBeingRedefined);
        if (classInfo.getTransformed() == null) {
            //we haven't been transformed before
            classInfo.setOriginal(classfileBuffer);
        }
        if (!cleanUp.get()) {
            byte[] classBufferToRedefine = classInfo.getOriginal();

            if (configuration.isAudit(className)) {
                if (classInfo.isTransformed()) {
                    //remove metrics from methods no longer defined
                    context.resetMethods(classInfo);
                }
                ClassReader cr = new ClassReader(classBufferToRedefine);

                ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);

                ApmClassVisitor visitor = new ApmClassVisitor(this, cw, classInfo);
                cr.accept(visitor, ClassReader.SKIP_FRAMES);
                buffer = cw.toByteArray();
                if (!verifyClass(className, buffer)) {
                    classInfo.setCanTransform(false);
                    buffer = null;
                }
                classInfo.setTransformed(buffer);
            }
        } else {
            if (classInfo.getOriginal() != null) {
                buffer = classInfo.getOriginal();
                context.resetAll(classInfo);
            }
        }
        return buffer;
    }

    @Override
    public void configurationChanged() {
        if (started.get()) {
            if (configuration.isFilterChanged()) {
                List<ClassInfo> deltas = context.buildDeltaList();
                if (deltas != null && !deltas.isEmpty()) {
                    for (ClassInfo classInfo : deltas) {
                        if (configuration.isAsyncTransformation()) {
                            try {
                                blockingQueue.put(classInfo.getOriginalClass());
                            } catch (InterruptedException e) {
                                Thread.currentThread().interrupt();
                                break;
                            }
                        } else {
                            try {
                                instrumentation.retransformClasses(new Class[]{classInfo.getOriginalClass()});
                            } catch (Throwable e) {
                                LOG.error("Could not transform " + classInfo.getClassName(), e);
                            }
                        }
                    }
                    if (configuration.isAsyncTransformation() && !blockingQueue.isEmpty()) {
                        startTransformThread();
                    }
                }
            }
        }
    }

    public Instrumentation getInstrumentation() {
        return instrumentation;
    }

    public void setInstrumentation(Instrumentation instrumentation) {
        this.instrumentation = instrumentation;
    }

    public ApmAgentContext getContext() {
        return context;
    }

    public void setContext(ApmAgentContext context) {
        this.context = context;
        this.configuration = context.getConfiguration();
    }

    private void instrumentApplication() throws FileNotFoundException, UnmodifiableClassException {
        if (!instrumentation.isRetransformClassesSupported()) {
            throw new UnmodifiableClassException();
        }

        instrumentation.addTransformer(this, true);

        for (Class<?> c : instrumentation.getAllLoadedClasses()) {
            if (isInstrumentClass(c)) {
                if (configuration.isAsyncTransformation()) {
                    try {
                        blockingQueue.put(c);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                } else {
                    try {
                        instrumentation.retransformClasses(new Class[]{c});
                    } catch (Throwable e) {
                        LOG.error("Could not transform " + c.getName(), e);
                    }
                }
            }
        }
        if (configuration.isAsyncTransformation() && !blockingQueue.isEmpty()) {
            startTransformThread();
        }
    }

    private boolean isInstrumentClass(Class c) {

        if (!instrumentation.isModifiableClass(c)) {
            LOG.trace("NO INSTRUMENT: Class " + c.getName() + " is not modifiable");
            return false;
        }
        if (!configuration.isAudit(c.getName())) {
            LOG.trace("NO INSTRUMENT: Class " + c.getName() + " is blacklisted");
            return false;
        }
        if (c.isArray() || c.isAnnotation() || c.isInterface() || c.isPrimitive() || c.isSynthetic() || c.isEnum()) {
            LOG.trace("NO INSTRUMENT: Class " + c.getName() + " is an array, primitive, annotation or enum etc");
            return false;
        }
        return true;
    }

    private synchronized void startTransformThread() {
        if (configuration.isAsyncTransformation() && transformThread == null) {
            transformThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (initialized.get() && !blockingQueue.isEmpty()) {
                        try {
                            Class<?> aClass = blockingQueue.take();
                            if (aClass != null) {
                                if (isInstrumentClass(aClass)) {
                                    try {
                                        instrumentation.retransformClasses(new Class[]{aClass});
                                    } catch (Throwable e) {
                                        LOG.error("Could not transform " + aClass.getName(), e);
                                    }
                                }
                            }
                        } catch (InterruptedException e) {
                            shutDown();
                        }
                    }
                }
            });
            transformThread.setDaemon(true);
            transformThread.start();
        }
    }

    private boolean verifyClass(String className, byte[] transformed) {
        boolean result = true;
        if (configuration.isVerifyClasses()) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            CheckClassAdapter.verify(new ClassReader(transformed), false, pw);
            if (sw.toString().length() != 0) {
                result = false;
                LOG.error(" Failed to transform class: " + className);
                LOG.error(sw.toString());
            }
        }
        return result;
    }
}


text:
package influxdb

import (
	"regexp"
)

type regexpRewriter struct {
	okStart, okRest [256]bool
	replacement     byte
}

func newRegexpRewriter(startRe, restRe string) *regexpRewriter {
	createArray := func(okRe string) (ret [256]bool) {
		re := regexp.MustCompile(okRe)
		// Check for only 7 bit non-control ASCII characters
		for i := 32; i < 128; i++ {
			if re.Match([]byte{byte(i)}) {
				ret[i] = true
			}
		}
		return
	}
	return &regexpRewriter{okStart: createArray(startRe), okRest: createArray(restRe), replacement: byte('_')}
}

func (rr *regexpRewriter) rewrite(input []byte) {
	if len(input) == 0 {
		return
	}
	if !rr.okStart[input[0]] {
		input[0] = rr.replacement
	}
	for i := 1; i < len(input); i++ {
		if !rr.okRest[input[i]] {
			input[i] = rr.replacement
		}
	}
}

// Utility, which handles both __name__ ('metric') tag, as well as
// rest of tags ('labels')
//
// It allow using any influxdb client, rewriting the tag names + the
// magic __name__ tag to match what Prometheus expects
type promRewriter struct {
	metric, metricTail, label *regexpRewriter
}

func newPromRewriter() *promRewriter {
	return &promRewriter{
		metric: newRegexpRewriter(
			"[a-zA-Z_:]",
			"[a-zA-Z0-9_:]"),
		metricTail: newRegexpRewriter(
			"[a-zA-Z0-9_:]",
			"[a-zA-Z0-9_:]"),
		label: newRegexpRewriter(
			"[a-zA-Z_]", "[a-zA-Z0-9_]")}
}

func (pr *promRewriter) rewriteMetric(data []byte) {
	pr.metric.rewrite(data)
}

func (pr *promRewriter) rewriteMetricTail(data []byte) {
	pr.metricTail.rewrite(data)
}

func (pr *promRewriter) rewriteLabel(data []byte) {
	pr.label.rewrite(data)
}


text:
namespace base {
class FilePath;
}

namespace leveldb_proto {

// Interface for classes providing persistent storage of Protocol Buffer
// entries (T must be a Proto type extending MessageLite).
template <typename T>
class ProtoDatabase {
 public:
  using InitCallback = base::Callback<void(bool success)>;
  using UpdateCallback = base::Callback<void(bool success)>;
  using LoadCallback =
      base::Callback<void(bool success, std::unique_ptr<std::vector<T>>)>;
  using LoadKeysCallback =
      base::Callback<void(bool success,
                          std::unique_ptr<std::vector<std::string>>)>;
  using GetCallback = base::Callback<void(bool success, std::unique_ptr<T>)>;
  using DestroyCallback = base::Callback<void(bool success)>;

  // A list of key-value (string, T) tuples.
  using KeyEntryVector = std::vector<std::pair<std::string, T>>;

  virtual ~ProtoDatabase() {}

  // Asynchronously initializes the object with default options. |callback| will
  // be invoked on the calling thread when complete.
  void Init(const char* client_name,
            const base::FilePath& database_dir,
            const InitCallback& callback) {
    InitWithOptions(client_name, Options(database_dir), callback);
  }

  // Similar to Init, but takes additional options.
  virtual void InitWithOptions(const char* client_name,
                               const Options& options,
                               const InitCallback& callback) = 0;

  // Asynchronously saves |entries_to_save| and deletes entries from
  // |keys_to_remove| from the database. |callback| will be invoked on the
  // calling thread when complete.
  virtual void UpdateEntries(
      std::unique_ptr<KeyEntryVector> entries_to_save,
      std::unique_ptr<std::vector<std::string>> keys_to_remove,
      const UpdateCallback& callback) = 0;

  // Asynchronously loads all entries from the database and invokes |callback|
  // when complete.
  virtual void LoadEntries(const LoadCallback& callback) = 0;

  // Asynchronously loads all keys from the database and invokes |callback| with
  // those keys when complete.
  virtual void LoadKeys(const LoadKeysCallback& callback) = 0;

  // Asynchronously loads a single entry, identified by |key|, from the database
  // and invokes |callback| when complete. If no entry with |key| is found,
  // a nullptr is passed to the callback, but the success flag is still true.
  virtual void GetEntry(const std::string& key,
                        const GetCallback& callback) = 0;

  // Asynchronously destroys the database.
  virtual void Destroy(const DestroyCallback& callback) = 0;
};

}  // namespace leveldb_proto

#endif  // COMPONENTS_LEVELDB_PROTO_PROTO_DATABASE_H_


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="favicon.ico">

    <title>Presente Agora | Estilo de vida</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/font-awesome.min.css" rel="stylesheet">
    <link href="css/datepicker3.css" rel="stylesheet">

    <link href="css/jumbotron.css" rel="stylesheet">
    <link href="css/custom.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>

Estilo de vida

Qual é o estilo de vida da pessoa que você quer presentear?

				<button type="button" class="btn btn-success btn-circle" style="cursor:pointer" onclick="location.href='/quem';"></button>

Quem?

				<button type="button" class="btn btn-primary btn-circle" disabled="disabled"></button>

Estilo de vida

				<button type="button" class="btn btn-default btn-circle" disabled="disabled"></button>

Sugestões

<a href="/sugestoes?quem=<?php print $_GET['quem']; ?>&estilo=nerd"><img src="img/<?php print substr($_GET['quem'], 0, 1); ?>-nerd.jpg" alt=""/>
Nerd

<a href="/sugestoes?quem=<?php print $_GET['quem']; ?>&estilo=hipster" onclick="alerta_estilo(); return false;"><img src="img/<?php print substr($_GET['quem'], 0, 1); ?>-hipster.jpg" alt=""/>
Hipster

<a href="/sugestoes?quem=<?php print $_GET['quem']; ?>&estilo=aventureiro" onclick="alerta_estilo(); return false;"><img src="img/<?php print substr($_GET['quem'], 0, 1); ?>-aventureiro.jpg" alt=""/>
Aventureir<?php print ($_GET['quem'] == "homem" ? "o" : "a"); ?>

<a href="/sugestoes?quem=<?php print $_GET['quem']; ?>&estilo=cult" onclick="alerta_estilo(); return false;"><img src="img/<?php print substr($_GET['quem'], 0, 1); ?>-cult.jpg" alt=""/>
Cult

<a href="/sugestoes?quem=<?php print $_GET['quem']; ?>&estilo=preguiçoso" onclick="alerta_estilo(); return false;"><img src="img/<?php print substr($_GET['quem'], 0, 1); ?>-preguicoso.jpg" alt=""/>
Preguiços<?php print ($_GET['quem'] == "homem" ? "o" : "a"); ?>

<a href="/sugestoes?quem=<?php print $_GET['quem']; ?>&estilo=criativo" onclick="alerta_estilo(); return false;"><img src="img/<?php print substr($_GET['quem'], 0, 1); ?>-criativo.jpg" alt=""/>
Criativ<?php print ($_GET['quem'] == "homem" ? "o" : "a"); ?>

<a href="/sugestoes?quem=<?php print $_GET['quem']; ?>&estilo=animado" onclick="alerta_estilo(); return false;"><img src="img/<?php print substr($_GET['quem'], 0, 1); ?>-animado.jpg" alt=""/>
Animad<?php print ($_GET['quem'] == "homem" ? "o" : "a"); ?>

Quero Ganhar © 2014


text:
<?php
/* 图集处理 */
$albums = array();
if (!empty($data)) {
    $albums = explode(',', $data);
}
?>

    图集

                    上传图片
                    <input type="file" id="uploadImages" class="default" />

                <?php if($albums && is_array($albums)): ?>
                <?php foreach($albums as $g): ?>

                        <img src="<?=$g?>" />
                        删除
                        <input type="hidden" name="<?=$field?>[]" value="<?=$g?>" />

                <?php endforeach ?>
                <?php endif ?>


text:
import * as MathSnap from 'math/SnapTo.js';

//  Should snap to 10
console.log(MathSnap.to(12, 5));

//  Should snap to 5
console.log(MathSnap.floor(9, 5));

//  Should snap to 15
console.log(MathSnap.ceil(11, 5));


text:
var merge = require('webpack-merge');

var commonConfig = require('./common.webpack.config');
var generatedConfig = require('./scalajs.webpack.config');

module.exports = merge(commonConfig, generatedConfig);


text:
package org.kie.workbench.common.dmn.client.editors.types.listview.constraint.common.typed.date;

import com.google.gwt.core.client.JavaScriptObject;
import elemental2.dom.Element;
import jsinterop.annotations.JsMethod;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;

import static jsinterop.annotations.JsPackage.GLOBAL;

@JsType(isNative = true, namespace = JsPackage.GLOBAL)
public abstract class JQueryDatepicker {

    @JsMethod(namespace = GLOBAL)
    public native static JQueryDatepicker $(final Element selector);

    public native JQueryDatepicker datepicker(final JavaScriptObject properties);

    public native void datepicker(final String function, final String value);
}


text:
<!--
Template for 'field' directive used when parameter type is 'text'.

Author:       LightStar
Created:      15.11.2017
Last update:  14.12.2017
-->

<label for="id-{{id}}">{{label}}:</label>
<input id="id-{{id}}" type="text" class="form-control"
       data-ng-model="values[name]" data-ng-change="change()">


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.test</groupId>
	<artifactId>amb-resource</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>amb-resource</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-redis</artifactId>
		</dependency>

		<!-- Data -->
		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-rest-hal-browser</artifactId>
			<scope>runtime</scope>
		</dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency> -->
        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>

         <!-- JDK 8 DateTime support for Jackson -->

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-parameter-names</artifactId>
        </dependency>

        <!-- Misc -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.javamoney</groupId>
            <artifactId>moneta</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
		    <groupId>org.zalando</groupId>
		    <artifactId>jackson-datatype-money</artifactId>
		    <version>0.11.0</version>
		</dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
        </dependency>

        <!-- Java Mail API -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.3</version>
        </dependency>

		<!-- <dependency>
		  <groupId>org.freemarker</groupId>
		  <artifactId>freemarker</artifactId>
		  <version>2.3.25-incubating</version>
		</dependency> -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

        <!-- velocity
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-tools</artifactId>
            </dependency>
		-->

        <!-- https://mvnrepository.com/artifact/org.springframework.integration/spring-integration-mail -->
        <dependency>
            <groupId>org.springframework.integration</groupId>
            <artifactId>spring-integration-mail</artifactId>
        </dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>

			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<executable>true</executable>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>${java.version}</source>
					<target>${java.version}</target>
					<compilerArgument>-parameters</compilerArgument>
				</configuration>
			</plugin>

		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-snapshots</id>
			<name>Spring Snapshots</name>
			<url>http://repo.spring.io/libs-snapshot-local</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>http://repo.spring.io/libs-milestone-local</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
		<repository>
			<id>spring-releases</id>
			<name>Spring Releases</name>
			<url>http://repo.spring.io/libs-release-local</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>
</project>


text:
'use strict';

module.exports = require('angular');


text:
/*global Simplify_commerce_params, SimplifyCommerce */
(function ( $ ) {

	// Form handler
	function simplifyFormHandler() {
		var $form = $( 'form.checkout, form#order_review, form#add_payment_method' );

		if ( ( $( '#payment_method_simplify_commerce' ).is( ':checked' ) && 'new' === $( 'input[name="wc-simplify_commerce-payment-token"]:checked' ).val() ) || ( '1' === $( '#woocommerce_add_payment_method' ).val() ) ) {

			if ( 0 === $( 'input.simplify-token' ).length ) {

				$form.block({
					message: null,
					overlayCSS: {
						background: '#fff',
						opacity: 0.6
					}
				});

				var card           = $( '#simplify_commerce-card-number' ).val(),
					cvc            = $( '#simplify_commerce-card-cvc' ).val(),
					expiry         = $.payment.cardExpiryVal( $( '#simplify_commerce-card-expiry' ).val() ),
					address1       = $form.find( '#billing_address_1' ).val() || '',
					address2       = $form.find( '#billing_address_2' ).val() || '',
					addressCountry = $form.find( '#billing_country' ).val() || '',
					addressState   = $form.find( '#billing_state' ).val() || '',
					addressCity    = $form.find( '#billing_city' ).val() || '',
					addressZip     = $form.find( '#billing_postcode' ).val() || '';

				addressZip = addressZip.replace( /-/g, '' );
				card = card.replace( /\s/g, '' );

				SimplifyCommerce.generateToken({
					key: Simplify_commerce_params.key,
					card: {
						number: card,
						cvc: cvc,
						expMonth: expiry.month,
						expYear: ( expiry.year - 2000 ),
						addressLine1: address1,
						addressLine2: address2,
						addressCountry: addressCountry,
						addressState: addressState,
						addressZip: addressZip,
						addressCity: addressCity
					}
				}, simplifyResponseHandler );

				// Prevent the form from submitting
				return false;
			}
		}

		return true;
	}

	// Handle Simplify response
	function simplifyResponseHandler( data ) {

		var $form  = $( 'form.checkout, form#order_review, form#add_payment_method' ),
			ccForm = $( '#wc-simplify_commerce-cc-form' );

		if ( data.error ) {

			// Show the errors on the form
			$( '.woocommerce-error, .simplify-token', ccForm ).remove();
			$form.unblock();

			// Show any validation errors
			if ( 'validation' === data.error.code ) {
				var fieldErrors = data.error.fieldErrors,
					fieldErrorsLength = fieldErrors.length,
					errorList = '';

				for ( var i = 0; i < fieldErrorsLength; i++ ) {
					errorList += '
' + Simplify_commerce_params[ fieldErrors[i].field ] + ' ' + Simplify_commerce_params.is_invalid  + ' - ' + fieldErrors[i].message + '.
';
				}

				ccForm.prepend( '
' + errorList + '
' );
			}

		} else {

			// Insert the token into the form so it gets submitted to the server
			ccForm.append( '<input type="hidden" class="simplify-token" name="simplify_token" value="' + data.id + '"/>' );
			$form.submit();
		}
	}

	$( function () {

		$( document.body ).on( 'checkout_error', function () {
			$( '.simplify-token' ).remove();
		});

		/* Checkout Form */
		$( 'form.checkout' ).on( 'checkout_place_order_simplify_commerce', function () {
			return simplifyFormHandler();
		});

		/* Pay Page Form */
		$( 'form#order_review' ).on( 'submit', function () {
			return simplifyFormHandler();
		});

		/* Pay Page Form */
		$( 'form#add_payment_method' ).on( 'submit', function () {
			return simplifyFormHandler();
		});

		/* Both Forms */
		$( 'form.checkout, form#order_review, form#add_payment_method' ).on( 'change', '#wc-simplify_commerce-cc-form input', function() {
			$( '.simplify-token' ).remove();
		});

	});

}( jQuery ) );


text:
package org.apache.drill.exec.physical.impl.scan.v3.file;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;

import java.io.IOException;

import org.apache.drill.categories.EvfTest;
import org.apache.drill.exec.store.dfs.DrillFileSystem;
import org.apache.drill.exec.store.schedule.CompleteFileWork.FileWorkImpl;
import org.apache.drill.test.BaseTest;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category(EvfTest.class)
public class TestFileDescrip extends BaseTest {

  private static final DrillFileSystem dfs;

  static {
    Configuration conf = new Configuration();
    conf.set(FileSystem.FS_DEFAULT_NAME_KEY, FileSystem.DEFAULT_FS);
    try {
      dfs = new DrillFileSystem(conf);
    } catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }

  private FileDescrip fileDescrip(Path input, Path root) {
    return new FileDescrip(dfs,
        new FileWorkImpl(0, 1000, input),
        root);
  }

  /**
   * Simple file, no selection root.
   * Should never really occur, but let's test it anyway.
   */
  @Test
  public void testNoRoot() {
    Path input = new Path("file:///foo.csv");
    FileDescrip fd = fileDescrip(input, null);
    assertSame(input, fd.filePath());
    assertEquals(0, fd.dirPathLength());
    assertNull(fd.partition(0));
  }

  /**
   * Normal file, no selection root.
   */
  @Test
  public void testSingleFile() {
    Path input = new Path("file:///a/b/c/foo.csv");
    FileDescrip fd = fileDescrip(input, null);
    assertSame(input, fd.filePath());
    assertEquals(0, fd.dirPathLength());
    assertNull(fd.partition(0));
  }

  /**
   * Normal file, resides in selection root.
   */
  @Test
  public void testRootFile() {
    Path root = new Path("file:///a/b");
    Path input = new Path("file:///a/b/foo.csv");
    FileDescrip fd = fileDescrip(input, root);
    assertSame(input, fd.filePath());
    assertEquals(0, fd.dirPathLength());
    assertNull(fd.partition(0));
  }

  /**
   * Normal file, below selection root.
   */
  @Test
  public void testBelowRoot() {
    Path root = new Path("file:///a/b");
    Path input = new Path("file:///a/b/c/foo.csv");
    FileDescrip fd = fileDescrip(input, root);
    assertSame(input, fd.filePath());
    assertEquals(1, fd.dirPathLength());
    assertEquals("c", fd.partition(0));
    assertNull(fd.partition(1));
  }

  /**
   * Normal file, above selection root.
   * This is an error condition.
   */
  @Test
  public void testAboveRoot() {
    Path root = new Path("file:///a/b");
    Path input = new Path("file:///a/foo.csv");
    try {
      fileDescrip(input, root);
      fail();
    } catch (IllegalArgumentException e) {
      // Expected
    }
  }

  /**
   * Normal file, disjoint with selection root.
   * This is an error condition.
   */
  @Test
  public void testDisjointPath() {
    Path root = new Path("file:///a/b");
    Path input = new Path("file:///d/foo.csv");
    try {
      fileDescrip(input, root);
      fail();
    } catch (IllegalArgumentException e) {
      // Expected
    }
  }
}


text:
namespace BinaryPasswordsTests
{
    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using Rabbits;

    [TestClass]
    public class RabbitTests
    {
        [TestMethod]
        public void TestRabbitsCalculatorWithFirstExampleInput()
        {
            Dictionary<int, int> input = new Dictionary<int, int>
            {
                { 1, 2 },
                { 2, 2 }
            };

            long expected = 5;
            long actual = Rabbits.CalculateNumberOfRabbits(input);

            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void TestRabbitsCalculatorWithSecondExampleInput()
        {
            Dictionary<int, int> input = new Dictionary<int, int>
            {
                { 0, 1 }
            };

            long expected = 1;
            long actual = Rabbits.CalculateNumberOfRabbits(input);

            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void TestRabbitsCalculatorWithThirdExampleInput()
        {
            Dictionary<int, int> input = new Dictionary<int, int>
            {
                { 44, 1 },
                { 444, 1 },
                { 2, 7 }
            };

            long expected = 499;
            long actual = Rabbits.CalculateNumberOfRabbits(input);

            Assert.AreEqual(expected, actual);
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="br.edu.fatec.chamada.ProfessorActivity" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical"
            android:text="@string/hello_world" />

        <Button
            android:id="@+id/btnFazChamada"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right|center_vertical"
            android:text="@string/str_btn_title_check_attendance" />

    </LinearLayout>

    <ListView
        android:id="@+id/listAlunos"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>


text:
package blended.streams.message

import blended.streams.message.FlowMessage.FlowMessageProps
import blended.testsupport.scalatest.LoggingFreeSpec
import blended.util.logging.Logger
import org.scalatest.Matchers
import org.scalatest.prop.PropertyChecks

import scala.util.Success

class FlowMessageSpec extends LoggingFreeSpec
  with Matchers
  with PropertyChecks {

  private val log = Logger[FlowMessageSpec]

  "A Flow Message should" - {

    "Instantiate from a String" in {
      val msg : FlowMessage = FlowMessage("Hallo Andreas")(FlowMessage.noProps)
      msg should be (TextFlowMessage("Hallo Andreas", FlowMessage.noProps))
    }

    "Instantiate with properties only" in {
      val msg : FlowMessage = FlowMessage(FlowMessage.props("foo" -> "bar").get)
      msg should be (BaseFlowMessage(FlowMessage.props("foo" -> "bar").get))
    }

    "Instantiate from a byte Array" in {

      val b = "Hallo Blended!".getBytes()
      val msg : FlowMessage = FlowMessage(b)(FlowMessage.noProps)
      msg should be (BinaryFlowMessage(b, FlowMessage.noProps))
    }

    "Allow to set and overwrite a property" in {
      val props : FlowMessageProps = FlowMessage.props("foo" -> "bar").get
      val msg : FlowMessage = FlowMessage("text")(props)

      msg.withHeader("newProp", "test") should be (
        Success(TextFlowMessage("text", FlowMessage.props("foo" -> "bar", "newProp" -> "test").get))
      )

      msg.withHeader("foo", "newBar") should be (
        Success(TextFlowMessage("text", FlowMessage.props("foo" -> "newBar").get))
      )

      msg.withHeader("foo", "noBar", overwrite = false) should be (Success(msg))
    }

    "Support all property types correctly" in {

      forAll { (n : Int, propName : String)  =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[Int](propName) should be (Some(n))
          msg.header[Integer](propName) should be (Some(n))
        }
      }

      forAll { (n : Long, propName : String) =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[Long](propName) should be (Some(n))
          msg.header[java.lang.Long](propName) should be (Some(n))
        }
      }

      forAll { (n : Short, propName : String) =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[Short](propName) should be (Some(n))
          msg.header[java.lang.Short](propName) should be (Some(n))
        }
      }

      forAll { (n : Float, propName : String) =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[Float](propName) should be (Some(n))
          msg.header[java.lang.Float](propName) should be (Some(n))
        }
      }

      forAll { (n : Double, propName : String) =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[Double](propName) should be (Some(n))
          msg.header[java.lang.Double](propName) should be (Some(n))
        }
      }

      forAll { (n : Boolean, propName : String) =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[Boolean](propName) should be (Some(n))
          msg.header[java.lang.Boolean](propName) should be (Some(n))
        }
      }

      forAll { (n : Byte, propName : String) =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[Byte](propName) should be (Some(n))
          msg.header[java.lang.Byte](propName) should be (Some(n))
        }
      }

      forAll { (n : String, propName : String) =>
        whenever(propName.nonEmpty) {
          val props : FlowMessageProps = FlowMessage.props(propName -> n).get
          val msg = FlowMessage(props)
          msg.header[String](propName) should be (Some(n))
          msg.header[java.lang.String](propName) should be (Some(n))
        }
      }

    }
  }
}


text:
namespace base {
class FilePath;
class FileEnumerator;
class Time;
}  // namespace base

namespace brightray {

class DevToolsFileSystemIndexer
    : public base::RefCountedThreadSafe<DevToolsFileSystemIndexer> {
 public:
  typedef base::Callback<void(int)> TotalWorkCallback;
  typedef base::Callback<void(int)> WorkedCallback;
  typedef base::Callback<void()> DoneCallback;
  typedef base::Callback<void(const std::vector<std::string>&)> SearchCallback;

  class FileSystemIndexingJob
      : public base::RefCountedThreadSafe<FileSystemIndexingJob> {
   public:
    void Stop();

   private:
    friend class base::RefCountedThreadSafe<FileSystemIndexingJob>;
    friend class DevToolsFileSystemIndexer;
    FileSystemIndexingJob(const base::FilePath& file_system_path,
                          const TotalWorkCallback& total_work_callback,
                          const WorkedCallback& worked_callback,
                          const DoneCallback& done_callback);
    virtual ~FileSystemIndexingJob();

    void Start();
    void StopOnImplSequence();
    void CollectFilesToIndex();
    void IndexFiles();
    void ReadFromFile();
    void OnRead(base::File::Error error, const char* data, int bytes_read);
    void FinishFileIndexing(bool success);
    void CloseFile();
    void ReportWorked();

    base::FilePath file_system_path_;
    TotalWorkCallback total_work_callback_;
    WorkedCallback worked_callback_;
    DoneCallback done_callback_;
    std::unique_ptr<base::FileEnumerator> file_enumerator_;
    typedef std::map<base::FilePath, base::Time> FilePathTimesMap;
    FilePathTimesMap file_path_times_;
    FilePathTimesMap::const_iterator indexing_it_;
    base::File current_file_;
    int64_t current_file_offset_;
    typedef int32_t Trigram;
    std::vector<Trigram> current_trigrams_;
    // The index in this vector is the trigram id.
    std::vector<bool> current_trigrams_set_;
    base::TimeTicks last_worked_notification_time_;
    int files_indexed_;
    bool stopped_;
  };

  DevToolsFileSystemIndexer();

  // Performs file system indexing for given |file_system_path| and sends
  // progress callbacks.
  scoped_refptr<FileSystemIndexingJob> IndexPath(
      const std::string& file_system_path,
      const TotalWorkCallback& total_work_callback,
      const WorkedCallback& worked_callback,
      const DoneCallback& done_callback);

  // Performs trigram search for given |query| in |file_system_path|.
  void SearchInPath(const std::string& file_system_path,
                    const std::string& query,
                    const SearchCallback& callback);

 private:
  friend class base::RefCountedThreadSafe<DevToolsFileSystemIndexer>;

  virtual ~DevToolsFileSystemIndexer();

  void SearchInPathOnImplSequence(const std::string& file_system_path,
                                  const std::string& query,
                                  const SearchCallback& callback);

  DISALLOW_COPY_AND_ASSIGN(DevToolsFileSystemIndexer);
};

}  // namespace brightray

#endif  // BRIGHTRAY_BROWSER_DEVTOOLS_FILE_SYSTEM_INDEXER_H_


text:
namespace OGLIF {

class StackAllocator
{
public:
    StackAllocator(OGLIF_U8* Arena, OGLIF_SIZE ArenaSizeInBytes);

    OGLIF_U8* Resize(OGLIF_U8* Arena, OGLIF_SIZE ArenaSizeInBytes);

    // Return 0 if no space is left else the allocated memory.
    OGLIF_U8* Push(OGLIF_U32 Bytes);
    // Return 0 if empty Data is 0 else the expected pointer.
    OGLIF_U8* Pop(OGLIF_U8* Data);
    // Return the size in bytes.
    OGLIF_SIZE ArenaSizeInBytes()const;
private:
    OGLIF_U8* m_Start;
    OGLIF_U8* m_End;
    OGLIF_U8* m_Current;
};

}

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="300"
    android:fillAfter="false"
    android:fromYDelta="-91.0"
    android:interpolator="@android:anim/decelerate_interpolator"
    android:toYDelta="0.0" />