text:
#ifndef VC_COMMON_MEMORY_H_
#define VC_COMMON_MEMORY_H_

#include "memorybase.h"
#include <assert.h>
#include <algorithm>
#include <cstring>
#include <cstddef>
#include <initializer_list>
#include "memoryfwd.h"
#include "malloc.h"
#include "macros.h"

namespace Vc_VERSIONED_NAMESPACE
{
/**
 * Allocates memory on the Heap with alignment and padding suitable for vectorized access.
 *
 * Memory that was allocated with this function must be released with Vc::free! Other methods might
 * work but are not portable.
 *
 * \param n Specifies the number of objects the allocated memory must be able to store.
 * \tparam T The type of the allocated memory. Note, that the constructor is not called.
 * \tparam A Determines the alignment of the memory. See \ref Vc::MallocAlignment.
 *
 * \return Pointer to memory of the requested type, or 0 on error. The allocated memory is padded at
 * the end to be a multiple of the requested alignment \p A. Thus if you request memory for 21
 * int objects, aligned via Vc::AlignOnCacheline, you can safely read a full cacheline until the
 * end of the array, without generating an out-of-bounds access. For a cacheline size of 64 Bytes
 * and an int size of 4 Bytes you would thus get an array of 128 Bytes to work with.
 *
 * \warning
 * \li The standard malloc function specifies the number of Bytes to allocate whereas this
 *     function specifies the number of values, thus differing in a factor of sizeof(T).
 * \li This function is mainly meant for use with builtin types. If you use a custom
 *     type with a sizeof that is not a multiple of 2 the results might not be what you expect.
 * \li The constructor of T is not called. You can make up for this:
 * \code
 * SomeType *array = new(Vc::malloc<SomeType, Vc::AlignOnCacheline>(N)) SomeType[N];
 * \endcode
 *
 * \see Vc::free
 *
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 */
template<typename T, Vc::MallocAlignment A>
Vc_ALWAYS_INLINE T *malloc(size_t n)
{
    return static_cast<T *>(Common::malloc<A>(n * sizeof(T)));
}

/**
 * Frees memory that was allocated with Vc::malloc.
 *
 * \param p The pointer to the memory to be freed.
 *
 * \tparam T The type of the allocated memory.
 *
 * \warning The destructor of T is not called. If needed, you can call the destructor before calling
 * free:
 * \code
 * for (int i = 0; i < N; ++i) {
 *   p[i].~T();
 * }
 * Vc::free(p);
 * \endcode
 *
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 *
 * \see Vc::malloc
 */
template<typename T>
Vc_ALWAYS_INLINE void free(T *p)
{
    Common::free(p);
}

namespace Common
{
template<typename V, size_t Size> struct _MemorySizeCalculation
{
    enum AlignmentCalculations {
        Alignment = V::Size,
        AlignmentMask = Alignment - 1,
        MaskedSize = Size & AlignmentMask,
        Padding = Alignment - MaskedSize,
        PaddedSize = MaskedSize == 0 ? Size : Size + Padding
    };
};

/**
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 *
 * A helper class for fixed-size two-dimensional arrays.
 *
 * \param V The vector type you want to operate on. (e.g. float_v or uint_v)
 * \param Size1 Number of rows
 * \param Size2 Number of columns
 */
template <typename V, size_t Size1, size_t Size2, bool InitPadding>
#ifdef Vc_RECURSIVE_MEMORY
class Memory : public MemoryBase<V, Memory<V, Size1, Size2, InitPadding>, 2,
                                 Memory<V, Size2, 0, InitPadding>>
#else
class Memory : public AlignedBase<V::MemoryAlignment>,
               public MemoryBase<V, Memory<V, Size1, Size2, InitPadding>, 2,
                                 Memory<V, Size2, 0, false>>
#endif
{
public:
    typedef typename V::EntryType EntryType;

private:
#ifdef Vc_RECURSIVE_MEMORY
    using RowMemory = Memory<V, Size2, 0, InitPadding>;
#else
    using RowMemory = Memory<V, Size2, 0, false>;
#endif
    typedef MemoryBase<V, Memory<V, Size1, Size2, InitPadding>, 2, RowMemory> Base;
    friend class MemoryBase<V, Memory<V, Size1, Size2, InitPadding>, 2, RowMemory>;
    friend class MemoryDimensionBase<V, Memory<V, Size1, Size2, InitPadding>, 2,
                                     RowMemory>;
    enum : size_t {
        Alignment = V::MemoryAlignment,
        PaddedSize2 = _MemorySizeCalculation<V, Size2>::PaddedSize
    };
    alignas(static_cast<size_t>(Alignment))  // GCC complains about 'is not an
                                             // integer constant' unless the
                                             // static_cast is present
#ifdef Vc_RECURSIVE_MEMORY
        RowMemory m_mem[Size1];
#else
        EntryType m_mem[Size1][PaddedSize2];
#endif

        public:
            using Base::vector;
            enum Constants {
                RowCount = Size1,
                VectorsCount = PaddedSize2 / V::Size
            };

#ifdef Vc_RECURSIVE_MEMORY
            Memory() = default;
#else
            Memory()
            {
                if (InitPadding) {
                    if (Size1 > 32)
                    for (size_t i = 0; i < Size1; ++i) {
                        V::Zero().store(&m_mem[i][PaddedSize2 - V::Size], Vc::Streaming);
                    }
                }
            }
#endif

            /**
             * \return the number of rows in the array.
             *
             * \note This function can be eliminated by an optimizing compiler.
             */
            static constexpr size_t rowsCount() { return RowCount; }
            /**
             * \return the number of scalar entries in the whole array.
             *
             * \warning Do not use this function for scalar iteration over the array since there will be
             * padding between rows if \c Size2 is not divisible by \c V::Size.
             *
             * \note This function can be optimized into a compile-time constant.
             */
            static constexpr size_t entriesCount() { return Size1 * Size2; }
            /**
             * \return the number of vectors in the whole array.
             *
             * \note This function can be optimized into a compile-time constant.
             */
            static constexpr size_t vectorsCount() { return VectorsCount * Size1; }

            /**
             * Copies the data from a different object.
             *
             * \param rhs The object to copy the data from.
             *
             * \return reference to the modified Memory object.
             *
             * \note Both objects must have the exact same vectorsCount().
             */
            template<typename Parent, typename RM>
            Vc_ALWAYS_INLINE Memory &operator=(const MemoryBase<V, Parent, 2, RM> &rhs) {
                assert(vectorsCount() == rhs.vectorsCount());
                Detail::copyVectors(*this, rhs);
                return *this;
            }

            Vc_ALWAYS_INLINE Memory &operator=(const Memory &rhs) {
                Detail::copyVectors(*this, rhs);
                return *this;
            }

            /**
             * Initialize all data with the given vector.
             *
             * \param v This vector will be used to initialize the memory.
             *
             * \return reference to the modified Memory object.
             */
            inline Memory &operator=(const V &v) {
                for (size_t i = 0; i < vectorsCount(); ++i) {
                    vector(i) = v;
                }
                return *this;
            }
};

