text:
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>imageBox</title>
	<link rel="stylesheet" href="css/jquery.imgBox.css">
	<link rel="stylesheet" href="css/font-awesome.min.css">

	<script src="http://cdn.bootcss.com/jquery/1.8.0/jquery.min.js"></script>
	<script type="text/javascript" src="js/ajaxfileupload.js"></script>
	<script type="text/javascript" src="js/jquery.imgBox.js"></script>
	<script>
		$(function() {
			$("#camera").ImgBox({
				url: '/Test/ImageUpload',
				shape:'rect',
				type: [".jpg", '.jpeg', '.png', '.gif', '.xxx'],
				afterUpload: function(data, status, showError) {
					console.log("status: "+status);
					console.log(data);
					showError("可以通过返回值确认图片格式和大小是否满足要求,此处设置提示语");
				}
			});
		})
	</script>
</head>
<body>
	<i id="camera" class="icon-camera-retro icon-3x"></i>
</body>
</html>


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.Network.Models
{
    /// <summary> The action type of a rule. </summary>
    public readonly partial struct FirewallPolicyNatRuleCollectionActionType : IEquatable<FirewallPolicyNatRuleCollectionActionType>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="FirewallPolicyNatRuleCollectionActionType"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public FirewallPolicyNatRuleCollectionActionType(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string DnatValue = "DNAT";

        /// <summary> DNAT. </summary>
        public static FirewallPolicyNatRuleCollectionActionType Dnat { get; } = new FirewallPolicyNatRuleCollectionActionType(DnatValue);
        /// <summary> Determines if two <see cref="FirewallPolicyNatRuleCollectionActionType"/> values are the same. </summary>
        public static bool operator ==(FirewallPolicyNatRuleCollectionActionType left, FirewallPolicyNatRuleCollectionActionType right) => left.Equals(right);
        /// <summary> Determines if two <see cref="FirewallPolicyNatRuleCollectionActionType"/> values are not the same. </summary>
        public static bool operator !=(FirewallPolicyNatRuleCollectionActionType left, FirewallPolicyNatRuleCollectionActionType right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="FirewallPolicyNatRuleCollectionActionType"/>. </summary>
        public static implicit operator FirewallPolicyNatRuleCollectionActionType(string value) => new FirewallPolicyNatRuleCollectionActionType(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is FirewallPolicyNatRuleCollectionActionType other && Equals(other);
        /// <inheritdoc />
        public bool Equals(FirewallPolicyNatRuleCollectionActionType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}

redpajama_set_name: RedPajamaGithub


text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

#ifndef CMEMORY_H
#define CMEMORY_H

#include "unicode/utypes.h"

#include <stddef.h>
#include <string.h>
#include "unicode/localpointer.h"

#if U_DEBUG && defined(UPRV_MALLOC_COUNT)
#include <stdio.h>
#endif

#if U_DEBUG

/*
 * The C++ standard requires that the source pointer for memcpy() & memmove()
 * is valid, not NULL, and not at the end of an allocated memory block.
 * In debug mode, we read one byte from the source point to verify that it's
 * a valid, readable pointer.
 */

U_CAPI void uprv_checkValidMemory(const void *p, size_t n);

#define uprv_memcpy(dst, src, size) ( \
    uprv_checkValidMemory(src, 1), \
    U_STANDARD_CPP_NAMESPACE memcpy(dst, src, size))
#define uprv_memmove(dst, src, size) ( \
    uprv_checkValidMemory(src, 1), \
    U_STANDARD_CPP_NAMESPACE memmove(dst, src, size))

#else

#define uprv_memcpy(dst, src, size) U_STANDARD_CPP_NAMESPACE memcpy(dst, src, size)
#define uprv_memmove(dst, src, size) U_STANDARD_CPP_NAMESPACE memmove(dst, src, size)

#endif  /* U_DEBUG */

/**
 * \def UPRV_LENGTHOF
 * Convenience macro to determine the length of a fixed array at compile-time.
 * @param array A fixed length array
 * @return The length of the array, in elements
 * @internal
 */
#define UPRV_LENGTHOF(array) (int32_t)(sizeof(array)/sizeof((array)[0]))
#define uprv_memset(buffer, mark, size) U_STANDARD_CPP_NAMESPACE memset(buffer, mark, size)
#define uprv_memcmp(buffer1, buffer2, size) U_STANDARD_CPP_NAMESPACE memcmp(buffer1, buffer2,size)

U_CAPI void * U_EXPORT2
uprv_malloc(size_t s) U_MALLOC_ATTR U_ALLOC_SIZE_ATTR(1);

U_CAPI void * U_EXPORT2
uprv_realloc(void *mem, size_t size) U_ALLOC_SIZE_ATTR(2);

U_CAPI void U_EXPORT2
uprv_free(void *mem);

U_CAPI void * U_EXPORT2
uprv_calloc(size_t num, size_t size) U_MALLOC_ATTR U_ALLOC_SIZE_ATTR2(1,2);

/**
 * This should align the memory properly on any machine.
 * This is very useful for the safeClone functions.
 */
typedef union {
    long    t1;
    double  t2;
    void   *t3;
} UAlignedMemory;

/**
 * Get the least significant bits of a pointer (a memory address).
 * For example, with a mask of 3, the macro gets the 2 least significant bits,
 * which will be 0 if the pointer is 32-bit (4-byte) aligned.
 *
 * ptrdiff_t is the most appropriate integer type to cast to.
 * size_t should work too, since on most (or all?) platforms it has the same
 * width as ptrdiff_t.
 */
#define U_POINTER_MASK_LSB(ptr, mask) (((ptrdiff_t)(char *)(ptr)) & (mask))

/**
 * Get the amount of bytes that a pointer is off by from
 * the previous UAlignedMemory-aligned pointer.
 */
#define U_ALIGNMENT_OFFSET(ptr) U_POINTER_MASK_LSB(ptr, sizeof(UAlignedMemory) - 1)

/**
 * Get the amount of bytes to add to a pointer
 * in order to get the next UAlignedMemory-aligned address.
 */
#define U_ALIGNMENT_OFFSET_UP(ptr) (sizeof(UAlignedMemory) - U_ALIGNMENT_OFFSET(ptr))

/**
  *  Heap clean up function, called from u_cleanup()
  *    Clears any user heap functions from u_setMemoryFunctions()
  *    Does NOT deallocate any remaining allocated memory.
  */
U_CFUNC UBool
cmemory_cleanup(void);

/**
 * A function called by <TT>uhash_remove</TT>,
 * <TT>uhash_close</TT>, or <TT>uhash_put</TT> to delete
 * an existing key or value.
 * @param obj A key or value stored in a hashtable
 * @see uprv_deleteUObject
 */
typedef void U_CALLCONV UObjectDeleter(void* obj);

/**
 * Deleter for UObject instances.
 * Works for all subclasses of UObject because it has a virtual destructor.
 */
U_CAPI void U_EXPORT2
uprv_deleteUObject(void *obj);

#ifdef __cplusplus

U_NAMESPACE_BEGIN

/**
 * "Smart pointer" class, deletes memory via uprv_free().
 * For most methods see the LocalPointerBase base class.
 * Adds operator[] for array item access.
 *
 * @see LocalPointerBase
 */
template<typename T>
class LocalMemory : public LocalPointerBase<T> {
public:
    using LocalPointerBase<T>::operator*;
    using LocalPointerBase<T>::operator->;
    /**
     * Constructor takes ownership.
     * @param p simple pointer to an array of T items that is adopted
     */
    explicit LocalMemory(T *p=NULL) : LocalPointerBase<T>(p) {}
    /**
     * Move constructor, leaves src with isNull().
     * @param src source smart pointer
     */
    LocalMemory(LocalMemory<T> &&src) U_NOEXCEPT : LocalPointerBase<T>(src.ptr) {
        src.ptr=NULL;
    }
    /**
     * Destructor deletes the memory it owns.
     */
    ~LocalMemory() {
        uprv_free(LocalPointerBase<T>::ptr);
    }
    /**
     * Move assignment operator, leaves src with isNull().
     * The behavior is undefined if *this and src are the same object.
     * @param src source smart pointer
     * @return *this
     */
    LocalMemory<T> &operator=(LocalMemory<T> &&src) U_NOEXCEPT {
        return moveFrom(src);
    }
    /**
     * Move assignment, leaves src with isNull().
     * The behavior is undefined if *this and src are the same object.
     *
     * Can be called explicitly, does not need C++11 support.
     * @param src source smart pointer
     * @return *this
     */
    LocalMemory<T> &moveFrom(LocalMemory<T> &src) U_NOEXCEPT {
        delete[] LocalPointerBase<T>::ptr;
        LocalPointerBase<T>::ptr=src.ptr;
        src.ptr=NULL;
        return *this;
    }
    /**
     * Swap pointers.
     * @param other other smart pointer
     */
    void swap(LocalMemory<T> &other) U_NOEXCEPT {
        T *temp=LocalPointerBase<T>::ptr;
        LocalPointerBase<T>::ptr=other.ptr;
        other.ptr=temp;
    }
    /**
     * Non-member LocalMemory swap function.
     * @param p1 will get p2's pointer
     * @param p2 will get p1's pointer
     */
    friend inline void swap(LocalMemory<T> &p1, LocalMemory<T> &p2) U_NOEXCEPT {
        p1.swap(p2);
    }
    /**
     * Deletes the array it owns,
     * and adopts (takes ownership of) the one passed in.
     * @param p simple pointer to an array of T items that is adopted
     */
    void adoptInstead(T *p) {
        uprv_free(LocalPointerBase<T>::ptr);
        LocalPointerBase<T>::ptr=p;
    }
    /**
     * Deletes the array it owns, allocates a new one and reset its bytes to 0.
     * Returns the new array pointer.
     * If the allocation fails, then the current array is unchanged and
     * this method returns NULL.
     * @param newCapacity must be >0
     * @return the allocated array pointer, or NULL if the allocation failed
     */
    inline T *allocateInsteadAndReset(int32_t newCapacity=1);
    /**
     * Deletes the array it owns and allocates a new one, copying length T items.
     * Returns the new array pointer.
     * If the allocation fails, then the current array is unchanged and
     * this method returns NULL.
     * @param newCapacity must be >0
     * @param length number of T items to be copied from the old array to the new one;
     *               must be no more than the capacity of the old array,
     *               which the caller must track because the LocalMemory does not track it
     * @return the allocated array pointer, or NULL if the allocation failed
     */
    inline T *allocateInsteadAndCopy(int32_t newCapacity=1, int32_t length=0);
    /**
     * Array item access (writable).
     * No index bounds check.
     * @param i array index
     * @return reference to the array item
     */
    T &operator[](ptrdiff_t i) const { return LocalPointerBase<T>::ptr[i]; }
};

template<typename T>
inline T *LocalMemory<T>::allocateInsteadAndReset(int32_t newCapacity) {
    if(newCapacity>0) {
        T *p=(T *)uprv_malloc(newCapacity*sizeof(T));
        if(p!=NULL) {
            uprv_memset(p, 0, newCapacity*sizeof(T));
            uprv_free(LocalPointerBase<T>::ptr);
            LocalPointerBase<T>::ptr=p;
        }
        return p;
    } else {
        return NULL;
    }
}

template<typename T>
inline T *LocalMemory<T>::allocateInsteadAndCopy(int32_t newCapacity, int32_t length) {
    if(newCapacity>0) {
        T *p=(T *)uprv_malloc(newCapacity*sizeof(T));
        if(p!=NULL) {
            if(length>0) {
                if(length>newCapacity) {
                    length=newCapacity;
                }
                uprv_memcpy(p, LocalPointerBase<T>::ptr, (size_t)length*sizeof(T));
            }
            uprv_free(LocalPointerBase<T>::ptr);
            LocalPointerBase<T>::ptr=p;
        }
        return p;
    } else {
        return NULL;
    }
}

/**
 * Simple array/buffer management class using uprv_malloc() and uprv_free().
 * Provides an internal array with fixed capacity. Can alias another array
 * or allocate one.
 *
 * The array address is properly aligned for type T. It might not be properly
 * aligned for types larger than T (or larger than the largest subtype of T).
 *
 * Unlike LocalMemory and LocalArray, this class never adopts
 * (takes ownership of) another array.
 */
template<typename T, int32_t stackCapacity>
class MaybeStackArray {
public:
    /**
     * Default constructor initializes with internal T[stackCapacity] buffer.
     */
    MaybeStackArray() : ptr(stackArray), capacity(stackCapacity), needToRelease(FALSE) {}
    /**
     * Automatically allocates the heap array if the argument is larger than the stack capacity.
     * Intended for use when an approximate capacity is known at compile time but the true
     * capacity is not known until runtime.
     */
    MaybeStackArray(int32_t newCapacity) : MaybeStackArray() {
        if (capacity < newCapacity) { resize(newCapacity); }
    };
    /**
     * Destructor deletes the array (if owned).
     */
    ~MaybeStackArray() { releaseArray(); }
    /**
     * Returns the array capacity (number of T items).
     * @return array capacity
     */
    int32_t getCapacity() const { return capacity; }
    /**
     * Access without ownership change.
     * @return the array pointer
     */
    T *getAlias() const { return ptr; }
    /**
     * Returns the array limit. Simple convenience method.
     * @return getAlias()+getCapacity()
     */
    T *getArrayLimit() const { return getAlias()+capacity; }
    // No "operator T *() const" because that can make
    // expressions like mbs[index] ambiguous for some compilers.
    /**
     * Array item access (const).
     * No index bounds check.
     * @param i array index
     * @return reference to the array item
     */
    const T &operator[](ptrdiff_t i) const { return ptr[i]; }
    /**
     * Array item access (writable).
     * No index bounds check.
     * @param i array index
     * @return reference to the array item
     */
    T &operator[](ptrdiff_t i) { return ptr[i]; }
    /**
     * Deletes the array (if owned) and aliases another one, no transfer of ownership.
     * If the arguments are illegal, then the current array is unchanged.
     * @param otherArray must not be NULL
     * @param otherCapacity must be >0
     */
    void aliasInstead(T *otherArray, int32_t otherCapacity) {
        if(otherArray!=NULL && otherCapacity>0) {
            releaseArray();
            ptr=otherArray;
            capacity=otherCapacity;
            needToRelease=FALSE;
        }
    }
    /**
     * Deletes the array (if owned) and allocates a new one, copying length T items.
     * Returns the new array pointer.
     * If the allocation fails, then the current array is unchanged and
     * this method returns NULL.
     * @param newCapacity can be less than or greater than the current capacity;
     *                    must be >0
     * @param length number of T items to be copied from the old array to the new one
     * @return the allocated array pointer, or NULL if the allocation failed
     */
    inline T *resize(int32_t newCapacity, int32_t length=0);
    /**
     * Gives up ownership of the array if owned, or else clones it,
     * copying length T items; resets itself to the internal stack array.
     * Returns NULL if the allocation failed.
     * @param length number of T items to copy when cloning,
     *        and capacity of the clone when cloning
     * @param resultCapacity will be set to the returned array's capacity (output-only)
     * @return the array pointer;
     *         caller becomes responsible for deleting the array
     */
    inline T *orphanOrClone(int32_t length, int32_t &resultCapacity);
private:
    T *ptr;
    int32_t capacity;
    UBool needToRelease;
    T stackArray[stackCapacity];
    void releaseArray() {
        if(needToRelease) {
            uprv_free(ptr);
        }
    }
    /* No comparison operators with other MaybeStackArray's. */
    bool operator==(const MaybeStackArray & /*other*/) {return FALSE;}
    bool operator!=(const MaybeStackArray & /*other*/) {return TRUE;}
    /* No ownership transfer: No copy constructor, no assignment operator. */
    MaybeStackArray(const MaybeStackArray & /*other*/) {}
    void operator=(const MaybeStackArray & /*other*/) {}

    // No heap allocation. Use only on the stack.
    //   (Declaring these functions private triggers a cascade of problems:
    //      MSVC insists on exporting an instantiation of MaybeStackArray, which
    //      requires that all functions be defined.
    //      An empty implementation of new() is rejected, it must return a value.
    //      Returning NULL is rejected by gcc for operator new.
    //      The expedient thing is just not to override operator new.
    //      While relatively pointless, heap allocated instances will function.
    // static void * U_EXPORT2 operator new(size_t size);
    // static void * U_EXPORT2 operator new[](size_t size);
#if U_HAVE_PLACEMENT_NEW
    // static void * U_EXPORT2 operator new(size_t, void *ptr);
#endif
};

template<typename T, int32_t stackCapacity>
inline T *MaybeStackArray<T, stackCapacity>::resize(int32_t newCapacity, int32_t length) {
    if(newCapacity>0) {
#if U_DEBUG && defined(UPRV_MALLOC_COUNT)
      ::fprintf(::stderr,"MaybeStacArray (resize) alloc %d * %lu\n", newCapacity,sizeof(T));
#endif
        T *p=(T *)uprv_malloc(newCapacity*sizeof(T));
        if(p!=NULL) {
            if(length>0) {
                if(length>capacity) {
                    length=capacity;
                }
                if(length>newCapacity) {
                    length=newCapacity;
                }
                uprv_memcpy(p, ptr, (size_t)length*sizeof(T));
            }
            releaseArray();
            ptr=p;
            capacity=newCapacity;
            needToRelease=TRUE;
        }
        return p;
    } else {
        return NULL;
    }
}

template<typename T, int32_t stackCapacity>
inline T *MaybeStackArray<T, stackCapacity>::orphanOrClone(int32_t length, int32_t &resultCapacity) {
    T *p;
    if(needToRelease) {
        p=ptr;
    } else if(length<=0) {
        return NULL;
    } else {
        if(length>capacity) {
            length=capacity;
        }
        p=(T *)uprv_malloc(length*sizeof(T));
#if U_DEBUG && defined(UPRV_MALLOC_COUNT)
      ::fprintf(::stderr,"MaybeStacArray (orphan) alloc %d * %lu\n", length,sizeof(T));
#endif
        if(p==NULL) {
            return NULL;
        }
        uprv_memcpy(p, ptr, (size_t)length*sizeof(T));
    }
    resultCapacity=length;
    ptr=stackArray;
    capacity=stackCapacity;
    needToRelease=FALSE;
    return p;
}

/**
 * Variant of MaybeStackArray that allocates a header struct and an array
 * in one contiguous memory block, using uprv_malloc() and uprv_free().
 * Provides internal memory with fixed array capacity. Can alias another memory
 * block or allocate one.
 * The stackCapacity is the number of T items in the internal memory,
 * not counting the H header.
 * Unlike LocalMemory and LocalArray, this class never adopts
 * (takes ownership of) another memory block.
 */
template<typename H, typename T, int32_t stackCapacity>
class MaybeStackHeaderAndArray {
public:
    /**
     * Default constructor initializes with internal H+T[stackCapacity] buffer.
     */
    MaybeStackHeaderAndArray() : ptr(&stackHeader), capacity(stackCapacity), needToRelease(FALSE) {}
    /**
     * Destructor deletes the memory (if owned).
     */
    ~MaybeStackHeaderAndArray() { releaseMemory(); }
    /**
     * Returns the array capacity (number of T items).
     * @return array capacity
     */
    int32_t getCapacity() const { return capacity; }
    /**
     * Access without ownership change.
     * @return the header pointer
     */
    H *getAlias() const { return ptr; }
    /**
     * Returns the array start.
     * @return array start, same address as getAlias()+1
     */
    T *getArrayStart() const { return reinterpret_cast<T *>(getAlias()+1); }
    /**
     * Returns the array limit.
     * @return array limit
     */
    T *getArrayLimit() const { return getArrayStart()+capacity; }
    /**
     * Access without ownership change. Same as getAlias().
     * A class instance can be used directly in expressions that take a T *.
     * @return the header pointer
     */
    operator H *() const { return ptr; }
    /**
     * Array item access (writable).
     * No index bounds check.
     * @param i array index
     * @return reference to the array item
     */
    T &operator[](ptrdiff_t i) { return getArrayStart()[i]; }
    /**
     * Deletes the memory block (if owned) and aliases another one, no transfer of ownership.
     * If the arguments are illegal, then the current memory is unchanged.
     * @param otherArray must not be NULL
     * @param otherCapacity must be >0
     */
    void aliasInstead(H *otherMemory, int32_t otherCapacity) {
        if(otherMemory!=NULL && otherCapacity>0) {
            releaseMemory();
            ptr=otherMemory;
            capacity=otherCapacity;
            needToRelease=FALSE;
        }
    }
    /**
     * Deletes the memory block (if owned) and allocates a new one,
     * copying the header and length T array items.
     * Returns the new header pointer.
     * If the allocation fails, then the current memory is unchanged and
     * this method returns NULL.
     * @param newCapacity can be less than or greater than the current capacity;
     *                    must be >0
     * @param length number of T items to be copied from the old array to the new one
     * @return the allocated pointer, or NULL if the allocation failed
     */
    inline H *resize(int32_t newCapacity, int32_t length=0);
    /**
     * Gives up ownership of the memory if owned, or else clones it,
     * copying the header and length T array items; resets itself to the internal memory.
     * Returns NULL if the allocation failed.
     * @param length number of T items to copy when cloning,
     *        and array capacity of the clone when cloning
     * @param resultCapacity will be set to the returned array's capacity (output-only)
     * @return the header pointer;
     *         caller becomes responsible for deleting the array
     */
    inline H *orphanOrClone(int32_t length, int32_t &resultCapacity);
private:
    H *ptr;
    int32_t capacity;
    UBool needToRelease;
    // stackHeader must precede stackArray immediately.
    H stackHeader;
    T stackArray[stackCapacity];
    void releaseMemory() {
        if(needToRelease) {
            uprv_free(ptr);
        }
    }
    /* No comparison operators with other MaybeStackHeaderAndArray's. */
    bool operator==(const MaybeStackHeaderAndArray & /*other*/) {return FALSE;}
    bool operator!=(const MaybeStackHeaderAndArray & /*other*/) {return TRUE;}
    /* No ownership transfer: No copy constructor, no assignment operator. */
    MaybeStackHeaderAndArray(const MaybeStackHeaderAndArray & /*other*/) {}
    void operator=(const MaybeStackHeaderAndArray & /*other*/) {}

    // No heap allocation. Use only on the stack.
    //   (Declaring these functions private triggers a cascade of problems;
    //    see the MaybeStackArray class for details.)
    // static void * U_EXPORT2 operator new(size_t size);
    // static void * U_EXPORT2 operator new[](size_t size);
#if U_HAVE_PLACEMENT_NEW
    // static void * U_EXPORT2 operator new(size_t, void *ptr);
#endif
};

template<typename H, typename T, int32_t stackCapacity>
inline H *MaybeStackHeaderAndArray<H, T, stackCapacity>::resize(int32_t newCapacity,
                                                                int32_t length) {
    if(newCapacity>=0) {
#if U_DEBUG && defined(UPRV_MALLOC_COUNT)
      ::fprintf(::stderr,"MaybeStackHeaderAndArray alloc %d + %d * %ul\n", sizeof(H),newCapacity,sizeof(T));
#endif
        H *p=(H *)uprv_malloc(sizeof(H)+newCapacity*sizeof(T));
        if(p!=NULL) {
            if(length<0) {
                length=0;
            } else if(length>0) {
                if(length>capacity) {
                    length=capacity;
                }
                if(length>newCapacity) {
                    length=newCapacity;
                }
            }
            uprv_memcpy(p, ptr, sizeof(H)+(size_t)length*sizeof(T));
            releaseMemory();
            ptr=p;
            capacity=newCapacity;
            needToRelease=TRUE;
        }
        return p;
    } else {
        return NULL;
    }
}

template<typename H, typename T, int32_t stackCapacity>
inline H *MaybeStackHeaderAndArray<H, T, stackCapacity>::orphanOrClone(int32_t length,
                                                                       int32_t &resultCapacity) {
    H *p;
    if(needToRelease) {
        p=ptr;
    } else {
        if(length<0) {
            length=0;
        } else if(length>capacity) {
            length=capacity;
        }
#if U_DEBUG && defined(UPRV_MALLOC_COUNT)
      ::fprintf(::stderr,"MaybeStackHeaderAndArray (orphan) alloc %ul + %d * %lu\n", sizeof(H),length,sizeof(T));
#endif
        p=(H *)uprv_malloc(sizeof(H)+length*sizeof(T));
        if(p==NULL) {
            return NULL;
        }
        uprv_memcpy(p, ptr, sizeof(H)+(size_t)length*sizeof(T));
    }
    resultCapacity=length;
    ptr=&stackHeader;
    capacity=stackCapacity;
    needToRelease=FALSE;
    return p;
}

U_NAMESPACE_END

#endif  /* __cplusplus */
#endif  /* CMEMORY_H */


text:
/**
 *
 * @class
 * @classdesc VIA Control Panel
 * @author Abhishek Dutta <adutta@robots.ox.ac.uk>
 * @date 16 May 2019
 *
 */

function _via_control_panel(control_panel_container, via) {
  this._ID = '_via_control_panel_';
  this.c   = control_panel_container;
  this.via = via;

  // registers on_event(), emit_event(), ... methods from
  // _via_event to let this module listen and emit events
  _via_event.call( this );

  this._init();
}

_via_control_panel.prototype._init = function(type) {
  this.c.innerHTML = '';

  var logo_panel = document.createElement('div');
  logo_panel.setAttribute('class', 'logo');
  logo_panel.innerHTML = 'VIA'
  this.c.appendChild(logo_panel);

  this.c.appendChild(this.via.vm.c);
  this._add_view_manager_tools();

  this._add_spacer();

  this._add_project_tools();

  this._add_spacer();

  this._add_region_shape_selector();

  this._add_spacer();

  var editor = _via_util_get_svg_button('micon_insertcomment', 'Show/Hide Attribute Editor');
  editor.addEventListener('click', function() {
    this.emit_event( 'editor_toggle', {});
  }.bind(this));
  this.c.appendChild(editor);

  this._add_spacer();

  if ( document.getElementById('micon_zoomin') ) {
    var zoom = _via_util_get_svg_button('micon_zoomin', 'Enable/disable magnifying glass to inspect finer details');
    zoom.addEventListener('click', function() {
      this.emit_event( 'zoom_toggle', {});
    }.bind(this));
    this.c.appendChild(zoom);
    this._add_spacer();
  }

  this._add_project_share_tools();

  this._add_spacer();

  var keyboard = _via_util_get_svg_button('micon_keyboard', 'Keyboard Shortcuts');
  keyboard.addEventListener('click', function() {
    _via_util_page_show('page_keyboard_shortcut');
  }.bind(this));
  this.c.appendChild(keyboard);

  var help = _via_util_get_svg_button('micon_help', 'About VIA');
  help.addEventListener('click', function() {
    _via_util_page_show('page_about');
  }.bind(this));
  this.c.appendChild(help);
}

_via_control_panel.prototype._add_spacer = function() {
  var spacer = document.createElement('div');
  spacer.setAttribute('class', 'spacer');
  this.c.appendChild(spacer);
}

_via_control_panel.prototype._add_view_manager_tools = function() {
  var prev_view = _via_util_get_svg_button('micon_navigate_prev', 'Show Previous File', 'show_prev');
  prev_view.addEventListener('click', this.via.vm._on_prev_view.bind(this.via.vm));
  this.c.appendChild(prev_view);

  var next_view = _via_util_get_svg_button('micon_navigate_next', 'Show Next File', 'show_next');
  next_view.addEventListener('click', this.via.vm._on_next_view.bind(this.via.vm));
  this.c.appendChild(next_view);

  var add_media_local = _via_util_get_svg_button('micon_add_circle', 'Add Audio or Video File in Local Computer', 'add_media_local');
  add_media_local.addEventListener('click', this.via.vm._on_add_media_local.bind(this.via.vm));
  this.c.appendChild(add_media_local);

  var add_media_bulk = _via_util_get_svg_button('micon_lib_add', 'Bulk add file URI ( e.g. file:///... or http://... ) contained in a local CSV file where each row is a remote or local filename.', 'add_media_bulk');
  //add_media_bulk.addEventListener('click', this.via.vm._on_add_media_bulk.bind(this.via.vm));
  add_media_bulk.addEventListener('click', function() {
    var action_map = {
      'via_page_fileuri_button_bulk_add':this._page_on_action_fileuri_bulk_add.bind(this),
    }
    _via_util_page_show('page_fileuri_bulk_add', action_map);
  }.bind(this));
  this.c.appendChild(add_media_bulk);

  var del_view = _via_util_get_svg_button('micon_remove_circle', 'Remove the Current File', 'remove_media');
  del_view.addEventListener('click', this.via.vm._on_del_view.bind(this.via.vm));
  this.c.appendChild(del_view);
}

_via_control_panel.prototype._add_region_shape_selector = function() {
  if ( document.getElementById('shape_point') === null ) {
    return;
  }

  var rect = _via_util_get_svg_button('shape_rectangle', 'Rectangle', 'RECTANGLE');
  rect.addEventListener('click', function() {
    this._set_region_shape('RECTANGLE');
  }.bind(this));
  this.c.appendChild(rect);

  var extreme_rect = _via_util_get_svg_button('shape_extreme_rectangle', 'Extreme rectangle is defined using four points along the boundary of a rectangular object.', 'EXTREME_RECTANGLE');
  extreme_rect.classList.add('shape_selector');
  extreme_rect.addEventListener('click', function() {
    this._set_region_shape('EXTREME_RECTANGLE');
  }.bind(this));
  this.c.appendChild(extreme_rect);

  var circle = _via_util_get_svg_button('shape_circle', 'Circle', 'CIRCLE');
  circle.addEventListener('click', function() {
    this._set_region_shape('CIRCLE');
  }.bind(this));
  this.c.appendChild(circle);

  var extreme_circle = _via_util_get_svg_button('shape_extreme_circle', 'Extreme circle is defined using any three points along the circumference of a circular object.', 'EXTREME_CIRCLE');
  extreme_circle.addEventListener('click', function() {
    this._set_region_shape('EXTREME_CIRCLE');
  }.bind(this));
  this.c.appendChild(extreme_circle);

  var ellipse = _via_util_get_svg_button('shape_ellipse', 'Ellipse', 'ELLIPSE');
  ellipse.addEventListener('click', function() {
    this._set_region_shape('ELLIPSE');
  }.bind(this));
  this.c.appendChild(ellipse);

  var line = _via_util_get_svg_button('shape_line', 'Line', 'LINE');
  line.addEventListener('click', function() {
    this._set_region_shape('LINE');
  }.bind(this));
  this.c.appendChild(line);

  var polygon = _via_util_get_svg_button('shape_polygon', 'Polygon', 'POLYGON');
  polygon.addEventListener('click', function() {
    this._set_region_shape('POLYGON');
  }.bind(this));
  this.c.appendChild(polygon);

  var polyline = _via_util_get_svg_button('shape_polyline', 'Polyline', 'POLYLINE');
  polyline.addEventListener('click', function() {
    this._set_region_shape('POLYLINE');
  }.bind(this));
  this.c.appendChild(polyline);

  var point = _via_util_get_svg_button('shape_point', 'Point', 'POINT');
  point.addEventListener('click', function() {
    this._set_region_shape('POINT');
  }.bind(this));
  this.c.appendChild(point);

  this.shape_selector_list = { 'POINT':point, 'RECTANGLE':rect, 'EXTREME_RECTANGLE':extreme_rect, 'CIRCLE':circle, 'EXTREME_CIRCLE':extreme_circle, 'ELLIPSE':ellipse, 'LINE':line, 'POLYGON':polygon, 'POLYLINE':polyline };
}

_via_control_panel.prototype._set_region_shape = function(shape) {
  this.emit_event( 'region_shape', {'shape':shape});
  for ( var si in this.shape_selector_list ) {
    if ( si === shape ) {
      this.shape_selector_list[si].classList.add('svg_button_selected');
    } else {
      this.shape_selector_list[si].classList.remove('svg_button_selected');
    }
  }
}

_via_control_panel.prototype._add_project_tools = function() {
  var load = _via_util_get_svg_button('micon_open', 'Open a VIA Project');
  load.addEventListener('click', function() {
    _via_util_file_select_local(_VIA_FILE_SELECT_TYPE.JSON, this._project_load_on_local_file_select.bind(this), false);
  }.bind(this));
  this.c.appendChild(load);

  var save = _via_util_get_svg_button('micon_save', 'Save current VIA Project');
  save.addEventListener('click', function() {
    this.via.d.project_save();
  }.bind(this));
  this.c.appendChild(save);

  var import_export_annotation = _via_util_get_svg_button('micon_import_export', 'Import or Export Annotations');
  import_export_annotation.addEventListener('click', this._page_show_import_export.bind(this));
  this.c.appendChild(import_export_annotation);
}

_via_control_panel.prototype._page_show_import_export = function(d) {
  var action_map = {
    'via_page_button_import':this._page_on_action_import.bind(this),
    'via_page_button_export':this._page_on_action_export.bind(this),
  }
  _via_util_page_show('page_import_export', action_map);
}

_via_control_panel.prototype._page_on_action_import = function(d) {
  if ( d._action_id === 'via_page_button_import' ) {
    if ( d.via_page_import_pid !== '' ) {
      this.via.s._project_pull(d.via_page_import_pid).then( function(remote_rev) {
        try {
          var project = JSON.parse(remote_rev);
          // clear remote project identifiers
          project.project.pid = _VIA_PROJECT_ID_MARKER;
          project.project.rev = _VIA_PROJECT_REV_ID_MARKER;
          project.project.rev_timestamp = _VIA_PROJECT_REV_TIMESTAMP_MARKER;
          this.via.d.project_load_json(project);
        }
        catch(e) {
          _via_util_msg_show('Malformed response from server: ' + e);
        }
      }.bind(this), function(err) {
        _via_util_msg_show(err + ': ' + d.via_page_import_pid);
      }.bind(this));
      return;
    }

    if ( d.via_page_import_via2_project_json.length === 1 ) {
      _via_util_load_text_file(d.via_page_import_via2_project_json[0],
                               this._project_import_via2_on_local_file_read.bind(this)
                              );
      return;
    }
    _via_util_msg_show('To import an existing shared project, you must enter its project-id.');
  }
}

_via_control_panel.prototype._page_on_action_export = function(d) {
  if ( d._action_id === 'via_page_button_export' ) {
    this.via.ie.export_to_file(d.via_page_export_format);
  }
}

_via_control_panel.prototype._project_load_on_local_file_select = function(e) {
  if ( e.target.files.length === 1 ) {
    _via_util_load_text_file(e.target.files[0], this._project_load_on_local_file_read.bind(this));
  }
}

_via_control_panel.prototype._project_load_on_local_file_read = function(project_data_str) {
  this.via.d.project_load(project_data_str);
}

_via_control_panel.prototype._project_import_via2_on_local_file_read = function(project_data_str) {
  this.via.d.project_import_via2_json(project_data_str);
}

_via_control_panel.prototype._add_project_share_tools = function() {
  if ( this.via.s ) {
    var share = _via_util_get_svg_button('micon_share', 'Information about sharing this VIA project with others for collaborative annotation');
    share.addEventListener('click', function() {
      this._share_show_info();
    }.bind(this));
    var push = _via_util_get_svg_button('micon_upload', 'Push (i.e. share this project or share your updates made to this project)');
    push.addEventListener('click', function() {
      this.via.s.push();
    }.bind(this));

    var pull = _via_util_get_svg_button('micon_download', 'Pull (i.e. open a shared project or fetch updates for the current project)');
    pull.addEventListener('click', function() {
      this._share_show_pull();
    }.bind(this));

    this.c.appendChild(share);
    this.c.appendChild(push);
    this.c.appendChild(pull);
  }
}

_via_control_panel.prototype._share_show_info = function() {
  if ( this.via.d.project_is_remote() ) {
    this.via.s.exists(this.via.d.store.project.pid).then( function() {
      this.via.s._project_pull(this.via.d.store.project.pid).then( function(ok) {
        try {
          var d = JSON.parse(ok);
          var remote_rev_timestamp = new Date( parseInt(d.project.rev_timestamp) );
          var local_rev_timestamp = new Date( parseInt(this.via.d.store.project.rev_timestamp) );

          var pinfo = '
';
          pinfo += '
Project Id	' + d.project.pid + '
';
          pinfo += '
Remote Revision	' + d.project.rev + ' (' + remote_rev_timestamp.toUTCString() + ')
';
          pinfo += '
Local Revision	' + this.via.d.store.project.rev + ' (' + local_rev_timestamp.toUTCString() + ')
';
          pinfo += '
';
          if ( d.project.rev !== this.via.d.store.project.rev ) {
            pinfo += '
Your version of this project is old. Press <svg class="svg_icon" onclick="" viewbox="0 0 24 24"><use xlink:href="#micon_download"></use></svg> to fetch the most recent version of this project.
';
          } else {
            pinfo += '
You already have the latest revision of this project.
';
          }

          document.getElementById('via_page_share_project_info').innerHTML = pinfo;
          document.getElementById('via_page_share_project_id').innerHTML = d.project.pid;
          _via_util_page_show('page_share_already_shared');
        }
        catch(e) {
          console.log(e)
          _via_util_msg_show('Malformed server response.' + e);
        }
      }.bind(this), function(pull_err) {
        _via_util_msg_show('Failed to pull project.');
        console.warn(pull_err);
      }.bind(this));
    }.bind(this), function(exists_err) {
      _via_util_page_show('page_share_not_shared_yet');
      console.warn(exists_err);
    }.bind(this));
  } else {
    _via_util_page_show('page_share_not_shared_yet');
  }
}

_via_control_panel.prototype._share_show_pull = function() {
  if ( this.via.d.project_is_remote() ) {
    // check if remote project has newer version
    this.via.s._project_pull(this.via.d.store.project.pid).then( function(ok) {
      try {
        var d = JSON.parse(ok);
        if ( d.project.rev === this.via.d.store.project.rev ) {
          _via_util_msg_show('You already have the latest revision of this project');
          return;
        } else {
          this.via.d.project_merge_rev(d);
        }
      }
      catch(e) {
        _via_util_msg_show('Malformed response from server.');
        console.warn(e);
      }
    }.bind(this), function(err) {
      _via_util_msg_show('Failed to pull project.');
      console.warn(err);
    }.bind(this));
  } else {
    var action_map = {
      'via_page_button_open_shared':this._page_on_action_open_shared.bind(this),
    }
    _via_util_page_show('page_share_open_shared', action_map);
  }
}

_via_control_panel.prototype._page_on_action_open_shared = function(d) {
  if ( d._action_id === 'via_page_button_open_shared' ) {
    this.via.s.pull(d.via_page_input_pid);
  }
}

_via_control_panel.prototype._page_on_action_fileuri_bulk_add = function(d) {
  if ( d.via_page_fileuri_urilist.length ) {
    this.fileuri_bulk_add_from_url_list(d.via_page_fileuri_urilist);
  }

  if ( d.via_page_fileuri_importfile.length === 1 ) {
    switch( parseInt(d.via_page_fileuri_filetype) ) {
    case _VIA_FILE_TYPE.IMAGE:
      _via_util_load_text_file(d.via_page_fileuri_importfile[0], this.fileuri_bulk_add_image_from_file.bind(this));
      break;
    case _VIA_FILE_TYPE.AUDIO:
      _via_util_load_text_file(d.via_page_fileuri_importfile[0], this.fileuri_bulk_add_audio_from_file.bind(this));
      break;
    case _VIA_FILE_TYPE.VIDEO:
      _via_util_load_text_file(d.via_page_fileuri_importfile[0], this.fileuri_bulk_add_video_from_file.bind(this));
      break;
    default:
      _via_util_load_text_file(d.via_page_fileuri_importfile[0], this.fileuri_bulk_add_auto_from_file.bind(this));
    }

  }
}

_via_control_panel.prototype.fileuri_bulk_add_image_from_file = function(uri_list_str) {
  this.fileuri_bulk_add_from_url_list(uri_list_str, _VIA_FILE_TYPE.IMAGE);
}

_via_control_panel.prototype.fileuri_bulk_add_audio_from_file = function(uri_list_str) {
  this.fileuri_bulk_add_from_url_list(uri_list_str, _VIA_FILE_TYPE.AUDIO);
}

_via_control_panel.prototype.fileuri_bulk_add_video_from_file = function(uri_list_str) {
  this.fileuri_bulk_add_from_url_list(uri_list_str, _VIA_FILE_TYPE.VIDEO);
}

_via_control_panel.prototype.fileuri_bulk_add_auto_from_file = function(uri_list_str) {
  this.fileuri_bulk_add_from_url_list(uri_list_str, 0);
}

_via_control_panel.prototype.fileuri_bulk_add_from_url_list = function(uri_list_str, type) {
  var uri_list = uri_list_str.split('\n');
  if ( uri_list.length ) {
    var filelist = [];
    for ( var i = 0; i < uri_list.length; ++i ) {
      if ( uri_list[i] === '' ||
           uri_list[i] === ' ' ||
           uri_list[i] === '\n'
         ) {
        continue; // skip
      }
      var filetype;
      if ( type === 0 || typeof(type) === 'undefined' ) {
        filetype = _via_util_infer_file_type_from_filename(uri_list[i]);
      } else {
        filetype = type;
      }

      filelist.push({ 'fname':uri_list[i],
                      'type':filetype,
                      'loc':_via_util_infer_file_loc_from_filename(uri_list[i]),
                      'src':uri_list[i],
                    });
    }
    this.via.vm._file_add_from_filelist(filelist);
  }
}


text:
package generators

import (
	"fmt"
	"io"

	args2 "github.com/rancher/wrangler/pkg/controller-gen/args"
	"k8s.io/gengo/args"
	"k8s.io/gengo/generator"
	"k8s.io/gengo/namer"
)

func GroupInterfaceGo(group string, args *args.GeneratorArgs, customArgs *args2.CustomArgs) generator.Generator {
	return &interfaceGo{
		group:      group,
		args:       args,
		customArgs: customArgs,
		DefaultGen: generator.DefaultGen{
			OptionalName: "interface",
			OptionalBody: []byte(interfaceBody),
		},
	}
}

type interfaceGo struct {
	generator.DefaultGen

	group      string
	args       *args.GeneratorArgs
	customArgs *args2.CustomArgs
}

func (f *interfaceGo) Imports(*generator.Context) []string {
	group := f.customArgs.Options.Groups[f.group]

	packages := []string{
		GenericPackage,
		fmt.Sprintf("clientset \"%s\"", group.ClientSetPackage),
		fmt.Sprintf("informers \"%s/%s\"", group.InformersPackage, groupPackageName(f.group, group.PackageName)),
	}

	for gv := range f.customArgs.TypesByGroup {
		if gv.Group != f.group {
			continue
		}

		packages = append(packages, fmt.Sprintf("%s \"%s/controllers/%s/%s\"", gv.Version, f.customArgs.Package, groupPackageName(gv.Group, ""), gv.Version))
	}

	return packages
}

func (f *interfaceGo) Init(c *generator.Context, w io.Writer) error {
	sw := generator.NewSnippetWriter(w, c, "{{", "}}")
	sw.Do("type Interface interface {\n", nil)
	for gv := range f.customArgs.TypesByGroup {
		if gv.Group != f.group {
			continue
		}

		sw.Do("{{.upperVersion}}() {{.version}}.Interface\n", map[string]interface{}{
			"upperVersion": namer.IC(gv.Version),
			"version":      gv.Version,
		})
	}
	sw.Do("}\n", nil)

	if err := f.DefaultGen.Init(c, w); err != nil {
		return err
	}

	for gv := range f.customArgs.TypesByGroup {
		if gv.Group != f.group {
			continue
		}

		m := map[string]interface{}{
			"upperGroup":   upperLowercase(f.group),
			"upperVersion": namer.IC(gv.Version),
			"version":      gv.Version,
		}
		sw.Do("\nfunc (g *group) {{.upperVersion}}() {{.version}}.Interface {\n", m)
		sw.Do("return {{.version}}.New(g.controllerManager, g.client.{{.upperGroup}}{{.upperVersion}}(), g.informers.{{.upperVersion}}())\n", m)
		sw.Do("}\n", m)
	}

	return sw.Error()
}

var interfaceBody = `
type group struct {
	controllerManager *generic.ControllerManager
	informers         informers.Interface
	client            clientset.Interface
}

// New returns a new Interface.
func New(controllerManager *generic.ControllerManager, informers informers.Interface,
	client clientset.Interface) Interface {
	return &group{
		controllerManager: controllerManager,
		informers:         informers,
		client:            client,
	}
}
`


text:
using namespace Leap;

class LeapMotionListener : public Listener
{
public:
    LeapMotionListener();
    void onConnect(const Controller &controller);
    void onFrame(const Controller& controller);
    void update();

private:
    CommandServer *server;

    // LeapMotion
    Hand handLeft;
    Hand handRight;

    int pitch = 0;
    int roll = 0;
    int speed = 0;
    int tmpPitch= 0;
    int tmpRoll = 0;
    int tmpSpeed = 0;

    bool isLoopingUp = false;
    bool isLoopingRight = false;
    bool isLoopingLeft = false;
    bool tmpIsLoopingUp = false;
    bool tmpIsLoopingRight = false;
    bool tmpIsLoopingLeft = false;

    bool initHandPosition = false;
    float handPosition;

    int cptFrame = 0;
};

#endif // LEAPMOTIONLISTENER_H


text:
package com.chinare.axe.swagger;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration;

/**
 * @author 王贵源 wangguiyuan@sinosoft.com.cn
 *
 */
@Configuration
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
@Import({
         Swagger2DocumentationConfiguration.class,
         BeanValidatorPluginsConfiguration.class
})
public class Swagger2Configuration {}


text:
RF-InDesign-Extended
====================

A framework for customising the menus and context menus in Adobe InDesign by placing script files in a directory structure (and some other stuff, see below).

See the wiki for [installation instructions](https://github.com/ryecroft/RF-InDesign-Extended/wiki#How%20do%20I%20install%20it?)

###What does it do?
By placing script files in a directory structure, you can:
* Create custom [menu-bar menus](https://github.com/ryecroft/RF-InDesign-Extended/wiki/menu-bar-menus).

![Rockfax application menu](https://github.com/ryecroft/RF-InDesign-Extended/wiki/images/rockfax-menu-in-indesign.png)

* Create custom [right-click menus](https://github.com/ryecroft/RF-InDesign-Extended/wiki/right-click-menus) based on the current selection in InDesign.

![Rockfax context menu](https://github.com/ryecroft/RF-InDesign-Extended/wiki/images/rockfax-context-menu.jpg "The final entry in this context menu was added based on the current selection")

* Add [application-level event handlers](https://github.com/ryecroft/RF-InDesign-Extended/wiki/application-level-event-handlers).

* Included in the event handlers is [Correct Layer](https://github.com/ryecroft/RF-InDesign-Extended/wiki/correct-layer) a script that sets the current layer based on your current object style.
* Also included are several useful scripts that we use daily at Rockfax (see [Included Scripts](https://github.com/ryecroft/RF-InDesign-Extended/wiki/included-scripts) for details).


text:
/** PURE_IMPORTS_START .._.._Observable,.._.._operator_multicast PURE_IMPORTS_END */
import { Observable } from '../../Observable';
import { multicast } from '../../operator/multicast';
Observable.prototype.multicast = multicast;
//# sourceMappingURL=multicast.js.map


text:
describe Avromatic::Model::Builder, 'validation' do
  let(:schema) { schema_store.find(schema_name) }
  let(:test_class) do
    described_class.model(schema_name: schema_name)
  end
  let(:attribute_names) do
    test_class.attribute_definitions.keys.map(&:to_s)
  end

  context "required" do
    context "primitive types" do
      let(:schema_name) { 'test.primitive_types' }
      let(:valid_attributes) do
        {
          s: 'foo',
          b: '123',
          tf: true,
          i: 777,
          l: 123456789,
          f: 0.5,
          d: 1.0 / 3.0,
          n: nil,
          fx: '1234567',
          e: 'A'
        }
      end

      it "validates that required fields must be present" do
        instance = test_class.new
        assert_model_invalid(instance, 's', 'tf')
      end

      it "passes validation if all required fields are present" do
        instance = test_class.new(valid_attributes)
        assert_model_valid(instance)
      end

      context "boolean" do
        it "allows a boolean field to be false" do
          instance = test_class.new(valid_attributes.merge(tf: false))
          assert_model_valid(instance)
        end
      end
    end

    context "array" do
      let(:schema) do
        Avro::Builder.build_schema do
          record :has_array do
            required :a, :array, items: :int
          end
        end
      end
      let(:test_class) { described_class.model(schema: schema) }

      it "validates that a required array is not nil" do
        instance = test_class.new(a: nil)
        assert_model_invalid(instance, 'a')
      end

      it "allows a required array to be empty" do
        instance = test_class.new(a: [])
        assert_model_valid(instance)
      end

      it "passes validation if all required fields are present" do
        instance = test_class.new(a: [1])
        assert_model_valid(instance)
      end
    end

    context "map" do
      let(:schema) do
        Avro::Builder.build_schema do
          record :has_map do
            required :m, :map, values: :int
          end
        end
      end
      let(:test_class) { described_class.model(schema: schema) }

      it "validates that a required map is not nil" do
        instance = test_class.new(m: nil)
        assert_model_invalid(instance, 'm')
      end

      it "allows a required map to be empty" do
        instance = test_class.new(m: {})
        assert_model_valid(instance)
      end

      it "passes validation if all required fields are present" do
        instance = test_class.new(m: { 'foo' => 1 })
        assert_model_valid(instance)
      end
    end

    context "nested records" do
      let(:schema) do
        Avro::Builder.build_schema do
          record :has_record do
            required :sub, :record, type_name: 'sub_type' do
              required :i, :int
              required :s, :string
            end
          end
        end
      end
      let(:test_class) { described_class.model(schema: schema) }

      it "validates nested records" do
        instance = test_class.new(sub: test_class.nested_models['sub_type'].new)
        assert_model_invalid(instance, 'sub.i', 'sub.s')
      end

      it "validates nested records initialized with a hash" do
        instance = test_class.new(sub: { i: 0 })
        assert_model_invalid(instance, 'sub.s')
      end

      it "passes validation if all required fields are present" do
        instance = test_class.new(sub: { i: 0, s: 'f' })
        assert_model_valid(instance)
      end

      context "doubly nested record" do
        let(:schema) do
          Avro::Builder.build_schema do
            record :outer do
              required :sub, :record, type_name: 'level1' do
                required :sub_sub, :record, type_name: 'level2' do
                  required :l, :long
                end
              end
            end
          end
        end

        it "validates multiple levels of nesting" do
          level1 = test_class.nested_models['level1']
          level2 = test_class.nested_models['level2']
          instance = test_class.new(sub: level1.new(sub_sub: level2.new))
          assert_model_invalid(instance, 'sub.sub_sub.l')
        end

        it "validates multiple levels of nesting initialized with a hash" do
          instance = test_class.new(sub: { sub_sub: {} })
          assert_model_invalid(instance, 'sub.sub_sub.l')
        end

        it "passes validation if all required fields are present" do
          instance = test_class.new(sub: { sub_sub: { l: 1 } })
          assert_model_valid(instance)
        end
      end

      context "array of records" do
        let(:schema) do
          Avro::Builder.build_schema do
            record :x_and_y do
              required :x, :int
              required :y, :int
            end

            record :array_of_records do
              required :ary, :array, items: :x_and_y
            end
          end
        end

        it "validates records in an array" do
          nested_model = test_class.nested_models['x_and_y']
          data = [nested_model.new,
                  nested_model.new(x: 1),
                  nested_model.new(y: 2)]
          instance = test_class.new(ary: data)
          assert_model_invalid(instance, 'ary[0].x', 'ary[0].y', 'ary[1].y', 'ary[2].x')
        end

        it "validates records in an array initialized with hashes" do
          data = [{},
                  { x: 1 },
                  { y: 2 }]
          instance = test_class.new(ary: data)
          assert_model_invalid(instance, 'ary[0].x', 'ary[0].y', 'ary[1].y', 'ary[2].x')
        end

        it "passes validation if all required fields are present" do
          instance = test_class.new(ary: [{ x: 1, y: 2 }])
          assert_model_valid(instance)
        end
      end

      context "nested arrays of records" do
        let(:schema) do
          Avro::Builder.build_schema do
            record :elt do
              required :s, :string
            end

            record :with_matrix do
              required :m, array(array(:elt))
            end
          end
        end
        let(:nested_model) { test_class.nested_models['elt'] }

        it "validates deeply nested records" do
          data = [
            [nested_model.new(s: 'a'), nested_model.new],
            [nested_model.new(s: 'c'), nested_model.new, nested_model.new(s: 'b')]
          ]
          instance = test_class.new(m: data)
          assert_model_invalid(instance, 'm[0][1].s', 'm[1][1].s')
        end

        it "passes validation if all required fields are present" do
          instance = test_class.new(m: [[{ s: 's' }]])
          assert_model_valid(instance)
        end
      end

      context "map of records" do
        let(:schema) do
          Avro::Builder.build_schema do
            record :x_and_y do
              required :x, :int
              required :y, :int
            end

            record :array_of_records do
              required :map, :map, values: :x_and_y
            end
          end
        end

        it "validates records in a map" do
          nested_model = test_class.nested_models['x_and_y']
          data = {
            a: nested_model.new(y: 3),
            b: nested_model.new,
            c: nested_model.new(x: 4)
          }
          instance = test_class.new(map: data)
          assert_model_invalid(instance, "map['a'].x", "map['b'].x", "map['b'].y", "map['c'].y")
        end

        it "validates records in a map initialized with hashes" do
          data = {
            a: { y: 3 },
            b: {},
            c: { x: 4 }
          }
          instance = test_class.new(map: data)
          assert_model_invalid(instance, "map['a'].x", "map['b'].x", "map['b'].y", "map['c'].y")
        end

        it "passes validation if all required fields are present" do
          instance = test_class.new(map: { a: { x: 0, y: 1 } })
          assert_model_valid(instance)
        end
      end

      context "record in a union" do
        let(:schema) do
          Avro::Builder.build_schema do
            record :x_and_y do
              required :x, :int
              required :y, :int
            end

            record :with_union do
              required :u, :union, types: [:x_and_y, :string]
            end
          end
        end

        it "validates a record in a union" do
          expect(test_class.new(u: 'foo')).to be_valid
          instance = test_class.new(u: test_class.nested_models['x_and_y'].new)
          assert_model_invalid(instance, 'u.x', 'u.y')
        end
      end
    end
  end

  context "optional" do
    let(:schema_name) { 'test.with_union' }

    it "does not require optional fields to be present" do
      instance = test_class.new
      assert_model_valid(instance)
    end
  end

  # Tests both ActiveModel validation and validation during serialization
  def assert_model_valid(instance)
    instance.value_attributes_for_avro
    expect(instance).to be_valid
  end

  # Tests both ActiveModel validation and validation during serialization
  def assert_model_invalid(instance, *missing_attributes)
    expect do
      instance.value_attributes_for_avro
    end.to raise_error do |error|
      expect(error).to be_a_kind_of(Avromatic::Model::ValidationError)
      missing_attributes.each do |missing_attribute|
        expect(error.message).to include(missing_attribute)
      end
    end

    expect(instance).to be_invalid
    missing_attributes.each do |missing_attribute|
      expect(instance.errors[:base]).to include("#{missing_attribute} can't be nil")
    end
  end
end


text:
FROM quay.io/terraform-docs/terraform-docs:0.16.0

RUN apk add --no-cache git

COPY ./entrypoint.sh /opt/entrypoint.sh

ENTRYPOINT ["/opt/entrypoint.sh"]


text:
@interface FMRecordProgressView : UIView
- (instancetype)initWithFrame:(CGRect)frame;
-(void)updateProgressWithValue:(CGFloat)progress;
-(void)resetProgress;

@end


text:
#include <aws/kinesisanalyticsv2/model/ApplicationVersionSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace KinesisAnalyticsV2
{
namespace Model
{

ApplicationVersionSummary::ApplicationVersionSummary() :
    m_applicationVersionId(0),
    m_applicationVersionIdHasBeenSet(false),
    m_applicationStatus(ApplicationStatus::NOT_SET),
    m_applicationStatusHasBeenSet(false)
{
}

ApplicationVersionSummary::ApplicationVersionSummary(JsonView jsonValue) :
    m_applicationVersionId(0),
    m_applicationVersionIdHasBeenSet(false),
    m_applicationStatus(ApplicationStatus::NOT_SET),
    m_applicationStatusHasBeenSet(false)
{
  *this = jsonValue;
}

ApplicationVersionSummary& ApplicationVersionSummary::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ApplicationVersionId"))
  {
    m_applicationVersionId = jsonValue.GetInt64("ApplicationVersionId");

    m_applicationVersionIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationStatus"))
  {
    m_applicationStatus = ApplicationStatusMapper::GetApplicationStatusForName(jsonValue.GetString("ApplicationStatus"));

    m_applicationStatusHasBeenSet = true;
  }

  return *this;
}

JsonValue ApplicationVersionSummary::Jsonize() const
{
  JsonValue payload;

  if(m_applicationVersionIdHasBeenSet)
  {
   payload.WithInt64("ApplicationVersionId", m_applicationVersionId);

  }

  if(m_applicationStatusHasBeenSet)
  {
   payload.WithString("ApplicationStatus", ApplicationStatusMapper::GetNameForApplicationStatus(m_applicationStatus));
  }

  return payload;
}

} // namespace Model
} // namespace KinesisAnalyticsV2
} // namespace Aws


text:
package com.orientechnologies.orient.core.storage.index.sbtree.local.v2;

import com.orientechnologies.common.directmemory.OByteBufferPool;
import com.orientechnologies.common.directmemory.ODirectMemoryAllocator.Intention;
import com.orientechnologies.common.directmemory.OPointer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.serialization.serializer.binary.impl.OLinkSerializer;
import com.orientechnologies.orient.core.storage.cache.OCacheEntry;
import com.orientechnologies.orient.core.storage.cache.OCacheEntryImpl;
import com.orientechnologies.orient.core.storage.cache.OCachePointer;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.TreeSet;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author Andrey Lomakin (a.lomakin-at-orientdb.com)
 * @since 12.08.13
 */
public class SBTreeNonLeafBucketV2Test {
  @Test
  public void testInitialization() {
    final OByteBufferPool bufferPool = OByteBufferPool.instance(null);
    final OPointer pointer = bufferPool.acquireDirect(true, Intention.TEST);

    OCachePointer cachePointer = new OCachePointer(pointer, bufferPool, 0, 0);
    OCacheEntry cacheEntry = new OCacheEntryImpl(0, 0, cachePointer, false, null);
    cacheEntry.acquireExclusiveLock();
    cachePointer.incrementReferrer();

    OSBTreeBucketV2<Long, OIdentifiable> treeBucket = new OSBTreeBucketV2<>(cacheEntry);
    treeBucket.init(false);

    Assert.assertEquals(treeBucket.size(), 0);
    Assert.assertFalse(treeBucket.isLeaf());

    treeBucket = new OSBTreeBucketV2<>(cacheEntry);
    Assert.assertEquals(treeBucket.size(), 0);
    Assert.assertFalse(treeBucket.isLeaf());
    Assert.assertEquals(treeBucket.getLeftSibling(), -1);
    Assert.assertEquals(treeBucket.getRightSibling(), -1);

    cacheEntry.releaseExclusiveLock();
    cachePointer.decrementReferrer();
  }

  @Test
  public void testSearch() {
    long seed = System.currentTimeMillis();
    System.out.println("testSearch seed : " + seed);

    TreeSet<Long> keys = new TreeSet<>();
    Random random = new Random(seed);

    while (keys.size() < 2 * OSBTreeBucketV2.MAX_PAGE_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
      keys.add(random.nextLong());
    }

    final OByteBufferPool bufferPool = OByteBufferPool.instance(null);
    final OPointer pointer = bufferPool.acquireDirect(true, Intention.TEST);

    OCachePointer cachePointer = new OCachePointer(pointer, bufferPool, 0, 0);
    OCacheEntry cacheEntry = new OCacheEntryImpl(0, 0, cachePointer, false, null);
    cacheEntry.acquireExclusiveLock();
    cachePointer.incrementReferrer();

    OSBTreeBucketV2<Long, OIdentifiable> treeBucket = new OSBTreeBucketV2<>(cacheEntry);
    treeBucket.init(false);

    int index = 0;
    Map<Long, Integer> keyIndexMap = new HashMap<>();
    for (Long key : keys) {
      if (!treeBucket.addNonLeafEntry(
          index,
          OLongSerializer.INSTANCE.serializeNativeAsWhole(key),
          random.nextInt(Integer.MAX_VALUE),
          random.nextInt(Integer.MAX_VALUE),
          true)) {
        break;
      }

      keyIndexMap.put(key, index);
      index++;
    }

    Assert.assertEquals(treeBucket.size(), keyIndexMap.size());

    for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
      int bucketIndex = treeBucket.find(keyIndexEntry.getKey(), OLongSerializer.INSTANCE);
      Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
    }

    long prevRight = -1;
    for (int i = 0; i < treeBucket.size(); i++) {
      OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
          treeBucket.getEntry(i, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);
      if (prevRight > 0) {
        Assert.assertEquals(entry.leftChild, prevRight);
      }

      prevRight = entry.rightChild;
    }

    long prevLeft = -1;
    for (int i = treeBucket.size() - 1; i >= 0; i--) {
      OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
          treeBucket.getEntry(i, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);

      if (prevLeft > 0) Assert.assertEquals(entry.rightChild, prevLeft);

      prevLeft = entry.leftChild;
    }

    cacheEntry.releaseExclusiveLock();
    cachePointer.decrementReferrer();
  }

  @Test
  public void testShrink() {
    long seed = System.currentTimeMillis();
    System.out.println("testShrink seed : " + seed);

    TreeSet<Long> keys = new TreeSet<>();
    Random random = new Random(seed);

    while (keys.size() < 2 * OSBTreeBucketV2.MAX_PAGE_SIZE_BYTES / OLongSerializer.LONG_SIZE) {
      keys.add(random.nextLong());
    }

    final OByteBufferPool bufferPool = OByteBufferPool.instance(null);
    final OPointer pointer = bufferPool.acquireDirect(true, Intention.TEST);

    OCachePointer cachePointer = new OCachePointer(pointer, bufferPool, 0, 0);
    OCacheEntry cacheEntry = new OCacheEntryImpl(0, 0, cachePointer, false, null);
    cacheEntry.acquireExclusiveLock();

    cachePointer.incrementReferrer();

    OSBTreeBucketV2<Long, OIdentifiable> treeBucket = new OSBTreeBucketV2<>(cacheEntry);
    treeBucket.init(false);

    int index = 0;
    for (Long key : keys) {
      if (!treeBucket.addNonLeafEntry(
          index, OLongSerializer.INSTANCE.serializeNativeAsWhole(key), index, index + 1, true)) {
        break;
      }

      index++;
    }

    int originalSize = treeBucket.size();

    treeBucket.shrink(treeBucket.size() / 2, OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);
    Assert.assertEquals(treeBucket.size(), index / 2);

    index = 0;
    final Map<Long, Integer> keyIndexMap = new HashMap<>();

    Iterator<Long> keysIterator = keys.iterator();
    while (keysIterator.hasNext() && index < treeBucket.size()) {
      Long key = keysIterator.next();
      keyIndexMap.put(key, index);
      index++;
    }

    for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
      int bucketIndex = treeBucket.find(keyIndexEntry.getKey(), OLongSerializer.INSTANCE);
      Assert.assertEquals(bucketIndex, (int) keyIndexEntry.getValue());
    }

    for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
      OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
          treeBucket.getEntry(
              keyIndexEntry.getValue(), OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);

      Assert.assertEquals(
          entry,
          new OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable>(
              keyIndexEntry.getValue(),
              keyIndexEntry.getValue() + 1,
              keyIndexEntry.getKey(),
              null));
    }

    int keysToAdd = originalSize - treeBucket.size();
    int addedKeys = 0;
    while (keysIterator.hasNext() && index < originalSize) {
      Long key = keysIterator.next();

      if (!treeBucket.addNonLeafEntry(
          index, OLongSerializer.INSTANCE.serializeNativeAsWhole(key), index, index + 1, true)) {
        break;
      }

      keyIndexMap.put(key, index);
      index++;
      addedKeys++;
    }

    for (Map.Entry<Long, Integer> keyIndexEntry : keyIndexMap.entrySet()) {
      OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable> entry =
          treeBucket.getEntry(
              keyIndexEntry.getValue(), OLongSerializer.INSTANCE, OLinkSerializer.INSTANCE);

      Assert.assertEquals(
          entry,
          new OSBTreeBucketV2.SBTreeEntry<Long, OIdentifiable>(
              keyIndexEntry.getValue(),
              keyIndexEntry.getValue() + 1,
              keyIndexEntry.getKey(),
              null));
    }

    Assert.assertEquals(treeBucket.size(), originalSize);
    Assert.assertEquals(addedKeys, keysToAdd);

    cacheEntry.releaseExclusiveLock();
    cachePointer.decrementReferrer();
  }
}


text:
"""This module, c_compiler.py, is a utility program to compiling c programs."""

from universal_code.shell_abstraction.shell_command_runner import run_shell_command_and_get_results

def create_object_file(source_file_path, object_output_path):
	"""Creates an object file."""
	return _run_command_and_return_output('gcc -c ' + source_file_path + ' -o ' + object_output_path)

def create_executable(source_file_path, c_libraries, object_output_path):
	"""Creates a new executable file."""
	object_file_paths_as_string = ''
	for o in c_libraries:
		object_file_paths_as_string += ' ' + o.path_to_object_file + ' '
	return _run_command_and_return_output('gcc -Wall -O2 ' + source_file_path + ' ' + object_file_paths_as_string + ' -o ' + object_output_path)

def _run_command_and_return_output(shell_command):
	"""Runs the provided shell command."""
	output_stdout, output_stderr = run_shell_command_and_get_results(shell_command)
	output_stdout = output_stdout.decode('utf-8')
	output_stderr = output_stderr.decode('utf-8')
	if len(output_stderr):
		print('ERROR')
		print(output_stderr)
	return output_stdout, output_stderr


text:
from mceditlib.worldeditor import WorldEditor
from timeit import timeit

import templevel

#import logging
#logging.basicConfig(level=logging.INFO)

def natural_relight():
    world = templevel.TempLevel("AnvilWorld")
    dim = world.getDimension()
    t = timeit(lambda: dim.generateLights(dim.chunkPositions()), number=1)
    print "Relight natural terrain: %d chunks in %.02f seconds (%.02fms per chunk)" % (dim.chunkCount, t,
                                                                                t / world.chunkCount * 1000)

def manmade_relight():
    t = templevel.TempLevel("TimeRelight", createFunc=lambda f:WorldEditor(f, create=True))

    world = t
    station = WorldEditor("test_files/station.schematic")

    times = 2

    for x in range(times):
        for z in range(times):
            world.copyBlocksFrom(station, station.bounds, (x * station.Width, 63, z * station.Length), create=True)

    t = timeit(lambda: world.generateLights(world.chunkPositions), number=1)
    print "Relight manmade building: %d chunks in %.02f seconds (%.02fms per chunk)" % (world.chunkCount, t, t / world.chunkCount * 1000)

if __name__ == '__main__':
    natural_relight()
    manmade_relight()


text:
%!TEX root = index.tex
\section[Biblioteca]{Biblioteca}
\begin{frame}{Biblioteca}{Ferramentas Utilizadas}

\textbf{IDE RStudio}
	\begin{itemize}
		\item Console
		\item Editor de texto e corretor de sintaxe
		\item Suporte a execução direta de código
		\item Visualização de gráficos
		\item Depuração de erros
		\item Gerenciamento de espaço de trabalho
	\end{itemize}
\end{frame}

\begin{frame}{Biblioteca}{Estrutura}
\textbf{Quatro principais seções}
\begin{description}
	\item DB
	\begin{itemize}
		\item Contém o banco de dados MovieLens 100k
	\end{itemize}
	\item Methods
	\begin{itemize}
		\item Contém os algoritmos de recomendação
	\end{itemize}
	\item Results
	\begin{itemize}
		\item Contém os métodos de avaliação de qualidade
	\end{itemize}
	\item Setup
	\begin{itemize}
		\item Contém funções de suporte
	\end{itemize}
\end{description}
\end{frame}


text:
package net.iaeste.iws.api.responses;

import net.iaeste.iws.api.constants.IWSConstants;
import net.iaeste.iws.api.constants.IWSError;
import net.iaeste.iws.api.dtos.Folder;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * @author  Kim Jensen / last $Author:$
 * @version $Revision:$ / $Date:$
 * @since   IWS 1.1
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "fetchFolderResponse", propOrder = "folder")
public final class FetchFolderResponse extends Response {

    /** {@link IWSConstants#SERIAL_VERSION_UID}. */
    private static final long serialVersionUID = IWSConstants.SERIAL_VERSION_UID;

    /** The Found Folder Object. */
    @XmlElement(required = true, nillable = true)
    private Folder folder = null;

    // =========================================================================
    // Object Constructors
    // =========================================================================

    /**
     * Empty Constructor, to use if the setters are invoked. This is required
     * for WebServices to work properly.
     */
    public FetchFolderResponse() {
        // Required for WebServices to work. Comment added to please Sonar.
    }

    /**
     * Default Constructor.
     *
     * @param folder Meta data
     */
    public FetchFolderResponse(final Folder folder) {
        setFolder(folder);
    }

    /**
     * Error Constructor.
     *
     * @param error   IWS Error Object
     * @param message Error Message
     */
    public FetchFolderResponse(final IWSError error, final String message) {
        super(error, message);
    }

    // =========================================================================
    // Standard Setters & Getters
    // =========================================================================

    public void setFolder(final Folder folder) {
        this.folder = new Folder(folder);
    }

    public Folder getFolder() {
        return new Folder(folder);
    }
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/components/tether/crash_recovery_manager_impl.h"

#include <memory>
#include <sstream>

#include "ash/components/multidevice/remote_device_test_util.h"
#include "ash/components/tether/device_id_tether_network_guid_map.h"
#include "ash/components/tether/fake_active_host.h"
#include "ash/components/tether/fake_host_scan_cache.h"
#include "ash/components/tether/host_scan_cache_entry.h"
#include "base/bind.h"
#include "base/test/task_environment.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/network_state_test_helper.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/cros_system_api/dbus/shill/dbus-constants.h"

namespace ash {

namespace tether {

namespace {

constexpr char kWifiNetworkGuid[] = "wifiNetworkGuid";

std::string CreateConfigurationJsonString(bool is_connected) {
  std::string connection_state =
      is_connected ? shill::kStateOnline : shill::kStateIdle;

  std::stringstream ss;
  ss << "{"
     << "  \"GUID\": \"" << kWifiNetworkGuid << "\","
     << "  \"Type\": \"" << shill::kTypeWifi << "\","
     << "  \"State\": \"" << connection_state << "\""
     << "}";
  return ss.str();
}

}  // namespace

class CrashRecoveryManagerImplTest : public testing::Test {
 public:
  CrashRecoveryManagerImplTest(const CrashRecoveryManagerImplTest&) = delete;
  CrashRecoveryManagerImplTest& operator=(const CrashRecoveryManagerImplTest&) =
      delete;

 protected:
  CrashRecoveryManagerImplTest()
      : test_device_(multidevice::CreateRemoteDeviceRefListForTest(1u)[0]) {}
  ~CrashRecoveryManagerImplTest() override = default;

  void SetUp() override {
    helper_.network_state_handler()->SetTetherTechnologyState(
        NetworkStateHandler::TECHNOLOGY_ENABLED);

    is_restoration_finished_ = false;

    fake_active_host_ = std::make_unique<FakeActiveHost>();
    fake_host_scan_cache_ = std::make_unique<FakeHostScanCache>();

    crash_recovery_manager_ = CrashRecoveryManagerImpl::Factory::Create(
        helper_.network_state_handler(), fake_active_host_.get(),
        fake_host_scan_cache_.get());

    device_id_tether_network_guid_map_ =
        std::make_unique<DeviceIdTetherNetworkGuidMap>();
  }

  void TearDown() override {
  }

  std::string GetTetherNetworkGuid() {
    return device_id_tether_network_guid_map_->GetTetherNetworkGuidForDeviceId(
        test_device_.GetDeviceId());
  }

  void SetConnected() {
    fake_active_host_->SetActiveHostConnected(
        test_device_.GetDeviceId(), GetTetherNetworkGuid(), kWifiNetworkGuid);
  }

  void AddScanEntry() {
    fake_host_scan_cache_->SetHostScanResult(
        *HostScanCacheEntry::Builder()
             .SetTetherNetworkGuid(GetTetherNetworkGuid())
             .SetDeviceName("deviceName")
             .SetCarrier("carrier")
             .SetBatteryPercentage(100)
             .SetSignalStrength(100)
             .SetSetupRequired(false)
             .Build());

    helper_.network_state_handler()->AddTetherNetworkState(
        GetTetherNetworkGuid(), "deviceName", "carrier",
        100 /* battery_percentage */, 100 /* signal_strength */,
        false /* has_connected_to_host */);
  }

  void AddWifiNetwork(bool is_connected) {
    helper_.ConfigureService(CreateConfigurationJsonString(is_connected));
  }

  void StartRestoration() {
    crash_recovery_manager_->RestorePreCrashStateIfNecessary(
        base::BindOnce(&CrashRecoveryManagerImplTest::OnRestorationFinished,
                       base::Unretained(this)));
  }

  void OnRestorationFinished() { is_restoration_finished_ = true; }

  void VerifyDisconnectedAfterRestoration() {
    EXPECT_TRUE(is_restoration_finished_);
    EXPECT_EQ(ActiveHost::ActiveHostStatus::DISCONNECTED,
              fake_active_host_->GetActiveHostStatus());
  }

  base::test::TaskEnvironment task_environment_;
  NetworkStateTestHelper helper_{true /* use_default_devices_and_services */};
  const multidevice::RemoteDeviceRef test_device_;

  std::unique_ptr<FakeActiveHost> fake_active_host_;
  std::unique_ptr<FakeHostScanCache> fake_host_scan_cache_;

  // TODO(hansberry): Use a fake for this when a real mapping scheme is created.
  std::unique_ptr<DeviceIdTetherNetworkGuidMap>
      device_id_tether_network_guid_map_;

  bool is_restoration_finished_;

  std::unique_ptr<CrashRecoveryManager> crash_recovery_manager_;
};

TEST_F(CrashRecoveryManagerImplTest, ActiveHostDisconnected) {
  StartRestoration();
  VerifyDisconnectedAfterRestoration();
}

TEST_F(CrashRecoveryManagerImplTest, ActiveHostConnecting) {
  fake_active_host_->SetActiveHostConnecting(test_device_.GetDeviceId(),
                                             GetTetherNetworkGuid());

  StartRestoration();
  VerifyDisconnectedAfterRestoration();
}

TEST_F(CrashRecoveryManagerImplTest, ActiveHostConnected_EntryNotInCache) {
  SetConnected();

  StartRestoration();
  VerifyDisconnectedAfterRestoration();
}

TEST_F(CrashRecoveryManagerImplTest, ActiveHostConnected_WifiNetworkMissing) {
  AddScanEntry();
  SetConnected();

  StartRestoration();
  VerifyDisconnectedAfterRestoration();
}

TEST_F(CrashRecoveryManagerImplTest,
       ActiveHostConnected_WifiNetworkDisconnected) {
  AddScanEntry();
  AddWifiNetwork(false /* is_connected */);
  SetConnected();

  StartRestoration();
  VerifyDisconnectedAfterRestoration();
}

TEST_F(CrashRecoveryManagerImplTest, ActiveHostConnected_RestoreSuccessful) {
  AddScanEntry();
  AddWifiNetwork(true /* is_connected */);
  SetConnected();

  StartRestoration();
  EXPECT_TRUE(is_restoration_finished_);
  EXPECT_EQ(ActiveHost::ActiveHostStatus::CONNECTED,
            fake_active_host_->GetActiveHostStatus());
}

}  // namespace tether

}  // namespace ash


text:
(function(angular) {
  "use strict";

  angular.module('myApp.mainMenu', [])

  .directive('mainmenu', function() {
    return {
      restrict: 'E',
      scope: {
      },
      transclude: true,
      templateUrl: 'partials/mainMenu.html',
      controller: function($scope, $rootScope, $location) {

    	  $scope.menu = [
    	    {label:'Home', route:'#/home'},
    	    {label:'LCARS', route:'#/lcars'},
          {label:'Account', route:'#/account'}
    	   ]

    	  $scope.menuActive = '/';

    	  $rootScope.$on('$routeChangeSuccess', function(e, curr, prev) {
           $scope.menuActive = $location.path();
        });

    	}
    };
  });

})(angular);


text:
<?php

namespace wcmf\lib\model;

use wcmf\lib\core\Session;
use wcmf\lib\persistence\ObjectId;
use wcmf\lib\persistence\PersistenceFacade;

/**
 * PersistentIterator is used to iterate over a tree/list built of persistent objects
 * using a Depth-First-Algorithm. To persist its state use the PersistentIterator::save() method,
 * to restore its state use the static PersistentIterator::load() method, which returns the loaded instance.
 *
 * @author ingo herwig <ingo@wemove.com>
 */
class PersistentIterator implements \Iterator {

  private $id = null;
  private $persistenceFacade = null;
  private $session = null;

  protected $end;              // indicates if the iteration is ended
  protected $oidList;          // the list of oids to process
  protected $processedOidList; // the list of all seen object ids
  protected $currentOid;       // the oid the iterator points to
  protected $startOid;         // the oid the iterator started with
  protected $currentDepth;     // the depth in the tree of the oid the iterator points to
  protected $aggregationKinds; // array of aggregation kind values to follow (empty: all)

  /**
   * Constructor.
   * @param $id The unique iterator id used to store iterator's the state in the session
   * @param $persistenceFacade
   * @param $session
   * @param $oid The object id to start from.
   * @param $aggregationKinds Array of aggregation kind values of relations to follow
   *   possible values: 'none', 'shared', 'composite'. Empty array means all (default: empty)
   */
  public function __construct($id, PersistenceFacade $persistenceFacade,
          Session $session,
          ObjectId $oid,
          $aggregationKinds=[]) {
    $this->id = $id;
    $this->persistenceFacade = $persistenceFacade;
    $this->session = $session;

    $this->end = false;
    $this->oidList = [];
    $this->processedOidList = [];
    $this->currentOid = $oid;
    $this->startOid = $oid;
    $this->currentDepth = 0;
    $this->aggregationKinds = $aggregationKinds;
    $this->session->remove($this->id);
  }

  /**
   * Save the iterator state to the session
   */
  public function save() {
    $state = ['end' => $this->end, 'oidList' => $this->oidList, 'processedOidList' => $this->processedOidList,
      'currentOID' => $this->currentOid, 'currentDepth' => $this->currentDepth, 'aggregationKinds' => $this->aggregationKinds];
    $this->session->set($this->id, $state);
  }

  /**
   * Reset the iterator with the given id
   * @param $id The iterator id
   * @param $session
   */
  public static function reset($id, Session $session) {
    $session->remove($id);
  }

  /**
   * Load an iterator state from the session
   * @param $id  The unique iterator id used to store iterator's the state in the session
   * @param $persistenceFacade
   * @param $session
   * @return PersistentIterator instance holding the saved state or null if unique id is not found
   */
  public static function load($id, $persistenceFacade, $session) {
    // get state from session
    $state = $session->get($id);
    if ($state == null) {
      return null;
    }
    // create instance
    $instance = new PersistentIterator($id, $persistenceFacade, $session,
            $state['currentOID']);
    $instance->end = $state['end'];
    $instance->oidList = $state['oidList'];
    $instance->processedOidList = $state['processedOidList'];
    $instance->currentDepth = $state['currentDepth'];
    $instance->aggregationKinds = $state['aggregationKinds'];
    return $instance;
  }

  /**
   * Return the current element
   * @return ObjectId, the current object id
   */
  public function current() {
    return $this->currentOid;
  }

  /**
   * Return the key of the current element
   * @return Number, the current depth
   */
  public function key() {
    return $this->currentDepth;
  }

  /**
   * Move forward to next element
   */
  public function next() {
    // the current oid was processed
    $this->processedOidList[] = $this->currentOid->__toString();

    $node = $this->persistenceFacade->load($this->currentOid);

    // collect navigable children for the given aggregation kinds
    $childOIDs = [];
    $mapper = $node->getMapper();
    $relations = $mapper->getRelations('child');
    $followAll = sizeof($this->aggregationKinds) == 0;
    foreach ($relations as $relation) {
      $aggregationKind = $relation->getOtherAggregationKind();
      if ($relation->getOtherNavigability() && ($followAll || in_array($aggregationKind, $this->aggregationKinds))) {
        $childValue = $node->getValue($relation->getOtherRole());
        if ($childValue != null) {
          $children = $relation->isMultiValued() ? $childValue : [$childValue];
          foreach ($children as $child) {
            $childOIDs[] = $child->getOID();
          }
        }
      }
    }
    $this->addToQueue($childOIDs, ++$this->currentDepth);

    // set current node
    if (sizeof($this->oidList) != 0) {
      list($oid, $depth) = array_pop($this->oidList);
      $oidStr = $oid->__toString();
      // not the last node -> search for unprocessed nodes
      while (sizeof($this->oidList) > 0 && in_array($oidStr, $this->processedOidList)) {
        list($oid, $depth) = array_pop($this->oidList);
        $oidStr = $oid->__toString();
      }
      // last node found, but it was processed already
      if (sizeof($this->oidList) == 0 && in_array($oidStr, $this->processedOidList)) {
        $this->end = true;
      }
      $this->currentOid = $oid;
      $this->currentDepth = $depth;
    }
    else {
      $this->end = true;
    }
    return $this;
  }

  /**
   * Rewind the Iterator to the first element
   */
  public function rewind() {
    $this->end = false;
    $this->oidList= [];
    $this->processedOidList = [];
    $this->currentOid = $this->startOid;
    $this->currentDepth = 0;
  }

  /**
   * Checks if current position is valid
   */
  public function valid() {
    return !$this->end;
  }

  /**
   * Add object ids to the processing queue.
   * @param $oidList An array of object ids.
   * @param $depth The depth of the object ids in the tree.
   */
  protected function addToQueue($oidList, $depth) {
    for ($i=sizeOf($oidList)-1; $i>=0; $i--) {
      $this->oidList[] = [$oidList[$i], $depth];
    }
  }
}
?>


text:
from distutils.core import setup

setup(name='pyboas',
      description='Bayesian Observation predictor and Adaptive Scheduler.',
      version='0.1.0',
      author='Rodrigo F. Diaz',
      author_email='rodrigo.diaz@unige.ch',
      #url='http://obswww.unige.ch/~diazr/pygpr',
      packages=['pyboas'],
      requires=['numpy', 'scipy']
      )


text:
/*
 * $Id: DOM_NodeList.cpp 176278 2005-01-07 14:38:22Z amassari $
 */

#include "DOM_NodeList.hpp"
#include "NodeListImpl.hpp"
#include "DOM_Node.hpp"
#include <assert.h>

XERCES_CPP_NAMESPACE_BEGIN

DOM_NodeList::DOM_NodeList()
{
    fImpl = 0;
}

DOM_NodeList::DOM_NodeList(NodeListImpl *impl)
{
    fImpl = impl;
    RefCountedImpl::addRef(fImpl);
}

DOM_NodeList::DOM_NodeList(const DOM_NodeList &other)
{
    fImpl = other.fImpl;
    RefCountedImpl::addRef(fImpl);
}

DOM_NodeList & DOM_NodeList::operator = (const DOM_NodeList &other)
{
    if (this->fImpl != other.fImpl)
    {
        RefCountedImpl::removeRef(this->fImpl);
        this->fImpl = other.fImpl;
        RefCountedImpl::addRef(this->fImpl);
    }
    return *this;
}

DOM_NodeList & DOM_NodeList::operator = (const DOM_NullPtr * /*other*/)
{
    RefCountedImpl::removeRef(this->fImpl);
    this->fImpl = 0;
    return *this;
}

DOM_NodeList::~DOM_NodeList()
{
    RefCountedImpl::removeRef(this->fImpl);
    fImpl = 0;
}

bool DOM_NodeList::operator == (const DOM_NodeList &other) const
{
    return this->fImpl == other.fImpl;
}

bool DOM_NodeList::operator != (const DOM_NodeList &other) const
{
    return this->fImpl != other.fImpl;
}

bool DOM_NodeList::operator == (const DOM_NullPtr * /*nullPtr*/) const
{
    return this->fImpl == 0;
}

bool DOM_NodeList::operator != (const DOM_NullPtr * /*nullPtr*/) const
{
    return this->fImpl != 0;
}

DOM_Node  DOM_NodeList::item(unsigned int index) const
{
    return DOM_Node(fImpl->item(index));
}

unsigned int DOM_NodeList::getLength() const
{
    return fImpl->getLength();
}

XERCES_CPP_NAMESPACE_END


text:
@interface BasicInstantiationBadgeViewController : UIViewController
@end


text:
using System;
using ColossalFramework.UI;
using PrecisionEngineering.Data;
using PrecisionEngineering.Detour;
using PrecisionEngineering.Rendering;
using PrecisionEngineering.UI;
using PrecisionEngineering.Utilities;
using UnityEngine;

namespace PrecisionEngineering
{
    internal class Manager : SimulationManagerBase<Manager, MonoBehaviour>,
        ISimulationManager, IRenderableManager
    {
        /// <summary>
        /// Managers should only be registered once, and then they persist over loads
        /// </summary>
        private static bool _hasRegistered;
        private bool _isLoaded;

        private readonly PrecisionCalculator _calculator = new PrecisionCalculator();
        private readonly PrecisionUI _ui = new PrecisionUI();

        private bool _advancedSnappingEnabled;
        private bool _secondaryDetailEnabled;

        private NetToolProxy _netToolProxy;

        public bool IsEnabled
        {
            get { return _netToolProxy != null && _netToolProxy.IsValid; }
        }

        public static void OnLevelLoaded()
        {
            if (!_hasRegistered)
            {
                Debug.Log("Registering Manager");

                SimulationManager.RegisterManager(instance);
                _hasRegistered = true;
            }

            instance.Load();
        }

        public static void OnLevelUnloaded()
        {
            instance.Unload();
        }

        private void Load()
        {
            if (_isLoaded)
            {
                return;
            }

            _isLoaded = true;

            Debug.Log("Manager Load");

            _ui.Calculator = _calculator;
        }

        private void Unload()
        {
            Debug.Log("Manager Unload");

            _netToolProxy = null;
            _isLoaded = false;

            _ui.ReleaseAll();
        }

        private void Update()
        {
            // Search for NetTool if not already loaded.
            // Performing this in the default MonoBehaviour so that we will
            // correctly catch any modded NetTools that replace the default.

            if (_isLoaded && !IsEnabled)
            {
                Debug.Log("Loading NetTool");

                _netToolProxy = NetToolLocator.Locate();

                if (_netToolProxy != null)
                {
                    Settings.BlueprintColor = _netToolProxy.ToolController.m_validColor;
                    _ui.NetToolProxy = _netToolProxy;
                }
            }
        }

        protected override void SimulationStepImpl(int subStep)
        {
            if (!IsEnabled)
            {
                //Debug.LogWarning("[SimulationStepImpl] !IsEnabled");
                return;
            }

            base.SimulationStepImpl(subStep);

            // Toggle with shift
            /*_secondaryDetailEnabled = (Input.GetKeyDown(KeyCode.LeftShift) || Input.GetKeyDown(KeyCode.RightShift))
				? !_secondaryDetailEnabled
				: _secondaryDetailEnabled;*/

            // Activate with shift
            _secondaryDetailEnabled = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);

            _advancedSnappingEnabled = Input.GetKey(KeyCode.LeftAlt) || Input.GetKey(KeyCode.RightAlt);

            SnapController.EnableSnapping = Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl);
            SnapController.EnableAdvancedSnapping = _advancedSnappingEnabled;
            SnapController.EnableLengthSnapping = !SnapController.EnableAdvancedSnapping;

            if (!SnapController.EnableAdvancedSnapping)
            {
                SnapController.SnappedGuideLine = null;
                SnapController.GuideLines.Clear();
            }

            _calculator.Update(_netToolProxy);
        }

        protected override void EndOverlayImpl(RenderManager.CameraInfo cameraInfo)
        {
            base.EndOverlayImpl(cameraInfo);

            if (!IsEnabled)
            {
                //Debug.LogWarning("[EndOverlayImpl] !IsEnabled");
                return;
            }

            _ui.ReleaseAll();

            for (var i = 0; i < _calculator.Measurements.Count; i++)
            {
                HandleMeasurement(cameraInfo, _calculator.Measurements[i]);
            }

            lock (SnapController.GuideLineLock)
            {
                if (SnapController.SnappedGuideLine.HasValue)
                {
                    GuideLineRenderer.Render(cameraInfo, SnapController.SnappedGuideLine.Value);
                }
            }

            try
            {
                _ui.Update();
            }
            catch (Exception e)
            {
                Debug.LogError("Error during UI Update");
                Debug.LogError(e.ToString());
            }
        }

        /// <summary>
        /// Perform rendering of a measurement.
        /// </summary>
        private void HandleMeasurement(RenderManager.CameraInfo cameraInfo, Measurement m)
        {
            // TODO: Move out of this slightly monolithic manager class

            if ((m.Flags & MeasurementFlags.Secondary) != 0 && !_secondaryDetailEnabled)
            {
                return;
            }

            if ((m.Flags & MeasurementFlags.Guide) != 0 && !SnapController.EnableAdvancedSnapping)
            {
                return;
            }

            if ((m.Flags & MeasurementFlags.Snap) != 0 && !SnapController.EnableSnapping)
            {
                return;
            }

            if (m is AngleMeasurement)
            {
                var am = m as AngleMeasurement;

                if (am.AngleSize < 1f)
                {
                    return;
                }

                AngleRenderer.Render(cameraInfo, am);

                var label = _ui.GetMeasurementLabel();
                label.SetValue(string.Format("{0:#.0}{1}", am.AngleSize.RoundToNearest(0.1f), "°"));
                label.SetWorldPosition(cameraInfo, AngleRenderer.GetLabelWorldPosition(am));

                return;
            }

            if (m is DistanceMeasurement)
            {
                var dm = m as DistanceMeasurement;

                if (Mathf.Abs(dm.Length) < Settings.MinimumDistanceMeasure)
                {
                    return;
                }

                DistanceRenderer.Render(cameraInfo, dm);

                var label = _ui.GetMeasurementLabel();

                string dist;

                if ((dm.Flags & MeasurementFlags.Height) != 0)
                {
                    dist = string.Format("H: {0}", StringUtil.GetHeightMeasurementString(dm.Length));
                }
                else
                {
                    dist = StringUtil.GetDistanceMeasurementString(dm.Length, _secondaryDetailEnabled);

                    if (_secondaryDetailEnabled)
                    {
                       var heightdiff = (int) dm.RelativeHeight.RoundToNearest(1);

                        if (Mathf.Abs(heightdiff) > 0)
                        {
                            dist += string.Format("\n(Elev: {0})", StringUtil.GetHeightMeasurementString(heightdiff));
                        }
                    }
                }

                label.SetValue(dist);
                label.SetWorldPosition(cameraInfo, DistanceRenderer.GetLabelWorldPosition(dm));

                return;
            }

            Debug.LogError("Measurement has no renderer: " + m);
        }
    }
}


text:
namespace DotNetScaffolder.Presentation.Forms.Controls.Project.DataType
{
    partial class DefaultModelUserControl
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.SuspendLayout();
            //
            // groupBox1
            //
            this.groupBox1.Location = new System.Drawing.Point(3, 3);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(713, 491);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Default";
            //
            // DefaultModelUserControl
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.Controls.Add(this.groupBox1);
            this.Margin = new System.Windows.Forms.Padding(2);
            this.Name = "DefaultModelUserControl";
            this.Size = new System.Drawing.Size(724, 502);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
    }
}


text:
from suds.client import Client

__author__ = 'Andrew Ben'

class OnPageHubApi():
    def __init__(self, url, enterpiseName, token):
        self.__url = url
        self.__enterpiseName = enterpiseName
        self.__token = token

        self.__hubApiClient = Client(url)
        self.__hubApiClient.set_options(location=url)

    def __getCredentials(self):
        credentials = self.__hubApiClient.factory.create('Credentials')
        credentials.Token = '%s+%s' % (self.__enterpiseName, self.__token)
        return credentials

    def __createSender(self, senderId):
        sender = self.__hubApiClient.factory.create('Sender')
        senderType = self.__hubApiClient.factory.create('SENDER_TYPE')
        if senderId.find('@') > 0:
            sender.type = senderType.EMAIL
        else:
            sender.type = senderType.PAGER
        sender.ID = senderId

        return sender

    def __createRecipient(self, recipient):
        hubApiRecipient = self.__hubApiClient.factory.create('Recipient')
        hubApiRecipient.id = recipient
        return hubApiRecipient

    def __createMessage(self, messageId, sender, recipients, subject, body, replyOptions, callBackUrl):
        message = self.__hubApiClient.factory.create('Message')

        message.id = messageId

        message.Sender = self.__createSender(senderId=sender)

        message.Subject = subject
        message.Body = body

        listOfRecipients = []
        for recipient in recipients:
            listOfRecipients.append(self.__createRecipient(recipient))
        message.Recipients = {'Recipient': [listOfRecipients]}

        replies = self.__hubApiClient.factory.create('ReplyOptions')
        replies.AllowFreeText = True
        replies.Requested = {'Option': replyOptions}

        message.Reply = replyOptions

        message.CallbackURI = callBackUrl

        return message

    def __prepareMessages(self, messages):
        listOfMessages = []
        for message in messages:
            hubApiMessage = self.__createMessage(
                messageId=message.messageId,
                sender=message.sender,
                recipients=message.recipients,
                subject=message.subject,
                body=message.body,
                replyOptions=message.replyOptions,
                callBackUrl=message.callBackUrl
            )

            listOfMessages.append(hubApiMessage)

        arrayOfMessages = {'Message': listOfMessages}

        return arrayOfMessages

    def sendPage(self, messages):
        arrayOfMessages = self.__prepareMessages(messages)

        return self.__hubApiClient.service.SendMessage(self.__getCredentials(), arrayOfMessages)