    /**
     * A helper class to simplify usage of correctly aligned and padded memory, allowing both vector and
     * scalar access.
     *
     * Example:
     * \code
        Vc::Memory<int_v, 11> array;

        // scalar access:
        for (size_t i = 0; i < array.entriesCount(); ++i) {
            int x = array[i]; // read
            array[i] = x;     // write
        }
        // more explicit alternative:
        for (size_t i = 0; i < array.entriesCount(); ++i) {
            int x = array.scalar(i); // read
            array.scalar(i) = x;     // write
        }

        // vector access:
        for (size_t i = 0; i < array.vectorsCount(); ++i) {
            int_v x = array.vector(i); // read
            array.vector(i) = x;       // write
        }
     * \endcode
     * This code allocates a small array and implements three equivalent loops (that do nothing useful).
     * The loops show how scalar and vector read/write access is best implemented.
     *
     * Since the size of 11 is not a multiple of int_v::Size (unless you use the
     * scalar Vc implementation) the last write access of the vector loop would normally be out of
     * bounds. But the Memory class automatically pads the memory such that the whole array can be
     * accessed with correctly aligned memory addresses.
     *
     * \param V The vector type you want to operate on. (e.g. float_v or uint_v)
     * \param Size The number of entries of the scalar base type the memory should hold. This
     * is thus the same number as you would use for a normal C array (e.g. float mem[11] becomes
     * Memory<float_v, 11> mem).
     *
     * \see Memory<V, 0u>
     *
     * \ingroup Utilities
     * \headerfile memory.h <Vc/Memory>
     */
template <typename V, size_t Size, bool InitPadding>
class Memory<V, Size, 0u, InitPadding> :
#ifndef Vc_RECURSIVE_MEMORY
    public AlignedBase<V::MemoryAlignment>,
#endif
    public MemoryBase<V, Memory<V, Size, 0u, InitPadding>, 1, void>
    {
        public:
            typedef typename V::EntryType EntryType;
        private:
            typedef MemoryBase<V, Memory<V, Size, 0u, InitPadding>, 1, void> Base;
            friend class MemoryBase<V, Memory<V, Size, 0u, InitPadding>, 1, void>;
            friend class MemoryDimensionBase<V, Memory<V, Size, 0u, InitPadding>, 1, void>;
            enum : size_t {
                Alignment = V::MemoryAlignment,     // in Bytes
                MaskedSize = Size & (V::Size - 1),  // the fraction of Size that exceeds
                                                    // an integral multiple of V::Size
                Padding = V::Size - MaskedSize,
                PaddedSize = MaskedSize == 0 ? Size : Size + Padding
            };
            alignas(static_cast<size_t>(Alignment))  // GCC complains about 'is not an
                                                     // integer constant' unless the
                                                     // static_cast is present
                EntryType m_mem[PaddedSize];

        public:
            using Base::vector;
            enum Constants {
                EntriesCount = Size,
                VectorsCount = PaddedSize / V::Size
            };

            Memory()
            {
                if (InitPadding) {
                    Base::lastVector() = V::Zero();
                }
            }

            Memory(std::initializer_list<EntryType> init)
            {
                Vc_ASSERT(init.size() <= Size);
                Base::lastVector() = V::Zero();
                std::copy(init.begin(), init.end(), &m_mem[0]);
            }

            /**
             * Wrap existing data with the Memory convenience class.
             *
             * This function returns a \em reference to a Memory<V, Size, 0> object that you must
             * capture to avoid a copy of the whole data:
             * \code
             * Memory<float_v, 16> &m = Memory<float_v, 16>::fromRawData(someAlignedPointerToFloat)
             * \endcode
             *
             * \param ptr An aligned pointer to memory of type \p V::EntryType (e.g. \c float for
             *            Vc::float_v).
             * \return A Memory object placed at the given location in memory.
             *
             * \warning The pointer \p ptr passed to this function must be aligned according to the
             * alignment restrictions of \p V.
             * \warning The size of the accessible memory must match \p Size. This includes the
             * required padding at the end to allow the last entries to be accessed via vectors. If
             * you know what you are doing you might violate this constraint.
             * \warning It is your responsibility to ensure that the memory is released correctly
             * (not too early/not leaked). This function simply adds convenience functions to \em
             * access the memory.
             */
            static Vc_ALWAYS_INLINE Vc_CONST Memory<V, Size, 0u, false> &fromRawData(EntryType *ptr)
            {
                // DANGER! This placement new has to use the right address. If the compiler decides
                // RowMemory requires padding before the actual data then the address has to be adjusted
                // accordingly
                char *addr = reinterpret_cast<char *>(ptr);
                typedef Memory<V, Size, 0u, false> MM;
                addr -= Vc_OFFSETOF(MM, m_mem);
                return *new(addr) MM;
            }

            /**
             * \return the number of scalar entries in the whole array.
             *
             * \note This function can be optimized into a compile-time constant.
             */
            static constexpr size_t entriesCount() { return EntriesCount; }

            /**
             * \return the number of vectors in the whole array.
             *
             * \note This function can be optimized into a compile-time constant.
             */
            static constexpr size_t vectorsCount() { return VectorsCount; }

            inline Memory(const Memory &rhs)
            {
                Detail::copyVectors(*this, rhs);
            }

            template <size_t S> inline Memory(const Memory<V, S> &rhs)
            {
                assert(vectorsCount() == rhs.vectorsCount());
                Detail::copyVectors(*this, rhs);
            }

            inline Memory &operator=(const Memory &rhs)
            {
                Detail::copyVectors(*this, rhs);
                return *this;
            }

            template <size_t S> inline Memory &operator=(const Memory<V, S> &rhs)
            {
                assert(vectorsCount() == rhs.vectorsCount());
                Detail::copyVectors(*this, rhs);
                return *this;
            }

            Vc_ALWAYS_INLINE Memory &operator=(const EntryType *rhs) {
                std::memcpy(m_mem, rhs, entriesCount() * sizeof(EntryType));
                return *this;
            }
            inline Memory &operator=(const V &v) {
                for (size_t i = 0; i < vectorsCount(); ++i) {
                    vector(i) = v;
                }
                return *this;
            }
    };

    /**
     * A helper class that is very similar to Memory<V, Size> but with dynamically allocated memory and
     * thus dynamic size.
     *
     * Example:
     * \code
        size_t size = 11;
        Vc::Memory<int_v> array(size);

        // scalar access:
        for (size_t i = 0; i < array.entriesCount(); ++i) {
            array[i] = i;
        }

        // vector access:
        for (size_t i = 0; i < array.vectorsCount(); ++i) {
            array.vector(i) = int_v::IndexesFromZero() + i * int_v::Size;
        }
     * \endcode
     * This code allocates a small array with 11 scalar entries
     * and implements two equivalent loops that initialize the memory.
     * The scalar loop writes each individual int. The vectorized loop writes int_v::Size values to
     * memory per iteration. Since the size of 11 is not a multiple of int_v::Size (unless you use the
     * scalar Vc implementation) the last write access of the vector loop would normally be out of
     * bounds. But the Memory class automatically pads the memory such that the whole array can be
     * accessed with correctly aligned memory addresses.
     * (Note: the scalar loop can be auto-vectorized, except for the last three assignments.)
     *
     * \note The internal data pointer is not declared with the \c __restrict__ keyword. Therefore
     * modifying memory of V::EntryType will require the compiler to assume aliasing. If you want to use
     * the \c __restrict__ keyword you need to use a standard pointer to memory and do the vector
     * address calculation and loads and stores manually.
     *
     * \param V The vector type you want to operate on. (e.g. float_v or uint_v)
     *
     * \see Memory<V, Size>
     *
     * \ingroup Utilities
     * \headerfile memory.h <Vc/Memory>
     */
    template<typename V> class Memory<V, 0u, 0u, true> : public MemoryBase<V, Memory<V, 0u, 0u, true>, 1, void>
    {
        public:
            typedef typename V::EntryType EntryType;
        private:
            typedef MemoryBase<V, Memory<V>, 1, void> Base;
            friend class MemoryBase<V, Memory<V>, 1, void>;
            friend class MemoryDimensionBase<V, Memory<V>, 1, void>;
        enum InternalConstants {
            Alignment = V::Size,
            AlignmentMask = Alignment - 1
        };
        size_t m_entriesCount;
        size_t m_vectorsCount;
        EntryType *m_mem;
        size_t calcPaddedEntriesCount(size_t x)
        {
            size_t masked = x & AlignmentMask;
            return (masked == 0 ? x : x + (Alignment - masked));
        }
    public:
        using Base::vector;

        /**
         * Allocate enough memory to access \p size values of type \p V::EntryType.
         *
         * The allocated memory is aligned and padded correctly for fully vectorized access.
         *
         * \param size Determines how many scalar values will fit into the allocated memory.
         */
        Vc_ALWAYS_INLINE Memory(size_t size)
            : m_entriesCount(size),
            m_vectorsCount(calcPaddedEntriesCount(m_entriesCount)),
            m_mem(Vc::malloc<EntryType, Vc::AlignOnVector>(m_vectorsCount))
        {
            m_vectorsCount /= V::Size;
            Base::lastVector() = V::Zero();
        }

        /**
         * Copy the memory into a new memory area.
         *
         * The allocated memory is aligned and padded correctly for fully vectorized access.
         *
         * \param rhs The Memory object to copy from.
         */
        template<typename Parent, typename RM>
        Vc_ALWAYS_INLINE Memory(const MemoryBase<V, Parent, 1, RM> &rhs)
            : m_entriesCount(rhs.entriesCount()),
            m_vectorsCount(rhs.vectorsCount()),
            m_mem(Vc::malloc<EntryType, Vc::AlignOnVector>(m_vectorsCount * V::Size))
        {
            Detail::copyVectors(*this, rhs);
        }

        /**
         * Overload of the above function.
         *
         * (Because C++ would otherwise not use the templated cctor and use a default-constructed cctor instead.)
         *
         * \param rhs The Memory object to copy from.
         */
        Vc_ALWAYS_INLINE Memory(const Memory &rhs)
            : m_entriesCount(rhs.entriesCount()),
            m_vectorsCount(rhs.vectorsCount()),
            m_mem(Vc::malloc<EntryType, Vc::AlignOnVector>(m_vectorsCount * V::Size))
        {
            Detail::copyVectors(*this, rhs);
        }

        /**
         * Frees the memory which was allocated in the constructor.
         */
        Vc_ALWAYS_INLINE ~Memory()
        {
            Vc::free(m_mem);
        }

        /**
         * Swap the contents and size information of two Memory objects.
         *
         * \param rhs The other Memory object to swap.
         */
        inline void swap(Memory &rhs) {
            std::swap(m_mem, rhs.m_mem);
            std::swap(m_entriesCount, rhs.m_entriesCount);
            std::swap(m_vectorsCount, rhs.m_vectorsCount);
        }

        /**
         * \return the number of scalar entries in the whole array.
         */
        Vc_ALWAYS_INLINE Vc_PURE size_t entriesCount() const { return m_entriesCount; }

        /**
         * \return the number of vectors in the whole array.
         */
        Vc_ALWAYS_INLINE Vc_PURE size_t vectorsCount() const { return m_vectorsCount; }

        /**
         * Overwrite all entries with the values stored in \p rhs.
         *
         * \param rhs The object to copy the data from.
         *
         * \return reference to the modified Memory object.
         *
         * \note this function requires the vectorsCount() of both Memory objects to be equal.
         */
        template<typename Parent, typename RM>
        Vc_ALWAYS_INLINE Memory &operator=(const MemoryBase<V, Parent, 1, RM> &rhs) {
            assert(vectorsCount() == rhs.vectorsCount());
            Detail::copyVectors(*this, rhs);
            return *this;
        }

        Vc_ALWAYS_INLINE Memory &operator=(const Memory &rhs) {
            assert(vectorsCount() == rhs.vectorsCount());
            Detail::copyVectors(*this, rhs);
            return *this;
        }

        /**
         * Overwrite all entries with the values stored in the memory at \p rhs.
         *
         * \param rhs The array to copy the data from.
         *
         * \return reference to the modified Memory object.
         *
         * \note this function requires that there are entriesCount() many values accessible from \p rhs.
         */
        Vc_ALWAYS_INLINE Memory &operator=(const EntryType *rhs) {
            std::memcpy(m_mem, rhs, entriesCount() * sizeof(EntryType));
            return *this;
        }
};

/**
 * Prefetch the cacheline containing \p addr for a single read access.
 *
 * This prefetch completely bypasses the cache, not evicting any other data.
 *
 * \param addr The cacheline containing \p addr will be prefetched.
 *
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 */
Vc_ALWAYS_INLINE void prefetchForOneRead(const void *addr)
{
    Vc::Detail::prefetchForOneRead(addr, VectorAbi::Best<float>());
}

/**
 * Prefetch the cacheline containing \p addr for modification.
 *
 * This prefetch evicts data from the cache. So use it only for data you really will use. When the
 * target system supports it the cacheline will be marked as modified while prefetching, saving work
 * later on.
 *
 * \param addr The cacheline containing \p addr will be prefetched.
 *
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 */
Vc_ALWAYS_INLINE void prefetchForModify(const void *addr)
{
    Vc::Detail::prefetchForModify(addr, VectorAbi::Best<float>());
}

/**
 * Prefetch the cacheline containing \p addr to L1 cache.
 *
 * This prefetch evicts data from the cache. So use it only for data you really will use.
 *
 * \param addr The cacheline containing \p addr will be prefetched.
 *
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 */
Vc_ALWAYS_INLINE void prefetchClose(const void *addr)
{
    Vc::Detail::prefetchClose(addr, VectorAbi::Best<float>());
}

/**
 * Prefetch the cacheline containing \p addr to L2 cache.
 *
 * This prefetch evicts data from the cache. So use it only for data you really will use.
 *
 * \param addr The cacheline containing \p addr will be prefetched.
 *
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 */
Vc_ALWAYS_INLINE void prefetchMid(const void *addr)
{
    Vc::Detail::prefetchMid(addr, VectorAbi::Best<float>());
}

/**
 * Prefetch the cacheline containing \p addr to L3 cache.
 *
 * This prefetch evicts data from the cache. So use it only for data you really will use.
 *
 * \param addr The cacheline containing \p addr will be prefetched.
 *
 * \ingroup Utilities
 * \headerfile memory.h <Vc/Memory>
 */
Vc_ALWAYS_INLINE void prefetchFar(const void *addr)
{
    Vc::Detail::prefetchFar(addr, VectorAbi::Best<float>());
}
}  // namespace Common

using Common::Memory;
using Common::prefetchForOneRead;
using Common::prefetchForModify;
using Common::prefetchClose;
using Common::prefetchMid;
using Common::prefetchFar;
}  // namespace Vc

namespace std
{
    template<typename V> Vc_ALWAYS_INLINE void swap(Vc::Memory<V> &a, Vc::Memory<V> &b) { a.swap(b); }
} // namespace std

#endif // VC_COMMON_MEMORY_H_


text:
<resources>
    <string name="app_name">FlynxFilter</string>
    <string name="title_activity_settings">FlynxFilter Einstellungen</string>
    <string name="settings_saved">Einstellungen gespeichert!</string>
    <string name="browser_cannot_be_opened">Web-Browser nicht gefunden!</string>
    <string name="web_browser">Web-Browser</string>
    <string name="browser_explanation">Bitte wählen Sie den Web-Browser mit dem alle Links vom Host http://www.google.com geöffnet werden sollen.</string>
</resources>

redpajama_set_name: RedPajamaGithub


text:
description: "How to upgrade your installation of Telepresence and install previous versions."
---

# Upgrading Telepresence

The Telepresence CLI will periodically check for new versions and notify you when an upgrade is available.  [Running the same commands used for installation](../../quick-start/) will replace your current binary with the latest version.

###  macOS

```
sudo curl -fL https://app.getambassador.io/download/tel2/darwin/amd64/latest/telepresence \
-o /usr/local/bin/telepresence && \
sudo chmod a+x /usr/local/bin/telepresence && \
telepresence version
```

###  Linux

```
sudo curl -fL https://app.getambassador.io/download/tel2/linux/amd64/latest/telepresence \
-o /usr/local/bin/telepresence && \
sudo chmod a+x /usr/local/bin/telepresence && \
telepresence version
```

### Upgrading Telepresence of version 2.0.1 or older

The traffic-manager must be uninstalled manually. This can be done using `telepresence uninstall --everything` _before_ the upgrade or by using `kubectl delete svc,deploy traffic-manager`.

## Installing Older Versions of Telepresence

Use the following URLs to install an older version, replacing `x.x.x` with the version you want.

### macOS
`https://app.getambassador.io/download/tel2/linux/amd64/x.x.x/telepresence`

### Linux
`https://app.getambassador.io/download/tel2/darwin/amd64/x.x.x/telepresence`

Use the following URLs to find the current latest version number.

### macOS
`https://app.getambassador.io/download/tel2/linux/amd64/stable.txt`

### Linux
`https://app.getambassador.io/download/tel2/darwin/amd64/stable.txt`


text:
properties {
  $base_dir  = resolve-path .
  $lib_dir = "$base_dir\SharedLibs"
  $build_dir = "$base_dir\build"

  $sln_file = "$base_dir\Rhino.Mocks.sln"
  $version = "3.6.0.0"
  $humanReadableversion = "3.6"
  $tools_dir = "$base_dir\Tools"
  $release_dir = "$base_dir\Release"
  $uploadCategory = "Rhino-Mocks"
  $uploader = "..\Uploader\S3Uploader.exe"
}

include .\psake_ext.ps1

task default -depends Release

task Clean {
  remove-item -force -recurse $build_dir -ErrorAction SilentlyContinue
  remove-item -force -recurse $release_dir -ErrorAction SilentlyContinue
}

task Init -depends Clean {

	Generate-Assembly-Info `
		-file "$base_dir\Rhino.Mocks\Properties\AssemblyInfo.cs" `
		-title "Rhino Mocks $version" `
		-description "Mocking Framework for .NET" `
		-company "Hibernating Rhinos" `
		-product "Rhino Mocks $version" `
		-version $version `
		-copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009" `
		-internalsVisibleTo "Rhino.Mocks.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001009d1cf4b75b7218b141ac64c15450141b1e5f41f6a302ac717ab9761fa6ae2c3ee0c354c22d0a60ac59de41fa285d572e7cf33c320aa7ff877e2b7da1792fcc6aa4eb0b4d8294a2f74cb14d03fb9b091f751d6dc49e626d74601692c99eab7718ed76a40c36d39af842be378b677e6e4eae973f643d7065241ad86ecc156d81ab"

	Generate-Assembly-Info `
		-file "$base_dir\Rhino.Mocks.Tests\Properties\AssemblyInfo.cs" `
		-title "Rhino Mocks Tests $version" `
		-description "Mocking Framework for .NET" `
		-company "Hibernating Rhinos" `
		-product "Rhino Mocks Tests $version" `
		-version $version `
		-clsCompliant "false" `
		-copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009"

	Generate-Assembly-Info `
		-file "$base_dir\Rhino.Mocks.Tests.Model\Properties\AssemblyInfo.cs" `
		-title "Rhino Mocks Tests Model $version" `
		-description "Mocking Framework for .NET" `
		-company "Hibernating Rhinos" `
		-product "Rhino Mocks Tests Model $version" `
		-version $version `
		-clsCompliant "false" `
		-copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009"

	Generate-Assembly-Info `
		-file "$base_dir\Rhino.Mocks.GettingStarted\Properties\AssemblyInfo.cs" `
		-title "Rhino Mocks Tests $version" `
		-description "Mocking Framework for .NET" `
		-company "Hibernating Rhinos" `
		-product "Rhino Mocks Tests $version" `
		-version $version `
		-clsCompliant "false" `
		-copyright "Hibernating Rhinos & Ayende Rahien 2004 - 2009"

	new-item $release_dir -itemType directory
	new-item $build_dir -itemType directory
	cp $tools_dir\xUnit\*.* $build_dir
}

task Compile -depends Init {
  & msbuild "$sln_file" "/p:OutDir=$build_dir\\" /p:Configuration=Release
  if ($lastExitCode -ne 0) {
        throw "Error: Failed to execute msbuild"
  }
}

task Test -depends Compile {
  $old = pwd
  cd $build_dir
  &.\Xunit.console.exe "$build_dir\Rhino.Mocks.Tests.dll"
  if ($lastExitCode -ne 0) {
        throw "Error: Failed to execute tests"
  }
  cd $old
}

task Merge {
	$old = pwd
	cd $build_dir

	Remove-Item Rhino.Mocks.Partial.dll -ErrorAction SilentlyContinue
	Rename-Item $build_dir\Rhino.Mocks.dll Rhino.Mocks.Partial.dll

	& $tools_dir\ILMerge.exe Rhino.Mocks.Partial.dll `
		Castle.DynamicProxy2.dll `
		Castle.Core.dll `
		/out:Rhino.Mocks.dll `
		/t:library `
		"/keyfile:$base_dir\ayende-open-source.snk" `
		"/internalize:$base_dir\ilmerge.exclude"
	if ($lastExitCode -ne 0) {
        throw "Error: Failed to merge assemblies!"
    }
	cd $old
}

task Release -depends Test, Merge {
	& $tools_dir\zip.exe -9 -A -j `
		$release_dir\Rhino.Mocks-$humanReadableversion-Build-$env:ccnetnumericlabel.zip `
		$build_dir\Rhino.Mocks.dll `
		$build_dir\Rhino.Mocks.xml `
		license.txt `
		acknowledgements.txt
	if ($lastExitCode -ne 0) {
        throw "Error: Failed to execute ZIP command"
    }
}

task Upload -depends Release {
	Write-Host "Starting upload"
	if (Test-Path $uploader) {
		$log = $env:push_msg
    if($log -eq $null -or $log.Length -eq 0) {
      $log = git log -n 1 --oneline
    }
		&$uploader "$uploadCategory" "$release_dir\Rhino.Mocks-$humanReadableversion-Build-$env:ccnetnumericlabel.zip" "$log"

		if ($lastExitCode -ne 0) {
      write-host "Failed to upload to S3: $lastExitCode"
			throw "Error: Failed to publish build"
		}
	}
	else {
		Write-Host "could not find upload script $uploadScript, skipping upload"
	}
}


text:
import json
from dlab.fab import *
from dlab.meta_lib import *
import sys, time, os
from dlab.actions_lib import *

if __name__ == "__main__":
    local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_name'],
                                               os.environ['request_id'])
    local_log_filepath = "/logs/edge/" + local_log_filename
    logging.basicConfig(format='%(levelname)-8s [%(asctime)s]  %(message)s',
                        level=logging.DEBUG,
                        filename=local_log_filepath)
    try:
        print('Generating infrastructure names and tags')
        edge_conf = dict()

        edge_conf['service_base_name'] = os.environ['conf_service_base_name']
        edge_conf['resource_group_name'] = os.environ['azure_resource_group_name']
        edge_conf['key_name'] = os.environ['conf_key_name']
        edge_conf['vpc_name'] = os.environ['azure_vpc_name']
        edge_conf['region'] = os.environ['azure_region']
        edge_conf['subnet_name'] = os.environ['azure_subnet_name']
        edge_conf['user_name'] = os.environ['edge_user_name'].replace('_', '-')
        edge_conf['user_keyname'] = os.environ['edge_user_name']
        edge_conf['private_subnet_name'] = edge_conf['service_base_name'] + '-' + edge_conf['user_name'] + '-subnet'
        edge_conf['instance_name'] = edge_conf['service_base_name'] + "-" + edge_conf['user_name'] + '-edge'
        edge_conf['network_interface_name'] = edge_conf['service_base_name'] + "-" + edge_conf['user_name'] + '-edge-nif'
        edge_conf['static_public_ip_name'] = edge_conf['service_base_name'] + "-" + edge_conf['user_name'] + '-edge-ip'
        edge_conf['primary_disk_name'] = edge_conf['instance_name'] + '-disk0'
        edge_conf['instance_dns_name'] = 'host-' + edge_conf['instance_name'] + '.' + edge_conf['region'] + '.cloudapp.azure.com'
        edge_conf['user_storage_account_name'] = edge_conf['service_base_name'] + '-' + edge_conf[
            'user_name'] + '-storage'
        edge_conf['user_container_name'] = (edge_conf['service_base_name'] + '-' + edge_conf['user_name'] + '-container').lower()
        edge_conf['shared_storage_account_name'] = edge_conf['service_base_name'] + '-shared-storage'
        edge_conf['shared_container_name'] = (edge_conf['service_base_name'] + '-shared-container').lower()
        edge_conf['datalake_store_name'] = edge_conf['service_base_name'] + '-ssn-datalake'
        edge_conf['datalake_shared_directory_name'] = edge_conf['service_base_name'] + '-shared-folder'
        edge_conf['datalake_user_directory_name'] = '{0}-{1}-folder'.format(edge_conf['service_base_name'], edge_conf['user_name'])
        edge_conf['edge_security_group_name'] = edge_conf['instance_name'] + '-sg'
        edge_conf['notebook_security_group_name'] = edge_conf['service_base_name'] + "-" + edge_conf['user_name'] + \
                                                    '-nb-sg'
        edge_conf['master_security_group_name'] = edge_conf['service_base_name'] + '-' \
                                                    + edge_conf['user_name'] + '-dataengine-master-sg'
        edge_conf['slave_security_group_name'] = edge_conf['service_base_name'] + '-' \
                                                   + edge_conf['user_name'] + '-dataengine-slave-sg'
        edge_conf['dlab_ssh_user'] = os.environ['conf_os_user']
        keyfile_name = "{}{}.pem".format(os.environ['conf_key_dir'], edge_conf['key_name'])
        edge_conf['private_subnet_cidr'] = AzureMeta().get_subnet(edge_conf['resource_group_name'], edge_conf['vpc_name'],
                                                                  edge_conf['private_subnet_name']).address_prefix
        edge_conf['edge_public_ip'] = AzureMeta().get_instance_public_ip_address(edge_conf['resource_group_name'],
                                                                       edge_conf['instance_name'])
        edge_conf['edge_private_ip'] = AzureMeta().get_private_ip_address(edge_conf['resource_group_name'],
                                                                                edge_conf['instance_name'])
        instance_hostname = AzureMeta().get_private_ip_address(edge_conf['resource_group_name'],
                                                                        edge_conf['instance_name'])
    except Exception as err:
        append_result("Failed to generate infrastructure names", str(err))
        AzureActions().remove_instance(edge_conf['resource_group_name'], edge_conf['instance_name'])
        AzureActions().remove_subnet(edge_conf['resource_group_name'], edge_conf['vpc_name'],
                                     edge_conf['private_subnet_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['edge_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['notebook_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                             edge_conf['master_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                                 edge_conf['slave_security_group_name'])
        for storage_account in AzureMeta().list_storage_accounts(edge_conf['resource_group_name']):
            if edge_conf['user_storage_account_name'] == storage_account.tags["Name"]:
                AzureActions().remove_storage_account(edge_conf['resource_group_name'], storage_account.name)
        if os.environ['azure_datalake_enable'] == 'true':
            for datalake in AzureMeta().list_datalakes(edge_conf['resource_group_name']):
                if edge_conf['datalake_store_name'] == datalake.tags["Name"]:
                    AzureActions().remove_datalake_directory(datalake.name, edge_conf['datalake_user_directory_name'])
        sys.exit(1)

    try:
        if os.environ['conf_os_family'] == 'debian':
            initial_user = 'ubuntu'
            sudo_group = 'sudo'
        if os.environ['conf_os_family'] == 'redhat':
            initial_user = 'ec2-user'
            sudo_group = 'wheel'

        logging.info('[CREATING DLAB SSH USER]')
        print('[CREATING DLAB SSH USER]')
        params = "--hostname {} --keyfile {} --initial_user {} --os_user {} --sudo_group {}".format\
            (instance_hostname, os.environ['conf_key_dir'] + os.environ['conf_key_name'] + ".pem", initial_user,
             edge_conf['dlab_ssh_user'], sudo_group)

        try:
            local("~/scripts/{}.py {}".format('create_ssh_user', params))
        except:
            traceback.print_exc()
            raise Exception
    except Exception as err:
        append_result("Failed creating ssh user 'dlab'.", str(err))
        AzureActions().remove_instance(edge_conf['resource_group_name'], edge_conf['instance_name'])
        AzureActions().remove_subnet(edge_conf['resource_group_name'], edge_conf['vpc_name'],
                                     edge_conf['private_subnet_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['edge_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['notebook_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                             edge_conf['master_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                                 edge_conf['slave_security_group_name'])
        for storage_account in AzureMeta().list_storage_accounts(edge_conf['resource_group_name']):
            if edge_conf['user_storage_account_name'] == storage_account.tags["Name"]:
                AzureActions().remove_storage_account(edge_conf['resource_group_name'], storage_account.name)
        if os.environ['azure_datalake_enable'] == 'true':
            for datalake in AzureMeta().list_datalakes(edge_conf['resource_group_name']):
                if edge_conf['datalake_store_name'] == datalake.tags["Name"]:
                    AzureActions().remove_datalake_directory(datalake.name, edge_conf['datalake_user_directory_name'])
        sys.exit(1)

    try:
        print('[INSTALLING PREREQUISITES]')
        logging.info('[INSTALLING PREREQUISITES]')
        params = "--hostname {} --keyfile {} --user {} --region {}".\
            format(instance_hostname, keyfile_name, edge_conf['dlab_ssh_user'], os.environ['azure_region'])
        try:
            local("~/scripts/{}.py {}".format('install_prerequisites', params))
        except:
            traceback.print_exc()
            raise Exception
    except Exception as err:
        append_result("Failed installing apps: apt & pip.", str(err))
        AzureActions().remove_instance(edge_conf['resource_group_name'], edge_conf['instance_name'])
        AzureActions().remove_subnet(edge_conf['resource_group_name'], edge_conf['vpc_name'],
                                     edge_conf['private_subnet_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['edge_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['notebook_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                             edge_conf['master_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                                 edge_conf['slave_security_group_name'])
        for storage_account in AzureMeta().list_storage_accounts(edge_conf['resource_group_name']):
            if edge_conf['user_storage_account_name'] == storage_account.tags["Name"]:
                AzureActions().remove_storage_account(edge_conf['resource_group_name'], storage_account.name)
        if os.environ['azure_datalake_enable'] == 'true':
            for datalake in AzureMeta().list_datalakes(edge_conf['resource_group_name']):
                if edge_conf['datalake_store_name'] == datalake.tags["Name"]:
                    AzureActions().remove_datalake_directory(datalake.name, edge_conf['datalake_user_directory_name'])
        sys.exit(1)

    try:
        print('[INSTALLING HTTP PROXY]')
        logging.info('[INSTALLING HTTP PROXY]')
        additional_config = {"exploratory_subnet": edge_conf['private_subnet_cidr'],
                             "template_file": "/root/templates/squid.conf"}
        params = "--hostname {} --keyfile {} --additional_config '{}' --user {}" \
                 .format(instance_hostname, keyfile_name, json.dumps(additional_config), edge_conf['dlab_ssh_user'])
        try:
            local("~/scripts/{}.py {}".format('configure_http_proxy', params))
        except:
            traceback.print_exc()
            raise Exception
    except Exception as err:
        append_result("Failed installing http proxy.", str(err))
        AzureActions().remove_instance(edge_conf['resource_group_name'], edge_conf['instance_name'])
        AzureActions().remove_subnet(edge_conf['resource_group_name'], edge_conf['vpc_name'],
                                     edge_conf['private_subnet_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['edge_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['notebook_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                             edge_conf['master_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                                 edge_conf['slave_security_group_name'])
        for storage_account in AzureMeta().list_storage_accounts(edge_conf['resource_group_name']):
            if edge_conf['user_storage_account_name'] == storage_account.tags["Name"]:
                AzureActions().remove_storage_account(edge_conf['resource_group_name'], storage_account.name)
        if os.environ['azure_datalake_enable'] == 'true':
            for datalake in AzureMeta().list_datalakes(edge_conf['resource_group_name']):
                if edge_conf['datalake_store_name'] == datalake.tags["Name"]:
                    AzureActions().remove_datalake_directory(datalake.name, edge_conf['datalake_user_directory_name'])
        sys.exit(1)

    try:
        print('[INSTALLING USERs KEY]')
        logging.info('[INSTALLING USERs KEY]')
        additional_config = {"user_keyname": edge_conf['user_keyname'],
                             "user_keydir": os.environ['conf_key_dir']}
        params = "--hostname {} --keyfile {} --additional_config '{}' --user {}".format(
            instance_hostname, keyfile_name, json.dumps(additional_config), edge_conf['dlab_ssh_user'])
        try:
            local("~/scripts/{}.py {}".format('install_user_key', params))
        except:
            traceback.print_exc()
            raise Exception
    except Exception as err:
        append_result("Failed installing users key. Excpeption: " + str(err))
        AzureActions().remove_instance(edge_conf['resource_group_name'], edge_conf['instance_name'])
        AzureActions().remove_subnet(edge_conf['resource_group_name'], edge_conf['vpc_name'],
                                     edge_conf['private_subnet_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['edge_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'], edge_conf['notebook_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                             edge_conf['master_security_group_name'])
        AzureActions().remove_security_group(edge_conf['resource_group_name'],
                                                 edge_conf['slave_security_group_name'])
        for storage_account in AzureMeta().list_storage_accounts(edge_conf['resource_group_name']):
            if edge_conf['user_storage_account_name'] == storage_account.tags["Name"]:
                AzureActions().remove_storage_account(edge_conf['resource_group_name'], storage_account.name)
        if os.environ['azure_datalake_enable'] == 'true':
            for datalake in AzureMeta().list_datalakes(edge_conf['resource_group_name']):
                if edge_conf['datalake_store_name'] == datalake.tags["Name"]:
                    AzureActions().remove_datalake_directory(datalake.name, edge_conf['datalake_user_directory_name'])
        sys.exit(1)

    try:
        for storage_account in AzureMeta().list_storage_accounts(edge_conf['resource_group_name']):
            if edge_conf['shared_storage_account_name'] == storage_account.tags["Name"]:
                shared_storage_account_name = storage_account.name
            if edge_conf['user_storage_account_name'] == storage_account.tags["Name"]:
                user_storage_account_name = storage_account.name

        print('[SUMMARY]')
        logging.info('[SUMMARY]')
        print("Instance name: {}".format(edge_conf['instance_name']))
        print("Hostname: {}".format(edge_conf['instance_dns_name']))
        print("Public IP: {}".format(edge_conf['edge_public_ip']))
        print("Private IP: {}".format(edge_conf['edge_private_ip']))
        print("Key name: {}".format(edge_conf['key_name']))
        print("User storage account name: {}".format(user_storage_account_name))
        print("User container name: {}".format(edge_conf['user_container_name']))
        if os.environ['azure_datalake_enable'] == 'true':
            for datalake in AzureMeta().list_datalakes(edge_conf['resource_group_name']):
                if edge_conf['datalake_store_name'] == datalake.tags["Name"]:
                    datalake_id = datalake.name
            print("Data Lake name: {}".format(datalake_id))
            print("Data Lake tag name: {}".format(edge_conf['datalake_store_name']))
            print("Data Lake Store user directory name: {}".format(edge_conf['datalake_user_directory_name']))
        print("Notebook SG: {}".format(edge_conf['notebook_security_group_name']))
        print("Edge SG: {}".format(edge_conf['edge_security_group_name']))
        print("Notebook subnet: {}".format(edge_conf['private_subnet_cidr']))
        with open("/root/result.json", 'w') as result:
            if os.environ['azure_datalake_enable'] == 'false':
                res = {"hostname": edge_conf['instance_dns_name'],
                       "public_ip": edge_conf['edge_public_ip'],
                       "ip": edge_conf['edge_private_ip'],
                       "key_name": edge_conf['key_name'],
                       "user_storage_account_name": user_storage_account_name,
                       "user_container_name": edge_conf['user_container_name'],
                       "shared_storage_account_name": shared_storage_account_name,
                       "shared_container_name": edge_conf['shared_container_name'],
                       "user_storage_account_tag_name": edge_conf['user_storage_account_name'],
                       "tunnel_port": "22",
                       "socks_port": "1080",
                       "notebook_sg": edge_conf['notebook_security_group_name'],
                       "edge_sg": edge_conf['edge_security_group_name'],
                       "notebook_subnet": edge_conf['private_subnet_cidr'],
                       "instance_id": edge_conf['instance_name'],
                       "full_edge_conf": edge_conf,
                       "Action": "Create new EDGE server"}
            else:
                res = {"hostname": edge_conf['instance_dns_name'],
                       "public_ip": edge_conf['edge_public_ip'],
                       "ip": edge_conf['edge_private_ip'],
                       "key_name": edge_conf['key_name'],
                       "user_storage_account_name": user_storage_account_name,
                       "user_container_name": edge_conf['user_container_name'],
                       "shared_storage_account_name": shared_storage_account_name,
                       "shared_container_name": edge_conf['shared_container_name'],
                       "user_storage_account_tag_name": edge_conf['user_storage_account_name'],
                       "datalake_name": datalake_id,
                       "datalake_tag_name": edge_conf['datalake_store_name'],
                       "datalake_shared_directory_name": edge_conf['datalake_shared_directory_name'],
                       "datalake_user_directory_name": edge_conf['datalake_user_directory_name'],
                       "tunnel_port": "22",
                       "socks_port": "1080",
                       "notebook_sg": edge_conf['notebook_security_group_name'],
                       "edge_sg": edge_conf['edge_security_group_name'],
                       "notebook_subnet": edge_conf['private_subnet_cidr'],
                       "instance_id": edge_conf['instance_name'],
                       "full_edge_conf": edge_conf,
                       "Action": "Create new EDGE server"}
            print(json.dumps(res))
            result.write(json.dumps(res))
    except:
        print("Failed writing results.")
        sys.exit(0)

    sys.exit(0)


text:
package org.gradle.nativeplatform.tasks;

import com.google.common.collect.Lists;
import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.Incubating;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.TaskAction;
import org.gradle.nativeplatform.toolchain.internal.PCHUtils;
import org.gradle.workers.IsolationMode;
import org.gradle.workers.WorkerConfiguration;
import org.gradle.workers.WorkerExecutor;

import javax.inject.Inject;
import java.io.File;

/**
 * Generates a prefix header file from a list of headers to be precompiled.
 */
@Incubating
public class PrefixHeaderFileGenerateTask extends DefaultTask {
    private String header;
    private File prefixHeaderFile;
    private final WorkerExecutor workerExecutor;

    /**
     * Injects a {@link WorkerExecutor} instance.
     *
     * @since 4.2
     */
    @Inject
    public PrefixHeaderFileGenerateTask(WorkerExecutor workerExecutor) {
        this.workerExecutor = workerExecutor;
    }

    @TaskAction
    void generatePrefixHeaderFile() {
        workerExecutor.submit(GeneratePrefixHeaderFile.class, new Action<WorkerConfiguration>() {
            @Override
            public void execute(WorkerConfiguration config) {
                config.setIsolationMode(IsolationMode.NONE);
                config.setParams(header, prefixHeaderFile);
            }
        });
    }

    @Input
    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    @OutputFile
    public File getPrefixHeaderFile() {
        return prefixHeaderFile;
    }

    public void setPrefixHeaderFile(File prefixHeaderFile) {
        this.prefixHeaderFile = prefixHeaderFile;
    }

    private static class GeneratePrefixHeaderFile implements Runnable {
        private final String header;
        private final File prefixHeaderFile;

        @Inject
        public GeneratePrefixHeaderFile(String header, File prefixHeaderFile) {
            this.header = header;
            this.prefixHeaderFile = prefixHeaderFile;
        }

        @Override
        public void run() {
            PCHUtils.generatePrefixHeaderFile(Lists.newArrayList(header), prefixHeaderFile);
        }
    }
}


text:
/*
 TreeParser.java

 Created on Aug 22, 2006 by Richard Johansson (richard@cs.lth.se).

 $Log: TreeParser.java,v $
 Revision 1.1  2009/01/16 10:09:50  johansson
 Added to brenta repository.

 Revision 1.4  2007/08/07 12:38:56  richard
 Complete refactoring.

 Revision 1.3  2007/07/04 14:58:58  richard
 Reordered collection steps.

 Revision 1.2  2007/07/03 07:08:38  richard
 Factory method.

 Revision 1.1  2006/09/07 17:55:16  richard
 Added.

 */
package se.lth.cs.nlp.nlputils.pstree;

/**
 * Parser of nested parse trees, such as the Penn Treebank format or
 * the format used by the Collins parser.
 *
 * @author Richard Johansson (richard@cs.lth.se)
 */
public abstract class TreeParser {

    protected HeadFinder headFinder;

    public TreeParser() {
    }

    public TreeParser(HeadFinder headFinder) {
        this();
        this.headFinder = headFinder;
    }

    public PhraseStructureTree parseTree() {

        Node top = parseNode();
        if(top == null)
            return null;

        PhraseStructureTree out = new PhraseStructureTree(top);
        top.setTree(out);

        beforeHeadFinder(out);

        /* Find heads for each node, if a head finder was supplied. */
        if(headFinder != null)
            out.getTopNode().setHeads(headFinder);

        return out;
    }

    /**
     * Returns a node in a parse tree. The first call generates the top
     * node.
     *
     * @return the node.
     */
    public abstract Node parseNode();

    public abstract boolean hasMoreTrees();

    public void beforeHeadFinder(PhraseStructureTree tree) {
    }

}


text:
from django.db import models

class Payment(models.Model):
    total = models.DecimalField(max_digits=14, decimal_places=2)

    def __unicode__(self):
        return str(self.total)


text:
<?php

/**
 * @file
 * Definition of Drupal\search\Plugin\views\row\SearchRow.
 */

namespace Drupal\search\Plugin\views\row;

use Drupal\views\Plugin\views\row\RowPluginBase;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;

/**
 * Plugin which performs a node_view on the resulting object.
 *
 * @Plugin(
 *   id = "search_view",
 *   module = "search",
 *   title = @Translation("Search"),
 *   no_uid = TRUE
 * )
 */
class SearchRow extends RowPluginBase {

  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['score'] = array('default' => TRUE, 'bool' => TRUE);

    return $options;
  }

  public function buildOptionsForm(&$form, &$form_state) {
    $form['score'] = array(
      '#type' => 'checkbox',
      '#title' => t('Display score'),
      '#default_value' => $this->options['score'],
    );
  }

  /**
   * Override the behavior of the render() function.
   */
  public function render($row) {
    return array(
      '#theme' => $this->themeFunctions(),
      '#view' => $this->view,
      '#options' => $this->options,
      '#row' => $row,
    );
  }

}


text:
using System;
using UnityEngine;

namespace UnityEditor.VFX.Operator
{
    [VFXInfo(category = "Sampling")]
    class SampleTexture2DArray : VFXOperator
    {
        override public string name { get { return "Sample Texture2DArray"; } }

        public class InputProperties
        {
            [Tooltip("The texture to sample from.")]
            public Texture2DArray texture = null;
            [Tooltip("The texture coordinate used for the sampling.")]
            public Vector2 uv = Vector2.zero;
            [Min(0), Tooltip("The array slice to sample from.")]
            public float slice = 0.0f;
            [Min(0), Tooltip("The mip level to sample from.")]
            public float mipLevel = 0.0f;
        }

        public class OutputProperties
        {
            public Vector4 s = Vector4.zero;
        }

        protected override sealed VFXExpression[] BuildExpression(VFXExpression[] inputExpression)
        {
            return new[] { new VFXExpressionSampleTexture2DArray(inputExpression[0], inputExpression[1], inputExpression[2], inputExpression[3]) };
        }
    }
}


text:
<?php

namespace ZendTest\Code\Generator\DocBlock\Tag;

use Zend\Code\Generator\DocBlock\Tag\MethodTag;
use Zend\Code\Generator\DocBlock\TagManager;
use Zend\Code\Reflection\DocBlockReflection;

/**
 * @group Zend_Code_Generator
 * @group Zend_Code_Generator_Php
 */
class MethodTagTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var MethodTag
     */
    protected $tag;

    /**
     * @var TagManager
     */
    protected $tagmanager;

    public function setUp()
    {
        $this->tag = new MethodTag();
        $this->tagmanager = new TagManager();
        $this->tagmanager->initializeDefaultTags();
    }

    public function tearDown()
    {
        $this->tag = null;
        $this->tagmanager = null;
    }

    public function testGetterAndSetterPersistValue()
    {
        $this->tag->setIsStatic(true);
        $this->tag->setMethodName('method');
        $this->assertEquals(true, $this->tag->isStatic());
        $this->assertEquals('method', $this->tag->getMethodName());
    }

    public function testGetterForMethodNameTrimsCorrectly()
    {
        $this->tag->setMethodName('()method()');
        $this->assertEquals('()method', $this->tag->getMethodName());
    }

    public function testNameIsCorrect()
    {
        $this->assertEquals('method', $this->tag->getName());
    }

    public function testParamProducesCorrectDocBlockLine()
    {
        $this->tag->setIsStatic(true);
        $this->tag->setMethodName('method');
        $this->tag->setTypes('int');
        $this->tag->setDescription('method(string $a)');
        $this->assertEquals('@method static int method() method(string $a)', $this->tag->generate());
    }

    public function testConstructorWithOptions()
    {
        $this->tag->setOptions(array(
            'isStatic' => true,
            'methodName' => 'method',
            'types' => array('string'),
            'description' => 'description'
        ));
        $tagWithOptionsFromConstructor = new MethodTag('method', array('string'), 'description', true);
        $this->assertEquals($this->tag->generate(), $tagWithOptionsFromConstructor->generate());
    }

    public function testCreatingTagFromReflection()
    {
        $docreflection = new DocBlockReflection('/** @method static int method() method(int $a)');
        $reflectionTag = $docreflection->getTag('method');

        /** @var MethodTag $tag */
        $tag = $this->tagmanager->createTagFromReflection($reflectionTag);
        $this->assertInstanceOf('Zend\Code\Generator\DocBlock\Tag\MethodTag', $tag);
        $this->assertEquals(true, $tag->isStatic());
        $this->assertEquals('int', $tag->getTypesAsString());
        $this->assertEquals('method', $tag->getMethodName());
        $this->assertEquals('method(int $a)', $tag->getDescription());
    }
}


text:
alter table multi_segfile_bitab ADD COLUMN added_col22 character varying(35) default NULL;
select count(*) as added_col22 from pg_attribute pa, pg_class pc where pa.attrelid = pc.oid and pc.relname='multi_segfile_bitab' and attname='added_col22';
alter table multi_segfile_bitab DROP COLUMN added_col22;
select count(*) as added_col22 from pg_attribute pa, pg_class pc where pa.attrelid = pc.oid and pc.relname='multi_segfile_bitab' and attname='added_col22';
VACUUM multi_segfile_bitab;


text:
<?php

namespace Concrete\Core\Updater\Migrations;

/**
 * Interface that migrations that can be safely re-executed should implement.
 */
interface RepeatableMigrationInterface
{
}


text:
local remap = require("user.keymap")
local nmap = remap.nmap
local nnoremap = remap.nnoremap
local vnoremap = remap.vnoremap
local xnoremap = remap.xnoremap
local inoremap = remap.inoremap

-- project view
nnoremap("<leader>e", ":Lexplore 25<CR>")

-- change window
nnoremap("<C-h>", "<C-w>h")
nnoremap("<C-j>", "<C-w>j")
nnoremap("<C-k>", "<C-w>k")
nnoremap("<C-l>", "<C-w>l")

-- to normal mode (from insert)
inoremap("jk", "<Esc>")

-- yank to clipboard, paste from clipboard
nnoremap("<leader>Y", "\"*y")
nnoremap("<leader>P", "\"+p")


text:
package org.apache.camel.opentelemetry;

import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

public class ABCRouteTest extends CamelOpenTelemetryTestSupport {
    private static SpanTestData[] testdata = {
            new SpanTestData().setLabel("seda:b server").setUri("seda://b").setOperation("b")
                    .setParentId(2).addLogMessage("routing at b"),
            new SpanTestData().setLabel("seda:c server").setUri("seda://c").setOperation("c")
                    .setParentId(2).addLogMessage("Exchange[ExchangePattern: InOut, BodyType: String, Body: Hello]"),
            new SpanTestData().setLabel("seda:a server").setUri("seda://a").setOperation("a")
                    .setParentId(3).addLogMessage("routing at a").addLogMessage("End of routing"),
            new SpanTestData().setLabel("direct:start server").setUri("direct://start").setOperation("start")
    };

    public ABCRouteTest() {
        super(testdata);
    }

    @Test
    public void testRoute() throws Exception {
        template.requestBody("direct:start", "Hello");
        verify();
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start").to("seda:a").routeId("start");

                from("seda:a").routeId("a")
                        .log("routing at ${routeId}")
                        .to("seda:b")
                        .delay(2000)
                        .to("seda:c")
                        .log("End of routing");

                from("seda:b").routeId("b")
                        .log("routing at ${routeId}")
                        .delay(simple("${random(1000,2000)}"));

                from("seda:c").routeId("c")
                        .to("log:test")
                        .delay(simple("${random(0,100)}"));
            }
        };
    }
}


text:
#ifndef __hil14_mdl_lib_sfun_h__
#define __hil14_mdl_lib_sfun_h__

/* Include files */
#define S_FUNCTION_NAME                 sf_sfun
#include "sfc_sf.h"
#include "sfc_mex.h"
#include "sfcdebug.h"

#define rtInf                           (mxGetInf())
#define rtMinusInf                      (-(mxGetInf()))
#define rtNaN                           (mxGetNaN())
#define rtIsNaN(X) ((int)mxIsNaN(X))
#define rtIsInf(X) ((int)mxIsInf(X))

/* Type Definitions */

/* Named Constants */
#define CALL_EVENT                      (MAX_uint8_T)

/* Variable Declarations */
extern uint8_T _sfEvent_;
extern uint32_T _hil14_mdl_libMachineNumber_;
extern real_T _sfTime_;

/* Variable Definitions */

/* Function Declarations */
void hil14_mdl_lib_initializer(void);
void hil14_mdl_lib_terminator(void);

/* Function Definitions */

#endif


text:
// -----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Pathfinder-fr">
// Copyright (c) Pathfinder-fr. Tous droits reserves.
// </copyright>
// -----------------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("PathfinderDb.Toolbelt.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]


text:
package org.n52.iceland.ogc.ows;

public interface DisableableExtension {
    public boolean isDisabled();
}


text:
package pgtype

import (
	"database/sql/driver"
	"fmt"
)

// ArrayGetter is a type that can be converted into a PostgreSQL array.

// RecordCodec is a codec for the generic PostgreSQL record type such as is created with the "row" function. Record can
// only decode the binary format. The text format output format from PostgreSQL does not include type information and
// is therefore impossible to decode. Encoding is impossible because PostgreSQL does not support input of generic
// records.
type RecordCodec struct{}

func (RecordCodec) FormatSupported(format int16) bool {
	return format == BinaryFormatCode
}

func (RecordCodec) PreferredFormat() int16 {
	return BinaryFormatCode
}

func (RecordCodec) PlanEncode(m *Map, oid uint32, format int16, value any) EncodePlan {
	return nil
}

func (RecordCodec) PlanScan(m *Map, oid uint32, format int16, target any) ScanPlan {
	if format == BinaryFormatCode {
		switch target.(type) {
		case CompositeIndexScanner:
			return &scanPlanBinaryRecordToCompositeIndexScanner{m: m}
		}
	}

	return nil
}

type scanPlanBinaryRecordToCompositeIndexScanner struct {
	m *Map
}

func (plan *scanPlanBinaryRecordToCompositeIndexScanner) Scan(src []byte, target any) error {
	targetScanner := (target).(CompositeIndexScanner)

	if src == nil {
		return targetScanner.ScanNull()
	}

	scanner := NewCompositeBinaryScanner(plan.m, src)
	for i := 0; scanner.Next(); i++ {
		fieldTarget := targetScanner.ScanIndex(i)
		if fieldTarget != nil {
			fieldPlan := plan.m.PlanScan(scanner.OID(), BinaryFormatCode, fieldTarget)
			if fieldPlan == nil {
				return fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), fieldTarget)
			}

			err := fieldPlan.Scan(scanner.Bytes(), fieldTarget)
			if err != nil {
				return err
			}
		}
	}

	if err := scanner.Err(); err != nil {
		return err
	}

	return nil
}

func (RecordCodec) DecodeDatabaseSQLValue(m *Map, oid uint32, format int16, src []byte) (driver.Value, error) {
	if src == nil {
		return nil, nil
	}

	switch format {
	case TextFormatCode:
		return string(src), nil
	case BinaryFormatCode:
		buf := make([]byte, len(src))
		copy(buf, src)
		return buf, nil
	default:
		return nil, fmt.Errorf("unknown format code %d", format)
	}
}

func (RecordCodec) DecodeValue(m *Map, oid uint32, format int16, src []byte) (any, error) {
	if src == nil {
		return nil, nil
	}

	switch format {
	case TextFormatCode:
		return string(src), nil
	case BinaryFormatCode:
		scanner := NewCompositeBinaryScanner(m, src)
		values := make([]any, scanner.FieldCount())
		for i := 0; scanner.Next(); i++ {
			var v any
			fieldPlan := m.PlanScan(scanner.OID(), BinaryFormatCode, &v)
			if fieldPlan == nil {
				return nil, fmt.Errorf("unable to scan OID %d in binary format into %v", scanner.OID(), v)
			}

			err := fieldPlan.Scan(scanner.Bytes(), &v)
			if err != nil {
				return nil, err
			}

			values[i] = v
		}

		if err := scanner.Err(); err != nil {
			return nil, err
		}

		return values, nil
	default:
		return nil, fmt.Errorf("unknown format code %d", format)
	}

}


text: ./astrond --loglevel info config/cluster.yml


text:
#!/usr/bin/env node
/*jshint node:true*/
'use strict';

require('look').start(); // perf output to http://localhost:5959
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var compress = require('compression');
var errorHandler = require('./utils/errorHandler')();
var favicon = require('serve-favicon');
var logger = require('morgan');
var port = process.env.PORT || 7272;
var staticFiles = express.static;
var routes;

var environment = process.env.NODE_ENV;

app.use(favicon(__dirname + '/favicon.ico'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(compress());        // Compress response data with gzip
app.use(require('cors')()); // enable ALL CORS requests
app.use(errorHandler.init);

app.use('/api', require('./routes'));

console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);

var source = '';

app.get('/ping', function(req, res, next) {
    console.log(req.body);
    res.send('pong');
});

switch (environment){
    case 'build':
        console.log('** BUILD **');
        app.use('/', staticFiles('./build/'));
        break;
    default:
        console.log('** DEV **');
        app.use(staticFiles('./src/client/'));
        app.use(staticFiles('./'));
        app.use(staticFiles('./.tmp/'));
        app.use('/*', staticFiles('./src/client/index.html'));
        break;
}

app.listen(port, function() {
    console.log('Express server listening on port ' + port);
    console.log('env = ' + app.get('env') +
        '\n__dirname = ' + __dirname  +
        '\nprocess.cwd = ' + process.cwd());
});


text:
import { ValidationContext } from "../index";

/**
 * Known argument names
 *
 * A GraphQL field is only valid if all supplied arguments are defined by
 * that field.
 */
export function KnownArgumentNames(context: ValidationContext): any;


text:
基于百度定位的插件
cordova plugin add  https://github.com/AromaSunbeam/bshinfo-plugin-geolocation.git


text:
class Recipe < ActiveRecord::Base

  validates :title, :presence => true,
                    :length => { :minimum => 10, :maximum => 70 }

  scope :last_ten, -> { all.order(:created_at).last(10).reverse }

end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>objective-c-sql-query-builder: ZIMSqlUpdateStatement.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

objective-c-sql-query-builder

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

File Members

ZIMSqlUpdateStatement.h

Go to the documentation of this file.

00001
00016
00017 #import "ZIMSqlStatement.h"
00018 #import "ZIMSqlDataManipulationCommand.h"
00019
00026 @interface ZIMSqlUpdateStatement : NSObject <ZIMSqlStatement, ZIMSqlDataManipulationCommand> {
00027
00028         @protected
00029                 NSString *_table;
00030                 NSMutableArray *_column;
00031                 NSMutableArray *_where;
00032                 NSMutableArray *_orderBy;
00033                 NSUInteger _limit;
00034                 NSUInteger _offset;
00035
00036 }
00043 - (void) table: (NSString *)table;
00051 - (void) column: (NSString *)column value: (id)value; // wrap primitives with NSNumber
00058 - (void) whereBlock: (NSString *)brace;
00066 - (void) whereBlock: (NSString *)brace connector: (NSString *)connector;
00075 - (void) where: (id)column1 operator: (NSString *)operator column: (id)column2;
00085 - (void) where: (id)column1 operator: (NSString *)operator column: (id)column2 connector: (NSString *)connector;
00094 - (void) where: (id)column operator: (NSString *)operator value: (id)value; // wrap primitives with NSNumber
00104 - (void) where: (id)column operator: (NSString *)operator value: (id)value connector: (NSString *)connector; // wrap primitives with NSNumber
00111 - (void) orderBy: (NSString *)column; // ORDER BY [COLUMN] ASC
00119 - (void) orderBy: (NSString *)column descending: (BOOL)descending; // ORDER BY [COLUMN] [ASC | DESC]
00130 - (void) orderBy: (NSString *)column nulls: (NSString *)weight; // ORDER BY [COLUMN] ASC [NULLS FIRST | NULLS LAST]
00142 - (void) orderBy: (NSString *)column descending: (BOOL)descending nulls: (NSString *)weight; // ORDER BY [COLUMN] [ASC | DESC] [NULLS FIRST | NULLS LAST]
00149 - (void) limit: (NSUInteger)limit;
00157 - (void) limit: (NSUInteger)limit offset: (NSUInteger)offset;
00164 - (void) offset: (NSUInteger)offset;
00171 - (NSString *) statement;
00172
00173 @end

 All Classes Files Functions Variables Properties Defines

<address class="footer">Generated by

 1.7.4 </address>


text:
<?php

namespace Michaeljennings\Laralastica\Tests;

use Elastica\Client;
use Elastica\Connection;
use Michaeljennings\Laralastica\LaralasticaServiceProvider;
use Michaeljennings\Laralastica\Tests\Fixtures\TestModel;
use Orchestra\Database\ConsoleServiceProvider;
use Orchestra\Testbench\TestCase as OrchestraTestCase;

class TestCase extends OrchestraTestCase
{
    /**
     * Setup the test environment.
     */
    public function setUp(): void
    {
        parent::setUp();

        $this->loadMigrationsFrom(__DIR__.'/database/migrations');

        $this->withFactories(__DIR__.'/database/factories');
    }

    /**
     * @inheritdoc
     */
    protected function getEnvironmentSetUp($app)
    {
        $app['config']->set('laralastica.driver', 'elastica');
        $app['config']->set('laralastica.index_prefix', 'testing_');

        $app['config']->set('laralastica.indexable', [
            'test' => TestModel::class,
        ]);

        $app['config']->set('laralastica.drivers.elastica', [
            'host' => $this->getHost(),
            'port' => $this->getPort(),
            'size' => 10,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function getPackageProviders($app)
    {
        return [
            ConsoleServiceProvider::class,
            LaralasticaServiceProvider::class,
        ];
    }

    /**
     * @return Client
     */
    public function getClient()
    {
        return app(Client::class);
    }

    /**
     * @return string Host to es for elastica tests
     */
    protected function getHost()
    {
        return getenv('ES_HOST') ?: Connection::DEFAULT_HOST;
    }

    /**
     * @return int Port to es for elastica tests
     */
    protected function getPort()
    {
        return getenv('ES_PORT') ?: Connection::DEFAULT_PORT;
    }
}


text:
package uk.co.real_logic.aeron.tools;

import uk.co.real_logic.aeron.tools.RateController.IntervalInternal;

public class SecondsAtMessagesPerSecondInterval extends RateControllerInterval
{
    /* The rate we _want_ to achieve, if possible.  Might not be able
     * to hit it exactly due to receiver pacing, etc.  But it's what
     * we're aiming for. */
    private final double goalMessagesPerSecond;
    /* Number of seconds (can be fractional) to run for, in total. */
    private final double seconds;

    public SecondsAtMessagesPerSecondInterval(final double seconds, final double messagesPerSecond)
    {
        this.goalMessagesPerSecond = messagesPerSecond;
        this.seconds = seconds;
    }

    public double messagesPerSecond()
    {
        return goalMessagesPerSecond;
    }

    public double seconds()
    {
        return seconds;
    }

    IntervalInternal makeInternal(final RateController rateController) throws Exception
    {
        return rateController.new SecondsAtMessagesPerSecondInternal(rateController, seconds, goalMessagesPerSecond);
    }
}


text: load File.expand_path('../tasks/bundler.cap', __FILE__)